repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/goal/__tests__/integration-full.test.ts

Raw
File outline
import { mkdirSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { createAssistantMessageEventStream } from "@earendil-works/pi-ai";
import {
	createTestSession,
	type TestSession,
} from "@marcfargas/pi-test-harness";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import goalExtension, { __goalTest, GOAL_PROBE_MESSAGE } from "../index.ts";

let t: TestSession | undefined;
const FOOTER_KEY = Symbol.for("@bugabinga/pi-ext-footer");

beforeEach(() => {
	delete (globalThis as Record<symbol, unknown>)[FOOTER_KEY];
});

afterEach(() => {
	t?.dispose();
	t = undefined;
	__goalTest.resetCompleteJudgeForTest();
	delete process.env.PI_GOAL_PROBE;
	delete process.env.PI_GOAL_LOG;
	delete (globalThis as Record<symbol, unknown>)[FOOTER_KEY];
});

function goalPath(): string {
	return fileURLToPath(new URL("../index.ts", import.meta.url));
}

function createGoalSession(
	options: Omit<
		Parameters<typeof createTestSession>[0],
		"extensions" | "extensionFactories"
	> = {},
) {
	return createTestSession({ ...options, extensionFactories: [goalExtension] });
}

function doneEvent(text: string) {
	return {
		type: "done" as const,
		reason: "stop" as const,
		message: {
			role: "assistant" as const,
			content: [{ type: "text" as const, text }],
			api: "openai-responses" as const,
			provider: "test",
			model: "playbook",
			usage: {
				input: 0,
				output: 0,
				cacheRead: 0,
				cacheWrite: 0,
				totalTokens: 0,
				cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
			},
			stopReason: "stop" as const,
			timestamp: Date.now(),
		},
	};
}

function errorEvent(message: string) {
	return {
		type: "error" as const,
		reason: "error" as const,
		error: {
			role: "assistant" as const,
			content: [],
			api: "openai-responses" as const,
			provider: "test",
			model: "playbook",
			usage: {
				input: 0,
				output: 0,
				cacheRead: 0,
				cacheWrite: 0,
				totalTokens: 0,
				cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
			},
			stopReason: "error" as const,
			errorMessage: message,
			timestamp: Date.now(),
		},
	};
}

function installSaysStream(session: TestSession, replies: string[]) {
	const queue = [...replies];
	session.session.agent.streamFn = () => {
		const stream = createAssistantMessageEventStream();
		const text = queue.shift() ?? "[EXHAUSTED]";
		queueMicrotask(() => stream.push(doneEvent(text)));
		return stream;
	};
}

function installSaysErrorStream(session: TestSession, message: string) {
	session.session.agent.streamFn = () => {
		const stream = createAssistantMessageEventStream();
		queueMicrotask(() => stream.push(errorEvent(message)));
		return stream;
	};
}

async function waitFor(
	predicate: () => boolean,
	timeoutMs = 500,
): Promise<void> {
	const start = Date.now();
	while (!predicate()) {
		if (Date.now() - start > timeoutMs)
			throw new Error("timed out waiting for condition");
		await new Promise((resolve) => setTimeout(resolve, 5));
	}
}

function customEvents(kind: string): Array<Record<string, unknown>> {
	return (
		(t?.session.sessionManager.getEntries() ?? []) as Array<{
			type: string;
			customType?: string;
			data?: Record<string, unknown>;
		}>
	)
		.filter((entry) => entry.type === "custom" && entry.customType === kind)
		.map((entry) => entry.data ?? {});
}

function customMessages(kind: string): Array<Record<string, unknown>> {
	return (
		(t?.session.sessionManager.getEntries() ?? []) as Array<{
			type: string;
			customType?: string;
			content?: string;
			display?: boolean;
			details?: Record<string, unknown>;
		}>
	)
		.filter(
			(entry) => entry.type === "custom_message" && entry.customType === kind,
		)
		.map((entry) => ({
			content: entry.content,
			display: entry.display,
			details: entry.details,
		}));
}

function uiArgs(method: string): unknown[][] {
	return t?.events.ui
		.filter((call) => call.method === method)
		.map((call) => call.args);
}

function latestNotify(): unknown[] | undefined {
	return uiArgs("notify").at(-1);
}

function latestGoal() {
	return __goalTest.latestGoalState({
		sessionManager: t?.session.sessionManager,
	} as never);
}

function installJudgeProvider(replies: string[]) {
	const queue = [...replies];
	__goalTest.setCompleteJudgeForTest(
		async () =>
			doneEvent(
				queue.shift() ?? '{"done":false,"blocked":false,"reason":"exhausted"}',
			).message,
	);
	return () => __goalTest.resetCompleteJudgeForTest();
}

function installJudgeErrorProvider(message: string) {
	__goalTest.setCompleteJudgeForTest(async () => {
		throw new Error(message);
	});
	return () => __goalTest.resetCompleteJudgeForTest();
}

function installDelayedJudgeProvider() {
	let resolveJudge: ((text: string) => void) | undefined;
	let called = false;
	__goalTest.setCompleteJudgeForTest(async () => {
		called = true;
		const text = await new Promise<string>((resolve) => {
			resolveJudge = resolve;
		});
		return doneEvent(text).message;
	});
	return {
		called: () => called,
		resolve: (text: string) => resolveJudge?.(text),
	};
}

async function runProbe(
	mode: "direct" | "microtask" | "timeout",
	expectedAgentEnds: number,
) {
	process.env.PI_GOAL_PROBE = "1";
	t = await createGoalSession();
	installSaysStream(t, ["first turn", "second turn"]);

	await t.session.prompt(`/goal-probe ${mode}`);
	await t.session.prompt("initial work");
	await waitFor(
		() =>
			t?.events.all.filter((event) => event.type === "agent_end").length >=
			expectedAgentEnds,
	);
	await new Promise((resolve) => setTimeout(resolve, 25));
	await t.session.agent.waitForIdle();
}

describe("goal integration", () => {
	it("update_goal is unavailable before judge review", async () => {
		t = await createGoalSession({
			propagateErrors: false,
		});
		await t.run({
			prompt:
				"Start working toward this standing goal.\n\n<objective>\nship it\n</objective>",
			actions: [
				{
					type: "call",
					toolName: "update_goal",
					params: { status: "complete", reason: "verified" },
				},
				{ type: "say", text: "done" },
			],
		});

		const result = t.events.toolResultsFor("update_goal")[0];
		expect(result.isError).toBe(true);
		expect(result.text).toContain("Tool update_goal not found");
		expect(latestGoal()).toMatchObject({
			objective: "ship it",
			status: "active",
			judgeFailures: 1,
		});
		expect(latestGoal()?.lastReason?.startsWith("judge retry 1/3:")).toBe(true);
	});

	it("update_goal is unavailable without active judged goal", async () => {
		t = await createGoalSession({
			propagateErrors: false,
		});
		await t.run({
			prompt: "try tool",
			actions: [
				{
					type: "call",
					toolName: "update_goal",
					params: { status: "complete", reason: "nothing active" },
				},
			],
		});

		const result = t.events.toolResultsFor("update_goal")[0];
		expect(result.isError).toBe(true);
		expect(result.text).toContain("Tool update_goal not found");
	});

	it("/goal complete is a user override and updates passive status", async () => {
		const restore = installJudgeProvider([
			'{"done":false,"blocked":false,"reason":"not yet"}',
		]);
		try {
			t = await createGoalSession();
			installSaysStream(t, ["partial"]);

			await t.session.prompt("/goal manually finish");
			await waitFor(() => latestGoal()?.status === "active");
			await t.session.prompt("/goal complete accepted by user");

			expect(latestGoal()).toMatchObject({
				objective: "manually finish",
				status: "complete",
				lastReason: "accepted by user",
			});
			const statusTexts = t.events.ui
				.filter(
					(call) => call.method === "setStatus" && call.args[0] === "goal",
				)
				.map((call) => call.args[1]);
			expect(statusTexts).toContain("goal complete");
		} finally {
			restore();
		}
	});

	it("goal status notify, pause status, and command notifications work", async () => {
		const restore = installJudgeProvider([
			'{"done":false,"blocked":false,"reason":"not yet"}',
		]);
		try {
			t = await createGoalSession();
			installSaysStream(t, ["partial"]);

			await t.session.prompt("/goal inspect ui status");
			await waitFor(() => latestGoal()?.status === "active");
			await t.session.prompt("/goal add visible criterion");
			await t.session.prompt("/goal status");

			expect(latestNotify()?.[0]).toContain("inspect ui status");
			expect(latestNotify()?.[0]).toContain("1. visible criterion");
			expect(latestNotify()?.[1]).toBe("info");

			await t.session.prompt("/goal pause");
			expect(latestGoal()).toMatchObject({ status: "paused" });
			expect(latestNotify()).toEqual(["Goal paused", "info"]);
			expect(
				uiArgs("setStatus")
					.filter((args) => args[0] === "goal")
					.map((args) => args[1])
					.some((text) => String(text).startsWith("goal paused 0t")),
			).toBe(true);
		} finally {
			restore();
		}
	});

	it("criteria commands and clear update notifications and UI", async () => {
		const restore = installJudgeProvider([
			'{"done":true,"blocked":false,"reason":"seed complete"}',
		]);
		try {
			t = await createGoalSession();
			installSaysStream(t, ["seed"]);

			await t.session.prompt("/goal lifecycle target");
			await waitFor(() => !!latestGoal());
			if (latestGoal()?.status === "active")
				await t.session.prompt("/goal pause");
			await t.session.prompt("/goal add first criterion");
			await t.session.prompt("/goal add second criterion");
			await t.session.prompt("/goal criteria");
			expect(latestNotify()).toEqual([
				"1. first criterion\n2. second criterion",
				"info",
			]);
			await t.session.prompt("/goal remove 1");
			await t.session.prompt("/goal criteria");
			expect(latestNotify()).toEqual(["1. second criterion", "info"]);
			await t.session.prompt("/goal clear-criteria");
			await t.session.prompt("/goal criteria");
			expect(latestNotify()).toEqual(["No goal criteria.", "info"]);
			await t.session.prompt("/goal clear");
			expect(latestGoal()).toBeUndefined();
			expect(latestNotify()).toEqual(["Goal cleared", "info"]);
			expect(
				uiArgs("setWidget")
					.filter((args) => args[0] === "goal")
					.map((args) => args[1]),
			).toContain(undefined);
		} finally {
			restore();
		}
	});

	it("debug logging records continuation scheduling", async () => {
		process.env.PI_GOAL_LOG = "1";
		const restore = installJudgeProvider([
			'{"done":false,"blocked":false,"reason":"continue"}',
			'{"done":true,"blocked":false,"reason":"done"}',
		]);
		try {
			t = await createGoalSession();
			installSaysStream(t, ["partial", "finished"]);

			await t.session.prompt("/goal debug continuation");
			await waitFor(() => latestGoal()?.status === "complete", 2_000);
			const events = customEvents("goal-debug").map((entry) => entry.event);
			expect(events).toContain("continuation-queued");
			expect(events).toContain("continuation-dispatched");
		} finally {
			restore();
		}
	});

	it("resume reactivates paused goal and schedules continuation", async () => {
		const restore = installJudgeProvider([
			'{"done":true,"blocked":false,"reason":"resumed done"}',
		]);
		try {
			t = await createGoalSession();
			installSaysStream(t, ["resumed work"]);

			await t.session.prompt("/goal target for resume");
			await waitFor(() => !!latestGoal());
			await t.session.prompt("/goal pause");
			await t.session.prompt("/goal resume");
			await waitFor(() => latestGoal()?.status === "complete");
			expect(latestGoal()).toMatchObject({
				status: "complete",
				lastReason: "resumed done",
			});
			expect(latestNotify()?.[0]).toContain("Goal complete");
		} finally {
			restore();
		}
	});

	it("adopts raw standing-goal prompts and runs judge", async () => {
		const restore = installJudgeProvider([
			'{"done":true,"blocked":false,"reason":"raw standing goal complete"}',
		]);
		try {
			t = await createGoalSession();
			installSaysStream(t, ["shipped the raw goal"]);

			await t.session.prompt(
				"Start working toward this standing goal.\n\n<objective>\nship raw prompt\n</objective>\n\nDo not stop just because one turn ends.",
			);
			await waitFor(() => latestGoal()?.status === "complete");

			expect(latestGoal()).toMatchObject({
				objective: "ship raw prompt",
				status: "complete",
				lastReason: "raw standing goal complete",
			});
			expect(customEvents("goal-judge")).toMatchObject([
				{ event: "start", objective: "ship raw prompt", turn: 1 },
				{
					event: "verdict",
					objective: "ship raw prompt",
					turn: 1,
					verdict: {
						done: true,
						blocked: false,
						reason: "raw standing goal complete",
					},
				},
			]);
		} finally {
			restore();
		}
	});

	it("expands prompt templates when a new goal starts with slash", async () => {
		const restore = installJudgeProvider([
			'{"done":true,"blocked":false,"reason":"template goal complete"}',
		]);
		try {
			t = await createGoalSession();
			mkdirSync(join(t.cwd, ".pi", "prompts"), { recursive: true });
			writeFileSync(
				join(t.cwd, ".pi", "prompts", "ship.md"),
				"Ship template goal for $ARGUMENTS.",
			);
			installSaysStream(t, ["template work done"]);

			await t.session.prompt("/goal /ship prompt args");
			await waitFor(() => latestGoal()?.status === "complete");

			expect(latestGoal()).toMatchObject({
				objective: "Ship template goal for prompt args.",
				status: "complete",
				lastReason: "template goal complete",
			});
		} finally {
			restore();
		}
	});

	it("judge complete verdict completes goal", async () => {
		const restore = installJudgeProvider([
			'{"done":true,"blocked":false,"reason":"all criteria verified"}',
		]);
		try {
			t = await createGoalSession();
			installSaysStream(t, ["verified files and tests"]);

			await t.session.prompt("/goal finish feature");
			await waitFor(() => latestGoal()?.status === "complete");

			expect(latestGoal()).toMatchObject({
				objective: "finish feature",
				status: "complete",
				lastReason: "all criteria verified",
			});
			expect(customEvents("goal-judge")).toMatchObject([
				{ event: "start", objective: "finish feature", turn: 1 },
				{
					event: "verdict",
					objective: "finish feature",
					turn: 1,
					verdict: {
						done: true,
						blocked: false,
						reason: "all criteria verified",
					},
				},
			]);
			const statusCalls = t.events.ui
				.filter(
					(call) => call.method === "setStatus" && call.args[0] === "goal",
				)
				.map((call) => call.args[1]);
			expect(statusCalls).toContain("goal complete");
			const widgetCalls = t.events.ui
				.filter(
					(call) => call.method === "setWidget" && call.args[0] === "goal",
				)
				.map((call) => call.args[1]);
			expect(widgetCalls.some(Boolean)).toBe(true);
			expect(widgetCalls).toContain(undefined);
			const workingMessages = t.events.ui
				.filter((call) => call.method === "setWorkingMessage")
				.map((call) => call.args[0]);
			expect(workingMessages).toContain("goal active 0t");
			expect(workingMessages).toContain("goal judging 1t");
			expect(workingMessages).toContain(undefined);
			expect(workingMessages.length).toBeGreaterThan(0);
		} finally {
			restore();
		}
	});

	it("keeps judge verdict when user steering arrives during judge", async () => {
		const judge = installDelayedJudgeProvider();
		t = await createGoalSession();
		installSaysStream(t, ["initial work"]);

		const run = t.session.prompt("/goal handle steering during judge");
		await waitFor(() => judge.called());
		await t.session.prompt("also update docs", { streamingBehavior: "steer" });
		judge.resolve(
			'{"done":false,"blocked":false,"reason":"needs updated docs"}',
		);
		await run;
		await waitFor(() => latestGoal()?.lastReason === "needs updated docs");

		expect(latestGoal()).toMatchObject({
			objective: "handle steering during judge",
			status: "active",
			turnsUsed: 1,
			lastVerdict: "continue",
			lastReason: "needs updated docs",
			criteria: ["also update docs"],
		});
	});

	it("persists visible judge transcript rows without another agent turn", async () => {
		const restore = installJudgeProvider([
			'{"done":true,"blocked":false,"reason":"visible verdict"}',
		]);
		try {
			t = await createGoalSession();
			installSaysStream(t, ["verified"]);

			await t.session.prompt("/goal show judge rows");
			await waitFor(() => customMessages("goal-judge").length >= 2);

			expect(customMessages("goal-judge")).toMatchObject([
				{
					content: "goal judge running · turn 1",
					display: true,
					details: { event: "start", turn: 1 },
				},
				{
					content:
						"goal judge passed → goal complete · turn 1 · visible verdict",
					display: true,
					details: { event: "complete", turn: 1 },
				},
			]);
			expect(
				t.events.all.filter((event) => event.type === "agent_start"),
			).toHaveLength(1);
		} finally {
			restore();
		}
	});

	it("retries an empty judge response", async () => {
		const restore = installJudgeProvider([
			"",
			'{"done":true,"blocked":false,"reason":"retry succeeded"}',
		]);
		try {
			t = await createGoalSession();
			installSaysStream(t, ["verified after retry"]);

			await t.session.prompt("/goal retry judge");
			await waitFor(() => latestGoal()?.status === "complete");

			expect(latestGoal()).toMatchObject({
				objective: "retry judge",
				status: "complete",
				lastReason: "retry succeeded",
			});
		} finally {
			restore();
		}
	});

	it("surfaces judge provider errors instead of reporting empty response", async () => {
		const restore = installJudgeErrorProvider("403 quota exhausted");
		try {
			t = await createGoalSession();
			installSaysStream(t, ["work done"]);

			await t.session.prompt("/goal quota judge");
			await waitFor(() => latestGoal()?.status === "paused");

			expect(latestGoal()).toMatchObject({
				objective: "quota judge",
				status: "paused",
				lastReason:
					"judge failed repeatedly: judge failed: 403 quota exhausted",
			});
		} finally {
			restore();
		}
	});

	it("pauses on transport errors when Pi retry is disabled", async () => {
		t = await createGoalSession();
		mkdirSync(join(t.cwd, ".pi"), { recursive: true });
		writeFileSync(
			join(t.cwd, ".pi", "settings.json"),
			JSON.stringify({ retry: { enabled: false } }),
		);
		installSaysErrorStream(t, "WebSocket closed 1006 Connection ended");

		await t.session.prompt("/goal survive websocket drop");
		await waitFor(() => latestGoal()?.status === "paused");

		expect(latestGoal()).toMatchObject({
			objective: "survive websocket drop",
			status: "paused",
			lastVerdict: "error",
			lastReason:
				"transport error: network or connection failure. reconnecting.",
		});
	});

	it("does not dispatch goal retry while Pi auto-retry delay is pending", async () => {
		process.env.PI_GOAL_LOG = "1";
		vi.useFakeTimers();
		try {
			t = await createGoalSession();
			mkdirSync(join(t.cwd, ".pi"), { recursive: true });
			writeFileSync(
				join(t.cwd, ".pi", "settings.json"),
				JSON.stringify({ retry: { enabled: true, maxRetries: 1 } }),
			);
			t.session.settingsManager.applyOverrides({
				retry: { enabled: true, maxRetries: 1, baseDelayMs: 10_000 },
			});
			installSaysErrorStream(t, "500 server error");

			const run = t.session.prompt("/goal survive transient server error");
			await vi.waitFor(() => {
				expect(
					t?.events.all.some((event) => event.type === "auto_retry_start"),
				).toBe(true);
			});

			await vi.advanceTimersByTimeAsync(4_000);

			expect(
				customEvents("goal-debug").map((entry) => entry.event),
			).not.toContain("continuation-dispatched");
			expect(
				t.events.all.filter((event) => event.type === "agent_start"),
			).toHaveLength(1);

			await vi.advanceTimersByTimeAsync(6_000);
			await run;

			expect(latestGoal()).toMatchObject({
				objective: "survive transient server error",
				status: "paused",
				lastVerdict: "error",
				lastReason: "retry exhausted: server error",
			});
			expect(
				customEvents("goal-debug").map((entry) => entry.event),
			).not.toContain("continuation-dispatched");
		} finally {
			vi.clearAllTimers();
			vi.useRealTimers();
		}
	});

	it("pauses only on auth errors with human-readable reason", async () => {
		t = await createGoalSession();
		installSaysErrorStream(t, "401 Unauthorized");

		await t.session.prompt("/goal locked out");
		await waitFor(() => latestGoal()?.status === "paused", 2_000);

		expect(latestGoal()).toMatchObject({
			objective: "locked out",
			status: "paused",
			lastVerdict: "error",
		});
		const reason = latestGoal()?.lastReason ?? "";
		expect(reason).toContain("auth failed");
		expect(reason).toContain("check API key");
		expect(reason).not.toContain("401 Unauthorized");
	});

	it("pauses after repeated judge parse failures", async () => {
		const restore = installJudgeProvider(["", "", "", "", "", ""]);
		try {
			t = await createGoalSession();
			installSaysStream(t, ["work done", "still work", "again"]);

			await t.session.prompt("/goal flaky judge");
			await waitFor(() => latestGoal()?.status === "paused", 2_000);
			await new Promise((resolve) => setTimeout(resolve, 25));

			expect(latestGoal()).toMatchObject({
				objective: "flaky judge",
				status: "paused",
				turnsUsed: 0,
				judgeFailures: 3,
				lastReason:
					"judge failed repeatedly: judge failed: judge returned empty response",
			});
			expect(
				t.events.all.filter((event) => event.type === "agent_start"),
			).toHaveLength(3);
		} finally {
			restore();
		}
	});

	it("judge blocked verdict requires same blocker streak", async () => {
		const restore = installJudgeProvider([
			'{"done":false,"blocked":true,"reason":"needs credentials"}',
			'{"done":false,"blocked":true,"reason":"needs credentials"}',
			'{"done":false,"blocked":true,"reason":"needs credentials"}',
		]);
		try {
			t = await createGoalSession();
			installSaysStream(t, [
				"cannot continue without credentials",
				"still need credentials",
				"still need credentials",
			]);

			await t.session.prompt("/goal deploy service");
			await waitFor(() => latestGoal()?.status === "blocked", 2_000);

			expect(latestGoal()).toMatchObject({
				objective: "deploy service",
				status: "blocked",
				turnsUsed: 3,
				blockedStreak: { count: 3 },
				lastReason: "needs credentials",
			});
			expect(latestNotify()).toEqual([
				"Goal blocked: needs credentials",
				"warning",
			]);
			expect(customEvents("goal-event")).toContainEqual(
				expect.objectContaining({
					event: "blocked",
					reason: "needs credentials",
				}),
			);
			expect(
				uiArgs("setStatus")
					.filter((args) => args[0] === "goal")
					.map((args) => args[1]),
			).toContain("goal blocked");
		} finally {
			restore();
		}
	});

	it("non-terminal judge verdict does not pause on turn count", async () => {
		const notDone = '{"done":false,"blocked":false,"reason":"needs more work"}';
		const restore = installJudgeProvider([
			...Array(20).fill(notDone),
			'{"done":true,"blocked":false,"reason":"eventually done"}',
		]);
		try {
			t = await createGoalSession();
			installSaysStream(t, [...Array(20).fill("partial progress"), "done"]);

			await t.session.prompt("/goal finish migration");
			await waitFor(() => latestGoal()?.status === "complete", 3_000);

			expect(latestGoal()).toMatchObject({
				objective: "finish migration",
				status: "complete",
				turnsUsed: 21,
				lastReason: "eventually done",
			});
		} finally {
			restore();
		}
	});
});

describe("goal continuation scheduling", () => {
	it("loads in real Pi extension runtime", async () => {
		t = await createTestSession({ extensions: [goalPath()] });
		const [extension] = t.session.extensionRunner.extensions;
		expect(extension.path).toBe(goalPath());
		expect(extension.commands.has("goal")).toBe(true);
		expect(extension.commands.has("goal-probe")).toBe(false);
		expect(extension.tools.has("update_goal")).toBe(true);
	});

	for (const mode of ["direct", "microtask"] as const) {
		it(`${mode} dispatch is still busy inside agent_end`, async () => {
			await runProbe(mode, 1);
			const agentStarts = t?.events.all.filter(
				(event) => event.type === "agent_start",
			);
			const agentEnds = t?.events.all.filter(
				(event) => event.type === "agent_end",
			);
			const probeEvents = customEvents("goal-probe").map(
				(entry) => entry.event,
			);

			expect(agentStarts).toHaveLength(1);
			expect(agentEnds).toHaveLength(1);
			expect(probeEvents).toContain("dispatch-skipped-busy");
			expect(probeEvents).not.toContain("dispatch");
		});
	}

	it("setTimeout(0) schedules exactly one continuation after idle", async () => {
		await runProbe("timeout", 2);

		const agentStarts = t?.events.all.filter(
			(event) => event.type === "agent_start",
		);
		const agentEnds = t?.events.all.filter(
			(event) => event.type === "agent_end",
		);
		const assistantMessages = t?.events.messages
			.filter((message) => message.role === "assistant")
			.map((message) =>
				Array.isArray(message.content)
					? message.content
							.map((part: { type?: string; text?: string }) =>
								part.type === "text" ? part.text : "",
							)
							.join("\n")
					: "",
			);
		const probeEvents = customEvents("goal-probe").map((entry) => entry.event);

		expect(agentStarts).toHaveLength(2);
		expect(agentEnds).toHaveLength(2);
		expect(assistantMessages).toEqual(["first turn", "second turn"]);
		expect(probeEvents.filter((event) => event === "dispatch")).toHaveLength(1);
		expect(probeEvents.indexOf("persisted-before-schedule")).toBeLessThan(
			probeEvents.indexOf("dispatch"),
		);
		expect(probeEvents.at(-1)).toBe("done");

		const userMessages = t?.session.sessionManager
			.getEntries()
			.filter(
				(entry: {
					type: string;
					message?: {
						role?: string;
						content?: Array<{ type?: string; text?: string }>;
					};
				}) => entry.type === "message" && entry.message?.role === "user",
			)
			.map(
				(entry: {
					message?: { content?: Array<{ type?: string; text?: string }> };
				}) => entry.message?.content?.map((part) => part.text ?? "").join("\n"),
			);
		expect(userMessages).toContain(GOAL_PROBE_MESSAGE);
	});

	it("replay treats clear tombstones as durable", async () => {
		t = await createGoalSession();
		const now = Date.now();
		const entries = [
			{
				type: "custom",
				customType: "goal-state",
				data: {
					id: "g",
					objective: "do it",
					criteria: [],
					status: "active",
					turnsUsed: 0,
					createdAt: now,
					updatedAt: now,
				},
			},
			{
				type: "custom",
				customType: "goal-state",
				data: { cleared: true, updatedAt: now + 1 },
			},
		];

		expect(
			__goalTest.latestGoalState({
				sessionManager: { getEntries: () => entries },
			} as never),
		).toBeUndefined();
	});

	it("strictly parses judge booleans", () => {
		expect(
			__goalTest.parseJudge('{"done":"false","blocked":"false","reason":"no"}'),
		).toEqual({ done: false, blocked: false, reason: "no" });
		expect(
			__goalTest.parseJudge('{"done":true,"blocked":false,"reason":"yes"}'),
		).toEqual({ done: true, blocked: false, reason: "yes" });
	});

	it("ignores stale judge result after goal is cleared during await", async () => {
		let resolveJudge: ((text: string) => void) | undefined;
		let judgeCalled = false;
		__goalTest.setCompleteJudgeForTest(async () => {
			judgeCalled = true;
			const text = await new Promise<string>((resolve) => {
				resolveJudge = resolve;
			});
			return doneEvent(text).message;
		});

		t = await createGoalSession();
		installSaysStream(t, ["still working"]);

		await t.session.prompt("/goal finish the task");
		await waitFor(() => judgeCalled);
		await t.session.prompt("/goal clear");
		resolveJudge?.('{"done":true,"blocked":false,"reason":"finished"}');
		await t.session.agent.waitForIdle();
		await new Promise((resolve) => setTimeout(resolve, 10));

		expect(
			customEvents("goal-state").map((entry) => entry.status),
		).not.toContain("complete");
		expect(latestGoal()).toBeUndefined();
	});
});