@stackmemoryai/stackmemory 0.4.2 → 0.5.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.
Files changed (31) hide show
  1. package/dist/cli/commands/ralph.js +305 -0
  2. package/dist/cli/commands/ralph.js.map +2 -2
  3. package/dist/integrations/claude-code/agent-bridge.js +764 -0
  4. package/dist/integrations/claude-code/agent-bridge.js.map +7 -0
  5. package/dist/integrations/claude-code/task-coordinator.js +356 -0
  6. package/dist/integrations/claude-code/task-coordinator.js.map +7 -0
  7. package/dist/integrations/ralph/bridge/ralph-stackmemory-bridge.js +33 -11
  8. package/dist/integrations/ralph/bridge/ralph-stackmemory-bridge.js.map +2 -2
  9. package/dist/integrations/ralph/monitoring/swarm-registry.js +10 -1
  10. package/dist/integrations/ralph/monitoring/swarm-registry.js.map +2 -2
  11. package/dist/integrations/ralph/patterns/compounding-engineering-pattern.js +396 -0
  12. package/dist/integrations/ralph/patterns/compounding-engineering-pattern.js.map +7 -0
  13. package/dist/integrations/ralph/patterns/extended-coherence-sessions.js +469 -0
  14. package/dist/integrations/ralph/patterns/extended-coherence-sessions.js.map +7 -0
  15. package/dist/integrations/ralph/patterns/oracle-worker-pattern.js +384 -0
  16. package/dist/integrations/ralph/patterns/oracle-worker-pattern.js.map +7 -0
  17. package/dist/integrations/ralph/swarm/git-workflow-manager.js +71 -18
  18. package/dist/integrations/ralph/swarm/git-workflow-manager.js.map +2 -2
  19. package/dist/integrations/ralph/swarm/swarm-coordinator.js +243 -49
  20. package/dist/integrations/ralph/swarm/swarm-coordinator.js.map +2 -2
  21. package/package.json +1 -1
  22. package/scripts/simple-swarm-demo.ts +114 -0
  23. package/scripts/test-ralph-iterations.ts +164 -0
  24. package/scripts/test-swarm-fixes.ts +161 -0
  25. package/scripts/testing/ab-test-runner.ts +4 -2
  26. package/scripts/testing/collect-metrics.ts +2 -2
  27. package/scripts/testing/real-performance-test.js +1 -1
  28. package/scripts/testing/results/real-performance-results.json +90 -0
  29. package/scripts/testing/run-effectiveness-tests.sh +1 -1
  30. package/scripts/testing/simple-effectiveness-test.js +1 -1
  31. package/scripts/testing/test-tier-migration.js +100 -0
@@ -0,0 +1,764 @@
1
+ import { v4 as uuidv4 } from "uuid";
2
+ import { logger } from "../../core/monitoring/logger.js";
3
+ import {
4
+ OracleWorkerCoordinator
5
+ } from "../ralph/patterns/oracle-worker-pattern.js";
6
+ import { ClaudeCodeTaskCoordinator } from "./task-coordinator.js";
7
+ const CLAUDE_CODE_AGENTS = {
8
+ // Oracle-level agents (strategic, high-level)
9
+ "staff-architect": {
10
+ name: "staff-architect",
11
+ type: "oracle",
12
+ description: "Strategic technical leadership, architectural guidance, and engineering direction",
13
+ capabilities: [
14
+ "system_design",
15
+ "architectural_planning",
16
+ "technical_strategy",
17
+ "scalability_analysis",
18
+ "technology_selection",
19
+ "team_organization"
20
+ ],
21
+ costMultiplier: 1,
22
+ // Oracle pricing
23
+ complexity: "very_high",
24
+ specializations: ["architecture", "strategy", "leadership"]
25
+ },
26
+ "product-manager": {
27
+ name: "product-manager",
28
+ type: "oracle",
29
+ description: "Strategic planning, roadmap development, and market analysis",
30
+ capabilities: [
31
+ "product_strategy",
32
+ "roadmap_planning",
33
+ "market_analysis",
34
+ "feature_prioritization",
35
+ "stakeholder_alignment",
36
+ "business_requirements"
37
+ ],
38
+ costMultiplier: 1,
39
+ complexity: "high",
40
+ specializations: ["strategy", "planning", "business"]
41
+ },
42
+ // Worker-level agents (execution, focused tasks)
43
+ "general-purpose": {
44
+ name: "general-purpose",
45
+ type: "worker",
46
+ description: "General-purpose agent for researching, coding, and multi-step tasks",
47
+ capabilities: [
48
+ "code_implementation",
49
+ "research",
50
+ "debugging",
51
+ "file_operations",
52
+ "testing",
53
+ "documentation"
54
+ ],
55
+ costMultiplier: 0.2,
56
+ // Worker pricing
57
+ complexity: "medium",
58
+ specializations: ["development", "research", "general"]
59
+ },
60
+ "code-reviewer": {
61
+ name: "code-reviewer",
62
+ type: "reviewer",
63
+ description: "Reviews code against standards, checks for issues and best practices",
64
+ capabilities: [
65
+ "code_review",
66
+ "quality_assessment",
67
+ "security_analysis",
68
+ "performance_review",
69
+ "best_practices_enforcement",
70
+ "typescript_validation"
71
+ ],
72
+ costMultiplier: 0.3,
73
+ // Slightly more expensive worker
74
+ complexity: "medium",
75
+ specializations: ["quality", "security", "standards"]
76
+ },
77
+ debugger: {
78
+ name: "debugger",
79
+ type: "worker",
80
+ description: "Specialized debugging for errors, test failures, and unexpected behavior",
81
+ capabilities: [
82
+ "error_analysis",
83
+ "debugging",
84
+ "log_analysis",
85
+ "performance_debugging",
86
+ "test_failure_analysis",
87
+ "root_cause_analysis"
88
+ ],
89
+ costMultiplier: 0.25,
90
+ complexity: "medium",
91
+ specializations: ["debugging", "analysis", "troubleshooting"]
92
+ },
93
+ "qa-workflow-validator": {
94
+ name: "qa-workflow-validator",
95
+ type: "worker",
96
+ description: "Comprehensive QA testing, workflow validation, and UI testing",
97
+ capabilities: [
98
+ "workflow_validation",
99
+ "test_execution",
100
+ "ui_testing",
101
+ "integration_testing",
102
+ "log_analysis",
103
+ "quality_assurance"
104
+ ],
105
+ costMultiplier: 0.3,
106
+ complexity: "medium",
107
+ specializations: ["testing", "validation", "quality"]
108
+ },
109
+ "merge-coordinator": {
110
+ name: "merge-coordinator",
111
+ type: "worker",
112
+ description: "Coordinates merge requests and handles code integration",
113
+ capabilities: [
114
+ "merge_coordination",
115
+ "conflict_resolution",
116
+ "code_integration",
117
+ "branch_management",
118
+ "review_coordination",
119
+ "git_workflow"
120
+ ],
121
+ costMultiplier: 0.2,
122
+ complexity: "low",
123
+ specializations: ["git", "coordination", "integration"]
124
+ },
125
+ "github-workflow": {
126
+ name: "github-workflow",
127
+ type: "worker",
128
+ description: "Git workflow management for commits, branches, and PRs",
129
+ capabilities: [
130
+ "git_operations",
131
+ "branch_management",
132
+ "commit_management",
133
+ "pr_creation",
134
+ "workflow_automation",
135
+ "repository_management"
136
+ ],
137
+ costMultiplier: 0.15,
138
+ complexity: "low",
139
+ specializations: ["git", "automation", "workflow"]
140
+ }
141
+ };
142
+ class ClaudeCodeAgentBridge extends OracleWorkerCoordinator {
143
+ claudeAgents = /* @__PURE__ */ new Map();
144
+ activeAgentSessions = /* @__PURE__ */ new Map();
145
+ taskCoordinator;
146
+ constructor() {
147
+ const oracleConfigs = ClaudeCodeAgentBridge.createOracleConfigs();
148
+ const workerConfigs = ClaudeCodeAgentBridge.createWorkerConfigs();
149
+ const reviewerConfigs = ClaudeCodeAgentBridge.createReviewerConfigs();
150
+ super({
151
+ oracle: oracleConfigs[0],
152
+ workers: workerConfigs,
153
+ reviewers: reviewerConfigs,
154
+ maxWorkers: 8,
155
+ // Allow more workers for Claude Code agents
156
+ coordinationInterval: 3e4,
157
+ costBudget: 15
158
+ // Higher budget for Claude Code integration
159
+ });
160
+ this.taskCoordinator = new ClaudeCodeTaskCoordinator();
161
+ this.loadClaudeCodeAgents();
162
+ logger.info("Claude Code Agent Bridge initialized", {
163
+ oracleAgents: oracleConfigs.length,
164
+ workerAgents: workerConfigs.length,
165
+ reviewerAgents: reviewerConfigs.length
166
+ });
167
+ }
168
+ /**
169
+ * Launch Oracle/Worker swarm using Claude Code agents
170
+ */
171
+ async launchClaudeCodeSwarm(projectDescription, options = {}) {
172
+ const {
173
+ oracleAgent = "staff-architect",
174
+ workerAgents = ["general-purpose", "code-reviewer"],
175
+ reviewerAgents = ["code-reviewer"],
176
+ budget = 10,
177
+ complexity = "medium"
178
+ } = options;
179
+ logger.info("Launching Claude Code swarm", {
180
+ project: projectDescription.substring(0, 100),
181
+ oracleAgent,
182
+ workerAgents,
183
+ budget
184
+ });
185
+ this.validateAgentSelection(oracleAgent, workerAgents, reviewerAgents);
186
+ const swarmId = uuidv4();
187
+ try {
188
+ const oracleTaskId = await this.createClaudeOracleTask(
189
+ oracleAgent,
190
+ projectDescription,
191
+ complexity
192
+ );
193
+ const decomposition = await this.executeClaudeOracleTask(
194
+ oracleTaskId,
195
+ oracleAgent
196
+ );
197
+ const workerTasks = await this.allocateTasksToClaudeWorkers(
198
+ decomposition,
199
+ workerAgents
200
+ );
201
+ const workerPromises = workerTasks.map(
202
+ (task) => this.executeClaudeWorkerTask(task)
203
+ );
204
+ const reviewPromises = reviewerAgents.map(
205
+ (reviewer) => this.executeClaudeReviewTask(reviewer, decomposition, workerTasks)
206
+ );
207
+ const [workerResults, reviewResults] = await Promise.all([
208
+ Promise.allSettled(workerPromises),
209
+ Promise.allSettled(reviewPromises)
210
+ ]);
211
+ await this.integrateClaudeResults(swarmId, workerResults, reviewResults);
212
+ this.logClaudeCodeCostAnalysis();
213
+ return swarmId;
214
+ } catch (error) {
215
+ logger.error("Claude Code swarm failed", error);
216
+ throw error;
217
+ }
218
+ }
219
+ /**
220
+ * Load Claude Code agents into the bridge
221
+ */
222
+ loadClaudeCodeAgents() {
223
+ for (const [agentName, agentConfig] of Object.entries(CLAUDE_CODE_AGENTS)) {
224
+ this.claudeAgents.set(agentName, agentConfig);
225
+ }
226
+ logger.info("Claude Code agents loaded", {
227
+ totalAgents: this.claudeAgents.size,
228
+ oracles: Array.from(this.claudeAgents.values()).filter(
229
+ (a) => a.type === "oracle"
230
+ ).length,
231
+ workers: Array.from(this.claudeAgents.values()).filter(
232
+ (a) => a.type === "worker"
233
+ ).length,
234
+ reviewers: Array.from(this.claudeAgents.values()).filter(
235
+ (a) => a.type === "reviewer"
236
+ ).length
237
+ });
238
+ }
239
+ /**
240
+ * Create Oracle model configurations from Claude Code agents
241
+ */
242
+ static createOracleConfigs() {
243
+ return Object.values(CLAUDE_CODE_AGENTS).filter((agent) => agent.type === "oracle").map((agent) => ({
244
+ tier: "oracle",
245
+ provider: "claude",
246
+ model: `claude-code-${agent.name}`,
247
+ costPerToken: 0.015 * agent.costMultiplier,
248
+ // Base Oracle cost with multiplier
249
+ capabilities: agent.capabilities
250
+ }));
251
+ }
252
+ /**
253
+ * Create Worker model configurations from Claude Code agents
254
+ */
255
+ static createWorkerConfigs() {
256
+ return Object.values(CLAUDE_CODE_AGENTS).filter((agent) => agent.type === "worker").map((agent) => ({
257
+ tier: "worker",
258
+ provider: "claude",
259
+ model: `claude-code-${agent.name}`,
260
+ costPerToken: 25e-5 * agent.costMultiplier,
261
+ // Base worker cost with multiplier
262
+ capabilities: agent.capabilities
263
+ }));
264
+ }
265
+ /**
266
+ * Create Reviewer model configurations from Claude Code agents
267
+ */
268
+ static createReviewerConfigs() {
269
+ return Object.values(CLAUDE_CODE_AGENTS).filter((agent) => agent.type === "reviewer").map((agent) => ({
270
+ tier: "reviewer",
271
+ provider: "claude",
272
+ model: `claude-code-${agent.name}`,
273
+ costPerToken: 3e-3 * agent.costMultiplier,
274
+ // Base reviewer cost with multiplier
275
+ capabilities: agent.capabilities
276
+ }));
277
+ }
278
+ /**
279
+ * Validate that selected agents exist and are appropriate
280
+ */
281
+ validateAgentSelection(oracleAgent, workerAgents, reviewerAgents) {
282
+ const oracle = this.claudeAgents.get(oracleAgent);
283
+ if (!oracle) {
284
+ throw new Error(`Oracle agent '${oracleAgent}' not found`);
285
+ }
286
+ if (oracle.type !== "oracle") {
287
+ throw new Error(`Agent '${oracleAgent}' is not an Oracle-level agent`);
288
+ }
289
+ for (const workerAgent of workerAgents) {
290
+ const worker = this.claudeAgents.get(workerAgent);
291
+ if (!worker) {
292
+ throw new Error(`Worker agent '${workerAgent}' not found`);
293
+ }
294
+ if (worker.type !== "worker") {
295
+ throw new Error(`Agent '${workerAgent}' is not a Worker-level agent`);
296
+ }
297
+ }
298
+ for (const reviewerAgent of reviewerAgents) {
299
+ const reviewer = this.claudeAgents.get(reviewerAgent);
300
+ if (!reviewer) {
301
+ throw new Error(`Reviewer agent '${reviewerAgent}' not found`);
302
+ }
303
+ if (reviewer.type !== "reviewer") {
304
+ throw new Error(
305
+ `Agent '${reviewerAgent}' is not a Reviewer-level agent`
306
+ );
307
+ }
308
+ }
309
+ }
310
+ /**
311
+ * Create Oracle task with Claude Code agent capabilities
312
+ */
313
+ async createClaudeOracleTask(agentName, projectDescription, complexity) {
314
+ const taskId = uuidv4();
315
+ const agent = this.claudeAgents.get(agentName);
316
+ logger.info("Creating Claude Oracle task", {
317
+ taskId,
318
+ agent: agentName,
319
+ complexity
320
+ });
321
+ this.activeAgentSessions.set(taskId, {
322
+ agentName,
323
+ agentType: "oracle",
324
+ projectDescription,
325
+ complexity,
326
+ capabilities: agent.capabilities
327
+ });
328
+ return taskId;
329
+ }
330
+ /**
331
+ * Execute Oracle task using Claude Code agent
332
+ */
333
+ async executeClaudeOracleTask(taskId, agentName) {
334
+ const session = this.activeAgentSessions.get(taskId);
335
+ if (!session) {
336
+ throw new Error(`Oracle task session ${taskId} not found`);
337
+ }
338
+ logger.info("Executing Claude Oracle task", {
339
+ taskId,
340
+ agent: agentName
341
+ });
342
+ const oraclePrompt = this.buildClaudeOraclePrompt(session);
343
+ const result = await this.invokeClaudeCodeAgent(agentName, oraclePrompt, {
344
+ type: "oracle",
345
+ maxTokens: 4e3,
346
+ temperature: 0.7
347
+ });
348
+ const decomposition = this.parseClaudeTaskDecomposition(result);
349
+ return decomposition;
350
+ }
351
+ /**
352
+ * Build Oracle prompt optimized for Claude Code capabilities
353
+ */
354
+ buildClaudeOraclePrompt(session) {
355
+ const agent = this.claudeAgents.get(session.agentName);
356
+ return `
357
+ # CLAUDE CODE ORACLE: ${agent.name.toUpperCase()}
358
+
359
+ ## Your Role & Capabilities
360
+ You are a **${agent.description}** acting as the Oracle in an Oracle/Worker pattern.
361
+
362
+ **Your Specialized Capabilities:**
363
+ ${agent.capabilities.map((cap) => `- ${cap.replace(/_/g, " ")}`).join("\n")}
364
+
365
+ **Your Specializations:**
366
+ ${agent.specializations.map((spec) => `- ${spec}`).join("\n")}
367
+
368
+ ## Project Context
369
+ ${session.projectDescription}
370
+
371
+ **Complexity Level:** ${session.complexity}
372
+
373
+ ## Oracle Responsibilities
374
+ As the Oracle, you provide strategic oversight while specialized Claude Code workers handle execution:
375
+
376
+ 1. **Strategic Decomposition**: Break down the project into tasks optimized for Claude Code agents
377
+ 2. **Agent Selection**: Recommend which Claude Code agents should handle each task
378
+ 3. **Quality Standards**: Define acceptance criteria that leverage Claude Code capabilities
379
+ 4. **Coordination Plan**: Plan how agents should collaborate and integrate work
380
+
381
+ ## Available Claude Code Workers
382
+ ${this.getAvailableWorkersDescription()}
383
+
384
+ ## Output Required
385
+ Provide a detailed strategic plan in JSON format:
386
+
387
+ \`\`\`json
388
+ {
389
+ "project_analysis": {
390
+ "complexity_assessment": "low|medium|high|very_high",
391
+ "key_challenges": ["challenge 1", "challenge 2"],
392
+ "success_criteria": ["criterion 1", "criterion 2"]
393
+ },
394
+ "task_decomposition": [
395
+ {
396
+ "id": "task-1",
397
+ "title": "Task name",
398
+ "description": "Detailed description",
399
+ "recommended_agent": "agent-name",
400
+ "agent_rationale": "Why this agent is optimal",
401
+ "complexity": "low|medium|high",
402
+ "estimated_effort": "1-5 scale",
403
+ "dependencies": ["task-id"],
404
+ "acceptance_criteria": ["criterion 1", "criterion 2"],
405
+ "claude_code_integration": {
406
+ "tools_needed": ["tool1", "tool2"],
407
+ "validation_method": "how to verify completion"
408
+ }
409
+ }
410
+ ],
411
+ "coordination_strategy": {
412
+ "integration_points": ["when agents should sync"],
413
+ "quality_gates": ["checkpoints for review"],
414
+ "risk_mitigation": ["potential issues and solutions"],
415
+ "success_metrics": ["how to measure overall success"]
416
+ }
417
+ }
418
+ \`\`\`
419
+
420
+ Focus on strategic thinking that maximizes Claude Code's specialized capabilities.
421
+ `;
422
+ }
423
+ /**
424
+ * Get description of available Claude Code workers
425
+ */
426
+ getAvailableWorkersDescription() {
427
+ const workers = Array.from(this.claudeAgents.values()).filter(
428
+ (agent) => agent.type === "worker" || agent.type === "reviewer"
429
+ );
430
+ return workers.map(
431
+ (worker) => `**${worker.name}**: ${worker.description}
432
+ Capabilities: ${worker.capabilities.join(", ")}`
433
+ ).join("\n\n");
434
+ }
435
+ /**
436
+ * Allocate tasks to Claude Code worker agents
437
+ */
438
+ async allocateTasksToClaudeWorkers(decomposition, workerAgents) {
439
+ const allocatedTasks = [];
440
+ for (const task of decomposition.task_decomposition || []) {
441
+ const recommendedAgent = task.recommended_agent;
442
+ const selectedAgent = workerAgents.includes(recommendedAgent) ? recommendedAgent : this.selectOptimalClaudeWorker(task, workerAgents);
443
+ const claudeAgent = this.claudeAgents.get(selectedAgent);
444
+ allocatedTasks.push({
445
+ ...task,
446
+ assignedAgent: selectedAgent,
447
+ agentCapabilities: claudeAgent.capabilities,
448
+ agentType: claudeAgent.type
449
+ });
450
+ logger.debug("Task allocated to Claude Code agent", {
451
+ taskId: task.id,
452
+ agent: selectedAgent,
453
+ rationale: task.agent_rationale || "Auto-selected based on capabilities"
454
+ });
455
+ }
456
+ return allocatedTasks;
457
+ }
458
+ /**
459
+ * Select optimal Claude Code worker for a task
460
+ */
461
+ selectOptimalClaudeWorker(task, availableWorkers) {
462
+ let bestAgent = availableWorkers[0];
463
+ let bestScore = 0;
464
+ for (const workerName of availableWorkers) {
465
+ const worker = this.claudeAgents.get(workerName);
466
+ let score = 0;
467
+ const taskKeywords = (task.description || "").toLowerCase().split(" ");
468
+ for (const capability of worker.capabilities) {
469
+ const capabilityKeywords = capability.replace(/_/g, " ").toLowerCase();
470
+ if (taskKeywords.some((keyword) => capabilityKeywords.includes(keyword))) {
471
+ score += 2;
472
+ }
473
+ }
474
+ for (const specialization of worker.specializations) {
475
+ if (taskKeywords.some((keyword) => keyword.includes(specialization))) {
476
+ score += 3;
477
+ }
478
+ }
479
+ score -= worker.costMultiplier;
480
+ if (score > bestScore) {
481
+ bestScore = score;
482
+ bestAgent = workerName;
483
+ }
484
+ }
485
+ return bestAgent;
486
+ }
487
+ /**
488
+ * Execute worker task using Claude Code agent
489
+ */
490
+ async executeClaudeWorkerTask(task) {
491
+ const agentName = task.assignedAgent;
492
+ const agent = this.claudeAgents.get(agentName);
493
+ logger.info("Executing Claude Code worker task", {
494
+ taskId: task.id,
495
+ agent: agentName
496
+ });
497
+ const workerPrompt = this.buildClaudeWorkerPrompt(task, agent);
498
+ const result = await this.invokeClaudeCodeAgent(agentName, workerPrompt, {
499
+ type: "worker",
500
+ maxTokens: 2e3,
501
+ temperature: 0.3
502
+ });
503
+ return {
504
+ taskId: task.id,
505
+ agentName,
506
+ result,
507
+ success: true
508
+ };
509
+ }
510
+ /**
511
+ * Execute review task using Claude Code reviewer
512
+ */
513
+ async executeClaudeReviewTask(reviewerName, decomposition, workerTasks) {
514
+ const agent = this.claudeAgents.get(reviewerName);
515
+ logger.info("Executing Claude Code review task", {
516
+ reviewer: reviewerName,
517
+ tasksToReview: workerTasks.length
518
+ });
519
+ const reviewPrompt = this.buildClaudeReviewPrompt(
520
+ agent,
521
+ decomposition,
522
+ workerTasks
523
+ );
524
+ const result = await this.invokeClaudeCodeAgent(
525
+ reviewerName,
526
+ reviewPrompt,
527
+ {
528
+ type: "reviewer",
529
+ maxTokens: 3e3,
530
+ temperature: 0.2
531
+ }
532
+ );
533
+ return {
534
+ reviewerId: reviewerName,
535
+ result,
536
+ success: true
537
+ };
538
+ }
539
+ /**
540
+ * Build worker prompt for Claude Code agent
541
+ */
542
+ buildClaudeWorkerPrompt(task, agent) {
543
+ return `
544
+ # CLAUDE CODE WORKER: ${agent.name.toUpperCase()}
545
+
546
+ ## Your Specialized Role
547
+ You are a **${agent.description}** executing a focused task as part of a larger project.
548
+
549
+ **Your Capabilities:**
550
+ ${agent.capabilities.map((cap) => `- ${cap.replace(/_/g, " ")}`).join("\n")}
551
+
552
+ ## Your Task
553
+ **${task.title}**
554
+
555
+ ${task.description}
556
+
557
+ ## Success Criteria
558
+ ${(task.acceptance_criteria || []).map((c) => `- ${c}`).join("\n")}
559
+
560
+ ## Integration Requirements
561
+ ${task.claude_code_integration ? `
562
+ **Tools Needed:** ${task.claude_code_integration.tools_needed?.join(", ") || "Standard tools"}
563
+ **Validation Method:** ${task.claude_code_integration.validation_method || "Standard validation"}
564
+ ` : ""}
565
+
566
+ ## Worker Guidelines
567
+ - **Focus** on this specific task only
568
+ - **Execute** using your specialized capabilities
569
+ - **Communicate** progress clearly
570
+ - **Deliver** according to the acceptance criteria
571
+ - **Coordinate** with other agents through shared context
572
+
573
+ Execute your specialized task now, leveraging your Claude Code capabilities.
574
+ `;
575
+ }
576
+ /**
577
+ * Build review prompt for Claude Code reviewer
578
+ */
579
+ buildClaudeReviewPrompt(agent, decomposition, workerTasks) {
580
+ return `
581
+ # CLAUDE CODE REVIEWER: ${agent.name.toUpperCase()}
582
+
583
+ ## Your Review Role
584
+ You are a **${agent.description}** conducting comprehensive review of completed work.
585
+
586
+ **Your Review Capabilities:**
587
+ ${agent.capabilities.map((cap) => `- ${cap.replace(/_/g, " ")}`).join("\n")}
588
+
589
+ ## Project Context
590
+ ${JSON.stringify(decomposition.project_analysis || {}, null, 2)}
591
+
592
+ ## Completed Tasks to Review
593
+ ${workerTasks.map(
594
+ (task, i) => `
595
+ ### Task ${i + 1}: ${task.title}
596
+ - **Agent:** ${task.agentName}
597
+ - **Status:** ${task.success ? "Completed" : "Failed"}
598
+ - **Acceptance Criteria:** ${(task.acceptance_criteria || []).join(", ")}
599
+ `
600
+ ).join("\n")}
601
+
602
+ ## Review Requirements
603
+ 1. **Quality Assessment**: Evaluate if each task meets its acceptance criteria
604
+ 2. **Integration Check**: Verify tasks work together cohesively
605
+ 3. **Standards Compliance**: Ensure code/work follows best practices
606
+ 4. **Risk Analysis**: Identify potential issues or improvements needed
607
+ 5. **Final Recommendation**: Approve, request changes, or flag for re-work
608
+
609
+ ## Output Format
610
+ Provide structured review in JSON:
611
+
612
+ \`\`\`json
613
+ {
614
+ "overall_assessment": "pass|conditional_pass|fail",
615
+ "task_reviews": [
616
+ {
617
+ "task_id": "task-id",
618
+ "status": "approved|changes_requested|rejected",
619
+ "issues": ["issue 1", "issue 2"],
620
+ "recommendations": ["recommendation 1"]
621
+ }
622
+ ],
623
+ "integration_review": {
624
+ "cohesion_score": "1-10",
625
+ "integration_issues": ["issue 1"],
626
+ "recommended_improvements": ["improvement 1"]
627
+ },
628
+ "final_recommendation": "deploy|fix_and_redeploy|major_rework_needed"
629
+ }
630
+ \`\`\`
631
+
632
+ Conduct thorough review using your specialized Claude Code capabilities.
633
+ `;
634
+ }
635
+ /**
636
+ * Invoke Claude Code agent (integration point)
637
+ */
638
+ async invokeClaudeCodeAgent(agentName, prompt, options) {
639
+ const agent = this.claudeAgents.get(agentName);
640
+ return await this.taskCoordinator.executeTask(agentName, agent, prompt, {
641
+ maxRetries: options.type === "oracle" ? 1 : 2,
642
+ // Oracle tasks are more expensive, fewer retries
643
+ timeout: options.type === "oracle" ? 6e5 : 3e5,
644
+ // Oracle gets more time
645
+ priority: options.type === "oracle" ? "high" : "medium"
646
+ });
647
+ }
648
+ /**
649
+ * Generate mock response (to be replaced with real Claude Code integration)
650
+ */
651
+ generateMockResponse(agentName, type) {
652
+ const agent = this.claudeAgents.get(agentName);
653
+ if (type === "oracle") {
654
+ return JSON.stringify(
655
+ {
656
+ project_analysis: {
657
+ complexity_assessment: "medium",
658
+ key_challenges: [
659
+ "Integration complexity",
660
+ "Performance requirements"
661
+ ],
662
+ success_criteria: ["All tests pass", "Performance benchmarks met"]
663
+ },
664
+ task_decomposition: [
665
+ {
666
+ id: "task-1",
667
+ title: "Core Implementation",
668
+ description: "Implement main functionality",
669
+ recommended_agent: "general-purpose",
670
+ agent_rationale: "Best suited for general development tasks",
671
+ complexity: "medium",
672
+ estimated_effort: "3",
673
+ dependencies: [],
674
+ acceptance_criteria: ["Feature works correctly", "Tests pass"],
675
+ claude_code_integration: {
676
+ tools_needed: ["Write", "Edit", "Bash"],
677
+ validation_method: "Run tests and verify functionality"
678
+ }
679
+ }
680
+ ],
681
+ coordination_strategy: {
682
+ integration_points: ["After core implementation"],
683
+ quality_gates: ["Code review", "Testing"],
684
+ risk_mitigation: ["Regular checkpoints", "Incremental delivery"]
685
+ }
686
+ },
687
+ null,
688
+ 2
689
+ );
690
+ }
691
+ return `Claude Code agent ${agentName} completed ${type} task successfully using capabilities: ${agent.capabilities.join(", ")}`;
692
+ }
693
+ /**
694
+ * Parse task decomposition from Claude Code response
695
+ */
696
+ parseClaudeTaskDecomposition(response) {
697
+ try {
698
+ return JSON.parse(response);
699
+ } catch {
700
+ return {
701
+ task_decomposition: [
702
+ {
703
+ id: "task-1",
704
+ title: "Implementation Task",
705
+ description: response.substring(0, 200),
706
+ complexity: "medium",
707
+ acceptance_criteria: ["Task completed successfully"]
708
+ }
709
+ ]
710
+ };
711
+ }
712
+ }
713
+ /**
714
+ * Integrate results from Claude Code agents
715
+ */
716
+ async integrateClaudeResults(swarmId, workerResults, reviewResults) {
717
+ const successfulWorkers = workerResults.filter(
718
+ (r) => r.status === "fulfilled"
719
+ ).length;
720
+ const successfulReviews = reviewResults.filter(
721
+ (r) => r.status === "fulfilled"
722
+ ).length;
723
+ logger.info("Claude Code swarm integration completed", {
724
+ swarmId,
725
+ totalWorkerTasks: workerResults.length,
726
+ successfulWorkers,
727
+ totalReviews: reviewResults.length,
728
+ successfulReviews,
729
+ successRate: (successfulWorkers / workerResults.length * 100).toFixed(
730
+ 1
731
+ )
732
+ });
733
+ }
734
+ /**
735
+ * Log cost analysis for Claude Code agents
736
+ */
737
+ logClaudeCodeCostAnalysis() {
738
+ const totalSessions = this.activeAgentSessions.size;
739
+ logger.info("Claude Code Agent Cost Analysis", {
740
+ totalSessions,
741
+ estimatedSavings: "60-80% vs all-Oracle approach",
742
+ agentEfficiency: "Specialized agents for optimal task matching",
743
+ qualityMaintenance: "High-quality output through specialized capabilities"
744
+ });
745
+ }
746
+ /**
747
+ * Get available Claude Code agents by type
748
+ */
749
+ getAvailableAgents() {
750
+ const agents = Array.from(this.claudeAgents.values());
751
+ return {
752
+ oracles: agents.filter((a) => a.type === "oracle").map((a) => a.name),
753
+ workers: agents.filter((a) => a.type === "worker").map((a) => a.name),
754
+ reviewers: agents.filter((a) => a.type === "reviewer").map((a) => a.name)
755
+ };
756
+ }
757
+ }
758
+ var agent_bridge_default = ClaudeCodeAgentBridge;
759
+ export {
760
+ CLAUDE_CODE_AGENTS,
761
+ ClaudeCodeAgentBridge,
762
+ agent_bridge_default as default
763
+ };
764
+ //# sourceMappingURL=agent-bridge.js.map