@xzzpig/pi-subagents 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (196) hide show
  1. package/CHANGELOG.md +1621 -0
  2. package/LICENSE +21 -0
  3. package/README.md +118 -0
  4. package/agents/delegate.md +14 -0
  5. package/agents/oracle.md +74 -0
  6. package/agents/researcher.md +52 -0
  7. package/agents/reviewer.md +79 -0
  8. package/agents/scout.md +50 -0
  9. package/agents/worker.md +58 -0
  10. package/index.ts +1 -0
  11. package/inspector-runner.mjs +11 -0
  12. package/install.mjs +93 -0
  13. package/package.json +105 -0
  14. package/prompts/gather-context-and-clarify.md +13 -0
  15. package/prompts/parallel-cleanup.md +59 -0
  16. package/prompts/parallel-research.md +50 -0
  17. package/prompts/parallel-review.md +54 -0
  18. package/prompts/review-loop.md +43 -0
  19. package/skills/pi-subagents/SKILL.md +41 -0
  20. package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
  21. package/skills/pi-subagents/references/execution-controls.md +428 -0
  22. package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
  23. package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
  24. package/src/agents/agent-management.ts +1256 -0
  25. package/src/agents/agent-memory.ts +254 -0
  26. package/src/agents/agent-refinements.ts +624 -0
  27. package/src/agents/agent-scope.ts +6 -0
  28. package/src/agents/agent-selection.ts +25 -0
  29. package/src/agents/agent-serializer.ts +163 -0
  30. package/src/agents/agents.ts +1889 -0
  31. package/src/agents/chain-serializer.ts +280 -0
  32. package/src/agents/frontmatter.ts +149 -0
  33. package/src/agents/identity.ts +30 -0
  34. package/src/agents/proactive-skills.ts +194 -0
  35. package/src/agents/skills.ts +761 -0
  36. package/src/api/background-work.ts +197 -0
  37. package/src/api/capability-ceiling.ts +17 -0
  38. package/src/api/control-channel.ts +4 -0
  39. package/src/api/delegation.ts +119 -0
  40. package/src/api/external-runs.ts +129 -0
  41. package/src/api/intercom-bridge.ts +3 -0
  42. package/src/api/pi-args.ts +5 -0
  43. package/src/api/preflight.ts +403 -0
  44. package/src/api/shared-types.ts +19 -0
  45. package/src/extension/config.ts +76 -0
  46. package/src/extension/control-notices.ts +58 -0
  47. package/src/extension/doctor.ts +230 -0
  48. package/src/extension/fanout-child.ts +201 -0
  49. package/src/extension/index.ts +805 -0
  50. package/src/extension/public-execution.ts +71 -0
  51. package/src/extension/rpc.ts +653 -0
  52. package/src/extension/schemas.ts +375 -0
  53. package/src/extension/steering-notices.ts +35 -0
  54. package/src/extension/tool-description.ts +164 -0
  55. package/src/inspectors/herdr/actions.ts +229 -0
  56. package/src/inspectors/herdr/client.ts +130 -0
  57. package/src/inspectors/herdr/inspector-runner.ts +141 -0
  58. package/src/inspectors/herdr/project-panes.ts +154 -0
  59. package/src/integrations/herdr-status.ts +330 -0
  60. package/src/intercom/intercom-bridge.ts +187 -0
  61. package/src/intercom/native-supervisor-channel.ts +715 -0
  62. package/src/intercom/result-intercom.ts +421 -0
  63. package/src/missions/actions.ts +410 -0
  64. package/src/missions/goal-driver.ts +162 -0
  65. package/src/missions/lifecycle.ts +346 -0
  66. package/src/missions/store.ts +507 -0
  67. package/src/missions/types.ts +157 -0
  68. package/src/missions/workflow-state.ts +250 -0
  69. package/src/policy/authority.ts +46 -0
  70. package/src/profiles/profiles.ts +661 -0
  71. package/src/runs/background/async-execution.ts +1574 -0
  72. package/src/runs/background/async-job-tracker.ts +511 -0
  73. package/src/runs/background/async-resume.ts +539 -0
  74. package/src/runs/background/async-status.ts +542 -0
  75. package/src/runs/background/auto-drain.ts +67 -0
  76. package/src/runs/background/chain-append.ts +328 -0
  77. package/src/runs/background/chain-root-attachment.ts +199 -0
  78. package/src/runs/background/completion-batcher.ts +168 -0
  79. package/src/runs/background/completion-dedupe.ts +54 -0
  80. package/src/runs/background/control-channel.ts +692 -0
  81. package/src/runs/background/fleet-view.ts +540 -0
  82. package/src/runs/background/notify.ts +332 -0
  83. package/src/runs/background/parallel-groups.ts +45 -0
  84. package/src/runs/background/process-terminal.ts +280 -0
  85. package/src/runs/background/result-watcher.ts +414 -0
  86. package/src/runs/background/retained-children.ts +68 -0
  87. package/src/runs/background/run-id-resolver.ts +167 -0
  88. package/src/runs/background/run-status.ts +504 -0
  89. package/src/runs/background/scheduled-runs.ts +753 -0
  90. package/src/runs/background/stale-run-reconciler.ts +396 -0
  91. package/src/runs/background/steering.ts +239 -0
  92. package/src/runs/background/subagent-runner.ts +4718 -0
  93. package/src/runs/background/subagent-wait.ts +661 -0
  94. package/src/runs/background/top-level-async.ts +14 -0
  95. package/src/runs/background/wait-completions.ts +112 -0
  96. package/src/runs/background/wait-config.ts +36 -0
  97. package/src/runs/background/wait-subscriptions.ts +253 -0
  98. package/src/runs/background/wait-tool.ts +34 -0
  99. package/src/runs/foreground/async-steering-action.ts +256 -0
  100. package/src/runs/foreground/async-stop-action.ts +65 -0
  101. package/src/runs/foreground/chain-clarify.ts +1354 -0
  102. package/src/runs/foreground/chain-execution.ts +1527 -0
  103. package/src/runs/foreground/execution.ts +1868 -0
  104. package/src/runs/foreground/foreground-control.ts +132 -0
  105. package/src/runs/foreground/subagent-executor.ts +5532 -0
  106. package/src/runs/shared/acceptance.ts +1365 -0
  107. package/src/runs/shared/agent-contract.ts +38 -0
  108. package/src/runs/shared/capability-ceiling.ts +209 -0
  109. package/src/runs/shared/chain-outputs.ts +118 -0
  110. package/src/runs/shared/child-protocol.ts +401 -0
  111. package/src/runs/shared/completion-guard.ts +95 -0
  112. package/src/runs/shared/context-mode.ts +44 -0
  113. package/src/runs/shared/dynamic-fanout.ts +297 -0
  114. package/src/runs/shared/external-cli-runner.ts +130 -0
  115. package/src/runs/shared/long-running-guard.ts +220 -0
  116. package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
  117. package/src/runs/shared/model-fallback.ts +336 -0
  118. package/src/runs/shared/model-scope.ts +128 -0
  119. package/src/runs/shared/nested-events.ts +1076 -0
  120. package/src/runs/shared/nested-path.ts +52 -0
  121. package/src/runs/shared/nested-render.ts +123 -0
  122. package/src/runs/shared/parallel-handoff.ts +238 -0
  123. package/src/runs/shared/parallel-utils.ts +256 -0
  124. package/src/runs/shared/permissions.ts +95 -0
  125. package/src/runs/shared/pi-args.ts +808 -0
  126. package/src/runs/shared/pi-spawn.ts +163 -0
  127. package/src/runs/shared/process-signal.ts +19 -0
  128. package/src/runs/shared/run-history.ts +181 -0
  129. package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
  130. package/src/runs/shared/session-lease.ts +299 -0
  131. package/src/runs/shared/single-output.ts +235 -0
  132. package/src/runs/shared/spawn-budget.ts +128 -0
  133. package/src/runs/shared/structured-output.ts +182 -0
  134. package/src/runs/shared/subagent-control.ts +231 -0
  135. package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
  136. package/src/runs/shared/subagent-startup-retry.ts +104 -0
  137. package/src/runs/shared/task-intent.ts +181 -0
  138. package/src/runs/shared/tool-availability.ts +83 -0
  139. package/src/runs/shared/tool-budget.ts +80 -0
  140. package/src/runs/shared/turn-budget.ts +98 -0
  141. package/src/runs/shared/usage-budget.ts +65 -0
  142. package/src/runs/shared/workflow-graph.ts +231 -0
  143. package/src/runs/shared/worktree.ts +759 -0
  144. package/src/shared/accessible-dir.ts +47 -0
  145. package/src/shared/artifacts.ts +285 -0
  146. package/src/shared/atomic-json.ts +61 -0
  147. package/src/shared/child-transcript.ts +264 -0
  148. package/src/shared/file-coalescer.ts +40 -0
  149. package/src/shared/file-system-retry.ts +47 -0
  150. package/src/shared/fork-context.ts +213 -0
  151. package/src/shared/formatters.ts +133 -0
  152. package/src/shared/jsonl-writer.ts +81 -0
  153. package/src/shared/launch-contract.ts +124 -0
  154. package/src/shared/model-info.ts +81 -0
  155. package/src/shared/post-exit-stdio-guard.ts +85 -0
  156. package/src/shared/session-identity.ts +10 -0
  157. package/src/shared/session-tokens.ts +44 -0
  158. package/src/shared/settings.ts +501 -0
  159. package/src/shared/status-format.ts +55 -0
  160. package/src/shared/types.ts +2069 -0
  161. package/src/shared/utils.ts +613 -0
  162. package/src/slash/delegation-adapters.ts +434 -0
  163. package/src/slash/delegation-json.ts +108 -0
  164. package/src/slash/delegation-request.ts +166 -0
  165. package/src/slash/prompt-template-bridge.ts +383 -0
  166. package/src/slash/prompt-workflows.ts +300 -0
  167. package/src/slash/selector.ts +147 -0
  168. package/src/slash/slash-bridge.ts +192 -0
  169. package/src/slash/slash-commands.ts +994 -0
  170. package/src/slash/slash-live-state.ts +296 -0
  171. package/src/slash/subagents-admin.ts +432 -0
  172. package/src/tui/fleet-status.ts +564 -0
  173. package/src/tui/fleet-transcript.ts +577 -0
  174. package/src/tui/fleet.ts +879 -0
  175. package/src/tui/render-helpers.ts +80 -0
  176. package/src/tui/render.ts +2029 -0
  177. package/src/types/pi-runtime-compat.d.ts +8 -0
  178. package/src/watchdog/change-signature.ts +220 -0
  179. package/src/watchdog/child-status.ts +205 -0
  180. package/src/watchdog/emission-guard.ts +123 -0
  181. package/src/watchdog/lsp-diagnostics.ts +537 -0
  182. package/src/watchdog/model-selection.ts +167 -0
  183. package/src/watchdog/permission-arbiter.ts +145 -0
  184. package/src/watchdog/register-child.ts +117 -0
  185. package/src/watchdog/register-main.ts +440 -0
  186. package/src/watchdog/render.ts +54 -0
  187. package/src/watchdog/review.ts +302 -0
  188. package/src/watchdog/runtime.ts +868 -0
  189. package/src/watchdog/scope.ts +62 -0
  190. package/src/watchdog/settings.ts +568 -0
  191. package/src/watchdog/tool-actions.ts +155 -0
  192. package/src/watchdog/turn-delta.ts +161 -0
  193. package/src/watchdog/types.ts +198 -0
  194. package/src/watchdog/warning-format.ts +73 -0
  195. package/src/workflows/chat-progress.ts +140 -0
  196. package/src/workflows/scripted-workflow.ts +506 -0
@@ -0,0 +1,759 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import * as fs from "node:fs";
3
+ import * as os from "node:os";
4
+ import * as path from "node:path";
5
+ import { resolveAuthorityDecision, type AuthorityPolicyConfig } from "../../policy/authority.ts";
6
+
7
+ export interface WorktreeSetup {
8
+ cwd: string;
9
+ worktrees: WorktreeInfo[];
10
+ baseCommit: string;
11
+ capturedDiffs?: WorktreeDiff[];
12
+ }
13
+
14
+ export interface WorktreeInfo {
15
+ path: string;
16
+ agentCwd: string;
17
+ branch: string;
18
+ index: number;
19
+ nodeModulesLinked: boolean;
20
+ syntheticPaths: string[];
21
+ }
22
+
23
+ export interface WorktreeDiff {
24
+ index: number;
25
+ agent: string;
26
+ branch: string;
27
+ diffStat: string;
28
+ filesChanged: number;
29
+ insertions: number;
30
+ deletions: number;
31
+ patchPath: string;
32
+ error?: string;
33
+ }
34
+
35
+ export interface WorktreeCleanupTask {
36
+ index: number;
37
+ path: string;
38
+ branch: string;
39
+ worktreeRemoved: boolean;
40
+ branchRemoved: boolean;
41
+ preserved?: boolean;
42
+ reason?: string;
43
+ errors?: string[];
44
+ }
45
+
46
+ export type WorktreeCleanupIntent =
47
+ | { kind: "preserve"; capturedDiffs?: WorktreeDiff[]; handoffManifestPath?: string }
48
+ | {
49
+ kind: "discard";
50
+ authorization:
51
+ | { kind: "policy"; policy?: AuthorityPolicyConfig }
52
+ | { kind: "confirmed"; policy?: AuthorityPolicyConfig };
53
+ }
54
+ | { kind: "setup-rollback" };
55
+
56
+ export interface WorktreeCleanupReport {
57
+ state: "complete" | "partial";
58
+ tasks: WorktreeCleanupTask[];
59
+ pruned: boolean;
60
+ errors?: string[];
61
+ }
62
+
63
+ interface WorktreeTaskCwdConflict {
64
+ index: number;
65
+ agent: string;
66
+ cwd: string;
67
+ }
68
+
69
+ interface WorktreeSetupHookConfig {
70
+ hookPath: string;
71
+ timeoutMs?: number;
72
+ }
73
+
74
+ interface CreateWorktreesOptions {
75
+ agents?: string[];
76
+ setupHook?: WorktreeSetupHookConfig;
77
+ baseDir?: string;
78
+ }
79
+
80
+ interface ResolvedWorktreeSetupHook {
81
+ hookPath: string;
82
+ timeoutMs: number;
83
+ }
84
+
85
+ interface WorktreeSetupHookInput {
86
+ version: 1;
87
+ repoRoot: string;
88
+ worktreePath: string;
89
+ agentCwd: string;
90
+ branch: string;
91
+ index: number;
92
+ runId: string;
93
+ baseCommit: string;
94
+ agent?: string;
95
+ }
96
+
97
+ interface WorktreeSetupHookOutput {
98
+ syntheticPaths?: string[];
99
+ }
100
+
101
+ interface GitResult {
102
+ stdout: string;
103
+ stderr: string;
104
+ status: number | null;
105
+ }
106
+
107
+ interface RepoState {
108
+ toplevel: string;
109
+ cwdRelative: string;
110
+ baseCommit: string;
111
+ }
112
+
113
+ const DEFAULT_WORKTREE_SETUP_HOOK_TIMEOUT_MS = 30000;
114
+
115
+ function runGit(cwd: string, args: string[]): GitResult {
116
+ const result = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf-8" });
117
+ return {
118
+ stdout: result.stdout ?? "",
119
+ stderr: result.stderr ?? "",
120
+ status: result.status,
121
+ };
122
+ }
123
+
124
+ function runGitChecked(cwd: string, args: string[]): string {
125
+ const result = runGit(cwd, args);
126
+ if (result.status !== 0) {
127
+ const command = `git -C ${cwd} ${args.join(" ")}`;
128
+ const message = result.stderr.trim() || result.stdout.trim() || `${command} failed`;
129
+ throw new Error(message);
130
+ }
131
+ return result.stdout;
132
+ }
133
+
134
+ function resolveRepoState(cwd: string): RepoState {
135
+ const cwdRelative = resolveRepoCwdRelative(cwd);
136
+ const toplevel = runGitChecked(cwd, ["rev-parse", "--show-toplevel"]).trim();
137
+
138
+ // pi-subagents writes durable runtime state under .pi-subagents/ by default;
139
+ // that state must not make managed isolation unusable for later runs.
140
+ const status = runGitChecked(toplevel, ["status", "--porcelain", "--", ":!.pi-subagents"]);
141
+ if (status.trim().length > 0) {
142
+ throw new Error("worktree isolation requires a clean git working tree. Commit or stash changes first.");
143
+ }
144
+
145
+ const baseCommit = runGitChecked(toplevel, ["rev-parse", "HEAD"]).trim();
146
+ return { toplevel, cwdRelative, baseCommit };
147
+ }
148
+
149
+ function normalizeComparableCwd(cwd: string): string {
150
+ const resolved = path.resolve(cwd);
151
+ try {
152
+ return fs.realpathSync(resolved);
153
+ } catch {
154
+ // Use the unresolved absolute path when realpath resolution is unavailable.
155
+ return resolved;
156
+ }
157
+ }
158
+
159
+ export function findWorktreeTaskCwdConflict(
160
+ tasks: ReadonlyArray<{ agent: string; cwd?: string }>,
161
+ sharedCwd: string,
162
+ ): WorktreeTaskCwdConflict | undefined {
163
+ const normalizedSharedCwd = normalizeComparableCwd(sharedCwd);
164
+ for (let index = 0; index < tasks.length; index++) {
165
+ const task = tasks[index]!;
166
+ if (!task.cwd) continue;
167
+ const taskCwd = path.isAbsolute(task.cwd) ? task.cwd : path.resolve(sharedCwd, task.cwd);
168
+ if (normalizeComparableCwd(taskCwd) === normalizedSharedCwd) continue;
169
+ return { index, agent: task.agent, cwd: task.cwd };
170
+ }
171
+ return undefined;
172
+ }
173
+
174
+ export function formatWorktreeTaskCwdConflict(
175
+ conflict: WorktreeTaskCwdConflict,
176
+ sharedCwd: string,
177
+ ): string {
178
+ return `worktree isolation uses the shared cwd (${sharedCwd}); task ${conflict.index + 1} (${conflict.agent}) sets cwd to ${conflict.cwd}. Remove task-level cwd overrides or disable worktree.`;
179
+ }
180
+
181
+ function safePatchAgentName(agent: string): string {
182
+ return agent.replace(/[^\w.-]/g, "_");
183
+ }
184
+
185
+ function buildWorktreeBranch(runId: string, index: number): string {
186
+ return `pi-parallel-${runId}-${index}`;
187
+ }
188
+
189
+ function resolveWorktreeBaseDir(configuredBaseDir: string | undefined, repoRoot: string): string {
190
+ const rawBaseDir = configuredBaseDir ?? process.env.PI_SUBAGENTS_WORKTREE_DIR;
191
+ if (rawBaseDir === undefined) return os.tmpdir();
192
+
193
+ const trimmed = rawBaseDir.trim();
194
+ if (!trimmed) throw new Error("worktree base directory cannot be empty");
195
+
196
+ const expanded = trimmed.startsWith("~/") ? path.join(os.homedir(), trimmed.slice(2)) : trimmed;
197
+ const resolved = path.isAbsolute(expanded) ? expanded : path.resolve(repoRoot, expanded);
198
+ try {
199
+ fs.mkdirSync(resolved, { recursive: true });
200
+ } catch (error) {
201
+ const message = error instanceof Error ? error.message : String(error);
202
+ throw new Error(`failed to create worktree base directory ${resolved}: ${message}`);
203
+ }
204
+ return resolved;
205
+ }
206
+
207
+ function buildWorktreePath(baseDir: string, runId: string, index: number): string {
208
+ return path.join(baseDir, `pi-worktree-${runId}-${index}`);
209
+ }
210
+
211
+ function resolveRepoCwdRelative(cwd: string): string {
212
+ const repoCheck = runGit(cwd, ["rev-parse", "--is-inside-work-tree"]);
213
+ if (repoCheck.status !== 0 || repoCheck.stdout.trim() !== "true") {
214
+ throw new Error("worktree isolation requires a git repository");
215
+ }
216
+ const rawPrefix = runGitChecked(cwd, ["rev-parse", "--show-prefix"]).trim();
217
+ const normalizedPrefix = rawPrefix
218
+ ? path.normalize(rawPrefix.replace(/[\\/]+$/, ""))
219
+ : "";
220
+ return normalizedPrefix === "." ? "" : normalizedPrefix;
221
+ }
222
+
223
+ export function resolveExpectedWorktreeAgentCwd(cwd: string, runId: string, index: number, baseDir?: string): string {
224
+ const cwdRelative = resolveRepoCwdRelative(cwd);
225
+ const repoRoot = runGitChecked(cwd, ["rev-parse", "--show-toplevel"]).trim();
226
+ const worktreePath = buildWorktreePath(resolveWorktreeBaseDir(baseDir, repoRoot), runId, index);
227
+ return cwdRelative ? path.join(worktreePath, cwdRelative) : worktreePath;
228
+ }
229
+
230
+ function linkNodeModulesIfPresent(toplevel: string, worktreePath: string): boolean {
231
+ const nodeModulesPath = path.join(toplevel, "node_modules");
232
+ const nodeModulesLinkPath = path.join(worktreePath, "node_modules");
233
+ if (!fs.existsSync(nodeModulesPath) || fs.existsSync(nodeModulesLinkPath)) return false;
234
+ try {
235
+ fs.symlinkSync(nodeModulesPath, nodeModulesLinkPath);
236
+ return true;
237
+ } catch {
238
+ // Symlink creation is optional (e.g., unsupported filesystems on CI runners).
239
+ return false;
240
+ }
241
+ }
242
+
243
+ function parseHookTimeout(timeoutMs: number | undefined): number {
244
+ if (timeoutMs === undefined) return DEFAULT_WORKTREE_SETUP_HOOK_TIMEOUT_MS;
245
+ if (!Number.isInteger(timeoutMs) || timeoutMs <= 0) {
246
+ throw new Error("worktree setup hook timeout must be an integer greater than 0");
247
+ }
248
+ return timeoutMs;
249
+ }
250
+
251
+ function resolveWorktreeSetupHook(
252
+ repoRoot: string,
253
+ config: WorktreeSetupHookConfig | undefined,
254
+ ): ResolvedWorktreeSetupHook | undefined {
255
+ if (!config) return undefined;
256
+ const hookPath = config.hookPath.trim();
257
+ if (!hookPath) {
258
+ throw new Error("worktree setup hook path cannot be empty");
259
+ }
260
+
261
+ const expandedHookPath = hookPath.startsWith("~/") ? path.join(os.homedir(), hookPath.slice(2)) : hookPath;
262
+ let resolvedPath: string;
263
+ if (path.isAbsolute(expandedHookPath)) {
264
+ resolvedPath = expandedHookPath;
265
+ } else if (expandedHookPath.includes("/") || expandedHookPath.includes("\\")) {
266
+ resolvedPath = path.resolve(repoRoot, expandedHookPath);
267
+ } else {
268
+ throw new Error("worktree setup hook must be an absolute path or a repo-relative path");
269
+ }
270
+
271
+ if (!fs.existsSync(resolvedPath)) {
272
+ throw new Error(`worktree setup hook not found: ${resolvedPath}`);
273
+ }
274
+ if (fs.statSync(resolvedPath).isDirectory()) {
275
+ throw new Error(`worktree setup hook must be a file, got directory: ${resolvedPath}`);
276
+ }
277
+
278
+ return {
279
+ hookPath: resolvedPath,
280
+ timeoutMs: parseHookTimeout(config.timeoutMs),
281
+ };
282
+ }
283
+
284
+ function normalizeSyntheticPath(worktreePath: string, rawPath: string): string {
285
+ const trimmed = rawPath.trim();
286
+ if (!trimmed) throw new Error("synthetic path cannot be empty");
287
+ if (path.isAbsolute(trimmed)) throw new Error(`synthetic path must be relative: ${rawPath}`);
288
+
289
+ const resolved = path.resolve(worktreePath, trimmed);
290
+ const relative = path.relative(worktreePath, resolved);
291
+ if (!relative || relative === ".") {
292
+ throw new Error(`synthetic path cannot target the worktree root: ${rawPath}`);
293
+ }
294
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
295
+ throw new Error(`synthetic path escapes the worktree root: ${rawPath}`);
296
+ }
297
+ return path.normalize(relative);
298
+ }
299
+
300
+ function hasTrackedEntries(worktreePath: string, relativePath: string): boolean {
301
+ const result = runGit(worktreePath, ["ls-files", "--", relativePath]);
302
+ return result.status === 0 && result.stdout.trim().length > 0;
303
+ }
304
+
305
+ function parseWorktreeSetupHookOutput(rawStdout: string): WorktreeSetupHookOutput {
306
+ const trimmed = rawStdout.trim();
307
+ if (!trimmed) {
308
+ throw new Error("worktree setup hook returned empty stdout; expected JSON object");
309
+ }
310
+ let parsed: unknown;
311
+ try {
312
+ parsed = JSON.parse(trimmed);
313
+ } catch (error) {
314
+ const message = error instanceof Error ? error.message : String(error);
315
+ throw new Error(`worktree setup hook returned invalid JSON: ${message}`);
316
+ }
317
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
318
+ throw new Error("worktree setup hook stdout must be a JSON object");
319
+ }
320
+ return parsed as WorktreeSetupHookOutput;
321
+ }
322
+
323
+ function runWorktreeSetupHook(
324
+ hook: ResolvedWorktreeSetupHook,
325
+ input: WorktreeSetupHookInput,
326
+ ): string[] {
327
+ const result = spawnSync(hook.hookPath, [], {
328
+ cwd: input.worktreePath,
329
+ encoding: "utf-8",
330
+ input: JSON.stringify(input),
331
+ timeout: hook.timeoutMs,
332
+ shell: false,
333
+ });
334
+
335
+ if (result.error) {
336
+ const code = "code" in result.error ? result.error.code : undefined;
337
+ if (code === "ETIMEDOUT") {
338
+ throw new Error(`worktree setup hook timed out after ${hook.timeoutMs}ms`);
339
+ }
340
+ throw new Error(`worktree setup hook failed: ${result.error.message}`);
341
+ }
342
+
343
+ if (result.status !== 0) {
344
+ const details = result.stderr.trim() || result.stdout.trim() || "no output";
345
+ throw new Error(`worktree setup hook failed with exit code ${result.status}: ${details}`);
346
+ }
347
+
348
+ const output = parseWorktreeSetupHookOutput(result.stdout);
349
+ if (output.syntheticPaths === undefined) return [];
350
+ if (!Array.isArray(output.syntheticPaths)) {
351
+ throw new Error("worktree setup hook output field 'syntheticPaths' must be an array of relative paths");
352
+ }
353
+
354
+ const uniquePaths = new Set<string>();
355
+ for (const candidate of output.syntheticPaths) {
356
+ if (typeof candidate !== "string") {
357
+ throw new Error("worktree setup hook output field 'syntheticPaths' must contain only strings");
358
+ }
359
+ const normalizedPath = normalizeSyntheticPath(input.worktreePath, candidate);
360
+ if (hasTrackedEntries(input.worktreePath, normalizedPath)) {
361
+ throw new Error(`worktree setup hook cannot mark tracked paths as synthetic: ${normalizedPath}`);
362
+ }
363
+ uniquePaths.add(normalizedPath);
364
+ }
365
+ return [...uniquePaths];
366
+ }
367
+
368
+ function createSingleWorktree(
369
+ toplevel: string,
370
+ cwdRelative: string,
371
+ runId: string,
372
+ index: number,
373
+ baseCommit: string,
374
+ setupHook: ResolvedWorktreeSetupHook | undefined,
375
+ agent: string | undefined,
376
+ baseDir: string,
377
+ ): WorktreeInfo {
378
+ const branch = buildWorktreeBranch(runId, index);
379
+ const worktreePath = buildWorktreePath(baseDir, runId, index);
380
+ const add = runGit(toplevel, ["worktree", "add", worktreePath, "-b", branch, "HEAD"]);
381
+ if (add.status !== 0) {
382
+ const message = add.stderr.trim() || add.stdout.trim() || `failed to create worktree ${worktreePath}`;
383
+ throw new Error(message);
384
+ }
385
+
386
+ const agentCwd = cwdRelative ? path.join(worktreePath, cwdRelative) : worktreePath;
387
+ try {
388
+ const nodeModulesLinked = linkNodeModulesIfPresent(toplevel, worktreePath);
389
+ const syntheticPaths = nodeModulesLinked ? ["node_modules"] : [];
390
+
391
+ if (setupHook) {
392
+ const hookSyntheticPaths = runWorktreeSetupHook(setupHook, {
393
+ version: 1,
394
+ repoRoot: toplevel,
395
+ worktreePath,
396
+ agentCwd,
397
+ branch,
398
+ index,
399
+ runId,
400
+ baseCommit,
401
+ agent,
402
+ });
403
+ syntheticPaths.push(...hookSyntheticPaths);
404
+ }
405
+
406
+ return {
407
+ path: worktreePath,
408
+ agentCwd,
409
+ branch,
410
+ index,
411
+ nodeModulesLinked,
412
+ syntheticPaths,
413
+ };
414
+ } catch (error) {
415
+ try { runGitChecked(toplevel, ["worktree", "remove", "--force", worktreePath]); } catch {
416
+ // Best-effort rollback; preserve the original setup failure.
417
+ }
418
+ try { runGitChecked(toplevel, ["branch", "-D", branch]); } catch {
419
+ // Best-effort rollback; preserve the original setup failure.
420
+ }
421
+ throw error;
422
+ }
423
+ }
424
+
425
+ function removeSyntheticPath(worktree: WorktreeInfo, syntheticPath: string): void {
426
+ const resolved = path.resolve(worktree.path, syntheticPath);
427
+ const relative = path.relative(worktree.path, resolved);
428
+ if (!relative || relative === "." || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
429
+ return;
430
+ }
431
+
432
+ let stat: fs.Stats;
433
+ try {
434
+ stat = fs.lstatSync(resolved);
435
+ } catch (error) {
436
+ const code = error && typeof error === "object" && "code" in error ? (error as { code?: unknown }).code : undefined;
437
+ if (code === "ENOENT") return;
438
+ throw error;
439
+ }
440
+
441
+ if (stat.isSymbolicLink()) {
442
+ fs.unlinkSync(resolved);
443
+ return;
444
+ }
445
+ if (stat.isDirectory()) {
446
+ fs.rmSync(resolved, { recursive: true, force: true });
447
+ return;
448
+ }
449
+ fs.rmSync(resolved, { force: true });
450
+ }
451
+
452
+ function removeSyntheticPathsBeforeDiff(worktree: WorktreeInfo): void {
453
+ if (worktree.syntheticPaths.length === 0) return;
454
+ const seen = new Set<string>();
455
+ for (const syntheticPath of worktree.syntheticPaths) {
456
+ if (seen.has(syntheticPath)) continue;
457
+ seen.add(syntheticPath);
458
+ removeSyntheticPath(worktree, syntheticPath);
459
+ }
460
+ }
461
+
462
+ function emptyDiff(index: number, agent: string, branch: string, patchPath: string, error?: string): WorktreeDiff {
463
+ return {
464
+ index,
465
+ agent,
466
+ branch,
467
+ diffStat: "",
468
+ filesChanged: 0,
469
+ insertions: 0,
470
+ deletions: 0,
471
+ patchPath,
472
+ ...(error ? { error } : {}),
473
+ };
474
+ }
475
+
476
+ function parseNumstat(numstat: string): { filesChanged: number; insertions: number; deletions: number } {
477
+ const lines = numstat
478
+ .split("\n")
479
+ .map((line) => line.trim())
480
+ .filter(Boolean);
481
+ let filesChanged = 0;
482
+ let insertions = 0;
483
+ let deletions = 0;
484
+
485
+ for (const line of lines) {
486
+ const [rawInsertions, rawDeletions] = line.split("\t");
487
+ if (rawInsertions === undefined || rawDeletions === undefined) continue;
488
+ filesChanged++;
489
+ if (/^\d+$/.test(rawInsertions)) insertions += parseInt(rawInsertions, 10);
490
+ if (/^\d+$/.test(rawDeletions)) deletions += parseInt(rawDeletions, 10);
491
+ }
492
+
493
+ return { filesChanged, insertions, deletions };
494
+ }
495
+
496
+ function captureWorktreeDiff(
497
+ setup: WorktreeSetup,
498
+ worktree: WorktreeInfo,
499
+ agent: string,
500
+ patchPath: string,
501
+ ): WorktreeDiff {
502
+ removeSyntheticPathsBeforeDiff(worktree);
503
+ runGitChecked(worktree.path, ["add", "-A"]);
504
+ const diffStat = runGitChecked(worktree.path, ["diff", "--cached", "--stat", setup.baseCommit]).trim();
505
+ const patch = runGitChecked(worktree.path, ["diff", "--cached", setup.baseCommit]);
506
+ const numstat = runGitChecked(worktree.path, ["diff", "--cached", "--numstat", setup.baseCommit]);
507
+ fs.writeFileSync(patchPath, patch, "utf-8");
508
+
509
+ if (!patch.trim()) {
510
+ return emptyDiff(worktree.index, agent, worktree.branch, patchPath);
511
+ }
512
+
513
+ const parsed = parseNumstat(numstat);
514
+ return {
515
+ index: worktree.index,
516
+ agent,
517
+ branch: worktree.branch,
518
+ diffStat,
519
+ filesChanged: parsed.filesChanged,
520
+ insertions: parsed.insertions,
521
+ deletions: parsed.deletions,
522
+ patchPath,
523
+ };
524
+ }
525
+
526
+ function writeEmptyPatch(patchPath: string): void {
527
+ try {
528
+ fs.writeFileSync(patchPath, "", "utf-8");
529
+ } catch {
530
+ // Diff artifact writing is best-effort in error paths.
531
+ }
532
+ }
533
+
534
+ function handoffRecordsPatch(manifestPath: string | undefined, patchPath: string): boolean {
535
+ if (!manifestPath || !fs.existsSync(manifestPath)) return false;
536
+ try {
537
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf-8")) as {
538
+ version?: unknown;
539
+ groups?: Array<{ children?: Array<{ patch?: { path?: unknown; error?: unknown } }> }>;
540
+ };
541
+ if (manifest.version !== 1 || !Array.isArray(manifest.groups)) return false;
542
+ const resolvedPatchPath = path.resolve(patchPath);
543
+ return manifest.groups.some((group) => Array.isArray(group.children) && group.children.some((child) =>
544
+ child.patch?.error === undefined
545
+ && typeof child.patch?.path === "string"
546
+ && path.resolve(child.patch.path) === resolvedPatchPath,
547
+ ));
548
+ } catch {
549
+ return false;
550
+ }
551
+ }
552
+
553
+ function cleanupSingleWorktree(
554
+ setup: WorktreeSetup,
555
+ worktree: WorktreeInfo,
556
+ intent: WorktreeCleanupIntent,
557
+ ): WorktreeCleanupTask {
558
+ const errors: string[] = [];
559
+ let worktreeRemoved = false;
560
+ let branchRemoved = false;
561
+ if (intent.kind !== "setup-rollback") {
562
+ try {
563
+ removeSyntheticPathsBeforeDiff(worktree);
564
+ } catch (error) {
565
+ errors.push(`synthetic path cleanup failed: ${error instanceof Error ? error.message : String(error)}`);
566
+ }
567
+ const status = runGit(worktree.path, ["status", "--porcelain"]);
568
+ const baseDiff = runGit(worktree.path, ["diff", "--quiet", setup.baseCommit, "--"]);
569
+ if (status.status !== 0 || (baseDiff.status !== 0 && baseDiff.status !== 1)) {
570
+ const reason = status.status !== 0
571
+ ? status.stderr.trim() || status.stdout.trim() || "git status failed"
572
+ : baseDiff.stderr.trim() || baseDiff.stdout.trim() || "git diff check failed";
573
+ return {
574
+ index: worktree.index,
575
+ path: worktree.path,
576
+ branch: worktree.branch,
577
+ worktreeRemoved: false,
578
+ branchRemoved: false,
579
+ preserved: true,
580
+ reason: "cleanup safety check failed",
581
+ errors: [...errors, `cleanup refused: ${reason}`],
582
+ };
583
+ }
584
+ const hasWork = status.stdout.trim().length > 0 || baseDiff.status === 1;
585
+ if (hasWork && intent.kind === "preserve") {
586
+ const captured = (intent.capturedDiffs ?? setup.capturedDiffs)?.find((diff) => diff.index === worktree.index);
587
+ const patchCaptured = captured !== undefined
588
+ && captured.error === undefined
589
+ && fs.existsSync(captured.patchPath)
590
+ && fs.statSync(captured.patchPath).size > 0
591
+ && handoffRecordsPatch(intent.handoffManifestPath, captured.patchPath);
592
+ if (!patchCaptured) {
593
+ const reason = "worktree contains changes that are not represented by a captured handoff patch";
594
+ return {
595
+ index: worktree.index,
596
+ path: worktree.path,
597
+ branch: worktree.branch,
598
+ worktreeRemoved: false,
599
+ branchRemoved: false,
600
+ preserved: true,
601
+ reason,
602
+ errors: [...errors, `cleanup refused: ${reason}; preserved ${worktree.path}`],
603
+ };
604
+ }
605
+ }
606
+ if (hasWork && intent.kind === "discard") {
607
+ const decision = resolveAuthorityDecision({ action: "discardWorktree", policy: intent.authorization.policy });
608
+ const authorized = decision === "auto" || (decision === "confirm" && intent.authorization.kind === "confirmed");
609
+ if (!authorized) {
610
+ const reason = decision === "forbid"
611
+ ? "authority policy forbids worktree discard"
612
+ : "worktree discard requires explicit user confirmation";
613
+ return {
614
+ index: worktree.index,
615
+ path: worktree.path,
616
+ branch: worktree.branch,
617
+ worktreeRemoved: false,
618
+ branchRemoved: false,
619
+ preserved: true,
620
+ reason,
621
+ errors: [...errors, `cleanup refused: ${reason}; preserved ${worktree.path}`],
622
+ };
623
+ }
624
+ }
625
+ }
626
+ try {
627
+ runGitChecked(setup.cwd, ["worktree", "remove", "--force", worktree.path]);
628
+ worktreeRemoved = true;
629
+ } catch (error) {
630
+ errors.push(`worktree removal failed: ${error instanceof Error ? error.message : String(error)}`);
631
+ }
632
+ if (worktreeRemoved) {
633
+ try {
634
+ runGitChecked(setup.cwd, ["branch", "-D", worktree.branch]);
635
+ branchRemoved = true;
636
+ } catch (error) {
637
+ errors.push(`branch removal failed: ${error instanceof Error ? error.message : String(error)}`);
638
+ }
639
+ }
640
+ return {
641
+ index: worktree.index,
642
+ path: worktree.path,
643
+ branch: worktree.branch,
644
+ worktreeRemoved,
645
+ branchRemoved,
646
+ ...(errors.length ? { errors } : {}),
647
+ };
648
+ }
649
+
650
+ function hasWorktreeChanges(diff: WorktreeDiff): boolean {
651
+ return diff.filesChanged > 0 || diff.insertions > 0 || diff.deletions > 0 || diff.diffStat.trim().length > 0;
652
+ }
653
+
654
+ export function createWorktrees(cwd: string, runId: string, count: number, options?: CreateWorktreesOptions): WorktreeSetup {
655
+ const repo = resolveRepoState(cwd);
656
+ const setupHook = resolveWorktreeSetupHook(repo.toplevel, options?.setupHook);
657
+ const baseDir = resolveWorktreeBaseDir(options?.baseDir, repo.toplevel);
658
+ const worktrees: WorktreeInfo[] = [];
659
+
660
+ try {
661
+ for (let index = 0; index < count; index++) {
662
+ worktrees.push(createSingleWorktree(
663
+ repo.toplevel,
664
+ repo.cwdRelative,
665
+ runId,
666
+ index,
667
+ repo.baseCommit,
668
+ setupHook,
669
+ options?.agents?.[index],
670
+ baseDir,
671
+ ));
672
+ }
673
+ } catch (error) {
674
+ cleanupWorktrees({
675
+ cwd: repo.toplevel,
676
+ worktrees,
677
+ baseCommit: repo.baseCommit,
678
+ }, { kind: "setup-rollback" });
679
+ throw error;
680
+ }
681
+
682
+ return {
683
+ cwd: repo.toplevel,
684
+ worktrees,
685
+ baseCommit: repo.baseCommit,
686
+ };
687
+ }
688
+
689
+ export function diffWorktrees(setup: WorktreeSetup, agents: string[], diffsDir: string): WorktreeDiff[] {
690
+ try {
691
+ fs.mkdirSync(diffsDir, { recursive: true });
692
+ } catch {
693
+ // Returning no diffs is safer than failing the whole command on artifact-dir issues.
694
+ return [];
695
+ }
696
+
697
+ const diffs: WorktreeDiff[] = [];
698
+ for (let index = 0; index < setup.worktrees.length; index++) {
699
+ const worktree = setup.worktrees[index]!;
700
+ const agent = agents[index] ?? `task-${index + 1}`;
701
+ const patchPath = path.join(diffsDir, `task-${index}-${safePatchAgentName(agent)}.patch`);
702
+ try {
703
+ diffs.push(captureWorktreeDiff(setup, worktree, agent, patchPath));
704
+ } catch (error) {
705
+ // Preserve execution flow while retaining the failed capture as handoff evidence.
706
+ writeEmptyPatch(patchPath);
707
+ diffs.push(emptyDiff(index, agent, worktree.branch, patchPath, error instanceof Error ? error.message : String(error)));
708
+ }
709
+ }
710
+
711
+ setup.capturedDiffs = diffs;
712
+ return diffs;
713
+ }
714
+
715
+ export function cleanupWorktrees(
716
+ setup: WorktreeSetup,
717
+ intent: WorktreeCleanupIntent = { kind: "preserve", ...(setup.capturedDiffs ? { capturedDiffs: setup.capturedDiffs } : {}) },
718
+ ): WorktreeCleanupReport {
719
+ const tasks: WorktreeCleanupTask[] = [];
720
+ for (let index = setup.worktrees.length - 1; index >= 0; index--) {
721
+ tasks.push(cleanupSingleWorktree(setup, setup.worktrees[index]!, intent));
722
+ }
723
+ tasks.sort((left, right) => left.index - right.index);
724
+ const errors: string[] = [];
725
+ let pruned = false;
726
+ try {
727
+ runGitChecked(setup.cwd, ["worktree", "prune"]);
728
+ pruned = true;
729
+ } catch (error) {
730
+ errors.push(`worktree prune failed: ${error instanceof Error ? error.message : String(error)}`);
731
+ }
732
+ const state = tasks.every((task) => task.worktreeRemoved && task.branchRemoved) && pruned ? "complete" : "partial";
733
+ return {
734
+ state,
735
+ tasks,
736
+ pruned,
737
+ ...(errors.length ? { errors } : {}),
738
+ };
739
+ }
740
+
741
+ export function formatWorktreeDiffSummary(diffs: WorktreeDiff[]): string {
742
+ const changed = diffs.filter(hasWorktreeChanges);
743
+ if (changed.length === 0) return "";
744
+
745
+ const lines: string[] = ["=== Worktree Changes ===", ""];
746
+ for (const diff of changed) {
747
+ lines.push(
748
+ `--- Task ${diff.index + 1} (${diff.agent}): ${diff.filesChanged} files changed, +${diff.insertions} -${diff.deletions} ---`,
749
+ );
750
+ if (diff.diffStat.trim().length > 0) {
751
+ lines.push(diff.diffStat);
752
+ }
753
+ lines.push("");
754
+ }
755
+
756
+ const patchesDir = path.dirname(changed[0]!.patchPath);
757
+ lines.push(`Full patches: ${patchesDir}`);
758
+ return lines.join("\n").trimEnd();
759
+ }