opencode-swarm-plugin 0.44.0 → 0.44.1

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 (205) hide show
  1. package/bin/swarm.serve.test.ts +6 -4
  2. package/bin/swarm.ts +16 -10
  3. package/dist/compaction-prompt-scoring.js +139 -0
  4. package/dist/eval-capture.js +12811 -0
  5. package/dist/hive.d.ts.map +1 -1
  6. package/dist/index.js +7644 -62599
  7. package/dist/plugin.js +23766 -78721
  8. package/dist/swarm-orchestrate.d.ts.map +1 -1
  9. package/dist/swarm-prompts.d.ts.map +1 -1
  10. package/dist/swarm-review.d.ts.map +1 -1
  11. package/package.json +17 -5
  12. package/.changeset/swarm-insights-data-layer.md +0 -63
  13. package/.hive/analysis/eval-failure-analysis-2025-12-25.md +0 -331
  14. package/.hive/analysis/session-data-quality-audit.md +0 -320
  15. package/.hive/eval-results.json +0 -483
  16. package/.hive/issues.jsonl +0 -138
  17. package/.hive/memories.jsonl +0 -729
  18. package/.opencode/eval-history.jsonl +0 -327
  19. package/.turbo/turbo-build.log +0 -9
  20. package/CHANGELOG.md +0 -2286
  21. package/SCORER-ANALYSIS.md +0 -598
  22. package/docs/analysis/subagent-coordination-patterns.md +0 -902
  23. package/docs/analysis-socratic-planner-pattern.md +0 -504
  24. package/docs/planning/ADR-001-monorepo-structure.md +0 -171
  25. package/docs/planning/ADR-002-package-extraction.md +0 -393
  26. package/docs/planning/ADR-003-performance-improvements.md +0 -451
  27. package/docs/planning/ADR-004-message-queue-features.md +0 -187
  28. package/docs/planning/ADR-005-devtools-observability.md +0 -202
  29. package/docs/planning/ADR-007-swarm-enhancements-worktree-review.md +0 -168
  30. package/docs/planning/ADR-008-worker-handoff-protocol.md +0 -293
  31. package/docs/planning/ADR-009-oh-my-opencode-patterns.md +0 -353
  32. package/docs/planning/ADR-010-cass-inhousing.md +0 -1215
  33. package/docs/planning/ROADMAP.md +0 -368
  34. package/docs/semantic-memory-cli-syntax.md +0 -123
  35. package/docs/swarm-mail-architecture.md +0 -1147
  36. package/docs/testing/context-recovery-test.md +0 -470
  37. package/evals/ARCHITECTURE.md +0 -1189
  38. package/evals/README.md +0 -768
  39. package/evals/compaction-prompt.eval.ts +0 -149
  40. package/evals/compaction-resumption.eval.ts +0 -289
  41. package/evals/coordinator-behavior.eval.ts +0 -307
  42. package/evals/coordinator-session.eval.ts +0 -154
  43. package/evals/evalite.config.ts.bak +0 -15
  44. package/evals/example.eval.ts +0 -31
  45. package/evals/fixtures/cass-baseline.ts +0 -217
  46. package/evals/fixtures/compaction-cases.ts +0 -350
  47. package/evals/fixtures/compaction-prompt-cases.ts +0 -311
  48. package/evals/fixtures/coordinator-sessions.ts +0 -328
  49. package/evals/fixtures/decomposition-cases.ts +0 -105
  50. package/evals/lib/compaction-loader.test.ts +0 -248
  51. package/evals/lib/compaction-loader.ts +0 -320
  52. package/evals/lib/data-loader.evalite-test.ts +0 -289
  53. package/evals/lib/data-loader.test.ts +0 -345
  54. package/evals/lib/data-loader.ts +0 -281
  55. package/evals/lib/llm.ts +0 -115
  56. package/evals/scorers/compaction-prompt-scorers.ts +0 -145
  57. package/evals/scorers/compaction-scorers.ts +0 -305
  58. package/evals/scorers/coordinator-discipline.evalite-test.ts +0 -539
  59. package/evals/scorers/coordinator-discipline.ts +0 -325
  60. package/evals/scorers/index.test.ts +0 -146
  61. package/evals/scorers/index.ts +0 -328
  62. package/evals/scorers/outcome-scorers.evalite-test.ts +0 -27
  63. package/evals/scorers/outcome-scorers.ts +0 -349
  64. package/evals/swarm-decomposition.eval.ts +0 -121
  65. package/examples/commands/swarm.md +0 -745
  66. package/examples/plugin-wrapper-template.ts +0 -2515
  67. package/examples/skills/hive-workflow/SKILL.md +0 -212
  68. package/examples/skills/skill-creator/SKILL.md +0 -223
  69. package/examples/skills/swarm-coordination/SKILL.md +0 -292
  70. package/global-skills/cli-builder/SKILL.md +0 -344
  71. package/global-skills/cli-builder/references/advanced-patterns.md +0 -244
  72. package/global-skills/learning-systems/SKILL.md +0 -644
  73. package/global-skills/skill-creator/LICENSE.txt +0 -202
  74. package/global-skills/skill-creator/SKILL.md +0 -352
  75. package/global-skills/skill-creator/references/output-patterns.md +0 -82
  76. package/global-skills/skill-creator/references/workflows.md +0 -28
  77. package/global-skills/swarm-coordination/SKILL.md +0 -995
  78. package/global-skills/swarm-coordination/references/coordinator-patterns.md +0 -235
  79. package/global-skills/swarm-coordination/references/strategies.md +0 -138
  80. package/global-skills/system-design/SKILL.md +0 -213
  81. package/global-skills/testing-patterns/SKILL.md +0 -430
  82. package/global-skills/testing-patterns/references/dependency-breaking-catalog.md +0 -586
  83. package/opencode-swarm-plugin-0.30.7.tgz +0 -0
  84. package/opencode-swarm-plugin-0.31.0.tgz +0 -0
  85. package/scripts/cleanup-test-memories.ts +0 -346
  86. package/scripts/init-skill.ts +0 -222
  87. package/scripts/migrate-unknown-sessions.ts +0 -349
  88. package/scripts/validate-skill.ts +0 -204
  89. package/src/agent-mail.ts +0 -1724
  90. package/src/anti-patterns.test.ts +0 -1167
  91. package/src/anti-patterns.ts +0 -448
  92. package/src/compaction-capture.integration.test.ts +0 -257
  93. package/src/compaction-hook.test.ts +0 -838
  94. package/src/compaction-hook.ts +0 -1204
  95. package/src/compaction-observability.integration.test.ts +0 -139
  96. package/src/compaction-observability.test.ts +0 -187
  97. package/src/compaction-observability.ts +0 -324
  98. package/src/compaction-prompt-scorers.test.ts +0 -475
  99. package/src/compaction-prompt-scoring.ts +0 -300
  100. package/src/contributor-tools.test.ts +0 -133
  101. package/src/contributor-tools.ts +0 -201
  102. package/src/dashboard.test.ts +0 -611
  103. package/src/dashboard.ts +0 -462
  104. package/src/error-enrichment.test.ts +0 -403
  105. package/src/error-enrichment.ts +0 -219
  106. package/src/eval-capture.test.ts +0 -1015
  107. package/src/eval-capture.ts +0 -929
  108. package/src/eval-gates.test.ts +0 -306
  109. package/src/eval-gates.ts +0 -218
  110. package/src/eval-history.test.ts +0 -508
  111. package/src/eval-history.ts +0 -214
  112. package/src/eval-learning.test.ts +0 -378
  113. package/src/eval-learning.ts +0 -360
  114. package/src/eval-runner.test.ts +0 -223
  115. package/src/eval-runner.ts +0 -402
  116. package/src/export-tools.test.ts +0 -476
  117. package/src/export-tools.ts +0 -257
  118. package/src/hive.integration.test.ts +0 -2241
  119. package/src/hive.ts +0 -1628
  120. package/src/index.ts +0 -940
  121. package/src/learning.integration.test.ts +0 -1815
  122. package/src/learning.ts +0 -1079
  123. package/src/logger.test.ts +0 -189
  124. package/src/logger.ts +0 -135
  125. package/src/mandate-promotion.test.ts +0 -473
  126. package/src/mandate-promotion.ts +0 -239
  127. package/src/mandate-storage.integration.test.ts +0 -601
  128. package/src/mandate-storage.test.ts +0 -578
  129. package/src/mandate-storage.ts +0 -794
  130. package/src/mandates.ts +0 -540
  131. package/src/memory-tools.test.ts +0 -195
  132. package/src/memory-tools.ts +0 -344
  133. package/src/memory.integration.test.ts +0 -334
  134. package/src/memory.test.ts +0 -158
  135. package/src/memory.ts +0 -527
  136. package/src/model-selection.test.ts +0 -188
  137. package/src/model-selection.ts +0 -68
  138. package/src/observability-tools.test.ts +0 -359
  139. package/src/observability-tools.ts +0 -871
  140. package/src/output-guardrails.test.ts +0 -438
  141. package/src/output-guardrails.ts +0 -381
  142. package/src/pattern-maturity.test.ts +0 -1160
  143. package/src/pattern-maturity.ts +0 -525
  144. package/src/planning-guardrails.test.ts +0 -491
  145. package/src/planning-guardrails.ts +0 -438
  146. package/src/plugin.ts +0 -23
  147. package/src/post-compaction-tracker.test.ts +0 -251
  148. package/src/post-compaction-tracker.ts +0 -237
  149. package/src/query-tools.test.ts +0 -636
  150. package/src/query-tools.ts +0 -324
  151. package/src/rate-limiter.integration.test.ts +0 -466
  152. package/src/rate-limiter.ts +0 -774
  153. package/src/replay-tools.test.ts +0 -496
  154. package/src/replay-tools.ts +0 -240
  155. package/src/repo-crawl.integration.test.ts +0 -441
  156. package/src/repo-crawl.ts +0 -610
  157. package/src/schemas/cell-events.test.ts +0 -347
  158. package/src/schemas/cell-events.ts +0 -807
  159. package/src/schemas/cell.ts +0 -257
  160. package/src/schemas/evaluation.ts +0 -166
  161. package/src/schemas/index.test.ts +0 -199
  162. package/src/schemas/index.ts +0 -286
  163. package/src/schemas/mandate.ts +0 -232
  164. package/src/schemas/swarm-context.ts +0 -115
  165. package/src/schemas/task.ts +0 -161
  166. package/src/schemas/worker-handoff.test.ts +0 -302
  167. package/src/schemas/worker-handoff.ts +0 -131
  168. package/src/sessions/agent-discovery.test.ts +0 -137
  169. package/src/sessions/agent-discovery.ts +0 -112
  170. package/src/sessions/index.ts +0 -15
  171. package/src/skills.integration.test.ts +0 -1192
  172. package/src/skills.test.ts +0 -643
  173. package/src/skills.ts +0 -1549
  174. package/src/storage.integration.test.ts +0 -341
  175. package/src/storage.ts +0 -884
  176. package/src/structured.integration.test.ts +0 -817
  177. package/src/structured.test.ts +0 -1046
  178. package/src/structured.ts +0 -762
  179. package/src/swarm-decompose.test.ts +0 -188
  180. package/src/swarm-decompose.ts +0 -1302
  181. package/src/swarm-deferred.integration.test.ts +0 -157
  182. package/src/swarm-deferred.test.ts +0 -38
  183. package/src/swarm-insights.test.ts +0 -214
  184. package/src/swarm-insights.ts +0 -459
  185. package/src/swarm-mail.integration.test.ts +0 -970
  186. package/src/swarm-mail.ts +0 -739
  187. package/src/swarm-orchestrate.integration.test.ts +0 -282
  188. package/src/swarm-orchestrate.test.ts +0 -548
  189. package/src/swarm-orchestrate.ts +0 -3084
  190. package/src/swarm-prompts.test.ts +0 -1270
  191. package/src/swarm-prompts.ts +0 -2077
  192. package/src/swarm-research.integration.test.ts +0 -701
  193. package/src/swarm-research.test.ts +0 -698
  194. package/src/swarm-research.ts +0 -472
  195. package/src/swarm-review.integration.test.ts +0 -285
  196. package/src/swarm-review.test.ts +0 -879
  197. package/src/swarm-review.ts +0 -709
  198. package/src/swarm-strategies.ts +0 -407
  199. package/src/swarm-worktree.test.ts +0 -501
  200. package/src/swarm-worktree.ts +0 -575
  201. package/src/swarm.integration.test.ts +0 -2377
  202. package/src/swarm.ts +0 -38
  203. package/src/tool-adapter.integration.test.ts +0 -1221
  204. package/src/tool-availability.ts +0 -461
  205. package/tsconfig.json +0 -28
@@ -1,575 +0,0 @@
1
- /**
2
- * Swarm Worktree Isolation Module
3
- *
4
- * Provides git worktree-based isolation for parallel swarm workers.
5
- * Each worker gets their own worktree at a shared start commit,
6
- * preventing file conflicts without needing reservations.
7
- *
8
- * Key features:
9
- * - Create worktrees at specific commits (swarm start point)
10
- * - Cherry-pick commits back to main branch
11
- * - Clean up worktrees on completion or abort
12
- * - List active worktrees for a project
13
- *
14
- * Credit: Patterns inspired by https://github.com/nexxeln/opencode-config
15
- */
16
-
17
- import { tool } from "@opencode-ai/plugin";
18
- import { z } from "zod";
19
- import { join } from "node:path";
20
- import { existsSync } from "node:fs";
21
-
22
- // ============================================================================
23
- // Types
24
- // ============================================================================
25
-
26
- /**
27
- * Worktree info returned by git worktree list
28
- */
29
- export interface WorktreeInfo {
30
- task_id: string;
31
- path: string;
32
- commit: string;
33
- branch?: string;
34
- created_at?: string;
35
- }
36
-
37
- /**
38
- * Result of worktree operations
39
- */
40
- export interface WorktreeResult {
41
- success: boolean;
42
- worktree_path?: string;
43
- task_id?: string;
44
- error?: string;
45
- created_at_commit?: string;
46
- merged_commit?: string;
47
- removed_path?: string;
48
- removed_count?: number;
49
- already_removed?: boolean;
50
- conflicting_files?: string[];
51
- }
52
-
53
- // ============================================================================
54
- // Constants
55
- // ============================================================================
56
-
57
- /**
58
- * Directory where worktrees are stored
59
- */
60
- const WORKTREE_DIR = ".swarm/worktrees";
61
-
62
- /**
63
- * Get the worktree path for a task
64
- */
65
- function getWorktreePath(projectPath: string, taskId: string): string {
66
- // Sanitize task ID for filesystem
67
- const safeTaskId = taskId.replace(/[^a-zA-Z0-9.-]/g, "_");
68
- return join(projectPath, WORKTREE_DIR, safeTaskId);
69
- }
70
-
71
- /**
72
- * Parse task ID from worktree path
73
- */
74
- function parseTaskIdFromPath(worktreePath: string): string | null {
75
- const parts = worktreePath.split("/");
76
- const worktreesIdx = parts.indexOf("worktrees");
77
- if (worktreesIdx >= 0 && worktreesIdx < parts.length - 1) {
78
- return parts[worktreesIdx + 1];
79
- }
80
- return null;
81
- }
82
-
83
- // ============================================================================
84
- // Helper Functions
85
- // ============================================================================
86
-
87
- /**
88
- * Check if a path is a git repository
89
- */
90
- async function isGitRepo(path: string): Promise<boolean> {
91
- const result = await Bun.$`git -C ${path} rev-parse --git-dir`
92
- .quiet()
93
- .nothrow();
94
- return result.exitCode === 0;
95
- }
96
-
97
- /**
98
- * Check if there are uncommitted changes
99
- */
100
- async function hasUncommittedChanges(path: string): Promise<boolean> {
101
- const result = await Bun.$`git -C ${path} status --porcelain`.quiet().nothrow();
102
- if (result.exitCode !== 0) return true; // Assume dirty if can't check
103
- return result.stdout.toString().trim().length > 0;
104
- }
105
-
106
- /**
107
- * Get current HEAD commit
108
- */
109
- async function getCurrentCommit(path: string): Promise<string | null> {
110
- const result = await Bun.$`git -C ${path} rev-parse HEAD`.quiet().nothrow();
111
- if (result.exitCode !== 0) return null;
112
- return result.stdout.toString().trim();
113
- }
114
-
115
- /**
116
- * Get commits in worktree since start_commit
117
- */
118
- async function getWorktreeCommits(
119
- worktreePath: string,
120
- startCommit: string,
121
- ): Promise<string[]> {
122
- const result =
123
- await Bun.$`git -C ${worktreePath} log --format=%H ${startCommit}..HEAD`
124
- .quiet()
125
- .nothrow();
126
- if (result.exitCode !== 0) return [];
127
- return result.stdout
128
- .toString()
129
- .trim()
130
- .split("\n")
131
- .filter((c: string) => c.length > 0);
132
- }
133
-
134
- /**
135
- * Ensure worktree directory exists
136
- */
137
- async function ensureWorktreeDir(projectPath: string): Promise<void> {
138
- const worktreeDir = join(projectPath, WORKTREE_DIR);
139
- await Bun.$`mkdir -p ${worktreeDir}`.quiet().nothrow();
140
- }
141
-
142
- // ============================================================================
143
- // Tool Definitions
144
- // ============================================================================
145
-
146
- /**
147
- * Create a git worktree for a task
148
- *
149
- * Creates an isolated worktree at the specified start commit.
150
- * Workers operate in their worktree without affecting main branch.
151
- */
152
- export const swarm_worktree_create = tool({
153
- description:
154
- "Create a git worktree for isolated task execution. Worker operates in worktree, not main branch.",
155
- args: {
156
- project_path: z.string().describe("Absolute path to project root"),
157
- task_id: z.string().describe("Task/bead ID (e.g., bd-abc123.1)"),
158
- start_commit: z
159
- .string()
160
- .describe("Commit SHA to create worktree at (swarm start point)"),
161
- },
162
- async execute(args): Promise<string> {
163
- // Validate git repo
164
- if (!(await isGitRepo(args.project_path))) {
165
- const result: WorktreeResult = {
166
- success: false,
167
- error: `${args.project_path} is not a git repository`,
168
- };
169
- return JSON.stringify(result, null, 2);
170
- }
171
-
172
- // Check if worktree already exists
173
- const worktreePath = getWorktreePath(args.project_path, args.task_id);
174
- const exists = existsSync(worktreePath);
175
- if (exists) {
176
- const result: WorktreeResult = {
177
- success: false,
178
- error: `Worktree already exists for task ${args.task_id}`,
179
- worktree_path: worktreePath,
180
- };
181
- return JSON.stringify(result, null, 2);
182
- }
183
-
184
- // Ensure worktree directory exists
185
- await ensureWorktreeDir(args.project_path);
186
-
187
- // Create worktree at start_commit with detached HEAD
188
- // Using detached HEAD avoids branch conflicts between workers
189
- const createResult =
190
- await Bun.$`git -C ${args.project_path} worktree add --detach ${worktreePath} ${args.start_commit}`
191
- .quiet()
192
- .nothrow();
193
-
194
- if (createResult.exitCode !== 0) {
195
- const result: WorktreeResult = {
196
- success: false,
197
- error: `Failed to create worktree: ${createResult.stderr.toString()}`,
198
- };
199
- return JSON.stringify(result, null, 2);
200
- }
201
-
202
- const result: WorktreeResult = {
203
- success: true,
204
- worktree_path: worktreePath,
205
- task_id: args.task_id,
206
- created_at_commit: args.start_commit,
207
- };
208
- return JSON.stringify(result, null, 2);
209
- },
210
- });
211
-
212
- /**
213
- * Merge (cherry-pick) commits from worktree back to main
214
- *
215
- * After worker completes, cherry-pick their commits to main branch.
216
- * This integrates the isolated work back into the shared codebase.
217
- */
218
- export const swarm_worktree_merge = tool({
219
- description:
220
- "Cherry-pick commits from worktree back to main branch. Call after worker completes.",
221
- args: {
222
- project_path: z.string().describe("Absolute path to project root"),
223
- task_id: z.string().describe("Task/bead ID"),
224
- start_commit: z
225
- .string()
226
- .optional()
227
- .describe("Original start commit (to find new commits)"),
228
- },
229
- async execute(args): Promise<string> {
230
- const worktreePath = getWorktreePath(args.project_path, args.task_id);
231
-
232
- // Check worktree exists
233
- const exists = existsSync(worktreePath);
234
- if (!exists) {
235
- const result: WorktreeResult = {
236
- success: false,
237
- error: `Worktree not found for task ${args.task_id}`,
238
- };
239
- return JSON.stringify(result, null, 2);
240
- }
241
-
242
- // Get start commit if not provided (from worktree's initial commit)
243
- let startCommit = args.start_commit;
244
- if (!startCommit) {
245
- // Try to get from worktree metadata or use merge-base
246
- const mergeBaseResult =
247
- await Bun.$`git -C ${args.project_path} merge-base HEAD ${worktreePath}`
248
- .quiet()
249
- .nothrow();
250
- if (mergeBaseResult.exitCode === 0) {
251
- startCommit = mergeBaseResult.stdout.toString().trim();
252
- }
253
- }
254
-
255
- if (!startCommit) {
256
- const result: WorktreeResult = {
257
- success: false,
258
- error: "Could not determine start commit for cherry-pick",
259
- };
260
- return JSON.stringify(result, null, 2);
261
- }
262
-
263
- // Get commits in worktree since start
264
- const commits = await getWorktreeCommits(worktreePath, startCommit);
265
-
266
- if (commits.length === 0) {
267
- const result: WorktreeResult = {
268
- success: false,
269
- error: `Worktree has no commits since ${startCommit.slice(0, 7)}`,
270
- };
271
- return JSON.stringify(result, null, 2);
272
- }
273
-
274
- // Cherry-pick commits in order (oldest first)
275
- const reversedCommits = commits.reverse();
276
- let lastMergedCommit: string | null = null;
277
-
278
- for (const commit of reversedCommits) {
279
- const cherryResult =
280
- await Bun.$`git -C ${args.project_path} cherry-pick ${commit}`
281
- .quiet()
282
- .nothrow();
283
-
284
- if (cherryResult.exitCode !== 0) {
285
- // Check if it's a conflict
286
- const stderr = cherryResult.stderr.toString();
287
- if (stderr.includes("conflict") || stderr.includes("CONFLICT")) {
288
- // Get conflicting files
289
- const statusResult =
290
- await Bun.$`git -C ${args.project_path} status --porcelain`
291
- .quiet()
292
- .nothrow();
293
- const conflictingFiles = statusResult.stdout
294
- .toString()
295
- .split("\n")
296
- .filter((line: string) => line.startsWith("UU") || line.startsWith("AA"))
297
- .map((line: string) => line.slice(3).trim());
298
-
299
- // Abort the cherry-pick
300
- await Bun.$`git -C ${args.project_path} cherry-pick --abort`
301
- .quiet()
302
- .nothrow();
303
-
304
- const result: WorktreeResult = {
305
- success: false,
306
- error: `Merge conflict during cherry-pick of ${commit.slice(0, 7)}`,
307
- conflicting_files: conflictingFiles,
308
- };
309
- return JSON.stringify(result, null, 2);
310
- }
311
-
312
- const result: WorktreeResult = {
313
- success: false,
314
- error: `Failed to cherry-pick ${commit.slice(0, 7)}: ${stderr}`,
315
- };
316
- return JSON.stringify(result, null, 2);
317
- }
318
-
319
- lastMergedCommit = commit;
320
- }
321
-
322
- const result: WorktreeResult = {
323
- success: true,
324
- task_id: args.task_id,
325
- merged_commit: lastMergedCommit || undefined,
326
- };
327
- return JSON.stringify(result, null, 2);
328
- },
329
- });
330
-
331
- /**
332
- * Clean up a worktree
333
- *
334
- * Removes the worktree directory and git tracking.
335
- * Call after merge or on abort.
336
- */
337
- export const swarm_worktree_cleanup = tool({
338
- description:
339
- "Remove a worktree after completion or abort. Idempotent - safe to call multiple times.",
340
- args: {
341
- project_path: z.string().describe("Absolute path to project root"),
342
- task_id: z.string().optional().describe("Task/bead ID to clean up"),
343
- cleanup_all: z
344
- .boolean()
345
- .optional()
346
- .describe("Remove all worktrees for this project"),
347
- },
348
- async execute(args): Promise<string> {
349
- if (args.cleanup_all) {
350
- // List and remove all worktrees
351
- const listResult =
352
- await Bun.$`git -C ${args.project_path} worktree list --porcelain`
353
- .quiet()
354
- .nothrow();
355
-
356
- if (listResult.exitCode !== 0) {
357
- const result: WorktreeResult = {
358
- success: false,
359
- error: `Failed to list worktrees: ${listResult.stderr.toString()}`,
360
- };
361
- return JSON.stringify(result, null, 2);
362
- }
363
-
364
- // Parse worktree list
365
- const output = listResult.stdout.toString();
366
- const worktreeDir = join(args.project_path, WORKTREE_DIR);
367
- const worktrees = output
368
- .split("\n\n")
369
- .filter((block: string) => block.includes(worktreeDir))
370
- .map((block: string) => {
371
- const pathMatch = block.match(/^worktree (.+)$/m);
372
- return pathMatch ? pathMatch[1] : null;
373
- })
374
- .filter((p: string | null): p is string => p !== null);
375
-
376
- let removedCount = 0;
377
- for (const wt of worktrees) {
378
- const removeResult =
379
- await Bun.$`git -C ${args.project_path} worktree remove --force ${wt}`
380
- .quiet()
381
- .nothrow();
382
- if (removeResult.exitCode === 0) {
383
- removedCount++;
384
- }
385
- }
386
-
387
- const result: WorktreeResult = {
388
- success: true,
389
- removed_count: removedCount,
390
- };
391
- return JSON.stringify(result, null, 2);
392
- }
393
-
394
- if (!args.task_id) {
395
- const result: WorktreeResult = {
396
- success: false,
397
- error: "Either task_id or cleanup_all must be provided",
398
- };
399
- return JSON.stringify(result, null, 2);
400
- }
401
-
402
- const worktreePath = getWorktreePath(args.project_path, args.task_id);
403
-
404
- // Check if worktree exists (use existsSync for directories)
405
- const exists = existsSync(worktreePath);
406
- if (!exists) {
407
- // Idempotent - already removed
408
- const result: WorktreeResult = {
409
- success: true,
410
- already_removed: true,
411
- removed_path: worktreePath,
412
- };
413
- return JSON.stringify(result, null, 2);
414
- }
415
-
416
- // Remove worktree
417
- const removeResult =
418
- await Bun.$`git -C ${args.project_path} worktree remove --force ${worktreePath}`
419
- .quiet()
420
- .nothrow();
421
-
422
- if (removeResult.exitCode !== 0) {
423
- // Try manual cleanup if git worktree remove fails
424
- await Bun.$`rm -rf ${worktreePath}`.quiet().nothrow();
425
- await Bun.$`git -C ${args.project_path} worktree prune`
426
- .quiet()
427
- .nothrow();
428
- }
429
-
430
- const result: WorktreeResult = {
431
- success: true,
432
- removed_path: worktreePath,
433
- task_id: args.task_id,
434
- };
435
- return JSON.stringify(result, null, 2);
436
- },
437
- });
438
-
439
- /**
440
- * List all worktrees for a project
441
- *
442
- * Returns info about active worktrees including task IDs and paths.
443
- */
444
- export const swarm_worktree_list = tool({
445
- description: "List all active worktrees for a project",
446
- args: {
447
- project_path: z.string().describe("Absolute path to project root"),
448
- },
449
- async execute(args): Promise<string> {
450
- const listResult =
451
- await Bun.$`git -C ${args.project_path} worktree list --porcelain`
452
- .quiet()
453
- .nothrow();
454
-
455
- if (listResult.exitCode !== 0) {
456
- return JSON.stringify(
457
- {
458
- worktrees: [],
459
- count: 0,
460
- error: `Failed to list worktrees: ${listResult.stderr.toString()}`,
461
- },
462
- null,
463
- 2,
464
- );
465
- }
466
-
467
- // Parse worktree list
468
- const output = listResult.stdout.toString();
469
- const worktreeDir = join(args.project_path, WORKTREE_DIR);
470
-
471
- const worktrees: WorktreeInfo[] = [];
472
-
473
- // Split by double newline (each worktree block)
474
- const blocks = output.split("\n\n").filter((b: string) => b.trim());
475
-
476
- for (const block of blocks) {
477
- const pathMatch = block.match(/^worktree (.+)$/m);
478
- const commitMatch = block.match(/^HEAD ([a-f0-9]+)$/m);
479
- const branchMatch = block.match(/^branch (.+)$/m);
480
-
481
- if (pathMatch && pathMatch[1].includes(worktreeDir)) {
482
- const path = pathMatch[1];
483
- const taskId = parseTaskIdFromPath(path);
484
-
485
- if (taskId) {
486
- worktrees.push({
487
- task_id: taskId,
488
- path,
489
- commit: commitMatch ? commitMatch[1] : "unknown",
490
- branch: branchMatch ? branchMatch[1] : undefined,
491
- });
492
- }
493
- }
494
- }
495
-
496
- return JSON.stringify(
497
- {
498
- worktrees,
499
- count: worktrees.length,
500
- },
501
- null,
502
- 2,
503
- );
504
- },
505
- });
506
-
507
- // ============================================================================
508
- // Isolation Mode Helpers
509
- // ============================================================================
510
-
511
- /**
512
- * Check if worktree isolation can be used
513
- *
514
- * Worktree mode requires:
515
- * - Clean working directory (no uncommitted changes)
516
- * - Valid git repository
517
- */
518
- export async function canUseWorktreeIsolation(
519
- projectPath: string,
520
- ): Promise<{ canUse: boolean; reason?: string }> {
521
- if (!(await isGitRepo(projectPath))) {
522
- return { canUse: false, reason: "Not a git repository" };
523
- }
524
-
525
- if (await hasUncommittedChanges(projectPath)) {
526
- return {
527
- canUse: false,
528
- reason: "Uncommitted changes exist - commit or stash first",
529
- };
530
- }
531
-
532
- return { canUse: true };
533
- }
534
-
535
- /**
536
- * Get the current commit for worktree start point
537
- */
538
- export async function getStartCommit(
539
- projectPath: string,
540
- ): Promise<string | null> {
541
- return getCurrentCommit(projectPath);
542
- }
543
-
544
- /**
545
- * Hard reset main branch to start commit (for abort)
546
- */
547
- export async function resetToStartCommit(
548
- projectPath: string,
549
- startCommit: string,
550
- ): Promise<{ success: boolean; error?: string }> {
551
- const result =
552
- await Bun.$`git -C ${projectPath} reset --hard ${startCommit}`
553
- .quiet()
554
- .nothrow();
555
-
556
- if (result.exitCode !== 0) {
557
- return {
558
- success: false,
559
- error: `Failed to reset: ${result.stderr.toString()}`,
560
- };
561
- }
562
-
563
- return { success: true };
564
- }
565
-
566
- // ============================================================================
567
- // Exports
568
- // ============================================================================
569
-
570
- export const worktreeTools = {
571
- swarm_worktree_create,
572
- swarm_worktree_merge,
573
- swarm_worktree_cleanup,
574
- swarm_worktree_list,
575
- };