opencode-swarm-plugin 0.32.0 → 0.33.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,544 @@
1
+ /**
2
+ * Integration tests for research phase
3
+ *
4
+ * Tests the full research workflow:
5
+ * - Tool discovery (discoverDocTools)
6
+ * - Lockfile parsing (getInstalledVersions)
7
+ * - Researcher prompt generation (formatResearcherPrompt, swarm_spawn_researcher)
8
+ * - Research orchestration (runResearchPhase, extractTechStack)
9
+ *
10
+ * Uses this repo as a real-world test fixture.
11
+ */
12
+
13
+ import { afterEach, beforeEach, describe, expect, test } from "bun:test";
14
+ import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
15
+ import { tmpdir } from "node:os";
16
+ import { join } from "node:path";
17
+ import type { SwarmMailAdapter } from "swarm-mail";
18
+ import {
19
+ clearAdapterCache,
20
+ createInMemorySwarmMailLibSQL,
21
+ } from "swarm-mail";
22
+ import { extractTechStack, runResearchPhase } from "./swarm-orchestrate";
23
+ import {
24
+ formatResearcherPrompt,
25
+ swarm_spawn_researcher,
26
+ } from "./swarm-prompts";
27
+ import {
28
+ discoverDocTools,
29
+ getInstalledVersions,
30
+ swarm_discover_tools,
31
+ swarm_get_versions,
32
+ } from "./swarm-research";
33
+
34
+ describe("Tool discovery integration", () => {
35
+ test("discoverDocTools returns available tools", async () => {
36
+ const tools = await discoverDocTools();
37
+
38
+ // Should return a non-empty array
39
+ expect(tools.length).toBeGreaterThan(0);
40
+
41
+ // Check structure of returned tools
42
+ for (const tool of tools) {
43
+ expect(tool.name).toBeDefined();
44
+ expect(tool.type).toMatch(/^(skill|mcp|cli)$/);
45
+ expect(Array.isArray(tool.capabilities)).toBe(true);
46
+ expect(typeof tool.available).toBe("boolean");
47
+ }
48
+
49
+ // Should include known tools
50
+ const toolNames = tools.map((t) => t.name);
51
+ expect(toolNames).toContain("next-devtools");
52
+ expect(toolNames).toContain("context7");
53
+ expect(toolNames).toContain("fetch");
54
+ expect(toolNames).toContain("pdf-brain");
55
+ expect(toolNames).toContain("semantic-memory");
56
+ });
57
+
58
+ test("swarm_discover_tools plugin tool returns JSON summary", async () => {
59
+ const result = await swarm_discover_tools.execute({});
60
+ const parsed = JSON.parse(result);
61
+
62
+ // Check summary structure
63
+ expect(parsed.tools).toBeDefined();
64
+ expect(parsed.summary).toBeDefined();
65
+ expect(parsed.summary.total).toBeGreaterThan(0);
66
+ expect(parsed.summary.available).toBeGreaterThanOrEqual(0);
67
+ expect(parsed.summary.by_type).toBeDefined();
68
+
69
+ // Check usage hint
70
+ expect(parsed.usage_hint).toBeDefined();
71
+ });
72
+ });
73
+
74
+ describe("Lockfile parsing integration", () => {
75
+ let testProjectPath: string;
76
+
77
+ beforeEach(() => {
78
+ // Create temp directory for test fixtures
79
+ testProjectPath = join(tmpdir(), `lockfile-test-${Date.now()}`);
80
+ mkdirSync(testProjectPath, { recursive: true });
81
+ });
82
+
83
+ afterEach(() => {
84
+ // Clean up
85
+ rmSync(testProjectPath, { recursive: true, force: true });
86
+ });
87
+
88
+ test("getInstalledVersions reads from bun.lock fallback to package.json", async () => {
89
+ // Create a package.json (bun.lock is binary, can't easily mock)
90
+ const packageJson = {
91
+ dependencies: {
92
+ zod: "^3.22.4",
93
+ typescript: "^5.3.3",
94
+ },
95
+ devDependencies: {
96
+ "@types/node": "^20.0.0",
97
+ },
98
+ };
99
+
100
+ writeFileSync(
101
+ join(testProjectPath, "package.json"),
102
+ JSON.stringify(packageJson, null, 2),
103
+ );
104
+
105
+ // Query for specific packages
106
+ const versions = await getInstalledVersions(testProjectPath, [
107
+ "zod",
108
+ "typescript",
109
+ "@types/node",
110
+ ]);
111
+
112
+ // Should return versions from package.json (since no npm/pnpm/yarn lockfile)
113
+ expect(versions.length).toBeGreaterThan(0);
114
+
115
+ // Check zod
116
+ const zodVersion = versions.find((v) => v.name === "zod");
117
+ expect(zodVersion).toBeDefined();
118
+ expect(zodVersion?.version).toBe("3.22.4");
119
+ expect(zodVersion?.source).toBe("package.json");
120
+ expect(zodVersion?.constraint).toBe("^3.22.4");
121
+
122
+ // Check typescript
123
+ const tsVersion = versions.find((v) => v.name === "typescript");
124
+ expect(tsVersion).toBeDefined();
125
+ expect(tsVersion?.version).toBe("5.3.3");
126
+ expect(tsVersion?.source).toBe("package.json");
127
+ });
128
+
129
+ test("getInstalledVersions handles missing packages gracefully", async () => {
130
+ // Create minimal package.json
131
+ const packageJson = {
132
+ dependencies: {
133
+ zod: "^3.22.4",
134
+ },
135
+ };
136
+
137
+ writeFileSync(
138
+ join(testProjectPath, "package.json"),
139
+ JSON.stringify(packageJson, null, 2),
140
+ );
141
+
142
+ // Query for packages that don't exist
143
+ const versions = await getInstalledVersions(testProjectPath, [
144
+ "zod",
145
+ "nonexistent-package",
146
+ "another-missing",
147
+ ]);
148
+
149
+ // Should only return zod
150
+ expect(versions.length).toBe(1);
151
+ expect(versions[0].name).toBe("zod");
152
+ });
153
+
154
+ test("getInstalledVersions returns empty array for no lockfile or package.json", async () => {
155
+ // Don't create any files - project has no dependencies
156
+ const versions = await getInstalledVersions(testProjectPath, [
157
+ "zod",
158
+ "typescript",
159
+ ]);
160
+
161
+ // Should return empty array
162
+ expect(versions).toEqual([]);
163
+ });
164
+
165
+ test("swarm_get_versions plugin tool returns JSON summary", async () => {
166
+ // Create a package.json
167
+ const packageJson = {
168
+ dependencies: {
169
+ zod: "^3.22.4",
170
+ typescript: "^5.3.3",
171
+ },
172
+ };
173
+
174
+ writeFileSync(
175
+ join(testProjectPath, "package.json"),
176
+ JSON.stringify(packageJson, null, 2),
177
+ );
178
+
179
+ // Call plugin tool
180
+ const result = await swarm_get_versions.execute({
181
+ projectPath: testProjectPath,
182
+ packages: ["zod", "typescript", "missing-pkg"],
183
+ });
184
+
185
+ const parsed = JSON.parse(result);
186
+
187
+ // Check summary
188
+ expect(parsed.versions).toBeDefined();
189
+ expect(parsed.summary).toBeDefined();
190
+ expect(parsed.summary.found).toBe(2);
191
+ expect(parsed.summary.requested).toBe(3);
192
+ expect(parsed.summary.missing).toEqual(["missing-pkg"]);
193
+ expect(parsed.summary.sources.package_json).toBe(2);
194
+
195
+ // Check usage hint
196
+ expect(parsed.usage_hint).toBeDefined();
197
+ });
198
+
199
+ test("reads from real bun.lock in this repo", async () => {
200
+ // Use the plugin package directory which has the dependencies
201
+ const pluginDir = join(process.cwd(), "packages/opencode-swarm-plugin");
202
+
203
+ // Query for packages we know exist in the plugin
204
+ const versions = await getInstalledVersions(pluginDir, [
205
+ "zod",
206
+ "effect",
207
+ "@opencode-ai/plugin",
208
+ ]);
209
+
210
+ // Should find at least some versions from package.json
211
+ expect(versions.length).toBeGreaterThan(0);
212
+
213
+ // Check zod (we know it's in dependencies)
214
+ const zodVersion = versions.find((v) => v.name === "zod");
215
+ expect(zodVersion).toBeDefined();
216
+ expect(zodVersion?.version).toMatch(/^\d+\.\d+\.\d+/); // Semver format
217
+ });
218
+ });
219
+
220
+ describe("Researcher prompt generation", () => {
221
+ test("formatResearcherPrompt generates valid prompt with tech stack", () => {
222
+ const prompt = formatResearcherPrompt({
223
+ research_id: "test-research-123",
224
+ epic_id: "epic-456",
225
+ tech_stack: ["zod", "typescript", "next.js"],
226
+ project_path: "/test/project",
227
+ check_upgrades: false,
228
+ });
229
+
230
+ // Should contain all parameters
231
+ expect(prompt).toContain("test-research-123");
232
+ expect(prompt).toContain("epic-456");
233
+ expect(prompt).toContain("zod");
234
+ expect(prompt).toContain("typescript");
235
+ expect(prompt).toContain("next.js");
236
+ expect(prompt).toContain("/test/project");
237
+
238
+ // Should be in DEFAULT MODE (not UPGRADE COMPARISON MODE)
239
+ expect(prompt).toContain("DEFAULT MODE");
240
+ expect(prompt).not.toContain("UPGRADE COMPARISON MODE");
241
+ });
242
+
243
+ test("formatResearcherPrompt includes upgrade mode when check_upgrades=true", () => {
244
+ const prompt = formatResearcherPrompt({
245
+ research_id: "test-research-123",
246
+ epic_id: "epic-456",
247
+ tech_stack: ["zod"],
248
+ project_path: "/test/project",
249
+ check_upgrades: true,
250
+ });
251
+
252
+ // Should be in UPGRADE COMPARISON MODE
253
+ expect(prompt).toContain("UPGRADE COMPARISON MODE");
254
+ expect(prompt).toContain("BOTH installed AND latest versions");
255
+ });
256
+
257
+ test("swarm_spawn_researcher returns JSON with prompt and metadata", async () => {
258
+ const result = await swarm_spawn_researcher.execute({
259
+ research_id: "research-789",
260
+ epic_id: "epic-101",
261
+ tech_stack: ["zod", "typescript"],
262
+ project_path: "/test/project",
263
+ check_upgrades: false,
264
+ });
265
+
266
+ const parsed = JSON.parse(result);
267
+
268
+ // Check structure
269
+ expect(parsed.prompt).toBeDefined();
270
+ expect(parsed.research_id).toBe("research-789");
271
+ expect(parsed.epic_id).toBe("epic-101");
272
+ expect(parsed.tech_stack).toEqual(["zod", "typescript"]);
273
+ expect(parsed.project_path).toBe("/test/project");
274
+ expect(parsed.check_upgrades).toBe(false);
275
+ expect(parsed.subagent_type).toBe("swarm/researcher");
276
+
277
+ // Check expected output schema
278
+ expect(parsed.expected_output).toBeDefined();
279
+ expect(parsed.expected_output.technologies).toBeDefined();
280
+ expect(parsed.expected_output.summary).toBeDefined();
281
+ });
282
+ });
283
+
284
+ describe("Research orchestration integration", () => {
285
+ let testProjectPath: string;
286
+ let swarmMail: SwarmMailAdapter;
287
+
288
+ beforeEach(async () => {
289
+ // Create temp project directory
290
+ testProjectPath = join(tmpdir(), `research-test-${Date.now()}`);
291
+ mkdirSync(testProjectPath, { recursive: true });
292
+
293
+ // Initialize swarm-mail for this project
294
+ swarmMail = await createInMemorySwarmMailLibSQL(testProjectPath);
295
+ });
296
+
297
+ afterEach(async () => {
298
+ // Clean up
299
+ await swarmMail.close();
300
+ clearAdapterCache();
301
+ rmSync(testProjectPath, { recursive: true, force: true });
302
+ });
303
+
304
+ test("extractTechStack identifies technologies from task description", () => {
305
+ const task =
306
+ "Add Zod validation to Next.js API routes with TypeScript types";
307
+ const techStack = extractTechStack(task);
308
+
309
+ // Should extract known technologies
310
+ expect(techStack).toContain("zod");
311
+ expect(techStack).toContain("next"); // Pattern matches "next" (not "next.js")
312
+ expect(techStack).toContain("typescript");
313
+ });
314
+
315
+ test("extractTechStack handles case-insensitive matches", () => {
316
+ const task = "Use REACT and NextJS with TYPESCRIPT";
317
+ const techStack = extractTechStack(task);
318
+
319
+ // Should normalize to lowercase
320
+ expect(techStack).toContain("react");
321
+ expect(techStack).toContain("next"); // Pattern matches "next"
322
+ expect(techStack).toContain("typescript");
323
+ });
324
+
325
+ test("extractTechStack returns empty array for unknown technologies", () => {
326
+ const task = "Implement something with FooBarBaz library";
327
+ const techStack = extractTechStack(task);
328
+
329
+ // Should return empty array (no known tech)
330
+ expect(techStack).toEqual([]);
331
+ });
332
+
333
+ test("runResearchPhase returns tech stack and research summaries", async () => {
334
+ // Create a package.json with dependencies
335
+ const packageJson = {
336
+ dependencies: {
337
+ zod: "^3.22.4",
338
+ typescript: "^5.3.3",
339
+ },
340
+ };
341
+
342
+ writeFileSync(
343
+ join(testProjectPath, "package.json"),
344
+ JSON.stringify(packageJson, null, 2),
345
+ );
346
+
347
+ // Run research phase
348
+ const result = await runResearchPhase(
349
+ "Add Zod validation to TypeScript API",
350
+ testProjectPath,
351
+ );
352
+
353
+ // Should extract tech stack
354
+ expect(result.tech_stack).toBeDefined();
355
+ expect(result.tech_stack.length).toBeGreaterThan(0);
356
+ expect(result.tech_stack).toContain("zod");
357
+ expect(result.tech_stack).toContain("typescript");
358
+
359
+ // Should have summaries object (even if empty for now)
360
+ expect(result.summaries).toBeDefined();
361
+ expect(typeof result.summaries).toBe("object");
362
+
363
+ // Should have memory_ids array (even if empty for now)
364
+ expect(result.memory_ids).toBeDefined();
365
+ expect(Array.isArray(result.memory_ids)).toBe(true);
366
+ });
367
+
368
+ test("runResearchPhase handles no package.json gracefully", async () => {
369
+ // Don't create package.json - project has no dependencies
370
+
371
+ const result = await runResearchPhase(
372
+ "Add Zod validation",
373
+ testProjectPath,
374
+ );
375
+
376
+ // Should still extract tech stack from description
377
+ expect(result.tech_stack).toBeDefined();
378
+ expect(result.tech_stack).toContain("zod");
379
+
380
+ // Should have empty summaries (no research yet)
381
+ expect(result.summaries).toEqual({});
382
+ expect(result.memory_ids).toEqual([]);
383
+ });
384
+ });
385
+
386
+ describe("End-to-end research workflow", () => {
387
+ let testProjectPath: string;
388
+ let swarmMail: SwarmMailAdapter;
389
+
390
+ beforeEach(async () => {
391
+ // Create temp project directory
392
+ testProjectPath = join(tmpdir(), `e2e-research-${Date.now()}`);
393
+ mkdirSync(testProjectPath, { recursive: true });
394
+
395
+ // Create a realistic package.json
396
+ const packageJson = {
397
+ name: "test-project",
398
+ version: "1.0.0",
399
+ dependencies: {
400
+ zod: "^3.22.4",
401
+ "@opencode-ai/plugin": "^0.1.0",
402
+ },
403
+ devDependencies: {
404
+ typescript: "^5.3.3",
405
+ "@types/node": "^20.0.0",
406
+ },
407
+ };
408
+
409
+ writeFileSync(
410
+ join(testProjectPath, "package.json"),
411
+ JSON.stringify(packageJson, null, 2),
412
+ );
413
+
414
+ // Initialize swarm-mail
415
+ swarmMail = await createInMemorySwarmMailLibSQL(testProjectPath);
416
+ });
417
+
418
+ afterEach(async () => {
419
+ await swarmMail.close();
420
+ clearAdapterCache();
421
+ rmSync(testProjectPath, { recursive: true, force: true });
422
+ });
423
+
424
+ test("full research phase workflow", async () => {
425
+ // Step 1: Extract tech stack from task
426
+ const task =
427
+ "Add Zod validation to OpenCode plugin with TypeScript types";
428
+ const techStack = extractTechStack(task);
429
+
430
+ expect(techStack).toContain("zod");
431
+ expect(techStack).toContain("typescript");
432
+
433
+ // Step 2: Discover available doc tools
434
+ const tools = await discoverDocTools();
435
+ expect(tools.length).toBeGreaterThan(0);
436
+
437
+ // Step 3: Get installed versions
438
+ const versions = await getInstalledVersions(testProjectPath, techStack);
439
+ expect(versions.length).toBeGreaterThan(0);
440
+
441
+ const zodVersion = versions.find((v) => v.name === "zod");
442
+ expect(zodVersion?.version).toBe("3.22.4");
443
+ expect(zodVersion?.source).toBe("package.json");
444
+
445
+ // Step 4: Generate researcher prompt
446
+ const prompt = formatResearcherPrompt({
447
+ research_id: "e2e-research",
448
+ epic_id: "epic-test",
449
+ tech_stack: techStack,
450
+ project_path: testProjectPath,
451
+ check_upgrades: false,
452
+ });
453
+
454
+ // Prompt should contain all context
455
+ expect(prompt).toContain("e2e-research");
456
+ expect(prompt).toContain("zod");
457
+ expect(prompt).toContain("typescript");
458
+ expect(prompt).toContain(testProjectPath);
459
+
460
+ // Step 5: Spawn researcher (get JSON for Task tool)
461
+ const spawnResult = await swarm_spawn_researcher.execute({
462
+ research_id: "e2e-research",
463
+ epic_id: "epic-test",
464
+ tech_stack: techStack,
465
+ project_path: testProjectPath,
466
+ check_upgrades: false,
467
+ });
468
+
469
+ const spawnData = JSON.parse(spawnResult);
470
+ expect(spawnData.prompt).toBeDefined();
471
+ expect(spawnData.subagent_type).toBe("swarm/researcher");
472
+ expect(spawnData.tech_stack).toEqual(techStack);
473
+
474
+ // The spawned prompt should be ready for Task tool
475
+ expect(spawnData.prompt).toContain("swarmmail_init");
476
+ expect(spawnData.prompt).toContain("semantic-memory_store");
477
+ expect(spawnData.prompt).toContain(testProjectPath);
478
+ });
479
+
480
+ test("research phase orchestration with runResearchPhase", async () => {
481
+ const task = "Build Next.js app with Zod validation and TypeScript";
482
+
483
+ // Run full research phase
484
+ const result = await runResearchPhase(task, testProjectPath);
485
+
486
+ // Should extract tech stack (normalized names)
487
+ expect(result.tech_stack).toContain("zod");
488
+ expect(result.tech_stack).toContain("typescript");
489
+ expect(result.tech_stack).toContain("next"); // Normalized from "Next.js"
490
+
491
+ // Should have research result structure (GREEN phase - empty for now)
492
+ expect(result.summaries).toBeDefined();
493
+ expect(result.memory_ids).toBeDefined();
494
+ expect(Array.isArray(result.memory_ids)).toBe(true);
495
+ });
496
+ });
497
+
498
+ describe("Real-world fixture: this repo", () => {
499
+ test("discovers tools and versions from actual repo", async () => {
500
+ // Use the plugin package directory, not monorepo root
501
+ const pluginDir = join(process.cwd(), "packages/opencode-swarm-plugin");
502
+
503
+ // Step 1: Tool discovery
504
+ const tools = await discoverDocTools();
505
+ expect(tools.length).toBeGreaterThan(0);
506
+
507
+ // Step 2: Version detection for packages we know exist in the plugin
508
+ const versions = await getInstalledVersions(pluginDir, [
509
+ "zod",
510
+ "@opencode-ai/plugin",
511
+ "effect",
512
+ ]);
513
+
514
+ // Should find at least some packages (from plugin's package.json)
515
+ expect(versions.length).toBeGreaterThan(0);
516
+
517
+ // Zod should be found (it's in dependencies)
518
+ const zodVersion = versions.find((v) => v.name === "zod");
519
+ expect(zodVersion).toBeDefined();
520
+
521
+ // Effect should be found (it's in dependencies)
522
+ const effectVersion = versions.find((v) => v.name === "effect");
523
+ expect(effectVersion).toBeDefined();
524
+ });
525
+
526
+ test("research phase with real task on this repo", async () => {
527
+ // Use the plugin package directory, not monorepo root
528
+ const pluginDir = join(process.cwd(), "packages/opencode-swarm-plugin");
529
+ const task =
530
+ "Add Zod validation to swarm coordination with TypeScript types";
531
+
532
+ // Run research phase on actual repo
533
+ const result = await runResearchPhase(task, pluginDir);
534
+
535
+ // Should extract tech stack
536
+ expect(result.tech_stack).toContain("zod");
537
+ expect(result.tech_stack).toContain("typescript");
538
+
539
+ // Should have research result structure
540
+ expect(result.summaries).toBeDefined();
541
+ expect(result.memory_ids).toBeDefined();
542
+ expect(Array.isArray(result.memory_ids)).toBe(true);
543
+ });
544
+ });