repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/overkill/lib/run-state.ts

Raw
File outline
import { randomUUID } from "node:crypto";
import { readFileSync, realpathSync } from "node:fs";
import {
	mkdir,
	readFile,
	realpath,
	rename,
	rm,
	writeFile,
} from "node:fs/promises";
import {
	basename,
	dirname,
	isAbsolute,
	join,
	relative,
	resolve,
} from "node:path";
import { parsePatch } from "./patches.ts";

const MANIFEST_FIELDS = new Set([
	"version",
	"runId",
	"kind",
	"source",
	"suite",
	"model",
	"sessionId",
	"linkEntryId",
	"stage",
	"terminal",
	"harvestFingerprint",
	"miningPromptVersion",
	"taskFingerprint",
	"scores",
	"calls",
	"artifacts",
	"target",
	"scorers",
	"splits",
]);
const CHECKPOINT_FIELDS = new Set(["version", "stage", "completed", "total"]);
const BASELINE_SCORE_FIELDS = new Set([
	"id",
	"score",
	"passed",
	"feedback",
	"evidenceFile",
]);
const BASELINE_CHECKPOINT_FIELDS = new Set([
	"version",
	"stage",
	"bodyHash",
	"completedItemIds",
	"total",
	"scores",
]);
const SCORE_CACHE_FIELDS = new Set(["version", "bodyHash", "scores"]);
const TRAINING_CHECKPOINT_FIELDS = new Set([
	"version",
	"stage",
	"nextStep",
	"currentBodyHash",
	"bestBodyHash",
	"currentSnapshot",
	"bestSnapshot",
	"baselineScore",
	"currentScore",
	"bestScore",
	"accepted",
	"optimizerCalls",
	"consecutiveRejections",
	"rejections",
	"attemptedPatchFiles",
	"pendingPatch",
	"pendingOptimizer",
	"finalTest",
	"reportFile",
	"stagedFile",
	"terminal",
]);
const RUN_ENTRY_FIELDS = new Set([
	"version",
	"runId",
	"kind",
	"stage",
	"terminal",
	"completed",
	"total",
	"currentScore",
	"bestScore",
	"sourcePath",
	"reportPath",
	"stagedPath",
]);
export type RunManifest = {
	version: 1;
	runId: string;
	kind: "suite" | "aftermath";
	source: { path: string; fingerprint: string };
	suite?: { path: string; fingerprint: string };
	model: { provider: string; id: string; thinking: string };
	sessionId: string;
	linkEntryId: string | null;
	stage: string;
	terminal: null | "staged" | "no_improvement" | "failed" | "discarded";
	harvestFingerprint?: string;
	taskFingerprint?: string;
	scores: {
		baseline: number | null;
		current: number | null;
		best: number | null;
		test: number | null;
	};
	calls: { target: number; checker: number; optimizer: number; judge: number };
	artifacts: {
		baselineSnapshot: "baseline-snapshot.md";
		report: "report.json" | null;
		staged: "staged-skill.md" | null;
	};
	target?: { name: string; path: string };
	scorers?: Array<{ id: string; kind: "deterministic" | "rubric" }>;
	splits?: { train: string[]; validation: string[]; test: string[] };
};

export type BaselineScore = {
	id: string;
	score: number;
	passed: boolean;
	feedback?: string;
	evidenceFile: string;
};

export type BaselineCheckpoint = {
	version: 1;
	stage: "baseline" | "baseline_complete" | "interrupted";
	bodyHash: string;
	completedItemIds: string[];
	total: number;
	scores: BaselineScore[];
};

type ScoreCache = {
	version: 1;
	bodyHash: string;
	scores: BaselineScore[];
};

export type TrainingRejection = {
	reason: string;
	delta: number;
	reports?: Array<{
		index: number;
		status: "applied" | "rejected";
		reason?: string;
	}>;
	edits?: Array<{
		op: "append" | "insert_after" | "replace" | "delete";
		target?: string;
		content?: string;
	}>;
};

export type TrainingCheckpoint = {
	version: 1;
	stage: "training" | "final_test" | "complete" | "interrupted";
	nextStep: number;
	terminal?: "perfect" | "all_pass" | "two_rejections" | "three_steps";
	currentBodyHash: string;
	bestBodyHash: string;
	currentSnapshot: string;
	bestSnapshot: string;
	baselineScore: number;
	currentScore: number;
	bestScore: number;
	accepted: number;
	optimizerCalls: number;
	consecutiveRejections: number;
	rejections: TrainingRejection[];
	attemptedPatchFiles: string[];
	pendingPatch?: { step: number; bodyHash: string; file: string };
	pendingOptimizer?: {
		step: number;
		failure?: string;
		success?: string;
		merged?: string;
	};
	finalTest?: {
		bodyHash: string;
		completedItemIds: string[];
		total: number;
		score?: number;
	};
	reportFile?: "report.json";
	stagedFile?: "staged-skill.md";
};

export type RunEntry = {
	version: 1;
	runId: string;
	kind: "suite" | "aftermath";
	stage: string;
	terminal: null | "staged" | "no_improvement" | "failed" | "discarded";
	completed?: number;
	total?: number;
	currentScore?: number;
	bestScore?: number;
	sourcePath?: string | null;
	reportPath?: string | null;
	stagedPath?: string | null;
};

function assertPrivateFilename(filename: string): void {
	if (basename(filename) !== filename || filename.length === 0)
		throw new Error("artifact must have a private filename");
}

function assertEvidenceFilename(filename: string): void {
	if (!/^evidence-[a-f0-9]{16}(?:-[a-f0-9]{16})?\.json$/.test(filename))
		throw new Error("artifact must have a bounded private evidence filename");
}

function assertScoreCacheFilename(filename: string): void {
	if (
		filename !== "scores.json" &&
		!/^scores-[a-f0-9]{64}-(?:train|validation|test)\.json$/.test(filename)
	)
		throw new Error(
			"artifact must have a bounded private score-cache filename",
		);
}

async function replaceFile(
	temporary: string,
	destination: string,
): Promise<void> {
	for (let attempt = 0; ; attempt++) {
		try {
			await rename(temporary, destination);
			return;
		} catch (error) {
			if (
				process.platform !== "win32" ||
				(error as NodeJS.ErrnoException).code !== "EPERM" ||
				attempt === 4
			)
				throw error;
			await new Promise((resolve) => setTimeout(resolve, 10 * 2 ** attempt));
		}
	}
}

async function atomicWriteJson(
	directory: string,
	filename: string,
	value: unknown,
): Promise<void> {
	assertPrivateFilename(filename);
	const root = await realpath(directory);
	const destination = resolve(root, filename);
	if (dirname(destination) !== root)
		throw new Error("artifact must remain in private run directory");
	const temporary = join(root, `.${filename}.${randomUUID()}.tmp`);
	await writeFile(temporary, `${JSON.stringify(value)}\n`, {
		encoding: "utf8",
		mode: 0o600,
	});
	await replaceFile(temporary, destination);
}

function assertFingerprint(
	value: unknown,
	label: string,
): asserts value is string {
	if (typeof value !== "string" || !/^[a-f0-9]{64}$/.test(value))
		throw new Error(`${label} must be a lowercase SHA-256 fingerprint`);
}

function isTerminal(value: unknown): value is RunManifest["terminal"] {
	return (
		value === null ||
		value === "staged" ||
		value === "no_improvement" ||
		value === "failed" ||
		value === "discarded"
	);
}

function assertBoundedString(
	value: unknown,
	label: string,
	maximumBytes = 1024,
): asserts value is string {
	if (
		typeof value !== "string" ||
		value.length === 0 ||
		Buffer.byteLength(value, "utf8") > maximumBytes
	)
		throw new Error(`${label} must be a bounded nonempty string`);
}

function assertExactObject(
	value: unknown,
	keys: readonly string[],
	label: string,
): asserts value is Record<string, unknown> {
	if (typeof value !== "object" || value === null || Array.isArray(value))
		throw new Error(`${label} must be an object`);
	for (const key of Object.keys(value))
		if (!keys.includes(key))
			throw new Error(`${label} has unknown field: ${key}`);
}

function assertManifest(value: unknown): asserts value is RunManifest {
	if (typeof value !== "object" || value === null || Array.isArray(value))
		throw new Error("manifest must be an object");
	for (const key of Object.keys(value))
		if (!MANIFEST_FIELDS.has(key))
			throw new Error(`manifest has unknown field: ${key}`);
	const manifest = value as Partial<RunManifest>;
	if (
		manifest.version !== 1 ||
		(manifest.kind !== "suite" && manifest.kind !== "aftermath") ||
		!/^[-a-f0-9]{36}$/i.test(manifest.runId ?? "")
	) {
		throw new Error("invalid run manifest identity");
	}
	assertExactObject(
		manifest.source,
		["path", "fingerprint"],
		"manifest source",
	);
	if (manifest.kind === "suite" || manifest.suite !== undefined) {
		assertExactObject(
			manifest.suite,
			["path", "fingerprint"],
			"manifest suite",
		);
		assertBoundedString(manifest.suite?.path, "suite path", 16 * 1024);
		assertFingerprint(manifest.suite?.fingerprint, "suite fingerprint");
	}
	assertExactObject(
		manifest.model,
		["provider", "id", "thinking"],
		"manifest model",
	);
	assertBoundedString(manifest.source.path, "source path", 16 * 1024);
	assertBoundedString(manifest.model.provider, "model provider");
	assertBoundedString(manifest.model.id, "model ID");
	assertBoundedString(manifest.model.thinking, "model thinking");
	assertBoundedString(manifest.sessionId, "session ID");
	if (manifest.linkEntryId !== null)
		assertBoundedString(manifest.linkEntryId, "link entry ID");
	assertBoundedString(manifest.stage, "manifest stage");
	if (!isTerminal(manifest.terminal)) throw new Error("invalid run manifest");
	if (manifest.harvestFingerprint !== undefined)
		assertFingerprint(manifest.harvestFingerprint, "harvest fingerprint");
	if (manifest.taskFingerprint !== undefined)
		assertFingerprint(manifest.taskFingerprint, "task fingerprint");
	assertFingerprint(manifest.source.fingerprint, "source fingerprint");
	assertExactObject(
		manifest.scores,
		["baseline", "current", "best", "test"],
		"manifest scores",
	);
	for (const [label, score] of Object.entries(manifest.scores))
		if (score !== null) assertScore(score, `manifest ${label} score`);
	assertExactObject(
		manifest.calls,
		["target", "checker", "optimizer", "judge"],
		"manifest calls",
	);
	for (const [label, count] of Object.entries(manifest.calls))
		if (!Number.isInteger(count) || count < 0)
			throw new Error(`manifest ${label} calls must be nonnegative integers`);
	assertExactObject(
		manifest.artifacts,
		["baselineSnapshot", "report", "staged"],
		"manifest artifacts",
	);
	if (
		manifest.artifacts.baselineSnapshot !== "baseline-snapshot.md" ||
		(manifest.artifacts.report !== null &&
			manifest.artifacts.report !== "report.json") ||
		(manifest.artifacts.staged !== null &&
			manifest.artifacts.staged !== "staged-skill.md")
	)
		throw new Error("invalid manifest artifacts");
	if (manifest.target !== undefined) {
		assertExactObject(manifest.target, ["name", "path"], "manifest target");
		assertBoundedString(manifest.target.name, "manifest target name");
		assertBoundedString(
			manifest.target.path,
			"manifest target path",
			16 * 1024,
		);
	}
	if (manifest.scorers !== undefined) {
		if (!Array.isArray(manifest.scorers))
			throw new Error("invalid manifest scorers");
		for (const scorer of manifest.scorers) {
			assertExactObject(scorer, ["id", "kind"], "manifest scorer");
			assertBoundedString(scorer.id, "manifest scorer ID");
			if (scorer.kind !== "deterministic" && scorer.kind !== "rubric")
				throw new Error("invalid manifest scorer");
		}
	}
	if (manifest.splits !== undefined) {
		assertExactObject(
			manifest.splits,
			["train", "validation", "test"],
			"manifest splits",
		);
		for (const ids of Object.values(manifest.splits))
			if (!Array.isArray(ids) || ids.some((id) => typeof id !== "string"))
				throw new Error("invalid manifest splits");
	}
}

export async function createRunDirectory(
	agentDir: string,
	runId = randomUUID(),
): Promise<string> {
	if (
		!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
			runId,
		)
	)
		throw new Error("run ID must be a UUID");
	const root = join(resolve(agentDir), "overkill-runs");
	await mkdir(root, { recursive: true, mode: 0o700 });
	const directory = join(root, runId);
	await mkdir(directory, { mode: 0o700 });
	return directory;
}

export async function persistManifest(
	directory: string,
	manifest: RunManifest,
): Promise<void> {
	assertManifest(manifest);
	await atomicWriteJson(directory, "manifest.json", manifest);
}

export async function readManifest(directory: string): Promise<RunManifest> {
	const value: unknown = JSON.parse(
		await readFile(join(directory, "manifest.json"), "utf8"),
	);
	assertManifest(value);
	return value;
}

export async function persistCheckpoint(
	directory: string,
	checkpoint: { version: 1; stage: string; completed?: number; total?: number },
): Promise<void> {
	for (const key of Object.keys(checkpoint))
		if (!CHECKPOINT_FIELDS.has(key))
			throw new Error(`private checkpoint has unknown field: ${key}`);
	if (
		checkpoint.version !== 1 ||
		typeof checkpoint.stage !== "string" ||
		checkpoint.stage.length === 0 ||
		(checkpoint.completed !== undefined &&
			(!Number.isInteger(checkpoint.completed) || checkpoint.completed < 0)) ||
		(checkpoint.total !== undefined &&
			(!Number.isInteger(checkpoint.total) || checkpoint.total < 0))
	) {
		throw new Error("invalid private checkpoint");
	}
	await atomicWriteJson(directory, "checkpoint.json", checkpoint);
}

function assertBaselineScore(value: unknown): asserts value is BaselineScore {
	if (typeof value !== "object" || value === null || Array.isArray(value))
		throw new Error("invalid baseline score");
	for (const key of Object.keys(value))
		if (!BASELINE_SCORE_FIELDS.has(key))
			throw new Error(`baseline score has unknown field: ${key}`);
	const score = value as Partial<BaselineScore>;
	if (
		typeof score.id !== "string" ||
		score.id.length === 0 ||
		typeof score.score !== "number" ||
		!Number.isFinite(score.score) ||
		score.score < 0 ||
		score.score > 1 ||
		typeof score.passed !== "boolean" ||
		typeof score.evidenceFile !== "string"
	) {
		throw new Error("invalid baseline score");
	}
	assertEvidenceFilename(score.evidenceFile);
	if (
		score.feedback !== undefined &&
		(typeof score.feedback !== "string" ||
			Buffer.byteLength(score.feedback, "utf8") > 8 * 1024)
	) {
		throw new Error("invalid baseline feedback");
	}
}

function assertBaselineCheckpoint(
	value: unknown,
): asserts value is BaselineCheckpoint {
	if (typeof value !== "object" || value === null || Array.isArray(value))
		throw new Error("invalid baseline checkpoint");
	for (const key of Object.keys(value))
		if (!BASELINE_CHECKPOINT_FIELDS.has(key))
			throw new Error(`baseline checkpoint has unknown field: ${key}`);
	const checkpoint = value as Partial<BaselineCheckpoint>;
	if (
		checkpoint.version !== 1 ||
		(checkpoint.stage !== "baseline" &&
			checkpoint.stage !== "baseline_complete" &&
			checkpoint.stage !== "interrupted") ||
		typeof checkpoint.bodyHash !== "string" ||
		!/^[a-f0-9]{64}$/.test(checkpoint.bodyHash) ||
		!Array.isArray(checkpoint.completedItemIds) ||
		typeof checkpoint.total !== "number" ||
		!Number.isInteger(checkpoint.total) ||
		checkpoint.total < 0 ||
		!Array.isArray(checkpoint.scores)
	) {
		throw new Error("invalid baseline checkpoint");
	}
	const ids = new Set<string>();
	for (const id of checkpoint.completedItemIds) {
		if (typeof id !== "string" || id.length === 0 || ids.has(id))
			throw new Error("invalid completed baseline item");
		ids.add(id);
	}
	if (checkpoint.completedItemIds.length > checkpoint.total)
		throw new Error("invalid completed baseline item count");
	const scoredIds = new Set<string>();
	for (const score of checkpoint.scores) {
		assertBaselineScore(score);
		if (!ids.has(score.id) || scoredIds.has(score.id))
			throw new Error("baseline score is not completed");
		scoredIds.add(score.id);
	}
	if (checkpoint.scores.length !== checkpoint.completedItemIds.length)
		throw new Error("baseline scores must match completed items");
}

function assertTrainingFilename(value: unknown, label: string): void {
	if (typeof value !== "string" || !/^attempt-[1-3]\.json$/.test(value))
		throw new Error(`${label} must be a bounded attempt artifact filename`);
}

function assertSnapshotFilename(value: unknown, label: string): void {
	if (
		typeof value !== "string" ||
		(value !== "baseline-snapshot.md" &&
			!/^candidate-[a-f0-9]{64}\.md$/.test(value))
	)
		throw new Error(`${label} must be a candidate snapshot filename`);
}

function assertScore(value: unknown, label: string): void {
	if (
		typeof value !== "number" ||
		!Number.isFinite(value) ||
		value < 0 ||
		value > 1
	)
		throw new Error(`${label} must be a score in [0, 1]`);
}

function assertTrainingCheckpoint(
	value: unknown,
): asserts value is TrainingCheckpoint {
	if (typeof value !== "object" || value === null || Array.isArray(value))
		throw new Error("invalid training checkpoint");
	for (const key of Object.keys(value))
		if (!TRAINING_CHECKPOINT_FIELDS.has(key))
			throw new Error(`training checkpoint has unknown field: ${key}`);
	const checkpoint = value as Partial<TrainingCheckpoint>;
	if (
		checkpoint.version !== 1 ||
		(checkpoint.stage !== "training" &&
			checkpoint.stage !== "final_test" &&
			checkpoint.stage !== "complete" &&
			checkpoint.stage !== "interrupted") ||
		typeof checkpoint.nextStep !== "number" ||
		!Number.isInteger(checkpoint.nextStep) ||
		checkpoint.nextStep < 0 ||
		checkpoint.nextStep > 4 ||
		typeof checkpoint.accepted !== "number" ||
		!Number.isInteger(checkpoint.accepted) ||
		checkpoint.accepted < 0 ||
		checkpoint.accepted > 3 ||
		typeof checkpoint.optimizerCalls !== "number" ||
		!Number.isInteger(checkpoint.optimizerCalls) ||
		checkpoint.optimizerCalls < 0 ||
		checkpoint.optimizerCalls > 12 ||
		typeof checkpoint.consecutiveRejections !== "number" ||
		!Number.isInteger(checkpoint.consecutiveRejections) ||
		checkpoint.consecutiveRejections < 0 ||
		checkpoint.consecutiveRejections > 2 ||
		!Array.isArray(checkpoint.rejections) ||
		checkpoint.rejections.length > 8 ||
		!Array.isArray(checkpoint.attemptedPatchFiles) ||
		checkpoint.attemptedPatchFiles.length > 3
	) {
		throw new Error("invalid training checkpoint");
	}
	if (
		checkpoint.terminal !== undefined &&
		checkpoint.terminal !== "perfect" &&
		checkpoint.terminal !== "all_pass" &&
		checkpoint.terminal !== "two_rejections" &&
		checkpoint.terminal !== "three_steps"
	)
		throw new Error("invalid training terminal state");
	for (const [label, hash] of [
		["current body hash", checkpoint.currentBodyHash],
		["best body hash", checkpoint.bestBodyHash],
	] as const)
		assertFingerprint(hash, label);
	assertSnapshotFilename(checkpoint.currentSnapshot, "current snapshot");
	assertSnapshotFilename(checkpoint.bestSnapshot, "best snapshot");
	for (const [label, score] of [
		["baseline score", checkpoint.baselineScore],
		["current score", checkpoint.currentScore],
		["best score", checkpoint.bestScore],
	] as const)
		assertScore(score, label);
	for (const rejection of checkpoint.rejections) {
		if (
			typeof rejection !== "object" ||
			rejection === null ||
			Array.isArray(rejection) ||
			Object.keys(rejection).some(
				(key) =>
					key !== "reason" &&
					key !== "delta" &&
					key !== "reports" &&
					key !== "edits",
			) ||
			typeof (rejection as TrainingRejection).reason !== "string" ||
			Buffer.byteLength((rejection as TrainingRejection).reason, "utf8") > 1024
		)
			throw new Error("invalid training rejection context");
		if (!Number.isFinite((rejection as TrainingRejection).delta))
			throw new Error("invalid training rejection delta");
		const reports = (rejection as TrainingRejection).reports;
		if (reports !== undefined) {
			if (!Array.isArray(reports) || reports.length > 4)
				throw new Error("invalid training rejection reports");
			for (const report of reports)
				if (
					typeof report !== "object" ||
					report === null ||
					Array.isArray(report) ||
					Object.keys(report).some(
						(key) => key !== "index" && key !== "status" && key !== "reason",
					) ||
					!Number.isInteger(report.index) ||
					report.index < 0 ||
					(report.status !== "applied" && report.status !== "rejected") ||
					(report.reason !== undefined &&
						(typeof report.reason !== "string" ||
							Buffer.byteLength(report.reason, "utf8") > 512))
				)
					throw new Error("invalid training rejection report");
		}
		const edits = (rejection as TrainingRejection).edits;
		if (edits !== undefined) {
			if (!Array.isArray(edits))
				throw new Error("invalid training rejection edits");
			try {
				parsePatch({ edits });
			} catch {
				throw new Error("invalid training rejection edits");
			}
		}
	}
	const names = new Set<string>();
	for (const filename of checkpoint.attemptedPatchFiles) {
		assertTrainingFilename(filename, "attempted patch");
		if (names.has(filename))
			throw new Error("duplicate attempted patch artifact");
		names.add(filename);
	}
	if (checkpoint.pendingPatch !== undefined) {
		const pending = checkpoint.pendingPatch;
		if (
			typeof pending !== "object" ||
			pending === null ||
			Object.keys(pending).some(
				(key) => key !== "step" && key !== "bodyHash" && key !== "file",
			) ||
			!Number.isInteger(pending.step) ||
			pending.step < 1 ||
			pending.step > 3
		)
			throw new Error("invalid pending optimizer patch");
		assertFingerprint(pending.bodyHash, "pending patch body hash");
		assertTrainingFilename(pending.file, "pending patch");
	}
	if (checkpoint.pendingOptimizer !== undefined) {
		const pending = checkpoint.pendingOptimizer;
		if (
			typeof pending !== "object" ||
			pending === null ||
			Array.isArray(pending) ||
			Object.keys(pending).some(
				(key) =>
					key !== "step" &&
					key !== "failure" &&
					key !== "success" &&
					key !== "merged",
			) ||
			!Number.isInteger(pending.step) ||
			pending.step < 1 ||
			pending.step > 3
		)
			throw new Error("invalid pending optimizer state");
		for (const key of ["failure", "success", "merged"] as const)
			if (
				pending[key] !== undefined &&
				(typeof pending[key] !== "string" ||
					Buffer.byteLength(pending[key], "utf8") > 16 * 1024)
			)
				throw new Error("invalid pending optimizer proposal");
	}
	if (checkpoint.finalTest !== undefined) {
		const test = checkpoint.finalTest;
		if (
			typeof test !== "object" ||
			test === null ||
			Object.keys(test).some(
				(key) =>
					key !== "bodyHash" &&
					key !== "completedItemIds" &&
					key !== "total" &&
					key !== "score",
			) ||
			!Array.isArray(test.completedItemIds) ||
			!Number.isInteger(test.total) ||
			test.total < 0 ||
			test.completedItemIds.length > test.total
		)
			throw new Error("invalid final test state");
		assertFingerprint(test.bodyHash, "final test body hash");
		const ids = new Set<string>();
		for (const id of test.completedItemIds)
			if (typeof id !== "string" || id.length === 0 || ids.has(id))
				throw new Error("invalid completed final test item");
			else ids.add(id);
		if (test.score !== undefined) assertScore(test.score, "final test score");
	}
	if (
		checkpoint.reportFile !== undefined &&
		checkpoint.reportFile !== "report.json"
	)
		throw new Error("invalid report artifact filename");
	if (
		checkpoint.stagedFile !== undefined &&
		checkpoint.stagedFile !== "staged-skill.md"
	)
		throw new Error("invalid staged artifact filename");
}

function assertScoreCache(value: unknown): asserts value is ScoreCache {
	if (typeof value !== "object" || value === null || Array.isArray(value))
		throw new Error("invalid score cache");
	for (const key of Object.keys(value))
		if (!SCORE_CACHE_FIELDS.has(key))
			throw new Error(`score cache has unknown field: ${key}`);
	const cache = value as Partial<ScoreCache>;
	if (
		cache.version !== 1 ||
		typeof cache.bodyHash !== "string" ||
		!/^[a-f0-9]{64}$/.test(cache.bodyHash) ||
		!Array.isArray(cache.scores)
	) {
		throw new Error("invalid score cache");
	}
	const ids = new Set<string>();
	for (const score of cache.scores) {
		assertBaselineScore(score);
		if (ids.has(score.id)) throw new Error("duplicate cached baseline item");
		ids.add(score.id);
	}
}

export async function persistTrainingCheckpoint(
	directory: string,
	checkpoint: TrainingCheckpoint,
): Promise<void> {
	assertTrainingCheckpoint(checkpoint);
	await atomicWriteJson(directory, "training-checkpoint.json", checkpoint);
}

export async function readTrainingCheckpoint(
	directory: string,
): Promise<TrainingCheckpoint | undefined> {
	try {
		const value: unknown = JSON.parse(
			await readFile(join(directory, "training-checkpoint.json"), "utf8"),
		);
		assertTrainingCheckpoint(value);
		return value;
	} catch (error) {
		if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
		throw error;
	}
}

export async function persistBaselineCheckpoint(
	directory: string,
	checkpoint: BaselineCheckpoint,
): Promise<void> {
	assertBaselineCheckpoint(checkpoint);
	await atomicWriteJson(directory, "baseline-checkpoint.json", checkpoint);
}

export async function readBaselineCheckpoint(
	directory: string,
): Promise<BaselineCheckpoint | undefined> {
	try {
		const value: unknown = JSON.parse(
			await readFile(join(directory, "baseline-checkpoint.json"), "utf8"),
		);
		assertBaselineCheckpoint(value);
		return value;
	} catch (error) {
		if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
		throw error;
	}
}

export async function persistScoreCache(
	directory: string,
	cache: ScoreCache,
	filename = "scores.json",
): Promise<void> {
	assertScoreCacheFilename(filename);
	assertScoreCache(cache);
	await atomicWriteJson(directory, filename, cache);
}

export async function writePrivateText(
	directory: string,
	filename: string,
	content: string | Buffer,
): Promise<string> {
	assertPrivateFilename(filename);
	const root = await realpath(directory);
	const destination = resolve(root, filename);
	if (dirname(destination) !== root)
		throw new Error("artifact must remain in private run directory");
	const temporary = join(root, `.${filename}.${randomUUID()}.tmp`);
	await writeFile(temporary, content, { encoding: "utf8", mode: 0o600 });
	await replaceFile(temporary, destination);
	return destination;
}

export async function persistFinalReport(
	directory: string,
	report: Record<string, unknown>,
): Promise<string> {
	await atomicWriteJson(directory, "report.json", report);
	return join(await realpath(directory), "report.json");
}

export async function readScoreCache(
	directory: string,
	filename = "scores.json",
): Promise<ScoreCache | undefined> {
	assertScoreCacheFilename(filename);
	try {
		const value: unknown = JSON.parse(
			await readFile(join(directory, filename), "utf8"),
		);
		assertScoreCache(value);
		return value;
	} catch (error) {
		if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
		throw error;
	}
}

function isPathOrNull(value: unknown): boolean {
	return (
		value === null ||
		(typeof value === "string" &&
			(isAbsolute(value) ||
				/^[a-zA-Z]:[\\/]/.test(value) ||
				/^\\\\[^\\]+\\[^\\]+/.test(value)))
	);
}

export function validateRunEntry(value: unknown): RunEntry {
	if (typeof value !== "object" || value === null || Array.isArray(value))
		throw new Error("run entry must be an object");
	const entry = value as Record<string, unknown>;
	for (const key of Object.keys(entry))
		if (!RUN_ENTRY_FIELDS.has(key))
			throw new Error(`run entry has unknown field: ${key}`);
	if (
		entry.version !== 1 ||
		typeof entry.runId !== "string" ||
		!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(
			entry.runId,
		) ||
		(entry.kind !== "suite" && entry.kind !== "aftermath") ||
		!isTerminal(entry.terminal)
	) {
		throw new Error("invalid run entry");
	}
	assertBoundedString(entry.stage, "stage");
	for (const key of ["completed", "total"] as const)
		if (
			entry[key] !== undefined &&
			(!Number.isInteger(entry[key]) || (entry[key] as number) < 0)
		)
			throw new Error(`invalid ${key}`);
	for (const key of ["currentScore", "bestScore"] as const)
		if (
			entry[key] !== undefined &&
			(typeof entry[key] !== "number" ||
				!Number.isFinite(entry[key]) ||
				(entry[key] as number) < 0 ||
				(entry[key] as number) > 1)
		)
			throw new Error(`invalid ${key}`);
	for (const key of ["sourcePath", "reportPath", "stagedPath"] as const)
		if (entry[key] !== undefined) {
			if (!isPathOrNull(entry[key])) throw new Error(`invalid ${key}`);
			if (entry[key] !== null)
				assertBoundedString(
					entry[key],
					key.replace("Path", " path"),
					16 * 1024,
				);
		}
	return entry as unknown as RunEntry;
}

function selectNewestRun(
	entries: readonly unknown[],
	kind: RunEntry["kind"],
): { id: string; data: RunEntry } | undefined {
	for (let index = entries.length - 1; index >= 0; index -= 1) {
		const entry = entries[index] as {
			id?: unknown;
			type?: unknown;
			customType?: unknown;
			data?: unknown;
		};
		if (
			entry?.type !== "custom" ||
			entry.customType !== "overkill-run" ||
			typeof entry.id !== "string"
		)
			continue;
		try {
			const data = validateRunEntry(entry.data);
			if (data.kind === kind) return { id: entry.id, data };
		} catch {}
	}
	return undefined;
}

export function selectNewestSuiteRun(entries: readonly unknown[]) {
	return selectNewestRun(entries, "suite");
}

export function selectNewestAftermathRun(entries: readonly unknown[]) {
	return selectNewestRun(entries, "aftermath");
}

export type FrozenReviewArtifacts = {
	sourcePath: string;
	reportPath: string | null;
	stagedPath: string | null;
	source: string;
	staged: string | null;
};

function reviewPaths(directory: string, manifest: RunManifest) {
	const stagedPath =
		manifest.terminal === "staged" ? join(directory, "staged-skill.md") : null;
	return {
		sourcePath: manifest.source.path,
		reportPath: manifest.terminal ? join(directory, "report.json") : null,
		stagedPath,
	};
}

/** Reads only deterministic, private run artifacts; never a public entry path. */
export async function readFrozenReviewArtifacts(
	directory: string,
): Promise<FrozenReviewArtifacts> {
	const root = await realpath(directory);
	const manifest = await readManifest(root);
	const paths = reviewPaths(root, manifest);
	return {
		...paths,
		source: await readFile(join(root, "baseline-snapshot.md"), "utf8"),
		staged: paths.stagedPath ? await readFile(paths.stagedPath, "utf8") : null,
	};
}

export function readFrozenReviewArtifactsSync(
	directory: string,
): FrozenReviewArtifacts {
	const root = realpathSync(directory);
	const manifestValue: unknown = JSON.parse(
		readFileSync(join(root, "manifest.json"), "utf8"),
	);
	assertManifest(manifestValue);
	const paths = reviewPaths(root, manifestValue);
	return {
		...paths,
		source: readFileSync(join(root, "baseline-snapshot.md"), "utf8"),
		staged: paths.stagedPath ? readFileSync(paths.stagedPath, "utf8") : null,
	};
}

function matchingRunLink(
	entry: unknown,
	manifest: RunManifest,
	entryId?: string,
): boolean {
	if (typeof entry !== "object" || entry === null) return false;
	const candidate = entry as {
		id?: unknown;
		type?: unknown;
		customType?: unknown;
		data?: unknown;
	};
	if (
		(entryId !== undefined && candidate.id !== entryId) ||
		typeof candidate.id !== "string" ||
		candidate.type !== "custom" ||
		candidate.customType !== "overkill-run"
	)
		return false;
	try {
		const data = validateRunEntry(candidate.data);
		return data.kind === manifest.kind && data.runId === manifest.runId;
	} catch {
		return false;
	}
}

/** Recovers the only unavoidable crash window after appending an initial link. */
export async function recoverRunLink(options: {
	directory: string;
	manifest: RunManifest;
	selected: { id: string; data: RunEntry };
	branch: readonly unknown[];
}): Promise<RunManifest> {
	let manifest = options.manifest;
	if (
		manifest.runId !== options.selected.data.runId ||
		manifest.kind !== options.selected.data.kind
	)
		throw new Error("run is not linked to this active session branch");
	if (manifest.linkEntryId === null) {
		const initial = options.branch.find((entry) =>
			matchingRunLink(entry, manifest, options.selected.id),
		);
		if (!initial)
			throw new Error("run is not linked to this active session branch");
		manifest = { ...manifest, linkEntryId: options.selected.id };
		await persistManifest(options.directory, manifest);
	}
	if (
		!options.branch.some((entry) =>
			matchingRunLink(entry, manifest, manifest.linkEntryId ?? undefined),
		)
	)
		throw new Error("run is not linked to this active session branch");
	return manifest;
}

export async function discardLinkedRun(options: {
	runRoot: string;
	runDirectory: string;
	selected: { id: string; data: RunEntry };
	branch: readonly unknown[];
	sessionId: string;
	allowNonterminal?: boolean;
	isRunActive?: (runId: string) => boolean;
}): Promise<void> {
	let manifest = await readManifest(options.runDirectory);
	if (
		manifest.runId !== options.selected.data.runId ||
		manifest.sessionId !== options.sessionId ||
		manifest.terminal !== options.selected.data.terminal
	)
		throw new Error("run is not linked to this active session branch");
	manifest = await recoverRunLink({
		directory: options.runDirectory,
		manifest,
		selected: options.selected,
		branch: options.branch,
	});
	if (options.selected.data.terminal === "discarded")
		throw new Error("discarded run artifacts are unavailable");
	if (!options.selected.data.terminal) {
		if (!options.allowNonterminal)
			throw new Error("only terminal runs can be discarded");
		if (!options.isRunActive)
			throw new Error("nonterminal discard requires an active-run check");
		if (options.isRunActive(manifest.runId))
			throw new Error("an active run cannot be discarded");
	}
	await discardRun(options.runRoot, options.runDirectory);
}

export async function discardRun(
	runRoot: string,
	runDirectory: string,
): Promise<void> {
	const canonicalRoot = await realpath(runRoot);
	const requestedRun = resolve(runDirectory);
	const requestedParent = await realpath(dirname(requestedRun));
	if (
		requestedParent !== canonicalRoot ||
		basename(requestedRun).length === 0
	) {
		throw new Error("can only discard a direct private run directory");
	}
	const canonicalRun = await realpath(requestedRun);
	if (
		dirname(canonicalRun) !== canonicalRoot ||
		relative(canonicalRoot, canonicalRun).startsWith("..")
	) {
		throw new Error("can only discard a direct private run directory");
	}
	await rm(canonicalRun, { force: true, recursive: true });
}