import { createHash } from "node:crypto"; import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; import { fingerprintSource } from "../lib/checker.ts"; import { createIsolatedTargetSession, promptTarget, runSplitRollout, runValidationBaseline, TARGET_CALL_TIMEOUT_MS, writeCandidateSnapshot, } from "../lib/rollouts.ts"; import { persistScoreCache, readBaselineCheckpoint } 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-rollouts-")); temporaryPaths.push(path); return path; } const source = { frontmatter: "---\nname: demo\ndescription: Demo\n---\n", body: "# Demo\n", name: "demo", description: "Demo", }; const loadedSkill = { name: "skill:demo", path: "/skill-package/SKILL.md", scope: "user", sourceInfo: { path: "/skill-package/SKILL.md", source: "user", scope: "user", origin: "top-level", baseDir: "/skill-package", }, }; const frozenModel = { provider: "test", id: "frozen", thinking: "high" }; const resolvedModel = { provider: "test", id: "frozen", thinkingLevelMap: { high: "high" }, }; function targetSession(events: unknown[] = []) { const listeners = new Set<(event: any) => void>(); return { prompts: [] as Array<[string, unknown]>, disposed: 0, aborted: 0, subscribe(listener: (event: any) => void) { listeners.add(listener); return () => listeners.delete(listener); }, async prompt(prompt: string, options?: unknown) { this.prompts.push([prompt, options]); for (const event of events) for (const listener of listeners) listener(event); }, async abort() { this.aborted += 1; }, dispose() { this.disposed += 1; }, }; } describe("isolated target session", () => { it("aborts a target call that exceeds the fixed deadline", async () => { expect(TARGET_CALL_TIMEOUT_MS).toBe(900_000); vi.useFakeTimers(); try { const target = targetSession(); target.prompt = async function (prompt: string, options?: unknown) { this.prompts.push([prompt, options]); await new Promise(() => {}); }; const result = promptTarget(target, "slow"); const rejection = expect(result).rejects.toThrow( `target rollout timed out after ${TARGET_CALL_TIMEOUT_MS / 1000}s`, ); await vi.advanceTimersByTimeAsync(TARGET_CALL_TIMEOUT_MS); await rejection; expect(target.aborted).toBe(1); } finally { vi.useRealTimers(); } }); it("uses a candidate-only normal skill loader with frozen model, thinking, and exactly read-only tools", async () => { const directory = await temporaryDirectory(); const snapshot = await writeCandidateSnapshot({ directory, source }); expect(await readFile(snapshot, "utf8")).toBe( "---\nname: demo\ndescription: Demo\n---\n# Demo\n", ); const created: Array> = []; const loaderOptions: Array> = []; const session = targetSession(); class Loader { constructor(options: Record) { loaderOptions.push(options); } async reload() { const options = loaderOptions.at(-1); if (!options) throw new Error("missing options"); const result = options.skillsOverride({ skills: [ { name: "demo", description: "Demo", filePath: loadedSkill.path, baseDir: "/skill-package", sourceInfo: { source: "temporary" }, disableModelInvocation: false, }, ], diagnostics: [], }); expect(result.skills).toEqual([ expect.objectContaining({ name: "demo", description: "Demo", filePath: snapshot, baseDir: "/skill-package", sourceInfo: loadedSkill.sourceInfo, disableModelInvocation: false, }), ]); } } await createIsolatedTargetSession( { cwd: "/project", agentDir: "/agent", sourcePath: loadedSkill.path, loadedSkill, candidatePath: snapshot, model: frozenModel, targetModel: resolvedModel, }, { DefaultResourceLoader: Loader, SettingsManager: { inMemory: (value: unknown) => value }, SessionManager: { inMemory: (cwd: string) => ({ kind: "in-memory", cwd }), }, async createAgentSession(options: Record) { created.push(options); return { session }; }, }, ); expect(loaderOptions).toHaveLength(1); expect(loaderOptions[0]).toMatchObject({ cwd: "/project", agentDir: "/agent", noExtensions: true, noSkills: true, noPromptTemplates: true, noThemes: true, noContextFiles: true, additionalSkillPaths: [loadedSkill.path], }); expect(loaderOptions[0]).not.toHaveProperty("systemPromptOverride"); expect(created).toEqual([ expect.objectContaining({ cwd: "/project", model: resolvedModel, thinkingLevel: "high", tools: ["read", "grep", "find", "ls"], sessionManager: { kind: "in-memory", cwd: "/project" }, }), ]); }); }); describe("validation baseline", () => { it("runs canonical validation items sequentially through normal skill expansion and atomically checkpoints bounded checker scores", async () => { const directory = await temporaryDirectory(); const calls: string[] = []; const sessions: ReturnType[] = []; const result = await runValidationBaseline( { directory, cwd: "/project", agentDir: "/agent", sourcePath: loadedSkill.path, source, loadedSkill, model: frozenModel, suite: { suitePath: "/project/suite", checkerPath: "/project/suite/check.mjs", splitCounts: { train: 1, val: 2, test: 1 }, }, items: [ { id: "z", prompt: "last" }, { id: "a", prompt: "first" }, ], }, { async createTarget() { const session = targetSession([ // End events deliberately omit args; starts establish call order. { type: "tool_execution_start", toolCallId: "read-1", toolName: "read", args: { path: "README.md" }, }, { type: "tool_execution_end", toolCallId: "read-1", toolName: "read", result: { content: [{ type: "text", text: "bounded" }] }, isError: false, }, { type: "message_end", message: { role: "assistant", stopReason: "stop", content: [{ type: "text", text: "final" }], }, }, ]); sessions.push(session); return session; }, async executeChecker(input) { const parsed = JSON.parse(input.input); calls.push(parsed.item.id); expect(parsed.trajectory.toolCalls).toEqual([ { name: "read", inputJson: '{"path":"README.md"}', outputText: "bounded", isError: false, }, ]); return { score: parsed.item.id === "a" ? 0.25 : 0.75, passed: true }; }, }, ); expect(calls).toEqual(["a", "z"]); expect(result.mean).toBe(0.5); expect(result.completed).toBe(2); expect(sessions).toHaveLength(2); for (const session of sessions) { expect(session.prompts).toHaveLength(1); expect(session.prompts[0]).toEqual([ expect.stringMatching(/^\/skill:demo /), { expandPromptTemplates: true }, ]); expect(session.disposed).toBe(1); } await expect(readBaselineCheckpoint(directory)).resolves.toMatchObject({ stage: "baseline_complete", completedItemIds: ["a", "z"], bodyHash: expect.stringMatching(/^[a-f0-9]{64}$/), }); }); it("rejects scoring when exact source bytes change during evaluator use", async () => { const directory = await temporaryDirectory(); const sourcePath = join(directory, "SKILL.md"); const sourceBytes = Buffer.from(`${source.frontmatter}${source.body}`); await writeFile(sourcePath, sourceBytes); await expect( runValidationBaseline( { directory, cwd: directory, agentDir: "/agent", sourcePath, sourceFingerprint: fingerprintSource(sourceBytes), source, loadedSkill, model: frozenModel, items: [{ id: "val", prompt: "validation" }], }, { async createTarget() { return targetSession([ { type: "message_end", message: { role: "assistant", stopReason: "stop", content: [{ type: "text", text: "final" }], }, }, ]); }, async scoreResponse() { await writeFile( sourcePath, Buffer.concat([sourceBytes, Buffer.from("changed")]), ); return { score: 1, passed: true }; }, }, ), ).rejects.toThrow("source fingerprint changed"); }); it("records parallel finalized tools in source order and rejects a terminal failed assistant message", async () => { const directory = await temporaryDirectory(); const checkerCalls: string[] = []; await expect( runValidationBaseline( { directory, cwd: "/project", agentDir: "/agent", sourcePath: loadedSkill.path, source, loadedSkill, model: frozenModel, suite: { suitePath: "/suite", checkerPath: "/suite/check.mjs", splitCounts: { train: 1, val: 1, test: 1 }, }, items: [{ id: "val", prompt: "validation" }], }, { async createTarget() { return targetSession([ { type: "tool_execution_start", toolCallId: "first", toolName: "read", args: { path: "a" }, }, { type: "tool_execution_start", toolCallId: "second", toolName: "grep", args: { pattern: "b" }, }, { type: "tool_execution_end", toolCallId: "second", toolName: "grep", result: { content: [{ type: "text", text: "second" }] }, isError: false, }, { type: "tool_execution_end", toolCallId: "first", toolName: "read", result: { content: [{ type: "text", text: "first" }] }, isError: false, }, { type: "message_end", message: { role: "assistant", stopReason: "stop", content: [{ type: "text", text: "intermediate" }], }, }, { type: "message_end", message: { role: "assistant", stopReason: "error", content: [], }, }, ]); }, async executeChecker(options) { checkerCalls.push(options.input); return { score: 1, passed: true }; }, }, ), ).rejects.toThrow("no final successful"); expect(checkerCalls).toEqual([]); }); it("replays private scores without target or checker calls and never requests held-out items", async () => { const directory = await temporaryDirectory(); const first = await runValidationBaseline( { directory, cwd: "/project", agentDir: "/agent", sourcePath: loadedSkill.path, source, loadedSkill, model: frozenModel, suite: { suitePath: "/suite", checkerPath: "/suite/check.mjs", splitCounts: { train: 1, val: 1, test: 1 }, }, items: [{ id: "val", prompt: "validation only" }], }, { async createTarget() { return targetSession([ { type: "message_end", message: { role: "assistant", stopReason: "stop", content: [{ type: "text", text: "final" }], }, }, ]); }, async executeChecker() { return { score: 0.5, passed: false }; }, }, ); expect(first.mean).toBe(0.5); let targets = 0; let checkers = 0; const replay = await runValidationBaseline( { directory, cwd: "/project", agentDir: "/agent", sourcePath: loadedSkill.path, source, loadedSkill, model: frozenModel, suite: { suitePath: "/suite", checkerPath: "/suite/check.mjs", splitCounts: { train: 1, val: 1, test: 1 }, }, items: [{ id: "val", prompt: "validation only" }], }, { async createTarget() { targets += 1; throw new Error("cache must not create targets"); }, async executeChecker() { checkers += 1; throw new Error("cache must not run checker"); }, }, ); expect(replay).toMatchObject({ mean: 0.5, completed: 1 }); expect({ targets, checkers }).toEqual({ targets: 0, checkers: 0 }); }); it("caches each candidate body and split independently", async () => { const directory = await temporaryDirectory(); let targets = 0; const options = { directory, cwd: "/project", agentDir: "/agent", sourcePath: loadedSkill.path, source, loadedSkill, model: frozenModel, suite: { suitePath: "/suite", checkerPath: "/suite/check.mjs", splitCounts: { train: 1, val: 1, test: 1 }, }, items: [{ id: "shared", prompt: "candidate" }], body: "# Changed\n", } as const; const seam = { async createTarget() { targets += 1; return targetSession([ { type: "message_end", message: { role: "assistant", stopReason: "stop", content: [{ type: "text", text: "final" }], }, }, ]); }, async executeChecker() { return { score: 1, passed: true }; }, }; await runSplitRollout({ ...options, split: "train" }, seam); await runSplitRollout({ ...options, split: "train" }, seam); await runSplitRollout({ ...options, split: "test" }, seam); expect(targets).toBe(2); }); it("rejects cached scores outside the exact requested split and rehydrates trajectory evidence", async () => { const directory = await temporaryDirectory(); const hash = createHash("sha256").update("candidate", "utf8").digest("hex"); await persistScoreCache( directory, { version: 1, bodyHash: hash, scores: [ { id: "other-split", score: 1, passed: true, evidenceFile: "evidence-0123456789abcdef.json", }, ], }, `scores-${hash}-train.json`, ); await expect( runSplitRollout( { directory, cwd: "/project", agentDir: "/agent", sourcePath: loadedSkill.path, source, loadedSkill, model: frozenModel, suite: { suitePath: "/suite", checkerPath: "/suite/check.mjs", splitCounts: { train: 1, val: 1, test: 1 }, }, items: [{ id: "train-1", prompt: "train" }], body: "candidate", split: "train", }, { async createTarget() { throw new Error("unsafe cache must be rejected before rollout"); }, async executeChecker() { throw new Error("unreachable"); }, }, ), ).rejects.toThrow("split"); const clean = await temporaryDirectory(); const rollout = await runSplitRollout( { directory: clean, cwd: "/project", agentDir: "/agent", sourcePath: loadedSkill.path, source, loadedSkill, model: frozenModel, suite: { suitePath: "/suite", checkerPath: "/suite/check.mjs", splitCounts: { train: 1, val: 1, test: 1 }, }, items: [{ id: "train-1", prompt: "train" }], body: "candidate", split: "train", }, { async createTarget() { return targetSession([ { type: "message_end", message: { role: "assistant", stopReason: "stop", content: [{ type: "text", text: "trajectory" }], }, }, ]); }, async executeChecker() { return { score: 0, passed: false, feedback: "checker evidence" }; }, }, ); expect(rollout.scores[0]).toMatchObject({ id: "train-1", trajectory: { response: "trajectory", trajectory: { assistantTexts: ["trajectory"] }, }, checker: { feedback: "checker evidence" }, }); }); it("resumes a partial validation baseline without replaying a checkpointed item", async () => { const directory = await temporaryDirectory(); const controller = new AbortController(); let targets = 0; const common = { directory, cwd: "/project", agentDir: "/agent", sourcePath: loadedSkill.path, source, loadedSkill, model: frozenModel, suite: { suitePath: "/suite", checkerPath: "/suite/check.mjs", splitCounts: { train: 1, val: 2, test: 1 }, }, items: [ { id: "a", prompt: "first" }, { id: "b", prompt: "second" }, ], }; await expect( runValidationBaseline( { ...common, signal: controller.signal }, { async createTarget() { targets += 1; const session = targetSession([ { type: "message_end", message: { role: "assistant", stopReason: "stop", content: [{ type: "text", text: "final" }], }, }, ]); if (targets === 2) session.prompt = async () => controller.abort(); return session; }, async executeChecker() { return { score: 0.5, passed: true }; }, }, ), ).rejects.toThrow("cancelled"); expect(await readBaselineCheckpoint(directory)).toMatchObject({ stage: "interrupted", completedItemIds: ["a"], }); const replayed: string[] = []; const resumed = await runValidationBaseline(common, { async createTarget() { return targetSession([ { type: "message_end", message: { role: "assistant", stopReason: "stop", content: [{ type: "text", text: "final" }], }, }, ]); }, async executeChecker(options) { replayed.push(JSON.parse(options.input).item.id); return { score: 0.75, passed: true }; }, }); expect(replayed).toEqual(["b"]); expect(resumed).toMatchObject({ completed: 2, mean: 0.625 }); }); it("aborts and disposes the active target without checkpointing an unscored item", async () => { const directory = await temporaryDirectory(); const controller = new AbortController(); const session = targetSession(); session.prompt = async () => { controller.abort(); }; await expect( runValidationBaseline( { directory, cwd: "/project", agentDir: "/agent", sourcePath: loadedSkill.path, source, loadedSkill, model: frozenModel, suite: { suitePath: "/suite", checkerPath: "/suite/check.mjs", splitCounts: { train: 1, val: 1, test: 1 }, }, items: [{ id: "val", prompt: "validation" }], signal: controller.signal, }, { async createTarget() { return session; }, async executeChecker() { throw new Error("checker must not run after cancellation"); }, }, ), ).rejects.toThrow("cancelled"); expect({ disposed: session.disposed, aborted: session.aborted }).toEqual({ disposed: 1, aborted: 1, }); await expect(readBaselineCheckpoint(directory)).resolves.toMatchObject({ stage: "interrupted", completedItemIds: [], }); }); });