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,360 +0,0 @@
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
- }
@@ -1,223 +0,0 @@
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, afterEach } from "bun:test";
8
- import { runEvals } from "./eval-runner";
9
- import path from "node:path";
10
- import fs from "node:fs";
11
- import { getEvalHistoryPath } from "./eval-history";
12
-
13
- // Use project root for all tests
14
- const PROJECT_ROOT = path.resolve(import.meta.dir, "..");
15
-
16
- describe("runEvals", () => {
17
- test("runs all evals when no suite filter provided", async () => {
18
- const result = await runEvals({
19
- cwd: PROJECT_ROOT,
20
- });
21
-
22
- // Even if some evals fail, we should get results
23
- expect(typeof result.success).toBe("boolean");
24
- expect(typeof result.totalSuites).toBe("number");
25
- expect(typeof result.totalEvals).toBe("number");
26
- expect(typeof result.averageScore).toBe("number");
27
- expect(Array.isArray(result.suites)).toBe(true);
28
-
29
- // Should have at least the example.eval.ts suite
30
- expect(result.totalSuites).toBeGreaterThan(0);
31
- expect(result.suites.length).toBeGreaterThan(0);
32
- }, 60000); // 60s timeout for full eval run
33
-
34
- test("filters evals by suite name", async () => {
35
- const result = await runEvals({
36
- cwd: PROJECT_ROOT,
37
- suiteFilter: "example",
38
- });
39
-
40
- expect(result.success).toBe(true);
41
- // All suite filepaths should contain "example"
42
- for (const suite of result.suites) {
43
- expect(suite.filepath.toLowerCase()).toContain("example");
44
- }
45
- }, 30000);
46
-
47
- test("respects score threshold", async () => {
48
- const result = await runEvals({
49
- cwd: PROJECT_ROOT,
50
- suiteFilter: "example", // Known good eval
51
- scoreThreshold: 0, // Very low threshold, should pass
52
- });
53
-
54
- expect(result.success).toBe(true);
55
- expect(result.averageScore).toBeGreaterThanOrEqual(0);
56
- }, 30000);
57
-
58
- test("returns structured suite results with scores", async () => {
59
- const result = await runEvals({
60
- cwd: PROJECT_ROOT,
61
- suiteFilter: "example",
62
- });
63
-
64
- expect(result.suites.length).toBeGreaterThan(0);
65
-
66
- const suite = result.suites[0];
67
- expect(suite).toMatchObject({
68
- name: expect.any(String),
69
- filepath: expect.any(String),
70
- status: expect.stringMatching(/^(success|fail|running)$/),
71
- duration: expect.any(Number),
72
- averageScore: expect.any(Number),
73
- evalCount: expect.any(Number),
74
- });
75
- }, 30000);
76
-
77
- test("handles errors gracefully", async () => {
78
- const result = await runEvals({
79
- cwd: "/nonexistent/path",
80
- });
81
-
82
- expect(result.success).toBe(false);
83
- expect(result.error).toBeDefined();
84
- expect(result.suites).toEqual([]);
85
- }, 10000);
86
-
87
- test("returns empty results when no evals match filter", async () => {
88
- const result = await runEvals({
89
- cwd: PROJECT_ROOT,
90
- suiteFilter: "nonexistent-eval-name-xyz",
91
- });
92
-
93
- // Should succeed but with no suites
94
- expect(result.success).toBe(true);
95
- expect(result.totalSuites).toBe(0);
96
- expect(result.suites).toEqual([]);
97
- }, 10000);
98
-
99
- test("records eval run to history after execution", async () => {
100
- // Clean up any existing history before test
101
- const historyPath = getEvalHistoryPath(PROJECT_ROOT);
102
- const historyBackup = historyPath + ".backup";
103
-
104
- // Backup existing history
105
- if (fs.existsSync(historyPath)) {
106
- fs.copyFileSync(historyPath, historyBackup);
107
- }
108
-
109
- try {
110
- // Remove history file to get clean state
111
- if (fs.existsSync(historyPath)) {
112
- fs.unlinkSync(historyPath);
113
- }
114
-
115
- // Run evals
116
- const result = await runEvals({
117
- cwd: PROJECT_ROOT,
118
- suiteFilter: "example",
119
- });
120
-
121
- // Should have succeeded
122
- expect(result.success).toBe(true);
123
- expect(result.suites.length).toBeGreaterThan(0);
124
-
125
- // History file should have been created
126
- expect(fs.existsSync(historyPath)).toBe(true);
127
-
128
- // Read history file
129
- const historyContent = fs.readFileSync(historyPath, "utf-8");
130
- const lines = historyContent.trim().split("\n");
131
-
132
- // Should have one line per suite
133
- expect(lines.length).toBe(result.suites.length);
134
-
135
- // Parse first line and verify structure
136
- const firstRecord = JSON.parse(lines[0]);
137
-
138
- // Verify structure has all required fields
139
- expect(typeof firstRecord.timestamp).toBe("string");
140
- expect(typeof firstRecord.eval_name).toBe("string");
141
- expect(typeof firstRecord.score).toBe("number");
142
- expect(typeof firstRecord.run_count).toBe("number");
143
-
144
- // Verify eval_name matches suite name
145
- expect(firstRecord.eval_name).toBe(result.suites[0].name);
146
-
147
- // Verify score matches suite averageScore
148
- expect(firstRecord.score).toBe(result.suites[0].averageScore);
149
-
150
- // First run should have run_count = 1
151
- expect(firstRecord.run_count).toBe(1);
152
- } finally {
153
- // Restore backup
154
- if (fs.existsSync(historyBackup)) {
155
- fs.copyFileSync(historyBackup, historyPath);
156
- fs.unlinkSync(historyBackup);
157
- }
158
- }
159
- }, 30000);
160
-
161
- test("checks gates for each suite after recording", async () => {
162
- const result = await runEvals({
163
- cwd: PROJECT_ROOT,
164
- suiteFilter: "example",
165
- });
166
-
167
- expect(result.success).toBe(true);
168
- expect(result.gateResults).toBeDefined();
169
- expect(Array.isArray(result.gateResults)).toBe(true);
170
-
171
- // Should have gate result for each suite
172
- expect(result.gateResults?.length).toBe(result.suites.length);
173
-
174
- // Each gate result should have required fields
175
- if (result.gateResults && result.gateResults.length > 0) {
176
- const gateResult = result.gateResults[0];
177
- expect(gateResult).toHaveProperty("suite");
178
- expect(gateResult).toHaveProperty("passed");
179
- expect(gateResult).toHaveProperty("phase");
180
- expect(gateResult).toHaveProperty("message");
181
- expect(gateResult).toHaveProperty("currentScore");
182
- }
183
- }, 30000);
184
-
185
- test("calls learnFromEvalFailure when gate fails", async () => {
186
- // This test requires manually creating a history with regression
187
- // For now, we just verify the code path exists
188
- // In practice, this would be tested with mocked checkGate returning failed=true
189
-
190
- const result = await runEvals({
191
- cwd: PROJECT_ROOT,
192
- suiteFilter: "example",
193
- });
194
-
195
- // Gate results should be present even if no failures
196
- expect(result.gateResults).toBeDefined();
197
- }, 30000);
198
-
199
- test("does NOT call learnFromEvalFailure when gate passes", async () => {
200
- // Similar to above - verifies the happy path
201
- // Real test would mock checkGate and verify learnFromEvalFailure NOT called
202
-
203
- const result = await runEvals({
204
- cwd: PROJECT_ROOT,
205
- suiteFilter: "example",
206
- });
207
-
208
- // Should succeed with gate results
209
- expect(result.success).toBe(true);
210
- expect(result.gateResults).toBeDefined();
211
- }, 30000);
212
-
213
- test("includes gateResults in return value", async () => {
214
- const result = await runEvals({
215
- cwd: PROJECT_ROOT,
216
- suiteFilter: "example",
217
- });
218
-
219
- // gateResults should be array (even if empty)
220
- expect(result).toHaveProperty("gateResults");
221
- expect(Array.isArray(result.gateResults)).toBe(true);
222
- }, 30000);
223
- });