import assert from "node:assert/strict";
import fsDefault, * as fs from "node:fs";
import { syncBuiltinESMExports } from "node:module";
import * as os from "node:os";
import * as path from "node:path";
import { randomUUID } from "node:crypto";
import { afterEach, describe, it } from "node:test";
import {
	createNativeSupervisorChannel,
	ensureSupervisorChannelDir,
	registerNativeSupervisorClient,
	resolveSupervisorChannelDir,
} from "../../src/intercom/native-supervisor-channel.ts";
import { SUPERVISOR_REPLY_ENTRY_TYPE, SUPERVISOR_REQUEST_MESSAGE_TYPE } from "../../src/intercom/supervisor-ui.ts";
import { recordSessionReplacement } from "../../src/shared/session-succession.ts";
import { currentCompletionOwnerId } from "../../src/shared/completion-owner.ts";
import { ASYNC_DIR, INTERCOM_DETACH_REQUEST_EVENT, type SubagentState } from "../../src/shared/types.ts";

const createdChannels: string[] = [];

function makeState(sessionId: string | null, ctx: unknown): SubagentState {
	return {
		baseCwd: process.cwd(),
		currentSessionId: sessionId,
		supervisorOwnerSessionId: (ctx as SubagentState["lastUiContext"])?.sessionManager.getSessionId() ?? null,
		asyncJobs: new Map(),
		foregroundControls: new Map(),
		lastForegroundControlId: null,
		cleanupTimers: new Map(),
		lastUiContext: ctx as SubagentState["lastUiContext"],
		poller: null,
		completionSeen: new Map(),
		watcher: null,
		watcherRestartTimer: null,
		resultFileCoalescer: { schedule: () => false, clear: () => {} },
	};
}

function writeRequest(input: { sessionId: string; runId: string; agent?: string; index?: number; message?: string; reason?: "need_decision" | "interview_request" | "progress_update"; childTarget?: string; interview?: unknown; createdAt?: number; expiresAt?: number }): string {
	const agent = input.agent ?? "worker";
	const index = input.index ?? 0;
	const channelDir = resolveSupervisorChannelDir(input.runId, agent, index);
	createdChannels.push(channelDir);
	ensureSupervisorChannelDir(channelDir);
	const requestId = randomUUID();
	fs.writeFileSync(path.join(channelDir, "requests", `${requestId}.json`), JSON.stringify({
		type: "subagent.supervisor.request",
		id: requestId,
		createdAt: input.createdAt ?? Date.now(),
		...(input.expiresAt !== undefined ? { expiresAt: input.expiresAt } : {}),
		reason: input.reason ?? "need_decision",
		message: input.message ?? "Need a decision",
		expectsReply: input.reason !== "progress_update",
		orchestratorSessionId: input.sessionId,
		orchestratorTarget: "shared-name",
		runId: input.runId,
		agent,
		childIndex: index,
		...(input.childTarget ? { childTarget: input.childTarget } : {}),
		...(input.interview !== undefined ? { interview: input.interview } : {}),
	}, null, "\t"));
	return requestId;
}

function requestFile(runId: string, requestId: string, agent = "worker", index = 0): string {
	return path.join(resolveSupervisorChannelDir(runId, agent, index), "requests", `${requestId}.json`);
}

function replyFile(runId: string, requestId: string, agent = "worker", index = 0): string {
	return path.join(resolveSupervisorChannelDir(runId, agent, index), "replies", `${requestId}.json`);
}

function makeEmptyChannel(runId: string): string {
	const channelDir = resolveSupervisorChannelDir(runId, "worker", 0);
	createdChannels.push(channelDir);
	ensureSupervisorChannelDir(channelDir);
	return channelDir;
}

function ageChannel(channelDir: string, ageMs: number): void {
	const timestamp = new Date(Date.now() - ageMs);
	for (const dir of [path.join(channelDir, "requests"), path.join(channelDir, "replies"), channelDir]) {
		fs.utimesSync(dir, timestamp, timestamp);
	}
}

async function waitForCondition(condition: () => boolean, description: string): Promise<void> {
	const deadline = Date.now() + 1000;
	while (!condition()) {
		if (Date.now() > deadline) assert.fail(`Timed out waiting for ${description}`);
		await new Promise((resolve) => setTimeout(resolve, 10));
	}
}

afterEach(() => {
	delete process.env.PI_INTERCOM_ASK_TIMEOUT_MS;
	for (const channel of createdChannels.splice(0)) fs.rmSync(channel, { recursive: true, force: true });
});

describe("native supervisor channel", () => {
	it("keeps blocked-child progress silent and leaves foreign-owner asks untouched", () => {
		const owner = randomUUID();
		const runId = randomUUID();
		const foreignId = randomUUID();
		const progress = writeRequest({ sessionId: owner, runId, reason: "progress_update" });
		const foreign = writeRequest({ sessionId: "other-owner", runId: foreignId });
		const state = makeState(owner, { sessionManager: { getSessionId: () => owner } });
		state.blockingWorkflowChildren = new Set([runId, foreignId]);
		const channel = createNativeSupervisorChannel({
			getAllTools: () => [], registerTool() {}, sendMessage() { assert.fail("neither request should wake the parent"); },
		} as never, state);
		try {
			channel.start();
			assert.equal(fs.existsSync(requestFile(runId, progress)), false);
			assert.equal(fs.existsSync(replyFile(runId, progress)), false);
			assert.equal(fs.existsSync(requestFile(foreignId, foreign)), true);
			assert.equal(fs.existsSync(replyFile(foreignId, foreign)), false);
		} finally {
			channel.dispose();
		}
	});

	for (const reason of ["need_decision", "interview_request"] as const) {
		it(`fails an unanswerable ${reason} ask from an awaited background workflow child`, async () => {
			const runId = `run-${randomUUID()}`;
			const owner = `session-${randomUUID()}`;
			const channelDir = resolveSupervisorChannelDir(runId, "worker", 0);
			createdChannels.push(channelDir);
			const tools = new Map<string, { execute(id: string, params: unknown, signal?: AbortSignal): Promise<unknown> }>();
			const notices: unknown[] = [];
			const pi = {
				getAllTools: () => [...tools.keys()].map(name => ({ name })),
				registerTool: (tool: { name: string; execute(id: string, params: unknown, signal?: AbortSignal): Promise<unknown> }) => tools.set(tool.name, tool),
				sendMessage: (message: unknown) => { notices.push(message); return false; },
			};
			const state = makeState(owner, { sessionManager: { getSessionId: () => owner } });
			state.blockingWorkflowChildren = new Set([runId]);
			registerNativeSupervisorClient(pi as never, { channelDir, runId, agent: "worker", childIndex: 0, orchestratorSessionId: owner });
			const channel = createNativeSupervisorChannel(pi as never, state);
			const controller = new AbortController();
			const timeout = setTimeout(() => controller.abort(), 2_000);
			const ask = tools.get("contact_supervisor")!.execute("ask", { reason, message: "Choose an approach", ...(reason === "interview_request" ? { interview: { questions: [] } } : {}) }, controller.signal);
			try {
				channel.start();
				await assert.rejects(ask, /parent is blocked.*async:false.*Report the blocker.*async:true/s);
				assert.equal(channel.pending.size, 0);
				assert.deepEqual(notices, [], "do not queue a question that will be unanswerable when the parent sees it");
				assert.deepEqual(fs.readdirSync(path.join(channelDir, "requests")), []);
			} finally {
				clearTimeout(timeout);
				controller.abort();
				await ask.catch(() => {});
				channel.dispose();
			}
		});
	}

	for (const platform of ["darwin", "win32", "linux"] as const) {
		it(`bounds coordinator polling to owned channels and stops when idle (${platform})`, async () => {
			const owner = randomUUID();
			const runId = randomUUID();
			const requestId = writeRequest({ sessionId: owner, runId });
			const ownDir = resolveSupervisorChannelDir(runId, "worker", 0);
			// Even a request with the same owner is not scanned unless its run is registered.
			for (let i = 0; i < 100; i++) writeRequest({ sessionId: owner, runId: randomUUID() });
			let dirs: string[] = [];
			let tick: (() => void) | undefined;
			const tools = new Map<string, { execute(id: string, params: unknown): Promise<unknown> }>();
			const notices: unknown[] = [];
			const ctx = { sessionManager: { getSessionId: () => owner } };
			const channel = createNativeSupervisorChannel({
				getAllTools: () => [...tools.keys()].map(name => ({ name })),
				registerTool: (tool: { name: string; execute: (id: string, params: unknown) => Promise<unknown> }) => tools.set(tool.name, tool),
				sendMessage: (message: unknown) => notices.push(message),
			} as never, makeState(owner, ctx), {
				platform, getChannelDirs: () => ({ dirs }),
				watch: (() => { throw new Error("scoped coordinator must not watch the global root"); }) as never,
				timers: {
					setInterval: ((handler: () => void) => { tick = handler; return { unref() {} } as NodeJS.Timeout; }) as typeof setInterval,
					clearInterval: (() => { tick = undefined; }) as typeof clearInterval,
					setImmediate, clearImmediate,
				},
			});
			const readdir = fsDefault.readdirSync;
			let scans = 0;
			fsDefault.readdirSync = ((dir: fs.PathLike, options: unknown) => {
				assert.equal(String(dir), path.join(ownDir, "requests"), "coordinators must not scan unrelated retained channels");
				scans++;
				return (readdir as (dir: fs.PathLike, options: unknown) => unknown)(dir, options);
			}) as typeof fsDefault.readdirSync;
			syncBuiltinESMExports();
			try {
				channel.start();
				assert.equal(tick, undefined, "idle coordinator has no polling timer");
				assert.equal(scans, 0);
				dirs = [ownDir];
				channel.activateTransport();
				assert.equal(scans, 1, "one owned mailbox read regardless of 100 retained foreign channels");
				assert.equal(notices.length, 1);
				assert.equal(typeof tick, "function");
				await channel.runParentAction({ action: "reply", replyTo: requestId, message: "Proceed" });
				dirs = [];
				const scansBeforeIdle = scans;
				tick!();
				assert.equal(tick, undefined, "finished descendants stop polling on every platform");
				assert.equal(scans, scansBeforeIdle);
			} finally {
				channel.dispose();
				fsDefault.readdirSync = readdir;
				syncBuiltinESMExports();
			}
		});
	}

	it("retires only polled mailbox snapshots, never demand probes", () => {
		const owner = randomUUID();
		const runId = randomUUID();
		const dir = resolveSupervisorChannelDir(runId, "worker", 0);
		const state = makeState(owner, { sessionManager: { getSessionId: () => owner } });
		let live = false;
		let retiring = false;
		let drained = 0;
		let tick: (() => void) | undefined;
		const notices: unknown[] = [];
		const channel = createNativeSupervisorChannel({
			getAllTools: () => [], registerTool() {},
			sendMessage(message: unknown) { notices.push(message); live = false; retiring = true; },
		} as never, state, {
			platform: "darwin",
			getChannelDirs: () => ({
				dirs: live || retiring ? [dir] : [],
				...(retiring ? { retire: () => {
					assert.equal(notices.length, 1, "delivery precedes retirement");
					drained++;
					retiring = false;
				} } : {}),
			}),
			timers: {
				setInterval: ((handler: () => void) => { tick = handler; return { unref() {} } as NodeJS.Timeout; }) as typeof setInterval,
				clearInterval: (() => { tick = undefined; }) as typeof clearInterval,
				setImmediate, clearImmediate,
			},
		});
		try {
			channel.start();
			live = true;
			const requestId = writeRequest({ sessionId: owner, runId });
			channel.activateTransport();
			assert.equal(drained, 0, "demand observes completion without retiring its unpolled snapshot");
			assert.equal(notices.length, 1);
			assert.equal(typeof tick, "function", "demand keeps the final drain scheduled");
			fs.writeFileSync(replyFile(runId, requestId), JSON.stringify({
				type: "subagent.supervisor.reply",
				requestId,
				createdAt: Date.now(),
				message: "Approved",
			}), "utf-8");
			tick!();
			assert.equal(tick, undefined);
			assert.equal(drained, 1);
		} finally { channel.dispose(); }
	});

	it("delivers requests only to the exact current session id and wakes the parent", () => {
		const currentSessionId = `session-${randomUUID()}`;
		const otherSessionId = `session-${randomUUID()}`;
		const matchingId = writeRequest({ sessionId: currentSessionId, runId: `run-${randomUUID()}` });
		const otherId = writeRequest({ sessionId: otherSessionId, runId: `run-${randomUUID()}` });
		const sent: Array<{
			message: { content?: string; details?: { id?: string } };
			options?: { triggerTurn?: boolean };
		}> = [];
		const registeredTools: Array<{ name: string; parameters: { properties: { action: unknown } } }> = [];
		const ctx = {
			cwd: process.cwd(),
			hasUI: false,
			sessionManager: {
				getSessionId: () => currentSessionId,
				getSessionFile: () => null,
				getEntries: () => [],
			},
		};
		const pi = {
			getAllTools: () => [],
			registerTool: (tool: typeof registeredTools[number]) => { registeredTools.push(tool); },
			sendMessage: (
				message: { content?: string; details?: { id?: string } },
				options?: { triggerTurn?: boolean },
			) => { sent.push({ message, options }); },
			getSessionName: () => "shared-name",
		};
		const channel = createNativeSupervisorChannel(pi as never, makeState(currentSessionId, ctx), { platform: "darwin" });

		assert.deepEqual(registeredTools, []);
		channel.start();
		assert.equal(channel.hasPendingRequests(), true, "fresh owned reply-bearing request is a drain barrier");
		channel.dispose();

		assert.deepEqual(registeredTools, [], "replies go through the subagent tool's reply action");
		assert.deepEqual(sent.map(({ message }) => message.details?.id), [matchingId]);
		assert.deepEqual(sent[0]?.options, { triggerTurn: true });
		assert.equal(channel.pending.has(matchingId), false, "disposed channel clears pending requests");
		assert.equal(channel.hasPendingRequests(), false, "disposed and foreign requests are not barriers");
		assert.equal(sent.some(({ message }) => message.details?.id === otherId), false);
	});

	it("does not inject progress updates into the parent session or wake a turn", () => {
		const currentSessionId = `session-${randomUUID()}`;
		const progressRunId = `run-${randomUUID()}`;
		const progressId = writeRequest({ sessionId: currentSessionId, runId: progressRunId, reason: "progress_update" });
		const sent: Array<{ message: { details?: { id?: string } }; options?: { triggerTurn?: boolean } }> = [];
		const ctx = {
			cwd: process.cwd(),
			hasUI: false,
			sessionManager: {
				getSessionId: () => currentSessionId,
				getSessionFile: () => null,
				getEntries: () => [],
			},
		};
		const pi = {
			getAllTools: () => [],
			registerTool: () => {},
			sendMessage: (
				message: { details?: { id?: string } },
				options?: { triggerTurn?: boolean },
			) => { sent.push({ message, options }); },
			getSessionName: () => "shared-name",
		};
		const channel = createNativeSupervisorChannel(pi as never, makeState(currentSessionId, ctx), { platform: "darwin" });

		channel.start();
		channel.hasPendingRequests();
		channel.dispose();

		assert.equal(sent.length, 0);
		assert.equal(channel.pending.has(progressId), false);
		assert.equal(fs.existsSync(requestFile(progressRunId, progressId)), false);
	});

	it("uses polling instead of native watchers on Windows", () => {
		const currentSessionId = `session-${randomUUID()}`;
		const requestId = writeRequest({ sessionId: currentSessionId, runId: `run-${randomUUID()}` });
		const sent: Array<{ details?: { id?: string } }> = [];
		const ctx = {
			cwd: process.cwd(),
			hasUI: false,
			sessionManager: {
				getSessionId: () => currentSessionId,
				getSessionFile: () => null,
				getEntries: () => [],
			},
		};
		const pi = {
			getAllTools: () => [],
			registerTool: () => {},
			sendMessage: (message: { details?: { id?: string } }) => { sent.push(message); },
			getSessionName: () => "shared-name",
		};
		let watchCalls = 0;
		const channel = createNativeSupervisorChannel(pi as never, makeState(currentSessionId, ctx), {
			platform: "win32",
			watch: (() => {
				watchCalls += 1;
				throw new Error("Windows supervisor channel must not call fs.watch.");
			}) as never,
		});

		channel.start();
		channel.dispose();

		assert.equal(watchCalls, 0);
		assert.deepEqual(sent.map((message) => message.details?.id), [requestId]);
	});

	it("keeps Windows polling alive when a supervisor directory scan returns UNKNOWN", () => {
		const currentSessionId = `session-${randomUUID()}`;
		const runId = `run-${randomUUID()}`;
		const sent: Array<{ details?: { id?: string } }> = [];
		let tick: (() => void) | undefined;
		const ctx = {
			cwd: process.cwd(), hasUI: false,
			sessionManager: { getSessionId: () => currentSessionId, getSessionFile: () => null, getEntries: () => [] },
		};
		const state = makeState(currentSessionId, ctx);
		state.foregroundControls.set("run-a", { runId: "run-a" } as never);
		const channel = createNativeSupervisorChannel({
			getAllTools: () => [], registerTool: () => {},
			sendMessage: (message: { details?: { id?: string } }) => { sent.push(message); },
			getSessionName: () => "shared-name",
		} as never, state, {
			platform: "win32",
			timers: {
				setInterval: ((callback: () => void) => { tick = callback; return 1; }) as never,
				clearInterval: (() => { tick = undefined; }) as never,
				setImmediate, clearImmediate,
			},
		});
		const readdir = fsDefault.readdirSync;

		try {
			channel.start();
			assert.equal(typeof tick, "function");
			let injectUnknown = true;
			fsDefault.readdirSync = ((dir: fs.PathLike, options?: unknown) => {
				if (injectUnknown) {
					injectUnknown = false;
					throw Object.assign(new Error("directory disappeared"), { code: "UNKNOWN" });
				}
				return (readdir as (dir: fs.PathLike, options?: unknown) => unknown)(dir, options);
			}) as typeof fsDefault.readdirSync;
			syncBuiltinESMExports();

			assert.doesNotThrow(() => tick!());
			const requestId = writeRequest({ sessionId: currentSessionId, runId });
			tick!();
			assert.deepEqual(sent.map((message) => message.details?.id), [requestId]);
		} finally {
			channel.dispose();
			fsDefault.readdirSync = readdir;
			syncBuiltinESMExports();
		}
	});

	it("keeps the darwin poller alive when a supervisor directory scan fails, and reports the failure to demand callers", async () => {
		const currentSessionId = `session-${randomUUID()}`;
		const runId = `run-${randomUUID()}`;
		const sent: Array<{ details?: { id?: string } }> = [];
		const tools = new Map<string, { execute(id: string, params: unknown): Promise<unknown> }>();
		let tick: (() => void) | undefined;
		const ctx = {
			cwd: process.cwd(), hasUI: false,
			sessionManager: { getSessionId: () => currentSessionId, getSessionFile: () => null, getEntries: () => [] },
		};
		const state = makeState(currentSessionId, ctx);
		state.foregroundControls.set("run-a", { runId: "run-a" } as never);
		const channel = createNativeSupervisorChannel({
			getAllTools: () => [...tools.values()],
			registerTool: (tool: { name: string; execute(id: string, params: unknown): Promise<unknown> }) => { tools.set(tool.name, tool); },
			sendMessage: (message: { details?: { id?: string } }) => { sent.push(message); },
			getSessionName: () => "shared-name",
		} as never, state, {
			platform: "darwin",
			timers: {
				setInterval: ((callback: () => void) => { tick = callback; return 1; }) as never,
				clearInterval: (() => { tick = undefined; }) as never,
				setImmediate, clearImmediate,
			},
		});
		const readdir = fsDefault.readdirSync;
		const consoleError = console.error;
		const consoleWarn = console.warn;
		const reported: string[] = [];
		const errors: string[] = [];

		try {
			channel.start();
			channel.activateTransport();
			assert.equal(typeof tick, "function", "darwin transport demand starts the 500ms poller");
			let failScans = true;
			fsDefault.readdirSync = ((dir: fs.PathLike, options?: unknown) => {
				if (failScans) throw Object.assign(new Error("ENFILE: file table overflow, scandir '/tmp/pisub-repro/temp/supervisor-channels'"), { code: "ENFILE" });
				return (readdir as (dir: fs.PathLike, options?: unknown) => unknown)(dir, options);
			}) as typeof fsDefault.readdirSync;
			syncBuiltinESMExports();
			// Without a UI the session warning goes to console.warn.
			console.warn = (...args: unknown[]) => { reported.push(args.map((arg) => String(arg)).join(" ")); };
			console.error = (...args: unknown[]) => { errors.push(args.map((arg) => String(arg)).join(" ")); };

			assert.doesNotThrow(() => tick!(), "a failed scan must not reach Pi's uncaughtException handler");
			assert.equal(reported.length, 1, "the first scan failure is reported");
			assert.match(reported[0]!, /ENFILE/);
			assert.doesNotThrow(() => tick!(), "the next poll survives the same failure");
			assert.equal(reported.length, 1, "repeated scan failures are reported once");
			assert.deepEqual(errors, []);

			// A failed scan is not "no pending requests" for callers whose answer a model or a drain decision reads.
			assert.throws(() => channel.hasPendingRequests(), /ENFILE/);
			await assert.rejects(channel.runParentAction({ action: "pending" }), /ENFILE/);

			failScans = false;
			const requestId = writeRequest({ sessionId: currentSessionId, runId });
			assert.doesNotThrow(() => tick!());
			assert.deepEqual(sent.map((message) => message.details?.id), [requestId]);
		} finally {
			console.error = consoleError;
			console.warn = consoleWarn;
			channel.dispose();
			fsDefault.readdirSync = readdir;
			syncBuiltinESMExports();
		}
	});

	it("stops idle Windows polling and restarts it on transport demand", () => {
		const currentSessionId = `session-${randomUUID()}`;
		const state = makeState(currentSessionId, { sessionManager: { getSessionId: () => currentSessionId } });
		let tick: (() => void) | undefined;
		const channel = createNativeSupervisorChannel({ getAllTools: () => [], registerTool: () => {}, sendMessage: () => {} } as never, state, {
			platform: "win32",
			timers: {
				setInterval: ((callback: () => void) => { tick = callback; return 1; }) as never,
				clearInterval: (() => { tick = undefined; }) as never,
				setImmediate, clearImmediate,
			},
		});
		try {
			channel.start();
			tick!();
			assert.equal(tick, undefined, "an idle parent stops polling");
			state.foregroundControls.set("run-a", { runId: "run-a" } as never);
			channel.activateTransport();
			assert.equal(typeof tick, "function", "demand restarts polling");
		} finally { channel.dispose(); }
	});

	it("does not classify UNKNOWN as a missing supervisor directory off Windows", () => {
		const currentSessionId = `session-${randomUUID()}`;
		const ctx = { sessionManager: { getSessionId: () => currentSessionId } };
		const channel = createNativeSupervisorChannel({
			getAllTools: () => [], registerTool: () => {}, sendMessage: () => {},
		} as never, makeState(currentSessionId, ctx), { platform: "linux" });
		const readdir = fsDefault.readdirSync;

		try {
			fsDefault.readdirSync = (() => {
				throw Object.assign(new Error("unexpected scan failure"), { code: "UNKNOWN" });
			}) as typeof fsDefault.readdirSync;
			syncBuiltinESMExports();

			assert.throws(
				() => channel.findPendingAsks({ runId: "run", agent: "worker", childIndex: 0 }),
				(error: NodeJS.ErrnoException) => error.code === "UNKNOWN",
			);
		} finally {
			channel.dispose();
			fsDefault.readdirSync = readdir;
			syncBuiltinESMExports();
		}
	});

	it("registers idle Darwin sessions without native watchers or polling", () => {
		const currentSessionId = `session-${randomUUID()}`;
		const ctx = {
			cwd: process.cwd(),
			hasUI: false,
			sessionManager: {
				getSessionId: () => currentSessionId,
				getSessionFile: () => null,
				getEntries: () => [],
			},
		};
		const pi = {
			getAllTools: () => [],
			registerTool: () => {},
			sendMessage: () => {},
			getSessionName: () => "shared-name",
		};
		let watchCalls = 0;
		const intervals: number[] = [];
		const channel = createNativeSupervisorChannel(pi as never, makeState(currentSessionId, ctx), {
			platform: "darwin",
			watch: (() => { watchCalls += 1; throw new Error("Darwin must not call fs.watch."); }) as never,
			timers: {
				setInterval: ((_handler: () => void, delay?: number) => { intervals.push(delay ?? 0); return { unref() {} } as NodeJS.Timeout; }) as typeof setInterval,
				clearInterval: (() => {}) as typeof clearInterval,
				setImmediate,
				clearImmediate,
			},
		});

		channel.start();
		channel.dispose();

		assert.equal(watchCalls, 0);
		assert.deepEqual(intervals, []);
	});

	it("activates Darwin supervisor polling only while child work is live", () => {
		const currentSessionId = `session-${randomUUID()}`;
		const ctx = {
			cwd: process.cwd(),
			hasUI: false,
			sessionManager: {
				getSessionId: () => currentSessionId,
				getSessionFile: () => null,
				getEntries: () => [],
			},
		};
		const pi = {
			getAllTools: () => [],
			registerTool: () => {},
			sendMessage: () => {},
			getSessionName: () => "shared-name",
		};
		const state = makeState(currentSessionId, ctx);
		state.foregroundControls.set("run-a", { runId: "run-a", startedAt: Date.now(), updatedAt: Date.now(), activeChildren: new Map(), schedulingOwners: 1 } as never);
		const intervals: number[] = [];
		const channel = createNativeSupervisorChannel(pi as never, state, {
			platform: "darwin",
			watch: (() => { throw new Error("Darwin must not call fs.watch."); }) as never,
			timers: {
				setInterval: ((_handler: () => void, delay?: number) => { intervals.push(delay ?? 0); return { unref() {} } as NodeJS.Timeout; }) as typeof setInterval,
				clearInterval: (() => {}) as typeof clearInterval,
				setImmediate,
				clearImmediate,
			},
		});

		channel.start();
		channel.activateTransport();
		channel.dispose();

		assert.deepEqual(intervals, [250]);
	});

	it("delivers requests written under an existing request directory by watch event", async () => {
		const currentSessionId = `session-${randomUUID()}`;
		const runId = `run-${randomUUID()}`;
		makeEmptyChannel(runId);
		const sent: Array<{ details?: { id?: string } }> = [];
		const ctx = {
			cwd: process.cwd(),
			hasUI: false,
			sessionManager: {
				getSessionId: () => currentSessionId,
				getSessionFile: () => null,
				getEntries: () => [],
			},
		};
		const pi = {
			getAllTools: () => [],
			registerTool: () => {},
			sendMessage: (message: { details?: { id?: string } }) => { sent.push(message); },
			getSessionName: () => "shared-name",
		};
		const watchListeners: fs.WatchListener<string>[] = [];
		const channel = createNativeSupervisorChannel(pi as never, makeState(currentSessionId, ctx), {
			platform: "linux",
			watch: ((_filename: fs.PathLike, listener: fs.WatchListener<string>) => {
				watchListeners.push(listener);
				return { on: () => {}, close: () => {}, unref: () => {} } as unknown as fs.FSWatcher;
			}) as never,
		});

		try {
			channel.start();
			const requestId = writeRequest({ sessionId: currentSessionId, runId });
			for (const listener of watchListeners) listener("rename", `${requestId}.json`);
			await waitForCondition(() => sent.some((message) => message.details?.id === requestId), "supervisor request watch delivery");
		} finally {
			channel.dispose();
		}
	});

	it("prunes stale empty supervisor channel directories before polling", () => {
		const currentSessionId = `session-${randomUUID()}`;
		const staleEmptyChannel = makeEmptyChannel(`run-${randomUUID()}`);
		ageChannel(staleEmptyChannel, 2 * 60 * 1000);
		const sent: Array<{ details?: { id?: string } }> = [];
		const ctx = {
			cwd: process.cwd(),
			hasUI: false,
			sessionManager: {
				getSessionId: () => currentSessionId,
				getSessionFile: () => null,
				getEntries: () => [],
			},
		};
		const pi = {
			getAllTools: () => [],
			registerTool: () => {},
			sendMessage: (message: { details?: { id?: string } }) => { sent.push(message); },
			getSessionName: () => "shared-name",
		};
		const channel = createNativeSupervisorChannel(pi as never, makeState(currentSessionId, ctx));

		channel.start();
		channel.dispose();

		assert.equal(fs.existsSync(staleEmptyChannel), false);
		assert.deepEqual(sent, []);
	});

	it("preserves fresh empty and stale non-empty supervisor channel directories", () => {
		const currentSessionId = `session-${randomUUID()}`;
		const freshEmptyChannel = makeEmptyChannel(`run-${randomUUID()}`);
		const staleWithReply = makeEmptyChannel(`run-${randomUUID()}`);
		fs.writeFileSync(path.join(staleWithReply, "replies", "reply.json"), "{}");
		ageChannel(staleWithReply, 2 * 60 * 1000);
		const ctx = {
			cwd: process.cwd(),
			hasUI: false,
			sessionManager: {
				getSessionId: () => currentSessionId,
				getSessionFile: () => null,
				getEntries: () => [],
			},
		};
		const pi = {
			getAllTools: () => [],
			registerTool: () => {},
			sendMessage: () => {},
			getSessionName: () => "shared-name",
		};
		const channel = createNativeSupervisorChannel(pi as never, makeState(currentSessionId, ctx));

		channel.start();
		channel.dispose();

		assert.equal(fs.existsSync(freshEmptyChannel), true);
		assert.equal(fs.existsSync(staleWithReply), true);
	});

	it("emits foreground detach only after displaying a pending supervisor request", () => {
		const currentSessionId = `session-${randomUUID()}`;
		const runId = `run-${randomUUID()}`;
		const requestId = writeRequest({ sessionId: currentSessionId, runId, agent: "worker", index: 2 });
		const log: string[] = [];
		const emitted: Array<{ channel: string; payload: { requestId?: string; runId?: string; agent?: string; childIndex?: number } }> = [];
		const ctx = {
			cwd: process.cwd(),
			hasUI: false,
			sessionManager: {
				getSessionId: () => currentSessionId,
				getSessionFile: () => null,
				getEntries: () => [],
			},
		};
		const pi = {
			getAllTools: () => [],
			registerTool: () => {},
			sendMessage: () => { log.push("send"); },
			events: {
				emit: (channel: string, payload: { requestId?: string; runId?: string; agent?: string; childIndex?: number }) => {
					log.push("emit");
					emitted.push({ channel, payload });
				},
			},
			getSessionName: () => "shared-name",
		};
		const channel = createNativeSupervisorChannel(pi as never, makeState(currentSessionId, ctx));

		channel.start();
		try {
			assert.deepEqual(log, ["send", "emit"]);
			assert.deepEqual(emitted, [{
				channel: INTERCOM_DETACH_REQUEST_EVENT,
				payload: { requestId, runId, agent: "worker", childIndex: 2 },
			}]);
			assert.equal(channel.pending.has(requestId), true);
		} finally {
			channel.dispose();
		}
	});

	it("re-arms remembered foreground attention for each blocking supervisor request", async () => {
		const currentSessionId = `session-${randomUUID()}`;
		const runId = `run-${randomUUID()}`;
		const requestId = writeRequest({ sessionId: currentSessionId, runId });
		const registeredTools = new Map<string, { execute: (_id: string, params: { action: string; replyTo?: string; message?: string }) => Promise<unknown> }>();
		const ctx = {
			cwd: process.cwd(),
			hasUI: false,
			sessionManager: {
				getSessionId: () => currentSessionId,
				getSessionFile: () => null,
				getEntries: () => [],
			},
		};
		const state = makeState(currentSessionId, ctx);
		state.foregroundRuns = new Map([[runId, {
			runId,
			mode: "single",
			cwd: process.cwd(),
			sessionId: currentSessionId,
			updatedAt: 1,
			children: [{ agent: "worker", index: 0, status: "detached", updatedAt: 1 }],
		}]]);
		const pi = {
			getAllTools: () => [...registeredTools.keys()].map((name) => ({ name })),
			registerTool: (tool: { name: string; execute: (_id: string, params: { action: string; replyTo?: string; message?: string }) => Promise<unknown> }) => {
				registeredTools.set(tool.name, tool);
			},
			sendMessage: () => {},
			getSessionName: () => "shared-name",
		};
		const channel = createNativeSupervisorChannel(pi as never, state);

		try {
			channel.start();
			const child = state.foregroundRuns.get(runId)!.children[0]!;
			assert.equal(child.activityState, "needs_attention");
			assert.equal(child.currentTool, "contact_supervisor");

			await channel.runParentAction({
				action: "reply",
				replyTo: requestId,
				message: "Approved",
			});
			assert.equal(child.activityState, undefined);
			assert.equal(child.currentTool, undefined);
		} finally {
			channel.dispose();
		}
	});

	it("marks attention after detach when the reply has not landed yet", () => {
		const currentSessionId = `session-${randomUUID()}`;
		const runId = `run-${randomUUID()}`;
		writeRequest({ sessionId: currentSessionId, runId });
		const ctx = {
			cwd: process.cwd(),
			hasUI: false,
			sessionManager: {
				getSessionId: () => currentSessionId,
				getSessionFile: () => null,
				getEntries: () => [],
			},
		};
		const state = makeState(currentSessionId, ctx);
		const pi = {
			getAllTools: () => [],
			registerTool: () => {},
			sendMessage: () => {},
			events: {
				emit: () => {
					state.foregroundRuns = new Map([[runId, {
						runId,
						mode: "single",
						cwd: process.cwd(),
						sessionId: currentSessionId,
						updatedAt: Date.now(),
						children: [{ agent: "worker", index: 0, status: "detached", updatedAt: Date.now() }],
					}]]);
				},
			},
			getSessionName: () => "shared-name",
		};
		const channel = createNativeSupervisorChannel(pi as never, state);
		try {
			channel.start();
			const child = state.foregroundRuns.get(runId)!.children[0]!;
			assert.equal(child.activityState, "needs_attention");
			assert.equal(child.currentTool, "contact_supervisor");
		} finally {
			channel.dispose();
		}
	});

	it("skips restamping attention when the reply already landed during detach", async () => {
		const currentSessionId = `session-${randomUUID()}`;
		const runId = `run-${randomUUID()}`;
		const requestId = writeRequest({ sessionId: currentSessionId, runId });
		const registeredTools = new Map<string, { execute: (_id: string, params: { action: string; replyTo?: string; message?: string }) => Promise<unknown> }>();
		const ctx = {
			cwd: process.cwd(),
			hasUI: false,
			sessionManager: {
				getSessionId: () => currentSessionId,
				getSessionFile: () => null,
				getEntries: () => [],
			},
		};
		const state = makeState(currentSessionId, ctx);
		state.foregroundRuns = new Map();
		const pi = {
			getAllTools: () => [...registeredTools.keys()].map((name) => ({ name })),
			registerTool: (tool: { name: string; execute: (_id: string, params: { action: string; replyTo?: string; message?: string }) => Promise<unknown> }) => {
				registeredTools.set(tool.name, tool);
			},
			sendMessage: () => {
				void channel.runParentAction({
					action: "reply",
					replyTo: requestId,
					message: "Approved",
				});
			},
			events: {
				emit: () => {
					state.foregroundRuns = new Map([[runId, {
						runId,
						mode: "single",
						cwd: process.cwd(),
						sessionId: currentSessionId,
						updatedAt: Date.now(),
						children: [{ agent: "worker", index: 0, status: "detached", updatedAt: Date.now() }],
					}]]);
				},
			},
			getSessionName: () => "shared-name",
		};
		const channel = createNativeSupervisorChannel(pi as never, state);
		try {
			channel.start();
			const child = state.foregroundRuns.get(runId)!.children[0]!;
			assert.equal(child.status, "detached");
			assert.equal(child.activityState, undefined);
			assert.equal(child.currentTool, undefined);
			assert.equal(channel.pending.has(requestId), false);
		} finally {
			channel.dispose();
		}
	});

	it("clears remembered attention even when currentTool is not contact_supervisor", async () => {
		const currentSessionId = `session-${randomUUID()}`;
		const runId = `run-${randomUUID()}`;
		const requestId = writeRequest({ sessionId: currentSessionId, runId });
		const registeredTools = new Map<string, { execute: (_id: string, params: { action: string; replyTo?: string; message?: string }) => Promise<unknown> }>();
		const ctx = {
			cwd: process.cwd(),
			hasUI: false,
			sessionManager: {
				getSessionId: () => currentSessionId,
				getSessionFile: () => null,
				getEntries: () => [],
			},
		};
		const state = makeState(currentSessionId, ctx);
		state.foregroundRuns = new Map([[runId, {
			runId,
			mode: "single",
			cwd: process.cwd(),
			sessionId: currentSessionId,
			updatedAt: 1,
			children: [{ agent: "worker", index: 0, status: "detached", activityState: "needs_attention", currentTool: "edit", updatedAt: 1 }],
		}]]);
		const pi = {
			getAllTools: () => [...registeredTools.keys()].map((name) => ({ name })),
			registerTool: (tool: { name: string; execute: (_id: string, params: { action: string; replyTo?: string; message?: string }) => Promise<unknown> }) => {
				registeredTools.set(tool.name, tool);
			},
			sendMessage: () => {},
			getSessionName: () => "shared-name",
		};
		const channel = createNativeSupervisorChannel(pi as never, state);
		try {
			channel.start();
			state.foregroundRuns.get(runId)!.children[0]!.currentTool = "edit";
			await channel.runParentAction({
				action: "reply",
				replyTo: requestId,
				message: "Approved",
			});
			const child = state.foregroundRuns.get(runId)!.children[0]!;
			assert.equal(child.activityState, undefined);
			assert.equal(child.currentTool, undefined);
		} finally {
			channel.dispose();
		}
	});

	it("matches supervisor requests against the runtime session id instead of persisted session file path", () => {
		const currentSessionId = `session-${randomUUID()}`;
		const persistedSessionFile = path.join(os.tmpdir(), `${currentSessionId}.jsonl`);
		const matchingId = writeRequest({ sessionId: currentSessionId, runId: `run-${randomUUID()}` });
		const sent: Array<{ details?: { id?: string } }> = [];
		const ctx = {
			cwd: process.cwd(),
			hasUI: false,
			sessionManager: {
				getSessionId: () => currentSessionId,
				getSessionFile: () => persistedSessionFile,
				getEntries: () => [],
			},
		};
		const pi = {
			getAllTools: () => [],
			registerTool: () => {},
			sendMessage: (message: { details?: { id?: string } }) => { sent.push(message); },
			getSessionName: () => "shared-name",
		};
		const channel = createNativeSupervisorChannel(pi as never, makeState(persistedSessionFile, ctx));

		channel.start();
		channel.dispose();

		assert.deepEqual(sent.map((message) => message.details?.id), [matchingId]);
	});

	it("lets a session answer asks from async runs of the session it replaced in this process", async () => {
		const previousFile = path.join(os.tmpdir(), `previous-${randomUUID()}.jsonl`);
		const currentFile = path.join(os.tmpdir(), `current-${randomUUID()}.jsonl`);
		const currentRuntimeId = `session-${randomUUID()}`;
		const inheritedRun = `run-${randomUUID()}`;
		const foreignRun = `run-${randomUUID()}`;
		for (const [runId, sessionId] of [[inheritedRun, previousFile], [foreignRun, path.join(os.tmpdir(), `other-${randomUUID()}.jsonl`)]]) {
			fs.mkdirSync(path.join(ASYNC_DIR, runId), { recursive: true });
			fs.writeFileSync(path.join(ASYNC_DIR, runId, "status.json"), JSON.stringify({ runId, sessionId, mode: "single", state: "running", startedAt: Date.now() }));
			createdChannels.push(path.join(ASYNC_DIR, runId));
		}
		const inheritedAsk = writeRequest({ sessionId: `session-${randomUUID()}`, runId: inheritedRun, message: "Inherited question" });
		const foreignAsk = writeRequest({ sessionId: `session-${randomUUID()}`, runId: foreignRun, message: "Foreign question" });
		const unreadableRun = `run-${randomUUID()}`;
		fs.mkdirSync(path.join(ASYNC_DIR, unreadableRun), { recursive: true });
		fs.writeFileSync(path.join(ASYNC_DIR, unreadableRun, "status.json"), "{");
		createdChannels.push(path.join(ASYNC_DIR, unreadableRun));
		writeRequest({ sessionId: `session-${randomUUID()}`, runId: unreadableRun, message: "Unreadable question" });
		recordSessionReplacement(currentFile, previousFile);
		const tools = new Map<string, { execute: (_id: string, params: { action: string; replyTo?: string; message?: string }) => Promise<{ content: Array<{ text: string }> }> }>();
		const ctx = { cwd: process.cwd(), hasUI: false, sessionManager: { getSessionId: () => currentRuntimeId, getSessionFile: () => currentFile, getEntries: () => [] } };
		const pi = {
			getAllTools: () => [...tools.keys()].map((name) => ({ name })),
			registerTool: (tool: { name: string; execute: (_id: string, params: { action: string; replyTo?: string; message?: string }) => Promise<{ content: Array<{ text: string }> }> }) => { tools.set(tool.name, tool); },
			sendMessage: () => {},
			appendEntry: () => {},
			getSessionName: () => "shared-name",
		};
		const channel = createNativeSupervisorChannel(pi as never, makeState(currentFile, ctx));

		try {
			channel.start();
			const pending = await channel.runParentAction({ action: "pending" });
			assert.match(pending.content[0]!.text, /Inherited question/);
			assert.doesNotMatch(pending.content[0]!.text, /Foreign question/);
			assert.doesNotMatch(pending.content[0]!.text, /Unreadable question/);

			await channel.runParentAction({ action: "reply", replyTo: inheritedAsk, message: "Go ahead" });
			assert.equal((JSON.parse(fs.readFileSync(replyFile(inheritedRun, inheritedAsk), "utf-8")) as { message?: string }).message, "Go ahead");
			await assert.rejects(() => channel.runParentAction({ action: "reply", replyTo: foreignAsk, message: "No" }));
			assert.equal(fs.existsSync(replyFile(foreignRun, foreignAsk)), false);
		} finally {
			channel.dispose();
		}
	});

	it("leaves asks from runs a replaced session started after the switch to the Pi that reopened it", async () => {
		const previousFile = path.join(os.tmpdir(), `previous-${randomUUID()}.jsonl`);
		const currentFile = path.join(os.tmpdir(), `current-${randomUUID()}.jsonl`);
		recordSessionReplacement(currentFile, previousFile);
		const switchedAt = Date.now();
		const writeRun = (startedAt: number, completionOwnerId: string) => {
			const runId = `run-${randomUUID()}`;
			fs.mkdirSync(path.join(ASYNC_DIR, runId), { recursive: true });
			fs.writeFileSync(path.join(ASYNC_DIR, runId, "status.json"), JSON.stringify({ runId, sessionId: previousFile, completionOwnerId, mode: "single", state: "running", startedAt }));
			createdChannels.push(path.join(ASYNC_DIR, runId));
			return runId;
		};
		const beforeRun = writeRun(switchedAt - 60_000, "other-pi");
		const afterRun = writeRun(switchedAt + 60_000, "other-pi");
		// The runner records its own start, which can land after a switch that followed the launch.
		const launchedHereRun = writeRun(switchedAt + 60_000, currentCompletionOwnerId());
		const runtimeId = `session-${randomUUID()}`;
		const beforeAsk = writeRequest({ sessionId: runtimeId, runId: beforeRun });
		const afterAsk = writeRequest({ sessionId: runtimeId, runId: afterRun });
		const launchedHereAsk = writeRequest({ sessionId: runtimeId, runId: launchedHereRun });
		const tools = new Map<string, { execute: (_id: string, params: { action: string; replyTo?: string; message?: string }) => Promise<unknown> }>();
		const sent: Array<{ details?: { id?: string } }> = [];
		const ctx = { cwd: process.cwd(), hasUI: false, sessionManager: { getSessionId: () => `session-${randomUUID()}`, getSessionFile: () => currentFile, getEntries: () => [] } };
		const pi = {
			getAllTools: () => [...tools.keys()].map((name) => ({ name })),
			registerTool: (tool: { name: string; execute: (_id: string, params: { action: string; replyTo?: string; message?: string }) => Promise<unknown> }) => { tools.set(tool.name, tool); },
			sendMessage: (message: { details?: { id?: string } }) => { sent.push(message); },
			appendEntry: () => {},
			getSessionName: () => "shared-name",
		};
		const channel = createNativeSupervisorChannel(pi as never, makeState(currentFile, ctx));

		try {
			channel.start();
			assert.deepEqual(sent.map((message) => message.details?.id).sort(), [beforeAsk, launchedHereAsk].sort());
			await assert.rejects(() => channel.runParentAction({ action: "reply", replyTo: afterAsk, message: "Not mine" }));
			assert.equal(fs.existsSync(replyFile(afterRun, afterAsk)), false);
		} finally {
			channel.dispose();
		}
	});

	it("keeps an installed intercom tool and still exposes a native supervisor reply path", async () => {
		const currentSessionId = `session-${randomUUID()}`;
		const runId = `run-${randomUUID()}`;
		const requestId = writeRequest({ sessionId: currentSessionId, runId });
		const registeredTools = new Map<string, { execute: (_id: string, params: { action: string; replyTo?: string; message?: string }) => Promise<unknown> }>();
		const ctx = {
			cwd: process.cwd(),
			hasUI: false,
			sessionManager: {
				getSessionId: () => currentSessionId,
				getSessionFile: () => null,
				getEntries: () => [],
			},
		};
		const pi = {
			getAllTools: () => [{ name: "intercom" }, ...[...registeredTools.keys()].map((name) => ({ name }))],
			registerTool: (tool: { name: string; execute: (_id: string, params: { action: string; replyTo?: string; message?: string }) => Promise<unknown> }) => {
				registeredTools.set(tool.name, tool);
			},
			sendMessage: () => {},
			getSessionName: () => "shared-name",
		};
		const channel = createNativeSupervisorChannel(pi as never, makeState(currentSessionId, ctx));

		try {
			assert.deepEqual([...registeredTools.keys()], []);
			channel.start();

			assert.deepEqual([...registeredTools.keys()], []);
			await channel.runParentAction({ action: "reply", replyTo: requestId, message: "Approved" });
			const reply = JSON.parse(fs.readFileSync(replyFile(runId, requestId), "utf-8")) as { message?: string; requestId?: string };
			assert.equal(reply.requestId, requestId);
			assert.equal(reply.message, "Approved");
			assert.equal(fs.existsSync(requestFile(runId, requestId)), false);
		} finally {
			channel.dispose();
		}
	});

	it("includes supervisor request metadata and journals a successful reply", async () => {
		const currentSessionId = `session-${randomUUID()}`;
		const runId = `run-${randomUUID()}`;
		const requestId = writeRequest({
			sessionId: currentSessionId,
			runId,
			agent: "worker",
			index: 2,
			message: "Should this change be applied?",
			reason: "interview_request",
			childTarget: "child-worker",
			interview: { approved: "boolean", rationale: "string" },
		});
		const sent: Array<{ customType?: string; content?: string; details?: Record<string, unknown> }> = [];
		const entries: Array<{ customType: string; data?: Record<string, unknown> }> = [];
		const journalState = { replyExistsAtAppend: false, requestExistsAtAppend: true };
		const registeredTools = new Map<string, { execute: (_id: string, params: { action: string; replyTo?: string; message?: string }) => Promise<unknown> }>();
		const ctx = {
			cwd: process.cwd(),
			hasUI: false,
			sessionManager: {
				getSessionId: () => currentSessionId,
				getSessionFile: () => null,
				getEntries: () => [],
			},
		};
		const pi = {
			getAllTools: () => [...registeredTools.keys()].map((name) => ({ name })),
			registerTool: (tool: { name: string; execute: (_id: string, params: { action: string; replyTo?: string; message?: string }) => Promise<unknown> }) => {
				registeredTools.set(tool.name, tool);
			},
			sendMessage: (message: { customType?: string; content?: string; details?: Record<string, unknown> }) => { sent.push(message); },
			appendEntry: (customType: string, data?: Record<string, unknown>) => {
				journalState.replyExistsAtAppend = fs.existsSync(replyFile(runId, requestId, "worker", 2));
				journalState.requestExistsAtAppend = fs.existsSync(requestFile(runId, requestId, "worker", 2));
				entries.push({ customType, data });
			},
			getSessionName: () => "shared-name",
		};
		const channel = createNativeSupervisorChannel(pi as never, makeState(currentSessionId, ctx));

		try {
			channel.start();
			assert.equal(sent.length, 1);
			assert.equal(sent[0]?.customType, SUPERVISOR_REQUEST_MESSAGE_TYPE);
			assert.match(sent[0]?.content ?? "", /Subagent requests a structured supervisor interview\./);
			assert.match(sent[0]?.content ?? "", /Should this change be applied\?/);
			assert.ok(sent[0]?.content?.includes(`Reply with: subagent({ action: "reply", replyTo: "${requestId}", message: "..." })`));
			assert.ok(sent[0]?.content?.includes(`Live guidance: subagent({ action: "steer", id: "${runId}", message: "...", options: { index: 2 } }) (Reply to the pending request first.)`));
			assert.doesNotMatch(sent[0]?.content ?? "", /Child intercom target:|child-worker/);
			assert.deepEqual(sent[0]?.details, {
				id: requestId,
				requestId,
				reason: "interview_request",
				expectsReply: true,
				runId,
				agent: "worker",
				childIndex: 2,
				childTarget: "child-worker",
				interview: { approved: "boolean", rationale: "string" },
				requestBody: "Should this change be applied?",
				replyHint: `subagent({ action: "reply", replyTo: "${requestId}", message: "..." })`,
			});

			await channel.runParentAction({
				action: "reply",
				replyTo: requestId,
				message: "Approved with rationale",
			});

			assert.equal(entries.length, 1);
			assert.equal(entries[0]?.customType, SUPERVISOR_REPLY_ENTRY_TYPE);
			assert.deepEqual(journalState, { replyExistsAtAppend: true, requestExistsAtAppend: false });
			assert.deepEqual({ ...entries[0]?.data, createdAt: undefined }, {
				requestId,
				reason: "interview_request",
				runId,
				agent: "worker",
				childIndex: 2,
				childTarget: "child-worker",
				message: "Approved with rationale",
				createdAt: undefined,
			});
			assert.equal(typeof entries[0]?.data?.createdAt, "number");
			const reply = JSON.parse(fs.readFileSync(replyFile(runId, requestId, "worker", 2), "utf-8")) as { message?: string };
			assert.equal(reply.message, "Approved with rationale");
			assert.equal(fs.existsSync(requestFile(runId, requestId, "worker", 2)), false);
		} finally {
			channel.dispose();
		}
	});

	it("keeps message-less interview metadata visible to the parent model", () => {
		const currentSessionId = `session-${randomUUID()}`;
		const runId = `run-${randomUUID()}`;
		const requestId = writeRequest({ sessionId: currentSessionId, runId, reason: "interview_request", message: "", interview: { approved: "boolean" } });
		const sent: Array<{ content?: string; details?: Record<string, unknown> }> = [];
		const ctx = {
			cwd: process.cwd(),
			hasUI: false,
			sessionManager: {
				getSessionId: () => currentSessionId,
				getSessionFile: () => null,
				getEntries: () => [],
			},
		};
		const pi = {
			getAllTools: () => [],
			registerTool: () => {},
			sendMessage: (message: { content?: string; details?: Record<string, unknown> }) => { sent.push(message); },
			getSessionName: () => "shared-name",
		};
		const channel = createNativeSupervisorChannel(pi as never, makeState(currentSessionId, ctx));

		channel.start();
		channel.dispose();

		assert.equal(sent.length, 1);
		assert.match(sent[0]?.content ?? "", /Structured response requested/);
		assert.match(sent[0]?.content ?? "", /"approved": "boolean"/);
		assert.match(sent[0]?.content ?? "", new RegExp(`replyTo: "${requestId}"`));
		assert.equal(sent[0]?.details?.requestBody, "");
	});

	it("suppresses resolved, expired, and inactive requests before displaying them", () => {
		const currentSessionId = `session-${randomUUID()}`;
		const resolvedRunId = `run-${randomUUID()}`;
		const expiredRunId = `run-${randomUUID()}`;
		const inactiveRunId = `run-${randomUUID()}`;
		const progressRunId = `run-${randomUUID()}`;
		const foreignRunId = `run-${randomUUID()}`;
		const resolvedId = writeRequest({ sessionId: currentSessionId, runId: resolvedRunId });
		const expiredId = writeRequest({ sessionId: currentSessionId, runId: expiredRunId, expiresAt: Date.now() - 1 });
		const inactiveId = writeRequest({ sessionId: currentSessionId, runId: inactiveRunId });
		const progressId = writeRequest({ sessionId: currentSessionId, runId: progressRunId, reason: "progress_update" });
		const foreignId = writeRequest({ sessionId: `foreign-${randomUUID()}`, runId: foreignRunId });
		fs.writeFileSync(replyFile(resolvedRunId, resolvedId), JSON.stringify({
			type: "subagent.supervisor.reply",
			requestId: resolvedId,
			createdAt: Date.now(),
			message: "Already handled",
		}), "utf-8");
		const sent: Array<{ details?: { id?: string } }> = [];
		const ctx = {
			cwd: process.cwd(),
			hasUI: false,
			sessionManager: {
				getSessionId: () => currentSessionId,
				getSessionFile: () => null,
				getEntries: () => [],
			},
		};
		const state = makeState(currentSessionId, ctx);
		state.foregroundRuns = new Map([[inactiveRunId, {
			runId: inactiveRunId,
			mode: "single",
			cwd: process.cwd(),
			updatedAt: Date.now(),
			children: [{ agent: "worker", index: 0, status: "completed", updatedAt: Date.now() }],
		}]]);
		const pi = {
			getAllTools: () => [],
			registerTool: () => {},
			sendMessage: (message: { details?: { id?: string } }) => { sent.push(message); },
			getSessionName: () => "shared-name",
		};
		const channel = createNativeSupervisorChannel(pi as never, state);

		channel.start();
		assert.equal(channel.hasPendingRequests(), false, "resolved, expired, and inactive requests are not barriers");
		channel.dispose();

		assert.deepEqual(sent.map((message) => message.details?.id), []);
		assert.equal(fs.existsSync(requestFile(resolvedRunId, resolvedId)), false);
		assert.equal(fs.existsSync(requestFile(expiredRunId, expiredId)), false);
		assert.equal(fs.existsSync(requestFile(inactiveRunId, inactiveId)), false);
		assert.equal(fs.existsSync(requestFile(progressRunId, progressId)), false);
		assert.equal(fs.existsSync(requestFile(foreignRunId, foreignId)), true);
	});

	it("lists each pending request with its question text", async () => {
		const currentSessionId = `session-${randomUUID()}`;
		const runId = `run-${randomUUID()}`;
		const requestId = writeRequest({ sessionId: currentSessionId, runId, message: "Rerun each failed job separately?\nOr rerun the whole run?" });
		const registeredTools = new Map<string, { execute: (_id: string, params: { action: string }) => Promise<{ content: Array<{ text: string }> }> }>();
		const ctx = {
			cwd: process.cwd(),
			hasUI: false,
			sessionManager: { getSessionId: () => currentSessionId, getSessionFile: () => null, getEntries: () => [] },
		};
		const pi = {
			getAllTools: () => [...registeredTools.keys()].map((name) => ({ name })),
			registerTool: (tool: { name: string; execute: (_id: string, params: { action: string }) => Promise<{ content: Array<{ text: string }> }> }) => { registeredTools.set(tool.name, tool); },
			sendMessage: () => {},
			getSessionName: () => "shared-name",
		};
		const channel = createNativeSupervisorChannel(pi as never, makeState(currentSessionId, ctx));
		try {
			channel.start();
			const result = await channel.runParentAction({ action: "pending" });
			const text = result.content[0]!.text;
			assert.match(text, new RegExp(`^- ${requestId}: `));
			assert.match(text, /\n {2}Rerun each failed job separately\?\n {2}Or rerun the whole run\?/);
		} finally {
			channel.dispose();
		}
	});

	it("refreshes pending requests before listing or replying", async () => {
		const currentSessionId = `session-${randomUUID()}`;
		const runId = `run-${randomUUID()}`;
		const requestId = writeRequest({ sessionId: currentSessionId, runId });
		const registeredTools = new Map<string, { execute: (_id: string, params: { action: string; replyTo?: string; message?: string }) => Promise<{ content: Array<{ text: string }>; details?: { pending?: unknown[] } }> }>();
		const sent: Array<{ details?: { id?: string } }> = [];
		const ctx = {
			cwd: process.cwd(),
			hasUI: false,
			sessionManager: {
				getSessionId: () => currentSessionId,
				getSessionFile: () => null,
				getEntries: () => [],
			},
		};
		const pi = {
			getAllTools: () => [...registeredTools.keys()].map((name) => ({ name })),
			registerTool: (tool: { name: string; execute: (_id: string, params: { action: string; replyTo?: string; message?: string }) => Promise<{ content: Array<{ text: string }>; details?: { pending?: unknown[] } }> }) => {
				registeredTools.set(tool.name, tool);
			},
			sendMessage: (message: { details?: { id?: string } }) => { sent.push(message); },
			getSessionName: () => "shared-name",
		};
		const channel = createNativeSupervisorChannel(pi as never, makeState(currentSessionId, ctx));

		try {
			channel.start();
			assert.deepEqual(sent.map((message) => message.details?.id), [requestId]);
			assert.equal(channel.pending.has(requestId), true);

			fs.rmSync(requestFile(runId, requestId), { force: true });
			const pendingResult = await channel.runParentAction({ action: "pending" });

			assert.match(pendingResult.content[0]!.text, /No pending supervisor requests/);
			assert.deepEqual(pendingResult.details?.pending, []);
			assert.equal(channel.pending.has(requestId), false);
			await assert.rejects(
				() => channel.runParentAction({ action: "reply", replyTo: requestId, message: "Too late" }),
				new RegExp(`Supervisor request '${requestId}' from worker \\[${runId}#0\\] was withdrawn by the child before its ask deadline \\(noticed at \\d{4}-\\d\\d-\\d\\dT[^ ]+Z\\)\\. A child withdraws its request when its run is stopped, interrupted or times out`),
			);
		} finally {
			channel.dispose();
		}
	});

	it("stores only the child-authored supervisor message in the request body", async () => {
		const runId = `run-${randomUUID()}`;
		const channelDir = resolveSupervisorChannelDir(runId, "worker", 3);
		createdChannels.push(channelDir);
		const registeredTools = new Map<string, { execute: (_id: string, params: { reason: string; message?: string }) => Promise<unknown> | unknown }>();
		const pi = {
			getAllTools: () => [...registeredTools.keys()].map((name) => ({ name })),
			registerTool: (tool: { name: string; execute: (_id: string, params: { reason: string; message?: string }) => Promise<unknown> | unknown }) => {
				registeredTools.set(tool.name, tool);
			},
		};
		registerNativeSupervisorClient(pi as never, {
			channelDir,
			runId,
			agent: "worker",
			childIndex: 3,
			orchestratorTarget: "shared-name",
			orchestratorSessionId: "session-parent",
		});

		await assert.rejects(
			() => registeredTools.get("contact_supervisor")!.execute("blank-progress", { reason: "progress_update" }),
			/message is required for supervisor decisions and progress updates/,
		);
		await registeredTools.get("contact_supervisor")!.execute("contact", {
			reason: "progress_update",
			message: "  Finished the first review pass.  ",
		});

		const [file] = fs.readdirSync(path.join(channelDir, "requests"));
		const request = JSON.parse(fs.readFileSync(path.join(channelDir, "requests", file!), "utf-8")) as { message?: string; runId?: string; agent?: string; childIndex?: number };
		assert.equal(request.message, "Finished the first review pass.");
		assert.equal(request.runId, runId);
		assert.equal(request.agent, "worker");
		assert.equal(request.childIndex, 3);
	});

	it("removes the request file when a child supervisor ask is cancelled", async () => {
		const runId = `run-${randomUUID()}`;
		const channelDir = resolveSupervisorChannelDir(runId, "worker", 0);
		createdChannels.push(channelDir);
		const registeredTools = new Map<string, { execute: (_id: string, params: { reason: string; message?: string }, signal?: AbortSignal) => Promise<unknown> | unknown }>();
		const pi = {
			getAllTools: () => [...registeredTools.keys()].map((name) => ({ name })),
			registerTool: (tool: { name: string; execute: (_id: string, params: { reason: string; message?: string }, signal?: AbortSignal) => Promise<unknown> | unknown }) => {
				registeredTools.set(tool.name, tool);
			},
		};
		registerNativeSupervisorClient(pi as never, {
			channelDir,
			runId,
			agent: "worker",
			childIndex: 0,
			orchestratorTarget: "shared-name",
			orchestratorSessionId: "session-parent",
		});
		const controller = new AbortController();
		controller.abort();

		await assert.rejects(
			() => registeredTools.get("contact_supervisor")!.execute("contact", { reason: "need_decision", message: "Need a decision" }, controller.signal),
			/Supervisor request cancelled/,
		);

		assert.deepEqual(fs.readdirSync(path.join(channelDir, "requests")), []);
	});

	it("keeps a child waiting while its parent moves expiresAt forward, and times out once it stops", async () => {
		process.env.PI_INTERCOM_ASK_TIMEOUT_MS = "300";
		const runId = `run-${randomUUID()}`;
		const channelDir = resolveSupervisorChannelDir(runId, "worker", 0);
		createdChannels.push(channelDir);
		const registeredTools = new Map<string, { execute: (_id: string, params: { reason: string; message?: string }) => Promise<{ content: Array<{ text?: string }> }> }>();
		const pi = {
			getAllTools: () => [...registeredTools.keys()].map((name) => ({ name })),
			registerTool: (tool: { name: string; execute: (_id: string, params: { reason: string; message?: string }) => Promise<{ content: Array<{ text?: string }> }> }) => {
				registeredTools.set(tool.name, tool);
			},
		};
		registerNativeSupervisorClient(pi as never, { channelDir, runId, agent: "worker", childIndex: 0, orchestratorSessionId: "session-parent" });
		const requestsDir = path.join(channelDir, "requests");
		const ask = async () => {
			for (const file of fs.existsSync(requestsDir) ? fs.readdirSync(requestsDir) : []) fs.rmSync(path.join(requestsDir, file));
			let settled = false;
			const result = registeredTools.get("contact_supervisor")!.execute("contact", { reason: "need_decision", message: "Proceed?" });
			void result.then(() => { settled = true; }, () => { settled = true; });
			await waitForCondition(() => fs.existsSync(requestsDir) && fs.readdirSync(requestsDir).length === 1, "the request file");
			const file = path.join(requestsDir, fs.readdirSync(requestsDir)[0]!);
			const extendBy = (ms: number) => fs.writeFileSync(file, JSON.stringify({ ...JSON.parse(fs.readFileSync(file, "utf-8")), expiresAt: Date.now() + ms }));
			return { result, file, extendBy, settled: () => settled };
		};

		const waiting = await ask();
		waiting.extendBy(900);
		await new Promise((resolve) => setTimeout(resolve, 600));
		assert.equal(waiting.settled(), false, "the child must not time out at its original deadline while the parent extends it");
		const requestId = path.basename(waiting.file, ".json");
		fs.writeFileSync(path.join(channelDir, "replies", `${requestId}.json`), JSON.stringify({ type: "subagent.supervisor.reply", requestId, createdAt: Date.now(), message: "Go ahead" }));
		assert.match((await waiting.result).content[0]?.text ?? "", /Go ahead/);

		const abandoned = await ask();
		abandoned.extendBy(400);
		const started = Date.now();
		await assert.rejects(abandoned.result, /Timed out waiting for supervisor reply/);
		const waited = Date.now() - started;
		assert.ok(waited >= 300 && waited < 1500, `a parent that stops extending lets the child time out at the last deadline (waited ${waited} ms)`);
	});
});
