opencode-swarm-plugin 0.42.9 → 0.43.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.
@@ -0,0 +1,476 @@
1
+ /**
2
+ * RED PHASE: Export Tools Tests
3
+ *
4
+ * Tests for exporting cell events to:
5
+ * 1. OTLP (OpenTelemetry Protocol) - distributed tracing format
6
+ * 2. CSV - spreadsheet/analysis format
7
+ * 3. JSON - generic interchange format
8
+ *
9
+ * These tests SHOULD FAIL because export-tools.ts doesn't exist yet.
10
+ * Implementation comes in GREEN phase.
11
+ */
12
+
13
+ import { describe, test, expect } from "bun:test";
14
+ import { exportToOTLP, exportToCSV, exportToJSON } from "./export-tools.js";
15
+ import type { CellEvent } from "./schemas/cell-events.js";
16
+
17
+ // ============================================================================
18
+ // Test Fixtures - Known Event Data
19
+ // ============================================================================
20
+
21
+ /**
22
+ * Fixture: Cell created event with known timestamp
23
+ */
24
+ const fixtureCreated: CellEvent = {
25
+ type: "cell_created",
26
+ project_key: "/test/project",
27
+ timestamp: 1735142400000, // 2024-12-25 12:00:00 UTC
28
+ cell_id: "test-epic-abc123",
29
+ title: "Implement authentication",
30
+ description: "Add OAuth2 flow with JWT tokens",
31
+ issue_type: "feature",
32
+ priority: 2,
33
+ created_by: "BlueOcean",
34
+ metadata: {
35
+ epic_id: "test-epic-parent",
36
+ strategy: "feature-based",
37
+ },
38
+ };
39
+
40
+ /**
41
+ * Fixture: Cell status changed event
42
+ */
43
+ const fixtureStatusChanged: CellEvent = {
44
+ type: "cell_status_changed",
45
+ project_key: "/test/project",
46
+ timestamp: 1735142460000, // 1 minute after creation
47
+ cell_id: "test-epic-abc123",
48
+ from_status: "open",
49
+ to_status: "in_progress",
50
+ changed_by: "BlueOcean",
51
+ };
52
+
53
+ /**
54
+ * Fixture: Cell closed event with special characters in reason
55
+ */
56
+ const fixtureClosedWithSpecialChars: CellEvent = {
57
+ type: "cell_closed",
58
+ project_key: "/test/project",
59
+ timestamp: 1735146000000, // 1 hour after creation
60
+ cell_id: "test-epic-abc123",
61
+ reason: 'Completed: implemented OAuth2, added "refresh token" logic, tested with mock provider',
62
+ closed_by: "BlueOcean",
63
+ files_touched: ["src/auth/oauth.ts", "src/auth/jwt.ts"],
64
+ duration_ms: 3600000, // 1 hour
65
+ };
66
+
67
+ /**
68
+ * Fixture: Cell with commas and quotes in title (CSV edge case)
69
+ */
70
+ const fixtureCsvEdgeCase: CellEvent = {
71
+ type: "cell_created",
72
+ project_key: "/test/project",
73
+ timestamp: 1735142400000,
74
+ cell_id: "test-csv-edge",
75
+ title: 'Fix bug in parser: handle "quoted strings", commas, and newlines',
76
+ issue_type: "bug",
77
+ priority: 1,
78
+ };
79
+
80
+ // ============================================================================
81
+ // OTLP Export Tests
82
+ // ============================================================================
83
+
84
+ describe("exportToOTLP", () => {
85
+ test("produces valid OpenTelemetry JSON structure", () => {
86
+ const events = [fixtureCreated, fixtureStatusChanged, fixtureClosedWithSpecialChars];
87
+ const otlp = exportToOTLP(events);
88
+
89
+ // Should have top-level OTLP structure
90
+ expect(otlp).toHaveProperty("resourceSpans");
91
+ expect(Array.isArray(otlp.resourceSpans)).toBe(true);
92
+ expect(otlp.resourceSpans.length).toBeGreaterThan(0);
93
+
94
+ // First resource span should have scope and spans
95
+ const resourceSpan = otlp.resourceSpans[0];
96
+ expect(resourceSpan).toHaveProperty("resource");
97
+ expect(resourceSpan).toHaveProperty("scopeSpans");
98
+ expect(Array.isArray(resourceSpan.scopeSpans)).toBe(true);
99
+
100
+ // Scope should identify swarm
101
+ const scopeSpan = resourceSpan.scopeSpans[0];
102
+ expect(scopeSpan.scope.name).toBe("swarm");
103
+ });
104
+
105
+ test("maps epic_id to trace_id (hex string)", () => {
106
+ const events = [fixtureCreated];
107
+ const otlp = exportToOTLP(events);
108
+
109
+ const spans = otlp.resourceSpans[0].scopeSpans[0].spans;
110
+ expect(spans.length).toBeGreaterThan(0);
111
+
112
+ const span = spans[0];
113
+ expect(span).toHaveProperty("traceId");
114
+ expect(typeof span.traceId).toBe("string");
115
+
116
+ // trace_id should be hex string derived from epic_id
117
+ // Epic ID from metadata: "test-epic-parent"
118
+ expect(span.traceId).toMatch(/^[0-9a-f]+$/);
119
+ expect(span.traceId.length).toBe(32); // OTLP trace_id is 16 bytes = 32 hex chars
120
+ });
121
+
122
+ test("maps cell_id to span_id (hex string)", () => {
123
+ const events = [fixtureCreated];
124
+ const otlp = exportToOTLP(events);
125
+
126
+ const spans = otlp.resourceSpans[0].scopeSpans[0].spans;
127
+ const span = spans[0];
128
+
129
+ expect(span).toHaveProperty("spanId");
130
+ expect(typeof span.spanId).toBe("string");
131
+
132
+ // span_id should be hex string derived from cell_id
133
+ // Cell ID: "test-epic-abc123"
134
+ expect(span.spanId).toMatch(/^[0-9a-f]+$/);
135
+ expect(span.spanId.length).toBe(16); // OTLP span_id is 8 bytes = 16 hex chars
136
+ });
137
+
138
+ test("maps timestamp to startTimeUnixNano", () => {
139
+ const events = [fixtureCreated];
140
+ const otlp = exportToOTLP(events);
141
+
142
+ const spans = otlp.resourceSpans[0].scopeSpans[0].spans;
143
+ const span = spans[0];
144
+
145
+ expect(span).toHaveProperty("startTimeUnixNano");
146
+
147
+ // Should be string representation of nanoseconds
148
+ // fixtureCreated.timestamp = 1735142400000 ms
149
+ // In nanoseconds: 1735142400000 * 1_000_000
150
+ const expectedNano = "1735142400000000000";
151
+ expect(span.startTimeUnixNano).toBe(expectedNano);
152
+ });
153
+
154
+ test("maps event type to span name", () => {
155
+ const events = [fixtureCreated, fixtureStatusChanged, fixtureClosedWithSpecialChars];
156
+ const otlp = exportToOTLP(events);
157
+
158
+ const spans = otlp.resourceSpans[0].scopeSpans[0].spans;
159
+
160
+ // Should have 3 spans, one per event
161
+ expect(spans.length).toBe(3);
162
+
163
+ // Event types become span names
164
+ expect(spans[0].name).toBe("cell_created");
165
+ expect(spans[1].name).toBe("cell_status_changed");
166
+ expect(spans[2].name).toBe("cell_closed");
167
+ });
168
+
169
+ test("includes event payload as span attributes", () => {
170
+ const events = [fixtureCreated];
171
+ const otlp = exportToOTLP(events);
172
+
173
+ const spans = otlp.resourceSpans[0].scopeSpans[0].spans;
174
+ const span = spans[0];
175
+
176
+ expect(span).toHaveProperty("attributes");
177
+ expect(Array.isArray(span.attributes)).toBe(true);
178
+
179
+ // Should include key event fields as attributes
180
+ const attrs = span.attributes;
181
+
182
+ // Find specific attributes by key
183
+ const titleAttr = attrs.find((a: { key: string }) => a.key === "cell.title");
184
+ expect(titleAttr).toBeDefined();
185
+ expect(titleAttr.value.stringValue).toBe("Implement authentication");
186
+
187
+ const priorityAttr = attrs.find((a: { key: string }) => a.key === "cell.priority");
188
+ expect(priorityAttr).toBeDefined();
189
+ expect(priorityAttr.value.intValue).toBe(2);
190
+
191
+ const typeAttr = attrs.find((a: { key: string }) => a.key === "cell.type");
192
+ expect(typeAttr).toBeDefined();
193
+ expect(typeAttr.value.stringValue).toBe("feature");
194
+ });
195
+
196
+ test("handles events with missing epic_id in metadata", () => {
197
+ // Event without epic_id - should derive trace_id from project_key
198
+ const eventWithoutEpic: CellEvent = {
199
+ type: "cell_created",
200
+ project_key: "/test/project",
201
+ timestamp: 1735142400000,
202
+ cell_id: "standalone-cell",
203
+ title: "Standalone task",
204
+ issue_type: "task",
205
+ priority: 1,
206
+ };
207
+
208
+ const otlp = exportToOTLP([eventWithoutEpic]);
209
+ const spans = otlp.resourceSpans[0].scopeSpans[0].spans;
210
+ const span = spans[0];
211
+
212
+ // Should still have valid trace_id (derived from project_key)
213
+ expect(span.traceId).toMatch(/^[0-9a-f]{32}$/);
214
+ expect(span.spanId).toMatch(/^[0-9a-f]{16}$/);
215
+ });
216
+
217
+ test("preserves event ordering in spans array", () => {
218
+ const events = [fixtureCreated, fixtureStatusChanged, fixtureClosedWithSpecialChars];
219
+ const otlp = exportToOTLP(events);
220
+
221
+ const spans = otlp.resourceSpans[0].scopeSpans[0].spans;
222
+
223
+ // Spans should be in same order as input events
224
+ expect(spans[0].name).toBe("cell_created");
225
+ expect(spans[1].name).toBe("cell_status_changed");
226
+ expect(spans[2].name).toBe("cell_closed");
227
+
228
+ // Timestamps should be monotonically increasing
229
+ const t0 = BigInt(spans[0].startTimeUnixNano);
230
+ const t1 = BigInt(spans[1].startTimeUnixNano);
231
+ const t2 = BigInt(spans[2].startTimeUnixNano);
232
+
233
+ expect(t1).toBeGreaterThan(t0);
234
+ expect(t2).toBeGreaterThan(t1);
235
+ });
236
+ });
237
+
238
+ // ============================================================================
239
+ // CSV Export Tests
240
+ // ============================================================================
241
+
242
+ describe("exportToCSV", () => {
243
+ test("includes CSV headers", () => {
244
+ const events = [fixtureCreated];
245
+ const csv = exportToCSV(events);
246
+
247
+ const lines = csv.split("\n");
248
+
249
+ // First line should be headers
250
+ expect(lines[0]).toBe("id,type,timestamp,project_key,cell_id,payload");
251
+ });
252
+
253
+ test("escapes commas in payload fields", () => {
254
+ const events = [fixtureCsvEdgeCase];
255
+ const csv = exportToCSV(events);
256
+
257
+ const lines = csv.split("\n");
258
+
259
+ // Title has commas: 'Fix bug in parser: handle "quoted strings", commas, and newlines'
260
+ // CSV should quote the entire payload field
261
+ const dataLine = lines[1];
262
+
263
+ // Should contain quoted payload with escaped inner quotes
264
+ expect(dataLine).toContain('"');
265
+
266
+ // Should NOT have unquoted commas in payload (would break CSV parsing)
267
+ // The payload field itself should be wrapped in quotes if it contains commas
268
+ const fields = dataLine.match(/("(?:[^"]|"")*"|[^,]*)/g);
269
+ expect(fields).toBeDefined();
270
+
271
+ // Last non-empty field (payload) should be quoted
272
+ const nonEmptyFields = fields!.filter((f) => f !== "");
273
+ const payloadField = nonEmptyFields[nonEmptyFields.length - 1];
274
+ expect(payloadField.startsWith('"')).toBe(true);
275
+ });
276
+
277
+ test("escapes double quotes in payload", () => {
278
+ const events = [fixtureCsvEdgeCase];
279
+ const csv = exportToCSV(events);
280
+
281
+ const lines = csv.split("\n");
282
+ const dataLine = lines[1];
283
+
284
+ // Original title: 'Fix bug in parser: handle "quoted strings", commas, and newlines'
285
+ // In CSV, inner quotes should be escaped as ""
286
+ expect(dataLine).toContain('""quoted strings""');
287
+ });
288
+
289
+ test("one event per line (no embedded newlines)", () => {
290
+ const events = [fixtureCreated, fixtureStatusChanged, fixtureClosedWithSpecialChars];
291
+ const csv = exportToCSV(events);
292
+
293
+ const lines = csv.split("\n").filter((line) => line.trim() !== "");
294
+
295
+ // Header + 3 data lines
296
+ expect(lines.length).toBe(4);
297
+
298
+ // Each line should have same number of commas (field separators)
299
+ const headerCommas = (lines[0].match(/,/g) || []).length;
300
+
301
+ for (let i = 1; i < lines.length; i++) {
302
+ // Count commas in line (should match header comma count)
303
+ // This validates no embedded commas broke the structure
304
+ const lineCommas = (lines[i].match(/,(?=(?:[^"]*"[^"]*")*[^"]*$)/g) || []).length;
305
+ expect(lineCommas).toBe(headerCommas);
306
+ }
307
+ });
308
+
309
+ test("serializes payload as JSON string", () => {
310
+ const events = [fixtureCreated];
311
+ const csv = exportToCSV(events);
312
+
313
+ const lines = csv.split("\n");
314
+ const dataLine = lines[1];
315
+
316
+ // Payload should be JSON representation of event (minus headers)
317
+ // Should include fields like title, description, priority, etc.
318
+ expect(dataLine).toContain("Implement authentication");
319
+ expect(dataLine).toContain("OAuth2");
320
+ });
321
+
322
+ test("handles empty events array", () => {
323
+ const csv = exportToCSV([]);
324
+
325
+ // Should still have headers, no data lines
326
+ const lines = csv.split("\n").filter((line) => line.trim() !== "");
327
+ expect(lines.length).toBe(1);
328
+ expect(lines[0]).toBe("id,type,timestamp,project_key,cell_id,payload");
329
+ });
330
+
331
+ test("includes all event fields in payload", () => {
332
+ const events = [fixtureClosedWithSpecialChars];
333
+ const csv = exportToCSV(events);
334
+
335
+ const lines = csv.split("\n");
336
+ const dataLine = lines[1];
337
+
338
+ // Should include all event-specific fields
339
+ expect(dataLine).toContain("files_touched");
340
+ expect(dataLine).toContain("duration_ms");
341
+ expect(dataLine).toContain("3600000"); // Duration value
342
+ });
343
+ });
344
+
345
+ // ============================================================================
346
+ // JSON Export Tests
347
+ // ============================================================================
348
+
349
+ describe("exportToJSON", () => {
350
+ test("produces valid JSON array", () => {
351
+ const events = [fixtureCreated, fixtureStatusChanged];
352
+ const json = exportToJSON(events);
353
+
354
+ // Should be parseable JSON
355
+ expect(() => JSON.parse(json)).not.toThrow();
356
+
357
+ const parsed = JSON.parse(json);
358
+
359
+ // Should be an array
360
+ expect(Array.isArray(parsed)).toBe(true);
361
+ expect(parsed.length).toBe(2);
362
+ });
363
+
364
+ test("preserves all event fields", () => {
365
+ const events = [fixtureCreated];
366
+ const json = exportToJSON(events);
367
+ const parsed = JSON.parse(json);
368
+
369
+ const event = parsed[0];
370
+
371
+ // All fields from fixture should be present
372
+ expect(event.type).toBe("cell_created");
373
+ expect(event.project_key).toBe("/test/project");
374
+ expect(event.timestamp).toBe(1735142400000);
375
+ expect(event.cell_id).toBe("test-epic-abc123");
376
+ expect(event.title).toBe("Implement authentication");
377
+ expect(event.description).toBe("Add OAuth2 flow with JWT tokens");
378
+ expect(event.issue_type).toBe("feature");
379
+ expect(event.priority).toBe(2);
380
+ expect(event.created_by).toBe("BlueOcean");
381
+ expect(event.metadata).toEqual({
382
+ epic_id: "test-epic-parent",
383
+ strategy: "feature-based",
384
+ });
385
+ });
386
+
387
+ test("preserves event type discriminators", () => {
388
+ const events = [fixtureCreated, fixtureStatusChanged, fixtureClosedWithSpecialChars];
389
+ const json = exportToJSON(events);
390
+ const parsed = JSON.parse(json);
391
+
392
+ // Each event should maintain its type
393
+ expect(parsed[0].type).toBe("cell_created");
394
+ expect(parsed[1].type).toBe("cell_status_changed");
395
+ expect(parsed[2].type).toBe("cell_closed");
396
+
397
+ // Type-specific fields should be preserved
398
+ expect(parsed[1].from_status).toBe("open");
399
+ expect(parsed[1].to_status).toBe("in_progress");
400
+
401
+ expect(parsed[2].reason).toContain("OAuth2");
402
+ expect(parsed[2].files_touched).toEqual(["src/auth/oauth.ts", "src/auth/jwt.ts"]);
403
+ });
404
+
405
+ test("pretty-prints with 2-space indentation", () => {
406
+ const events = [fixtureCreated];
407
+ const json = exportToJSON(events);
408
+
409
+ // Should have newlines (pretty-printed)
410
+ expect(json).toContain("\n");
411
+
412
+ // Should use 2-space indentation
413
+ const lines = json.split("\n");
414
+
415
+ // Find a nested field line (e.g., "type": "cell_created")
416
+ const typeLine = lines.find((line) => line.includes('"type"'));
417
+ expect(typeLine).toBeDefined();
418
+
419
+ // Should start with 2 spaces (array item) + 2 spaces (object property) = 4 spaces
420
+ expect(typeLine).toMatch(/^\s{4}"/);
421
+ });
422
+
423
+ test("handles empty events array", () => {
424
+ const json = exportToJSON([]);
425
+
426
+ // Should be empty array
427
+ const parsed = JSON.parse(json);
428
+ expect(Array.isArray(parsed)).toBe(true);
429
+ expect(parsed.length).toBe(0);
430
+
431
+ // Pretty-printed empty array
432
+ expect(json).toBe("[]");
433
+ });
434
+
435
+ test("maintains event ordering", () => {
436
+ const events = [fixtureCreated, fixtureStatusChanged, fixtureClosedWithSpecialChars];
437
+ const json = exportToJSON(events);
438
+ const parsed = JSON.parse(json);
439
+
440
+ // Order should match input
441
+ expect(parsed[0].type).toBe("cell_created");
442
+ expect(parsed[1].type).toBe("cell_status_changed");
443
+ expect(parsed[2].type).toBe("cell_closed");
444
+
445
+ // Timestamps should be in order
446
+ expect(parsed[0].timestamp).toBe(1735142400000);
447
+ expect(parsed[1].timestamp).toBe(1735142460000);
448
+ expect(parsed[2].timestamp).toBe(1735146000000);
449
+ });
450
+
451
+ test("handles special characters in strings", () => {
452
+ const events = [fixtureCsvEdgeCase];
453
+ const json = exportToJSON(events);
454
+ const parsed = JSON.parse(json);
455
+
456
+ // Special chars should be preserved via JSON escaping
457
+ const title = parsed[0].title;
458
+ expect(title).toBe('Fix bug in parser: handle "quoted strings", commas, and newlines');
459
+
460
+ // JSON should use \" for quotes
461
+ expect(json).toContain('\\"quoted strings\\"');
462
+ });
463
+
464
+ test("serializes metadata objects correctly", () => {
465
+ const events = [fixtureCreated];
466
+ const json = exportToJSON(events);
467
+ const parsed = JSON.parse(json);
468
+
469
+ const metadata = parsed[0].metadata;
470
+
471
+ // Should be an object, not a string
472
+ expect(typeof metadata).toBe("object");
473
+ expect(metadata.epic_id).toBe("test-epic-parent");
474
+ expect(metadata.strategy).toBe("feature-based");
475
+ });
476
+ });