opencode-swarm-plugin 0.31.7 → 0.33.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.turbo/turbo-build.log +4 -4
- package/.turbo/turbo-test.log +324 -316
- package/CHANGELOG.md +394 -0
- package/README.md +129 -181
- package/bin/swarm.test.ts +31 -0
- package/bin/swarm.ts +635 -140
- package/dist/compaction-hook.d.ts +1 -1
- package/dist/compaction-hook.d.ts.map +1 -1
- package/dist/hive.d.ts.map +1 -1
- package/dist/index.d.ts +17 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +653 -139
- package/dist/memory-tools.d.ts.map +1 -1
- package/dist/memory.d.ts +5 -4
- package/dist/memory.d.ts.map +1 -1
- package/dist/observability-tools.d.ts +116 -0
- package/dist/observability-tools.d.ts.map +1 -0
- package/dist/plugin.js +648 -136
- package/dist/skills.d.ts.map +1 -1
- package/dist/swarm-orchestrate.d.ts +29 -5
- package/dist/swarm-orchestrate.d.ts.map +1 -1
- package/dist/swarm-prompts.d.ts +66 -0
- package/dist/swarm-prompts.d.ts.map +1 -1
- package/dist/swarm.d.ts +17 -2
- package/dist/swarm.d.ts.map +1 -1
- package/evals/lib/{data-loader.test.ts → data-loader.evalite-test.ts} +7 -6
- package/evals/lib/data-loader.ts +1 -1
- package/evals/scorers/{outcome-scorers.test.ts → outcome-scorers.evalite-test.ts} +1 -1
- package/examples/plugin-wrapper-template.ts +316 -12
- package/global-skills/swarm-coordination/SKILL.md +118 -8
- package/package.json +3 -2
- package/src/compaction-hook.ts +5 -3
- package/src/hive.integration.test.ts +83 -1
- package/src/hive.ts +37 -12
- package/src/index.ts +25 -1
- package/src/mandate-storage.integration.test.ts +601 -0
- package/src/memory-tools.ts +6 -4
- package/src/memory.integration.test.ts +117 -49
- package/src/memory.test.ts +41 -217
- package/src/memory.ts +12 -8
- package/src/observability-tools.test.ts +346 -0
- package/src/observability-tools.ts +594 -0
- package/src/repo-crawl.integration.test.ts +441 -0
- package/src/skills.integration.test.ts +1192 -0
- package/src/skills.test.ts +42 -1
- package/src/skills.ts +8 -4
- package/src/structured.integration.test.ts +817 -0
- package/src/swarm-deferred.integration.test.ts +157 -0
- package/src/swarm-deferred.test.ts +38 -0
- package/src/swarm-mail.integration.test.ts +15 -19
- package/src/swarm-orchestrate.integration.test.ts +282 -0
- package/src/swarm-orchestrate.test.ts +123 -0
- package/src/swarm-orchestrate.ts +279 -201
- package/src/swarm-prompts.test.ts +481 -0
- package/src/swarm-prompts.ts +297 -0
- package/src/swarm-research.integration.test.ts +544 -0
- package/src/swarm-research.test.ts +698 -0
- package/src/swarm-research.ts +472 -0
- package/src/swarm-review.integration.test.ts +290 -0
- package/src/swarm.integration.test.ts +23 -20
- package/src/swarm.ts +6 -3
- package/src/tool-adapter.integration.test.ts +1221 -0
|
@@ -0,0 +1,594 @@
|
|
|
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
|
+
// Exports
|
|
587
|
+
// ============================================================================
|
|
588
|
+
|
|
589
|
+
export const observabilityTools = {
|
|
590
|
+
swarm_analytics,
|
|
591
|
+
swarm_query,
|
|
592
|
+
swarm_diagnose,
|
|
593
|
+
swarm_insights,
|
|
594
|
+
};
|