import { mkdir, mkdtemp, rm, symlink, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { visibleWidth } from "@earendil-works/pi-tui"; import { describe, expect, it } from "vitest"; import overkill, { chooseLoadedSkill, parseArguments, unfinishedRunWarning, } from "../index.ts"; import { createRunDirectory, persistManifest } from "../lib/run-state.ts"; type Command = { handler: (args: string, ctx: any) => Promise; getArgumentCompletions?: (prefix: string) => unknown; }; function setup(branch: unknown[] = [], loadedCommands: unknown[] = []) { const commands = new Map(); const notices: Array<[string, string]> = []; const userMessages: string[] = []; let next = 0; const pi = { on() {}, registerCommand(name: string, command: Command) { commands.set(name, command); }, registerEntryRenderer() {}, appendEntry(customType: string, data: unknown) { branch.push({ id: `entry-${next++}`, type: "custom", customType, data }); }, getCommands() { return loadedCommands; }, getThinkingLevel() { return "off"; }, sendUserMessage(message: string) { userMessages.push(message); }, }; overkill(pi as never); const ctx = { cwd: "/project", mode: "tui", hasUI: true, model: undefined, modelRegistry: { async getAvailable() { return []; }, }, isProjectTrusted() { return true; }, isIdle() { return true; }, sessionManager: { getBranch() { return branch; }, getSessionId() { return "session"; }, }, ui: { notify(message: string, level: string) { notices.push([message, level]); }, async select(_title: string, items: string[]) { return items[0]; }, }, }; return { branch, commands, ctx, notices, userMessages }; } function overkillCommand(state: ReturnType): Command { const command = state.commands.get("overkill"); if (!command) throw new Error("overkill command was not registered"); return command; } describe("/overkill Phase 3 command fixtures", () => { it("parses quoted, empty, concatenated, and Windows path arguments", () => { expect( parseArguments( '"path with spaces/SKILL.md" "" pre"joined value" \\\\server\\share', ), ).toEqual([ "path with spaces/SKILL.md", "", "prejoined value", "\\\\server\\share", ]); expect(() => parseArguments("'unterminated")).toThrow( "unterminated quoted argument", ); }); it("keeps a large Aftermath skill picker inside the terminal", async () => { const skills = Array.from({ length: 20 }, (_, index) => ({ name: `skill-${String(index).padStart(2, "0")}`, path: `/very/long/skill/path/${index}/SKILL.md`, })); let rendered: string[] = []; const selected = await chooseLoadedSkill( { mode: "tui", ui: { async custom(factory: any) { let result: string | null | undefined; const component = factory( { terminal: { rows: 12 }, requestRender() {} }, { bold: (text: string) => text, fg: (_color: string, text: string) => text, }, {}, (value: string | null) => { result = value; }, ); rendered = component.render(48); component.handleInput("\r"); return result; }, }, } as any, skills, new Map(skills.map((skill) => [skill.path, skill.path])), "Aftermath", ); expect(selected).toEqual(skills[0]); expect(rendered.length).toBeLessThanOrEqual(12); expect(rendered.some((line) => line.includes("(1/20)"))).toBe(true); expect(rendered.every((line) => visibleWidth(line) <= 48)).toBe(true); }); it("returns no skill when the small picker is cancelled", async () => { const skills = [ { name: "one", path: "/skills/one/SKILL.md" }, { name: "two", path: "/skills/two/SKILL.md" }, ]; const selected = await chooseLoadedSkill( { mode: "tui", ui: { async select() { return undefined; }, }, } as any, skills, new Map(skills.map((skill) => [skill.path, skill.path])), "Aftermath", ); expect(selected).toBeUndefined(); }); it("warns about unfinished matching runs from other processes", async () => { const agentDir = await mkdtemp( join(tmpdir(), "overkill-parallel-warning-"), ); try { const runId = "123e4567-e89b-12d3-a456-426614174000"; const directory = await createRunDirectory(agentDir, runId); await persistManifest(directory, { version: 1, runId, kind: "suite", source: { path: "/source/SKILL.md", fingerprint: "a".repeat(64) }, suite: { path: "/project/suite", fingerprint: "b".repeat(64) }, model: { provider: "test", id: "model", thinking: "off" }, sessionId: "session", linkEntryId: null, stage: "training", terminal: null, scores: { baseline: null, current: null, best: null, test: null, }, calls: { target: 0, checker: 0, optimizer: 0, judge: 0 }, artifacts: { baselineSnapshot: "baseline-snapshot.md", report: null, staged: null, }, }); const warning = await unfinishedRunWarning( "/source/SKILL.md", undefined, agentDir, ); expect(warning).toContain("1 unfinished Overkill run"); expect(warning).toContain(runId); expect(warning).toContain("other Pi processes"); } finally { await rm(agentDir, { force: true, recursive: true }); } }); it("reports complete branch-local suite status without exposing private data", async () => { const state = setup([ { id: "run", type: "custom", customType: "overkill-run", data: { version: 1, runId: "123e4567-e89b-12d3-a456-426614174000", kind: "suite", stage: "validation", terminal: "staged", completed: 2, total: 3, currentScore: 0.5, bestScore: 0.75, sourcePath: "/source/SKILL.md", reportPath: null, stagedPath: "/private/staged.md", }, }, ]); await overkillCommand(state).handler("status", state.ctx); expect(state.notices).toEqual([ [ "Overkill: validation | completed: 2/3 | current score: 0.5 | best score: 0.75 | terminal: staged | staged: /private/staged.md", "info", ], ]); }); it("explains a perfect baseline without raw terminal jargon", async () => { const state = setup([ { id: "run", type: "custom", customType: "overkill-run", data: { version: 1, runId: "123e4567-e89b-12d3-a456-426614174000", kind: "suite", stage: "complete", terminal: "no_improvement", completed: 8, total: 8, bestScore: 1, reportPath: "/private/report.json", stagedPath: null, }, }, ]); await overkillCommand(state).handler("status", state.ctx); expect(state.notices).toEqual([ [ "Overkill: complete | completed: 8/8 | outcome: baseline perfect; optimization skipped", "info", ], ]); }); it("reports checkpointed training and final-test progress for staged review without private evidence", async () => { const state = setup([ { id: "initial-link", type: "custom", customType: "overkill-run", data: { version: 1, runId: "123e4567-e89b-12d3-a456-426614174000", kind: "suite", stage: "final_test", terminal: null, completed: 1, total: 2, currentScore: 0.75, bestScore: 0.75, reportPath: null, stagedPath: null, }, }, { id: "staged", type: "custom", customType: "overkill-run", data: { version: 1, runId: "123e4567-e89b-12d3-a456-426614174000", kind: "suite", stage: "complete", terminal: "staged", currentScore: 0.75, bestScore: 0.75, reportPath: "/private/report.json", stagedPath: "/private/staged-skill.md", }, }, ]); await overkillCommand(state).handler("status", state.ctx); expect(state.notices.at(-1)).toEqual([ "Overkill: complete | current score: 0.75 | best score: 0.75 | terminal: staged | staged: /private/staged-skill.md", "info", ]); await overkillCommand(state).handler("cancel", state.ctx); expect(state.notices.at(-1)).toEqual([ "No Overkill rollout is active.", "info", ]); }); it("confirms the canonical cost contract before creating a run", async () => { const root = await mkdtemp(join(tmpdir(), "overkill-command-")); try { const skill = join(root, "SKILL.md"); const suite = join(root, "suite"); await writeFile(skill, "---\nname: demo\ndescription: Demo\n---\nBody\n"); for (const split of ["train", "val", "test"]) { await mkdir(join(suite, split), { recursive: true }); await writeFile( join(suite, split, "items.json"), JSON.stringify([{ id: split, prompt: `${split} task` }]), ); } await writeFile(join(suite, "check.mjs"), "process.exit(0)"); const state = setup( [], [ { name: "skill:demo", source: "skill", sourceInfo: { path: skill, scope: "user" }, }, ], ); const model = { provider: "test", id: "model" }; state.ctx.cwd = root; state.ctx.mode = "tui"; state.ctx.model = model; state.ctx.modelRegistry.find = () => model; state.ctx.modelRegistry.getAvailable = async () => [model]; let confirmation = ""; state.ctx.ui.confirm = async (_title: string, message: string) => { confirmation = message; return false; }; await overkillCommand(state).handler(`${skill} ${suite}`, state.ctx); expect(confirmation).toContain(`Source: ${skill}`); expect(confirmation).toContain(`Suite: ${suite}`); expect(confirmation).toContain( "Upper bound: 8 target calls, 12 optimizer calls.", ); expect(confirmation).toContain( "trusted checker executes project code with your process environment", ); expect(confirmation).toContain( "will not write the source skill or suite", ); expect(state.branch).toEqual([]); } finally { await rm(root, { force: true, recursive: true }); } }); it("reports missing terminal review artifacts without throwing", async () => { const state = setup([ { id: "run", type: "custom", customType: "overkill-run", data: { version: 1, runId: "00000000-0000-4000-8000-000000000001", kind: "suite", stage: "complete", terminal: "staged", reportPath: null, stagedPath: null, }, }, ]); await overkillCommand(state).handler("review", state.ctx); expect(state.notices.at(-1)?.[0]).toContain("Overkill review failed:"); }); it("emits headless status as a normal run entry instead of a no-op notification", async () => { const state = setup([ { id: "run", type: "custom", customType: "overkill-run", data: { version: 1, runId: "123e4567-e89b-12d3-a456-426614174000", kind: "suite", stage: "training", terminal: null, reportPath: null, stagedPath: null, }, }, ]); state.ctx.mode = "json"; await overkillCommand(state).handler("status", state.ctx); expect(state.notices).toEqual([]); expect(state.branch).toHaveLength(2); expect((state.branch.at(-1) as any).data).toMatchObject({ stage: "training", terminal: null, }); }); it("rejects suite-authoring destinations that escape through a symlink", async () => { const root = await mkdtemp(join(tmpdir(), "overkill-suite-symlink-")); const outside = await mkdtemp(join(tmpdir(), "overkill-suite-outside-")); try { const skill = join(root, "SKILL.md"); await writeFile(skill, "---\nname: demo\ndescription: Demo\n---\nBody\n"); await symlink( outside, join(root, "escaped"), process.platform === "win32" ? "junction" : "dir", ); const state = setup( [], [ { name: "skill:demo", source: "skill", sourceInfo: { path: skill, scope: "user" }, }, ], ); state.ctx.cwd = root; await overkillCommand(state).handler("suite SKILL.md escaped", state.ctx); expect(state.userMessages).toEqual([]); expect(state.notices.at(-1)?.[0]).toContain( "suite directory must be inside the project", ); } finally { await rm(root, { force: true, recursive: true }); await rm(outside, { force: true, recursive: true }); } }); it("teaches Pi to author a standard suite for one loaded skill", async () => { const root = await mkdtemp(join(tmpdir(), "overkill-suite-authoring-")); try { const skill = join(root, "SKILL.md"); await writeFile(skill, "---\nname: demo\ndescription: Demo\n---\nBody\n"); const state = setup( [], [ { name: "skill:demo", source: "skill", sourceInfo: { path: skill, scope: "user" }, }, ], ); state.ctx.cwd = root; await overkillCommand(state).handler("suite SKILL.md eval", state.ctx); expect(state.userMessages).toHaveLength(1); expect(state.userMessages[0]).toContain( `skill at ${JSON.stringify(skill)}`, ); expect(state.userMessages[0]).toContain( `Use ${JSON.stringify(join(root, "eval"))}`, ); expect(state.userMessages[0]).toContain("train/items.json"); expect(state.userMessages[0]).toContain("held-out test cases"); expect(state.userMessages[0]).toContain( "exactly 3 train items, 2 validation items, and 2 test items", ); expect(state.userMessages[0]).toContain( "suite contract below is authoritative", ); expect(state.userMessages[0]).toContain("keep check.mjs under 120 lines"); expect(state.userMessages[0]).toContain( "Do not design locks, atomic reservations, or repeated concurrency probes", ); expect(state.userMessages[0]).toContain( "Do not start Overkill automatically", ); } finally { await rm(root, { force: true, recursive: true }); } }); it("picks a skill and lets Pi choose a project-local suite directory", async () => { const root = await mkdtemp(join(tmpdir(), "overkill-suite-picker-")); try { const skill = join(root, "skills", "demo", "SKILL.md"); await mkdir(join(root, "skills", "demo"), { recursive: true }); await writeFile(skill, "---\nname: demo\ndescription: Demo\n---\nBody\n"); const state = setup( [], [ { name: "skill:demo", source: "skill", sourceInfo: { path: skill, scope: "user" }, }, ], ); state.ctx.cwd = root; await overkillCommand(state).handler("suite", state.ctx); expect(state.userMessages).toHaveLength(1); expect(state.userMessages[0]).toContain( `Choose a suite directory inside ${JSON.stringify(root)}`, ); expect(state.userMessages[0]).toContain( JSON.stringify(join(root, ".overkill", "suites", "demo")), ); } finally { await rm(root, { force: true, recursive: true }); } }); it("keeps completion boundaries and rejects malformed or extra arguments", async () => { const state = setup(); const command = overkillCommand(state); expect(command.getArgumentCompletions?.("su")).toEqual([ { value: "suite", label: "suite" }, ]); expect(command.getArgumentCompletions?.("aftermathx")).toBeNull(); await command.handler("only-one-path", state.ctx); expect(state.notices.at(-1)).toEqual([ "Usage: /overkill ", "error", ]); await command.handler("status extra", state.ctx); expect(state.notices.at(-1)).toEqual(["Usage: /overkill status", "error"]); await command.handler("aftermath status extra", state.ctx); expect(state.notices.at(-1)).toEqual([ "Usage: /overkill aftermath status", "error", ]); await command.handler("'unterminated", state.ctx); expect(state.notices.at(-1)).toEqual([ "Overkill command failed: unterminated quoted argument", "error", ]); }); });