import { access, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { createRunDirectory, discardLinkedRun, discardRun, persistCheckpoint, persistManifest, persistTrainingCheckpoint, readBaselineCheckpoint, readFrozenReviewArtifacts, readManifest, readTrainingCheckpoint, selectNewestSuiteRun, validateRunEntry, } from "../lib/run-state.ts"; const temporaryPaths: string[] = []; afterEach(async () => { await Promise.all( temporaryPaths .splice(0) .map((path) => rm(path, { force: true, recursive: true })), ); }); async function temporaryDirectory(): Promise { const path = await mkdtemp(join(tmpdir(), "overkill-state-")); temporaryPaths.push(path); return path; } const manifest = { version: 1 as const, runId: "123e4567-e89b-12d3-a456-426614174000", kind: "suite" as const, source: { path: "/source/SKILL.md", fingerprint: "a".repeat(64) }, suite: { path: "/suite", fingerprint: "b".repeat(64) }, model: { provider: "test", id: "model", thinking: "off" }, sessionId: "session", linkEntryId: "entry", stage: "preflight", 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" as const, report: null, staged: null, }, }; describe("private run artifacts", () => { it("creates private UUID directories and atomically persists bounded manifest/checkpoint data", async () => { const agentDir = await temporaryDirectory(); const directory = await createRunDirectory(agentDir, manifest.runId); expect(directory).toBe(join(agentDir, "overkill-runs", manifest.runId)); await persistManifest(directory, manifest); await persistCheckpoint(directory, { version: 1, stage: "preflight", completed: 0, total: 3, }); expect(await readManifest(directory)).toEqual(manifest); expect( JSON.parse(await readFile(join(directory, "checkpoint.json"), "utf8")), ).toEqual({ version: 1, stage: "preflight", completed: 0, total: 3 }); }); it("rejects unknown nested manifest fields and oversized branch-link identities", async () => { const directory = await temporaryDirectory(); await writeFile( join(directory, "manifest.json"), JSON.stringify({ ...manifest, model: { ...manifest.model, secret: "forbidden" }, }), ); await expect(readManifest(directory)).rejects.toThrow("unknown"); await writeFile( join(directory, "manifest.json"), JSON.stringify({ ...manifest, linkEntryId: "x".repeat(1025) }), ); await expect(readManifest(directory)).rejects.toThrow("bounded"); }); it("rejects unknown private checkpoint fields and non-evidence artifact names", async () => { const directory = await temporaryDirectory(); const valid = { version: 1, stage: "baseline", bodyHash: "a".repeat(64), completedItemIds: ["val"], total: 1, scores: [ { id: "val", score: 1, passed: true, evidenceFile: "evidence-0123456789abcdef.json", }, ], }; await writeFile( join(directory, "baseline-checkpoint.json"), JSON.stringify({ ...valid, response: "private response" }), ); await expect(readBaselineCheckpoint(directory)).rejects.toThrow("unknown"); await writeFile( join(directory, "baseline-checkpoint.json"), JSON.stringify({ ...valid, scores: [{ ...valid.scores[0], evidenceFile: "anything.json" }], }), ); await expect(readBaselineCheckpoint(directory)).rejects.toThrow("evidence"); }); it("atomically persists a durable Phase 3 scheduler checkpoint without bodies, prompts, or patches", async () => { const directory = await temporaryDirectory(); const checkpoint = { version: 1 as const, stage: "training" as const, nextStep: 2, currentBodyHash: "a".repeat(64), bestBodyHash: "b".repeat(64), currentSnapshot: `candidate-${"a".repeat(64)}.md`, bestSnapshot: `candidate-${"b".repeat(64)}.md`, baselineScore: 0.25, currentScore: 0.5, bestScore: 0.5, accepted: 1, optimizerCalls: 4, consecutiveRejections: 0, rejections: [{ reason: "tie", delta: 0 }], attemptedPatchFiles: ["attempt-1.json"], pendingOptimizer: { step: 2, failure: "prior reflection" }, finalTest: { bodyHash: "b".repeat(64), completedItemIds: [], total: 1, }, }; await persistTrainingCheckpoint(directory, checkpoint); expect(await readTrainingCheckpoint(directory)).toEqual(checkpoint); await writeFile( join(directory, "training-checkpoint.json"), JSON.stringify({ ...checkpoint, body: "private candidate" }), ); await expect(readTrainingCheckpoint(directory)).rejects.toThrow("unknown"); await expect( persistTrainingCheckpoint(directory, { ...checkpoint, attemptedPatchFiles: ["patch.json"], }), ).rejects.toThrow("attempt"); }); it("reviews only frozen private baseline and staged artifacts", async () => { const agentDir = await temporaryDirectory(); const directory = await createRunDirectory(agentDir, manifest.runId); await persistManifest(directory, { ...manifest, terminal: "staged" }); await writeFile(join(directory, "baseline-snapshot.md"), "frozen source"); await writeFile(join(directory, "staged-skill.md"), "frozen candidate"); const artifacts = await readFrozenReviewArtifacts(directory); expect(artifacts).toMatchObject({ sourcePath: manifest.source.path, source: "frozen source", staged: "frozen candidate", stagedPath: join(directory, "staged-skill.md"), }); }); it("never discards outside its private run root", async () => { const agentDir = await temporaryDirectory(); const directory = await createRunDirectory(agentDir, manifest.runId); await expect( discardRun(join(agentDir, "overkill-runs"), join(agentDir, "elsewhere")), ).rejects.toThrow("private run directory"); await discardRun(join(agentDir, "overkill-runs"), directory); await expect(readFile(join(directory, "manifest.json"))).rejects.toThrow(); }); it("discards only a run linked by its manifest to the active session branch", async () => { const agentDir = await temporaryDirectory(); const directory = await createRunDirectory(agentDir, manifest.runId); await persistManifest(directory, manifest); const entry = { version: 1, runId: manifest.runId, kind: "suite", stage: "preflight", terminal: null, }; const selected = { id: "forged", data: validateRunEntry(entry) }; await expect( discardLinkedRun({ runRoot: join(agentDir, "overkill-runs"), runDirectory: directory, selected, branch: [ { id: "forged", type: "custom", customType: "overkill-run", data: entry, }, ], sessionId: manifest.sessionId, }), ).rejects.toThrow("linked"); await access(join(directory, "manifest.json")); const linked = { id: manifest.linkEntryId as string, data: validateRunEntry(entry), }; await expect( discardLinkedRun({ runRoot: join(agentDir, "overkill-runs"), runDirectory: directory, selected: linked, branch: [ { id: manifest.linkEntryId, type: "custom", customType: "overkill-run", data: entry, }, ], sessionId: manifest.sessionId, }), ).rejects.toThrow("terminal"); await access(join(directory, "manifest.json")); const terminalEntry = { ...entry, terminal: "no_improvement" as const }; await persistManifest(directory, { ...manifest, terminal: "no_improvement", }); await discardLinkedRun({ runRoot: join(agentDir, "overkill-runs"), runDirectory: directory, selected: { id: "terminal-progress", data: validateRunEntry(terminalEntry), }, branch: [ { id: manifest.linkEntryId, type: "custom", customType: "overkill-run", data: entry, }, { id: "terminal-progress", type: "custom", customType: "overkill-run", data: terminalEntry, }, ], sessionId: manifest.sessionId, }); await expect(readFile(join(directory, "manifest.json"))).rejects.toThrow(); }); it("recovers a partial initial branch link before securely discarding", async () => { const agentDir = await temporaryDirectory(); const directory = await createRunDirectory(agentDir, manifest.runId); const terminalEntry = validateRunEntry({ version: 1, runId: manifest.runId, kind: "suite", stage: "complete", terminal: "no_improvement", }); await persistManifest(directory, { ...manifest, linkEntryId: null, stage: "complete", terminal: "no_improvement", }); await discardLinkedRun({ runRoot: join(agentDir, "overkill-runs"), runDirectory: directory, selected: { id: "initial-link", data: terminalEntry }, branch: [ { id: "initial-link", type: "custom", customType: "overkill-run", data: terminalEntry, }, ], sessionId: manifest.sessionId, }); await expect(access(directory)).rejects.toThrow(); }); it("permits inactive nonterminal discard but rejects an active run", async () => { const agentDir = await temporaryDirectory(); const directory = await createRunDirectory(agentDir, manifest.runId); await persistManifest(directory, manifest); const entry = validateRunEntry({ version: 1, runId: manifest.runId, kind: "suite", stage: "interrupted", terminal: null, }); const options = { runRoot: join(agentDir, "overkill-runs"), runDirectory: directory, selected: { id: manifest.linkEntryId as string, data: entry }, branch: [ { id: manifest.linkEntryId, type: "custom", customType: "overkill-run", data: entry, }, ], sessionId: manifest.sessionId, allowNonterminal: true, }; await expect( discardLinkedRun({ ...options, isRunActive: () => true }), ).rejects.toThrow("active"); await discardLinkedRun({ ...options, isRunActive: () => false }); await expect(access(directory)).rejects.toThrow(); }); }); describe("branch-local suite run entries", () => { it("validates bounded versioned data and selects the newest active-branch suite entry", () => { const entry = { version: 1, runId: manifest.runId, kind: "suite", stage: "preflight", terminal: null, sourcePath: "/source/SKILL.md", reportPath: null, stagedPath: null, }; expect(validateRunEntry(entry)).toEqual(entry); expect(() => validateRunEntry({ ...entry, prompt: "held out" })).toThrow( "unknown", ); expect( validateRunEntry({ ...entry, sourcePath: "\\\\server\\share\\SKILL.md" }), ).toMatchObject({ sourcePath: "\\\\server\\share\\SKILL.md" }); expect(() => validateRunEntry({ ...entry, stage: "x".repeat(1025) }), ).toThrow("stage"); expect(() => validateRunEntry({ ...entry, sourcePath: `/${"x".repeat(16 * 1024)}` }), ).toThrow("source path"); const selected = selectNewestSuiteRun([ { id: "old", type: "custom", customType: "overkill-run", data: entry }, { id: "other", type: "custom", customType: "overkill-run", data: { ...entry, kind: "aftermath" }, }, { id: "new", type: "custom", customType: "overkill-run", data: { ...entry, stage: "interrupted" }, }, ]); expect(selected?.id).toBe("new"); expect( selectNewestSuiteRun([ { id: "bad", type: "custom", customType: "overkill-run", data: { ...entry, version: 2 }, }, ]), ).toBeUndefined(); }); });