repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

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

Raw
File outline
import { describe, expect, it } from "vitest";
import {
	assignSplits,
	chunkConsecutively,
	estimateMiningCalls,
	mineTaskProposals,
	validateAndFreezeTasks,
} from "../lib/aftermath-mining.ts";

const target = { name: "chrome-cdp", description: "Use live Chrome CDP." };

describe("Aftermath mining contracts", () => {
	it("chunks consecutively and estimates recursive aggregation", () => {
		expect(
			chunkConsecutively(
				Array.from({ length: 21 }, (_, index) => index),
				20,
			).map((group) => group.length),
		).toEqual([20, 1]);
		expect(estimateMiningCalls(401)).toEqual({
			mining: 21,
			aggregation: 3,
			total: 24,
		});
	});

	it("mines deterministic bounded chunks through fresh structured sessions", async () => {
		const prompts: string[] = [];
		const proposals = await mineTaskProposals({
			digests: [{ sessionId: "a" }, { sessionId: "b" }],
			target,
			onCall: async (phase) => {
				prompts.push(`attempt persisted:${phase}`);
			},
			async createSession() {
				let listener: ((event: any) => void) | undefined;
				return {
					subscribe(next: (event: any) => void) {
						listener = next;
						return () => {};
					},
					async prompt(prompt: string) {
						prompts.push(prompt);
						listener?.({
							type: "tool_execution_end",
							toolName: "structured_output",
							isError: false,
							result: { details: { tasks: [{ intent: "x" }] } },
						});
					},
					async abort() {},
					dispose() {},
				};
			},
		});
		expect(proposals).toEqual([{ intent: "x" }]);
		expect(prompts).toEqual([
			"attempt persisted:mining",
			expect.stringContaining(
				'phase:mine\ntargetSkill:{"description":"Use live Chrome CDP.","name":"chrome-cdp"}\nPropose only recurring tasks whose correct completion requires this target skill',
			),
		]);
	});

	it("retries one malformed structured output in a fresh session", async () => {
		let sessions = 0;
		const attempts: number[] = [];
		const proposals = await mineTaskProposals({
			digests: [{ sessionId: "a" }],
			target,
			onCall: async (_phase, attempt) => {
				attempts.push(attempt);
			},
			async createSession() {
				sessions += 1;
				const current = sessions;
				let listener: ((event: any) => void) | undefined;
				return {
					subscribe(next: (event: any) => void) {
						listener = next;
						return () => {};
					},
					async prompt() {
						if (current === 1) return;
						listener?.({
							type: "tool_execution_end",
							toolName: "structured_output",
							isError: false,
							result: { details: { tasks: [{ intent: "recovered" }] } },
						});
					},
					async abort() {},
					dispose() {},
				};
			},
		});

		expect(proposals).toEqual([{ intent: "recovered" }]);
		expect(sessions).toBe(2);
		expect(attempts).toEqual([1, 2]);
	});

	it.each([
		[
			"duplicate",
			(listener: (event: any) => void) => {
				const event = {
					type: "tool_execution_end",
					toolName: "structured_output",
					isError: false,
					result: { details: { tasks: [] } },
				};
				listener(event);
				listener(event);
			},
			"emitted 2",
		],
		[
			"error-only",
			(listener: (event: any) => void) =>
				listener({
					type: "tool_execution_end",
					toolName: "structured_output",
					isError: true,
					result: { details: { tasks: [] } },
				}),
			"emitted 0",
		],
		[
			"task-cap",
			(listener: (event: any) => void) =>
				listener({
					type: "tool_execution_end",
					toolName: "structured_output",
					isError: false,
					result: {
						details: { tasks: Array.from({ length: 11 }, () => ({})) },
					},
				}),
			"task cap",
		],
	] as const)(
		"rejects %s structured mining output after one retry",
		async (_name, emit, message) => {
			let disposed = 0;
			await expect(
				mineTaskProposals({
					digests: [{ sessionId: "a" }],
					target,
					async createSession() {
						let listener: ((event: any) => void) | undefined;
						return {
							subscribe(next: (event: any) => void) {
								listener = next;
								return () => {};
							},
							async prompt() {
								if (listener) emit(listener);
							},
							async abort() {},
							dispose() {
								disposed += 1;
							},
						};
					},
				}),
			).rejects.toThrow(message);
			expect(disposed).toBe(2);
		},
	);

	it("does not retry pre-aborted mining", async () => {
		const controller = new AbortController();
		controller.abort();
		let sessions = 0;
		await expect(
			mineTaskProposals({
				digests: [{ sessionId: "a" }],
				target,
				signal: controller.signal,
				async createSession() {
					sessions += 1;
					return {
						subscribe() {
							return () => {};
						},
						async prompt() {},
						async abort() {},
						dispose() {},
					};
				},
			}),
		).rejects.toThrow("cancelled");
		expect(sessions).toBe(1);
	});

	it("freezes only recurring exact proposals with extension-derived IDs", () => {
		const tasks = validateAndFreezeTasks({
			proposals: [
				{
					intent: " Answer ",
					context: "evidence",
					sourceSessionIds: ["b", "a"],
					checks: [{ type: "contains", value: "yes", caseSensitive: true }],
				},
				{
					intent: "Answer",
					context: "evidence",
					sourceSessionIds: ["a", "b"],
					checks: [{ type: "contains", value: "yes", caseSensitive: true }],
				},
				{ intent: "bad", context: "x", sourceSessionIds: ["a"], rubric: "x" },
			],
			harvestedSessionIds: new Set(["a", "b"]),
		});
		expect(tasks).toHaveLength(1);
		expect(tasks[0]?.id).toMatch(/^task-[a-f0-9]{64}$/);
		expect(tasks[0]?.sourceSessionIds).toEqual(["a", "b"]);
	});

	it("rejects a wholly incompatible nonempty miner schema", () => {
		expect(() =>
			validateAndFreezeTasks({
				proposals: [
					{
						title: "Wrong schema",
						task: "Missing provenance and scorer",
						checks: ["not structured checks"],
					},
				],
				harvestedSessionIds: new Set(["a", "b"]),
			}),
		).toThrow("all 1 miner proposals violated the required task schema");
	});

	it("normalizes every hashed string boundary before deduplication", () => {
		const tasks = validateAndFreezeTasks({
			proposals: [
				{
					intent: " Intent ",
					context: " Context ",
					sourceSessionIds: ["a", "b"],
					observedOutcome: " Outcome ",
					checks: [{ type: "contains", value: " Value ", caseSensitive: true }],
				},
				{
					intent: "Intent",
					context: "Context",
					sourceSessionIds: ["b", "a"],
					observedOutcome: "Outcome",
					checks: [{ type: "contains", value: "Value", caseSensitive: true }],
				},
			],
			harvestedSessionIds: new Set(["a", "b"]),
		});
		expect(tasks).toHaveLength(1);
	});

	it("creates deterministic nonempty disjoint splits", () => {
		const tasks = validateAndFreezeTasks({
			proposals: ["a", "b", "c"].map((intent) => ({
				intent,
				context: "context",
				sourceSessionIds: ["x", "y"],
				rubric: "judge",
			})),
			harvestedSessionIds: new Set(["x", "y"]),
		});
		const splits = assignSplits(tasks);
		expect(splits.train.length).toBeGreaterThan(0);
		expect(splits.validation.length).toBeGreaterThan(0);
		expect(splits.test.length).toBeGreaterThan(0);
		expect(
			new Set([...splits.train, ...splits.validation, ...splits.test]).size,
		).toBe(3);
	});
});