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 { afterEach, describe, it } from "node:test";
import type { AsyncStatus, SubagentState } from "../../src/shared/types.ts";
import { readActiveRunIndex, releaseActiveRunIndex, updateActiveRunIndex } from "../../src/runs/background/active-run-index.ts";
import { resultFilePath, writeAsyncResultFile, writePendingAsyncResultFile } from "../../src/runs/background/result-files.ts";
import { resolveSubagentRunId } from "../../src/runs/background/run-id-resolver.ts";
import { readRecentTerminalRunIndex, readTerminalRunToolCallIndex, updateTerminalRunIndex, TERMINAL_RUN_INDEX_DIR } from "../../src/runs/background/terminal-run-index.ts";
import { encodeIndexSegment } from "../../src/runs/background/index-segment.ts";
import { createNestedRoute, writeNestedEvent } from "../../src/runs/shared/nested-events.ts";
import { removeForegroundControlIfIdle } from "../../src/runs/foreground/subagent-executor.ts";
import { inspectSubagentStatus } from "../../src/runs/background/run-status.ts";

const routeRoots: string[] = [];

afterEach(() => {
	for (const root of routeRoots.splice(0)) fs.rmSync(root, { recursive: true, force: true, maxRetries: 5, retryDelay: 20 });
});

function stateWithForeground(id: string): SubagentState {
	return {
		baseCwd: "",
		currentSessionId: null,
		asyncJobs: new Map(),
		foregroundRuns: new Map(),
		foregroundControls: new Map([[id, { runId: id, mode: "single", startedAt: 1, updatedAt: 1 }]]),
		lastForegroundControlId: id,
		pendingForegroundControlNotices: new Map(),
		cleanupTimers: new Map(),
		lastUiContext: null,
		poller: null,
		completionSeen: new Map(),
		watcher: null,
		watcherRestartTimer: null,
		resultFileCoalescer: { schedule: () => false, clear: () => {} },
	};
}

function nested(rootRunId: string, id: string) {
	const route = createNestedRoute(rootRunId);
	routeRoots.push(path.dirname(route.eventSink));
	writeNestedChild(route, rootRunId, id, 0);
	return route;
}

function writeNestedChild(route: ReturnType<typeof createNestedRoute>, parentRunId: string, id: string, parentStepIndex?: number) {
	writeNestedEvent(route, {
		type: "subagent.nested.updated",
		ts: 100,
		parentRunId,
		...(parentStepIndex !== undefined ? { parentStepIndex } : {}),
		child: { id, parentRunId, ...(parentStepIndex !== undefined ? { parentStepIndex } : {}), depth: 1, path: [{ runId: parentRunId, ...(parentStepIndex !== undefined ? { stepIndex: parentStepIndex } : {}) }], state: "running", agent: "worker" },
	});
}

function stateWithNestedRoute(route: ReturnType<typeof createNestedRoute>): SubagentState {
	const state = stateWithForeground("foreground-only");
	state.foregroundControls.set(route.rootRunId, { runId: route.rootRunId, mode: "single", startedAt: 1, updatedAt: 1, nestedRoute: route });
	return state;
}

describe("subagent run id resolver", () => {
	it("prefers exact foreground, then exact async, then exact nested before prefix matches", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-run-id-resolver-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const resultsDir = path.join(root, "results");
			fs.mkdirSync(path.join(asyncRoot, "shared-id"), { recursive: true });
			fs.writeFileSync(path.join(asyncRoot, "shared-id", "status.json"), "{}");
			nested("root-shared", "shared-id");
			nested("root-prefix", "shared-id-child");

			assert.equal(resolveSubagentRunId("shared-id", { state: stateWithForeground("shared-id"), asyncDirRoot: asyncRoot, resultsDir })?.kind, "foreground");
			assert.equal(resolveSubagentRunId("shared-id", { asyncDirRoot: asyncRoot, resultsDir })?.kind, "async");
			fs.rmSync(path.join(asyncRoot, "shared-id"), { recursive: true, force: true });
			const resolved = resolveSubagentRunId("shared-id", { asyncDirRoot: asyncRoot, resultsDir });
			assert.equal(resolved?.kind, "nested");
			assert.equal(resolved?.id, "shared-id");
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("does not let a mission-only directory shadow owned nested status by exact id or prefix", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-run-id-mission-shadow-"));
		try {
			const route = nested("mission-root", "mission-child");
			const state = stateWithNestedRoute(route);
			const asyncRoot = path.join(root, "runs");
			fs.mkdirSync(path.join(asyncRoot, "mission-child"), { recursive: true });
			fs.writeFileSync(path.join(asyncRoot, "mission-child", "mission.json"), "{}");
			for (const id of ["mission-child", "mission-chi"]) {
				const deps = { state, asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") };
				assert.equal(resolveSubagentRunId(id, deps)?.kind, "nested");
				assert.notEqual(inspectSubagentStatus({ id }, deps).isError, true);
			}
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("retains session-owned nested lookup after coordinator removal and descendant completion", () => {
		const route = nested("retired-root", "finished-coordinator");
		writeNestedEvent(route, { type: "subagent.nested.started", ts: 110, parentRunId: "finished-coordinator",
			child: { id: "retired-child", parentRunId: "finished-coordinator", depth: 2, path: [{ runId: route.rootRunId }, { runId: "finished-coordinator" }], state: "running", agent: "worker" },
		});
		writeNestedEvent(route, { type: "subagent.nested.completed", ts: 120, parentRunId: route.rootRunId,
			child: { id: "finished-coordinator", parentRunId: route.rootRunId, depth: 1, path: [{ runId: route.rootRunId }], state: "complete", agent: "coordinator" },
		});
		const state = stateWithNestedRoute(route);
		state.currentSessionId = "owner";
		state.foregroundControls.get(route.rootRunId)!.sessionId = "owner";
		assert.equal(resolveSubagentRunId("retired-child", { state })?.kind, "nested");
		assert.equal(removeForegroundControlIfIdle(state, route.rootRunId), true);
		assert.equal(resolveSubagentRunId("retired-child", { state })?.kind, "nested");
		writeNestedEvent(route, { type: "subagent.nested.completed", ts: 200, parentRunId: "finished-coordinator",
			child: { id: "retired-child", parentRunId: "finished-coordinator", depth: 2, path: [{ runId: route.rootRunId }, { runId: "finished-coordinator" }], state: "complete", agent: "worker" },
		});
		const status = inspectSubagentStatus({ id: "retired-child" }, { state });
		assert.notEqual(status.isError, true);
		assert.match(status.content[0].text, /State: complete/);
		assert.equal(resolveSubagentRunId("retired-child", { state, nested: { routes: [] } }), undefined, "child subtree restriction still wins");
		state.currentSessionId = "foreign";
		assert.equal(resolveSubagentRunId("retired-child", { state }), undefined);
	});

	it("reports one combined ambiguity for prefixes across namespaces", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-run-id-ambiguous-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const resultsDir = path.join(root, "results");
			fs.mkdirSync(path.join(asyncRoot, "fanout-x-async"), { recursive: true });
			fs.writeFileSync(path.join(asyncRoot, "fanout-x-async", "status.json"), "{}");
			nested("root-fanout", "fanout-x-nested");
			assert.throws(
				() => resolveSubagentRunId("fanout-x", { asyncDirRoot: asyncRoot, resultsDir }),
				/Ambiguous subagent run id prefix 'fanout-x' matched: async:fanout-x-async, nested:fanout-x-nested/,
			);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("limits nested lookup to active state routes when state is provided", () => {
		const allowed = nested("root-allowed", "shared-nested");
		nested("root-outside", "shared-nested");

		assert.throws(
			() => resolveSubagentRunId("shared-nested"),
			/ambiguous across authorized registries|ambiguous across registries/i,
		);
		assert.equal(resolveSubagentRunId("shared-nested", { state: stateWithForeground("foreground-only") }), undefined);
		const resolved = resolveSubagentRunId("shared-nested", { state: stateWithNestedRoute(allowed) });
		assert.equal(resolved?.kind, "nested");
		assert.equal(resolved?.kind === "nested" ? resolved.match.rootRunId : undefined, "root-allowed");
	});

	it("limits nested lookup to descendants of a scoped child address", () => {
		const route = createNestedRoute("root-scoped");
		routeRoots.push(path.dirname(route.eventSink));
		writeNestedChild(route, "root-scoped", "same-child-zero", 0);
		writeNestedChild(route, "root-scoped", "same-child-one", 1);

		assert.throws(
			() => resolveSubagentRunId("same-child", { nested: { routes: [route] } }),
			/Ambiguous subagent run id prefix 'same-child'/,
		);
		const resolved = resolveSubagentRunId("same-child", { nested: { routes: [route], descendantOf: { parentRunId: "root-scoped", parentStepIndex: 0 } } });
		assert.equal(resolved?.kind, "nested");
		assert.equal(resolved?.id, "same-child-zero");
		assert.equal(resolved?.kind === "nested" ? resolved.match.run.parentStepIndex : undefined, 0);
	});

	it("reports async prefix ambiguity without parsing resolver error text", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-run-id-async-ambiguous-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const resultsDir = path.join(root, "results");
			fs.mkdirSync(path.join(asyncRoot, "dupe-aaa-one"), { recursive: true });
			fs.mkdirSync(path.join(asyncRoot, "dupe-aaa-two"), { recursive: true });
			fs.writeFileSync(path.join(asyncRoot, "dupe-aaa-one", "status.json"), "{}");
			fs.writeFileSync(path.join(asyncRoot, "dupe-aaa-two", "status.json"), "{}");

			assert.throws(
				() => resolveSubagentRunId("dupe-aaa", { asyncDirRoot: asyncRoot, resultsDir }),
				/Ambiguous subagent run id prefix 'dupe-aaa' matched: async:dupe-aaa-one, async:dupe-aaa-two/,
			);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("does not resolve unindexed result files by prefix", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-run-id-result-prefix-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const resultsDir = path.join(root, "results");
			fs.mkdirSync(resultsDir, { recursive: true });
			fs.writeFileSync(path.join(resultsDir, "legacy-run.json"), JSON.stringify({ id: "legacy-run", sessionId: "session-a", success: true }), "utf-8");

			const exact = resolveSubagentRunId("legacy-run", { asyncDirRoot: asyncRoot, resultsDir });
			assert.equal(exact?.kind, "async");
			assert.equal(exact?.id, "legacy-run");
			assert.equal(resolveSubagentRunId("legacy", { asyncDirRoot: asyncRoot, resultsDir }), undefined);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("resolves workflow tool-call ids through active and result indexes", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-run-resolver-tool-call-index-"));
		try {
			const asyncRoot = path.join(root, "async");
			const resultsDir = path.join(root, "results");
			const activeDir = path.join(asyncRoot, "workflow-active");
			fs.mkdirSync(activeDir, { recursive: true });
			fs.writeFileSync(path.join(activeDir, "status.json"), JSON.stringify({ runId: "workflow-active", toolCallId: "call-active", state: "running", mode: "workflow", startedAt: 1, lastUpdate: 1, steps: [] }), "utf-8");
			updateActiveRunIndex(activeDir, "running", "call-active");

			const active = resolveSubagentRunId("call-active", { asyncDirRoot: asyncRoot, resultsDir });
			assert.equal(active?.kind, "async");
			assert.equal(active?.id, "workflow-active");
			releaseActiveRunIndex(activeDir);
			assert.equal(resolveSubagentRunId("call-active", { asyncDirRoot: asyncRoot, resultsDir }), undefined);

			writeAsyncResultFile(resultFilePath(resultsDir, "workflow-done"), { id: "workflow-done", runId: "workflow-done", toolCallId: "call-done", sessionId: "session-a", state: "complete", success: true });
			const done = resolveSubagentRunId("call-done", { asyncDirRoot: asyncRoot, resultsDir });
			assert.equal(done?.kind, "async");
			assert.equal(done?.id, "workflow-done");
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("resolves retained terminal aliases without scanning unrelated runs or mixing session indexes", (t) => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-terminal-alias-"));
		t.after(() => fs.rmSync(root, { recursive: true, force: true }));
		const toolCallId = `call_${"界".repeat(100)}`;
		for (const [runId, sessionId, endedAt, alias] of [
			["retained", "@tool-calls", 1, toolCallId],
			["unrelated", "tool-calls", 2, undefined],
		] as const) {
			const dir = path.join(root, runId);
			const status: AsyncStatus = { runId, sessionId, state: "complete", mode: "single", startedAt: 1, endedAt, ...(alias ? { toolCallId: alias } : {}) };
			fs.mkdirSync(dir, { recursive: true });
			fs.writeFileSync(path.join(dir, "status.json"), JSON.stringify(status));
			updateTerminalRunIndex(dir, status);
		}
		assert.deepEqual(readRecentTerminalRunIndex(root), ["unrelated", "retained"]);
		assert.deepEqual(readRecentTerminalRunIndex(root, { limit: 1 }), ["unrelated"]);
		assert.deepEqual(readRecentTerminalRunIndex(root, { sessionId: "@tool-calls" }), ["retained"]);
		const readdir = fsDefault.readdirSync;
		t.mock.method(fsDefault, "readdirSync", (dir, ...args) => {
			assert.notEqual(String(dir), root, "alias lookup must not scan run directories");
			assert.notEqual(String(dir), path.join(root, TERMINAL_RUN_INDEX_DIR), "alias lookup must not scan sessions");
			assert.notEqual(String(dir), path.join(root, "unrelated"));
			return Reflect.apply(readdir, fsDefault, [dir, ...args]);
		});
		syncBuiltinESMExports();
		try {
			assert.equal(resolveSubagentRunId(toolCallId, { asyncDirRoot: root, resultsDir: path.join(root, "results") })?.id, "retained");
		} finally {
			t.mock.restoreAll();
			syncBuiltinESMExports();
		}
	});

	it("reports an alias shared by a live run and a delivered run as ambiguous", (t) => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-live-terminal-alias-"));
		t.after(() => fs.rmSync(root, { recursive: true, force: true }));
		const toolCallId = "rpc-spawn-original-request";
		const retainedDir = path.join(root, "retained-run");
		const retained: AsyncStatus = { runId: "retained-run", sessionId: "s", state: "complete", mode: "single", startedAt: 1, endedAt: 2, toolCallId };
		fs.mkdirSync(retainedDir, { recursive: true });
		fs.writeFileSync(path.join(retainedDir, "status.json"), JSON.stringify(retained));
		updateTerminalRunIndex(retainedDir, retained);
		const liveDir = path.join(root, "live-run");
		fs.mkdirSync(liveDir, { recursive: true });
		const state = { asyncJobs: new Map([["live-run", { asyncId: "live-run", asyncDir: liveDir, toolCallId }]]), foregroundControls: new Map() } as unknown as SubagentState;
		const deps = { asyncDirRoot: root, resultsDir: path.join(root, "results") };
		assert.throws(() => resolveSubagentRunId(toolCallId, { ...deps, state }), /ambiguous across async runs/);
		assert.equal(resolveSubagentRunId(toolCallId, deps)?.id, "retained-run", "without a live run the delivered run's alias is unique");
	});

	it("cleans stale and mismatched terminal alias pointers without resolving them", (t) => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-terminal-alias-stale-"));
		t.after(() => fs.rmSync(root, { recursive: true, force: true }));
		const toolCallId = "call-retained";
		for (const mismatch of ["missing", "runId", "sessionId", "toolCallId", "state", "malformed", "unsafe"] as const) {
			const dir = path.join(root, mismatch);
			const status: AsyncStatus = { runId: mismatch, sessionId: "owner", toolCallId, mode: "single", state: "complete", startedAt: 1 };
			fs.mkdirSync(dir, { recursive: true });
			fs.writeFileSync(path.join(dir, "status.json"), JSON.stringify(status));
			updateTerminalRunIndex(dir, status);
			const marker = path.join(root, TERMINAL_RUN_INDEX_DIR, "@tool-calls", encodeIndexSegment(toolCallId), `${mismatch}.json`);
			if (mismatch === "missing") fs.unlinkSync(path.join(dir, "status.json"));
			else if (mismatch === "malformed") fs.writeFileSync(marker, "{");
			else if (mismatch === "unsafe") fs.writeFileSync(marker, JSON.stringify({ version: 1, runId: "../outside", sessionId: "owner", endedAt: 1 }));
			else fs.writeFileSync(path.join(dir, "status.json"), JSON.stringify({ ...status, [mismatch]: mismatch === "state" ? "running" : "different" }));
			assert.deepEqual(readTerminalRunToolCallIndex(root, toolCallId), []);
			assert.equal(fs.existsSync(marker), false, `${mismatch} pointer was removed`);
		}
		assert.equal(resolveSubagentRunId(toolCallId, { asyncDirRoot: root, resultsDir: path.join(root, "results") }), undefined);
	});

	it("reports optional terminal alias write failures without blocking active marker release", (t) => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-terminal-alias-write-"));
		t.after(() => fs.rmSync(root, { recursive: true, force: true }));
		const dir = path.join(root, "retained");
		const status: AsyncStatus = { runId: "retained", sessionId: "owner", toolCallId: "call-retained", mode: "single", state: "complete", startedAt: 1 };
		fs.mkdirSync(dir, { recursive: true });
		updateActiveRunIndex(dir, "running", status.toolCallId);
		fs.writeFileSync(path.join(dir, "status.json"), JSON.stringify(status));
		fs.mkdirSync(path.join(root, TERMINAL_RUN_INDEX_DIR));
		// A file at the alias namespace blocks only the optional alias publication.
		fs.writeFileSync(path.join(root, TERMINAL_RUN_INDEX_DIR, "@tool-calls"), "blocked");
		const errors: unknown[][] = [];
		t.mock.method(console, "error", (...args) => { errors.push(args); });
		updateActiveRunIndex(dir, "complete", status.toolCallId, { terminalIndexBeforeRelease: true, retryCapacityErrors: true });
		assert.deepEqual(readActiveRunIndex(root), []);
		assert.deepEqual(readRecentTerminalRunIndex(root), ["retained"]);
		assert.equal(errors.length, 1);
		assert.match(String(errors[0]?.[0]), /terminal-run tool-call index/);
		assert.ok(errors[0]?.[1] instanceof Error);
	});

	it("preserves terminal alias read errors instead of treating them as missing evidence", (t) => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-terminal-alias-error-"));
		t.after(() => fs.rmSync(root, { recursive: true, force: true }));
		const dir = path.join(root, "retained");
		const toolCallId = "call-retained";
		const status: AsyncStatus = { runId: "retained", sessionId: "owner", toolCallId, mode: "single", state: "complete", startedAt: 1 };
		fs.mkdirSync(dir, { recursive: true });
		fs.writeFileSync(path.join(dir, "status.json"), JSON.stringify(status));
		updateTerminalRunIndex(dir, status);
		const marker = path.join(root, TERMINAL_RUN_INDEX_DIR, "@tool-calls", toolCallId, "retained.json");
		const readFile = fsDefault.readFileSync;
		const failure = Object.assign(new Error("terminal alias permission denied"), { code: "EACCES" });
		t.mock.method(fsDefault, "readFileSync", (file, ...args) => {
			if (String(file) === marker) throw failure;
			return Reflect.apply(readFile, fsDefault, [file, ...args]);
		});
		syncBuiltinESMExports();
		try {
			assert.throws(() => resolveSubagentRunId(toolCallId, { asyncDirRoot: root, resultsDir: path.join(root, "results") }), (error) => error === failure);
			assert.equal(fs.existsSync(marker), true);
		} finally {
			t.mock.restoreAll();
			syncBuiltinESMExports();
		}
	});

	it("prefers a newer pending payload when resolving run and tool-call ids", (t) => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-run-resolver-pending-payload-"));
		try {
			const asyncRoot = path.join(root, "async");
			const resultsDir = path.join(root, "results");
			const resultPath = resultFilePath(resultsDir, "workflow-done");
			writeAsyncResultFile(resultPath, { id: "workflow-done", runId: "workflow-done", toolCallId: "call-done", sessionId: "session-a", success: false });
			writePendingAsyncResultFile(resultPath, { id: "workflow-done", runId: "workflow-done", toolCallId: "call-done", sessionId: "session-a", success: true });

			t.mock.method(fsDefault, "renameSync", () => {
				const error = new Error("destination exists") as NodeJS.ErrnoException;
				error.code = "EEXIST";
				throw error;
			});
			syncBuiltinESMExports();

			const pendingPath = path.join(resultsDir, "result-pending", "session-a", "workflow-done.json");
			const byRunId = resolveSubagentRunId("workflow-done", { asyncDirRoot: asyncRoot, resultsDir });
			assert.equal(byRunId?.kind, "async");
			assert.equal(byRunId?.kind === "async" ? byRunId.location.resultPath : undefined, pendingPath);

			const byToolCallId = resolveSubagentRunId("call-done", { asyncDirRoot: asyncRoot, resultsDir });
			assert.equal(byToolCallId?.kind, "async");
			assert.equal(byToolCallId?.id, "workflow-done");
			assert.equal(byToolCallId?.kind === "async" ? byToolCallId.location.resultPath : undefined, pendingPath);
			assert.equal(JSON.parse(fs.readFileSync(pendingPath, "utf-8")).success, true);
			assert.equal(JSON.parse(fs.readFileSync(resultPath, "utf-8")).success, false);
		} finally {
			t.mock.restoreAll();
			syncBuiltinESMExports();
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("resolves oversized workflow tool-call ids through bounded indexes", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-run-resolver-long-tool-call-index-"));
		try {
			const asyncRoot = path.join(root, "async");
			const resultsDir = path.join(root, "results");
			const toolCallId = `call_${"界".repeat(100)}`;
			const activeDir = path.join(asyncRoot, "workflow-active-long");
			fs.mkdirSync(activeDir, { recursive: true });
			fs.writeFileSync(path.join(activeDir, "status.json"), JSON.stringify({ runId: "workflow-active-long", toolCallId, state: "running", mode: "workflow", startedAt: 1, lastUpdate: 1, steps: [] }), "utf-8");
			updateActiveRunIndex(activeDir, "running", toolCallId);

			assert.equal(resolveSubagentRunId(toolCallId, { asyncDirRoot: asyncRoot, resultsDir })?.id, "workflow-active-long");
			releaseActiveRunIndex(activeDir);

			writeAsyncResultFile(resultFilePath(resultsDir, "workflow-done-long"), { id: "workflow-done-long", runId: "workflow-done-long", toolCallId, sessionId: "session-a", state: "complete", success: true });
			assert.equal(resolveSubagentRunId(toolCallId, { asyncDirRoot: asyncRoot, resultsDir })?.id, "workflow-done-long");
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("rejects unsafe nested id tokens before lookup", () => {
		assert.throws(() => resolveSubagentRunId("../run"), /safe id token/);
		assert.throws(() => resolveSubagentRunId("a/b"), /safe id token/);
		assert.throws(() => resolveSubagentRunId(""), /safe id token/);
	});
});
