opencode-swarm-plugin 0.38.0 → 0.39.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 (69) hide show
  1. package/.env +2 -0
  2. package/.hive/eval-results.json +26 -0
  3. package/.hive/issues.jsonl +11 -0
  4. package/.hive/memories.jsonl +23 -1
  5. package/.opencode/eval-history.jsonl +12 -0
  6. package/CHANGELOG.md +130 -0
  7. package/README.md +29 -12
  8. package/bin/swarm.test.ts +475 -0
  9. package/bin/swarm.ts +383 -0
  10. package/dist/compaction-hook.d.ts +1 -1
  11. package/dist/compaction-hook.d.ts.map +1 -1
  12. package/dist/compaction-prompt-scoring.d.ts +124 -0
  13. package/dist/compaction-prompt-scoring.d.ts.map +1 -0
  14. package/dist/eval-capture.d.ts +81 -1
  15. package/dist/eval-capture.d.ts.map +1 -1
  16. package/dist/eval-gates.d.ts +84 -0
  17. package/dist/eval-gates.d.ts.map +1 -0
  18. package/dist/eval-history.d.ts +117 -0
  19. package/dist/eval-history.d.ts.map +1 -0
  20. package/dist/eval-learning.d.ts +216 -0
  21. package/dist/eval-learning.d.ts.map +1 -0
  22. package/dist/index.d.ts +44 -0
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +370 -13
  25. package/dist/plugin.js +203 -13
  26. package/dist/post-compaction-tracker.d.ts +133 -0
  27. package/dist/post-compaction-tracker.d.ts.map +1 -0
  28. package/dist/swarm-orchestrate.d.ts +23 -0
  29. package/dist/swarm-orchestrate.d.ts.map +1 -1
  30. package/dist/swarm-prompts.d.ts +25 -1
  31. package/dist/swarm-prompts.d.ts.map +1 -1
  32. package/dist/swarm.d.ts +4 -0
  33. package/dist/swarm.d.ts.map +1 -1
  34. package/evals/README.md +589 -105
  35. package/evals/compaction-prompt.eval.ts +149 -0
  36. package/evals/coordinator-behavior.eval.ts +8 -8
  37. package/evals/fixtures/compaction-prompt-cases.ts +305 -0
  38. package/evals/lib/compaction-loader.test.ts +248 -0
  39. package/evals/lib/compaction-loader.ts +320 -0
  40. package/evals/lib/data-loader.test.ts +345 -0
  41. package/evals/lib/data-loader.ts +107 -6
  42. package/evals/scorers/compaction-prompt-scorers.ts +145 -0
  43. package/evals/scorers/compaction-scorers.ts +13 -13
  44. package/evals/scorers/coordinator-discipline.evalite-test.ts +3 -2
  45. package/evals/scorers/coordinator-discipline.ts +13 -13
  46. package/examples/plugin-wrapper-template.ts +117 -0
  47. package/package.json +7 -5
  48. package/scripts/migrate-unknown-sessions.ts +349 -0
  49. package/src/compaction-capture.integration.test.ts +257 -0
  50. package/src/compaction-hook.test.ts +42 -0
  51. package/src/compaction-hook.ts +81 -0
  52. package/src/compaction-prompt-scorers.test.ts +299 -0
  53. package/src/compaction-prompt-scoring.ts +298 -0
  54. package/src/eval-capture.test.ts +422 -0
  55. package/src/eval-capture.ts +94 -2
  56. package/src/eval-gates.test.ts +306 -0
  57. package/src/eval-gates.ts +218 -0
  58. package/src/eval-history.test.ts +508 -0
  59. package/src/eval-history.ts +214 -0
  60. package/src/eval-learning.test.ts +378 -0
  61. package/src/eval-learning.ts +360 -0
  62. package/src/index.ts +61 -1
  63. package/src/post-compaction-tracker.test.ts +251 -0
  64. package/src/post-compaction-tracker.ts +237 -0
  65. package/src/swarm-decompose.ts +2 -2
  66. package/src/swarm-orchestrate.ts +2 -2
  67. package/src/swarm-prompts.ts +2 -2
  68. package/src/swarm-review.ts +3 -3
  69. /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
+ }
package/src/index.ts CHANGED
@@ -213,7 +213,7 @@ const SwarmPlugin: Plugin = async (
213
213
  if (isInCoordinatorContext()) {
214
214
  const ctx = getCoordinatorContext();
215
215
  const violation = detectCoordinatorViolation({
216
- sessionId: ctx.sessionId || "unknown",
216
+ sessionId: input.sessionID || "unknown",
217
217
  epicId: ctx.epicId || "unknown",
218
218
  toolName,
219
219
  toolArgs: output.args as Record<string, unknown>,
@@ -771,6 +771,66 @@ export {
771
771
  } from "./memory-tools";
772
772
  export type { Memory, SearchResult, SearchOptions } from "swarm-mail";
773
773
 
774
+ /**
775
+ * Re-export eval-history module
776
+ *
777
+ * Includes:
778
+ * - recordEvalRun - Record eval run to JSONL history
779
+ * - getScoreHistory - Get score history for a specific eval
780
+ * - getPhase - Get current phase based on run count and variance
781
+ * - calculateVariance - Calculate statistical variance of scores
782
+ * - ensureEvalHistoryDir - Ensure history directory exists
783
+ * - getEvalHistoryPath - Get path to eval history file
784
+ *
785
+ * Constants:
786
+ * - DEFAULT_EVAL_HISTORY_PATH - Default path (.opencode/eval-history.jsonl)
787
+ * - VARIANCE_THRESHOLD - Variance threshold for production phase (0.1)
788
+ * - BOOTSTRAP_THRESHOLD - Run count for bootstrap phase (10)
789
+ * - STABILIZATION_THRESHOLD - Run count for stabilization phase (50)
790
+ *
791
+ * Types:
792
+ * - Phase - Progressive phases (bootstrap | stabilization | production)
793
+ * - EvalRunRecord - Single eval run record
794
+ */
795
+ export {
796
+ recordEvalRun,
797
+ getScoreHistory,
798
+ getPhase,
799
+ calculateVariance,
800
+ ensureEvalHistoryDir,
801
+ getEvalHistoryPath,
802
+ DEFAULT_EVAL_HISTORY_PATH,
803
+ VARIANCE_THRESHOLD,
804
+ BOOTSTRAP_THRESHOLD,
805
+ STABILIZATION_THRESHOLD,
806
+ type Phase,
807
+ type EvalRunRecord,
808
+ } from "./eval-history";
809
+
810
+ /**
811
+ * Re-export eval-gates module
812
+ *
813
+ * Includes:
814
+ * - checkGate - Check if current score passes quality gate
815
+ * - DEFAULT_THRESHOLDS - Default regression thresholds by phase
816
+ *
817
+ * Types:
818
+ * - GateResult - Result from gate check
819
+ * - GateConfig - Configuration for gate thresholds
820
+ *
821
+ * Features:
822
+ * - Phase-based regression thresholds (Bootstrap: none, Stabilization: 10%, Production: 5%)
823
+ * - Configurable thresholds via GateConfig
824
+ * - Clear pass/fail messages with baseline comparison
825
+ * - Handles edge cases (division by zero, no history)
826
+ */
827
+ export {
828
+ checkGate,
829
+ DEFAULT_THRESHOLDS,
830
+ type GateResult,
831
+ type GateConfig,
832
+ } from "./eval-gates";
833
+
774
834
  /**
775
835
  * Re-export logger infrastructure
776
836
  *
@@ -0,0 +1,251 @@
1
+ /**
2
+ * Post-Compaction Tool Call Tracker Tests
3
+ *
4
+ * TDD: RED → GREEN → REFACTOR
5
+ *
6
+ * Tests tracking of tool calls after compaction resumption.
7
+ * Emits resumption_started on first tool call, then tool_call_tracked for each call (max 20).
8
+ * Detects coordinator violations: Edit, Write, swarmmail_reserve are forbidden.
9
+ */
10
+ import { describe, test, expect, beforeEach, mock } from "bun:test";
11
+ import {
12
+ createPostCompactionTracker,
13
+ type PostCompactionTracker,
14
+ type ToolCallEvent,
15
+ } from "./post-compaction-tracker";
16
+
17
+ describe("PostCompactionTracker - TDD", () => {
18
+ let tracker: PostCompactionTracker;
19
+ let mockCapture: ReturnType<typeof mock>;
20
+
21
+ beforeEach(() => {
22
+ mockCapture = mock((event: any) => {});
23
+ tracker = createPostCompactionTracker({
24
+ sessionId: "test-session",
25
+ epicId: "mjkwehsqnbm",
26
+ onEvent: mockCapture,
27
+ });
28
+ });
29
+
30
+ // ============================================================================
31
+ // RED: Test resumption_started event
32
+ // ============================================================================
33
+
34
+ test("emits resumption_started on first tool call", () => {
35
+ const toolCall: ToolCallEvent = {
36
+ tool: "read",
37
+ args: { filePath: "/test/file.ts" },
38
+ timestamp: Date.now(),
39
+ };
40
+
41
+ tracker.trackToolCall(toolCall);
42
+
43
+ expect(mockCapture).toHaveBeenCalledTimes(2); // resumption_started + tool_call_tracked
44
+ const firstCall = mockCapture.mock.calls[0][0];
45
+ expect(firstCall.compaction_type).toBe("resumption_started");
46
+ expect(firstCall.payload.session_id).toBe("test-session");
47
+ expect(firstCall.payload.epic_id).toBe("mjkwehsqnbm");
48
+ });
49
+
50
+ test("resumption_started only emitted once", () => {
51
+ tracker.trackToolCall({
52
+ tool: "read",
53
+ args: {},
54
+ timestamp: Date.now(),
55
+ });
56
+ tracker.trackToolCall({
57
+ tool: "glob",
58
+ args: {},
59
+ timestamp: Date.now(),
60
+ });
61
+
62
+ // First call: resumption_started + tool_call_tracked
63
+ // Second call: tool_call_tracked only
64
+ expect(mockCapture).toHaveBeenCalledTimes(3);
65
+
66
+ const calls = mockCapture.mock.calls;
67
+ expect(calls[0][0].compaction_type).toBe("resumption_started");
68
+ expect(calls[1][0].compaction_type).toBe("tool_call_tracked");
69
+ expect(calls[2][0].compaction_type).toBe("tool_call_tracked");
70
+ });
71
+
72
+ // ============================================================================
73
+ // RED: Test tool_call_tracked event
74
+ // ============================================================================
75
+
76
+ test("emits tool_call_tracked for each of first 20 calls", () => {
77
+ for (let i = 0; i < 20; i++) {
78
+ tracker.trackToolCall({
79
+ tool: `tool-${i}`,
80
+ args: {},
81
+ timestamp: Date.now(),
82
+ });
83
+ }
84
+
85
+ // First call: resumption_started + tool_call_tracked = 2
86
+ // Next 19 calls: tool_call_tracked only = 19
87
+ // Total: 21 events (1 resumption_started + 20 tool_call_tracked)
88
+ expect(mockCapture).toHaveBeenCalledTimes(21);
89
+
90
+ const trackedEvents = mockCapture.mock.calls.filter(
91
+ (call: any) => call[0].compaction_type === "tool_call_tracked",
92
+ );
93
+ expect(trackedEvents).toHaveLength(20);
94
+ });
95
+
96
+ test("tool_call_tracked includes tool name and args", () => {
97
+ tracker.trackToolCall({
98
+ tool: "edit",
99
+ args: { filePath: "/test.ts", oldString: "foo", newString: "bar" },
100
+ timestamp: Date.now(),
101
+ });
102
+
103
+ const trackedEvent = mockCapture.mock.calls.find(
104
+ (call: any) => call[0].compaction_type === "tool_call_tracked",
105
+ )?.[0];
106
+
107
+ expect(trackedEvent).toBeDefined();
108
+ expect(trackedEvent.payload.tool).toBe("edit");
109
+ expect(trackedEvent.payload.args.filePath).toBe("/test.ts");
110
+ expect(trackedEvent.payload.call_number).toBe(1);
111
+ });
112
+
113
+ // ============================================================================
114
+ // RED: Test coordinator violation detection
115
+ // ============================================================================
116
+
117
+ test("detects Edit as coordinator violation", () => {
118
+ tracker.trackToolCall({
119
+ tool: "edit",
120
+ args: { filePath: "/test.ts", oldString: "a", newString: "b" },
121
+ timestamp: Date.now(),
122
+ });
123
+
124
+ const trackedEvent = mockCapture.mock.calls.find(
125
+ (call: any) => call[0].compaction_type === "tool_call_tracked",
126
+ )?.[0];
127
+
128
+ expect(trackedEvent.payload.is_coordinator_violation).toBe(true);
129
+ expect(trackedEvent.payload.violation_reason).toBe(
130
+ "Coordinators NEVER edit files - spawn worker instead",
131
+ );
132
+ });
133
+
134
+ test("detects Write as coordinator violation", () => {
135
+ tracker.trackToolCall({
136
+ tool: "write",
137
+ args: { filePath: "/new.ts", content: "export {}" },
138
+ timestamp: Date.now(),
139
+ });
140
+
141
+ const trackedEvent = mockCapture.mock.calls.find(
142
+ (call: any) => call[0].compaction_type === "tool_call_tracked",
143
+ )?.[0];
144
+
145
+ expect(trackedEvent.payload.is_coordinator_violation).toBe(true);
146
+ expect(trackedEvent.payload.violation_reason).toBe(
147
+ "Coordinators NEVER write files - spawn worker instead",
148
+ );
149
+ });
150
+
151
+ test("detects swarmmail_reserve as coordinator violation", () => {
152
+ tracker.trackToolCall({
153
+ tool: "swarmmail_reserve",
154
+ args: { paths: ["/src/**"], reason: "test" },
155
+ timestamp: Date.now(),
156
+ });
157
+
158
+ const trackedEvent = mockCapture.mock.calls.find(
159
+ (call: any) => call[0].compaction_type === "tool_call_tracked",
160
+ )?.[0];
161
+
162
+ expect(trackedEvent.payload.is_coordinator_violation).toBe(true);
163
+ expect(trackedEvent.payload.violation_reason).toBe(
164
+ "Coordinators NEVER reserve files - workers reserve files",
165
+ );
166
+ });
167
+
168
+ test("does not flag Read as violation", () => {
169
+ tracker.trackToolCall({
170
+ tool: "read",
171
+ args: { filePath: "/test.ts" },
172
+ timestamp: Date.now(),
173
+ });
174
+
175
+ const trackedEvent = mockCapture.mock.calls.find(
176
+ (call: any) => call[0].compaction_type === "tool_call_tracked",
177
+ )?.[0];
178
+
179
+ expect(trackedEvent.payload.is_coordinator_violation).toBe(false);
180
+ expect(trackedEvent.payload.violation_reason).toBeUndefined();
181
+ });
182
+
183
+ test("does not flag swarm_spawn_subtask as violation", () => {
184
+ tracker.trackToolCall({
185
+ tool: "swarm_spawn_subtask",
186
+ args: { bead_id: "bd-123", subtask_title: "Test" },
187
+ timestamp: Date.now(),
188
+ });
189
+
190
+ const trackedEvent = mockCapture.mock.calls.find(
191
+ (call: any) => call[0].compaction_type === "tool_call_tracked",
192
+ )?.[0];
193
+
194
+ expect(trackedEvent.payload.is_coordinator_violation).toBe(false);
195
+ });
196
+
197
+ // ============================================================================
198
+ // RED: Test tracking stops after 20 calls
199
+ // ============================================================================
200
+
201
+ test("stops tracking after 20 calls", () => {
202
+ for (let i = 0; i < 25; i++) {
203
+ tracker.trackToolCall({
204
+ tool: `tool-${i}`,
205
+ args: {},
206
+ timestamp: Date.now(),
207
+ });
208
+ }
209
+
210
+ // Should only track first 20: 1 resumption_started + 20 tool_call_tracked
211
+ expect(mockCapture).toHaveBeenCalledTimes(21);
212
+ });
213
+
214
+ test("returns tracking status", () => {
215
+ expect(tracker.isTracking()).toBe(true);
216
+
217
+ for (let i = 0; i < 20; i++) {
218
+ tracker.trackToolCall({
219
+ tool: `tool-${i}`,
220
+ args: {},
221
+ timestamp: Date.now(),
222
+ });
223
+ }
224
+
225
+ expect(tracker.isTracking()).toBe(false);
226
+ });
227
+
228
+ // ============================================================================
229
+ // RED: Test configurable limit
230
+ // ============================================================================
231
+
232
+ test("respects custom call limit", () => {
233
+ const customTracker = createPostCompactionTracker({
234
+ sessionId: "test",
235
+ epicId: "test",
236
+ onEvent: mockCapture,
237
+ maxCalls: 5,
238
+ });
239
+
240
+ for (let i = 0; i < 10; i++) {
241
+ customTracker.trackToolCall({
242
+ tool: `tool-${i}`,
243
+ args: {},
244
+ timestamp: Date.now(),
245
+ });
246
+ }
247
+
248
+ // 1 resumption_started + 5 tool_call_tracked
249
+ expect(mockCapture).toHaveBeenCalledTimes(6);
250
+ });
251
+ });