repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/tune/__tests__/unit.test.ts

Raw
File outline
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { DEFAULT_MAX_LINES } from "@earendil-works/pi-coding-agent";
import { describe, expect, it } from "vitest";
import { buildTuneCompactionSummary } from "../compaction.ts";
import { hookScriptPath } from "../hooks.ts";
import { __test } from "../index.ts";
import {
	extractTuneSessionName,
	hasTuneConfigHeader,
	isTuneConfigEntry,
	isTuneRunEntry,
	parseJsonlEntry,
	reconstructJsonlState,
} from "../jsonl.ts";

// ── Dashboard HTML ────────────────────────────────────────────────────────

describe("dashboard template", () => {
	it("keeps the runs table header below the sticky topbar", () => {
		const html = fs.readFileSync(
			path.join(import.meta.dirname, "..", "assets", "template.html"),
			"utf8",
		);

		expect(html).toContain("th { position: sticky; top: var(--topbar-height);");
		expect(html).not.toContain("th { position: sticky; top: 63px;");
	});

	it("chooses the best dashboard run from kept runs only", () => {
		const html = fs.readFileSync(
			path.join(import.meta.dirname, "..", "assets", "template.html"),
			"utf8",
		);

		expect(html).toContain(
			'state.runs.filter(r => r.status === "keep" && r.metric > 0)',
		);
	});
});

// ── Metric line parsing ───────────────────────────────────────────────────

describe("parseMetricLines", () => {
	const { parseMetricLines } = __test;

	it("parses single METRIC line", () => {
		const result = parseMetricLines("METRIC total_µs=15200\n");
		expect(result.get("total_µs")).toBe(15200);
	});

	it("parses multiple METRIC lines", () => {
		const output = "METRIC total_µs=15200\nMETRIC compile_µs=4200\n";
		const result = parseMetricLines(output);
		expect(result.get("total_µs")).toBe(15200);
		expect(result.get("compile_µs")).toBe(4200);
	});

	it("ignores non-METRIC lines", () => {
		const result = parseMetricLines("hello\nMETRIC x=42\nworld\n");
		expect(result.size).toBe(1);
		expect(result.get("x")).toBe(42);
	});

	it("rejects NaN and Infinity values", () => {
		const result = parseMetricLines(
			"METRIC a=Infinity\nMETRIC b=NaN\nMETRIC c=42\n",
		);
		expect(result.size).toBe(1);
		expect(result.get("c")).toBe(42);
	});

	it("rejects prototype pollution names", () => {
		const result = parseMetricLines(
			"METRIC __proto__=1\nMETRIC constructor=2\n",
		);
		expect(result.size).toBe(0);
	});
});

// ── Tune config ───────────────────────────────────────────────────────────

describe("tune settings", () => {
	function project(tune: Record<string, unknown>): string {
		const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "tune-settings-"));
		fs.mkdirSync(path.join(cwd, ".pi"));
		fs.writeFileSync(
			path.join(cwd, ".pi", "settings.json"),
			JSON.stringify({ tune }),
		);
		return cwd;
	}

	it("reads positive numeric limits from settings.tune", () => {
		expect(
			__test.readTuneSettings(
				project({ maxIterations: 9.8, autoResumeLimit: 12.9 }),
			),
		).toMatchObject({ maxIterations: 9, autoResumeLimit: 12 });
	});

	it("treats invalid limits as unlimited", () => {
		for (const tune of [
			{},
			{ maxIterations: 0, autoResumeLimit: 0 },
			{ maxIterations: -1, autoResumeLimit: -1 },
			{ maxIterations: "20", autoResumeLimit: "20" },
		]) {
			expect(__test.readTuneSettings(project(tune))).toMatchObject({
				maxIterations: null,
				autoResumeLimit: null,
			});
		}
	});
});

// ── Best metric ───────────────────────────────────────────────────────────

describe("findBestMetric", () => {
	const { findBestMetric } = __test;

	it("ignores discarded runs", () => {
		expect(
			findBestMetric(
				[
					{ metric: 100, status: "keep", segment: 0 },
					{ metric: 1, status: "discard", segment: 0 },
					{ metric: 80, status: "keep", segment: 0 },
				] as never,
				0,
				"lower",
			),
		).toBe(80);
	});
});

// ── Tune prompt contracts ─────────────────────────────────────────────────

describe("tune prompt contracts", () => {
	it("requires next action hints for dashboard and compaction", () => {
		expect(__test.LOG_ASI_GUIDELINE).toContain("next_action_hint");
	});
});

// ── Number formatting ─────────────────────────────────────────────────────

describe("formatNum", () => {
	const { formatNum } = __test;

	it("formats integers with commas", () => {
		expect(formatNum(15586, "")).toBe("15,586");
	});

	it("formats with unit suffix", () => {
		expect(formatNum(15200, "µs")).toBe("15,200µs");
	});

	it("formats fractional with 2 decimals", () => {
		expect(formatNum(42.5, "ms")).toBe("42.50ms");
	});
});

// ── VCS backend ──────────────────────────────────────────────────────────

describe("vcs backend", () => {
	it("detects jj before git", async () => {
		const calls: string[] = [];
		const exec = async (cmd: string) => {
			calls.push(cmd);
			return { code: cmd === "jj" ? 0 : 1, stdout: "", stderr: "" };
		};
		expect(await __test.detectVcsKind(exec, "/repo")).toBe("jj");
		expect(calls).toEqual(["jj"]);
	});

	it("uses jj describe and jj new on keep", async () => {
		const calls: Array<[string, string[]]> = [];
		const exec = async (cmd: string, args: string[]) => {
			calls.push([cmd, args]);
			if (cmd === "jj" && args[0] === "root")
				return { code: 0, stdout: "/repo\n", stderr: "" };
			if (
				cmd === "jj" &&
				args[0] === "log" &&
				args.includes("change_id.short()")
			)
				return { code: 0, stdout: "chg123\n", stderr: "" };
			if (
				cmd === "jj" &&
				args[0] === "log" &&
				args.includes("commit_id.short(7)")
			)
				return { code: 0, stdout: "abc1234\n", stderr: "" };
			return { code: 0, stdout: "", stderr: "" };
		};
		const result = await __test.keepVcsChanges(exec, "/repo", "msg");
		expect(result.kind).toBe("jj");
		expect(result.commit).toBe("abc1234");
		expect(result.text).toContain("jj: kept change chg123 abc1234");
		expect(calls.map(([cmd, args]) => [cmd, args[0]])).toEqual([
			["jj", "root"],
			["jj", "describe"],
			["jj", "log"],
			["jj", "log"],
			["jj", "new"],
		]);
	});

	it("uses jj abandon and jj new on discard", async () => {
		const calls: Array<[string, string[]]> = [];
		const exec = async (cmd: string, args: string[]) => {
			calls.push([cmd, args]);
			return { code: cmd === "jj" ? 0 : 1, stdout: "", stderr: "" };
		};
		const result = await __test.discardVcsChanges(exec, "/repo", "discard");
		expect(result.kind).toBe("jj");
		expect(result.text).toContain("jj: abandoned change (discard)");
		expect(calls.map(([cmd, args]) => [cmd, args[0]])).toEqual([
			["jj", "root"],
			["jj", "abandon"],
			["jj", "new"],
		]);
	});

	it("uses direct Git calls on discard", async () => {
		const calls: Array<[string, string[]]> = [];
		const exec = async (cmd: string, args: string[]) => {
			calls.push([cmd, args]);
			return { code: cmd === "jj" ? 1 : 0, stdout: "", stderr: "" };
		};

		await __test.discardVcsChanges(exec, "/repo", "discard");

		expect(calls).toEqual([
			["jj", ["root"]],
			[
				"git",
				[
					"checkout",
					"--",
					".",
					":(exclude,glob).pi/tune/**",
					":(exclude,glob).pi/tune/*",
				],
			],
			["git", ["clean", "-fd", "-e", ".pi/tune", "-e", ".pi/tune/**"]],
		]);
	});

	it("does not clean after checkout failure", async () => {
		const calls: string[] = [];
		const exec = async (cmd: string, args: string[]) => {
			calls.push(`${cmd} ${args[0]}`);
			if (cmd === "jj") return { code: 1, stdout: "", stderr: "" };
			return { code: 1, stdout: "", stderr: "checkout failed" };
		};

		await expect(
			__test.discardVcsChanges(exec, "/repo", "discard"),
		).rejects.toThrow("git checkout failed: checkout failed");
		expect(calls).toEqual(["jj root", "git checkout"]);
	});
});

// ── Tune tool activation ──────────────────────────────────────────

describe("tune tool activation", () => {
	it("disables only tune tools", () => {
		let activeTools = ["read", "init_experiment", "bash", "log_experiment"];
		const pi = {
			getActiveTools: () => activeTools,
			setActiveTools: (names: string[]) => {
				activeTools = names;
			},
		} as never;

		__test.setTuneToolsActive(pi, false);

		expect(activeTools).toEqual(["read", "bash"]);
	});

	it("enables tune tools without dropping existing tools", () => {
		let activeTools = ["read", "bash"];
		const pi = {
			getActiveTools: () => activeTools,
			setActiveTools: (names: string[]) => {
				activeTools = names;
			},
		} as never;

		__test.setTuneToolsActive(pi, true);
		__test.setTuneToolsActive(pi, true);

		expect(activeTools).toEqual([
			"read",
			"bash",
			"init_experiment",
			"run_experiment",
			"log_experiment",
		]);
	});
});

// ── /tune autocomplete ────────────────────────────────────────────

describe("tune autocomplete", () => {
	const { tuneArgumentCompletions, tuneCommandArgumentSuggestions } = __test;

	it("suggests subcommands from argument prefixes", () => {
		expect(tuneArgumentCompletions("e")).toEqual([
			{ value: "export", label: "export", description: "Open live dashboard" },
		]);
		expect(tuneArgumentCompletions("  c")).toEqual([
			{
				value: "clear",
				label: "clear",
				description: "Delete session.jsonl and stop",
			},
		]);
	});

	it("does not suggest after freeform objective text begins", () => {
		expect(tuneArgumentCompletions("optimize runtime")).toBeNull();
		expect(tuneArgumentCompletions("z")).toBeNull();
	});

	it("intercepts forced autocomplete for tune subcommands", () => {
		expect(tuneCommandArgumentSuggestions(["/tune "], 0, 6)).toEqual({
			prefix: "",
			items: [
				{ value: "off", label: "off", description: "Turn tune mode off" },
				{
					value: "clear",
					label: "clear",
					description: "Delete session.jsonl and stop",
				},
				{
					value: "export",
					label: "export",
					description: "Open live dashboard",
				},
			],
		});
		expect(tuneCommandArgumentSuggestions(["/tune e"], 0, 7)).toEqual({
			prefix: "e",
			items: [
				{
					value: "export",
					label: "export",
					description: "Open live dashboard",
				},
			],
		});
		expect(
			tuneCommandArgumentSuggestions(["/tune optimize"], 0, 14),
		).toBeNull();
	});
});

// ── JSONL parsing ─────────────────────────────────────────────────────────

describe("parseJsonlEntry", () => {
	it("parses valid JSON", () => {
		const entry = parseJsonlEntry('{"type":"config","name":"test"}');
		expect(entry).not.toBeNull();
		expect(entry?.type).toBe("config");
	});

	it("returns null for invalid JSON", () => {
		expect(parseJsonlEntry("not json")).toBeNull();
	});

	it("returns null for arrays", () => {
		expect(parseJsonlEntry("[1,2,3]")).toBeNull();
	});
});

describe("isTuneConfigEntry", () => {
	it("recognizes config entries", () => {
		expect(isTuneConfigEntry({ type: "config" })).toBe(true);
	});

	it("rejects run entries", () => {
		expect(isTuneConfigEntry({ type: "run", run: 1 })).toBe(false);
	});
});

describe("isTuneRunEntry", () => {
	it("recognizes run entries", () => {
		expect(isTuneRunEntry({ run: 1, metric: 42 })).toBe(true);
	});

	it("rejects non-run entries", () => {
		expect(isTuneRunEntry({ type: "config" })).toBe(false);
	});
});

describe("hasTuneConfigHeader", () => {
	it("detects config header", () => {
		const content = '{"type":"config","name":"test"}\n{"run":1}\n';
		expect(hasTuneConfigHeader(content)).toBe(true);
	});

	it("returns false for no config", () => {
		const content = '{"run":1}\n{"run":2}\n';
		expect(hasTuneConfigHeader(content)).toBe(false);
	});
});

describe("extractTuneSessionName", () => {
	it("extracts name from config", () => {
		const content = '{"type":"config","name":"Optimize tests"}\n';
		expect(extractTuneSessionName(content)).toBe("Optimize tests");
	});

	it("returns default when no config", () => {
		expect(extractTuneSessionName('{"run":1}\n')).toBe("Tune");
	});
});

describe("reconstructJsonlState", () => {
	it("reconstructs from a complete session", () => {
		const content = [
			'{"type":"config","name":"test","metricName":"total_ms","metricUnit":"ms","bestDirection":"lower"}',
			'{"run":1,"commit":"abc1234","metric":100,"status":"keep","description":"baseline","timestamp":1000}',
			'{"run":2,"commit":"def5678","metric":95,"status":"keep","description":"optimized","timestamp":2000}',
		].join("\n");

		const state = reconstructJsonlState(content);
		expect(state.name).toBe("test");
		expect(state.metricName).toBe("total_ms");
		expect(state.bestDirection).toBe("lower");
		expect(state.results).toHaveLength(2);
		expect(state.results[0].metric).toBe(100);
		expect(state.results[1].metric).toBe(95);
		expect(state.currentSegment).toBe(0);
	});

	it("handles empty content", () => {
		const state = reconstructJsonlState("");
		expect(state.results).toHaveLength(0);
		expect(state.name).toBeNull();
	});

	it("segments on re-init", () => {
		const content = [
			'{"type":"config","name":"v1","metricName":"x"}',
			'{"run":1,"commit":"a","metric":10,"status":"keep","description":"b1","timestamp":1000}',
			'{"type":"config","name":"v2","metricName":"y"}',
			'{"run":2,"commit":"b","metric":20,"status":"keep","description":"b2","timestamp":2000}',
		].join("\n");

		const state = reconstructJsonlState(content);
		expect(state.results[0].segment).toBe(0);
		expect(state.results[1].segment).toBe(1);
		expect(state.currentSegment).toBe(1);
		expect(state.metricName).toBe("y");
	});
});

// ── Compaction summary ────────────────────────────────────────────────────

describe("buildTuneCompactionSummary", () => {
	it("produces a summary with no data", () => {
		const paths = {
			workDir: "/tmp/nonexistent",
			jsonlPath: "/tmp/nonexistent/session.jsonl",
			mdPath: "/tmp/nonexistent/session.md",
			ideasPath: "/tmp/nonexistent/ideas.md",
		};
		const summary = buildTuneCompactionSummary(paths);
		expect(summary).toContain("Tune Compaction Summary");
		expect(summary).toContain("Runs so far: 0");
		expect(summary).toContain("Next Step");
	});
});

// ── DEFAULT_MAX_LINES import regression ───────────────────────────────────
// https://github.com/earendil-works/pi-ext/issues/XXX
// ReferenceError: DEFAULT_MAX_LINES is not defined at runtime

describe("DEFAULT_MAX_LINES is defined", () => {
	it("is a positive number", () => {
		// Regression: DEFAULT_MAX_LINES was used but never imported.
		// If the import is missing again, this file fails to load.
		// Additionally verify the value is sane.
		expect(typeof DEFAULT_MAX_LINES).toBe("number");
		expect(DEFAULT_MAX_LINES).toBeGreaterThan(0);
	});
});

// ── Hook script path ──────────────────────────────────────────────────────

describe("hookScriptPath", () => {
	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"),
		);
	});
});