claude-flow 2.0.0-alpha.71 → 2.0.0-alpha.73

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 (79) hide show
  1. package/.claude/agents/MIGRATION_SUMMARY.md +215 -0
  2. package/.claude/agents/README.md +82 -0
  3. package/.claude/agents/analysis/code-review/analyze-code-quality.md +180 -0
  4. package/.claude/agents/architecture/system-design/arch-system-design.md +156 -0
  5. package/.claude/agents/base-template-generator.md +42 -0
  6. package/.claude/agents/consensus/README.md +246 -0
  7. package/.claude/agents/consensus/byzantine-coordinator.md +63 -0
  8. package/.claude/agents/consensus/crdt-synchronizer.md +997 -0
  9. package/.claude/agents/consensus/gossip-coordinator.md +63 -0
  10. package/.claude/agents/consensus/performance-benchmarker.md +851 -0
  11. package/.claude/agents/consensus/quorum-manager.md +823 -0
  12. package/.claude/agents/consensus/raft-manager.md +63 -0
  13. package/.claude/agents/consensus/security-manager.md +622 -0
  14. package/.claude/agents/core/coder.md +211 -0
  15. package/.claude/agents/core/planner.md +116 -0
  16. package/.claude/agents/core/researcher.md +136 -0
  17. package/.claude/agents/core/reviewer.md +272 -0
  18. package/.claude/agents/core/tester.md +266 -0
  19. package/.claude/agents/data/ml/data-ml-model.md +193 -0
  20. package/.claude/agents/development/backend/dev-backend-api.md +142 -0
  21. package/.claude/agents/devops/ci-cd/ops-cicd-github.md +164 -0
  22. package/.claude/agents/documentation/api-docs/docs-api-openapi.md +174 -0
  23. package/.claude/agents/github/code-review-swarm.md +538 -0
  24. package/.claude/agents/github/github-modes.md +173 -0
  25. package/.claude/agents/github/issue-tracker.md +319 -0
  26. package/.claude/agents/github/multi-repo-swarm.md +553 -0
  27. package/.claude/agents/github/pr-manager.md +191 -0
  28. package/.claude/agents/github/project-board-sync.md +509 -0
  29. package/.claude/agents/github/release-manager.md +367 -0
  30. package/.claude/agents/github/release-swarm.md +583 -0
  31. package/.claude/agents/github/repo-architect.md +398 -0
  32. package/.claude/agents/github/swarm-issue.md +573 -0
  33. package/.claude/agents/github/swarm-pr.md +428 -0
  34. package/.claude/agents/github/sync-coordinator.md +452 -0
  35. package/.claude/agents/github/workflow-automation.md +635 -0
  36. package/.claude/agents/hive-mind/collective-intelligence-coordinator.md +82 -0
  37. package/.claude/agents/hive-mind/consensus-builder.md +102 -0
  38. package/.claude/agents/hive-mind/swarm-memory-manager.md +120 -0
  39. package/.claude/agents/optimization/README.md +243 -0
  40. package/.claude/agents/optimization/benchmark-suite.md +658 -0
  41. package/.claude/agents/optimization/load-balancer.md +424 -0
  42. package/.claude/agents/optimization/performance-monitor.md +665 -0
  43. package/.claude/agents/optimization/resource-allocator.md +667 -0
  44. package/.claude/agents/optimization/topology-optimizer.md +801 -0
  45. package/.claude/agents/sparc/architecture.md +472 -0
  46. package/.claude/agents/sparc/pseudocode.md +318 -0
  47. package/.claude/agents/sparc/refinement.md +525 -0
  48. package/.claude/agents/sparc/specification.md +276 -0
  49. package/.claude/agents/specialized/mobile/spec-mobile-react-native.md +226 -0
  50. package/.claude/agents/swarm/README.md +183 -0
  51. package/.claude/agents/swarm/adaptive-coordinator.md +396 -0
  52. package/.claude/agents/swarm/hierarchical-coordinator.md +256 -0
  53. package/.claude/agents/swarm/mesh-coordinator.md +392 -0
  54. package/.claude/agents/templates/automation-smart-agent.md +205 -0
  55. package/.claude/agents/templates/coordinator-swarm-init.md +90 -0
  56. package/.claude/agents/templates/github-pr-manager.md +177 -0
  57. package/.claude/agents/templates/implementer-sparc-coder.md +259 -0
  58. package/.claude/agents/templates/memory-coordinator.md +187 -0
  59. package/.claude/agents/templates/migration-plan.md +746 -0
  60. package/.claude/agents/templates/orchestrator-task.md +139 -0
  61. package/.claude/agents/templates/performance-analyzer.md +199 -0
  62. package/.claude/agents/templates/sparc-coordinator.md +183 -0
  63. package/.claude/agents/testing/unit/tdd-london-swarm.md +244 -0
  64. package/.claude/agents/testing/validation/production-validator.md +395 -0
  65. package/.claude/settings.json +20 -0
  66. package/.claude/settings.local.json +5 -1
  67. package/bin/claude-flow +1 -1
  68. package/package.json +1 -1
  69. package/src/cli/help-text.js +2 -2
  70. package/src/cli/simple-cli.js +1 -1
  71. package/src/cli/simple-commands/init/agent-copier.js +217 -0
  72. package/src/cli/simple-commands/init/index.js +23 -0
  73. package/src/cli/simple-commands/init/templates/CLAUDE.md +293 -14
  74. package/src/cli/simple-commands/init/templates/settings.json +24 -4
  75. package/src/swarm/advanced-orchestrator.ts +1200 -0
  76. package/src/swarm/claude-code-interface.ts +1268 -0
  77. package/src/swarm/hive-mind-integration.ts +1127 -0
  78. package/src/swarm/mcp-integration-wrapper.ts +860 -0
  79. package/src/swarm/result-aggregator.ts +1046 -0
@@ -0,0 +1,1127 @@
1
+ /**
2
+ * Hive-Mind System Integration Interface
3
+ *
4
+ * This module provides seamless integration with the existing hive-mind system,
5
+ * enabling swarms to leverage collective intelligence, shared memory, and
6
+ * distributed coordination capabilities while maintaining compatibility
7
+ * with the current claude-flow architecture.
8
+ */
9
+
10
+ import { EventEmitter } from 'node:events';
11
+ import { Logger } from '../core/logger.js';
12
+ import { generateId } from '../utils/helpers.js';
13
+ import { MemoryManager } from '../memory/manager.js';
14
+ import type { AdvancedSwarmOrchestrator } from './advanced-orchestrator.js';
15
+ import {
16
+ SwarmExecutionContext,
17
+ SwarmAgent,
18
+ SwarmTask,
19
+ TaskResult,
20
+ SwarmObjective,
21
+ AgentState,
22
+ SwarmMetrics,
23
+ } from './types.js';
24
+
25
+ export interface HiveMindConfig {
26
+ enableSharedIntelligence: boolean;
27
+ enableCollectiveMemory: boolean;
28
+ enableDistributedLearning: boolean;
29
+ enableKnowledgeSharing: boolean;
30
+ hiveMindEndpoint?: string;
31
+ syncInterval: number;
32
+ maxSharedMemorySize: number;
33
+ intelligencePoolSize: number;
34
+ learningRate: number;
35
+ knowledgeRetentionPeriod: number;
36
+ }
37
+
38
+ export interface HiveMindSession {
39
+ id: string;
40
+ swarmId: string;
41
+ participants: string[];
42
+ sharedMemory: Map<string, any>;
43
+ collectiveIntelligence: CollectiveIntelligence;
44
+ knowledgeBase: KnowledgeBase;
45
+ distributedLearning: DistributedLearning;
46
+ status: 'active' | 'paused' | 'terminated';
47
+ startTime: Date;
48
+ lastSync: Date;
49
+ }
50
+
51
+ export interface CollectiveIntelligence {
52
+ patterns: Map<string, Pattern>;
53
+ insights: Map<string, Insight>;
54
+ decisions: Map<string, CollectiveDecision>;
55
+ predictions: Map<string, Prediction>;
56
+ }
57
+
58
+ export interface Pattern {
59
+ id: string;
60
+ type: 'behavioral' | 'performance' | 'error' | 'success';
61
+ description: string;
62
+ frequency: number;
63
+ confidence: number;
64
+ contexts: string[];
65
+ impact: 'low' | 'medium' | 'high';
66
+ discoveredBy: string[];
67
+ lastSeen: Date;
68
+ }
69
+
70
+ export interface Insight {
71
+ id: string;
72
+ category: 'optimization' | 'coordination' | 'quality' | 'efficiency';
73
+ title: string;
74
+ description: string;
75
+ evidence: any[];
76
+ confidence: number;
77
+ applicability: string[];
78
+ contributingAgents: string[];
79
+ timestamp: Date;
80
+ }
81
+
82
+ export interface CollectiveDecision {
83
+ id: string;
84
+ question: string;
85
+ options: DecisionOption[];
86
+ votingResults: Map<string, string>;
87
+ consensus: string;
88
+ confidence: number;
89
+ reasoning: string;
90
+ participants: string[];
91
+ timestamp: Date;
92
+ }
93
+
94
+ export interface DecisionOption {
95
+ id: string;
96
+ description: string;
97
+ pros: string[];
98
+ cons: string[];
99
+ risk: 'low' | 'medium' | 'high';
100
+ effort: 'low' | 'medium' | 'high';
101
+ expectedOutcome: string;
102
+ }
103
+
104
+ export interface Prediction {
105
+ id: string;
106
+ target: string;
107
+ predicted_value: any;
108
+ confidence: number;
109
+ timeframe: string;
110
+ methodology: string;
111
+ factors: string[];
112
+ accuracy?: number;
113
+ createdBy: string[];
114
+ timestamp: Date;
115
+ }
116
+
117
+ export interface KnowledgeBase {
118
+ facts: Map<string, Fact>;
119
+ procedures: Map<string, Procedure>;
120
+ bestPractices: Map<string, BestPractice>;
121
+ lessons: Map<string, Lesson>;
122
+ }
123
+
124
+ export interface Fact {
125
+ id: string;
126
+ statement: string;
127
+ category: string;
128
+ confidence: number;
129
+ sources: string[];
130
+ validatedBy: string[];
131
+ contexts: string[];
132
+ timestamp: Date;
133
+ }
134
+
135
+ export interface Procedure {
136
+ id: string;
137
+ name: string;
138
+ description: string;
139
+ steps: ProcedureStep[];
140
+ preconditions: string[];
141
+ postconditions: string[];
142
+ successRate: number;
143
+ contexts: string[];
144
+ lastUsed: Date;
145
+ }
146
+
147
+ export interface ProcedureStep {
148
+ order: number;
149
+ action: string;
150
+ parameters: Record<string, any>;
151
+ expectedResult: string;
152
+ alternatives: string[];
153
+ }
154
+
155
+ export interface BestPractice {
156
+ id: string;
157
+ domain: string;
158
+ practice: string;
159
+ rationale: string;
160
+ benefits: string[];
161
+ applicableContexts: string[];
162
+ effectiveness: number;
163
+ adoptionRate: number;
164
+ validatedBy: string[];
165
+ timestamp: Date;
166
+ }
167
+
168
+ export interface Lesson {
169
+ id: string;
170
+ title: string;
171
+ situation: string;
172
+ actions: string[];
173
+ outcome: string;
174
+ learning: string;
175
+ applicability: string[];
176
+ importance: 'low' | 'medium' | 'high' | 'critical';
177
+ learnedBy: string[];
178
+ timestamp: Date;
179
+ }
180
+
181
+ export interface DistributedLearning {
182
+ models: Map<string, LearningModel>;
183
+ experiences: Map<string, Experience>;
184
+ adaptations: Map<string, Adaptation>;
185
+ performance: PerformanceTrends;
186
+ }
187
+
188
+ export interface LearningModel {
189
+ id: string;
190
+ type: 'neural' | 'statistical' | 'heuristic' | 'ensemble';
191
+ purpose: string;
192
+ parameters: Record<string, any>;
193
+ performance: ModelPerformance;
194
+ trainingData: string[];
195
+ lastUpdated: Date;
196
+ version: string;
197
+ }
198
+
199
+ export interface ModelPerformance {
200
+ accuracy: number;
201
+ precision: number;
202
+ recall: number;
203
+ f1Score: number;
204
+ validationResults: any[];
205
+ benchmarkResults: any[];
206
+ }
207
+
208
+ export interface Experience {
209
+ id: string;
210
+ context: string;
211
+ situation: string;
212
+ actions: string[];
213
+ results: any[];
214
+ feedback: number;
215
+ tags: string[];
216
+ agentId: string;
217
+ timestamp: Date;
218
+ }
219
+
220
+ export interface Adaptation {
221
+ id: string;
222
+ trigger: string;
223
+ change: string;
224
+ reason: string;
225
+ effectiveness: number;
226
+ rollbackPlan: string;
227
+ approvedBy: string[];
228
+ implementedAt: Date;
229
+ }
230
+
231
+ export interface PerformanceTrends {
232
+ metrics: Map<string, number[]>;
233
+ improvements: string[];
234
+ degradations: string[];
235
+ stability: number;
236
+ trends: TrendAnalysis[];
237
+ }
238
+
239
+ export interface TrendAnalysis {
240
+ metric: string;
241
+ direction: 'increasing' | 'decreasing' | 'stable' | 'volatile';
242
+ magnitude: number;
243
+ confidence: number;
244
+ timeframe: string;
245
+ factors: string[];
246
+ }
247
+
248
+ export class HiveMindIntegration extends EventEmitter {
249
+ private logger: Logger;
250
+ private config: HiveMindConfig;
251
+ private memoryManager: MemoryManager;
252
+ private activeSessions: Map<string, HiveMindSession> = new Map();
253
+ private globalKnowledgeBase: KnowledgeBase;
254
+ private globalIntelligence: CollectiveIntelligence;
255
+ private syncInterval?: NodeJS.Timeout;
256
+ private isInitialized: boolean = false;
257
+
258
+ constructor(
259
+ config: Partial<HiveMindConfig> = {},
260
+ memoryManager: MemoryManager
261
+ ) {
262
+ super();
263
+
264
+ this.logger = new Logger('HiveMindIntegration');
265
+ this.config = this.createDefaultConfig(config);
266
+ this.memoryManager = memoryManager;
267
+ this.globalKnowledgeBase = this.initializeKnowledgeBase();
268
+ this.globalIntelligence = this.initializeCollectiveIntelligence();
269
+
270
+ this.setupEventHandlers();
271
+ }
272
+
273
+ /**
274
+ * Initialize the hive-mind integration
275
+ */
276
+ async initialize(): Promise<void> {
277
+ if (this.isInitialized) {
278
+ this.logger.warn('Hive-mind integration already initialized');
279
+ return;
280
+ }
281
+
282
+ this.logger.info('Initializing hive-mind integration...');
283
+
284
+ try {
285
+ // Load existing knowledge base from memory
286
+ await this.loadKnowledgeBase();
287
+
288
+ // Load collective intelligence data
289
+ await this.loadCollectiveIntelligence();
290
+
291
+ // Start synchronization if enabled
292
+ if (this.config.syncInterval > 0) {
293
+ this.startPeriodicSync();
294
+ }
295
+
296
+ this.isInitialized = true;
297
+ this.logger.info('Hive-mind integration initialized successfully');
298
+ this.emit('initialized');
299
+
300
+ } catch (error) {
301
+ this.logger.error('Failed to initialize hive-mind integration', error);
302
+ throw error;
303
+ }
304
+ }
305
+
306
+ /**
307
+ * Shutdown the integration gracefully
308
+ */
309
+ async shutdown(): Promise<void> {
310
+ if (!this.isInitialized) return;
311
+
312
+ this.logger.info('Shutting down hive-mind integration...');
313
+
314
+ try {
315
+ // Stop synchronization
316
+ if (this.syncInterval) {
317
+ clearInterval(this.syncInterval);
318
+ }
319
+
320
+ // Save current state
321
+ await this.saveKnowledgeBase();
322
+ await this.saveCollectiveIntelligence();
323
+
324
+ // Terminate active sessions
325
+ const terminationPromises = Array.from(this.activeSessions.keys())
326
+ .map(sessionId => this.terminateSession(sessionId));
327
+
328
+ await Promise.allSettled(terminationPromises);
329
+
330
+ this.isInitialized = false;
331
+ this.logger.info('Hive-mind integration shut down successfully');
332
+ this.emit('shutdown');
333
+
334
+ } catch (error) {
335
+ this.logger.error('Error during hive-mind integration shutdown', error);
336
+ throw error;
337
+ }
338
+ }
339
+
340
+ /**
341
+ * Create a new hive-mind session for a swarm
342
+ */
343
+ async createSession(
344
+ swarmId: string,
345
+ orchestrator: AdvancedSwarmOrchestrator
346
+ ): Promise<string> {
347
+ const sessionId = generateId('hive-session');
348
+
349
+ this.logger.info('Creating hive-mind session', {
350
+ sessionId,
351
+ swarmId,
352
+ });
353
+
354
+ const session: HiveMindSession = {
355
+ id: sessionId,
356
+ swarmId,
357
+ participants: [],
358
+ sharedMemory: new Map(),
359
+ collectiveIntelligence: this.initializeCollectiveIntelligence(),
360
+ knowledgeBase: this.initializeKnowledgeBase(),
361
+ distributedLearning: this.initializeDistributedLearning(),
362
+ status: 'active',
363
+ startTime: new Date(),
364
+ lastSync: new Date(),
365
+ };
366
+
367
+ this.activeSessions.set(sessionId, session);
368
+
369
+ // Initialize session with global knowledge
370
+ await this.initializeSessionWithGlobalKnowledge(session);
371
+
372
+ this.emit('session:created', {
373
+ sessionId,
374
+ swarmId,
375
+ });
376
+
377
+ return sessionId;
378
+ }
379
+
380
+ /**
381
+ * Add an agent to a hive-mind session
382
+ */
383
+ async addAgentToSession(
384
+ sessionId: string,
385
+ agentId: string,
386
+ agent: SwarmAgent
387
+ ): Promise<void> {
388
+ const session = this.activeSessions.get(sessionId);
389
+ if (!session) {
390
+ throw new Error(`Hive-mind session not found: ${sessionId}`);
391
+ }
392
+
393
+ if (!session.participants.includes(agentId)) {
394
+ session.participants.push(agentId);
395
+
396
+ this.logger.info('Agent added to hive-mind session', {
397
+ sessionId,
398
+ agentId,
399
+ participantCount: session.participants.length,
400
+ });
401
+
402
+ // Share relevant knowledge with the agent
403
+ await this.shareKnowledgeWithAgent(session, agentId, agent);
404
+
405
+ this.emit('agent:joined', {
406
+ sessionId,
407
+ agentId,
408
+ participantCount: session.participants.length,
409
+ });
410
+ }
411
+ }
412
+
413
+ /**
414
+ * Remove an agent from a hive-mind session
415
+ */
416
+ async removeAgentFromSession(
417
+ sessionId: string,
418
+ agentId: string
419
+ ): Promise<void> {
420
+ const session = this.activeSessions.get(sessionId);
421
+ if (!session) {
422
+ throw new Error(`Hive-mind session not found: ${sessionId}`);
423
+ }
424
+
425
+ const index = session.participants.indexOf(agentId);
426
+ if (index !== -1) {
427
+ session.participants.splice(index, 1);
428
+
429
+ this.logger.info('Agent removed from hive-mind session', {
430
+ sessionId,
431
+ agentId,
432
+ participantCount: session.participants.length,
433
+ });
434
+
435
+ this.emit('agent:left', {
436
+ sessionId,
437
+ agentId,
438
+ participantCount: session.participants.length,
439
+ });
440
+ }
441
+ }
442
+
443
+ /**
444
+ * Share knowledge or experience with the hive-mind
445
+ */
446
+ async shareWithHive(
447
+ sessionId: string,
448
+ agentId: string,
449
+ type: 'knowledge' | 'experience' | 'insight' | 'pattern',
450
+ data: any
451
+ ): Promise<void> {
452
+ const session = this.activeSessions.get(sessionId);
453
+ if (!session) {
454
+ throw new Error(`Hive-mind session not found: ${sessionId}`);
455
+ }
456
+
457
+ this.logger.debug('Sharing with hive-mind', {
458
+ sessionId,
459
+ agentId,
460
+ type,
461
+ });
462
+
463
+ switch (type) {
464
+ case 'knowledge':
465
+ await this.addKnowledge(session, agentId, data);
466
+ break;
467
+ case 'experience':
468
+ await this.addExperience(session, agentId, data);
469
+ break;
470
+ case 'insight':
471
+ await this.addInsight(session, agentId, data);
472
+ break;
473
+ case 'pattern':
474
+ await this.addPattern(session, agentId, data);
475
+ break;
476
+ }
477
+
478
+ this.emit('knowledge:shared', {
479
+ sessionId,
480
+ agentId,
481
+ type,
482
+ });
483
+ }
484
+
485
+ /**
486
+ * Request collective decision making
487
+ */
488
+ async requestCollectiveDecision(
489
+ sessionId: string,
490
+ question: string,
491
+ options: DecisionOption[],
492
+ requesterAgentId: string
493
+ ): Promise<string> {
494
+ const session = this.activeSessions.get(sessionId);
495
+ if (!session) {
496
+ throw new Error(`Hive-mind session not found: ${sessionId}`);
497
+ }
498
+
499
+ const decisionId = generateId('decision');
500
+
501
+ this.logger.info('Requesting collective decision', {
502
+ sessionId,
503
+ decisionId,
504
+ question,
505
+ optionCount: options.length,
506
+ requesterAgentId,
507
+ });
508
+
509
+ const decision: CollectiveDecision = {
510
+ id: decisionId,
511
+ question,
512
+ options,
513
+ votingResults: new Map(),
514
+ consensus: '',
515
+ confidence: 0,
516
+ reasoning: '',
517
+ participants: [...session.participants],
518
+ timestamp: new Date(),
519
+ };
520
+
521
+ session.collectiveIntelligence.decisions.set(decisionId, decision);
522
+
523
+ // Initiate voting process
524
+ await this.initiateVoting(session, decision);
525
+
526
+ this.emit('decision:requested', {
527
+ sessionId,
528
+ decisionId,
529
+ question,
530
+ });
531
+
532
+ return decisionId;
533
+ }
534
+
535
+ /**
536
+ * Get collective decision result
537
+ */
538
+ getCollectiveDecision(sessionId: string, decisionId: string): CollectiveDecision | null {
539
+ const session = this.activeSessions.get(sessionId);
540
+ if (!session) return null;
541
+
542
+ return session.collectiveIntelligence.decisions.get(decisionId) || null;
543
+ }
544
+
545
+ /**
546
+ * Query the hive-mind knowledge base
547
+ */
548
+ async queryKnowledge(
549
+ sessionId: string,
550
+ query: {
551
+ type: 'fact' | 'procedure' | 'bestPractice' | 'lesson';
552
+ keywords?: string[];
553
+ context?: string;
554
+ category?: string;
555
+ }
556
+ ): Promise<any[]> {
557
+ const session = this.activeSessions.get(sessionId);
558
+ if (!session) {
559
+ throw new Error(`Hive-mind session not found: ${sessionId}`);
560
+ }
561
+
562
+ this.logger.debug('Querying hive-mind knowledge', {
563
+ sessionId,
564
+ query,
565
+ });
566
+
567
+ let results: any[] = [];
568
+
569
+ switch (query.type) {
570
+ case 'fact':
571
+ results = this.queryFacts(session, query);
572
+ break;
573
+ case 'procedure':
574
+ results = this.queryProcedures(session, query);
575
+ break;
576
+ case 'bestPractice':
577
+ results = this.queryBestPractices(session, query);
578
+ break;
579
+ case 'lesson':
580
+ results = this.queryLessons(session, query);
581
+ break;
582
+ }
583
+
584
+ this.emit('knowledge:queried', {
585
+ sessionId,
586
+ query,
587
+ resultCount: results.length,
588
+ });
589
+
590
+ return results;
591
+ }
592
+
593
+ /**
594
+ * Get collective insights for a swarm
595
+ */
596
+ getCollectiveInsights(sessionId: string): Insight[] {
597
+ const session = this.activeSessions.get(sessionId);
598
+ if (!session) return [];
599
+
600
+ return Array.from(session.collectiveIntelligence.insights.values());
601
+ }
602
+
603
+ /**
604
+ * Get identified patterns
605
+ */
606
+ getIdentifiedPatterns(sessionId: string): Pattern[] {
607
+ const session = this.activeSessions.get(sessionId);
608
+ if (!session) return [];
609
+
610
+ return Array.from(session.collectiveIntelligence.patterns.values());
611
+ }
612
+
613
+ /**
614
+ * Get performance predictions
615
+ */
616
+ getPerformancePredictions(sessionId: string): Prediction[] {
617
+ const session = this.activeSessions.get(sessionId);
618
+ if (!session) return [];
619
+
620
+ return Array.from(session.collectiveIntelligence.predictions.values());
621
+ }
622
+
623
+ /**
624
+ * Terminate a hive-mind session
625
+ */
626
+ async terminateSession(sessionId: string): Promise<void> {
627
+ const session = this.activeSessions.get(sessionId);
628
+ if (!session) return;
629
+
630
+ this.logger.info('Terminating hive-mind session', {
631
+ sessionId,
632
+ participantCount: session.participants.length,
633
+ duration: Date.now() - session.startTime.getTime(),
634
+ });
635
+
636
+ // Save session knowledge to global knowledge base
637
+ await this.consolidateSessionKnowledge(session);
638
+
639
+ // Update status and cleanup
640
+ session.status = 'terminated';
641
+ this.activeSessions.delete(sessionId);
642
+
643
+ this.emit('session:terminated', {
644
+ sessionId,
645
+ duration: Date.now() - session.startTime.getTime(),
646
+ });
647
+ }
648
+
649
+ /**
650
+ * Get hive-mind session status
651
+ */
652
+ getSessionStatus(sessionId: string): HiveMindSession | null {
653
+ return this.activeSessions.get(sessionId) || null;
654
+ }
655
+
656
+ /**
657
+ * Get integration metrics
658
+ */
659
+ getIntegrationMetrics(): {
660
+ activeSessions: number;
661
+ totalParticipants: number;
662
+ knowledgeItems: number;
663
+ insights: number;
664
+ patterns: number;
665
+ decisions: number;
666
+ predictions: number;
667
+ learningModels: number;
668
+ } {
669
+ const sessions = Array.from(this.activeSessions.values());
670
+
671
+ return {
672
+ activeSessions: sessions.length,
673
+ totalParticipants: sessions.reduce((sum, s) => sum + s.participants.length, 0),
674
+ knowledgeItems: this.countKnowledgeItems(),
675
+ insights: this.globalIntelligence.insights.size,
676
+ patterns: this.globalIntelligence.patterns.size,
677
+ decisions: this.globalIntelligence.decisions.size,
678
+ predictions: this.globalIntelligence.predictions.size,
679
+ learningModels: sessions.reduce((sum, s) => sum + s.distributedLearning.models.size, 0),
680
+ };
681
+ }
682
+
683
+ // Private methods
684
+
685
+ private async loadKnowledgeBase(): Promise<void> {
686
+ try {
687
+ const knowledgeEntries = await this.memoryManager.retrieve({
688
+ namespace: 'hive-mind-knowledge',
689
+ type: 'knowledge-base',
690
+ });
691
+
692
+ for (const entry of knowledgeEntries) {
693
+ const data = JSON.parse(entry.content);
694
+ // Load facts, procedures, best practices, and lessons
695
+ this.loadKnowledgeData(data);
696
+ }
697
+
698
+ this.logger.debug('Knowledge base loaded', {
699
+ factsCount: this.globalKnowledgeBase.facts.size,
700
+ proceduresCount: this.globalKnowledgeBase.procedures.size,
701
+ bestPracticesCount: this.globalKnowledgeBase.bestPractices.size,
702
+ lessonsCount: this.globalKnowledgeBase.lessons.size,
703
+ });
704
+
705
+ } catch (error) {
706
+ this.logger.warn('Failed to load knowledge base, starting fresh', error);
707
+ }
708
+ }
709
+
710
+ private async loadCollectiveIntelligence(): Promise<void> {
711
+ try {
712
+ const intelligenceEntries = await this.memoryManager.retrieve({
713
+ namespace: 'hive-mind-intelligence',
714
+ type: 'collective-intelligence',
715
+ });
716
+
717
+ for (const entry of intelligenceEntries) {
718
+ const data = JSON.parse(entry.content);
719
+ this.loadIntelligenceData(data);
720
+ }
721
+
722
+ this.logger.debug('Collective intelligence loaded', {
723
+ patternsCount: this.globalIntelligence.patterns.size,
724
+ insightsCount: this.globalIntelligence.insights.size,
725
+ decisionsCount: this.globalIntelligence.decisions.size,
726
+ predictionsCount: this.globalIntelligence.predictions.size,
727
+ });
728
+
729
+ } catch (error) {
730
+ this.logger.warn('Failed to load collective intelligence, starting fresh', error);
731
+ }
732
+ }
733
+
734
+ private async saveKnowledgeBase(): Promise<void> {
735
+ try {
736
+ const knowledgeData = {
737
+ facts: Array.from(this.globalKnowledgeBase.facts.entries()),
738
+ procedures: Array.from(this.globalKnowledgeBase.procedures.entries()),
739
+ bestPractices: Array.from(this.globalKnowledgeBase.bestPractices.entries()),
740
+ lessons: Array.from(this.globalKnowledgeBase.lessons.entries()),
741
+ };
742
+
743
+ await this.memoryManager.store({
744
+ id: `knowledge-base-${Date.now()}`,
745
+ agentId: 'hive-mind-integration',
746
+ type: 'knowledge-base',
747
+ content: JSON.stringify(knowledgeData),
748
+ namespace: 'hive-mind-knowledge',
749
+ timestamp: new Date(),
750
+ metadata: {
751
+ type: 'knowledge-base-snapshot',
752
+ itemCount: this.countKnowledgeItems(),
753
+ },
754
+ });
755
+
756
+ } catch (error) {
757
+ this.logger.error('Failed to save knowledge base', error);
758
+ }
759
+ }
760
+
761
+ private async saveCollectiveIntelligence(): Promise<void> {
762
+ try {
763
+ const intelligenceData = {
764
+ patterns: Array.from(this.globalIntelligence.patterns.entries()),
765
+ insights: Array.from(this.globalIntelligence.insights.entries()),
766
+ decisions: Array.from(this.globalIntelligence.decisions.entries()),
767
+ predictions: Array.from(this.globalIntelligence.predictions.entries()),
768
+ };
769
+
770
+ await this.memoryManager.store({
771
+ id: `collective-intelligence-${Date.now()}`,
772
+ agentId: 'hive-mind-integration',
773
+ type: 'collective-intelligence',
774
+ content: JSON.stringify(intelligenceData),
775
+ namespace: 'hive-mind-intelligence',
776
+ timestamp: new Date(),
777
+ metadata: {
778
+ type: 'intelligence-snapshot',
779
+ itemCount: this.globalIntelligence.patterns.size +
780
+ this.globalIntelligence.insights.size +
781
+ this.globalIntelligence.decisions.size +
782
+ this.globalIntelligence.predictions.size,
783
+ },
784
+ });
785
+
786
+ } catch (error) {
787
+ this.logger.error('Failed to save collective intelligence', error);
788
+ }
789
+ }
790
+
791
+ private startPeriodicSync(): void {
792
+ this.syncInterval = setInterval(async () => {
793
+ try {
794
+ await this.performPeriodicSync();
795
+ } catch (error) {
796
+ this.logger.error('Error during periodic sync', error);
797
+ }
798
+ }, this.config.syncInterval);
799
+ }
800
+
801
+ private async performPeriodicSync(): Promise<void> {
802
+ // Sync with external hive-mind endpoint if configured
803
+ if (this.config.hiveMindEndpoint) {
804
+ // Implementation would sync with external system
805
+ this.logger.debug('Performing external hive-mind sync');
806
+ }
807
+
808
+ // Update session knowledge bases
809
+ for (const session of this.activeSessions.values()) {
810
+ await this.syncSessionKnowledge(session);
811
+ session.lastSync = new Date();
812
+ }
813
+
814
+ this.emit('sync:completed', {
815
+ sessionsSynced: this.activeSessions.size,
816
+ timestamp: new Date(),
817
+ });
818
+ }
819
+
820
+ private async initializeSessionWithGlobalKnowledge(session: HiveMindSession): Promise<void> {
821
+ // Copy relevant global knowledge to session
822
+ for (const [id, fact] of this.globalKnowledgeBase.facts) {
823
+ session.knowledgeBase.facts.set(id, fact);
824
+ }
825
+
826
+ for (const [id, insight] of this.globalIntelligence.insights) {
827
+ session.collectiveIntelligence.insights.set(id, insight);
828
+ }
829
+
830
+ for (const [id, pattern] of this.globalIntelligence.patterns) {
831
+ session.collectiveIntelligence.patterns.set(id, pattern);
832
+ }
833
+ }
834
+
835
+ private async shareKnowledgeWithAgent(
836
+ session: HiveMindSession,
837
+ agentId: string,
838
+ agent: SwarmAgent
839
+ ): Promise<void> {
840
+ // Share relevant knowledge based on agent capabilities
841
+ const relevantKnowledge = this.getRelevantKnowledge(session, agent.capabilities);
842
+
843
+ this.logger.debug('Sharing knowledge with agent', {
844
+ sessionId: session.id,
845
+ agentId,
846
+ knowledgeItems: relevantKnowledge.length,
847
+ });
848
+
849
+ // Implementation would send knowledge to agent through MCP tools
850
+ }
851
+
852
+ private getRelevantKnowledge(session: HiveMindSession, capabilities: string[]): any[] {
853
+ const relevantItems: any[] = [];
854
+
855
+ // Filter facts by capabilities
856
+ for (const fact of session.knowledgeBase.facts.values()) {
857
+ if (capabilities.some(cap => fact.category.includes(cap))) {
858
+ relevantItems.push(fact);
859
+ }
860
+ }
861
+
862
+ // Filter procedures by capabilities
863
+ for (const procedure of session.knowledgeBase.procedures.values()) {
864
+ if (capabilities.some(cap => procedure.contexts.includes(cap))) {
865
+ relevantItems.push(procedure);
866
+ }
867
+ }
868
+
869
+ return relevantItems;
870
+ }
871
+
872
+ private async addKnowledge(session: HiveMindSession, agentId: string, data: any): Promise<void> {
873
+ // Add new knowledge item to session
874
+ if (data.type === 'fact') {
875
+ const fact: Fact = {
876
+ id: generateId('fact'),
877
+ statement: data.statement,
878
+ category: data.category || 'general',
879
+ confidence: data.confidence || 0.8,
880
+ sources: [agentId],
881
+ validatedBy: [agentId],
882
+ contexts: data.contexts || [],
883
+ timestamp: new Date(),
884
+ };
885
+
886
+ session.knowledgeBase.facts.set(fact.id, fact);
887
+ }
888
+ // Similar implementations for procedures, best practices, and lessons
889
+ }
890
+
891
+ private async addExperience(session: HiveMindSession, agentId: string, data: any): Promise<void> {
892
+ const experience: Experience = {
893
+ id: generateId('experience'),
894
+ context: data.context || 'general',
895
+ situation: data.situation,
896
+ actions: data.actions || [],
897
+ results: data.results || [],
898
+ feedback: data.feedback || 0,
899
+ tags: data.tags || [],
900
+ agentId,
901
+ timestamp: new Date(),
902
+ };
903
+
904
+ session.distributedLearning.experiences.set(experience.id, experience);
905
+ }
906
+
907
+ private async addInsight(session: HiveMindSession, agentId: string, data: any): Promise<void> {
908
+ const insight: Insight = {
909
+ id: generateId('insight'),
910
+ category: data.category || 'optimization',
911
+ title: data.title,
912
+ description: data.description,
913
+ evidence: data.evidence || [],
914
+ confidence: data.confidence || 0.7,
915
+ applicability: data.applicability || [],
916
+ contributingAgents: [agentId],
917
+ timestamp: new Date(),
918
+ };
919
+
920
+ session.collectiveIntelligence.insights.set(insight.id, insight);
921
+ }
922
+
923
+ private async addPattern(session: HiveMindSession, agentId: string, data: any): Promise<void> {
924
+ const pattern: Pattern = {
925
+ id: generateId('pattern'),
926
+ type: data.type || 'behavioral',
927
+ description: data.description,
928
+ frequency: data.frequency || 1,
929
+ confidence: data.confidence || 0.7,
930
+ contexts: data.contexts || [],
931
+ impact: data.impact || 'medium',
932
+ discoveredBy: [agentId],
933
+ lastSeen: new Date(),
934
+ };
935
+
936
+ session.collectiveIntelligence.patterns.set(pattern.id, pattern);
937
+ }
938
+
939
+ private async initiateVoting(session: HiveMindSession, decision: CollectiveDecision): Promise<void> {
940
+ // Implementation would send voting request to all participants
941
+ // For now, simulate consensus building
942
+ this.logger.debug('Initiating collective voting', {
943
+ sessionId: session.id,
944
+ decisionId: decision.id,
945
+ participantCount: decision.participants.length,
946
+ });
947
+
948
+ // Placeholder implementation - in reality, this would involve
949
+ // sophisticated consensus algorithms
950
+ setTimeout(() => {
951
+ this.processVotingResults(session, decision);
952
+ }, 5000);
953
+ }
954
+
955
+ private processVotingResults(session: HiveMindSession, decision: CollectiveDecision): void {
956
+ // Placeholder implementation
957
+ decision.consensus = decision.options[0].id;
958
+ decision.confidence = 0.8;
959
+ decision.reasoning = 'Consensus reached through collective voting';
960
+
961
+ this.emit('decision:completed', {
962
+ sessionId: session.id,
963
+ decisionId: decision.id,
964
+ consensus: decision.consensus,
965
+ confidence: decision.confidence,
966
+ });
967
+ }
968
+
969
+ private queryFacts(session: HiveMindSession, query: any): Fact[] {
970
+ const results: Fact[] = [];
971
+
972
+ for (const fact of session.knowledgeBase.facts.values()) {
973
+ let matches = true;
974
+
975
+ if (query.category && !fact.category.includes(query.category)) {
976
+ matches = false;
977
+ }
978
+
979
+ if (query.keywords && !query.keywords.some(keyword =>
980
+ fact.statement.toLowerCase().includes(keyword.toLowerCase()))) {
981
+ matches = false;
982
+ }
983
+
984
+ if (query.context && !fact.contexts.includes(query.context)) {
985
+ matches = false;
986
+ }
987
+
988
+ if (matches) {
989
+ results.push(fact);
990
+ }
991
+ }
992
+
993
+ return results;
994
+ }
995
+
996
+ private queryProcedures(session: HiveMindSession, query: any): Procedure[] {
997
+ // Similar implementation to queryFacts but for procedures
998
+ return Array.from(session.knowledgeBase.procedures.values());
999
+ }
1000
+
1001
+ private queryBestPractices(session: HiveMindSession, query: any): BestPractice[] {
1002
+ // Similar implementation to queryFacts but for best practices
1003
+ return Array.from(session.knowledgeBase.bestPractices.values());
1004
+ }
1005
+
1006
+ private queryLessons(session: HiveMindSession, query: any): Lesson[] {
1007
+ // Similar implementation to queryFacts but for lessons
1008
+ return Array.from(session.knowledgeBase.lessons.values());
1009
+ }
1010
+
1011
+ private async consolidateSessionKnowledge(session: HiveMindSession): Promise<void> {
1012
+ // Merge session knowledge into global knowledge base
1013
+ for (const [id, fact] of session.knowledgeBase.facts) {
1014
+ if (!this.globalKnowledgeBase.facts.has(id)) {
1015
+ this.globalKnowledgeBase.facts.set(id, fact);
1016
+ }
1017
+ }
1018
+
1019
+ for (const [id, insight] of session.collectiveIntelligence.insights) {
1020
+ if (!this.globalIntelligence.insights.has(id)) {
1021
+ this.globalIntelligence.insights.set(id, insight);
1022
+ }
1023
+ }
1024
+
1025
+ // Similar consolidation for other knowledge types
1026
+ }
1027
+
1028
+ private async syncSessionKnowledge(session: HiveMindSession): Promise<void> {
1029
+ // Sync session with global knowledge base
1030
+ // Implementation would handle bidirectional sync
1031
+ }
1032
+
1033
+ private loadKnowledgeData(data: any): void {
1034
+ // Load knowledge data from stored format
1035
+ if (data.facts) {
1036
+ for (const [id, fact] of data.facts) {
1037
+ this.globalKnowledgeBase.facts.set(id, fact);
1038
+ }
1039
+ }
1040
+ // Similar loading for other knowledge types
1041
+ }
1042
+
1043
+ private loadIntelligenceData(data: any): void {
1044
+ // Load intelligence data from stored format
1045
+ if (data.patterns) {
1046
+ for (const [id, pattern] of data.patterns) {
1047
+ this.globalIntelligence.patterns.set(id, pattern);
1048
+ }
1049
+ }
1050
+ // Similar loading for other intelligence types
1051
+ }
1052
+
1053
+ private countKnowledgeItems(): number {
1054
+ return this.globalKnowledgeBase.facts.size +
1055
+ this.globalKnowledgeBase.procedures.size +
1056
+ this.globalKnowledgeBase.bestPractices.size +
1057
+ this.globalKnowledgeBase.lessons.size;
1058
+ }
1059
+
1060
+ private initializeKnowledgeBase(): KnowledgeBase {
1061
+ return {
1062
+ facts: new Map(),
1063
+ procedures: new Map(),
1064
+ bestPractices: new Map(),
1065
+ lessons: new Map(),
1066
+ };
1067
+ }
1068
+
1069
+ private initializeCollectiveIntelligence(): CollectiveIntelligence {
1070
+ return {
1071
+ patterns: new Map(),
1072
+ insights: new Map(),
1073
+ decisions: new Map(),
1074
+ predictions: new Map(),
1075
+ };
1076
+ }
1077
+
1078
+ private initializeDistributedLearning(): DistributedLearning {
1079
+ return {
1080
+ models: new Map(),
1081
+ experiences: new Map(),
1082
+ adaptations: new Map(),
1083
+ performance: {
1084
+ metrics: new Map(),
1085
+ improvements: [],
1086
+ degradations: [],
1087
+ stability: 1.0,
1088
+ trends: [],
1089
+ },
1090
+ };
1091
+ }
1092
+
1093
+ private createDefaultConfig(config: Partial<HiveMindConfig>): HiveMindConfig {
1094
+ return {
1095
+ enableSharedIntelligence: true,
1096
+ enableCollectiveMemory: true,
1097
+ enableDistributedLearning: true,
1098
+ enableKnowledgeSharing: true,
1099
+ syncInterval: 30000, // 30 seconds
1100
+ maxSharedMemorySize: 100 * 1024 * 1024, // 100MB
1101
+ intelligencePoolSize: 1000,
1102
+ learningRate: 0.1,
1103
+ knowledgeRetentionPeriod: 7 * 24 * 60 * 60 * 1000, // 7 days
1104
+ ...config,
1105
+ };
1106
+ }
1107
+
1108
+ private setupEventHandlers(): void {
1109
+ this.on('session:created', (data) => {
1110
+ this.logger.info('Hive-mind session created', data);
1111
+ });
1112
+
1113
+ this.on('agent:joined', (data) => {
1114
+ this.logger.info('Agent joined hive-mind', data);
1115
+ });
1116
+
1117
+ this.on('knowledge:shared', (data) => {
1118
+ this.logger.debug('Knowledge shared with hive-mind', data);
1119
+ });
1120
+
1121
+ this.on('decision:completed', (data) => {
1122
+ this.logger.info('Collective decision completed', data);
1123
+ });
1124
+ }
1125
+ }
1126
+
1127
+ export default HiveMindIntegration;