opencode-swarm-plugin 0.38.0 → 0.40.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.
Files changed (91) hide show
  1. package/.env +2 -0
  2. package/.hive/eval-results.json +26 -0
  3. package/.hive/issues.jsonl +27 -0
  4. package/.hive/memories.jsonl +23 -1
  5. package/.opencode/eval-history.jsonl +12 -0
  6. package/CHANGELOG.md +182 -0
  7. package/README.md +29 -12
  8. package/bin/swarm.test.ts +881 -0
  9. package/bin/swarm.ts +686 -0
  10. package/dist/compaction-hook.d.ts +8 -1
  11. package/dist/compaction-hook.d.ts.map +1 -1
  12. package/dist/compaction-observability.d.ts +173 -0
  13. package/dist/compaction-observability.d.ts.map +1 -0
  14. package/dist/compaction-prompt-scoring.d.ts +124 -0
  15. package/dist/compaction-prompt-scoring.d.ts.map +1 -0
  16. package/dist/eval-capture.d.ts +174 -1
  17. package/dist/eval-capture.d.ts.map +1 -1
  18. package/dist/eval-gates.d.ts +84 -0
  19. package/dist/eval-gates.d.ts.map +1 -0
  20. package/dist/eval-history.d.ts +117 -0
  21. package/dist/eval-history.d.ts.map +1 -0
  22. package/dist/eval-learning.d.ts +216 -0
  23. package/dist/eval-learning.d.ts.map +1 -0
  24. package/dist/hive.d.ts.map +1 -1
  25. package/dist/index.d.ts +80 -1
  26. package/dist/index.d.ts.map +1 -1
  27. package/dist/index.js +16098 -651
  28. package/dist/plugin.js +16012 -756
  29. package/dist/post-compaction-tracker.d.ts +133 -0
  30. package/dist/post-compaction-tracker.d.ts.map +1 -0
  31. package/dist/schemas/task.d.ts +3 -3
  32. package/dist/swarm-orchestrate.d.ts +23 -0
  33. package/dist/swarm-orchestrate.d.ts.map +1 -1
  34. package/dist/swarm-prompts.d.ts +25 -1
  35. package/dist/swarm-prompts.d.ts.map +1 -1
  36. package/dist/swarm.d.ts +4 -0
  37. package/dist/swarm.d.ts.map +1 -1
  38. package/evals/README.md +702 -105
  39. package/evals/compaction-prompt.eval.ts +149 -0
  40. package/evals/coordinator-behavior.eval.ts +8 -8
  41. package/evals/fixtures/compaction-prompt-cases.ts +305 -0
  42. package/evals/lib/compaction-loader.test.ts +248 -0
  43. package/evals/lib/compaction-loader.ts +320 -0
  44. package/evals/lib/data-loader.test.ts +345 -0
  45. package/evals/lib/data-loader.ts +107 -6
  46. package/evals/scorers/compaction-prompt-scorers.ts +145 -0
  47. package/evals/scorers/compaction-scorers.ts +13 -13
  48. package/evals/scorers/coordinator-discipline.evalite-test.ts +166 -2
  49. package/evals/scorers/coordinator-discipline.ts +348 -15
  50. package/evals/scorers/index.test.ts +146 -0
  51. package/evals/scorers/index.ts +104 -0
  52. package/evals/swarm-decomposition.eval.ts +9 -2
  53. package/examples/commands/swarm.md +291 -21
  54. package/examples/plugin-wrapper-template.ts +117 -0
  55. package/package.json +7 -5
  56. package/scripts/migrate-unknown-sessions.ts +349 -0
  57. package/src/compaction-capture.integration.test.ts +257 -0
  58. package/src/compaction-hook.test.ts +42 -0
  59. package/src/compaction-hook.ts +315 -86
  60. package/src/compaction-observability.integration.test.ts +139 -0
  61. package/src/compaction-observability.test.ts +187 -0
  62. package/src/compaction-observability.ts +324 -0
  63. package/src/compaction-prompt-scorers.test.ts +299 -0
  64. package/src/compaction-prompt-scoring.ts +298 -0
  65. package/src/eval-capture.test.ts +626 -1
  66. package/src/eval-capture.ts +286 -2
  67. package/src/eval-gates.test.ts +306 -0
  68. package/src/eval-gates.ts +218 -0
  69. package/src/eval-history.test.ts +508 -0
  70. package/src/eval-history.ts +214 -0
  71. package/src/eval-learning.test.ts +378 -0
  72. package/src/eval-learning.ts +360 -0
  73. package/src/eval-runner.test.ts +96 -0
  74. package/src/eval-runner.ts +356 -0
  75. package/src/hive.ts +34 -0
  76. package/src/index.ts +115 -2
  77. package/src/memory.test.ts +110 -0
  78. package/src/memory.ts +34 -0
  79. package/src/post-compaction-tracker.test.ts +251 -0
  80. package/src/post-compaction-tracker.ts +237 -0
  81. package/src/swarm-decompose.ts +2 -2
  82. package/src/swarm-orchestrate.ts +2 -2
  83. package/src/swarm-prompts.ts +2 -2
  84. package/src/swarm-review.ts +3 -3
  85. package/dist/beads.d.ts +0 -386
  86. package/dist/beads.d.ts.map +0 -1
  87. package/dist/schemas/bead-events.d.ts +0 -698
  88. package/dist/schemas/bead-events.d.ts.map +0 -1
  89. package/dist/schemas/bead.d.ts +0 -255
  90. package/dist/schemas/bead.d.ts.map +0 -1
  91. /package/evals/{evalite.config.ts → evalite.config.ts.bak} +0 -0
@@ -0,0 +1,360 @@
1
+ /**
2
+ * Eval-to-Learning Feedback Loop
3
+ *
4
+ * Automatically stores eval failures to semantic memory for learning.
5
+ * When eval scores drop significantly from rolling average (default >15%),
6
+ * stores context to semantic-memory with tags for future prompt generation.
7
+ *
8
+ * ## Usage
9
+ *
10
+ * ```typescript
11
+ * import { learnFromEvalFailure } from "./eval-learning";
12
+ * import { getMemoryAdapter } from "./memory-tools";
13
+ * import { getScoreHistory } from "./eval-history";
14
+ *
15
+ * const memoryAdapter = await getMemoryAdapter();
16
+ * const history = getScoreHistory(projectPath, "compaction-test");
17
+ *
18
+ * const result = await learnFromEvalFailure(
19
+ * "compaction-test",
20
+ * currentScore,
21
+ * history,
22
+ * memoryAdapter
23
+ * );
24
+ *
25
+ * if (result.triggered) {
26
+ * console.log(`📉 Regression detected: ${(result.drop_percentage * 100).toFixed(1)}% drop`);
27
+ * console.log(`Memory ID: ${result.memory_id}`);
28
+ * }
29
+ * ```
30
+ *
31
+ * ## Integration Points
32
+ *
33
+ * - **After each eval run**: Call to detect regressions automatically
34
+ * - **Memory tags**: `eval-failure`, `{eval-name}`, `regression`
35
+ * - **Future prompts**: Query memories with these tags for context
36
+ * - **Scorer context**: Optional detail about which scorer failed
37
+ *
38
+ * ## Customization
39
+ *
40
+ * ```typescript
41
+ * const customConfig = {
42
+ * dropThreshold: 0.10, // 10% threshold (more sensitive)
43
+ * windowSize: 10, // Last 10 runs for baseline
44
+ * };
45
+ *
46
+ * await learnFromEvalFailure(
47
+ * "test",
48
+ * score,
49
+ * history,
50
+ * adapter,
51
+ * { config: customConfig }
52
+ * );
53
+ * ```
54
+ *
55
+ * @module eval-learning
56
+ */
57
+
58
+ import type { EvalRunRecord } from "./eval-history";
59
+ import type { MemoryAdapter } from "./memory-tools";
60
+
61
+ // ============================================================================
62
+ // Configuration
63
+ // ============================================================================
64
+
65
+ /**
66
+ * Configuration for eval-to-learning feedback
67
+ */
68
+ export interface EvalLearningConfig {
69
+ /** Threshold for significant drop (0-1, default 0.15 = 15%) */
70
+ dropThreshold: number;
71
+ /** Rolling average window size (default 5 runs) */
72
+ windowSize: number;
73
+ }
74
+
75
+ /**
76
+ * Default configuration
77
+ */
78
+ export const DEFAULT_EVAL_LEARNING_CONFIG: EvalLearningConfig = {
79
+ dropThreshold: 0.15, // 15% drop triggers storage
80
+ windowSize: 5, // Last 5 runs for baseline
81
+ };
82
+
83
+ // ============================================================================
84
+ // Result Types
85
+ // ============================================================================
86
+
87
+ /**
88
+ * Result from learning check
89
+ */
90
+ export interface LearningResult {
91
+ /** Whether the check triggered memory storage */
92
+ triggered: boolean;
93
+ /** Baseline score from rolling average */
94
+ baseline: number;
95
+ /** Current score */
96
+ current: number;
97
+ /** Drop percentage (0-1, e.g., 0.20 = 20% drop) */
98
+ drop_percentage: number;
99
+ /** Memory ID if stored */
100
+ memory_id?: string;
101
+ }
102
+
103
+ // ============================================================================
104
+ // Core Functions
105
+ // ============================================================================
106
+
107
+ /**
108
+ * Calculate rolling average of recent scores
109
+ *
110
+ * Uses last N runs (default 5) to establish baseline.
111
+ * If history shorter than window, uses all available.
112
+ *
113
+ * @param history - Score history (chronological order)
114
+ * @param windowSize - Number of recent runs to average (default 5)
115
+ * @returns Average score (0 if empty)
116
+ */
117
+ export function calculateRollingAverage(
118
+ history: EvalRunRecord[],
119
+ windowSize: number = 5,
120
+ ): number {
121
+ if (history.length === 0) {
122
+ return 0;
123
+ }
124
+
125
+ const recentRuns = history.slice(-windowSize);
126
+ const sum = recentRuns.reduce((acc, run) => acc + run.score, 0);
127
+ return sum / recentRuns.length;
128
+ }
129
+
130
+ /**
131
+ * Check if current score is a significant drop from baseline
132
+ *
133
+ * Significant = drop exceeds threshold (default 15%).
134
+ * Formula: (baseline - current) / baseline >= threshold
135
+ *
136
+ * @param currentScore - Current eval score
137
+ * @param baseline - Baseline score (rolling average)
138
+ * @param threshold - Drop threshold (default 0.15 = 15%)
139
+ * @returns True if drop is significant
140
+ */
141
+ export function isSignificantDrop(
142
+ currentScore: number,
143
+ baseline: number,
144
+ threshold: number = 0.15,
145
+ ): boolean {
146
+ // Avoid division by zero
147
+ if (baseline === 0) {
148
+ return false;
149
+ }
150
+
151
+ const drop = (baseline - currentScore) / baseline;
152
+ return drop >= threshold;
153
+ }
154
+
155
+ /**
156
+ * Format failure context for semantic memory storage
157
+ *
158
+ * Creates human-readable description of the failure with
159
+ * quantified metrics and optional scorer context.
160
+ *
161
+ * @param evalName - Name of eval that failed
162
+ * @param currentScore - Current score
163
+ * @param baseline - Baseline score
164
+ * @param scorerContext - Optional context about which scorer failed
165
+ * @returns Formatted context string
166
+ */
167
+ export function formatFailureContext(
168
+ evalName: string,
169
+ currentScore: number,
170
+ baseline: number,
171
+ scorerContext?: string,
172
+ ): string {
173
+ const dropPercentage =
174
+ baseline > 0 ? ((baseline - currentScore) / baseline) * 100 : 0;
175
+
176
+ const lines = [
177
+ `Eval "${evalName}" regression detected:`,
178
+ `- Current score: ${currentScore.toFixed(2)}`,
179
+ `- Baseline (rolling avg): ${baseline.toFixed(2)}`,
180
+ `- Drop: ${dropPercentage.toFixed(1)}%`,
181
+ ];
182
+
183
+ if (scorerContext) {
184
+ lines.push("", "Scorer context:", scorerContext);
185
+ }
186
+
187
+ lines.push(
188
+ "",
189
+ "Action: Review recent changes that may have caused regression.",
190
+ "Query this memory when generating future prompts for this eval.",
191
+ );
192
+
193
+ return lines.join("\n");
194
+ }
195
+
196
+ /**
197
+ * Main learning function - automatically stores eval failures to semantic memory
198
+ *
199
+ * **Closed-loop learning**: When eval scores drop significantly from baseline,
200
+ * this function stores failure context to semantic memory. Future prompt generation
201
+ * queries these memories for context, preventing repeated mistakes.
202
+ *
203
+ * **Trigger condition**: Score drops >15% (default) from rolling average baseline.
204
+ * Uses last 5 runs (default) to establish baseline, not just previous run.
205
+ *
206
+ * **What gets stored**:
207
+ * - Eval name, baseline score, current score, drop percentage
208
+ * - Scorer-specific context (which scorer failed, why)
209
+ * - Timestamp and metadata for querying
210
+ * - Tags: `eval-failure`, `{eval-name}`, `regression`
211
+ *
212
+ * **Future use**: Before generating prompts for the same eval, query semantic memory
213
+ * with tags to inject learnings from past failures.
214
+ *
215
+ * **Integration points**:
216
+ * - After each eval run (in evalite runner or CI)
217
+ * - In `checkGate()` when regression detected
218
+ * - Manual calls for custom eval tracking
219
+ *
220
+ * @param evalName - Name of eval (e.g., "compaction-test", "coordinator-behavior")
221
+ * @param currentScore - Current eval score (typically 0-1 range)
222
+ * @param history - Score history in chronological order (oldest first)
223
+ * @param memoryAdapter - Semantic memory adapter (from `getMemoryAdapter()`)
224
+ * @param options - Optional config (thresholds, window size) and scorer context
225
+ * @param options.config - Custom thresholds (dropThreshold, windowSize)
226
+ * @param options.scorerContext - Details about which scorer failed (for context)
227
+ * @returns Learning result with trigger status, baseline, drop percentage, memory ID
228
+ *
229
+ * @example
230
+ * ```typescript
231
+ * import { learnFromEvalFailure } from "./eval-learning.js";
232
+ * import { getMemoryAdapter } from "./memory-tools.js";
233
+ * import { getScoreHistory } from "./eval-history.js";
234
+ *
235
+ * const memoryAdapter = await getMemoryAdapter();
236
+ * const history = getScoreHistory("/path/to/project", "coordinator-behavior");
237
+ *
238
+ * const result = await learnFromEvalFailure(
239
+ * "coordinator-behavior",
240
+ * 0.68, // Current score
241
+ * history,
242
+ * memoryAdapter,
243
+ * { scorerContext: "violationCount: 5 violations (coordinator edited files)" }
244
+ * );
245
+ *
246
+ * if (result.triggered) {
247
+ * console.log(`📉 Regression detected: ${(result.drop_percentage * 100).toFixed(1)}% drop`);
248
+ * console.log(`Stored to memory: ${result.memory_id}`);
249
+ * }
250
+ * ```
251
+ *
252
+ * @example
253
+ * ```typescript
254
+ * // Custom threshold (more sensitive)
255
+ * const result = await learnFromEvalFailure(
256
+ * "critical-eval",
257
+ * 0.85,
258
+ * history,
259
+ * memoryAdapter,
260
+ * {
261
+ * config: {
262
+ * dropThreshold: 0.10, // 10% threshold (default is 15%)
263
+ * windowSize: 10, // Last 10 runs for baseline (default is 5)
264
+ * },
265
+ * }
266
+ * );
267
+ * ```
268
+ */
269
+ export async function learnFromEvalFailure(
270
+ evalName: string,
271
+ currentScore: number,
272
+ history: EvalRunRecord[],
273
+ memoryAdapter: MemoryAdapter,
274
+ options?: {
275
+ config?: EvalLearningConfig;
276
+ scorerContext?: string;
277
+ },
278
+ ): Promise<LearningResult> {
279
+ const config = options?.config ?? DEFAULT_EVAL_LEARNING_CONFIG;
280
+
281
+ // Calculate baseline from rolling average
282
+ const baseline = calculateRollingAverage(history, config.windowSize);
283
+
284
+ // Check if this is a significant drop
285
+ const dropPercentage =
286
+ baseline > 0 ? (baseline - currentScore) / baseline : 0;
287
+ const significant = isSignificantDrop(
288
+ currentScore,
289
+ baseline,
290
+ config.dropThreshold,
291
+ );
292
+
293
+ const result: LearningResult = {
294
+ triggered: significant,
295
+ baseline,
296
+ current: currentScore,
297
+ drop_percentage: dropPercentage,
298
+ };
299
+
300
+ // Store to semantic memory if significant
301
+ if (significant) {
302
+ const information = formatFailureContext(
303
+ evalName,
304
+ currentScore,
305
+ baseline,
306
+ options?.scorerContext,
307
+ );
308
+
309
+ const tags = ["eval-failure", evalName, "regression"].join(",");
310
+
311
+ const metadata = JSON.stringify({
312
+ eval_name: evalName,
313
+ baseline_score: baseline,
314
+ current_score: currentScore,
315
+ drop_percentage: dropPercentage,
316
+ timestamp: new Date().toISOString(),
317
+ });
318
+
319
+ const storeResult = await memoryAdapter.store({
320
+ information,
321
+ tags,
322
+ metadata,
323
+ });
324
+
325
+ if (storeResult.id) {
326
+ result.memory_id = storeResult.id;
327
+ }
328
+ }
329
+
330
+ return result;
331
+ }
332
+
333
+ // ============================================================================
334
+ // Convenience Exports
335
+ // ============================================================================
336
+
337
+ /**
338
+ * Create custom learning config with specific threshold
339
+ *
340
+ * Helper for common use case: custom drop threshold.
341
+ *
342
+ * @param dropThreshold - Drop threshold (0-1)
343
+ * @param windowSize - Optional window size (default 5)
344
+ * @returns Custom config
345
+ *
346
+ * @example
347
+ * ```typescript
348
+ * const config = createLearningConfig(0.10); // 10% threshold
349
+ * await learnFromEvalFailure("test", score, history, adapter, { config });
350
+ * ```
351
+ */
352
+ export function createLearningConfig(
353
+ dropThreshold: number,
354
+ windowSize?: number,
355
+ ): EvalLearningConfig {
356
+ return {
357
+ dropThreshold,
358
+ windowSize: windowSize ?? DEFAULT_EVAL_LEARNING_CONFIG.windowSize,
359
+ };
360
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Tests for eval-runner - Programmatic evalite execution
3
+ *
4
+ * TDD: These tests MUST fail initially, then pass after implementation.
5
+ */
6
+
7
+ import { describe, test, expect, beforeAll } from "bun:test";
8
+ import { runEvals } from "./eval-runner";
9
+ import path from "node:path";
10
+
11
+ // Use project root for all tests
12
+ const PROJECT_ROOT = path.resolve(import.meta.dir, "..");
13
+
14
+ describe("runEvals", () => {
15
+ test("runs all evals when no suite filter provided", async () => {
16
+ const result = await runEvals({
17
+ cwd: PROJECT_ROOT,
18
+ });
19
+
20
+ // Even if some evals fail, we should get results
21
+ expect(typeof result.success).toBe("boolean");
22
+ expect(typeof result.totalSuites).toBe("number");
23
+ expect(typeof result.totalEvals).toBe("number");
24
+ expect(typeof result.averageScore).toBe("number");
25
+ expect(Array.isArray(result.suites)).toBe(true);
26
+
27
+ // Should have at least the example.eval.ts suite
28
+ expect(result.totalSuites).toBeGreaterThan(0);
29
+ expect(result.suites.length).toBeGreaterThan(0);
30
+ }, 60000); // 60s timeout for full eval run
31
+
32
+ test("filters evals by suite name", async () => {
33
+ const result = await runEvals({
34
+ cwd: PROJECT_ROOT,
35
+ suiteFilter: "example",
36
+ });
37
+
38
+ expect(result.success).toBe(true);
39
+ // All suite filepaths should contain "example"
40
+ for (const suite of result.suites) {
41
+ expect(suite.filepath.toLowerCase()).toContain("example");
42
+ }
43
+ }, 30000);
44
+
45
+ test("respects score threshold", async () => {
46
+ const result = await runEvals({
47
+ cwd: PROJECT_ROOT,
48
+ suiteFilter: "example", // Known good eval
49
+ scoreThreshold: 0, // Very low threshold, should pass
50
+ });
51
+
52
+ expect(result.success).toBe(true);
53
+ expect(result.averageScore).toBeGreaterThanOrEqual(0);
54
+ }, 30000);
55
+
56
+ test("returns structured suite results with scores", async () => {
57
+ const result = await runEvals({
58
+ cwd: PROJECT_ROOT,
59
+ suiteFilter: "example",
60
+ });
61
+
62
+ expect(result.suites.length).toBeGreaterThan(0);
63
+
64
+ const suite = result.suites[0];
65
+ expect(suite).toMatchObject({
66
+ name: expect.any(String),
67
+ filepath: expect.any(String),
68
+ status: expect.stringMatching(/^(success|fail|running)$/),
69
+ duration: expect.any(Number),
70
+ averageScore: expect.any(Number),
71
+ evalCount: expect.any(Number),
72
+ });
73
+ }, 30000);
74
+
75
+ test("handles errors gracefully", async () => {
76
+ const result = await runEvals({
77
+ cwd: "/nonexistent/path",
78
+ });
79
+
80
+ expect(result.success).toBe(false);
81
+ expect(result.error).toBeDefined();
82
+ expect(result.suites).toEqual([]);
83
+ }, 10000);
84
+
85
+ test("returns empty results when no evals match filter", async () => {
86
+ const result = await runEvals({
87
+ cwd: PROJECT_ROOT,
88
+ suiteFilter: "nonexistent-eval-name-xyz",
89
+ });
90
+
91
+ // Should succeed but with no suites
92
+ expect(result.success).toBe(true);
93
+ expect(result.totalSuites).toBe(0);
94
+ expect(result.suites).toEqual([]);
95
+ }, 10000);
96
+ });