repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/overkill/__tests__/aftermath-acceptance.test.ts

Raw
File outline
import { createHash } from "node:crypto";
import {
	access,
	mkdir,
	mkdtemp,
	readdir,
	readFile,
	rm,
	writeFile,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { dirname, join, relative } from "node:path";
import { fileURLToPath } from "node:url";
import {
	type ExtensionCommandContext,
	SessionManager,
} from "@earendil-works/pi-coding-agent";
import {
	createTestSession,
	type TestSession,
} from "@marcfargas/pi-test-harness";
import { afterEach, describe, expect, it } from "vitest";
import {
	type AftermathAcceptanceSeam,
	installAftermathAcceptanceSeam,
	installModeAcceptanceSeam,
} from "../index.ts";
import {
	assignSplits,
	type FrozenTask,
	taskId,
} from "../lib/aftermath-mining.ts";
import { persistFrozenTasks, readFrozenTasks } from "../lib/aftermath-state.ts";

const extensionPath = fileURLToPath(new URL("../index.ts", import.meta.url));
const temporaryPaths: string[] = [];
let session: TestSession | undefined;
let removeSeam: (() => void) | undefined;
let removeModeSeam: (() => void) | undefined;
let originalAgentDir: string | undefined;
let activeMode: "tui" | "rpc" | "json" | "print" = "tui";
let terminalInput: ((data: string) => unknown) | undefined;
let terminalListenerRemoved = false;
const stdoutWrites: Array<{ fd: number; text: string }> = [];

afterEach(async () => {
	removeSeam?.();
	removeSeam = undefined;
	removeModeSeam?.();
	removeModeSeam = undefined;
	activeMode = "tui";
	terminalInput = undefined;
	terminalListenerRemoved = false;
	stdoutWrites.length = 0;
	session?.dispose();
	session = undefined;
	if (originalAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
	else process.env.PI_CODING_AGENT_DIR = originalAgentDir;
	await Promise.all(
		temporaryPaths
			.splice(0)
			.map((path) => rm(path, { force: true, recursive: true })),
	);
});

type Interruption =
	| "harvest"
	| "mining"
	| "judge"
	| "rollout"
	| "optimizer"
	| "final-test"
	| "persistence";

type Fixture = {
	root: string;
	agentDir: string;
	sessionDir: string;
	skill: string;
	sourceBefore: Buffer;
	persistedBefore: Map<string, Buffer>;
	sessionIds: string[];
};

type RecordedCall = {
	key: string;
	completed: boolean;
	kind: "mining" | "judge" | "target" | "optimizer";
	prompt: string;
};

type Runtime = {
	seam: AftermathAcceptanceSeam;
	calls: RecordedCall[];
	structuredCreations: Array<Record<string, any>>;
	structuredLoaders: Array<Record<string, unknown>>;
	disableInterruption: () => void;
	blocker: () => Promise<string | undefined>;
	tasks: FrozenTask[];
	splits: ReturnType<typeof assignSplits>;
};

function message(role: "user" | "assistant", text: string): any {
	if (role === "user")
		return { role, content: [{ type: "text", text }], timestamp: Date.now() };
	return {
		role,
		content: [{ type: "text", text }],
		api: "test",
		provider: "test",
		model: "test",
		usage: {
			input: 0,
			output: 0,
			cacheRead: 0,
			cacheWrite: 0,
			totalTokens: 0,
			cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
		},
		stopReason: "stop",
		timestamp: Date.now(),
	};
}

async function snapshotFiles(directory: string): Promise<Map<string, Buffer>> {
	const result = new Map<string, Buffer>();
	for (const entry of await readdir(directory, { withFileTypes: true })) {
		if (entry.isFile())
			result.set(entry.name, await readFile(join(directory, entry.name)));
	}
	return result;
}

async function createFixture(sessionCount = 6): Promise<Fixture> {
	const root = await mkdtemp(join(tmpdir(), "aftermath-acceptance-"));
	temporaryPaths.push(root);
	const agentDir = await mkdtemp(join(tmpdir(), "aftermath-acceptance-agent-"));
	temporaryPaths.push(agentDir);
	const sessionDir = join(agentDir, "acceptance-sessions");
	await mkdir(sessionDir, { recursive: true });
	const skill = join(root, ".pi", "skills", "demo", "SKILL.md");
	await mkdir(dirname(skill), { recursive: true });
	await writeFile(
		skill,
		"---\nname: demo\ndescription: Aftermath acceptance fixture\n---\n# Demo\n\nKeep source immutable.\n",
	);
	const sessionIds: string[] = [];
	for (let index = 0; index < sessionCount; index += 1) {
		const id = `10000000-0000-4000-8000-${String(index).padStart(12, "0")}`;
		sessionIds.push(id);
		const persisted = SessionManager.create(root, sessionDir, { id });
		persisted.appendMessage(
			message(
				"user",
				`<skill name="demo" location="${skill}">\nfixture\n</skill>\n\nPersisted task ${index}`,
			),
		);
		persisted.appendMessage(
			message("assistant", `Persisted response ${index}`),
		);
	}
	return {
		root,
		agentDir,
		sessionDir,
		skill,
		sourceBefore: await readFile(skill),
		persistedBefore: await snapshotFiles(sessionDir),
		sessionIds,
	};
}

function proposalTasks(sourceSessionIds: string[]): FrozenTask[] {
	for (let seed = 0; seed < 2_000; seed += 1) {
		const tasks = Array.from({ length: 10 }, (_, index) => {
			const body = {
				intent: `Acceptance intent ${seed}-${index}`,
				context: `Frozen context ${index}`,
				sourceSessionIds: sourceSessionIds.slice(0, 2),
				...(index % 2 === 0
					? {
							checks: [
								{
									type: "contains" as const,
									value: "PASS",
									caseSensitive: true,
								},
							],
						}
					: { rubric: "Score one only when the response contains GOOD." }),
			};
			return { id: taskId(body), ...body };
		});
		const splits = assignSplits(tasks);
		const byId = new Map(tasks.map((task) => [task.id, task]));
		const validation = splits.validation.map((id) => byId.get(id));
		if (
			validation.filter((task) => task?.rubric).length >= 2 &&
			validation.some((task) => task?.checks) &&
			splits.test.length >= 2
		)
			return tasks;
	}
	throw new Error("could not construct deterministic mixed task splits");
}

function proposals(tasks: readonly FrozenTask[]): unknown[] {
	return tasks.map(({ id: _id, ...task }) => task);
}

function deterministicRuntime(
	fixture: Fixture,
	options: {
		outcome?: "staged" | "no-improvement" | "insufficient";
		interrupt?: Interruption;
		onTarget?: (call: RecordedCall) => Promise<boolean>;
		onTargetAbort?: () => void;
	} = {},
): Runtime {
	const outcome = options.outcome ?? "staged";
	const tasks = proposalTasks(fixture.sessionIds);
	const selectedTasks = outcome === "insufficient" ? tasks.slice(0, 2) : tasks;
	const splits = assignSplits(selectedTasks);
	const byId = new Map(selectedTasks.map((task) => [task.id, task]));
	const testIntents = new Set(
		splits.test.map((id) => byId.get(id)?.intent).filter(Boolean),
	);
	const calls: RecordedCall[] = [];
	let interrupt = options.interrupt;
	let targetPath = "";
	let ranking = 0;
	let miningCalls = 0;
	let judgeCalls = 0;
	let baselineCalls = 0;
	let finalTestCalls = 0;
	let persistenceBlocker: string | undefined;
	let commandHandler: ((args: string) => Promise<void>) | undefined;
	const structuredCreations: Array<Record<string, any>> = [];
	const structuredLoaders: Array<Record<string, unknown>> = [];

	const cancel = async () => {
		const run = commandHandler;
		if (!run) throw new Error("acceptance command is unavailable");
		await run("aftermath cancel");
	};
	const shouldInterrupt = async (stage: Interruption): Promise<boolean> => {
		if (interrupt !== stage) return false;
		interrupt = undefined;
		await cancel();
		return true;
	};
	class StructuredLoader {
		constructor(readonly options: Record<string, unknown>) {
			structuredLoaders.push(options);
		}
		async reload() {}
	}
	const structuredSdk = {
		DefaultResourceLoader: StructuredLoader,
		SettingsManager: { inMemory: (value: unknown) => value },
		SessionManager: { inMemory: (cwd: string) => ({ kind: "memory", cwd }) },
		async createAgentSession(created: Record<string, any>) {
			structuredCreations.push(created);
			const listeners = new Set<(event: any) => void>();
			let aborted = false;
			return {
				session: {
					subscribe(listener: (event: any) => void) {
						listeners.add(listener);
						return () => listeners.delete(listener);
					},
					async prompt(prompt: string) {
						const mining = prompt.startsWith("phase:");
						const kind = mining ? "mining" : "judge";
						const call: RecordedCall = {
							kind,
							prompt,
							key: `${kind}:${createHash("sha256").update(prompt).digest("hex")}`,
							completed: false,
						};
						calls.push(call);
						if (mining) {
							miningCalls += 1;
							if (
								interrupt === "mining" &&
								miningCalls === 2 &&
								(await shouldInterrupt("mining"))
							)
								return;
							const details = { tasks: proposals(selectedTasks) };
							for (const listener of listeners)
								listener({
									type: "tool_execution_end",
									toolName: "structured_output",
									isError: false,
									result: { details },
								});
							call.completed = true;
							if (interrupt === "persistence") {
								interrupt = undefined;
								const roots = await readdir(
									join(fixture.agentDir, "overkill-runs"),
								);
								const runDirectory = join(
									fixture.agentDir,
									"overkill-runs",
									roots[0] ?? "missing",
								);
								persistenceBlocker = join(runDirectory, "tasks.json");
								await mkdir(persistenceBlocker);
							}
							return;
						}
						judgeCalls += 1;
						if (
							interrupt === "judge" &&
							judgeCalls === 2 &&
							(await shouldInterrupt("judge"))
						)
							return;
						const good = prompt.includes('"response":"PASS GOOD"');
						const details = {
							score: outcome === "no-improvement" ? 0 : good ? 1 : 0,
							passed: outcome !== "no-improvement" && good,
							rationale: good
								? "held frozen evidence passed"
								: "held frozen evidence failed",
						};
						for (const listener of listeners)
							listener({
								type: "tool_execution_end",
								toolName: "structured_output",
								isError: false,
								result: { details },
							});
						call.completed = true;
					},
					async abort() {
						aborted = true;
					},
					dispose() {
						void aborted;
					},
				},
			};
		},
	};
	class TargetLoader {
		constructor(private readonly loaderOptions: Record<string, any>) {}
		async reload() {
			const sourcePath = this.loaderOptions.additionalSkillPaths[0] as string;
			const loaded = this.loaderOptions.skillsOverride({
				skills: [
					{
						name: "demo",
						description: "fixture",
						filePath: sourcePath,
						baseDir: dirname(sourcePath),
						sourceInfo: { path: sourcePath },
					},
				],
				diagnostics: [],
			});
			targetPath = loaded.skills[0].filePath;
		}
	}
	const targetSdk = {
		DefaultResourceLoader: TargetLoader,
		SettingsManager: { inMemory: (value: unknown) => value },
		SessionManager: { inMemory: (cwd: string) => ({ kind: "memory", cwd }) },
		async createAgentSession() {
			const candidatePath = targetPath;
			const listeners = new Set<(event: any) => void>();
			return {
				session: {
					subscribe(listener: (event: any) => void) {
						listeners.add(listener);
						return () => listeners.delete(listener);
					},
					async prompt(prompt: string) {
						const body = await readFile(candidatePath, "utf8");
						const candidate = body.includes("AFTERMATH-CANDIDATE");
						const intent = [...byId.values()].find((task) =>
							prompt.includes(task.intent),
						)?.intent;
						const heldOut = intent !== undefined && testIntents.has(intent);
						const call: RecordedCall = {
							kind: "target",
							prompt,
							key: `target:${candidate ? "candidate" : "source"}:${prompt}`,
							completed: false,
						};
						calls.push(call);
						if (await options.onTarget?.(call)) return;
						if (!candidate && !heldOut) baselineCalls += 1;
						if (heldOut) finalTestCalls += 1;
						if (
							(interrupt === "rollout" &&
								baselineCalls === 2 &&
								(await shouldInterrupt("rollout"))) ||
							(interrupt === "final-test" &&
								heldOut &&
								finalTestCalls === 2 &&
								(await shouldInterrupt("final-test")))
						)
							return;
						const text =
							outcome === "no-improvement"
								? "unchanged response"
								: candidate
									? "PASS GOOD"
									: "baseline response";
						for (const listener of listeners)
							listener({
								type: "message_end",
								message: {
									role: "assistant",
									stopReason: "stop",
									content: [{ type: "text", text }],
								},
							});
						call.completed = true;
					},
					async abort() {
						options.onTargetAbort?.();
					},
					dispose() {},
				},
			};
		},
	};
	class OptimizerLoader {
		async reload() {}
	}
	const optimizerSdk = {
		DefaultResourceLoader: OptimizerLoader,
		SettingsManager: { inMemory: (value: unknown) => value },
		SessionManager: { inMemory: (cwd: string) => ({ kind: "memory", cwd }) },
		async createAgentSession() {
			const listeners = new Set<(event: any) => void>();
			return {
				session: {
					subscribe(listener: (event: any) => void) {
						listeners.add(listener);
						return () => listeners.delete(listener);
					},
					async prompt(prompt: string) {
						const phase = prompt.match(/^phase:(\w+)/u)?.[1] ?? "unknown";
						const call: RecordedCall = {
							kind: "optimizer",
							prompt,
							key: `optimizer:${createHash("sha256").update(prompt).digest("hex")}`,
							completed: false,
						};
						calls.push(call);
						if (
							interrupt === "optimizer" &&
							phase === "merge" &&
							(await shouldInterrupt("optimizer"))
						)
							return;
						const details =
							phase === "ranking"
								? {
										edits: [
											{
												op: "append",
												content:
													outcome === "no-improvement"
														? `NO-IMPROVEMENT-${++ranking}`
														: "AFTERMATH-CANDIDATE",
											},
										],
									}
								: { proposal: `${phase} proposal` };
						for (const listener of listeners)
							listener({
								type: "tool_execution_end",
								toolName: "structured_output",
								isError: false,
								result: { details },
							});
						call.completed = true;
					},
					async abort() {},
					dispose() {},
				},
			};
		},
	};
	const sessionApi = {
		async listAll() {
			if (interrupt === "harvest") await shouldInterrupt("harvest");
			return await SessionManager.listAll(fixture.sessionDir);
		},
		open(path: string) {
			return SessionManager.open(path, fixture.sessionDir);
		},
	};
	return {
		seam: {
			sessionApi,
			structuredOutputSdk: structuredSdk,
			targetSdk,
			optimizerSdk,
			bindCommand(handler) {
				commandHandler = handler;
			},
		},
		calls,
		structuredCreations,
		structuredLoaders,
		disableInterruption() {
			interrupt = undefined;
		},
		async blocker() {
			return persistenceBlocker;
		},
		tasks: selectedTasks,
		splits,
	};
}

async function load(
	fixture: Fixture,
	runtime: Runtime,
	options: {
		mode?: "tui" | "rpc" | "json" | "print";
		confirm?: boolean;
		select?: (title: string, items: string[]) => string | undefined;
	} = {},
): Promise<void> {
	originalAgentDir = process.env.PI_CODING_AGENT_DIR;
	process.env.PI_CODING_AGENT_DIR = fixture.agentDir;
	activeMode = options.mode ?? "tui";
	removeSeam = installAftermathAcceptanceSeam(runtime.seam);
	removeModeSeam = installModeAcceptanceSeam({
		write(fd, text) {
			stdoutWrites.push({ fd, text });
		},
	});
	session = await createTestSession({
		cwd: fixture.root,
		extensions: [extensionPath],
		mockUI: {
			select:
				options.select ??
				((_title, items) =>
					items.find((item) => item === "use demo") ?? items[0]),
			confirm: options.confirm ?? true,
		},
	});
	const current = session.session.sessionManager;
	const duplicate = SessionManager.create(fixture.root, fixture.sessionDir, {
		id: current.getSessionId(),
	});
	duplicate.appendMessage(message("user", "PERSISTED-DUPLICATE"));
	current.appendMessage(
		message(
			"user",
			`<skill name="demo" location="${fixture.skill}">\nfixture\n</skill>\n\nINVOKING-SNAPSHOT`,
		),
	);
	current.appendMessage(message("assistant", "Invoking response"));
	fixture.persistedBefore = await snapshotFiles(fixture.sessionDir);
	const registered =
		session.session.extensionRunner.extensions[0]?.commands.get("overkill");
	if (!registered) throw new Error("real Aftermath command was not registered");
	runtime.seam.bindCommand?.(async (args) => await command(args));
}

async function command(args: string): Promise<void> {
	if (!session) throw new Error("missing acceptance session");
	const registered =
		session.session.extensionRunner.extensions[0]?.commands.get("overkill");
	if (!registered) throw new Error("real overkill command was not registered");
	const base = session.session.extensionRunner.createCommandContext();
	const ui = new Proxy(base.ui, {
		get(target, property, receiver) {
			if (property === "onTerminalInput")
				return (handler: (data: string) => unknown) => {
					terminalInput = handler;
					terminalListenerRemoved = false;
					return () => {
						if (terminalInput === handler) terminalInput = undefined;
						terminalListenerRemoved = true;
					};
				};
			return Reflect.get(target, property, receiver);
		},
	});
	const ctx = new Proxy(base, {
		get(target, property, receiver) {
			if (property === "mode") return activeMode;
			if (property === "hasUI")
				return activeMode === "tui" || activeMode === "rpc";
			if (property === "ui") return ui;
			return Reflect.get(target, property, receiver);
		},
	}) as ExtensionCommandContext;
	await registered.handler(args, ctx);
}

function runEntries(): any[] {
	if (!session) throw new Error("missing acceptance session");
	return session.session.sessionManager
		.getBranch()
		.filter((entry: any) => entry.customType === "overkill-run");
}

async function runDirectory(fixture: Fixture): Promise<string> {
	const runId = runEntries().at(-1)?.data.runId;
	if (!runId) throw new Error("missing Aftermath run ID");
	return join(fixture.agentDir, "overkill-runs", runId);
}

async function expectInputsUnchanged(fixture: Fixture): Promise<void> {
	expect(await readFile(fixture.skill)).toEqual(fixture.sourceBefore);
	const after = await snapshotFiles(fixture.sessionDir);
	expect([...after.keys()].sort()).toEqual(
		[...fixture.persistedBefore.keys()].sort(),
	);
	for (const [path, bytes] of fixture.persistedBefore)
		expect(after.get(path), path).toEqual(bytes);
}

function expectCompletedCallsNotRepeated(calls: RecordedCall[]): void {
	const completed = calls
		.filter((call) => call.completed)
		.map((call) => call.key);
	for (const key of new Set(completed))
		expect(
			completed.filter((candidate) => candidate === key),
			key,
		).toHaveLength(1);
}

describe("registered /overkill aftermath acceptance", () => {
	it("harvests persisted active branches, replaces the invoking snapshot, confirms consent/target, mines fresh structured tasks, gates mixed scores, tests held-out tasks, stages privately, and securely discards", async () => {
		const fixture = await createFixture();
		const runtime = deterministicRuntime(fixture);
		await load(fixture, runtime);
		const beforeRunLeaf = session?.session.sessionManager.getLeafId();
		await command("aftermath");

		const progressWidgets = session?.events
			.uiCallsFor("setWidget")
			.filter((call) => call.args[0] === "overkill-progress");
		expect(
			progressWidgets?.some(
				(call) =>
					Array.isArray(call.args[1]) &&
					call.args[1][0] === "Overkill mining 0/1 · mining call 1 running",
			),
		).toBe(true);
		expect(progressWidgets?.at(-1)?.args).toEqual([
			"overkill-progress",
			undefined,
		]);
		const terminalEntry = runEntries().at(-1);
		const terminal = terminalEntry?.data;
		expect(terminal).toMatchObject({
			kind: "aftermath",
			stage: "complete",
			terminal: "staged",
			bestScore: 1,
		});
		const directory = await runDirectory(fixture);
		expect(relative(fixture.root, directory).startsWith("..")).toBe(true);
		const harvest = JSON.parse(
			await readFile(join(directory, "harvest.json"), "utf8"),
		);
		const current = harvest.digests.find(
			(digest: any) =>
				digest.sessionId === session?.session.sessionManager.getSessionId(),
		);
		expect(current.userPrompts.join("\n")).toContain("INVOKING-SNAPSHOT");
		expect(current.userPrompts.join("\n")).not.toContain("PERSISTED-DUPLICATE");
		expect(harvest.digests).toHaveLength(fixture.sessionIds.length + 1);
		const confirms = session?.events.uiCallsFor("confirm") ?? [];
		expect(confirms).toHaveLength(1);
		expect(confirms[0]?.args[1]).toContain("without redaction");
		expect(confirms[0]?.args[1]).toContain("16 KiB");
		const selects = session?.events.uiCallsFor("select") ?? [];
		expect(selects[0]?.args[0]).toBe("Choose exactly one Aftermath skill.");
		expect(selects[0]?.args[1][0]).toContain("demo —");
		const structured = runtime.calls.filter(
			(call) => call.kind === "mining" || call.kind === "judge",
		);
		expect(structured.every((call) => call.completed)).toBe(true);
		expect(runtime.structuredCreations).toHaveLength(structured.length);
		expect(
			runtime.structuredCreations.map((created) => created.sessionManager),
		).toHaveLength(
			new Set(
				runtime.structuredCreations.map((created) => created.sessionManager),
			).size,
		);
		for (const created of runtime.structuredCreations) {
			expect(created).toMatchObject({ tools: ["structured_output"] });
			expect(created.customTools).toEqual([
				expect.objectContaining({ name: "structured_output" }),
			]);
		}
		for (const loader of runtime.structuredLoaders)
			expect(loader).toMatchObject({
				noExtensions: true,
				noSkills: true,
				noPromptTemplates: true,
				noThemes: true,
				noContextFiles: true,
			});
		expect(runtime.calls.some((call) => call.kind === "judge")).toBe(true);
		expect(
			runtime.calls.some(
				(call) =>
					call.kind === "target" &&
					runtime.splits.test.some((id) =>
						call.prompt.includes(
							runtime.tasks.find((task) => task.id === id)?.intent ?? "never",
						),
					),
			),
		).toBe(true);
		const report = JSON.parse(
			await readFile(join(directory, "report.json"), "utf8"),
		);
		expect(report).toMatchObject({
			baselineScore: 0,
			bestScore: 1,
			testScore: 1,
			accepted: 1,
		});
		expect(
			await readFile(join(directory, "staged-skill.md"), "utf8"),
		).toContain("AFTERMATH-CANDIDATE");
		const frozen = await readFrozenTasks(directory);
		await expect(
			persistFrozenTasks(directory, frozen.tasks, frozen.splits),
		).rejects.toThrow("immutable");
		await expectInputsUnchanged(fixture);

		const sentinel = join(fixture.agentDir, "outside-sentinel");
		await writeFile(sentinel, "keep");
		if (!beforeRunLeaf || !terminalEntry)
			throw new Error("missing Aftermath branch fixtures");
		await session?.session.reload();
		await command("aftermath status");
		expect(session?.events.uiCallsFor("notify").at(-1)?.args[0]).toContain(
			"terminal: staged",
		);
		await command("aftermath review");
		expect(
			session?.events
				.uiCallsFor("notify")
				.some((call) =>
					String(call.args[0]).includes(`Source: ${fixture.skill}`),
				),
		).toBe(true);
		session?.session.sessionManager.branch(beforeRunLeaf);
		await command("aftermath status");
		expect(session?.events.uiCallsFor("notify").at(-1)?.args[0]).toContain(
			"No Overkill Aftermath run",
		);
		session?.session.sessionManager.branch(terminalEntry.id);
		await command("aftermath discard");
		await expect(access(directory)).rejects.toThrow();
		expect(await readFile(sentinel, "utf8")).toBe("keep");
		expect(runEntries().at(-1)?.data).toMatchObject({
			stage: "discarded",
			terminal: "discarded",
		});
	});

	it("uses RPC target/consent confirmations and reports completion review paths without embedding a diff", async () => {
		const fixture = await createFixture();
		const runtime = deterministicRuntime(fixture);
		await load(fixture, runtime, {
			mode: "rpc",
			select: (title, items) => {
				if (title.startsWith("Aftermath suggests")) return "use demo";
				if (title.startsWith("Aftermath complete")) return "review diff";
				return items[0];
			},
		});
		await command("aftermath");
		expect(session?.events.uiCallsFor("confirm")).toHaveLength(1);
		expect(session?.events.uiCallsFor("confirm")[0]?.args[1]).toContain(
			"without redaction",
		);
		const completion = session?.events.uiCallsFor("notify").at(-1)?.args[0];
		expect(completion).not.toContain(`Source: ${fixture.skill}`);
		expect(completion).toContain("Report:");
		expect(completion).toContain("Staged:");
		expect(completion).not.toContain(`--- ${fixture.skill}`);
		expect(completion).not.toContain("AFTERMATH-CANDIDATE");
		expect(stdoutWrites).toEqual([]);
	});

	it("falls back from a suggested target to exactly one user-selected loaded skill and keeps staged artifacts", async () => {
		const fixture = await createFixture();
		const other = join(fixture.root, ".pi", "skills", "other", "SKILL.md");
		await mkdir(dirname(other), { recursive: true });
		await writeFile(
			other,
			"---\nname: other\ndescription: Alternate acceptance skill\n---\n# Other\n",
		);
		const runtime = deterministicRuntime(fixture);
		await load(fixture, runtime, {
			select: (title, items) => {
				if (title.startsWith("Aftermath suggests")) return "choose another";
				if (title.startsWith("Choose exactly one"))
					return items.find((item) => item.startsWith("other —"));
				if (title.startsWith("Aftermath complete")) return "done";
				return items[0];
			},
		});
		await command("aftermath");
		const directory = await runDirectory(fixture);
		const manifest = JSON.parse(
			await readFile(join(directory, "manifest.json"), "utf8"),
		);
		expect(manifest.target).toEqual({ name: "other", path: other });
		expect(
			session?.events
				.uiCallsFor("notify")
				.some((call) => String(call.args[0]).includes("retained")),
		).toBe(false);
		await access(join(directory, "staged-skill.md"));
	});

	it("reports JSON progress only through parseable entry_appended events", async () => {
		const fixture = await createFixture();
		const runtime = deterministicRuntime(fixture);
		await load(fixture, runtime, { mode: "json" });
		await command(`aftermath "${fixture.skill}"`);
		const events = session?.events.all ?? [];
		expect(events.length).toBeGreaterThan(0);
		expect(events.every((event) => event.type === "entry_appended")).toBe(true);
		for (const event of events)
			expect(JSON.parse(JSON.stringify(event))).toMatchObject({
				type: "entry_appended",
				entry: { customType: "overkill-run" },
			});
		expect(stdoutWrites).toEqual([]);
		expect(session?.events.uiCallsFor("confirm")).toEqual([]);
		expect(session?.events.uiCallsFor("select")).toEqual([]);
	});

	it("writes print progress, absolute paths, and bounded review diff only to fd 1", async () => {
		const fixture = await createFixture();
		const runtime = deterministicRuntime(fixture);
		await load(fixture, runtime, { mode: "print" });
		await command(`aftermath "${fixture.skill}"`);
		await command("aftermath review");
		expect(stdoutWrites.length).toBeGreaterThan(0);
		expect(stdoutWrites.every((write) => write.fd === 1)).toBe(true);
		const output = stdoutWrites.map((write) => write.text).join("");
		const directory = await runDirectory(fixture);
		expect(output).toContain("Overkill mining");
		expect(output).toContain(`Source: ${fixture.skill}`);
		expect(output).toContain(`Report: ${join(directory, "report.json")}`);
		expect(output).toContain(`Staged: ${join(directory, "staged-skill.md")}`);
		const diff = output.slice(output.lastIndexOf(`--- ${fixture.skill}`));
		expect(diff).toContain("AFTERMATH-CANDIDATE");
		expect(diff.split("\n").length).toBeLessThanOrEqual(200);
		expect(Buffer.byteLength(diff, "utf8")).toBeLessThanOrEqual(32 * 1024);
		expect(session?.events.uiCallsFor("notify")).toEqual([]);
	});

	it("offers post-run discard and removes only the completed private run", async () => {
		const fixture = await createFixture();
		const runtime = deterministicRuntime(fixture, { outcome: "insufficient" });
		await load(fixture, runtime, {
			select: (title, items) =>
				title.startsWith("Aftermath complete") ? "discard report" : items[0],
		});
		await command("aftermath");
		const terminal = runEntries().at(-1)?.data;
		expect(terminal).toMatchObject({
			stage: "discarded",
			terminal: "discarded",
		});
		await expect(
			access(join(fixture.agentDir, "overkill-runs", terminal.runId)),
		).rejects.toThrow();
	});

	it("headlessly discards an inactive incomplete Aftermath run", async () => {
		const fixture = await createFixture();
		const runtime = deterministicRuntime(fixture, { interrupt: "rollout" });
		await load(fixture, runtime, { mode: "print" });
		await command(`aftermath "${fixture.skill}"`);
		const interrupted = runEntries().at(-1)?.data;
		expect(interrupted).toMatchObject({ terminal: null });
		const directory = await runDirectory(fixture);
		await command("aftermath discard");
		expect(runEntries().at(-1)?.data).toMatchObject({
			stage: "discarded",
			terminal: "discarded",
		});
		await expect(access(directory)).rejects.toThrow();
	});

	it.each(["resume", "discard", "cancel"] as const)(
		"offers %s for a linked interrupted run and never silently replaces it",
		async (choice) => {
			const fixture = await createFixture();
			const runtime = deterministicRuntime(fixture, { interrupt: "rollout" });
			await load(fixture, runtime, {
				select: (title, items) => {
					if (title.startsWith("Aftermath suggests")) return "use demo";
					if (title.startsWith("Resume incomplete")) return choice;
					if (title.startsWith("Aftermath complete")) return "done";
					return items[0];
				},
			});
			await command("aftermath");
			const interrupted = runEntries().at(-1);
			expect(interrupted?.data).toMatchObject({
				stage: "interrupted",
				terminal: null,
			});
			const directory = await runDirectory(fixture);
			await command(`aftermath "${fixture.skill}"`);
			expect(session?.events.uiCallsFor("notify").at(-1)?.args[0]).toContain(
				"use /overkill aftermath resume, discard, or cancel",
			);
			await command("aftermath");
			if (choice === "resume") {
				expect(runEntries().at(-1)?.data).toMatchObject({ terminal: "staged" });
				await access(directory);
			} else if (choice === "discard") {
				expect(runEntries().at(-1)?.data).toMatchObject({
					terminal: "discarded",
				});
				await expect(access(directory)).rejects.toThrow();
			} else {
				expect(runEntries().at(-1)?.data).toMatchObject({
					stage: "interrupted",
					terminal: null,
				});
				await access(directory);
			}
		},
	);

	it.each(["escape", "command", "sigint", "shutdown"] as const)(
		"checkpoint-cancels Aftermath via %s and removes temporary listeners/status",
		async (mechanism) => {
			const fixture = await createFixture();
			let release!: () => void;
			const gate = new Promise<void>((resolve) => {
				release = resolve;
			});
			let started!: () => void;
			const targetStarted = new Promise<void>((resolve) => {
				started = resolve;
			});
			let blocked = false;
			const runtime = deterministicRuntime(fixture, {
				onTarget: async () => {
					if (blocked) return false;
					blocked = true;
					started();
					await gate;
					return true;
				},
				onTargetAbort: release,
			});
			const mode = mechanism === "sigint" ? "print" : "tui";
			const baselineSignals = process.listenerCount("SIGINT");
			const baselineSignalListeners = new Set(process.rawListeners("SIGINT"));
			await load(fixture, runtime, { mode });
			const running = command(
				mode === "print" ? `aftermath "${fixture.skill}"` : "aftermath",
			);
			await targetStarted;
			if (mechanism === "escape") {
				expect(terminalInput?.("\u001b")).toEqual({ consume: true });
			} else if (mechanism === "command") {
				await command("aftermath cancel");
			} else if (mechanism === "sigint") {
				expect(process.listenerCount("SIGINT")).toBe(baselineSignals + 1);
				const firstSignal = process
					.rawListeners("SIGINT")
					.find((listener) => !baselineSignalListeners.has(listener));
				if (!firstSignal) throw new Error("missing first SIGINT listener");
				firstSignal.call(process);
				expect(process.listenerCount("SIGINT")).toBe(baselineSignals);
				expect(
					process
						.rawListeners("SIGINT")
						.every((listener) => baselineSignalListeners.has(listener)),
				).toBe(true);
			} else {
				await Promise.all([
					running,
					session?.session.extensionRunner.emit({
						type: "session_shutdown",
						reason: "reload",
					} as never),
				]);
			}
			await running;
			expect(runEntries().at(-1)?.data).toMatchObject({
				stage: "interrupted",
				terminal: null,
			});
			if (mode === "tui") {
				expect(terminalListenerRemoved).toBe(true);
				expect(terminalInput).toBeUndefined();
			}
			if (mode === "tui")
				expect(session?.events.uiCallsFor("setWidget").at(-1)?.args).toEqual([
					"overkill-progress",
					undefined,
				]);
			expect(process.listenerCount("SIGINT")).toBe(baselineSignals);
		},
	);

	it("completes insufficient-task mining without target, judge, optimizer, staging, or held-out access", async () => {
		const fixture = await createFixture();
		const runtime = deterministicRuntime(fixture, { outcome: "insufficient" });
		await load(fixture, runtime);
		await command("aftermath");
		const directory = await runDirectory(fixture);
		expect(runEntries().at(-1)?.data).toMatchObject({
			terminal: "no_improvement",
			completed: 2,
			total: 3,
		});
		expect(runtime.calls.filter((call) => call.kind !== "mining")).toEqual([]);
		await expect(access(join(directory, "staged-skill.md"))).rejects.toThrow();
		const report = JSON.parse(
			await readFile(join(directory, "report.json"), "utf8"),
		);
		expect(report).toMatchObject({ terminal: "insufficient_tasks" });
		const completion = session?.events
			.uiCallsFor("select")
			.find((call) =>
				String(call.args[0]).startsWith("Aftermath complete — no candidate"),
			);
		expect(completion?.args[0]).toContain(
			"Only 2/3 recurring tasks; replay was skipped.",
		);
		expect(completion?.args[0]).toContain(
			`Report: ${join(directory, "report.json")}`,
		);
		expect(completion?.args[1]).toEqual(["done", "discard report"]);
		await expectInputsUnchanged(fixture);
	});

	it("rejects tied candidates through the shared strict gate without staging or held-out access", async () => {
		const fixture = await createFixture();
		const runtime = deterministicRuntime(fixture, {
			outcome: "no-improvement",
		});
		await load(fixture, runtime);
		await command("aftermath");
		const directory = await runDirectory(fixture);
		expect(runEntries().at(-1)?.data).toMatchObject({
			terminal: "no_improvement",
		});
		await expect(access(join(directory, "staged-skill.md"))).rejects.toThrow();
		for (const id of runtime.splits.test) {
			const intent = runtime.tasks.find((task) => task.id === id)?.intent;
			expect(
				runtime.calls.some(
					(call) =>
						call.kind === "target" && call.prompt.includes(intent ?? "never"),
				),
			).toBe(false);
		}
		const report = JSON.parse(
			await readFile(join(directory, "report.json"), "utf8"),
		);
		expect(report).toMatchObject({ accepted: 0, terminal: "two_rejections" });
		const completion = session?.events
			.uiCallsFor("select")
			.find((call) => String(call.args[0]).startsWith("Aftermath complete"));
		expect(completion?.args[0]).toContain(
			"Best validation 0 did not beat baseline 0; no diff was staged.",
		);
		expect(completion?.args[0]).toContain(
			`Report: ${join(directory, "report.json")}`,
		);
		await expectInputsUnchanged(fixture);
	});

	it("cancels harvest before consent/artifacts and permits a clean deterministic restart", async () => {
		const fixture = await createFixture();
		const runtime = deterministicRuntime(fixture, { interrupt: "harvest" });
		await load(fixture, runtime);
		await command("aftermath");
		expect(runEntries()).toEqual([]);
		expect(session?.events.uiCallsFor("confirm")).toHaveLength(0);
		await expect(
			access(join(fixture.agentDir, "overkill-runs")),
		).rejects.toThrow();
		runtime.disableInterruption();
		await command("aftermath");
		expect(runEntries().at(-1)?.data).toMatchObject({ terminal: "staged" });
		await expectInputsUnchanged(fixture);
	});

	it.each([
		"mining",
		"judge",
		"rollout",
		"optimizer",
		"final-test",
		"persistence",
	] as const)(
		"resumes exactly after %s interruption without repeating durable completed calls",
		async (stage) => {
			const fixture = await createFixture(stage === "mining" ? 21 : 6);
			const runtime = deterministicRuntime(fixture, { interrupt: stage });
			await load(fixture, runtime);
			await command("aftermath");
			const blocker = await runtime.blocker();
			if (stage === "persistence") {
				expect(blocker).toBeDefined();
				await rm(blocker as string, { recursive: true, force: true });
			} else {
				expect(runEntries().at(-1)?.data).toMatchObject({
					stage: "interrupted",
					terminal: null,
				});
			}
			if (stage === "optimizer") {
				const interruptedEntry = runEntries().at(-1);
				const beforeRun = session?.session.sessionManager
					.getBranch()
					.find((entry: any) => entry.type === "message")?.id;
				if (!interruptedEntry || !beforeRun)
					throw new Error("missing Aftermath resume branch fixtures");
				session?.session.sessionManager.branch(beforeRun);
				await command("aftermath resume");
				expect(session?.events.uiCallsFor("notify").at(-1)?.args[0]).toContain(
					"No Overkill Aftermath run",
				);
				session?.session.sessionManager.branch(interruptedEntry.id);
				await session?.session.reload();
			}
			await command("aftermath resume");
			expect(runEntries().at(-1)?.data).toMatchObject({
				stage: "complete",
				terminal: "staged",
			});
			expectCompletedCallsNotRepeated(runtime.calls);
			await expectInputsUnchanged(fixture);
		},
	);
});