opencode-swarm-plugin 0.44.0 → 0.44.2

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 (215) hide show
  1. package/bin/swarm.serve.test.ts +6 -4
  2. package/bin/swarm.ts +18 -12
  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/hive.js +14834 -0
  7. package/dist/index.d.ts +18 -0
  8. package/dist/index.d.ts.map +1 -1
  9. package/dist/index.js +7743 -62593
  10. package/dist/plugin.js +24052 -78907
  11. package/dist/swarm-orchestrate.d.ts.map +1 -1
  12. package/dist/swarm-prompts.d.ts.map +1 -1
  13. package/dist/swarm-prompts.js +39407 -0
  14. package/dist/swarm-review.d.ts.map +1 -1
  15. package/dist/swarm-validation.d.ts +127 -0
  16. package/dist/swarm-validation.d.ts.map +1 -0
  17. package/dist/validators/index.d.ts +7 -0
  18. package/dist/validators/index.d.ts.map +1 -0
  19. package/dist/validators/schema-validator.d.ts +58 -0
  20. package/dist/validators/schema-validator.d.ts.map +1 -0
  21. package/package.json +17 -5
  22. package/.changeset/swarm-insights-data-layer.md +0 -63
  23. package/.hive/analysis/eval-failure-analysis-2025-12-25.md +0 -331
  24. package/.hive/analysis/session-data-quality-audit.md +0 -320
  25. package/.hive/eval-results.json +0 -483
  26. package/.hive/issues.jsonl +0 -138
  27. package/.hive/memories.jsonl +0 -729
  28. package/.opencode/eval-history.jsonl +0 -327
  29. package/.turbo/turbo-build.log +0 -9
  30. package/CHANGELOG.md +0 -2286
  31. package/SCORER-ANALYSIS.md +0 -598
  32. package/docs/analysis/subagent-coordination-patterns.md +0 -902
  33. package/docs/analysis-socratic-planner-pattern.md +0 -504
  34. package/docs/planning/ADR-001-monorepo-structure.md +0 -171
  35. package/docs/planning/ADR-002-package-extraction.md +0 -393
  36. package/docs/planning/ADR-003-performance-improvements.md +0 -451
  37. package/docs/planning/ADR-004-message-queue-features.md +0 -187
  38. package/docs/planning/ADR-005-devtools-observability.md +0 -202
  39. package/docs/planning/ADR-007-swarm-enhancements-worktree-review.md +0 -168
  40. package/docs/planning/ADR-008-worker-handoff-protocol.md +0 -293
  41. package/docs/planning/ADR-009-oh-my-opencode-patterns.md +0 -353
  42. package/docs/planning/ADR-010-cass-inhousing.md +0 -1215
  43. package/docs/planning/ROADMAP.md +0 -368
  44. package/docs/semantic-memory-cli-syntax.md +0 -123
  45. package/docs/swarm-mail-architecture.md +0 -1147
  46. package/docs/testing/context-recovery-test.md +0 -470
  47. package/evals/ARCHITECTURE.md +0 -1189
  48. package/evals/README.md +0 -768
  49. package/evals/compaction-prompt.eval.ts +0 -149
  50. package/evals/compaction-resumption.eval.ts +0 -289
  51. package/evals/coordinator-behavior.eval.ts +0 -307
  52. package/evals/coordinator-session.eval.ts +0 -154
  53. package/evals/evalite.config.ts.bak +0 -15
  54. package/evals/example.eval.ts +0 -31
  55. package/evals/fixtures/cass-baseline.ts +0 -217
  56. package/evals/fixtures/compaction-cases.ts +0 -350
  57. package/evals/fixtures/compaction-prompt-cases.ts +0 -311
  58. package/evals/fixtures/coordinator-sessions.ts +0 -328
  59. package/evals/fixtures/decomposition-cases.ts +0 -105
  60. package/evals/lib/compaction-loader.test.ts +0 -248
  61. package/evals/lib/compaction-loader.ts +0 -320
  62. package/evals/lib/data-loader.evalite-test.ts +0 -289
  63. package/evals/lib/data-loader.test.ts +0 -345
  64. package/evals/lib/data-loader.ts +0 -281
  65. package/evals/lib/llm.ts +0 -115
  66. package/evals/scorers/compaction-prompt-scorers.ts +0 -145
  67. package/evals/scorers/compaction-scorers.ts +0 -305
  68. package/evals/scorers/coordinator-discipline.evalite-test.ts +0 -539
  69. package/evals/scorers/coordinator-discipline.ts +0 -325
  70. package/evals/scorers/index.test.ts +0 -146
  71. package/evals/scorers/index.ts +0 -328
  72. package/evals/scorers/outcome-scorers.evalite-test.ts +0 -27
  73. package/evals/scorers/outcome-scorers.ts +0 -349
  74. package/evals/swarm-decomposition.eval.ts +0 -121
  75. package/examples/commands/swarm.md +0 -745
  76. package/examples/plugin-wrapper-template.ts +0 -2515
  77. package/examples/skills/hive-workflow/SKILL.md +0 -212
  78. package/examples/skills/skill-creator/SKILL.md +0 -223
  79. package/examples/skills/swarm-coordination/SKILL.md +0 -292
  80. package/global-skills/cli-builder/SKILL.md +0 -344
  81. package/global-skills/cli-builder/references/advanced-patterns.md +0 -244
  82. package/global-skills/learning-systems/SKILL.md +0 -644
  83. package/global-skills/skill-creator/LICENSE.txt +0 -202
  84. package/global-skills/skill-creator/SKILL.md +0 -352
  85. package/global-skills/skill-creator/references/output-patterns.md +0 -82
  86. package/global-skills/skill-creator/references/workflows.md +0 -28
  87. package/global-skills/swarm-coordination/SKILL.md +0 -995
  88. package/global-skills/swarm-coordination/references/coordinator-patterns.md +0 -235
  89. package/global-skills/swarm-coordination/references/strategies.md +0 -138
  90. package/global-skills/system-design/SKILL.md +0 -213
  91. package/global-skills/testing-patterns/SKILL.md +0 -430
  92. package/global-skills/testing-patterns/references/dependency-breaking-catalog.md +0 -586
  93. package/opencode-swarm-plugin-0.30.7.tgz +0 -0
  94. package/opencode-swarm-plugin-0.31.0.tgz +0 -0
  95. package/scripts/cleanup-test-memories.ts +0 -346
  96. package/scripts/init-skill.ts +0 -222
  97. package/scripts/migrate-unknown-sessions.ts +0 -349
  98. package/scripts/validate-skill.ts +0 -204
  99. package/src/agent-mail.ts +0 -1724
  100. package/src/anti-patterns.test.ts +0 -1167
  101. package/src/anti-patterns.ts +0 -448
  102. package/src/compaction-capture.integration.test.ts +0 -257
  103. package/src/compaction-hook.test.ts +0 -838
  104. package/src/compaction-hook.ts +0 -1204
  105. package/src/compaction-observability.integration.test.ts +0 -139
  106. package/src/compaction-observability.test.ts +0 -187
  107. package/src/compaction-observability.ts +0 -324
  108. package/src/compaction-prompt-scorers.test.ts +0 -475
  109. package/src/compaction-prompt-scoring.ts +0 -300
  110. package/src/contributor-tools.test.ts +0 -133
  111. package/src/contributor-tools.ts +0 -201
  112. package/src/dashboard.test.ts +0 -611
  113. package/src/dashboard.ts +0 -462
  114. package/src/error-enrichment.test.ts +0 -403
  115. package/src/error-enrichment.ts +0 -219
  116. package/src/eval-capture.test.ts +0 -1015
  117. package/src/eval-capture.ts +0 -929
  118. package/src/eval-gates.test.ts +0 -306
  119. package/src/eval-gates.ts +0 -218
  120. package/src/eval-history.test.ts +0 -508
  121. package/src/eval-history.ts +0 -214
  122. package/src/eval-learning.test.ts +0 -378
  123. package/src/eval-learning.ts +0 -360
  124. package/src/eval-runner.test.ts +0 -223
  125. package/src/eval-runner.ts +0 -402
  126. package/src/export-tools.test.ts +0 -476
  127. package/src/export-tools.ts +0 -257
  128. package/src/hive.integration.test.ts +0 -2241
  129. package/src/hive.ts +0 -1628
  130. package/src/index.ts +0 -940
  131. package/src/learning.integration.test.ts +0 -1815
  132. package/src/learning.ts +0 -1079
  133. package/src/logger.test.ts +0 -189
  134. package/src/logger.ts +0 -135
  135. package/src/mandate-promotion.test.ts +0 -473
  136. package/src/mandate-promotion.ts +0 -239
  137. package/src/mandate-storage.integration.test.ts +0 -601
  138. package/src/mandate-storage.test.ts +0 -578
  139. package/src/mandate-storage.ts +0 -794
  140. package/src/mandates.ts +0 -540
  141. package/src/memory-tools.test.ts +0 -195
  142. package/src/memory-tools.ts +0 -344
  143. package/src/memory.integration.test.ts +0 -334
  144. package/src/memory.test.ts +0 -158
  145. package/src/memory.ts +0 -527
  146. package/src/model-selection.test.ts +0 -188
  147. package/src/model-selection.ts +0 -68
  148. package/src/observability-tools.test.ts +0 -359
  149. package/src/observability-tools.ts +0 -871
  150. package/src/output-guardrails.test.ts +0 -438
  151. package/src/output-guardrails.ts +0 -381
  152. package/src/pattern-maturity.test.ts +0 -1160
  153. package/src/pattern-maturity.ts +0 -525
  154. package/src/planning-guardrails.test.ts +0 -491
  155. package/src/planning-guardrails.ts +0 -438
  156. package/src/plugin.ts +0 -23
  157. package/src/post-compaction-tracker.test.ts +0 -251
  158. package/src/post-compaction-tracker.ts +0 -237
  159. package/src/query-tools.test.ts +0 -636
  160. package/src/query-tools.ts +0 -324
  161. package/src/rate-limiter.integration.test.ts +0 -466
  162. package/src/rate-limiter.ts +0 -774
  163. package/src/replay-tools.test.ts +0 -496
  164. package/src/replay-tools.ts +0 -240
  165. package/src/repo-crawl.integration.test.ts +0 -441
  166. package/src/repo-crawl.ts +0 -610
  167. package/src/schemas/cell-events.test.ts +0 -347
  168. package/src/schemas/cell-events.ts +0 -807
  169. package/src/schemas/cell.ts +0 -257
  170. package/src/schemas/evaluation.ts +0 -166
  171. package/src/schemas/index.test.ts +0 -199
  172. package/src/schemas/index.ts +0 -286
  173. package/src/schemas/mandate.ts +0 -232
  174. package/src/schemas/swarm-context.ts +0 -115
  175. package/src/schemas/task.ts +0 -161
  176. package/src/schemas/worker-handoff.test.ts +0 -302
  177. package/src/schemas/worker-handoff.ts +0 -131
  178. package/src/sessions/agent-discovery.test.ts +0 -137
  179. package/src/sessions/agent-discovery.ts +0 -112
  180. package/src/sessions/index.ts +0 -15
  181. package/src/skills.integration.test.ts +0 -1192
  182. package/src/skills.test.ts +0 -643
  183. package/src/skills.ts +0 -1549
  184. package/src/storage.integration.test.ts +0 -341
  185. package/src/storage.ts +0 -884
  186. package/src/structured.integration.test.ts +0 -817
  187. package/src/structured.test.ts +0 -1046
  188. package/src/structured.ts +0 -762
  189. package/src/swarm-decompose.test.ts +0 -188
  190. package/src/swarm-decompose.ts +0 -1302
  191. package/src/swarm-deferred.integration.test.ts +0 -157
  192. package/src/swarm-deferred.test.ts +0 -38
  193. package/src/swarm-insights.test.ts +0 -214
  194. package/src/swarm-insights.ts +0 -459
  195. package/src/swarm-mail.integration.test.ts +0 -970
  196. package/src/swarm-mail.ts +0 -739
  197. package/src/swarm-orchestrate.integration.test.ts +0 -282
  198. package/src/swarm-orchestrate.test.ts +0 -548
  199. package/src/swarm-orchestrate.ts +0 -3084
  200. package/src/swarm-prompts.test.ts +0 -1270
  201. package/src/swarm-prompts.ts +0 -2077
  202. package/src/swarm-research.integration.test.ts +0 -701
  203. package/src/swarm-research.test.ts +0 -698
  204. package/src/swarm-research.ts +0 -472
  205. package/src/swarm-review.integration.test.ts +0 -285
  206. package/src/swarm-review.test.ts +0 -879
  207. package/src/swarm-review.ts +0 -709
  208. package/src/swarm-strategies.ts +0 -407
  209. package/src/swarm-worktree.test.ts +0 -501
  210. package/src/swarm-worktree.ts +0 -575
  211. package/src/swarm.integration.test.ts +0 -2377
  212. package/src/swarm.ts +0 -38
  213. package/src/tool-adapter.integration.test.ts +0 -1221
  214. package/src/tool-availability.ts +0 -461
  215. package/tsconfig.json +0 -28
@@ -1,459 +0,0 @@
1
- /**
2
- * Swarm Insights Data Layer
3
- *
4
- * Aggregates insights from swarm coordination for prompt injection.
5
- * Provides concise, context-efficient summaries for coordinators and workers.
6
- *
7
- * Data sources:
8
- * - Event store (subtask_outcome, eval_finalized)
9
- * - Semantic memory (file-specific learnings)
10
- * - Anti-pattern registry
11
- */
12
-
13
- import type { SwarmMailAdapter } from "swarm-mail";
14
-
15
- // ============================================================================
16
- // Types
17
- // ============================================================================
18
-
19
- export interface StrategyInsight {
20
- strategy: string;
21
- successRate: number;
22
- totalAttempts: number;
23
- recommendation: string;
24
- }
25
-
26
- export interface FileInsight {
27
- file: string;
28
- failureCount: number;
29
- lastFailure: string | null;
30
- gotchas: string[];
31
- }
32
-
33
- export interface PatternInsight {
34
- pattern: string;
35
- frequency: number;
36
- recommendation: string;
37
- }
38
-
39
- export interface InsightsBundle {
40
- strategies?: StrategyInsight[];
41
- files?: FileInsight[];
42
- patterns?: PatternInsight[];
43
- }
44
-
45
- export interface FormatOptions {
46
- maxTokens?: number;
47
- }
48
-
49
- // ============================================================================
50
- // Strategy Insights
51
- // ============================================================================
52
-
53
- /**
54
- * Get strategy success rates and recommendations for a task.
55
- *
56
- * Queries the event store for subtask_outcome events and calculates
57
- * success rates by strategy. Returns recommendations based on historical data.
58
- *
59
- * @param swarmMail - SwarmMail adapter for database access
60
- * @param _task - Task description (currently unused, reserved for future filtering)
61
- * @returns Promise resolving to array of strategy insights with success rates and recommendations
62
- *
63
- * @example
64
- * ```typescript
65
- * const insights = await getStrategyInsights(swarmMail, "Add authentication");
66
- * // Returns: [
67
- * // { strategy: "file-based", successRate: 85.5, totalAttempts: 12, recommendation: "..." },
68
- * // { strategy: "feature-based", successRate: 65.0, totalAttempts: 8, recommendation: "..." }
69
- * // ]
70
- * ```
71
- */
72
- export async function getStrategyInsights(
73
- swarmMail: SwarmMailAdapter,
74
- _task: string,
75
- ): Promise<StrategyInsight[]> {
76
- const db = await swarmMail.getDatabase();
77
-
78
- const query = `
79
- SELECT
80
- json_extract(data, '$.strategy') as strategy,
81
- COUNT(*) as total_attempts,
82
- SUM(CASE WHEN json_extract(data, '$.success') = 'true' THEN 1 ELSE 0 END) as successes
83
- FROM events
84
- WHERE type = 'subtask_outcome'
85
- AND json_extract(data, '$.strategy') IS NOT NULL
86
- GROUP BY json_extract(data, '$.strategy')
87
- ORDER BY total_attempts DESC
88
- `;
89
-
90
- const result = await db.query(query, []);
91
- const rows = result.rows as Array<{
92
- strategy: string;
93
- total_attempts: number;
94
- successes: number;
95
- }>;
96
-
97
- return rows.map((row) => {
98
- const successRate = (row.successes / row.total_attempts) * 100;
99
- return {
100
- strategy: row.strategy,
101
- successRate: Math.round(successRate * 100) / 100,
102
- totalAttempts: row.total_attempts,
103
- recommendation: getStrategyRecommendation(row.strategy, successRate),
104
- };
105
- });
106
- }
107
-
108
- /**
109
- * Generate recommendation based on strategy and success rate.
110
- *
111
- * @param strategy - Strategy name (e.g., "file-based", "feature-based")
112
- * @param successRate - Success rate percentage (0-100)
113
- * @returns Recommendation string based on performance thresholds
114
- *
115
- * @example
116
- * ```typescript
117
- * getStrategyRecommendation("file-based", 85);
118
- * // Returns: "file-based is performing well (85% success)"
119
- *
120
- * getStrategyRecommendation("feature-based", 35);
121
- * // Returns: "AVOID feature-based - high failure rate (35%)"
122
- * ```
123
- */
124
- function getStrategyRecommendation(strategy: string, successRate: number): string {
125
- if (successRate >= 80) {
126
- return `${strategy} is performing well (${successRate.toFixed(0)}% success)`;
127
- }
128
- if (successRate >= 60) {
129
- return `${strategy} is moderate - monitor for issues`;
130
- }
131
- if (successRate >= 40) {
132
- return `${strategy} has low success - consider alternatives`;
133
- }
134
- return `AVOID ${strategy} - high failure rate (${successRate.toFixed(0)}%)`;
135
- }
136
-
137
- // ============================================================================
138
- // File Insights
139
- // ============================================================================
140
-
141
- /**
142
- * Get insights for specific files based on historical outcomes.
143
- *
144
- * Queries the event store for failures involving these files and
145
- * semantic memory for file-specific gotchas.
146
- *
147
- * @param swarmMail - SwarmMail adapter for database access
148
- * @param files - Array of file paths to analyze
149
- * @returns Promise resolving to array of file-specific insights including failure counts and gotchas
150
- *
151
- * @example
152
- * ```typescript
153
- * const insights = await getFileInsights(swarmMail, ["src/auth.ts", "src/db.ts"]);
154
- * // Returns: [
155
- * // { file: "src/auth.ts", failureCount: 3, lastFailure: "2025-12-20T10:30:00Z", gotchas: [...] }
156
- * // ]
157
- * ```
158
- */
159
- export async function getFileInsights(
160
- swarmMail: SwarmMailAdapter,
161
- files: string[],
162
- ): Promise<FileInsight[]> {
163
- if (files.length === 0) return [];
164
-
165
- const db = await swarmMail.getDatabase();
166
- const insights: FileInsight[] = [];
167
-
168
- for (const file of files) {
169
- // Query for failures involving this file
170
- const query = `
171
- SELECT
172
- COUNT(*) as failure_count,
173
- MAX(timestamp) as last_failure
174
- FROM events
175
- WHERE type = 'subtask_outcome'
176
- AND json_extract(data, '$.success') = 'false'
177
- AND json_extract(data, '$.files_touched') LIKE ?
178
- `;
179
-
180
- const result = await db.query(query, [`%${file}%`]);
181
- const row = result.rows[0] as {
182
- failure_count: number;
183
- last_failure: string | null;
184
- };
185
-
186
- if (row && row.failure_count > 0) {
187
- // Query semantic memory for gotchas (simplified - would use actual memory search)
188
- const gotchas = await getFileGotchas(swarmMail, file);
189
-
190
- insights.push({
191
- file,
192
- failureCount: row.failure_count,
193
- lastFailure: row.last_failure,
194
- gotchas,
195
- });
196
- }
197
- }
198
-
199
- return insights;
200
- }
201
-
202
- /**
203
- * Get gotchas for a file from semantic memory.
204
- *
205
- * In a full implementation, this would query the semantic memory
206
- * for file-specific learnings. For now, returns empty array.
207
- *
208
- * @param _swarmMail - SwarmMail adapter (currently unused)
209
- * @param _file - File path to query learnings for
210
- * @returns Promise resolving to array of gotcha strings (currently empty, TODO)
211
- *
212
- * @example
213
- * ```typescript
214
- * const gotchas = await getFileGotchas(swarmMail, "src/auth.ts");
215
- * // TODO: Will return semantic memory learnings like:
216
- * // ["OAuth tokens need 5min buffer", "Always validate refresh token expiry"]
217
- * ```
218
- */
219
- async function getFileGotchas(
220
- _swarmMail: SwarmMailAdapter,
221
- _file: string,
222
- ): Promise<string[]> {
223
- // TODO: Query semantic memory for file-specific learnings
224
- // const memories = await semanticMemoryFind({ query: `file:${file}`, limit: 3 });
225
- // return memories.map(m => m.summary);
226
- return [];
227
- }
228
-
229
- // ============================================================================
230
- // Pattern Insights
231
- // ============================================================================
232
-
233
- /**
234
- * Get common failure patterns and anti-patterns.
235
- *
236
- * Analyzes event store for recurring failure patterns and
237
- * queries the anti-pattern registry.
238
- *
239
- * @param swarmMail - SwarmMail adapter for database access
240
- * @returns Promise resolving to array of pattern insights with frequency and recommendations
241
- *
242
- * @example
243
- * ```typescript
244
- * const patterns = await getPatternInsights(swarmMail);
245
- * // Returns: [
246
- * // { pattern: "type_error", frequency: 5, recommendation: "Add explicit type annotations and null checks" },
247
- * // { pattern: "timeout", frequency: 3, recommendation: "Consider breaking into smaller tasks" }
248
- * // ]
249
- * ```
250
- */
251
- export async function getPatternInsights(
252
- swarmMail: SwarmMailAdapter,
253
- ): Promise<PatternInsight[]> {
254
- const db = await swarmMail.getDatabase();
255
- const patterns: PatternInsight[] = [];
256
-
257
- // Query for common error patterns
258
- const query = `
259
- SELECT
260
- json_extract(data, '$.error_type') as error_type,
261
- COUNT(*) as frequency
262
- FROM events
263
- WHERE type = 'subtask_outcome'
264
- AND json_extract(data, '$.success') = 'false'
265
- AND json_extract(data, '$.error_type') IS NOT NULL
266
- GROUP BY json_extract(data, '$.error_type')
267
- HAVING COUNT(*) >= 2
268
- ORDER BY frequency DESC
269
- LIMIT 5
270
- `;
271
-
272
- const result = await db.query(query, []);
273
- const rows = result.rows as Array<{
274
- error_type: string;
275
- frequency: number;
276
- }>;
277
-
278
- for (const row of rows) {
279
- patterns.push({
280
- pattern: row.error_type,
281
- frequency: row.frequency,
282
- recommendation: getPatternRecommendation(row.error_type),
283
- });
284
- }
285
-
286
- return patterns;
287
- }
288
-
289
- /**
290
- * Generate recommendation for a failure pattern.
291
- *
292
- * @param errorType - Type of error pattern (e.g., "type_error", "timeout", "conflict")
293
- * @returns Recommendation string for addressing the pattern
294
- *
295
- * @example
296
- * ```typescript
297
- * getPatternRecommendation("type_error");
298
- * // Returns: "Add explicit type annotations and null checks"
299
- *
300
- * getPatternRecommendation("unknown_error");
301
- * // Returns: "Address unknown_error issues"
302
- * ```
303
- */
304
- function getPatternRecommendation(errorType: string): string {
305
- // Common patterns and their recommendations
306
- const recommendations: Record<string, string> = {
307
- type_error: "Add explicit type annotations and null checks",
308
- timeout: "Consider breaking into smaller tasks",
309
- conflict: "Check file reservations before editing",
310
- test_failure: "Run tests incrementally during implementation",
311
- };
312
-
313
- return recommendations[errorType] || `Address ${errorType} issues`;
314
- }
315
-
316
- // ============================================================================
317
- // Prompt Formatting
318
- // ============================================================================
319
-
320
- /**
321
- * Format insights bundle for prompt injection.
322
- *
323
- * Produces a concise, context-efficient summary suitable for
324
- * inclusion in coordinator or worker prompts.
325
- *
326
- * @param bundle - Insights bundle containing strategies, files, and patterns
327
- * @param options - Formatting options (maxTokens defaults to 500)
328
- * @returns Formatted markdown string for prompt injection, or empty string if no insights
329
- *
330
- * @example
331
- * ```typescript
332
- * const bundle = {
333
- * strategies: [{ strategy: "file-based", successRate: 85.5, totalAttempts: 12, recommendation: "..." }],
334
- * files: [{ file: "src/auth.ts", failureCount: 2, lastFailure: null, gotchas: [] }],
335
- * patterns: [{ pattern: "type_error", frequency: 3, recommendation: "Add type checks" }]
336
- * };
337
- * const formatted = formatInsightsForPrompt(bundle, { maxTokens: 300 });
338
- * // Returns formatted markdown with top 3 strategies, top 5 files, top 3 patterns
339
- * ```
340
- */
341
- export function formatInsightsForPrompt(
342
- bundle: InsightsBundle,
343
- options: FormatOptions = {},
344
- ): string {
345
- const { maxTokens = 500 } = options;
346
- const sections: string[] = [];
347
-
348
- // Format strategy insights
349
- if (bundle.strategies && bundle.strategies.length > 0) {
350
- const strategyLines = bundle.strategies
351
- .slice(0, 3) // Top 3 strategies
352
- .map(
353
- (s) =>
354
- `- ${s.strategy}: ${s.successRate.toFixed(0)}% success (${s.totalAttempts} attempts)`,
355
- );
356
- sections.push(`**Strategy Performance:**\n${strategyLines.join("\n")}`);
357
- }
358
-
359
- // Format file insights
360
- if (bundle.files && bundle.files.length > 0) {
361
- const fileLines = bundle.files.slice(0, 5).map((f) => {
362
- const gotchaStr =
363
- f.gotchas.length > 0 ? ` - ${f.gotchas[0]}` : "";
364
- return `- ${f.file}: ${f.failureCount} past failures${gotchaStr}`;
365
- });
366
- sections.push(`**File-Specific Gotchas:**\n${fileLines.join("\n")}`);
367
- }
368
-
369
- // Format pattern insights
370
- if (bundle.patterns && bundle.patterns.length > 0) {
371
- const patternLines = bundle.patterns
372
- .slice(0, 3)
373
- .map((p) => `- ${p.pattern} (${p.frequency}x): ${p.recommendation}`);
374
- sections.push(`**Common Pitfalls:**\n${patternLines.join("\n")}`);
375
- }
376
-
377
- if (sections.length === 0) {
378
- return "";
379
- }
380
-
381
- let result = sections.join("\n\n");
382
-
383
- // Truncate to fit token budget (rough estimate: 4 chars per token)
384
- const maxChars = maxTokens * 4;
385
- if (result.length > maxChars) {
386
- result = result.slice(0, maxChars - 3) + "...";
387
- }
388
-
389
- return result;
390
- }
391
-
392
- // ============================================================================
393
- // Caching (for future optimization)
394
- // ============================================================================
395
-
396
- // Simple in-memory cache with TTL
397
- const insightsCache = new Map<
398
- string,
399
- { data: InsightsBundle; expires: number }
400
- >();
401
- const CACHE_TTL_MS = 5 * 60 * 1000; // 5 minutes
402
-
403
- /**
404
- * Get cached insights or compute fresh ones.
405
- *
406
- * Simple in-memory cache with 5-minute TTL to avoid redundant database queries.
407
- *
408
- * @param _swarmMail - SwarmMail adapter (currently unused, reserved for future cache invalidation)
409
- * @param cacheKey - Unique key for caching (e.g., "strategies:task-name" or "files:src/auth.ts")
410
- * @param computeFn - Function to compute fresh insights if cache miss
411
- * @returns Promise resolving to cached or freshly computed insights bundle
412
- *
413
- * @example
414
- * ```typescript
415
- * const insights = await getCachedInsights(
416
- * swarmMail,
417
- * "strategies:add-auth",
418
- * async () => ({
419
- * strategies: await getStrategyInsights(swarmMail, "add auth"),
420
- * })
421
- * );
422
- * // First call: computes and caches. Subsequent calls within 5min: returns cached.
423
- * ```
424
- */
425
- export async function getCachedInsights(
426
- _swarmMail: SwarmMailAdapter,
427
- cacheKey: string,
428
- computeFn: () => Promise<InsightsBundle>,
429
- ): Promise<InsightsBundle> {
430
- const cached = insightsCache.get(cacheKey);
431
- if (cached && cached.expires > Date.now()) {
432
- return cached.data;
433
- }
434
-
435
- const data = await computeFn();
436
- insightsCache.set(cacheKey, {
437
- data,
438
- expires: Date.now() + CACHE_TTL_MS,
439
- });
440
-
441
- return data;
442
- }
443
-
444
- /**
445
- * Clear the insights cache.
446
- *
447
- * Useful for testing or forcing fresh insights computation.
448
- *
449
- * @returns void
450
- *
451
- * @example
452
- * ```typescript
453
- * clearInsightsCache();
454
- * // All cached insights invalidated, next getCachedInsights() will recompute
455
- * ```
456
- */
457
- export function clearInsightsCache(): void {
458
- insightsCache.clear();
459
- }