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,OAAO,CAAC;IAClB,MAAM,CAAC,EAAE,MAAM,CAAC;CAChB;AAID,wBAAgB,aAAa,CAAC,EAAE,EAAE,MAAM,GAAG,IAAI,CAE9C;AAED,wBAAgB,WAAW,CAAC,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,CAO/E;AAED,2EAA2E;AAC3E,wBAAgB,SAAS,CAAC,EAAE,EAAE,MAAM,GAAG,OAAO,CAO7C;AAED,2EAA2E;AAC3E,wBAAgB,UAAU,IAAI,SAAS,EAAE,CAOxC;AAED,sDAAsD;AACtD,wBAAgB,mBAAmB,IAAI,IAAI,CAI1C;AAED;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,iBAAiB,GAAG,MAAM,CAWxE;AA0DD;;;;GAIG;AACH,wBAAsB,WAAW,CAAC,KAAK,EAAE,YAAY,EAAE,EAAE,IAAI,GAAE,kBAAuB,GAAG,OAAO,CAAC,WAAW,EAAE,CAAC,CAiB9G","sourcesContent":["/**\n * Bounded parallel sub-agent executor with worktree isolation.\n *\n * Each task runs inside its own git worktree (via worktree.ts) so concurrent\n * writes never collide; after the task completes its diff is merged back onto\n * the main tree, and conflicting merges surface an explicit conflict report\n * (both diffs) in the structured result instead of overwriting silently.\n *\n * Spawn policy: depth = 1. Tasks run at depth 0; a sub-agent (depth >= 1)\n * cannot fan out again — runParallel throws if called at depth >= 1.\n *\n * Also hosts the live agent registry (registerAgent/finishAgent/killAgent/\n * listAgents) consumed by the /agents command.\n */\n\nimport { createWorktree, type MergeConflictInfo, mergeWorktree, removeWorktree } from \"./worktree.ts\";\n\nexport const DEFAULT_MAX_CONCURRENCY = 3;\nexport const MAX_SPAWN_DEPTH = 1;\n\nexport type Verdict = \"success\" | \"failure\" | \"conflict\" | \"killed\" | \"error\";\n\nexport interface TaskContext {\n\t/** Working directory for the task: its isolated worktree path (or repoRoot when useWorktrees=false). */\n\tcwd: string;\n\t/** Spawn depth of this task. Tasks at depth >= MAX_SPAWN_DEPTH must not fan out. */\n\tdepth: number;\n\tsignal: AbortSignal;\n}\n\nexport interface ParallelTask {\n\tid: string;\n\t/** Injected task body (no LLM coupling): returns its output text. */\n\trun: (ctx: TaskContext) => Promise<string> | string;\n}\n\nexport interface AgentResult {\n\tid: string;\n\tverdict: Verdict;\n\toutput: string;\n\tconflicts?: MergeConflictInfo;\n}\n\nexport interface RunParallelOptions {\n\t/** Repo root for worktree isolation. Required unless useWorktrees=false. */\n\trepoRoot?: string;\n\tmaxConcurrency?: number;\n\t/** Current spawn depth; >= MAX_SPAWN_DEPTH refuses to run. */\n\tdepth?: number;\n\t/** Set false for read-only tasks that need no isolation. */\n\tuseWorktrees?: boolean;\n}\n\n// ─── Live agent registry (consumed by /agents) ───────────────────\n\nexport interface AgentInfo {\n\tid: string;\n\tstatus: \"running\" | \"finished\" | \"killed\" | \"error\";\n\tstartedAt: number;\n\tfinishedAt?: number;\n\tverdict?: Verdict;\n\toutput?: string;\n}\n\nconst registry = new Map<string, AgentInfo & { controller: AbortController }>();\n\nexport function registerAgent(id: string): void {\n\tregistry.set(id, { id, status: \"running\", startedAt: Date.now(), controller: new AbortController() });\n}\n\nexport function finishAgent(id: string, verdict: Verdict, output?: string): void {\n\tconst entry = registry.get(id);\n\tif (!entry) return;\n\tentry.status = verdict === \"killed\" ? \"killed\" : verdict === \"error\" ? \"error\" : \"finished\";\n\tentry.verdict = verdict;\n\tentry.output = output;\n\tentry.finishedAt = Date.now();\n}\n\n/** Abort a running agent. Returns false if unknown or already finished. */\nexport function killAgent(id: string): boolean {\n\tconst entry = registry.get(id);\n\tif (!entry || entry.status !== \"running\") return false;\n\tentry.controller.abort();\n\tentry.status = \"killed\";\n\tentry.finishedAt = Date.now();\n\treturn true;\n}\n\n/** Live snapshot of all known agents (running first, then most recent). */\nexport function listAgents(): AgentInfo[] {\n\treturn [...registry.values()]\n\t\t.map(({ controller: _c, ...info }) => info)\n\t\t.sort((a, b) => {\n\t\t\tif ((a.status === \"running\") !== (b.status === \"running\")) return a.status === \"running\" ? -1 : 1;\n\t\t\treturn b.startedAt - a.startedAt;\n\t\t});\n}\n\n/** Drop finished/killed entries from the registry. */\nexport function clearFinishedAgents(): void {\n\tfor (const [id, entry] of registry) {\n\t\tif (entry.status !== \"running\") registry.delete(id);\n\t}\n}\n\n/**\n * Build the explicit conflict report appended to an agent's output when its\n * merge fails: lists the conflicting files and BOTH diffs (incoming vs current\n * main tree) so the director can decide. Nothing is overwritten silently.\n */\nexport function formatConflictReport(conflict: MergeConflictInfo): string {\n\treturn [\n\t\t\"## MERGE CONFLICT\",\n\t\t`Files: ${conflict.files.join(\", \")}`,\n\t\t\"\",\n\t\t\"### Incoming diff (this agent)\",\n\t\tconflict.incomingDiff || \"(empty)\",\n\t\t\"\",\n\t\t\"### Current diff (main tree)\",\n\t\tconflict.currentDiff || \"(empty)\",\n\t].join(\"\\n\");\n}\n\nfunction agentSignal(id: string): AbortSignal {\n\tconst entry = registry.get(id);\n\treturn entry ? entry.controller.signal : new AbortController().signal;\n}\n\n// ─── Executor ────────────────────────────────────────────────────\n\nasync function runOne(\n\ttask: ParallelTask,\n\topts: Required<Pick<RunParallelOptions, \"depth\" | \"useWorktrees\">> & RunParallelOptions,\n): Promise<AgentResult> {\n\tregisterAgent(task.id);\n\tlet output = \"\";\n\tlet verdict: Verdict = \"error\";\n\tlet conflicts: MergeConflictInfo | undefined;\n\tlet wtPath: string | undefined;\n\ttry {\n\t\tif (opts.useWorktrees) {\n\t\t\tif (!opts.repoRoot) throw new Error(\"repoRoot is required when useWorktrees=true\");\n\t\t\twtPath = createWorktree(opts.repoRoot, task.id).path;\n\t\t}\n\t\tconst cwd = wtPath ?? opts.repoRoot ?? process.cwd();\n\t\tconst signal = agentSignal(task.id);\n\t\toutput = await task.run({ cwd, depth: opts.depth, signal });\n\t\tif (signal.aborted) {\n\t\t\tverdict = \"killed\";\n\t\t} else if (wtPath && opts.repoRoot) {\n\t\t\tconst merge = mergeWorktree(opts.repoRoot, task.id);\n\t\t\tif (merge.ok) {\n\t\t\t\tverdict = \"success\";\n\t\t\t} else {\n\t\t\t\tverdict = \"conflict\";\n\t\t\t\tconflicts = merge.conflict;\n\t\t\t\tif (conflicts) output += `\\n\\n${formatConflictReport(conflicts)}`;\n\t\t\t}\n\t\t} else {\n\t\t\tverdict = \"success\";\n\t\t}\n\t} catch (e) {\n\t\tverdict = agentSignal(task.id).aborted ? \"killed\" : \"error\";\n\t\toutput = output || String(e);\n\t} finally {\n\t\tif (wtPath && opts.repoRoot) {\n\t\t\ttry {\n\t\t\t\tremoveWorktree(opts.repoRoot, task.id);\n\t\t\t} catch {\n\t\t\t\t/* best effort cleanup */\n\t\t\t}\n\t\t}\n\t\tfinishAgent(task.id, verdict, output);\n\t}\n\tconst result: AgentResult = { id: task.id, verdict, output };\n\tif (conflicts) result.conflicts = conflicts;\n\treturn result;\n}\n\n/**\n * Run tasks with bounded concurrency, each in an isolated worktree.\n * Never throws for individual task failures; throws synchronously when the\n * spawn-depth policy is violated.\n */\nexport async function runParallel(tasks: ParallelTask[], opts: RunParallelOptions = {}): Promise<AgentResult[]> {\n\tconst depth = opts.depth ?? 0;\n\tif (depth >= MAX_SPAWN_DEPTH) {\n\t\tthrow new Error(`spawn depth limit reached (${MAX_SPAWN_DEPTH}): sub-agents cannot spawn sub-agents`);\n\t}\n\tconst maxConcurrency = Math.max(1, opts.maxConcurrency ?? DEFAULT_MAX_CONCURRENCY);\n\tconst useWorktrees = opts.useWorktrees ?? true;\n\tconst results: AgentResult[] = new Array(tasks.length);\n\tlet next = 0;\n\tconst worker = async () => {\n\t\twhile (next < tasks.length) {\n\t\t\tconst i = next++;\n\t\t\tresults[i] = await runOne(tasks[i], { ...opts, depth, useWorktrees });\n\t\t}\n\t};\n\tawait Promise.all(Array.from({ length: Math.min(maxConcurrency, tasks.length) }, worker));\n\treturn results;\n}\n"]}