@stackmemoryai/stackmemory 0.3.22 → 0.3.24

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 (39) hide show
  1. package/dist/cli/commands/ralph.js +294 -0
  2. package/dist/cli/commands/ralph.js.map +7 -0
  3. package/dist/cli/index.js +2 -0
  4. package/dist/cli/index.js.map +2 -2
  5. package/dist/integrations/ralph/bridge/ralph-stackmemory-bridge.js +586 -0
  6. package/dist/integrations/ralph/bridge/ralph-stackmemory-bridge.js.map +7 -0
  7. package/dist/integrations/ralph/context/context-budget-manager.js +297 -0
  8. package/dist/integrations/ralph/context/context-budget-manager.js.map +7 -0
  9. package/dist/integrations/ralph/context/stackmemory-context-loader.js +356 -0
  10. package/dist/integrations/ralph/context/stackmemory-context-loader.js.map +7 -0
  11. package/dist/integrations/ralph/index.js +14 -0
  12. package/dist/integrations/ralph/index.js.map +7 -0
  13. package/dist/integrations/ralph/learning/pattern-learner.js +397 -0
  14. package/dist/integrations/ralph/learning/pattern-learner.js.map +7 -0
  15. package/dist/integrations/ralph/lifecycle/iteration-lifecycle.js +444 -0
  16. package/dist/integrations/ralph/lifecycle/iteration-lifecycle.js.map +7 -0
  17. package/dist/integrations/ralph/orchestration/multi-loop-orchestrator.js +459 -0
  18. package/dist/integrations/ralph/orchestration/multi-loop-orchestrator.js.map +7 -0
  19. package/dist/integrations/ralph/performance/performance-optimizer.js +354 -0
  20. package/dist/integrations/ralph/performance/performance-optimizer.js.map +7 -0
  21. package/dist/integrations/ralph/ralph-integration-demo.js +178 -0
  22. package/dist/integrations/ralph/ralph-integration-demo.js.map +7 -0
  23. package/dist/integrations/ralph/state/state-reconciler.js +400 -0
  24. package/dist/integrations/ralph/state/state-reconciler.js.map +7 -0
  25. package/dist/integrations/ralph/swarm/swarm-coordinator.js +487 -0
  26. package/dist/integrations/ralph/swarm/swarm-coordinator.js.map +7 -0
  27. package/dist/integrations/ralph/types.js +1 -0
  28. package/dist/integrations/ralph/types.js.map +7 -0
  29. package/dist/integrations/ralph/visualization/ralph-debugger.js +581 -0
  30. package/dist/integrations/ralph/visualization/ralph-debugger.js.map +7 -0
  31. package/package.json +1 -1
  32. package/scripts/deploy-ralph-swarm.sh +365 -0
  33. package/scripts/ralph-integration-test.js +274 -0
  34. package/scripts/ralph-loop-implementation.js +404 -0
  35. package/scripts/swarm-monitor.js +509 -0
  36. package/scripts/test-parallel-swarms.js +443 -0
  37. package/scripts/testing/ralph-cli-test.js +88 -0
  38. package/scripts/testing/ralph-integration-validation.js +727 -0
  39. package/scripts/testing/ralph-swarm-test-scenarios.js +613 -0
@@ -0,0 +1,487 @@
1
+ import { v4 as uuidv4 } from "uuid";
2
+ import { logger } from "../../../core/monitoring/logger.js";
3
+ import { FrameManager } from "../../../core/context/frame-manager.js";
4
+ import { sessionManager } from "../../../core/session/index.js";
5
+ import { sharedContextLayer } from "../../../core/context/shared-context-layer.js";
6
+ import { RalphStackMemoryBridge } from "../bridge/ralph-stackmemory-bridge.js";
7
+ class SwarmCoordinator {
8
+ frameManager;
9
+ activeAgents = /* @__PURE__ */ new Map();
10
+ swarmState;
11
+ config;
12
+ coordinationTimer;
13
+ plannerWakeupQueue = /* @__PURE__ */ new Map();
14
+ constructor(config) {
15
+ this.config = {
16
+ maxAgents: 10,
17
+ coordinationInterval: 3e4,
18
+ // 30 seconds
19
+ driftDetectionThreshold: 5,
20
+ // 5 failed iterations before considering drift
21
+ freshStartInterval: 36e5,
22
+ // 1 hour
23
+ conflictResolutionStrategy: "expertise",
24
+ enableDynamicPlanning: true,
25
+ pathologicalBehaviorDetection: true,
26
+ ...config
27
+ };
28
+ this.swarmState = {
29
+ id: uuidv4(),
30
+ status: "idle",
31
+ startTime: Date.now(),
32
+ activeTaskCount: 0,
33
+ completedTaskCount: 0,
34
+ coordination: {
35
+ events: [],
36
+ conflicts: [],
37
+ resolutions: []
38
+ },
39
+ performance: {
40
+ throughput: 0,
41
+ efficiency: 0,
42
+ coordination_overhead: 0
43
+ }
44
+ };
45
+ logger.info("Swarm coordinator initialized", this.config);
46
+ }
47
+ async initialize() {
48
+ try {
49
+ await sessionManager.initialize();
50
+ await sharedContextLayer.initialize();
51
+ const session = await sessionManager.getOrCreateSession({});
52
+ if (session.database) {
53
+ this.frameManager = new FrameManager(session.database, session.projectId);
54
+ }
55
+ this.startCoordinationLoop();
56
+ logger.info("Swarm coordinator initialized successfully");
57
+ } catch (error) {
58
+ logger.error("Failed to initialize swarm coordinator", error);
59
+ throw error;
60
+ }
61
+ }
62
+ /**
63
+ * Launch a swarm of agents to work on a complex project
64
+ */
65
+ async launchSwarm(projectDescription, agents, coordination) {
66
+ logger.info("Launching swarm", {
67
+ project: projectDescription.substring(0, 100),
68
+ agentCount: agents.length
69
+ });
70
+ const swarmId = uuidv4();
71
+ try {
72
+ if (agents.length > this.config.maxAgents) {
73
+ throw new Error(`Too many agents requested: ${agents.length} > ${this.config.maxAgents}`);
74
+ }
75
+ const swarmTasks = await this.decomposeProjectIntoSwarmTasks(projectDescription);
76
+ const initializedAgents = await this.initializeSpecializedAgents(agents, swarmTasks);
77
+ const allocation = await this.allocateTasksToAgents(swarmTasks, initializedAgents);
78
+ this.swarmState = {
79
+ ...this.swarmState,
80
+ id: swarmId,
81
+ status: "active",
82
+ activeTaskCount: swarmTasks.length,
83
+ project: projectDescription,
84
+ agents: initializedAgents,
85
+ tasks: swarmTasks,
86
+ allocation
87
+ };
88
+ await this.executeSwarmTasks(allocation);
89
+ logger.info("Swarm launched successfully", { swarmId, agentCount: initializedAgents.length });
90
+ return swarmId;
91
+ } catch (error) {
92
+ logger.error("Failed to launch swarm", error);
93
+ throw error;
94
+ }
95
+ }
96
+ /**
97
+ * Decompose project into tasks suitable for swarm execution
98
+ */
99
+ async decomposeProjectIntoSwarmTasks(projectDescription) {
100
+ const tasks = [];
101
+ const complexity = this.analyzeProjectComplexity(projectDescription);
102
+ if (complexity.needsArchitecture) {
103
+ tasks.push({
104
+ id: uuidv4(),
105
+ type: "architecture",
106
+ title: "System Architecture Design",
107
+ description: "Design overall system architecture and component relationships",
108
+ priority: 1,
109
+ estimatedEffort: "high",
110
+ requiredRoles: ["architect", "system_designer"],
111
+ dependencies: [],
112
+ acceptanceCriteria: [
113
+ "Architecture diagram created",
114
+ "Component interfaces defined",
115
+ "Data flow documented"
116
+ ]
117
+ });
118
+ }
119
+ const coreFeatures = this.extractCoreFeatures(projectDescription);
120
+ for (const feature of coreFeatures) {
121
+ tasks.push({
122
+ id: uuidv4(),
123
+ type: "implementation",
124
+ title: `Implement ${feature.name}`,
125
+ description: feature.description,
126
+ priority: 2,
127
+ estimatedEffort: feature.complexity,
128
+ requiredRoles: ["developer", feature.specialization || "fullstack"],
129
+ dependencies: complexity.needsArchitecture ? [tasks[0].id] : [],
130
+ acceptanceCriteria: feature.criteria
131
+ });
132
+ }
133
+ if (complexity.needsTesting) {
134
+ tasks.push({
135
+ id: uuidv4(),
136
+ type: "testing",
137
+ title: "Comprehensive Testing Suite",
138
+ description: "Create unit, integration, and end-to-end tests",
139
+ priority: 3,
140
+ estimatedEffort: "medium",
141
+ requiredRoles: ["qa_engineer", "test_automation"],
142
+ dependencies: tasks.filter((t) => t.type === "implementation").map((t) => t.id),
143
+ acceptanceCriteria: [
144
+ "Unit tests achieve >90% coverage",
145
+ "Integration tests pass",
146
+ "Performance benchmarks met"
147
+ ]
148
+ });
149
+ }
150
+ if (complexity.needsDocumentation) {
151
+ tasks.push({
152
+ id: uuidv4(),
153
+ type: "documentation",
154
+ title: "Documentation and Examples",
155
+ description: "Create user documentation, API docs, and usage examples",
156
+ priority: 4,
157
+ estimatedEffort: "low",
158
+ requiredRoles: ["technical_writer", "developer"],
159
+ dependencies: [],
160
+ // Can run in parallel
161
+ acceptanceCriteria: [
162
+ "README with setup instructions",
163
+ "API documentation complete",
164
+ "Usage examples provided"
165
+ ]
166
+ });
167
+ }
168
+ return tasks;
169
+ }
170
+ /**
171
+ * Initialize specialized agents with role-specific configurations
172
+ */
173
+ async initializeSpecializedAgents(specifications, tasks) {
174
+ const agents = [];
175
+ for (const spec of specifications) {
176
+ const agent = {
177
+ id: uuidv4(),
178
+ role: spec.role,
179
+ specialization: spec,
180
+ status: "initializing",
181
+ capabilities: this.defineCapabilities(spec.role),
182
+ workingDirectory: `.swarm/${spec.role}-${Date.now()}`,
183
+ currentTask: null,
184
+ performance: {
185
+ tasksCompleted: 0,
186
+ successRate: 1,
187
+ averageTaskTime: 0,
188
+ driftDetected: false,
189
+ lastFreshStart: Date.now()
190
+ },
191
+ coordination: {
192
+ communicationStyle: this.defineCommuncationStyle(spec.role),
193
+ conflictResolution: spec.conflictResolution || "defer_to_expertise",
194
+ collaborationPreferences: spec.collaborationPreferences || []
195
+ }
196
+ };
197
+ await this.setupAgentEnvironment(agent);
198
+ await this.configureAgentPrompts(agent);
199
+ agents.push(agent);
200
+ this.activeAgents.set(agent.id, agent);
201
+ }
202
+ logger.info(`Initialized ${agents.length} specialized agents`);
203
+ return agents;
204
+ }
205
+ /**
206
+ * Allocate tasks to agents based on specialization and workload
207
+ */
208
+ async allocateTasksToAgents(tasks, agents) {
209
+ const allocation = {
210
+ assignments: /* @__PURE__ */ new Map(),
211
+ loadBalancing: "capability_based",
212
+ conflictResolution: this.config.conflictResolutionStrategy
213
+ };
214
+ const sortedTasks = this.topologicalSort(tasks);
215
+ for (const task of sortedTasks) {
216
+ const suitableAgents = agents.filter(
217
+ (agent) => task.requiredRoles.some((role) => this.agentCanHandle(agent, role))
218
+ );
219
+ if (suitableAgents.length === 0) {
220
+ logger.warn(`No suitable agents found for task: ${task.title}`);
221
+ continue;
222
+ }
223
+ const selectedAgent = this.selectOptimalAgent(suitableAgents, task);
224
+ allocation.assignments.set(task.id, {
225
+ agentId: selectedAgent.id,
226
+ taskId: task.id,
227
+ assignedAt: Date.now(),
228
+ estimatedCompletion: Date.now() + this.estimateTaskDuration(task),
229
+ coordination: {
230
+ collaborators: this.findCollaborators(selectedAgent, task, agents),
231
+ reviewers: this.findReviewers(selectedAgent, task, agents)
232
+ }
233
+ });
234
+ selectedAgent.currentTask = task.id;
235
+ }
236
+ return allocation;
237
+ }
238
+ /**
239
+ * Execute swarm tasks with coordination
240
+ */
241
+ async executeSwarmTasks(allocation) {
242
+ const executionPromises = [];
243
+ for (const [taskId, assignment] of allocation.assignments) {
244
+ const agent = this.activeAgents.get(assignment.agentId);
245
+ const task = this.swarmState.tasks?.find((t) => t.id === taskId);
246
+ if (!agent || !task) continue;
247
+ const executionPromise = this.executeAgentTask(agent, task, assignment);
248
+ executionPromises.push(executionPromise);
249
+ }
250
+ await Promise.allSettled(executionPromises);
251
+ }
252
+ /**
253
+ * Execute a single agent task with coordination
254
+ */
255
+ async executeAgentTask(agent, task, assignment) {
256
+ logger.info(`Agent ${agent.role} starting task: ${task.title}`);
257
+ try {
258
+ agent.status = "active";
259
+ const ralph = new RalphStackMemoryBridge({
260
+ baseDir: path.join(agent.workingDirectory, task.id),
261
+ maxIterations: this.calculateMaxIterations(task),
262
+ useStackMemory: true
263
+ });
264
+ const contextualPrompt = await this.synthesizeContextualPrompt(agent, task);
265
+ await ralph.initialize({
266
+ task: contextualPrompt,
267
+ criteria: task.acceptanceCriteria.join("\n")
268
+ });
269
+ this.setupAgentCoordination(agent, ralph, assignment);
270
+ await ralph.run();
271
+ this.updateAgentPerformance(agent, true);
272
+ await this.notifyTaskCompletion(agent, task, true);
273
+ agent.status = "idle";
274
+ logger.info(`Agent ${agent.role} completed task: ${task.title}`);
275
+ } catch (error) {
276
+ logger.error(`Agent ${agent.role} failed task: ${task.title}`, error);
277
+ this.updateAgentPerformance(agent, false);
278
+ await this.handleTaskFailure(agent, task, error);
279
+ agent.status = "error";
280
+ }
281
+ }
282
+ /**
283
+ * Synthesize contextual prompt incorporating swarm knowledge
284
+ */
285
+ async synthesizeContextualPrompt(agent, task) {
286
+ const basePrompt = task.description;
287
+ const roleSpecificInstructions = this.getRoleSpecificInstructions(agent.role);
288
+ const swarmContext = await this.getSwarmContext(task);
289
+ const coordinationInstructions = this.getCoordinationInstructions(agent);
290
+ return `
291
+ ${roleSpecificInstructions}
292
+
293
+ TASK: ${basePrompt}
294
+
295
+ SWARM CONTEXT:
296
+ ${swarmContext}
297
+
298
+ COORDINATION GUIDELINES:
299
+ ${coordinationInstructions}
300
+
301
+ Remember:
302
+ - You are part of a swarm working on: ${this.swarmState.project}
303
+ - Other agents are working on related tasks
304
+ - Communicate findings through StackMemory shared context
305
+ - Focus on your specialization while being aware of the bigger picture
306
+ - Detect and avoid pathological behaviors (infinite loops, tunnel vision)
307
+ - Request fresh starts if you detect drift in your approach
308
+
309
+ ACCEPTANCE CRITERIA:
310
+ ${task.acceptanceCriteria.map((c) => `- ${c}`).join("\n")}
311
+ `;
312
+ }
313
+ /**
314
+ * Start coordination monitoring loop
315
+ */
316
+ startCoordinationLoop() {
317
+ this.coordinationTimer = setInterval(() => {
318
+ this.performCoordinationCycle().catch((error) => {
319
+ logger.error("Coordination cycle failed", error);
320
+ });
321
+ }, this.config.coordinationInterval);
322
+ }
323
+ /**
324
+ * Perform coordination cycle
325
+ */
326
+ async performCoordinationCycle() {
327
+ if (this.swarmState.status !== "active") return;
328
+ logger.debug("Performing coordination cycle");
329
+ if (this.config.pathologicalBehaviorDetection) {
330
+ await this.detectPathologicalBehaviors();
331
+ }
332
+ if (this.config.enableDynamicPlanning) {
333
+ await this.wakeUpPlanners();
334
+ }
335
+ await this.resolveActiveConflicts();
336
+ await this.rebalanceWorkload();
337
+ await this.triggerFreshStartsIfNeeded();
338
+ this.updateSwarmMetrics();
339
+ }
340
+ /**
341
+ * Detect pathological behaviors in agents
342
+ */
343
+ async detectPathologicalBehaviors() {
344
+ for (const agent of this.activeAgents.values()) {
345
+ if (agent.status !== "active") continue;
346
+ if (agent.performance.driftDetected) {
347
+ logger.warn(`Drift detected in agent ${agent.role}, triggering fresh start`);
348
+ await this.triggerFreshStart(agent);
349
+ continue;
350
+ }
351
+ if (await this.detectTunnelVision(agent)) {
352
+ logger.warn(`Tunnel vision detected in agent ${agent.role}, providing alternative approach`);
353
+ await this.provideAlternativeApproach(agent);
354
+ }
355
+ if (await this.detectExcessiveRuntime(agent)) {
356
+ logger.warn(`Excessive runtime detected in agent ${agent.role}, requesting checkpoint`);
357
+ await this.requestCheckpoint(agent);
358
+ }
359
+ }
360
+ }
361
+ /**
362
+ * Wake up planners when their tasks complete
363
+ */
364
+ async wakeUpPlanners() {
365
+ for (const [agentId, wakeupCallback] of this.plannerWakeupQueue) {
366
+ const agent = this.activeAgents.get(agentId);
367
+ if (!agent || agent.status !== "idle") continue;
368
+ logger.info(`Waking up planner agent: ${agent.role}`);
369
+ wakeupCallback();
370
+ this.plannerWakeupQueue.delete(agentId);
371
+ }
372
+ }
373
+ // Helper methods for role specialization and coordination
374
+ defineCapabilities(role) {
375
+ const capabilityMap = {
376
+ "architect": ["system_design", "component_modeling", "architecture_validation"],
377
+ "planner": ["task_decomposition", "dependency_analysis", "resource_planning"],
378
+ "developer": ["code_implementation", "debugging", "refactoring"],
379
+ "reviewer": ["code_review", "quality_assessment", "best_practice_enforcement"],
380
+ "tester": ["test_design", "automation", "validation"],
381
+ "optimizer": ["performance_analysis", "resource_optimization", "bottleneck_identification"],
382
+ "documenter": ["technical_writing", "api_documentation", "example_creation"],
383
+ "coordinator": ["task_coordination", "conflict_resolution", "progress_tracking"]
384
+ };
385
+ return capabilityMap[role] || [];
386
+ }
387
+ defineCommuncationStyle(role) {
388
+ const styleMap = {
389
+ "architect": "high_level_design_focused",
390
+ "planner": "structured_and_methodical",
391
+ "developer": "implementation_focused",
392
+ "reviewer": "quality_focused_constructive",
393
+ "tester": "validation_focused",
394
+ "optimizer": "performance_metrics_focused",
395
+ "documenter": "clarity_focused",
396
+ "coordinator": "facilitative_and_diplomatic"
397
+ };
398
+ return styleMap[role] || "collaborative";
399
+ }
400
+ getRoleSpecificInstructions(role) {
401
+ const instructionMap = {
402
+ "architect": `
403
+ You are a SYSTEM ARCHITECT. Your role is to:
404
+ - Design high-level system architecture
405
+ - Define component interfaces and relationships
406
+ - Ensure architectural consistency across the project
407
+ - Think in terms of scalability, maintainability, and extensibility
408
+ - Collaborate with developers to validate feasibility`,
409
+ "planner": `
410
+ You are a PROJECT PLANNER. Your role is to:
411
+ - Break down complex tasks into manageable steps
412
+ - Identify dependencies and critical path
413
+ - Coordinate with other agents on sequencing
414
+ - Wake up when tasks complete to plan next steps
415
+ - Adapt plans based on actual progress`,
416
+ "developer": `
417
+ You are a SPECIALIZED DEVELOPER. Your role is to:
418
+ - Implement features according to specifications
419
+ - Write clean, maintainable code
420
+ - Follow established patterns and conventions
421
+ - Integrate with other components
422
+ - Communicate implementation details clearly`,
423
+ "reviewer": `
424
+ You are a CODE REVIEWER. Your role is to:
425
+ - Review code for quality, correctness, and best practices
426
+ - Provide constructive feedback
427
+ - Ensure consistency with project standards
428
+ - Identify potential issues before they become problems
429
+ - Approve or request changes`,
430
+ "tester": `
431
+ You are a QA ENGINEER. Your role is to:
432
+ - Design comprehensive test strategies
433
+ - Implement automated tests
434
+ - Validate functionality and performance
435
+ - Report bugs clearly and reproducibly
436
+ - Ensure quality gates are met`,
437
+ "optimizer": `
438
+ You are a PERFORMANCE OPTIMIZER. Your role is to:
439
+ - Analyze system performance and identify bottlenecks
440
+ - Implement optimizations
441
+ - Monitor resource usage
442
+ - Establish performance benchmarks
443
+ - Ensure scalability requirements are met`,
444
+ "documenter": `
445
+ You are a TECHNICAL WRITER. Your role is to:
446
+ - Create clear, comprehensive documentation
447
+ - Write API documentation and usage examples
448
+ - Ensure documentation stays up-to-date
449
+ - Focus on user experience and clarity
450
+ - Collaborate with developers to understand features`,
451
+ "coordinator": `
452
+ You are a PROJECT COORDINATOR. Your role is to:
453
+ - Facilitate communication between agents
454
+ - Resolve conflicts and blockers
455
+ - Track overall project progress
456
+ - Ensure no tasks fall through cracks
457
+ - Maintain project timeline and quality`
458
+ };
459
+ return instructionMap[role] || "You are a specialized agent contributing to a larger project.";
460
+ }
461
+ // Additional helper methods would be implemented here...
462
+ analyzeProjectComplexity(description) {
463
+ return {
464
+ needsArchitecture: description.length > 500 || description.includes("system") || description.includes("platform"),
465
+ needsTesting: true,
466
+ // Almost all projects need testing
467
+ needsDocumentation: description.includes("API") || description.includes("library"),
468
+ complexity: "medium"
469
+ };
470
+ }
471
+ extractCoreFeatures(description) {
472
+ return [{
473
+ name: "Core Feature",
474
+ description: "Main functionality implementation",
475
+ complexity: "medium",
476
+ criteria: ["Feature works correctly", "Handles edge cases", "Follows coding standards"]
477
+ }];
478
+ }
479
+ // Implement remaining helper methods...
480
+ [Symbol.toStringTag] = "SwarmCoordinator";
481
+ }
482
+ const swarmCoordinator = new SwarmCoordinator();
483
+ export {
484
+ SwarmCoordinator,
485
+ swarmCoordinator
486
+ };
487
+ //# sourceMappingURL=swarm-coordinator.js.map
@@ -0,0 +1,7 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../../../../src/integrations/ralph/swarm/swarm-coordinator.ts"],
4
+ "sourcesContent": ["/**\n * Swarm Coordination System for StackMemory\n * Orchestrates multiple specialized agents working together on the same codebase\n * Addresses multi-agent coordination challenges with role specialization and dynamic planning\n */\n\nimport { v4 as uuidv4 } from 'uuid';\nimport { logger } from '../../../core/monitoring/logger.js';\nimport { FrameManager } from '../../../core/context/frame-manager.js';\nimport { sessionManager } from '../../../core/session/index.js';\nimport { sharedContextLayer } from '../../../core/context/shared-context-layer.js';\nimport { RalphStackMemoryBridge } from '../bridge/ralph-stackmemory-bridge.js';\nimport {\n SwarmConfiguration,\n Agent,\n AgentRole,\n SwarmTask,\n CoordinationEvent,\n SwarmState,\n TaskAllocation,\n AgentSpecialization\n} from '../types.js';\n\nexport interface SwarmCoordinatorConfig {\n maxAgents: number;\n coordinationInterval: number;\n driftDetectionThreshold: number;\n freshStartInterval: number;\n conflictResolutionStrategy: 'democratic' | 'hierarchical' | 'expertise';\n enableDynamicPlanning: boolean;\n pathologicalBehaviorDetection: boolean;\n}\n\nexport class SwarmCoordinator {\n private frameManager?: FrameManager;\n private activeAgents: Map<string, Agent> = new Map();\n private swarmState: SwarmState;\n private config: SwarmCoordinatorConfig;\n private coordinationTimer?: NodeJS.Timeout;\n private plannerWakeupQueue: Map<string, () => void> = new Map();\n\n constructor(config?: Partial<SwarmCoordinatorConfig>) {\n this.config = {\n maxAgents: 10,\n coordinationInterval: 30000, // 30 seconds\n driftDetectionThreshold: 5, // 5 failed iterations before considering drift\n freshStartInterval: 3600000, // 1 hour\n conflictResolutionStrategy: 'expertise',\n enableDynamicPlanning: true,\n pathologicalBehaviorDetection: true,\n ...config\n };\n\n this.swarmState = {\n id: uuidv4(),\n status: 'idle',\n startTime: Date.now(),\n activeTaskCount: 0,\n completedTaskCount: 0,\n coordination: {\n events: [],\n conflicts: [],\n resolutions: []\n },\n performance: {\n throughput: 0,\n efficiency: 0,\n coordination_overhead: 0\n }\n };\n\n logger.info('Swarm coordinator initialized', this.config);\n }\n\n async initialize(): Promise<void> {\n try {\n await sessionManager.initialize();\n await sharedContextLayer.initialize();\n\n const session = await sessionManager.getOrCreateSession({});\n if (session.database) {\n this.frameManager = new FrameManager(session.database, session.projectId);\n }\n\n // Start coordination monitoring\n this.startCoordinationLoop();\n\n logger.info('Swarm coordinator initialized successfully');\n } catch (error: unknown) {\n logger.error('Failed to initialize swarm coordinator', error as Error);\n throw error;\n }\n }\n\n /**\n * Launch a swarm of agents to work on a complex project\n */\n async launchSwarm(\n projectDescription: string,\n agents: AgentSpecialization[],\n coordination?: SwarmConfiguration\n ): Promise<string> {\n logger.info('Launching swarm', {\n project: projectDescription.substring(0, 100),\n agentCount: agents.length\n });\n\n const swarmId = uuidv4();\n \n try {\n // 1. Validate swarm configuration\n if (agents.length > this.config.maxAgents) {\n throw new Error(`Too many agents requested: ${agents.length} > ${this.config.maxAgents}`);\n }\n\n // 2. Break down project into swarm tasks\n const swarmTasks = await this.decomposeProjectIntoSwarmTasks(projectDescription);\n\n // 3. Initialize specialized agents\n const initializedAgents = await this.initializeSpecializedAgents(agents, swarmTasks);\n\n // 4. Create task allocation plan\n const allocation = await this.allocateTasksToAgents(swarmTasks, initializedAgents);\n\n // 5. Begin swarm execution\n this.swarmState = {\n ...this.swarmState,\n id: swarmId,\n status: 'active',\n activeTaskCount: swarmTasks.length,\n project: projectDescription,\n agents: initializedAgents,\n tasks: swarmTasks,\n allocation\n };\n\n // 6. Start agent execution\n await this.executeSwarmTasks(allocation);\n\n logger.info('Swarm launched successfully', { swarmId, agentCount: initializedAgents.length });\n return swarmId;\n\n } catch (error: unknown) {\n logger.error('Failed to launch swarm', error as Error);\n throw error;\n }\n }\n\n /**\n * Decompose project into tasks suitable for swarm execution\n */\n private async decomposeProjectIntoSwarmTasks(projectDescription: string): Promise<SwarmTask[]> {\n const tasks: SwarmTask[] = [];\n \n // Analyze project complexity and decompose based on patterns\n const complexity = this.analyzeProjectComplexity(projectDescription);\n \n // Pattern 1: Architecture and Planning\n if (complexity.needsArchitecture) {\n tasks.push({\n id: uuidv4(),\n type: 'architecture',\n title: 'System Architecture Design',\n description: 'Design overall system architecture and component relationships',\n priority: 1,\n estimatedEffort: 'high',\n requiredRoles: ['architect', 'system_designer'],\n dependencies: [],\n acceptanceCriteria: [\n 'Architecture diagram created',\n 'Component interfaces defined',\n 'Data flow documented'\n ]\n });\n }\n\n // Pattern 2: Core Implementation Tasks\n const coreFeatures = this.extractCoreFeatures(projectDescription);\n for (const feature of coreFeatures) {\n tasks.push({\n id: uuidv4(),\n type: 'implementation',\n title: `Implement ${feature.name}`,\n description: feature.description,\n priority: 2,\n estimatedEffort: feature.complexity,\n requiredRoles: ['developer', feature.specialization || 'fullstack'],\n dependencies: complexity.needsArchitecture ? [tasks[0].id] : [],\n acceptanceCriteria: feature.criteria\n });\n }\n\n // Pattern 3: Testing and Validation\n if (complexity.needsTesting) {\n tasks.push({\n id: uuidv4(),\n type: 'testing',\n title: 'Comprehensive Testing Suite',\n description: 'Create unit, integration, and end-to-end tests',\n priority: 3,\n estimatedEffort: 'medium',\n requiredRoles: ['qa_engineer', 'test_automation'],\n dependencies: tasks.filter(t => t.type === 'implementation').map(t => t.id),\n acceptanceCriteria: [\n 'Unit tests achieve >90% coverage',\n 'Integration tests pass',\n 'Performance benchmarks met'\n ]\n });\n }\n\n // Pattern 4: Documentation and Polish\n if (complexity.needsDocumentation) {\n tasks.push({\n id: uuidv4(),\n type: 'documentation',\n title: 'Documentation and Examples',\n description: 'Create user documentation, API docs, and usage examples',\n priority: 4,\n estimatedEffort: 'low',\n requiredRoles: ['technical_writer', 'developer'],\n dependencies: [], // Can run in parallel\n acceptanceCriteria: [\n 'README with setup instructions',\n 'API documentation complete',\n 'Usage examples provided'\n ]\n });\n }\n\n return tasks;\n }\n\n /**\n * Initialize specialized agents with role-specific configurations\n */\n private async initializeSpecializedAgents(\n specifications: AgentSpecialization[],\n tasks: SwarmTask[]\n ): Promise<Agent[]> {\n const agents: Agent[] = [];\n\n for (const spec of specifications) {\n const agent: Agent = {\n id: uuidv4(),\n role: spec.role,\n specialization: spec,\n status: 'initializing',\n capabilities: this.defineCapabilities(spec.role),\n workingDirectory: `.swarm/${spec.role}-${Date.now()}`,\n currentTask: null,\n performance: {\n tasksCompleted: 0,\n successRate: 1.0,\n averageTaskTime: 0,\n driftDetected: false,\n lastFreshStart: Date.now()\n },\n coordination: {\n communicationStyle: this.defineCommuncationStyle(spec.role),\n conflictResolution: spec.conflictResolution || 'defer_to_expertise',\n collaborationPreferences: spec.collaborationPreferences || []\n }\n };\n\n // Initialize agent's working environment\n await this.setupAgentEnvironment(agent);\n\n // Configure role-specific prompting strategies\n await this.configureAgentPrompts(agent);\n\n agents.push(agent);\n this.activeAgents.set(agent.id, agent);\n }\n\n logger.info(`Initialized ${agents.length} specialized agents`);\n return agents;\n }\n\n /**\n * Allocate tasks to agents based on specialization and workload\n */\n private async allocateTasksToAgents(\n tasks: SwarmTask[],\n agents: Agent[]\n ): Promise<TaskAllocation> {\n const allocation: TaskAllocation = {\n assignments: new Map(),\n loadBalancing: 'capability_based',\n conflictResolution: this.config.conflictResolutionStrategy\n };\n\n // Sort tasks by priority and dependencies\n const sortedTasks = this.topologicalSort(tasks);\n\n for (const task of sortedTasks) {\n // Find best-suited agents for this task\n const suitableAgents = agents.filter(agent =>\n task.requiredRoles.some(role => this.agentCanHandle(agent, role))\n );\n\n if (suitableAgents.length === 0) {\n logger.warn(`No suitable agents found for task: ${task.title}`);\n continue;\n }\n\n // Select agent based on workload and expertise\n const selectedAgent = this.selectOptimalAgent(suitableAgents, task);\n \n allocation.assignments.set(task.id, {\n agentId: selectedAgent.id,\n taskId: task.id,\n assignedAt: Date.now(),\n estimatedCompletion: Date.now() + this.estimateTaskDuration(task),\n coordination: {\n collaborators: this.findCollaborators(selectedAgent, task, agents),\n reviewers: this.findReviewers(selectedAgent, task, agents)\n }\n });\n\n // Update agent workload\n selectedAgent.currentTask = task.id;\n }\n\n return allocation;\n }\n\n /**\n * Execute swarm tasks with coordination\n */\n private async executeSwarmTasks(allocation: TaskAllocation): Promise<void> {\n const executionPromises: Promise<void>[] = [];\n\n for (const [taskId, assignment] of allocation.assignments) {\n const agent = this.activeAgents.get(assignment.agentId);\n const task = this.swarmState.tasks?.find(t => t.id === taskId);\n\n if (!agent || !task) continue;\n\n // Create execution promise for each agent\n const executionPromise = this.executeAgentTask(agent, task, assignment);\n executionPromises.push(executionPromise);\n }\n\n // Monitor all executions\n await Promise.allSettled(executionPromises);\n }\n\n /**\n * Execute a single agent task with coordination\n */\n private async executeAgentTask(\n agent: Agent,\n task: SwarmTask,\n assignment: any\n ): Promise<void> {\n logger.info(`Agent ${agent.role} starting task: ${task.title}`);\n\n try {\n agent.status = 'active';\n \n // Create Ralph loop for this agent/task\n const ralph = new RalphStackMemoryBridge({\n baseDir: path.join(agent.workingDirectory, task.id),\n maxIterations: this.calculateMaxIterations(task),\n useStackMemory: true\n });\n\n // Initialize with context from other agents\n const contextualPrompt = await this.synthesizeContextualPrompt(agent, task);\n \n await ralph.initialize({\n task: contextualPrompt,\n criteria: task.acceptanceCriteria.join('\\n')\n });\n\n // Set up coordination hooks\n this.setupAgentCoordination(agent, ralph, assignment);\n\n // Run the task\n await ralph.run();\n\n // Update performance metrics\n this.updateAgentPerformance(agent, true);\n \n // Notify planners and collaborators\n await this.notifyTaskCompletion(agent, task, true);\n\n agent.status = 'idle';\n logger.info(`Agent ${agent.role} completed task: ${task.title}`);\n\n } catch (error: unknown) {\n logger.error(`Agent ${agent.role} failed task: ${task.title}`, error as Error);\n \n // Update performance metrics\n this.updateAgentPerformance(agent, false);\n \n // Trigger conflict resolution or reassignment\n await this.handleTaskFailure(agent, task, error as Error);\n \n agent.status = 'error';\n }\n }\n\n /**\n * Synthesize contextual prompt incorporating swarm knowledge\n */\n private async synthesizeContextualPrompt(agent: Agent, task: SwarmTask): Promise<string> {\n const basePrompt = task.description;\n const roleSpecificInstructions = this.getRoleSpecificInstructions(agent.role);\n const swarmContext = await this.getSwarmContext(task);\n const coordinationInstructions = this.getCoordinationInstructions(agent);\n\n return `\n${roleSpecificInstructions}\n\nTASK: ${basePrompt}\n\nSWARM CONTEXT:\n${swarmContext}\n\nCOORDINATION GUIDELINES:\n${coordinationInstructions}\n\nRemember:\n- You are part of a swarm working on: ${this.swarmState.project}\n- Other agents are working on related tasks\n- Communicate findings through StackMemory shared context\n- Focus on your specialization while being aware of the bigger picture\n- Detect and avoid pathological behaviors (infinite loops, tunnel vision)\n- Request fresh starts if you detect drift in your approach\n\nACCEPTANCE CRITERIA:\n${task.acceptanceCriteria.map(c => `- ${c}`).join('\\n')}\n`;\n }\n\n /**\n * Start coordination monitoring loop\n */\n private startCoordinationLoop(): void {\n this.coordinationTimer = setInterval(() => {\n this.performCoordinationCycle().catch(error => {\n logger.error('Coordination cycle failed', error as Error);\n });\n }, this.config.coordinationInterval);\n }\n\n /**\n * Perform coordination cycle\n */\n private async performCoordinationCycle(): Promise<void> {\n if (this.swarmState.status !== 'active') return;\n\n logger.debug('Performing coordination cycle');\n\n // 1. Detect pathological behaviors\n if (this.config.pathologicalBehaviorDetection) {\n await this.detectPathologicalBehaviors();\n }\n\n // 2. Check for task completion and wake planners\n if (this.config.enableDynamicPlanning) {\n await this.wakeUpPlanners();\n }\n\n // 3. Resolve conflicts\n await this.resolveActiveConflicts();\n\n // 4. Rebalance workload if needed\n await this.rebalanceWorkload();\n\n // 5. Trigger fresh starts if needed\n await this.triggerFreshStartsIfNeeded();\n\n // 6. Update swarm performance metrics\n this.updateSwarmMetrics();\n }\n\n /**\n * Detect pathological behaviors in agents\n */\n private async detectPathologicalBehaviors(): Promise<void> {\n for (const agent of this.activeAgents.values()) {\n if (agent.status !== 'active') continue;\n\n // Check for drift (repeated failures)\n if (agent.performance.driftDetected) {\n logger.warn(`Drift detected in agent ${agent.role}, triggering fresh start`);\n await this.triggerFreshStart(agent);\n continue;\n }\n\n // Check for tunnel vision (same approach repeated)\n if (await this.detectTunnelVision(agent)) {\n logger.warn(`Tunnel vision detected in agent ${agent.role}, providing alternative approach`);\n await this.provideAlternativeApproach(agent);\n }\n\n // Check for excessive runtime (running too long)\n if (await this.detectExcessiveRuntime(agent)) {\n logger.warn(`Excessive runtime detected in agent ${agent.role}, requesting checkpoint`);\n await this.requestCheckpoint(agent);\n }\n }\n }\n\n /**\n * Wake up planners when their tasks complete\n */\n private async wakeUpPlanners(): Promise<void> {\n for (const [agentId, wakeupCallback] of this.plannerWakeupQueue) {\n const agent = this.activeAgents.get(agentId);\n if (!agent || agent.status !== 'idle') continue;\n\n logger.info(`Waking up planner agent: ${agent.role}`);\n wakeupCallback();\n this.plannerWakeupQueue.delete(agentId);\n }\n }\n\n // Helper methods for role specialization and coordination\n private defineCapabilities(role: AgentRole): string[] {\n const capabilityMap: Record<AgentRole, string[]> = {\n 'architect': ['system_design', 'component_modeling', 'architecture_validation'],\n 'planner': ['task_decomposition', 'dependency_analysis', 'resource_planning'],\n 'developer': ['code_implementation', 'debugging', 'refactoring'],\n 'reviewer': ['code_review', 'quality_assessment', 'best_practice_enforcement'],\n 'tester': ['test_design', 'automation', 'validation'],\n 'optimizer': ['performance_analysis', 'resource_optimization', 'bottleneck_identification'],\n 'documenter': ['technical_writing', 'api_documentation', 'example_creation'],\n 'coordinator': ['task_coordination', 'conflict_resolution', 'progress_tracking']\n };\n\n return capabilityMap[role] || [];\n }\n\n private defineCommuncationStyle(role: AgentRole): string {\n const styleMap: Record<AgentRole, string> = {\n 'architect': 'high_level_design_focused',\n 'planner': 'structured_and_methodical',\n 'developer': 'implementation_focused',\n 'reviewer': 'quality_focused_constructive',\n 'tester': 'validation_focused',\n 'optimizer': 'performance_metrics_focused',\n 'documenter': 'clarity_focused',\n 'coordinator': 'facilitative_and_diplomatic'\n };\n\n return styleMap[role] || 'collaborative';\n }\n\n private getRoleSpecificInstructions(role: AgentRole): string {\n const instructionMap: Record<AgentRole, string> = {\n 'architect': `\nYou are a SYSTEM ARCHITECT. Your role is to:\n- Design high-level system architecture\n- Define component interfaces and relationships\n- Ensure architectural consistency across the project\n- Think in terms of scalability, maintainability, and extensibility\n- Collaborate with developers to validate feasibility`,\n\n 'planner': `\nYou are a PROJECT PLANNER. Your role is to:\n- Break down complex tasks into manageable steps\n- Identify dependencies and critical path\n- Coordinate with other agents on sequencing\n- Wake up when tasks complete to plan next steps\n- Adapt plans based on actual progress`,\n\n 'developer': `\nYou are a SPECIALIZED DEVELOPER. Your role is to:\n- Implement features according to specifications\n- Write clean, maintainable code\n- Follow established patterns and conventions\n- Integrate with other components\n- Communicate implementation details clearly`,\n\n 'reviewer': `\nYou are a CODE REVIEWER. Your role is to:\n- Review code for quality, correctness, and best practices\n- Provide constructive feedback\n- Ensure consistency with project standards\n- Identify potential issues before they become problems\n- Approve or request changes`,\n\n 'tester': `\nYou are a QA ENGINEER. Your role is to:\n- Design comprehensive test strategies\n- Implement automated tests\n- Validate functionality and performance\n- Report bugs clearly and reproducibly\n- Ensure quality gates are met`,\n\n 'optimizer': `\nYou are a PERFORMANCE OPTIMIZER. Your role is to:\n- Analyze system performance and identify bottlenecks\n- Implement optimizations\n- Monitor resource usage\n- Establish performance benchmarks\n- Ensure scalability requirements are met`,\n\n 'documenter': `\nYou are a TECHNICAL WRITER. Your role is to:\n- Create clear, comprehensive documentation\n- Write API documentation and usage examples\n- Ensure documentation stays up-to-date\n- Focus on user experience and clarity\n- Collaborate with developers to understand features`,\n\n 'coordinator': `\nYou are a PROJECT COORDINATOR. Your role is to:\n- Facilitate communication between agents\n- Resolve conflicts and blockers\n- Track overall project progress\n- Ensure no tasks fall through cracks\n- Maintain project timeline and quality`\n };\n\n return instructionMap[role] || 'You are a specialized agent contributing to a larger project.';\n }\n\n // Additional helper methods would be implemented here...\n private analyzeProjectComplexity(description: string): any {\n // Analyze project description to determine decomposition strategy\n return {\n needsArchitecture: description.length > 500 || description.includes('system') || description.includes('platform'),\n needsTesting: true, // Almost all projects need testing\n needsDocumentation: description.includes('API') || description.includes('library'),\n complexity: 'medium'\n };\n }\n\n private extractCoreFeatures(description: string): any[] {\n // Extract core features from project description\n // This would use NLP in a real implementation\n return [{\n name: 'Core Feature',\n description: 'Main functionality implementation',\n complexity: 'medium',\n criteria: ['Feature works correctly', 'Handles edge cases', 'Follows coding standards']\n }];\n }\n\n // Implement remaining helper methods...\n [Symbol.toStringTag] = 'SwarmCoordinator';\n}\n\n// Export default instance\nexport const swarmCoordinator = new SwarmCoordinator();"],
5
+ "mappings": "AAMA,SAAS,MAAM,cAAc;AAC7B,SAAS,cAAc;AACvB,SAAS,oBAAoB;AAC7B,SAAS,sBAAsB;AAC/B,SAAS,0BAA0B;AACnC,SAAS,8BAA8B;AAsBhC,MAAM,iBAAiB;AAAA,EACpB;AAAA,EACA,eAAmC,oBAAI,IAAI;AAAA,EAC3C;AAAA,EACA;AAAA,EACA;AAAA,EACA,qBAA8C,oBAAI,IAAI;AAAA,EAE9D,YAAY,QAA0C;AACpD,SAAK,SAAS;AAAA,MACZ,WAAW;AAAA,MACX,sBAAsB;AAAA;AAAA,MACtB,yBAAyB;AAAA;AAAA,MACzB,oBAAoB;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