repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/overkill/__tests__/aftermath-state.test.ts

Raw
File outline
import { createHash } from "node:crypto";
import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import {
	assignSplits,
	canonicalJson,
	taskId,
} from "../lib/aftermath-mining.ts";
import {
	createAftermathDirectory,
	persistAftermathManifest,
	persistFrozenTasks,
	persistHarvest,
	persistJudgeCache,
	persistMiningCheckpoint,
	readAftermathManifest,
	readFrozenTasks,
	readHarvest,
	readJudgeCache,
	readMiningCheckpoint,
} from "../lib/aftermath-state.ts";
import { selectNewestAftermathRun } from "../lib/run-state.ts";

const paths: string[] = [];
afterEach(async () => {
	await Promise.all(
		paths.splice(0).map((path) => rm(path, { recursive: true, force: true })),
	);
});

describe("Aftermath durable state", () => {
	it("selects only newest active-branch Aftermath links", () => {
		expect(
			selectNewestAftermathRun([
				{
					id: "suite",
					type: "custom",
					customType: "overkill-run",
					data: {
						version: 1,
						runId: "123e4567-e89b-12d3-a456-426614174000",
						kind: "suite",
						stage: "x",
						terminal: null,
					},
				},
				{
					id: "after",
					type: "custom",
					customType: "overkill-run",
					data: {
						version: 1,
						runId: "123e4567-e89b-12d3-a456-426614174001",
						kind: "aftermath",
						stage: "x",
						terminal: null,
					},
				},
			])?.id,
		).toBe("after");
	});

	it("rejects tampered harvests and invalid split partitions", async () => {
		const root = await mkdtemp(join(tmpdir(), "aftermath-state-"));
		paths.push(root);
		const { directory } = await createAftermathDirectory(root);
		const frozenTask = {
			intent: "x",
			context: "y",
			sourceSessionIds: ["a", "b"],
			rubric: "r",
		};
		const frozenId = taskId(frozenTask);
		await expect(
			persistFrozenTasks(directory, [{ id: frozenId, ...frozenTask }], {
				train: [frozenId],
				validation: [frozenId],
				test: [],
			}),
		).rejects.toThrow("split");
		await writeFile(
			join(directory, "harvest.json"),
			JSON.stringify({
				digests: [],
				unreadable: 0,
				total: 0,
				evidence: {},
				fingerprint: "0".repeat(64),
			}),
		);
		await expect(readHarvest(directory)).rejects.toThrow("fingerprint");
	});

	it("fingerprints immutable task records independently from deterministic splits", async () => {
		const root = await mkdtemp(join(tmpdir(), "aftermath-state-"));
		paths.push(root);
		const { directory } = await createAftermathDirectory(root);
		const tasks = ["one", "two", "three"].map((intent) => {
			const task = {
				intent,
				context: "context",
				sourceSessionIds: ["a", "b"],
				rubric: "judge",
			};
			return { id: taskId(task), ...task };
		});
		const persisted = await persistFrozenTasks(
			directory,
			tasks,
			assignSplits(tasks),
		);
		const expected = createHash("sha256")
			.update(
				canonicalJson(
					[...tasks].sort((left, right) => left.id.localeCompare(right.id)),
				),
				"utf8",
			)
			.digest("hex");
		expect(persisted.fingerprint).toBe(expected);
		expect(
			JSON.parse(await readFile(join(directory, "tasks.json"), "utf8")),
		).toMatchObject({
			fingerprint: expected,
		});
	});

	it("persists attempted mining calls before incomplete outputs", async () => {
		const root = await mkdtemp(join(tmpdir(), "aftermath-state-"));
		paths.push(root);
		const { directory } = await createAftermathDirectory(root);
		await persistMiningCheckpoint(directory, {
			attemptedCalls: 2,
			completedChunks: [0],
			completedLevels: [],
		});
		await expect(readMiningCheckpoint(directory)).resolves.toEqual({
			attemptedCalls: 2,
			completedChunks: [0],
			completedLevels: [],
		});
	});

	it("persists rubric judgments under task ID and lowercase response hash keys", async () => {
		const root = await mkdtemp(join(tmpdir(), "aftermath-state-"));
		paths.push(root);
		const { directory } = await createAftermathDirectory(root);
		const key = `task-${"a".repeat(64)}:${"b".repeat(64)}`;
		await persistJudgeCache(directory, {
			[key]: { score: 0.5, passed: false, rationale: "bounded" },
		});
		expect(await readJudgeCache(directory)).toEqual({
			[key]: { score: 0.5, passed: false, rationale: "bounded" },
		});
		await writeFile(
			join(directory, "judge-cache.json"),
			JSON.stringify({
				"task-invalid:not-a-hash": { score: 1, passed: true, rationale: "x" },
			}),
		);
		await expect(readJudgeCache(directory)).rejects.toThrow("judge cache");
	});

	it("rejects frozen tasks whose persisted split is not the deterministic assignment", async () => {
		const root = await mkdtemp(join(tmpdir(), "aftermath-state-"));
		paths.push(root);
		const { directory } = await createAftermathDirectory(root);
		const bodies = ["one", "two", "three"].map((intent) => ({
			intent,
			context: "context",
			sourceSessionIds: ["a", "b"],
			rubric: "judge",
		}));
		const tasks = bodies.map((body) => ({ id: taskId(body), ...body }));
		const stored = await persistFrozenTasks(
			directory,
			tasks,
			assignSplits(tasks),
		);
		const taskFile = join(directory, "tasks.json");
		const tampered = JSON.parse(
			await (await import("node:fs/promises")).readFile(taskFile, "utf8"),
		);
		const original = tampered.splits;
		tampered.splits = {
			train: original.validation,
			validation: original.train,
			test: original.test,
		};
		tampered.fingerprint = stored.fingerprint;
		await writeFile(taskFile, JSON.stringify(tampered));
		await expect(readFrozenTasks(directory)).rejects.toThrow("split");
	});

	it("persists harvest after consent and makes frozen task records immutable", async () => {
		const root = await mkdtemp(join(tmpdir(), "aftermath-state-"));
		paths.push(root);
		const { directory, runId } = await createAftermathDirectory(root);
		const manifest = {
			version: 1 as const,
			runId,
			kind: "aftermath" as const,
			source: { path: "/skill/SKILL.md", fingerprint: "a".repeat(64) },
			model: { provider: "p", id: "m", thinking: "off" },
			sessionId: "session",
			linkEntryId: null,
			stage: "harvest",
			terminal: null,
			scores: { baseline: null, current: null, best: null, test: null },
			calls: { target: 0, checker: 0, optimizer: 0, judge: 0 },
			artifacts: {
				baselineSnapshot: "baseline-snapshot.md" as const,
				report: null,
				staged: null,
			},
			target: { name: "demo", path: "/skill/SKILL.md" },
		};
		await persistAftermathManifest(directory, manifest);
		expect(await readAftermathManifest(directory)).toEqual(manifest);
		await expect(
			persistHarvest(directory, {
				digests: [
					{
						sessionId: "s",
						cwd: "/",
						leafId: "l",
						userPrompts: ["unredacted"],
						assistantResponses: [],
						toolNames: [],
						touchedPaths: [],
						skillActivations: [],
						followUps: [],
					},
				],
				unreadable: 0,
				total: 1,
				evidence: {},
			}),
		).resolves.toMatchObject({
			fingerprint: expect.stringMatching(/^[a-f0-9]{64}$/),
		});
		const taskBody = {
			intent: "x",
			context: "y",
			sourceSessionIds: ["a", "b"],
			rubric: "r",
		};
		const task = { id: taskId(taskBody), ...taskBody };
		const tasks = [task];
		await persistFrozenTasks(directory, tasks, {
			train: [task.id],
			validation: [],
			test: [],
		});
		await expect(
			persistFrozenTasks(directory, tasks, {
				train: [],
				validation: [],
				test: [],
			}),
		).rejects.toThrow("immutable");
	});
});