repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/loop/__tests__/controller.test.ts

Raw
File outline
import { mkdtempSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterEach, describe, expect, it } from "vitest";
import { LoopController } from "../src/controller.ts";
import { LoopStore } from "../src/store.ts";

let root: string | undefined;
let store: LoopStore | undefined;
afterEach(() => {
	store?.close();
	if (root) rmSync(root, { recursive: true, force: true });
	store = undefined;
	root = undefined;
});

const boundary = {
	outcome: "completed" as const,
	continue: false,
	entries: [],
	context: {
		pendingMessages: [],
		contextEntries: [],
		contextMessages: [],
		llmMessages: [],
		canContinue: true,
	},
};

async function controller(now: () => number) {
	root = mkdtempSync(join(tmpdir(), "loop-controller-"));
	store = await LoopStore.open(join(root, "state.db"));
	return new LoopController(store, now);
}

describe("loop budgets", () => {
	it("pauses when the time budget is exhausted and restarts it on resume", async () => {
		let now = 1_000;
		const loop = await controller(() => now);
		const run = loop.start(
			{ goal: "Goal", gates: [{ command: process.execPath }], cwd: tmpdir() },
			{ minutes: 1, turns: null, attempts: null },
		);
		expect(loop.settle(boundary, false)?.continue).toBe(true);
		now += 60_000;
		expect(loop.settle(boundary, false)).toEqual({ continue: false });
		expect(loop.status()).toMatchObject({
			status: "paused",
			reason: "Time budget exhausted",
		});
		await expect(loop.checkGates()).rejects.toThrow(/not active/u);

		const record = store?.getRun(run.id);
		if (!record) throw new Error("run not persisted");
		loop.resume(record);
		expect(loop.status()).toMatchObject({
			status: "active",
			deadline: now + 60_000,
		});
	});

	it("bounds the audit queue and reports failed state writes", async () => {
		const loop = await controller(Date.now);
		loop.start(
			{ goal: "Goal", gates: [{ command: process.execPath }], cwd: tmpdir() },
			{ minutes: null, turns: null, attempts: null },
		);
		store?.close();
		for (let index = 0; index < 5_000; index++) loop.turn();
		loop.interrupt("User pause");
		const status = loop.status();
		expect(status?.pendingAudit).toBe(4_096);
		expect(status?.storageError).toBeTruthy();
	});
});