snow-flow 2.0.2 → 2.0.4

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 (173) hide show
  1. package/{.claude/mcp-config.json → .mcp.json} +13 -12
  2. package/.releaserc.json +47 -0
  3. package/README.md +48 -1
  4. package/package.json +1 -1
  5. package/.claude/claude-settings.json +0 -15
  6. package/.claude/commands/analysis/README.md +0 -9
  7. package/.claude/commands/automation/README.md +0 -9
  8. package/.claude/commands/github/README.md +0 -11
  9. package/.claude/commands/helpers/standard-checkpoint-hooks.sh +0 -179
  10. package/.claude/commands/hooks/README.md +0 -11
  11. package/.claude/commands/monitoring/README.md +0 -9
  12. package/.claude/commands/optimization/README.md +0 -9
  13. package/.claude/commands/training/README.md +0 -9
  14. package/.claude/commands/workflows/README.md +0 -9
  15. package/.claude/config.json +0 -36
  16. package/.claude/helpers/github-setup.sh +0 -28
  17. package/.claude/helpers/quick-start.sh +0 -19
  18. package/.claude/helpers/setup-mcp.sh +0 -18
  19. package/.claude/settings.json +0 -114
  20. package/.claude/settings.local.json +0 -33
  21. package/.claude-flow/metrics/agent-metrics.json +0 -1
  22. package/.claude-flow/metrics/performance.json +0 -9
  23. package/.claude-flow/metrics/system-metrics.json +0 -15986
  24. package/.claude-flow/metrics/task-metrics.json +0 -10
  25. package/.roo/README.md +0 -402
  26. package/.roo/mcp-list.txt +0 -257
  27. package/.roo/mcp.json +0 -32
  28. package/.roo/workflows/basic-tdd.json +0 -32
  29. package/.roomodes +0 -201
  30. package/CLAUDE.md +0 -393
  31. package/bin/snow-flow.js +0 -3
  32. package/dist/cli.js.bak +0 -2052
  33. package/dist/config/snow-flow-config.d.ts +0 -1492
  34. package/dist/config/snow-flow-config.js +0 -938
  35. package/scripts/create-env.js +0 -91
  36. package/scripts/postinstall.js +0 -30
  37. package/scripts/register-mcp-servers.js +0 -210
  38. package/scripts/reset-mcp-servers.js +0 -246
  39. package/scripts/setup-mcp.js +0 -106
  40. package/scripts/update-version.js +0 -31
  41. package/src/agents/README.md +0 -192
  42. package/src/agents/base-agent.ts +0 -251
  43. package/src/agents/coordinator.ts +0 -971
  44. package/src/agents/index.ts +0 -18
  45. package/src/agents/queen-403-handler.ts +0 -230
  46. package/src/agents/queen-agent.ts +0 -1399
  47. package/src/agents/script-writer-agent.ts +0 -769
  48. package/src/agents/security-agent.ts +0 -726
  49. package/src/agents/widget-creator-agent.ts +0 -568
  50. package/src/api/error-handling.ts +0 -1758
  51. package/src/api/natural-language-mapper.ts +0 -630
  52. package/src/api/performance-optimizer.ts +0 -891
  53. package/src/api/transaction-manager.ts +0 -754
  54. package/src/cli/deploy-artifact.ts +0 -304
  55. package/src/cli/snow-flow-cli-integration.ts +0 -434
  56. package/src/cli.ts +0 -4455
  57. package/src/cli.ts.bak +0 -5616
  58. package/src/compliance/advanced-compliance-system.ts +0 -1268
  59. package/src/compliance/index.ts +0 -19
  60. package/src/config/snow-flow-config.ts +0 -1019
  61. package/src/documentation/index.ts +0 -16
  62. package/src/documentation/self-documenting-system.ts +0 -1421
  63. package/src/dynamic-version.ts +0 -44
  64. package/src/healing/index.ts +0 -20
  65. package/src/healing/self-healing-system.ts +0 -1435
  66. package/src/health/README.md +0 -161
  67. package/src/health/system-health.ts +0 -995
  68. package/src/index.ts +0 -60
  69. package/src/intelligence/acl-analyzer.ts +0 -377
  70. package/src/intelligence/auto-resolution-engine.ts +0 -643
  71. package/src/intelligence/gap-analysis-engine.ts +0 -488
  72. package/src/intelligence/manual-instructions-generator.ts +0 -744
  73. package/src/intelligence/mcp-coverage-analyzer.ts +0 -708
  74. package/src/intelligence/multi-pass-requirements-analyzer.ts +0 -603
  75. package/src/intelligence/performance-recommendations-engine.ts +0 -1223
  76. package/src/intelligence/requirements-analyzer.ts +0 -1148
  77. package/src/intelligence/task-analyzer.ts +0 -628
  78. package/src/managers/scope-manager.ts +0 -555
  79. package/src/mcp/advanced/servicenow-advanced-features-mcp.ts +0 -16110
  80. package/src/mcp/base-mcp-server.ts +0 -660
  81. package/src/mcp/http-transport-wrapper.ts +0 -426
  82. package/src/mcp/service-discovery-client.ts +0 -312
  83. package/src/mcp/servicenow-automation-mcp-refactored.ts +0 -678
  84. package/src/mcp/servicenow-automation-mcp.ts +0 -838
  85. package/src/mcp/servicenow-deployment-mcp-refactored.ts +0 -1292
  86. package/src/mcp/servicenow-deployment-mcp.ts +0 -7244
  87. package/src/mcp/servicenow-graph-memory-mcp-refactored.ts +0 -721
  88. package/src/mcp/servicenow-graph-memory-mcp.ts +0 -832
  89. package/src/mcp/servicenow-integration-mcp-refactored.ts +0 -655
  90. package/src/mcp/servicenow-integration-mcp.ts +0 -819
  91. package/src/mcp/servicenow-intelligent-mcp-refactored.ts +0 -977
  92. package/src/mcp/servicenow-intelligent-mcp.ts +0 -4638
  93. package/src/mcp/servicenow-mcp-server.ts +0 -728
  94. package/src/mcp/servicenow-memory-mcp.ts +0 -474
  95. package/src/mcp/servicenow-operations-mcp-refactored.ts +0 -1995
  96. package/src/mcp/servicenow-operations-mcp.ts +0 -3384
  97. package/src/mcp/servicenow-platform-development-mcp-refactored.ts +0 -611
  98. package/src/mcp/servicenow-platform-development-mcp.ts +0 -970
  99. package/src/mcp/servicenow-progressive-indexer.ts +0 -370
  100. package/src/mcp/servicenow-reporting-analytics-mcp-refactored.ts +0 -695
  101. package/src/mcp/servicenow-reporting-analytics-mcp.ts +0 -1123
  102. package/src/mcp/servicenow-security-compliance-mcp-refactored.ts +0 -642
  103. package/src/mcp/servicenow-security-compliance-mcp.ts +0 -1157
  104. package/src/mcp/servicenow-update-set-mcp-refactored.ts +0 -751
  105. package/src/mcp/servicenow-update-set-mcp.ts +0 -811
  106. package/src/mcp/shared/agent-context-provider.ts +0 -365
  107. package/src/mcp/shared/base-mcp-server.ts +0 -2463
  108. package/src/mcp/shared/mcp-memory-manager.ts +0 -540
  109. package/src/mcp/shared/mcp-resource-manager.ts +0 -367
  110. package/src/mcp/snow-flow-mcp.ts +0 -911
  111. package/src/mcp/start-all-mcp-servers.ts +0 -102
  112. package/src/mcp/start-servicenow-mcp.ts +0 -67
  113. package/src/monitoring/enhanced-monitoring-system.ts +0 -1345
  114. package/src/monitoring/performance-tracker.ts +0 -777
  115. package/src/optimization/cost-optimization-engine.ts +0 -1125
  116. package/src/optimization/index.ts +0 -10
  117. package/src/queen/README.md +0 -403
  118. package/src/queen/agent-factory.ts +0 -574
  119. package/src/queen/index.ts +0 -94
  120. package/src/queen/mcp-execution-bridge.ts +0 -681
  121. package/src/queen/neural-learning.ts +0 -319
  122. package/src/queen/parallel-agent-engine.ts +0 -848
  123. package/src/queen/queen-memory-system.ts +0 -490
  124. package/src/queen/queen-memory.ts +0 -456
  125. package/src/queen/servicenow-queen.ts +0 -1029
  126. package/src/queen/types.ts +0 -87
  127. package/src/rollback/smart-rollback-system.ts +0 -866
  128. package/src/schemas/deployment.schema.json +0 -58
  129. package/src/schemas/flow.schema.json +0 -79
  130. package/src/schemas/widget.schema.json +0 -72
  131. package/src/snow-flow-system.ts +0 -541
  132. package/src/sparc/sparc-help.ts +0 -49
  133. package/src/sparc/team-sparc.ts +0 -88
  134. package/src/strategies/global-scope-strategy.ts +0 -736
  135. package/src/templates/base/application.template.json +0 -45
  136. package/src/templates/base/business_rule.template.json +0 -33
  137. package/src/templates/base/script_include.template.json +0 -18
  138. package/src/templates/base/table.template.json +0 -64
  139. package/src/templates/base/widget.template.json +0 -25
  140. package/src/templates/patterns/composite.incident-management.template.json +0 -140
  141. package/src/templates/patterns/widget.dashboard.template.json +0 -238
  142. package/src/templates/patterns/widget.datatable.template.json +0 -292
  143. package/src/testing/integration-test-suite.ts +0 -1276
  144. package/src/types/index.ts +0 -183
  145. package/src/types/neo4j-driver.d.ts +0 -23
  146. package/src/types/servicenow.types.ts +0 -307
  147. package/src/types/snow-flow.types.ts +0 -186
  148. package/src/types/todo.types.ts +0 -70
  149. package/src/utils/action-type-cache.ts +0 -286
  150. package/src/utils/agent-detector.ts +0 -573
  151. package/src/utils/artifact-tracker.ts +0 -379
  152. package/src/utils/dependency-detector.ts +0 -233
  153. package/src/utils/deployment-metadata-handler.ts +0 -518
  154. package/src/utils/error-recovery.ts +0 -680
  155. package/src/utils/logger.ts +0 -60
  156. package/src/utils/mcp-auth-middleware.ts +0 -262
  157. package/src/utils/mcp-config-manager.ts +0 -270
  158. package/src/utils/mcp-server-manager.ts +0 -446
  159. package/src/utils/mcp-tool-registry.ts +0 -298
  160. package/src/utils/migrate-snow-flow.ts +0 -98
  161. package/src/utils/oauth-html-templates.ts +0 -188
  162. package/src/utils/scope-utils.ts +0 -443
  163. package/src/utils/servicenow-client.ts +0 -3321
  164. package/src/utils/servicenow-id-generator.ts +0 -181
  165. package/src/utils/snow-memory-manager.ts +0 -605
  166. package/src/utils/snow-oauth.ts +0 -797
  167. package/src/utils/template-engine.ts +0 -463
  168. package/src/utils/theme-manager.ts +0 -295
  169. package/src/utils/unified-auth-store.ts +0 -222
  170. package/src/utils/update-set-importer.ts +0 -422
  171. package/src/utils/update-set-xml-packager.ts +0 -371
  172. package/src/utils/widget-template-generator.ts +0 -1744
  173. package/src/version.ts +0 -1950
@@ -1,971 +0,0 @@
1
- /**
2
- * Agent Coordination System
3
- * Manages inter-agent communication, task dependencies, and handoffs
4
- * Integrates with SQLite memory for persistent coordination state
5
- */
6
-
7
- import { EventEmitter } from 'eventemitter3';
8
- import { Agent, AgentMessage } from '../queen/types';
9
- import { QueenMemorySystem } from '../queen/queen-memory';
10
- import * as crypto from 'crypto';
11
-
12
- export interface CoordinationContext {
13
- sessionId: string;
14
- objectiveId: string;
15
- agents: Map<string, Agent>;
16
- dependencies: Map<string, string[]>;
17
- handoffs: Map<string, HandoffRequest>;
18
- blockages: Map<string, BlockageInfo>;
19
- }
20
-
21
- export interface HandoffRequest {
22
- id: string;
23
- fromAgent: string;
24
- toAgent: string;
25
- artifactType: string;
26
- artifactData: any;
27
- status: 'pending' | 'accepted' | 'completed' | 'failed';
28
- createdAt: Date;
29
- completedAt?: Date;
30
- }
31
-
32
- export interface BlockageInfo {
33
- agentId: string;
34
- reason: string;
35
- blockedTasks: string[];
36
- dependencies: string[];
37
- attemptedResolutions: string[];
38
- createdAt: Date;
39
- }
40
-
41
- export interface CoordinationStrategy {
42
- type: 'sequential' | 'parallel' | 'adaptive';
43
- rules: CoordinationRule[];
44
- fallbackStrategy?: string;
45
- }
46
-
47
- export interface CoordinationRule {
48
- condition: string;
49
- action: string;
50
- priority: number;
51
- }
52
-
53
- export interface RecoveryStrategy {
54
- errorType: string;
55
- recoveryActions: RecoveryAction[];
56
- maxRetries: number;
57
- }
58
-
59
- export interface RecoveryAction {
60
- type: 'retry' | 'fallback' | 'reassign' | 'escalate';
61
- config: Record<string, any>;
62
- }
63
-
64
- export class AgentCoordinator extends EventEmitter {
65
- private memory: QueenMemorySystem;
66
- private contexts: Map<string, CoordinationContext>;
67
- private strategies: Map<string, CoordinationStrategy>;
68
- private recoveryStrategies: Map<string, RecoveryStrategy>;
69
- private messageQueue: Map<string, AgentMessage[]>;
70
-
71
- constructor(memory: QueenMemorySystem) {
72
- super();
73
- this.memory = memory;
74
- this.contexts = new Map();
75
- this.strategies = new Map();
76
- this.recoveryStrategies = new Map();
77
- this.messageQueue = new Map();
78
-
79
- this.initializeDefaultStrategies();
80
- this.setupMemorySync();
81
- }
82
-
83
- /**
84
- * Create a new coordination context for an objective
85
- */
86
- async createContext(sessionId: string, objectiveId: string): Promise<CoordinationContext> {
87
- const context: CoordinationContext = {
88
- sessionId,
89
- objectiveId,
90
- agents: new Map(),
91
- dependencies: new Map(),
92
- handoffs: new Map(),
93
- blockages: new Map()
94
- };
95
-
96
- this.contexts.set(objectiveId, context);
97
-
98
- // Store context in memory for persistence
99
- await this.memory.store(`coordination_context_${objectiveId}`, {
100
- sessionId,
101
- objectiveId,
102
- createdAt: new Date().toISOString()
103
- });
104
-
105
- this.emit('context:created', { sessionId, objectiveId });
106
-
107
- return context;
108
- }
109
-
110
- /**
111
- * Register an agent with the coordinator
112
- */
113
- async registerAgent(agent: Agent, objectiveId?: string): Promise<void> {
114
- // Find or create context
115
- let context: CoordinationContext | undefined;
116
- if (objectiveId) {
117
- context = this.contexts.get(objectiveId);
118
- } else {
119
- // Find context that needs this agent type
120
- for (const ctx of this.contexts.values()) {
121
- if (!Array.from(ctx.agents.values()).some(a => a.type === agent.type)) {
122
- context = ctx;
123
- break;
124
- }
125
- }
126
- }
127
-
128
- if (!context) {
129
- throw new Error('No suitable coordination context found for agent');
130
- }
131
-
132
- context.agents.set(agent.id, agent);
133
-
134
- // Store agent registration in memory
135
- await this.memory.store(`agent_registration_${agent.id}`, {
136
- agentId: agent.id,
137
- agentType: agent.type,
138
- objectiveId: context.objectiveId,
139
- sessionId: context.sessionId,
140
- registeredAt: new Date().toISOString()
141
- });
142
-
143
- // Initialize message queue for agent
144
- this.messageQueue.set(agent.id, []);
145
-
146
- this.emit('agent:registered', { agent, objectiveId: context.objectiveId });
147
- }
148
-
149
- /**
150
- * Manage task dependencies between agents
151
- */
152
- async manageDependencies(
153
- objectiveId: string,
154
- taskId: string,
155
- dependencies: string[]
156
- ): Promise<void> {
157
- const context = this.contexts.get(objectiveId);
158
- if (!context) {
159
- throw new Error(`No context found for objective: ${objectiveId}`);
160
- }
161
-
162
- context.dependencies.set(taskId, dependencies);
163
-
164
- // Store dependencies in memory
165
- await this.memory.store(`dependencies_${taskId}`, {
166
- taskId,
167
- dependencies,
168
- objectiveId,
169
- createdAt: new Date().toISOString()
170
- });
171
-
172
- // Check if any dependencies are already satisfied
173
- await this.checkDependencySatisfaction(context, taskId);
174
- }
175
-
176
- /**
177
- * Coordinate handoff between agents
178
- */
179
- async coordinateHandoff(
180
- fromAgentId: string,
181
- toAgentId: string,
182
- artifactType: string,
183
- artifactData: any
184
- ): Promise<HandoffRequest> {
185
- const handoffId = this.generateId('handoff');
186
-
187
- const handoff: HandoffRequest = {
188
- id: handoffId,
189
- fromAgent: fromAgentId,
190
- toAgent: toAgentId,
191
- artifactType,
192
- artifactData,
193
- status: 'pending',
194
- createdAt: new Date()
195
- };
196
-
197
- // Find context containing these agents
198
- let context: CoordinationContext | undefined;
199
- for (const ctx of this.contexts.values()) {
200
- if (ctx.agents.has(fromAgentId) && ctx.agents.has(toAgentId)) {
201
- context = ctx;
202
- break;
203
- }
204
- }
205
-
206
- if (!context) {
207
- throw new Error('No coordination context found for agents');
208
- }
209
-
210
- context.handoffs.set(handoffId, handoff);
211
-
212
- // Store handoff in memory
213
- await this.memory.store(`handoff_${handoffId}`, {
214
- handoff,
215
- objectiveId: context.objectiveId,
216
- timestamp: new Date().toISOString()
217
- });
218
-
219
- // Notify receiving agent
220
- await this.sendMessage(fromAgentId, toAgentId, 'coordination', {
221
- type: 'handoff_request',
222
- handoffId,
223
- artifactType,
224
- artifactData
225
- });
226
-
227
- this.emit('agent:handoff', {
228
- handoffId,
229
- fromAgent: fromAgentId,
230
- toAgent: toAgentId,
231
- artifactType,
232
- objectiveId: context.objectiveId
233
- });
234
-
235
- return handoff;
236
- }
237
-
238
- /**
239
- * Handle agent blockage with recovery strategies
240
- */
241
- async handleBlockage(
242
- agentId: string,
243
- reason: string,
244
- blockedTasks: string[]
245
- ): Promise<void> {
246
- // Find context containing this agent
247
- let context: CoordinationContext | undefined;
248
- for (const ctx of this.contexts.values()) {
249
- if (ctx.agents.has(agentId)) {
250
- context = ctx;
251
- break;
252
- }
253
- }
254
-
255
- if (!context) {
256
- throw new Error(`No context found for agent: ${agentId}`);
257
- }
258
-
259
- const blockage: BlockageInfo = {
260
- agentId,
261
- reason,
262
- blockedTasks,
263
- dependencies: this.findBlockedDependencies(context, blockedTasks),
264
- attemptedResolutions: [],
265
- createdAt: new Date()
266
- };
267
-
268
- context.blockages.set(agentId, blockage);
269
-
270
- // Store blockage in memory
271
- await this.memory.store(`blockage_${agentId}_${Date.now()}`, {
272
- blockage,
273
- objectiveId: context.objectiveId,
274
- timestamp: new Date().toISOString()
275
- });
276
-
277
- // Attempt recovery
278
- await this.attemptRecovery(context, blockage);
279
-
280
- this.emit('agent:blocked', {
281
- agentId,
282
- reason,
283
- blockedTasks,
284
- objectiveId: context.objectiveId
285
- });
286
- }
287
-
288
- /**
289
- * Send message between agents
290
- */
291
- async sendMessage(
292
- fromAgentId: string,
293
- toAgentId: string,
294
- messageType: AgentMessage['type'],
295
- content: any
296
- ): Promise<void> {
297
- const message: AgentMessage = {
298
- from: fromAgentId,
299
- to: toAgentId,
300
- type: messageType,
301
- content,
302
- timestamp: new Date()
303
- };
304
-
305
- // Add to message queue
306
- const queue = this.messageQueue.get(toAgentId) || [];
307
- queue.push(message);
308
- this.messageQueue.set(toAgentId, queue);
309
-
310
- // Store message in memory for audit
311
- await this.memory.store(`message_${Date.now()}_${crypto.randomBytes(4).toString('hex')}`, {
312
- message,
313
- delivered: false,
314
- timestamp: new Date().toISOString()
315
- });
316
-
317
- // Process message immediately if agent is listening
318
- await this.processAgentMessages(toAgentId);
319
-
320
- this.emit('message:sent', message);
321
- }
322
-
323
- /**
324
- * Get pending messages for an agent
325
- */
326
- async getAgentMessages(agentId: string): Promise<AgentMessage[]> {
327
- const messages = this.messageQueue.get(agentId) || [];
328
-
329
- // Clear processed messages
330
- this.messageQueue.set(agentId, []);
331
-
332
- return messages;
333
- }
334
-
335
- /**
336
- * Update handoff status
337
- */
338
- async updateHandoffStatus(
339
- handoffId: string,
340
- status: HandoffRequest['status']
341
- ): Promise<void> {
342
- let handoff: HandoffRequest | undefined;
343
- let context: CoordinationContext | undefined;
344
-
345
- // Find handoff in contexts
346
- for (const ctx of this.contexts.values()) {
347
- if (ctx.handoffs.has(handoffId)) {
348
- handoff = ctx.handoffs.get(handoffId);
349
- context = ctx;
350
- break;
351
- }
352
- }
353
-
354
- if (!handoff || !context) {
355
- throw new Error(`Handoff not found: ${handoffId}`);
356
- }
357
-
358
- handoff.status = status;
359
- if (status === 'completed' || status === 'failed') {
360
- handoff.completedAt = new Date();
361
- }
362
-
363
- // Update memory
364
- await this.memory.store(`handoff_status_${handoffId}`, {
365
- handoffId,
366
- newStatus: status,
367
- timestamp: new Date().toISOString()
368
- });
369
-
370
- this.emit('handoff:updated', {
371
- handoffId,
372
- status,
373
- objectiveId: context.objectiveId
374
- });
375
- }
376
-
377
- /**
378
- * Get coordination status for an objective
379
- */
380
- async getCoordinationStatus(objectiveId: string): Promise<{
381
- agents: { total: number; active: number; blocked: number };
382
- handoffs: { total: number; pending: number; completed: number };
383
- dependencies: { total: number; satisfied: number };
384
- blockages: number;
385
- }> {
386
- const context = this.contexts.get(objectiveId);
387
- if (!context) {
388
- throw new Error(`No context found for objective: ${objectiveId}`);
389
- }
390
-
391
- const agents = Array.from(context.agents.values());
392
- const handoffs = Array.from(context.handoffs.values());
393
-
394
- // Count satisfied dependencies
395
- let totalDeps = 0;
396
- let satisfiedDeps = 0;
397
- for (const deps of context.dependencies.values()) {
398
- totalDeps += deps.length;
399
- // Check each dependency (would need task completion tracking)
400
- satisfiedDeps += deps.filter(d => this.isDependencySatisfied(context, d)).length;
401
- }
402
-
403
- return {
404
- agents: {
405
- total: agents.length,
406
- active: agents.filter(a => a.status === 'working').length,
407
- blocked: context.blockages.size
408
- },
409
- handoffs: {
410
- total: handoffs.length,
411
- pending: handoffs.filter(h => h.status === 'pending').length,
412
- completed: handoffs.filter(h => h.status === 'completed').length
413
- },
414
- dependencies: {
415
- total: totalDeps,
416
- satisfied: satisfiedDeps
417
- },
418
- blockages: context.blockages.size
419
- };
420
- }
421
-
422
- /**
423
- * Apply coordination strategy
424
- */
425
- async applyStrategy(
426
- objectiveId: string,
427
- strategyType: string
428
- ): Promise<void> {
429
- const context = this.contexts.get(objectiveId);
430
- if (!context) {
431
- throw new Error(`No context found for objective: ${objectiveId}`);
432
- }
433
-
434
- const strategy = this.strategies.get(strategyType);
435
- if (!strategy) {
436
- throw new Error(`Unknown strategy: ${strategyType}`);
437
- }
438
-
439
- // Apply strategy rules
440
- for (const rule of strategy.rules) {
441
- if (this.evaluateCondition(context, rule.condition)) {
442
- await this.executeAction(context, rule.action);
443
- }
444
- }
445
-
446
- this.emit('strategy:applied', { objectiveId, strategyType });
447
- }
448
-
449
- /**
450
- * Terminate an agent
451
- */
452
- async terminateAgent(agentId: string): Promise<void> {
453
- // Find and remove agent from all contexts
454
- for (const context of this.contexts.values()) {
455
- if (context.agents.has(agentId)) {
456
- context.agents.delete(agentId);
457
-
458
- // Clear any blockages
459
- context.blockages.delete(agentId);
460
-
461
- // Update memory
462
- await this.memory.store(`agent_terminated_${agentId}`, {
463
- agentId,
464
- objectiveId: context.objectiveId,
465
- terminatedAt: new Date().toISOString()
466
- });
467
-
468
- this.emit('agent:terminated', { agentId, objectiveId: context.objectiveId });
469
- break;
470
- }
471
- }
472
-
473
- // Clear message queue
474
- this.messageQueue.delete(agentId);
475
- }
476
-
477
- /**
478
- * Initialize default coordination strategies
479
- */
480
- private initializeDefaultStrategies(): void {
481
- // Sequential strategy
482
- this.strategies.set('sequential', {
483
- type: 'sequential',
484
- rules: [
485
- {
486
- condition: 'hasBlockedAgent',
487
- action: 'waitForDependencies',
488
- priority: 1
489
- },
490
- {
491
- condition: 'allDependenciesSatisfied',
492
- action: 'proceedToNextTask',
493
- priority: 2
494
- }
495
- ]
496
- });
497
-
498
- // Parallel strategy
499
- this.strategies.set('parallel', {
500
- type: 'parallel',
501
- rules: [
502
- {
503
- condition: 'hasIndependentTasks',
504
- action: 'assignToAvailableAgents',
505
- priority: 1
506
- },
507
- {
508
- condition: 'hasBlockedAgent',
509
- action: 'reassignToOtherAgent',
510
- priority: 2
511
- }
512
- ]
513
- });
514
-
515
- // Adaptive strategy
516
- this.strategies.set('adaptive', {
517
- type: 'adaptive',
518
- rules: [
519
- {
520
- condition: 'highComplexity',
521
- action: 'spawnSpecialistAgent',
522
- priority: 1
523
- },
524
- {
525
- condition: 'repeatedFailures',
526
- action: 'switchToFallbackApproach',
527
- priority: 2
528
- }
529
- ]
530
- });
531
-
532
- // Initialize recovery strategies
533
- this.initializeRecoveryStrategies();
534
- }
535
-
536
- /**
537
- * Initialize recovery strategies for error handling
538
- */
539
- private initializeRecoveryStrategies(): void {
540
- // Permission error recovery
541
- this.recoveryStrategies.set('permission_error', {
542
- errorType: 'permission_error',
543
- recoveryActions: [
544
- {
545
- type: 'fallback',
546
- config: { scope: 'global' }
547
- },
548
- {
549
- type: 'escalate',
550
- config: { requestElevation: true }
551
- }
552
- ],
553
- maxRetries: 3
554
- });
555
-
556
- // Dependency timeout recovery
557
- this.recoveryStrategies.set('dependency_timeout', {
558
- errorType: 'dependency_timeout',
559
- recoveryActions: [
560
- {
561
- type: 'reassign',
562
- config: { preferredAgentType: 'any' }
563
- },
564
- {
565
- type: 'fallback',
566
- config: { skipDependency: true }
567
- }
568
- ],
569
- maxRetries: 2
570
- });
571
-
572
- // Resource exhaustion recovery
573
- this.recoveryStrategies.set('resource_exhaustion', {
574
- errorType: 'resource_exhaustion',
575
- recoveryActions: [
576
- {
577
- type: 'retry',
578
- config: { delay: 5000 }
579
- },
580
- {
581
- type: 'reassign',
582
- config: { reduceComplexity: true }
583
- }
584
- ],
585
- maxRetries: 3
586
- });
587
- }
588
-
589
- /**
590
- * Set up memory synchronization
591
- */
592
- private setupMemorySync(): void {
593
- // Periodically sync coordination state to memory
594
- setInterval(async () => {
595
- for (const [objectiveId, context] of this.contexts) {
596
- await this.syncContextToMemory(objectiveId, context);
597
- }
598
- }, 30000); // Every 30 seconds
599
- }
600
-
601
- /**
602
- * Sync context to memory
603
- */
604
- private async syncContextToMemory(
605
- objectiveId: string,
606
- context: CoordinationContext
607
- ): Promise<void> {
608
- await this.memory.store(`coordination_state_${objectiveId}`, {
609
- objectiveId,
610
- sessionId: context.sessionId,
611
- agentCount: context.agents.size,
612
- activeHandoffs: Array.from(context.handoffs.values()).filter(h => h.status === 'pending').length,
613
- blockages: context.blockages.size,
614
- lastSync: new Date().toISOString()
615
- });
616
- }
617
-
618
- /**
619
- * Check if dependencies are satisfied
620
- */
621
- private async checkDependencySatisfaction(
622
- context: CoordinationContext,
623
- taskId: string
624
- ): Promise<void> {
625
- const dependencies = context.dependencies.get(taskId) || [];
626
- const allSatisfied = dependencies.every(dep => this.isDependencySatisfied(context, dep));
627
-
628
- if (allSatisfied) {
629
- this.emit('dependencies:satisfied', {
630
- taskId,
631
- objectiveId: context.objectiveId
632
- });
633
- }
634
- }
635
-
636
- /**
637
- * Check if a specific dependency is satisfied
638
- */
639
- private isDependencySatisfied(context: CoordinationContext, dependencyId: string): boolean {
640
- // Check if dependency task is completed
641
- // This would integrate with TodoWrite status
642
- // For now, check if there's a completed handoff for this dependency
643
- for (const handoff of context.handoffs.values()) {
644
- if (handoff.artifactType === dependencyId && handoff.status === 'completed') {
645
- return true;
646
- }
647
- }
648
- return false;
649
- }
650
-
651
- /**
652
- * Find blocked dependencies
653
- */
654
- private findBlockedDependencies(
655
- context: CoordinationContext,
656
- blockedTasks: string[]
657
- ): string[] {
658
- const blockedDeps: string[] = [];
659
-
660
- for (const task of blockedTasks) {
661
- const deps = context.dependencies.get(task) || [];
662
- blockedDeps.push(...deps);
663
- }
664
-
665
- return [...new Set(blockedDeps)]; // Remove duplicates
666
- }
667
-
668
- /**
669
- * Attempt recovery for blocked agent
670
- */
671
- private async attemptRecovery(
672
- context: CoordinationContext,
673
- blockage: BlockageInfo
674
- ): Promise<void> {
675
- // Find appropriate recovery strategy
676
- const strategy = this.findRecoveryStrategy(blockage.reason);
677
- if (!strategy) {
678
- this.emit('recovery:failed', {
679
- agentId: blockage.agentId,
680
- reason: 'No recovery strategy available'
681
- });
682
- return;
683
- }
684
-
685
- // Try recovery actions
686
- for (const action of strategy.recoveryActions) {
687
- if (blockage.attemptedResolutions.length >= strategy.maxRetries) {
688
- break;
689
- }
690
-
691
- try {
692
- await this.executeRecoveryAction(context, blockage, action);
693
- blockage.attemptedResolutions.push(action.type);
694
-
695
- // If successful, remove blockage
696
- context.blockages.delete(blockage.agentId);
697
-
698
- this.emit('recovery:success', {
699
- agentId: blockage.agentId,
700
- action: action.type
701
- });
702
-
703
- return;
704
- } catch (error) {
705
- blockage.attemptedResolutions.push(`${action.type}_failed`);
706
- }
707
- }
708
-
709
- this.emit('recovery:exhausted', {
710
- agentId: blockage.agentId,
711
- attempts: blockage.attemptedResolutions
712
- });
713
- }
714
-
715
- /**
716
- * Find recovery strategy for error type
717
- */
718
- private findRecoveryStrategy(errorReason: string): RecoveryStrategy | undefined {
719
- // Match error reason to strategy
720
- for (const [key, strategy] of this.recoveryStrategies) {
721
- if (errorReason.toLowerCase().includes(key.replace('_', ' '))) {
722
- return strategy;
723
- }
724
- }
725
- return undefined;
726
- }
727
-
728
- /**
729
- * Execute recovery action
730
- */
731
- private async executeRecoveryAction(
732
- context: CoordinationContext,
733
- blockage: BlockageInfo,
734
- action: RecoveryAction
735
- ): Promise<void> {
736
- switch (action.type) {
737
- case 'retry':
738
- // Wait and retry
739
- await new Promise(resolve => setTimeout(resolve, action.config.delay || 1000));
740
- // Agent would retry its task
741
- break;
742
-
743
- case 'fallback':
744
- // Use fallback approach
745
- await this.sendMessage('coordinator', blockage.agentId, 'coordination', {
746
- type: 'use_fallback',
747
- config: action.config
748
- });
749
- break;
750
-
751
- case 'reassign': {
752
- // Find another agent
753
- const availableAgent = this.findAvailableAgent(context, action.config.preferredAgentType);
754
- if (availableAgent) {
755
- await this.reassignTasks(context, blockage.agentId, availableAgent.id);
756
- }
757
- break;
758
- }
759
-
760
- case 'escalate':
761
- // Escalate to Queen
762
- this.emit('escalation:required', {
763
- blockage,
764
- action: action.config
765
- });
766
- break;
767
- }
768
- }
769
-
770
- /**
771
- * Find available agent of specified type
772
- */
773
- private findAvailableAgent(
774
- context: CoordinationContext,
775
- preferredType: string
776
- ): Agent | undefined {
777
- for (const agent of context.agents.values()) {
778
- if (agent.status === 'idle' &&
779
- (preferredType === 'any' || agent.type === preferredType)) {
780
- return agent;
781
- }
782
- }
783
- return undefined;
784
- }
785
-
786
- /**
787
- * Reassign tasks from one agent to another
788
- */
789
- private async reassignTasks(
790
- context: CoordinationContext,
791
- fromAgentId: string,
792
- toAgentId: string
793
- ): Promise<void> {
794
- // Send reassignment message
795
- await this.sendMessage('coordinator', toAgentId, 'task_assignment', {
796
- type: 'reassignment',
797
- fromAgent: fromAgentId,
798
- reason: 'agent_blocked'
799
- });
800
-
801
- this.emit('tasks:reassigned', {
802
- fromAgent: fromAgentId,
803
- toAgent: toAgentId,
804
- objectiveId: context.objectiveId
805
- });
806
- }
807
-
808
- /**
809
- * Process pending messages for an agent
810
- */
811
- private async processAgentMessages(agentId: string): Promise<void> {
812
- const messages = await this.getAgentMessages(agentId);
813
-
814
- for (const message of messages) {
815
- this.emit('message:delivered', message);
816
- }
817
- }
818
-
819
- /**
820
- * Evaluate strategy condition
821
- */
822
- private evaluateCondition(context: CoordinationContext, condition: string): boolean {
823
- switch (condition) {
824
- case 'hasBlockedAgent':
825
- return context.blockages.size > 0;
826
-
827
- case 'allDependenciesSatisfied':
828
- // Check if all dependencies are satisfied
829
- for (const deps of context.dependencies.values()) {
830
- if (!deps.every(d => this.isDependencySatisfied(context, d))) {
831
- return false;
832
- }
833
- }
834
- return true;
835
-
836
- case 'hasIndependentTasks':
837
- // Check for tasks with no dependencies
838
- return Array.from(context.dependencies.values()).some(deps => deps.length === 0);
839
-
840
- case 'highComplexity':
841
- // Would need complexity metric
842
- return context.agents.size > 5;
843
-
844
- case 'repeatedFailures':
845
- // Check for multiple blockages
846
- return context.blockages.size > 2;
847
-
848
- default:
849
- return false;
850
- }
851
- }
852
-
853
- /**
854
- * Execute strategy action
855
- */
856
- private async executeAction(context: CoordinationContext, action: string): Promise<void> {
857
- switch (action) {
858
- case 'waitForDependencies':
859
- // Agents would wait for dependencies
860
- this.emit('action:wait', { objectiveId: context.objectiveId });
861
- break;
862
-
863
- case 'proceedToNextTask':
864
- // Signal agents to proceed
865
- for (const agent of context.agents.values()) {
866
- await this.sendMessage('coordinator', agent.id, 'coordination', {
867
- type: 'proceed'
868
- });
869
- }
870
- break;
871
-
872
- case 'assignToAvailableAgents': {
873
- // Distribute tasks to available agents
874
- const availableAgents = Array.from(context.agents.values())
875
- .filter(a => a.status === 'idle');
876
-
877
- // Would assign tasks here
878
- this.emit('action:assign', {
879
- objectiveId: context.objectiveId,
880
- agentCount: availableAgents.length
881
- });
882
- break;
883
- }
884
-
885
- case 'spawnSpecialistAgent':
886
- // Request Queen to spawn specialist
887
- this.emit('action:spawn_specialist', { objectiveId: context.objectiveId });
888
- break;
889
-
890
- case 'switchToFallbackApproach':
891
- // Signal all agents to use fallback
892
- for (const agent of context.agents.values()) {
893
- await this.sendMessage('coordinator', agent.id, 'coordination', {
894
- type: 'use_fallback'
895
- });
896
- }
897
- break;
898
- }
899
- }
900
-
901
- /**
902
- * Generate unique ID
903
- */
904
- private generateId(prefix: string): string {
905
- return `${prefix}_${Date.now()}_${crypto.randomBytes(4).toString('hex')}`;
906
- }
907
-
908
- /**
909
- * Get coordinator statistics
910
- */
911
- async getStats(): Promise<{
912
- activeContexts: number;
913
- totalAgents: number;
914
- activeHandoffs: number;
915
- blockedAgents: number;
916
- messagesInQueue: number;
917
- }> {
918
- let totalAgents = 0;
919
- let activeHandoffs = 0;
920
- let blockedAgents = 0;
921
- let messagesInQueue = 0;
922
-
923
- for (const context of this.contexts.values()) {
924
- totalAgents += context.agents.size;
925
- activeHandoffs += Array.from(context.handoffs.values())
926
- .filter(h => h.status === 'pending').length;
927
- blockedAgents += context.blockages.size;
928
- }
929
-
930
- for (const queue of this.messageQueue.values()) {
931
- messagesInQueue += queue.length;
932
- }
933
-
934
- return {
935
- activeContexts: this.contexts.size,
936
- totalAgents,
937
- activeHandoffs,
938
- blockedAgents,
939
- messagesInQueue
940
- };
941
- }
942
-
943
- /**
944
- * Clean up completed contexts
945
- */
946
- async cleanup(): Promise<void> {
947
- const now = Date.now();
948
- const maxAge = 3600000; // 1 hour
949
-
950
- for (const [objectiveId, context] of this.contexts) {
951
- // Check if all agents are terminated and no active handoffs
952
- const allAgentsIdle = Array.from(context.agents.values())
953
- .every(a => a.status === 'idle' || a.status === 'completed');
954
- const noActiveHandoffs = Array.from(context.handoffs.values())
955
- .every(h => h.status === 'completed' || h.status === 'failed');
956
-
957
- if (allAgentsIdle && noActiveHandoffs) {
958
- // Check age of last activity
959
- const lastActivity = Math.max(
960
- ...Array.from(context.handoffs.values())
961
- .map(h => h.completedAt?.getTime() || 0)
962
- );
963
-
964
- if (now - lastActivity > maxAge) {
965
- this.contexts.delete(objectiveId);
966
- this.emit('context:cleaned', { objectiveId });
967
- }
968
- }
969
- }
970
- }
971
- }