@sparkleideas/swarm 3.0.0-alpha.6-patch.16 → 3.0.0-alpha.6-patch.18

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 (126) hide show
  1. package/package.json +1 -1
  2. package/dist/agent-pool.d.ts +0 -52
  3. package/dist/agent-pool.d.ts.map +0 -1
  4. package/dist/agent-pool.js +0 -365
  5. package/dist/agent-pool.js.map +0 -1
  6. package/dist/application/commands/create-task.command.d.ts +0 -64
  7. package/dist/application/commands/create-task.command.d.ts.map +0 -1
  8. package/dist/application/commands/create-task.command.js +0 -77
  9. package/dist/application/commands/create-task.command.js.map +0 -1
  10. package/dist/application/commands/spawn-agent.command.d.ts +0 -63
  11. package/dist/application/commands/spawn-agent.command.d.ts.map +0 -1
  12. package/dist/application/commands/spawn-agent.command.js +0 -74
  13. package/dist/application/commands/spawn-agent.command.js.map +0 -1
  14. package/dist/application/index.d.ts +0 -9
  15. package/dist/application/index.d.ts.map +0 -1
  16. package/dist/application/index.js +0 -11
  17. package/dist/application/index.js.map +0 -1
  18. package/dist/application/services/swarm-application-service.d.ts +0 -112
  19. package/dist/application/services/swarm-application-service.d.ts.map +0 -1
  20. package/dist/application/services/swarm-application-service.js +0 -153
  21. package/dist/application/services/swarm-application-service.js.map +0 -1
  22. package/dist/attention-coordinator.d.ts +0 -212
  23. package/dist/attention-coordinator.d.ts.map +0 -1
  24. package/dist/attention-coordinator.js +0 -667
  25. package/dist/attention-coordinator.js.map +0 -1
  26. package/dist/consensus/byzantine.d.ts +0 -63
  27. package/dist/consensus/byzantine.d.ts.map +0 -1
  28. package/dist/consensus/byzantine.js +0 -316
  29. package/dist/consensus/byzantine.js.map +0 -1
  30. package/dist/consensus/gossip.d.ts +0 -69
  31. package/dist/consensus/gossip.d.ts.map +0 -1
  32. package/dist/consensus/gossip.js +0 -378
  33. package/dist/consensus/gossip.js.map +0 -1
  34. package/dist/consensus/index.d.ts +0 -49
  35. package/dist/consensus/index.d.ts.map +0 -1
  36. package/dist/consensus/index.js +0 -203
  37. package/dist/consensus/index.js.map +0 -1
  38. package/dist/consensus/raft.d.ts +0 -62
  39. package/dist/consensus/raft.d.ts.map +0 -1
  40. package/dist/consensus/raft.js +0 -324
  41. package/dist/consensus/raft.js.map +0 -1
  42. package/dist/coordination/agent-registry.d.ts +0 -68
  43. package/dist/coordination/agent-registry.d.ts.map +0 -1
  44. package/dist/coordination/agent-registry.js +0 -412
  45. package/dist/coordination/agent-registry.js.map +0 -1
  46. package/dist/coordination/index.d.ts +0 -8
  47. package/dist/coordination/index.d.ts.map +0 -1
  48. package/dist/coordination/index.js +0 -8
  49. package/dist/coordination/index.js.map +0 -1
  50. package/dist/coordination/swarm-hub.d.ts +0 -150
  51. package/dist/coordination/swarm-hub.d.ts.map +0 -1
  52. package/dist/coordination/swarm-hub.js +0 -617
  53. package/dist/coordination/swarm-hub.js.map +0 -1
  54. package/dist/coordination/task-orchestrator.d.ts +0 -96
  55. package/dist/coordination/task-orchestrator.d.ts.map +0 -1
  56. package/dist/coordination/task-orchestrator.js +0 -412
  57. package/dist/coordination/task-orchestrator.js.map +0 -1
  58. package/dist/domain/entities/agent.d.ts +0 -151
  59. package/dist/domain/entities/agent.d.ts.map +0 -1
  60. package/dist/domain/entities/agent.js +0 -280
  61. package/dist/domain/entities/agent.js.map +0 -1
  62. package/dist/domain/entities/task.d.ts +0 -133
  63. package/dist/domain/entities/task.d.ts.map +0 -1
  64. package/dist/domain/entities/task.js +0 -261
  65. package/dist/domain/entities/task.js.map +0 -1
  66. package/dist/domain/index.d.ts +0 -11
  67. package/dist/domain/index.d.ts.map +0 -1
  68. package/dist/domain/index.js +0 -11
  69. package/dist/domain/index.js.map +0 -1
  70. package/dist/domain/repositories/agent-repository.interface.d.ts +0 -57
  71. package/dist/domain/repositories/agent-repository.interface.d.ts.map +0 -1
  72. package/dist/domain/repositories/agent-repository.interface.js +0 -9
  73. package/dist/domain/repositories/agent-repository.interface.js.map +0 -1
  74. package/dist/domain/repositories/task-repository.interface.d.ts +0 -61
  75. package/dist/domain/repositories/task-repository.interface.d.ts.map +0 -1
  76. package/dist/domain/repositories/task-repository.interface.js +0 -9
  77. package/dist/domain/repositories/task-repository.interface.js.map +0 -1
  78. package/dist/domain/services/coordination-service.d.ts +0 -84
  79. package/dist/domain/services/coordination-service.d.ts.map +0 -1
  80. package/dist/domain/services/coordination-service.js +0 -231
  81. package/dist/domain/services/coordination-service.js.map +0 -1
  82. package/dist/federation-hub.d.ts +0 -284
  83. package/dist/federation-hub.d.ts.map +0 -1
  84. package/dist/federation-hub.js +0 -692
  85. package/dist/federation-hub.js.map +0 -1
  86. package/dist/index.d.ts +0 -107
  87. package/dist/index.d.ts.map +0 -1
  88. package/dist/index.js +0 -142
  89. package/dist/index.js.map +0 -1
  90. package/dist/message-bus.d.ts +0 -48
  91. package/dist/message-bus.d.ts.map +0 -1
  92. package/dist/message-bus.js +0 -499
  93. package/dist/message-bus.js.map +0 -1
  94. package/dist/queen-coordinator.d.ts +0 -577
  95. package/dist/queen-coordinator.d.ts.map +0 -1
  96. package/dist/queen-coordinator.js +0 -1308
  97. package/dist/queen-coordinator.js.map +0 -1
  98. package/dist/shared/events.d.ts +0 -63
  99. package/dist/shared/events.d.ts.map +0 -1
  100. package/dist/shared/events.js +0 -203
  101. package/dist/shared/events.js.map +0 -1
  102. package/dist/shared/types.d.ts +0 -212
  103. package/dist/shared/types.d.ts.map +0 -1
  104. package/dist/shared/types.js +0 -22
  105. package/dist/shared/types.js.map +0 -1
  106. package/dist/topology-manager.d.ts +0 -62
  107. package/dist/topology-manager.d.ts.map +0 -1
  108. package/dist/topology-manager.js +0 -538
  109. package/dist/topology-manager.js.map +0 -1
  110. package/dist/types.d.ts +0 -353
  111. package/dist/types.d.ts.map +0 -1
  112. package/dist/types.js +0 -43
  113. package/dist/types.js.map +0 -1
  114. package/dist/unified-coordinator.d.ts +0 -260
  115. package/dist/unified-coordinator.d.ts.map +0 -1
  116. package/dist/unified-coordinator.js +0 -1460
  117. package/dist/unified-coordinator.js.map +0 -1
  118. package/dist/workers/index.d.ts +0 -29
  119. package/dist/workers/index.d.ts.map +0 -1
  120. package/dist/workers/index.js +0 -49
  121. package/dist/workers/index.js.map +0 -1
  122. package/dist/workers/worker-dispatch.d.ts +0 -239
  123. package/dist/workers/worker-dispatch.d.ts.map +0 -1
  124. package/dist/workers/worker-dispatch.js +0 -846
  125. package/dist/workers/worker-dispatch.js.map +0 -1
  126. package/tsconfig.build.tsbuildinfo +0 -1
@@ -1,1308 +0,0 @@
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 @sparkleideas/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 using hash-based approach.
509
- * For higher quality embeddings, integrate agentic-flow's computeEmbedding.
510
- */
511
- createSimpleEmbedding(text) {
512
- // Hash-based embedding - lightweight and fast for local similarity matching
513
- // For production ML embeddings, use: import('agentic-flow').computeEmbedding
514
- const embedding = new Float32Array(768);
515
- const words = text.toLowerCase().split(/\s+/);
516
- for (let i = 0; i < words.length; i++) {
517
- const word = words[i];
518
- for (let j = 0; j < word.length; j++) {
519
- const idx = (word.charCodeAt(j) * (i + 1) * (j + 1)) % 768;
520
- embedding[idx] += 1 / words.length;
521
- }
522
- }
523
- // Normalize
524
- let norm = 0;
525
- for (let i = 0; i < embedding.length; i++) {
526
- norm += embedding[i] * embedding[i];
527
- }
528
- norm = Math.sqrt(norm);
529
- if (norm > 0) {
530
- for (let i = 0; i < embedding.length; i++) {
531
- embedding[i] /= norm;
532
- }
533
- }
534
- return embedding;
535
- }
536
- /**
537
- * Estimate resource requirements
538
- */
539
- estimateResources(task, complexity) {
540
- const minAgents = complexity > 0.7 ? 2 : 1;
541
- const maxAgents = complexity > 0.8 ? 4 : complexity > 0.5 ? 3 : 2;
542
- return {
543
- minAgents,
544
- maxAgents,
545
- memoryMb: Math.round(256 + complexity * 512),
546
- cpuIntensive: ['coding', 'analysis'].includes(task.type),
547
- ioIntensive: ['research', 'testing'].includes(task.type),
548
- networkRequired: task.type === 'research',
549
- };
550
- }
551
- /**
552
- * Calculate confidence in analysis
553
- */
554
- calculateAnalysisConfidence(patterns, complexity, capabilities) {
555
- let confidence = 0.5; // Base confidence
556
- // Higher confidence with more matching patterns
557
- confidence += patterns.length * 0.1;
558
- // Higher confidence for simpler tasks
559
- confidence += (1 - complexity) * 0.2;
560
- // Higher confidence with clear capabilities
561
- confidence += Math.min(capabilities.length * 0.05, 0.15);
562
- // Boost from high-success patterns
563
- const avgPatternSuccess = patterns.length > 0
564
- ? patterns.reduce((sum, p) => sum + p.successRate, 0) / patterns.length
565
- : 0;
566
- confidence += avgPatternSuccess * 0.1;
567
- return Math.min(confidence, 0.95);
568
- }
569
- // ===========================================================================
570
- // Agent Delegation
571
- // ===========================================================================
572
- /**
573
- * Delegate a task to agents based on analysis
574
- *
575
- * @param task - Task to delegate
576
- * @param analysis - Previous task analysis
577
- * @returns Delegation plan
578
- */
579
- async delegateToAgents(task, analysis) {
580
- const startTime = performance.now();
581
- this.planCounter++;
582
- const planId = `plan_${Date.now()}_${this.planCounter}`;
583
- // Score all available agents for this task
584
- const agentScores = this.scoreAgents(task, analysis.matchedPatterns);
585
- // Select primary agent
586
- const primaryAgent = this.selectPrimaryAgent(task, agentScores, analysis);
587
- // Select backup agents
588
- const backupAgents = this.selectBackupAgents(task, agentScores, primaryAgent);
589
- // Create parallel assignments for subtasks
590
- const parallelAssignments = this.createParallelAssignments(analysis.subtasks, agentScores);
591
- // Determine execution strategy
592
- const strategy = this.determineExecutionStrategy(analysis);
593
- const plan = {
594
- planId,
595
- taskId: task.id.id,
596
- analysisId: analysis.analysisId,
597
- primaryAgent,
598
- backupAgents,
599
- parallelAssignments,
600
- strategy,
601
- estimatedCompletionMs: analysis.estimatedDurationMs,
602
- timestamp: new Date(),
603
- };
604
- // Store the plan
605
- this.delegationPlans.set(planId, plan);
606
- // Execute the delegation
607
- await this.executeDelegation(plan);
608
- // Record latency
609
- const latency = performance.now() - startTime;
610
- this.delegationLatencies.push(latency);
611
- if (this.delegationLatencies.length > 100) {
612
- this.delegationLatencies.shift();
613
- }
614
- this.emitEvent('queen.task.delegated', {
615
- planId,
616
- taskId: task.id.id,
617
- primaryAgent: primaryAgent.agentId,
618
- strategy,
619
- latencyMs: latency,
620
- });
621
- return plan;
622
- }
623
- /**
624
- * Score agents for task assignment
625
- */
626
- scoreAgents(task, patterns) {
627
- const agents = this.swarm.getAllAgents();
628
- const scores = [];
629
- for (const agent of agents) {
630
- const score = this.scoreAgent(agent, task, patterns);
631
- scores.push(score);
632
- }
633
- // Sort by total score descending
634
- scores.sort((a, b) => b.totalScore - a.totalScore);
635
- return scores;
636
- }
637
- scoreAgent(agent, task, patterns) {
638
- const domain = this.getAgentDomain(agent);
639
- // Capability score - how well agent capabilities match task
640
- const capabilityScore = this.calculateCapabilityScore(agent, task);
641
- // Load score - prefer less loaded agents
642
- const loadScore = 1 - agent.workload;
643
- // Performance score - based on past performance
644
- const performanceScore = this.calculatePerformanceScore(agent, patterns);
645
- // Health score - agent health
646
- const healthScore = agent.health;
647
- // Availability score - is agent actually available
648
- const availabilityScore = agent.status === 'idle' ? 1.0 :
649
- agent.status === 'busy' ? 0.3 : 0.0;
650
- // Weighted total
651
- const totalScore = capabilityScore * 0.30 +
652
- loadScore * 0.20 +
653
- performanceScore * 0.25 +
654
- healthScore * 0.15 +
655
- availabilityScore * 0.10;
656
- return {
657
- agentId: agent.id.id,
658
- domain,
659
- totalScore,
660
- capabilityScore,
661
- loadScore,
662
- performanceScore,
663
- healthScore,
664
- availabilityScore,
665
- };
666
- }
667
- calculateCapabilityScore(agent, task) {
668
- let score = 0.5; // Base score
669
- // Check type match
670
- const typeMatches = {
671
- research: ['researcher'],
672
- analysis: ['analyst', 'researcher'],
673
- coding: ['coder'],
674
- testing: ['tester'],
675
- review: ['reviewer'],
676
- documentation: ['documenter'],
677
- coordination: ['coordinator', 'queen'],
678
- consensus: ['coordinator', 'queen'],
679
- custom: ['worker'],
680
- };
681
- const preferredTypes = typeMatches[task.type] || ['worker'];
682
- if (preferredTypes.includes(agent.type)) {
683
- score += 0.3;
684
- }
685
- // Check specific capabilities
686
- const caps = agent.capabilities;
687
- if (task.type === 'coding' && caps.codeGeneration)
688
- score += 0.1;
689
- if (task.type === 'review' && caps.codeReview)
690
- score += 0.1;
691
- if (task.type === 'testing' && caps.testing)
692
- score += 0.1;
693
- if (task.type === 'coordination' && caps.coordination)
694
- score += 0.1;
695
- return Math.min(score, 1.0);
696
- }
697
- calculatePerformanceScore(agent, patterns) {
698
- // Base on agent's success rate
699
- let score = agent.metrics.successRate;
700
- // Boost if patterns suggest this agent type is successful
701
- const agentDomain = this.getAgentDomain(agent);
702
- for (const pattern of patterns) {
703
- if (pattern.strategy.toLowerCase().includes(agentDomain)) {
704
- score += pattern.successRate * 0.1;
705
- }
706
- }
707
- return Math.min(score, 1.0);
708
- }
709
- getAgentDomain(agent) {
710
- // Determine domain from agent type
711
- switch (agent.type) {
712
- case 'queen':
713
- return 'queen';
714
- case 'specialist':
715
- return 'security';
716
- case 'architect':
717
- return 'core';
718
- case 'coder':
719
- return 'integration';
720
- case 'tester':
721
- return 'support';
722
- default:
723
- return 'core';
724
- }
725
- }
726
- selectPrimaryAgent(task, scores, analysis) {
727
- // Prefer agent from recommended domain
728
- const domainAgents = scores.filter(s => s.domain === analysis.recommendedDomain);
729
- // Fall back to best overall if no domain match
730
- const bestScore = domainAgents.length > 0 ? domainAgents[0] : scores[0];
731
- return {
732
- agentId: bestScore.agentId,
733
- domain: bestScore.domain,
734
- taskId: task.id.id,
735
- score: bestScore.totalScore,
736
- assignedAt: new Date(),
737
- };
738
- }
739
- selectBackupAgents(task, scores, primary) {
740
- const backups = [];
741
- // Select up to 2 backup agents
742
- for (const score of scores) {
743
- if (score.agentId === primary.agentId)
744
- continue;
745
- if (score.totalScore < 0.3)
746
- continue;
747
- if (backups.length >= 2)
748
- break;
749
- backups.push({
750
- agentId: score.agentId,
751
- domain: score.domain,
752
- taskId: task.id.id,
753
- score: score.totalScore,
754
- assignedAt: new Date(),
755
- });
756
- }
757
- return backups;
758
- }
759
- createParallelAssignments(subtasks, scores) {
760
- const assignments = [];
761
- for (const subtask of subtasks) {
762
- // Find best agent for this subtask's domain
763
- const domainScores = scores.filter(s => s.domain === subtask.recommendedDomain);
764
- const bestScore = domainScores.length > 0 ? domainScores[0] : scores[0];
765
- assignments.push({
766
- subtaskId: subtask.id,
767
- agentId: bestScore.agentId,
768
- domain: subtask.recommendedDomain,
769
- dependencies: subtask.dependencies,
770
- });
771
- }
772
- return assignments;
773
- }
774
- determineExecutionStrategy(analysis) {
775
- const subtaskCount = analysis.subtasks.length;
776
- if (subtaskCount === 0) {
777
- return 'sequential';
778
- }
779
- // Check for dependencies
780
- const hasDependencies = analysis.subtasks.some(st => st.dependencies.length > 0);
781
- if (!hasDependencies && subtaskCount > 2) {
782
- return 'parallel';
783
- }
784
- if (hasDependencies && subtaskCount > 3) {
785
- return 'pipeline';
786
- }
787
- if (analysis.complexity > 0.7) {
788
- return 'fan-out-fan-in';
789
- }
790
- return 'hybrid';
791
- }
792
- async executeDelegation(plan) {
793
- // Delegate to the primary agent
794
- await this.swarm.assignTaskToDomain(plan.taskId, plan.primaryAgent.domain);
795
- // Notify about the delegation
796
- await this.swarm.broadcastMessage({
797
- type: 'delegation',
798
- planId: plan.planId,
799
- taskId: plan.taskId,
800
- primaryAgent: plan.primaryAgent.agentId,
801
- strategy: plan.strategy,
802
- }, 'normal');
803
- }
804
- // ===========================================================================
805
- // Swarm Health Monitoring
806
- // ===========================================================================
807
- /**
808
- * Monitor swarm health and detect issues
809
- *
810
- * @returns Health report
811
- */
812
- async monitorSwarmHealth() {
813
- this.reportCounter++;
814
- const reportId = `health_${Date.now()}_${this.reportCounter}`;
815
- const agents = this.swarm.getAllAgents();
816
- const status = this.swarm.getStatus();
817
- const metrics = this.swarm.getMetrics();
818
- // Compute domain health
819
- const domainHealth = this.computeDomainHealth(status.domains);
820
- // Compute agent health
821
- const agentHealth = this.computeAgentHealth(agents);
822
- // Detect bottlenecks
823
- const bottlenecks = this.detectBottlenecks(status, agents, metrics);
824
- // Generate alerts
825
- const alerts = this.generateAlerts(bottlenecks, agentHealth, metrics);
826
- // Overall health score
827
- const overallHealth = this.calculateOverallHealth(domainHealth, agentHealth, bottlenecks);
828
- // Generate recommendations
829
- const recommendations = this.generateRecommendations(bottlenecks, overallHealth);
830
- // Compile health metrics
831
- const healthMetrics = {
832
- totalAgents: agents.length,
833
- activeAgents: agents.filter(a => a.status === 'idle' || a.status === 'busy').length,
834
- idleAgents: agents.filter(a => a.status === 'idle').length,
835
- errorAgents: agents.filter(a => a.status === 'error').length,
836
- totalTasks: metrics.totalTasks,
837
- completedTasks: metrics.completedTasks,
838
- failedTasks: metrics.failedTasks,
839
- avgTaskDurationMs: metrics.avgTaskDurationMs,
840
- taskThroughputPerMin: metrics.completedTasks / Math.max(metrics.uptime / 60, 1),
841
- consensusSuccessRate: metrics.consensusSuccessRate,
842
- };
843
- const report = {
844
- reportId,
845
- timestamp: new Date(),
846
- overallHealth,
847
- domainHealth,
848
- agentHealth,
849
- bottlenecks,
850
- alerts,
851
- metrics: healthMetrics,
852
- recommendations,
853
- };
854
- // Store in history
855
- this.healthHistory.push(report);
856
- if (this.healthHistory.length > 100) {
857
- this.healthHistory.shift();
858
- }
859
- this.lastHealthReport = report;
860
- this.emitEvent('queen.health.report', {
861
- reportId,
862
- overallHealth,
863
- bottleneckCount: bottlenecks.length,
864
- alertCount: alerts.length,
865
- });
866
- return report;
867
- }
868
- computeDomainHealth(domains) {
869
- const health = new Map();
870
- for (const domain of domains) {
871
- const utilization = domain.agentCount > 0
872
- ? domain.busyAgents / domain.agentCount
873
- : 0;
874
- const queuePressure = domain.tasksQueued > 5 ? 0.3 : domain.tasksQueued * 0.05;
875
- const domainHealth = Math.max(0, 1 - queuePressure - (1 - utilization) * 0.2);
876
- health.set(domain.name, {
877
- domain: domain.name,
878
- health: domainHealth,
879
- activeAgents: domain.availableAgents + domain.busyAgents,
880
- totalAgents: domain.agentCount,
881
- queuedTasks: domain.tasksQueued,
882
- avgResponseTimeMs: 0, // Would need tracking
883
- errorRate: 0, // Would need tracking
884
- });
885
- }
886
- return health;
887
- }
888
- computeAgentHealth(agents) {
889
- return agents.map(agent => ({
890
- agentId: agent.id.id,
891
- domain: this.getAgentDomain(agent),
892
- health: agent.health,
893
- status: agent.status,
894
- lastHeartbeat: agent.lastHeartbeat,
895
- currentLoad: agent.workload,
896
- recentErrors: agent.metrics.tasksFailed,
897
- }));
898
- }
899
- detectBottlenecks(status, agents, metrics) {
900
- const bottlenecks = [];
901
- // Check domain queues
902
- for (const domain of status.domains) {
903
- if (domain.tasksQueued > this.config.bottleneckThresholds.queueDepth) {
904
- bottlenecks.push({
905
- type: 'domain',
906
- location: domain.name,
907
- severity: domain.tasksQueued > 20 ? 'critical' : 'high',
908
- description: `High task queue depth in ${domain.name} domain`,
909
- impact: `${domain.tasksQueued} tasks waiting for processing`,
910
- suggestedAction: `Consider scaling ${domain.name} domain agents`,
911
- });
912
- }
913
- }
914
- // Check error agents
915
- const errorAgents = agents.filter(a => a.status === 'error');
916
- if (errorAgents.length > 0) {
917
- bottlenecks.push({
918
- type: 'agent',
919
- location: errorAgents.map(a => a.id.id).join(', '),
920
- severity: errorAgents.length > 3 ? 'critical' : 'medium',
921
- description: `${errorAgents.length} agents in error state`,
922
- impact: 'Reduced processing capacity',
923
- suggestedAction: 'Investigate and recover error agents',
924
- });
925
- }
926
- // Check coordination latency
927
- if (metrics.coordinationLatencyMs > this.config.bottleneckThresholds.responseTimeMs) {
928
- bottlenecks.push({
929
- type: 'resource',
930
- location: 'coordination',
931
- severity: 'high',
932
- description: 'High coordination latency detected',
933
- impact: `Current latency: ${metrics.coordinationLatencyMs}ms`,
934
- suggestedAction: 'Optimize coordination or reduce concurrent tasks',
935
- });
936
- }
937
- return bottlenecks;
938
- }
939
- generateAlerts(bottlenecks, agentHealth, metrics) {
940
- const alerts = [];
941
- // Generate alerts for critical bottlenecks
942
- for (const bottleneck of bottlenecks) {
943
- if (bottleneck.severity === 'critical' || bottleneck.severity === 'high') {
944
- alerts.push({
945
- alertId: `alert_${Date.now()}_${alerts.length}`,
946
- type: bottleneck.severity === 'critical' ? 'critical' : 'error',
947
- source: bottleneck.location,
948
- message: bottleneck.description,
949
- timestamp: new Date(),
950
- acknowledged: false,
951
- });
952
- }
953
- }
954
- // Alert on low overall agent health
955
- const avgHealth = agentHealth.length > 0
956
- ? agentHealth.reduce((sum, a) => sum + a.health, 0) / agentHealth.length
957
- : 1.0;
958
- if (avgHealth < 0.5) {
959
- alerts.push({
960
- alertId: `alert_${Date.now()}_health`,
961
- type: avgHealth < 0.3 ? 'critical' : 'warning',
962
- source: 'swarm',
963
- message: `Low average agent health: ${(avgHealth * 100).toFixed(1)}%`,
964
- timestamp: new Date(),
965
- acknowledged: false,
966
- });
967
- }
968
- // Alert on high failure rate
969
- const failureRate = metrics.totalTasks > 0
970
- ? metrics.failedTasks / metrics.totalTasks
971
- : 0;
972
- if (failureRate > this.config.bottleneckThresholds.errorRate) {
973
- alerts.push({
974
- alertId: `alert_${Date.now()}_failures`,
975
- type: failureRate > 0.2 ? 'critical' : 'warning',
976
- source: 'tasks',
977
- message: `High task failure rate: ${(failureRate * 100).toFixed(1)}%`,
978
- timestamp: new Date(),
979
- acknowledged: false,
980
- });
981
- }
982
- return alerts;
983
- }
984
- calculateOverallHealth(domainHealth, agentHealth, bottlenecks) {
985
- // Average domain health
986
- const domainHealthAvg = domainHealth.size > 0
987
- ? Array.from(domainHealth.values()).reduce((sum, d) => sum + d.health, 0) / domainHealth.size
988
- : 1.0;
989
- // Average agent health
990
- const agentHealthAvg = agentHealth.length > 0
991
- ? agentHealth.reduce((sum, a) => sum + a.health, 0) / agentHealth.length
992
- : 1.0;
993
- // Bottleneck penalty
994
- const bottleneckPenalty = bottlenecks.reduce((penalty, b) => {
995
- switch (b.severity) {
996
- case 'critical': return penalty + 0.2;
997
- case 'high': return penalty + 0.1;
998
- case 'medium': return penalty + 0.05;
999
- case 'low': return penalty + 0.02;
1000
- default: return penalty;
1001
- }
1002
- }, 0);
1003
- const overallHealth = (domainHealthAvg * 0.4 + agentHealthAvg * 0.4) - bottleneckPenalty;
1004
- return Math.max(0, Math.min(1, overallHealth));
1005
- }
1006
- generateRecommendations(bottlenecks, overallHealth) {
1007
- const recommendations = [];
1008
- // Add bottleneck-specific recommendations
1009
- for (const bottleneck of bottlenecks) {
1010
- recommendations.push(bottleneck.suggestedAction);
1011
- }
1012
- // General recommendations based on health
1013
- if (overallHealth < 0.5) {
1014
- recommendations.push('Consider reducing task load or adding more agents');
1015
- }
1016
- if (overallHealth < 0.3) {
1017
- recommendations.push('URGENT: Investigate system-wide issues immediately');
1018
- }
1019
- return [...new Set(recommendations)]; // Deduplicate
1020
- }
1021
- startHealthMonitoring() {
1022
- this.healthCheckInterval = setInterval(async () => {
1023
- try {
1024
- await this.monitorSwarmHealth();
1025
- }
1026
- catch (error) {
1027
- this.emitEvent('queen.health.error', { error: String(error) });
1028
- }
1029
- }, this.config.healthCheckIntervalMs);
1030
- }
1031
- stopHealthMonitoring() {
1032
- if (this.healthCheckInterval) {
1033
- clearInterval(this.healthCheckInterval);
1034
- this.healthCheckInterval = undefined;
1035
- }
1036
- }
1037
- // ===========================================================================
1038
- // Consensus Coordination
1039
- // ===========================================================================
1040
- /**
1041
- * Coordinate consensus for a decision
1042
- *
1043
- * @param decision - Decision requiring consensus
1044
- * @returns Consensus result
1045
- */
1046
- async coordinateConsensus(decision) {
1047
- const startTime = performance.now();
1048
- this.decisionCounter++;
1049
- decision.decisionId = `decision_${Date.now()}_${this.decisionCounter}`;
1050
- // Store active decision
1051
- this.activeDecisions.set(decision.decisionId, decision);
1052
- try {
1053
- let result;
1054
- switch (decision.requiredConsensus) {
1055
- case 'queen-override':
1056
- // Queen can make unilateral decisions for certain types
1057
- result = this.queenOverride(decision);
1058
- break;
1059
- case 'unanimous':
1060
- result = await this.unanimousConsensus(decision);
1061
- break;
1062
- case 'supermajority':
1063
- result = await this.supermajorityConsensus(decision);
1064
- break;
1065
- case 'weighted':
1066
- result = await this.weightedConsensus(decision);
1067
- break;
1068
- case 'majority':
1069
- default:
1070
- result = await this.majorityConsensus(decision);
1071
- }
1072
- // Record latency
1073
- const latency = performance.now() - startTime;
1074
- this.consensusLatencies.push(latency);
1075
- if (this.consensusLatencies.length > 100) {
1076
- this.consensusLatencies.shift();
1077
- }
1078
- this.emitEvent('queen.consensus.completed', {
1079
- decisionId: decision.decisionId,
1080
- type: decision.requiredConsensus,
1081
- approved: result.approved,
1082
- approvalRate: result.approvalRate,
1083
- latencyMs: latency,
1084
- });
1085
- return result;
1086
- }
1087
- finally {
1088
- this.activeDecisions.delete(decision.decisionId);
1089
- }
1090
- }
1091
- queenOverride(decision) {
1092
- // Queen can make immediate decisions for:
1093
- // - Emergency actions
1094
- // - Agent termination
1095
- // - Priority overrides
1096
- const allowedTypes = ['emergency-action', 'agent-termination', 'priority-override'];
1097
- if (!allowedTypes.includes(decision.type)) {
1098
- throw new Error(`Queen override not allowed for decision type: ${decision.type}`);
1099
- }
1100
- return {
1101
- proposalId: decision.decisionId,
1102
- approved: true,
1103
- approvalRate: 1.0,
1104
- participationRate: 1.0,
1105
- finalValue: decision.proposal,
1106
- rounds: 1,
1107
- durationMs: 0,
1108
- };
1109
- }
1110
- async majorityConsensus(decision) {
1111
- // Use swarm's consensus engine with majority threshold
1112
- const result = await this.swarm.proposeConsensus({
1113
- decision,
1114
- threshold: 0.51,
1115
- timeout: this.config.consensusTimeouts.majority,
1116
- });
1117
- return result;
1118
- }
1119
- async supermajorityConsensus(decision) {
1120
- // Use swarm's consensus engine with 2/3 threshold
1121
- const result = await this.swarm.proposeConsensus({
1122
- decision,
1123
- threshold: 0.67,
1124
- timeout: this.config.consensusTimeouts.supermajority,
1125
- });
1126
- return result;
1127
- }
1128
- async unanimousConsensus(decision) {
1129
- // Use swarm's consensus engine with unanimous requirement
1130
- const result = await this.swarm.proposeConsensus({
1131
- decision,
1132
- threshold: 1.0,
1133
- timeout: this.config.consensusTimeouts.unanimous,
1134
- });
1135
- return result;
1136
- }
1137
- async weightedConsensus(decision) {
1138
- // Weighted consensus based on agent performance
1139
- // For now, delegate to the standard consensus with metadata
1140
- const agents = this.swarm.getAllAgents();
1141
- const weights = new Map();
1142
- for (const agent of agents) {
1143
- const weight = agent.metrics.successRate * agent.health;
1144
- weights.set(agent.id.id, weight);
1145
- }
1146
- const result = await this.swarm.proposeConsensus({
1147
- decision,
1148
- weights: Object.fromEntries(weights),
1149
- threshold: 0.51,
1150
- timeout: this.config.consensusTimeouts.majority,
1151
- });
1152
- return result;
1153
- }
1154
- // ===========================================================================
1155
- // Learning from Outcomes
1156
- // ===========================================================================
1157
- /**
1158
- * Record task outcome for learning
1159
- *
1160
- * @param task - Completed task
1161
- * @param result - Task result
1162
- */
1163
- async recordOutcome(task, result) {
1164
- // Store in outcome history
1165
- this.outcomeHistory.push(result);
1166
- if (this.outcomeHistory.length > 1000) {
1167
- this.outcomeHistory.shift();
1168
- }
1169
- // Learn from outcome if neural system available
1170
- if (this.neural && this.config.enableLearning) {
1171
- await this.learnFromOutcome(task, result);
1172
- }
1173
- // Store in memory service if available
1174
- if (this.memory) {
1175
- await this.storeOutcomeMemory(task, result);
1176
- }
1177
- this.emitEvent('queen.outcome.recorded', {
1178
- taskId: task.id.id,
1179
- success: result.success,
1180
- durationMs: result.durationMs,
1181
- qualityScore: result.metrics.qualityScore,
1182
- });
1183
- }
1184
- async learnFromOutcome(task, result) {
1185
- if (!this.neural)
1186
- return;
1187
- // Create trajectory for this task
1188
- const trajectoryId = this.neural.beginTask(task.description || task.name, result.domain);
1189
- // Record the execution step
1190
- const embedding = this.createSimpleEmbedding(task.description || task.name);
1191
- const reward = result.success
1192
- ? result.metrics.qualityScore * 0.8 + 0.2
1193
- : result.metrics.qualityScore * 0.3;
1194
- this.neural.recordStep(trajectoryId, `executed_${task.type}_in_${result.domain}`, reward, embedding);
1195
- // Complete the task trajectory
1196
- await this.neural.completeTask(trajectoryId, result.metrics.qualityScore);
1197
- }
1198
- async storeOutcomeMemory(task, result) {
1199
- if (!this.memory)
1200
- return;
1201
- try {
1202
- await this.memory.store({
1203
- key: `outcome_${task.id.id}`,
1204
- content: this.formatOutcomeContent(task, result),
1205
- namespace: 'queen-outcomes',
1206
- tags: [
1207
- task.type,
1208
- result.domain,
1209
- result.success ? 'success' : 'failure',
1210
- ],
1211
- metadata: {
1212
- taskId: task.id.id,
1213
- success: result.success,
1214
- durationMs: result.durationMs,
1215
- qualityScore: result.metrics.qualityScore,
1216
- agentId: result.agentId,
1217
- },
1218
- });
1219
- }
1220
- catch (error) {
1221
- // Log but don't fail - memory storage is optional
1222
- this.emitEvent('queen.memory.error', { error: String(error) });
1223
- }
1224
- }
1225
- formatOutcomeContent(task, result) {
1226
- return [
1227
- `Task: ${task.name}`,
1228
- `Type: ${task.type}`,
1229
- `Domain: ${result.domain}`,
1230
- `Agent: ${result.agentId}`,
1231
- `Success: ${result.success}`,
1232
- `Duration: ${result.durationMs}ms`,
1233
- `Quality: ${result.metrics.qualityScore}`,
1234
- `Description: ${task.description || 'N/A'}`,
1235
- ].join('\n');
1236
- }
1237
- // ===========================================================================
1238
- // Utility Methods
1239
- // ===========================================================================
1240
- /**
1241
- * Get the last health report
1242
- */
1243
- getLastHealthReport() {
1244
- return this.lastHealthReport;
1245
- }
1246
- /**
1247
- * Get outcome history
1248
- */
1249
- getOutcomeHistory() {
1250
- return [...this.outcomeHistory];
1251
- }
1252
- /**
1253
- * Get analysis cache
1254
- */
1255
- getAnalysisCache() {
1256
- return new Map(this.analysisCache);
1257
- }
1258
- /**
1259
- * Get delegation plans
1260
- */
1261
- getDelegationPlans() {
1262
- return new Map(this.delegationPlans);
1263
- }
1264
- /**
1265
- * Get performance statistics
1266
- */
1267
- getPerformanceStats() {
1268
- const avg = (arr) => arr.length > 0
1269
- ? arr.reduce((a, b) => a + b, 0) / arr.length
1270
- : 0;
1271
- return {
1272
- avgAnalysisLatencyMs: avg(this.analysisLatencies),
1273
- avgDelegationLatencyMs: avg(this.delegationLatencies),
1274
- avgConsensusLatencyMs: avg(this.consensusLatencies),
1275
- totalAnalyses: this.analysisCounter,
1276
- totalDelegations: this.planCounter,
1277
- totalDecisions: this.decisionCounter,
1278
- };
1279
- }
1280
- /**
1281
- * Check if learning is enabled
1282
- */
1283
- isLearningEnabled() {
1284
- return this.config.enableLearning && !!this.neural;
1285
- }
1286
- emitEvent(type, data) {
1287
- const event = {
1288
- id: `event_${Date.now()}_${Math.random().toString(36).substr(2, 6)}`,
1289
- type,
1290
- source: 'queen-coordinator',
1291
- timestamp: new Date(),
1292
- data,
1293
- };
1294
- this.emit(type, event);
1295
- this.emit('event', event);
1296
- }
1297
- }
1298
- // =============================================================================
1299
- // Factory Function
1300
- // =============================================================================
1301
- /**
1302
- * Create a Queen Coordinator instance
1303
- */
1304
- export function createQueenCoordinator(swarm, config, neural, memory) {
1305
- return new QueenCoordinator(swarm, config, neural, memory);
1306
- }
1307
- export default QueenCoordinator;
1308
- //# sourceMappingURL=queen-coordinator.js.map