@claude-flow/swarm 3.0.0-alpha.1

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 (190) hide show
  1. package/.agentic-flow/intelligence.json +16 -0
  2. package/MIGRATION.md +472 -0
  3. package/README.md +634 -0
  4. package/__tests__/consensus.test.ts +577 -0
  5. package/__tests__/coordinator.test.ts +501 -0
  6. package/__tests__/queen-coordinator.test.ts +1335 -0
  7. package/__tests__/topology.test.ts +621 -0
  8. package/dist/agent-pool.d.ts +52 -0
  9. package/dist/agent-pool.d.ts.map +1 -0
  10. package/dist/agent-pool.js +365 -0
  11. package/dist/agent-pool.js.map +1 -0
  12. package/dist/application/commands/create-task.command.d.ts +64 -0
  13. package/dist/application/commands/create-task.command.d.ts.map +1 -0
  14. package/dist/application/commands/create-task.command.js +77 -0
  15. package/dist/application/commands/create-task.command.js.map +1 -0
  16. package/dist/application/commands/spawn-agent.command.d.ts +63 -0
  17. package/dist/application/commands/spawn-agent.command.d.ts.map +1 -0
  18. package/dist/application/commands/spawn-agent.command.js +74 -0
  19. package/dist/application/commands/spawn-agent.command.js.map +1 -0
  20. package/dist/application/index.d.ts +9 -0
  21. package/dist/application/index.d.ts.map +1 -0
  22. package/dist/application/index.js +11 -0
  23. package/dist/application/index.js.map +1 -0
  24. package/dist/application/services/swarm-application-service.d.ts +112 -0
  25. package/dist/application/services/swarm-application-service.d.ts.map +1 -0
  26. package/dist/application/services/swarm-application-service.js +153 -0
  27. package/dist/application/services/swarm-application-service.js.map +1 -0
  28. package/dist/attention-coordinator.d.ts +212 -0
  29. package/dist/attention-coordinator.d.ts.map +1 -0
  30. package/dist/attention-coordinator.js +667 -0
  31. package/dist/attention-coordinator.js.map +1 -0
  32. package/dist/consensus/byzantine.d.ts +63 -0
  33. package/dist/consensus/byzantine.d.ts.map +1 -0
  34. package/dist/consensus/byzantine.js +316 -0
  35. package/dist/consensus/byzantine.js.map +1 -0
  36. package/dist/consensus/gossip.d.ts +69 -0
  37. package/dist/consensus/gossip.d.ts.map +1 -0
  38. package/dist/consensus/gossip.js +378 -0
  39. package/dist/consensus/gossip.js.map +1 -0
  40. package/dist/consensus/index.d.ts +49 -0
  41. package/dist/consensus/index.d.ts.map +1 -0
  42. package/dist/consensus/index.js +203 -0
  43. package/dist/consensus/index.js.map +1 -0
  44. package/dist/consensus/raft.d.ts +62 -0
  45. package/dist/consensus/raft.d.ts.map +1 -0
  46. package/dist/consensus/raft.js +324 -0
  47. package/dist/consensus/raft.js.map +1 -0
  48. package/dist/coordination/agent-registry.d.ts +68 -0
  49. package/dist/coordination/agent-registry.d.ts.map +1 -0
  50. package/dist/coordination/agent-registry.js +412 -0
  51. package/dist/coordination/agent-registry.js.map +1 -0
  52. package/dist/coordination/index.d.ts +8 -0
  53. package/dist/coordination/index.d.ts.map +1 -0
  54. package/dist/coordination/index.js +8 -0
  55. package/dist/coordination/index.js.map +1 -0
  56. package/dist/coordination/swarm-hub.d.ts +150 -0
  57. package/dist/coordination/swarm-hub.d.ts.map +1 -0
  58. package/dist/coordination/swarm-hub.js +617 -0
  59. package/dist/coordination/swarm-hub.js.map +1 -0
  60. package/dist/coordination/task-orchestrator.d.ts +96 -0
  61. package/dist/coordination/task-orchestrator.d.ts.map +1 -0
  62. package/dist/coordination/task-orchestrator.js +412 -0
  63. package/dist/coordination/task-orchestrator.js.map +1 -0
  64. package/dist/domain/entities/agent.d.ts +151 -0
  65. package/dist/domain/entities/agent.d.ts.map +1 -0
  66. package/dist/domain/entities/agent.js +280 -0
  67. package/dist/domain/entities/agent.js.map +1 -0
  68. package/dist/domain/entities/task.d.ts +133 -0
  69. package/dist/domain/entities/task.d.ts.map +1 -0
  70. package/dist/domain/entities/task.js +261 -0
  71. package/dist/domain/entities/task.js.map +1 -0
  72. package/dist/domain/index.d.ts +11 -0
  73. package/dist/domain/index.d.ts.map +1 -0
  74. package/dist/domain/index.js +11 -0
  75. package/dist/domain/index.js.map +1 -0
  76. package/dist/domain/repositories/agent-repository.interface.d.ts +57 -0
  77. package/dist/domain/repositories/agent-repository.interface.d.ts.map +1 -0
  78. package/dist/domain/repositories/agent-repository.interface.js +9 -0
  79. package/dist/domain/repositories/agent-repository.interface.js.map +1 -0
  80. package/dist/domain/repositories/task-repository.interface.d.ts +61 -0
  81. package/dist/domain/repositories/task-repository.interface.d.ts.map +1 -0
  82. package/dist/domain/repositories/task-repository.interface.js +9 -0
  83. package/dist/domain/repositories/task-repository.interface.js.map +1 -0
  84. package/dist/domain/services/coordination-service.d.ts +84 -0
  85. package/dist/domain/services/coordination-service.d.ts.map +1 -0
  86. package/dist/domain/services/coordination-service.js +231 -0
  87. package/dist/domain/services/coordination-service.js.map +1 -0
  88. package/dist/federation-hub.d.ts +284 -0
  89. package/dist/federation-hub.d.ts.map +1 -0
  90. package/dist/federation-hub.js +692 -0
  91. package/dist/federation-hub.js.map +1 -0
  92. package/dist/index.d.ts +107 -0
  93. package/dist/index.d.ts.map +1 -0
  94. package/dist/index.js +142 -0
  95. package/dist/index.js.map +1 -0
  96. package/dist/message-bus.d.ts +48 -0
  97. package/dist/message-bus.d.ts.map +1 -0
  98. package/dist/message-bus.js +499 -0
  99. package/dist/message-bus.js.map +1 -0
  100. package/dist/queen-coordinator.d.ts +576 -0
  101. package/dist/queen-coordinator.d.ts.map +1 -0
  102. package/dist/queen-coordinator.js +1307 -0
  103. package/dist/queen-coordinator.js.map +1 -0
  104. package/dist/shared/events.d.ts +63 -0
  105. package/dist/shared/events.d.ts.map +1 -0
  106. package/dist/shared/events.js +203 -0
  107. package/dist/shared/events.js.map +1 -0
  108. package/dist/shared/types.d.ts +212 -0
  109. package/dist/shared/types.d.ts.map +1 -0
  110. package/dist/shared/types.js +22 -0
  111. package/dist/shared/types.js.map +1 -0
  112. package/dist/topology-manager.d.ts +62 -0
  113. package/dist/topology-manager.d.ts.map +1 -0
  114. package/dist/topology-manager.js +538 -0
  115. package/dist/topology-manager.js.map +1 -0
  116. package/dist/types.d.ts +353 -0
  117. package/dist/types.d.ts.map +1 -0
  118. package/dist/types.js +43 -0
  119. package/dist/types.js.map +1 -0
  120. package/dist/unified-coordinator.d.ts +260 -0
  121. package/dist/unified-coordinator.d.ts.map +1 -0
  122. package/dist/unified-coordinator.js +1460 -0
  123. package/dist/unified-coordinator.js.map +1 -0
  124. package/dist/workers/index.d.ts +29 -0
  125. package/dist/workers/index.d.ts.map +1 -0
  126. package/dist/workers/index.js +49 -0
  127. package/dist/workers/index.js.map +1 -0
  128. package/dist/workers/worker-dispatch.d.ts +234 -0
  129. package/dist/workers/worker-dispatch.d.ts.map +1 -0
  130. package/dist/workers/worker-dispatch.js +842 -0
  131. package/dist/workers/worker-dispatch.js.map +1 -0
  132. package/package.json +33 -0
  133. package/src/agent-pool.ts +476 -0
  134. package/src/application/commands/create-task.command.ts +124 -0
  135. package/src/application/commands/spawn-agent.command.ts +122 -0
  136. package/src/application/index.ts +30 -0
  137. package/src/application/services/swarm-application-service.ts +200 -0
  138. package/src/attention-coordinator.ts +1000 -0
  139. package/src/consensus/byzantine.ts +431 -0
  140. package/src/consensus/gossip.ts +513 -0
  141. package/src/consensus/index.ts +267 -0
  142. package/src/consensus/raft.ts +443 -0
  143. package/src/coordination/agent-registry.ts +544 -0
  144. package/src/coordination/index.ts +23 -0
  145. package/src/coordination/swarm-hub.ts +776 -0
  146. package/src/coordination/task-orchestrator.ts +605 -0
  147. package/src/domain/entities/agent.d.ts +151 -0
  148. package/src/domain/entities/agent.d.ts.map +1 -0
  149. package/src/domain/entities/agent.js +280 -0
  150. package/src/domain/entities/agent.js.map +1 -0
  151. package/src/domain/entities/agent.ts +370 -0
  152. package/src/domain/entities/task.d.ts +133 -0
  153. package/src/domain/entities/task.d.ts.map +1 -0
  154. package/src/domain/entities/task.js +261 -0
  155. package/src/domain/entities/task.js.map +1 -0
  156. package/src/domain/entities/task.ts +319 -0
  157. package/src/domain/index.ts +41 -0
  158. package/src/domain/repositories/agent-repository.interface.d.ts +57 -0
  159. package/src/domain/repositories/agent-repository.interface.d.ts.map +1 -0
  160. package/src/domain/repositories/agent-repository.interface.js +9 -0
  161. package/src/domain/repositories/agent-repository.interface.js.map +1 -0
  162. package/src/domain/repositories/agent-repository.interface.ts +69 -0
  163. package/src/domain/repositories/task-repository.interface.d.ts +61 -0
  164. package/src/domain/repositories/task-repository.interface.d.ts.map +1 -0
  165. package/src/domain/repositories/task-repository.interface.js +9 -0
  166. package/src/domain/repositories/task-repository.interface.js.map +1 -0
  167. package/src/domain/repositories/task-repository.interface.ts +75 -0
  168. package/src/domain/services/coordination-service.ts +320 -0
  169. package/src/federation-hub.d.ts +284 -0
  170. package/src/federation-hub.d.ts.map +1 -0
  171. package/src/federation-hub.js +692 -0
  172. package/src/federation-hub.js.map +1 -0
  173. package/src/federation-hub.ts +979 -0
  174. package/src/index.ts +348 -0
  175. package/src/message-bus.ts +607 -0
  176. package/src/queen-coordinator.ts +2024 -0
  177. package/src/shared/events.ts +285 -0
  178. package/src/shared/types.ts +389 -0
  179. package/src/topology-manager.ts +656 -0
  180. package/src/types.ts +545 -0
  181. package/src/unified-coordinator.ts +1844 -0
  182. package/src/workers/index.ts +65 -0
  183. package/src/workers/worker-dispatch.d.ts +234 -0
  184. package/src/workers/worker-dispatch.d.ts.map +1 -0
  185. package/src/workers/worker-dispatch.js +842 -0
  186. package/src/workers/worker-dispatch.js.map +1 -0
  187. package/src/workers/worker-dispatch.ts +1072 -0
  188. package/tsconfig.json +9 -0
  189. package/tsconfig.tsbuildinfo +1 -0
  190. package/vitest.config.ts +20 -0
@@ -0,0 +1,1307 @@
1
+ /**
2
+ * Queen Coordinator - Central Orchestrator for 15-Agent Swarm
3
+ *
4
+ * The Queen Coordinator is the strategic decision-maker for the V3 hive-mind system.
5
+ * It analyzes tasks, delegates to appropriate agents, monitors swarm health,
6
+ * coordinates consensus, and learns from outcomes using ReasoningBank patterns.
7
+ *
8
+ * Features:
9
+ * - Strategic task analysis with ReasoningBank pattern matching
10
+ * - Agent delegation with capability scoring and load balancing
11
+ * - Swarm health monitoring with bottleneck detection
12
+ * - Consensus coordination (majority, weighted, unanimous)
13
+ * - Learning from outcomes for continuous improvement
14
+ *
15
+ * Performance Targets:
16
+ * - Task analysis: <50ms
17
+ * - Agent scoring: <20ms
18
+ * - Consensus coordination: <100ms
19
+ * - Health check: <30ms
20
+ *
21
+ * @module @claude-flow/swarm/queen-coordinator
22
+ */
23
+ import { EventEmitter } from 'events';
24
+ /**
25
+ * Default Queen Coordinator configuration
26
+ */
27
+ const DEFAULT_CONFIG = {
28
+ enableLearning: true,
29
+ patternRetrievalK: 5,
30
+ patternThreshold: 0.6,
31
+ complexityThresholds: {
32
+ simple: 0.3,
33
+ moderate: 0.6,
34
+ complex: 0.85,
35
+ },
36
+ healthCheckIntervalMs: 10000,
37
+ bottleneckThresholds: {
38
+ queueDepth: 10,
39
+ errorRate: 0.1,
40
+ responseTimeMs: 5000,
41
+ },
42
+ consensusTimeouts: {
43
+ majority: 5000,
44
+ supermajority: 10000,
45
+ unanimous: 30000,
46
+ },
47
+ enableFailover: true,
48
+ maxDelegationAttempts: 3,
49
+ };
50
+ // =============================================================================
51
+ // Queen Coordinator Class
52
+ // =============================================================================
53
+ /**
54
+ * Queen Coordinator - Central orchestrator for the 15-agent hive-mind swarm
55
+ *
56
+ * The Queen is responsible for:
57
+ * 1. Strategic task analysis and decomposition
58
+ * 2. Agent delegation with load balancing
59
+ * 3. Swarm health monitoring
60
+ * 4. Consensus coordination
61
+ * 5. Learning from outcomes
62
+ */
63
+ export class QueenCoordinator extends EventEmitter {
64
+ config;
65
+ swarm;
66
+ neural;
67
+ memory;
68
+ // Internal state
69
+ analysisCache = new Map();
70
+ delegationPlans = new Map();
71
+ activeDecisions = new Map();
72
+ outcomeHistory = [];
73
+ healthHistory = [];
74
+ // Counters for IDs
75
+ analysisCounter = 0;
76
+ planCounter = 0;
77
+ reportCounter = 0;
78
+ decisionCounter = 0;
79
+ // Health monitoring
80
+ healthCheckInterval;
81
+ lastHealthReport;
82
+ // Performance tracking
83
+ analysisLatencies = [];
84
+ delegationLatencies = [];
85
+ consensusLatencies = [];
86
+ constructor(swarm, config = {}, neural, memory) {
87
+ super();
88
+ this.swarm = swarm;
89
+ this.config = { ...DEFAULT_CONFIG, ...config };
90
+ this.neural = neural;
91
+ this.memory = memory;
92
+ }
93
+ // ===========================================================================
94
+ // Lifecycle
95
+ // ===========================================================================
96
+ /**
97
+ * Initialize the Queen Coordinator
98
+ */
99
+ async initialize() {
100
+ // Initialize neural system if available
101
+ if (this.neural && this.config.enableLearning) {
102
+ await this.neural.initialize();
103
+ }
104
+ // Start health monitoring
105
+ this.startHealthMonitoring();
106
+ this.emitEvent('queen.initialized', {
107
+ config: this.config,
108
+ learningEnabled: this.config.enableLearning && !!this.neural,
109
+ });
110
+ }
111
+ /**
112
+ * Shutdown the Queen Coordinator
113
+ */
114
+ async shutdown() {
115
+ this.stopHealthMonitoring();
116
+ // Trigger final learning if enabled
117
+ if (this.neural && this.config.enableLearning) {
118
+ await this.neural.triggerLearning();
119
+ }
120
+ this.emitEvent('queen.shutdown', {
121
+ totalAnalyses: this.analysisCounter,
122
+ totalPlans: this.planCounter,
123
+ totalDecisions: this.decisionCounter,
124
+ });
125
+ }
126
+ // ===========================================================================
127
+ // Strategic Task Analysis
128
+ // ===========================================================================
129
+ /**
130
+ * Analyze a task for optimal execution
131
+ *
132
+ * @param task - Task to analyze
133
+ * @returns Task analysis with recommendations
134
+ */
135
+ async analyzeTask(task) {
136
+ const startTime = performance.now();
137
+ this.analysisCounter++;
138
+ const analysisId = `analysis_${Date.now()}_${this.analysisCounter}`;
139
+ // Decompose complex tasks
140
+ const subtasks = this.decomposeTask(task);
141
+ // Identify required capabilities
142
+ const requiredCapabilities = this.identifyRequiredCapabilities(task);
143
+ // Calculate complexity
144
+ const complexity = this.calculateComplexity(task, subtasks);
145
+ // Estimate duration
146
+ const estimatedDurationMs = this.estimateDuration(task, complexity, subtasks);
147
+ // Determine recommended domain
148
+ const recommendedDomain = this.determineOptimalDomain(task, requiredCapabilities);
149
+ // Find matching patterns from ReasoningBank
150
+ const matchedPatterns = await this.findMatchingPatterns(task);
151
+ // Estimate resource requirements
152
+ const resourceRequirements = this.estimateResources(task, complexity);
153
+ // Calculate confidence
154
+ const confidence = this.calculateAnalysisConfidence(matchedPatterns, complexity, requiredCapabilities);
155
+ const analysis = {
156
+ analysisId,
157
+ taskId: task.id.id,
158
+ complexity,
159
+ estimatedDurationMs,
160
+ requiredCapabilities,
161
+ recommendedDomain,
162
+ subtasks,
163
+ matchedPatterns,
164
+ resourceRequirements,
165
+ confidence,
166
+ timestamp: new Date(),
167
+ };
168
+ // Cache the analysis
169
+ this.analysisCache.set(analysisId, analysis);
170
+ // Record latency
171
+ const latency = performance.now() - startTime;
172
+ this.analysisLatencies.push(latency);
173
+ if (this.analysisLatencies.length > 100) {
174
+ this.analysisLatencies.shift();
175
+ }
176
+ this.emitEvent('queen.task.analyzed', {
177
+ analysisId,
178
+ taskId: task.id.id,
179
+ complexity,
180
+ recommendedDomain,
181
+ patternsFound: matchedPatterns.length,
182
+ latencyMs: latency,
183
+ });
184
+ return analysis;
185
+ }
186
+ /**
187
+ * Decompose a complex task into subtasks
188
+ */
189
+ decomposeTask(task) {
190
+ const subtasks = [];
191
+ // Simple tasks don't need decomposition
192
+ if (this.isSimpleTask(task)) {
193
+ return subtasks;
194
+ }
195
+ // Decompose based on task type
196
+ switch (task.type) {
197
+ case 'coding':
198
+ subtasks.push(...this.decomposeCodingTask(task));
199
+ break;
200
+ case 'testing':
201
+ subtasks.push(...this.decomposeTestingTask(task));
202
+ break;
203
+ case 'research':
204
+ subtasks.push(...this.decomposeResearchTask(task));
205
+ break;
206
+ case 'coordination':
207
+ subtasks.push(...this.decomposeCoordinationTask(task));
208
+ break;
209
+ default:
210
+ // Generic decomposition
211
+ subtasks.push(...this.decomposeGenericTask(task));
212
+ }
213
+ return subtasks;
214
+ }
215
+ isSimpleTask(task) {
216
+ // Estimate if task is simple based on description length and type
217
+ const descLength = task.description?.length || 0;
218
+ const isSimpleType = ['documentation', 'review'].includes(task.type);
219
+ return descLength < 200 || isSimpleType;
220
+ }
221
+ decomposeCodingTask(task) {
222
+ return [
223
+ {
224
+ id: `${task.id.id}_design`,
225
+ name: 'Design & Planning',
226
+ description: 'Design the solution architecture',
227
+ type: 'analysis',
228
+ priority: task.priority,
229
+ dependencies: [],
230
+ estimatedDurationMs: 10000,
231
+ requiredCapabilities: ['design', 'architecture'],
232
+ recommendedDomain: 'core',
233
+ },
234
+ {
235
+ id: `${task.id.id}_implement`,
236
+ name: 'Implementation',
237
+ description: 'Implement the designed solution',
238
+ type: 'coding',
239
+ priority: task.priority,
240
+ dependencies: [`${task.id.id}_design`],
241
+ estimatedDurationMs: 30000,
242
+ requiredCapabilities: ['coding', 'implementation'],
243
+ recommendedDomain: 'integration',
244
+ },
245
+ {
246
+ id: `${task.id.id}_test`,
247
+ name: 'Testing',
248
+ description: 'Test the implementation',
249
+ type: 'testing',
250
+ priority: task.priority,
251
+ dependencies: [`${task.id.id}_implement`],
252
+ estimatedDurationMs: 15000,
253
+ requiredCapabilities: ['testing', 'validation'],
254
+ recommendedDomain: 'support',
255
+ },
256
+ ];
257
+ }
258
+ decomposeTestingTask(task) {
259
+ return [
260
+ {
261
+ id: `${task.id.id}_analyze`,
262
+ name: 'Test Analysis',
263
+ description: 'Analyze what needs to be tested',
264
+ type: 'analysis',
265
+ priority: task.priority,
266
+ dependencies: [],
267
+ estimatedDurationMs: 5000,
268
+ requiredCapabilities: ['analysis', 'testing'],
269
+ recommendedDomain: 'support',
270
+ },
271
+ {
272
+ id: `${task.id.id}_execute`,
273
+ name: 'Test Execution',
274
+ description: 'Execute the tests',
275
+ type: 'testing',
276
+ priority: task.priority,
277
+ dependencies: [`${task.id.id}_analyze`],
278
+ estimatedDurationMs: 20000,
279
+ requiredCapabilities: ['testing', 'execution'],
280
+ recommendedDomain: 'support',
281
+ },
282
+ ];
283
+ }
284
+ decomposeResearchTask(task) {
285
+ return [
286
+ {
287
+ id: `${task.id.id}_gather`,
288
+ name: 'Information Gathering',
289
+ description: 'Gather relevant information',
290
+ type: 'research',
291
+ priority: task.priority,
292
+ dependencies: [],
293
+ estimatedDurationMs: 15000,
294
+ requiredCapabilities: ['research', 'analysis'],
295
+ recommendedDomain: 'core',
296
+ },
297
+ {
298
+ id: `${task.id.id}_analyze`,
299
+ name: 'Analysis',
300
+ description: 'Analyze gathered information',
301
+ type: 'analysis',
302
+ priority: task.priority,
303
+ dependencies: [`${task.id.id}_gather`],
304
+ estimatedDurationMs: 10000,
305
+ requiredCapabilities: ['analysis', 'synthesis'],
306
+ recommendedDomain: 'core',
307
+ },
308
+ ];
309
+ }
310
+ decomposeCoordinationTask(task) {
311
+ return [
312
+ {
313
+ id: `${task.id.id}_plan`,
314
+ name: 'Planning',
315
+ description: 'Create coordination plan',
316
+ type: 'coordination',
317
+ priority: task.priority,
318
+ dependencies: [],
319
+ estimatedDurationMs: 5000,
320
+ requiredCapabilities: ['planning', 'coordination'],
321
+ recommendedDomain: 'queen',
322
+ },
323
+ {
324
+ id: `${task.id.id}_execute`,
325
+ name: 'Execution',
326
+ description: 'Execute coordination plan',
327
+ type: 'coordination',
328
+ priority: task.priority,
329
+ dependencies: [`${task.id.id}_plan`],
330
+ estimatedDurationMs: 10000,
331
+ requiredCapabilities: ['coordination', 'oversight'],
332
+ recommendedDomain: 'queen',
333
+ },
334
+ ];
335
+ }
336
+ decomposeGenericTask(task) {
337
+ return [
338
+ {
339
+ id: `${task.id.id}_execute`,
340
+ name: 'Task Execution',
341
+ description: task.description,
342
+ type: task.type,
343
+ priority: task.priority,
344
+ dependencies: [],
345
+ estimatedDurationMs: 20000,
346
+ requiredCapabilities: this.identifyRequiredCapabilities(task),
347
+ recommendedDomain: this.inferDomainFromType(task.type),
348
+ },
349
+ ];
350
+ }
351
+ /**
352
+ * Identify required capabilities for a task
353
+ */
354
+ identifyRequiredCapabilities(task) {
355
+ const capabilities = new Set();
356
+ // Add type-based capabilities
357
+ const typeCapabilities = {
358
+ research: ['research', 'analysis', 'synthesis'],
359
+ analysis: ['analysis', 'reasoning', 'synthesis'],
360
+ coding: ['coding', 'implementation', 'debugging'],
361
+ testing: ['testing', 'validation', 'quality'],
362
+ review: ['review', 'analysis', 'feedback'],
363
+ documentation: ['documentation', 'writing', 'clarity'],
364
+ coordination: ['coordination', 'planning', 'oversight'],
365
+ consensus: ['consensus', 'voting', 'agreement'],
366
+ custom: ['general', 'execution'],
367
+ };
368
+ for (const cap of typeCapabilities[task.type] || ['general']) {
369
+ capabilities.add(cap);
370
+ }
371
+ // Extract additional capabilities from description
372
+ const descLower = (task.description || '').toLowerCase();
373
+ if (descLower.includes('security'))
374
+ capabilities.add('security');
375
+ if (descLower.includes('performance'))
376
+ capabilities.add('performance');
377
+ if (descLower.includes('architecture'))
378
+ capabilities.add('architecture');
379
+ if (descLower.includes('integration'))
380
+ capabilities.add('integration');
381
+ if (descLower.includes('deploy'))
382
+ capabilities.add('deployment');
383
+ return Array.from(capabilities);
384
+ }
385
+ /**
386
+ * Calculate task complexity score
387
+ */
388
+ calculateComplexity(task, subtasks) {
389
+ let complexity = 0.3; // Base complexity
390
+ // Add complexity for subtasks
391
+ complexity += subtasks.length * 0.1;
392
+ // Add complexity for dependencies
393
+ const totalDeps = subtasks.reduce((sum, st) => sum + st.dependencies.length, 0);
394
+ complexity += totalDeps * 0.05;
395
+ // Add complexity for priority
396
+ const priorityMultipliers = {
397
+ critical: 1.3,
398
+ high: 1.15,
399
+ normal: 1.0,
400
+ low: 0.9,
401
+ background: 0.8,
402
+ };
403
+ complexity *= priorityMultipliers[task.priority];
404
+ // Add complexity for task type
405
+ const typeComplexity = {
406
+ coordination: 0.2,
407
+ consensus: 0.25,
408
+ coding: 0.15,
409
+ testing: 0.1,
410
+ analysis: 0.1,
411
+ research: 0.1,
412
+ review: 0.05,
413
+ documentation: 0.05,
414
+ custom: 0.1,
415
+ };
416
+ complexity += typeComplexity[task.type] || 0.1;
417
+ // Add complexity for description length
418
+ const descLength = task.description?.length || 0;
419
+ complexity += Math.min(descLength / 2000, 0.2);
420
+ return Math.min(complexity, 1.0);
421
+ }
422
+ /**
423
+ * Estimate task duration
424
+ */
425
+ estimateDuration(task, complexity, subtasks) {
426
+ // Base duration by type (in ms)
427
+ const baseDurations = {
428
+ research: 30000,
429
+ analysis: 20000,
430
+ coding: 60000,
431
+ testing: 30000,
432
+ review: 15000,
433
+ documentation: 20000,
434
+ coordination: 10000,
435
+ consensus: 15000,
436
+ custom: 30000,
437
+ };
438
+ const baseDuration = baseDurations[task.type] || 30000;
439
+ // Adjust for complexity
440
+ const complexityMultiplier = 0.5 + complexity * 1.5;
441
+ // Add subtask durations
442
+ const subtaskDuration = subtasks.reduce((sum, st) => sum + st.estimatedDurationMs, 0);
443
+ // Total estimate
444
+ return Math.round(baseDuration * complexityMultiplier + subtaskDuration * 0.5);
445
+ }
446
+ /**
447
+ * Determine optimal domain for task execution
448
+ */
449
+ determineOptimalDomain(task, capabilities) {
450
+ // Check capabilities for domain hints
451
+ if (capabilities.includes('security'))
452
+ return 'security';
453
+ if (capabilities.includes('coordination') || capabilities.includes('planning'))
454
+ return 'queen';
455
+ if (capabilities.includes('testing') || capabilities.includes('performance'))
456
+ return 'support';
457
+ if (capabilities.includes('integration'))
458
+ return 'integration';
459
+ // Fall back to type-based inference
460
+ return this.inferDomainFromType(task.type);
461
+ }
462
+ inferDomainFromType(type) {
463
+ const typeDomains = {
464
+ coordination: 'queen',
465
+ consensus: 'queen',
466
+ coding: 'integration',
467
+ testing: 'support',
468
+ review: 'security',
469
+ analysis: 'core',
470
+ research: 'core',
471
+ documentation: 'support',
472
+ custom: 'core',
473
+ };
474
+ return typeDomains[type] || 'core';
475
+ }
476
+ /**
477
+ * Find matching patterns from ReasoningBank
478
+ */
479
+ async findMatchingPatterns(task) {
480
+ const patterns = [];
481
+ if (!this.neural || !this.config.enableLearning) {
482
+ return patterns;
483
+ }
484
+ try {
485
+ // Create a simple embedding from task description
486
+ const embedding = this.createSimpleEmbedding(task.description || task.name);
487
+ // Query ReasoningBank for similar patterns
488
+ const results = await this.neural.findPatterns(embedding, this.config.patternRetrievalK);
489
+ for (const result of results) {
490
+ if (result.relevanceScore >= this.config.patternThreshold) {
491
+ patterns.push({
492
+ patternId: result.patternId,
493
+ strategy: result.strategy,
494
+ successRate: result.successRate,
495
+ relevanceScore: result.relevanceScore,
496
+ keyLearnings: result.keyLearnings || [],
497
+ });
498
+ }
499
+ }
500
+ }
501
+ catch (error) {
502
+ // Log but don't fail - patterns are optional
503
+ this.emitEvent('queen.pattern.error', { error: String(error) });
504
+ }
505
+ return patterns;
506
+ }
507
+ /**
508
+ * Create a simple embedding from text (placeholder)
509
+ */
510
+ createSimpleEmbedding(text) {
511
+ // Simple hash-based embedding for demonstration
512
+ // In production, this would use a real embedding model
513
+ const embedding = new Float32Array(768);
514
+ const words = text.toLowerCase().split(/\s+/);
515
+ for (let i = 0; i < words.length; i++) {
516
+ const word = words[i];
517
+ for (let j = 0; j < word.length; j++) {
518
+ const idx = (word.charCodeAt(j) * (i + 1) * (j + 1)) % 768;
519
+ embedding[idx] += 1 / words.length;
520
+ }
521
+ }
522
+ // Normalize
523
+ let norm = 0;
524
+ for (let i = 0; i < embedding.length; i++) {
525
+ norm += embedding[i] * embedding[i];
526
+ }
527
+ norm = Math.sqrt(norm);
528
+ if (norm > 0) {
529
+ for (let i = 0; i < embedding.length; i++) {
530
+ embedding[i] /= norm;
531
+ }
532
+ }
533
+ return embedding;
534
+ }
535
+ /**
536
+ * Estimate resource requirements
537
+ */
538
+ estimateResources(task, complexity) {
539
+ const minAgents = complexity > 0.7 ? 2 : 1;
540
+ const maxAgents = complexity > 0.8 ? 4 : complexity > 0.5 ? 3 : 2;
541
+ return {
542
+ minAgents,
543
+ maxAgents,
544
+ memoryMb: Math.round(256 + complexity * 512),
545
+ cpuIntensive: ['coding', 'analysis'].includes(task.type),
546
+ ioIntensive: ['research', 'testing'].includes(task.type),
547
+ networkRequired: task.type === 'research',
548
+ };
549
+ }
550
+ /**
551
+ * Calculate confidence in analysis
552
+ */
553
+ calculateAnalysisConfidence(patterns, complexity, capabilities) {
554
+ let confidence = 0.5; // Base confidence
555
+ // Higher confidence with more matching patterns
556
+ confidence += patterns.length * 0.1;
557
+ // Higher confidence for simpler tasks
558
+ confidence += (1 - complexity) * 0.2;
559
+ // Higher confidence with clear capabilities
560
+ confidence += Math.min(capabilities.length * 0.05, 0.15);
561
+ // Boost from high-success patterns
562
+ const avgPatternSuccess = patterns.length > 0
563
+ ? patterns.reduce((sum, p) => sum + p.successRate, 0) / patterns.length
564
+ : 0;
565
+ confidence += avgPatternSuccess * 0.1;
566
+ return Math.min(confidence, 0.95);
567
+ }
568
+ // ===========================================================================
569
+ // Agent Delegation
570
+ // ===========================================================================
571
+ /**
572
+ * Delegate a task to agents based on analysis
573
+ *
574
+ * @param task - Task to delegate
575
+ * @param analysis - Previous task analysis
576
+ * @returns Delegation plan
577
+ */
578
+ async delegateToAgents(task, analysis) {
579
+ const startTime = performance.now();
580
+ this.planCounter++;
581
+ const planId = `plan_${Date.now()}_${this.planCounter}`;
582
+ // Score all available agents for this task
583
+ const agentScores = this.scoreAgents(task, analysis.matchedPatterns);
584
+ // Select primary agent
585
+ const primaryAgent = this.selectPrimaryAgent(task, agentScores, analysis);
586
+ // Select backup agents
587
+ const backupAgents = this.selectBackupAgents(task, agentScores, primaryAgent);
588
+ // Create parallel assignments for subtasks
589
+ const parallelAssignments = this.createParallelAssignments(analysis.subtasks, agentScores);
590
+ // Determine execution strategy
591
+ const strategy = this.determineExecutionStrategy(analysis);
592
+ const plan = {
593
+ planId,
594
+ taskId: task.id.id,
595
+ analysisId: analysis.analysisId,
596
+ primaryAgent,
597
+ backupAgents,
598
+ parallelAssignments,
599
+ strategy,
600
+ estimatedCompletionMs: analysis.estimatedDurationMs,
601
+ timestamp: new Date(),
602
+ };
603
+ // Store the plan
604
+ this.delegationPlans.set(planId, plan);
605
+ // Execute the delegation
606
+ await this.executeDelegation(plan);
607
+ // Record latency
608
+ const latency = performance.now() - startTime;
609
+ this.delegationLatencies.push(latency);
610
+ if (this.delegationLatencies.length > 100) {
611
+ this.delegationLatencies.shift();
612
+ }
613
+ this.emitEvent('queen.task.delegated', {
614
+ planId,
615
+ taskId: task.id.id,
616
+ primaryAgent: primaryAgent.agentId,
617
+ strategy,
618
+ latencyMs: latency,
619
+ });
620
+ return plan;
621
+ }
622
+ /**
623
+ * Score agents for task assignment
624
+ */
625
+ scoreAgents(task, patterns) {
626
+ const agents = this.swarm.getAllAgents();
627
+ const scores = [];
628
+ for (const agent of agents) {
629
+ const score = this.scoreAgent(agent, task, patterns);
630
+ scores.push(score);
631
+ }
632
+ // Sort by total score descending
633
+ scores.sort((a, b) => b.totalScore - a.totalScore);
634
+ return scores;
635
+ }
636
+ scoreAgent(agent, task, patterns) {
637
+ const domain = this.getAgentDomain(agent);
638
+ // Capability score - how well agent capabilities match task
639
+ const capabilityScore = this.calculateCapabilityScore(agent, task);
640
+ // Load score - prefer less loaded agents
641
+ const loadScore = 1 - agent.workload;
642
+ // Performance score - based on past performance
643
+ const performanceScore = this.calculatePerformanceScore(agent, patterns);
644
+ // Health score - agent health
645
+ const healthScore = agent.health;
646
+ // Availability score - is agent actually available
647
+ const availabilityScore = agent.status === 'idle' ? 1.0 :
648
+ agent.status === 'busy' ? 0.3 : 0.0;
649
+ // Weighted total
650
+ const totalScore = capabilityScore * 0.30 +
651
+ loadScore * 0.20 +
652
+ performanceScore * 0.25 +
653
+ healthScore * 0.15 +
654
+ availabilityScore * 0.10;
655
+ return {
656
+ agentId: agent.id.id,
657
+ domain,
658
+ totalScore,
659
+ capabilityScore,
660
+ loadScore,
661
+ performanceScore,
662
+ healthScore,
663
+ availabilityScore,
664
+ };
665
+ }
666
+ calculateCapabilityScore(agent, task) {
667
+ let score = 0.5; // Base score
668
+ // Check type match
669
+ const typeMatches = {
670
+ research: ['researcher'],
671
+ analysis: ['analyst', 'researcher'],
672
+ coding: ['coder'],
673
+ testing: ['tester'],
674
+ review: ['reviewer'],
675
+ documentation: ['documenter'],
676
+ coordination: ['coordinator', 'queen'],
677
+ consensus: ['coordinator', 'queen'],
678
+ custom: ['worker'],
679
+ };
680
+ const preferredTypes = typeMatches[task.type] || ['worker'];
681
+ if (preferredTypes.includes(agent.type)) {
682
+ score += 0.3;
683
+ }
684
+ // Check specific capabilities
685
+ const caps = agent.capabilities;
686
+ if (task.type === 'coding' && caps.codeGeneration)
687
+ score += 0.1;
688
+ if (task.type === 'review' && caps.codeReview)
689
+ score += 0.1;
690
+ if (task.type === 'testing' && caps.testing)
691
+ score += 0.1;
692
+ if (task.type === 'coordination' && caps.coordination)
693
+ score += 0.1;
694
+ return Math.min(score, 1.0);
695
+ }
696
+ calculatePerformanceScore(agent, patterns) {
697
+ // Base on agent's success rate
698
+ let score = agent.metrics.successRate;
699
+ // Boost if patterns suggest this agent type is successful
700
+ const agentDomain = this.getAgentDomain(agent);
701
+ for (const pattern of patterns) {
702
+ if (pattern.strategy.toLowerCase().includes(agentDomain)) {
703
+ score += pattern.successRate * 0.1;
704
+ }
705
+ }
706
+ return Math.min(score, 1.0);
707
+ }
708
+ getAgentDomain(agent) {
709
+ // Determine domain from agent type
710
+ switch (agent.type) {
711
+ case 'queen':
712
+ return 'queen';
713
+ case 'specialist':
714
+ return 'security';
715
+ case 'architect':
716
+ return 'core';
717
+ case 'coder':
718
+ return 'integration';
719
+ case 'tester':
720
+ return 'support';
721
+ default:
722
+ return 'core';
723
+ }
724
+ }
725
+ selectPrimaryAgent(task, scores, analysis) {
726
+ // Prefer agent from recommended domain
727
+ const domainAgents = scores.filter(s => s.domain === analysis.recommendedDomain);
728
+ // Fall back to best overall if no domain match
729
+ const bestScore = domainAgents.length > 0 ? domainAgents[0] : scores[0];
730
+ return {
731
+ agentId: bestScore.agentId,
732
+ domain: bestScore.domain,
733
+ taskId: task.id.id,
734
+ score: bestScore.totalScore,
735
+ assignedAt: new Date(),
736
+ };
737
+ }
738
+ selectBackupAgents(task, scores, primary) {
739
+ const backups = [];
740
+ // Select up to 2 backup agents
741
+ for (const score of scores) {
742
+ if (score.agentId === primary.agentId)
743
+ continue;
744
+ if (score.totalScore < 0.3)
745
+ continue;
746
+ if (backups.length >= 2)
747
+ break;
748
+ backups.push({
749
+ agentId: score.agentId,
750
+ domain: score.domain,
751
+ taskId: task.id.id,
752
+ score: score.totalScore,
753
+ assignedAt: new Date(),
754
+ });
755
+ }
756
+ return backups;
757
+ }
758
+ createParallelAssignments(subtasks, scores) {
759
+ const assignments = [];
760
+ for (const subtask of subtasks) {
761
+ // Find best agent for this subtask's domain
762
+ const domainScores = scores.filter(s => s.domain === subtask.recommendedDomain);
763
+ const bestScore = domainScores.length > 0 ? domainScores[0] : scores[0];
764
+ assignments.push({
765
+ subtaskId: subtask.id,
766
+ agentId: bestScore.agentId,
767
+ domain: subtask.recommendedDomain,
768
+ dependencies: subtask.dependencies,
769
+ });
770
+ }
771
+ return assignments;
772
+ }
773
+ determineExecutionStrategy(analysis) {
774
+ const subtaskCount = analysis.subtasks.length;
775
+ if (subtaskCount === 0) {
776
+ return 'sequential';
777
+ }
778
+ // Check for dependencies
779
+ const hasDependencies = analysis.subtasks.some(st => st.dependencies.length > 0);
780
+ if (!hasDependencies && subtaskCount > 2) {
781
+ return 'parallel';
782
+ }
783
+ if (hasDependencies && subtaskCount > 3) {
784
+ return 'pipeline';
785
+ }
786
+ if (analysis.complexity > 0.7) {
787
+ return 'fan-out-fan-in';
788
+ }
789
+ return 'hybrid';
790
+ }
791
+ async executeDelegation(plan) {
792
+ // Delegate to the primary agent
793
+ await this.swarm.assignTaskToDomain(plan.taskId, plan.primaryAgent.domain);
794
+ // Notify about the delegation
795
+ await this.swarm.broadcastMessage({
796
+ type: 'delegation',
797
+ planId: plan.planId,
798
+ taskId: plan.taskId,
799
+ primaryAgent: plan.primaryAgent.agentId,
800
+ strategy: plan.strategy,
801
+ }, 'normal');
802
+ }
803
+ // ===========================================================================
804
+ // Swarm Health Monitoring
805
+ // ===========================================================================
806
+ /**
807
+ * Monitor swarm health and detect issues
808
+ *
809
+ * @returns Health report
810
+ */
811
+ async monitorSwarmHealth() {
812
+ this.reportCounter++;
813
+ const reportId = `health_${Date.now()}_${this.reportCounter}`;
814
+ const agents = this.swarm.getAllAgents();
815
+ const status = this.swarm.getStatus();
816
+ const metrics = this.swarm.getMetrics();
817
+ // Compute domain health
818
+ const domainHealth = this.computeDomainHealth(status.domains);
819
+ // Compute agent health
820
+ const agentHealth = this.computeAgentHealth(agents);
821
+ // Detect bottlenecks
822
+ const bottlenecks = this.detectBottlenecks(status, agents, metrics);
823
+ // Generate alerts
824
+ const alerts = this.generateAlerts(bottlenecks, agentHealth, metrics);
825
+ // Overall health score
826
+ const overallHealth = this.calculateOverallHealth(domainHealth, agentHealth, bottlenecks);
827
+ // Generate recommendations
828
+ const recommendations = this.generateRecommendations(bottlenecks, overallHealth);
829
+ // Compile health metrics
830
+ const healthMetrics = {
831
+ totalAgents: agents.length,
832
+ activeAgents: agents.filter(a => a.status === 'idle' || a.status === 'busy').length,
833
+ idleAgents: agents.filter(a => a.status === 'idle').length,
834
+ errorAgents: agents.filter(a => a.status === 'error').length,
835
+ totalTasks: metrics.totalTasks,
836
+ completedTasks: metrics.completedTasks,
837
+ failedTasks: metrics.failedTasks,
838
+ avgTaskDurationMs: metrics.avgTaskDurationMs,
839
+ taskThroughputPerMin: metrics.completedTasks / Math.max(metrics.uptime / 60, 1),
840
+ consensusSuccessRate: metrics.consensusSuccessRate,
841
+ };
842
+ const report = {
843
+ reportId,
844
+ timestamp: new Date(),
845
+ overallHealth,
846
+ domainHealth,
847
+ agentHealth,
848
+ bottlenecks,
849
+ alerts,
850
+ metrics: healthMetrics,
851
+ recommendations,
852
+ };
853
+ // Store in history
854
+ this.healthHistory.push(report);
855
+ if (this.healthHistory.length > 100) {
856
+ this.healthHistory.shift();
857
+ }
858
+ this.lastHealthReport = report;
859
+ this.emitEvent('queen.health.report', {
860
+ reportId,
861
+ overallHealth,
862
+ bottleneckCount: bottlenecks.length,
863
+ alertCount: alerts.length,
864
+ });
865
+ return report;
866
+ }
867
+ computeDomainHealth(domains) {
868
+ const health = new Map();
869
+ for (const domain of domains) {
870
+ const utilization = domain.agentCount > 0
871
+ ? domain.busyAgents / domain.agentCount
872
+ : 0;
873
+ const queuePressure = domain.tasksQueued > 5 ? 0.3 : domain.tasksQueued * 0.05;
874
+ const domainHealth = Math.max(0, 1 - queuePressure - (1 - utilization) * 0.2);
875
+ health.set(domain.name, {
876
+ domain: domain.name,
877
+ health: domainHealth,
878
+ activeAgents: domain.availableAgents + domain.busyAgents,
879
+ totalAgents: domain.agentCount,
880
+ queuedTasks: domain.tasksQueued,
881
+ avgResponseTimeMs: 0, // Would need tracking
882
+ errorRate: 0, // Would need tracking
883
+ });
884
+ }
885
+ return health;
886
+ }
887
+ computeAgentHealth(agents) {
888
+ return agents.map(agent => ({
889
+ agentId: agent.id.id,
890
+ domain: this.getAgentDomain(agent),
891
+ health: agent.health,
892
+ status: agent.status,
893
+ lastHeartbeat: agent.lastHeartbeat,
894
+ currentLoad: agent.workload,
895
+ recentErrors: agent.metrics.tasksFailed,
896
+ }));
897
+ }
898
+ detectBottlenecks(status, agents, metrics) {
899
+ const bottlenecks = [];
900
+ // Check domain queues
901
+ for (const domain of status.domains) {
902
+ if (domain.tasksQueued > this.config.bottleneckThresholds.queueDepth) {
903
+ bottlenecks.push({
904
+ type: 'domain',
905
+ location: domain.name,
906
+ severity: domain.tasksQueued > 20 ? 'critical' : 'high',
907
+ description: `High task queue depth in ${domain.name} domain`,
908
+ impact: `${domain.tasksQueued} tasks waiting for processing`,
909
+ suggestedAction: `Consider scaling ${domain.name} domain agents`,
910
+ });
911
+ }
912
+ }
913
+ // Check error agents
914
+ const errorAgents = agents.filter(a => a.status === 'error');
915
+ if (errorAgents.length > 0) {
916
+ bottlenecks.push({
917
+ type: 'agent',
918
+ location: errorAgents.map(a => a.id.id).join(', '),
919
+ severity: errorAgents.length > 3 ? 'critical' : 'medium',
920
+ description: `${errorAgents.length} agents in error state`,
921
+ impact: 'Reduced processing capacity',
922
+ suggestedAction: 'Investigate and recover error agents',
923
+ });
924
+ }
925
+ // Check coordination latency
926
+ if (metrics.coordinationLatencyMs > this.config.bottleneckThresholds.responseTimeMs) {
927
+ bottlenecks.push({
928
+ type: 'resource',
929
+ location: 'coordination',
930
+ severity: 'high',
931
+ description: 'High coordination latency detected',
932
+ impact: `Current latency: ${metrics.coordinationLatencyMs}ms`,
933
+ suggestedAction: 'Optimize coordination or reduce concurrent tasks',
934
+ });
935
+ }
936
+ return bottlenecks;
937
+ }
938
+ generateAlerts(bottlenecks, agentHealth, metrics) {
939
+ const alerts = [];
940
+ // Generate alerts for critical bottlenecks
941
+ for (const bottleneck of bottlenecks) {
942
+ if (bottleneck.severity === 'critical' || bottleneck.severity === 'high') {
943
+ alerts.push({
944
+ alertId: `alert_${Date.now()}_${alerts.length}`,
945
+ type: bottleneck.severity === 'critical' ? 'critical' : 'error',
946
+ source: bottleneck.location,
947
+ message: bottleneck.description,
948
+ timestamp: new Date(),
949
+ acknowledged: false,
950
+ });
951
+ }
952
+ }
953
+ // Alert on low overall agent health
954
+ const avgHealth = agentHealth.length > 0
955
+ ? agentHealth.reduce((sum, a) => sum + a.health, 0) / agentHealth.length
956
+ : 1.0;
957
+ if (avgHealth < 0.5) {
958
+ alerts.push({
959
+ alertId: `alert_${Date.now()}_health`,
960
+ type: avgHealth < 0.3 ? 'critical' : 'warning',
961
+ source: 'swarm',
962
+ message: `Low average agent health: ${(avgHealth * 100).toFixed(1)}%`,
963
+ timestamp: new Date(),
964
+ acknowledged: false,
965
+ });
966
+ }
967
+ // Alert on high failure rate
968
+ const failureRate = metrics.totalTasks > 0
969
+ ? metrics.failedTasks / metrics.totalTasks
970
+ : 0;
971
+ if (failureRate > this.config.bottleneckThresholds.errorRate) {
972
+ alerts.push({
973
+ alertId: `alert_${Date.now()}_failures`,
974
+ type: failureRate > 0.2 ? 'critical' : 'warning',
975
+ source: 'tasks',
976
+ message: `High task failure rate: ${(failureRate * 100).toFixed(1)}%`,
977
+ timestamp: new Date(),
978
+ acknowledged: false,
979
+ });
980
+ }
981
+ return alerts;
982
+ }
983
+ calculateOverallHealth(domainHealth, agentHealth, bottlenecks) {
984
+ // Average domain health
985
+ const domainHealthAvg = domainHealth.size > 0
986
+ ? Array.from(domainHealth.values()).reduce((sum, d) => sum + d.health, 0) / domainHealth.size
987
+ : 1.0;
988
+ // Average agent health
989
+ const agentHealthAvg = agentHealth.length > 0
990
+ ? agentHealth.reduce((sum, a) => sum + a.health, 0) / agentHealth.length
991
+ : 1.0;
992
+ // Bottleneck penalty
993
+ const bottleneckPenalty = bottlenecks.reduce((penalty, b) => {
994
+ switch (b.severity) {
995
+ case 'critical': return penalty + 0.2;
996
+ case 'high': return penalty + 0.1;
997
+ case 'medium': return penalty + 0.05;
998
+ case 'low': return penalty + 0.02;
999
+ default: return penalty;
1000
+ }
1001
+ }, 0);
1002
+ const overallHealth = (domainHealthAvg * 0.4 + agentHealthAvg * 0.4) - bottleneckPenalty;
1003
+ return Math.max(0, Math.min(1, overallHealth));
1004
+ }
1005
+ generateRecommendations(bottlenecks, overallHealth) {
1006
+ const recommendations = [];
1007
+ // Add bottleneck-specific recommendations
1008
+ for (const bottleneck of bottlenecks) {
1009
+ recommendations.push(bottleneck.suggestedAction);
1010
+ }
1011
+ // General recommendations based on health
1012
+ if (overallHealth < 0.5) {
1013
+ recommendations.push('Consider reducing task load or adding more agents');
1014
+ }
1015
+ if (overallHealth < 0.3) {
1016
+ recommendations.push('URGENT: Investigate system-wide issues immediately');
1017
+ }
1018
+ return [...new Set(recommendations)]; // Deduplicate
1019
+ }
1020
+ startHealthMonitoring() {
1021
+ this.healthCheckInterval = setInterval(async () => {
1022
+ try {
1023
+ await this.monitorSwarmHealth();
1024
+ }
1025
+ catch (error) {
1026
+ this.emitEvent('queen.health.error', { error: String(error) });
1027
+ }
1028
+ }, this.config.healthCheckIntervalMs);
1029
+ }
1030
+ stopHealthMonitoring() {
1031
+ if (this.healthCheckInterval) {
1032
+ clearInterval(this.healthCheckInterval);
1033
+ this.healthCheckInterval = undefined;
1034
+ }
1035
+ }
1036
+ // ===========================================================================
1037
+ // Consensus Coordination
1038
+ // ===========================================================================
1039
+ /**
1040
+ * Coordinate consensus for a decision
1041
+ *
1042
+ * @param decision - Decision requiring consensus
1043
+ * @returns Consensus result
1044
+ */
1045
+ async coordinateConsensus(decision) {
1046
+ const startTime = performance.now();
1047
+ this.decisionCounter++;
1048
+ decision.decisionId = `decision_${Date.now()}_${this.decisionCounter}`;
1049
+ // Store active decision
1050
+ this.activeDecisions.set(decision.decisionId, decision);
1051
+ try {
1052
+ let result;
1053
+ switch (decision.requiredConsensus) {
1054
+ case 'queen-override':
1055
+ // Queen can make unilateral decisions for certain types
1056
+ result = this.queenOverride(decision);
1057
+ break;
1058
+ case 'unanimous':
1059
+ result = await this.unanimousConsensus(decision);
1060
+ break;
1061
+ case 'supermajority':
1062
+ result = await this.supermajorityConsensus(decision);
1063
+ break;
1064
+ case 'weighted':
1065
+ result = await this.weightedConsensus(decision);
1066
+ break;
1067
+ case 'majority':
1068
+ default:
1069
+ result = await this.majorityConsensus(decision);
1070
+ }
1071
+ // Record latency
1072
+ const latency = performance.now() - startTime;
1073
+ this.consensusLatencies.push(latency);
1074
+ if (this.consensusLatencies.length > 100) {
1075
+ this.consensusLatencies.shift();
1076
+ }
1077
+ this.emitEvent('queen.consensus.completed', {
1078
+ decisionId: decision.decisionId,
1079
+ type: decision.requiredConsensus,
1080
+ approved: result.approved,
1081
+ approvalRate: result.approvalRate,
1082
+ latencyMs: latency,
1083
+ });
1084
+ return result;
1085
+ }
1086
+ finally {
1087
+ this.activeDecisions.delete(decision.decisionId);
1088
+ }
1089
+ }
1090
+ queenOverride(decision) {
1091
+ // Queen can make immediate decisions for:
1092
+ // - Emergency actions
1093
+ // - Agent termination
1094
+ // - Priority overrides
1095
+ const allowedTypes = ['emergency-action', 'agent-termination', 'priority-override'];
1096
+ if (!allowedTypes.includes(decision.type)) {
1097
+ throw new Error(`Queen override not allowed for decision type: ${decision.type}`);
1098
+ }
1099
+ return {
1100
+ proposalId: decision.decisionId,
1101
+ approved: true,
1102
+ approvalRate: 1.0,
1103
+ participationRate: 1.0,
1104
+ finalValue: decision.proposal,
1105
+ rounds: 1,
1106
+ durationMs: 0,
1107
+ };
1108
+ }
1109
+ async majorityConsensus(decision) {
1110
+ // Use swarm's consensus engine with majority threshold
1111
+ const result = await this.swarm.proposeConsensus({
1112
+ decision,
1113
+ threshold: 0.51,
1114
+ timeout: this.config.consensusTimeouts.majority,
1115
+ });
1116
+ return result;
1117
+ }
1118
+ async supermajorityConsensus(decision) {
1119
+ // Use swarm's consensus engine with 2/3 threshold
1120
+ const result = await this.swarm.proposeConsensus({
1121
+ decision,
1122
+ threshold: 0.67,
1123
+ timeout: this.config.consensusTimeouts.supermajority,
1124
+ });
1125
+ return result;
1126
+ }
1127
+ async unanimousConsensus(decision) {
1128
+ // Use swarm's consensus engine with unanimous requirement
1129
+ const result = await this.swarm.proposeConsensus({
1130
+ decision,
1131
+ threshold: 1.0,
1132
+ timeout: this.config.consensusTimeouts.unanimous,
1133
+ });
1134
+ return result;
1135
+ }
1136
+ async weightedConsensus(decision) {
1137
+ // Weighted consensus based on agent performance
1138
+ // For now, delegate to the standard consensus with metadata
1139
+ const agents = this.swarm.getAllAgents();
1140
+ const weights = new Map();
1141
+ for (const agent of agents) {
1142
+ const weight = agent.metrics.successRate * agent.health;
1143
+ weights.set(agent.id.id, weight);
1144
+ }
1145
+ const result = await this.swarm.proposeConsensus({
1146
+ decision,
1147
+ weights: Object.fromEntries(weights),
1148
+ threshold: 0.51,
1149
+ timeout: this.config.consensusTimeouts.majority,
1150
+ });
1151
+ return result;
1152
+ }
1153
+ // ===========================================================================
1154
+ // Learning from Outcomes
1155
+ // ===========================================================================
1156
+ /**
1157
+ * Record task outcome for learning
1158
+ *
1159
+ * @param task - Completed task
1160
+ * @param result - Task result
1161
+ */
1162
+ async recordOutcome(task, result) {
1163
+ // Store in outcome history
1164
+ this.outcomeHistory.push(result);
1165
+ if (this.outcomeHistory.length > 1000) {
1166
+ this.outcomeHistory.shift();
1167
+ }
1168
+ // Learn from outcome if neural system available
1169
+ if (this.neural && this.config.enableLearning) {
1170
+ await this.learnFromOutcome(task, result);
1171
+ }
1172
+ // Store in memory service if available
1173
+ if (this.memory) {
1174
+ await this.storeOutcomeMemory(task, result);
1175
+ }
1176
+ this.emitEvent('queen.outcome.recorded', {
1177
+ taskId: task.id.id,
1178
+ success: result.success,
1179
+ durationMs: result.durationMs,
1180
+ qualityScore: result.metrics.qualityScore,
1181
+ });
1182
+ }
1183
+ async learnFromOutcome(task, result) {
1184
+ if (!this.neural)
1185
+ return;
1186
+ // Create trajectory for this task
1187
+ const trajectoryId = this.neural.beginTask(task.description || task.name, result.domain);
1188
+ // Record the execution step
1189
+ const embedding = this.createSimpleEmbedding(task.description || task.name);
1190
+ const reward = result.success
1191
+ ? result.metrics.qualityScore * 0.8 + 0.2
1192
+ : result.metrics.qualityScore * 0.3;
1193
+ this.neural.recordStep(trajectoryId, `executed_${task.type}_in_${result.domain}`, reward, embedding);
1194
+ // Complete the task trajectory
1195
+ await this.neural.completeTask(trajectoryId, result.metrics.qualityScore);
1196
+ }
1197
+ async storeOutcomeMemory(task, result) {
1198
+ if (!this.memory)
1199
+ return;
1200
+ try {
1201
+ await this.memory.store({
1202
+ key: `outcome_${task.id.id}`,
1203
+ content: this.formatOutcomeContent(task, result),
1204
+ namespace: 'queen-outcomes',
1205
+ tags: [
1206
+ task.type,
1207
+ result.domain,
1208
+ result.success ? 'success' : 'failure',
1209
+ ],
1210
+ metadata: {
1211
+ taskId: task.id.id,
1212
+ success: result.success,
1213
+ durationMs: result.durationMs,
1214
+ qualityScore: result.metrics.qualityScore,
1215
+ agentId: result.agentId,
1216
+ },
1217
+ });
1218
+ }
1219
+ catch (error) {
1220
+ // Log but don't fail - memory storage is optional
1221
+ this.emitEvent('queen.memory.error', { error: String(error) });
1222
+ }
1223
+ }
1224
+ formatOutcomeContent(task, result) {
1225
+ return [
1226
+ `Task: ${task.name}`,
1227
+ `Type: ${task.type}`,
1228
+ `Domain: ${result.domain}`,
1229
+ `Agent: ${result.agentId}`,
1230
+ `Success: ${result.success}`,
1231
+ `Duration: ${result.durationMs}ms`,
1232
+ `Quality: ${result.metrics.qualityScore}`,
1233
+ `Description: ${task.description || 'N/A'}`,
1234
+ ].join('\n');
1235
+ }
1236
+ // ===========================================================================
1237
+ // Utility Methods
1238
+ // ===========================================================================
1239
+ /**
1240
+ * Get the last health report
1241
+ */
1242
+ getLastHealthReport() {
1243
+ return this.lastHealthReport;
1244
+ }
1245
+ /**
1246
+ * Get outcome history
1247
+ */
1248
+ getOutcomeHistory() {
1249
+ return [...this.outcomeHistory];
1250
+ }
1251
+ /**
1252
+ * Get analysis cache
1253
+ */
1254
+ getAnalysisCache() {
1255
+ return new Map(this.analysisCache);
1256
+ }
1257
+ /**
1258
+ * Get delegation plans
1259
+ */
1260
+ getDelegationPlans() {
1261
+ return new Map(this.delegationPlans);
1262
+ }
1263
+ /**
1264
+ * Get performance statistics
1265
+ */
1266
+ getPerformanceStats() {
1267
+ const avg = (arr) => arr.length > 0
1268
+ ? arr.reduce((a, b) => a + b, 0) / arr.length
1269
+ : 0;
1270
+ return {
1271
+ avgAnalysisLatencyMs: avg(this.analysisLatencies),
1272
+ avgDelegationLatencyMs: avg(this.delegationLatencies),
1273
+ avgConsensusLatencyMs: avg(this.consensusLatencies),
1274
+ totalAnalyses: this.analysisCounter,
1275
+ totalDelegations: this.planCounter,
1276
+ totalDecisions: this.decisionCounter,
1277
+ };
1278
+ }
1279
+ /**
1280
+ * Check if learning is enabled
1281
+ */
1282
+ isLearningEnabled() {
1283
+ return this.config.enableLearning && !!this.neural;
1284
+ }
1285
+ emitEvent(type, data) {
1286
+ const event = {
1287
+ id: `event_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`,
1288
+ type,
1289
+ source: 'queen-coordinator',
1290
+ timestamp: new Date(),
1291
+ data,
1292
+ };
1293
+ this.emit(type, event);
1294
+ this.emit('event', event);
1295
+ }
1296
+ }
1297
+ // =============================================================================
1298
+ // Factory Function
1299
+ // =============================================================================
1300
+ /**
1301
+ * Create a Queen Coordinator instance
1302
+ */
1303
+ export function createQueenCoordinator(swarm, config, neural, memory) {
1304
+ return new QueenCoordinator(swarm, config, neural, memory);
1305
+ }
1306
+ export default QueenCoordinator;
1307
+ //# sourceMappingURL=queen-coordinator.js.map