repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/iq/check/runner.ts

Raw
File outline
import { join } from "node:path";
import type { Api, Model } from "@earendil-works/pi-ai";
import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
import {
	boundedError,
	type EvidenceObservation,
	emptyJudgeUsage,
	type JudgeUsage,
	type NormalizedEvent,
	prepareSession,
} from "../core.js";
import type { ProgressOutcome, ScanDisplayState } from "../ui.js";
import { runProgress } from "../ui.js";
import {
	CHECK_PROMPT_VERSION,
	judgeCheckStep,
	judgeFinalState,
} from "./judging.js";
import {
	CHECK_RECORD_VERSION,
	type CheckFinalRecord,
	type CheckStepRecord,
	type CheckTaskRunRecord,
	makeCheckRunDir,
	newRunId,
	removeDir,
	saveCheckRun,
} from "./records.js";
import {
	type CandidateUsage,
	emptyCandidateUsage,
	forbiddenViolations,
	gitEndState,
	type PiCli,
	runAcceptance,
	runCheckStep,
} from "./runtime.js";
import {
	CHECK_RECIPE_VERSION,
	type CheckTask,
	materializeWorkspace,
} from "./tasks.js";

type AnyModel = Model<Api>;

/** One side of a check run: the model object plus its user-facing reference. */
export interface CheckParticipant {
	model: AnyModel;
	reference: string;
}

interface CheckCosts {
	judge: number;
	candidate: number;
}

/** Sums judge usage pieces that check scoring records per step. */
function mergeJudgeUsage(target: JudgeUsage, source: JudgeUsage): void {
	for (const key of Object.keys(target) as (keyof JudgeUsage)[]) {
		target[key] = (target[key] as number) + (source[key] as number);
	}
}

/** Per-step usage is the session-total delta; never negative across restarts. */
function deltaUsage(
	seen: CandidateUsage,
	total: CandidateUsage,
): CandidateUsage {
	return {
		inputTokens: Math.max(0, total.inputTokens - seen.inputTokens),
		outputTokens: Math.max(0, total.outputTokens - seen.outputTokens),
		cost: Math.max(0, total.cost - seen.cost),
	};
}

/** Accumulated task state shared by the step loop and the final phase. */
interface TaskRunState {
	sessionFile?: string;
	knownIds: Set<string>;
	seenUsage: CandidateUsage;
	allEvents: NormalizedEvent[];
	ledger: EvidenceObservation[];
	judgeUsage: JudgeUsage;
	steps: CheckStepRecord[];
	/** Only instructions that were actually delivered to the candidate. */
	instructions: string[];
	lastReport: string;
}

interface SessionDelta {
	events: NormalizedEvent[];
	all: NormalizedEvent[] | undefined;
	/** Reading failed after delivery: harness-side, not candidate "no work". */
	readError: string | undefined;
}

async function sessionDelta(
	sessionFile: string | undefined,
	knownIds: Set<string>,
	signal: AbortSignal,
): Promise<SessionDelta> {
	if (!sessionFile) return { events: [], all: undefined, readError: undefined };
	try {
		const prepared = await prepareSession(sessionFile, Date.now(), signal);
		return {
			events: prepared.events.filter((event) => !knownIds.has(event.id)),
			all: prepared.events,
			readError: undefined,
		};
	} catch (error) {
		if (signal.aborted) throw error;
		return { events: [], all: undefined, readError: boundedError(error) };
	}
}

/** Verifies the delivered end state and judges it; appends to the ledger. */
async function judgeFinalPhase(
	ctx: ExtensionCommandContext,
	args: {
		judge: CheckParticipant;
		task: CheckTask;
		workspace: string;
		run: TaskRunState;
		display: ScanDisplayState;
		render: () => void;
	},
	signal: AbortSignal,
): Promise<CheckFinalRecord> {
	const { task, run } = args;
	args.display.currentName = `${task.id} · verifying end state`;
	args.render();
	const acceptance = await runAcceptance(args.workspace, task);
	const git = await gitEndState(args.workspace);
	const violated = forbiddenViolations(
		git.pathsTouched,
		task.acceptance.pathsUntouched ?? [],
	);
	args.display.currentName = `${task.id} · final judgment`;
	args.render();
	const finalJudged = await judgeFinalState(
		ctx,
		args.judge.model,
		{
			taskId: task.id,
			difficulty: task.difficulty,
			instructionsDelivered: run.instructions,
			acceptance,
			pathsTouched: git.pathsTouched,
			forbiddenViolated: violated,
			diffStat: git.diffStat,
			diff: git.diff,
			finalReport: run.lastReport,
			lastEvents: run.allEvents.slice(-80),
			prior: run.ledger,
			finalChunk: task.recipe.length + 1,
		},
		signal,
	);
	mergeJudgeUsage(run.judgeUsage, finalJudged.usage);
	run.ledger.push(...finalJudged.observations);
	return {
		acceptance,
		pathsTouched: git.pathsTouched,
		forbiddenViolations: violated,
		diffStat: git.diffStat,
		observations: finalJudged.observations,
		judgeUsage: finalJudged.usage,
	};
}

/**
 * One task: a frozen workspace, the recipe delivered item by item as scripted
 * user turns, checkpoint judging, and a final end-state judgment.
 *
 * A run that produced any step evidence always persists (incomplete, with
 * reason), so a crashed final evaluation never destroys judged evidence.
 */
export async function runOneCheckTask(
	ctx: ExtensionCommandContext,
	args: {
		candidate: CheckParticipant;
		judge: CheckParticipant;
		task: CheckTask;
		pi: PiCli;
		stateDirectory: string;
	},
	signal: AbortSignal,
	display: ScanDisplayState,
	render: () => void,
	costs: CheckCosts,
): Promise<CheckTaskRunRecord> {
	const startedAt = new Date().toISOString();
	const runDir = await makeCheckRunDir(args.task.id);
	const workspace = await materializeWorkspace(args.task, runDir);
	const sessionDir = join(runDir, "sessions");
	const run: TaskRunState = {
		knownIds: new Set(),
		seenUsage: emptyCandidateUsage(),
		allEvents: [],
		ledger: [],
		judgeUsage: emptyJudgeUsage(),
		steps: [],
		instructions: [],
		lastReport: "",
	};
	/** First stop wins; later stops are symptoms, not causes. */
	let stopReason: string | undefined;
	const stop = (reason: string) => {
		stopReason ??= reason;
	};
	const bumpCost = () => {
		display.cost = costs.judge + costs.candidate;
	};

	for (const [index, step] of args.task.recipe.entries()) {
		if (signal.aborted) {
			stop("cancelled");
			break;
		}
		const number = index + 1;
		display.chunk = number;
		display.chunks = args.task.recipe.length;
		display.currentName = `${args.task.id} · step ${number}`;
		display.evidence = run.ledger.length;
		render();
		const stepStartedAt = new Date().toISOString();
		const outcome = await runCheckStep({
			pi: args.pi,
			workspaceDir: workspace,
			sessionDir,
			sessionFile: run.sessionFile,
			modelReference: args.candidate.reference,
			message: step.message,
			signal,
		});
		if (outcome.sessionFile) run.sessionFile = outcome.sessionFile;
		if (outcome.exitState === "cancelled") {
			stop("cancelled");
			break;
		}
		// The item was delivered, so it counts as instructed from here on.
		run.instructions.push(step.message);
		const candidateUsage = deltaUsage(run.seenUsage, outcome.usage);
		run.seenUsage = { ...outcome.usage };
		costs.candidate += candidateUsage.cost;
		bumpCost();
		const delta = await sessionDelta(outcome.sessionFile, run.knownIds, signal);
		for (const id of outcome.ids) run.knownIds.add(id);
		if (delta.all) run.allEvents = delta.all;
		const endedAt = new Date().toISOString();
		if (delta.readError) {
			run.steps.push({
				index: number,
				instruction: step.message,
				exitState: outcome.exitState,
				detail: `session unreadable: ${delta.readError}`,
				startedAt: stepStartedAt,
				endedAt,
				candidateUsage,
				observations: [],
				judgeUsage: emptyJudgeUsage(),
			});
			stop(
				`step ${number} session could not be read (${outcome.exitState}: ${delta.readError})`,
			);
			break;
		}
		if (delta.events.length === 0) {
			run.steps.push({
				index: number,
				instruction: step.message,
				exitState: outcome.exitState,
				detail: outcome.detail ?? "no new session entries",
				startedAt: stepStartedAt,
				endedAt,
				candidateUsage,
				observations: [],
				judgeUsage: emptyJudgeUsage(),
			});
			stop(
				`step ${number} produced no work (${outcome.exitState}${outcome.detail ? `: ${outcome.detail}` : ""})`,
			);
			break;
		}
		const lastAssistant = [...delta.events]
			.reverse()
			.find(
				(event) =>
					event.kind === "assistant" &&
					typeof event.text === "string" &&
					event.text.trim().length > 0,
			);
		if (lastAssistant)
			run.lastReport = String(lastAssistant.text).slice(0, 1_500);
		display.currentName = `${args.task.id} · judging step ${number}`;
		render();
		try {
			const judged = await judgeCheckStep(
				ctx,
				args.judge.model,
				{
					taskId: args.task.id,
					difficulty: args.task.difficulty,
					instructionsDelivered: run.instructions,
					newEvents: delta.events,
					prior: run.ledger,
					stepNumber: number,
				},
				signal,
				(evidence, usage) => {
					display.evidence = evidence;
					display.cost = costs.judge + costs.candidate + usage.cost;
					render();
				},
			);
			mergeJudgeUsage(run.judgeUsage, judged.usage);
			costs.judge += judged.usage.cost;
			bumpCost();
			run.ledger.push(...judged.observations);
			run.steps.push({
				index: number,
				instruction: step.message,
				exitState: outcome.exitState,
				detail: outcome.detail,
				startedAt: stepStartedAt,
				endedAt: new Date().toISOString(),
				candidateUsage,
				observations: judged.observations,
				judgeUsage: judged.usage,
			});
		} catch (error) {
			if (signal.aborted) throw error;
			stop(`judging step ${number} failed: ${boundedError(error)}`);
			break;
		}
	}

	let final: CheckFinalRecord | undefined;
	if (!stopReason && !signal.aborted && run.steps.length > 0) {
		try {
			final = await judgeFinalPhase(
				ctx,
				{ ...args, workspace, run, display, render },
				signal,
			);
			costs.judge += final.judgeUsage.cost;
			bumpCost();
		} catch (error) {
			if (signal.aborted) throw error;
			stop(`final evaluation failed: ${boundedError(error)}`);
		}
	}
	if (!final) stopReason ??= signal.aborted ? "cancelled" : "no steps executed";

	const record: CheckTaskRunRecord = {
		version: CHECK_RECORD_VERSION,
		recipeVersion: CHECK_RECIPE_VERSION,
		promptVersion: CHECK_PROMPT_VERSION,
		runId: newRunId(),
		taskId: args.task.id,
		difficulty: args.task.difficulty,
		fixtureHash: args.task.fixtureHash,
		candidate: args.candidate.reference,
		judge: args.judge.reference,
		piVersion: args.pi.version,
		steps: run.steps,
		final,
		ledger: run.ledger,
		judgeUsage: run.judgeUsage,
		state: final ? "complete" : "incomplete",
		incompleteReason: final ? undefined : stopReason,
		startedAt,
		completedAt: new Date().toISOString(),
	};
	await saveCheckRun(record, args.stateDirectory);
	if (record.state === "complete") await removeDir(runDir);
	return record;
}

export async function runCheckSuite(
	ctx: ExtensionCommandContext,
	args: {
		candidate: CheckParticipant;
		judge: CheckParticipant;
		tasks: readonly CheckTask[];
		pi: PiCli;
		stateDirectory: string;
	},
): Promise<ProgressOutcome<{ kept: CheckTaskRunRecord[] }>> {
	const state: ScanDisplayState = {
		phase: "check",
		model: args.candidate.reference,
		candidateModel: args.candidate.reference,
		judgeModel: args.judge.reference,
		currentName: "",
		session: 0,
		sessions: args.tasks.length,
		chunk: 0,
		chunks: 0,
		evidence: 0,
		cost: 0,
		failures: 0,
		startedAt: Date.now(),
	};
	const costs: CheckCosts = { judge: 0, candidate: 0 };
	return runProgress(ctx, state, async (signal, display, render) => {
		const kept: CheckTaskRunRecord[] = [];
		for (const [index, task] of args.tasks.entries()) {
			if (signal.aborted) break;
			display.session = index + 1;
			display.currentName = `${task.id} (${task.difficulty})`;
			display.chunk = 0;
			display.chunks = task.recipe.length;
			render();
			try {
				const record = await runOneCheckTask(
					ctx,
					{ ...args, task },
					signal,
					display,
					render,
					costs,
				);
				if (record.steps.length > 0) kept.push(record);
				if (record.state === "incomplete") {
					display.failures++;
					display.lastFailure =
						`${task.id}: ${record.incompleteReason ?? "incomplete"}`.slice(
							0,
							120,
						);
					render();
				}
			} catch (error) {
				if (signal.aborted) throw error;
				display.failures++;
				display.lastFailure = `${task.id}: ${boundedError(error)}`.slice(
					0,
					120,
				);
				render();
			}
		}
		return { kept };
	});
}