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,871 +0,0 @@
1
- /**
2
- * Observability Tools - Agent-facing Analytics
3
- *
4
- * Exposes observability tools to agents via plugin tools.
5
- * Agents get programmatic access to analytics, not just CLI.
6
- *
7
- * Tools:
8
- * - swarm_analytics: Query pre-built analytics
9
- * - swarm_query: Raw SQL for power users
10
- * - swarm_diagnose: Auto-diagnosis for epic/task
11
- * - swarm_insights: Generate learning insights
12
- */
13
-
14
- import { tool } from "@opencode-ai/plugin";
15
- import {
16
- agentActivity,
17
- checkpointFrequency,
18
- failedDecompositions,
19
- getSwarmMailLibSQL,
20
- humanFeedback,
21
- lockContention,
22
- messageLatency,
23
- recoverySuccess,
24
- scopeViolations,
25
- strategySuccessRates,
26
- taskDuration,
27
- type AnalyticsQuery,
28
- type SwarmMailAdapter,
29
- } from "swarm-mail";
30
-
31
- // ============================================================================
32
- // Types
33
- // ============================================================================
34
-
35
- interface ToolContext {
36
- sessionID: string;
37
- }
38
-
39
- export interface SwarmAnalyticsArgs {
40
- query:
41
- | "failed-decompositions"
42
- | "strategy-success-rates"
43
- | "lock-contention"
44
- | "agent-activity"
45
- | "message-latency"
46
- | "scope-violations"
47
- | "task-duration"
48
- | "checkpoint-frequency"
49
- | "recovery-success"
50
- | "human-feedback";
51
- since?: string; // "7d", "24h", "1h"
52
- format?: "json" | "summary";
53
- }
54
-
55
- export interface SwarmQueryArgs {
56
- sql: string;
57
- format?: "json" | "table";
58
- }
59
-
60
- export interface SwarmDiagnoseArgs {
61
- epic_id?: string;
62
- bead_id?: string;
63
- include?: Array<
64
- "blockers" | "conflicts" | "slow_tasks" | "errors" | "timeline"
65
- >;
66
- }
67
-
68
- export interface SwarmInsightsArgs {
69
- scope: "epic" | "project" | "recent";
70
- epic_id?: string;
71
- metrics: Array<"success_rate" | "avg_duration" | "conflict_rate" | "retry_rate">;
72
- }
73
-
74
- // ============================================================================
75
- // Helper Functions
76
- // ============================================================================
77
-
78
- /**
79
- * Parse "since" time string to milliseconds
80
- * @param since - Time string like "7d", "24h", "1h"
81
- * @returns Timestamp in milliseconds
82
- */
83
- function parseSince(since: string): number {
84
- const now = Date.now();
85
- const match = since.match(/^(\d+)([dhm])$/);
86
- if (!match) {
87
- throw new Error(`Invalid since format: ${since}. Use "7d", "24h", or "1h"`);
88
- }
89
-
90
- const [, value, unit] = match;
91
- const num = Number.parseInt(value, 10);
92
-
93
- switch (unit) {
94
- case "d":
95
- return now - num * 24 * 60 * 60 * 1000;
96
- case "h":
97
- return now - num * 60 * 60 * 1000;
98
- case "m":
99
- return now - num * 60 * 1000;
100
- default:
101
- throw new Error(`Unknown unit: ${unit}`);
102
- }
103
- }
104
-
105
- /**
106
- * Execute analytics query and return results
107
- */
108
- async function executeQuery(
109
- swarmMail: SwarmMailAdapter,
110
- query: AnalyticsQuery,
111
- ): Promise<unknown[]> {
112
- // Get the underlying database adapter
113
- const db = await swarmMail.getDatabase();
114
-
115
- // Execute the query
116
- const result = await db.query(
117
- query.sql,
118
- Object.values(query.parameters || {}),
119
- );
120
-
121
- return result.rows as unknown[];
122
- }
123
-
124
- /**
125
- * Format results as summary (context-efficient)
126
- */
127
- function formatSummary(
128
- queryType: string,
129
- results: unknown[],
130
- ): string {
131
- if (results.length === 0) {
132
- return `No ${queryType} data found.`;
133
- }
134
-
135
- const count = results.length;
136
- const preview = results.slice(0, 3);
137
-
138
- return `${queryType}: ${count} result(s). Top 3: ${JSON.stringify(preview, null, 2).slice(0, 400)}`;
139
- }
140
-
141
- /**
142
- * Cap results at max 50 rows
143
- */
144
- function capResults(results: unknown[]): unknown[] {
145
- return results.slice(0, 50);
146
- }
147
-
148
- // ============================================================================
149
- // Tools
150
- // ============================================================================
151
-
152
- /**
153
- * swarm_analytics - Query pre-built analytics
154
- *
155
- * Provides access to 10 pre-built analytics queries for swarm coordination.
156
- */
157
- const swarm_analytics = tool({
158
- description:
159
- "Query pre-built analytics for swarm coordination. Returns structured data about failed decompositions, strategy success rates, lock contention, agent activity, message latency, scope violations, task duration, checkpoint frequency, recovery success, and human feedback.",
160
- args: {
161
- query: tool.schema
162
- .enum([
163
- "failed-decompositions",
164
- "strategy-success-rates",
165
- "lock-contention",
166
- "agent-activity",
167
- "message-latency",
168
- "scope-violations",
169
- "task-duration",
170
- "checkpoint-frequency",
171
- "recovery-success",
172
- "human-feedback",
173
- ])
174
- .describe("Type of analytics query to run"),
175
- since: tool.schema
176
- .string()
177
- .optional()
178
- .describe("Time filter: '7d', '24h', '1h' (optional)"),
179
- format: tool.schema
180
- .enum(["json", "summary"])
181
- .optional()
182
- .describe("Output format: 'json' (default) or 'summary' (context-efficient)"),
183
- },
184
- async execute(args: SwarmAnalyticsArgs): Promise<string> {
185
- try {
186
- const projectPath = process.cwd(); // TODO: Get from session state
187
- const db = await getSwarmMailLibSQL(projectPath);
188
-
189
- // Build filters
190
- const filters: Record<string, string | number> = {
191
- project_key: projectPath,
192
- };
193
-
194
- if (args.since) {
195
- filters.since = parseSince(args.since);
196
- }
197
-
198
- // Map query type to query function or object
199
- let query: AnalyticsQuery;
200
- switch (args.query) {
201
- case "failed-decompositions":
202
- query = failedDecompositions(filters);
203
- break;
204
- case "strategy-success-rates":
205
- query = strategySuccessRates(filters);
206
- break;
207
- case "lock-contention":
208
- query = lockContention(filters);
209
- break;
210
- case "agent-activity":
211
- query = agentActivity(filters);
212
- break;
213
- case "message-latency":
214
- query = messageLatency(filters);
215
- break;
216
- case "scope-violations":
217
- query = scopeViolations.buildQuery
218
- ? scopeViolations.buildQuery(filters)
219
- : scopeViolations;
220
- break;
221
- case "task-duration":
222
- query = taskDuration.buildQuery
223
- ? taskDuration.buildQuery(filters)
224
- : taskDuration;
225
- break;
226
- case "checkpoint-frequency":
227
- query = checkpointFrequency.buildQuery
228
- ? checkpointFrequency.buildQuery(filters)
229
- : checkpointFrequency;
230
- break;
231
- case "recovery-success":
232
- query = recoverySuccess.buildQuery
233
- ? recoverySuccess.buildQuery(filters)
234
- : recoverySuccess;
235
- break;
236
- case "human-feedback":
237
- query = humanFeedback.buildQuery
238
- ? humanFeedback.buildQuery(filters)
239
- : humanFeedback;
240
- break;
241
- default:
242
- return JSON.stringify({
243
- error: `Unknown query type: ${args.query}`,
244
- });
245
- }
246
-
247
- // Execute query
248
- const results = await executeQuery(db, query);
249
-
250
- // Format output
251
- if (args.format === "summary") {
252
- return formatSummary(args.query, results);
253
- }
254
-
255
- return JSON.stringify({
256
- query: args.query,
257
- filters,
258
- count: results.length,
259
- results,
260
- }, null, 2);
261
- } catch (error) {
262
- return JSON.stringify({
263
- error: error instanceof Error ? error.message : String(error),
264
- });
265
- }
266
- },
267
- });
268
-
269
- /**
270
- * swarm_query - Raw SQL for power users
271
- *
272
- * Execute arbitrary SQL queries with context safety (max 50 rows).
273
- */
274
- const swarm_query = tool({
275
- description:
276
- "Execute raw SQL queries against the swarm event store. Context-safe: results capped at 50 rows. Useful for custom analytics and debugging.",
277
- args: {
278
- sql: tool.schema
279
- .string()
280
- .describe("SQL query to execute (SELECT only for safety)"),
281
- format: tool.schema
282
- .enum(["json", "table"])
283
- .optional()
284
- .describe("Output format: 'json' (default) or 'table' (visual)"),
285
- },
286
- async execute(args: SwarmQueryArgs): Promise<string> {
287
- try {
288
- const projectPath = process.cwd(); // TODO: Get from session state
289
- const swarmMail = await getSwarmMailLibSQL(projectPath);
290
- const db = await swarmMail.getDatabase();
291
-
292
- // Safety: Only allow SELECT queries
293
- if (!args.sql.trim().toLowerCase().startsWith("select")) {
294
- return JSON.stringify({
295
- error: "Only SELECT queries are allowed for safety",
296
- });
297
- }
298
-
299
- // Execute query via adapter
300
- const result = await db.query(args.sql, []);
301
- const rows = result.rows as unknown[];
302
-
303
- // Cap at 50 rows
304
- const cappedRows = capResults(rows);
305
-
306
- // Format output
307
- if (args.format === "table") {
308
- // Simple table format
309
- if (cappedRows.length === 0) {
310
- return "No results";
311
- }
312
-
313
- const headers = Object.keys(cappedRows[0] as Record<string, unknown>);
314
- const headerRow = headers.join(" | ");
315
- const separator = headers.map(() => "---").join(" | ");
316
- const dataRows = cappedRows.map((row) =>
317
- headers.map((h) => (row as Record<string, unknown>)[h]).join(" | "),
318
- );
319
-
320
- return [headerRow, separator, ...dataRows].join("\n");
321
- }
322
-
323
- return JSON.stringify({
324
- count: cappedRows.length,
325
- total: rows.length,
326
- capped: rows.length > 50,
327
- results: cappedRows,
328
- }, null, 2);
329
- } catch (error) {
330
- return JSON.stringify({
331
- error: error instanceof Error ? error.message : String(error),
332
- });
333
- }
334
- },
335
- });
336
-
337
- /**
338
- * swarm_diagnose - Auto-diagnosis for epic/task
339
- *
340
- * Analyzes a specific epic or task and returns structured diagnosis.
341
- */
342
- const swarm_diagnose = tool({
343
- description:
344
- "Auto-diagnose issues for a specific epic or task. Returns structured diagnosis with blockers, conflicts, slow tasks, errors, and timeline.",
345
- args: {
346
- epic_id: tool.schema
347
- .string()
348
- .optional()
349
- .describe("Epic ID to diagnose"),
350
- bead_id: tool.schema
351
- .string()
352
- .optional()
353
- .describe("Task ID to diagnose"),
354
- include: tool.schema
355
- .array(
356
- tool.schema.enum([
357
- "blockers",
358
- "conflicts",
359
- "slow_tasks",
360
- "errors",
361
- "timeline",
362
- ]),
363
- )
364
- .optional()
365
- .describe("What to include in diagnosis (default: all)"),
366
- },
367
- async execute(args: SwarmDiagnoseArgs): Promise<string> {
368
- try {
369
- const projectPath = process.cwd();
370
- const swarmMail = await getSwarmMailLibSQL(projectPath);
371
-
372
- // Get the underlying database adapter
373
- const db = await swarmMail.getDatabase();
374
-
375
- const diagnosis: Array<{ type: string; message: string; severity: string }> = [];
376
- const include = args.include || [
377
- "blockers",
378
- "conflicts",
379
- "slow_tasks",
380
- "errors",
381
- "timeline",
382
- ];
383
-
384
- // Query for blockers
385
- if (include.includes("blockers")) {
386
- const blockerQuery = `
387
- SELECT json_extract(data, '$.agent_name') as agent,
388
- json_extract(data, '$.bead_id') as bead_id,
389
- timestamp
390
- FROM events
391
- WHERE type = 'task_blocked'
392
- ${args.epic_id ? "AND json_extract(data, '$.epic_id') = ?" : ""}
393
- ${args.bead_id ? "AND json_extract(data, '$.bead_id') = ?" : ""}
394
- ORDER BY timestamp DESC
395
- LIMIT 10
396
- `;
397
-
398
- const params = [];
399
- if (args.epic_id) params.push(args.epic_id);
400
- if (args.bead_id) params.push(args.bead_id);
401
-
402
- const blockers = await db.query(blockerQuery, params);
403
- if (blockers.rows.length > 0) {
404
- diagnosis.push({
405
- type: "blockers",
406
- message: `Found ${blockers.rows.length} blocked task(s)`,
407
- severity: "high",
408
- });
409
- }
410
- }
411
-
412
- // Query for errors
413
- if (include.includes("errors")) {
414
- const errorQuery = `
415
- SELECT type, json_extract(data, '$.error_count') as error_count
416
- FROM events
417
- WHERE type = 'subtask_outcome'
418
- AND json_extract(data, '$.success') = 'false'
419
- ${args.epic_id ? "AND json_extract(data, '$.epic_id') = ?" : ""}
420
- ${args.bead_id ? "AND json_extract(data, '$.bead_id') = ?" : ""}
421
- LIMIT 10
422
- `;
423
-
424
- const params = [];
425
- if (args.epic_id) params.push(args.epic_id);
426
- if (args.bead_id) params.push(args.bead_id);
427
-
428
- const errors = await db.query(errorQuery, params);
429
- if (errors.rows.length > 0) {
430
- diagnosis.push({
431
- type: "errors",
432
- message: `Found ${errors.rows.length} failed task(s)`,
433
- severity: "high",
434
- });
435
- }
436
- }
437
-
438
- // Build timeline if requested
439
- let timeline: unknown[] = [];
440
- if (include.includes("timeline")) {
441
- const timelineQuery = `
442
- SELECT timestamp, type, json_extract(data, '$.agent_name') as agent
443
- FROM events
444
- ${args.epic_id ? "WHERE json_extract(data, '$.epic_id') = ?" : ""}
445
- ${args.bead_id ? (args.epic_id ? "AND" : "WHERE") + " json_extract(data, '$.bead_id') = ?" : ""}
446
- ORDER BY timestamp DESC
447
- LIMIT 20
448
- `;
449
-
450
- const params = [];
451
- if (args.epic_id) params.push(args.epic_id);
452
- if (args.bead_id) params.push(args.bead_id);
453
-
454
- const events = await db.query(timelineQuery, params);
455
- timeline = events.rows;
456
- }
457
-
458
- return JSON.stringify({
459
- epic_id: args.epic_id,
460
- bead_id: args.bead_id,
461
- diagnosis,
462
- timeline: include.includes("timeline") ? timeline : undefined,
463
- }, null, 2);
464
- } catch (error) {
465
- return JSON.stringify({
466
- error: error instanceof Error ? error.message : String(error),
467
- });
468
- }
469
- },
470
- });
471
-
472
- /**
473
- * swarm_insights - Generate learning insights
474
- *
475
- * Analyzes metrics and generates actionable insights.
476
- */
477
- const swarm_insights = tool({
478
- description:
479
- "Generate learning insights from swarm coordination metrics. Analyzes success rates, duration, conflicts, and retries to provide actionable recommendations.",
480
- args: {
481
- scope: tool.schema
482
- .enum(["epic", "project", "recent"])
483
- .describe("Scope of analysis: 'epic', 'project', or 'recent'"),
484
- epic_id: tool.schema
485
- .string()
486
- .optional()
487
- .describe("Epic ID (required if scope='epic')"),
488
- metrics: tool.schema
489
- .array(
490
- tool.schema.enum([
491
- "success_rate",
492
- "avg_duration",
493
- "conflict_rate",
494
- "retry_rate",
495
- ]),
496
- )
497
- .describe("Metrics to analyze"),
498
- },
499
- async execute(args: SwarmInsightsArgs): Promise<string> {
500
- try {
501
- // Validate args
502
- if (args.scope === "epic" && !args.epic_id) {
503
- return JSON.stringify({
504
- error: "epic_id is required when scope='epic'",
505
- });
506
- }
507
-
508
- const projectPath = process.cwd();
509
- const swarmMail = await getSwarmMailLibSQL(projectPath);
510
- const db = await swarmMail.getDatabase();
511
-
512
- const insights: Array<{
513
- metric: string;
514
- value: string | number;
515
- insight: string;
516
- }> = [];
517
-
518
- // Calculate success rate
519
- if (args.metrics.includes("success_rate")) {
520
- const query = `
521
- SELECT
522
- SUM(CASE WHEN json_extract(data, '$.success') = 'true' THEN 1 ELSE 0 END) as successes,
523
- COUNT(*) as total
524
- FROM events
525
- WHERE type = 'subtask_outcome'
526
- ${args.epic_id ? "AND json_extract(data, '$.epic_id') = ?" : ""}
527
- `;
528
-
529
- const result = await db.query(query, args.epic_id ? [args.epic_id] : []);
530
- const row = result.rows[0] as { successes: number; total: number };
531
-
532
- if (row && row.total > 0) {
533
- const rate = (row.successes / row.total) * 100;
534
- insights.push({
535
- metric: "success_rate",
536
- value: `${rate.toFixed(1)}%`,
537
- insight:
538
- rate < 50
539
- ? "Low success rate - review decomposition strategy"
540
- : rate < 80
541
- ? "Moderate success rate - monitor for patterns"
542
- : "Good success rate - maintain current approach",
543
- });
544
- }
545
- }
546
-
547
- // Calculate average duration
548
- if (args.metrics.includes("avg_duration")) {
549
- const query = `
550
- SELECT AVG(CAST(json_extract(data, '$.duration_ms') AS REAL)) as avg_duration
551
- FROM events
552
- WHERE type = 'subtask_outcome'
553
- ${args.epic_id ? "AND json_extract(data, '$.epic_id') = ?" : ""}
554
- `;
555
-
556
- const result = await db.query(query, args.epic_id ? [args.epic_id] : []);
557
- const row = result.rows[0] as { avg_duration: number };
558
-
559
- if (row?.avg_duration) {
560
- const avgMinutes = (row.avg_duration / 60000).toFixed(1);
561
- insights.push({
562
- metric: "avg_duration",
563
- value: `${avgMinutes} min`,
564
- insight:
565
- row.avg_duration > 600000
566
- ? "Tasks taking >10min - consider smaller decomposition"
567
- : "Task duration is reasonable",
568
- });
569
- }
570
- }
571
-
572
- return JSON.stringify({
573
- scope: args.scope,
574
- epic_id: args.epic_id,
575
- insights,
576
- }, null, 2);
577
- } catch (error) {
578
- return JSON.stringify({
579
- error: error instanceof Error ? error.message : String(error),
580
- });
581
- }
582
- },
583
- });
584
-
585
- // ============================================================================
586
- // Stats CLI Helpers (exported for bin/swarm.ts)
587
- // ============================================================================
588
-
589
- export interface SwarmStatsData {
590
- overall: {
591
- totalSwarms: number;
592
- successRate: number;
593
- avgDurationMin: number;
594
- };
595
- byStrategy: Array<{
596
- strategy: string;
597
- total: number;
598
- successRate: number;
599
- successes: number;
600
- }>;
601
- coordinator: {
602
- violationRate: number;
603
- spawnEfficiency: number;
604
- reviewThoroughness: number;
605
- };
606
- recentDays: number;
607
- }
608
-
609
- /**
610
- * Format swarm stats as beautiful CLI output with box drawing
611
- */
612
- export function formatSwarmStats(stats: SwarmStatsData): string {
613
- const lines: string[] = [];
614
-
615
- // Header with ASCII art
616
- lines.push("┌─────────────────────────────────────────┐");
617
- lines.push("│ 🐝 SWARM STATISTICS 🐝 │");
618
- lines.push("├─────────────────────────────────────────┤");
619
-
620
- // Overall stats
621
- const totalStr = stats.overall.totalSwarms.toString().padEnd(4);
622
- const rateStr = `${Math.round(stats.overall.successRate)}%`.padStart(3);
623
- lines.push(`│ Total Swarms: ${totalStr} Success: ${rateStr} │`);
624
-
625
- const durationStr = stats.overall.avgDurationMin.toFixed(1);
626
- lines.push(`│ Avg Duration: ${durationStr}min${" ".repeat(23 - durationStr.length)}│`);
627
- lines.push("├─────────────────────────────────────────┤");
628
-
629
- // Strategy breakdown
630
- lines.push("│ BY STRATEGY │");
631
- if (stats.byStrategy.length === 0) {
632
- lines.push("│ ├─ No data yet │");
633
- } else {
634
- for (const strategy of stats.byStrategy) {
635
- const label = strategy.strategy.padEnd(15);
636
- const rate = `${Math.round(strategy.successRate)}%`.padStart(4);
637
- const counts = `(${strategy.successes}/${strategy.total})`.padEnd(8);
638
- lines.push(`│ ├─ ${label} ${rate} ${counts} │`);
639
- }
640
- }
641
- lines.push("├─────────────────────────────────────────┤");
642
-
643
- // Coordinator health
644
- lines.push("│ COORDINATOR HEALTH │");
645
- const violationStr = `${Math.round(stats.coordinator.violationRate)}%`.padStart(3);
646
- const spawnStr = `${Math.round(stats.coordinator.spawnEfficiency)}%`.padStart(4);
647
- const reviewStr = `${Math.round(stats.coordinator.reviewThoroughness)}%`.padStart(3);
648
-
649
- lines.push(`│ Violation Rate: ${violationStr}${" ".repeat(19 - violationStr.length)}│`);
650
- lines.push(`│ Spawn Efficiency: ${spawnStr}${" ".repeat(17 - spawnStr.length)}│`);
651
- lines.push(`│ Review Rate: ${reviewStr}${" ".repeat(19 - reviewStr.length)}│`);
652
- lines.push("└─────────────────────────────────────────┘");
653
-
654
- lines.push("");
655
- lines.push(`📊 Stats for last ${stats.recentDays} days`);
656
-
657
- return lines.join("\n");
658
- }
659
-
660
- /**
661
- * Parse time period string like "7d", "24h", "30m" to timestamp
662
- */
663
- export function parseTimePeriod(period: string): number {
664
- const match = period.match(/^(\d+)([dhm])$/);
665
- if (!match) {
666
- throw new Error(
667
- `Invalid time period format: ${period}. Use "7d", "24h", or "30m"`,
668
- );
669
- }
670
-
671
- const [, value, unit] = match;
672
- const num = Number.parseInt(value, 10);
673
- const now = Date.now();
674
-
675
- switch (unit) {
676
- case "d":
677
- return now - num * 24 * 60 * 60 * 1000;
678
- case "h":
679
- return now - num * 60 * 60 * 1000;
680
- case "m":
681
- return now - num * 60 * 1000;
682
- default:
683
- throw new Error(`Unknown time unit: ${unit}`);
684
- }
685
- }
686
-
687
- /**
688
- * Aggregate swarm outcomes by strategy
689
- */
690
- export function aggregateByStrategy(
691
- outcomes: Array<{ strategy: string | null; success: boolean }>,
692
- ): Array<{ strategy: string; total: number; successRate: number; successes: number }> {
693
- const grouped: Record<string, { total: number; successes: number }> = {};
694
-
695
- for (const outcome of outcomes) {
696
- const strategy = outcome.strategy || "unknown";
697
- if (!grouped[strategy]) {
698
- grouped[strategy] = { total: 0, successes: 0 };
699
- }
700
- grouped[strategy].total++;
701
- if (outcome.success) {
702
- grouped[strategy].successes++;
703
- }
704
- }
705
-
706
- return Object.entries(grouped).map(([strategy, stats]) => ({
707
- strategy,
708
- total: stats.total,
709
- successes: stats.successes,
710
- successRate: (stats.successes / stats.total) * 100,
711
- }));
712
- }
713
-
714
- // ============================================================================
715
- // History CLI Helpers (exported for bin/swarm.ts)
716
- // ============================================================================
717
-
718
- export interface SwarmHistoryRecord {
719
- epic_id: string;
720
- epic_title: string;
721
- strategy: string;
722
- timestamp: string;
723
- overall_success: boolean;
724
- task_count: number;
725
- completed_count: number;
726
- }
727
-
728
- /**
729
- * Query swarm history from eval_records table
730
- */
731
- export async function querySwarmHistory(
732
- projectPath: string,
733
- options?: {
734
- limit?: number;
735
- status?: "success" | "failed" | "in_progress";
736
- strategy?: "file-based" | "feature-based" | "risk-based";
737
- },
738
- ): Promise<SwarmHistoryRecord[]> {
739
- const swarmMail = await getSwarmMailLibSQL(projectPath);
740
- const db = await swarmMail.getDatabase();
741
-
742
- // Build WHERE clause
743
- const conditions: string[] = [];
744
- const params: (string | number)[] = [];
745
-
746
- if (options?.status) {
747
- switch (options.status) {
748
- case "success":
749
- conditions.push("json_extract(data, '$.overall_success') = 'true'");
750
- break;
751
- case "failed":
752
- conditions.push(
753
- "json_extract(data, '$.overall_success') = 'false' AND json_extract(data, '$.completed_count') = json_extract(data, '$.task_count')",
754
- );
755
- break;
756
- case "in_progress":
757
- conditions.push(
758
- "json_extract(data, '$.completed_count') < json_extract(data, '$.task_count')",
759
- );
760
- break;
761
- }
762
- }
763
-
764
- if (options?.strategy) {
765
- conditions.push("json_extract(data, '$.strategy') = ?");
766
- params.push(options.strategy);
767
- }
768
-
769
- const whereClause = conditions.length > 0 ? `AND ${conditions.join(" AND ")}` : "";
770
- const limit = options?.limit || 10;
771
-
772
- const query = `
773
- SELECT
774
- json_extract(data, '$.epic_id') as epic_id,
775
- json_extract(data, '$.task') as epic_title,
776
- json_extract(data, '$.strategy') as strategy,
777
- timestamp,
778
- json_extract(data, '$.overall_success') as overall_success,
779
- CAST(json_extract(data, '$.task_count') AS INTEGER) as task_count,
780
- CAST(json_extract(data, '$.completed_count') AS INTEGER) as completed_count
781
- FROM events
782
- WHERE type = 'eval_finalized'
783
- ${whereClause}
784
- ORDER BY timestamp DESC
785
- LIMIT ?
786
- `;
787
-
788
- params.push(limit);
789
-
790
- const result = await db.query(query, params);
791
- const rows = result.rows as unknown[];
792
-
793
- return rows.map((row) => {
794
- const r = row as Record<string, unknown>;
795
- return {
796
- epic_id: String(r.epic_id || ""),
797
- epic_title: String(r.epic_title || "Unknown"),
798
- strategy: String(r.strategy || "unknown"),
799
- timestamp: String(r.timestamp || new Date().toISOString()),
800
- overall_success: String(r.overall_success) === "true",
801
- task_count: Number(r.task_count) || 0,
802
- completed_count: Number(r.completed_count) || 0,
803
- };
804
- });
805
- }
806
-
807
- /**
808
- * Format relative time (e.g., "2h ago", "1d ago")
809
- */
810
- export function formatRelativeTime(timestamp: string): string {
811
- const now = Date.now();
812
- const then = new Date(timestamp).getTime();
813
- const diffMs = now - then;
814
-
815
- const minutes = Math.floor(diffMs / 60000);
816
- const hours = Math.floor(diffMs / 3600000);
817
- const days = Math.floor(diffMs / 86400000);
818
-
819
- if (minutes < 60) return `${minutes}m ago`;
820
- if (hours < 24) return `${hours}h ago`;
821
- return `${days}d ago`;
822
- }
823
-
824
- /**
825
- * Format swarm history as beautiful CLI table
826
- */
827
- export function formatSwarmHistory(records: SwarmHistoryRecord[]): string {
828
- if (records.length === 0) {
829
- return "No swarm history found";
830
- }
831
-
832
- const rows = records.map((r) => ({
833
- time: formatRelativeTime(r.timestamp),
834
- status: r.overall_success ? "✅" : "❌",
835
- title:
836
- r.epic_title.length > 30 ? `${r.epic_title.slice(0, 27)}...` : r.epic_title,
837
- strategy: r.strategy,
838
- tasks: `${r.completed_count}/${r.task_count} tasks`,
839
- }));
840
-
841
- // Box drawing characters
842
- const lines: string[] = [];
843
- lines.push("┌─────────────────────────────────────────────────────────────┐");
844
- lines.push("│ SWARM HISTORY │");
845
- lines.push("├─────────────────────────────────────────────────────────────┤");
846
-
847
- for (const row of rows) {
848
- const statusCol = `${row.time.padEnd(8)} ${row.status}`;
849
- const titleCol = row.title.padEnd(32);
850
- const strategyCol = row.strategy.padEnd(13);
851
- const tasksCol = row.tasks;
852
-
853
- const line = `│ ${statusCol} ${titleCol} ${strategyCol} ${tasksCol.padEnd(3)} │`;
854
- lines.push(line);
855
- }
856
-
857
- lines.push("└─────────────────────────────────────────────────────────────┘");
858
-
859
- return lines.join("\n");
860
- }
861
-
862
- // ============================================================================
863
- // Exports
864
- // ============================================================================
865
-
866
- export const observabilityTools = {
867
- swarm_analytics,
868
- swarm_query,
869
- swarm_diagnose,
870
- swarm_insights,
871
- };