import assert from "node:assert/strict";
import { execFileSync } from "node:child_process";
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 { writeWorkflowLaunchRecord } from "../../src/workflows/workflow-launch-record.ts";
import { applySteeringRecoveryAgentConfig, asyncReviveRequiresRecoveryDescriptor, buildRevivedAsyncTask, resolveAsyncResumeTarget } from "../../src/runs/background/async-resume.ts";
import type { AgentConfig } from "../../src/agents/agents.ts";
import { createRunFanoutBudget } from "../../src/runs/shared/run-fanout-budget.ts";
import { parallelHandoffPath, writeParallelHandoffGroup, writeWorktreeSetupHandoff } from "../../src/runs/shared/parallel-handoff.ts";
import { cleanupWorktrees, createWorktrees } from "../../src/runs/shared/worktree.ts";
import { recordSessionReplacement } from "../../src/shared/session-succession.ts";
import { recoveryDescriptorPath } from "../../src/runs/shared/run-launch-folder.ts";

function writeJson(filePath: string, value: object): void {
	fs.mkdirSync(path.dirname(filePath), { recursive: true });
	fs.writeFileSync(filePath, JSON.stringify(value, null, 2), "utf-8");
}

describe("async resume lookup", () => {
	it("resolves a completed single-child run from persisted status", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const sessionFile = path.join(root, "session.jsonl");
			fs.writeFileSync(sessionFile, "", "utf-8");
			writeJson(path.join(asyncRoot, "run-abcde", "status.json"), {
				runId: "run-abcde",
				mode: "single",
				state: "complete",
				startedAt: 100,
				endedAt: 200,
				lastUpdate: 200,
				cwd: root,
				sessionFile,
				steps: [{ agent: "worker", status: "complete" }],
			});

			const target = resolveAsyncResumeTarget({ id: "run-abcd" }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") });

			assert.equal(target.kind, "revive");
			assert.equal(target.runId, "run-abcde");
			assert.equal(target.agent, "worker");
			assert.equal(target.sessionFile, sessionFile);
			assert.equal(target.cwd, root);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("says a missing forked session copy was removed by cleanup", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-fork-gone-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const sessionFile = path.join(root, "parent", "forks", "run-fork1", "child.jsonl");
			writeJson(path.join(asyncRoot, "run-fork1", "status.json"), {
				runId: "run-fork1", mode: "single", state: "complete", startedAt: 100, endedAt: 200, lastUpdate: 200, cwd: root, sessionFile,
				steps: [{ agent: "worker", status: "complete" }],
			});

			assert.throws(
				() => resolveAsyncResumeTarget({ id: "run-fork1" }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") }),
				/session file does not exist: .*child\.jsonl\. It was a forked child's copy of the parent session; such copies are deleted once nothing has written to them for artifactConfig\.cleanupDays days/,
			);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("refuses a run directory whose status names another run", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-mismatch-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const sessionFile = path.join(root, "session.jsonl");
			fs.writeFileSync(sessionFile, "", "utf-8");
			writeJson(path.join(asyncRoot, "run-abcde", "status.json"), {
				runId: "run-other", mode: "single", state: "running", pid: 2147483646, sessionId: sessionFile, startedAt: 100, lastUpdate: 200, cwd: root, sessionFile,
				steps: [{ agent: "worker", status: "running" }],
			});
			assert.throws(
				() => resolveAsyncResumeTarget({ id: "run-abcd" }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") }),
				/Async run 'run-abcde' has a status file for a different run 'run-other'/,
			);
			// Refused before stale-run repair, which would publish a failed result under the other run's id.
			assert.equal(fs.existsSync(path.join(root, "results")) && fs.readdirSync(path.join(root, "results")).length > 0, false);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("requires a recovery descriptor for a legacy workflow child session", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-workflow-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const resultsDir = path.join(root, "results");
			const sessionFile = path.join(root, "child-session.jsonl");
			fs.writeFileSync(sessionFile, "", "utf-8");
			writeJson(path.join(asyncRoot, "workflow-1", "status.json"), {
				runId: "workflow-1",
				mode: "workflow",
				state: "failed",
				startedAt: 100,
				endedAt: 200,
				lastUpdate: 200,
				cwd: root,
				steps: [{ agent: "worker", status: "failed", sessionFile, runId: "child-1" }],
			});

			const target = resolveAsyncResumeTarget({ id: "workflow-1" }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") });

			assert.equal(target.kind, "revive");
			assert.equal(target.mode, "workflow");
			assert.equal(target.agent, "worker");
			assert.equal(target.sessionFile, sessionFile);
			assert.equal(target.recoveryDescriptor, undefined);
			assert.equal(asyncReviveRequiresRecoveryDescriptor(target), true);
			assert.equal(asyncReviveRequiresRecoveryDescriptor({}), true);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("uses a current workflow's persisted parent admission authority", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-current-workflow-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const resultsDir = path.join(root, "results");
			const sessionFile = path.join(root, "child-session.jsonl");
			const parentAuthority = { version: 1 as const, allowedAgents: ["researcher", "worker"], denyExtensions: false, sources: ["workflow-parent"] };
			const statusAuthority = { version: 1 as const, allowedAgents: ["anything"], denyExtensions: false, sources: ["status"] };
			fs.writeFileSync(sessionFile, "", "utf-8");
			writeWorkflowLaunchRecord(asyncRoot, "workflow-2", { version: 2, sessionId: "session", source: "structured", scriptDigest: "d", admissionCapabilityCeiling: parentAuthority });
			writeJson(path.join(asyncRoot, "workflow-2", "status.json"), {
				runId: "workflow-2", mode: "workflow", state: "complete", startedAt: 100, endedAt: 200, lastUpdate: 200, cwd: root,
				admissionCapabilityCeiling: statusAuthority,
				steps: [{ agent: "worker", status: "complete", sessionFile, capabilityCeiling: { version: 1, allowedAgents: ["researcher"], denyExtensions: false, sources: ["agent:worker"] } }],
			});

			const target = resolveAsyncResumeTarget({ id: "workflow-2" }, { asyncDirRoot: asyncRoot, resultsDir });

			assert.deepEqual(target.capabilityCeiling, parentAuthority);
			assert.equal(asyncReviveRequiresRecoveryDescriptor(target), false);

			fs.rmSync(path.join(asyncRoot, "workflow-2"), { recursive: true });
			writeJson(path.join(resultsDir, "workflow-2.json"), {
				runId: "workflow-2", mode: "workflow", state: "complete", success: true, cwd: root,
				admissionCapabilityCeiling: parentAuthority,
				results: [{ agent: "worker", success: true, sessionFile }],
			});
			// The shared results directory is writable by runs, so a result file alone does not give a ceiling.
			const resultOnly = resolveAsyncResumeTarget({ id: "workflow-2" }, { asyncDirRoot: asyncRoot, resultsDir });
			assert.equal(resultOnly.capabilityCeiling, undefined);
			assert.equal(asyncReviveRequiresRecoveryDescriptor(resultOnly), true);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("requires a recovery descriptor for a run that wrote a workflow status into its own directory", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-forged-workflow-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const sessionFile = path.join(root, "other-session.jsonl");
			fs.writeFileSync(sessionFile, "", "utf-8");
			writeJson(path.join(asyncRoot, "single-1", "status.json"), {
				runId: "single-1", mode: "workflow", state: "complete", startedAt: 100, endedAt: 200, lastUpdate: 200, cwd: root,
				admissionCapabilityCeiling: { version: 1, allowedAgents: ["worker"], denyExtensions: false, sources: ["forged"] },
				steps: [{ agent: "worker", status: "complete", sessionFile }],
			});
			const target = resolveAsyncResumeTarget({ id: "single-1" }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") });
			assert.equal(target.capabilityCeiling, undefined);
			assert.equal(asyncReviveRequiresRecoveryDescriptor(target), true);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("resolves a retained managed worktree cwd and fails closed when it is missing", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-missing-cwd-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const asyncDir = path.join(asyncRoot, "run-missing-cwd");
			const sessionFile = path.join(root, "session.jsonl");
			const worktreeCwd = path.join(root, "managed-worktree");
			fs.writeFileSync(sessionFile, "", "utf-8");
			fs.mkdirSync(worktreeCwd);
			writeJson(path.join(asyncDir, "status.json"), {
				runId: "run-missing-cwd", mode: "single", state: "complete", startedAt: 100, endedAt: 200, lastUpdate: 200,
				cwd: root,
				steps: [{ agent: "worker", status: "complete", sessionFile }],
			});
			writeJson(path.join(asyncDir, "handoff.json"), {
				version: 1, runId: "run-missing-cwd", mode: "single", source: "async", cwd: root, createdAt: 100, updatedAt: 200,
				groups: [{
					stepIndex: 0, baseCommit: "deadbeef", repoRoot: root,
					children: [{ index: 0, taskIndex: 0, agent: "worker", status: "completed", summary: "done", patch: { path: path.join(root, "patch"), branch: "branch", changed: false, diffStat: "", filesChanged: 0, insertions: 0, deletions: 0 } }],
					cleanup: { state: "partial", pruned: true, tasks: [{ index: 0, path: worktreeCwd, branch: "branch", worktreeRemoved: false, branchRemoved: false, preserved: true }] },
				}],
			});

			const target = resolveAsyncResumeTarget({ id: "run-missing-cwd" }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") });
			assert.equal(target.cwd, worktreeCwd);
			assert.equal(target.managedWorktree, true);
			fs.rmSync(worktreeCwd, { recursive: true });

			assert.throws(
				() => resolveAsyncResumeTarget({ id: "run-missing-cwd" }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") }),
				/required managed worktree cwd is missing/,
			);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("takes a managed worktree cwd from handoff.json only when it is the worktree the launch chose", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-forged-handoff-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const asyncDir = path.join(asyncRoot, "run-forged-handoff");
			const sessionFile = path.join(root, "session.jsonl");
			const launchedWorktree = path.join(root, "launched-worktree");
			const victimRepo = path.join(root, "victim-repo");
			fs.writeFileSync(sessionFile, "", "utf-8");
			fs.mkdirSync(launchedWorktree);
			fs.mkdirSync(victimRepo);
			writeJson(path.join(asyncDir, "status.json"), {
				runId: "run-forged-handoff", mode: "single", state: "complete", startedAt: 100, endedAt: 200, lastUpdate: 200, cwd: root,
				steps: [{ agent: "worker", status: "complete", sessionFile }],
			});
			// The run wrote this into its own folder: cwd === repoRoot makes the cwd the cleanup path itself.
			const handoffTo = (worktree: string) => writeJson(path.join(asyncDir, "handoff.json"), {
				version: 1, runId: "run-forged-handoff", mode: "single", source: "async", cwd: root, createdAt: 100, updatedAt: 200,
				groups: [{
					stepIndex: 0, baseCommit: "deadbeef", repoRoot: root,
					children: [{ index: 0, taskIndex: 0, agent: "worker", status: "completed", summary: "done", patch: { path: path.join(root, "patch"), branch: "branch", changed: false, diffStat: "", filesChanged: 0, insertions: 0, deletions: 0 } }],
					cleanup: { state: "partial", pruned: true, tasks: [{ index: 0, path: worktree, branch: "branch", worktreeRemoved: false, branchRemoved: false, preserved: true }] },
				}],
			});
			const descriptor = (managedWorktree?: unknown) => writeJson(recoveryDescriptorPath(path.dirname(asyncDir), path.basename(asyncDir)), {
				version: 1, runFanoutBudget: createRunFanoutBudget("run-forged-handoff", 64), sourceRunId: "run-forged-handoff", agent: "worker", sessionFile, cwd: root,
				systemPromptMode: "replace", inheritProjectContext: false, inheritGlobalContext: false, inheritSkills: false, outputMode: "inline", maxSubagentDepth: 2, share: false,
				...(managedWorktree ? { managedWorktree } : {}),
			});
			const resume = () => resolveAsyncResumeTarget({ id: "run-forged-handoff" }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") });
			handoffTo(victimRepo);

			descriptor();
			assert.deepEqual({ cwd: resume().cwd, managedWorktree: resume().managedWorktree }, { cwd: root, managedWorktree: undefined }, "a run launched without a worktree keeps the launch cwd");
			descriptor({ provider: "native", cwd: launchedWorktree });
			assert.throws(resume, /managed worktree .*victim-repo is not the worktree its launch created/);
			handoffTo(launchedWorktree);
			assert.equal(resume().cwd, launchedWorktree);
			// Without handoff.json the recorded worktree is still required; the source checkout is never used.
			fs.rmSync(path.join(asyncDir, "handoff.json"));
			assert.equal(resume().cwd, launchedWorktree);
			fs.rmSync(launchedWorktree, { recursive: true });
			assert.throws(resume, /ran in a managed worktree .* that no longer exists; it cannot resume in the source checkout/);

			// Worktrunk picks the path itself, so git must list it on the branch the launch requested.
			const repo = path.join(root, "repo");
			const git = (...args: string[]) => execFileSync("git", ["-C", repo, ...args], { encoding: "utf-8" });
			fs.mkdirSync(repo);
			git("init", "-q");
			git("-c", "user.email=t@example.com", "-c", "user.name=t", "commit", "-q", "--allow-empty", "-m", "init");
			const worktrunkPath = path.join(root, "wt-launched");
			git("worktree", "add", "-q", "-b", "pi/launched", worktrunkPath);
			writeJson(recoveryDescriptorPath(path.dirname(asyncDir), path.basename(asyncDir)), { ...JSON.parse(fs.readFileSync(recoveryDescriptorPath(path.dirname(asyncDir), path.basename(asyncDir)), "utf-8")), cwd: repo, managedWorktree: { provider: "worktrunk", branch: "pi/launched" } });
			handoffTo(victimRepo);
			assert.throws(resume, /is not the worktree its launch created/);
			handoffTo(worktrunkPath);
			assert.equal(fs.realpathSync.native(resume().cwd!), fs.realpathSync.native(worktrunkPath));
			fs.rmSync(path.join(asyncDir, "handoff.json"));
			assert.equal(fs.realpathSync.native(resume().cwd!), fs.realpathSync.native(worktrunkPath));
			git("worktree", "remove", "--force", worktrunkPath);
			assert.throws(resume, /branch pi\/launched\) that no longer exists/);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("trusts no recovery record for a run folder that is not directly under the runs root", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-nested-forgery-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const sessionFile = path.join(root, "session.jsonl");
			fs.writeFileSync(sessionFile, "", "utf-8");
			// A sandboxed run builds a runs-shaped tree inside its own folder and names it with `dir`.
			const ownDir = path.join(asyncRoot, "own-run");
			const fakeDir = path.join(ownDir, "fake-runs", "fake-run");
			writeJson(path.join(fakeDir, "status.json"), { runId: "fake-run", mode: "single", state: "complete", startedAt: 100, endedAt: 200, lastUpdate: 200, cwd: root, steps: [{ agent: "worker", status: "complete", sessionFile }] });
			writeJson(recoveryDescriptorPath(path.join(ownDir, "fake-runs"), "fake-run"), {
				version: 1, runFanoutBudget: createRunFanoutBudget("fake-run", 64), sourceRunId: "fake-run", agent: "worker", sessionFile, cwd: root, launcher: null,
				systemPromptMode: "replace", inheritProjectContext: false, inheritGlobalContext: false, inheritSkills: false, outputMode: "inline", maxSubagentDepth: 2, share: false,
			});
			const target = resolveAsyncResumeTarget({ dir: fakeDir }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") });
			assert.equal(target.recoveryDescriptor, undefined);
			assert.equal(asyncReviveRequiresRecoveryDescriptor(target), true);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("refuses to revive a worktree child in the source checkout while its runner is finalizing", async () => {
		// Git reports the long Windows path; a short 8.3 temp path would fail the cwd containment check first.
		const root = fs.realpathSync.native(fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-finalizing-")));
		const repo = path.join(root, "repo");
		const asyncDir = path.join(root, "runs", "run-finalizing");
		const manifestPath = parallelHandoffPath(asyncDir);
		const git = (...args: string[]) => execFileSync("git", ["-C", repo, ...args], { encoding: "utf-8" });
		fs.mkdirSync(repo);
		git("init", "-q");
		fs.writeFileSync(path.join(repo, "a.txt"), "a", "utf-8");
		git("add", ".");
		git("-c", "user.email=t@example.com", "-c", "user.name=t", "commit", "-qm", "init");
		const handoff = { manifestPath, runId: "run-finalizing", mode: "single" as const, source: "async" as const, cwd: repo, stepIndex: 0, flatStartIndex: 0 };
		const setup = await createWorktrees(repo, "run-finalizing-s0", 1, { baseDir: path.join(root, "worktrees"), onProgress: (progress) => { writeWorktreeSetupHandoff({ ...handoff, progress }); } });
		try {
			const sessionFile = path.join(root, "session.jsonl");
			fs.writeFileSync(sessionFile, "", "utf-8");
			// Interrupt marks the run paused before the runner captures the child's handoff.
			writeJson(path.join(asyncDir, "status.json"), {
				runId: "run-finalizing", mode: "single", state: "paused", startedAt: 100, lastUpdate: 200, cwd: repo,
				steps: [{ agent: "worker", status: "paused", sessionFile, worktreePath: setup.worktrees[0]!.path, branch: setup.worktrees[0]!.branch }],
			});
			const resume = () => resolveAsyncResumeTarget({ id: "run-finalizing" }, { asyncDirRoot: path.join(root, "runs"), resultsDir: path.join(root, "results") });

			assert.throws(resume, /handoff has no resumable record yet/);
			writeParallelHandoffGroup({ ...handoff, setup, diffs: [], results: [{ agent: "worker", status: "paused", summary: "paused", sessionPath: sessionFile }] });
			assert.throws(resume, /still finalizing its managed worktree/);
		} finally {
			cleanupWorktrees(setup);
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("resolves a retained managed worktree cwd in the original repository subdirectory", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-nested-cwd-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const asyncDir = path.join(asyncRoot, "run-nested-cwd");
			const repoRoot = path.join(root, "repo");
			const repoCwd = path.join(repoRoot, "packages", "feature");
			const worktreeRoot = path.join(root, "managed-worktree");
			const worktreeCwd = path.join(worktreeRoot, "packages", "feature");
			const sessionFile = path.join(root, "session.jsonl");
			fs.mkdirSync(repoCwd, { recursive: true });
			fs.mkdirSync(worktreeCwd, { recursive: true });
			fs.writeFileSync(sessionFile, "", "utf-8");
			writeJson(path.join(asyncDir, "status.json"), {
				runId: "run-nested-cwd", mode: "single", state: "complete", startedAt: 100, endedAt: 200, lastUpdate: 200,
				cwd: repoCwd,
				steps: [{ agent: "worker", status: "complete", sessionFile }],
			});
			writeJson(path.join(asyncDir, "handoff.json"), {
				version: 1, runId: "run-nested-cwd", mode: "single", source: "async", cwd: repoCwd, createdAt: 100, updatedAt: 200,
				groups: [{
					stepIndex: 0, baseCommit: "deadbeef", repoRoot,
					children: [{ index: 0, taskIndex: 0, agent: "worker", status: "completed", summary: "done", patch: { path: path.join(root, "patch"), branch: "branch", changed: false, diffStat: "", filesChanged: 0, insertions: 0, deletions: 0 } }],
					cleanup: { state: "partial", pruned: true, tasks: [{ index: 0, path: worktreeRoot, branch: "branch", worktreeRemoved: false, branchRemoved: false, preserved: true }] },
				}],
			});

			const target = resolveAsyncResumeTarget({ id: "run-nested-cwd" }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") });
			assert.equal(target.cwd, worktreeCwd);
			assert.equal(target.managedWorktree, true);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("resumes a normal child when a sibling has a managed worktree handoff", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-mixed-cwd-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const asyncDir = path.join(asyncRoot, "run-mixed-cwd");
			const worktreeCwd = path.join(root, "managed-worktree");
			const sessionFile = path.join(root, "session.jsonl");
			fs.mkdirSync(worktreeCwd);
			fs.writeFileSync(sessionFile, "", "utf-8");
			writeJson(path.join(asyncDir, "status.json"), {
				runId: "run-mixed-cwd", mode: "parallel", state: "complete", startedAt: 100, endedAt: 200, lastUpdate: 200, cwd: root,
				steps: [{ agent: "worktree-worker", status: "complete" }, { agent: "normal-worker", status: "complete", sessionFile }],
			});
			writeJson(path.join(asyncDir, "handoff.json"), {
				version: 1, runId: "run-mixed-cwd", mode: "parallel", source: "async", cwd: root, createdAt: 100, updatedAt: 200,
				groups: [{
					stepIndex: 0, baseCommit: "deadbeef", repoRoot: root,
					children: [{ index: 0, taskIndex: 0, agent: "worktree-worker", status: "completed", summary: "done", patch: { path: path.join(root, "patch"), branch: "branch", changed: false, diffStat: "", filesChanged: 0, insertions: 0, deletions: 0 } }],
					cleanup: { state: "partial", pruned: true, tasks: [{ index: 0, path: worktreeCwd, branch: "branch", worktreeRemoved: false, branchRemoved: false, preserved: true }] },
				}],
			});

			const target = resolveAsyncResumeTarget({ id: "run-mixed-cwd", index: 1 }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") });
			assert.equal(target.agent, "normal-worker");
			assert.equal(target.cwd, root);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("rejects a retained managed worktree cwd that resolves outside the preserved worktree", (context) => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-escaped-cwd-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const asyncDir = path.join(asyncRoot, "run-escaped-cwd");
			const repoRoot = path.join(root, "repo");
			const repoCwd = path.join(repoRoot, "pkg");
			const worktreeRoot = path.join(root, "managed-worktree");
			const outsideCwd = path.join(root, "outside");
			const sessionFile = path.join(root, "session.jsonl");
			fs.mkdirSync(repoCwd, { recursive: true });
			fs.mkdirSync(worktreeRoot);
			fs.mkdirSync(outsideCwd);
			fs.writeFileSync(sessionFile, "", "utf-8");
			try {
				fs.symlinkSync(outsideCwd, path.join(worktreeRoot, "pkg"), "dir");
			} catch (error) {
				const code = (error as NodeJS.ErrnoException).code;
				if (code === "EPERM" || code === "EACCES") {
					context.skip("directory symlink creation is unavailable");
					return;
				}
				throw error;
			}
			writeJson(path.join(asyncDir, "status.json"), {
				runId: "run-escaped-cwd", mode: "single", state: "complete", startedAt: 100, endedAt: 200, lastUpdate: 200,
				cwd: repoCwd,
				steps: [{ agent: "worker", status: "complete", sessionFile }],
			});
			writeJson(path.join(asyncDir, "handoff.json"), {
				version: 1, runId: "run-escaped-cwd", mode: "single", source: "async", cwd: repoCwd, createdAt: 100, updatedAt: 200,
				groups: [{
					stepIndex: 0, baseCommit: "deadbeef", repoRoot,
					children: [{ index: 0, taskIndex: 0, agent: "worker", status: "completed", summary: "done", patch: { path: path.join(root, "patch"), branch: "branch", changed: false, diffStat: "", filesChanged: 0, insertions: 0, deletions: 0 } }],
					cleanup: { state: "partial", pruned: true, tasks: [{ index: 0, path: worktreeRoot, branch: "branch", worktreeRemoved: false, branchRemoved: false, preserved: true }] },
				}],
			});

			assert.throws(
				() => resolveAsyncResumeTarget({ id: "run-escaped-cwd" }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") }),
				/invalid managed worktree cwd/,
			);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("preserves and validates persisted capability ceilings for resume", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-ceiling-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const asyncDir = path.join(asyncRoot, "run-ceiling");
			const resultsDir = path.join(root, "results");
			const sessionFile = path.join(root, "session.jsonl");
			fs.writeFileSync(sessionFile, "", "utf-8");
			writeJson(path.join(asyncDir, "status.json"), {
				runId: "run-ceiling", mode: "single", state: "complete", startedAt: 100, endedAt: 200, lastUpdate: 200, cwd: root,
				capabilityCeiling: { version: 1, allowedTools: ["read", "write"], denyExtensions: true, sources: ["run"] },
				steps: [{ agent: "worker", status: "complete", sessionFile, capabilityCeiling: { version: 1, allowedTools: ["read"], denyExtensions: false, sources: ["step"] } }],
			});

			const target = resolveAsyncResumeTarget({ id: "run-ceiling" }, { asyncDirRoot: asyncRoot, resultsDir });
			assert.deepEqual(target.capabilityCeiling, { version: 1, allowedTools: ["read"], denyExtensions: true, sources: ["run", "step"] });

			writeJson(path.join(asyncDir, "status.json"), {
				runId: "run-ceiling", mode: "single", state: "complete", startedAt: 100, endedAt: 200, lastUpdate: 200, cwd: root,
				capabilityCeiling: { version: 2, allowedTools: ["read"], denyExtensions: true, sources: ["run"] },
				steps: [{ agent: "worker", status: "complete", sessionFile }],
			});
			assert.throws(() => resolveAsyncResumeTarget({ id: "run-ceiling" }, { asyncDirRoot: asyncRoot, resultsDir }), /capabilityCeiling version/);

			fs.rmSync(asyncDir, { recursive: true, force: true });
			writeJson(path.join(resultsDir, "run-ceiling.json"), {
				runId: "run-ceiling", mode: "single", state: "complete", success: true, cwd: root,
				capabilityCeiling: { version: 1, allowedTools: ["read", "grep"], denyExtensions: false, sources: ["result"] },
				results: [{ agent: "worker", success: true, sessionFile, capabilityCeiling: { version: 1, allowedTools: ["read"], denyExtensions: true, sources: ["result-step"] } }],
			});
			const resultOnly = resolveAsyncResumeTarget({ id: "run-ceiling" }, { asyncDirRoot: asyncRoot, resultsDir });
			assert.deepEqual(resultOnly.capabilityCeiling, { version: 1, allowedTools: ["read"], denyExtensions: true, sources: ["result", "result-step"] });

			writeJson(path.join(resultsDir, "run-ceiling.json"), {
				runId: "run-ceiling", mode: "single", state: "complete", success: true, cwd: root,
				results: [{ agent: "worker", success: true, sessionFile, capabilityCeiling: { version: 1, allowedTools: ["read"], denyExtensions: true } }],
			});
			assert.throws(() => resolveAsyncResumeTarget({ id: "run-ceiling" }, { asyncDirRoot: asyncRoot, resultsDir }), /capabilityCeiling sources/);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("rejects unknown and cross-run recovery descriptors and takes the run's identity from the descriptor", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-descriptor-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const asyncDir = path.join(asyncRoot, "run-descriptor");
			const resultsDir = path.join(root, "results");
			const sessionFile = path.join(root, "session.jsonl");
			fs.writeFileSync(sessionFile, "", "utf-8");
			writeJson(path.join(asyncDir, "status.json"), {
				runId: "run-descriptor", mode: "single", state: "paused", startedAt: 100, lastUpdate: 200, cwd: root,
				steps: [{ agent: "worker", status: "paused", sessionFile }],
			});
			const descriptor = {
				version: 1, runFanoutBudget: createRunFanoutBudget("run-descriptor", 64), sourceRunId: "run-descriptor", agent: "worker", sessionFile, cwd: root, systemPromptMode: "replace",
				inheritProjectContext: false, inheritGlobalContext: false, inheritSkills: false, outputMode: "inline", maxSubagentDepth: 2, share: false,
			};
			writeJson(recoveryDescriptorPath(path.dirname(asyncDir), path.basename(asyncDir)), { ...descriptor, token: "must-not-be-accepted" });
			assert.throws(() => resolveAsyncResumeTarget({ id: "run-descriptor" }, { asyncDirRoot: asyncRoot, resultsDir }), /unknown field 'token'/);

			writeJson(recoveryDescriptorPath(path.dirname(asyncDir), path.basename(asyncDir)), {
				...descriptor,
				capabilityCeiling: { version: 1, allowedTools: ["read"], denyExtensions: true },
			});
			assert.throws(() => resolveAsyncResumeTarget({ id: "run-descriptor" }, { asyncDirRoot: asyncRoot, resultsDir }), /capabilityCeiling sources/);

			writeJson(recoveryDescriptorPath(path.dirname(asyncDir), path.basename(asyncDir)), {
				...descriptor,
				launchContractDigest: "launch-contract-digest",
				allowNestedSubagents: true,
				allowedAgents: ["worker", "scout", "worker"],
				intercomBridge: { mode: "off" },
				extensionBindings: { "shepherd.dispatch/1": { role: "coder" } },
				requiredExtensions: [{ id: "provider", path: path.join(root, "provider.mjs") }],
			});
			const valid = resolveAsyncResumeTarget({ id: "run-descriptor" }, { asyncDirRoot: asyncRoot, resultsDir });
			assert.equal(valid.launchContractDigest, "launch-contract-digest");
			assert.equal(valid.recoveryDescriptor?.launchContractDigest, "launch-contract-digest");
			assert.equal(valid.recoveryDescriptor?.allowNestedSubagents, true);
			assert.deepEqual(valid.recoveryDescriptor?.allowedAgents, ["scout", "worker"]);
			assert.deepEqual(valid.recoveryDescriptor?.intercomBridge, { mode: "off" });
			assert.deepEqual(valid.recoveryDescriptor?.extensionBindings, { "shepherd.dispatch/1": { role: "coder" } });
			assert.deepEqual(valid.recoveryDescriptor?.requiredExtensions, [{ id: "provider", path: path.join(root, "provider.mjs") }]);
			assert.ok(Object.isFrozen(valid.recoveryDescriptor?.requiredExtensions));
			const currentAgent = {
				name: "worker", description: "Current", systemPrompt: "Current", systemPromptMode: "replace",
				inheritProjectContext: false, inheritGlobalContext: false, inheritSkills: false,
				source: "project", filePath: "/current/worker.md", allowedAgents: ["reviewer", "worker"],
			} as AgentConfig;
			assert.deepEqual(applySteeringRecoveryAgentConfig(currentAgent, valid.recoveryDescriptor!).allowedAgents, ["scout", "worker"]);

			writeJson(recoveryDescriptorPath(path.dirname(asyncDir), path.basename(asyncDir)), { ...descriptor, allowedAgents: [] });
			const denied = resolveAsyncResumeTarget({ id: "run-descriptor" }, { asyncDirRoot: asyncRoot, resultsDir });
			assert.deepEqual(applySteeringRecoveryAgentConfig(currentAgent, denied.recoveryDescriptor!).allowedAgents, []);

			writeJson(recoveryDescriptorPath(path.dirname(asyncDir), path.basename(asyncDir)), descriptor);
			const unrestricted = resolveAsyncResumeTarget({ id: "run-descriptor" }, { asyncDirRoot: asyncRoot, resultsDir });
			assert.equal(applySteeringRecoveryAgentConfig(currentAgent, unrestricted.recoveryDescriptor!).allowedAgents, undefined);

			writeJson(recoveryDescriptorPath(path.dirname(asyncDir), path.basename(asyncDir)), { ...descriptor, allowNestedSubagents: "true" });
			assert.throws(() => resolveAsyncResumeTarget({ id: "run-descriptor" }, { asyncDirRoot: asyncRoot, resultsDir }), /allowNestedSubagents/);

			writeJson(recoveryDescriptorPath(path.dirname(asyncDir), path.basename(asyncDir)), { ...descriptor, allowedAgents: ["bad name"] });
			assert.throws(() => resolveAsyncResumeTarget({ id: "run-descriptor" }, { asyncDirRoot: asyncRoot, resultsDir }), /allowedAgents entry 'bad name'/);

			writeJson(recoveryDescriptorPath(path.dirname(asyncDir), path.basename(asyncDir)), { ...descriptor, extensionBindings: { invalid: true } });
			assert.throws(() => resolveAsyncResumeTarget({ id: "run-descriptor" }, { asyncDirRoot: asyncRoot, resultsDir }), /namespace/);

			writeJson(recoveryDescriptorPath(path.dirname(asyncDir), path.basename(asyncDir)), { ...descriptor, requiredExtensions: [{ id: "unsafe id", path: "/provider.mjs" }] });
			assert.throws(() => resolveAsyncResumeTarget({ id: "run-descriptor" }, { asyncDirRoot: asyncRoot, resultsDir }), /safe id/);

			writeJson(recoveryDescriptorPath(path.dirname(asyncDir), path.basename(asyncDir)), { ...descriptor, sourceRunId: "another-run" });
			assert.throws(() => resolveAsyncResumeTarget({ id: "run-descriptor" }, { asyncDirRoot: asyncRoot, resultsDir }), /different source run/);

			// With a descriptor, status.json does not choose the agent, transcript, cwd or ceiling: a run
			// behind a runner launcher can rewrite it to point at another run's transcript.
			const otherTranscript = path.join(root, "other-run-session.jsonl");
			fs.writeFileSync(otherTranscript, "", "utf-8");
			fs.mkdirSync(path.join(root, "elsewhere"));
			writeJson(path.join(asyncDir, "status.json"), {
				runId: "run-descriptor", mode: "workflow", state: "paused", startedAt: 100, lastUpdate: 200, cwd: path.join(root, "elsewhere"),
				capabilityCeiling: { version: 1, allowedTools: ["bash"], denyExtensions: false, sources: ["forged"] },
				steps: [{ agent: "another-agent", status: "paused", sessionFile: otherTranscript, model: "forged/model" }],
			});
			writeJson(recoveryDescriptorPath(path.dirname(asyncDir), path.basename(asyncDir)), { ...descriptor, capabilityCeiling: { version: 1, allowedTools: ["read"], denyExtensions: true, sources: ["launch"] } });
			const fromDescriptor = resolveAsyncResumeTarget({ id: "run-descriptor" }, { asyncDirRoot: asyncRoot, resultsDir });
			assert.deepEqual(
				{ mode: fromDescriptor.mode, agent: fromDescriptor.agent, sessionFile: fromDescriptor.sessionFile, cwd: fromDescriptor.cwd, model: fromDescriptor.model, capabilityCeiling: fromDescriptor.capabilityCeiling },
				{ mode: "single", agent: "worker", sessionFile, cwd: root, model: undefined, capabilityCeiling: { version: 1, allowedTools: ["read"], denyExtensions: true, sources: ["launch"] } },
			);
			// The owner is the descriptor's session too, whatever status.json claims.
			writeJson(recoveryDescriptorPath(path.dirname(asyncDir), path.basename(asyncDir)), { ...descriptor, sessionId: "owner-session" });
			writeJson(path.join(asyncDir, "status.json"), { runId: "run-descriptor", sessionId: "intruder-session", mode: "single", state: "paused", startedAt: 100, lastUpdate: 200, cwd: root, steps: [{ agent: "worker", status: "paused", sessionFile }] });
			assert.equal(resolveAsyncResumeTarget({ id: "run-descriptor" }, { asyncDirRoot: asyncRoot, resultsDir }, { sessionId: "owner-session" }).agent, "worker");
			assert.throws(() => resolveAsyncResumeTarget({ id: "run-descriptor" }, { asyncDirRoot: asyncRoot, resultsDir }, { sessionId: "intruder-session" }), /not found in the active session/);
			// A descriptor left in the run folder by an earlier version is not read.
			fs.rmSync(recoveryDescriptorPath(path.dirname(asyncDir), path.basename(asyncDir)));
			writeJson(path.join(asyncDir, "recovery-descriptor.json"), descriptor);
			const legacy = resolveAsyncResumeTarget({ id: "run-descriptor" }, { asyncDirRoot: asyncRoot, resultsDir });
			assert.equal(legacy.recoveryDescriptor, undefined);
			assert.equal(asyncReviveRequiresRecoveryDescriptor(legacy), true);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("ignores removed turn budgets in persisted recovery descriptors", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-turn-budget-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const asyncDir = path.join(asyncRoot, "run-turn-budget");
			const resultsDir = path.join(root, "results");
			const sessionFile = path.join(root, "session.jsonl");
			fs.writeFileSync(sessionFile, "", "utf-8");
			writeJson(path.join(asyncDir, "status.json"), {
				runId: "run-turn-budget", mode: "single", state: "paused", startedAt: 100, lastUpdate: 200, cwd: root,
				steps: [{ agent: "worker", status: "paused", sessionFile }],
			});
			const descriptor = {
				version: 1,
				runFanoutBudget: createRunFanoutBudget("run-turn-budget", 64),
				sourceRunId: "run-turn-budget",
				agent: "worker",
				sessionFile,
				cwd: root,
				systemPromptMode: "replace",
				inheritGlobalContext: false,
				inheritProjectContext: false,
				inheritSkills: false,
				outputMode: "inline",
				maxSubagentDepth: 2,
				share: false,
			};
			writeJson(recoveryDescriptorPath(path.dirname(asyncDir), path.basename(asyncDir)), {
				...descriptor,
				initialTurnBudget: {
					maxTurns: 8,
					graceTurns: 2,
					outcome: "within-budget",
					turnCount: 0,
					wrapUpRequestedAtTurn: 8,
					terminationDeferredAtTurn: 10,
					exceededAtTurn: 11,
				},
			});

			const target = resolveAsyncResumeTarget({ id: "run-turn-budget" }, { asyncDirRoot: asyncRoot, resultsDir });

			assert.equal("initialTurnBudget" in (target.recoveryDescriptor ?? {}), false);

			writeJson(recoveryDescriptorPath(path.dirname(asyncDir), path.basename(asyncDir)), {
				...descriptor,
				initialTurnBudget: { maxTurns: 8, graceTurns: 2, unrelated: true },
			});
			const malformedLegacy = resolveAsyncResumeTarget({ id: "run-turn-budget" }, { asyncDirRoot: asyncRoot, resultsDir });
			assert.equal("initialTurnBudget" in (malformedLegacy.recoveryDescriptor ?? {}), false);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("accepts current acceptance metadata in recovery descriptors", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-acceptance-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const asyncDir = path.join(asyncRoot, "run-acceptance");
			const resultsDir = path.join(root, "results");
			const sessionFile = path.join(root, "session.jsonl");
			fs.writeFileSync(sessionFile, "", "utf-8");
			writeJson(path.join(asyncDir, "status.json"), {
				runId: "run-acceptance", mode: "single", state: "paused", startedAt: 100, lastUpdate: 200, cwd: root,
				steps: [{ agent: "worker", status: "paused", sessionFile }],
			});
			writeJson(recoveryDescriptorPath(path.dirname(asyncDir), path.basename(asyncDir)), {
				version: 1,
				runFanoutBudget: createRunFanoutBudget("run-acceptance", 64),
				sourceRunId: "run-acceptance",
				agent: "worker",
				sessionFile,
				cwd: root,
				systemPromptMode: "replace",
				inheritGlobalContext: false,
				inheritProjectContext: false,
				inheritSkills: false,
				outputMode: "inline",
				maxSubagentDepth: 2,
				share: false,
				acceptance: {
					level: "attested",
					criteria: [{ id: "criterion-1", must: "Return evidence", evidence: ["manual-notes"], severity: "required" }],
					evidence: ["manual-notes", "residual-risks"],
					verify: [],
					stopRules: [],
				},
			});

			const target = resolveAsyncResumeTarget({ id: "run-acceptance" }, { asyncDirRoot: asyncRoot, resultsDir });

			assert.equal(target.kind, "revive");
			assert.deepEqual(target.recoveryDescriptor?.acceptance, {
				level: "attested",
				criteria: [{ id: "criterion-1", must: "Return evidence", evidence: ["manual-notes"], severity: "required" }],
				evidence: ["manual-notes", "residual-risks"],
				verify: [],
				stopRules: [],
			});
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("rejects reviewed acceptance metadata in recovery descriptors", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-reviewed-acceptance-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const asyncDir = path.join(asyncRoot, "run-reviewed-acceptance");
			const resultsDir = path.join(root, "results");
			const sessionFile = path.join(root, "session.jsonl");
			fs.writeFileSync(sessionFile, "", "utf-8");
			writeJson(path.join(asyncDir, "status.json"), {
				runId: "run-reviewed-acceptance", mode: "single", state: "paused", startedAt: 100, lastUpdate: 200, cwd: root,
				steps: [{ agent: "worker", status: "paused", sessionFile }],
			});
			writeJson(recoveryDescriptorPath(path.dirname(asyncDir), path.basename(asyncDir)), {
				version: 1,
				runFanoutBudget: createRunFanoutBudget("run-reviewed-acceptance", 64),
				sourceRunId: "run-reviewed-acceptance",
				agent: "worker",
				cwd: root,
				systemPromptMode: "replace",
				inheritGlobalContext: false,
				inheritProjectContext: false,
				inheritSkills: false,
				outputMode: "inline",
				maxSubagentDepth: 2,
				share: false,
				acceptance: {
					level: "reviewed",
					criteria: ["Return evidence"],
					evidence: ["validation-output"],
					verify: [],
					review: { agent: "reviewer", required: true },
					stopRules: [],
				},
			});

			assert.throws(
				() => resolveAsyncResumeTarget({ id: "run-reviewed-acceptance" }, { asyncDirRoot: asyncRoot, resultsDir }),
				/achieved status.*acceptance\.review\.required/i,
			);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("rejects legacy acceptance metadata in recovery descriptors", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-inferred-acceptance-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const asyncDir = path.join(asyncRoot, "run-inferred-acceptance");
			const resultsDir = path.join(root, "results");
			const sessionFile = path.join(root, "session.jsonl");
			fs.writeFileSync(sessionFile, "", "utf-8");
			writeJson(path.join(asyncDir, "status.json"), {
				runId: "run-inferred-acceptance", mode: "single", state: "paused", startedAt: 100, lastUpdate: 200, cwd: root,
				steps: [{ agent: "worker", status: "paused", sessionFile }],
			});
			writeJson(recoveryDescriptorPath(path.dirname(asyncDir), path.basename(asyncDir)), {
				version: 1,
				runFanoutBudget: createRunFanoutBudget("run-inferred-acceptance", 64),
				sourceRunId: "run-inferred-acceptance",
				agent: "worker",
				cwd: root,
				systemPromptMode: "replace",
				inheritGlobalContext: false,
				inheritProjectContext: false,
				inheritSkills: false,
				outputMode: "inline",
				maxSubagentDepth: 2,
				share: false,
				acceptance: {
					level: "attested",
					explicit: false,
					inferredReason: ["async write-capable or risky run"],
					criteria: [],
					evidence: [],
					verify: [],
					stopRules: [],
				},
			});

			assert.throws(
				() => resolveAsyncResumeTarget({ id: "run-inferred-acceptance" }, { asyncDirRoot: asyncRoot, resultsDir }),
				/recoveryDescriptor\.acceptance\.(explicit|inferredReason) is not supported/i,
			);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("rejects a stopped child selected from a terminal aggregate", () => {
		for (const stoppedStep of [{ status: "stopped" }, { status: "failed", stopped: true }]) {
			const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-stopped-child-"));
			try {
				const asyncRoot = path.join(root, "runs");
				const stoppedSession = path.join(root, "stopped.jsonl");
				const completedSession = path.join(root, "completed.jsonl");
				fs.writeFileSync(stoppedSession, "", "utf-8");
				fs.writeFileSync(completedSession, "", "utf-8");
				writeJson(path.join(asyncRoot, "run-aggregate", "status.json"), {
					runId: "run-aggregate", mode: "parallel", state: "failed", startedAt: 100, endedAt: 200, lastUpdate: 200, cwd: root,
					steps: [
						{ agent: "stopped-child", ...stoppedStep, sessionFile: stoppedSession },
						{ agent: "completed-child", status: "complete", sessionFile: completedSession },
					],
				});

				assert.throws(
					() => resolveAsyncResumeTarget({ id: "run-aggregate", index: 0 }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") }),
					/child 0 was stopped and cannot be resumed/,
				);
				assert.equal(resolveAsyncResumeTarget({ id: "run-aggregate", index: 1 }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") }).agent, "completed-child");
			} finally {
				fs.rmSync(root, { recursive: true, force: true });
			}
		}
	});

	it("rejects stopped runs instead of reviving them", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-stopped-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const sessionFile = path.join(root, "session.jsonl");
			fs.writeFileSync(sessionFile, "", "utf-8");
			writeJson(path.join(asyncRoot, "run-stopped", "status.json"), {
				runId: "run-stopped",
				mode: "single",
				state: "stopped",
				stopped: true,
				startedAt: 100,
				endedAt: 200,
				lastUpdate: 200,
				cwd: root,
				sessionFile,
				steps: [{ agent: "worker", status: "stopped", stopped: true, sessionFile }],
			});

			assert.throws(
				() => resolveAsyncResumeTarget({ id: "run-stopped" }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") }),
				/stopped and cannot be resumed/,
			);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("rejects ambiguous run id prefixes", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-ambiguous-"));
		try {
			const asyncRoot = path.join(root, "runs");
			writeJson(path.join(asyncRoot, "run-aaaa-1", "status.json"), {
				runId: "run-aaaa-1",
				mode: "single",
				state: "running",
				startedAt: 100,
				steps: [{ agent: "scout", status: "running" }],
			});
			writeJson(path.join(asyncRoot, "run-aaaa-2", "status.json"), {
				runId: "run-aaaa-2",
				mode: "single",
				state: "running",
				startedAt: 100,
				steps: [{ agent: "worker", status: "running" }],
			});

			assert.throws(
				() => resolveAsyncResumeTarget({ id: "run-aaaa" }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") }),
				/Ambiguous async run id prefix 'run-aaaa' matched: run-aaaa-1, run-aaaa-2/,
			);
			assert.throws(
				() => resolveAsyncResumeTarget({ id: "run-a" }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") }),
				/at least 8 characters/,
			);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("rejects path-like ids and directories outside the async root", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-paths-"));
		try {
			const asyncRoot = path.join(root, "runs");
			assert.throws(
				() => resolveAsyncResumeTarget({ id: "../run" }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") }),
				/id must be an async run id or prefix, not a path/,
			);
			assert.throws(
				() => resolveAsyncResumeTarget({ dir: path.join(root, "outside") }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") }),
				/Async run directory must be inside/,
			);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("names the requested id when no async run matches it", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-unknown-"));
		try {
			const deps = { asyncDirRoot: path.join(root, "runs"), resultsDir: path.join(root, "results") };
			assert.throws(() => resolveAsyncResumeTarget({ id: "nonexistent-probe-1234" }, deps), /^Error: Async run not found for 'nonexistent-probe-1234'\.$/);
			assert.throws(() => resolveAsyncResumeTarget({}, deps), /^Error: Async run not found\. Provide id or dir\.$/);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("rejects non-jsonl session files before reviving", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-session-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const sessionFile = path.join(root, "session.txt");
			fs.writeFileSync(sessionFile, "", "utf-8");
			writeJson(path.join(asyncRoot, "run-session", "status.json"), {
				runId: "run-session",
				mode: "single",
				state: "complete",
				startedAt: 100,
				lastUpdate: 200,
				sessionFile,
				steps: [{ agent: "worker", status: "complete" }],
			});

			assert.throws(
				() => resolveAsyncResumeTarget({ id: "run-session" }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") }),
				/session file must be a \.jsonl file/,
			);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("rejects malformed result metadata before using session fields", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-malformed-result-"));
		try {
			const resultsDir = path.join(root, "results");
			writeJson(path.join(resultsDir, "run-result.json"), {
				id: "run-result",
				agent: "worker",
				success: true,
				state: "complete",
				results: [{ agent: "worker", sessionFile: { path: "session.jsonl" } }],
			});

			assert.throws(
				() => resolveAsyncResumeTarget({ id: "run-result" }, { asyncDirRoot: path.join(root, "runs"), resultsDir }),
				/results\[0\].sessionFile must be a string/,
			);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("rejects malformed result model metadata", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-malformed-result-model-"));
		try {
			const resultsDir = path.join(root, "results");
			writeJson(path.join(resultsDir, "run-result-model.json"), {
				id: "run-result-model",
				agent: "worker",
				success: true,
				state: "complete",
				results: [{ agent: "worker", model: { id: "bad" } }],
			});

			assert.throws(
				() => resolveAsyncResumeTarget({ id: "run-result-model" }, { asyncDirRoot: path.join(root, "runs"), resultsDir }, { requireSessionFile: false }),
				/results\[0\].model must be a string/,
			);

			writeJson(path.join(resultsDir, "run-result-model.json"), {
				id: "run-result-model",
				agent: "worker",
				success: true,
				state: "complete",
				results: [{ agent: "worker", thinking: { level: "high" } }],
			});

			assert.throws(
				() => resolveAsyncResumeTarget({ id: "run-result-model" }, { asyncDirRoot: path.join(root, "runs"), resultsDir }, { requireSessionFile: false }),
				/results\[0\].thinking must be a string/,
			);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("rejects malformed status session ids", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-malformed-session-id-"));
		try {
			const asyncRoot = path.join(root, "runs");
			writeJson(path.join(asyncRoot, "run-session-id", "status.json"), {
				runId: "run-session-id",
				sessionId: { value: "session" },
				mode: "single",
				state: "running",
				startedAt: 100,
				steps: [{ agent: "worker", status: "running" }],
			});

			assert.throws(
				() => resolveAsyncResumeTarget({ id: "run-session-id" }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") }),
				/sessionId must be a string/,
			);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("rejects malformed status model metadata", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-malformed-status-model-"));
		try {
			const asyncRoot = path.join(root, "runs");
			writeJson(path.join(asyncRoot, "run-status-model", "status.json"), {
				runId: "run-status-model",
				mode: "single",
				state: "running",
				startedAt: 100,
				steps: [{ agent: "worker", status: "running", model: { id: "bad" } }],
			});

			assert.throws(
				() => resolveAsyncResumeTarget({ id: "run-status-model" }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") }),
				/steps\[0\].model must be a string/,
			);

			writeJson(path.join(asyncRoot, "run-status-model", "status.json"), {
				runId: "run-status-model",
				mode: "single",
				state: "running",
				startedAt: 100,
				steps: [{ agent: "worker", status: "running", thinking: { level: "high" } }],
			});

			assert.throws(
				() => resolveAsyncResumeTarget({ id: "run-status-model" }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") }),
				/steps\[0\].thinking must be a string/,
			);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("returns live child metadata for a running child", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-live-"));
		try {
			const asyncRoot = path.join(root, "runs");
			writeJson(path.join(asyncRoot, "run-live", "status.json"), {
				runId: "run-live",
				mode: "single",
				state: "running",
				startedAt: 100,
				lastUpdate: 100,
				steps: [{ agent: "scout", status: "running", model: "openai/gpt-4.1", thinking: "off" }],
			});

			const target = resolveAsyncResumeTarget({ id: "run-live" }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") });

			assert.equal(target.kind, "live");
			assert.equal(target.model, "openai/gpt-4.1");
			assert.equal(target.thinking, "off");
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("enforces current-session ownership for status and result-only runs", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-ownership-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const resultsDir = path.join(root, "results");
			writeJson(path.join(asyncRoot, "owned", "status.json"), {
				runId: "owned",
				sessionId: "session-a",
				mode: "single",
				state: "running",
				startedAt: 100,
				steps: [{ agent: "worker", status: "running" }],
			});
			writeJson(path.join(asyncRoot, "sessionless", "status.json"), {
				runId: "sessionless",
				mode: "single",
				state: "running",
				startedAt: 100,
				steps: [{ agent: "worker", status: "running" }],
			});
			writeJson(path.join(resultsDir, "result-only.json"), {
				id: "result-only",
				sessionId: "session-a",
				agent: "worker",
				state: "complete",
				success: true,
			});
			writeJson(path.join(asyncRoot, "mixed", "status.json"), {
				runId: "mixed",
				sessionId: "session-a",
				mode: "single",
				state: "complete",
				startedAt: 100,
				steps: [{ agent: "worker", status: "complete" }],
			});
			writeJson(path.join(resultsDir, "mixed.json"), {
				id: "mixed",
				agent: "worker",
				state: "complete",
				success: true,
			});
			writeJson(path.join(asyncRoot, "mixed-reverse", "status.json"), {
				runId: "mixed-reverse",
				mode: "single",
				state: "complete",
				startedAt: 100,
				steps: [{ agent: "worker", status: "complete" }],
			});
			writeJson(path.join(resultsDir, "mixed-reverse.json"), {
				id: "mixed-reverse",
				sessionId: "session-a",
				agent: "worker",
				state: "complete",
				success: true,
			});

			assert.equal(resolveAsyncResumeTarget({ id: "owned" }, { asyncDirRoot: asyncRoot, resultsDir }, { sessionId: "session-a" }).kind, "live");
			assert.throws(
				() => resolveAsyncResumeTarget({ id: "owned" }, { asyncDirRoot: asyncRoot, resultsDir }, { sessionId: "session-b" }),
				/not found in the active session/,
			);
			assert.throws(
				() => resolveAsyncResumeTarget({ id: "sessionless" }, { asyncDirRoot: asyncRoot, resultsDir }, { sessionId: "session-a" }),
				/not found in the active session/,
			);
			assert.equal(resolveAsyncResumeTarget({ id: "result-only" }, { asyncDirRoot: asyncRoot, resultsDir }, { requireSessionFile: false, sessionId: "session-a" }).kind, "revive");
			assert.throws(
				() => resolveAsyncResumeTarget({ id: "result-only" }, { asyncDirRoot: asyncRoot, resultsDir }, { requireSessionFile: false, sessionId: "session-b" }),
				/not found in the active session/,
			);
			assert.throws(
				() => resolveAsyncResumeTarget({ id: "mixed" }, { asyncDirRoot: asyncRoot, resultsDir }, { requireSessionFile: false, sessionId: "session-a" }),
				/not found in the active session/,
			);
			assert.throws(
				() => resolveAsyncResumeTarget({ id: "mixed-reverse" }, { asyncDirRoot: asyncRoot, resultsDir }, { requireSessionFile: false, sessionId: "session-a" }),
				/not found in the active session/,
			);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("revives a run of a session this process replaced, and still refuses other sessions' runs", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-inherited-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const resultsDir = path.join(root, "results");
			const sessionFile = path.join(root, "child.jsonl");
			fs.writeFileSync(sessionFile, "", "utf-8");
			const [replaced, successor, unrelated] = ["replaced", "successor", "unrelated"].map((name) => path.join(root, `${name}.jsonl`));
			writeJson(path.join(asyncRoot, "failed-child", "status.json"), {
				runId: "failed-child",
				sessionId: replaced,
				mode: "single",
				state: "failed",
				startedAt: 100,
				endedAt: 200,
				cwd: root,
				sessionFile,
				steps: [{ agent: "worker", status: "failed", sessionFile }],
			});
			const resume = (sessionId: string) => resolveAsyncResumeTarget({ id: "failed-child" }, { asyncDirRoot: asyncRoot, resultsDir }, { sessionId });
			assert.throws(() => resume(successor), /not found in the active session/);
			recordSessionReplacement(successor, replaced);
			const target = resume(successor);
			assert.equal(target.kind, "revive");
			assert.equal(target.sessionFile, sessionFile);
			assert.throws(() => resume(unrelated), /not found in the active session/);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("revives a completed child by index while a sibling async child is still running", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-partial-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const sessionFile = path.join(root, "done.jsonl");
			fs.writeFileSync(sessionFile, "", "utf-8");
			writeJson(path.join(asyncRoot, "run-partial", "status.json"), {
				runId: "run-partial",
				mode: "parallel",
				state: "running",
				startedAt: 100,
				lastUpdate: 200,
				steps: [
					{ agent: "done", status: "complete", sessionFile },
					{ agent: "active", status: "running" },
				],
			});

			const target = resolveAsyncResumeTarget({ id: "run-partial", index: 0 }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") });
			assert.equal(target.kind, "revive");
			assert.equal(target.agent, "done");
			assert.equal(target.sessionFile, sessionFile);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("rejects pending indexed children in still-running async runs", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-pending-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const sessionFile = path.join(root, "pending.jsonl");
			fs.writeFileSync(sessionFile, "", "utf-8");
			writeJson(path.join(asyncRoot, "run-pending", "status.json"), {
				runId: "run-pending",
				mode: "chain",
				state: "running",
				startedAt: 100,
				lastUpdate: 200,
				steps: [
					{ agent: "active", status: "running" },
					{ agent: "later", status: "pending", sessionFile },
				],
			});

			assert.throws(
				() => resolveAsyncResumeTarget({ id: "run-pending", index: 1 }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") }),
				/pending and has not started yet/,
			);
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("resolves a completed multi-child run when an index and per-child session file are available", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-multi-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const firstSession = path.join(root, "a.jsonl");
			const secondSession = path.join(root, "b.jsonl");
			fs.writeFileSync(firstSession, "", "utf-8");
			fs.writeFileSync(secondSession, "", "utf-8");
			writeJson(path.join(asyncRoot, "run-multi", "status.json"), {
				runId: "run-multi",
				mode: "chain",
				state: "complete",
				startedAt: 100,
				lastUpdate: 200,
				steps: [
					{ agent: "a", status: "complete", sessionFile: firstSession },
					{ agent: "b", status: "complete", sessionFile: secondSession, model: "anthropic/claude-sonnet-4", thinking: "high" },
				],
			});

			assert.throws(
				() => resolveAsyncResumeTarget({ id: "run-multi" }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") }),
				/Provide index to choose one/,
			);
			const target = resolveAsyncResumeTarget({ id: "run-multi", index: 1 }, { asyncDirRoot: asyncRoot, resultsDir: path.join(root, "results") });
			assert.equal(target.kind, "revive");
			assert.equal(target.agent, "b");
			assert.equal(target.index, 1);
			assert.equal(target.sessionFile, secondSession);
			assert.equal(target.model, "anthropic/claude-sonnet-4");
			assert.equal(target.thinking, "high");
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("resolves a completed result-only child with per-child model metadata", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-result-only-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const resultsDir = path.join(root, "results");
			const firstSession = path.join(root, "a.jsonl");
			const secondSession = path.join(root, "b.jsonl");
			fs.writeFileSync(firstSession, "", "utf-8");
			fs.writeFileSync(secondSession, "", "utf-8");
			writeJson(path.join(resultsDir, "run-result-only.json"), {
				id: "run-result-only",
				mode: "parallel",
				success: true,
				state: "complete",
				cwd: root,
				results: [
					{ agent: "a", success: true, sessionFile: firstSession, model: "openai/gpt-4.1" },
					{ agent: "b", success: true, sessionFile: secondSession, model: "anthropic/claude-sonnet-4", thinking: "high" },
				],
			});

			assert.throws(
				() => resolveAsyncResumeTarget({ id: "run-result-only" }, { asyncDirRoot: asyncRoot, resultsDir }),
				/Provide index to choose one/,
			);
			const target = resolveAsyncResumeTarget({ id: "run-result-only", index: 1 }, { asyncDirRoot: asyncRoot, resultsDir });
			assert.equal(target.kind, "revive");
			assert.equal(target.agent, "b");
			assert.equal(target.index, 1);
			assert.equal(target.cwd, root);
			assert.equal(target.sessionFile, secondSession);
			assert.equal(target.model, "anthropic/claude-sonnet-4");
			assert.equal(target.thinking, "high");
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("revives on the launch model when status reports a model a host extension switched to and no result exists yet", () => {
		const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-async-resume-routed-"));
		try {
			const asyncRoot = path.join(root, "runs");
			const resultsDir = path.join(root, "results");
			const sessionFile = path.join(root, "a.jsonl");
			fs.writeFileSync(sessionFile, "", "utf-8");
			writeJson(path.join(asyncRoot, "run-routed", "status.json"), {
				runId: "run-routed",
				mode: "parallel",
				state: "running",
				startedAt: 100,
				lastUpdate: 200,
				steps: [
					{ agent: "worker", status: "complete", sessionFile, model: "openai-codex/gpt-6-sol", launchModel: "llama-swap/qwen3.5:9b", thinking: "high" },
					{ agent: "worker", status: "running" },
				],
			});

			const target = resolveAsyncResumeTarget({ id: "run-routed", index: 0 }, { asyncDirRoot: asyncRoot, resultsDir });
			assert.equal(target.kind, "revive");
			assert.equal(target.model, "llama-swap/qwen3.5:9b");
		} finally {
			fs.rmSync(root, { recursive: true, force: true });
		}
	});

	it("frames the revived follow-up with original run context", () => {
		const task = buildRevivedAsyncTask({
			kind: "revive",
			runId: "run-old",
			state: "complete",
			agent: "worker",
			index: 0,
			sessionFile: "/tmp/session.jsonl",
		}, "What changed?");

		assert.match(task, /Original run: run-old/);
		assert.doesNotMatch(task, /async subagent conversation/);
		assert.match(task, /Original agent: worker/);
		assert.match(task, /Original session file: \/tmp\/session\.jsonl/);
		assert.match(task, /Follow-up:\nWhat changed\?/);
	});
});
