repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/tune/__tests__/remaining.test.ts

Raw
File outline
import * as fs from "node:fs";
import { tmpdir } from "node:os";
import * as path from "node:path";
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import {
	buildTuneCompactionSummary,
	tuneSummaryPathsFor,
} from "../compaction.ts";
import { hookScriptPath } from "../hooks.ts";
import { __test } from "../index.ts";
import { reconstructJsonlState } from "../jsonl.ts";
import { resolveTuneShortcuts } from "../shortcuts.ts";

const TESTDIR = fs.mkdtempSync(path.join(tmpdir(), "pi-ext-tune-"));
const LOCK_TESTDIR = path.join(TESTDIR, "lock");
const TEST_JSONL =
	[
		'{"type":"config","name":"Optimize sqrt/sin loop","metricName":"total_ms","metricUnit":"ms","bestDirection":"lower"}',
		'{"run":1,"commit":"92d4b83","metric":7,"metrics":{},"status":"keep","description":"Baseline: unoptimized sqrt/sin loop","timestamp":1780152220658,"segment":0,"confidence":null,"asi":{"hypothesis":"Baseline measurement"}}',
		'{"run":2,"commit":"92d4b83","metric":10,"metrics":{},"status":"discard","description":"Sin LUT inside timed region — slower","timestamp":1780152284058,"segment":0,"confidence":null,"asi":{"hypothesis":"Sin lookup table inside timed region adds overhead"}}',
		'{"run":3,"commit":"5666498","metric":1,"metrics":{},"status":"keep","description":"Sin LUT built before timed region","timestamp":1780152315721,"segment":0,"confidence":2,"asi":{"hypothesis":"Move sin LUT construction before timed region"}}',
		'{"run":4,"commit":"5666498","metric":1,"metrics":{},"status":"discard","description":"Sqrt+sin LUTs — no improvement","timestamp":1780152358180,"segment":0,"confidence":2,"asi":{"hypothesis":"Pre-compute both sqrt and sin"}}',
		'{"run":5,"commit":"5666498","metric":1,"metrics":{},"status":"discard","description":"Full product LUT — no improvement","timestamp":1780152396062,"segment":0,"confidence":null,"asi":{"hypothesis":"Pre-compute full products"}}',
	].join("\n") + "\n";

beforeAll(() => {
	const tuneDir = path.join(TESTDIR, ".pi", "tune");
	fs.mkdirSync(tuneDir, { recursive: true });
	fs.writeFileSync(path.join(tuneDir, "session.jsonl"), TEST_JSONL);
});

afterEach(() => {
	fs.rmSync(LOCK_TESTDIR, { recursive: true, force: true });
});

afterAll(() => {
	fs.rmSync(TESTDIR, { recursive: true, force: true });
});

// ── 1. COMPACTION RESUME ────────────────────────────────────────────────

describe("compaction resume", () => {
	it("builds summary from live session.jsonl", () => {
		const paths = tuneSummaryPathsFor(TESTDIR);
		const summary = buildTuneCompactionSummary(paths);

		expect(summary).toContain("Tune Compaction Summary");
		expect(summary).toContain("## Session");
		expect(summary).toContain("Optimize");
		expect(summary).toContain("total_ms");
		expect(summary).toContain("## Recent Runs");
		expect(summary).toContain("## Next Step");
		expect(summary).toContain("#1");
		expect(summary).toContain("#3");
		expect(summary).toContain("keep");
		expect(summary).toContain("discard");
	});

	it("includes run metrics and deltas", () => {
		const paths = tuneSummaryPathsFor(TESTDIR);
		const summary = buildTuneCompactionSummary(paths);

		// Run 1 baseline=7ms, run 3 best=1ms → should show delta
		expect(summary).toContain("7");
		expect(summary).toContain("1");
	});

	it("reconstructs correct state for compaction", () => {
		const paths = tuneSummaryPathsFor(TESTDIR);
		const jsonl = fs.readFileSync(paths.jsonlPath, "utf-8");
		const state = reconstructJsonlState(jsonl);

		expect(state.name).toBe("Optimize sqrt/sin loop");
		expect(state.metricName).toBe("total_ms");
		expect(state.bestDirection).toBe("lower");
		expect(state.results).toHaveLength(5);
		expect(state.currentSegment).toBe(0);
	});

	it("confidence=2 for run 3 (real improvement)", () => {
		const paths = tuneSummaryPathsFor(TESTDIR);
		const jsonl = fs.readFileSync(paths.jsonlPath, "utf-8");
		const state = reconstructJsonlState(jsonl);
		const run3 = state.results.find((r) => r.run === 3);
		expect(run3?.confidence).toBe(2);
	});
});

// ── 2. WIDGET / RENDERING HELPERS ──────────────────────────────────────

describe("widget rendering helpers", () => {
	it("parseMetricLines handles edge cases", () => {
		expect(__test.parseMetricLines("METRIC x=42\n").get("x")).toBe(42);
		expect(__test.parseMetricLines("METRIC a=1\nMETRIC b=2\n").size).toBe(2);
		expect(__test.parseMetricLines("nope\n").size).toBe(0);
	});

	it("formatNum covers null, int, float", () => {
		expect(__test.formatNum(null, "ms")).toBe("—");
		expect(__test.formatNum(15586, "µs")).toBe("15,586µs");
		expect(__test.formatNum(42.5, "ms")).toBe("42.50ms");
		expect(__test.formatNum(0, "")).toBe("0");
	});
});

// ── 3. SHORTCUTS ──────────────────────────────────────────────────────

describe("shortcuts", () => {
	it("returns defaults when settings are missing", () => {
		const s = resolveTuneShortcuts();
		expect(s.toggleDashboard).toBe("ctrl+shift+t");
		expect(s.fullscreenDashboard).toBe("ctrl+alt+t");
	});

	it("reads shortcut overrides and null disables from settings.tune.shortcuts", () => {
		const s = resolveTuneShortcuts({
			tune: {
				shortcuts: {
					toggleDashboard: null,
					fullscreenDashboard: "ctrl+alt+f",
				},
			},
		});
		expect(s.toggleDashboard).toBeNull();
		expect(s.fullscreenDashboard).toBe("ctrl+alt+f");
	});
});

// ── 4. REPO LOCK ───────────────────────────────────────────────────────

describe("repo lock", () => {
	it("allows one session to acquire and re-enter, blocks others, and only owner releases", () => {
		expect(__test.acquireTuneLock(LOCK_TESTDIR, "s1")).toEqual({ ok: true });
		expect(__test.acquireTuneLock(LOCK_TESTDIR, "s1")).toEqual({ ok: true });
		expect(__test.ownsTuneLock(LOCK_TESTDIR, "s1")).toBe(true);
		expect(__test.acquireTuneLock(LOCK_TESTDIR, "s2")).toEqual({
			ok: false,
			owner: "s1",
		});
		expect(__test.releaseTuneLock(LOCK_TESTDIR, "s2")).toBe(false);
		expect(__test.ownsTuneLock(LOCK_TESTDIR, "s1")).toBe(true);
		expect(__test.releaseTuneLock(LOCK_TESTDIR, "s1")).toBe(true);
		expect(__test.ownsTuneLock(LOCK_TESTDIR, "s1")).toBe(false);
	});
});

// ── 5. HOOK PATHS ─────────────────────────────────────────────────────

describe("hook paths", () => {
	it("resolves to .pi/tune/hooks/{stage}.mjs", () => {
		expect(hookScriptPath("/project", "before")).toBe(
			path.join("/project", ".pi", "tune", "hooks", "before.mjs"),
		);
		expect(hookScriptPath("/project", "after")).toBe(
			path.join("/project", ".pi", "tune", "hooks", "after.mjs"),
		);
	});
});

// ── 6. EXPORT DASHBOARD ───────────────────────────────────────────────

describe("export dashboard", () => {
	it("ships a dashboard template next to the tune extension", () => {
		const templatePath = __test.dashboardTemplatePath();
		const template = fs.readFileSync(templatePath, "utf-8");

		expect(
			templatePath.endsWith(path.join("tune", "assets", "template.html")),
		).toBe(true);
		expect(template).toContain("__TUNE_TITLE__");
		expect(template).toContain("session.jsonl");
		expect(template).toContain("Nugu dark palette");
		expect(template).toContain("diff-review-theme");
	});

	it("uses measured topbar height for sticky table header", () => {
		const template = fs.readFileSync(__test.dashboardTemplatePath(), "utf-8");

		expect(template).toContain("--topbar-height");
		expect(template).toContain("top: var(--topbar-height)");
		expect(template).toContain("syncTopbarHeight");
		expect(template).toContain("ResizeObserver");
		expect(template).not.toContain("top: 63px");
		expect(template).not.toContain(
			".panel { margin-top: 14px; overflow: hidden; }",
		);
	});
});