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,2515 +0,0 @@
1
- /**
2
- * OpenCode Swarm Plugin Wrapper
3
- *
4
- * This is a thin wrapper that shells out to the `swarm` CLI for all tool execution.
5
- * Generated by: swarm setup
6
- *
7
- * The plugin only depends on @opencode-ai/plugin (provided by OpenCode).
8
- * All tool logic lives in the npm package - this just bridges to it.
9
- *
10
- * Environment variables:
11
- * - OPENCODE_SESSION_ID: Passed to CLI for session state persistence
12
- * - OPENCODE_MESSAGE_ID: Passed to CLI for context
13
- * - OPENCODE_AGENT: Passed to CLI for context
14
- * - SWARM_PROJECT_DIR: Project directory (critical for database path)
15
- */
16
- import type { Plugin, PluginInput, Hooks } from "@opencode-ai/plugin";
17
- import type { ToolPart } from "@opencode-ai/sdk";
18
- import { tool } from "@opencode-ai/plugin";
19
- import { spawn } from "child_process";
20
- import { appendFileSync, mkdirSync, existsSync } from "node:fs";
21
- import { join } from "node:path";
22
- import { homedir } from "node:os";
23
-
24
- const SWARM_CLI = "swarm";
25
-
26
- // =============================================================================
27
- // File-based Logging (writes to ~/.config/swarm-tools/logs/)
28
- // =============================================================================
29
-
30
- const LOG_DIR = join(homedir(), ".config", "swarm-tools", "logs");
31
- const COMPACTION_LOG = join(LOG_DIR, "compaction.log");
32
-
33
- /**
34
- * Ensure log directory exists
35
- */
36
- function ensureLogDir(): void {
37
- if (!existsSync(LOG_DIR)) {
38
- mkdirSync(LOG_DIR, { recursive: true });
39
- }
40
- }
41
-
42
- /**
43
- * Log a compaction event to file (JSON lines format, compatible with `swarm log`)
44
- *
45
- * @param level - Log level (info, debug, warn, error)
46
- * @param msg - Log message
47
- * @param data - Additional structured data
48
- */
49
- function logCompaction(
50
- level: "info" | "debug" | "warn" | "error",
51
- msg: string,
52
- data?: Record<string, unknown>,
53
- ): void {
54
- try {
55
- ensureLogDir();
56
- const entry = JSON.stringify({
57
- time: new Date().toISOString(),
58
- level,
59
- msg,
60
- ...data,
61
- });
62
- appendFileSync(COMPACTION_LOG, entry + "\n");
63
- } catch {
64
- // Silently fail - logging should never break the plugin
65
- }
66
- }
67
-
68
- /**
69
- * Capture compaction event for evals (non-fatal dynamic import)
70
- *
71
- * Uses dynamic import to avoid circular dependencies and keep the plugin wrapper
72
- * self-contained. Captures COMPACTION events to session JSONL for eval analysis.
73
- *
74
- * @param sessionID - Session ID
75
- * @param epicID - Epic ID (or "unknown" if not detected)
76
- * @param compactionType - Event type (detection_complete, prompt_generated, context_injected)
77
- * @param payload - Event-specific data (full prompts, detection results, etc.)
78
- */
79
- async function captureCompaction(
80
- sessionID: string,
81
- epicID: string,
82
- compactionType: "detection_complete" | "prompt_generated" | "context_injected",
83
- payload: any,
84
- ): Promise<void> {
85
- try {
86
- // Dynamic import to avoid circular deps (plugin wrapper → src → plugin wrapper)
87
- const { captureCompactionEvent } = await import("../src/eval-capture");
88
- captureCompactionEvent({
89
- session_id: sessionID,
90
- epic_id: epicID,
91
- compaction_type: compactionType,
92
- payload,
93
- });
94
- } catch (err) {
95
- // Non-fatal - capture failures shouldn't break compaction
96
- logCompaction("warn", "compaction_capture_failed", {
97
- session_id: sessionID,
98
- compaction_type: compactionType,
99
- error: err instanceof Error ? err.message : String(err),
100
- });
101
- }
102
- }
103
-
104
- // Module-level project directory - set during plugin initialization
105
- // This is CRITICAL: without it, the CLI uses process.cwd() which may be wrong
106
- let projectDirectory: string = process.cwd();
107
-
108
- // Module-level SDK client - set during plugin initialization
109
- // Used for scanning session messages during compaction
110
- let sdkClient: any = null;
111
-
112
- // =============================================================================
113
- // CLI Execution Helper
114
- // =============================================================================
115
-
116
- /**
117
- * Execute a swarm tool via CLI
118
- *
119
- * Spawns `swarm tool <name> --json '<args>'` and returns the result.
120
- * Passes session context via environment variables.
121
- *
122
- * IMPORTANT: Runs in projectDirectory (set by OpenCode) not process.cwd()
123
- */
124
- async function execTool(
125
- name: string,
126
- args: Record<string, unknown>,
127
- ctx: { sessionID: string; messageID: string; agent: string },
128
- ): Promise<string> {
129
- return new Promise((resolve, reject) => {
130
- const hasArgs = Object.keys(args).length > 0;
131
- const cliArgs = hasArgs
132
- ? ["tool", name, "--json", JSON.stringify(args)]
133
- : ["tool", name];
134
-
135
- const proc = spawn(SWARM_CLI, cliArgs, {
136
- cwd: projectDirectory, // Run in project directory, not plugin directory
137
- stdio: ["ignore", "pipe", "pipe"],
138
- env: {
139
- ...process.env,
140
- OPENCODE_SESSION_ID: ctx.sessionID,
141
- OPENCODE_MESSAGE_ID: ctx.messageID,
142
- OPENCODE_AGENT: ctx.agent,
143
- SWARM_PROJECT_DIR: projectDirectory, // Also pass as env var
144
- },
145
- });
146
-
147
- let stdout = "";
148
- let stderr = "";
149
-
150
- proc.stdout.on("data", (data) => {
151
- stdout += data;
152
- });
153
- proc.stderr.on("data", (data) => {
154
- stderr += data;
155
- });
156
-
157
- proc.on("close", (code) => {
158
- if (code === 0) {
159
- // Success - return the JSON output
160
- try {
161
- const result = JSON.parse(stdout);
162
- if (result.success && result.data !== undefined) {
163
- // Unwrap the data for cleaner tool output
164
- resolve(
165
- typeof result.data === "string"
166
- ? result.data
167
- : JSON.stringify(result.data, null, 2),
168
- );
169
- } else if (!result.success && result.error) {
170
- // Tool returned an error in JSON format
171
- // Handle both string errors and object errors with .message
172
- const errorMsg = typeof result.error === "string"
173
- ? result.error
174
- : (result.error.message || "Tool execution failed");
175
- reject(new Error(errorMsg));
176
- } else {
177
- resolve(stdout);
178
- }
179
- } catch {
180
- resolve(stdout);
181
- }
182
- } else if (code === 2) {
183
- reject(new Error(`Unknown tool: ${name}`));
184
- } else if (code === 3) {
185
- reject(new Error(`Invalid JSON args: ${stderr}`));
186
- } else {
187
- // Tool returned error
188
- try {
189
- const result = JSON.parse(stdout);
190
- if (!result.success && result.error) {
191
- // Handle both string errors and object errors with .message
192
- const errorMsg = typeof result.error === "string"
193
- ? result.error
194
- : (result.error.message || `Tool failed with code ${code}`);
195
- reject(new Error(errorMsg));
196
- } else {
197
- reject(
198
- new Error(stderr || stdout || `Tool failed with code ${code}`),
199
- );
200
- }
201
- } catch {
202
- reject(
203
- new Error(stderr || stdout || `Tool failed with code ${code}`),
204
- );
205
- }
206
- }
207
- });
208
-
209
- proc.on("error", (err) => {
210
- if ((err as NodeJS.ErrnoException).code === "ENOENT") {
211
- reject(
212
- new Error(
213
- `swarm CLI not found. Install with: npm install -g opencode-swarm-plugin`,
214
- ),
215
- );
216
- } else {
217
- reject(err);
218
- }
219
- });
220
- });
221
- }
222
-
223
- // =============================================================================
224
- // Beads Tools
225
- // =============================================================================
226
-
227
- const hive_create = tool({
228
- description: "Create a new bead with type-safe validation",
229
- args: {
230
- title: tool.schema.string().describe("Bead title"),
231
- type: tool.schema
232
- .enum(["bug", "feature", "task", "epic", "chore"])
233
- .optional()
234
- .describe("Issue type (default: task)"),
235
- priority: tool.schema
236
- .number()
237
- .min(0)
238
- .max(3)
239
- .optional()
240
- .describe("Priority 0-3 (default: 2)"),
241
- description: tool.schema.string().optional().describe("Bead description"),
242
- parent_id: tool.schema
243
- .string()
244
- .optional()
245
- .describe("Parent bead ID for epic children"),
246
- },
247
- execute: (args, ctx) => execTool("hive_create", args, ctx),
248
- });
249
-
250
- const hive_create_epic = tool({
251
- description: "Create epic with subtasks in one atomic operation",
252
- args: {
253
- epic_title: tool.schema.string().describe("Epic title"),
254
- epic_description: tool.schema
255
- .string()
256
- .optional()
257
- .describe("Epic description"),
258
- subtasks: tool.schema
259
- .array(
260
- tool.schema.object({
261
- title: tool.schema.string(),
262
- priority: tool.schema.number().min(0).max(3).optional(),
263
- files: tool.schema.array(tool.schema.string()).optional(),
264
- }),
265
- )
266
- .describe("Subtasks to create under the epic"),
267
- },
268
- execute: (args, ctx) => execTool("hive_create_epic", args, ctx),
269
- });
270
-
271
- const hive_query = tool({
272
- description: "Query beads with filters (replaces bd list, bd ready, bd wip)",
273
- args: {
274
- status: tool.schema
275
- .enum(["open", "in_progress", "blocked", "closed"])
276
- .optional()
277
- .describe("Filter by status"),
278
- type: tool.schema
279
- .enum(["bug", "feature", "task", "epic", "chore"])
280
- .optional()
281
- .describe("Filter by type"),
282
- ready: tool.schema
283
- .boolean()
284
- .optional()
285
- .describe("Only show unblocked beads"),
286
- limit: tool.schema
287
- .number()
288
- .optional()
289
- .describe("Max results (default: 20)"),
290
- },
291
- execute: (args, ctx) => execTool("hive_query", args, ctx),
292
- });
293
-
294
- const hive_update = tool({
295
- description: "Update bead status/description",
296
- args: {
297
- id: tool.schema.string().describe("Cell ID"),
298
- status: tool.schema
299
- .enum(["open", "in_progress", "blocked", "closed"])
300
- .optional()
301
- .describe("New status"),
302
- description: tool.schema.string().optional().describe("New description"),
303
- priority: tool.schema
304
- .number()
305
- .min(0)
306
- .max(3)
307
- .optional()
308
- .describe("New priority"),
309
- },
310
- execute: (args, ctx) => execTool("hive_update", args, ctx),
311
- });
312
-
313
- const hive_close = tool({
314
- description: "Close a bead with reason",
315
- args: {
316
- id: tool.schema.string().describe("Cell ID"),
317
- reason: tool.schema.string().describe("Completion reason"),
318
- },
319
- execute: (args, ctx) => execTool("hive_close", args, ctx),
320
- });
321
-
322
- const hive_start = tool({
323
- description: "Mark a bead as in-progress",
324
- args: {
325
- id: tool.schema.string().describe("Cell ID"),
326
- },
327
- execute: (args, ctx) => execTool("hive_start", args, ctx),
328
- });
329
-
330
- const hive_ready = tool({
331
- description: "Get the next ready bead (unblocked, highest priority)",
332
- args: {},
333
- execute: (args, ctx) => execTool("hive_ready", args, ctx),
334
- });
335
-
336
- const hive_sync = tool({
337
- description: "Sync beads to git and push (MANDATORY at session end)",
338
- args: {
339
- auto_pull: tool.schema.boolean().optional().describe("Pull before sync"),
340
- },
341
- execute: (args, ctx) => execTool("hive_sync", args, ctx),
342
- });
343
-
344
- const hive_cells = tool({
345
- description: `Query cells from the hive database with flexible filtering.
346
-
347
- USE THIS TOOL TO:
348
- - List all open cells: hive_cells()
349
- - Find cells by status: hive_cells({ status: "in_progress" })
350
- - Find cells by type: hive_cells({ type: "bug" })
351
- - Get a specific cell by partial ID: hive_cells({ id: "mjkmd" })
352
- - Get the next ready (unblocked) cell: hive_cells({ ready: true })
353
- - Combine filters: hive_cells({ status: "open", type: "task" })
354
-
355
- RETURNS: Array of cells with id, title, status, priority, type, parent_id, created_at, updated_at
356
-
357
- PREFER THIS OVER hive_query when you need to:
358
- - See what work is available
359
- - Check status of multiple cells
360
- - Find cells matching criteria
361
- - Look up a cell by partial ID`,
362
- args: {
363
- id: tool.schema.string().optional().describe("Partial or full cell ID to look up"),
364
- status: tool.schema.enum(["open", "in_progress", "blocked", "closed"]).optional().describe("Filter by status"),
365
- type: tool.schema.enum(["task", "bug", "feature", "epic", "chore"]).optional().describe("Filter by type"),
366
- ready: tool.schema.boolean().optional().describe("If true, return only the next unblocked cell"),
367
- limit: tool.schema.number().optional().describe("Max cells to return (default 20)"),
368
- },
369
- execute: (args, ctx) => execTool("hive_cells", args, ctx),
370
- });
371
-
372
- const beads_link_thread = tool({
373
- description: "Add metadata linking bead to Agent Mail thread",
374
- args: {
375
- bead_id: tool.schema.string().describe("Cell ID"),
376
- thread_id: tool.schema.string().describe("Agent Mail thread ID"),
377
- },
378
- execute: (args, ctx) => execTool("beads_link_thread", args, ctx),
379
- });
380
-
381
- // =============================================================================
382
- // Swarm Mail Tools (Embedded)
383
- // =============================================================================
384
-
385
- const swarmmail_init = tool({
386
- description: "Initialize Swarm Mail session (REQUIRED FIRST)",
387
- args: {
388
- project_path: tool.schema.string().describe("Absolute path to the project"),
389
- agent_name: tool.schema.string().optional().describe("Custom agent name"),
390
- task_description: tool.schema
391
- .string()
392
- .optional()
393
- .describe("Task description"),
394
- },
395
- execute: (args, ctx) => execTool("swarmmail_init", args, ctx),
396
- });
397
-
398
- const swarmmail_send = tool({
399
- description: "Send message to other agents via Swarm Mail",
400
- args: {
401
- to: tool.schema
402
- .array(tool.schema.string())
403
- .describe("Recipient agent names"),
404
- subject: tool.schema.string().describe("Message subject"),
405
- body: tool.schema.string().describe("Message body"),
406
- thread_id: tool.schema
407
- .string()
408
- .optional()
409
- .describe("Thread ID for grouping"),
410
- importance: tool.schema
411
- .enum(["low", "normal", "high", "urgent"])
412
- .optional()
413
- .describe("Message importance"),
414
- ack_required: tool.schema
415
- .boolean()
416
- .optional()
417
- .describe("Require acknowledgment"),
418
- },
419
- execute: (args, ctx) => execTool("swarmmail_send", args, ctx),
420
- });
421
-
422
- const swarmmail_inbox = tool({
423
- description: "Fetch inbox (CONTEXT-SAFE: bodies excluded, max 5 messages)",
424
- args: {
425
- limit: tool.schema
426
- .number()
427
- .max(5)
428
- .optional()
429
- .describe("Max messages (max 5)"),
430
- urgent_only: tool.schema
431
- .boolean()
432
- .optional()
433
- .describe("Only urgent messages"),
434
- },
435
- execute: (args, ctx) => execTool("swarmmail_inbox", args, ctx),
436
- });
437
-
438
- const swarmmail_read_message = tool({
439
- description: "Fetch ONE message body by ID",
440
- args: {
441
- message_id: tool.schema.number().describe("Message ID"),
442
- },
443
- execute: (args, ctx) => execTool("swarmmail_read_message", args, ctx),
444
- });
445
-
446
- const swarmmail_reserve = tool({
447
- description: "Reserve file paths for exclusive editing",
448
- args: {
449
- paths: tool.schema
450
- .array(tool.schema.string())
451
- .describe("File paths/patterns"),
452
- ttl_seconds: tool.schema.number().optional().describe("Reservation TTL"),
453
- exclusive: tool.schema.boolean().optional().describe("Exclusive lock"),
454
- reason: tool.schema.string().optional().describe("Reservation reason"),
455
- },
456
- execute: (args, ctx) => execTool("swarmmail_reserve", args, ctx),
457
- });
458
-
459
- const swarmmail_release = tool({
460
- description: "Release file reservations",
461
- args: {
462
- paths: tool.schema
463
- .array(tool.schema.string())
464
- .optional()
465
- .describe("Paths to release"),
466
- reservation_ids: tool.schema
467
- .array(tool.schema.number())
468
- .optional()
469
- .describe("Reservation IDs"),
470
- },
471
- execute: (args, ctx) => execTool("swarmmail_release", args, ctx),
472
- });
473
-
474
- const swarmmail_ack = tool({
475
- description: "Acknowledge a message",
476
- args: {
477
- message_id: tool.schema.number().describe("Message ID"),
478
- },
479
- execute: (args, ctx) => execTool("swarmmail_ack", args, ctx),
480
- });
481
-
482
- const swarmmail_health = tool({
483
- description: "Check Swarm Mail database health",
484
- args: {},
485
- execute: (args, ctx) => execTool("swarmmail_health", args, ctx),
486
- });
487
-
488
- // =============================================================================
489
- // Structured Tools
490
- // =============================================================================
491
-
492
- const structured_extract_json = tool({
493
- description: "Extract JSON from markdown/text response",
494
- args: {
495
- text: tool.schema.string().describe("Text containing JSON"),
496
- },
497
- execute: (args, ctx) => execTool("structured_extract_json", args, ctx),
498
- });
499
-
500
- const structured_validate = tool({
501
- description: "Validate agent response against a schema",
502
- args: {
503
- response: tool.schema.string().describe("Agent response to validate"),
504
- schema_name: tool.schema
505
- .enum(["evaluation", "task_decomposition", "cell_tree"])
506
- .describe("Schema to validate against"),
507
- max_retries: tool.schema
508
- .number()
509
- .min(1)
510
- .max(5)
511
- .optional()
512
- .describe("Max retries"),
513
- },
514
- execute: (args, ctx) => execTool("structured_validate", args, ctx),
515
- });
516
-
517
- const structured_parse_evaluation = tool({
518
- description: "Parse and validate evaluation response",
519
- args: {
520
- response: tool.schema.string().describe("Agent response"),
521
- },
522
- execute: (args, ctx) => execTool("structured_parse_evaluation", args, ctx),
523
- });
524
-
525
- const structured_parse_decomposition = tool({
526
- description: "Parse and validate task decomposition response",
527
- args: {
528
- response: tool.schema.string().describe("Agent response"),
529
- },
530
- execute: (args, ctx) => execTool("structured_parse_decomposition", args, ctx),
531
- });
532
-
533
- const structured_parse_cell_tree = tool({
534
- description: "Parse and validate bead tree response",
535
- args: {
536
- response: tool.schema.string().describe("Agent response"),
537
- },
538
- execute: (args, ctx) => execTool("structured_parse_cell_tree", args, ctx),
539
- });
540
-
541
- // =============================================================================
542
- // Swarm Tools
543
- // =============================================================================
544
-
545
- const swarm_init = tool({
546
- description: "Initialize swarm session and check tool availability",
547
- args: {
548
- project_path: tool.schema.string().optional().describe("Project path"),
549
- isolation: tool.schema
550
- .enum(["worktree", "reservation"])
551
- .optional()
552
- .describe(
553
- "Isolation mode: 'worktree' for git worktree isolation, 'reservation' for file reservations (default)",
554
- ),
555
- },
556
- execute: (args, ctx) => execTool("swarm_init", args, ctx),
557
- });
558
-
559
- const swarm_select_strategy = tool({
560
- description: "Analyze task and recommend decomposition strategy",
561
- args: {
562
- task: tool.schema.string().min(1).describe("Task to analyze"),
563
- codebase_context: tool.schema
564
- .string()
565
- .optional()
566
- .describe("Codebase context"),
567
- },
568
- execute: (args, ctx) => execTool("swarm_select_strategy", args, ctx),
569
- });
570
-
571
- const swarm_plan_prompt = tool({
572
- description: "Generate strategy-specific decomposition prompt",
573
- args: {
574
- task: tool.schema.string().min(1).describe("Task to decompose"),
575
- strategy: tool.schema
576
- .enum(["file-based", "feature-based", "risk-based", "auto"])
577
- .optional()
578
- .describe("Decomposition strategy"),
579
- max_subtasks: tool.schema
580
- .number()
581
- .int()
582
- .min(2)
583
- .max(10)
584
- .optional()
585
- .describe("Max subtasks"),
586
- context: tool.schema.string().optional().describe("Additional context"),
587
- query_cass: tool.schema
588
- .boolean()
589
- .optional()
590
- .describe("Query CASS for similar tasks"),
591
- cass_limit: tool.schema
592
- .number()
593
- .int()
594
- .min(1)
595
- .max(10)
596
- .optional()
597
- .describe("CASS limit"),
598
- },
599
- execute: (args, ctx) => execTool("swarm_plan_prompt", args, ctx),
600
- });
601
-
602
- const swarm_decompose = tool({
603
- description: "Generate decomposition prompt for breaking task into subtasks",
604
- args: {
605
- task: tool.schema.string().min(1).describe("Task to decompose"),
606
- max_subtasks: tool.schema
607
- .number()
608
- .int()
609
- .min(2)
610
- .max(10)
611
- .optional()
612
- .describe("Max subtasks"),
613
- context: tool.schema.string().optional().describe("Additional context"),
614
- query_cass: tool.schema.boolean().optional().describe("Query CASS"),
615
- cass_limit: tool.schema
616
- .number()
617
- .int()
618
- .min(1)
619
- .max(10)
620
- .optional()
621
- .describe("CASS limit"),
622
- },
623
- execute: (args, ctx) => execTool("swarm_decompose", args, ctx),
624
- });
625
-
626
- const swarm_validate_decomposition = tool({
627
- description: "Validate a decomposition response against CellTreeSchema",
628
- args: {
629
- response: tool.schema.string().describe("Decomposition response"),
630
- },
631
- execute: (args, ctx) => execTool("swarm_validate_decomposition", args, ctx),
632
- });
633
-
634
- const swarm_status = tool({
635
- description: "Get status of a swarm by epic ID",
636
- args: {
637
- epic_id: tool.schema.string().describe("Epic bead ID"),
638
- project_key: tool.schema.string().describe("Project key"),
639
- },
640
- execute: (args, ctx) => execTool("swarm_status", args, ctx),
641
- });
642
-
643
- const swarm_progress = tool({
644
- description: "Report progress on a subtask to coordinator",
645
- args: {
646
- project_key: tool.schema.string().describe("Project key"),
647
- agent_name: tool.schema.string().describe("Agent name"),
648
- bead_id: tool.schema.string().describe("Cell ID"),
649
- status: tool.schema
650
- .enum(["in_progress", "blocked", "completed", "failed"])
651
- .describe("Status"),
652
- message: tool.schema.string().optional().describe("Progress message"),
653
- progress_percent: tool.schema
654
- .number()
655
- .min(0)
656
- .max(100)
657
- .optional()
658
- .describe("Progress %"),
659
- files_touched: tool.schema
660
- .array(tool.schema.string())
661
- .optional()
662
- .describe("Files modified"),
663
- },
664
- execute: (args, ctx) => execTool("swarm_progress", args, ctx),
665
- });
666
-
667
- const swarm_complete = tool({
668
- description:
669
- "Mark subtask complete with Verification Gate. Runs UBS scan, typecheck, and tests before allowing completion.",
670
- args: {
671
- project_key: tool.schema.string().describe("Project key"),
672
- agent_name: tool.schema.string().describe("Agent name"),
673
- bead_id: tool.schema.string().describe("Cell ID"),
674
- summary: tool.schema.string().describe("Completion summary"),
675
- evaluation: tool.schema.string().optional().describe("Self-evaluation JSON"),
676
- files_touched: tool.schema
677
- .array(tool.schema.string())
678
- .optional()
679
- .describe("Files modified - will be verified"),
680
- skip_ubs_scan: tool.schema.boolean().optional().describe("Skip UBS scan"),
681
- skip_verification: tool.schema
682
- .boolean()
683
- .optional()
684
- .describe("Skip ALL verification (UBS, typecheck, tests)"),
685
- skip_review: tool.schema
686
- .boolean()
687
- .optional()
688
- .describe("Skip review gate check"),
689
- },
690
- execute: (args, ctx) => execTool("swarm_complete", args, ctx),
691
- });
692
-
693
- const swarm_record_outcome = tool({
694
- description: "Record subtask outcome for implicit feedback scoring",
695
- args: {
696
- bead_id: tool.schema.string().describe("Cell ID"),
697
- duration_ms: tool.schema.number().int().min(0).describe("Duration in ms"),
698
- error_count: tool.schema
699
- .number()
700
- .int()
701
- .min(0)
702
- .optional()
703
- .describe("Error count"),
704
- retry_count: tool.schema
705
- .number()
706
- .int()
707
- .min(0)
708
- .optional()
709
- .describe("Retry count"),
710
- success: tool.schema.boolean().describe("Whether task succeeded"),
711
- files_touched: tool.schema
712
- .array(tool.schema.string())
713
- .optional()
714
- .describe("Files modified"),
715
- criteria: tool.schema
716
- .array(tool.schema.string())
717
- .optional()
718
- .describe("Evaluation criteria"),
719
- strategy: tool.schema
720
- .enum(["file-based", "feature-based", "risk-based"])
721
- .optional()
722
- .describe("Strategy used"),
723
- },
724
- execute: (args, ctx) => execTool("swarm_record_outcome", args, ctx),
725
- });
726
-
727
- const swarm_subtask_prompt = tool({
728
- description: "Generate the prompt for a spawned subtask agent",
729
- args: {
730
- agent_name: tool.schema.string().describe("Agent name"),
731
- bead_id: tool.schema.string().describe("Cell ID"),
732
- epic_id: tool.schema.string().describe("Epic ID"),
733
- subtask_title: tool.schema.string().describe("Subtask title"),
734
- subtask_description: tool.schema
735
- .string()
736
- .optional()
737
- .describe("Description"),
738
- files: tool.schema.array(tool.schema.string()).describe("Files to work on"),
739
- shared_context: tool.schema.string().optional().describe("Shared context"),
740
- },
741
- execute: (args, ctx) => execTool("swarm_subtask_prompt", args, ctx),
742
- });
743
-
744
- const swarm_spawn_subtask = tool({
745
- description: "Prepare a subtask for spawning with Task tool",
746
- args: {
747
- bead_id: tool.schema.string().describe("Cell ID"),
748
- epic_id: tool.schema.string().describe("Epic ID"),
749
- subtask_title: tool.schema.string().describe("Subtask title"),
750
- subtask_description: tool.schema
751
- .string()
752
- .optional()
753
- .describe("Description"),
754
- files: tool.schema.array(tool.schema.string()).describe("Files to work on"),
755
- shared_context: tool.schema.string().optional().describe("Shared context"),
756
- },
757
- execute: (args, ctx) => execTool("swarm_spawn_subtask", args, ctx),
758
- });
759
-
760
- const swarm_complete_subtask = tool({
761
- description: "Handle subtask completion after Task agent returns",
762
- args: {
763
- bead_id: tool.schema.string().describe("Cell ID"),
764
- task_result: tool.schema.string().describe("Task result JSON"),
765
- files_touched: tool.schema
766
- .array(tool.schema.string())
767
- .optional()
768
- .describe("Files modified"),
769
- },
770
- execute: (args, ctx) => execTool("swarm_complete_subtask", args, ctx),
771
- });
772
-
773
- const swarm_evaluation_prompt = tool({
774
- description: "Generate self-evaluation prompt for a completed subtask",
775
- args: {
776
- bead_id: tool.schema.string().describe("Cell ID"),
777
- subtask_title: tool.schema.string().describe("Subtask title"),
778
- files_touched: tool.schema
779
- .array(tool.schema.string())
780
- .describe("Files modified"),
781
- },
782
- execute: (args, ctx) => execTool("swarm_evaluation_prompt", args, ctx),
783
- });
784
-
785
- const swarm_broadcast = tool({
786
- description:
787
- "Broadcast context update to all agents working on the same epic",
788
- args: {
789
- project_path: tool.schema.string().describe("Project path"),
790
- agent_name: tool.schema.string().describe("Agent name"),
791
- epic_id: tool.schema.string().describe("Epic ID"),
792
- message: tool.schema.string().describe("Context update message"),
793
- importance: tool.schema
794
- .enum(["info", "warning", "blocker"])
795
- .optional()
796
- .describe("Priority level (default: info)"),
797
- files_affected: tool.schema
798
- .array(tool.schema.string())
799
- .optional()
800
- .describe("Files this context relates to"),
801
- },
802
- execute: (args, ctx) => execTool("swarm_broadcast", args, ctx),
803
- });
804
-
805
- // =============================================================================
806
- // Worktree Isolation Tools
807
- // =============================================================================
808
-
809
- const swarm_worktree_create = tool({
810
- description:
811
- "Create a git worktree for isolated task execution. Worker operates in worktree, not main branch.",
812
- args: {
813
- project_path: tool.schema.string().describe("Absolute path to project root"),
814
- task_id: tool.schema.string().describe("Task/bead ID (e.g., bd-abc123.1)"),
815
- start_commit: tool.schema
816
- .string()
817
- .describe("Commit SHA to create worktree at (swarm start point)"),
818
- },
819
- execute: (args, ctx) => execTool("swarm_worktree_create", args, ctx),
820
- });
821
-
822
- const swarm_worktree_merge = tool({
823
- description:
824
- "Cherry-pick commits from worktree back to main branch. Call after worker completes.",
825
- args: {
826
- project_path: tool.schema.string().describe("Absolute path to project root"),
827
- task_id: tool.schema.string().describe("Task/bead ID"),
828
- start_commit: tool.schema
829
- .string()
830
- .optional()
831
- .describe("Original start commit (to find new commits)"),
832
- },
833
- execute: (args, ctx) => execTool("swarm_worktree_merge", args, ctx),
834
- });
835
-
836
- const swarm_worktree_cleanup = tool({
837
- description:
838
- "Remove a worktree after completion or abort. Idempotent - safe to call multiple times.",
839
- args: {
840
- project_path: tool.schema.string().describe("Absolute path to project root"),
841
- task_id: tool.schema.string().optional().describe("Task/bead ID to clean up"),
842
- cleanup_all: tool.schema
843
- .boolean()
844
- .optional()
845
- .describe("Remove all worktrees for this project"),
846
- },
847
- execute: (args, ctx) => execTool("swarm_worktree_cleanup", args, ctx),
848
- });
849
-
850
- const swarm_worktree_list = tool({
851
- description: "List all active worktrees for a project",
852
- args: {
853
- project_path: tool.schema.string().describe("Absolute path to project root"),
854
- },
855
- execute: (args, ctx) => execTool("swarm_worktree_list", args, ctx),
856
- });
857
-
858
- // =============================================================================
859
- // Structured Review Tools
860
- // =============================================================================
861
-
862
- const swarm_review = tool({
863
- description:
864
- "Generate a review prompt for a completed subtask. Includes epic context, dependencies, and diff.",
865
- args: {
866
- project_key: tool.schema.string().describe("Project path"),
867
- epic_id: tool.schema.string().describe("Epic bead ID"),
868
- task_id: tool.schema.string().describe("Subtask bead ID to review"),
869
- files_touched: tool.schema
870
- .array(tool.schema.string())
871
- .optional()
872
- .describe("Files modified (will get diff for these)"),
873
- },
874
- execute: (args, ctx) => execTool("swarm_review", args, ctx),
875
- });
876
-
877
- const swarm_review_feedback = tool({
878
- description:
879
- "Send review feedback to a worker. Tracks attempts (max 3). Fails task after 3 rejections.",
880
- args: {
881
- project_key: tool.schema.string().describe("Project path"),
882
- task_id: tool.schema.string().describe("Subtask bead ID"),
883
- worker_id: tool.schema.string().describe("Worker agent name"),
884
- status: tool.schema
885
- .enum(["approved", "needs_changes"])
886
- .describe("Review status"),
887
- summary: tool.schema.string().optional().describe("Review summary"),
888
- issues: tool.schema
889
- .string()
890
- .optional()
891
- .describe("JSON array of ReviewIssue objects (for needs_changes)"),
892
- },
893
- execute: (args, ctx) => execTool("swarm_review_feedback", args, ctx),
894
- });
895
-
896
- // =============================================================================
897
- // Skills Tools
898
- // =============================================================================
899
-
900
- const skills_list = tool({
901
- description:
902
- "List all available skills from global, project, and bundled sources",
903
- args: {
904
- source: tool.schema
905
- .enum(["all", "global", "project", "bundled"])
906
- .optional()
907
- .describe("Filter by source (default: all)"),
908
- },
909
- execute: (args, ctx) => execTool("skills_list", args, ctx),
910
- });
911
-
912
- const skills_read = tool({
913
- description: "Read a skill's full content including SKILL.md and references",
914
- args: {
915
- name: tool.schema.string().describe("Skill name"),
916
- },
917
- execute: (args, ctx) => execTool("skills_read", args, ctx),
918
- });
919
-
920
- const skills_use = tool({
921
- description:
922
- "Get skill content formatted for injection into agent context. Use this when you need to apply a skill's knowledge to the current task.",
923
- args: {
924
- name: tool.schema.string().describe("Skill name"),
925
- context: tool.schema
926
- .string()
927
- .optional()
928
- .describe("Optional context about how the skill will be used"),
929
- },
930
- execute: (args, ctx) => execTool("skills_use", args, ctx),
931
- });
932
-
933
- const skills_create = tool({
934
- description: "Create a new skill with SKILL.md template",
935
- args: {
936
- name: tool.schema.string().describe("Skill name (kebab-case)"),
937
- description: tool.schema.string().describe("Brief skill description"),
938
- scope: tool.schema
939
- .enum(["global", "project"])
940
- .optional()
941
- .describe("Where to create (default: project)"),
942
- tags: tool.schema
943
- .array(tool.schema.string())
944
- .optional()
945
- .describe("Skill tags for discovery"),
946
- },
947
- execute: (args, ctx) => execTool("skills_create", args, ctx),
948
- });
949
-
950
- const skills_update = tool({
951
- description: "Update an existing skill's SKILL.md content",
952
- args: {
953
- name: tool.schema.string().describe("Skill name"),
954
- content: tool.schema.string().describe("New SKILL.md content"),
955
- },
956
- execute: (args, ctx) => execTool("skills_update", args, ctx),
957
- });
958
-
959
- const skills_delete = tool({
960
- description: "Delete a skill (project skills only)",
961
- args: {
962
- name: tool.schema.string().describe("Skill name"),
963
- },
964
- execute: (args, ctx) => execTool("skills_delete", args, ctx),
965
- });
966
-
967
- const skills_init = tool({
968
- description: "Initialize skills directory in current project",
969
- args: {
970
- path: tool.schema
971
- .string()
972
- .optional()
973
- .describe("Custom path (default: .opencode/skills)"),
974
- },
975
- execute: (args, ctx) => execTool("skills_init", args, ctx),
976
- });
977
-
978
- const skills_add_script = tool({
979
- description: "Add an executable script to a skill",
980
- args: {
981
- skill_name: tool.schema.string().describe("Skill name"),
982
- script_name: tool.schema.string().describe("Script filename"),
983
- content: tool.schema.string().describe("Script content"),
984
- executable: tool.schema
985
- .boolean()
986
- .optional()
987
- .describe("Make executable (default: true)"),
988
- },
989
- execute: (args, ctx) => execTool("skills_add_script", args, ctx),
990
- });
991
-
992
- const skills_execute = tool({
993
- description: "Execute a skill's script",
994
- args: {
995
- skill_name: tool.schema.string().describe("Skill name"),
996
- script_name: tool.schema.string().describe("Script to execute"),
997
- args: tool.schema
998
- .array(tool.schema.string())
999
- .optional()
1000
- .describe("Script arguments"),
1001
- },
1002
- execute: (args, ctx) => execTool("skills_execute", args, ctx),
1003
- });
1004
-
1005
- // =============================================================================
1006
- // Swarm Insights Tools
1007
- // =============================================================================
1008
-
1009
- const swarm_get_strategy_insights = tool({
1010
- description: "Get strategy success rates for decomposition planning. Use this when planning task decomposition to see which strategies (file-based, feature-based, risk-based) have historically succeeded or failed. Returns success rates and recommendations based on past swarm outcomes.",
1011
- args: {
1012
- task: tool.schema.string().describe("Task description to analyze for strategy recommendation"),
1013
- },
1014
- execute: (args, ctx) => execTool("swarm_get_strategy_insights", args, ctx),
1015
- });
1016
-
1017
- const swarm_get_file_insights = tool({
1018
- description: "Get file-specific gotchas for worker context. Use this when assigning files to workers to warn them about historical failure patterns. Queries past outcomes and semantic memory for file-specific learnings (edge cases, common bugs, performance traps).",
1019
- args: {
1020
- files: tool.schema.array(tool.schema.string()).describe("File paths to get insights for"),
1021
- },
1022
- execute: (args, ctx) => execTool("swarm_get_file_insights", args, ctx),
1023
- });
1024
-
1025
- const swarm_get_pattern_insights = tool({
1026
- description: "Get common failure patterns across swarms. Use this during planning or when debugging stuck swarms to see recurring anti-patterns (type errors, timeouts, conflicts, test failures). Returns top 5 most frequent failure patterns with recommendations.",
1027
- args: {},
1028
- execute: (args, ctx) => execTool("swarm_get_pattern_insights", args, ctx),
1029
- });
1030
-
1031
- // =============================================================================
1032
- // CASS Tools (Cross-Agent Session Search)
1033
- // =============================================================================
1034
-
1035
- const cass_search = tool({
1036
- description: "Search across all AI coding agent histories (Claude, Codex, Cursor, Gemini, Aider, ChatGPT, Cline, OpenCode, Amp, Pi-Agent). Query BEFORE solving problems from scratch - another agent may have already solved it. Returns matching sessions ranked by relevance.",
1037
- args: {
1038
- query: tool.schema.string().describe("Search query (e.g., 'authentication error Next.js')"),
1039
- agent: tool.schema
1040
- .string()
1041
- .optional()
1042
- .describe("Filter by agent name (e.g., 'claude', 'cursor')"),
1043
- days: tool.schema
1044
- .number()
1045
- .optional()
1046
- .describe("Only search sessions from last N days"),
1047
- limit: tool.schema
1048
- .number()
1049
- .optional()
1050
- .describe("Max results to return (default: 5)"),
1051
- fields: tool.schema
1052
- .string()
1053
- .optional()
1054
- .describe("Field selection: 'minimal' for compact output (path, line, agent only)"),
1055
- },
1056
- execute: (args, ctx) => execTool("cass_search", args, ctx),
1057
- });
1058
-
1059
- const cass_view = tool({
1060
- description: "View a specific conversation/session from search results. Use source_path from cass_search output.",
1061
- args: {
1062
- path: tool.schema
1063
- .string()
1064
- .describe("Path to session file (from cass_search results)"),
1065
- line: tool.schema
1066
- .number()
1067
- .optional()
1068
- .describe("Jump to specific line number"),
1069
- },
1070
- execute: (args, ctx) => execTool("cass_view", args, ctx),
1071
- });
1072
-
1073
- const cass_expand = tool({
1074
- description: "Expand context around a specific line in a session. Shows messages before/after.",
1075
- args: {
1076
- path: tool.schema
1077
- .string()
1078
- .describe("Path to session file"),
1079
- line: tool.schema
1080
- .number()
1081
- .describe("Line number to expand around"),
1082
- context: tool.schema
1083
- .number()
1084
- .optional()
1085
- .describe("Number of lines before/after to show (default: 5)"),
1086
- },
1087
- execute: (args, ctx) => execTool("cass_expand", args, ctx),
1088
- });
1089
-
1090
- const cass_health = tool({
1091
- description: "Check if cass index is healthy. Exit 0 = ready, Exit 1 = needs indexing. Run this before searching.",
1092
- args: {},
1093
- execute: (args, ctx) => execTool("cass_health", args, ctx),
1094
- });
1095
-
1096
- const cass_index = tool({
1097
- description: "Build or rebuild the search index. Run this if health check fails or to pick up new sessions.",
1098
- args: {
1099
- full: tool.schema
1100
- .boolean()
1101
- .optional()
1102
- .describe("Force full rebuild (default: incremental)"),
1103
- },
1104
- execute: (args, ctx) => execTool("cass_index", args, ctx),
1105
- });
1106
-
1107
- const cass_stats = tool({
1108
- description: "Show index statistics - how many sessions, messages, agents indexed.",
1109
- args: {},
1110
- execute: (args, ctx) => execTool("cass_stats", args, ctx),
1111
- });
1112
-
1113
- // =============================================================================
1114
- // Plugin Export
1115
- // =============================================================================
1116
-
1117
- // =============================================================================
1118
- // Compaction Hook - Swarm Recovery Context
1119
- // =============================================================================
1120
-
1121
- /**
1122
- * Detection result with confidence level
1123
- */
1124
- interface SwarmDetection {
1125
- detected: boolean;
1126
- confidence: "high" | "medium" | "low" | "none";
1127
- reasons: string[];
1128
- }
1129
-
1130
- /**
1131
- * Structured state snapshot for LLM-powered compaction
1132
- *
1133
- * This is passed to the lite model to generate a continuation prompt
1134
- * with concrete data instead of just instructions.
1135
- */
1136
- interface SwarmStateSnapshot {
1137
- sessionID: string;
1138
- detection: {
1139
- confidence: "high" | "medium" | "low" | "none";
1140
- reasons: string[];
1141
- };
1142
- epic?: {
1143
- id: string;
1144
- title: string;
1145
- status: string;
1146
- subtasks: Array<{
1147
- id: string;
1148
- title: string;
1149
- status: "open" | "in_progress" | "blocked" | "closed";
1150
- files: string[];
1151
- assignedTo?: string;
1152
- }>;
1153
- };
1154
- messages: Array<{
1155
- from: string;
1156
- to: string[];
1157
- subject: string;
1158
- body: string;
1159
- timestamp: number;
1160
- importance?: string;
1161
- }>;
1162
- reservations: Array<{
1163
- agent: string;
1164
- paths: string[];
1165
- exclusive: boolean;
1166
- expiresAt: number;
1167
- }>;
1168
- }
1169
-
1170
- /**
1171
- * Query actual swarm state using spawn (like detectSwarm does)
1172
- *
1173
- * Returns structured snapshot of current state for LLM compaction.
1174
- * Shells out to swarm CLI to get real data.
1175
- */
1176
- async function querySwarmState(sessionID: string): Promise<SwarmStateSnapshot> {
1177
- const startTime = Date.now();
1178
-
1179
- logCompaction("debug", "query_swarm_state_start", {
1180
- session_id: sessionID,
1181
- project_directory: projectDirectory,
1182
- });
1183
-
1184
- try {
1185
- // Query cells via swarm CLI
1186
- const cliStart = Date.now();
1187
- const cellsResult = await new Promise<{ exitCode: number; stdout: string; stderr: string }>(
1188
- (resolve) => {
1189
- const proc = spawn(SWARM_CLI, ["tool", "hive_query"], {
1190
- cwd: projectDirectory,
1191
- stdio: ["ignore", "pipe", "pipe"],
1192
- });
1193
- let stdout = "";
1194
- let stderr = "";
1195
- proc.stdout.on("data", (d) => {
1196
- stdout += d;
1197
- });
1198
- proc.stderr.on("data", (d) => {
1199
- stderr += d;
1200
- });
1201
- proc.on("close", (exitCode) =>
1202
- resolve({ exitCode: exitCode ?? 1, stdout, stderr }),
1203
- );
1204
- },
1205
- );
1206
- const cliDuration = Date.now() - cliStart;
1207
-
1208
- logCompaction("debug", "query_swarm_state_cli_complete", {
1209
- session_id: sessionID,
1210
- duration_ms: cliDuration,
1211
- exit_code: cellsResult.exitCode,
1212
- stdout_length: cellsResult.stdout.length,
1213
- stderr_length: cellsResult.stderr.length,
1214
- });
1215
-
1216
- let cells: any[] = [];
1217
- if (cellsResult.exitCode === 0) {
1218
- try {
1219
- const parsed = JSON.parse(cellsResult.stdout);
1220
- // Handle wrapped response: { success: true, data: [...] }
1221
- cells = Array.isArray(parsed) ? parsed : (parsed?.data ?? []);
1222
- } catch (parseErr) {
1223
- logCompaction("error", "query_swarm_state_parse_failed", {
1224
- session_id: sessionID,
1225
- error: parseErr instanceof Error ? parseErr.message : String(parseErr),
1226
- stdout_preview: cellsResult.stdout.substring(0, 500),
1227
- });
1228
- }
1229
- }
1230
-
1231
- logCompaction("debug", "query_swarm_state_cells_parsed", {
1232
- session_id: sessionID,
1233
- cell_count: cells.length,
1234
- cells: cells.map((c: any) => ({
1235
- id: c.id,
1236
- title: c.title,
1237
- type: c.type,
1238
- status: c.status,
1239
- parent_id: c.parent_id,
1240
- })),
1241
- });
1242
-
1243
- // Find active epic (first unclosed epic with subtasks)
1244
- const openEpics = cells.filter(
1245
- (c: { type?: string; status: string }) =>
1246
- c.type === "epic" && c.status !== "closed",
1247
- );
1248
- const epic = openEpics[0];
1249
-
1250
- logCompaction("debug", "query_swarm_state_epics", {
1251
- session_id: sessionID,
1252
- open_epic_count: openEpics.length,
1253
- selected_epic: epic ? { id: epic.id, title: epic.title, status: epic.status } : null,
1254
- });
1255
-
1256
- // Get subtasks if we have an epic
1257
- const subtasks =
1258
- epic && epic.id
1259
- ? cells.filter(
1260
- (c: { parent_id?: string }) => c.parent_id === epic.id,
1261
- )
1262
- : [];
1263
-
1264
- logCompaction("debug", "query_swarm_state_subtasks", {
1265
- session_id: sessionID,
1266
- subtask_count: subtasks.length,
1267
- subtasks: subtasks.map((s: any) => ({
1268
- id: s.id,
1269
- title: s.title,
1270
- status: s.status,
1271
- files: s.files,
1272
- })),
1273
- });
1274
-
1275
- // TODO: Query swarm mail for messages and reservations
1276
- // For MVP, use empty arrays - the fallback chain handles this
1277
- const messages: SwarmStateSnapshot["messages"] = [];
1278
- const reservations: SwarmStateSnapshot["reservations"] = [];
1279
-
1280
- // Run detection for confidence (already logged internally)
1281
- const detection = await detectSwarm();
1282
-
1283
- const snapshot: SwarmStateSnapshot = {
1284
- sessionID,
1285
- detection: {
1286
- confidence: detection.confidence,
1287
- reasons: detection.reasons,
1288
- },
1289
- epic: epic
1290
- ? {
1291
- id: epic.id,
1292
- title: epic.title,
1293
- status: epic.status,
1294
- subtasks: subtasks.map((s: {
1295
- id: string;
1296
- title: string;
1297
- status: string;
1298
- files?: string[];
1299
- }) => ({
1300
- id: s.id,
1301
- title: s.title,
1302
- status: s.status as "open" | "in_progress" | "blocked" | "closed",
1303
- files: s.files || [],
1304
- })),
1305
- }
1306
- : undefined,
1307
- messages,
1308
- reservations,
1309
- };
1310
-
1311
- const totalDuration = Date.now() - startTime;
1312
- logCompaction("debug", "query_swarm_state_complete", {
1313
- session_id: sessionID,
1314
- duration_ms: totalDuration,
1315
- has_epic: !!snapshot.epic,
1316
- epic_id: snapshot.epic?.id,
1317
- subtask_count: snapshot.epic?.subtasks?.length ?? 0,
1318
- message_count: snapshot.messages.length,
1319
- reservation_count: snapshot.reservations.length,
1320
- });
1321
-
1322
- return snapshot;
1323
- } catch (err) {
1324
- logCompaction("error", "query_swarm_state_exception", {
1325
- session_id: sessionID,
1326
- error: err instanceof Error ? err.message : String(err),
1327
- stack: err instanceof Error ? err.stack : undefined,
1328
- duration_ms: Date.now() - startTime,
1329
- });
1330
-
1331
- // If query fails, return minimal snapshot
1332
- const detection = await detectSwarm();
1333
- return {
1334
- sessionID,
1335
- detection: {
1336
- confidence: detection.confidence,
1337
- reasons: detection.reasons,
1338
- },
1339
- messages: [],
1340
- reservations: [],
1341
- };
1342
- }
1343
- }
1344
-
1345
- /**
1346
- * Generate compaction prompt using LLM
1347
- *
1348
- * Shells out to `opencode run -m <liteModel>` with structured state.
1349
- * Returns markdown continuation prompt or null on failure.
1350
- *
1351
- * Timeout: 30 seconds
1352
- */
1353
- async function generateCompactionPrompt(
1354
- snapshot: SwarmStateSnapshot,
1355
- ): Promise<string | null> {
1356
- const startTime = Date.now();
1357
- const liteModel = process.env.OPENCODE_LITE_MODEL || "__SWARM_LITE_MODEL__";
1358
-
1359
- logCompaction("debug", "generate_compaction_prompt_start", {
1360
- session_id: snapshot.sessionID,
1361
- lite_model: liteModel,
1362
- has_epic: !!snapshot.epic,
1363
- epic_id: snapshot.epic?.id,
1364
- subtask_count: snapshot.epic?.subtasks?.length ?? 0,
1365
- snapshot_size: JSON.stringify(snapshot).length,
1366
- });
1367
-
1368
- try {
1369
- const promptText = `You are generating a continuation prompt for a compacted swarm coordination session.
1370
-
1371
- Analyze this swarm state and generate a structured markdown prompt that will be given to the resumed session:
1372
-
1373
- ${JSON.stringify(snapshot, null, 2)}
1374
-
1375
- Generate a prompt following this structure:
1376
-
1377
- ┌─────────────────────────────────────────────────────────────┐
1378
- │ │
1379
- │ 🐝 YOU ARE THE COORDINATOR 🐝 │
1380
- │ │
1381
- │ NOT A WORKER. NOT AN IMPLEMENTER. │
1382
- │ YOU ORCHESTRATE. │
1383
- │ │
1384
- └─────────────────────────────────────────────────────────────┘
1385
-
1386
- # 🐝 Swarm Continuation - [Epic Title or "Unknown"]
1387
-
1388
- **NON-NEGOTIABLE: YOU ARE THE COORDINATOR.** You resumed after context compaction.
1389
-
1390
- ## Epic State
1391
-
1392
- **ID:** [epic ID or "Unknown"]
1393
- **Title:** [epic title or "No active epic"]
1394
- **Status:** [X/Y subtasks complete]
1395
- **Project:** ${projectDirectory}
1396
-
1397
- ## Subtask Status
1398
-
1399
- ### ✅ Completed (N)
1400
- [List completed subtasks with IDs]
1401
-
1402
- ### 🚧 In Progress (N)
1403
- [List in-progress subtasks with IDs, files, agents if known]
1404
-
1405
- ### 🚫 Blocked (N)
1406
- [List blocked subtasks]
1407
-
1408
- ### ⏳ Pending (N)
1409
- [List pending subtasks]
1410
-
1411
- ## Next Actions (IMMEDIATE)
1412
-
1413
- [List 3-5 concrete actions with actual commands, using real IDs from the state]
1414
-
1415
- ## 🎯 COORDINATOR MANDATES (NON-NEGOTIABLE)
1416
-
1417
- **YOU ARE THE COORDINATOR. NOT A WORKER.**
1418
-
1419
- ### ⛔ FORBIDDEN - NEVER do these:
1420
- - ❌ NEVER use \`edit\`, \`write\`, or \`bash\` for implementation - SPAWN A WORKER
1421
- - ❌ NEVER fetch directly with \`repo-crawl_*\`, \`repo-autopsy_*\`, \`webfetch\`, \`fetch_fetch\` - SPAWN A RESEARCHER
1422
- - ❌ NEVER use \`context7_*\` or \`pdf-brain_*\` directly - SPAWN A RESEARCHER
1423
- - ❌ NEVER reserve files - Workers reserve files
1424
-
1425
- ### ✅ ALWAYS do these:
1426
- - ✅ ALWAYS check \`swarm_status\` and \`swarmmail_inbox\` first
1427
- - ✅ ALWAYS use \`swarm_spawn_subtask\` for implementation work
1428
- - ✅ ALWAYS use \`swarm_spawn_researcher\` for external data fetching
1429
- - ✅ ALWAYS review worker output with \`swarm_review\` → \`swarm_review_feedback\`
1430
- - ✅ ALWAYS monitor actively - Check messages every ~10 minutes
1431
- - ✅ ALWAYS unblock aggressively - Resolve dependencies immediately
1432
-
1433
- **If you need external data:** Use \`swarm_spawn_researcher\` with a clear research task. The researcher will fetch, summarize, and return findings.
1434
-
1435
- **3-strike rule enforced:** Workers get 3 review attempts. After 3 rejections, escalate to human.
1436
-
1437
- Keep the prompt concise but actionable. Use actual data from the snapshot, not placeholders. Include the ASCII header and ALL coordinator mandates.`;
1438
-
1439
- logCompaction("debug", "generate_compaction_prompt_calling_llm", {
1440
- session_id: snapshot.sessionID,
1441
- prompt_length: promptText.length,
1442
- model: liteModel,
1443
- command: `opencode run -m ${liteModel} -- <prompt>`,
1444
- });
1445
-
1446
- const llmStart = Date.now();
1447
- const result = await new Promise<{ exitCode: number; stdout: string; stderr: string }>(
1448
- (resolve, reject) => {
1449
- const proc = spawn("opencode", ["run", "-m", liteModel, "--", promptText], {
1450
- cwd: projectDirectory,
1451
- stdio: ["ignore", "pipe", "pipe"],
1452
- timeout: 30000, // 30 second timeout
1453
- });
1454
-
1455
- let stdout = "";
1456
- let stderr = "";
1457
-
1458
- proc.stdout.on("data", (d) => {
1459
- stdout += d;
1460
- });
1461
- proc.stderr.on("data", (d) => {
1462
- stderr += d;
1463
- });
1464
-
1465
- proc.on("close", (exitCode) => {
1466
- resolve({ exitCode: exitCode ?? 1, stdout, stderr });
1467
- });
1468
-
1469
- proc.on("error", (err) => {
1470
- reject(err);
1471
- });
1472
-
1473
- // Timeout handling
1474
- setTimeout(() => {
1475
- proc.kill("SIGTERM");
1476
- reject(new Error("LLM compaction timeout (30s)"));
1477
- }, 30000);
1478
- },
1479
- );
1480
- const llmDuration = Date.now() - llmStart;
1481
-
1482
- logCompaction("debug", "generate_compaction_prompt_llm_complete", {
1483
- session_id: snapshot.sessionID,
1484
- duration_ms: llmDuration,
1485
- exit_code: result.exitCode,
1486
- stdout_length: result.stdout.length,
1487
- stderr_length: result.stderr.length,
1488
- stderr_preview: result.stderr.substring(0, 500),
1489
- stdout_preview: result.stdout.substring(0, 500),
1490
- });
1491
-
1492
- if (result.exitCode !== 0) {
1493
- logCompaction("error", "generate_compaction_prompt_llm_failed", {
1494
- session_id: snapshot.sessionID,
1495
- exit_code: result.exitCode,
1496
- stderr: result.stderr,
1497
- stdout: result.stdout,
1498
- duration_ms: llmDuration,
1499
- });
1500
- return null;
1501
- }
1502
-
1503
- // Extract the prompt from stdout (LLM may wrap in markdown)
1504
- const prompt = result.stdout.trim();
1505
-
1506
- const totalDuration = Date.now() - startTime;
1507
- logCompaction("debug", "generate_compaction_prompt_success", {
1508
- session_id: snapshot.sessionID,
1509
- total_duration_ms: totalDuration,
1510
- llm_duration_ms: llmDuration,
1511
- prompt_length: prompt.length,
1512
- prompt_preview: prompt.substring(0, 500),
1513
- prompt_has_content: prompt.length > 0,
1514
- });
1515
-
1516
- return prompt.length > 0 ? prompt : null;
1517
- } catch (err) {
1518
- const totalDuration = Date.now() - startTime;
1519
- logCompaction("error", "generate_compaction_prompt_exception", {
1520
- session_id: snapshot.sessionID,
1521
- error: err instanceof Error ? err.message : String(err),
1522
- stack: err instanceof Error ? err.stack : undefined,
1523
- duration_ms: totalDuration,
1524
- });
1525
- return null;
1526
- }
1527
- }
1528
-
1529
- /**
1530
- * Session message scan result
1531
- */
1532
- interface SessionScanResult {
1533
- messageCount: number;
1534
- toolCalls: Array<{
1535
- toolName: string;
1536
- args: Record<string, unknown>;
1537
- output?: string;
1538
- }>;
1539
- swarmDetected: boolean;
1540
- reasons: string[];
1541
- }
1542
-
1543
- /**
1544
- * Scan session messages for swarm tool calls
1545
- *
1546
- * Uses SDK client to fetch messages and look for swarm activity.
1547
- * This can detect swarm work even if no cells exist yet.
1548
- */
1549
- async function scanSessionMessages(sessionID: string): Promise<SessionScanResult> {
1550
- const startTime = Date.now();
1551
- const result: SessionScanResult = {
1552
- messageCount: 0,
1553
- toolCalls: [],
1554
- swarmDetected: false,
1555
- reasons: [],
1556
- };
1557
-
1558
- logCompaction("debug", "session_scan_start", {
1559
- session_id: sessionID,
1560
- has_sdk_client: !!sdkClient,
1561
- });
1562
-
1563
- if (!sdkClient) {
1564
- logCompaction("warn", "session_scan_no_sdk_client", {
1565
- session_id: sessionID,
1566
- });
1567
- return result;
1568
- }
1569
-
1570
- try {
1571
- // Fetch session messages
1572
- const messagesStart = Date.now();
1573
- const rawResponse = await sdkClient.session.messages({ path: { id: sessionID } });
1574
- const messagesDuration = Date.now() - messagesStart;
1575
-
1576
- // Log the RAW response to understand its shape
1577
- logCompaction("debug", "session_scan_raw_response", {
1578
- session_id: sessionID,
1579
- response_type: typeof rawResponse,
1580
- is_array: Array.isArray(rawResponse),
1581
- is_null: rawResponse === null,
1582
- is_undefined: rawResponse === undefined,
1583
- keys: rawResponse && typeof rawResponse === 'object' ? Object.keys(rawResponse) : [],
1584
- raw_preview: JSON.stringify(rawResponse)?.slice(0, 500),
1585
- });
1586
-
1587
- // The response might be wrapped - check common patterns
1588
- const messages = Array.isArray(rawResponse)
1589
- ? rawResponse
1590
- : rawResponse?.data
1591
- ? rawResponse.data
1592
- : rawResponse?.messages
1593
- ? rawResponse.messages
1594
- : rawResponse?.items
1595
- ? rawResponse.items
1596
- : [];
1597
-
1598
- result.messageCount = messages?.length ?? 0;
1599
-
1600
- logCompaction("debug", "session_scan_messages_fetched", {
1601
- session_id: sessionID,
1602
- duration_ms: messagesDuration,
1603
- message_count: result.messageCount,
1604
- extraction_method: Array.isArray(rawResponse) ? 'direct_array' : rawResponse?.data ? 'data_field' : rawResponse?.messages ? 'messages_field' : rawResponse?.items ? 'items_field' : 'fallback_empty',
1605
- });
1606
-
1607
- if (!Array.isArray(messages) || messages.length === 0) {
1608
- logCompaction("debug", "session_scan_no_messages", {
1609
- session_id: sessionID,
1610
- });
1611
- return result;
1612
- }
1613
-
1614
- // Swarm-related tool patterns
1615
- const swarmTools = [
1616
- // High confidence - active swarm coordination
1617
- "hive_create_epic",
1618
- "swarm_decompose",
1619
- "swarm_spawn_subtask",
1620
- "swarm_complete",
1621
- "swarmmail_init",
1622
- "swarmmail_reserve",
1623
- // Medium confidence - swarm activity
1624
- "hive_start",
1625
- "hive_close",
1626
- "swarm_status",
1627
- "swarm_progress",
1628
- "swarmmail_send",
1629
- // Low confidence - possible swarm
1630
- "hive_create",
1631
- "hive_query",
1632
- ];
1633
-
1634
- const highConfidenceTools = new Set([
1635
- "hive_create_epic",
1636
- "swarm_decompose",
1637
- "swarm_spawn_subtask",
1638
- "swarmmail_init",
1639
- "swarmmail_reserve",
1640
- ]);
1641
-
1642
- // Scan messages for tool calls
1643
- let swarmToolCount = 0;
1644
- let highConfidenceCount = 0;
1645
-
1646
- // Debug: collect part types to understand message structure
1647
- const partTypeCounts: Record<string, number> = {};
1648
- let messagesWithParts = 0;
1649
- let messagesWithoutParts = 0;
1650
- let samplePartTypes: string[] = [];
1651
-
1652
- for (const message of messages) {
1653
- if (!message.parts || !Array.isArray(message.parts)) {
1654
- messagesWithoutParts++;
1655
- continue;
1656
- }
1657
- messagesWithParts++;
1658
-
1659
- for (const part of message.parts) {
1660
- const partType = part.type || "unknown";
1661
- partTypeCounts[partType] = (partTypeCounts[partType] || 0) + 1;
1662
-
1663
- // Collect first 10 unique part types for debugging
1664
- if (samplePartTypes.length < 10 && !samplePartTypes.includes(partType)) {
1665
- samplePartTypes.push(partType);
1666
- }
1667
-
1668
- // Check if this is a tool call part
1669
- // OpenCode SDK: ToolPart has type="tool", tool=<string name>, state={...}
1670
- if (part.type === "tool") {
1671
- const toolPart = part as ToolPart;
1672
- const toolName = toolPart.tool; // tool name is a string directly
1673
-
1674
- if (toolName && swarmTools.includes(toolName)) {
1675
- swarmToolCount++;
1676
-
1677
- if (highConfidenceTools.has(toolName)) {
1678
- highConfidenceCount++;
1679
- }
1680
-
1681
- // Extract args/output from state if available
1682
- const state = toolPart.state;
1683
- const args = state && "input" in state ? state.input : {};
1684
- const output = state && "output" in state ? state.output : undefined;
1685
-
1686
- result.toolCalls.push({
1687
- toolName,
1688
- args,
1689
- output,
1690
- });
1691
-
1692
- logCompaction("debug", "session_scan_tool_found", {
1693
- session_id: sessionID,
1694
- tool_name: toolName,
1695
- is_high_confidence: highConfidenceTools.has(toolName),
1696
- });
1697
- }
1698
- }
1699
- }
1700
- }
1701
-
1702
- // Determine if swarm detected based on tool calls
1703
- if (highConfidenceCount > 0) {
1704
- result.swarmDetected = true;
1705
- result.reasons.push(`${highConfidenceCount} high-confidence swarm tools (${Array.from(new Set(result.toolCalls.filter(tc => highConfidenceTools.has(tc.toolName)).map(tc => tc.toolName))).join(", ")})`);
1706
- }
1707
-
1708
- if (swarmToolCount > 0 && !result.swarmDetected) {
1709
- result.swarmDetected = true;
1710
- result.reasons.push(`${swarmToolCount} swarm-related tools used`);
1711
- }
1712
-
1713
- const totalDuration = Date.now() - startTime;
1714
-
1715
- // Debug: log part type distribution to understand message structure
1716
- logCompaction("debug", "session_scan_part_types", {
1717
- session_id: sessionID,
1718
- messages_with_parts: messagesWithParts,
1719
- messages_without_parts: messagesWithoutParts,
1720
- part_type_counts: partTypeCounts,
1721
- sample_part_types: samplePartTypes,
1722
- });
1723
-
1724
- logCompaction("info", "session_scan_complete", {
1725
- session_id: sessionID,
1726
- duration_ms: totalDuration,
1727
- message_count: result.messageCount,
1728
- tool_call_count: result.toolCalls.length,
1729
- swarm_tool_count: swarmToolCount,
1730
- high_confidence_count: highConfidenceCount,
1731
- swarm_detected: result.swarmDetected,
1732
- reasons: result.reasons,
1733
- unique_tools: Array.from(new Set(result.toolCalls.map(tc => tc.toolName))),
1734
- });
1735
-
1736
- return result;
1737
- } catch (err) {
1738
- const totalDuration = Date.now() - startTime;
1739
- logCompaction("error", "session_scan_exception", {
1740
- session_id: sessionID,
1741
- error: err instanceof Error ? err.message : String(err),
1742
- stack: err instanceof Error ? err.stack : undefined,
1743
- duration_ms: totalDuration,
1744
- });
1745
- return result;
1746
- }
1747
- }
1748
-
1749
- /**
1750
- * Check for swarm sign - evidence a swarm passed through
1751
- *
1752
- * Uses multiple signals with different confidence levels:
1753
- * - HIGH: in_progress cells (active work)
1754
- * - MEDIUM: Open subtasks, unclosed epics, recently updated cells
1755
- * - LOW: Any cells exist
1756
- *
1757
- * Philosophy: Err on the side of continuation.
1758
- * False positive = extra context (low cost)
1759
- * False negative = lost swarm (high cost)
1760
- */
1761
- async function detectSwarm(): Promise<SwarmDetection> {
1762
- const startTime = Date.now();
1763
- const reasons: string[] = [];
1764
- let highConfidence = false;
1765
- let mediumConfidence = false;
1766
- let lowConfidence = false;
1767
-
1768
- logCompaction("debug", "detect_swarm_start", {
1769
- project_directory: projectDirectory,
1770
- cwd: process.cwd(),
1771
- });
1772
-
1773
- try {
1774
- const cliStart = Date.now();
1775
- const result = await new Promise<{ exitCode: number; stdout: string; stderr: string }>(
1776
- (resolve) => {
1777
- // Use swarm tool to query beads
1778
- const proc = spawn(SWARM_CLI, ["tool", "hive_query"], {
1779
- cwd: projectDirectory,
1780
- stdio: ["ignore", "pipe", "pipe"],
1781
- });
1782
- let stdout = "";
1783
- let stderr = "";
1784
- proc.stdout.on("data", (d) => {
1785
- stdout += d;
1786
- });
1787
- proc.stderr.on("data", (d) => {
1788
- stderr += d;
1789
- });
1790
- proc.on("close", (exitCode) =>
1791
- resolve({ exitCode: exitCode ?? 1, stdout, stderr }),
1792
- );
1793
- },
1794
- );
1795
- const cliDuration = Date.now() - cliStart;
1796
-
1797
- logCompaction("debug", "detect_swarm_cli_complete", {
1798
- duration_ms: cliDuration,
1799
- exit_code: result.exitCode,
1800
- stdout_length: result.stdout.length,
1801
- stderr_length: result.stderr.length,
1802
- stderr_preview: result.stderr.substring(0, 200),
1803
- });
1804
-
1805
- if (result.exitCode !== 0) {
1806
- logCompaction("warn", "detect_swarm_cli_failed", {
1807
- exit_code: result.exitCode,
1808
- stderr: result.stderr,
1809
- });
1810
- return { detected: false, confidence: "none", reasons: ["hive_query failed"] };
1811
- }
1812
-
1813
- let cells: any[];
1814
- try {
1815
- cells = JSON.parse(result.stdout);
1816
- } catch (parseErr) {
1817
- logCompaction("error", "detect_swarm_parse_failed", {
1818
- error: parseErr instanceof Error ? parseErr.message : String(parseErr),
1819
- stdout_preview: result.stdout.substring(0, 500),
1820
- });
1821
- return { detected: false, confidence: "none", reasons: ["hive_query parse failed"] };
1822
- }
1823
-
1824
- if (!Array.isArray(cells) || cells.length === 0) {
1825
- logCompaction("debug", "detect_swarm_no_cells", {
1826
- is_array: Array.isArray(cells),
1827
- length: cells?.length ?? 0,
1828
- });
1829
- return { detected: false, confidence: "none", reasons: ["no cells found"] };
1830
- }
1831
-
1832
- // Log ALL cells for debugging
1833
- logCompaction("debug", "detect_swarm_cells_found", {
1834
- total_cells: cells.length,
1835
- cells: cells.map((c: any) => ({
1836
- id: c.id,
1837
- title: c.title,
1838
- type: c.type,
1839
- status: c.status,
1840
- parent_id: c.parent_id,
1841
- updated_at: c.updated_at,
1842
- created_at: c.created_at,
1843
- })),
1844
- });
1845
-
1846
- // HIGH: Any in_progress cells
1847
- const inProgress = cells.filter(
1848
- (c: { status: string }) => c.status === "in_progress"
1849
- );
1850
- if (inProgress.length > 0) {
1851
- highConfidence = true;
1852
- reasons.push(`${inProgress.length} cells in_progress`);
1853
- logCompaction("debug", "detect_swarm_in_progress", {
1854
- count: inProgress.length,
1855
- cells: inProgress.map((c: any) => ({ id: c.id, title: c.title })),
1856
- });
1857
- }
1858
-
1859
- // MEDIUM: Open subtasks (cells with parent_id)
1860
- const subtasks = cells.filter(
1861
- (c: { status: string; parent_id?: string }) =>
1862
- c.status === "open" && c.parent_id
1863
- );
1864
- if (subtasks.length > 0) {
1865
- mediumConfidence = true;
1866
- reasons.push(`${subtasks.length} open subtasks`);
1867
- logCompaction("debug", "detect_swarm_open_subtasks", {
1868
- count: subtasks.length,
1869
- cells: subtasks.map((c: any) => ({ id: c.id, title: c.title, parent_id: c.parent_id })),
1870
- });
1871
- }
1872
-
1873
- // MEDIUM: Unclosed epics
1874
- const openEpics = cells.filter(
1875
- (c: { status: string; type?: string }) =>
1876
- c.type === "epic" && c.status !== "closed"
1877
- );
1878
- if (openEpics.length > 0) {
1879
- mediumConfidence = true;
1880
- reasons.push(`${openEpics.length} unclosed epics`);
1881
- logCompaction("debug", "detect_swarm_open_epics", {
1882
- count: openEpics.length,
1883
- cells: openEpics.map((c: any) => ({ id: c.id, title: c.title, status: c.status })),
1884
- });
1885
- }
1886
-
1887
- // MEDIUM: Recently updated cells (last hour)
1888
- const oneHourAgo = Date.now() - 60 * 60 * 1000;
1889
- const recentCells = cells.filter(
1890
- (c: { updated_at?: number }) => c.updated_at && c.updated_at > oneHourAgo
1891
- );
1892
- if (recentCells.length > 0) {
1893
- mediumConfidence = true;
1894
- reasons.push(`${recentCells.length} cells updated in last hour`);
1895
- logCompaction("debug", "detect_swarm_recent_cells", {
1896
- count: recentCells.length,
1897
- one_hour_ago: oneHourAgo,
1898
- cells: recentCells.map((c: any) => ({
1899
- id: c.id,
1900
- title: c.title,
1901
- updated_at: c.updated_at,
1902
- age_minutes: Math.round((Date.now() - c.updated_at) / 60000),
1903
- })),
1904
- });
1905
- }
1906
-
1907
- // LOW: Any cells exist at all
1908
- if (cells.length > 0) {
1909
- lowConfidence = true;
1910
- reasons.push(`${cells.length} total cells in hive`);
1911
- }
1912
- } catch (err) {
1913
- // Detection failed, use fallback
1914
- lowConfidence = true;
1915
- reasons.push("Detection error, using fallback");
1916
- logCompaction("error", "detect_swarm_exception", {
1917
- error: err instanceof Error ? err.message : String(err),
1918
- stack: err instanceof Error ? err.stack : undefined,
1919
- });
1920
- }
1921
-
1922
- // Determine overall confidence
1923
- let confidence: "high" | "medium" | "low" | "none";
1924
- if (highConfidence) {
1925
- confidence = "high";
1926
- } else if (mediumConfidence) {
1927
- confidence = "medium";
1928
- } else if (lowConfidence) {
1929
- confidence = "low";
1930
- } else {
1931
- confidence = "none";
1932
- }
1933
-
1934
- const totalDuration = Date.now() - startTime;
1935
- logCompaction("debug", "detect_swarm_complete", {
1936
- duration_ms: totalDuration,
1937
- confidence,
1938
- detected: confidence !== "none",
1939
- reason_count: reasons.length,
1940
- reasons,
1941
- high_confidence: highConfidence,
1942
- medium_confidence: mediumConfidence,
1943
- low_confidence: lowConfidence,
1944
- });
1945
-
1946
- return {
1947
- detected: confidence !== "none",
1948
- confidence,
1949
- reasons,
1950
- };
1951
- }
1952
-
1953
- /**
1954
- * Swarm-aware compaction context
1955
- *
1956
- * Injected during compaction to keep the swarm cooking. The coordinator should
1957
- * wake up from compaction and immediately resume orchestration - spawning agents,
1958
- * monitoring progress, unblocking work.
1959
- */
1960
- const SWARM_COMPACTION_CONTEXT = `## 🐝 SWARM ACTIVE - Keep Cooking
1961
-
1962
- You are the **COORDINATOR** of an active swarm. Context was compacted but the swarm is still running.
1963
-
1964
- **YOUR JOB:** Keep orchestrating. Spawn agents. Monitor progress. Unblock work. Ship it.
1965
-
1966
- ### Preserve in Summary
1967
-
1968
- Extract from session context:
1969
-
1970
- 1. **Epic & Subtasks** - IDs, titles, status, file assignments
1971
- 2. **What's Running** - Which agents are active, what they're working on
1972
- 3. **What's Blocked** - Blockers and what's needed to unblock
1973
- 4. **What's Done** - Completed work and any follow-ups needed
1974
- 5. **What's Next** - Pending subtasks ready to spawn
1975
-
1976
- ### Summary Format
1977
-
1978
- \`\`\`
1979
- ## 🐝 Swarm State
1980
-
1981
- **Epic:** <bd-xxx> - <title>
1982
- **Project:** <path>
1983
- **Progress:** X/Y subtasks complete
1984
-
1985
- **Active:**
1986
- - <bd-xxx>: <title> [in_progress] → <agent> working on <files>
1987
-
1988
- **Blocked:**
1989
- - <bd-xxx>: <title> - BLOCKED: <reason>
1990
-
1991
- **Completed:**
1992
- - <bd-xxx>: <title> ✓
1993
-
1994
- **Ready to Spawn:**
1995
- - <bd-xxx>: <title> (files: <...>)
1996
- \`\`\`
1997
-
1998
- ### On Resume - IMMEDIATELY
1999
-
2000
- 1. \`swarm_status(epic_id="<epic>", project_key="<path>")\` - Get current state
2001
- 2. \`swarmmail_inbox(limit=5)\` - Check for agent messages
2002
- 3. \`swarm_review(project_key, epic_id, task_id, files_touched)\` - Review any completed work
2003
- 4. \`swarm_review_feedback(project_key, task_id, worker_id, status, issues)\` - Approve or request changes
2004
- 5. **Spawn ready subtasks** - Don't wait, fire them off
2005
- 6. **Unblock blocked work** - Resolve dependencies, reassign if needed
2006
- 7. **Collect completed work** - Close done subtasks, verify quality
2007
-
2008
- ### Keep the Swarm Cooking
2009
-
2010
- - **Spawn aggressively** - If a subtask is ready and unblocked, spawn an agent
2011
- - **Monitor actively** - Check status, read messages, respond to blockers
2012
- - **Close the loop** - When all subtasks done, verify and close the epic
2013
- - **Don't stop** - The swarm runs until the epic is closed
2014
-
2015
- **You are not waiting for instructions. You are the coordinator. Coordinate.**
2016
- `;
2017
-
2018
- /**
2019
- * Fallback detection prompt - tells the compactor what to look for
2020
- *
2021
- * Used when we can't definitively detect a swarm but want to be safe.
2022
- * The compactor can check the conversation context for these patterns.
2023
- */
2024
- const SWARM_DETECTION_FALLBACK = `## 🐝 Swarm Detection - Check Your Context
2025
-
2026
- **IMPORTANT:** Before summarizing, check if this session involves an active swarm.
2027
-
2028
- Look for ANY of these patterns in the conversation:
2029
-
2030
- ### Tool Calls (definite swarm sign)
2031
- - \`swarm_decompose\`, \`swarm_spawn_subtask\`, \`swarm_status\`, \`swarm_complete\`
2032
- - \`swarmmail_init\`, \`swarmmail_reserve\`, \`swarmmail_send\`
2033
- - \`hive_create_epic\`, \`hive_start\`, \`hive_close\`
2034
-
2035
- ### IDs and Names
2036
- - Cell IDs: \`bd-xxx\`, \`bd-xxx.N\` (subtask format)
2037
- - Agent names: BlueLake, RedMountain, GreenValley, etc.
2038
- - Epic references: "epic", "subtask", "parent"
2039
-
2040
- ### Coordination Language
2041
- - "spawn", "worker", "coordinator"
2042
- - "reserve", "reservation", "files"
2043
- - "blocked", "unblock", "dependency"
2044
- - "progress", "complete", "in_progress"
2045
-
2046
- ### If You Find Swarm Evidence
2047
-
2048
- Include this in your summary:
2049
- 1. Epic ID and title
2050
- 2. Project path
2051
- 3. Subtask status (running/blocked/done/pending)
2052
- 4. Any blockers or issues
2053
- 5. What should happen next
2054
-
2055
- **Then tell the resumed session:**
2056
- "This is an active swarm. Check swarm_status and swarmmail_inbox immediately."
2057
- `;
2058
-
2059
- // Extended hooks type to include experimental compaction hook with new prompt API
2060
- type CompactionOutput = {
2061
- context: string[];
2062
- prompt?: string; // NEW API from OpenCode PR #5907
2063
- };
2064
-
2065
- type ExtendedHooks = Hooks & {
2066
- "experimental.session.compacting"?: (
2067
- input: { sessionID: string },
2068
- output: CompactionOutput,
2069
- ) => Promise<void>;
2070
- };
2071
-
2072
- // NOTE: Only default export - named exports cause double registration!
2073
- // OpenCode's plugin loader calls ALL exports as functions.
2074
- const SwarmPlugin: Plugin = async (
2075
- input: PluginInput,
2076
- ): Promise<ExtendedHooks> => {
2077
- // CRITICAL: Set project directory from OpenCode input
2078
- // Without this, CLI uses wrong database path
2079
- projectDirectory = input.directory;
2080
-
2081
- // Store SDK client for session message scanning during compaction
2082
- sdkClient = input.client;
2083
-
2084
- return {
2085
- tool: {
2086
- // Beads
2087
- hive_create,
2088
- hive_create_epic,
2089
- hive_query,
2090
- hive_update,
2091
- hive_close,
2092
- hive_start,
2093
- hive_ready,
2094
- hive_cells,
2095
- hive_sync,
2096
- beads_link_thread,
2097
- // Swarm Mail (Embedded)
2098
- swarmmail_init,
2099
- swarmmail_send,
2100
- swarmmail_inbox,
2101
- swarmmail_read_message,
2102
- swarmmail_reserve,
2103
- swarmmail_release,
2104
- swarmmail_ack,
2105
- swarmmail_health,
2106
- // Structured
2107
- structured_extract_json,
2108
- structured_validate,
2109
- structured_parse_evaluation,
2110
- structured_parse_decomposition,
2111
- structured_parse_cell_tree,
2112
- // Swarm
2113
- swarm_init,
2114
- swarm_select_strategy,
2115
- swarm_plan_prompt,
2116
- swarm_decompose,
2117
- swarm_validate_decomposition,
2118
- swarm_status,
2119
- swarm_progress,
2120
- swarm_complete,
2121
- swarm_record_outcome,
2122
- swarm_subtask_prompt,
2123
- swarm_spawn_subtask,
2124
- swarm_complete_subtask,
2125
- swarm_evaluation_prompt,
2126
- swarm_broadcast,
2127
- // Worktree Isolation
2128
- swarm_worktree_create,
2129
- swarm_worktree_merge,
2130
- swarm_worktree_cleanup,
2131
- swarm_worktree_list,
2132
- // Structured Review
2133
- swarm_review,
2134
- swarm_review_feedback,
2135
- // Skills
2136
- skills_list,
2137
- skills_read,
2138
- skills_use,
2139
- skills_create,
2140
- skills_update,
2141
- skills_delete,
2142
- skills_init,
2143
- skills_add_script,
2144
- skills_execute,
2145
- // Swarm Insights
2146
- swarm_get_strategy_insights,
2147
- swarm_get_file_insights,
2148
- swarm_get_pattern_insights,
2149
- // CASS (Cross-Agent Session Search)
2150
- cass_search,
2151
- cass_view,
2152
- cass_expand,
2153
- cass_health,
2154
- cass_index,
2155
- cass_stats,
2156
- },
2157
-
2158
- // Swarm-aware compaction hook with LLM-powered continuation prompts
2159
- // Three-level fallback chain: LLM → static context → detection fallback → none
2160
- "experimental.session.compacting": async (
2161
- input: { sessionID: string },
2162
- output: CompactionOutput,
2163
- ) => {
2164
- const startTime = Date.now();
2165
-
2166
- // =======================================================================
2167
- // LOG: Compaction hook invoked - capture EVERYTHING we receive
2168
- // =======================================================================
2169
- logCompaction("info", "compaction_hook_invoked", {
2170
- session_id: input.sessionID,
2171
- project_directory: projectDirectory,
2172
- input_keys: Object.keys(input),
2173
- input_full: JSON.parse(JSON.stringify(input)), // Deep clone for logging
2174
- output_keys: Object.keys(output),
2175
- output_context_count: output.context?.length ?? 0,
2176
- output_has_prompt_field: "prompt" in output,
2177
- output_initial_state: {
2178
- context: output.context,
2179
- prompt: (output as any).prompt,
2180
- },
2181
- env: {
2182
- OPENCODE_SESSION_ID: process.env.OPENCODE_SESSION_ID,
2183
- OPENCODE_MESSAGE_ID: process.env.OPENCODE_MESSAGE_ID,
2184
- OPENCODE_AGENT: process.env.OPENCODE_AGENT,
2185
- OPENCODE_LITE_MODEL: process.env.OPENCODE_LITE_MODEL,
2186
- SWARM_PROJECT_DIR: process.env.SWARM_PROJECT_DIR,
2187
- },
2188
- cwd: process.cwd(),
2189
- timestamp: new Date().toISOString(),
2190
- });
2191
-
2192
- // =======================================================================
2193
- // STEP 1: Scan session messages for swarm tool calls
2194
- // =======================================================================
2195
- const sessionScanStart = Date.now();
2196
- const sessionScan = await scanSessionMessages(input.sessionID);
2197
- const sessionScanDuration = Date.now() - sessionScanStart;
2198
-
2199
- logCompaction("info", "session_scan_results", {
2200
- session_id: input.sessionID,
2201
- duration_ms: sessionScanDuration,
2202
- message_count: sessionScan.messageCount,
2203
- tool_call_count: sessionScan.toolCalls.length,
2204
- swarm_detected_from_messages: sessionScan.swarmDetected,
2205
- reasons: sessionScan.reasons,
2206
- });
2207
-
2208
- // =======================================================================
2209
- // STEP 2: Detect swarm state from hive cells
2210
- // =======================================================================
2211
- const detectionStart = Date.now();
2212
- const detection = await detectSwarm();
2213
- const detectionDuration = Date.now() - detectionStart;
2214
-
2215
- logCompaction("info", "swarm_detection_complete", {
2216
- session_id: input.sessionID,
2217
- duration_ms: detectionDuration,
2218
- detected: detection.detected,
2219
- confidence: detection.confidence,
2220
- reasons: detection.reasons,
2221
- reason_count: detection.reasons.length,
2222
- });
2223
-
2224
- // =======================================================================
2225
- // STEP 3: Merge session scan with hive detection for final confidence
2226
- // =======================================================================
2227
- // If session messages show high-confidence swarm tools, boost confidence
2228
- if (sessionScan.swarmDetected && sessionScan.reasons.some(r => r.includes("high-confidence"))) {
2229
- if (detection.confidence === "none" || detection.confidence === "low") {
2230
- detection.confidence = "high";
2231
- detection.detected = true;
2232
- detection.reasons.push(...sessionScan.reasons);
2233
-
2234
- logCompaction("info", "confidence_boost_from_session_scan", {
2235
- session_id: input.sessionID,
2236
- original_confidence: detection.confidence,
2237
- boosted_to: "high",
2238
- session_reasons: sessionScan.reasons,
2239
- });
2240
- }
2241
- } else if (sessionScan.swarmDetected) {
2242
- // Medium boost for any swarm tools found
2243
- if (detection.confidence === "none") {
2244
- detection.confidence = "medium";
2245
- detection.detected = true;
2246
- detection.reasons.push(...sessionScan.reasons);
2247
-
2248
- logCompaction("info", "confidence_boost_from_session_scan", {
2249
- session_id: input.sessionID,
2250
- original_confidence: "none",
2251
- boosted_to: "medium",
2252
- session_reasons: sessionScan.reasons,
2253
- });
2254
- } else if (detection.confidence === "low") {
2255
- detection.confidence = "medium";
2256
- detection.reasons.push(...sessionScan.reasons);
2257
-
2258
- logCompaction("info", "confidence_boost_from_session_scan", {
2259
- session_id: input.sessionID,
2260
- original_confidence: "low",
2261
- boosted_to: "medium",
2262
- session_reasons: sessionScan.reasons,
2263
- });
2264
- }
2265
- }
2266
-
2267
- logCompaction("info", "final_swarm_detection", {
2268
- session_id: input.sessionID,
2269
- confidence: detection.confidence,
2270
- detected: detection.detected,
2271
- combined_reasons: detection.reasons,
2272
- message_scan_contributed: sessionScan.swarmDetected,
2273
- });
2274
-
2275
- if (detection.confidence === "high" || detection.confidence === "medium") {
2276
- // Definite or probable swarm - try LLM-powered compaction
2277
- logCompaction("info", "swarm_detected_attempting_llm", {
2278
- session_id: input.sessionID,
2279
- confidence: detection.confidence,
2280
- reasons: detection.reasons,
2281
- });
2282
-
2283
- try {
2284
- // Level 1: Query actual state
2285
- const queryStart = Date.now();
2286
- const snapshot = await querySwarmState(input.sessionID);
2287
- const queryDuration = Date.now() - queryStart;
2288
-
2289
- logCompaction("info", "swarm_state_queried", {
2290
- session_id: input.sessionID,
2291
- duration_ms: queryDuration,
2292
- has_epic: !!snapshot.epic,
2293
- epic_id: snapshot.epic?.id,
2294
- epic_title: snapshot.epic?.title,
2295
- epic_status: snapshot.epic?.status,
2296
- subtask_count: snapshot.epic?.subtasks?.length ?? 0,
2297
- subtasks: snapshot.epic?.subtasks?.map(s => ({
2298
- id: s.id,
2299
- title: s.title,
2300
- status: s.status,
2301
- file_count: s.files?.length ?? 0,
2302
- })),
2303
- message_count: snapshot.messages?.length ?? 0,
2304
- reservation_count: snapshot.reservations?.length ?? 0,
2305
- detection_confidence: snapshot.detection.confidence,
2306
- detection_reasons: snapshot.detection.reasons,
2307
- full_snapshot: snapshot, // Log the entire snapshot
2308
- });
2309
-
2310
- // =======================================================================
2311
- // CAPTURE POINT 1: Detection complete - record confidence and reasons
2312
- // =======================================================================
2313
- await captureCompaction(
2314
- input.sessionID,
2315
- snapshot.epic?.id || "unknown",
2316
- "detection_complete",
2317
- {
2318
- confidence: snapshot.detection.confidence,
2319
- detected: detection.detected,
2320
- reasons: snapshot.detection.reasons,
2321
- session_scan_contributed: sessionScan.swarmDetected,
2322
- session_scan_reasons: sessionScan.reasons,
2323
- epic_id: snapshot.epic?.id,
2324
- epic_title: snapshot.epic?.title,
2325
- subtask_count: snapshot.epic?.subtasks?.length ?? 0,
2326
- },
2327
- );
2328
-
2329
- // Level 2: Generate prompt with LLM
2330
- const llmStart = Date.now();
2331
- const llmPrompt = await generateCompactionPrompt(snapshot);
2332
- const llmDuration = Date.now() - llmStart;
2333
-
2334
- logCompaction("info", "llm_generation_complete", {
2335
- session_id: input.sessionID,
2336
- duration_ms: llmDuration,
2337
- success: !!llmPrompt,
2338
- prompt_length: llmPrompt?.length ?? 0,
2339
- prompt_preview: llmPrompt?.substring(0, 500),
2340
- });
2341
-
2342
- // =======================================================================
2343
- // CAPTURE POINT 2: Prompt generated - record FULL prompt content
2344
- // =======================================================================
2345
- if (llmPrompt) {
2346
- await captureCompaction(
2347
- input.sessionID,
2348
- snapshot.epic?.id || "unknown",
2349
- "prompt_generated",
2350
- {
2351
- prompt_length: llmPrompt.length,
2352
- full_prompt: llmPrompt, // FULL content, not truncated
2353
- context_type: "llm_generated",
2354
- duration_ms: llmDuration,
2355
- },
2356
- );
2357
- }
2358
-
2359
- if (llmPrompt) {
2360
- // SUCCESS: Use LLM-generated prompt
2361
- const header = `[Swarm compaction: LLM-generated, ${detection.reasons.join(", ")}]\n\n`;
2362
- const fullContent = header + llmPrompt;
2363
-
2364
- // Progressive enhancement: use new API if available
2365
- if ("prompt" in output) {
2366
- output.prompt = fullContent;
2367
- logCompaction("info", "context_injected_via_prompt_api", {
2368
- session_id: input.sessionID,
2369
- content_length: fullContent.length,
2370
- method: "output.prompt",
2371
- });
2372
- } else {
2373
- output.context.push(fullContent);
2374
- logCompaction("info", "context_injected_via_context_array", {
2375
- session_id: input.sessionID,
2376
- content_length: fullContent.length,
2377
- method: "output.context.push",
2378
- context_count_after: output.context.length,
2379
- });
2380
- }
2381
-
2382
- // =======================================================================
2383
- // CAPTURE POINT 3a: Context injected (LLM path) - record FULL content
2384
- // =======================================================================
2385
- await captureCompaction(
2386
- input.sessionID,
2387
- snapshot.epic?.id || "unknown",
2388
- "context_injected",
2389
- {
2390
- full_content: fullContent, // FULL content, not truncated
2391
- content_length: fullContent.length,
2392
- injection_method: "prompt" in output ? "output.prompt" : "output.context.push",
2393
- context_type: "llm_generated",
2394
- },
2395
- );
2396
-
2397
- const totalDuration = Date.now() - startTime;
2398
- logCompaction("info", "compaction_complete_llm_success", {
2399
- session_id: input.sessionID,
2400
- total_duration_ms: totalDuration,
2401
- detection_duration_ms: detectionDuration,
2402
- query_duration_ms: queryDuration,
2403
- llm_duration_ms: llmDuration,
2404
- confidence: detection.confidence,
2405
- context_type: "llm_generated",
2406
- content_length: fullContent.length,
2407
- });
2408
- return;
2409
- }
2410
-
2411
- // LLM failed, fall through to static prompt
2412
- logCompaction("warn", "llm_generation_returned_null", {
2413
- session_id: input.sessionID,
2414
- llm_duration_ms: llmDuration,
2415
- falling_back_to: "static_prompt",
2416
- });
2417
- } catch (err) {
2418
- // LLM failed, fall through to static prompt
2419
- logCompaction("error", "llm_generation_failed", {
2420
- session_id: input.sessionID,
2421
- error: err instanceof Error ? err.message : String(err),
2422
- error_stack: err instanceof Error ? err.stack : undefined,
2423
- falling_back_to: "static_prompt",
2424
- });
2425
- }
2426
-
2427
- // Level 3: Fall back to static context
2428
- const header = `[Swarm detected: ${detection.reasons.join(", ")}]\n\n`;
2429
- const staticContent = header + SWARM_COMPACTION_CONTEXT;
2430
- output.context.push(staticContent);
2431
-
2432
- // =======================================================================
2433
- // CAPTURE POINT 3b: Context injected (static fallback) - record FULL content
2434
- // =======================================================================
2435
- await captureCompaction(
2436
- input.sessionID,
2437
- "unknown", // No snapshot available in this path
2438
- "context_injected",
2439
- {
2440
- full_content: staticContent,
2441
- content_length: staticContent.length,
2442
- injection_method: "output.context.push",
2443
- context_type: "static_swarm_context",
2444
- },
2445
- );
2446
-
2447
- const totalDuration = Date.now() - startTime;
2448
- logCompaction("info", "compaction_complete_static_fallback", {
2449
- session_id: input.sessionID,
2450
- total_duration_ms: totalDuration,
2451
- confidence: detection.confidence,
2452
- context_type: "static_swarm_context",
2453
- content_length: staticContent.length,
2454
- context_count_after: output.context.length,
2455
- });
2456
- } else if (detection.confidence === "low") {
2457
- // Level 4: Possible swarm - inject fallback detection prompt
2458
- const header = `[Possible swarm: ${detection.reasons.join(", ")}]\n\n`;
2459
- const fallbackContent = header + SWARM_DETECTION_FALLBACK;
2460
- output.context.push(fallbackContent);
2461
-
2462
- // =======================================================================
2463
- // CAPTURE POINT 3c: Context injected (detection fallback) - record FULL content
2464
- // =======================================================================
2465
- await captureCompaction(
2466
- input.sessionID,
2467
- "unknown", // No snapshot for low confidence
2468
- "context_injected",
2469
- {
2470
- full_content: fallbackContent,
2471
- content_length: fallbackContent.length,
2472
- injection_method: "output.context.push",
2473
- context_type: "detection_fallback",
2474
- },
2475
- );
2476
-
2477
- const totalDuration = Date.now() - startTime;
2478
- logCompaction("info", "compaction_complete_detection_fallback", {
2479
- session_id: input.sessionID,
2480
- total_duration_ms: totalDuration,
2481
- confidence: detection.confidence,
2482
- context_type: "detection_fallback",
2483
- content_length: fallbackContent.length,
2484
- context_count_after: output.context.length,
2485
- reasons: detection.reasons,
2486
- });
2487
- } else {
2488
- // Level 5: confidence === "none" - no injection, probably not a swarm
2489
- const totalDuration = Date.now() - startTime;
2490
- logCompaction("info", "compaction_complete_no_swarm", {
2491
- session_id: input.sessionID,
2492
- total_duration_ms: totalDuration,
2493
- confidence: detection.confidence,
2494
- context_type: "none",
2495
- reasons: detection.reasons,
2496
- context_count_unchanged: output.context.length,
2497
- });
2498
- }
2499
-
2500
- // =======================================================================
2501
- // LOG: Final output state
2502
- // =======================================================================
2503
- logCompaction("debug", "compaction_hook_complete_final_state", {
2504
- session_id: input.sessionID,
2505
- output_context_count: output.context?.length ?? 0,
2506
- output_context_lengths: output.context?.map(c => c.length) ?? [],
2507
- output_has_prompt: !!(output as any).prompt,
2508
- output_prompt_length: (output as any).prompt?.length ?? 0,
2509
- total_duration_ms: Date.now() - startTime,
2510
- });
2511
- },
2512
- };
2513
- };
2514
-
2515
- export default SwarmPlugin;