/**
 * Handler-level integration suite (Stage 6 of the hardening plan): drives the
 * ACTUAL registered five tools and the GoalService through a mock pi, with an
 * injected auditor fixture — no removed tools, no model-only bypass fields.
 *
 * This replaces the historical tests/e2e/extension.test.ts (complete_goal +
 * confirmBypassAuditor surface) and joins the validation scripts as
 * `npm run test:integration`.
 */

import { skipWhenRoot } from "../support/permissions.ts";
import { createExtensionHarness } from "../support/extension-harness.ts";
import { chmodSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, appendFileSync, writeFileSync } from "node:fs";
import path from "node:path";
import { describe, it } from "node:test";
import assert from "node:assert/strict";

import { createGoal, goalFocusDetails } from "../../extensions/goal-record.ts";
import { activePathForGoal, parseGoalFile, serializeGoalFile, writeActiveGoalFile } from "../../extensions/storage/goal-files.ts";
import { goalLedgerPath } from "../../extensions/goal-ledger.ts";
import { activeGoalFiles, ledgerEvents, removeDir, tempDir } from "../support/fs.ts";

interface HarnessOptions {
	cwd: string;
	sessionEntries: unknown[];
	runCompletionAuditor?: (...args: any[]) => Promise<any>;
	hasUI?: boolean;
	select?: (prompt: string, options: string[]) => Promise<string | undefined>;
	input?: (prompt: string, fallback: string) => Promise<string | undefined>;
	confirm?: () => Promise<boolean>;
	uiCustom?: () => Promise<any>;
}

/** The shared host, plus a record of the status and widget calls these tests inspect. */
function createHarness(options: HarnessOptions) {
	const statusCalls: Array<{ key: string; value?: string }> = [];
	const widgetCalls: Array<{ key: string; factory: unknown }> = [];
	const h = createExtensionHarness({
		cwd: options.cwd,
		sessionEntries: options.sessionEntries,
		hasUI: options.hasUI,
		sessionId: "integration-session",
		systemPrompt: "base",
		runCompletionAuditor: options.runCompletionAuditor,
		ctx: { modelRegistry: { getAvailable: () => [] }, model: undefined },
		ui: {
			setStatus: (key: string, value?: string) => { statusCalls.push({ key, value }); },
			setWidget: (key: string, factory: unknown) => { widgetCalls.push({ key, factory }); },
			...(options.select ? { select: options.select } : {}),
			...(options.input ? { input: options.input } : {}),
			...(options.confirm ? { confirm: options.confirm } : {}),
			...(options.uiCustom ? { custom: options.uiCustom } : {}),
		},
	});
	return Object.assign(h, { statusCalls, widgetCalls });
}

type Harness = ReturnType<typeof createHarness>;

async function start(h: Harness): Promise<void> {
	await h.handlers.get("session_start")?.({ reason: "start" }, h.ctx);
	await h.handlers.get("before_agent_start")?.({ systemPrompt: "base", prompt: "go", systemPromptOptions: {} }, h.ctx);
}

const HOST_TOOLS = ["read", "bash", "edit", "write"];
const THREE = ["create_goal", "get_goal", "update_goal"];

/** The installed profile (from captured setActiveTools calls) contains these names. */
function installedProfileContains(history: string[][], names: string[]): boolean {
	for (const snapshot of history) {
		if (names.every((name) => snapshot.includes(name))) return true;
	}
	return false;
}

/** The installed profile (from captured setActiveTools calls) excludes these names. */
function installedProfileExcludes(history: string[][], names: string[]): boolean {
	for (const snapshot of history) {
		if (names.some((name) => snapshot.includes(name))) return false;
	}
	return true;
}

function fixture(opts: { objective?: string; skipAuditor?: boolean; tasksEnabled?: boolean } = {}) {
	const cwd = tempDir("goal-int-");
	mkdirSync(path.join(cwd, ".pi", "goals", "archived"), { recursive: true });
	if (opts.tasksEnabled === false) {
		writeFileSync(path.join(cwd, ".pi", "pi-goal-x-settings.json"), JSON.stringify({ disableTasks: true }));
	}
	const goal = createGoal({
		objective: opts.objective ?? "=== Goal ===\nObjective: Integration test",
		autoContinue: true,
		sisyphus: false,
	}, Date.UTC(2026, 8, 4, 9, 0, 0));
	if (opts.skipAuditor) goal.skipAuditor = true;
	const written = writeActiveGoalFile({ cwd }, goal);
	const sessionEntries = [
		{ type: "custom", customType: "pi-goal-focus", data: goalFocusDetails(goal.id, "created") },
	];
	const cleanup = () => { removeDir(cwd); };
	return { cwd, goal: written, sessionEntries, cleanup };
}

describe("five-tool handler integration", () => {
	it("extension loading defers getActiveTools until session_start", async () => {
		// The fixed profile is installed at session_start; extension loading
		// itself must not touch the active-tool API (host compatibility).
		let getActiveToolsCalls = 0;
		const cwd = tempDir("goal-int-load-");
		mkdirSync(path.join(cwd, ".pi", "goals", "archived"), { recursive: true });
		try {
			const isolated = createExtensionHarness({
				cwd,
				sessionEntries: [],
				systemPrompt: "",
				sessionId: "s",
				pi: { getActiveTools: () => { getActiveToolsCalls++; throw new Error("Extension runtime not initialized."); } },
			});
			assert.equal(getActiveToolsCalls, 0, "no getActiveTools call during extension loading");
			const originalConsoleError = console.error;
			console.error = () => {};
			try {
				await isolated.sessionStart();
			} finally {
				console.error = originalConsoleError;
			}
			assert.ok(getActiveToolsCalls >= 1, "profile install at session_start calls getActiveTools once");
		} finally {
			removeDir(cwd);
		}
	});

	it("/goal-status health is wired as a read-only command mode", async () => {
		const f = fixture();
		try {
			const h = createHarness({ cwd: f.cwd, sessionEntries: f.sessionEntries });
			await start(h);
			await h.commands.get("goal-status")?.handler("health", h.ctx);
			const notification = h.notices.at(-1)?.message ?? "";
			assert.match(notification, /^Goal health: OK/);
			assert.match(notification, /OK Goal file:/);
			assert.equal(activeGoalFiles(f.cwd).length, 1, "health mode must not mutate goal storage");
			assert.equal(ledgerEvents(f.cwd).length, 0, "health mode must not append ledger events");
		} finally {
			f.cleanup();
		}
	});

	it("/goal-refresh invalidates caches and reports external changes", async () => {
		const f = fixture();
		try {
			// Initial settings file so the settings diff compares content, not
			// absence -> presence (a first-time write is already visible to the
			// before-stat and correctly reports no change).
			writeFileSync(path.join(f.cwd, ".pi", "pi-goal-x-settings.json"), JSON.stringify({ subtaskDepth: 2 }), "utf8");
			const h = createHarness({ cwd: f.cwd, sessionEntries: f.sessionEntries });
			await start(h);

			await h.commands.get("goal-refresh")?.handler("", h.ctx);
			const first = h.notices.at(-1)?.message ?? "";
			assert.match(first, /no changes detected/, "unchanged state reports no changes");

			// External edits (raw fs, bypassing the extension's own cache
			// invalidation): a second goal file, a ledger line, and a settings
			// rewrite with different content.
			const second = createGoal({ objective: "External goal", autoContinue: false, sisyphus: false }, Date.UTC(2026, 8, 4, 10, 0, 0));
			writeFileSync(path.join(f.cwd, ".pi", "goals", path.basename(activePathForGoal({ cwd: f.cwd }, second))), serializeGoalFile(second), "utf8");
			appendFileSync(goalLedgerPath({ cwd: f.cwd }), JSON.stringify({ type: "goal_created", goalId: second.id, objective: "External goal", sisyphus: false, autoContinue: false, at: new Date().toISOString() }) + "\n", "utf8");
			writeFileSync(path.join(f.cwd, ".pi", "pi-goal-x-settings.json"), JSON.stringify({ subtaskDepth: 3, provider: "anthropic" }), "utf8");

			await h.commands.get("goal-refresh")?.handler("", h.ctx);
			const report = h.notices.at(-1)?.message ?? "";
			assert.match(report, /goal-refresh: re-read caches from disk — 3 change\(s\):/);
			assert.ok(report.includes(`pool: 1 goal(s) added — ${second.id}`), `pool addition reported for ${second.id}`);
			assert.match(report, /ledger: 0 -> 1 events/);
			assert.match(report, /settings: effective settings changed \(external edit\)/);

			// A second refresh with no new external edits reports no changes again.
			await h.commands.get("goal-refresh")?.handler("", h.ctx);
			const again = h.notices.at(-1)?.message ?? "";
			assert.match(again, /no changes detected/);
		} finally {
			f.cleanup();
		}
	});

	it("update_goal(complete) with an approved auditor fixture completes and archives at turn_end", async () => {
		const f = fixture();
		let auditArgs: any = null;
		try {
			const h = createHarness({ cwd: f.cwd, sessionEntries: f.sessionEntries, runCompletionAuditor: async (args: any) => {
				auditArgs = args;
				return { approved: true, disapproved: false, output: "All good\n<approved/>", model: "fixture" };
			} });
			await start(h);
			assert.ok(installedProfileContains(h.toolHistory, [...HOST_TOOLS, "create_goal", "get_goal", "update_goal", "set_goal_tasks"]),
				"session_start advertises active goal operations before a task tree exists");
			const update = h.tools.get("update_goal")!;
			const result = await (update.execute as any)("u-1", { status: "complete" }, new AbortController().signal, undefined, h.ctx);
			const text = result.content?.[0]?.text ?? "";
			assert.ok(text.includes("Goal audit approved"), "approval report");
			assert.ok(text.includes("<approved/>"), "auditor output included");
			assert.equal(auditArgs.verificationSummary, undefined, "no paperwork field");
			await h.handlers.get("turn_end")?.({ message: { role: "assistant", stopReason: "stop", usage: { input: 0, output: 0 } } }, h.ctx);
			assert.equal(activeGoalFiles(f.cwd).length, 0, "archived at turn_end");
			const events = ledgerEvents(f.cwd);
			assert.ok(events.some((e) => e.type === "audit_result" && (e as any).verdict === "approved"));
			assert.ok(events.some((e) => e.type === "goal_completed"));
		} finally {
			f.cleanup();
		}
	});

	it("update_goal(complete) with a disapproved auditor fixture stays open with feedback", async () => {
		const f = fixture();
		try {
			const h = createHarness({ cwd: f.cwd, sessionEntries: f.sessionEntries, runCompletionAuditor: async () =>
				({ approved: false, disapproved: true, output: "Missing requirement\n<disapproved/>", model: "fixture" }) });
			await start(h);
			const update = h.tools.get("update_goal")!;
			const result = await (update.execute as any)("u-2", { status: "complete" }, new AbortController().signal, undefined, h.ctx);
			const text = result.content?.[0]?.text ?? "";
			assert.ok(text.includes("Goal audit rejected"), "rejection feedback");
			assert.equal(activeGoalFiles(f.cwd).length, 1, "goal stays open");
		} finally {
			f.cleanup();
		}
	});

	it("update_goal(complete) with settings.disabled skips the auditor and records audit_skipped", async () => {
		const f = fixture();
		let auditorCalled = 0;
		try {
			writeFileSync(path.join(f.cwd, ".pi", "pi-goal-x-settings.json"), JSON.stringify({ disabled: true }));
			const h = createHarness({ cwd: f.cwd, sessionEntries: f.sessionEntries, runCompletionAuditor: async () => { auditorCalled++; throw new Error("must not run"); } });
			await start(h);
			const update = h.tools.get("update_goal")!;
			const result = await (update.execute as any)("u-3", { status: "complete" }, new AbortController().signal, undefined, h.ctx);
			const text = result.content?.[0]?.text ?? "";
			assert.ok(text.includes("Goal audit skipped"), "skip report");
			assert.ok(text.includes("auditor disabled in settings"));
			assert.equal(auditorCalled, 0);
			const events = ledgerEvents(f.cwd);
			assert.ok(events.some((e) => e.type === "audit_skipped" && (e as any).reason === "disabled"));
		} finally {
			f.cleanup();
		}
	});

	it("update_goal(complete) honors a legacy persisted skipAuditor record", async () => {
		const f = fixture({ skipAuditor: true });
		let auditorCalled = 0;
		try {
			const h = createHarness({ cwd: f.cwd, sessionEntries: f.sessionEntries, runCompletionAuditor: async () => { auditorCalled++; throw new Error("must not run"); } });
			await start(h);
			const update = h.tools.get("update_goal")!;
			const result = await (update.execute as any)("u-4", { status: "complete" }, new AbortController().signal, undefined, h.ctx);
			const text = result.content?.[0]?.text ?? "";
			assert.ok(text.includes("per-goal auditor disabled"), "legacy skip honored");
			assert.equal(auditorCalled, 0);
		} finally {
			f.cleanup();
		}
	});

	it("set_goal_tasks + update_goal_task work end-to-end through the registered handlers", async () => {
		const f = fixture();
		try {
			const h = createHarness({ cwd: f.cwd, sessionEntries: f.sessionEntries });
			await start(h);
			const setTasks = h.tools.get("set_goal_tasks")!;
			const result = await (setTasks.execute as any)("s-1", {
				tasks: [{ id: "t1", title: "Alpha" }, { id: "t2", title: "Beta" }],
			}, new AbortController().signal, undefined, h.ctx);
			assert.ok(result.terminate === true, "structural change terminates the turn");
			await h.handlers.get("before_agent_start")?.({ systemPrompt: "base", prompt: "go2", systemPromptOptions: {} }, h.ctx);
			const updateTask = h.tools.get("update_goal_task")!;
			const upd = await (updateTask.execute as any)("u-5", { task_id: "t1", status: "complete", evidence: "verified" },
				new AbortController().signal, undefined, h.ctx);
			const text = upd.content?.[0]?.text ?? "";
			assert.ok(text.includes("t1 complete"), `task update result: ${text}`);
			const goal = parseGoalFile(path.join(f.cwd, ".pi", "goals", activeGoalFiles(f.cwd)[0]!));
			assert.equal(goal?.taskList?.tasks.find((t) => t.id === "t1")?.status, "complete");
			assert.equal(goal?.taskList?.tasks.find((t) => t.id === "t2")?.status, "pending");
		} finally {
			f.cleanup();
		}
	});

	it("tasks-disabled settings install the three-core profile", async () => {
		const f = fixture({ tasksEnabled: false });
		try {
			const h = createHarness({ cwd: f.cwd, sessionEntries: f.sessionEntries });
			await start(h);
			for (const present of ["create_goal", "get_goal", "update_goal"]) {
				assert.ok(h.tools.has(present), `${present} registered`);
			}
			// Captured setActiveTools calls (not just registered names): the
			// three-core profile is installed and task tools are never active.
			assert.ok(installedProfileContains(h.toolHistory, [...HOST_TOOLS, ...THREE]),
				"captured profile includes host + three core tools");
			assert.ok(installedProfileExcludes(h.toolHistory, ["set_goal_tasks", "update_goal_task"]),
				"task tools are never installed when tasks are disabled");
			// The executors reject task calls when disabled.
			const setTasks = h.tools.get("set_goal_tasks")!;
			const result = await (setTasks.execute as any)("s-2", { tasks: [{ id: "t1", title: "X" }] },
				new AbortController().signal, undefined, h.ctx);
			const text = result.content?.[0]?.text ?? "";
			assert.ok(text.includes("disabled by settings"), `task tool disabled message: ${text}`);
		} finally {
			f.cleanup();
		}
	});
});

	it("goal-settings menu toggles the disabled switch through the registered handler", async () => {
		const f = fixture();
		try {
			const selects: string[] = ["  auditor disabled: false (default)", "Set project override to true", "Done"];
			const h = createHarness({
				cwd: f.cwd,
				sessionEntries: f.sessionEntries,
				hasUI: true,
				select: async () => selects.shift(),
			});
			await start(h);
			const settingsCmd = h.commands.get("goal-settings");
			assert.ok(settingsCmd, "goal-settings command registered");
			await settingsCmd.handler("", h.ctx); // must not throw (regression: recursive saveSettings)
			const settingsPath = path.join(f.cwd, ".pi", "pi-goal-x-settings.json");
			const saved = JSON.parse(readFileSync(settingsPath, "utf8"));
			assert.equal(saved.disabled, true, "menu toggle must persist disabled: true");
		} finally {
			f.cleanup();
		}
	});

	it("goal-settings menu editing persists a field without stack overflow", async () => {
		const f = fixture();
		try {
			writeFileSync(path.join(f.cwd, ".pi", "pi-goal-x-settings.json"), JSON.stringify({ disabled: true }));
			const selects: string[] = ["  thinking_level: (default) (default)", "off", "Done"];
			const inputs: string[] = ["off"];
			const h = createHarness({
				cwd: f.cwd,
				sessionEntries: f.sessionEntries,
				hasUI: true,
				select: async () => selects.shift(),
				input: async () => inputs.shift(),
			});
			await start(h);
			const settingsCmd = h.commands.get("goal-settings");
			await settingsCmd.handler("", h.ctx);
			const saved = JSON.parse(readFileSync(path.join(f.cwd, ".pi", "pi-goal-x-settings.json"), "utf8"));
			assert.equal(saved.disabled, true, "existing setting preserved");
			assert.equal(saved.thinking_level, "off", "thinking_level edited through the menu");
		} finally {
			f.cleanup();
		}
	});

	describe("goal-settings menu (follow-up Stage 1)", () => {
		const settingsPath = (cwd: string) => path.join(cwd, ".pi", "pi-goal-x-settings.json");
		const readSettings = (cwd: string) => {
			const p = settingsPath(cwd);
			return existsSync(p) ? JSON.parse(readFileSync(p, "utf8")) : {};
		};

		it("displays every persisted settings row and reflects file values", async () => {
			const f = fixture();
			try {
				writeFileSync(settingsPath(f.cwd), JSON.stringify({
					disableTasks: true, subtaskDepth: 3, provider: "anthropic", thinking_level: "high", disabled: true,
				}));
				let firstOptions: string[] = [];
				const h = createHarness({
					cwd: f.cwd, sessionEntries: f.sessionEntries, hasUI: true,
					select: async (_prompt: string, options: string[]) => {
						if (firstOptions.length === 0) firstOptions = [...options];
						return "Done";
					},
				});
				await start(h);
				await h.commands.get("goal-settings").handler("", h.ctx);
				const lines = firstOptions.filter((o) => o.startsWith("  ") && !o.startsWith("  ───"));
				assert.equal(lines.length, 27, `all settings rows rendered, got: ${lines.join(" | ")}`);
				assert.ok(lines.includes("  slow repeated idle replies (opt-in): false (default)"));
				assert.ok(lines.includes("  show context usage line: false (default)"));
				assert.ok(lines.some((l) => l === "  show autonomous runs line: true (default)"), "the runs-line setting is listed and defaults to on");
				assert.ok(lines.some((l) => l === "  auditor disabled: true (project override)"));
				assert.ok(lines.some((l) => l === "  provider: anthropic (project override)"));
				assert.ok(lines.some((l) => l === "  model: (default) (default)"));
				assert.ok(lines.some((l) => l === "  thinking_level: high (project override)"));
				assert.ok(lines.some((l) => l === "  disableTasks: true (project override)"));
				assert.ok(lines.some((l) => l === "  disableContracts: false (default)"));
				assert.ok(lines.includes("  explicit execution contracts (opt-in): false (default)"));
				assert.ok(lines.some((l) => l === "  subtaskDepth: 3 (project override)"));
				assert.ok(lines.some((l) => l === "  autoSelectSingleGoal: false (default)"));
				assert.ok(lines.some((l) => l === "  hideUnfocusedBanner: false (default)"));
				assert.ok(lines.some((l) => l === "  hideUnfocusedPrompt: false (default)"));
				assert.ok(lines.some((l) => l === "  stall timeout (minutes): 0 (default)"));
				assert.ok(lines.some((l) => l === "  max objective length (0 = none): 0 (default)"), "objective length row defaults to 0");
			} finally {
				f.cleanup();
			}
		});

		it("toggles every boolean row directly and persists each value", async () => {
			const f = fixture();
			try {
				const selects = [
					"  disableTasks: false (default)", "Set project override to true",
					"  disableContracts: false (default)", "Set project override to true",
					"  auditor disabled: false (default)", "Set project override to true",
					"  autoSelectSingleGoal: false (default)", "Set project override to true",
					"Done",
				];
				const h = createHarness({
					cwd: f.cwd, sessionEntries: f.sessionEntries, hasUI: true,
					select: async () => selects.shift(),
				});
				await start(h);
				await h.commands.get("goal-settings").handler("", h.ctx);
				const saved = readSettings(f.cwd);
				assert.equal(saved.disableTasks, true);
				assert.equal(saved.disableContracts, true);
				assert.equal(saved.disabled, true);
				assert.equal(saved.autoSelectSingleGoal, true);
				// Second pass removes the local overrides via the action menu's
				// inherit choice; the file then omits both keys.
				const selects2 = ["  disableTasks: true (project override)", "Use inherited value", "  autoSelectSingleGoal: true (project override)", "Use inherited value", "Done"];
				const h2 = createHarness({
					cwd: f.cwd, sessionEntries: f.sessionEntries, hasUI: true,
					select: async () => selects2.shift(),
				});
				await start(h2);
				await h2.commands.get("goal-settings").handler("", h2.ctx);
				const saved2 = readSettings(f.cwd);
				assert.equal(saved2.disableTasks, undefined, "disableTasks toggled back off clears the key");
				assert.equal(saved2.autoSelectSingleGoal, undefined, "autoSelectSingleGoal toggled back off clears the key");
				assert.equal(saved2.disableContracts, true, "untouched boolean preserved");
				assert.equal(saved2.disabled, true, "untouched boolean preserved");
			} finally {
				f.cleanup();
			}
		});

		it("edits and clears provider and model text fields", async () => {
			const f = fixture();
			try {
				// Set both via the manual provider/model entry: filter first, then
				// pick "✎ Enter provider/model manually (advanced)", then type the pair.
				const selects = [
					"  provider: (default) (default)", "✎ Enter provider/model manually (advanced)",
					"  model: claude-sonnet-4 (project override)", "✎ Enter provider/model manually (advanced)",
					"Done",
				];
				const inputs = ["", "anthropic/claude-sonnet-4", "", "anthropic/claude-sonnet-4"];
				const h = createHarness({
					cwd: f.cwd, sessionEntries: f.sessionEntries, hasUI: true,
					select: async () => selects.shift(),
					input: async () => inputs.shift(),
				});
				await start(h);
				await h.commands.get("goal-settings").handler("", h.ctx);
				const saved = readSettings(f.cwd);
				assert.equal(saved.provider, "anthropic");
				assert.equal(saved.model, "claude-sonnet-4");
				// Clear both by returning to the current-session/default choice from
				// either row: the default choice deletes provider and model together.
				const selects2 = ["  provider: anthropic (project override)", "  Current session / default (system default)", "Done"];
				const inputs2 = [""];
				const h2 = createHarness({
					cwd: f.cwd, sessionEntries: f.sessionEntries, hasUI: true,
					select: async () => selects2.shift(),
					input: async () => inputs2.shift(),
				});
				await start(h2);
				await h2.commands.get("goal-settings").handler("", h2.ctx);
				const saved2 = readSettings(f.cwd);
				assert.equal(saved2.provider, undefined, "default choice clears provider");
				assert.equal(saved2.model, undefined, "default choice clears model");
			} finally {
				f.cleanup();
			}
		});

		it("accepts every thinking level and rejects unknown values", async () => {
			const f = fixture();
			try {
				const selects = [
					"  thinking_level: (default) (default)", "off",
					"  thinking_level: off (project override)", "minimal",
					"  thinking_level: minimal (project override)", "low",
					"  thinking_level: low (project override)", "medium",
					"  thinking_level: medium (project override)", "high",
					"  thinking_level: high (project override)", "xhigh",
					"  thinking_level: xhigh (project override)", "max",
					"Done",
				];
				const inputs = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
				const h = createHarness({
					cwd: f.cwd, sessionEntries: f.sessionEntries, hasUI: true,
					select: async () => selects.shift(),
					input: async () => inputs.shift(),
				});
				await start(h);
				await h.commands.get("goal-settings").handler("", h.ctx);
				const saved = readSettings(f.cwd);
				assert.equal(saved.thinking_level, "max", "all seven levels accepted in sequence");
				// Unknown value is rejected with a warning and nothing is persisted.
				const selects2 = ["  thinking_level: max (project override)", "bogus", "Done"];
				const inputs2 = ["bogus"];
				const h2 = createHarness({
					cwd: f.cwd, sessionEntries: f.sessionEntries, hasUI: true,
					select: async () => selects2.shift(),
					input: async () => inputs2.shift(),
				});
				await start(h2);
				await h2.commands.get("goal-settings").handler("", h2.ctx);
				assert.ok(h2.notices.some((n) => n.level === "warning" && n.message.includes("thinking_level must be one of")),
					"unknown thinking level warns");
				assert.equal(readSettings(f.cwd).thinking_level, "max", "rejected value is not persisted");
			} finally {
				f.cleanup();
			}
		});

		it("subtaskDepth accepts 1 and rejects 1.5, 1x, zero, negative, infinity, and unsafe values", async () => {
			const f = fixture();
			try {
				const rejects = ["1.5", "1x", "0", "-3", "Infinity", "9007199254740992", "", "1"];
				const inputs = [...rejects];
				const selects: string[] = [];
				for (let i = 0; i < rejects.length; i++) {
					selects.push("  subtaskDepth: 1 (default)", "Set project override...");
				}
				selects.push("Done");
				const h = createHarness({
					cwd: f.cwd, sessionEntries: f.sessionEntries, hasUI: true,
					select: async () => selects.shift(),
					input: async () => inputs.shift(),
				});
				await start(h);
				await h.commands.get("goal-settings").handler("", h.ctx);
				const warnings = h.notices.filter((n) => n.level === "warning" && n.message.includes("subtaskDepth"));
				assert.equal(warnings.length, rejects.length - 1, `every invalid input warns: ${warnings.length}`);
				assert.equal(readSettings(f.cwd).subtaskDepth, 1, "only the valid input is persisted");
			} finally {
				f.cleanup();
			}
		});

		it("toggling tasks off, on, and off in one menu session reinstalls the correct fixed profile each time", async () => {
			const f = fixture();
			try {
				const selects = [
					"  disableTasks: false (default)", "Set project override to true",
					"  disableTasks: true (project override)", "Use inherited value",
					"  disableTasks: false (default)", "Set project override to true",
					"Done",
				];
				const h = createHarness({
					cwd: f.cwd, sessionEntries: f.sessionEntries, hasUI: true,
					select: async () => selects.shift(),
				});
				await start(h);
				// session_start installed the five-tool profile: history[0].
				assert.equal(h.toolHistory.length, 1, "one install at session_start");
				await h.commands.get("goal-settings").handler("", h.ctx);
				// Each real change reinstalls exactly once: three, five, three.
				assert.equal(h.toolHistory.length, 4, "three reinstalls after session_start");
				const installed = h.toolHistory.slice(1).map((tools) => (tools.includes("set_goal_tasks") ? "five" : "three"));
				assert.deepEqual(installed, ["three", "five", "three"], "profile alternates three/five/three, never skipping a toggle");
				const saved = readSettings(f.cwd);
				assert.equal(saved.disableTasks, true, "final file state has tasks disabled");
			} finally {
				f.cleanup();
			}
		});

		it("hideUnfocusedBanner hides and restores the unfocused chrome live (PR #29)", async () => {
			const f = fixture();
			try {
				// Two open goals, nothing focused: the unfocused banner renders.
				writeActiveGoalFile({ cwd: f.cwd }, { ...f.goal, id: "second-open-goal", objective: "Second open goal for the banner test" } as never);
				const entries = [{ type: "custom", customType: "pi-goal-focus", data: goalFocusDetails(null, "unfocused") }];
				const h = createHarness({
					cwd: f.cwd, sessionEntries: entries, hasUI: true,
					select: async () => {
						return "Done";
					},
				});
				await start(h);
				await Promise.resolve(); // flush the coalesced UI microtask
				assert.ok(
					h.statusCalls.some((c) => c.key === "goal" && typeof c.value === "string" && c.value.includes("goal: unfocused")),
					`unfocused hint visible before the setting: ${JSON.stringify(h.statusCalls)}`,
				);

				// Turn the setting on through the menu; the hide must be visible in
				// captured UI state before the handler resolves.
				let queue = ["  hideUnfocusedBanner: false (default)", "Set project override to true", "Done"];
				const h2 = createHarness({
					cwd: f.cwd, sessionEntries: entries, hasUI: true,
					select: async (_prompt: string, options: string[]) => {
						const hit = queue.find((q) => options.includes(q));
						if (hit === undefined) return "Done";
						queue = queue.filter((q) => q !== hit);
						return hit;
					},
				});
				await start(h2);
				await h2.commands.get("goal-settings").handler("", h2.ctx);
				await Promise.resolve(); // coalesced flush is a single microtask
				const cleared = h2.statusCalls.some((c) => c.key === "goal" && c.value === undefined)
					&& h2.widgetCalls.some((w) => w.factory === undefined || w.factory === null);
				assert.ok(cleared, `live hide clears status + widget: ${JSON.stringify(h2.statusCalls)} / ${h2.widgetCalls.length} widget calls`);
				const saved = readSettings(f.cwd);
				assert.equal(saved.hideUnfocusedBanner, true);

				// Restore via the action menu's inherit choice.
				queue = ["  hideUnfocusedBanner: true (project override)", "Use inherited value", "Done"];
				const h3 = createHarness({
					cwd: f.cwd, sessionEntries: entries, hasUI: true,
					select: async (_prompt: string, options: string[]) => {
						const hit = queue.find((q) => options.includes(q));
						if (hit === undefined) return "Done";
						queue = queue.filter((q) => q !== hit);
						return hit;
					},
				});
				await start(h3);
				await h3.commands.get("goal-settings").handler("", h3.ctx);
				await Promise.resolve();
				assert.ok(
					h3.statusCalls.some((c) => c.key === "goal" && typeof c.value === "string" && c.value.includes("goal: unfocused")),
					"live restore re-renders the unfocused hint",
					);
			} finally {
				f.cleanup();
			}
		});

		it("headless /goal-settings reports the settings file path without editing", async () => {
			const f = fixture();
			try {
				const h = createHarness({ cwd: f.cwd, sessionEntries: f.sessionEntries, hasUI: false });
				await start(h);
				await h.commands.get("goal-settings").handler("", h.ctx);
				assert.ok(h.notices.some((n) => n.message.includes("project file: ") && n.message.includes("pi-goal-x-settings.json") && n.message.includes("Global file: ")),
					`headless notification reports both layer paths: ${h.notices.map((n) => n.message).join(" | ")}`);
				const p = settingsPath(f.cwd);
				assert.ok(!existsSync(p), "headless invocation must not create the settings file");
			} finally {
				f.cleanup();
			}
		});

		it("environment overrides take precedence in the profile-reinstall decision", async () => {
			const f = fixture();
			const prevTasks = process.env.PI_GOAL_DISABLE_TASKS;
			process.env.PI_GOAL_DISABLE_TASKS = "true";
			try {
				// session_start installs the three-tool profile because the env
				// override forces disableTasks even though the file is absent.
				const h = createHarness({ cwd: f.cwd, sessionEntries: f.sessionEntries, hasUI: true });
				await start(h);
				assert.equal(h.toolHistory.length, 1, "three-tool install at session_start");
				assert.ok(!h.toolHistory[0]!.includes("set_goal_tasks"), "env override installs the core profile");
				// The env override makes the disableTasks row read-only: selecting it
				// warns and never mutates, so no reinstall may happen.
				const selects = ["  disableTasks: false (environment; read-only)", "Done"];
				const h2 = createHarness({
					cwd: f.cwd, sessionEntries: f.sessionEntries, hasUI: true,
					select: async () => selects.shift(),
				});
				await start(h2);
				await h2.commands.get("goal-settings").handler("", h2.ctx);
				assert.equal(h2.toolHistory.length, 1, "no reinstall when the effective setting never changed");
			} finally {
				if (prevTasks === undefined) delete process.env.PI_GOAL_DISABLE_TASKS;
				else process.env.PI_GOAL_DISABLE_TASKS = prevTasks;
				f.cleanup();
			}
		});
	});

describe("confirmation and audit UX (follow-up Stage 2)", () => {
	it("/goal-clear asks for confirmation; cancelling is a byte-for-byte no-op", async () => {
		const f = fixture();
		try {
			const before = readFileSync(path.join(f.cwd, ".pi", "goals", activeGoalFiles(f.cwd)[0]!), "utf8");
			const ledgerBefore = ledgerEvents(f.cwd).length;
			let confirmPrompt = "";
			const h = createHarness({
				cwd: f.cwd, sessionEntries: f.sessionEntries, hasUI: true,
				confirm: async () => { confirmPrompt = "asked"; return false; },
			});
			await start(h);
			await h.commands.get("goal-clear").handler("", h.ctx);
			assert.ok(confirmPrompt === "asked", "confirmation must be requested before archiving");
			assert.equal(activeGoalFiles(f.cwd).length, 1, "goal must stay open after cancel");
			const after = readFileSync(path.join(f.cwd, ".pi", "goals", activeGoalFiles(f.cwd)[0]!), "utf8");
			assert.equal(after, before, "active goal file unchanged byte-for-byte");
			assert.equal(ledgerEvents(f.cwd).length, ledgerBefore, "no ledger entry appended on cancel");
			assert.ok(h.notices.some((n) => n.message.includes("cancelled")), "cancel acknowledged");
		} finally {
			f.cleanup();
		}
	});

	it("/goal-clear confirms and archives the selected goal", async () => {
		const f = fixture();
		try {
			const h = createHarness({
				cwd: f.cwd, sessionEntries: f.sessionEntries, hasUI: true,
				confirm: async () => true,
			});
			await start(h);
			await h.commands.get("goal-clear").handler("", h.ctx);
			assert.equal(activeGoalFiles(f.cwd).length, 0, "goal archived after confirm");
			const archived = readdirSync(path.join(f.cwd, ".pi", "goals", "archived"));
			assert.equal(archived.length, 1, "exactly one goal archived");
			assert.ok(h.notices.some((n) => n.message.includes("cleared and archived")), "archive acknowledged");
		} finally {
			f.cleanup();
		}
	});

	it("/goal-clear headless returns guidance without mutation", async () => {
		const f = fixture();
		try {
			const before = readFileSync(path.join(f.cwd, ".pi", "goals", activeGoalFiles(f.cwd)[0]!), "utf8");
			const ledgerBefore = ledgerEvents(f.cwd).length;
			const h = createHarness({ cwd: f.cwd, sessionEntries: f.sessionEntries, hasUI: false });
			await start(h);
			await h.commands.get("goal-clear").handler("", h.ctx);
			assert.equal(activeGoalFiles(f.cwd).length, 1, "headless clear must not archive");
			assert.equal(readFileSync(path.join(f.cwd, ".pi", "goals", activeGoalFiles(f.cwd)[0]!), "utf8"), before, "file unchanged");
			assert.equal(ledgerEvents(f.cwd).length, ledgerBefore, "no ledger entry in headless clear");
			assert.ok(h.notices.some((n) => n.message.includes("interactive session")), "headless guidance notification");
		} finally {
			f.cleanup();
		}
	});

	it("Escape abort during audit appends exactly one audit_skipped and completes without audit", async () => {
		const f = fixture();
		let auditorStartedResolve: (() => void) | null = null;
		try {
			const h = createHarness({
				cwd: f.cwd, sessionEntries: f.sessionEntries, hasUI: true,
				uiCustom: async () => "complete_without_audit",
				runCompletionAuditor: async ({ signal }: any) => {
						auditorStartedResolve?.();
					await new Promise<void>((resolve) => {
						signal.addEventListener("abort", () => resolve(), { once: true });
					});
					return { approved: false, disapproved: false, output: "Auditor aborted.", error: "Auditor aborted." };
				},
			});
			await start(h);
			const auditorStarted = new Promise<void>((resolve) => { auditorStartedResolve = resolve; });
			const update = h.tools.get("update_goal")!;
			const pending = (update.execute as any)("abort-1", { status: "complete" }, new AbortController().signal, undefined, h.ctx);
			// The auditor fixture is now running: progress display and the abort
			// controller are set. Simulate the user pressing Escape mid-audit.
			await auditorStarted;
			// The widget's Escape handler matches the raw ESC byte (\x1b).
			h.terminalInput("");
			const result = await pending;
			const text = result.content?.[0]?.text ?? "";
			assert.ok(text.includes("Goal audit skipped"), `skip report: ${text.slice(0, 80)}`);
			const skipped = ledgerEvents(f.cwd).filter((e) => e.type === "audit_skipped");
			assert.equal(skipped.length, 1, "exactly one canonical audit_skipped event (no duplicate from the abort callback)");
			assert.equal((skipped[0] as any).reason, "user_aborted");
		} finally {
			f.cleanup();
		}
	});

	it("Escape abort then continue working leaves the goal active with no skip event", async () => {
		const f = fixture();
		let auditorStartedResolve: (() => void) | null = null;
		try {
			const h = createHarness({
				cwd: f.cwd, sessionEntries: f.sessionEntries, hasUI: true,
				uiCustom: async () => "continue_working",
				runCompletionAuditor: async ({ signal }: any) => {
					auditorStartedResolve?.();
					await new Promise<void>((resolve) => {
						signal.addEventListener("abort", () => resolve(), { once: true });
					});
					return { approved: false, disapproved: false, output: "Auditor aborted.", error: "Auditor aborted." };
				},
			});
			await start(h);
			const auditorStarted = new Promise<void>((resolve) => { auditorStartedResolve = resolve; });
			const update = h.tools.get("update_goal")!;
			const pending = (update.execute as any)("abort-2", { status: "complete" }, new AbortController().signal, undefined, h.ctx);
			await auditorStarted;
			// The widget's Escape handler matches the raw ESC byte (\x1b).
			h.terminalInput("");
			const result = await pending;
			const text = result.content?.[0]?.text ?? "";
			assert.ok(text.includes("remains active"), `continue-working report: ${text}`);
			assert.notEqual(result.terminate, true, "continue working must not terminate the turn");
			const goal = parseGoalFile(path.join(f.cwd, ".pi", "goals", activeGoalFiles(f.cwd)[0]!));
			assert.equal(goal?.status, "active", "goal stays active after continue working");
			const events = ledgerEvents(f.cwd);
			assert.equal(events.some((e) => e.type === "audit_skipped"), false, "no skip event for continue working");
			assert.equal(events.some((e) => e.type === "goal_completed"), false, "goal not completed");
		} finally {
			f.cleanup();
		}
	});
});

describe("completion transaction hardening (follow-up Stage 3)", () => {
	it("completion commit write failure never reports success and never clears focus", skipWhenRoot, async () => {
		const f = fixture();
		const goalsDir = path.join(f.cwd, ".pi", "goals");
		try {
			// Pre-create the ledger file so its fallback append path works even
			// when the goals directory is read-only (append needs write on the
			// file, not the directory; the atomic goal write needs a writable
			// directory and therefore fails).
			writeFileSync(goalLedgerPath({ cwd: f.cwd }), "", "utf8");
			const h = createHarness({
				cwd: f.cwd, sessionEntries: f.sessionEntries,
				runCompletionAuditor: async () =>
					({ approved: true, disapproved: false, output: "All good\n<approved/>", model: "fixture" }),
			});
			await start(h);
			// Block the authoritative active-file write (reads still work).
			chmodSync(goalsDir, 0o555);
			const update = h.tools.get("update_goal")!;
			const result = await (update.execute as any)("fail-write-1", { status: "complete" }, new AbortController().signal, undefined, h.ctx);
			const text = result.content?.[0]?.text ?? "";
			assert.ok(text.includes("Goal completion failed"), `failure report expected: ${text.slice(0, 120)}`);
			assert.ok(text.includes("not completed"), "must state the goal was not completed");
			assert.ok(!text.includes("Goal audit approved"), "no success report when the state mutation failed");
			assert.notEqual(result.terminate, true, "no termination request on failed completion");
			// The deferred archival at turn_end must not emit goal_completed.
			await h.handlers.get("turn_end")?.({ message: { role: "assistant", stopReason: "stop", usage: { input: 0, output: 0 } } }, h.ctx);
			const events = ledgerEvents(f.cwd);
			assert.equal(events.some((e) => e.type === "goal_completed"), false, "no goal_completed event");
			assert.ok(events.some((e) => e.type === "audit_result"), "audit itself ran and recorded its result");
			// The goal stays open and focused (get_goal still reports it, not complete).
			const get = h.tools.get("get_goal")!;
			const snapshot = await (get.execute as any)("g-1", {}, new AbortController().signal, undefined, h.ctx);
			const snapText = snapshot.content?.[0]?.text ?? "";
			assert.match(snapText, /Goal \S+: running/, `goal still open and active: ${snapText.slice(0, 100)}`);
		} finally {
			try { chmodSync(goalsDir, 0o755); } catch {}
			f.cleanup();
		}
	});

	it("deferred-archive failure at turn_end keeps the goal open and records no goal_completed", async () => {
		const f = fixture();
		try {
			const h = createHarness({
				cwd: f.cwd, sessionEntries: f.sessionEntries,
				runCompletionAuditor: async () =>
					({ approved: true, disapproved: false, output: "All good\n<approved/>", model: "fixture" }),
			});
			await start(h);
			const update = h.tools.get("update_goal")!;
			const result = await (update.execute as any)("fail-arch-1", { status: "complete" }, new AbortController().signal, undefined, h.ctx);
			const text = result.content?.[0]?.text ?? "";
			assert.ok(text.includes("Goal audit approved"), "commit itself succeeded");
			// Sabotage the archived directory: the deferred archive write fails.
			const archivedDir = path.join(f.cwd, ".pi", "goals", "archived");
			rmSync(archivedDir, { recursive: true, force: true });
			writeFileSync(archivedDir, "not a directory", "utf8");
			await h.handlers.get("turn_end")?.({ message: { role: "assistant", stopReason: "stop", usage: { input: 0, output: 0 } } }, h.ctx);
			const events = ledgerEvents(f.cwd);
			assert.equal(events.some((e) => e.type === "goal_completed"), false, "no goal_completed when archive failed");
			assert.ok(h.notices.some((n) => n.message.includes("Failed to archive completed goal")), "archive failure is observable");
			assert.equal(activeGoalFiles(f.cwd).length, 1, "goal file stays in the active pool");
			// The active file still holds the completed goal (not archived).
			const remaining = parseGoalFile(path.join(f.cwd, ".pi", "goals", activeGoalFiles(f.cwd)[0]!));
			assert.equal(remaining?.status, "complete", "completed goal remains on disk, unarchived");
		} finally {
			f.cleanup();
		}
	});
});

describe("capability parity (follow-up Stage 5.1-C)", () => {
	it("update_goal(paused) pauses an active goal immediately with an agent ledger event", async () => {
		const f = fixture();
		try {
			const h = createHarness({ cwd: f.cwd, sessionEntries: f.sessionEntries });
			await start(h);
			const update = h.tools.get("update_goal")!;
			const result = await (update.execute as any)("u-1", { status: "paused", reason: "Waiting on credentials", suggested_action: "Set FOO_API_KEY" }, new AbortController().signal, undefined, h.ctx);
			assert.match(result.content[0].text, /Goal paused by the agent/);
			assert.equal(result.terminate, true, "continuation stops");
			const files = activeGoalFiles(f.cwd);
			assert.equal(files.length, 1, "goal file remains open");
			const goal = parseGoalFile(path.join(f.cwd, ".pi", "goals", files[0]!))!;
			assert.equal(goal.status, "paused");
			assert.equal(goal.autoContinue, false);
			assert.equal(goal.stopReason, "agent");
			assert.equal(goal.pauseReason, "Waiting on credentials");
			assert.equal(goal.pauseSuggestedAction, "Set FOO_API_KEY");
			const paused = ledgerEvents(f.cwd).filter((e) => e.type === "goal_paused");
			assert.equal(paused.length, 1, "exactly one goal_paused event");
			assert.equal((paused[0] as any).source, "agent", "source agent recorded");
			assert.equal((paused[0] as any).reason, "Waiting on credentials");
		} finally {
			f.cleanup();
		}
	});

	it("update_goal(paused) requires a reason and applies only to an active goal", async () => {
		const f = fixture();
		try {
			const h = createHarness({ cwd: f.cwd, sessionEntries: f.sessionEntries });
			await start(h);
			const update = h.tools.get("update_goal")!;
			const noReason = await (update.execute as any)("u-2", { status: "paused" }, new AbortController().signal, undefined, h.ctx);
			assert.match(noReason.content[0].text, /requires a "reason"/);
			assert.equal(activeGoalFiles(f.cwd).length, 1, "goal unchanged");
			await (update.execute as any)("u-3", { status: "paused", reason: "First pause" }, new AbortController().signal, undefined, h.ctx);
			const second = await (update.execute as any)("u-4", { status: "paused", reason: "Again" }, new AbortController().signal, undefined, h.ctx);
			assert.match(second.content[0].text, /applies only to an active goal/);
		} finally {
			f.cleanup();
		}
	});

	it("completion_summary reaches the auditor as an untrusted claim and cannot approve", async () => {
		const f = fixture();
		let auditArgs: any = null;
		try {
			const h = createHarness({ cwd: f.cwd, sessionEntries: f.sessionEntries, runCompletionAuditor: async (args: any) => {
				auditArgs = args;
				return { approved: false, disapproved: true, output: "Still missing evidence\n<disapproved/>", model: "fixture" };
			} });
			await start(h);
			const update = h.tools.get("update_goal")!;
			const result = await (update.execute as any)("u-5", { status: "complete", completion_summary: "All tests pass and the docs are updated." }, new AbortController().signal, undefined, h.ctx);
			assert.equal(auditArgs.completionSummary, "All tests pass and the docs are updated.", "claim reaches the auditor");
			assert.equal(auditArgs.verificationSummary, undefined, "still no verification-summary paperwork");
			assert.match(result.content[0].text, /Goal audit rejected/, "a claim cannot override a disapproval");
			assert.equal(activeGoalFiles(f.cwd).length, 1, "goal stays open");
		} finally {
			f.cleanup();
		}
	});

	it("prompt guidance directs abandonment to /goal-clear and requirement changes to /goal-tweak", () => {
		const source = readFileSync("extensions/goal-core-tools.ts", "utf8");
		const policy = readFileSync("extensions/prompts/goal-prompts.ts", "utf8");
		assert.ok(policy.includes("/goal-clear"), "abandonment guidance directs the user command");
		assert.ok(policy.includes("/goal-tweak"), "requirement changes stay user-started");
		assert.ok(!source.includes('name: "propose_goal_tweak"'), "no steady-state propose_goal_tweak tool");
		assert.ok(!source.includes('name: "abort_goal"'), "no abort_goal tool");
	});
});
