import assert from "node:assert/strict";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import { describe, it } from "node:test";
import { resolvePiLaunchToolPlan } from "../../src/runs/shared/child-tool-plan.ts";
import { buildInProcessChildLaunch } from "../../src/runs/shared/child-launch.ts";
import { runSingleStepInner } from "../../src/runs/background/subagent-runner.ts";
import { MCP_RUNTIME_SNAPSHOT_EVENT, MCP_RUNTIME_SNAPSHOT_VERSION, type McpHostToolInfo, type McpRuntimeSnapshotHost } from "../../src/runs/shared/mcp-direct-tool-allowlist.ts";
import { createFakeChildSessions } from "../support/fake-child-session.ts";

/** A parent whose pi-mcp-adapter answers snapshot requests for one runtime-only server. */
function runtimeSnapshotHost(serverName: string): McpRuntimeSnapshotHost {
	return {
		events: {
			emit(event, request) {
				if (event !== MCP_RUNTIME_SNAPSHOT_EVENT || request.version !== MCP_RUNTIME_SNAPSHOT_VERSION || request.name !== serverName) return;
				request.result = { ok: true, snapshot: { name: serverName, runtime: true, persisted: false, definition: { command: "node", args: ["server.js"] } } };
			},
		},
	};
}

/** A parent whose /mcp is owned by `mcpOwner` and whose tool registry holds `tools`. */
function mcpHost(mcpOwner: string, tools: McpHostToolInfo[]): McpRuntimeSnapshotHost {
	return {
		events: { emit() {} },
		getCommands: () => [{ name: "mcp", sourceInfo: { path: mcpOwner } }],
		getAllTools: () => tools,
	};
}

const BUILTIN_MCP_TOOLS: McpHostToolInfo[] = [
	{ name: "mcp__docs__search_pages", exposure: "codemode", namespace: { name: "mcp__docs" } },
	{ name: "mcp__docs__fetch", exposure: "direct", namespace: { name: "mcp__docs" } },
	{ name: "mcp__docs__admin", exposure: "hidden", namespace: { name: "mcp__docs" } },
	{ name: "mcp__other__fetch", exposure: "codemode", namespace: { name: "mcp__other" } },
];

describe("child tool plan with Pi built-in MCP", () => {
	const host = mcpHost("builtin:mcp", BUILTIN_MCP_TOOLS);

	it("grants every non-hidden tool of a selected server as a required child tool", () => {
		const plan = resolvePiLaunchToolPlan({ tools: ["read"], mcpDirectTools: ["docs"], runtimeSnapshotHost: host });
		const granted = ["mcp__docs__search_pages", "mcp__docs__fetch"];
		assert.deepEqual(plan.builtinMcpTools, granted.map((name) => ({ name, selector: "docs" })));
		assert.deepEqual(plan.effectiveToolAllowlist, ["read", ...granted]);
		assert.deepEqual(plan.requiredChildTools, ["read", ...granted]);
	});

	it("grants one tool for a tool selector and applies exclusions", () => {
		const plan = resolvePiLaunchToolPlan({ mcpDirectTools: ["docs/search.pages", "docs/fetch"], excludeTools: ["mcp__docs__fetch"], runtimeSnapshotHost: host });
		assert.deepEqual(plan.builtinMcpTools, [{ name: "mcp__docs__search_pages", selector: "docs/search.pages" }]);
	});

	it("grants the hash-suffixed name Pi gives a tool whose sanitized name another tool took", () => {
		const plan = resolvePiLaunchToolPlan({ mcpDirectTools: ["srv/a.b"], runtimeSnapshotHost: mcpHost("builtin:mcp", [
			{ name: "mcp__srv__a_b", exposure: "codemode", namespace: { name: "mcp__srv" } },
			{ name: "mcp__srv__a_b_df0974cd", exposure: "codemode", namespace: { name: "mcp__srv" } },
		]) });
		assert.deepEqual(plan.effectiveMcpTools, ["mcp__srv__a_b_df0974cd"]);
	});

	it("resolves a raw hyphenated selector to the name and namespace Pi gives the tool", () => {
		const plan = resolvePiLaunchToolPlan({
			mcpDirectTools: ["my-docs/get-item"],
			capabilityCeiling: { version: 1, allowedTools: ["mcp__my_docs__get_item"], sources: ["test"] },
			runtimeSnapshotHost: mcpHost("builtin:mcp", [{ name: "mcp__my_docs__get_item", exposure: "codemode", namespace: { name: "mcp__my_docs" } }]),
		});
		assert.deepEqual(plan.builtinMcpTools, [{ name: "mcp__my_docs__get_item", selector: "my-docs/get-item" }]);
	});

	it("fails a launch whose selector matches no offered tool", () => {
		assert.throws(
			() => resolvePiLaunchToolPlan({ mcpDirectTools: ["docs/admin", "gone"], agentName: "browser", runtimeSnapshotHost: host }),
			/Agent 'browser' selects MCP tools that Pi's built-in MCP does not offer: mcp:docs\/admin, mcp:gone\. The server may be missing, disconnected, still connecting, or its tools hidden; check \/mcp\./,
		);
	});

	for (const [description, adapterHost] of [
		["when the adapter owns /mcp", mcpHost("/ext/pi-mcp-adapter/index.ts", BUILTIN_MCP_TOOLS)],
		["when adapter 3.x loads next to Pi's built-in /mcp", {
			...mcpHost("builtin:mcp", BUILTIN_MCP_TOOLS),
			getCommands: () => [
				{ name: "mcp", sourceInfo: { path: "builtin:mcp" } },
				{ name: "mcp-adapter", sourceInfo: { path: "/ext/pi-mcp-adapter/index.ts" } },
			],
		}],
	] satisfies Array<[string, McpRuntimeSnapshotHost]>) {
		it(`keeps the pi-mcp-adapter path ${description}`, () => {
			const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagents-adapter-mcp-"));
			try {
				assert.throws(
					() => resolvePiLaunchToolPlan({ mcpDirectTools: ["docs"], cwd, runtimeSnapshotHost: adapterHost }),
					/Unresolved MCP direct-tool selectors: docs\. Direct MCP tools require a matching configured server/,
				);
			} finally {
				fs.rmSync(cwd, { recursive: true, force: true });
			}
		});
	}
});

describe("child tool plan", () => {
	it("does not grant watchdog_diff unless an agent explicitly requests it", () => {
		for (const agentName of ["worker", "scout", "project-reviewer"]) {
			const plan = resolvePiLaunchToolPlan({ tools: ["read", "contact_supervisor"], agentName });
			assert.equal(plan.effectiveToolAllowlist.includes("watchdog_diff"), false);
		}
		const bundledReviewer = resolvePiLaunchToolPlan({ tools: ["read", "watchdog_diff", "contact_supervisor"], agentName: "reviewer" });
		assert.deepEqual(bundledReviewer.effectiveToolAllowlist, ["read", "watchdog_diff", "contact_supervisor"]);
	});

	it("fails a launch that selects MCP tools from the adapter's runtime snapshot", () => {
		const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagents-runtime-mcp-"));
		try {
			assert.throws(
				() => resolvePiLaunchToolPlan({ tools: ["read"], mcpDirectTools: ["runtime-only/search"], cwd, agentName: "browser", runtimeSnapshotHost: runtimeSnapshotHost("runtime-only") }),
				/cannot be provided to in-process children; MCP tools must come from an ambient adapter extension in a background child/,
			);
		} finally {
			fs.rmSync(cwd, { recursive: true, force: true });
		}
	});
});

describe("child tool plan declared tools", () => {
	it("keeps every declared core tool, so the child registry decides what exists", () => {
		const plan = resolvePiLaunchToolPlan({ tools: ["read", "grep", "find", "ls", "bash"], agentName: "verifier" });
		assert.deepEqual(plan.declaredBuiltinTools, ["read", "grep", "find", "ls", "bash"]);
		assert.deepEqual(plan.effectiveToolAllowlist, ["read", "grep", "find", "ls", "bash"]);
		assert.deepEqual(plan.requiredChildTools, ["read", "grep", "find", "ls", "bash"]);
	});

	it("grants command observation only when explicitly declared", () => {
		const automatic = resolvePiLaunchToolPlan({ tools: ["bash"] });
		assert.deepEqual(automatic.effectiveToolAllowlist, ["bash"]);
		assert.deepEqual(automatic.requiredChildTools, ["bash"]);
		const explicit = resolvePiLaunchToolPlan({ tools: ["bash", "subagent_command"] });
		assert.deepEqual(explicit.requiredChildTools, ["bash", "subagent_command"]);
	});

	it("does not enable command controls through a ceiling alone and honors explicit exclusions", () => {
		const ceiling = { version: 1 as const, allowedTools: ["bash", "subagent_command"], denyExtensions: false, sources: ["test"] };
		assert.deepEqual(resolvePiLaunchToolPlan({ capabilityCeiling: ceiling }).effectiveToolAllowlist, ["bash"]);
		assert.deepEqual(resolvePiLaunchToolPlan({ tools: ["bash", "subagent_command"], excludeTools: ["subagent_command"] }).effectiveToolAllowlist, ["bash"]);
		assert.deepEqual(resolvePiLaunchToolPlan({ tools: ["bash", "subagent_command"], capabilityCeiling: { ...ceiling, allowedTools: ["bash"] } }).effectiveToolAllowlist, ["bash"]);
	});

	it("adds read for lazy skill loading without an explicit declaration", () => {
		const plan = resolvePiLaunchToolPlan({ tools: ["bash"], requireReadTool: true });
		assert.deepEqual(plan.requiredChildTools, ["read", "bash"]);
	});

	it("rejects Pi tool modifier entries instead of planning them as tool names", () => {
		assert.throws(() => resolvePiLaunchToolPlan({ tools: ["+codemode"], agentName: "modifier-repro" }), {
			message: "Agent 'modifier-repro' lists Pi tool modifier entry in `tools`: +codemode. A child's `tools` list is the complete set of tools it gets, so +name and -name entries are not supported; name every tool the child needs, or omit `tools` and use `excludeTools` to drop one.",
		});
		for (const { input, rejected } of [
			{ input: { tools: ["-write"], agentName: "modifier-repro" }, rejected: /^Agent 'modifier-repro' lists Pi tool modifier entry in `tools`: -write\. .*use `excludeTools` to drop one\.$/ },
			{ input: { tools: ["read", "+codemode"], agentName: "modifier-repro" }, rejected: /^Agent 'modifier-repro' lists Pi tool modifier entry in `tools`: \+codemode\. / },
			{ input: { tools: ["+codemode"], requireReadTool: true, agentName: "modifier-repro" }, rejected: /^Agent 'modifier-repro' lists Pi tool modifier entry in `tools`: \+codemode\. / },
			{ input: { tools: ["+codemode", "read", "-write"] }, rejected: /^Subagent lists Pi tool modifier entries in `tools`: \+codemode, -write\. / },
		]) {
			assert.throws(() => resolvePiLaunchToolPlan(input), { message: rejected });
		}
	});

	it("rejects a modifier entry that the ceiling or an exclusion would filter out", () => {
		for (const { input, rejected } of [
			{ input: { tools: ["+codemode"], capabilityCeiling: { version: 1 as const, allowedTools: ["read"], denyExtensions: false, sources: ["test"] }, agentName: "modifier-repro" }, rejected: /^Agent 'modifier-repro' lists Pi tool modifier entry in `tools`: \+codemode\. / },
			{ input: { tools: ["read", "-write"], excludeTools: ["-write"], agentName: "modifier-repro" }, rejected: /^Agent 'modifier-repro' lists Pi tool modifier entry in `tools`: -write\. / },
		]) {
			assert.throws(() => resolvePiLaunchToolPlan(input), { message: rejected });
		}
	});

	it("leaves a path-like entry that starts with a hyphen to the extension loader", () => {
		for (const entry of ["-tools/fixture.ts", "-tools/fixture", "-fixture.ts", "-fixture.js"]) {
			const plan = resolvePiLaunchToolPlan({ tools: ["read", entry], agentName: "modifier-repro" });
			assert.deepEqual(plan.requiredChildTools, ["read"], entry);
			assert.ok(plan.extensionArgs.includes(entry), entry);
		}
	});

	it("still plans a plain tool list whose names contain hyphens", () => {
		const plan = resolvePiLaunchToolPlan({ tools: ["bash", "codemode", "fixture-search"], requireReadTool: true, agentName: "modifier-repro" });
		assert.deepEqual(plan.effectiveToolAllowlist, ["read", "bash", "codemode", "fixture-search"]);
		assert.deepEqual(plan.requiredChildTools, ["read", "bash", "codemode", "fixture-search"]);
	});

	it("preserves arbitrary non-core requirements without inferring their child providers", () => {
		const tools = ["read", "fixture_search", "__proto__", "ipython"];
		for (const configuration of [
			{},
			{ capabilityCeiling: { version: 1 as const, denyExtensions: true, sources: ["test"] } },
		]) {
			const plan = resolvePiLaunchToolPlan({ tools, ...configuration });
			assert.deepEqual(plan.effectiveToolAllowlist, tools);
			assert.deepEqual(plan.requiredChildTools, tools);
		}
		const restricted = resolvePiLaunchToolPlan({
			tools, excludeTools: ["__proto__"],
			capabilityCeiling: { version: 1, allowedTools: ["fixture_search", "__proto__"], sources: ["test"] },
		});
		assert.deepEqual(restricted.effectiveToolAllowlist, ["fixture_search"]);
		assert.deepEqual(restricted.requiredChildTools, ["fixture_search"]);
		for (const restriction of [{ tools: [] }, { capabilityCeiling: { version: 1 as const, allowedTools: [], sources: ["test"] } }]) {
			const empty = resolvePiLaunchToolPlan({ tools, ...restriction });
			assert.deepEqual(empty.effectiveToolAllowlist, []);
			assert.deepEqual(empty.requiredChildTools, []);
		}
	});

	it("retains the supervisor pairing exception but requires a lone intercom", () => {
		for (const tools of [["intercom"], ["intercom", "contact_supervisor"]]) {
			const plan = resolvePiLaunchToolPlan({ tools });
			assert.deepEqual(plan.effectiveToolAllowlist, tools);
			assert.deepEqual(plan.requiredChildTools, tools.length === 1 ? tools : []);
		}
	});

	it("keeps requested native coordination tools, but honors ceilings and exclusions", () => {
		const tools = ["read", "subagent", "contact_supervisor", "grep"];
		const plan = resolvePiLaunchToolPlan({ tools });
		assert.deepEqual(plan.effectiveToolAllowlist, tools);
		assert.deepEqual(plan.requiredChildTools, ["read", "subagent", "grep"]);
		assert.equal(plan.fanoutAuthorized, true);
		for (const restriction of [
			{ excludeTools: ["grep"] },
			{ capabilityCeiling: { version: 1 as const, allowedTools: ["read", "subagent", "contact_supervisor"], denyExtensions: true, sources: ["test"] } },
		]) {
			const restricted = resolvePiLaunchToolPlan({ tools, ...restriction });
			assert.equal(restricted.fanoutAuthorized, true);
			assert.equal(restricted.effectiveToolAllowlist.includes("grep"), false);
		}
		assert.equal(resolvePiLaunchToolPlan({ tools: ["read", "contact_supervisor"] }).fanoutAuthorized, false);
	});

	it("respects a capability ceiling", () => {
		const plan = resolvePiLaunchToolPlan({
			tools: ["read", "grep", "bash", "write"],
			capabilityCeiling: { version: 1, allowedTools: ["read", "bash"], denyExtensions: false, sources: ["test"] },
		});
		assert.deepEqual(plan.declaredBuiltinTools, ["read", "bash"]);
		assert.deepEqual(plan.capabilityAudit?.ceiling.sources, ["test"]);
	});
});

describe("production launch path keeps declared child tools", () => {
	it("keeps adapter direct tools ambient when the child has no tool allowlist", () => {
		const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagents-ambient-mcp-"));
		const previousAgentDir = process.env.PI_CODING_AGENT_DIR;
		process.env.PI_CODING_AGENT_DIR = cwd;
		try {
			const base = {
				host: "runner" as const,
				cwd,
				childAgentName: "worker",
				childIndex: 0,
				sessionEnabled: false,
				inheritProjectContext: false,
				inheritGlobalContext: false,
				inheritSkills: false,
			};
			const directTool = "mcp__long_server__echo";
			const ambient = buildInProcessChildLaunch(base);
			assert.equal(Object.hasOwn(ambient.session.processEnv ?? {}, "MCP_DIRECT_TOOLS"), true);
			assert.equal(ambient.session.processEnv?.MCP_DIRECT_TOOLS, undefined);
			assert.equal(ambient.session.tools, undefined);

			const restricted = buildInProcessChildLaunch({ ...base, excludeTools: [directTool] });
			assert.equal(Object.hasOwn(restricted.session.processEnv ?? {}, "MCP_DIRECT_TOOLS"), true);
			assert.equal(restricted.session.processEnv?.MCP_DIRECT_TOOLS, undefined);
			assert.deepEqual(restricted.session.excludeTools, [directTool]);

			const explicit = buildInProcessChildLaunch({ ...base, tools: ["read"] });
			assert.equal(explicit.session.processEnv?.MCP_DIRECT_TOOLS, "__none__");
			const ceiling = buildInProcessChildLaunch({ ...base, capabilityCeiling: { version: 1, allowedTools: ["read"], denyExtensions: false, sources: ["test"] } });
			assert.equal(ceiling.session.processEnv?.MCP_DIRECT_TOOLS, "__none__");
		} finally {
			if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
			else process.env.PI_CODING_AGENT_DIR = previousAgentDir;
			fs.rmSync(cwd, { recursive: true, force: true });
		}
	});

	it("buildInProcessChildLaunch requires every declared tool from the child registry", () => {
		const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagents-launch-builtins-"));
		const previousAgentDir = process.env.PI_CODING_AGENT_DIR;
		process.env.PI_CODING_AGENT_DIR = cwd;
		try {
			for (const childAgentName of ["test-agent", "scout"]) {
				const launch = buildInProcessChildLaunch({
					host: "runner",
					cwd,
					childAgentName,
					childIndex: 0,
					sessionEnabled: false,
					inheritProjectContext: false,
					inheritGlobalContext: false,
					inheritSkills: false,
					tools: ["read", "grep", "bash"],
				});
				assert.deepEqual(launch.toolPlan.declaredBuiltinTools, ["read", "grep", "bash"]);
				assert.deepEqual(launch.toolPlan.effectiveToolAllowlist, ["read", "grep", "bash"]);
				assert.deepEqual(launch.toolPlan.requiredChildTools, ["read", "grep", "bash"]);
				assert.deepEqual(launch.config.requiredTools, ["read", "grep", "bash"]);
			}
		} finally {
			if (previousAgentDir === undefined) delete process.env.PI_CODING_AGENT_DIR;
			else process.env.PI_CODING_AGENT_DIR = previousAgentDir;
			fs.rmSync(cwd, { recursive: true, force: true });
		}
	});

	it("the background runner names the agent when a step lists a tool modifier entry", async () => {
		const cwd = fs.mkdtempSync(path.join(os.tmpdir(), "pi-subagents-runner-modifier-"));
		const fake = createFakeChildSessions(() => cwd);
		try {
			await assert.rejects(runSingleStepInner({ agent: "modifier-repro", task: "do the work", tools: ["+codemode"] }, { cwd, id: "runner-modifier", flatIndex: 0, flatStepCount: 1, previousOutput: "", placeholder: "{previous}", outputFile: path.join(cwd, "output.log"), sessionEnabled: false, childSessions: fake.factory }), {
				message: /^Agent 'modifier-repro' lists Pi tool modifier entry in `tools`: \+codemode\. /,
			});
			assert.equal(fake.sessions.length, 0);
		} finally {
			fs.rmSync(cwd, { recursive: true, force: true });
		}
	});
});
