@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,2024 @@
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
+
24
+ import { EventEmitter } from 'events';
25
+ import type {
26
+ AgentState,
27
+ AgentType,
28
+ AgentId,
29
+ TaskDefinition,
30
+ TaskType,
31
+ TaskPriority,
32
+ TaskStatus,
33
+ CoordinatorMetrics,
34
+ ConsensusResult,
35
+ SwarmEvent,
36
+ SwarmEventType,
37
+ } from './types.js';
38
+ import type { AgentDomain, DomainConfig, DomainStatus } from './unified-coordinator.js';
39
+
40
+ // =============================================================================
41
+ // Types
42
+ // =============================================================================
43
+
44
+ /**
45
+ * Task analysis result from the Queen
46
+ */
47
+ export interface TaskAnalysis {
48
+ /** Unique analysis ID */
49
+ analysisId: string;
50
+ /** Original task ID */
51
+ taskId: string;
52
+ /** Task complexity score (0-1) */
53
+ complexity: number;
54
+ /** Estimated duration in milliseconds */
55
+ estimatedDurationMs: number;
56
+ /** Required capabilities for this task */
57
+ requiredCapabilities: string[];
58
+ /** Recommended domain for execution */
59
+ recommendedDomain: AgentDomain;
60
+ /** Sub-tasks if decomposition is needed */
61
+ subtasks: SubTask[];
62
+ /** Patterns found from ReasoningBank */
63
+ matchedPatterns: MatchedPattern[];
64
+ /** Resource requirements */
65
+ resourceRequirements: ResourceRequirements;
66
+ /** Confidence in this analysis (0-1) */
67
+ confidence: number;
68
+ /** Analysis timestamp */
69
+ timestamp: Date;
70
+ }
71
+
72
+ /**
73
+ * Sub-task from task decomposition
74
+ */
75
+ export interface SubTask {
76
+ id: string;
77
+ name: string;
78
+ description: string;
79
+ type: TaskType;
80
+ priority: TaskPriority;
81
+ dependencies: string[];
82
+ estimatedDurationMs: number;
83
+ requiredCapabilities: string[];
84
+ recommendedDomain: AgentDomain;
85
+ }
86
+
87
+ /**
88
+ * Pattern matched from ReasoningBank
89
+ */
90
+ export interface MatchedPattern {
91
+ patternId: string;
92
+ strategy: string;
93
+ successRate: number;
94
+ relevanceScore: number;
95
+ keyLearnings: string[];
96
+ }
97
+
98
+ /**
99
+ * Resource requirements for a task
100
+ */
101
+ export interface ResourceRequirements {
102
+ minAgents: number;
103
+ maxAgents: number;
104
+ memoryMb: number;
105
+ cpuIntensive: boolean;
106
+ ioIntensive: boolean;
107
+ networkRequired: boolean;
108
+ }
109
+
110
+ /**
111
+ * Delegation plan for task execution
112
+ */
113
+ export interface DelegationPlan {
114
+ /** Plan ID */
115
+ planId: string;
116
+ /** Task ID being delegated */
117
+ taskId: string;
118
+ /** Analysis that informed this plan */
119
+ analysisId: string;
120
+ /** Primary agent assignment */
121
+ primaryAgent: AgentAssignment;
122
+ /** Backup agents for failover */
123
+ backupAgents: AgentAssignment[];
124
+ /** Parallel sub-task assignments */
125
+ parallelAssignments: ParallelAssignment[];
126
+ /** Execution strategy */
127
+ strategy: ExecutionStrategy;
128
+ /** Estimated completion time */
129
+ estimatedCompletionMs: number;
130
+ /** Plan creation timestamp */
131
+ timestamp: Date;
132
+ }
133
+
134
+ /**
135
+ * Agent assignment in a delegation plan
136
+ */
137
+ export interface AgentAssignment {
138
+ agentId: string;
139
+ domain: AgentDomain;
140
+ taskId: string;
141
+ score: number;
142
+ assignedAt: Date;
143
+ }
144
+
145
+ /**
146
+ * Parallel task assignment
147
+ */
148
+ export interface ParallelAssignment {
149
+ subtaskId: string;
150
+ agentId: string;
151
+ domain: AgentDomain;
152
+ dependencies: string[];
153
+ }
154
+
155
+ /**
156
+ * Execution strategy for delegation
157
+ */
158
+ export type ExecutionStrategy =
159
+ | 'sequential'
160
+ | 'parallel'
161
+ | 'pipeline'
162
+ | 'fan-out-fan-in'
163
+ | 'hybrid';
164
+
165
+ /**
166
+ * Agent score for task assignment
167
+ */
168
+ export interface AgentScore {
169
+ agentId: string;
170
+ domain: AgentDomain;
171
+ totalScore: number;
172
+ capabilityScore: number;
173
+ loadScore: number;
174
+ performanceScore: number;
175
+ healthScore: number;
176
+ availabilityScore: number;
177
+ }
178
+
179
+ /**
180
+ * Health report for the swarm
181
+ */
182
+ export interface HealthReport {
183
+ /** Report ID */
184
+ reportId: string;
185
+ /** Report timestamp */
186
+ timestamp: Date;
187
+ /** Overall swarm health (0-1) */
188
+ overallHealth: number;
189
+ /** Status of each domain */
190
+ domainHealth: Map<AgentDomain, DomainHealthStatus>;
191
+ /** Individual agent health */
192
+ agentHealth: AgentHealthEntry[];
193
+ /** Detected bottlenecks */
194
+ bottlenecks: Bottleneck[];
195
+ /** Active alerts */
196
+ alerts: HealthAlert[];
197
+ /** Performance metrics */
198
+ metrics: HealthMetrics;
199
+ /** Recommendations for improvement */
200
+ recommendations: string[];
201
+ }
202
+
203
+ /**
204
+ * Domain health status
205
+ */
206
+ export interface DomainHealthStatus {
207
+ domain: AgentDomain;
208
+ health: number;
209
+ activeAgents: number;
210
+ totalAgents: number;
211
+ queuedTasks: number;
212
+ avgResponseTimeMs: number;
213
+ errorRate: number;
214
+ }
215
+
216
+ /**
217
+ * Agent health entry
218
+ */
219
+ export interface AgentHealthEntry {
220
+ agentId: string;
221
+ domain: AgentDomain;
222
+ health: number;
223
+ status: string;
224
+ lastHeartbeat: Date;
225
+ currentLoad: number;
226
+ recentErrors: number;
227
+ }
228
+
229
+ /**
230
+ * Bottleneck detection result
231
+ */
232
+ export interface Bottleneck {
233
+ type: 'agent' | 'domain' | 'task' | 'resource';
234
+ location: string;
235
+ severity: 'low' | 'medium' | 'high' | 'critical';
236
+ description: string;
237
+ impact: string;
238
+ suggestedAction: string;
239
+ }
240
+
241
+ /**
242
+ * Health alert
243
+ */
244
+ export interface HealthAlert {
245
+ alertId: string;
246
+ type: 'warning' | 'error' | 'critical';
247
+ source: string;
248
+ message: string;
249
+ timestamp: Date;
250
+ acknowledged: boolean;
251
+ }
252
+
253
+ /**
254
+ * Health metrics
255
+ */
256
+ export interface HealthMetrics {
257
+ totalAgents: number;
258
+ activeAgents: number;
259
+ idleAgents: number;
260
+ errorAgents: number;
261
+ totalTasks: number;
262
+ completedTasks: number;
263
+ failedTasks: number;
264
+ avgTaskDurationMs: number;
265
+ taskThroughputPerMin: number;
266
+ consensusSuccessRate: number;
267
+ }
268
+
269
+ /**
270
+ * Decision requiring consensus
271
+ */
272
+ export interface Decision {
273
+ decisionId: string;
274
+ type: DecisionType;
275
+ proposal: unknown;
276
+ requiredConsensus: ConsensusType;
277
+ timeout: number;
278
+ initiator: string;
279
+ metadata: Record<string, unknown>;
280
+ }
281
+
282
+ /**
283
+ * Decision types
284
+ */
285
+ export type DecisionType =
286
+ | 'task-assignment'
287
+ | 'resource-allocation'
288
+ | 'topology-change'
289
+ | 'agent-termination'
290
+ | 'priority-override'
291
+ | 'emergency-action';
292
+
293
+ /**
294
+ * Consensus types
295
+ */
296
+ export type ConsensusType =
297
+ | 'majority'
298
+ | 'supermajority'
299
+ | 'unanimous'
300
+ | 'weighted'
301
+ | 'queen-override';
302
+
303
+ /**
304
+ * Task result for learning
305
+ */
306
+ export interface TaskResult {
307
+ taskId: string;
308
+ success: boolean;
309
+ output?: unknown;
310
+ error?: string;
311
+ durationMs: number;
312
+ agentId: string;
313
+ domain: AgentDomain;
314
+ metrics: TaskMetrics;
315
+ }
316
+
317
+ /**
318
+ * Task execution metrics
319
+ */
320
+ export interface TaskMetrics {
321
+ startTime: Date;
322
+ endTime: Date;
323
+ retries: number;
324
+ resourceUsage: {
325
+ memoryMb: number;
326
+ cpuPercent: number;
327
+ };
328
+ stepsCompleted: number;
329
+ qualityScore: number;
330
+ }
331
+
332
+ /**
333
+ * Queen Coordinator configuration
334
+ */
335
+ export interface QueenCoordinatorConfig {
336
+ /** Enable ReasoningBank integration */
337
+ enableLearning: boolean;
338
+ /** Number of patterns to retrieve for analysis */
339
+ patternRetrievalK: number;
340
+ /** Minimum pattern relevance threshold */
341
+ patternThreshold: number;
342
+ /** Task complexity thresholds */
343
+ complexityThresholds: {
344
+ simple: number;
345
+ moderate: number;
346
+ complex: number;
347
+ };
348
+ /** Health check interval in ms */
349
+ healthCheckIntervalMs: number;
350
+ /** Bottleneck detection thresholds */
351
+ bottleneckThresholds: {
352
+ queueDepth: number;
353
+ errorRate: number;
354
+ responseTimeMs: number;
355
+ };
356
+ /** Consensus timeouts */
357
+ consensusTimeouts: {
358
+ majority: number;
359
+ supermajority: number;
360
+ unanimous: number;
361
+ };
362
+ /** Enable automatic failover */
363
+ enableFailover: boolean;
364
+ /** Maximum delegation attempts */
365
+ maxDelegationAttempts: number;
366
+ }
367
+
368
+ /**
369
+ * Default Queen Coordinator configuration
370
+ */
371
+ const DEFAULT_CONFIG: QueenCoordinatorConfig = {
372
+ enableLearning: true,
373
+ patternRetrievalK: 5,
374
+ patternThreshold: 0.6,
375
+ complexityThresholds: {
376
+ simple: 0.3,
377
+ moderate: 0.6,
378
+ complex: 0.85,
379
+ },
380
+ healthCheckIntervalMs: 10000,
381
+ bottleneckThresholds: {
382
+ queueDepth: 10,
383
+ errorRate: 0.1,
384
+ responseTimeMs: 5000,
385
+ },
386
+ consensusTimeouts: {
387
+ majority: 5000,
388
+ supermajority: 10000,
389
+ unanimous: 30000,
390
+ },
391
+ enableFailover: true,
392
+ maxDelegationAttempts: 3,
393
+ };
394
+
395
+ // =============================================================================
396
+ // Interfaces for Dependencies
397
+ // =============================================================================
398
+
399
+ /**
400
+ * Interface for swarm coordinator interactions
401
+ */
402
+ export interface ISwarmCoordinator {
403
+ getAgentsByDomain(domain: AgentDomain): AgentState[];
404
+ getAllAgents(): AgentState[];
405
+ getAvailableAgents(): AgentState[];
406
+ getMetrics(): CoordinatorMetrics;
407
+ getDomainConfigs(): Map<AgentDomain, DomainConfig>;
408
+ getStatus(): {
409
+ domains: DomainStatus[];
410
+ metrics: CoordinatorMetrics;
411
+ };
412
+ assignTaskToDomain(taskId: string, domain: AgentDomain): Promise<string | undefined>;
413
+ proposeConsensus(value: unknown): Promise<ConsensusResult>;
414
+ broadcastMessage(payload: unknown, priority?: 'urgent' | 'high' | 'normal' | 'low'): Promise<void>;
415
+ }
416
+
417
+ /**
418
+ * Interface for neural learning system interactions
419
+ */
420
+ export interface INeuralLearningSystem {
421
+ initialize(): Promise<void>;
422
+ beginTask(context: string, domain?: string): string;
423
+ recordStep(trajectoryId: string, action: string, reward: number, stateEmbedding: Float32Array): void;
424
+ completeTask(trajectoryId: string, quality?: number): Promise<void>;
425
+ findPatterns(queryEmbedding: Float32Array, k?: number): Promise<PatternMatchResult[]>;
426
+ retrieveMemories(queryEmbedding: Float32Array, k?: number): Promise<MemoryRetrievalResult[]>;
427
+ triggerLearning(): Promise<void>;
428
+ }
429
+
430
+ /**
431
+ * Pattern match result from neural system
432
+ */
433
+ export interface PatternMatchResult {
434
+ patternId: string;
435
+ strategy: string;
436
+ successRate: number;
437
+ relevanceScore: number;
438
+ keyLearnings?: string[];
439
+ }
440
+
441
+ /**
442
+ * Memory retrieval result from neural system
443
+ */
444
+ export interface MemoryRetrievalResult {
445
+ memory: {
446
+ memoryId: string;
447
+ strategy: string;
448
+ quality: number;
449
+ keyLearnings: string[];
450
+ };
451
+ relevanceScore: number;
452
+ combinedScore: number;
453
+ }
454
+
455
+ /**
456
+ * Interface for memory service interactions
457
+ */
458
+ export interface IMemoryService {
459
+ semanticSearch(query: string, k?: number): Promise<SearchResultEntry[]>;
460
+ store(entry: MemoryStoreEntry): Promise<void>;
461
+ }
462
+
463
+ /**
464
+ * Search result entry from memory service
465
+ */
466
+ export interface SearchResultEntry {
467
+ entry: {
468
+ id: string;
469
+ content: string;
470
+ metadata: Record<string, unknown>;
471
+ };
472
+ score: number;
473
+ }
474
+
475
+ /**
476
+ * Memory store entry
477
+ */
478
+ export interface MemoryStoreEntry {
479
+ key: string;
480
+ content: string;
481
+ namespace: string;
482
+ tags: string[];
483
+ metadata: Record<string, unknown>;
484
+ }
485
+
486
+ // =============================================================================
487
+ // Queen Coordinator Class
488
+ // =============================================================================
489
+
490
+ /**
491
+ * Queen Coordinator - Central orchestrator for the 15-agent hive-mind swarm
492
+ *
493
+ * The Queen is responsible for:
494
+ * 1. Strategic task analysis and decomposition
495
+ * 2. Agent delegation with load balancing
496
+ * 3. Swarm health monitoring
497
+ * 4. Consensus coordination
498
+ * 5. Learning from outcomes
499
+ */
500
+ export class QueenCoordinator extends EventEmitter {
501
+ private config: QueenCoordinatorConfig;
502
+ private swarm: ISwarmCoordinator;
503
+ private neural?: INeuralLearningSystem;
504
+ private memory?: IMemoryService;
505
+
506
+ // Internal state
507
+ private analysisCache: Map<string, TaskAnalysis> = new Map();
508
+ private delegationPlans: Map<string, DelegationPlan> = new Map();
509
+ private activeDecisions: Map<string, Decision> = new Map();
510
+ private outcomeHistory: TaskResult[] = [];
511
+ private healthHistory: HealthReport[] = [];
512
+
513
+ // Counters for IDs
514
+ private analysisCounter = 0;
515
+ private planCounter = 0;
516
+ private reportCounter = 0;
517
+ private decisionCounter = 0;
518
+
519
+ // Health monitoring
520
+ private healthCheckInterval?: NodeJS.Timeout;
521
+ private lastHealthReport?: HealthReport;
522
+
523
+ // Performance tracking
524
+ private analysisLatencies: number[] = [];
525
+ private delegationLatencies: number[] = [];
526
+ private consensusLatencies: number[] = [];
527
+
528
+ constructor(
529
+ swarm: ISwarmCoordinator,
530
+ config: Partial<QueenCoordinatorConfig> = {},
531
+ neural?: INeuralLearningSystem,
532
+ memory?: IMemoryService
533
+ ) {
534
+ super();
535
+ this.swarm = swarm;
536
+ this.config = { ...DEFAULT_CONFIG, ...config };
537
+ this.neural = neural;
538
+ this.memory = memory;
539
+ }
540
+
541
+ // ===========================================================================
542
+ // Lifecycle
543
+ // ===========================================================================
544
+
545
+ /**
546
+ * Initialize the Queen Coordinator
547
+ */
548
+ async initialize(): Promise<void> {
549
+ // Initialize neural system if available
550
+ if (this.neural && this.config.enableLearning) {
551
+ await this.neural.initialize();
552
+ }
553
+
554
+ // Start health monitoring
555
+ this.startHealthMonitoring();
556
+
557
+ this.emitEvent('queen.initialized', {
558
+ config: this.config,
559
+ learningEnabled: this.config.enableLearning && !!this.neural,
560
+ });
561
+ }
562
+
563
+ /**
564
+ * Shutdown the Queen Coordinator
565
+ */
566
+ async shutdown(): Promise<void> {
567
+ this.stopHealthMonitoring();
568
+
569
+ // Trigger final learning if enabled
570
+ if (this.neural && this.config.enableLearning) {
571
+ await this.neural.triggerLearning();
572
+ }
573
+
574
+ this.emitEvent('queen.shutdown', {
575
+ totalAnalyses: this.analysisCounter,
576
+ totalPlans: this.planCounter,
577
+ totalDecisions: this.decisionCounter,
578
+ });
579
+ }
580
+
581
+ // ===========================================================================
582
+ // Strategic Task Analysis
583
+ // ===========================================================================
584
+
585
+ /**
586
+ * Analyze a task for optimal execution
587
+ *
588
+ * @param task - Task to analyze
589
+ * @returns Task analysis with recommendations
590
+ */
591
+ async analyzeTask(task: TaskDefinition): Promise<TaskAnalysis> {
592
+ const startTime = performance.now();
593
+
594
+ this.analysisCounter++;
595
+ const analysisId = `analysis_${Date.now()}_${this.analysisCounter}`;
596
+
597
+ // Decompose complex tasks
598
+ const subtasks = this.decomposeTask(task);
599
+
600
+ // Identify required capabilities
601
+ const requiredCapabilities = this.identifyRequiredCapabilities(task);
602
+
603
+ // Calculate complexity
604
+ const complexity = this.calculateComplexity(task, subtasks);
605
+
606
+ // Estimate duration
607
+ const estimatedDurationMs = this.estimateDuration(task, complexity, subtasks);
608
+
609
+ // Determine recommended domain
610
+ const recommendedDomain = this.determineOptimalDomain(task, requiredCapabilities);
611
+
612
+ // Find matching patterns from ReasoningBank
613
+ const matchedPatterns = await this.findMatchingPatterns(task);
614
+
615
+ // Estimate resource requirements
616
+ const resourceRequirements = this.estimateResources(task, complexity);
617
+
618
+ // Calculate confidence
619
+ const confidence = this.calculateAnalysisConfidence(
620
+ matchedPatterns,
621
+ complexity,
622
+ requiredCapabilities
623
+ );
624
+
625
+ const analysis: TaskAnalysis = {
626
+ analysisId,
627
+ taskId: task.id.id,
628
+ complexity,
629
+ estimatedDurationMs,
630
+ requiredCapabilities,
631
+ recommendedDomain,
632
+ subtasks,
633
+ matchedPatterns,
634
+ resourceRequirements,
635
+ confidence,
636
+ timestamp: new Date(),
637
+ };
638
+
639
+ // Cache the analysis
640
+ this.analysisCache.set(analysisId, analysis);
641
+
642
+ // Record latency
643
+ const latency = performance.now() - startTime;
644
+ this.analysisLatencies.push(latency);
645
+ if (this.analysisLatencies.length > 100) {
646
+ this.analysisLatencies.shift();
647
+ }
648
+
649
+ this.emitEvent('queen.task.analyzed', {
650
+ analysisId,
651
+ taskId: task.id.id,
652
+ complexity,
653
+ recommendedDomain,
654
+ patternsFound: matchedPatterns.length,
655
+ latencyMs: latency,
656
+ });
657
+
658
+ return analysis;
659
+ }
660
+
661
+ /**
662
+ * Decompose a complex task into subtasks
663
+ */
664
+ private decomposeTask(task: TaskDefinition): SubTask[] {
665
+ const subtasks: SubTask[] = [];
666
+
667
+ // Simple tasks don't need decomposition
668
+ if (this.isSimpleTask(task)) {
669
+ return subtasks;
670
+ }
671
+
672
+ // Decompose based on task type
673
+ switch (task.type) {
674
+ case 'coding':
675
+ subtasks.push(...this.decomposeCodingTask(task));
676
+ break;
677
+ case 'testing':
678
+ subtasks.push(...this.decomposeTestingTask(task));
679
+ break;
680
+ case 'research':
681
+ subtasks.push(...this.decomposeResearchTask(task));
682
+ break;
683
+ case 'coordination':
684
+ subtasks.push(...this.decomposeCoordinationTask(task));
685
+ break;
686
+ default:
687
+ // Generic decomposition
688
+ subtasks.push(...this.decomposeGenericTask(task));
689
+ }
690
+
691
+ return subtasks;
692
+ }
693
+
694
+ private isSimpleTask(task: TaskDefinition): boolean {
695
+ // Estimate if task is simple based on description length and type
696
+ const descLength = task.description?.length || 0;
697
+ const isSimpleType = ['documentation', 'review'].includes(task.type);
698
+ return descLength < 200 || isSimpleType;
699
+ }
700
+
701
+ private decomposeCodingTask(task: TaskDefinition): SubTask[] {
702
+ return [
703
+ {
704
+ id: `${task.id.id}_design`,
705
+ name: 'Design & Planning',
706
+ description: 'Design the solution architecture',
707
+ type: 'analysis',
708
+ priority: task.priority,
709
+ dependencies: [],
710
+ estimatedDurationMs: 10000,
711
+ requiredCapabilities: ['design', 'architecture'],
712
+ recommendedDomain: 'core',
713
+ },
714
+ {
715
+ id: `${task.id.id}_implement`,
716
+ name: 'Implementation',
717
+ description: 'Implement the designed solution',
718
+ type: 'coding',
719
+ priority: task.priority,
720
+ dependencies: [`${task.id.id}_design`],
721
+ estimatedDurationMs: 30000,
722
+ requiredCapabilities: ['coding', 'implementation'],
723
+ recommendedDomain: 'integration',
724
+ },
725
+ {
726
+ id: `${task.id.id}_test`,
727
+ name: 'Testing',
728
+ description: 'Test the implementation',
729
+ type: 'testing',
730
+ priority: task.priority,
731
+ dependencies: [`${task.id.id}_implement`],
732
+ estimatedDurationMs: 15000,
733
+ requiredCapabilities: ['testing', 'validation'],
734
+ recommendedDomain: 'support',
735
+ },
736
+ ];
737
+ }
738
+
739
+ private decomposeTestingTask(task: TaskDefinition): SubTask[] {
740
+ return [
741
+ {
742
+ id: `${task.id.id}_analyze`,
743
+ name: 'Test Analysis',
744
+ description: 'Analyze what needs to be tested',
745
+ type: 'analysis',
746
+ priority: task.priority,
747
+ dependencies: [],
748
+ estimatedDurationMs: 5000,
749
+ requiredCapabilities: ['analysis', 'testing'],
750
+ recommendedDomain: 'support',
751
+ },
752
+ {
753
+ id: `${task.id.id}_execute`,
754
+ name: 'Test Execution',
755
+ description: 'Execute the tests',
756
+ type: 'testing',
757
+ priority: task.priority,
758
+ dependencies: [`${task.id.id}_analyze`],
759
+ estimatedDurationMs: 20000,
760
+ requiredCapabilities: ['testing', 'execution'],
761
+ recommendedDomain: 'support',
762
+ },
763
+ ];
764
+ }
765
+
766
+ private decomposeResearchTask(task: TaskDefinition): SubTask[] {
767
+ return [
768
+ {
769
+ id: `${task.id.id}_gather`,
770
+ name: 'Information Gathering',
771
+ description: 'Gather relevant information',
772
+ type: 'research',
773
+ priority: task.priority,
774
+ dependencies: [],
775
+ estimatedDurationMs: 15000,
776
+ requiredCapabilities: ['research', 'analysis'],
777
+ recommendedDomain: 'core',
778
+ },
779
+ {
780
+ id: `${task.id.id}_analyze`,
781
+ name: 'Analysis',
782
+ description: 'Analyze gathered information',
783
+ type: 'analysis',
784
+ priority: task.priority,
785
+ dependencies: [`${task.id.id}_gather`],
786
+ estimatedDurationMs: 10000,
787
+ requiredCapabilities: ['analysis', 'synthesis'],
788
+ recommendedDomain: 'core',
789
+ },
790
+ ];
791
+ }
792
+
793
+ private decomposeCoordinationTask(task: TaskDefinition): SubTask[] {
794
+ return [
795
+ {
796
+ id: `${task.id.id}_plan`,
797
+ name: 'Planning',
798
+ description: 'Create coordination plan',
799
+ type: 'coordination',
800
+ priority: task.priority,
801
+ dependencies: [],
802
+ estimatedDurationMs: 5000,
803
+ requiredCapabilities: ['planning', 'coordination'],
804
+ recommendedDomain: 'queen',
805
+ },
806
+ {
807
+ id: `${task.id.id}_execute`,
808
+ name: 'Execution',
809
+ description: 'Execute coordination plan',
810
+ type: 'coordination',
811
+ priority: task.priority,
812
+ dependencies: [`${task.id.id}_plan`],
813
+ estimatedDurationMs: 10000,
814
+ requiredCapabilities: ['coordination', 'oversight'],
815
+ recommendedDomain: 'queen',
816
+ },
817
+ ];
818
+ }
819
+
820
+ private decomposeGenericTask(task: TaskDefinition): SubTask[] {
821
+ return [
822
+ {
823
+ id: `${task.id.id}_execute`,
824
+ name: 'Task Execution',
825
+ description: task.description,
826
+ type: task.type,
827
+ priority: task.priority,
828
+ dependencies: [],
829
+ estimatedDurationMs: 20000,
830
+ requiredCapabilities: this.identifyRequiredCapabilities(task),
831
+ recommendedDomain: this.inferDomainFromType(task.type),
832
+ },
833
+ ];
834
+ }
835
+
836
+ /**
837
+ * Identify required capabilities for a task
838
+ */
839
+ private identifyRequiredCapabilities(task: TaskDefinition): string[] {
840
+ const capabilities: Set<string> = new Set();
841
+
842
+ // Add type-based capabilities
843
+ const typeCapabilities: Record<TaskType, string[]> = {
844
+ research: ['research', 'analysis', 'synthesis'],
845
+ analysis: ['analysis', 'reasoning', 'synthesis'],
846
+ coding: ['coding', 'implementation', 'debugging'],
847
+ testing: ['testing', 'validation', 'quality'],
848
+ review: ['review', 'analysis', 'feedback'],
849
+ documentation: ['documentation', 'writing', 'clarity'],
850
+ coordination: ['coordination', 'planning', 'oversight'],
851
+ consensus: ['consensus', 'voting', 'agreement'],
852
+ custom: ['general', 'execution'],
853
+ };
854
+
855
+ for (const cap of typeCapabilities[task.type] || ['general']) {
856
+ capabilities.add(cap);
857
+ }
858
+
859
+ // Extract additional capabilities from description
860
+ const descLower = (task.description || '').toLowerCase();
861
+ if (descLower.includes('security')) capabilities.add('security');
862
+ if (descLower.includes('performance')) capabilities.add('performance');
863
+ if (descLower.includes('architecture')) capabilities.add('architecture');
864
+ if (descLower.includes('integration')) capabilities.add('integration');
865
+ if (descLower.includes('deploy')) capabilities.add('deployment');
866
+
867
+ return Array.from(capabilities);
868
+ }
869
+
870
+ /**
871
+ * Calculate task complexity score
872
+ */
873
+ private calculateComplexity(task: TaskDefinition, subtasks: SubTask[]): number {
874
+ let complexity = 0.3; // Base complexity
875
+
876
+ // Add complexity for subtasks
877
+ complexity += subtasks.length * 0.1;
878
+
879
+ // Add complexity for dependencies
880
+ const totalDeps = subtasks.reduce((sum, st) => sum + st.dependencies.length, 0);
881
+ complexity += totalDeps * 0.05;
882
+
883
+ // Add complexity for priority
884
+ const priorityMultipliers: Record<TaskPriority, number> = {
885
+ critical: 1.3,
886
+ high: 1.15,
887
+ normal: 1.0,
888
+ low: 0.9,
889
+ background: 0.8,
890
+ };
891
+ complexity *= priorityMultipliers[task.priority];
892
+
893
+ // Add complexity for task type
894
+ const typeComplexity: Record<TaskType, number> = {
895
+ coordination: 0.2,
896
+ consensus: 0.25,
897
+ coding: 0.15,
898
+ testing: 0.1,
899
+ analysis: 0.1,
900
+ research: 0.1,
901
+ review: 0.05,
902
+ documentation: 0.05,
903
+ custom: 0.1,
904
+ };
905
+ complexity += typeComplexity[task.type] || 0.1;
906
+
907
+ // Add complexity for description length
908
+ const descLength = task.description?.length || 0;
909
+ complexity += Math.min(descLength / 2000, 0.2);
910
+
911
+ return Math.min(complexity, 1.0);
912
+ }
913
+
914
+ /**
915
+ * Estimate task duration
916
+ */
917
+ private estimateDuration(
918
+ task: TaskDefinition,
919
+ complexity: number,
920
+ subtasks: SubTask[]
921
+ ): number {
922
+ // Base duration by type (in ms)
923
+ const baseDurations: Record<TaskType, number> = {
924
+ research: 30000,
925
+ analysis: 20000,
926
+ coding: 60000,
927
+ testing: 30000,
928
+ review: 15000,
929
+ documentation: 20000,
930
+ coordination: 10000,
931
+ consensus: 15000,
932
+ custom: 30000,
933
+ };
934
+
935
+ const baseDuration = baseDurations[task.type] || 30000;
936
+
937
+ // Adjust for complexity
938
+ const complexityMultiplier = 0.5 + complexity * 1.5;
939
+
940
+ // Add subtask durations
941
+ const subtaskDuration = subtasks.reduce((sum, st) => sum + st.estimatedDurationMs, 0);
942
+
943
+ // Total estimate
944
+ return Math.round(baseDuration * complexityMultiplier + subtaskDuration * 0.5);
945
+ }
946
+
947
+ /**
948
+ * Determine optimal domain for task execution
949
+ */
950
+ private determineOptimalDomain(
951
+ task: TaskDefinition,
952
+ capabilities: string[]
953
+ ): AgentDomain {
954
+ // Check capabilities for domain hints
955
+ if (capabilities.includes('security')) return 'security';
956
+ if (capabilities.includes('coordination') || capabilities.includes('planning')) return 'queen';
957
+ if (capabilities.includes('testing') || capabilities.includes('performance')) return 'support';
958
+ if (capabilities.includes('integration')) return 'integration';
959
+
960
+ // Fall back to type-based inference
961
+ return this.inferDomainFromType(task.type);
962
+ }
963
+
964
+ private inferDomainFromType(type: TaskType): AgentDomain {
965
+ const typeDomains: Record<TaskType, AgentDomain> = {
966
+ coordination: 'queen',
967
+ consensus: 'queen',
968
+ coding: 'integration',
969
+ testing: 'support',
970
+ review: 'security',
971
+ analysis: 'core',
972
+ research: 'core',
973
+ documentation: 'support',
974
+ custom: 'core',
975
+ };
976
+ return typeDomains[type] || 'core';
977
+ }
978
+
979
+ /**
980
+ * Find matching patterns from ReasoningBank
981
+ */
982
+ private async findMatchingPatterns(task: TaskDefinition): Promise<MatchedPattern[]> {
983
+ const patterns: MatchedPattern[] = [];
984
+
985
+ if (!this.neural || !this.config.enableLearning) {
986
+ return patterns;
987
+ }
988
+
989
+ try {
990
+ // Create a simple embedding from task description
991
+ const embedding = this.createSimpleEmbedding(task.description || task.name);
992
+
993
+ // Query ReasoningBank for similar patterns
994
+ const results = await this.neural.findPatterns(embedding, this.config.patternRetrievalK);
995
+
996
+ for (const result of results) {
997
+ if (result.relevanceScore >= this.config.patternThreshold) {
998
+ patterns.push({
999
+ patternId: result.patternId,
1000
+ strategy: result.strategy,
1001
+ successRate: result.successRate,
1002
+ relevanceScore: result.relevanceScore,
1003
+ keyLearnings: result.keyLearnings || [],
1004
+ });
1005
+ }
1006
+ }
1007
+ } catch (error) {
1008
+ // Log but don't fail - patterns are optional
1009
+ this.emitEvent('queen.pattern.error', { error: String(error) });
1010
+ }
1011
+
1012
+ return patterns;
1013
+ }
1014
+
1015
+ /**
1016
+ * Create a simple embedding from text (placeholder)
1017
+ */
1018
+ private createSimpleEmbedding(text: string): Float32Array {
1019
+ // Simple hash-based embedding for demonstration
1020
+ // In production, this would use a real embedding model
1021
+ const embedding = new Float32Array(768);
1022
+ const words = text.toLowerCase().split(/\s+/);
1023
+
1024
+ for (let i = 0; i < words.length; i++) {
1025
+ const word = words[i];
1026
+ for (let j = 0; j < word.length; j++) {
1027
+ const idx = (word.charCodeAt(j) * (i + 1) * (j + 1)) % 768;
1028
+ embedding[idx] += 1 / words.length;
1029
+ }
1030
+ }
1031
+
1032
+ // Normalize
1033
+ let norm = 0;
1034
+ for (let i = 0; i < embedding.length; i++) {
1035
+ norm += embedding[i] * embedding[i];
1036
+ }
1037
+ norm = Math.sqrt(norm);
1038
+ if (norm > 0) {
1039
+ for (let i = 0; i < embedding.length; i++) {
1040
+ embedding[i] /= norm;
1041
+ }
1042
+ }
1043
+
1044
+ return embedding;
1045
+ }
1046
+
1047
+ /**
1048
+ * Estimate resource requirements
1049
+ */
1050
+ private estimateResources(task: TaskDefinition, complexity: number): ResourceRequirements {
1051
+ const minAgents = complexity > 0.7 ? 2 : 1;
1052
+ const maxAgents = complexity > 0.8 ? 4 : complexity > 0.5 ? 3 : 2;
1053
+
1054
+ return {
1055
+ minAgents,
1056
+ maxAgents,
1057
+ memoryMb: Math.round(256 + complexity * 512),
1058
+ cpuIntensive: ['coding', 'analysis'].includes(task.type),
1059
+ ioIntensive: ['research', 'testing'].includes(task.type),
1060
+ networkRequired: task.type === 'research',
1061
+ };
1062
+ }
1063
+
1064
+ /**
1065
+ * Calculate confidence in analysis
1066
+ */
1067
+ private calculateAnalysisConfidence(
1068
+ patterns: MatchedPattern[],
1069
+ complexity: number,
1070
+ capabilities: string[]
1071
+ ): number {
1072
+ let confidence = 0.5; // Base confidence
1073
+
1074
+ // Higher confidence with more matching patterns
1075
+ confidence += patterns.length * 0.1;
1076
+
1077
+ // Higher confidence for simpler tasks
1078
+ confidence += (1 - complexity) * 0.2;
1079
+
1080
+ // Higher confidence with clear capabilities
1081
+ confidence += Math.min(capabilities.length * 0.05, 0.15);
1082
+
1083
+ // Boost from high-success patterns
1084
+ const avgPatternSuccess = patterns.length > 0
1085
+ ? patterns.reduce((sum, p) => sum + p.successRate, 0) / patterns.length
1086
+ : 0;
1087
+ confidence += avgPatternSuccess * 0.1;
1088
+
1089
+ return Math.min(confidence, 0.95);
1090
+ }
1091
+
1092
+ // ===========================================================================
1093
+ // Agent Delegation
1094
+ // ===========================================================================
1095
+
1096
+ /**
1097
+ * Delegate a task to agents based on analysis
1098
+ *
1099
+ * @param task - Task to delegate
1100
+ * @param analysis - Previous task analysis
1101
+ * @returns Delegation plan
1102
+ */
1103
+ async delegateToAgents(task: TaskDefinition, analysis: TaskAnalysis): Promise<DelegationPlan> {
1104
+ const startTime = performance.now();
1105
+
1106
+ this.planCounter++;
1107
+ const planId = `plan_${Date.now()}_${this.planCounter}`;
1108
+
1109
+ // Score all available agents for this task
1110
+ const agentScores = this.scoreAgents(task, analysis.matchedPatterns);
1111
+
1112
+ // Select primary agent
1113
+ const primaryAgent = this.selectPrimaryAgent(task, agentScores, analysis);
1114
+
1115
+ // Select backup agents
1116
+ const backupAgents = this.selectBackupAgents(task, agentScores, primaryAgent);
1117
+
1118
+ // Create parallel assignments for subtasks
1119
+ const parallelAssignments = this.createParallelAssignments(
1120
+ analysis.subtasks,
1121
+ agentScores
1122
+ );
1123
+
1124
+ // Determine execution strategy
1125
+ const strategy = this.determineExecutionStrategy(analysis);
1126
+
1127
+ const plan: DelegationPlan = {
1128
+ planId,
1129
+ taskId: task.id.id,
1130
+ analysisId: analysis.analysisId,
1131
+ primaryAgent,
1132
+ backupAgents,
1133
+ parallelAssignments,
1134
+ strategy,
1135
+ estimatedCompletionMs: analysis.estimatedDurationMs,
1136
+ timestamp: new Date(),
1137
+ };
1138
+
1139
+ // Store the plan
1140
+ this.delegationPlans.set(planId, plan);
1141
+
1142
+ // Execute the delegation
1143
+ await this.executeDelegation(plan);
1144
+
1145
+ // Record latency
1146
+ const latency = performance.now() - startTime;
1147
+ this.delegationLatencies.push(latency);
1148
+ if (this.delegationLatencies.length > 100) {
1149
+ this.delegationLatencies.shift();
1150
+ }
1151
+
1152
+ this.emitEvent('queen.task.delegated', {
1153
+ planId,
1154
+ taskId: task.id.id,
1155
+ primaryAgent: primaryAgent.agentId,
1156
+ strategy,
1157
+ latencyMs: latency,
1158
+ });
1159
+
1160
+ return plan;
1161
+ }
1162
+
1163
+ /**
1164
+ * Score agents for task assignment
1165
+ */
1166
+ scoreAgents(task: TaskDefinition, patterns: MatchedPattern[]): AgentScore[] {
1167
+ const agents = this.swarm.getAllAgents();
1168
+ const scores: AgentScore[] = [];
1169
+
1170
+ for (const agent of agents) {
1171
+ const score = this.scoreAgent(agent, task, patterns);
1172
+ scores.push(score);
1173
+ }
1174
+
1175
+ // Sort by total score descending
1176
+ scores.sort((a, b) => b.totalScore - a.totalScore);
1177
+
1178
+ return scores;
1179
+ }
1180
+
1181
+ private scoreAgent(
1182
+ agent: AgentState,
1183
+ task: TaskDefinition,
1184
+ patterns: MatchedPattern[]
1185
+ ): AgentScore {
1186
+ const domain = this.getAgentDomain(agent);
1187
+
1188
+ // Capability score - how well agent capabilities match task
1189
+ const capabilityScore = this.calculateCapabilityScore(agent, task);
1190
+
1191
+ // Load score - prefer less loaded agents
1192
+ const loadScore = 1 - agent.workload;
1193
+
1194
+ // Performance score - based on past performance
1195
+ const performanceScore = this.calculatePerformanceScore(agent, patterns);
1196
+
1197
+ // Health score - agent health
1198
+ const healthScore = agent.health;
1199
+
1200
+ // Availability score - is agent actually available
1201
+ const availabilityScore = agent.status === 'idle' ? 1.0 :
1202
+ agent.status === 'busy' ? 0.3 : 0.0;
1203
+
1204
+ // Weighted total
1205
+ const totalScore =
1206
+ capabilityScore * 0.30 +
1207
+ loadScore * 0.20 +
1208
+ performanceScore * 0.25 +
1209
+ healthScore * 0.15 +
1210
+ availabilityScore * 0.10;
1211
+
1212
+ return {
1213
+ agentId: agent.id.id,
1214
+ domain,
1215
+ totalScore,
1216
+ capabilityScore,
1217
+ loadScore,
1218
+ performanceScore,
1219
+ healthScore,
1220
+ availabilityScore,
1221
+ };
1222
+ }
1223
+
1224
+ private calculateCapabilityScore(agent: AgentState, task: TaskDefinition): number {
1225
+ let score = 0.5; // Base score
1226
+
1227
+ // Check type match
1228
+ const typeMatches: Record<TaskType, AgentType[]> = {
1229
+ research: ['researcher'],
1230
+ analysis: ['analyst', 'researcher'],
1231
+ coding: ['coder'],
1232
+ testing: ['tester'],
1233
+ review: ['reviewer'],
1234
+ documentation: ['documenter'],
1235
+ coordination: ['coordinator', 'queen'],
1236
+ consensus: ['coordinator', 'queen'],
1237
+ custom: ['worker'],
1238
+ };
1239
+
1240
+ const preferredTypes = typeMatches[task.type] || ['worker'];
1241
+ if (preferredTypes.includes(agent.type)) {
1242
+ score += 0.3;
1243
+ }
1244
+
1245
+ // Check specific capabilities
1246
+ const caps = agent.capabilities;
1247
+ if (task.type === 'coding' && caps.codeGeneration) score += 0.1;
1248
+ if (task.type === 'review' && caps.codeReview) score += 0.1;
1249
+ if (task.type === 'testing' && caps.testing) score += 0.1;
1250
+ if (task.type === 'coordination' && caps.coordination) score += 0.1;
1251
+
1252
+ return Math.min(score, 1.0);
1253
+ }
1254
+
1255
+ private calculatePerformanceScore(
1256
+ agent: AgentState,
1257
+ patterns: MatchedPattern[]
1258
+ ): number {
1259
+ // Base on agent's success rate
1260
+ let score = agent.metrics.successRate;
1261
+
1262
+ // Boost if patterns suggest this agent type is successful
1263
+ const agentDomain = this.getAgentDomain(agent);
1264
+ for (const pattern of patterns) {
1265
+ if (pattern.strategy.toLowerCase().includes(agentDomain)) {
1266
+ score += pattern.successRate * 0.1;
1267
+ }
1268
+ }
1269
+
1270
+ return Math.min(score, 1.0);
1271
+ }
1272
+
1273
+ private getAgentDomain(agent: AgentState): AgentDomain {
1274
+ // Determine domain from agent type
1275
+ switch (agent.type) {
1276
+ case 'queen':
1277
+ return 'queen';
1278
+ case 'specialist':
1279
+ return 'security';
1280
+ case 'architect':
1281
+ return 'core';
1282
+ case 'coder':
1283
+ return 'integration';
1284
+ case 'tester':
1285
+ return 'support';
1286
+ default:
1287
+ return 'core';
1288
+ }
1289
+ }
1290
+
1291
+ private selectPrimaryAgent(
1292
+ task: TaskDefinition,
1293
+ scores: AgentScore[],
1294
+ analysis: TaskAnalysis
1295
+ ): AgentAssignment {
1296
+ // Prefer agent from recommended domain
1297
+ const domainAgents = scores.filter(s => s.domain === analysis.recommendedDomain);
1298
+
1299
+ // Fall back to best overall if no domain match
1300
+ const bestScore = domainAgents.length > 0 ? domainAgents[0] : scores[0];
1301
+
1302
+ return {
1303
+ agentId: bestScore.agentId,
1304
+ domain: bestScore.domain,
1305
+ taskId: task.id.id,
1306
+ score: bestScore.totalScore,
1307
+ assignedAt: new Date(),
1308
+ };
1309
+ }
1310
+
1311
+ private selectBackupAgents(
1312
+ task: TaskDefinition,
1313
+ scores: AgentScore[],
1314
+ primary: AgentAssignment
1315
+ ): AgentAssignment[] {
1316
+ const backups: AgentAssignment[] = [];
1317
+
1318
+ // Select up to 2 backup agents
1319
+ for (const score of scores) {
1320
+ if (score.agentId === primary.agentId) continue;
1321
+ if (score.totalScore < 0.3) continue;
1322
+ if (backups.length >= 2) break;
1323
+
1324
+ backups.push({
1325
+ agentId: score.agentId,
1326
+ domain: score.domain,
1327
+ taskId: task.id.id,
1328
+ score: score.totalScore,
1329
+ assignedAt: new Date(),
1330
+ });
1331
+ }
1332
+
1333
+ return backups;
1334
+ }
1335
+
1336
+ private createParallelAssignments(
1337
+ subtasks: SubTask[],
1338
+ scores: AgentScore[]
1339
+ ): ParallelAssignment[] {
1340
+ const assignments: ParallelAssignment[] = [];
1341
+
1342
+ for (const subtask of subtasks) {
1343
+ // Find best agent for this subtask's domain
1344
+ const domainScores = scores.filter(s => s.domain === subtask.recommendedDomain);
1345
+ const bestScore = domainScores.length > 0 ? domainScores[0] : scores[0];
1346
+
1347
+ assignments.push({
1348
+ subtaskId: subtask.id,
1349
+ agentId: bestScore.agentId,
1350
+ domain: subtask.recommendedDomain,
1351
+ dependencies: subtask.dependencies,
1352
+ });
1353
+ }
1354
+
1355
+ return assignments;
1356
+ }
1357
+
1358
+ private determineExecutionStrategy(analysis: TaskAnalysis): ExecutionStrategy {
1359
+ const subtaskCount = analysis.subtasks.length;
1360
+
1361
+ if (subtaskCount === 0) {
1362
+ return 'sequential';
1363
+ }
1364
+
1365
+ // Check for dependencies
1366
+ const hasDependencies = analysis.subtasks.some(st => st.dependencies.length > 0);
1367
+
1368
+ if (!hasDependencies && subtaskCount > 2) {
1369
+ return 'parallel';
1370
+ }
1371
+
1372
+ if (hasDependencies && subtaskCount > 3) {
1373
+ return 'pipeline';
1374
+ }
1375
+
1376
+ if (analysis.complexity > 0.7) {
1377
+ return 'fan-out-fan-in';
1378
+ }
1379
+
1380
+ return 'hybrid';
1381
+ }
1382
+
1383
+ private async executeDelegation(plan: DelegationPlan): Promise<void> {
1384
+ // Delegate to the primary agent
1385
+ await this.swarm.assignTaskToDomain(plan.taskId, plan.primaryAgent.domain);
1386
+
1387
+ // Notify about the delegation
1388
+ await this.swarm.broadcastMessage(
1389
+ {
1390
+ type: 'delegation',
1391
+ planId: plan.planId,
1392
+ taskId: plan.taskId,
1393
+ primaryAgent: plan.primaryAgent.agentId,
1394
+ strategy: plan.strategy,
1395
+ },
1396
+ 'normal'
1397
+ );
1398
+ }
1399
+
1400
+ // ===========================================================================
1401
+ // Swarm Health Monitoring
1402
+ // ===========================================================================
1403
+
1404
+ /**
1405
+ * Monitor swarm health and detect issues
1406
+ *
1407
+ * @returns Health report
1408
+ */
1409
+ async monitorSwarmHealth(): Promise<HealthReport> {
1410
+ this.reportCounter++;
1411
+ const reportId = `health_${Date.now()}_${this.reportCounter}`;
1412
+
1413
+ const agents = this.swarm.getAllAgents();
1414
+ const status = this.swarm.getStatus();
1415
+ const metrics = this.swarm.getMetrics();
1416
+
1417
+ // Compute domain health
1418
+ const domainHealth = this.computeDomainHealth(status.domains);
1419
+
1420
+ // Compute agent health
1421
+ const agentHealth = this.computeAgentHealth(agents);
1422
+
1423
+ // Detect bottlenecks
1424
+ const bottlenecks = this.detectBottlenecks(status, agents, metrics);
1425
+
1426
+ // Generate alerts
1427
+ const alerts = this.generateAlerts(bottlenecks, agentHealth, metrics);
1428
+
1429
+ // Overall health score
1430
+ const overallHealth = this.calculateOverallHealth(domainHealth, agentHealth, bottlenecks);
1431
+
1432
+ // Generate recommendations
1433
+ const recommendations = this.generateRecommendations(bottlenecks, overallHealth);
1434
+
1435
+ // Compile health metrics
1436
+ const healthMetrics: HealthMetrics = {
1437
+ totalAgents: agents.length,
1438
+ activeAgents: agents.filter(a => a.status === 'idle' || a.status === 'busy').length,
1439
+ idleAgents: agents.filter(a => a.status === 'idle').length,
1440
+ errorAgents: agents.filter(a => a.status === 'error').length,
1441
+ totalTasks: metrics.totalTasks,
1442
+ completedTasks: metrics.completedTasks,
1443
+ failedTasks: metrics.failedTasks,
1444
+ avgTaskDurationMs: metrics.avgTaskDurationMs,
1445
+ taskThroughputPerMin: metrics.completedTasks / Math.max(metrics.uptime / 60, 1),
1446
+ consensusSuccessRate: metrics.consensusSuccessRate,
1447
+ };
1448
+
1449
+ const report: HealthReport = {
1450
+ reportId,
1451
+ timestamp: new Date(),
1452
+ overallHealth,
1453
+ domainHealth,
1454
+ agentHealth,
1455
+ bottlenecks,
1456
+ alerts,
1457
+ metrics: healthMetrics,
1458
+ recommendations,
1459
+ };
1460
+
1461
+ // Store in history
1462
+ this.healthHistory.push(report);
1463
+ if (this.healthHistory.length > 100) {
1464
+ this.healthHistory.shift();
1465
+ }
1466
+ this.lastHealthReport = report;
1467
+
1468
+ this.emitEvent('queen.health.report', {
1469
+ reportId,
1470
+ overallHealth,
1471
+ bottleneckCount: bottlenecks.length,
1472
+ alertCount: alerts.length,
1473
+ });
1474
+
1475
+ return report;
1476
+ }
1477
+
1478
+ private computeDomainHealth(domains: DomainStatus[]): Map<AgentDomain, DomainHealthStatus> {
1479
+ const health = new Map<AgentDomain, DomainHealthStatus>();
1480
+
1481
+ for (const domain of domains) {
1482
+ const utilization = domain.agentCount > 0
1483
+ ? domain.busyAgents / domain.agentCount
1484
+ : 0;
1485
+
1486
+ const queuePressure = domain.tasksQueued > 5 ? 0.3 : domain.tasksQueued * 0.05;
1487
+ const domainHealth = Math.max(0, 1 - queuePressure - (1 - utilization) * 0.2);
1488
+
1489
+ health.set(domain.name, {
1490
+ domain: domain.name,
1491
+ health: domainHealth,
1492
+ activeAgents: domain.availableAgents + domain.busyAgents,
1493
+ totalAgents: domain.agentCount,
1494
+ queuedTasks: domain.tasksQueued,
1495
+ avgResponseTimeMs: 0, // Would need tracking
1496
+ errorRate: 0, // Would need tracking
1497
+ });
1498
+ }
1499
+
1500
+ return health;
1501
+ }
1502
+
1503
+ private computeAgentHealth(agents: AgentState[]): AgentHealthEntry[] {
1504
+ return agents.map(agent => ({
1505
+ agentId: agent.id.id,
1506
+ domain: this.getAgentDomain(agent),
1507
+ health: agent.health,
1508
+ status: agent.status,
1509
+ lastHeartbeat: agent.lastHeartbeat,
1510
+ currentLoad: agent.workload,
1511
+ recentErrors: agent.metrics.tasksFailed,
1512
+ }));
1513
+ }
1514
+
1515
+ private detectBottlenecks(
1516
+ status: { domains: DomainStatus[]; metrics: CoordinatorMetrics },
1517
+ agents: AgentState[],
1518
+ metrics: CoordinatorMetrics
1519
+ ): Bottleneck[] {
1520
+ const bottlenecks: Bottleneck[] = [];
1521
+
1522
+ // Check domain queues
1523
+ for (const domain of status.domains) {
1524
+ if (domain.tasksQueued > this.config.bottleneckThresholds.queueDepth) {
1525
+ bottlenecks.push({
1526
+ type: 'domain',
1527
+ location: domain.name,
1528
+ severity: domain.tasksQueued > 20 ? 'critical' : 'high',
1529
+ description: `High task queue depth in ${domain.name} domain`,
1530
+ impact: `${domain.tasksQueued} tasks waiting for processing`,
1531
+ suggestedAction: `Consider scaling ${domain.name} domain agents`,
1532
+ });
1533
+ }
1534
+ }
1535
+
1536
+ // Check error agents
1537
+ const errorAgents = agents.filter(a => a.status === 'error');
1538
+ if (errorAgents.length > 0) {
1539
+ bottlenecks.push({
1540
+ type: 'agent',
1541
+ location: errorAgents.map(a => a.id.id).join(', '),
1542
+ severity: errorAgents.length > 3 ? 'critical' : 'medium',
1543
+ description: `${errorAgents.length} agents in error state`,
1544
+ impact: 'Reduced processing capacity',
1545
+ suggestedAction: 'Investigate and recover error agents',
1546
+ });
1547
+ }
1548
+
1549
+ // Check coordination latency
1550
+ if (metrics.coordinationLatencyMs > this.config.bottleneckThresholds.responseTimeMs) {
1551
+ bottlenecks.push({
1552
+ type: 'resource',
1553
+ location: 'coordination',
1554
+ severity: 'high',
1555
+ description: 'High coordination latency detected',
1556
+ impact: `Current latency: ${metrics.coordinationLatencyMs}ms`,
1557
+ suggestedAction: 'Optimize coordination or reduce concurrent tasks',
1558
+ });
1559
+ }
1560
+
1561
+ return bottlenecks;
1562
+ }
1563
+
1564
+ private generateAlerts(
1565
+ bottlenecks: Bottleneck[],
1566
+ agentHealth: AgentHealthEntry[],
1567
+ metrics: CoordinatorMetrics
1568
+ ): HealthAlert[] {
1569
+ const alerts: HealthAlert[] = [];
1570
+
1571
+ // Generate alerts for critical bottlenecks
1572
+ for (const bottleneck of bottlenecks) {
1573
+ if (bottleneck.severity === 'critical' || bottleneck.severity === 'high') {
1574
+ alerts.push({
1575
+ alertId: `alert_${Date.now()}_${alerts.length}`,
1576
+ type: bottleneck.severity === 'critical' ? 'critical' : 'error',
1577
+ source: bottleneck.location,
1578
+ message: bottleneck.description,
1579
+ timestamp: new Date(),
1580
+ acknowledged: false,
1581
+ });
1582
+ }
1583
+ }
1584
+
1585
+ // Alert on low overall agent health
1586
+ const avgHealth = agentHealth.length > 0
1587
+ ? agentHealth.reduce((sum, a) => sum + a.health, 0) / agentHealth.length
1588
+ : 1.0;
1589
+
1590
+ if (avgHealth < 0.5) {
1591
+ alerts.push({
1592
+ alertId: `alert_${Date.now()}_health`,
1593
+ type: avgHealth < 0.3 ? 'critical' : 'warning',
1594
+ source: 'swarm',
1595
+ message: `Low average agent health: ${(avgHealth * 100).toFixed(1)}%`,
1596
+ timestamp: new Date(),
1597
+ acknowledged: false,
1598
+ });
1599
+ }
1600
+
1601
+ // Alert on high failure rate
1602
+ const failureRate = metrics.totalTasks > 0
1603
+ ? metrics.failedTasks / metrics.totalTasks
1604
+ : 0;
1605
+
1606
+ if (failureRate > this.config.bottleneckThresholds.errorRate) {
1607
+ alerts.push({
1608
+ alertId: `alert_${Date.now()}_failures`,
1609
+ type: failureRate > 0.2 ? 'critical' : 'warning',
1610
+ source: 'tasks',
1611
+ message: `High task failure rate: ${(failureRate * 100).toFixed(1)}%`,
1612
+ timestamp: new Date(),
1613
+ acknowledged: false,
1614
+ });
1615
+ }
1616
+
1617
+ return alerts;
1618
+ }
1619
+
1620
+ private calculateOverallHealth(
1621
+ domainHealth: Map<AgentDomain, DomainHealthStatus>,
1622
+ agentHealth: AgentHealthEntry[],
1623
+ bottlenecks: Bottleneck[]
1624
+ ): number {
1625
+ // Average domain health
1626
+ const domainHealthAvg = domainHealth.size > 0
1627
+ ? Array.from(domainHealth.values()).reduce((sum, d) => sum + d.health, 0) / domainHealth.size
1628
+ : 1.0;
1629
+
1630
+ // Average agent health
1631
+ const agentHealthAvg = agentHealth.length > 0
1632
+ ? agentHealth.reduce((sum, a) => sum + a.health, 0) / agentHealth.length
1633
+ : 1.0;
1634
+
1635
+ // Bottleneck penalty
1636
+ const bottleneckPenalty = bottlenecks.reduce((penalty, b) => {
1637
+ switch (b.severity) {
1638
+ case 'critical': return penalty + 0.2;
1639
+ case 'high': return penalty + 0.1;
1640
+ case 'medium': return penalty + 0.05;
1641
+ case 'low': return penalty + 0.02;
1642
+ default: return penalty;
1643
+ }
1644
+ }, 0);
1645
+
1646
+ const overallHealth = (domainHealthAvg * 0.4 + agentHealthAvg * 0.4) - bottleneckPenalty;
1647
+ return Math.max(0, Math.min(1, overallHealth));
1648
+ }
1649
+
1650
+ private generateRecommendations(bottlenecks: Bottleneck[], overallHealth: number): string[] {
1651
+ const recommendations: string[] = [];
1652
+
1653
+ // Add bottleneck-specific recommendations
1654
+ for (const bottleneck of bottlenecks) {
1655
+ recommendations.push(bottleneck.suggestedAction);
1656
+ }
1657
+
1658
+ // General recommendations based on health
1659
+ if (overallHealth < 0.5) {
1660
+ recommendations.push('Consider reducing task load or adding more agents');
1661
+ }
1662
+
1663
+ if (overallHealth < 0.3) {
1664
+ recommendations.push('URGENT: Investigate system-wide issues immediately');
1665
+ }
1666
+
1667
+ return [...new Set(recommendations)]; // Deduplicate
1668
+ }
1669
+
1670
+ private startHealthMonitoring(): void {
1671
+ this.healthCheckInterval = setInterval(async () => {
1672
+ try {
1673
+ await this.monitorSwarmHealth();
1674
+ } catch (error) {
1675
+ this.emitEvent('queen.health.error', { error: String(error) });
1676
+ }
1677
+ }, this.config.healthCheckIntervalMs);
1678
+ }
1679
+
1680
+ private stopHealthMonitoring(): void {
1681
+ if (this.healthCheckInterval) {
1682
+ clearInterval(this.healthCheckInterval);
1683
+ this.healthCheckInterval = undefined;
1684
+ }
1685
+ }
1686
+
1687
+ // ===========================================================================
1688
+ // Consensus Coordination
1689
+ // ===========================================================================
1690
+
1691
+ /**
1692
+ * Coordinate consensus for a decision
1693
+ *
1694
+ * @param decision - Decision requiring consensus
1695
+ * @returns Consensus result
1696
+ */
1697
+ async coordinateConsensus(decision: Decision): Promise<ConsensusResult> {
1698
+ const startTime = performance.now();
1699
+
1700
+ this.decisionCounter++;
1701
+ decision.decisionId = `decision_${Date.now()}_${this.decisionCounter}`;
1702
+
1703
+ // Store active decision
1704
+ this.activeDecisions.set(decision.decisionId, decision);
1705
+
1706
+ try {
1707
+ let result: ConsensusResult;
1708
+
1709
+ switch (decision.requiredConsensus) {
1710
+ case 'queen-override':
1711
+ // Queen can make unilateral decisions for certain types
1712
+ result = this.queenOverride(decision);
1713
+ break;
1714
+
1715
+ case 'unanimous':
1716
+ result = await this.unanimousConsensus(decision);
1717
+ break;
1718
+
1719
+ case 'supermajority':
1720
+ result = await this.supermajorityConsensus(decision);
1721
+ break;
1722
+
1723
+ case 'weighted':
1724
+ result = await this.weightedConsensus(decision);
1725
+ break;
1726
+
1727
+ case 'majority':
1728
+ default:
1729
+ result = await this.majorityConsensus(decision);
1730
+ }
1731
+
1732
+ // Record latency
1733
+ const latency = performance.now() - startTime;
1734
+ this.consensusLatencies.push(latency);
1735
+ if (this.consensusLatencies.length > 100) {
1736
+ this.consensusLatencies.shift();
1737
+ }
1738
+
1739
+ this.emitEvent('queen.consensus.completed', {
1740
+ decisionId: decision.decisionId,
1741
+ type: decision.requiredConsensus,
1742
+ approved: result.approved,
1743
+ approvalRate: result.approvalRate,
1744
+ latencyMs: latency,
1745
+ });
1746
+
1747
+ return result;
1748
+ } finally {
1749
+ this.activeDecisions.delete(decision.decisionId);
1750
+ }
1751
+ }
1752
+
1753
+ private queenOverride(decision: Decision): ConsensusResult {
1754
+ // Queen can make immediate decisions for:
1755
+ // - Emergency actions
1756
+ // - Agent termination
1757
+ // - Priority overrides
1758
+ const allowedTypes: DecisionType[] = ['emergency-action', 'agent-termination', 'priority-override'];
1759
+
1760
+ if (!allowedTypes.includes(decision.type)) {
1761
+ throw new Error(`Queen override not allowed for decision type: ${decision.type}`);
1762
+ }
1763
+
1764
+ return {
1765
+ proposalId: decision.decisionId,
1766
+ approved: true,
1767
+ approvalRate: 1.0,
1768
+ participationRate: 1.0,
1769
+ finalValue: decision.proposal,
1770
+ rounds: 1,
1771
+ durationMs: 0,
1772
+ };
1773
+ }
1774
+
1775
+ private async majorityConsensus(decision: Decision): Promise<ConsensusResult> {
1776
+ // Use swarm's consensus engine with majority threshold
1777
+ const result = await this.swarm.proposeConsensus({
1778
+ decision,
1779
+ threshold: 0.51,
1780
+ timeout: this.config.consensusTimeouts.majority,
1781
+ });
1782
+
1783
+ return result;
1784
+ }
1785
+
1786
+ private async supermajorityConsensus(decision: Decision): Promise<ConsensusResult> {
1787
+ // Use swarm's consensus engine with 2/3 threshold
1788
+ const result = await this.swarm.proposeConsensus({
1789
+ decision,
1790
+ threshold: 0.67,
1791
+ timeout: this.config.consensusTimeouts.supermajority,
1792
+ });
1793
+
1794
+ return result;
1795
+ }
1796
+
1797
+ private async unanimousConsensus(decision: Decision): Promise<ConsensusResult> {
1798
+ // Use swarm's consensus engine with unanimous requirement
1799
+ const result = await this.swarm.proposeConsensus({
1800
+ decision,
1801
+ threshold: 1.0,
1802
+ timeout: this.config.consensusTimeouts.unanimous,
1803
+ });
1804
+
1805
+ return result;
1806
+ }
1807
+
1808
+ private async weightedConsensus(decision: Decision): Promise<ConsensusResult> {
1809
+ // Weighted consensus based on agent performance
1810
+ // For now, delegate to the standard consensus with metadata
1811
+ const agents = this.swarm.getAllAgents();
1812
+ const weights = new Map<string, number>();
1813
+
1814
+ for (const agent of agents) {
1815
+ const weight = agent.metrics.successRate * agent.health;
1816
+ weights.set(agent.id.id, weight);
1817
+ }
1818
+
1819
+ const result = await this.swarm.proposeConsensus({
1820
+ decision,
1821
+ weights: Object.fromEntries(weights),
1822
+ threshold: 0.51,
1823
+ timeout: this.config.consensusTimeouts.majority,
1824
+ });
1825
+
1826
+ return result;
1827
+ }
1828
+
1829
+ // ===========================================================================
1830
+ // Learning from Outcomes
1831
+ // ===========================================================================
1832
+
1833
+ /**
1834
+ * Record task outcome for learning
1835
+ *
1836
+ * @param task - Completed task
1837
+ * @param result - Task result
1838
+ */
1839
+ async recordOutcome(task: TaskDefinition, result: TaskResult): Promise<void> {
1840
+ // Store in outcome history
1841
+ this.outcomeHistory.push(result);
1842
+ if (this.outcomeHistory.length > 1000) {
1843
+ this.outcomeHistory.shift();
1844
+ }
1845
+
1846
+ // Learn from outcome if neural system available
1847
+ if (this.neural && this.config.enableLearning) {
1848
+ await this.learnFromOutcome(task, result);
1849
+ }
1850
+
1851
+ // Store in memory service if available
1852
+ if (this.memory) {
1853
+ await this.storeOutcomeMemory(task, result);
1854
+ }
1855
+
1856
+ this.emitEvent('queen.outcome.recorded', {
1857
+ taskId: task.id.id,
1858
+ success: result.success,
1859
+ durationMs: result.durationMs,
1860
+ qualityScore: result.metrics.qualityScore,
1861
+ });
1862
+ }
1863
+
1864
+ private async learnFromOutcome(task: TaskDefinition, result: TaskResult): Promise<void> {
1865
+ if (!this.neural) return;
1866
+
1867
+ // Create trajectory for this task
1868
+ const trajectoryId = this.neural.beginTask(
1869
+ task.description || task.name,
1870
+ result.domain
1871
+ );
1872
+
1873
+ // Record the execution step
1874
+ const embedding = this.createSimpleEmbedding(task.description || task.name);
1875
+ const reward = result.success
1876
+ ? result.metrics.qualityScore * 0.8 + 0.2
1877
+ : result.metrics.qualityScore * 0.3;
1878
+
1879
+ this.neural.recordStep(
1880
+ trajectoryId,
1881
+ `executed_${task.type}_in_${result.domain}`,
1882
+ reward,
1883
+ embedding
1884
+ );
1885
+
1886
+ // Complete the task trajectory
1887
+ await this.neural.completeTask(trajectoryId, result.metrics.qualityScore);
1888
+ }
1889
+
1890
+ private async storeOutcomeMemory(task: TaskDefinition, result: TaskResult): Promise<void> {
1891
+ if (!this.memory) return;
1892
+
1893
+ try {
1894
+ await this.memory.store({
1895
+ key: `outcome_${task.id.id}`,
1896
+ content: this.formatOutcomeContent(task, result),
1897
+ namespace: 'queen-outcomes',
1898
+ tags: [
1899
+ task.type,
1900
+ result.domain,
1901
+ result.success ? 'success' : 'failure',
1902
+ ],
1903
+ metadata: {
1904
+ taskId: task.id.id,
1905
+ success: result.success,
1906
+ durationMs: result.durationMs,
1907
+ qualityScore: result.metrics.qualityScore,
1908
+ agentId: result.agentId,
1909
+ },
1910
+ });
1911
+ } catch (error) {
1912
+ // Log but don't fail - memory storage is optional
1913
+ this.emitEvent('queen.memory.error', { error: String(error) });
1914
+ }
1915
+ }
1916
+
1917
+ private formatOutcomeContent(task: TaskDefinition, result: TaskResult): string {
1918
+ return [
1919
+ `Task: ${task.name}`,
1920
+ `Type: ${task.type}`,
1921
+ `Domain: ${result.domain}`,
1922
+ `Agent: ${result.agentId}`,
1923
+ `Success: ${result.success}`,
1924
+ `Duration: ${result.durationMs}ms`,
1925
+ `Quality: ${result.metrics.qualityScore}`,
1926
+ `Description: ${task.description || 'N/A'}`,
1927
+ ].join('\n');
1928
+ }
1929
+
1930
+ // ===========================================================================
1931
+ // Utility Methods
1932
+ // ===========================================================================
1933
+
1934
+ /**
1935
+ * Get the last health report
1936
+ */
1937
+ getLastHealthReport(): HealthReport | undefined {
1938
+ return this.lastHealthReport;
1939
+ }
1940
+
1941
+ /**
1942
+ * Get outcome history
1943
+ */
1944
+ getOutcomeHistory(): TaskResult[] {
1945
+ return [...this.outcomeHistory];
1946
+ }
1947
+
1948
+ /**
1949
+ * Get analysis cache
1950
+ */
1951
+ getAnalysisCache(): Map<string, TaskAnalysis> {
1952
+ return new Map(this.analysisCache);
1953
+ }
1954
+
1955
+ /**
1956
+ * Get delegation plans
1957
+ */
1958
+ getDelegationPlans(): Map<string, DelegationPlan> {
1959
+ return new Map(this.delegationPlans);
1960
+ }
1961
+
1962
+ /**
1963
+ * Get performance statistics
1964
+ */
1965
+ getPerformanceStats(): {
1966
+ avgAnalysisLatencyMs: number;
1967
+ avgDelegationLatencyMs: number;
1968
+ avgConsensusLatencyMs: number;
1969
+ totalAnalyses: number;
1970
+ totalDelegations: number;
1971
+ totalDecisions: number;
1972
+ } {
1973
+ const avg = (arr: number[]) => arr.length > 0
1974
+ ? arr.reduce((a, b) => a + b, 0) / arr.length
1975
+ : 0;
1976
+
1977
+ return {
1978
+ avgAnalysisLatencyMs: avg(this.analysisLatencies),
1979
+ avgDelegationLatencyMs: avg(this.delegationLatencies),
1980
+ avgConsensusLatencyMs: avg(this.consensusLatencies),
1981
+ totalAnalyses: this.analysisCounter,
1982
+ totalDelegations: this.planCounter,
1983
+ totalDecisions: this.decisionCounter,
1984
+ };
1985
+ }
1986
+
1987
+ /**
1988
+ * Check if learning is enabled
1989
+ */
1990
+ isLearningEnabled(): boolean {
1991
+ return this.config.enableLearning && !!this.neural;
1992
+ }
1993
+
1994
+ private emitEvent(type: string, data: Record<string, unknown>): void {
1995
+ const event = {
1996
+ id: `event_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`,
1997
+ type,
1998
+ source: 'queen-coordinator',
1999
+ timestamp: new Date(),
2000
+ data,
2001
+ };
2002
+
2003
+ this.emit(type, event);
2004
+ this.emit('event', event);
2005
+ }
2006
+ }
2007
+
2008
+ // =============================================================================
2009
+ // Factory Function
2010
+ // =============================================================================
2011
+
2012
+ /**
2013
+ * Create a Queen Coordinator instance
2014
+ */
2015
+ export function createQueenCoordinator(
2016
+ swarm: ISwarmCoordinator,
2017
+ config?: Partial<QueenCoordinatorConfig>,
2018
+ neural?: INeuralLearningSystem,
2019
+ memory?: IMemoryService
2020
+ ): QueenCoordinator {
2021
+ return new QueenCoordinator(swarm, config, neural, memory);
2022
+ }
2023
+
2024
+ export default QueenCoordinator;