opencode-swarm-plugin 0.37.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 (79) hide show
  1. package/.env +2 -0
  2. package/.hive/eval-results.json +26 -0
  3. package/.hive/issues.jsonl +20 -5
  4. package/.hive/memories.jsonl +35 -1
  5. package/.opencode/eval-history.jsonl +12 -0
  6. package/.turbo/turbo-build.log +4 -4
  7. package/.turbo/turbo-test.log +319 -319
  8. package/CHANGELOG.md +258 -0
  9. package/README.md +50 -0
  10. package/bin/swarm.test.ts +475 -0
  11. package/bin/swarm.ts +385 -208
  12. package/dist/compaction-hook.d.ts +1 -1
  13. package/dist/compaction-hook.d.ts.map +1 -1
  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 +81 -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 +59 -0
  25. package/dist/hive.d.ts.map +1 -1
  26. package/dist/index.d.ts +87 -0
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +823 -131
  29. package/dist/plugin.js +655 -131
  30. package/dist/post-compaction-tracker.d.ts +133 -0
  31. package/dist/post-compaction-tracker.d.ts.map +1 -0
  32. package/dist/swarm-decompose.d.ts +30 -0
  33. package/dist/swarm-decompose.d.ts.map +1 -1
  34. package/dist/swarm-orchestrate.d.ts +23 -0
  35. package/dist/swarm-orchestrate.d.ts.map +1 -1
  36. package/dist/swarm-prompts.d.ts +25 -1
  37. package/dist/swarm-prompts.d.ts.map +1 -1
  38. package/dist/swarm.d.ts +19 -0
  39. package/dist/swarm.d.ts.map +1 -1
  40. package/evals/README.md +595 -94
  41. package/evals/compaction-prompt.eval.ts +149 -0
  42. package/evals/coordinator-behavior.eval.ts +8 -8
  43. package/evals/fixtures/compaction-prompt-cases.ts +305 -0
  44. package/evals/lib/compaction-loader.test.ts +248 -0
  45. package/evals/lib/compaction-loader.ts +320 -0
  46. package/evals/lib/data-loader.test.ts +345 -0
  47. package/evals/lib/data-loader.ts +107 -6
  48. package/evals/scorers/compaction-prompt-scorers.ts +145 -0
  49. package/evals/scorers/compaction-scorers.ts +13 -13
  50. package/evals/scorers/coordinator-discipline.evalite-test.ts +3 -2
  51. package/evals/scorers/coordinator-discipline.ts +13 -13
  52. package/examples/plugin-wrapper-template.ts +177 -8
  53. package/package.json +7 -2
  54. package/scripts/migrate-unknown-sessions.ts +349 -0
  55. package/src/compaction-capture.integration.test.ts +257 -0
  56. package/src/compaction-hook.test.ts +139 -2
  57. package/src/compaction-hook.ts +113 -2
  58. package/src/compaction-prompt-scorers.test.ts +299 -0
  59. package/src/compaction-prompt-scoring.ts +298 -0
  60. package/src/eval-capture.test.ts +422 -0
  61. package/src/eval-capture.ts +94 -2
  62. package/src/eval-gates.test.ts +306 -0
  63. package/src/eval-gates.ts +218 -0
  64. package/src/eval-history.test.ts +508 -0
  65. package/src/eval-history.ts +214 -0
  66. package/src/eval-learning.test.ts +378 -0
  67. package/src/eval-learning.ts +360 -0
  68. package/src/index.ts +61 -1
  69. package/src/post-compaction-tracker.test.ts +251 -0
  70. package/src/post-compaction-tracker.ts +237 -0
  71. package/src/swarm-decompose.test.ts +40 -47
  72. package/src/swarm-decompose.ts +2 -2
  73. package/src/swarm-orchestrate.test.ts +270 -7
  74. package/src/swarm-orchestrate.ts +100 -13
  75. package/src/swarm-prompts.test.ts +121 -0
  76. package/src/swarm-prompts.ts +297 -4
  77. package/src/swarm-research.integration.test.ts +157 -0
  78. package/src/swarm-review.ts +3 -3
  79. /package/evals/{evalite.config.ts → evalite.config.ts.bak} +0 -0
@@ -0,0 +1,349 @@
1
+ #!/usr/bin/env bun
2
+
3
+ /**
4
+ * Migration script to re-attribute unknown.jsonl events to proper session files
5
+ *
6
+ * Strategy:
7
+ * 1. Read all events from unknown.jsonl
8
+ * 2. For each event, find matching session by epic_id
9
+ * 3. Append to existing session or create new session file
10
+ * 4. Rename unknown.jsonl to unknown.jsonl.migrated
11
+ *
12
+ * Usage:
13
+ * bun run scripts/migrate-unknown-sessions.ts [--dry-run]
14
+ */
15
+
16
+ import { execSync } from "node:child_process";
17
+ import { readFileSync, renameSync, writeFileSync } from "node:fs";
18
+ import { join } from "node:path";
19
+
20
+ interface SessionEvent {
21
+ session_id: string;
22
+ epic_id: string;
23
+ timestamp: string;
24
+ event_type: string;
25
+ [key: string]: unknown;
26
+ }
27
+
28
+ interface MigrationStats {
29
+ totalEvents: number;
30
+ migratedEvents: number;
31
+ sessionsUpdated: number;
32
+ sessionsCreated: number;
33
+ unattributableEvents: number;
34
+ eventsByEpic: Map<string, number>;
35
+ }
36
+
37
+ const SESSIONS_DIR = join(process.env.HOME || "~", ".config/swarm-tools/sessions");
38
+ const UNKNOWN_FILE = join(SESSIONS_DIR, "unknown.jsonl");
39
+ const MIGRATED_FILE = join(SESSIONS_DIR, "unknown.jsonl.migrated");
40
+
41
+ /**
42
+ * Atomic file write using temp file + rename
43
+ * Based on learned pattern for crash-safe state persistence
44
+ */
45
+ function atomicWriteFile(path: string, content: string): void {
46
+ const dir = join(path, "..");
47
+ const tempFile = `${dir}/.${Date.now()}.tmp`;
48
+
49
+ try {
50
+ // Write to temp file in same directory (required for atomic rename)
51
+ writeFileSync(tempFile, content, "utf-8");
52
+
53
+ // Atomic rename (POSIX guarantees atomicity on same filesystem)
54
+ renameSync(tempFile, path);
55
+
56
+ // Sync directory entry (ensures rename is flushed)
57
+ execSync(`sync "${dir}"`, { stdio: "ignore" });
58
+ } catch (error) {
59
+ // Cleanup temp file on error
60
+ try {
61
+ execSync(`rm -f "${tempFile}"`, { stdio: "ignore" });
62
+ } catch {
63
+ // Ignore cleanup errors
64
+ }
65
+ throw error;
66
+ }
67
+ }
68
+
69
+ /**
70
+ * Read JSONL file and parse events
71
+ */
72
+ function readJSONL(path: string): SessionEvent[] {
73
+ try {
74
+ const content = readFileSync(path, "utf-8");
75
+ return content
76
+ .trim()
77
+ .split("\n")
78
+ .filter((line) => line.trim())
79
+ .map((line) => JSON.parse(line));
80
+ } catch (error) {
81
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") {
82
+ return [];
83
+ }
84
+ throw error;
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Build index of epic_id -> session_id from all existing session files
90
+ */
91
+ function buildEpicIndex(): Map<string, string> {
92
+ const epicIndex = new Map<string, string>();
93
+
94
+ try {
95
+ const files = execSync(`ls "${SESSIONS_DIR}"/ses_*.jsonl 2>/dev/null || true`, {
96
+ encoding: "utf-8",
97
+ })
98
+ .trim()
99
+ .split("\n")
100
+ .filter((f) => f);
101
+
102
+ for (const sessionFile of files) {
103
+ const events = readJSONL(sessionFile);
104
+ const sessionId = events[0]?.session_id;
105
+
106
+ if (!sessionId) continue;
107
+
108
+ // Index all epic_ids in this session
109
+ for (const event of events) {
110
+ if (event.epic_id && !epicIndex.has(event.epic_id)) {
111
+ epicIndex.set(event.epic_id, sessionId);
112
+ }
113
+ }
114
+ }
115
+ } catch (error) {
116
+ console.error("Error building epic index:", error);
117
+ }
118
+
119
+ return epicIndex;
120
+ }
121
+
122
+ /**
123
+ * Generate a new session ID
124
+ * Format: ses_<base58-like-id>
125
+ */
126
+ function generateSessionId(): string {
127
+ // Generate random base58-like suffix (avoiding 0, O, I, l for readability)
128
+ const chars = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
129
+ let suffix = "";
130
+ for (let i = 0; i < 22; i++) {
131
+ suffix += chars[Math.floor(Math.random() * chars.length)];
132
+ }
133
+
134
+ return `ses_${suffix}`;
135
+ }
136
+
137
+ /**
138
+ * Append events to a session file atomically
139
+ */
140
+ function appendToSession(sessionId: string, events: SessionEvent[], dryRun: boolean): void {
141
+ const sessionFile = `${SESSIONS_DIR}/${sessionId}.jsonl`;
142
+
143
+ // Read existing events (if file exists)
144
+ const existingEvents = readJSONL(sessionFile);
145
+
146
+ // Create set of existing event fingerprints for idempotency check
147
+ const existingFingerprints = new Set(
148
+ existingEvents.map((e) =>
149
+ JSON.stringify({ epic_id: e.epic_id, timestamp: e.timestamp, event_type: e.event_type })
150
+ )
151
+ );
152
+
153
+ // Filter out events that already exist (idempotency)
154
+ const newEvents = events.filter((e) => {
155
+ const fingerprint = JSON.stringify({
156
+ epic_id: e.epic_id,
157
+ timestamp: e.timestamp,
158
+ event_type: e.event_type,
159
+ });
160
+ return !existingFingerprints.has(fingerprint);
161
+ });
162
+
163
+ if (newEvents.length === 0) {
164
+ console.log(` → No new events to add to ${sessionId}.jsonl (all already exist)`);
165
+ return;
166
+ }
167
+
168
+ // Update session_id for all events
169
+ const updatedEvents = newEvents.map((e) => ({ ...e, session_id: sessionId }));
170
+
171
+ // Combine and write
172
+ const allEvents = [...existingEvents, ...updatedEvents];
173
+ const content = allEvents.map((e) => JSON.stringify(e)).join("\n") + "\n";
174
+
175
+ if (dryRun) {
176
+ console.log(` → Would write ${newEvents.length} events to ${sessionId}.jsonl`);
177
+ } else {
178
+ atomicWriteFile(sessionFile, content);
179
+ console.log(` → Wrote ${newEvents.length} events to ${sessionId}.jsonl`);
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Main migration logic
185
+ */
186
+ function migrate(dryRun: boolean = false): MigrationStats {
187
+ const stats: MigrationStats = {
188
+ totalEvents: 0,
189
+ migratedEvents: 0,
190
+ sessionsUpdated: 0,
191
+ sessionsCreated: 0,
192
+ unattributableEvents: 0,
193
+ eventsByEpic: new Map(),
194
+ };
195
+
196
+ console.log("🔍 Reading unknown.jsonl...");
197
+ const unknownEvents = readJSONL(UNKNOWN_FILE);
198
+ stats.totalEvents = unknownEvents.length;
199
+
200
+ if (stats.totalEvents === 0) {
201
+ console.log("✅ No events to migrate (unknown.jsonl is empty)");
202
+ return stats;
203
+ }
204
+
205
+ console.log(`📊 Found ${stats.totalEvents} events in unknown.jsonl`);
206
+
207
+ console.log("🗂️ Building epic_id index from existing sessions...");
208
+ const epicIndex = buildEpicIndex();
209
+ console.log(`📇 Indexed ${epicIndex.size} epic_ids across existing sessions`);
210
+
211
+ // Group events by target session
212
+ const eventsBySession = new Map<string, SessionEvent[]>();
213
+ const newSessions = new Set<string>();
214
+
215
+ for (const event of unknownEvents) {
216
+ const { epic_id } = event;
217
+
218
+ if (!epic_id) {
219
+ console.warn(`⚠️ Event without epic_id: ${JSON.stringify(event)}`);
220
+ stats.unattributableEvents++;
221
+ continue;
222
+ }
223
+
224
+ // Track events per epic
225
+ stats.eventsByEpic.set(epic_id, (stats.eventsByEpic.get(epic_id) || 0) + 1);
226
+
227
+ // Find or create session
228
+ let sessionId = epicIndex.get(epic_id);
229
+
230
+ if (!sessionId) {
231
+ // Create new session for this epic_id
232
+ sessionId = generateSessionId();
233
+ epicIndex.set(epic_id, sessionId);
234
+ newSessions.add(sessionId);
235
+ console.log(`🆕 Creating new session ${sessionId} for epic ${epic_id}`);
236
+ }
237
+
238
+ // Group events by session
239
+ if (!eventsBySession.has(sessionId)) {
240
+ eventsBySession.set(sessionId, []);
241
+ }
242
+ const sessionEvents = eventsBySession.get(sessionId);
243
+ if (sessionEvents) {
244
+ sessionEvents.push(event);
245
+ }
246
+ }
247
+
248
+ // Write events to sessions
249
+ console.log(`\n📝 Writing events to ${eventsBySession.size} session files...`);
250
+
251
+ for (const [sessionId, events] of eventsBySession) {
252
+ const isNew = newSessions.has(sessionId);
253
+ console.log(`\n${isNew ? "🆕" : "➕"} Session ${sessionId} (${events.length} events)`);
254
+
255
+ appendToSession(sessionId, events, dryRun);
256
+
257
+ stats.migratedEvents += events.length;
258
+ if (isNew) {
259
+ stats.sessionsCreated++;
260
+ } else {
261
+ stats.sessionsUpdated++;
262
+ }
263
+ }
264
+
265
+ // Rename unknown.jsonl to .migrated
266
+ if (!dryRun) {
267
+ console.log(`\n🏷️ Renaming unknown.jsonl to unknown.jsonl.migrated...`);
268
+ renameSync(UNKNOWN_FILE, MIGRATED_FILE);
269
+ } else {
270
+ console.log(`\n🏷️ Would rename unknown.jsonl to unknown.jsonl.migrated`);
271
+ }
272
+
273
+ return stats;
274
+ }
275
+
276
+ /**
277
+ * Print summary
278
+ */
279
+ function printSummary(stats: MigrationStats, dryRun: boolean): void {
280
+ console.log("\n" + "=".repeat(60));
281
+ console.log(dryRun ? "DRY RUN SUMMARY" : "MIGRATION SUMMARY");
282
+ console.log("=".repeat(60));
283
+ console.log(`Total events in unknown.jsonl: ${stats.totalEvents}`);
284
+ console.log(`Events migrated: ${stats.migratedEvents}`);
285
+ console.log(`Sessions updated: ${stats.sessionsUpdated}`);
286
+ console.log(`Sessions created: ${stats.sessionsCreated}`);
287
+ console.log(`Unattributable events: ${stats.unattributableEvents}`);
288
+ console.log(`Unique epic_ids: ${stats.eventsByEpic.size}`);
289
+
290
+ if (stats.eventsByEpic.size > 0 && stats.eventsByEpic.size <= 10) {
291
+ console.log("\nEvents by epic_id:");
292
+ for (const [epicId, count] of Array.from(stats.eventsByEpic.entries()).sort((a, b) => b[1] - a[1])) {
293
+ console.log(` ${epicId}: ${count} events`);
294
+ }
295
+ }
296
+
297
+ console.log("=".repeat(60));
298
+
299
+ if (dryRun) {
300
+ console.log("\n💡 Run without --dry-run to perform actual migration");
301
+ } else {
302
+ console.log("\n✅ Migration complete!");
303
+ }
304
+ }
305
+
306
+ // Show help
307
+ if (process.argv.includes("--help") || process.argv.includes("-h")) {
308
+ console.log(`
309
+ Migration script to re-attribute unknown.jsonl events to proper session files
310
+
311
+ USAGE:
312
+ bun run scripts/migrate-unknown-sessions.ts [OPTIONS]
313
+
314
+ OPTIONS:
315
+ --dry-run Preview changes without modifying files
316
+ --help, -h Show this help message
317
+
318
+ DESCRIPTION:
319
+ This script reads events from unknown.jsonl and re-attributes them to the
320
+ correct session files based on their epic_id. Events are matched to existing
321
+ sessions, or new session files are created as needed.
322
+
323
+ The script is idempotent - running it multiple times will not duplicate events.
324
+
325
+ EXAMPLES:
326
+ # Preview migration
327
+ bun run scripts/migrate-unknown-sessions.ts --dry-run
328
+
329
+ # Perform migration
330
+ bun run scripts/migrate-unknown-sessions.ts
331
+ `);
332
+ process.exit(0);
333
+ }
334
+
335
+ // Main execution
336
+ const dryRun = process.argv.includes("--dry-run");
337
+
338
+ if (dryRun) {
339
+ console.log("🧪 DRY RUN MODE - No files will be modified\n");
340
+ }
341
+
342
+ try {
343
+ const stats = migrate(dryRun);
344
+ printSummary(stats, dryRun);
345
+ process.exit(0);
346
+ } catch (error) {
347
+ console.error("\n❌ Migration failed:", error);
348
+ process.exit(1);
349
+ }
@@ -0,0 +1,257 @@
1
+ /**
2
+ * Integration test for compaction event capture
3
+ *
4
+ * Verifies that captureCompactionEvent writes events to session JSONL
5
+ * and that all event types are captured with correct data.
6
+ */
7
+
8
+ import { describe, expect, it, afterAll } from "bun:test";
9
+ import { existsSync, unlinkSync } from "node:fs";
10
+ import {
11
+ captureCompactionEvent,
12
+ readSessionEvents,
13
+ getSessionPath,
14
+ } from "./eval-capture";
15
+
16
+ describe("Compaction Event Capture Integration", () => {
17
+ const testSessionId = `test-compaction-${Date.now()}`;
18
+ const sessionPath = getSessionPath(testSessionId);
19
+
20
+ afterAll(() => {
21
+ // Clean up test session file
22
+ if (existsSync(sessionPath)) {
23
+ unlinkSync(sessionPath);
24
+ }
25
+ });
26
+
27
+ it("captures detection_complete event with confidence and reasons", () => {
28
+ captureCompactionEvent({
29
+ session_id: testSessionId,
30
+ epic_id: "bd-test-123",
31
+ compaction_type: "detection_complete",
32
+ payload: {
33
+ confidence: "high",
34
+ detected: true,
35
+ reasons: ["3 cells in_progress", "2 open subtasks"],
36
+ session_scan_contributed: true,
37
+ session_scan_reasons: ["swarm tool calls found in session"],
38
+ epic_id: "bd-test-123",
39
+ epic_title: "Test Epic",
40
+ subtask_count: 5,
41
+ },
42
+ });
43
+
44
+ // Verify event was written to session file
45
+ expect(existsSync(sessionPath)).toBe(true);
46
+
47
+ // Read events from session
48
+ const events = readSessionEvents(testSessionId);
49
+ expect(events.length).toBe(1);
50
+
51
+ const event = events[0];
52
+ expect(event.session_id).toBe(testSessionId);
53
+ expect(event.epic_id).toBe("bd-test-123");
54
+ expect(event.event_type).toBe("COMPACTION");
55
+ expect(event.compaction_type).toBe("detection_complete");
56
+
57
+ // Verify payload structure
58
+ expect(event.payload.confidence).toBe("high");
59
+ expect(event.payload.detected).toBe(true);
60
+ expect(event.payload.reasons).toEqual(["3 cells in_progress", "2 open subtasks"]);
61
+ expect(event.payload.epic_id).toBe("bd-test-123");
62
+ expect(event.payload.epic_title).toBe("Test Epic");
63
+ expect(event.payload.subtask_count).toBe(5);
64
+ });
65
+
66
+ it("captures prompt_generated event with FULL prompt content", () => {
67
+ const fullPrompt = `
68
+ ┌─────────────────────────────────────────┐
69
+ │ 🐝 YOU ARE THE COORDINATOR 🐝 │
70
+ └─────────────────────────────────────────┘
71
+
72
+ # Swarm Continuation
73
+
74
+ **NON-NEGOTIABLE: YOU ARE THE COORDINATOR.**
75
+
76
+ ## Epic State
77
+ **ID:** bd-epic-456
78
+ **Title:** Refactor authentication
79
+ **Status:** 2/5 subtasks complete
80
+
81
+ ## Next Actions
82
+ 1. Check swarm_status(epic_id="bd-epic-456")
83
+ 2. Review completed work
84
+ 3. Spawn remaining subtasks
85
+ `.trim();
86
+
87
+ captureCompactionEvent({
88
+ session_id: testSessionId,
89
+ epic_id: "bd-epic-456",
90
+ compaction_type: "prompt_generated",
91
+ payload: {
92
+ prompt_length: fullPrompt.length,
93
+ full_prompt: fullPrompt, // FULL content, not truncated
94
+ context_type: "llm_generated",
95
+ duration_ms: 1234,
96
+ },
97
+ });
98
+
99
+ const events = readSessionEvents(testSessionId);
100
+ const promptEvent = events.find((e) => e.compaction_type === "prompt_generated");
101
+
102
+ expect(promptEvent).toBeDefined();
103
+ if (promptEvent) {
104
+ expect(promptEvent.payload.full_prompt).toBe(fullPrompt);
105
+ expect(promptEvent.payload.prompt_length).toBe(fullPrompt.length);
106
+ expect(promptEvent.payload.context_type).toBe("llm_generated");
107
+ expect(promptEvent.payload.duration_ms).toBe(1234);
108
+ }
109
+ });
110
+
111
+ it("captures context_injected event with FULL content", () => {
112
+ const fullContent = `[Swarm compaction: LLM-generated, high confidence]
113
+
114
+ # 🐝 Swarm State
115
+
116
+ **Epic:** bd-epic-789 - Add user permissions
117
+ **Project:** /Users/test/project
118
+
119
+ **Subtasks:**
120
+ - 2 closed
121
+ - 1 in_progress
122
+ - 2 open
123
+
124
+ ## COORDINATOR MANDATES
125
+
126
+ ⛔ NEVER use edit/write directly - SPAWN A WORKER
127
+ ✅ ALWAYS use swarm_spawn_subtask for implementation
128
+ ✅ ALWAYS review with swarm_review
129
+ `;
130
+
131
+ captureCompactionEvent({
132
+ session_id: testSessionId,
133
+ epic_id: "bd-epic-789",
134
+ compaction_type: "context_injected",
135
+ payload: {
136
+ full_content: fullContent, // FULL content, not truncated
137
+ content_length: fullContent.length,
138
+ injection_method: "output.prompt",
139
+ context_type: "llm_generated",
140
+ },
141
+ });
142
+
143
+ const events = readSessionEvents(testSessionId);
144
+ const injectEvent = events.find((e) => e.compaction_type === "context_injected");
145
+
146
+ expect(injectEvent).toBeDefined();
147
+ if (injectEvent) {
148
+ expect(injectEvent.payload.full_content).toBe(fullContent);
149
+ expect(injectEvent.payload.content_length).toBe(fullContent.length);
150
+ expect(injectEvent.payload.injection_method).toBe("output.prompt");
151
+ expect(injectEvent.payload.context_type).toBe("llm_generated");
152
+ }
153
+ });
154
+
155
+ it("captures all three event types in sequence", () => {
156
+ const sequenceSessionId = `test-sequence-${Date.now()}`;
157
+ const sequencePath = getSessionPath(sequenceSessionId);
158
+
159
+ try {
160
+ // Simulate compaction lifecycle
161
+
162
+ // 1. Detection
163
+ captureCompactionEvent({
164
+ session_id: sequenceSessionId,
165
+ epic_id: "bd-seq-123",
166
+ compaction_type: "detection_complete",
167
+ payload: {
168
+ confidence: "medium",
169
+ detected: true,
170
+ reasons: ["1 unclosed epic"],
171
+ },
172
+ });
173
+
174
+ // 2. Prompt generation
175
+ captureCompactionEvent({
176
+ session_id: sequenceSessionId,
177
+ epic_id: "bd-seq-123",
178
+ compaction_type: "prompt_generated",
179
+ payload: {
180
+ full_prompt: "Test prompt content",
181
+ prompt_length: 19,
182
+ },
183
+ });
184
+
185
+ // 3. Context injection
186
+ captureCompactionEvent({
187
+ session_id: sequenceSessionId,
188
+ epic_id: "bd-seq-123",
189
+ compaction_type: "context_injected",
190
+ payload: {
191
+ full_content: "Test context content",
192
+ content_length: 20,
193
+ },
194
+ });
195
+
196
+ // Verify all three events captured
197
+ const events = readSessionEvents(sequenceSessionId);
198
+ expect(events.length).toBe(3);
199
+
200
+ const types = events.map((e) => e.compaction_type);
201
+ expect(types).toContain("detection_complete");
202
+ expect(types).toContain("prompt_generated");
203
+ expect(types).toContain("context_injected");
204
+
205
+ // Verify order (chronological by timestamp)
206
+ const timestamps = events.map((e) => new Date(e.timestamp).getTime());
207
+ expect(timestamps[0]).toBeLessThanOrEqual(timestamps[1]);
208
+ expect(timestamps[1]).toBeLessThanOrEqual(timestamps[2]);
209
+ } finally {
210
+ // Clean up
211
+ if (existsSync(sequencePath)) {
212
+ unlinkSync(sequencePath);
213
+ }
214
+ }
215
+ });
216
+
217
+ it("validates event schema with Zod", () => {
218
+ // This should not throw - captureCompactionEvent validates internally
219
+ expect(() => {
220
+ captureCompactionEvent({
221
+ session_id: testSessionId,
222
+ epic_id: "bd-validate-123",
223
+ compaction_type: "detection_complete",
224
+ payload: { confidence: "high" },
225
+ });
226
+ }).not.toThrow();
227
+ });
228
+
229
+ it("rejects invalid compaction_type", () => {
230
+ expect(() => {
231
+ captureCompactionEvent({
232
+ session_id: testSessionId,
233
+ epic_id: "bd-invalid-123",
234
+ // @ts-expect-error - intentionally invalid type
235
+ compaction_type: "invalid_type",
236
+ payload: {},
237
+ });
238
+ }).toThrow();
239
+ });
240
+
241
+ it("handles empty epic_id gracefully", () => {
242
+ captureCompactionEvent({
243
+ session_id: testSessionId,
244
+ epic_id: "unknown",
245
+ compaction_type: "detection_complete",
246
+ payload: {
247
+ confidence: "none",
248
+ detected: false,
249
+ reasons: [],
250
+ },
251
+ });
252
+
253
+ const events = readSessionEvents(testSessionId);
254
+ const unknownEvent = events.find((e) => e.epic_id === "unknown");
255
+ expect(unknownEvent).toBeDefined();
256
+ });
257
+ });