repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/overkill/__tests__/acceptance.test.ts

Raw
File outline
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 {
	createTestSession,
	type TestSession,
} from "@marcfargas/pi-test-harness";
import { afterEach, describe, expect, it } from "vitest";
import {
	type ExplicitSuiteAcceptanceSeam,
	installExplicitSuiteAcceptanceSeam,
	installModeAcceptanceSeam,
} from "../index.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 TargetCall = {
	body: string;
	completed: boolean;
	prompt: string;
};

type DeterministicRuntime = {
	seam: ExplicitSuiteAcceptanceSeam;
	targetCalls: TargetCall[];
	optimizerCalls: Array<{ completed: boolean; phase: string }>;
};

type Fixture = {
	root: string;
	agentDir: string;
	skill: string;
	suite: string;
	checkerLog: string;
	sourceBefore: Buffer;
	suiteBefore: Map<string, Buffer>;
};

async function snapshotDirectory(root: string): Promise<Map<string, Buffer>> {
	const result = new Map<string, Buffer>();
	const visit = async (directory: string) => {
		for (const entry of await readdir(directory, { withFileTypes: true })) {
			const path = join(directory, entry.name);
			if (entry.isDirectory()) await visit(path);
			else result.set(path.slice(root.length + 1), await readFile(path));
		}
	};
	await visit(root);
	return result;
}

async function fixture(
	options: { validationItems?: number; testItems?: number } = {},
): Promise<Fixture> {
	const root = await mkdtemp(join(tmpdir(), "overkill-acceptance-"));
	temporaryPaths.push(root);
	const agentDir = await mkdtemp(join(tmpdir(), "overkill-acceptance-agent-"));
	temporaryPaths.push(agentDir);
	const skill = join(root, ".pi", "skills", "demo", "SKILL.md");
	const suite = join(root, "suite");
	const checkerLog = join(root, "checker-calls.ndjson");
	await mkdir(dirname(skill), { recursive: true });
	await writeFile(
		skill,
		"---\nname: demo\ndescription: Acceptance fixture\n---\n# Demo\n\nKeep this source immutable.\n",
	);
	const counts = {
		train: 1,
		val: options.validationItems ?? 2,
		test: options.testItems ?? 2,
	};
	for (const [split, count] of Object.entries(counts)) {
		await mkdir(join(suite, split), { recursive: true });
		await writeFile(
			join(suite, split, "items.json"),
			`${JSON.stringify(
				Array.from({ length: count }, (_, index) => ({
					id: `${split}-${index + 1}`,
					prompt: `${split === "val" ? "validation" : split} ${index + 1}`,
				})),
			)}\n`,
		);
	}
	await writeFile(
		join(suite, "check.mjs"),
		`import { appendFileSync } from "node:fs";
let input = "";
process.stdin.setEncoding("utf8");
process.stdin.on("data", chunk => input += chunk);
process.stdin.on("end", () => {
  const value = JSON.parse(input);
  const match = /^score=([0-9.]+)$/u.exec(value.response);
  if (!match) process.exit(9);
  const score = Number(match[1]);
  appendFileSync(${JSON.stringify(checkerLog)}, JSON.stringify({ id: value.item.id, response: value.response }) + "\\n");
  process.stdout.write(JSON.stringify({ score, passed: score === 1, feedback: "fixture" }));
});
`,
	);
	return {
		root,
		agentDir,
		skill,
		suite,
		checkerLog,
		sourceBefore: await readFile(skill),
		suiteBefore: await snapshotDirectory(suite),
	};
}

function deterministicRuntime(options: {
	candidateScore: number;
	patchContent?: (ranking: number) => string;
	onTarget?: (call: TargetCall) => Promise<boolean>;
	onOptimizer?: (phase: string) => Promise<boolean>;
	onTargetAbort?: () => void;
}): DeterministicRuntime {
	const targetCalls: TargetCall[] = [];
	const optimizerCalls: Array<{ completed: boolean; phase: string }> = [];
	let candidatePath = "";
	let ranking = 0;
	class TargetLoader {
		private readonly options: Record<string, any>;
		constructor(loaderOptions: Record<string, any>) {
			this.options = loaderOptions;
		}
		async reload() {
			const sourcePath = this.options.additionalSkillPaths[0] as string;
			const overridden = this.options.skillsOverride({
				skills: [
					{
						name: "demo",
						description: "Acceptance fixture",
						filePath: sourcePath,
						baseDir: dirname(sourcePath),
						sourceInfo: { path: sourcePath },
					},
				],
				diagnostics: [],
			});
			candidatePath = overridden.skills[0].filePath;
		}
	}
	class OptimizerLoader {
		async reload() {}
	}
	const targetSdk = {
		DefaultResourceLoader: TargetLoader,
		SettingsManager: { inMemory: (value: unknown) => value },
		SessionManager: { inMemory: (cwd: string) => ({ cwd }) },
		async createAgentSession() {
			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 snapshot = await readFile(candidatePath, "utf8");
						const body = snapshot.slice(snapshot.indexOf("---\n", 4) + 4);
						const call = { body, completed: false, prompt };
						targetCalls.push(call);
						if ((await options.onTarget?.(call)) || aborted) return;
						const task = prompt.slice(prompt.indexOf(" ") + 1);
						const score = task.startsWith("train")
							? 0
							: task.startsWith("test")
								? 0.5
								: body.includes("Keep this source immutable.") &&
										!body.includes("ACCEPTANCE-CANDIDATE") &&
										!body.includes("TRY-")
									? 0.25
									: options.candidateScore;
						for (const listener of listeners)
							listener({
								type: "message_end",
								message: {
									role: "assistant",
									stopReason: "stop",
									content: [{ type: "text", text: `score=${score}` }],
								},
							});
						call.completed = true;
					},
					async abort() {
						aborted = true;
						options.onTargetAbort?.();
					},
					dispose() {},
				},
			};
		},
	};
	const optimizerSdk = {
		DefaultResourceLoader: OptimizerLoader,
		SettingsManager: { inMemory: (value: unknown) => value },
		SessionManager: { inMemory: (cwd: string) => ({ cwd }) },
		async createAgentSession() {
			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 phase = prompt.match(/^phase:(\w+)/u)?.[1] ?? "unknown";
						const call = { completed: false, phase };
						optimizerCalls.push(call);
						if ((await options.onOptimizer?.(phase)) || aborted) return;
						const details =
							phase === "ranking"
								? {
										edits: [
											{
												op: "append",
												content:
													options.patchContent?.(++ranking) ??
													"ACCEPTANCE-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() {
						aborted = true;
					},
					dispose() {},
				},
			};
		},
	};
	return { seam: { targetSdk, optimizerSdk }, targetCalls, optimizerCalls };
}

async function load(
	fixture: Fixture,
	runtime: DeterministicRuntime,
	options: {
		mode?: "tui" | "rpc" | "json" | "print";
		confirm?: boolean;
	} = {},
): Promise<void> {
	originalAgentDir = process.env.PI_CODING_AGENT_DIR;
	process.env.PI_CODING_AGENT_DIR = fixture.agentDir;
	activeMode = options.mode ?? "tui";
	removeSeam = installExplicitSuiteAcceptanceSeam(runtime.seam);
	removeModeSeam = installModeAcceptanceSeam({
		write(fd, text) {
			stdoutWrites.push({ fd, text });
		},
	});
	session = await createTestSession({
		cwd: fixture.root,
		extensions: [extensionPath],
		mockUI: { confirm: options.confirm ?? true },
	});
	expect(
		session.session.extensionRunner.extensions[0]?.commands.has("overkill"),
	).toBe(true);
}

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);
		},
	});
	await registered.handler(args, ctx);
}

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

async function start(fixture: Fixture): Promise<void> {
	await command(`"${fixture.skill}" "${fixture.suite}"`);
}

async function checkerCalls(
	fixture: Fixture,
): Promise<Array<{ id: string; response: string }>> {
	return (await readFile(fixture.checkerLog, "utf8"))
		.trim()
		.split("\n")
		.filter(Boolean)
		.map((line) => JSON.parse(line));
}

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

describe("registered /overkill explicit-suite acceptance", () => {
	it("strictly improves through held-out test, stages privately, emits branch progress, bounds review, and preserves inputs", async () => {
		const data = await fixture();
		const largePatch = [
			"ACCEPTANCE-CANDIDATE",
			...Array.from({ length: 260 }, (_, index) => `review-line-${index}`),
		].join("\n");
		const runtime = deterministicRuntime({
			candidateScore: 1,
			patchContent: () => largePatch,
		});
		await load(data, runtime);
		await start(data);

		const progressWidgets = session?.events
			.uiCallsFor("setWidget")
			.filter((call) => call.args[0] === "overkill-progress");
		expect(
			progressWidgets?.some(
				(call) =>
					Array.isArray(call.args[1]) &&
					String(call.args[1][0]).startsWith("Overkill baseline"),
			),
		).toBe(true);
		expect(progressWidgets?.at(-1)?.args).toEqual([
			"overkill-progress",
			undefined,
		]);
		const entries = branchEntries();
		expect(entries.at(-1)?.data).toMatchObject({
			kind: "suite",
			stage: "complete",
			terminal: "staged",
			currentScore: 1,
			bestScore: 1,
		});
		const stages = entries.map((entry) => entry.data.stage);
		expect(stages).toEqual(["preflight", "complete"]);
		const runId = entries.at(-1)?.data.runId;
		const runDirectory = join(data.agentDir, "overkill-runs", runId);
		expect(relative(data.root, runDirectory).startsWith("..")).toBe(true);
		const staged = await readFile(
			join(runDirectory, "staged-skill.md"),
			"utf8",
		);
		expect(staged).toContain(largePatch);
		expect((await checkerCalls(data)).map((call) => call.id)).toEqual([
			"val-1",
			"val-2",
			"train-1",
			"val-1",
			"val-2",
			"test-1",
			"test-2",
		]);
		const report = JSON.parse(
			await readFile(join(runDirectory, "report.json"), "utf8"),
		);
		expect(report).toMatchObject({
			baselineScore: 0.25,
			bestScore: 1,
			testScore: 0.5,
			accepted: 1,
		});

		await command("review");
		const review = session?.events.uiCallsFor("notify").at(-1)?.args[0];
		expect(review).toContain("…[diff truncated]");
		expect(String(review).split("\n").length).toBeLessThanOrEqual(200);
		expect(Buffer.byteLength(String(review), "utf8")).toBeLessThanOrEqual(
			32 * 1024,
		);
		await expectInputsUnchanged(data);
	});

	it("stops after two ties without held-out rollout or staged artifact", async () => {
		const data = await fixture();
		const runtime = deterministicRuntime({
			candidateScore: 0.25,
			patchContent: (ranking) => `TRY-${ranking}`,
		});
		await load(data, runtime);
		await start(data);

		const terminal = branchEntries().at(-1)?.data;
		expect(terminal).toMatchObject({
			stage: "complete",
			terminal: "no_improvement",
		});
		const runDirectory = join(data.agentDir, "overkill-runs", terminal.runId);
		await expect(
			access(join(runDirectory, "staged-skill.md")),
		).rejects.toThrow();
		expect(
			runtime.targetCalls.some((call) => call.prompt.includes("test ")),
		).toBe(false);
		expect(
			(await checkerCalls(data)).some((call) => call.id.startsWith("test-")),
		).toBe(false);
		const report = JSON.parse(
			await readFile(join(runDirectory, "report.json"), "utf8"),
		);
		expect(report).toMatchObject({ accepted: 0, terminal: "two_rejections" });
		expect(report).not.toHaveProperty("testScore");
		await command("review");
		expect(session?.events.uiCallsFor("notify").at(-1)?.args[0]).toContain(
			"No candidate staged.",
		);
		await expectInputsUnchanged(data);
	});

	it.each(["tui", "rpc"] as const)(
		"requires the canonical %s confirmation before creating artifacts",
		async (mode) => {
			const data = await fixture();
			const runtime = deterministicRuntime({ candidateScore: 1 });
			await load(data, runtime, { mode, confirm: false });
			await start(data);
			const confirms = session?.events.uiCallsFor("confirm") ?? [];
			expect(confirms).toHaveLength(1);
			expect(confirms[0]?.args[1]).toContain(`Source: ${data.skill}`);
			expect(confirms[0]?.args[1]).toContain(`Suite: ${data.suite}`);
			expect(confirms[0]?.args[1]).toContain(
				"trusted checker executes project code with your process environment",
			);
			expect(confirms[0]?.args[1]).toContain(
				"will not write the source skill or suite",
			);
			expect(branchEntries()).toEqual([]);
			await expect(
				access(join(data.agentDir, "overkill-runs")),
			).rejects.toThrow();
		},
	);

	it("emits JSON progress only as parseable entry_appended events without stdout writes", async () => {
		const data = await fixture({ validationItems: 1, testItems: 1 });
		const runtime = deterministicRuntime({ candidateScore: 1 });
		await load(data, runtime, { mode: "json" });
		await start(data);
		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) {
			const parsed = JSON.parse(JSON.stringify(event));
			expect(parsed).toMatchObject({
				type: "entry_appended",
				entry: { customType: "overkill-run" },
			});
		}
		expect(stdoutWrites).toEqual([]);
		expect(session?.events.uiCallsFor("notify")).toEqual([]);
	});

	it("writes print progress and bounded review to fd 1 with absolute artifact paths", async () => {
		const data = await fixture({ validationItems: 1, testItems: 1 });
		const patch = [
			"ACCEPTANCE-CANDIDATE",
			...Array.from({ length: 260 }, (_, index) => `print-line-${index}`),
		].join("\n");
		const runtime = deterministicRuntime({
			candidateScore: 1,
			patchContent: () => patch,
		});
		await load(data, runtime, { mode: "print" });
		await start(data);
		await command("review");
		expect(stdoutWrites.length).toBeGreaterThan(0);
		expect(stdoutWrites.every((write) => write.fd === 1)).toBe(true);
		const output = stdoutWrites.map((write) => write.text).join("");
		const runId = branchEntries().at(-1)?.data.runId;
		const directory = join(data.agentDir, "overkill-runs", runId);
		expect(output).toContain("Overkill baseline");
		expect(output).toContain(`Source: ${data.skill}`);
		expect(output).toContain(`Report: ${join(directory, "report.json")}`);
		expect(output).toContain(`Staged: ${join(directory, "staged-skill.md")}`);
		const diff = output.slice(output.lastIndexOf(`--- ${data.skill}`));
		expect(diff).toContain("…[diff truncated]");
		expect(diff.split("\n").length).toBeLessThanOrEqual(201);
		expect(Buffer.byteLength(diff, "utf8")).toBeLessThanOrEqual(32 * 1024);
		expect(session?.events.uiCallsFor("notify")).toEqual([]);
	});

	it.each(["escape", "command", "sigint", "shutdown"] as const)(
		"checkpoint-cancels via %s, removes temporary listeners/status, then resumes",
		async (mechanism) => {
			const data = await fixture();
			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({
				candidateScore: 1,
				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(data, runtime, { mode });
			const running = start(data);
			await targetStarted;
			if (mechanism === "escape") {
				expect(terminalInput).toBeTypeOf("function");
				expect(terminalInput?.("\u001b")).toEqual({ consume: true });
			} else if (mechanism === "command") {
				await command("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(branchEntries().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);
			await command("resume");
			expect(branchEntries().at(-1)?.data).toMatchObject({
				stage: "complete",
				terminal: "staged",
			});
		},
	);

	it("keeps suite status, review, branch selection, and discard durable across extension reload", async () => {
		const data = await fixture({ validationItems: 1, testItems: 1 });
		const runtime = deterministicRuntime({ candidateScore: 1 });
		await load(data, runtime);
		await start(data);
		const terminalEntry = branchEntries().at(-1);
		const runId = terminalEntry?.data.runId;
		if (!terminalEntry || !runId)
			throw new Error("missing terminal suite entry");
		const directory = join(data.agentDir, "overkill-runs", runId);
		await session?.session.reload();
		await command("status");
		expect(session?.events.uiCallsFor("notify").at(-1)?.args[0]).toContain(
			"terminal: staged",
		);
		await command("review");
		expect(
			session?.events
				.uiCallsFor("notify")
				.some((call) => String(call.args[0]).includes(`Source: ${data.skill}`)),
		).toBe(true);
		session?.session.sessionManager.resetLeaf();
		await command("status");
		expect(session?.events.uiCallsFor("notify").at(-1)?.args[0]).toContain(
			"No Overkill suite run",
		);
		session?.session.sessionManager.branch(terminalEntry.id);
		await command("discard");
		await expect(access(directory)).rejects.toThrow();
		expect(branchEntries().at(-1)?.data).toMatchObject({
			stage: "discarded",
			terminal: "discarded",
		});
		expect(session?.events.uiCallsFor("setWidget").at(-1)?.args).toEqual([
			"overkill-progress",
			undefined,
		]);
	});

	it("discards an interrupted inactive suite run", async () => {
		const data = await fixture();
		let cancelled = false;
		const runtime = deterministicRuntime({
			onTarget: async (call) => {
				if (cancelled || !call.prompt.includes("validation 2")) return false;
				cancelled = true;
				await command("cancel");
				return true;
			},
		});
		await load(data, runtime);
		await start(data);
		const interrupted = branchEntries().at(-1)?.data;
		expect(interrupted).toMatchObject({ stage: "interrupted", terminal: null });
		const directory = join(data.agentDir, "overkill-runs", interrupted.runId);
		await command("discard");
		await expect(access(directory)).rejects.toThrow();
		expect(branchEntries().at(-1)?.data).toMatchObject({
			stage: "discarded",
			terminal: "discarded",
		});
	});

	it.each(["baseline", "optimizer", "validation", "final_test"] as const)(
		"cancels at %s and resumes exactly without repeating completed calls",
		async (cancelStage) => {
			const data = await fixture();
			let cancelled = false;
			const cancel = async () => {
				if (cancelled) return false;
				cancelled = true;
				await command("cancel");
				return true;
			};
			const runtime = deterministicRuntime({
				candidateScore: 1,
				onTarget: async (call) => {
					const candidate = call.body.includes("ACCEPTANCE-CANDIDATE");
					if (
						(cancelStage === "baseline" &&
							!candidate &&
							call.prompt.includes("validation 2")) ||
						(cancelStage === "validation" &&
							candidate &&
							call.prompt.includes("validation 2")) ||
						(cancelStage === "final_test" && call.prompt.includes("test 2"))
					)
						return await cancel();
					return false;
				},
				onOptimizer: async (phase) =>
					cancelStage === "optimizer" && phase === "merge"
						? await cancel()
						: false,
			});
			await load(data, runtime);
			await start(data);

			const interrupted = branchEntries().at(-1)?.data;
			expect(interrupted).toMatchObject({
				stage: "interrupted",
				terminal: null,
			});
			const runDirectory = join(
				data.agentDir,
				"overkill-runs",
				interrupted.runId,
			);
			const interruptedManifest = JSON.parse(
				await readFile(join(runDirectory, "manifest.json"), "utf8"),
			);
			expect(interruptedManifest.calls.target).toBe(runtime.targetCalls.length);
			expect(interruptedManifest.calls.optimizer).toBe(
				runtime.optimizerCalls.length,
			);
			if (cancelStage === "optimizer") {
				const interruptedEntry = branchEntries().at(-1);
				if (!interruptedEntry)
					throw new Error("missing interrupted suite entry");
				session?.session.sessionManager.resetLeaf();
				await command("resume");
				expect(session?.events.uiCallsFor("notify").at(-1)?.args[0]).toContain(
					"No Overkill suite run",
				);
				session?.session.sessionManager.branch(interruptedEntry.id);
				await session?.session.reload();
			}
			await command("resume");
			expect(branchEntries().at(-1)?.data).toMatchObject({
				stage: "complete",
				terminal: "staged",
			});
			const completedTargetKeys = runtime.targetCalls
				.filter((call) => call.completed)
				.map(
					(call) =>
						`${call.body.includes("ACCEPTANCE-CANDIDATE") ? "candidate" : "base"}:${call.prompt}`,
				);
			for (const key of new Set(completedTargetKeys))
				expect(
					completedTargetKeys.filter((candidate) => candidate === key),
					key,
				).toHaveLength(1);
			const completedOptimizerPhases = runtime.optimizerCalls
				.filter((call) => call.completed)
				.map((call) => call.phase);
			for (const phase of new Set(completedOptimizerPhases))
				expect(
					completedOptimizerPhases.filter((candidate) => candidate === phase),
					phase,
				).toHaveLength(1);
			expect((await checkerCalls(data)).map((call) => call.id)).toEqual([
				"val-1",
				"val-2",
				"train-1",
				"val-1",
				"val-2",
				"test-1",
				"test-2",
			]);
			await expectInputsUnchanged(data);

			await command("discard");
			await expect(access(runDirectory)).rejects.toThrow();
			expect(branchEntries().at(-1)?.data).toMatchObject({
				stage: "discarded",
				terminal: "discarded",
			});
		},
	);
});