repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/tune/__tests__/unit.test.ts

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

// ── 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);
	});
});

// ── 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");
	});
});

// ── Benchmark command guard ───────────────────────────────────────────────

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

	it("accepts node benchmark.mjs", () => {
		expect(isBenchmarkCommand("node .pi/tune/benchmark.mjs")).toBe(true);
	});

	it("accepts node with path to benchmark.mjs", () => {
		expect(isBenchmarkCommand("node benchmark.mjs")).toBe(true);
	});

	it("rejects arbitrary commands", () => {
		expect(isBenchmarkCommand("pnpm test")).toBe(false);
	});

	it("strips env prefix", () => {
		expect(isBenchmarkCommand("NODE_ENV=test node benchmark.mjs")).toBe(true);
	});

	it("rejects chained commands", () => {
		expect(isBenchmarkCommand("evil.py; node benchmark.mjs")).toBe(false);
		expect(isBenchmarkCommand("node benchmark.mjs && echo pwned")).toBe(false);
	});
});

// ── 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"],
		]);
	});
});

// ── /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(
			"/project/.pi/tune/hooks/before.mjs",
		);
		expect(hookScriptPath("/project", "after")).toBe(
			"/project/.pi/tune/hooks/after.mjs",
		);
	});
});