import { createHash } from "node:crypto"; import { writeSync } from "node:fs"; import { readdir, readFile, realpath } from "node:fs/promises"; import { basename, dirname, extname, isAbsolute, join, relative, resolve, } from "node:path"; import { type ExtensionAPI, type ExtensionCommandContext, getAgentDir, keyHint, renderDiff, SessionManager, } from "@earendil-works/pi-coding-agent"; import { Key, matchesKey, SelectList, 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, buildReviewDiffPreview, formatProgress, formatResultPaths, formatScore, 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", "suite", "status", "resume", "review", "discard", "cancel", ] as const; type ActiveRun = { kind: "suite" | "aftermath"; runId: string; sessionId: string; controller: AbortController; suppressOutput: boolean; completed?: Promise; cancelRequested?: boolean; interrupt?: () => Promise; 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: ( sessionDir?: string, ) => Promise>; open: ( path: string, sessionDir?: 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; }; 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)[ explicitSuiteAcceptanceSeam ] as ExplicitSuiteAcceptanceSeam | undefined; } function installedAftermathAcceptanceSeam(): | AftermathAcceptanceSeam | undefined { return (globalThis as Record)[ aftermathAcceptanceSeam ] as AftermathAcceptanceSeam | undefined; } function installedModeAcceptanceSeam(): ModeAcceptanceSeam | undefined { return (globalThis as Record)[modeAcceptanceSeam] as | ModeAcceptanceSeam | undefined; } /** Installs deterministic session boundaries while retaining command orchestration. */ export function installExplicitSuiteAcceptanceSeam( seam: ExplicitSuiteAcceptanceSeam, ): () => void { const globals = globalThis as Record; 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; 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; 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 buildSuiteAuthoringPrompt( sourcePath: string, suitePath: string | undefined, projectRoot: string, ): string { const sourceName = basename(sourcePath); const skillName = sourceName === "SKILL.md" ? basename(dirname(sourcePath)) : basename(sourceName, extname(sourceName)); const destination = suitePath ? `Use ${JSON.stringify(suitePath)} as the suite directory.` : `Choose a suite directory inside ${JSON.stringify(projectRoot)}. Prefer an established project evaluator location; otherwise use the project-local scratch directory ${JSON.stringify(join(projectRoot, ".overkill", "suites", skillName))}.`; return `Create a trusted explicit evaluator suite for the loaded Pi skill at ${JSON.stringify(sourcePath)}. ${destination} Read the complete skill and only its directly referenced files needed to understand behavior. The suite contract below is authoritative; do not inspect Overkill implementation or unrelated project documentation. Inspect the destination once immediately before writing; if evaluator files already exist or appear concurrently modified, stop and ask rather than overwriting them. Do not design locks, atomic reservations, or repeated concurrency probes. After that single inspection, write the four files immediately without narrating a plan. Create exactly this layout and nothing else inside the suite directory: - train/items.json - val/items.json - test/items.json - check.mjs Create a small first suite: exactly 3 train items, 2 validation items, and 2 test items, with globally unique nonempty string ids and nonempty prompts no larger than 16 KiB. Add checker-owned expected fields when useful. Use train cases for optimization, validation cases for candidate selection, and held-out test cases for final evaluation; keep scenarios distinct across splits. Prioritize the skill's highest-risk and most representative successful and failure workflows; report omitted coverage instead of adding more cases. Keep each item concise and use a small shared expectation vocabulary such as exact, required substrings, forbidden substrings, or simple patterns. Do not design a domain-specific testing framework. The checker must read one JSON object from stdin, inspect item, response, trajectory, and calledTools, then write exactly one JSON object with score in [0,1], Boolean passed, and optional feedback. Write all four files before refining them, and keep check.mjs under 120 lines. Use only Node.js standard library in check.mjs. Keep checks bounded, cross-platform, and independent of network, credentials, mutable external state, and the source skill's exact wording. Do not weaken trust-boundary, security, data-loss, or required human-confirmation behavior. Validate the JSON and checker locally with one passing and one failing input. Do not start Overkill automatically. Summarize coverage, limitations, and the exact /overkill command the user should run after reviewing check.mjs.`; } export function parseArguments(input: string): string[] { const parts: string[] = []; let index = 0; while (index < input.length) { while (/\s/u.test(input[index] ?? "")) index += 1; if (index >= input.length) break; let token = ""; while (index < input.length && !/\s/u.test(input[index] ?? "")) { const quote = input[index]; if (quote !== '"' && quote !== "'") { token += quote; index += 1; continue; } index += 1; let closed = false; while (index < input.length) { const character = input[index]; if (character === quote) { closed = true; index += 1; break; } if (character === "\\" && input[index + 1] === quote) { token += quote; index += 2; } else { token += character; index += 1; } } if (!closed) throw new Error("unterminated quoted argument"); } parts.push(token); } return parts; } async function canonicalProspectivePath(path: string): Promise { let existing = resolve(path); const missing: string[] = []; while (true) { try { return resolve(await realpath(existing), ...missing); } catch (error) { if ( !(error instanceof Error) || !("code" in error) || error.code !== "ENOENT" ) throw error; } const parent = dirname(existing); if (parent === existing) throw new Error("path has no existing ancestor"); missing.unshift(basename(existing)); existing = parent; } } 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 = { 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 { 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()); } export async function unfinishedRunWarning( sourcePath: string | undefined, suitePath?: string, agentDir = getAgentDir(), ): Promise { const root = join(agentDir, "overkill-runs"); const entries = await readdir(root, { withFileTypes: true }).catch(() => []); const runIds: string[] = []; for (const entry of entries) { if (!entry.isDirectory()) continue; const manifest = await readManifest(join(root, entry.name)).catch( () => undefined, ); if ( manifest?.terminal === null && ((sourcePath !== undefined && manifest.source.path === sourcePath) || (suitePath !== undefined && manifest.suite?.path === suitePath)) ) runIds.push(manifest.runId); } if (runIds.length === 0) return undefined; return `${runIds.length} unfinished Overkill run${runIds.length === 1 ? "" : "s"} already target this skill or suite (${runIds.slice(0, 3).join(", ")}${runIds.length > 3 ? ", …" : ""}). They may be active in other Pi processes; parallel runs duplicate model cost, and suite edits can invalidate running evaluations.`; } function statusMessage(run: RunEntry): string { if ( run.kind === "suite" && run.stage === "complete" && run.terminal === "no_improvement" && run.bestScore === 1 ) return `Overkill: complete | completed: ${run.completed ?? 0}${run.total === undefined ? "" : `/${run.total}`} | outcome: baseline perfect; optimization skipped`; 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 showProgress(ctx: ExtensionCommandContext, text: string): void { const mode = commandMode(ctx); if (mode === "rpc") ctx.ui.setStatus("overkill", text); if (mode === "tui") ctx.ui.setWidget("overkill-progress", [text], { placement: "belowEditor", }); } function appendProgress( pi: ExtensionAPI, ctx: ExtensionCommandContext, entry: RunEntry, ): void { const mode = commandMode(ctx); const durable = entry.terminal !== null || entry.stage === "preflight" || entry.stage === "interrupted" || (entry.kind === "aftermath" && entry.stage === "mining" && entry.completed === undefined); if (mode !== "tui" || durable) appendProgressEntry(pi, entry); const progress = formatProgress(entry); showProgress(ctx, progress); if (mode === "print") writePrint(progress); } function clearProgress(ctx: ExtensionCommandContext): void { if (commandMode(ctx) === "rpc") ctx.ui.setStatus("overkill", undefined); if (commandMode(ctx) === "tui") ctx.ui.setWidget("overkill-progress", 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, kind: ActiveRun["kind"] = "suite", ): Promise { 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(); } 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 { 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; }; async function executeBaseline(options: { pi: ExtensionAPI; ctx: ExtensionCommandContext; directory: string; manifest: RunManifest; source: ReturnType; loadedSkill: Awaited>; suite?: Awaited>; targetModel: unknown; taskAdapter?: CoreTaskAdapter; reportExtras?: () => Record; deferCompletionNotice?: boolean; }): Promise { 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, }, 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 (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( `Baseline already scores 1; no strictly better candidate exists, so optimization was skipped.\n${paths}`, ); else if ( commandMode(ctx) !== "json" && !options.deferCompletionNotice ) ctx.ui.notify( "Baseline already scores 1; no strictly better candidate exists, so optimization was skipped.", "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 => { 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; 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, }, 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" && !options.deferCompletionNotice) ctx.ui.notify(paths, "info"); } async function splitScores( split: "train" | "validation" | "test", body: string, onProgress?: (progress: { completed: number; total: number; }) => Promise, ) { 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, }, 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; sessionApi?: AftermathSessionApi; }): Promise<{ digests: Digest[]; total: number; unreadable: number }> { const api = options.sessionApi ?? (SessionManager as unknown as NonNullable); const sessionDir = options.ctx.sessionManager.getSessionDir(); const listed = await api.listAll(sessionDir); const snapshots = new Map(); const unreadableIds = new Set(); for (const listedSession of listed) { try { const session = api.open(listedSession.path, sessionDir); 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, }; } type LoadedSkillTarget = { name: string; path: string }; function loadedSkills(pi: ExtensionAPI): LoadedSkillTarget[] { 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), ); } export async function chooseLoadedSkill( ctx: ExtensionCommandContext, skills: readonly LoadedSkillTarget[], canonicalPaths: ReadonlyMap, purpose: string, ): Promise { if (commandMode(ctx) !== "tui" || skills.length <= 8) { const labels = skills.map( (skill) => `${skill.name} — ${canonicalPaths.get(skill.path) ?? skill.path}`, ); const choice = await ctx.ui.select( `Choose exactly one ${purpose} skill.`, labels, ); return skills[labels.indexOf(choice ?? "")]; } const path = await ctx.ui.custom( (tui, theme, _keybindings, done) => { const list = new SelectList( skills.map((skill) => { const canonical = canonicalPaths.get(skill.path) ?? skill.path; const parent = dirname(canonical); return { value: skill.path, label: skill.name, description: join( "…", basename(dirname(parent)), basename(parent), basename(canonical), ), }; }), Math.max(1, Math.min(8, tui.terminal.rows - 3)), { selectedPrefix: (text) => theme.fg("accent", text), selectedText: (text) => theme.fg("accent", text), description: (text) => theme.fg("muted", text), scrollInfo: (text) => theme.fg("dim", text), noMatch: (text) => theme.fg("warning", text), }, ); list.onSelect = (item) => done(item.value); list.onCancel = () => done(null); return { render: (width: number) => [ theme.fg("accent", `Choose one ${purpose} skill`), ...list.render(width), theme.fg("dim", "type filter · arrows move · enter · esc"), ], invalidate: () => list.invalidate(), handleInput: (data: string) => { list.handleInput(data); tui.requestRender(); }, }; }, ); return skills.find((skill) => skill.path === path); } async function runAftermath( pi: ExtensionAPI, ctx: ExtensionCommandContext, parts: string[], ): Promise { const active = activeRun; if (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(); const canonicalSkillPaths = new Map(); 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"); if (!selected && ctx.hasUI) selected = await chooseLoadedSkill( ctx, skills, canonicalSkillPaths, "Aftermath", ); if (!selected) throw new Error("one confirmed Aftermath skill is required"); throwIfCancelled(active); const sourcePath = canonicalSkillPaths.get(selected.path) ?? (await realpath(selected.path)); const parallelWarning = await unfinishedRunWarning(sourcePath); const harvested = await harvestAftermath({ ctx, knownSkillPaths: knownPaths, sessionApi: installedAftermathAcceptanceSeam()?.sessionApi, }); throwIfCancelled(active); const evidence = rankSkillEvidence( harvested.digests, new Set(skills.map((skill) => skill.name)), ); 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.", `Expected mining/aggregation calls: ${calls.mining}/${calls.aggregation}; malformed structured output retries once per call.`, `Maximum mining/aggregation calls with retries: ${calls.mining * 2}/${calls.aggregation * 2}.`, "Maximum replay calls after mining: 116 target, 116 rubric-judge, 12 optimizer.", ...(parallelWarning ? [`Warning: ${parallelWarning}`] : []), "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 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", miningPromptVersion: 2, 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 { if (!ctx.hasUI || (commandMode(ctx) !== "tui" && commandMode(ctx) !== "rpc")) return; const artifacts = await readFrozenReviewArtifacts(directory); const manifest = await readAftermathManifest(directory); const staged = artifacts.stagedPath !== null && artifacts.staged !== null; const report = artifacts.reportPath ? `Report: ${sanitizeTerminalText(artifacts.reportPath)}` : ""; let summary: string; if (staged) { const scores = [ manifest.scores.baseline === null ? null : `baseline ${formatScore(manifest.scores.baseline)}`, manifest.scores.best === null ? null : `validation ${formatScore(manifest.scores.best)}`, manifest.scores.test === null ? null : `held-out ${formatScore(manifest.scores.test)}`, ].filter((value): value is string => value !== null); summary = `Aftermath complete — candidate staged.\n${scores.join(" → ")}\n${report}`; } else if (manifest.scores.baseline === null) { const frozen = await readFrozenTasks(directory); summary = `Aftermath complete — no candidate.\nOnly ${frozen.tasks.length}/3 recurring tasks; replay was skipped.\n${report}`; } else if (manifest.scores.baseline === 1) { summary = `Aftermath complete — no candidate needed.\nBaseline already scores 1; no improvement is possible.\n${report}`; } else { summary = `Aftermath complete — no candidate.\nBest validation ${formatScore(manifest.scores.best ?? manifest.scores.baseline)} did not beat baseline ${formatScore(manifest.scores.baseline)}; no diff was staged.\n${report}`; } const choice = await ctx.ui.select( summary, staged ? ["review diff", "done", "discard"] : ["done", "discard report"], ); if (choice === "review diff") { const paths = [ artifacts.reportPath ? `Report: ${sanitizeTerminalText(artifacts.reportPath)}` : null, artifacts.stagedPath ? `Staged: ${sanitizeTerminalText(artifacts.stagedPath)}` : null, ] .filter((value): value is string => value !== null) .join("\n"); ctx.ui.notify( commandMode(ctx) === "tui" && artifacts.stagedPath && artifacts.staged ? `${paths}\n${buildReviewDiff( artifacts.sourcePath, artifacts.stagedPath, artifacts.source, artifacts.staged, )}` : paths, "info", ); return; } if (choice === "done" || choice === undefined) return; if (choice === "discard" || choice === "discard report") { 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; completedLevels?: ReadonlyMap; attemptedMiningCalls?: number; frozen?: Awaited>; }): Promise { const active = activeRun; if (active?.kind !== "aftermath") throw new Error("Aftermath run ownership is unavailable"); const { ctx, manifest } = options; if (manifest.miningPromptVersion !== 2) throw new Error( "Aftermath run predates target-relevant mining; discard it and start a new run", ); 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); if (source.name !== manifest.target.name) throw new Error("frozen source name changed; replay is unsafe"); 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(); let attemptedMiningCalls = options.attemptedMiningCalls ?? 0; for (const [level, outputs] of options.completedLevels ?? []) for (const index of outputs.keys()) levels.add(`${level}:${index}`); const miningTotal = estimateMiningCalls(options.digests.length).total; const updateMiningProgress = ( phase?: "mining" | "aggregation", attempt?: number, maximumAttempts?: number, ) => { const completed = chunks.size + levels.size; const progress = formatProgress({ stage: "mining", completed, total: miningTotal, }); showProgress( ctx, phase ? `${progress} · ${phase} call ${Math.min(completed + 1, miningTotal)} running${attempt && attempt > 1 ? ` · retry ${attempt}/${maximumAttempts}` : ""}` : progress, ); }; 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 () => { updateMiningProgress(); const proposals = await mineTaskProposals({ digests: options.digests, target: { name: source.name, description: source.description }, createSession: () => createMiningSession( { cwd: ctx.cwd, agentDir: getAgentDir(), model: manifest.model, targetModel: options.targetModel, }, installedAftermathAcceptanceSeam()?.structuredOutputSdk, ), signal: active.controller.signal, completedChunks: options.completedChunks, completedLevels: options.completedLevels, onCall: async (phase, attempt, maximumAttempts) => { attemptedMiningCalls += 1; await persistCheckpoint(); updateMiningProgress(phase, attempt, maximumAttempts); }, onChunk: async (index, output) => { await persistMiningOutput( options.directory, `miner-chunk-${index}.json`, output, ); chunks.add(index); await persistCheckpoint(); updateMiningProgress(); }, onLevel: async (level, index, output) => { await persistMiningOutput( options.directory, `aggregate-${level}-${index}.json`, output, ); levels.add(`${level}:${index}`); await persistCheckpoint(); updateMiningProgress(); }, }); 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 = `Replay budget: ≤${costs.targetMaximum} target + ${costs.judgeMaximum} judge calls; malformed judge retries consume this budget.`; 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: 3 }, { reportPath, stagedPath: null }, ); appendProgress(options.pi, ctx, entry); if (commandMode(ctx) === "print") writePrint( `Aftermath complete — no candidate.\nOnly ${tasks.length}/3 recurring tasks; replay was skipped.\nReport: ${sanitizeTerminalText(reportPath)}`, ); 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 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, }, 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, }), deferCompletionNotice: true, }); await offerAftermathCompletion(options.pi, ctx, options.directory); } async function resumeAftermath( pi: ExtensionAPI, ctx: ExtensionCommandContext, selected: NonNullable>, ): Promise { const active = activeRun; if (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(); const levels = new Map(); 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>, ): Promise { 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( "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) { const details = [ `${summary} ${theme.fg("dim", keyHint("app.tools.expand", "to expand"))}`, ]; if (data.terminal === "staged") try { const artifacts = readFrozenReviewArtifactsSync( join(getAgentDir(), "overkill-runs", data.runId), ); if (artifacts.stagedPath && artifacts.staged) details.push( renderDiff( buildReviewDiffPreview( buildReviewDiff( artifacts.sourcePath, artifacts.stagedPath, artifacts.source, artifacts.staged, ), ), ), ); } catch { // The durable run summary remains useful without review artifacts. } return new Text(details.join("\n"), 0, 0); } const details = [summary]; if (data.stage === "preflight") return new Text(summary, 0, 0); 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( renderDiff( 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: "Author or optimize a loaded Pi skill with trusted evaluators.", getArgumentCompletions: (prefix) => { const trimmed = prefix.trim(); if (trimmed === "aftermath" && !prefix.endsWith(" ")) return null; if (trimmed === "aftermath" || 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) => { let parts: string[]; try { parts = parseArguments(args); } catch (error) { ctx.ui.notify( `Overkill command failed: ${error instanceof Error ? error.message : String(error)}`, "error", ); return; } const command = parts[0]; if (command === "suite") { let [sourcePath, suitePath, ...extra] = parts.slice(1); if (extra.length > 0) { ctx.ui.notify( "Usage: /overkill suite [skill-path] [suite-dir]", "error", ); return; } if (!ctx.isIdle()) { ctx.ui.notify("Agent is busy.", "error"); return; } try { if (!ctx.isProjectTrusted()) throw new Error("suite authoring requires a trusted project"); if (!sourcePath) { if (!ctx.hasUI) throw new Error( "headless suite authoring requires an explicit skill path", ); const skills = loadedSkills(pi); if (skills.length === 0) throw new Error("no loaded Pi skills are available"); const canonicalPaths = new Map(); for (const skill of skills) canonicalPaths.set(skill.path, await realpath(skill.path)); const selected = await chooseLoadedSkill( ctx, skills, canonicalPaths, "suite", ); if (!selected) return; sourcePath = selected.path; } const loaded = await resolveLoadedSkill( sourcePath, pi.getCommands(), true, ctx.cwd, ); const projectRoot = await realpath(resolve(ctx.cwd)); if (suitePath) { suitePath = await canonicalProspectivePath( resolve(projectRoot, suitePath), ); const projectRelative = relative(projectRoot, suitePath); if (projectRelative.startsWith("..") || isAbsolute(projectRelative)) throw new Error("suite directory must be inside the project"); } const parallelWarning = await unfinishedRunWarning( undefined, suitePath, ); if (parallelWarning) ctx.ui.notify(parallelWarning, "warning"); pi.sendUserMessage( buildSuiteAuthoringPrompt(loaded.path, suitePath, projectRoot), ); } catch (error) { ctx.ui.notify( `Overkill suite authoring failed: ${error instanceof Error ? error.message : String(error)}`, "error", ); } return; } if (command === "aftermath") { const subcommand = parts[1]; if ( ["status", "resume", "review", "discard", "cancel"].includes( subcommand ?? "", ) && parts.length !== 2 ) { ctx.ui.notify(`Usage: /overkill aftermath ${subcommand}`, "error"); return; } 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", }); clearProgress(ctx); } 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( "This Pi process already has an Overkill rollout active; wait or cancel it before starting another.", "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 ( ["status", "discard", "cancel", "review", "resume"].includes( command ?? "", ) && parts.length !== 1 ) { ctx.ui.notify(`Usage: /overkill ${command}`, "error"); 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(), allowNonterminal: true, isRunActive: (runId) => activeRun?.runId === runId, }); appendProgress(pi, ctx, { ...run.data, stage: "discarded", terminal: "discarded", }); clearProgress(ctx); 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; } let artifacts: Awaited>; try { artifacts = await readFrozenReviewArtifacts( join(getAgentDir(), "overkill-runs", run.data.runId), ); } catch (error) { ctx.ui.notify( `Overkill review failed: ${error instanceof Error ? error.message : String(error)}`, "error", ); return; } 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( "This Pi process already has an Overkill rollout active; wait or cancel it before resuming another.", "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 ", "error"); return; } if (activeRun || startPending) { ctx.ui.notify( "This Pi process already has an Overkill rollout active; wait or cancel it before starting another.", "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); const inspectedSuiteFingerprint = inspected.suite.fingerprint; if (!inspectedSuiteFingerprint) throw new Error("validated suite fingerprint is unavailable"); const confirmedFingerprints = { sourceFingerprint: fingerprintSource(inspected.sourceBytes), suiteFingerprint: inspectedSuiteFingerprint, }; const parallelWarning = await unfinishedRunWarning( inspected.sourcePath, inspected.suite.suitePath, ); 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, warning: parallelWarning, }), ); 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, confirmedFingerprints, ); 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 run failed: ${error instanceof Error ? error.message : String(error)}`, "error", ); } finally { startPending = false; pendingSessionId = undefined; pendingCancelled = false; } }, }); }