repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/loop/__tests__/contract.test.ts

Raw
File outline
import { execFileSync } from "node:child_process";
import { existsSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { DatabaseSync } from "node:sqlite";
import { fileURLToPath } from "node:url";
import {
	type FauxResponseStep,
	fauxAssistantMessage,
	fauxToolCall,
	type TranscriptContext,
} from "@earendil-works/pi-ai";
import type { AutocompleteItem } from "@earendil-works/pi-tui";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
	createPiSession,
	type PiSession,
} from "../../../test/fixture/create-pi-session.ts";

const extensionPath = fileURLToPath(new URL("../index.ts", import.meta.url));
let box: PiSession | undefined;
let owned: string | undefined;
afterEach(async () => {
	await box?.dispose();
	box = undefined;
	if (owned) rmSync(owned, { recursive: true, force: true });
	owned = undefined;
});

/** Gate that fails until it has run `passOn` times; state lives in the project cwd. */
function countingGate(passOn: number, name = "counter") {
	return {
		name,
		command: process.execPath,
		args: [
			"-e",
			`const fs=require('fs');const n=(fs.existsSync('count')?+fs.readFileSync('count','utf8'):0)+1;fs.writeFileSync('count',String(n));console.error('attempt '+n);process.exit(n>=${passOn}?0:1)`,
		],
	};
}
const fileGate = {
	name: "ready",
	command: process.execPath,
	args: ["-e", "process.exit(require('fs').existsSync('ready')?0:1)"],
};

const holdUntilAborted: FauxResponseStep = async (_context, options) => {
	await new Promise<void>((resolve) => {
		if (options?.signal?.aborted) return resolve();
		options?.signal?.addEventListener("abort", () => resolve(), { once: true });
	});
	return fauxAssistantMessage("", { stopReason: "aborted" });
};

function promptTexts(context: TranscriptContext) {
	return context.messages.flatMap((message) =>
		message.role === "user"
			? [
					typeof message.content === "string"
						? message.content
						: message.content
								.flatMap((part) => (part.type === "text" ? [part.text] : []))
								.join("\n"),
				]
			: [],
	);
}

async function start(
	options: { statePath?: string; responses?: FauxResponseStep[] } = {},
) {
	box = await createPiSession({
		extensionPaths: [extensionPath],
		env: { PI_LOOP_DEBUG: "0", PI_LOOP_STATE_PATH: options.statePath },
		responses: options.responses ?? [],
	});
	expect(box.errors).toEqual([]);
	const editors: string[] = [];
	const notes: { message: string; type: string | undefined }[] = [];
	const statuses: (string | undefined)[] = [];
	await box.session.bindExtensions({
		mode: "rpc",
		uiContext: {
			...box.session.extensionRunner.getUIContext(),
			editor: async () => editors.shift(),
			setStatus: (key: string, text: string | undefined) => {
				if (key === "loop") statuses.push(text);
			},
			notify: (message: string, type?: "info" | "warning" | "error") => {
				notes.push({ message, type });
			},
		},
	});
	const command = box.extensions[0]!.commands.get("loop")!;
	const session = box;
	return {
		box: session,
		editors,
		notes,
		statuses,
		command,
		run: (args: string) =>
			command.handler(
				args,
				session.session.extensionRunner.createContext() as never,
			),
	};
}

function readDb(path: string) {
	const db = new DatabaseSync(path, { readOnly: true });
	try {
		return {
			runs: db.prepare("SELECT * FROM runs").all(),
			attempts: db.prepare("SELECT * FROM gate_attempts ORDER BY id").all(),
			events: db
				.prepare("SELECT kind FROM events ORDER BY id")
				.all()
				.map((row) => row["kind"]),
		};
	} finally {
		db.close();
	}
}

describe("loop extension contract", () => {
	it("loops until every gate exits 0 and persists the run in the project", async () => {
		const contexts: string[][] = [];
		const step: FauxResponseStep = (context) => {
			contexts.push(promptTexts(context));
			return fauxAssistantMessage("Tests passed, trust me.");
		};
		const loop = await start({ responses: [step, step, step, step] });
		loop.editors.push(
			"Make the counter gate pass",
			JSON.stringify([
				{ name: "noop", command: process.execPath, args: ["-e", ""] },
				countingGate(3),
			]),
		);
		await loop.run("start");
		await vi.waitFor(
			() =>
				expect(loop.notes.map((note) => note.message).join("\n")).toMatch(
					/succeeded/u,
				),
			{ timeout: 10_000 },
		);
		await loop.box.session.waitForIdle();

		const db = readDb(join(loop.box.cwd, ".pi", "loop", "state.db"));
		expect(db.runs).toHaveLength(1);
		expect(db.runs[0]).toMatchObject({
			status: "succeeded",
			attempts: 3,
			turns: 2,
		});
		// Each attempt runs the gates in order and stops at the first failure.
		expect(
			db.attempts.map((row) => [
				row["attempt_no"],
				row["gate_index"],
				row["exit_code"],
			]),
		).toEqual([
			[1, 0, 0],
			[1, 1, 1],
			[2, 0, 0],
			[2, 1, 1],
			[3, 0, 0],
			[3, 1, 0],
		]);
		expect(db.events).toEqual(
			expect.arrayContaining(["start", "gate_result", "continue", "success"]),
		);
		// The model's claim of success never completed the run; the gate did.
		expect(loop.box.providerState.callCount).toBe(2);
		// The newest prompt carries bounded gate output; older prompts shrink to stubs.
		const second = contexts[1]!;
		const loopPrompts = second.filter((text) => text.startsWith("Loop run"));
		expect(loopPrompts).toHaveLength(2);
		expect(loopPrompts[0]).toMatch(/Superseded by a later loop prompt\.$/u);
		expect(loopPrompts[1]).toContain('gate 2/2 "counter" failed (exit 1)');
		expect(loopPrompts[1]).toContain('stderr tail: "attempt 2\\n"');
		expect(loopPrompts[1]).toMatch(
			/Do not edit, skip, weaken, or redefine the gates/u,
		);
		expect(loopPrompts[1]!.split("\n\n")[0]).toBe(
			contexts[0]![0]!.split("\n\n")[0],
		);
	});

	it("succeeds on a passing baseline without any model request", async () => {
		const loop = await start();
		loop.editors.push("Already done", JSON.stringify([countingGate(1)]));
		await loop.run("start");
		expect(loop.notes.at(-1)?.message).toMatch(/succeeded/u);
		expect(loop.box.providerState.callCount).toBe(0);
	});

	it("pauses when the attempt budget is exhausted", async () => {
		const loop = await start();
		loop.editors.push("Never passes", JSON.stringify([fileGate]));
		await loop.run("start none none 1");
		// Nerd Font status: autorenew, gate attempts, forum turns, then pause_circle.
		expect(loop.statuses).toContain("\u{F006A} \u{F0299} 0/1 \u{F028C} 0");
		expect(loop.statuses.at(-1)).toBe("\u{F03E5} loop paused");
		expect(loop.notes.at(-1)).toMatchObject({
			type: "warning",
			message: expect.stringMatching(/paused: Attempt budget exhausted/u),
		});
		expect(loop.box.providerState.callCount).toBe(0);
	});

	it("pauses when the turn budget is exhausted", async () => {
		const loop = await start({ responses: [fauxAssistantMessage("working")] });
		loop.editors.push("Never passes", JSON.stringify([fileGate]));
		await loop.run("start none 1");
		await vi.waitFor(() =>
			expect(loop.notes.at(-1)?.message).toMatch(
				/paused: Turn budget exhausted/u,
			),
		);
		await loop.box.session.waitForIdle();
		expect(loop.box.providerState.callCount).toBe(1);
	});

	it("rejects invalid budgets and gates before running anything", async () => {
		const loop = await start();
		await expect(loop.run("start 0")).rejects.toThrow(
			/Invalid minutes budget/u,
		);
		await expect(loop.run("start none -2")).rejects.toThrow(
			/Invalid turns budget/u,
		);
		loop.editors.push("Goal", '[{"command":"x","shell":true}]');
		await expect(loop.run("start")).rejects.toThrow(/unknown field shell/u);
		expect(existsSync(join(loop.box.cwd, "count"))).toBe(false);
	});

	it("pauses on user stop input and resumes across sessions with consumed budgets", async () => {
		owned = mkdtempSync(join(tmpdir(), "loop-contract-"));
		const statePath = join(owned, "state.db");
		const first = await start({ statePath, responses: [holdUntilAborted] });
		first.editors.push(
			"Create the ready file",
			JSON.stringify([{ ...fileGate, cwd: owned }]),
		);
		await first.run("start none 5 4");
		await vi.waitFor(() => expect(first.box.providerState.callCount).toBe(1));
		await first.box.session.extensionRunner.emitInput(
			"stop",
			undefined,
			"interactive",
			"steer",
		);
		await first.box.session.waitForIdle();
		expect(first.notes.map((note) => note.message).join("\n")).toMatch(
			/paused: User stop/u,
		);
		await first.box.dispose();
		box = undefined;

		const before = readDb(statePath).runs[0]!;
		expect(before).toMatchObject({ status: "paused", attempts: 1, turns: 1 });

		const second = await start({ statePath });
		const items = (await second.command.getArgumentCompletions?.(
			"resume ",
		)) as AutocompleteItem[];
		expect(items.map((item) => item.label)).toEqual([
			"latest",
			String(before["id"]).slice(0, 8),
		]);
		writeFileSync(join(owned, "ready"), "");
		await second.run(`resume ${String(before["id"]).slice(0, 8)}`);
		expect(second.notes.at(-1)?.message).toMatch(/succeeded/u);
		expect(readDb(statePath).runs[0]).toMatchObject({
			status: "succeeded",
			attempts: 2,
			turns: 1,
		});
		await expect(second.run("resume latest")).rejects.toThrow(/No paused run/u);
	});

	it.each(["abort", "switch", "shutdown"])(
		"pauses the active run on %s and never resumes it",
		async (how) => {
			owned = mkdtempSync(join(tmpdir(), "loop-contract-"));
			const statePath = join(owned, "state.db");
			const loop = await start({ statePath, responses: [holdUntilAborted] });
			loop.editors.push("Never passes", JSON.stringify([fileGate]));
			await loop.run("start");
			await vi.waitFor(() => expect(loop.box.providerState.callCount).toBe(1));
			if (how === "abort") await loop.box.session.abort();
			if (how === "switch")
				await loop.box.session.extensionRunner.emit({
					type: "session_before_switch",
					reason: "new",
				} as never);
			// Pi aborts the old session's agent itself during a real switch.
			await loop.box.session.abort();
			if (how === "shutdown") {
				await loop.box.dispose();
				box = undefined;
			} else await loop.box.session.waitForIdle();
			// Longer than the watchdog interval: nothing may kick the paused run.
			await new Promise((resolve) => setTimeout(resolve, 2_500));
			const [run] = readDb(statePath).runs;
			expect(run).toMatchObject({
				status: "paused",
				reason: {
					abort: "Agent aborted",
					switch: "Session changed; never auto-resumed",
					// Disposal may abort the in-flight turn before shutdown handlers run.
					shutdown: expect.stringMatching(/^(Agent aborted|Session shutdown)/u),
				}[how],
			});
			expect(loop.box.providerState.callCount).toBe(1);
		},
		10_000,
	);

	it("pauses on Escape during the baseline pass", async () => {
		const loop = await start();
		let terminal: ((data: string) => unknown) | undefined;
		await loop.box.session.bindExtensions({
			mode: "tui",
			uiContext: {
				...loop.box.session.extensionRunner.getUIContext(),
				editor: async () => loop.editors.shift(),
				notify: (message: string, type?: "info" | "warning" | "error") => {
					loop.notes.push({ message, type });
				},
				onTerminalInput: (handler) => {
					terminal = handler as never;
					return () => {
						terminal = undefined;
					};
				},
			},
		});
		loop.editors.push(
			"Slow gate",
			JSON.stringify([
				{
					command: process.execPath,
					args: ["-e", "setTimeout(() => {}, 20000)"],
				},
			]),
		);
		const started = loop.run("start");
		await vi.waitFor(() => expect(terminal).toBeDefined());
		expect(terminal?.("\x1b")).toEqual({ consume: true });
		await started;
		expect(loop.notes.at(-1)?.message).toMatch(
			/paused: Escape pressed during baseline/u,
		);
		expect(terminal).toBeUndefined();
		expect(loop.box.providerState.callCount).toBe(0);
	});

	it("mounts the animated companion in the TUI and removes it on stop", async () => {
		const loop = await start();
		const widgets: Array<{ key: string; mounted: boolean }> = [];
		await loop.box.session.bindExtensions({
			mode: "tui",
			uiContext: {
				...loop.box.session.extensionRunner.getUIContext(),
				editor: async () => loop.editors.shift(),
				notify: () => {},
				onTerminalInput: () => () => {},
				setWidget: (key: string, content: unknown) => {
					widgets.push({ key, mounted: content !== undefined });
				},
			},
		});
		loop.editors.push("Never passes", JSON.stringify([fileGate]));
		await loop.run("start none none 1");
		expect(widgets).toContainEqual({ key: "loop-companion", mounted: true });
		await loop.run("stop");
		expect(widgets.at(-1)).toEqual({ key: "loop-companion", mounted: false });
	});

	it("stops a paused persisted run and lists it", async () => {
		const loop = await start();
		loop.editors.push("Never passes", JSON.stringify([fileGate]));
		await loop.run("start none none 1");
		await loop.run("stop latest");
		await loop.run("list");
		expect(loop.notes.at(-1)?.message).toMatch(
			/^[0-9a-f]{8} stopped · attempts 1\/1 · turns 0 · Never passes$/u,
		);
	});

	it("guides goal and gate setup, then loop_begin starts the run", async () => {
		const seen: string[] = [];
		const begin: FauxResponseStep = (context) => {
			seen.push(...promptTexts(context));
			return fauxAssistantMessage(
				fauxToolCall("loop_begin", {
					goal: "Counter reaches two",
					gates: [countingGate(2)],
				}),
				{ stopReason: "toolUse" },
			);
		};
		const loop = await start({
			responses: [begin, fauxAssistantMessage("Working on it.")],
		});
		execFileSync("git", ["init", "-q"], { cwd: loop.box.cwd });
		await loop.run("guide none none 3");
		await vi.waitFor(
			() =>
				expect(loop.notes.map((note) => note.message).join("\n")).toMatch(
					/succeeded/u,
				),
			{ timeout: 10_000 },
		);
		await loop.box.session.waitForIdle();
		const guide = seen.find((text) => text.startsWith("Loop guide:"));
		expect(guide).toMatch(/Interview the user/u);
		expect(guide).toMatch(/\.pi\/loop\/state\.db, which Git does not ignore/u);
		const result = loop.box.session.messages.find(
			(message) =>
				message.role === "toolResult" && message.toolName === "loop_begin",
		);
		expect(result).toMatchObject({ isError: false });
		expect(JSON.stringify(result)).toContain(
			'Baseline attempt 1: gate \\"counter\\" failed (exit 1)',
		);
		const db = readDb(join(loop.box.cwd, ".pi", "loop", "state.db"));
		expect(db.runs[0]).toMatchObject({ status: "succeeded", attempts: 2 });
		// Arming is single-use.
		await expect(
			loop.box.extensions[0]!.tools.get("loop_begin")!.definition.execute(
				"again",
				{ goal: "Again", gates: [countingGate(1)] },
				undefined,
				undefined,
				loop.box.session.extensionRunner.createToolContext("again", undefined),
			),
		).rejects.toThrow(/only available after the user runs \/loop guide/u);
	});

	it("lets a blocked agent pause, talk normally, and resume the loop", async () => {
		owned = mkdtempSync(join(tmpdir(), "loop-contract-"));
		const statePath = join(owned, "state.db");
		const control = (args: Record<string, string>) =>
			fauxAssistantMessage(fauxToolCall("loop_control", args), {
				stopReason: "toolUse",
			});
		const loop = await start({
			statePath,
			responses: [
				control({ action: "pause", reason: "need the ready file" }),
				fauxAssistantMessage("Please create the ready file."),
				fauxAssistantMessage("It must exist in the project root."),
				control({ action: "resume" }),
				fauxAssistantMessage("Gates pass."),
			],
		});
		loop.editors.push(
			"Create the ready file",
			JSON.stringify([{ ...fileGate, cwd: owned }]),
		);
		await loop.run("start");
		await vi.waitFor(() => expect(loop.box.providerState.callCount).toBe(2));
		await loop.box.session.waitForIdle();
		expect(readDb(statePath).runs[0]).toMatchObject({
			status: "paused",
			reason: "Agent paused: need the ready file",
		});
		// Longer than the watchdog: a paused run never prompts on its own.
		await new Promise((resolve) => setTimeout(resolve, 2_500));
		expect(loop.box.providerState.callCount).toBe(2);

		// While paused the human talks with the agent without spending loop budget.
		await loop.box.session.prompt("Where should the file go?");
		expect(readDb(statePath).runs[0]).toMatchObject({
			status: "paused",
			turns: 1,
		});

		writeFileSync(join(owned, "ready"), "");
		await loop.box.session.prompt("Created it, carry on.");
		await loop.box.session.waitForIdle();
		expect(readDb(statePath).runs[0]).toMatchObject({
			status: "succeeded",
			attempts: 2,
		});
		const results = loop.box.session.messages.filter(
			(message) =>
				message.role === "toolResult" && message.toolName === "loop_control",
		);
		expect(results.map((message) => JSON.stringify(message))).toEqual([
			expect.stringContaining("paused"),
			expect.stringContaining("succeeded"),
		]);
	});

	it("rejects loop_control pause without an active run", async () => {
		const loop = await start();
		await expect(
			loop.box.extensions[0]?.tools
				.get("loop_control")
				?.definition.execute(
					"pause",
					{ action: "pause", reason: "x" },
					undefined,
					undefined,
					loop.box.session.extensionRunner.createToolContext(
						"pause",
						undefined,
					),
				),
		).rejects.toThrow(/No active loop run/u);
	});

	it("rejects loop_begin without an armed guide", async () => {
		const loop = await start({
			responses: [
				fauxAssistantMessage(
					fauxToolCall("loop_begin", {
						goal: "Sneaky",
						gates: [countingGate(1)],
					}),
					{ stopReason: "toolUse" },
				),
				fauxAssistantMessage("Understood."),
			],
		});
		await loop.box.session.prompt("Start a loop yourself.");
		const result = loop.box.session.messages.find(
			(message) =>
				message.role === "toolResult" && message.toolName === "loop_begin",
		);
		expect(result).toMatchObject({ isError: true });
		expect(existsSync(join(loop.box.cwd, ".pi", "loop"))).toBe(false);
	});

	it("serves the site URL from /loop view and closes it with the session", async () => {
		const loop = await start();
		loop.editors.push("Never passes", JSON.stringify([fileGate]));
		await loop.run("start none none 1");
		await loop.run("view");
		const url = /Loop site: (\S+)/u.exec(loop.notes.at(-1)?.message ?? "")?.[1];
		if (!url) throw new Error("missing site URL");
		const { origin, hash } = new URL(url);
		const snapshot = await (
			await fetch(`${origin}/api/snapshot?token=${hash.slice(1)}`)
		).json();
		expect(snapshot.run).toMatchObject({
			goal: "Never passes",
			status: "paused",
		});
		await loop.box.dispose();
		box = undefined;
		await vi.waitFor(async () => expect(fetch(`${origin}/`)).rejects.toThrow());
	});

	it("completes subcommands and budget placeholders", async () => {
		const loop = await start();
		const complete = async (prefix: string) =>
			((await loop.command.getArgumentCompletions?.(prefix)) ?? []).map(
				(item) => item.value,
			);
		expect(await complete("")).toEqual([
			"start",
			"guide",
			"resume",
			"pause",
			"stop",
			"status",
			"view",
			"list",
		]);
		expect(await complete("st")).toEqual(["start", "stop", "status"]);
		expect(await complete("start 10 ")).toEqual(["start 10 none"]);
		expect(await complete("guide n")).toEqual(["guide none"]);
		// Completion never creates the state database.
		expect(await complete("resume ")).toEqual(["resume latest"]);
		expect(existsSync(join(loop.box.cwd, ".pi", "loop"))).toBe(false);
	});
});