repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/overkill/index.ts

Raw
import { createHash } from "node:crypto";
import { writeSync } from "node:fs";
import { readFile, realpath } from "node:fs/promises";
import { join, resolve } from "node:path";
import {
	type ExtensionAPI,
	type ExtensionCommandContext,
	getAgentDir,
	keyHint,
	SessionManager,
} from "@earendil-works/pi-coding-agent";
import { Key, matchesKey, Text } from "@earendil-works/pi-tui";
import {
	buildDigest,
	type Digest,
	rankSkillEvidence,
} from "./lib/aftermath-harvest.ts";
import {
	assignSplits,
	createMiningSession,
	estimateMiningCalls,
	mineTaskProposals,
	type StructuredOutputSdkSeam,
	validateAndFreezeTasks,
} from "./lib/aftermath-mining.ts";
import {
	createGeneratedTaskScorer,
	createRubricJudgeSession,
	generatedTaskPrompt,
	rubricCacheKey,
	runRubricJudge,
} from "./lib/aftermath-scoring.ts";
import {
	type AftermathManifest,
	createAftermathDirectory,
	persistAftermathCost,
	persistAftermathManifest,
	persistFrozenTasks,
	persistHarvest,
	persistJudgeCache,
	persistMiningCheckpoint,
	persistMiningOutput,
	readAftermathCost,
	readAftermathManifest,
	readFrozenTasks,
	readHarvest,
	readJudgeCache,
	readMiningCheckpoint,
	readMiningOutput,
} from "./lib/aftermath-state.ts";
import {
	executeChecker,
	fingerprintSource,
	fingerprintSuite,
} from "./lib/checker.ts";
import {
	getValidatedSuiteItems,
	parseSourceSkill,
	resolveLoadedSkill,
	type ValidatedItem,
	validateTrustedSuite,
} from "./lib/contracts.ts";
import {
	buildConfirmation,
	buildReviewDiff,
	formatProgress,
	formatResultPaths,
	sanitizeTerminalText,
	upperBoundCalls,
} from "./lib/modes.ts";
import {
	createOptimizerSession,
	defaultOptimizerSdk,
	OptimizerCancelledError,
	type OptimizerSdkSeam,
	runOptimizerStep,
} from "./lib/optimizer.ts";
import { parsePatch } from "./lib/patches.ts";
import { inspectSuiteRun, prepareSuiteRun } from "./lib/preflight.ts";
import {
	createIsolatedTargetSession,
	defaultTargetSdk,
	RolloutCancelledError,
	runSplitRollout,
	runValidationBaseline,
	type TargetSdkSeam,
} from "./lib/rollouts.ts";
import {
	discardLinkedRun,
	persistFinalReport,
	persistManifest,
	persistTrainingCheckpoint,
	type RunEntry,
	type RunManifest,
	readFrozenReviewArtifacts,
	readFrozenReviewArtifactsSync,
	readManifest,
	readScoreCache,
	readTrainingCheckpoint,
	recoverRunLink,
	selectNewestAftermathRun,
	selectNewestSuiteRun,
	validateRunEntry,
	writePrivateText,
} from "./lib/run-state.ts";
import {
	type AttemptedPatch,
	createTrainingState,
	type DurableTrainingState,
	runDurableTrainingSchedule,
} from "./lib/training.ts";

const SUBCOMMANDS = [
	"aftermath",
	"status",
	"resume",
	"review",
	"discard",
	"cancel",
] as const;

type ActiveRun = {
	kind: "suite" | "aftermath";
	runId: string;
	sessionId: string;
	controller: AbortController;
	suppressOutput: boolean;
	completed?: Promise<void>;
	cancelRequested?: boolean;
	interrupt?: () => Promise<void>;
	removeCancellationListeners?: () => void;
};

let activeRun: ActiveRun | undefined;
let startPending = false;
let pendingSessionId: string | undefined;
let pendingCancelled = false;

export type ExplicitSuiteAcceptanceSeam = {
	targetSdk: TargetSdkSeam;
	optimizerSdk: OptimizerSdkSeam;
};

export type AftermathSessionApi = {
	listAll: () => Promise<Array<{ path: string; id: string }>>;
	open: (path: string) => {
		getBranch: () => unknown[];
		getSessionId: () => string;
		getCwd: () => string;
	};
};

export type AftermathAcceptanceSeam = ExplicitSuiteAcceptanceSeam & {
	sessionApi: AftermathSessionApi;
	structuredOutputSdk: StructuredOutputSdkSeam;
	/** Lets acceptance fakes request cancellation through the registered command. */
	bindCommand?: (handler: (args: string) => Promise<void>) => void;
};

export type ModeAcceptanceSeam = {
	write: (fd: number, text: string) => void;
};

const explicitSuiteAcceptanceSeam = Symbol.for(
	"@bugabinga/pi-ext-overkill/explicit-suite-acceptance-seam",
);
const aftermathAcceptanceSeam = Symbol.for(
	"@bugabinga/pi-ext-overkill/aftermath-acceptance-seam",
);
const modeAcceptanceSeam = Symbol.for(
	"@bugabinga/pi-ext-overkill/mode-acceptance-seam",
);

function installedExplicitSuiteAcceptanceSeam():
	| ExplicitSuiteAcceptanceSeam
	| undefined {
	return (globalThis as Record<PropertyKey, unknown>)[
		explicitSuiteAcceptanceSeam
	] as ExplicitSuiteAcceptanceSeam | undefined;
}

function installedAftermathAcceptanceSeam():
	| AftermathAcceptanceSeam
	| undefined {
	return (globalThis as Record<PropertyKey, unknown>)[
		aftermathAcceptanceSeam
	] as AftermathAcceptanceSeam | undefined;
}

function installedModeAcceptanceSeam(): ModeAcceptanceSeam | undefined {
	return (globalThis as Record<PropertyKey, unknown>)[modeAcceptanceSeam] as
		| ModeAcceptanceSeam
		| undefined;
}

/** Installs deterministic session boundaries while retaining command orchestration. */
export function installExplicitSuiteAcceptanceSeam(
	seam: ExplicitSuiteAcceptanceSeam,
): () => void {
	const globals = globalThis as Record<PropertyKey, unknown>;
	const previous = globals[explicitSuiteAcceptanceSeam];
	globals[explicitSuiteAcceptanceSeam] = seam;
	return () => {
		if (globals[explicitSuiteAcceptanceSeam] !== seam) return;
		if (previous === undefined) delete globals[explicitSuiteAcceptanceSeam];
		else globals[explicitSuiteAcceptanceSeam] = previous;
	};
}

/** Captures direct mode output while preserving the fd selected by production code. */
export function installModeAcceptanceSeam(
	seam: ModeAcceptanceSeam,
): () => void {
	const globals = globalThis as Record<PropertyKey, unknown>;
	const previous = globals[modeAcceptanceSeam];
	globals[modeAcceptanceSeam] = seam;
	return () => {
		if (globals[modeAcceptanceSeam] !== seam) return;
		if (previous === undefined) delete globals[modeAcceptanceSeam];
		else globals[modeAcceptanceSeam] = previous;
	};
}

/** Installs deterministic constructors at Aftermath's production boundaries. */
export function installAftermathAcceptanceSeam(
	seam: AftermathAcceptanceSeam,
): () => void {
	const globals = globalThis as Record<PropertyKey, unknown>;
	const previous = globals[aftermathAcceptanceSeam];
	globals[aftermathAcceptanceSeam] = seam;
	return () => {
		if (globals[aftermathAcceptanceSeam] !== seam) return;
		if (previous === undefined) delete globals[aftermathAcceptanceSeam];
		else globals[aftermathAcceptanceSeam] = previous;
	};
}

export function parseArguments(input: string): string[] {
	const parts: string[] = [];
	const expression =
		/"([^"\\]*(?:\\.[^"\\]*)*)"|'([^'\\]*(?:\\.[^'\\]*)*)'|(\S+)/g;
	let match = expression.exec(input);
	while (match !== null) {
		const token = match[1] ?? match[2] ?? match[3];
		if (token !== undefined) {
			const quoted = match[1] !== undefined || match[2] !== undefined;
			parts.push(quoted ? token.replace(/\\(["'])/g, "$1") : token);
		}
		match = expression.exec(input);
	}
	return parts;
}

function runEntry(
	run: {
		manifest: {
			runId: string;
			kind: "suite" | "aftermath";
			stage: string;
			terminal: RunEntry["terminal"];
			source: { path: string };
		};
	},
	progress: Pick<
		RunEntry,
		"completed" | "total" | "currentScore" | "bestScore"
	> = {},
	artifacts: Pick<RunEntry, "reportPath" | "stagedPath"> = {
		reportPath: null,
		stagedPath: null,
	},
): RunEntry {
	return {
		version: 1,
		runId: run.manifest.runId,
		kind: run.manifest.kind,
		stage: run.manifest.stage,
		terminal: run.manifest.terminal,
		sourcePath: run.manifest.source.path,
		...artifacts,
		...progress,
	};
}

async function modelHasAuth(
	ctx: ExtensionCommandContext,
	provider = ctx.model?.provider,
	id = ctx.model?.id,
): Promise<boolean> {
	if (!provider || !id) return false;
	const available = await ctx.modelRegistry.getAvailable();
	return available.some(
		(model) => model.provider === provider && model.id === id,
	);
}

function selectedRun(ctx: ExtensionCommandContext) {
	return selectNewestSuiteRun(ctx.sessionManager.getBranch());
}

function selectedAftermathRun(ctx: ExtensionCommandContext) {
	return selectNewestAftermathRun(ctx.sessionManager.getBranch());
}

function statusMessage(run: RunEntry): string {
	const fields = [`Overkill: ${run.stage}`];
	if (run.completed !== undefined)
		fields.push(
			`completed: ${run.completed}${run.total === undefined ? "" : `/${run.total}`}`,
		);
	if (run.currentScore !== undefined)
		fields.push(`current score: ${run.currentScore}`);
	if (run.bestScore !== undefined) fields.push(`best score: ${run.bestScore}`);
	fields.push(`terminal: ${run.terminal ?? "active"}`);
	if (run.stagedPath) fields.push(`staged: ${run.stagedPath}`);
	return fields.join(" | ");
}

function commandMode(
	ctx: ExtensionCommandContext,
): "tui" | "rpc" | "json" | "print" {
	return ctx.mode ?? "tui";
}

function writePrint(line: string): void {
	const text = `${line}\n`;
	const seam = installedModeAcceptanceSeam();
	if (seam) seam.write(1, text);
	else writeSync(1, text);
}

function appendProgressEntry(pi: ExtensionAPI, entry: RunEntry): void {
	pi.appendEntry("overkill-run", entry);
}

function appendProgress(
	pi: ExtensionAPI,
	ctx: ExtensionCommandContext,
	entry: RunEntry,
): void {
	appendProgressEntry(pi, entry);
	const mode = commandMode(ctx);
	if (mode === "tui" || mode === "rpc")
		ctx.ui.setStatus("overkill", formatProgress(entry));
	else if (mode === "print") writePrint(formatProgress(entry));
}

function clearProgress(ctx: ExtensionCommandContext): void {
	if (commandMode(ctx) === "tui" || commandMode(ctx) === "rpc")
		ctx.ui.setStatus("overkill", undefined);
}

function requestCancellation(active: ActiveRun): void {
	if (active.cancelRequested) return;
	active.cancelRequested = true;
	active.controller.abort();
}

function installCancellationListeners(
	active: ActiveRun,
	ctx: ExtensionCommandContext,
): void {
	const mode = commandMode(ctx);
	const cleanup: Array<() => void> = [];
	if (mode === "tui")
		cleanup.push(
			ctx.ui.onTerminalInput((data) => {
				if (!matchesKey(data, Key.escape)) return undefined;
				requestCancellation(active);
				return { consume: true };
			}),
		);
	if (mode === "json" || mode === "print") {
		const onSignal = () => requestCancellation(active);
		process.once("SIGINT", onSignal);
		cleanup.push(() => process.removeListener("SIGINT", onSignal));
	}
	active.removeCancellationListeners = () => {
		for (const remove of cleanup.splice(0)) remove();
	};
}

async function withActiveRun(
	ctx: ExtensionCommandContext,
	operation: (active: ActiveRun) => Promise<void>,
	kind: ActiveRun["kind"] = "suite",
): Promise<void> {
	if (activeRun) throw new Error("an Overkill rollout is already active");
	const active: ActiveRun = {
		kind,
		runId: "pending",
		sessionId: ctx.sessionManager.getSessionId(),
		controller: new AbortController(),
		suppressOutput: false,
	};
	activeRun = active;
	installCancellationListeners(active, ctx);
	const completed = (async () => {
		try {
			await operation(active);
		} catch (error) {
			if (active.controller.signal.aborted) {
				await active.interrupt?.();
				throw new RolloutCancelledError();
			}
			if (active.kind === "aftermath") {
				try {
					await active.interrupt?.();
				} catch {
					// Preserve the original infrastructure failure.
				}
			}
			throw error;
		} finally {
			active.removeCancellationListeners?.();
			clearProgress(ctx);
			if (activeRun === active) activeRun = undefined;
		}
	})();
	active.completed = completed;
	return await completed;
}

async function checkpointInterrupted(
	directory: string,
	manifest: RunManifest,
): Promise<void> {
	const training = await readTrainingCheckpoint(directory);
	if (training)
		await persistTrainingCheckpoint(directory, {
			...training,
			stage: "interrupted",
		});
	manifest.stage = "interrupted";
	manifest.terminal = null;
	await persistManifest(directory, manifest);
}

function throwIfCancelled(active: ActiveRun): void {
	if (active.controller.signal.aborted) throw new RolloutCancelledError();
}

type CoreTaskAdapter = {
	items: (split: "train" | "validation" | "test") => readonly ValidatedItem[];
	scoreResponse: (options: {
		item: ValidatedItem;
		response: string;
		input: string;
		signal?: AbortSignal;
	}) => Promise<{ score: number; passed: boolean; feedback?: string }>;
	onTargetCall?: () => void | Promise<void>;
};

async function executeBaseline(options: {
	pi: ExtensionAPI;
	ctx: ExtensionCommandContext;
	directory: string;
	manifest: RunManifest;
	source: ReturnType<typeof parseSourceSkill>;
	loadedSkill: Awaited<ReturnType<typeof resolveLoadedSkill>>;
	suite?: Awaited<ReturnType<typeof validateTrustedSuite>>;
	targetModel: unknown;
	taskAdapter?: CoreTaskAdapter;
	reportExtras?: () => Record<string, unknown>;
}): Promise<void> {
	const { ctx, manifest } = options;
	const itemsFor = (split: "train" | "validation" | "test") =>
		options.taskAdapter
			? options.taskAdapter.items(split)
			: getValidatedSuiteItems(
					options.suite ??
						(() => {
							throw new Error("suite tasks are unavailable");
						})(),
					split === "validation" ? "val" : split,
				);
	const scorer = options.taskAdapter
		? { scoreResponse: options.taskAdapter.scoreResponse }
		: { executeChecker };
	const active = activeRun;
	if (!active || active.sessionId !== ctx.sessionManager.getSessionId())
		throw new Error("Overkill run ownership is unavailable");
	active.runId = manifest.runId;
	active.interrupt = async () =>
		await checkpointInterrupted(options.directory, manifest);
	throwIfCancelled(active);
	const controller = active.controller;
	const acceptanceSeam =
		manifest.kind === "aftermath"
			? installedAftermathAcceptanceSeam()
			: installedExplicitSuiteAcceptanceSeam();
	const recordTargetAttempt = async () => {
		if (options.taskAdapter?.onTargetCall) {
			await options.taskAdapter.onTargetCall();
			return;
		}
		if (!options.suite || !manifest.suite)
			throw new Error("suite call contract is unavailable");
		const maximum = upperBoundCalls(options.suite.splitCounts).target;
		if (manifest.calls.target >= maximum)
			throw new Error("target call maximum exceeded");
		if (
			fingerprintSource(await readFile(manifest.source.path)) !==
			manifest.source.fingerprint
		)
			throw new Error("source fingerprint changed");
		if (
			(await fingerprintSuite(options.suite.suitePath)) !==
			manifest.suite.fingerprint
		)
			throw new Error("suite fingerprint changed");
		manifest.calls.target += 1;
		await persistManifest(options.directory, manifest);
	};
	let progress: Pick<
		RunEntry,
		"completed" | "total" | "currentScore" | "bestScore"
	> = {};
	const operation = (async () => {
		manifest.stage = "baseline";
		await persistManifest(options.directory, manifest);
		try {
			const result = await runValidationBaseline(
				{
					directory: options.directory,
					cwd: ctx.cwd,
					agentDir: getAgentDir(),
					sourcePath: manifest.source.path,
					sourceFingerprint: manifest.source.fingerprint,
					source: options.source,
					loadedSkill: options.loadedSkill,
					model: manifest.model,
					suite: options.suite,
					items: itemsFor("validation"),
					signal: controller.signal,
					onTargetCall: recordTargetAttempt,
					onCheckerCall: async () => {
						if (options.taskAdapter) return;
						manifest.calls.checker += 1;
						await persistManifest(options.directory, manifest);
					},
					onProgress: async (next) => {
						progress = {
							completed: next.completed,
							total: next.total,
							...(next.mean === undefined
								? {}
								: { currentScore: next.mean, bestScore: next.mean }),
						};
						if (!active.suppressOutput)
							appendProgress(options.pi, ctx, runEntry({ manifest }, progress));
					},
				},
				{
					createTarget: () =>
						createIsolatedTargetSession(
							{
								cwd: ctx.cwd,
								agentDir: getAgentDir(),
								sourcePath: manifest.source.path,
								loadedSkill: options.loadedSkill,
								candidatePath: join(options.directory, "baseline-snapshot.md"),
								model: manifest.model,
								targetModel: options.targetModel,
								modelRegistry: ctx.modelRegistry,
							},
							acceptanceSeam?.targetSdk ?? defaultTargetSdk,
						),
					...scorer,
				},
			);
			manifest.stage = "baseline_complete";
			manifest.scores = {
				...manifest.scores,
				baseline: result.mean,
				current: result.mean,
				best: result.mean,
			};
			await persistManifest(options.directory, manifest);
			if (controller.signal.aborted) throw new RolloutCancelledError();
			if (!active.suppressOutput)
				appendProgress(options.pi, ctx, runEntry({ manifest }, progress));
			if (commandMode(ctx) !== "json" && commandMode(ctx) !== "print")
				ctx.ui.notify(`Overkill validation baseline: ${result.mean}`, "info");
			if (result.mean === 1) {
				const reportPath = await persistFinalReport(options.directory, {
					version: 1,
					baselineScore: result.mean,
					bestScore: result.mean,
					accepted: 0,
					optimizerCalls: 0,
					targetCalls: manifest.calls.target,
					checkerCalls: manifest.calls.checker,
					terminal: "perfect",
					...options.reportExtras?.(),
				});
				if (controller.signal.aborted) throw new RolloutCancelledError();
				manifest.stage = "complete";
				manifest.terminal = "no_improvement";
				manifest.artifacts.report = "report.json";
				await persistManifest(options.directory, manifest);
				if (!active.suppressOutput) {
					const entry = runEntry({ manifest }, progress, {
						reportPath,
						stagedPath: null,
					});
					appendProgress(options.pi, ctx, entry);
					const paths = formatResultPaths({
						sourcePath: manifest.source.path,
						reportPath,
						stagedPath: null,
					});
					if (commandMode(ctx) === "print") writePrint(paths);
					else if (commandMode(ctx) !== "json") ctx.ui.notify(paths, "info");
				}
				return;
			}
			const baselineCache = await readScoreCache(options.directory);
			if (!baselineCache)
				throw new Error("validation baseline cache is unavailable");
			const sourceHash = createHash("sha256")
				.update(options.source.body, "utf8")
				.digest("hex");
			const saved = await readTrainingCheckpoint(options.directory);
			const readSnapshotBody = async (hash: string, filename: string) => {
				if (hash === sourceHash) return options.source.body;
				const snapshot = await readFile(
					join(options.directory, filename),
					"utf8",
				);
				if (!snapshot.startsWith(options.source.frontmatter))
					throw new Error("candidate snapshot frontmatter is unsafe");
				const body = snapshot.slice(options.source.frontmatter.length);
				if (createHash("sha256").update(body, "utf8").digest("hex") !== hash)
					throw new Error("candidate snapshot identity is unsafe");
				return body;
			};
			const readAttempt = async (filename: string): Promise<AttemptedPatch> => {
				const value: unknown = JSON.parse(
					await readFile(join(options.directory, filename), "utf8"),
				);
				if (typeof value !== "object" || value === null || Array.isArray(value))
					throw new Error("attempt artifact is malformed");
				const artifact = value as Record<string, unknown>;
				if (!Array.isArray(artifact.reports))
					throw new Error("attempt artifact reports are malformed");
				return {
					patch: parsePatch(artifact.patch),
					reports: artifact.reports as AttemptedPatch["reports"],
					...(typeof artifact.validationScore === "number"
						? { validationScore: artifact.validationScore }
						: {}),
				};
			};
			let latestTraining: DurableTrainingState;
			if (saved) {
				const attempts = await Promise.all(
					saved.attemptedPatchFiles.map(readAttempt),
				);
				const pendingArtifact = saved.pendingPatch
					? await readAttempt(saved.pendingPatch.file)
					: undefined;
				latestTraining = {
					nextStep: saved.nextStep,
					body: await readSnapshotBody(
						saved.currentBodyHash,
						saved.currentSnapshot,
					),
					bestBody: await readSnapshotBody(
						saved.bestBodyHash,
						saved.bestSnapshot,
					),
					baselineScore: saved.baselineScore,
					currentScore: saved.currentScore,
					bestScore: saved.bestScore,
					accepted: saved.accepted,
					optimizerCalls: saved.optimizerCalls,
					consecutiveRejections: saved.consecutiveRejections,
					rejections: saved.rejections.map(({ edits, ...rejection }) => ({
						...rejection,
						...(edits === undefined
							? {}
							: { edits: parsePatch({ edits }).edits }),
					})),
					attempts,
					...(pendingArtifact && saved.pendingPatch
						? {
								pendingPatch: {
									step: saved.pendingPatch.step,
									body: await readSnapshotBody(
										saved.pendingPatch.bodyHash,
										saved.currentSnapshot,
									),
									patch: pendingArtifact.patch,
								},
							}
						: {}),
					...(saved.terminal === undefined ? {} : { terminal: saved.terminal }),
					...(saved.finalTest === undefined
						? {}
						: {
								finalTest: {
									body: await readSnapshotBody(
										saved.finalTest.bodyHash,
										saved.bestSnapshot,
									),
									completedItemIds: saved.finalTest.completedItemIds,
									total: saved.finalTest.total,
									...(saved.finalTest.score === undefined
										? {}
										: { score: saved.finalTest.score }),
								},
								...(saved.finalTest.score === undefined
									? {}
									: { finalTestScore: saved.finalTest.score }),
							}),
					...(saved.pendingOptimizer === undefined
						? {}
						: { pendingOptimizer: saved.pendingOptimizer }),
				};
			} else
				latestTraining = createTrainingState({
					body: options.source.body,
					baseline: baselineCache.scores,
				});
			const checkpointTraining = async (state: DurableTrainingState) => {
				latestTraining = state;
				if (state.pendingPatch)
					await writePrivateText(
						options.directory,
						`attempt-${state.pendingPatch.step}.json`,
						`${JSON.stringify({ patch: state.pendingPatch.patch, reports: [] })}\n`,
					);
				for (const [index, attempt] of state.attempts.entries())
					await writePrivateText(
						options.directory,
						`attempt-${index + 1}.json`,
						`${JSON.stringify(attempt)}\n`,
					);
				const snapshotName = (body: string) => {
					const hash = createHash("sha256").update(body, "utf8").digest("hex");
					return hash === sourceHash
						? "baseline-snapshot.md"
						: `candidate-${hash}.md`;
				};
				const stage =
					state.terminal &&
					state.accepted > 0 &&
					state.finalTestScore === undefined
						? "final_test"
						: "training";
				await persistTrainingCheckpoint(options.directory, {
					version: 1,
					stage,
					nextStep: state.nextStep,
					currentBodyHash: createHash("sha256")
						.update(state.body, "utf8")
						.digest("hex"),
					bestBodyHash: createHash("sha256")
						.update(state.bestBody, "utf8")
						.digest("hex"),
					currentSnapshot: snapshotName(state.body),
					bestSnapshot: snapshotName(state.bestBody),
					...(state.terminal === undefined ? {} : { terminal: state.terminal }),
					baselineScore: state.baselineScore,
					currentScore: state.currentScore,
					bestScore: state.bestScore,
					accepted: state.accepted,
					optimizerCalls: state.optimizerCalls,
					consecutiveRejections: state.consecutiveRejections,
					rejections: state.rejections.map(
						({ reason, delta, reports, edits }) => ({
							reason,
							delta,
							...(reports === undefined ? {} : { reports }),
							...(edits === undefined ? {} : { edits }),
						}),
					),
					attemptedPatchFiles: state.attempts.map(
						(_, index) => `attempt-${index + 1}.json`,
					),
					...(state.pendingPatch
						? {
								pendingPatch: {
									step: state.pendingPatch.step,
									bodyHash: createHash("sha256")
										.update(state.pendingPatch.body, "utf8")
										.digest("hex"),
									file: `attempt-${state.pendingPatch.step}.json`,
								},
							}
						: {}),
					...(state.pendingOptimizer === undefined
						? {}
						: { pendingOptimizer: state.pendingOptimizer }),
					...(state.finalTest
						? {
								finalTest: {
									bodyHash: createHash("sha256")
										.update(state.finalTest.body, "utf8")
										.digest("hex"),
									completedItemIds: state.finalTest.completedItemIds,
									total: state.finalTest.total,
									...(state.finalTest.score === undefined
										? {}
										: { score: state.finalTest.score }),
								},
							}
						: {}),
				});
				manifest.stage = stage;
				manifest.scores = {
					...manifest.scores,
					current: state.currentScore,
					best: state.bestScore,
					...(state.finalTestScore === undefined
						? {}
						: { test: state.finalTestScore }),
				};
				manifest.calls.optimizer = state.optimizerCalls;
				await persistManifest(options.directory, manifest);
				if (!active.suppressOutput)
					appendProgress(
						options.pi,
						ctx,
						runEntry(
							{ manifest },
							{
								...(state.finalTest
									? {
											completed: state.finalTest.completedItemIds.length,
											total: state.finalTest.total,
										}
									: {}),
								currentScore: state.currentScore,
								bestScore: state.bestScore,
							},
						),
					);
			};
			const training = await runDurableTrainingSchedule(latestTraining, {
				evaluate: async (body, split, onProgress) =>
					await splitScores(split, body, onProgress),
				optimize: async (input, onCall, onProgress) =>
					await runOptimizerStep(
						input,
						{
							createSession: () =>
								createOptimizerSession(
									{
										cwd: ctx.cwd,
										agentDir: getAgentDir(),
										model: manifest.model,
										targetModel: options.targetModel,
										modelRegistry: ctx.modelRegistry,
									},
									acceptanceSeam?.optimizerSdk ?? defaultOptimizerSdk,
								),
						},
						controller.signal,
						latestTraining.pendingOptimizer,
						onCall,
						onProgress,
					),
				checkpoint: checkpointTraining,
				testItemIds: async () => itemsFor("test").map((item) => item.id),
				signal: controller.signal,
			});
			if (controller.signal.aborted) throw new RolloutCancelledError();
			const reportPath = await persistFinalReport(options.directory, {
				version: 1,
				baselineScore: training.baselineScore,
				bestScore: training.bestScore,
				accepted: training.accepted,
				optimizerCalls: training.optimizerCalls,
				targetCalls: manifest.calls.target,
				checkerCalls: manifest.calls.checker,
				terminal: training.terminal,
				rejections: training.rejections,
				attempts: training.attempts,
				...(training.testScore === undefined
					? {}
					: { testScore: training.testScore }),
				...options.reportExtras?.(),
			});
			const stagedPath =
				training.accepted > 0
					? await writePrivateText(
							options.directory,
							"staged-skill.md",
							`${options.source.frontmatter}${training.bestBody}`,
						)
					: null;
			await checkpointTraining(latestTraining);
			if (controller.signal.aborted) throw new RolloutCancelledError();
			const completeCheckpoint = await readTrainingCheckpoint(
				options.directory,
			);
			if (!completeCheckpoint)
				throw new Error("training checkpoint is unavailable");
			await persistTrainingCheckpoint(options.directory, {
				...completeCheckpoint,
				stage: "complete",
				reportFile: "report.json",
				...(stagedPath === null ? {} : { stagedFile: "staged-skill.md" }),
			});
			manifest.stage = "complete";
			manifest.terminal = training.accepted > 0 ? "staged" : "no_improvement";
			manifest.scores = {
				...manifest.scores,
				best: training.bestScore,
				...(training.testScore === undefined
					? {}
					: { test: training.testScore }),
			};
			manifest.calls.optimizer = training.optimizerCalls;
			manifest.artifacts.report = "report.json";
			manifest.artifacts.staged =
				stagedPath === null ? null : "staged-skill.md";
			await persistManifest(options.directory, manifest);
			if (controller.signal.aborted) throw new RolloutCancelledError();
			if (!active.suppressOutput) {
				const entry = runEntry(
					{ manifest },
					{ currentScore: training.bestScore, bestScore: training.bestScore },
					{ reportPath, stagedPath },
				);
				appendProgress(options.pi, ctx, entry);
				const paths = formatResultPaths({
					sourcePath: manifest.source.path,
					reportPath,
					stagedPath,
				});
				if (commandMode(ctx) === "print") writePrint(paths);
				else if (commandMode(ctx) !== "json") ctx.ui.notify(paths, "info");
			}

			async function splitScores(
				split: "train" | "validation" | "test",
				body: string,
				onProgress?: (progress: {
					completed: number;
					total: number;
				}) => Promise<void>,
			) {
				const hash = createHash("sha256").update(body, "utf8").digest("hex");
				const rollout = await runSplitRollout(
					{
						directory: options.directory,
						cwd: ctx.cwd,
						agentDir: getAgentDir(),
						sourcePath: manifest.source.path,
						sourceFingerprint: manifest.source.fingerprint,
						source: options.source,
						loadedSkill: options.loadedSkill,
						model: manifest.model,
						suite: options.suite,
						items: itemsFor(split),
						body,
						split,
						signal: controller.signal,
						onProgress,
						onTargetCall: recordTargetAttempt,
						onCheckerCall: async () => {
							if (options.taskAdapter) return;
							manifest.calls.checker += 1;
							await persistManifest(options.directory, manifest);
						},
					},
					{
						createTarget: () =>
							createIsolatedTargetSession(
								{
									cwd: ctx.cwd,
									agentDir: getAgentDir(),
									sourcePath: manifest.source.path,
									loadedSkill: options.loadedSkill,
									candidatePath: join(
										options.directory,
										`candidate-${hash}.md`,
									),
									model: manifest.model,
									targetModel: options.targetModel,
									modelRegistry: ctx.modelRegistry,
								},
								acceptanceSeam?.targetSdk ?? defaultTargetSdk,
							),
						...scorer,
					},
				);
				return rollout.scores;
			}
		} catch (error) {
			if (
				error instanceof RolloutCancelledError ||
				error instanceof OptimizerCancelledError ||
				controller.signal.aborted
			) {
				await checkpointInterrupted(options.directory, manifest);
				const entry = runEntry({ manifest }, progress);
				if (active.suppressOutput) appendProgressEntry(options.pi, entry);
				else appendProgress(options.pi, ctx, entry);
				throw new RolloutCancelledError();
			}
			throw error;
		}
	})();
	return await operation;
}

export async function harvestAftermath(options: {
	ctx: ExtensionCommandContext;
	knownSkillPaths: ReadonlyMap<string, string>;
	sessionApi?: AftermathSessionApi;
}): Promise<{ digests: Digest[]; total: number; unreadable: number }> {
	const api =
		options.sessionApi ??
		(SessionManager as unknown as NonNullable<typeof options.sessionApi>);
	const listed = await api.listAll();
	const snapshots = new Map<string, Digest>();
	const unreadableIds = new Set<string>();
	for (const listedSession of listed) {
		try {
			const session = api.open(listedSession.path);
			const id = session.getSessionId();
			snapshots.set(
				id,
				buildDigest({
					sessionId: id,
					cwd: session.getCwd(),
					branch: session.getBranch(),
					knownSkillPaths: options.knownSkillPaths,
				}),
			);
		} catch {
			unreadableIds.add(listedSession.id);
		}
	}
	const current = options.ctx.sessionManager;
	const currentId = current.getSessionId();
	snapshots.set(
		currentId,
		buildDigest({
			sessionId: currentId,
			cwd: options.ctx.cwd,
			branch: current.getBranch(),
			knownSkillPaths: options.knownSkillPaths,
		}),
	);
	unreadableIds.delete(currentId);
	const currentWasListed = listed.some((session) => session.id === currentId);
	return {
		digests: [...snapshots.values()].sort((left, right) =>
			left.sessionId.localeCompare(right.sessionId),
		),
		total: listed.length + (currentWasListed ? 0 : 1),
		unreadable: unreadableIds.size,
	};
}

function loadedSkills(pi: ExtensionAPI): Array<{ name: string; path: string }> {
	return pi
		.getCommands()
		.flatMap((command) => {
			if (
				command.source !== "skill" ||
				typeof command.sourceInfo?.path !== "string"
			)
				return [];
			return [
				{
					name: command.name.replace(/^skill:/, ""),
					path: command.sourceInfo.path,
				},
			];
		})
		.sort(
			(left, right) =>
				left.name.localeCompare(right.name) ||
				left.path.localeCompare(right.path),
		);
}

async function runAftermath(
	pi: ExtensionAPI,
	ctx: ExtensionCommandContext,
	parts: string[],
): Promise<void> {
	const active = activeRun;
	if (!active || active.kind !== "aftermath")
		throw new Error("Aftermath run ownership is unavailable");
	throwIfCancelled(active);
	const explicitPath = parts[0];
	if (parts.length > 1)
		throw new Error("Usage: /overkill aftermath [skill-path]");
	const interrupted = selectedAftermathRun(ctx);
	if (interrupted) {
		const directory = join(
			getAgentDir(),
			"overkill-runs",
			interrupted.data.runId,
		);
		const manifest = await readAftermathManifest(directory).catch(
			() => undefined,
		);
		if (manifest && !manifest.terminal) {
			const instructions =
				"An incomplete Aftermath run is linked here; use /overkill aftermath resume, discard, or cancel.";
			if (explicitPath) throw new Error(instructions);
			if (ctx.hasUI) {
				const choice = await ctx.ui.select("Resume incomplete Aftermath run?", [
					"resume",
					"discard",
					"cancel",
				]);
				if (choice === "resume") {
					await resumeAftermath(pi, ctx, interrupted);
					return;
				}
				if (choice === "discard") {
					await discardLinkedRun({
						runRoot: join(getAgentDir(), "overkill-runs"),
						runDirectory: directory,
						selected: interrupted,
						branch: ctx.sessionManager.getBranch(),
						sessionId: ctx.sessionManager.getSessionId(),
						allowNonterminal: true,
						isRunActive: (runId) => activeRun?.runId === runId,
					});
					appendProgress(pi, ctx, {
						...interrupted.data,
						stage: "discarded",
						terminal: "discarded",
					});
				}
				return;
			}
			throw new Error(instructions);
		}
	}
	if (
		(commandMode(ctx) === "json" || commandMode(ctx) === "print") &&
		!explicitPath
	)
		throw new Error(
			"JSON and print Aftermath runs require an explicit skill path",
		);
	const skills = loadedSkills(pi);
	if (skills.length === 0) {
		ctx.ui.notify("No loaded Pi skills are available for Aftermath.", "info");
		return;
	}
	const knownPaths = new Map<string, string>();
	const canonicalSkillPaths = new Map<string, string>();
	for (const skill of skills) {
		try {
			const canonical = await realpath(skill.path);
			knownPaths.set(canonical, skill.name);
			canonicalSkillPaths.set(skill.path, canonical);
		} catch {}
	}
	const canonicalExplicit = explicitPath
		? await realpath(resolve(ctx.cwd, explicitPath)).catch(() => undefined)
		: undefined;
	let selected = explicitPath
		? skills.find(
				(skill) =>
					canonicalExplicit !== undefined &&
					canonicalSkillPaths.get(skill.path) === canonicalExplicit,
			)
		: undefined;
	if (explicitPath && !selected)
		throw new Error("explicit Aftermath skill path is not a loaded skill");
	throwIfCancelled(active);
	const harvested = await harvestAftermath({
		ctx,
		knownSkillPaths: knownPaths,
		sessionApi: installedAftermathAcceptanceSeam()?.sessionApi,
	});
	throwIfCancelled(active);
	const evidence = rankSkillEvidence(
		harvested.digests,
		new Set(skills.map((skill) => skill.name)),
	);
	if (!selected && ctx.hasUI) {
		if (evidence.suggestion) {
			const action = await ctx.ui.select(
				`Aftermath suggests ${evidence.suggestion}.`,
				[`use ${evidence.suggestion}`, "choose another", "cancel"],
			);
			if (!action || action === "cancel") return;
			if (action === `use ${evidence.suggestion}`)
				selected = skills.find((skill) => skill.name === evidence.suggestion);
		}
		if (!selected) {
			const choices = skills.map(
				(skill) =>
					`${skill.name} — ${canonicalSkillPaths.get(skill.path) ?? skill.path}`,
			);
			const choice = await ctx.ui.select(
				"Choose exactly one Aftermath skill.",
				choices,
			);
			if (!choice) return;
			selected = skills.find(
				(skill) =>
					`${skill.name} — ${canonicalSkillPaths.get(skill.path) ?? skill.path}` ===
					choice,
			);
		}
	}
	if (!selected) throw new Error("one confirmed Aftermath skill is required");
	throwIfCancelled(active);
	const calls = estimateMiningCalls(harvested.digests.length);
	const confirmation = [
		`Readable sessions: ${harvested.digests.length}; unreadable: ${harvested.unreadable}.`,
		"Each digest is capped at 16 KiB, persisted, and sent to the model without redaction.",
		`Estimated mining/aggregation calls: ${calls.mining}/${calls.aggregation}.`,
		"Maximum replay calls after mining: 116 target, 116 rubric-judge, 12 optimizer.",
		"Overkill will not write the source skill.",
	].join("\n");
	if (
		ctx.hasUI &&
		!(await ctx.ui.confirm("Persist and mine Aftermath digests?", confirmation))
	)
		return;
	throwIfCancelled(active);
	const frozenModel = ctx.model;
	const targetModel =
		frozenModel && ctx.modelRegistry.find(frozenModel.provider, frozenModel.id);
	if (!frozenModel || !targetModel || !(await modelHasAuth(ctx)))
		throw new Error("selected model authentication is unavailable");
	const sourcePath = await realpath(selected.path);
	const sourceBytes = await readFile(sourcePath);
	throwIfCancelled(active);
	parseSourceSkill(sourceBytes);
	await resolveLoadedSkill(
		sourcePath,
		pi.getCommands(),
		ctx.isProjectTrusted(),
		ctx.cwd,
	);
	throwIfCancelled(active);
	{
		const created = await createAftermathDirectory(getAgentDir());
		active.runId = created.runId;
		const manifest: AftermathManifest = {
			version: 1 as const,
			runId: created.runId,
			kind: "aftermath" as const,
			source: {
				path: sourcePath,
				fingerprint: fingerprintSource(sourceBytes),
			},
			model: {
				provider: frozenModel.provider,
				id: frozenModel.id,
				thinking: pi.getThinkingLevel(),
			},
			sessionId: ctx.sessionManager.getSessionId(),
			linkEntryId: null,
			stage: "harvest",
			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,
			},
			target: { name: selected.name, path: sourcePath },
		};
		active.interrupt = async () =>
			await persistAftermathManifest(created.directory, {
				...manifest,
				stage: "interrupted",
			});
		await writePrivateText(
			created.directory,
			"baseline-snapshot.md",
			sourceBytes,
		);
		const persisted = await persistHarvest(created.directory, {
			digests: harvested.digests,
			unreadable: harvested.unreadable,
			total: harvested.total,
			evidence: evidence.counts,
		});
		manifest.stage = "mining";
		await persistAftermathManifest(created.directory, {
			...manifest,
			harvestFingerprint: persisted.fingerprint,
		});
		appendProgress(pi, ctx, runEntry({ manifest }));
		const link = ctx.sessionManager.getBranch().at(-1);
		if (!link || typeof link.id !== "string")
			throw new Error("could not persist Aftermath branch link");
		manifest.linkEntryId = link.id;
		await persistAftermathManifest(created.directory, {
			...manifest,
			harvestFingerprint: persisted.fingerprint,
		});
		await mineAftermath({
			pi,
			ctx,
			directory: created.directory,
			manifest,
			digests: harvested.digests,
			targetModel,
			harvestFingerprint: persisted.fingerprint,
		});
	}
}

async function offerAftermathCompletion(
	pi: ExtensionAPI,
	ctx: ExtensionCommandContext,
	directory: string,
): Promise<void> {
	if (!ctx.hasUI || (commandMode(ctx) !== "tui" && commandMode(ctx) !== "rpc"))
		return;
	const choice = await ctx.ui.select(
		"Aftermath complete. Choose next action.",
		["review diff", "keep staged", "discard"],
	);
	if (choice === "review diff") {
		const artifacts = await readFrozenReviewArtifacts(directory);
		const paths = formatResultPaths(artifacts);
		const canRenderDiff = commandMode(ctx) === "tui";
		ctx.ui.notify(
			artifacts.stagedPath && artifacts.staged
				? canRenderDiff
					? `${paths}\n${buildReviewDiff(
							artifacts.sourcePath,
							artifacts.stagedPath,
							artifacts.source,
							artifacts.staged,
						)}`
					: paths
				: `${paths}\nNo candidate staged.`,
			"info",
		);
		return;
	}
	if (choice === "keep staged") {
		ctx.ui.notify("Aftermath artifacts retained.", "info");
		return;
	}
	if (choice === "discard") {
		const selected = selectedAftermathRun(ctx);
		if (!selected)
			throw new Error("Aftermath run is no longer linked to this branch");
		await discardLinkedRun({
			runRoot: join(getAgentDir(), "overkill-runs"),
			runDirectory: directory,
			selected,
			branch: ctx.sessionManager.getBranch(),
			sessionId: ctx.sessionManager.getSessionId(),
		});
		appendProgress(pi, ctx, {
			...selected.data,
			stage: "discarded",
			terminal: "discarded",
		});
	}
}

async function mineAftermath(options: {
	pi: ExtensionAPI;
	ctx: ExtensionCommandContext;
	directory: string;
	manifest: AftermathManifest;
	digests: Digest[];
	targetModel: unknown;
	harvestFingerprint: string;
	completedChunks?: ReadonlyMap<number, unknown[]>;
	completedLevels?: ReadonlyMap<number, unknown[][]>;
	attemptedMiningCalls?: number;
	frozen?: Awaited<ReturnType<typeof readFrozenTasks>>;
}): Promise<void> {
	const active = activeRun;
	if (!active || active.kind !== "aftermath")
		throw new Error("Aftermath run ownership is unavailable");
	const { ctx, manifest } = options;
	manifest.stage = "mining";
	active.interrupt = async () => {
		const interrupted = {
			...manifest,
			stage: "interrupted",
			harvestFingerprint: options.harvestFingerprint,
		};
		await persistAftermathManifest(options.directory, interrupted);
		const entry = runEntry({ manifest: interrupted });
		if (active.suppressOutput) appendProgressEntry(options.pi, entry);
		else appendProgress(options.pi, ctx, entry);
	};
	const chunks = new Set(options.completedChunks?.keys());
	const levels = new Set<string>();
	let attemptedMiningCalls = options.attemptedMiningCalls ?? 0;
	for (const [level, outputs] of options.completedLevels ?? [])
		for (const index of outputs.keys()) levels.add(`${level}:${index}`);
	const persistCheckpoint = async () =>
		await persistMiningCheckpoint(options.directory, {
			attemptedCalls: attemptedMiningCalls,
			completedChunks: [...chunks],
			completedLevels: [...levels].map((item) => {
				const [levelText, indexText] = item.split(":");
				return { level: Number(levelText), index: Number(indexText) };
			}),
		});
	const frozen =
		options.frozen ??
		(await (async () => {
			const proposals = await mineTaskProposals({
				digests: options.digests,
				createSession: () =>
					createMiningSession(
						{
							cwd: ctx.cwd,
							agentDir: getAgentDir(),
							model: manifest.model,
							targetModel: options.targetModel,
							modelRegistry: ctx.modelRegistry,
						},
						installedAftermathAcceptanceSeam()?.structuredOutputSdk,
					),
				signal: active.controller.signal,
				completedChunks: options.completedChunks,
				completedLevels: options.completedLevels,
				onCall: async () => {
					attemptedMiningCalls += 1;
					await persistCheckpoint();
				},
				onChunk: async (index, output) => {
					await persistMiningOutput(
						options.directory,
						`miner-chunk-${index}.json`,
						output,
					);
					chunks.add(index);
					await persistCheckpoint();
				},
				onLevel: async (level, index, output) => {
					await persistMiningOutput(
						options.directory,
						`aggregate-${level}-${index}.json`,
						output,
					);
					levels.add(`${level}:${index}`);
					await persistCheckpoint();
				},
			});
			throwIfCancelled(active);
			const tasks = validateAndFreezeTasks({
				proposals,
				harvestedSessionIds: new Set(
					options.digests.map((digest) => digest.sessionId),
				),
			});
			const splits = assignSplits(tasks);
			const persisted = await persistFrozenTasks(
				options.directory,
				tasks,
				splits,
			);
			return { ...persisted, tasks, splits };
		})());
	const { tasks, splits } = frozen;
	if (
		manifest.taskFingerprint !== undefined &&
		manifest.taskFingerprint !== frozen.fingerprint
	)
		throw new Error("frozen task fingerprint changed; resume is unsafe");
	manifest.harvestFingerprint = options.harvestFingerprint;
	manifest.taskFingerprint = frozen.fingerprint;
	const callBounds = upperBoundCalls({
		train: splits.train.length,
		val: splits.validation.length,
		test: splits.test.length,
	});
	const taskById = new Map(tasks.map((task) => [task.id, task]));
	const rubricCount = (split: "train" | "validation" | "test") =>
		splits[split].filter((id) => taskById.get(id)?.rubric !== undefined).length;
	const judgeMaximum =
		rubricCount("validation") +
		3 * (rubricCount("train") + rubricCount("validation")) +
		rubricCount("test");
	manifest.scorers = tasks.map((task) => ({
		id: task.id,
		kind: task.checks ? ("deterministic" as const) : ("rubric" as const),
	}));
	manifest.splits = splits;
	let costs = (await readAftermathCost(options.directory)) ?? {
		targetMaximum: tasks.length < 3 ? 0 : callBounds.target,
		judgeMaximum: tasks.length < 3 ? 0 : judgeMaximum,
		targetConsumed: 0,
		judgeConsumed: 0,
	};
	if (
		costs.targetMaximum !== (tasks.length < 3 ? 0 : callBounds.target) ||
		costs.judgeMaximum !== (tasks.length < 3 ? 0 : judgeMaximum)
	)
		throw new Error("Aftermath replay call maximum changed; resume is unsafe");
	manifest.calls.target = costs.targetConsumed;
	manifest.calls.judge = costs.judgeConsumed;
	await persistAftermathCost(options.directory, costs);
	const callNotice = `Aftermath replay maximum: ${costs.targetMaximum} target calls, ${costs.judgeMaximum} rubric-judge calls.`;
	if (commandMode(ctx) === "print") writePrint(callNotice);
	else if (commandMode(ctx) !== "json") ctx.ui.notify(callNotice, "info");
	const allowCall = (kind: "target" | "judge") => {
		const maximum =
			kind === "target" ? costs.targetMaximum : costs.judgeMaximum;
		const consumed =
			kind === "target" ? costs.targetConsumed : costs.judgeConsumed;
		if (consumed >= maximum)
			throw new Error(`Aftermath ${kind} call maximum exceeded`);
	};
	const recordCall = async (kind: "target" | "judge") => {
		allowCall(kind);
		if (
			kind === "target" &&
			fingerprintSource(await readFile(manifest.source.path)) !==
				manifest.source.fingerprint
		)
			throw new Error("source fingerprint changed; replay is unsafe");
		costs = {
			...costs,
			...(kind === "target"
				? { targetConsumed: costs.targetConsumed + 1 }
				: { judgeConsumed: costs.judgeConsumed + 1 }),
		};
		await persistAftermathCost(options.directory, costs);
		manifest.calls[kind] =
			kind === "target" ? costs.targetConsumed : costs.judgeConsumed;
		await persistAftermathManifest(options.directory, manifest);
	};
	throwIfCancelled(active);
	if (tasks.length < 3) {
		const reportPath = await persistFinalReport(options.directory, {
			version: 1,
			kind: "aftermath",
			taskFingerprint: frozen.fingerprint,
			taskIds: tasks.map((task) => task.id),
			splits,
			targetCallMaximum: costs.targetMaximum,
			judgeCallMaximum: costs.judgeMaximum,
			targetCalls: costs.targetConsumed,
			judgeCalls: costs.judgeConsumed,
			terminal: "insufficient_tasks",
		});
		manifest.stage = "complete";
		manifest.terminal = "no_improvement";
		manifest.artifacts.report = "report.json";
		await persistAftermathManifest(options.directory, manifest);
		const entry = runEntry(
			{ manifest },
			{ completed: tasks.length, total: 30 },
			{ reportPath, stagedPath: null },
		);
		appendProgress(options.pi, ctx, entry);
		const paths = formatResultPaths({
			sourcePath: manifest.source.path,
			reportPath,
			stagedPath: null,
		});
		if (commandMode(ctx) === "print") writePrint(paths);
		else if (commandMode(ctx) !== "json")
			ctx.ui.notify(`${paths}\nAftermath found insufficient tasks.`, "info");
		await offerAftermathCompletion(options.pi, ctx, options.directory);
		return;
	}
	await persistAftermathManifest(options.directory, manifest);
	const currentSource = await readFile(manifest.source.path);
	if (fingerprintSource(currentSource) !== manifest.source.fingerprint)
		throw new Error("source fingerprint changed; replay is unsafe");
	const frozenSource = await readFile(
		join(options.directory, "baseline-snapshot.md"),
	);
	if (fingerprintSource(frozenSource) !== manifest.source.fingerprint)
		throw new Error("frozen source fingerprint changed; replay is unsafe");
	const source = parseSourceSkill(frozenSource);
	const loadedSkill = await resolveLoadedSkill(
		manifest.source.path,
		options.pi.getCommands(),
		ctx.isProjectTrusted(),
		ctx.cwd,
	);
	const byId = new Map(tasks.map((task) => [task.id, task]));
	const taskItems = (split: "train" | "validation" | "test") =>
		splits[split].map((id) => {
			const task = byId.get(id);
			if (!task) throw new Error("frozen split task is unavailable");
			return { id, prompt: generatedTaskPrompt(task) };
		});
	const judgeCache = await readJudgeCache(options.directory);
	const scorer = createGeneratedTaskScorer(tasks, {
		judge: async (task, response, signal) => {
			const key = rubricCacheKey(task.id, response);
			const cached = judgeCache[key];
			if (cached) return cached;
			const result = await runRubricJudge(
				task,
				response,
				{
					createSession: () =>
						createRubricJudgeSession(
							{
								cwd: ctx.cwd,
								agentDir: getAgentDir(),
								model: manifest.model,
								targetModel: options.targetModel,
								modelRegistry: ctx.modelRegistry,
							},
							installedAftermathAcceptanceSeam()?.structuredOutputSdk,
						),
				},
				signal,
				async () => await recordCall("judge"),
			);
			judgeCache[result.cacheKey] = {
				score: result.score,
				passed: result.passed,
				rationale: result.rationale,
			};
			await persistJudgeCache(options.directory, judgeCache);
			return result;
		},
	});
	await executeBaseline({
		pi: options.pi,
		ctx,
		directory: options.directory,
		manifest,
		source,
		loadedSkill,
		targetModel: options.targetModel,
		taskAdapter: {
			items: taskItems,
			scoreResponse: async ({ item, response, signal }) =>
				await scorer({ id: item.id, response, signal }),
			onTargetCall: async () => await recordCall("target"),
		},
		reportExtras: () => ({
			taskFingerprint: frozen.fingerprint,
			targetCallMaximum: costs.targetMaximum,
			judgeCallMaximum: costs.judgeMaximum,
			targetCalls: costs.targetConsumed,
			judgeCalls: costs.judgeConsumed,
		}),
	});
	await offerAftermathCompletion(options.pi, ctx, options.directory);
}

async function resumeAftermath(
	pi: ExtensionAPI,
	ctx: ExtensionCommandContext,
	selected: NonNullable<ReturnType<typeof selectedAftermathRun>>,
): Promise<void> {
	const active = activeRun;
	if (!active || active.kind !== "aftermath")
		throw new Error("Aftermath run ownership is unavailable");
	const directory = join(getAgentDir(), "overkill-runs", selected.data.runId);
	let manifest = await readAftermathManifest(directory);
	if (manifest.terminal)
		throw new Error("only incomplete Aftermath runs can resume");
	if (
		manifest.runId !== selected.data.runId ||
		manifest.sessionId !== ctx.sessionManager.getSessionId()
	)
		throw new Error("run is not linked to this active session branch");
	manifest = (await recoverRunLink({
		directory,
		manifest,
		selected,
		branch: ctx.sessionManager.getBranch(),
	})) as AftermathManifest;
	const sourcePath = await realpath(manifest.source.path);
	const source = await readFile(sourcePath);
	if (fingerprintSource(source) !== manifest.source.fingerprint)
		throw new Error("source fingerprint changed; resume is unsafe");
	const targetModel = ctx.modelRegistry.find(
		manifest.model.provider,
		manifest.model.id,
	);
	if (
		!targetModel ||
		!(await modelHasAuth(ctx, manifest.model.provider, manifest.model.id))
	)
		throw new Error("recorded model authentication is unavailable");
	const harvest = await readHarvest(directory);
	if (harvest.fingerprint !== manifest.harvestFingerprint)
		throw new Error("harvest fingerprint changed; resume is unsafe");
	const frozen = await readFrozenTasks(directory).catch((error) => {
		if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
		throw error;
	});
	const checkpoint = await readMiningCheckpoint(directory);
	const chunks = new Map<number, unknown[]>();
	const levels = new Map<number, unknown[][]>();
	for (const index of checkpoint?.completedChunks ?? [])
		chunks.set(
			index,
			await readMiningOutput(directory, `miner-chunk-${index}.json`),
		);
	for (const { level, index } of checkpoint?.completedLevels ?? []) {
		const outputs = levels.get(level) ?? [];
		outputs[index] = await readMiningOutput(
			directory,
			`aggregate-${level}-${index}.json`,
		);
		levels.set(level, outputs);
	}
	active.runId = manifest.runId;
	await mineAftermath({
		pi,
		ctx,
		directory,
		manifest,
		digests: harvest.digests,
		targetModel,
		harvestFingerprint: harvest.fingerprint,
		completedChunks: chunks,
		completedLevels: levels,
		attemptedMiningCalls: checkpoint?.attemptedCalls ?? 0,
		frozen,
	});
}

async function resumeBaseline(
	pi: ExtensionAPI,
	ctx: ExtensionCommandContext,
	selected: NonNullable<ReturnType<typeof selectedRun>>,
): Promise<void> {
	const directory = join(getAgentDir(), "overkill-runs", selected.data.runId);
	const active = activeRun;
	if (!active || active.sessionId !== ctx.sessionManager.getSessionId())
		throw new Error("Overkill run ownership is unavailable");
	active.runId = selected.data.runId;
	active.interrupt = async () =>
		await checkpointInterrupted(directory, await readManifest(directory));
	let manifest = await readManifest(directory);
	if (manifest.terminal) throw new Error("selected run is terminal");
	if (
		manifest.runId !== selected.data.runId ||
		manifest.sessionId !== ctx.sessionManager.getSessionId()
	)
		throw new Error("run is not linked to this active session branch");
	manifest = await recoverRunLink({
		directory,
		manifest,
		selected,
		branch: ctx.sessionManager.getBranch(),
	});
	active.runId = manifest.runId;
	active.interrupt = async () =>
		await checkpointInterrupted(directory, manifest);
	throwIfCancelled(active);
	const originalLink = ctx.sessionManager.getBranch().find((entry) => {
		if (typeof entry !== "object" || entry === null) return false;
		const candidate = entry as {
			id?: unknown;
			type?: unknown;
			customType?: unknown;
			data?: unknown;
		};
		if (
			candidate.id !== manifest.linkEntryId ||
			candidate.type !== "custom" ||
			candidate.customType !== "overkill-run"
		)
			return false;
		try {
			const data = validateRunEntry(candidate.data);
			return data.kind === "suite" && data.runId === manifest.runId;
		} catch {
			return false;
		}
	});
	if (!originalLink)
		throw new Error("run is no longer linked to this active branch");
	const sourcePath = await realpath(manifest.source.path);
	throwIfCancelled(active);
	const sourceBytes = await readFile(sourcePath);
	throwIfCancelled(active);
	if (fingerprintSource(sourceBytes) !== manifest.source.fingerprint)
		throw new Error("source fingerprint changed; resume is unsafe");
	if (!manifest.suite) throw new Error("suite run has no suite contract");
	const suite = await validateTrustedSuite(
		manifest.suite.path,
		ctx.cwd,
		ctx.isProjectTrusted(),
	);
	throwIfCancelled(active);
	if ((await fingerprintSuite(suite.suitePath)) !== manifest.suite.fingerprint)
		throw new Error("suite fingerprint changed; resume is unsafe");
	throwIfCancelled(active);
	const model = ctx.modelRegistry.find(
		manifest.model.provider,
		manifest.model.id,
	);
	if (
		!model ||
		!(await modelHasAuth(ctx, manifest.model.provider, manifest.model.id))
	)
		throw new Error("recorded model authentication is unavailable");
	const loadedSkill = await resolveLoadedSkill(
		sourcePath,
		pi.getCommands(),
		ctx.isProjectTrusted(),
		ctx.cwd,
	);
	throwIfCancelled(active);
	await executeBaseline({
		pi,
		ctx,
		directory,
		manifest,
		source: parseSourceSkill(sourceBytes),
		loadedSkill,
		suite,
		targetModel: model,
	});
}

export default function overkill(pi: ExtensionAPI): void {
	pi.on("session_shutdown", async (_event, ctx) => {
		const sessionId = ctx.sessionManager.getSessionId();
		if (!activeRun) {
			if (startPending && pendingSessionId === sessionId)
				pendingCancelled = true;
			return;
		}
		if (activeRun.sessionId !== sessionId) return;
		activeRun.suppressOutput = true;
		requestCancellation(activeRun);
		try {
			await activeRun.completed;
		} catch {}
	});
	pi.registerEntryRenderer<RunEntry>(
		"overkill-run",
		(entry, options, theme) => {
			let data: RunEntry;
			try {
				data = validateRunEntry(entry.data);
			} catch {
				return undefined;
			}
			const summary = theme.fg("accent", formatProgress(data));
			if (!options.expanded)
				return new Text(
					`${summary} ${theme.fg("dim", keyHint("app.tools.expand", "to expand"))}`,
					0,
					0,
				);
			const details = [summary];
			try {
				const artifacts = readFrozenReviewArtifactsSync(
					join(getAgentDir(), "overkill-runs", data.runId),
				);
				details.push(
					theme.fg(
						"dim",
						`Source: ${sanitizeTerminalText(artifacts.sourcePath)}`,
					),
				);
				if (artifacts.reportPath)
					details.push(
						theme.fg(
							"dim",
							`Report: ${sanitizeTerminalText(artifacts.reportPath)}`,
						),
					);
				if (artifacts.stagedPath && artifacts.staged) {
					details.push(
						theme.fg(
							"dim",
							`Staged: ${sanitizeTerminalText(artifacts.stagedPath)}`,
						),
					);
					details.push(
						buildReviewDiff(
							artifacts.sourcePath,
							artifacts.stagedPath,
							artifacts.source,
							artifacts.staged,
						),
					);
				}
			} catch {
				details.push(theme.fg("warning", "Review artifacts unavailable."));
			}
			return new Text(details.join("\n"), 0, 0);
		},
	);
	pi.registerCommand("overkill", {
		description:
			"Evaluate a trusted explicit suite baseline for a loaded Pi skill.",
		getArgumentCompletions: (prefix) => {
			const trimmed = prefix.trim();
			if (trimmed.startsWith("aftermath")) {
				const nested = trimmed.slice("aftermath".length).trim();
				const choices = ["status", "resume", "review", "discard", "cancel"]
					.filter((command) => command.startsWith(nested))
					.map((command) => ({
						value: `aftermath ${command}`,
						label: `aftermath ${command}`,
					}));
				return choices.length > 0 ? choices : null;
			}
			const choices = SUBCOMMANDS.filter((command) =>
				command.startsWith(trimmed),
			).map((command) => ({ value: command, label: command }));
			return choices.length > 0 ? choices : null;
		},
		handler: async (args, ctx) => {
			const parts = parseArguments(args);
			const command = parts[0];
			if (command === "aftermath") {
				const subcommand = parts[1];
				if (subcommand === "status") {
					const run = selectedAftermathRun(ctx);
					if (!run)
						ctx.ui.notify(
							"No Overkill Aftermath run is linked to this branch.",
							"info",
						);
					else if (commandMode(ctx) === "json")
						appendProgress(pi, ctx, run.data);
					else if (commandMode(ctx) === "print")
						writePrint(statusMessage(run.data));
					else ctx.ui.notify(statusMessage(run.data), "info");
					return;
				}
				if (subcommand === "cancel") {
					if (
						activeRun &&
						activeRun.kind === "aftermath" &&
						activeRun.sessionId === ctx.sessionManager.getSessionId()
					)
						requestCancellation(activeRun);
					else ctx.ui.notify("No Overkill Aftermath run is active.", "info");
					return;
				}
				if (["resume", "review", "discard"].includes(subcommand ?? "")) {
					const run = selectedAftermathRun(ctx);
					if (!run) {
						ctx.ui.notify(
							"No Overkill Aftermath run is linked to this branch.",
							"info",
						);
						return;
					}
					const directory = join(
						getAgentDir(),
						"overkill-runs",
						run.data.runId,
					);
					try {
						const manifest = await readAftermathManifest(directory);
						if (manifest.sessionId !== ctx.sessionManager.getSessionId())
							throw new Error(
								"run is not linked to this active session branch",
							);
						if (subcommand === "review") {
							const artifacts = await readFrozenReviewArtifacts(directory);
							const entry = {
								...run.data,
								sourcePath: artifacts.sourcePath,
								reportPath: artifacts.reportPath,
								stagedPath: artifacts.stagedPath,
							};
							const paths = formatResultPaths(entry);
							if (commandMode(ctx) === "json") appendProgress(pi, ctx, entry);
							else if (commandMode(ctx) === "print") {
								writePrint(paths);
								if (artifacts.stagedPath && artifacts.staged)
									writePrint(
										buildReviewDiff(
											artifacts.sourcePath,
											artifacts.stagedPath,
											artifacts.source,
											artifacts.staged,
										),
									);
								else writePrint("No candidate staged.");
							} else {
								ctx.ui.notify(
									artifacts.stagedPath
										? paths
										: `${paths}\nNo candidate staged.`,
									"info",
								);
								if (
									commandMode(ctx) === "tui" &&
									artifacts.stagedPath &&
									artifacts.staged
								)
									ctx.ui.notify(
										buildReviewDiff(
											artifacts.sourcePath,
											artifacts.stagedPath,
											artifacts.source,
											artifacts.staged,
										),
										"info",
									);
							}
						} else if (subcommand === "discard") {
							if (manifest.terminal === "discarded")
								throw new Error("discarded run artifacts are unavailable");
							await discardLinkedRun({
								runRoot: join(getAgentDir(), "overkill-runs"),
								runDirectory: directory,
								selected: run,
								branch: ctx.sessionManager.getBranch(),
								sessionId: ctx.sessionManager.getSessionId(),
								allowNonterminal: true,
								isRunActive: (runId) => activeRun?.runId === runId,
							});
							appendProgress(pi, ctx, {
								...run.data,
								stage: "discarded",
								terminal: "discarded",
							});
						} else if (manifest.terminal) {
							ctx.ui.notify(
								"Aftermath mining is already complete; stored tasks are frozen.",
								"info",
							);
						} else {
							await withActiveRun(
								ctx,
								async () => await resumeAftermath(pi, ctx, run),
								"aftermath",
							);
						}
					} catch (error) {
						if (!(error instanceof RolloutCancelledError))
							ctx.ui.notify(
								`Overkill Aftermath ${subcommand} failed: ${error instanceof Error ? error.message : String(error)}`,
								"error",
							);
					}
					return;
				}
				if (activeRun || startPending) {
					ctx.ui.notify("An Overkill rollout is already active.", "error");
					return;
				}
				startPending = true;
				pendingSessionId = ctx.sessionManager.getSessionId();
				pendingCancelled = false;
				try {
					await withActiveRun(
						ctx,
						async () => await runAftermath(pi, ctx, parts.slice(1)),
						"aftermath",
					);
				} catch (error) {
					if (!(error instanceof RolloutCancelledError))
						ctx.ui.notify(
							`Overkill Aftermath failed: ${error instanceof Error ? error.message : String(error)}`,
							"error",
						);
				} finally {
					startPending = false;
					pendingSessionId = undefined;
					pendingCancelled = false;
				}
				return;
			}
			if (command === "status") {
				const run = selectedRun(ctx);
				if (!run) {
					ctx.ui.notify(
						"No Overkill suite run is linked to this branch.",
						"info",
					);
					return;
				}
				const mode = commandMode(ctx);
				if (mode === "json") appendProgress(pi, ctx, run.data);
				else if (mode === "print") writePrint(statusMessage(run.data));
				else ctx.ui.notify(statusMessage(run.data), "info");
				return;
			}
			if (command === "discard") {
				const run = selectedRun(ctx);
				if (!run) {
					ctx.ui.notify(
						"No Overkill suite run is linked to this branch.",
						"info",
					);
					return;
				}
				try {
					await discardLinkedRun({
						runRoot: join(getAgentDir(), "overkill-runs"),
						runDirectory: join(getAgentDir(), "overkill-runs", run.data.runId),
						selected: run,
						branch: ctx.sessionManager.getBranch(),
						sessionId: ctx.sessionManager.getSessionId(),
					});
					appendProgress(pi, ctx, {
						...run.data,
						stage: "discarded",
						terminal: "discarded",
					});
					ctx.ui.notify("Overkill run discarded.", "info");
				} catch (error) {
					ctx.ui.notify(
						`Overkill discard failed: ${error instanceof Error ? error.message : String(error)}`,
						"error",
					);
				}
				return;
			}
			if (command === "cancel") {
				if (
					!activeRun ||
					activeRun.sessionId !== ctx.sessionManager.getSessionId()
				) {
					ctx.ui.notify("No Overkill rollout is active.", "info");
					return;
				}
				requestCancellation(activeRun);
				if (commandMode(ctx) !== "json")
					ctx.ui.notify("Overkill cancellation requested.", "info");
				return;
			}
			if (command === "review") {
				const run = selectedRun(ctx);
				if (!run) {
					ctx.ui.notify(
						"No Overkill suite run is linked to this branch.",
						"info",
					);
					return;
				}
				if (!run.data.terminal) {
					ctx.ui.notify("Overkill run is not terminal yet.", "info");
					return;
				}
				if (run.data.terminal === "discarded") {
					ctx.ui.notify(
						"Overkill run was discarded; review artifacts are unavailable.",
						"info",
					);
					return;
				}
				const artifacts = await readFrozenReviewArtifacts(
					join(getAgentDir(), "overkill-runs", run.data.runId),
				);
				const entry = {
					...run.data,
					sourcePath: artifacts.sourcePath,
					reportPath: artifacts.reportPath,
					stagedPath: artifacts.stagedPath,
				};
				const paths = formatResultPaths(entry);
				const mode = commandMode(ctx);
				if (mode === "json") appendProgress(pi, ctx, entry);
				else if (mode === "print") {
					writePrint(paths);
					if (artifacts.stagedPath && artifacts.staged)
						writePrint(
							buildReviewDiff(
								artifacts.sourcePath,
								artifacts.stagedPath,
								artifacts.source,
								artifacts.staged,
							),
						);
					else writePrint("No candidate staged.");
				} else {
					ctx.ui.notify(
						artifacts.stagedPath ? paths : `${paths}\nNo candidate staged.`,
						"info",
					);
					if (mode === "tui" && artifacts.stagedPath && artifacts.staged)
						ctx.ui.notify(
							buildReviewDiff(
								artifacts.sourcePath,
								artifacts.stagedPath,
								artifacts.source,
								artifacts.staged,
							),
							"info",
						);
				}
				return;
			}
			if (command === "resume") {
				if (activeRun || startPending) {
					ctx.ui.notify("An Overkill rollout is already active.", "error");
					return;
				}
				const run = selectedRun(ctx);
				if (!run) {
					ctx.ui.notify(
						"No Overkill suite run is linked to this branch.",
						"info",
					);
					return;
				}
				startPending = true;
				pendingSessionId = ctx.sessionManager.getSessionId();
				pendingCancelled = false;
				try {
					await withActiveRun(
						ctx,
						async () => await resumeBaseline(pi, ctx, run),
					);
				} catch (error) {
					if (
						error instanceof RolloutCancelledError ||
						error instanceof OptimizerCancelledError
					)
						return;
					ctx.ui.notify(
						`Overkill resume failed: ${error instanceof Error ? error.message : String(error)}`,
						"error",
					);
				} finally {
					startPending = false;
					pendingSessionId = undefined;
					pendingCancelled = false;
				}
				return;
			}
			const [sourcePath, suitePath, ...extra] = parts;
			if (!sourcePath || !suitePath || extra.length > 0) {
				ctx.ui.notify("Usage: /overkill <skill-path> <suite-dir>", "error");
				return;
			}
			if (activeRun || startPending) {
				ctx.ui.notify("An Overkill rollout is already active.", "error");
				return;
			}
			const invokingModel = ctx.model;
			const targetModel =
				invokingModel &&
				ctx.modelRegistry.find(invokingModel.provider, invokingModel.id);
			startPending = true;
			pendingSessionId = ctx.sessionManager.getSessionId();
			pendingCancelled = false;
			try {
				if (invokingModel && !targetModel)
					throw new Error(
						"selected model is unavailable from the invoking registry",
					);
				const preflightOptions = {
					agentDir: getAgentDir(),
					cwd: ctx.cwd,
					sourcePath,
					suitePath,
					commands: pi.getCommands(),
					projectTrusted: ctx.isProjectTrusted(),
					sessionId: ctx.sessionManager.getSessionId(),
					model: invokingModel
						? {
								provider: invokingModel.provider,
								id: invokingModel.id,
								thinking: pi.getThinkingLevel(),
							}
						: undefined,
					authAvailable: await modelHasAuth(
						ctx,
						invokingModel?.provider,
						invokingModel?.id,
					),
				};
				const inspected = await inspectSuiteRun(preflightOptions);
				if (commandMode(ctx) === "tui" || commandMode(ctx) === "rpc") {
					const confirmed = await ctx.ui.confirm(
						"Start Overkill run?",
						buildConfirmation({
							sourcePath: inspected.sourcePath,
							suitePath: inspected.suite.suitePath,
							splitCounts: inspected.suite.splitCounts,
						}),
					);
					if (!confirmed) {
						ctx.ui.notify("Overkill start cancelled.", "info");
						return;
					}
				}
				if (pendingCancelled) throw new RolloutCancelledError();
				await withActiveRun(ctx, async (active) => {
					throwIfCancelled(active);
					const run = await prepareSuiteRun(preflightOptions);
					active.runId = run.manifest.runId;
					active.interrupt = async () =>
						await checkpointInterrupted(run.directory, run.manifest);
					throwIfCancelled(active);
					appendProgress(pi, ctx, runEntry(run));
					const link = ctx.sessionManager.getBranch().at(-1);
					if (!link || typeof link.id !== "string")
						throw new Error("could not persist branch link");
					run.manifest.linkEntryId = link.id;
					await persistManifest(run.directory, run.manifest);
					throwIfCancelled(active);
					await executeBaseline({
						pi,
						ctx,
						directory: run.directory,
						manifest: run.manifest,
						source: run.source,
						loadedSkill: run.loadedSkill,
						suite: run.suite,
						targetModel,
					});
				});
			} catch (error) {
				if (
					error instanceof RolloutCancelledError ||
					error instanceof OptimizerCancelledError
				)
					return;
				ctx.ui.notify(
					`Overkill baseline failed: ${error instanceof Error ? error.message : String(error)}`,
					"error",
				);
			} finally {
				startPending = false;
				pendingSessionId = undefined;
				pendingCancelled = false;
			}
		},
	});
}