repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

extensions/devil/__tests__/settings.test.ts

Raw
File outline
import { describe, expect, it } from "bun:test";
import {
	DEFAULT_DEFENDER_THINKING,
	DEFAULT_DEVIL_THINKING,
	DEFAULT_SYNTHESIS_THINKING,
	DebateReviewComponent,
	DevilTimeoutError,
	buildMainAgentHandoff,
	createDebateState,
	handleDebateResult,
	normalizeThinkingLevel,
	renderDebateTranscript,
	responseTextFromContent,
	withRoleTimeout,
} from "../index.ts";

describe("devil settings", () => {
	it("uses role thinking defaults", () => {
		expect(DEFAULT_DEVIL_THINKING).toBe("medium");
		expect(DEFAULT_DEFENDER_THINKING).toBe("high");
		expect(DEFAULT_SYNTHESIS_THINKING).toBe("off");
	});

	it("normalizes thinking levels", () => {
		expect(normalizeThinkingLevel("off")).toBe("off");
		expect(normalizeThinkingLevel("xhigh")).toBe("xhigh");
		expect(normalizeThinkingLevel("invalid")).toBeUndefined();
		expect(normalizeThinkingLevel(undefined)).toBeUndefined();
	});

	it("ignores thinking-only content", () => {
		expect(responseTextFromContent([{ type: "thinking", thinking: "fallback" }])).toBe("");
		expect(responseTextFromContent([{ type: "text", text: "visible" }, { type: "thinking", thinking: "hidden" }])).toBe("visible");
	});

	it("returns completed work before timeout", async () => {
		await expect(withRoleTimeout("Devil", 100, undefined, async () => "ok")).resolves.toBe("ok");
	});

	it("times out synthesis with typed error", async () => {
		await expect(withRoleTimeout("Synthesis", 1, undefined, () => new Promise(() => {}))).rejects.toMatchObject({
			name: "DevilTimeoutError",
			role: "Synthesis",
			timeoutMs: 1,
		});
	});

	it("aborts child signal and calls timeout hook on timeout", async () => {
		let aborted = false;
		let timeoutCount = 0;
		await expect(withRoleTimeout("Devil", 1, undefined, (signal) => {
			signal.addEventListener("abort", () => { aborted = true; });
			return new Promise(() => {});
		}, () => { timeoutCount++; })).rejects.toBeInstanceOf(DevilTimeoutError);
		expect(aborted).toBe(true);
		expect(timeoutCount).toBe(1);
	});

	it("propagates parent abort into child signal", async () => {
		const parent = new AbortController();
		let childAborted = false;
		const promise = withRoleTimeout("Defense", 1000, parent.signal, (signal) => {
			signal.addEventListener("abort", () => { childAborted = true; });
			return new Promise(() => {});
		});
		parent.abort();
		await expect(promise).rejects.toThrow("Aborted");
		expect(childAborted).toBe(true);
	});

	it("rejects immediately when parent is already aborted", async () => {
		const parent = new AbortController();
		parent.abort();
		await expect(withRoleTimeout("Devil", 100, parent.signal, async () => "never")).rejects.toThrow("Aborted");
	});

	it("renders compact review status", () => {
		const state = createDebateState("idea", 2);
		state.status = "Round 1/2 · Devil streaming";
		state.currentRound = 1;
		state.blocking = 1;
		const theme = { fg: (_color: string, text: string) => text } as any;
		const lines = renderDebateTranscript(state, theme, 80, { compact: false, maxBodyLines: 100 });
		expect(lines.join("\n")).toContain("Round 1/2 · Devil streaming · 1 blocking");
		expect(lines.join("\n")).not.toContain("Review: Round");
	});

	it("renders complete review key legend", () => {
		const state = createDebateState("idea", 2);
		const tui = { terminal: { rows: 30 }, requestRender() {} } as any;
		const theme = { fg: (_color: string, text: string) => text } as any;
		const review = new DebateReviewComponent(tui, theme, state, () => {}, new AbortController());
		const text = review.render(100).join("\n");
		expect(text).toContain("↑↓/j/k scroll");
		expect(text).toContain("Pg/C-u/d page");
		expect(text).toContain("g/G top/end");
		expect(text).toContain("q/Esc cancel");
		expect(text).not.toContain("1/2 ─");
	});

	it("keeps failed review open until q closes", () => {
		const state = createDebateState("idea", 2);
		state.error = "Synthesis timed out after 90s. Run /compact.";
		let renderCount = 0;
		let doneValue: unknown = "unset";
		const controller = new AbortController();
		const tui = { terminal: { rows: 30 }, requestRender() { renderCount++; } } as any;
		const theme = { fg: (_color: string, text: string) => text } as any;
		const review = new DebateReviewComponent(tui, theme, state, (value) => { doneValue = value; }, controller);

		review.fail();
		expect(controller.signal.aborted).toBe(false);
		expect(renderCount).toBe(1);
		const text = review.render(100).join("\n");
		expect(text).toContain("⚠ Debate failed");
		expect(text).toContain("Synthesis timed out after 90s");
		expect(text).toContain("q/Esc close");

		review.handleInput("q");
		expect(controller.signal.aborted).toBe(true);
		expect(doneValue).toBeNull();
	});

	it("closes failed review with Esc", () => {
		const state = createDebateState("idea", 2);
		state.error = "Provider failed";
		let doneValue: unknown = "unset";
		const controller = new AbortController();
		const tui = { terminal: { rows: 30 }, requestRender() {} } as any;
		const theme = { fg: (_color: string, text: string) => text } as any;
		const review = new DebateReviewComponent(tui, theme, state, (value) => { doneValue = value; }, controller);
		review.fail();
		review.handleInput("\u001b");
		expect(controller.signal.aborted).toBe(true);
		expect(doneValue).toBeNull();
	});

	it("cancel aborts active review once", () => {
		let doneCount = 0;
		const controller = new AbortController();
		const tui = { terminal: { rows: 30 }, requestRender() {} } as any;
		const theme = { fg: (_color: string, text: string) => text } as any;
		const review = new DebateReviewComponent(tui, theme, createDebateState("idea", 2), () => { doneCount++; }, controller);
		review.handleInput("q");
		review.handleInput("q");
		expect(controller.signal.aborted).toBe(true);
		expect(doneCount).toBe(1);
	});

	it("sends edited debate result to main agent", async () => {
		const appends: Array<{ type: string; data: any }> = [];
		const sent: string[] = [];
		const notify: unknown[] = [];
		const result = {
			synthesis: "## Verdict\nShip it",
			roundsData: ["r1", "r2"],
			recommendation: "proceed_with_caution" as const,
			blockingRaised: 1,
			blockingRemaining: 0,
		};

		await handleDebateResult("idea", result, undefined, "surface", {
			notify: (...args) => notify.push(args),
			editor: async (_title, prefill) => `${prefill}\n\nuser edit`,
		}, {
			appendEntry: (type, data) => appends.push({ type, data }),
			sendUserMessage: (content) => sent.push(content),
		});

		expect(notify).toEqual([]);
		expect(appends).toHaveLength(1);
		expect(appends[0].type).toBe("devil-result");
		expect(appends[0].data.idea).toBe("idea");
		expect(appends[0].data.rounds).toBe(2);
		expect(typeof appends[0].data.timestamp).toBe("number");
		expect(sent).toHaveLength(1);
		expect(sent[0]).toBe(buildMainAgentHandoff("idea", appends[0].data.verdict));
	});

	it("passes verdict prefill and humanized recommendation to editor", async () => {
		let title = "";
		let prefill = "";
		await handleDebateResult("idea", {
			synthesis: "## Verdict\nRevise first",
			roundsData: ["r1"],
			recommendation: "proceed_with_caution",
			blockingRaised: 2,
			blockingRemaining: 1,
		}, undefined, "escalate", {
			notify: () => {},
			editor: async (t, p) => { title = t; prefill = p ?? ""; return p; },
		}, {
			appendEntry: () => {},
			sendUserMessage: () => {},
		});
		expect(title).toContain("proceed with caution");
		expect(prefill).toContain("## Verdict\nRevise first");
		expect(prefill).toContain("⚠️ **1 unresolved blocking issue(s).**");
		expect(prefill).toContain("*Debate: 1r | 2 blocking challenges raised | 1 unresolved in verdict*");
	});

	it("does not hand off blank discarded debate result", async () => {
		const appends: unknown[] = [];
		const sent: string[] = [];
		const notify: unknown[] = [];
		await handleDebateResult("idea", {
			synthesis: "x",
			roundsData: [],
			recommendation: "revise",
			blockingRaised: 0,
			blockingRemaining: 0,
		}, undefined, "surface", {
			notify: (...args) => notify.push(args),
			editor: async () => "   ",
		}, {
			appendEntry: (_type, data) => appends.push(data),
			sendUserMessage: (content) => sent.push(content),
		});

		expect(notify).toEqual([["Debate result discarded", "info"]]);
		expect(appends).toEqual([]);
		expect(sent).toEqual([]);
	});

	it("does not hand off undefined discarded debate result", async () => {
		const appends: unknown[] = [];
		const sent: string[] = [];
		const notify: unknown[] = [];
		await handleDebateResult("idea", {
			synthesis: "x",
			roundsData: [],
			recommendation: "abandon",
			blockingRaised: 0,
			blockingRemaining: 0,
		}, undefined, "surface", {
			notify: (...args) => notify.push(args),
			editor: async () => undefined,
		}, {
			appendEntry: (_type, data) => appends.push(data),
			sendUserMessage: (content) => sent.push(content),
		});

		expect(notify).toEqual([["Debate result discarded", "info"]]);
		expect(appends).toEqual([]);
		expect(sent).toEqual([]);
	});

	it("stages retry after failed null result", async () => {
		const notify: unknown[] = [];
		const staged: string[] = [];
		await handleDebateResult("fix flaky timeout", null, "Synthesis timed out", "surface", {
			notify: (...args) => notify.push(args),
			editor: async () => { throw new Error("editor should not open"); },
			setEditorText: (text) => staged.push(text),
		}, {
			appendEntry: () => { throw new Error("append should not happen"); },
			sendUserMessage: () => { throw new Error("send should not happen"); },
		});

		expect(notify).toEqual([]);
		expect(staged).toEqual(["/devil fix flaky timeout"]);
	});

	it("failed null result does not require setEditorText", async () => {
		const notify: unknown[] = [];
		await expect(handleDebateResult("idea", null, "provider failed", "surface", {
			notify: (...args) => notify.push(args),
			editor: async () => undefined,
		}, {
			appendEntry: () => {},
			sendUserMessage: () => {},
		})).resolves.toBeUndefined();
		expect(notify).toEqual([]);
	});

	it("cancelled null result notifies but does not stage retry", async () => {
		const notify: unknown[] = [];
		const staged: string[] = [];
		const pi = { appendEntry() {}, sendUserMessage() {} };
		const ui = {
			notify: (...args: unknown[]) => notify.push(args),
			editor: async () => undefined,
			setEditorText: (text: string) => staged.push(text),
		};

		await handleDebateResult("idea", null, undefined, "surface", ui, pi);

		expect(notify).toEqual([["Debate cancelled", "info"]]);
		expect(staged).toEqual([]);
	});

	it("main-agent handoff includes advisory gate and original idea", () => {
		const handoff = buildMainAgentHandoff("change auth", "report body");
		expect(handoff).toContain("Treat it as advisory evidence, not truth.");
		expect(handoff).toContain("First response must be critique + concrete plan only.");
		expect(handoff).toContain("Original idea:\nchange auth");
		expect(handoff).toContain("Report:\nreport body");
	});
});