repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by bugabinga
extensions/tune/__tests__/unit.test.ts
RawFile outline
- parseMetricLines line 17
- { parseMetricLines } line 18
- parses single METRIC line line 20
- parses multiple METRIC lines line 25
- ignores non-METRIC lines line 32
- rejects NaN and Infinity values line 38
- rejects prototype pollution names line 44
- formatNum line 52
- { formatNum } line 53
- formats integers with commas line 55
- formats with unit suffix line 59
- formats fractional with 2 decimals line 63
- isBenchmarkCommand line 70
- { isBenchmarkCommand } line 71
- accepts node benchmark.mjs line 73
- accepts node with path to benchmark.mjs line 77
- rejects arbitrary commands line 81
- strips env prefix line 85
- rejects chained commands line 89
- vcs backend line 97
- detects jj before git line 98
- uses jj describe and jj new on keep line 108
- uses jj abandon and jj new on discard line 130
- tune autocomplete line 149
- { tuneArgumentCompletions, tuneCommandArgumentSuggestions } line 150
- suggests subcommands from argument prefixes line 152
- does not suggest after freeform objective text begins line 161
- intercepts forced autocomplete for tune subcommands line 166
- parseJsonlEntry line 185
- parses valid JSON line 186
- returns null for invalid JSON line 192
- returns null for arrays line 196
- isTuneConfigEntry line 201
- recognizes config entries line 202
- rejects run entries line 206
- isTuneRunEntry line 211
- recognizes run entries line 212
- rejects non-run entries line 216
- hasTuneConfigHeader line 221
- detects config header line 222
- returns false for no config line 227
- extractTuneSessionName line 233
- extracts name from config line 234
- returns default when no config line 239
- reconstructJsonlState line 244
- reconstructs from a complete session line 245
- handles empty content line 262
- segments on re-init line 268
- buildTuneCompactionSummary line 286
- produces a summary with no data line 287
- DEFAULT_MAX_LINES is defined line 305
- is a positive number line 306
- hookScriptPath line 317
- resolves to .pi/tune/hooks/{stage}.mjs line 318
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",
);
});
});