@stackmemoryai/stackmemory 1.12.0 → 1.14.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 (162) hide show
  1. package/LICENSE +131 -64
  2. package/README.md +3 -1
  3. package/bin/claude-sm +16 -1
  4. package/bin/claude-smd +16 -1
  5. package/bin/codex-smd +16 -1
  6. package/bin/gemini-sm +16 -1
  7. package/bin/hermes-sm +21 -0
  8. package/bin/hermes-smd +21 -0
  9. package/bin/opencode-sm +16 -1
  10. package/dist/src/cli/codex-sm.js +51 -11
  11. package/dist/src/cli/commands/brain.js +206 -0
  12. package/dist/src/cli/commands/company-os.js +184 -0
  13. package/dist/src/cli/commands/context.js +5 -0
  14. package/dist/src/cli/commands/operator.js +127 -0
  15. package/dist/src/cli/commands/orchestrate.js +2 -0
  16. package/dist/src/cli/commands/orchestrator.js +3 -2
  17. package/dist/src/cli/commands/patterns.js +254 -0
  18. package/dist/src/cli/commands/portal.js +161 -0
  19. package/dist/src/cli/commands/scaffold.js +92 -0
  20. package/dist/src/cli/commands/setup.js +1 -4
  21. package/dist/src/cli/commands/sync.js +253 -0
  22. package/dist/src/cli/commands/tasks.js +130 -1
  23. package/dist/src/cli/commands/vision.js +221 -0
  24. package/dist/src/cli/hermes-sm.js +224 -0
  25. package/dist/src/cli/index.js +15 -10
  26. package/dist/src/cli/utils/real-cli-bin.js +72 -0
  27. package/dist/src/core/brain/brain-store.js +187 -0
  28. package/dist/src/core/brain/brain-sync.js +193 -0
  29. package/dist/src/core/brain/index.js +78 -0
  30. package/dist/src/core/brain/types.js +10 -0
  31. package/dist/src/core/cache/token-estimator.js +24 -1
  32. package/dist/src/core/config/feature-flags.js +2 -6
  33. package/dist/src/core/context/frame-database.js +44 -0
  34. package/dist/src/core/context/recursive-context-manager.js +1 -1
  35. package/dist/src/core/context/rehydration.js +2 -1
  36. package/dist/src/core/database/sqlite-adapter.js +14 -1
  37. package/dist/src/core/models/model-router.js +33 -1
  38. package/dist/src/core/models/provider-pricing.js +58 -4
  39. package/dist/src/core/patterns/index.js +22 -0
  40. package/dist/src/core/patterns/pattern-applier.js +39 -0
  41. package/dist/src/core/patterns/pattern-observer.js +157 -0
  42. package/dist/src/core/patterns/pattern-store.js +259 -0
  43. package/dist/src/core/patterns/types.js +19 -0
  44. package/dist/src/core/retrieval/llm-context-retrieval.js +5 -4
  45. package/dist/src/core/retrieval/unified-context-assembler.js +11 -66
  46. package/dist/src/core/skill-packs/types.js +14 -1
  47. package/dist/src/core/storage/cloud-sync-manager.js +116 -0
  48. package/dist/src/core/storage/cloud-sync.js +574 -0
  49. package/dist/src/core/storage/two-tier-storage.js +5 -1
  50. package/dist/src/core/tasks/master-tasks-template.js +43 -0
  51. package/dist/src/core/tasks/md-task-parser.js +138 -0
  52. package/dist/src/core/vision/index.js +27 -0
  53. package/dist/src/core/vision/signals.js +79 -0
  54. package/dist/src/core/vision/types.js +22 -0
  55. package/dist/src/core/vision/vision-file.js +146 -0
  56. package/dist/src/core/vision/vision-loop.js +220 -0
  57. package/dist/src/core/wiki/wiki-compiler.js +103 -1
  58. package/dist/src/daemon/daemon-config.js +45 -0
  59. package/dist/src/daemon/services/desire-path-service.js +566 -0
  60. package/dist/src/daemon/services/research-stream-service.js +320 -0
  61. package/dist/src/daemon/services/telemetry-service.js +192 -0
  62. package/dist/src/daemon/unified-daemon.js +28 -1
  63. package/dist/src/features/browser/cli-browser-agent.js +417 -0
  64. package/dist/src/features/browser/stagehand-workflows.js +578 -0
  65. package/dist/src/features/operator/adapter-factory.js +62 -0
  66. package/dist/src/features/operator/browser-adapter.js +109 -0
  67. package/dist/src/features/operator/desktop-adapter.js +125 -0
  68. package/dist/src/features/operator/index.js +39 -0
  69. package/dist/src/features/operator/llm-decision.js +137 -0
  70. package/dist/src/features/operator/operator-logger.js +92 -0
  71. package/dist/src/features/operator/overnight-runner.js +327 -0
  72. package/dist/src/features/operator/screen-adapter.js +91 -0
  73. package/dist/src/features/operator/session-manager.js +127 -0
  74. package/dist/src/features/operator/state-machine.js +227 -0
  75. package/dist/src/features/operator/task-queue.js +81 -0
  76. package/dist/src/features/portal/index.js +26 -0
  77. package/dist/src/features/portal/server.js +240 -0
  78. package/dist/src/features/portal/types.js +14 -0
  79. package/dist/src/features/portal/ui.js +195 -0
  80. package/dist/src/features/tasks/task-aware-context.js +2 -1
  81. package/dist/src/features/tui/simple-monitor.js +0 -23
  82. package/dist/src/features/tui/swarm-monitor.js +8 -66
  83. package/dist/src/{integrations/diffmem/index.js → features/web/client/hooks/use-socket.js} +6 -5
  84. package/dist/src/features/web/client/lib/utils.js +12 -0
  85. package/dist/src/features/web/client/stores/session-store.js +12 -0
  86. package/dist/src/features/web/server/gcp-billing.js +76 -0
  87. package/dist/src/features/web/server/index.js +10 -0
  88. package/dist/src/features/web/server/spend-calculator.js +228 -0
  89. package/dist/src/hooks/schemas.js +4 -1
  90. package/dist/src/integrations/anthropic/client.js +3 -2
  91. package/dist/src/integrations/claude-code/agent-bridge.js +0 -3
  92. package/dist/src/integrations/claude-code/subagent-client.js +218 -11
  93. package/dist/src/integrations/claude-code/task-coordinator.js +2 -1
  94. package/dist/src/integrations/linear/webhook-retry.js +196 -0
  95. package/dist/src/integrations/linear/webhook-server.js +18 -22
  96. package/dist/src/integrations/mcp/handlers/cloud-sync-handlers.js +101 -0
  97. package/dist/src/integrations/mcp/handlers/index.js +27 -52
  98. package/dist/src/integrations/mcp/server.js +122 -335
  99. package/dist/src/integrations/mcp/tool-alias-registry.js +0 -73
  100. package/dist/src/integrations/mcp/tool-definitions.js +111 -510
  101. package/dist/src/mcp/stackmemory-mcp-server.js +404 -379
  102. package/dist/src/orchestrators/multimodal/determinism.js +2 -1
  103. package/dist/src/orchestrators/multimodal/harness.js +2 -1
  104. package/dist/src/skills/recursive-agent-orchestrator.js +2 -4
  105. package/dist/src/utils/process-cleanup.js +1 -7
  106. package/docs/README.md +42 -0
  107. package/docs/guides/README_INSTALL.md +208 -0
  108. package/package.json +18 -9
  109. package/scripts/claude-code-wrapper.sh +11 -0
  110. package/scripts/claude-sm-setup.sh +12 -1
  111. package/scripts/codex-wrapper.sh +11 -0
  112. package/scripts/git-hooks/branch-context-manager.sh +11 -0
  113. package/scripts/git-hooks/post-checkout-stackmemory.sh +11 -0
  114. package/scripts/git-hooks/post-commit-stackmemory.sh +11 -0
  115. package/scripts/git-hooks/pre-commit-stackmemory.sh +11 -0
  116. package/scripts/hooks/cleanup-shell.sh +12 -1
  117. package/scripts/hooks/task-complete.sh +12 -1
  118. package/scripts/install-code-execution-hooks.sh +12 -1
  119. package/scripts/install-sweep-hook.sh +12 -0
  120. package/scripts/install.sh +11 -0
  121. package/scripts/opencode-wrapper.sh +11 -0
  122. package/scripts/portal/cloud-init.yaml +69 -0
  123. package/scripts/portal/setup.sh +69 -0
  124. package/scripts/portal/stackmemory-portal.service +34 -0
  125. package/scripts/setup-claude-integration.sh +12 -1
  126. package/scripts/smoke-init-db.sh +23 -0
  127. package/scripts/stackmemory-daemon.sh +11 -0
  128. package/scripts/verify-dist.cjs +11 -4
  129. package/dist/src/cli/commands/ralph.js +0 -1053
  130. package/dist/src/hooks/diffmem-hooks.js +0 -376
  131. package/dist/src/integrations/diffmem/client.js +0 -208
  132. package/dist/src/integrations/diffmem/config.js +0 -14
  133. package/dist/src/integrations/greptile/client.js +0 -101
  134. package/dist/src/integrations/greptile/config.js +0 -14
  135. package/dist/src/integrations/greptile/index.js +0 -11
  136. package/dist/src/integrations/mcp/handlers/cross-search-handlers.js +0 -188
  137. package/dist/src/integrations/mcp/handlers/diffmem-handlers.js +0 -455
  138. package/dist/src/integrations/mcp/handlers/greptile-handlers.js +0 -456
  139. package/dist/src/integrations/mcp/handlers/provider-handlers.js +0 -227
  140. package/dist/src/integrations/ralph/bridge/ralph-stackmemory-bridge.js +0 -863
  141. package/dist/src/integrations/ralph/context/context-budget-manager.js +0 -308
  142. package/dist/src/integrations/ralph/context/stackmemory-context-loader.js +0 -354
  143. package/dist/src/integrations/ralph/index.js +0 -17
  144. package/dist/src/integrations/ralph/learning/pattern-learner.js +0 -416
  145. package/dist/src/integrations/ralph/lifecycle/iteration-lifecycle.js +0 -448
  146. package/dist/src/integrations/ralph/loopmax.js +0 -488
  147. package/dist/src/integrations/ralph/monitoring/swarm-dashboard.js +0 -293
  148. package/dist/src/integrations/ralph/monitoring/swarm-registry.js +0 -107
  149. package/dist/src/integrations/ralph/orchestration/multi-loop-orchestrator.js +0 -508
  150. package/dist/src/integrations/ralph/patterns/compounding-engineering-pattern.js +0 -407
  151. package/dist/src/integrations/ralph/patterns/extended-coherence-sessions.js +0 -495
  152. package/dist/src/integrations/ralph/patterns/oracle-worker-pattern.js +0 -387
  153. package/dist/src/integrations/ralph/performance/performance-optimizer.js +0 -357
  154. package/dist/src/integrations/ralph/recovery/crash-recovery.js +0 -461
  155. package/dist/src/integrations/ralph/state/state-reconciler.js +0 -420
  156. package/dist/src/integrations/ralph/swarm/git-workflow-manager.js +0 -444
  157. package/dist/src/integrations/ralph/swarm/swarm-coordinator.js +0 -1005
  158. package/dist/src/integrations/ralph/visualization/ralph-debugger.js +0 -635
  159. package/scripts/ralph-loop-implementation.js +0 -404
  160. /package/dist/src/{integrations/diffmem/types.js → core/storage/cloud-sync-types.js} +0 -0
  161. /package/dist/src/{integrations/greptile → features/operator}/types.js +0 -0
  162. /package/dist/src/{integrations/ralph/types.js → features/web/client/next-env.d.js} +0 -0
@@ -1,1005 +0,0 @@
1
- import { fileURLToPath as __fileURLToPath } from 'url';
2
- import { dirname as __pathDirname } from 'path';
3
- const __filename = __fileURLToPath(import.meta.url);
4
- const __dirname = __pathDirname(__filename);
5
- import { v4 as uuidv4 } from "uuid";
6
- import * as fs from "fs/promises";
7
- import * as path from "path";
8
- import { logger } from "../../../core/monitoring/logger.js";
9
- import { FrameManager } from "../../../core/context/index.js";
10
- import { sessionManager } from "../../../core/session/index.js";
11
- import { RalphStackMemoryBridge } from "../bridge/ralph-stackmemory-bridge.js";
12
- import { GitWorkflowManager } from "./git-workflow-manager.js";
13
- import { SwarmRegistry } from "../monitoring/swarm-registry.js";
14
- class SwarmCoordinationError extends Error {
15
- constructor(message, context) {
16
- super(message);
17
- this.context = context;
18
- this.name = "SwarmCoordinationError";
19
- }
20
- }
21
- class AgentExecutionError extends Error {
22
- constructor(message, agentId, taskId, context) {
23
- super(message);
24
- this.agentId = agentId;
25
- this.taskId = taskId;
26
- this.context = context;
27
- this.name = "AgentExecutionError";
28
- }
29
- }
30
- class TaskAllocationError extends Error {
31
- constructor(message, taskId, context) {
32
- super(message);
33
- this.taskId = taskId;
34
- this.context = context;
35
- this.name = "TaskAllocationError";
36
- }
37
- }
38
- class SwarmCoordinator {
39
- frameManager;
40
- activeAgents = /* @__PURE__ */ new Map();
41
- swarmState;
42
- config;
43
- coordinationTimer;
44
- plannerWakeupQueue = /* @__PURE__ */ new Map();
45
- gitWorkflowManager;
46
- registeredSwarmId;
47
- get swarmId() {
48
- return this.registeredSwarmId;
49
- }
50
- get agents() {
51
- return Array.from(this.activeAgents.values());
52
- }
53
- constructor(config) {
54
- this.config = {
55
- maxAgents: 10,
56
- coordinationInterval: 3e4,
57
- // 30 seconds
58
- driftDetectionThreshold: 5,
59
- // 5 failed iterations before considering drift
60
- freshStartInterval: 36e5,
61
- // 1 hour
62
- conflictResolutionStrategy: "expertise",
63
- enableDynamicPlanning: true,
64
- pathologicalBehaviorDetection: true,
65
- ...config
66
- };
67
- this.swarmState = {
68
- id: uuidv4(),
69
- status: "idle",
70
- startTime: Date.now(),
71
- activeTaskCount: 0,
72
- completedTaskCount: 0,
73
- coordination: {
74
- events: [],
75
- conflicts: [],
76
- resolutions: []
77
- },
78
- performance: {
79
- throughput: 0,
80
- efficiency: 0,
81
- coordination_overhead: 0
82
- }
83
- };
84
- this.gitWorkflowManager = new GitWorkflowManager({
85
- enableGitWorkflow: true,
86
- branchStrategy: "agent",
87
- autoCommit: true,
88
- commitFrequency: 5,
89
- mergStrategy: "squash"
90
- });
91
- logger.info("Swarm coordinator initialized", this.config);
92
- }
93
- async initialize() {
94
- try {
95
- await sessionManager.initialize();
96
- const session = await sessionManager.getOrCreateSession({});
97
- if (session.database) {
98
- this.frameManager = new FrameManager(
99
- session.database,
100
- session.projectId
101
- );
102
- }
103
- this.startCoordinationLoop();
104
- const registry = SwarmRegistry.getInstance();
105
- this.registeredSwarmId = registry.registerSwarm(
106
- this,
107
- `Swarm ${this.swarmState.id.substring(0, 8)}`
108
- );
109
- logger.info("Swarm coordinator initialized successfully");
110
- } catch (error) {
111
- logger.error("Failed to initialize swarm coordinator", error);
112
- throw error;
113
- }
114
- }
115
- /**
116
- * Launch a swarm of agents to work on a complex project
117
- */
118
- async launchSwarm(projectDescription, agents, _coordination) {
119
- logger.info("Launching swarm", {
120
- project: projectDescription.substring(0, 100),
121
- agentCount: agents.length
122
- });
123
- const swarmId = uuidv4();
124
- try {
125
- if (agents.length > this.config.maxAgents) {
126
- throw new Error(
127
- `Too many agents requested: ${agents.length} > ${this.config.maxAgents}`
128
- );
129
- }
130
- const swarmTasks = await this.decomposeProjectIntoSwarmTasks(projectDescription);
131
- const initializedAgents = await this.initializeSpecializedAgents(
132
- agents,
133
- swarmTasks
134
- );
135
- const allocation = await this.allocateTasksToAgents(
136
- swarmTasks,
137
- initializedAgents
138
- );
139
- this.swarmState = {
140
- ...this.swarmState,
141
- id: swarmId,
142
- status: "active",
143
- activeTaskCount: swarmTasks.length,
144
- project: projectDescription,
145
- agents: initializedAgents,
146
- tasks: swarmTasks,
147
- allocation
148
- };
149
- await this.executeSwarmTasks(allocation);
150
- logger.info("Swarm launched successfully", {
151
- swarmId,
152
- agentCount: initializedAgents.length
153
- });
154
- return swarmId;
155
- } catch (error) {
156
- logger.error("Failed to launch swarm", error);
157
- throw error;
158
- }
159
- }
160
- /**
161
- * Decompose project into tasks suitable for swarm execution
162
- */
163
- async decomposeProjectIntoSwarmTasks(projectDescription) {
164
- const tasks = [];
165
- const complexity = this.analyzeProjectComplexity(projectDescription);
166
- if (complexity.needsArchitecture) {
167
- tasks.push({
168
- id: uuidv4(),
169
- type: "architecture",
170
- title: "System Architecture Design",
171
- description: "Design overall system architecture and component relationships",
172
- priority: 1,
173
- estimatedEffort: "high",
174
- requiredRoles: ["architect", "system_designer"],
175
- dependencies: [],
176
- acceptanceCriteria: [
177
- "Architecture diagram created",
178
- "Component interfaces defined",
179
- "Data flow documented"
180
- ]
181
- });
182
- }
183
- const coreFeatures = this.extractCoreFeatures(projectDescription);
184
- for (const feature of coreFeatures) {
185
- tasks.push({
186
- id: uuidv4(),
187
- type: "implementation",
188
- title: `Implement ${feature.name}`,
189
- description: feature.description,
190
- priority: 2,
191
- estimatedEffort: feature.complexity,
192
- requiredRoles: ["developer", feature.specialization || "fullstack"],
193
- dependencies: complexity.needsArchitecture ? [tasks[0].id] : [],
194
- acceptanceCriteria: feature.criteria
195
- });
196
- }
197
- if (complexity.needsTesting) {
198
- tasks.push({
199
- id: uuidv4(),
200
- type: "testing",
201
- title: "Comprehensive Testing Suite",
202
- description: "Create unit, integration, and end-to-end tests",
203
- priority: 3,
204
- estimatedEffort: "medium",
205
- requiredRoles: ["qa_engineer", "test_automation"],
206
- dependencies: tasks.filter((t) => t.type === "implementation").map((t) => t.id),
207
- acceptanceCriteria: [
208
- "Unit tests achieve >90% coverage",
209
- "Integration tests pass",
210
- "Performance benchmarks met"
211
- ]
212
- });
213
- }
214
- if (complexity.needsDocumentation) {
215
- tasks.push({
216
- id: uuidv4(),
217
- type: "documentation",
218
- title: "Documentation and Examples",
219
- description: "Create user documentation, API docs, and usage examples",
220
- priority: 4,
221
- estimatedEffort: "low",
222
- requiredRoles: ["technical_writer", "developer"],
223
- dependencies: [],
224
- // Can run in parallel
225
- acceptanceCriteria: [
226
- "README with setup instructions",
227
- "API documentation complete",
228
- "Usage examples provided"
229
- ]
230
- });
231
- }
232
- return tasks;
233
- }
234
- /**
235
- * Initialize specialized agents with role-specific configurations
236
- */
237
- async initializeSpecializedAgents(specifications, _tasks) {
238
- const agents = [];
239
- for (const spec of specifications) {
240
- const agent = {
241
- id: uuidv4(),
242
- role: spec.role,
243
- specialization: spec,
244
- status: "initializing",
245
- capabilities: this.defineCapabilities(spec.role),
246
- workingDirectory: `.swarm/${spec.role}-${Date.now()}`,
247
- currentTask: null,
248
- performance: {
249
- tasksCompleted: 0,
250
- successRate: 1,
251
- averageTaskTime: 0,
252
- driftDetected: false,
253
- lastFreshStart: Date.now()
254
- },
255
- coordination: {
256
- communicationStyle: this.defineCommuncationStyle(spec.role),
257
- conflictResolution: spec.conflictResolution || "defer_to_expertise",
258
- collaborationPreferences: spec.collaborationPreferences || []
259
- }
260
- };
261
- await this.setupAgentEnvironment(agent);
262
- await this.configureAgentPrompts(agent);
263
- agents.push(agent);
264
- this.activeAgents.set(agent.id, agent);
265
- }
266
- logger.info(`Initialized ${agents.length} specialized agents`);
267
- return agents;
268
- }
269
- /**
270
- * Allocate tasks to agents based on specialization and workload
271
- */
272
- async allocateTasksToAgents(tasks, agents) {
273
- const allocation = {
274
- assignments: /* @__PURE__ */ new Map(),
275
- loadBalancing: "capability_based",
276
- conflictResolution: this.config.conflictResolutionStrategy
277
- };
278
- const sortedTasks = this.topologicalSort(tasks);
279
- for (const task of sortedTasks) {
280
- const suitableAgents = agents.filter(
281
- (agent) => task.requiredRoles.some((role) => this.agentCanHandle(agent, role))
282
- );
283
- if (suitableAgents.length === 0) {
284
- logger.warn(`No suitable agents found for task: ${task.title}`);
285
- continue;
286
- }
287
- const selectedAgent = this.selectOptimalAgent(suitableAgents, task);
288
- allocation.assignments.set(task.id, {
289
- agentId: selectedAgent.id,
290
- taskId: task.id,
291
- assignedAt: Date.now(),
292
- estimatedCompletion: Date.now() + this.estimateTaskDuration(task),
293
- coordination: {
294
- collaborators: this.findCollaborators(selectedAgent, task, agents),
295
- reviewers: this.findReviewers(selectedAgent, task, agents)
296
- }
297
- });
298
- selectedAgent.currentTask = task.id;
299
- }
300
- return allocation;
301
- }
302
- /**
303
- * Execute swarm tasks with coordination
304
- */
305
- async executeSwarmTasks(allocation) {
306
- const executionPromises = [];
307
- for (const [taskId, assignment] of allocation.assignments) {
308
- const agent = this.activeAgents.get(assignment.agentId);
309
- const task = this.swarmState.tasks?.find((t) => t.id === taskId);
310
- if (!agent || !task) continue;
311
- const executionPromise = this.executeAgentTask(agent, task, assignment);
312
- executionPromises.push(executionPromise);
313
- }
314
- await Promise.allSettled(executionPromises);
315
- }
316
- /**
317
- * Execute a single agent task with coordination
318
- */
319
- async executeAgentTask(agent, task, assignment) {
320
- logger.info(`Agent ${agent.role} starting task: ${task.title}`);
321
- try {
322
- agent.status = "active";
323
- await this.gitWorkflowManager.initializeAgentWorkflow(agent, task);
324
- const ralph = new RalphStackMemoryBridge({
325
- baseDir: path.join(agent.workingDirectory, task.id),
326
- maxIterations: this.calculateMaxIterations(task),
327
- useStackMemory: true
328
- });
329
- const contextualPrompt = await this.synthesizeContextualPrompt(
330
- agent,
331
- task
332
- );
333
- await ralph.initialize({
334
- task: contextualPrompt,
335
- criteria: task.acceptanceCriteria.join("\n")
336
- });
337
- this.setupAgentCoordination(agent, ralph, assignment);
338
- let iteration = 1;
339
- const maxIterations = this.calculateMaxIterations(task);
340
- while (iteration <= maxIterations) {
341
- try {
342
- const result = await ralph.runWorkerIteration();
343
- if (result.isComplete) {
344
- logger.info(`Task completed in ${iteration} iterations`);
345
- break;
346
- }
347
- iteration++;
348
- } catch (error) {
349
- logger.error(`Iteration ${iteration} failed:`, error);
350
- if (iteration >= maxIterations) {
351
- throw error;
352
- }
353
- iteration++;
354
- }
355
- }
356
- await this.gitWorkflowManager.commitAgentWork(agent, task);
357
- this.updateAgentPerformance(agent, true);
358
- await this.gitWorkflowManager.mergeAgentWork(agent, task);
359
- await this.notifyTaskCompletion(agent, task, true);
360
- agent.status = "idle";
361
- logger.info(`Agent ${agent.role} completed task: ${task.title}`);
362
- } catch (error) {
363
- logger.error(
364
- `Agent ${agent.role} failed task: ${task.title}`,
365
- error
366
- );
367
- this.updateAgentPerformance(agent, false);
368
- await this.handleTaskFailure(agent, task, error);
369
- agent.status = "error";
370
- }
371
- }
372
- /**
373
- * Synthesize contextual prompt incorporating swarm knowledge
374
- */
375
- async synthesizeContextualPrompt(agent, task) {
376
- const basePrompt = task.description;
377
- const roleSpecificInstructions = this.getRoleSpecificInstructions(
378
- agent.role
379
- );
380
- const swarmContext = await this.getSwarmContext(task);
381
- const coordinationInstructions = this.getCoordinationInstructions(agent);
382
- return `
383
- ${roleSpecificInstructions}
384
-
385
- TASK: ${basePrompt}
386
-
387
- SWARM CONTEXT:
388
- ${swarmContext}
389
-
390
- COORDINATION GUIDELINES:
391
- ${coordinationInstructions}
392
-
393
- Remember:
394
- - You are part of a swarm working on: ${this.swarmState.project}
395
- - Other agents are working on related tasks
396
- - Communicate findings through StackMemory shared context
397
- - Focus on your specialization while being aware of the bigger picture
398
- - Detect and avoid pathological behaviors (infinite loops, tunnel vision)
399
- - Request fresh starts if you detect drift in your approach
400
-
401
- ACCEPTANCE CRITERIA:
402
- ${task.acceptanceCriteria.map((c) => `- ${c}`).join("\n")}
403
- `;
404
- }
405
- /**
406
- * Start coordination monitoring loop
407
- */
408
- startCoordinationLoop() {
409
- this.coordinationTimer = setInterval(() => {
410
- this.performCoordinationCycle().catch((error) => {
411
- logger.error("Coordination cycle failed", error);
412
- });
413
- }, this.config.coordinationInterval);
414
- }
415
- /**
416
- * Perform coordination cycle
417
- */
418
- async performCoordinationCycle() {
419
- if (this.swarmState.status !== "active") return;
420
- logger.debug("Performing coordination cycle");
421
- if (this.config.pathologicalBehaviorDetection) {
422
- await this.detectPathologicalBehaviors();
423
- }
424
- if (this.config.enableDynamicPlanning) {
425
- await this.wakeUpPlanners();
426
- }
427
- await this.resolveActiveConflicts();
428
- await this.rebalanceWorkload();
429
- await this.triggerFreshStartsIfNeeded();
430
- this.updateSwarmMetrics();
431
- }
432
- /**
433
- * Detect pathological behaviors in agents
434
- */
435
- async detectPathologicalBehaviors() {
436
- for (const agent of this.activeAgents.values()) {
437
- if (agent.status !== "active") continue;
438
- if (agent.performance.driftDetected) {
439
- logger.warn(
440
- `Drift detected in agent ${agent.role}, triggering fresh start`
441
- );
442
- await this.triggerFreshStart(agent);
443
- continue;
444
- }
445
- if (await this.detectTunnelVision(agent)) {
446
- logger.warn(
447
- `Tunnel vision detected in agent ${agent.role}, providing alternative approach`
448
- );
449
- await this.provideAlternativeApproach(agent);
450
- }
451
- if (await this.detectExcessiveRuntime(agent)) {
452
- logger.warn(
453
- `Excessive runtime detected in agent ${agent.role}, requesting checkpoint`
454
- );
455
- await this.requestCheckpoint(agent);
456
- }
457
- }
458
- }
459
- /**
460
- * Wake up planners when their tasks complete
461
- */
462
- async wakeUpPlanners() {
463
- for (const [agentId, wakeupCallback] of this.plannerWakeupQueue) {
464
- const agent = this.activeAgents.get(agentId);
465
- if (!agent || agent.status !== "idle") continue;
466
- logger.info(`Waking up planner agent: ${agent.role}`);
467
- wakeupCallback();
468
- this.plannerWakeupQueue.delete(agentId);
469
- }
470
- }
471
- /**
472
- * Get status of a specific swarm
473
- */
474
- getSwarmStatus(swarmId) {
475
- const registry = SwarmRegistry.getInstance();
476
- const swarm = registry.getSwarm(swarmId);
477
- if (!swarm) {
478
- return null;
479
- }
480
- return {
481
- id: swarmId,
482
- state: swarm.status || "running",
483
- activeAgents: swarm.agents?.length || 0,
484
- startTime: swarm.startTime || Date.now(),
485
- agents: swarm.agents?.map((agent) => ({
486
- role: agent.role,
487
- status: agent.status || "active",
488
- task: agent.task || "Working"
489
- }))
490
- };
491
- }
492
- /**
493
- * Get all active swarms
494
- */
495
- getAllActiveSwarms() {
496
- const registry = SwarmRegistry.getInstance();
497
- const activeSwarms = registry.listActiveSwarms();
498
- return activeSwarms.map((swarm) => ({
499
- id: swarm.id,
500
- description: swarm.description,
501
- agentCount: swarm.agents?.length || 0,
502
- status: swarm.status || "running",
503
- startTime: swarm.startTime || Date.now()
504
- }));
505
- }
506
- /**
507
- * Stop a specific swarm gracefully
508
- */
509
- async stopSwarm(swarmId) {
510
- const targetId = swarmId || this.swarmId;
511
- if (!targetId) {
512
- throw new Error("No swarm ID provided");
513
- }
514
- logger.info("Stopping swarm", { swarmId: targetId });
515
- for (const agent of this.agents) {
516
- try {
517
- await this.stopAgent(agent);
518
- } catch (error) {
519
- logger.error("Failed to stop agent", {
520
- agent: agent.id,
521
- error: error.message
522
- });
523
- }
524
- }
525
- if (this.gitWorkflowManager) {
526
- try {
527
- await this.gitWorkflowManager.cleanup();
528
- } catch (error) {
529
- logger.error("Git cleanup failed", { error: error.message });
530
- }
531
- }
532
- const registry = SwarmRegistry.getInstance();
533
- registry.unregisterSwarm(targetId);
534
- logger.info("Swarm stopped", { swarmId: targetId });
535
- }
536
- /**
537
- * Force stop a swarm without saving state
538
- */
539
- async forceStopSwarm(swarmId) {
540
- logger.info("Force stopping swarm", { swarmId });
541
- const registry = SwarmRegistry.getInstance();
542
- registry.unregisterSwarm(swarmId);
543
- this.activeAgents.clear();
544
- logger.info("Swarm force stopped", { swarmId });
545
- }
546
- /**
547
- * Cleanup all resources
548
- */
549
- async cleanup() {
550
- logger.info("Cleaning up SwarmCoordinator resources");
551
- const activeSwarms = this.getAllActiveSwarms();
552
- for (const swarm of activeSwarms) {
553
- try {
554
- await this.stopSwarm(swarm.id);
555
- } catch (error) {
556
- logger.error("Failed to stop swarm during cleanup", {
557
- swarmId: swarm.id,
558
- error: error.message
559
- });
560
- }
561
- }
562
- const registry = SwarmRegistry.getInstance();
563
- registry.cleanup();
564
- this.activeAgents.clear();
565
- logger.info("SwarmCoordinator cleanup completed");
566
- }
567
- /**
568
- * Stop an individual agent
569
- */
570
- async stopAgent(agent) {
571
- logger.debug("Stopping agent", { agentId: agent.id, role: agent.role });
572
- agent.status = "stopped";
573
- if (agent.ralphBridge) {
574
- try {
575
- await agent.ralphBridge.cleanup();
576
- } catch (error) {
577
- logger.error("Failed to cleanup agent bridge", {
578
- error: error.message
579
- });
580
- }
581
- }
582
- }
583
- // Helper methods for role specialization and coordination
584
- defineCapabilities(role) {
585
- const capabilityMap = {
586
- architect: [
587
- "system_design",
588
- "component_modeling",
589
- "architecture_validation"
590
- ],
591
- planner: [
592
- "task_decomposition",
593
- "dependency_analysis",
594
- "resource_planning"
595
- ],
596
- developer: ["code_implementation", "debugging", "refactoring"],
597
- reviewer: [
598
- "code_review",
599
- "quality_assessment",
600
- "best_practice_enforcement"
601
- ],
602
- tester: ["test_design", "automation", "validation"],
603
- optimizer: [
604
- "performance_analysis",
605
- "resource_optimization",
606
- "bottleneck_identification"
607
- ],
608
- documenter: [
609
- "technical_writing",
610
- "api_documentation",
611
- "example_creation"
612
- ],
613
- coordinator: [
614
- "task_coordination",
615
- "conflict_resolution",
616
- "progress_tracking"
617
- ]
618
- };
619
- return capabilityMap[role] || [];
620
- }
621
- defineCommuncationStyle(role) {
622
- const styleMap = {
623
- architect: "high_level_design_focused",
624
- planner: "structured_and_methodical",
625
- developer: "implementation_focused",
626
- reviewer: "quality_focused_constructive",
627
- tester: "validation_focused",
628
- optimizer: "performance_metrics_focused",
629
- documenter: "clarity_focused",
630
- coordinator: "facilitative_and_diplomatic"
631
- };
632
- return styleMap[role] || "collaborative";
633
- }
634
- getRoleSpecificInstructions(role) {
635
- const instructionMap = {
636
- architect: `
637
- You are a SYSTEM ARCHITECT. Your role is to:
638
- - Design high-level system architecture
639
- - Define component interfaces and relationships
640
- - Ensure architectural consistency across the project
641
- - Think in terms of scalability, maintainability, and extensibility
642
- - Collaborate with developers to validate feasibility`,
643
- planner: `
644
- You are a PROJECT PLANNER. Your role is to:
645
- - Break down complex tasks into manageable steps
646
- - Identify dependencies and critical path
647
- - Coordinate with other agents on sequencing
648
- - Wake up when tasks complete to plan next steps
649
- - Adapt plans based on actual progress`,
650
- developer: `
651
- You are a SPECIALIZED DEVELOPER. Your role is to:
652
- - Implement features according to specifications
653
- - Write clean, maintainable code
654
- - Follow established patterns and conventions
655
- - Integrate with other components
656
- - Communicate implementation details clearly`,
657
- reviewer: `
658
- You are a CODE REVIEWER. Your role is to:
659
- - Review code for quality, correctness, and best practices
660
- - Provide constructive feedback
661
- - Ensure consistency with project standards
662
- - Identify potential issues before they become problems
663
- - Approve or request changes`,
664
- tester: `
665
- You are a QA ENGINEER. Your role is to:
666
- - Design comprehensive test strategies
667
- - Implement automated tests
668
- - Validate functionality and performance
669
- - Report bugs clearly and reproducibly
670
- - Ensure quality gates are met`,
671
- optimizer: `
672
- You are a PERFORMANCE OPTIMIZER. Your role is to:
673
- - Analyze system performance and identify bottlenecks
674
- - Implement optimizations
675
- - Monitor resource usage
676
- - Establish performance benchmarks
677
- - Ensure scalability requirements are met`,
678
- documenter: `
679
- You are a TECHNICAL WRITER. Your role is to:
680
- - Create clear, comprehensive documentation
681
- - Write API documentation and usage examples
682
- - Ensure documentation stays up-to-date
683
- - Focus on user experience and clarity
684
- - Collaborate with developers to understand features`,
685
- coordinator: `
686
- You are a PROJECT COORDINATOR. Your role is to:
687
- - Facilitate communication between agents
688
- - Resolve conflicts and blockers
689
- - Track overall project progress
690
- - Ensure no tasks fall through cracks
691
- - Maintain project timeline and quality`
692
- };
693
- return instructionMap[role] || "You are a specialized agent contributing to a larger project.";
694
- }
695
- // Additional helper methods would be implemented here...
696
- analyzeProjectComplexity(description) {
697
- return {
698
- needsArchitecture: description.length > 500 || description.includes("system") || description.includes("platform"),
699
- needsTesting: true,
700
- // Almost all projects need testing
701
- needsDocumentation: description.includes("API") || description.includes("library"),
702
- complexity: "medium"
703
- };
704
- }
705
- extractCoreFeatures(_description) {
706
- return [
707
- {
708
- name: "Core Feature",
709
- description: "Main functionality implementation",
710
- complexity: "medium",
711
- criteria: [
712
- "Feature works correctly",
713
- "Handles edge cases",
714
- "Follows coding standards"
715
- ]
716
- }
717
- ];
718
- }
719
- // Implement remaining helper methods...
720
- async setupAgentEnvironment(agent) {
721
- try {
722
- await fs.mkdir(agent.workingDirectory, { recursive: true });
723
- logger.debug(
724
- `Created working directory for agent ${agent.id}: ${agent.workingDirectory}`
725
- );
726
- } catch (error) {
727
- logger.warn(
728
- `Could not create working directory for agent ${agent.id}`,
729
- error
730
- );
731
- }
732
- }
733
- async configureAgentPrompts(agent) {
734
- logger.debug(`Configured prompts for agent ${agent.role}`);
735
- }
736
- topologicalSort(tasks) {
737
- const sorted = [];
738
- const visited = /* @__PURE__ */ new Set();
739
- const visiting = /* @__PURE__ */ new Set();
740
- const visit = (task) => {
741
- if (visited.has(task.id)) return;
742
- if (visiting.has(task.id)) {
743
- logger.warn(`Circular dependency detected for task: ${task.id}`);
744
- return;
745
- }
746
- visiting.add(task.id);
747
- for (const depId of task.dependencies) {
748
- const depTask = tasks.find((t) => t.id === depId);
749
- if (depTask) visit(depTask);
750
- }
751
- visiting.delete(task.id);
752
- visited.add(task.id);
753
- sorted.push(task);
754
- };
755
- tasks.forEach(visit);
756
- return sorted;
757
- }
758
- agentCanHandle(agent, role) {
759
- return agent.role === role || agent.capabilities.includes(role);
760
- }
761
- selectOptimalAgent(agents, _task) {
762
- return agents.reduce((best, current) => {
763
- const bestLoad = best.currentTask ? 1 : 0;
764
- const currentLoad = current.currentTask ? 1 : 0;
765
- return currentLoad < bestLoad ? current : best;
766
- });
767
- }
768
- estimateTaskDuration(task) {
769
- const durations = {
770
- low: 6e4,
771
- // 1 minute
772
- medium: 3e5,
773
- // 5 minutes
774
- high: 9e5
775
- // 15 minutes
776
- };
777
- return durations[task.estimatedEffort] || 3e5;
778
- }
779
- findCollaborators(agent, task, agents) {
780
- return agents.filter((a) => a.id !== agent.id && a.currentTask).map((a) => a.id).slice(0, 2);
781
- }
782
- findReviewers(agent, task, agents) {
783
- return agents.filter((a) => a.role === "reviewer" && a.id !== agent.id).map((a) => a.id);
784
- }
785
- calculateMaxIterations(task) {
786
- const iterations = {
787
- low: 5,
788
- medium: 10,
789
- high: 20
790
- };
791
- return iterations[task.estimatedEffort] || 10;
792
- }
793
- async getSwarmContext(_task) {
794
- const relatedTasks = Array.from(this.activeAgents.values()).filter((a) => a.currentTask).map((a) => `- Agent ${a.role} is working on task ${a.currentTask}`).join("\n");
795
- return relatedTasks || "No other agents currently active";
796
- }
797
- getCoordinationInstructions(_agent) {
798
- return `
799
- - Save progress to shared context regularly
800
- - Check for updates from collaborators
801
- - Request help if blocked for more than 2 iterations
802
- - Report completion immediately`;
803
- }
804
- setupAgentCoordination(agent, _ralph, _assignment) {
805
- logger.debug(`Setting up coordination for agent ${agent.id}`);
806
- }
807
- updateAgentPerformance(agent, success) {
808
- agent.performance.tasksCompleted++;
809
- if (!success) {
810
- agent.performance.successRate = agent.performance.successRate * (agent.performance.tasksCompleted - 1) / agent.performance.tasksCompleted;
811
- }
812
- }
813
- async notifyTaskCompletion(agent, task, success) {
814
- const event = {
815
- type: "task_completion",
816
- agentId: agent.id,
817
- timestamp: Date.now(),
818
- data: {
819
- taskId: task.id,
820
- success,
821
- agent: agent.role
822
- }
823
- };
824
- this.swarmState.coordination?.events.push(event);
825
- logger.info(
826
- `Task ${task.id} completed by agent ${agent.role}: ${success ? "SUCCESS" : "FAILED"}`
827
- );
828
- }
829
- async handleTaskFailure(agent, task, error) {
830
- logger.error(`Agent ${agent.role} failed task ${task.id}`, error);
831
- if (this.swarmState.coordination) {
832
- this.swarmState.coordination.conflicts.push({
833
- type: "task_failure",
834
- agents: [agent.id],
835
- timestamp: Date.now(),
836
- description: error.message
837
- });
838
- }
839
- }
840
- async detectTunnelVision(_agent) {
841
- return false;
842
- }
843
- async provideAlternativeApproach(agent) {
844
- logger.info(`Providing alternative approach to agent ${agent.role}`);
845
- }
846
- async detectExcessiveRuntime(agent) {
847
- if (!agent.performance.lastFreshStart) return false;
848
- return Date.now() - agent.performance.lastFreshStart > 36e5;
849
- }
850
- async requestCheckpoint(agent) {
851
- logger.info(`Requesting checkpoint from agent ${agent.role}`);
852
- }
853
- async triggerFreshStart(agent) {
854
- logger.info(`Triggering fresh start for agent ${agent.role}`);
855
- agent.performance.lastFreshStart = Date.now();
856
- agent.performance.driftDetected = false;
857
- }
858
- async resolveActiveConflicts() {
859
- if (this.swarmState.coordination?.conflicts.length) {
860
- logger.debug(
861
- `Resolving ${this.swarmState.coordination.conflicts.length} conflicts`
862
- );
863
- }
864
- }
865
- async rebalanceWorkload() {
866
- const activeAgents = Array.from(this.activeAgents.values()).filter(
867
- (a) => a.status === "active"
868
- );
869
- if (activeAgents.length > 0) {
870
- logger.debug(
871
- `Rebalancing workload among ${activeAgents.length} active agents`
872
- );
873
- }
874
- }
875
- async triggerFreshStartsIfNeeded() {
876
- for (const agent of this.activeAgents.values()) {
877
- if (agent.performance.driftDetected) {
878
- await this.triggerFreshStart(agent);
879
- }
880
- }
881
- }
882
- updateSwarmMetrics() {
883
- if (!this.swarmState.performance) return;
884
- const activeCount = Array.from(this.activeAgents.values()).filter(
885
- (a) => a.status === "active"
886
- ).length;
887
- this.swarmState.performance.throughput = this.swarmState.completedTaskCount / ((Date.now() - this.swarmState.startTime) / 1e3);
888
- this.swarmState.performance.efficiency = activeCount > 0 ? this.swarmState.completedTaskCount / activeCount : 0;
889
- }
890
- /**
891
- * Cleanup completed swarms and their resources
892
- */
893
- async cleanupCompletedSwarms() {
894
- if (this.swarmState.status !== "completed") {
895
- return;
896
- }
897
- try {
898
- logger.info("Cleaning up completed swarm resources");
899
- if (this.coordinationTimer) {
900
- clearInterval(this.coordinationTimer);
901
- this.coordinationTimer = void 0;
902
- }
903
- for (const agent of this.activeAgents.values()) {
904
- try {
905
- await fs.rmdir(agent.workingDirectory, { recursive: true });
906
- logger.debug(`Cleaned up working directory for agent ${agent.id}`);
907
- } catch (error) {
908
- logger.warn(
909
- `Could not clean up directory for agent ${agent.id}`,
910
- error
911
- );
912
- }
913
- }
914
- await this.gitWorkflowManager.coordinateMerges(
915
- Array.from(this.activeAgents.values())
916
- );
917
- this.activeAgents.clear();
918
- this.swarmState = {
919
- id: uuidv4(),
920
- status: "idle",
921
- startTime: Date.now(),
922
- activeTaskCount: 0,
923
- completedTaskCount: 0,
924
- coordination: {
925
- events: [],
926
- conflicts: [],
927
- resolutions: []
928
- },
929
- performance: {
930
- throughput: 0,
931
- efficiency: 0,
932
- coordination_overhead: 0
933
- }
934
- };
935
- logger.info("Swarm cleanup completed successfully");
936
- } catch (error) {
937
- logger.error("Failed to cleanup completed swarm", error);
938
- throw new SwarmCoordinationError("Cleanup failed", {
939
- swarmId: this.swarmState.id,
940
- error
941
- });
942
- }
943
- }
944
- /**
945
- * Force cleanup of a swarm (for emergency situations)
946
- */
947
- async forceCleanup() {
948
- logger.warn("Force cleanup initiated");
949
- try {
950
- if (this.coordinationTimer) {
951
- clearInterval(this.coordinationTimer);
952
- this.coordinationTimer = void 0;
953
- }
954
- for (const agent of this.activeAgents.values()) {
955
- agent.status = "stopped";
956
- }
957
- this.swarmState.status = "stopped";
958
- await this.cleanupCompletedSwarms();
959
- } catch (error) {
960
- logger.error("Force cleanup failed", error);
961
- }
962
- }
963
- /**
964
- * Get swarm resource usage and cleanup recommendations
965
- */
966
- getResourceUsage() {
967
- const workingDirs = Array.from(this.activeAgents.values()).map(
968
- (a) => a.workingDirectory
969
- );
970
- const memoryEstimate = this.activeAgents.size * 50;
971
- const isStale = Date.now() - this.swarmState.startTime > 36e5;
972
- const hasCompletedTasks = this.swarmState.completedTaskCount > 0 && this.swarmState.activeTaskCount === 0;
973
- const recommendations = [];
974
- let cleanupRecommended = false;
975
- if (isStale) {
976
- recommendations.push(
977
- "Swarm has been running for over 1 hour - consider cleanup"
978
- );
979
- cleanupRecommended = true;
980
- }
981
- if (hasCompletedTasks) {
982
- recommendations.push("All tasks completed - cleanup is recommended");
983
- cleanupRecommended = true;
984
- }
985
- if (this.activeAgents.size > 5) {
986
- recommendations.push("High agent count - monitor resource usage");
987
- }
988
- return {
989
- activeAgents: this.activeAgents.size,
990
- workingDirectories: workingDirs,
991
- memoryEstimate,
992
- cleanupRecommended,
993
- recommendations
994
- };
995
- }
996
- [Symbol.toStringTag] = "SwarmCoordinator";
997
- }
998
- const swarmCoordinator = new SwarmCoordinator();
999
- export {
1000
- AgentExecutionError,
1001
- SwarmCoordinationError,
1002
- SwarmCoordinator,
1003
- TaskAllocationError,
1004
- swarmCoordinator
1005
- };