@sparkleideas/swarm 3.0.0-alpha.7

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 (65) hide show
  1. package/MIGRATION.md +472 -0
  2. package/README.md +634 -0
  3. package/__tests__/consensus.test.ts +577 -0
  4. package/__tests__/coordinator.test.ts +501 -0
  5. package/__tests__/queen-coordinator.test.ts +1335 -0
  6. package/__tests__/topology.test.ts +621 -0
  7. package/package.json +32 -0
  8. package/src/agent-pool.ts +476 -0
  9. package/src/application/commands/create-task.command.ts +124 -0
  10. package/src/application/commands/spawn-agent.command.ts +122 -0
  11. package/src/application/index.ts +30 -0
  12. package/src/application/services/swarm-application-service.ts +200 -0
  13. package/src/attention-coordinator.ts +1000 -0
  14. package/src/consensus/byzantine.ts +431 -0
  15. package/src/consensus/gossip.ts +513 -0
  16. package/src/consensus/index.ts +267 -0
  17. package/src/consensus/raft.ts +443 -0
  18. package/src/coordination/agent-registry.ts +544 -0
  19. package/src/coordination/index.ts +23 -0
  20. package/src/coordination/swarm-hub.ts +776 -0
  21. package/src/coordination/task-orchestrator.ts +605 -0
  22. package/src/domain/entities/agent.d.ts +151 -0
  23. package/src/domain/entities/agent.d.ts.map +1 -0
  24. package/src/domain/entities/agent.js +280 -0
  25. package/src/domain/entities/agent.js.map +1 -0
  26. package/src/domain/entities/agent.ts +370 -0
  27. package/src/domain/entities/task.d.ts +133 -0
  28. package/src/domain/entities/task.d.ts.map +1 -0
  29. package/src/domain/entities/task.js +261 -0
  30. package/src/domain/entities/task.js.map +1 -0
  31. package/src/domain/entities/task.ts +319 -0
  32. package/src/domain/index.ts +41 -0
  33. package/src/domain/repositories/agent-repository.interface.d.ts +57 -0
  34. package/src/domain/repositories/agent-repository.interface.d.ts.map +1 -0
  35. package/src/domain/repositories/agent-repository.interface.js +9 -0
  36. package/src/domain/repositories/agent-repository.interface.js.map +1 -0
  37. package/src/domain/repositories/agent-repository.interface.ts +69 -0
  38. package/src/domain/repositories/task-repository.interface.d.ts +61 -0
  39. package/src/domain/repositories/task-repository.interface.d.ts.map +1 -0
  40. package/src/domain/repositories/task-repository.interface.js +9 -0
  41. package/src/domain/repositories/task-repository.interface.js.map +1 -0
  42. package/src/domain/repositories/task-repository.interface.ts +75 -0
  43. package/src/domain/services/coordination-service.ts +320 -0
  44. package/src/federation-hub.d.ts +284 -0
  45. package/src/federation-hub.d.ts.map +1 -0
  46. package/src/federation-hub.js +692 -0
  47. package/src/federation-hub.js.map +1 -0
  48. package/src/federation-hub.ts +979 -0
  49. package/src/index.ts +348 -0
  50. package/src/message-bus.ts +607 -0
  51. package/src/queen-coordinator.ts +2025 -0
  52. package/src/shared/events.ts +285 -0
  53. package/src/shared/types.ts +389 -0
  54. package/src/topology-manager.ts +656 -0
  55. package/src/types.ts +545 -0
  56. package/src/unified-coordinator.ts +1844 -0
  57. package/src/workers/index.ts +65 -0
  58. package/src/workers/worker-dispatch.d.ts +234 -0
  59. package/src/workers/worker-dispatch.d.ts.map +1 -0
  60. package/src/workers/worker-dispatch.js +842 -0
  61. package/src/workers/worker-dispatch.js.map +1 -0
  62. package/src/workers/worker-dispatch.ts +1076 -0
  63. package/tmp.json +0 -0
  64. package/tsconfig.json +9 -0
  65. package/vitest.config.ts +20 -0
@@ -0,0 +1,776 @@
1
+ /**
2
+ * V3 Swarm Hub - COMPATIBILITY LAYER (ADR-003)
3
+ *
4
+ * DEPRECATION NOTICE:
5
+ * This is a THIN FACADE over UnifiedSwarmCoordinator for backward compatibility.
6
+ * All operations are delegated to the canonical UnifiedSwarmCoordinator.
7
+ *
8
+ * For new code, use UnifiedSwarmCoordinator directly:
9
+ * ```typescript
10
+ * import { createUnifiedSwarmCoordinator } from '@sparkleideas/swarm';
11
+ * const coordinator = createUnifiedSwarmCoordinator(config);
12
+ * await coordinator.initialize();
13
+ * ```
14
+ *
15
+ * ADR-003 Decision:
16
+ * - ONE canonical coordination engine: UnifiedSwarmCoordinator
17
+ * - SwarmHub maintained ONLY for compatibility with existing code
18
+ * - All core logic delegated to UnifiedSwarmCoordinator
19
+ *
20
+ * Based on ADR-001 (@sparkleideas/agentic-flow integration), ADR-003 (Single Coordination Engine),
21
+ * and the 15-Agent Swarm Architecture
22
+ */
23
+
24
+ import {
25
+ AgentId,
26
+ AgentRole,
27
+ AgentDomain,
28
+ AgentState,
29
+ TaskId,
30
+ TaskDefinition,
31
+ TaskResult,
32
+ PhaseId,
33
+ PhaseDefinition,
34
+ MilestoneDefinition,
35
+ TopologyType,
36
+ SwarmConfig,
37
+ SwarmState,
38
+ SwarmMetrics,
39
+ SwarmMessage,
40
+ MessageType,
41
+ MessageHandler,
42
+ EventHandler,
43
+ V3_PERFORMANCE_TARGETS
44
+ } from '../shared/types';
45
+ import {
46
+ IEventBus,
47
+ EventBus,
48
+ swarmInitializedEvent,
49
+ swarmPhaseChangedEvent,
50
+ swarmMilestoneReachedEvent,
51
+ swarmErrorEvent
52
+ } from '../shared/events';
53
+ import { IAgentRegistry, AgentRegistry, createAgentRegistry } from './agent-registry';
54
+ import { ITaskOrchestrator, TaskOrchestrator, TaskSpec, createTaskOrchestrator } from './task-orchestrator';
55
+ import { UnifiedSwarmCoordinator, createUnifiedSwarmCoordinator } from '../unified-coordinator';
56
+
57
+ // =============================================================================
58
+ // Swarm Hub Interface
59
+ // =============================================================================
60
+
61
+ export interface ISwarmHub {
62
+ // Lifecycle
63
+ initialize(config?: Partial<SwarmConfig>): Promise<void>;
64
+ shutdown(): Promise<void>;
65
+ isInitialized(): boolean;
66
+
67
+ // Agent Management
68
+ spawnAgent(agentId: AgentId): Promise<AgentState>;
69
+ spawnAllAgents(): Promise<Map<AgentId, AgentState>>;
70
+ spawnAgentsByDomain(domain: AgentDomain): Promise<AgentState[]>;
71
+ terminateAgent(agentId: AgentId): Promise<boolean>;
72
+
73
+ // Task Management
74
+ submitTask(spec: TaskSpec): TaskDefinition;
75
+ submitBatchTasks(specs: TaskSpec[]): TaskDefinition[];
76
+ assignNextTask(agentId: AgentId): TaskDefinition | undefined;
77
+ completeTask(taskId: TaskId, result: TaskResult): void;
78
+
79
+ // Phase Management
80
+ getCurrentPhase(): PhaseId;
81
+ advancePhase(): PhaseId;
82
+ getPhaseDefinition(phaseId: PhaseId): PhaseDefinition;
83
+
84
+ // Milestone Tracking
85
+ getMilestones(): MilestoneDefinition[];
86
+ completeMilestone(milestoneId: string): void;
87
+
88
+ // Messaging
89
+ sendMessage<T>(message: Omit<SwarmMessage<T>, 'id' | 'timestamp'>): void;
90
+ broadcast<T>(from: AgentId, type: MessageType, payload: T): void;
91
+ onMessage<T>(handler: MessageHandler<T>): () => void;
92
+
93
+ // Metrics & Status
94
+ getState(): SwarmState;
95
+ getMetrics(): SwarmMetrics;
96
+ getAgentRegistry(): IAgentRegistry;
97
+ getTaskOrchestrator(): ITaskOrchestrator;
98
+
99
+ // Events
100
+ onSwarmEvent(handler: EventHandler): () => void;
101
+ }
102
+
103
+ // =============================================================================
104
+ // Swarm Hub Implementation - COMPATIBILITY LAYER
105
+ // =============================================================================
106
+
107
+ /**
108
+ * @deprecated Use UnifiedSwarmCoordinator directly instead.
109
+ * This class is maintained for backward compatibility only.
110
+ *
111
+ * Migration guide:
112
+ * ```typescript
113
+ * // OLD:
114
+ * const hub = createSwarmHub();
115
+ * await hub.initialize();
116
+ *
117
+ * // NEW:
118
+ * const coordinator = createUnifiedSwarmCoordinator();
119
+ * await coordinator.initialize();
120
+ * ```
121
+ */
122
+ export class SwarmHub implements ISwarmHub {
123
+ // Core coordinator - ALL operations delegate to this
124
+ private coordinator: UnifiedSwarmCoordinator;
125
+
126
+ // Compatibility layer state
127
+ private eventBus: IEventBus;
128
+ private agentRegistry: IAgentRegistry;
129
+ private taskOrchestrator: ITaskOrchestrator;
130
+ private currentPhase: PhaseId = 'phase-1-foundation';
131
+ private phases: Map<PhaseId, PhaseDefinition>;
132
+ private milestones: Map<string, MilestoneDefinition> = new Map();
133
+ private messageHandlers: Set<MessageHandler> = new Set();
134
+ private messageCounter: number = 0;
135
+ private startTime: number = 0;
136
+
137
+ constructor(eventBus?: IEventBus) {
138
+ this.eventBus = eventBus ?? new EventBus();
139
+ this.agentRegistry = createAgentRegistry(this.eventBus);
140
+ this.taskOrchestrator = createTaskOrchestrator(this.eventBus, this.agentRegistry);
141
+ this.phases = this.createPhaseDefinitions();
142
+
143
+ // Initialize the canonical coordinator
144
+ this.coordinator = createUnifiedSwarmCoordinator(this.convertToCoordinatorConfig());
145
+ }
146
+
147
+ // ==========================================================================
148
+ // Lifecycle - DELEGATES to UnifiedSwarmCoordinator
149
+ // ==========================================================================
150
+
151
+ /**
152
+ * @deprecated Delegates to UnifiedSwarmCoordinator.initialize()
153
+ */
154
+ async initialize(config?: Partial<SwarmConfig>): Promise<void> {
155
+ this.startTime = Date.now();
156
+ this.initializeMilestones();
157
+
158
+ // Start compatibility layer components
159
+ (this.agentRegistry as AgentRegistry).startHealthChecks();
160
+
161
+ // DELEGATE to canonical coordinator
162
+ await this.coordinator.initialize();
163
+
164
+ await this.eventBus.emit(swarmInitializedEvent('swarm-hub', {
165
+ topology: this.coordinator.getTopology(),
166
+ maxAgents: 15,
167
+ performanceTargets: V3_PERFORMANCE_TARGETS
168
+ }));
169
+
170
+ console.log(`[SwarmHub] COMPATIBILITY LAYER: Initialized via UnifiedSwarmCoordinator`);
171
+ }
172
+
173
+ /**
174
+ * @deprecated Delegates to UnifiedSwarmCoordinator.shutdown()
175
+ */
176
+ async shutdown(): Promise<void> {
177
+ // Stop compatibility layer components
178
+ (this.agentRegistry as AgentRegistry).stopHealthChecks();
179
+
180
+ // DELEGATE to canonical coordinator
181
+ await this.coordinator.shutdown();
182
+
183
+ console.log('[SwarmHub] COMPATIBILITY LAYER: Shutdown complete');
184
+ }
185
+
186
+ /**
187
+ * @deprecated Check UnifiedSwarmCoordinator state instead
188
+ */
189
+ isInitialized(): boolean {
190
+ const state = this.coordinator.getState();
191
+ return state.status !== 'stopped' && state.status !== 'initializing';
192
+ }
193
+
194
+ // ==========================================================================
195
+ // Agent Management
196
+ // ==========================================================================
197
+
198
+ async spawnAgent(agentId: AgentId): Promise<AgentState> {
199
+ this.ensureInitialized();
200
+ return this.agentRegistry.spawn(agentId);
201
+ }
202
+
203
+ async spawnAllAgents(): Promise<Map<AgentId, AgentState>> {
204
+ this.ensureInitialized();
205
+
206
+ const results = new Map<AgentId, AgentState>();
207
+ const allAgents = this.agentRegistry.getAllAgents();
208
+
209
+ const sortedAgents = allAgents.sort((a, b) => a.priority - b.priority);
210
+
211
+ for (const agent of sortedAgents) {
212
+ try {
213
+ const state = await this.spawnAgent(agent.id);
214
+ results.set(agent.id, state);
215
+ } catch (err) {
216
+ console.error(`[SwarmHub] Failed to spawn agent ${agent.id}: ${err}`);
217
+ }
218
+ }
219
+
220
+ return results;
221
+ }
222
+
223
+ async spawnAgentsByDomain(domain: AgentDomain): Promise<AgentState[]> {
224
+ this.ensureInitialized();
225
+
226
+ const domainAgents = this.agentRegistry.getAgentsByDomain(domain);
227
+ const results: AgentState[] = [];
228
+
229
+ for (const agent of domainAgents) {
230
+ try {
231
+ const state = await this.spawnAgent(agent.id);
232
+ results.push(state);
233
+ } catch (err) {
234
+ console.error(`[SwarmHub] Failed to spawn agent ${agent.id}: ${err}`);
235
+ }
236
+ }
237
+
238
+ return results;
239
+ }
240
+
241
+ async terminateAgent(agentId: AgentId): Promise<boolean> {
242
+ this.ensureInitialized();
243
+ return this.agentRegistry.terminate(agentId);
244
+ }
245
+
246
+ // ==========================================================================
247
+ // Task Management
248
+ // ==========================================================================
249
+
250
+ submitTask(spec: TaskSpec): TaskDefinition {
251
+ this.ensureInitialized();
252
+ return this.taskOrchestrator.createTask(spec);
253
+ }
254
+
255
+ submitBatchTasks(specs: TaskSpec[]): TaskDefinition[] {
256
+ this.ensureInitialized();
257
+ return this.taskOrchestrator.createBatchTasks(specs);
258
+ }
259
+
260
+ assignNextTask(agentId: AgentId): TaskDefinition | undefined {
261
+ this.ensureInitialized();
262
+
263
+ const nextTask = this.taskOrchestrator.getNextTask(agentId);
264
+ if (nextTask) {
265
+ this.taskOrchestrator.queueTask(nextTask.id);
266
+ this.taskOrchestrator.assignTask(nextTask.id, agentId);
267
+ this.taskOrchestrator.startTask(nextTask.id);
268
+ }
269
+
270
+ return nextTask;
271
+ }
272
+
273
+ completeTask(taskId: TaskId, result: TaskResult): void {
274
+ this.ensureInitialized();
275
+
276
+ if (result.success) {
277
+ this.taskOrchestrator.completeTask(taskId, result);
278
+ } else {
279
+ this.taskOrchestrator.failTask(taskId, result.error ?? new Error('Unknown error'));
280
+ }
281
+ }
282
+
283
+ // ==========================================================================
284
+ // Phase Management
285
+ // ==========================================================================
286
+
287
+ getCurrentPhase(): PhaseId {
288
+ return this.currentPhase;
289
+ }
290
+
291
+ advancePhase(): PhaseId {
292
+ const phaseOrder: PhaseId[] = [
293
+ 'phase-1-foundation',
294
+ 'phase-2-core',
295
+ 'phase-3-integration',
296
+ 'phase-4-release'
297
+ ];
298
+
299
+ const currentIndex = phaseOrder.indexOf(this.currentPhase);
300
+ if (currentIndex < phaseOrder.length - 1) {
301
+ const previousPhase = this.currentPhase;
302
+ this.currentPhase = phaseOrder[currentIndex + 1];
303
+
304
+ this.eventBus.emitSync(swarmPhaseChangedEvent('swarm-hub', previousPhase, this.currentPhase));
305
+
306
+ console.log(`[SwarmHub] Advanced from ${previousPhase} to ${this.currentPhase}`);
307
+ }
308
+
309
+ return this.currentPhase;
310
+ }
311
+
312
+ getPhaseDefinition(phaseId: PhaseId): PhaseDefinition {
313
+ const phase = this.phases.get(phaseId);
314
+ if (!phase) {
315
+ throw new Error(`Phase ${phaseId} not found`);
316
+ }
317
+ return phase;
318
+ }
319
+
320
+ // ==========================================================================
321
+ // Milestone Tracking
322
+ // ==========================================================================
323
+
324
+ getMilestones(): MilestoneDefinition[] {
325
+ return Array.from(this.milestones.values());
326
+ }
327
+
328
+ completeMilestone(milestoneId: string): void {
329
+ const milestone = this.milestones.get(milestoneId);
330
+ if (!milestone) {
331
+ throw new Error(`Milestone ${milestoneId} not found`);
332
+ }
333
+
334
+ milestone.status = 'completed';
335
+ milestone.completedAt = Date.now();
336
+
337
+ this.eventBus.emitSync(swarmMilestoneReachedEvent(milestoneId, milestone.name));
338
+
339
+ console.log(`[SwarmHub] Milestone completed: ${milestone.name}`);
340
+ }
341
+
342
+ // ==========================================================================
343
+ // Messaging
344
+ // ==========================================================================
345
+
346
+ sendMessage<T>(message: Omit<SwarmMessage<T>, 'id' | 'timestamp'>): void {
347
+ const fullMessage: SwarmMessage<T> = {
348
+ ...message,
349
+ id: `msg-${Date.now()}-${++this.messageCounter}`,
350
+ timestamp: Date.now()
351
+ };
352
+
353
+ for (const handler of this.messageHandlers) {
354
+ try {
355
+ handler(fullMessage);
356
+ } catch (err) {
357
+ console.error(`[SwarmHub] Message handler error: ${err}`);
358
+ }
359
+ }
360
+ }
361
+
362
+ broadcast<T>(from: AgentId, type: MessageType, payload: T): void {
363
+ this.sendMessage({
364
+ type,
365
+ from,
366
+ to: 'broadcast',
367
+ payload,
368
+ correlationId: null
369
+ });
370
+ }
371
+
372
+ onMessage<T>(handler: MessageHandler<T>): () => void {
373
+ this.messageHandlers.add(handler as MessageHandler);
374
+
375
+ return () => {
376
+ this.messageHandlers.delete(handler as MessageHandler);
377
+ };
378
+ }
379
+
380
+ // ==========================================================================
381
+ // Metrics & Status
382
+ // ==========================================================================
383
+
384
+ getState(): SwarmState {
385
+ const allAgents = this.agentRegistry.getAllAgents();
386
+ const agents = new Map<AgentId, AgentState>();
387
+
388
+ for (const agent of allAgents) {
389
+ const state = this.agentRegistry.getState(agent.id);
390
+ if (state) {
391
+ agents.set(agent.id, state);
392
+ }
393
+ }
394
+
395
+ const allTasks = this.taskOrchestrator.getAllTasks();
396
+ const tasks = new Map<TaskId, TaskDefinition>();
397
+
398
+ for (const task of allTasks) {
399
+ tasks.set(task.id, task);
400
+ }
401
+
402
+ const status = this.coordinator.getStatus();
403
+ return {
404
+ initialized: status.status === 'running',
405
+ topology: status.topology as TopologyType,
406
+ agents,
407
+ tasks,
408
+ currentPhase: this.currentPhase,
409
+ metrics: this.getMetrics()
410
+ };
411
+ }
412
+
413
+ getMetrics(): SwarmMetrics {
414
+ const activeAgents = this.agentRegistry.getActiveAgents();
415
+ const allAgents = this.agentRegistry.getAllAgents();
416
+ const taskMetrics = this.taskOrchestrator.getTaskMetrics();
417
+
418
+ const idleAgents = allAgents.filter(a => {
419
+ const state = this.agentRegistry.getState(a.id);
420
+ return state && state.status === 'idle';
421
+ }).length;
422
+
423
+ const blockedAgents = allAgents.filter(a => {
424
+ const state = this.agentRegistry.getState(a.id);
425
+ return state && state.status === 'blocked';
426
+ }).length;
427
+
428
+ const totalAgentsWithState = activeAgents.length + idleAgents + blockedAgents;
429
+
430
+ return {
431
+ totalAgents: allAgents.length,
432
+ activeAgents: activeAgents.length,
433
+ idleAgents,
434
+ blockedAgents,
435
+ totalTasks: taskMetrics.totalTasks,
436
+ completedTasks: taskMetrics.tasksByStatus['completed'],
437
+ failedTasks: taskMetrics.tasksByStatus['failed'],
438
+ pendingTasks: taskMetrics.tasksByStatus['pending'] + taskMetrics.tasksByStatus['queued'],
439
+ averageTaskDuration: taskMetrics.averageExecutionTime,
440
+ utilization: totalAgentsWithState > 0 ? activeAgents.length / totalAgentsWithState : 0,
441
+ startTime: this.startTime,
442
+ lastUpdate: Date.now()
443
+ };
444
+ }
445
+
446
+ getAgentRegistry(): IAgentRegistry {
447
+ return this.agentRegistry;
448
+ }
449
+
450
+ getTaskOrchestrator(): ITaskOrchestrator {
451
+ return this.taskOrchestrator;
452
+ }
453
+
454
+ // ==========================================================================
455
+ // Events
456
+ // ==========================================================================
457
+
458
+ onSwarmEvent(handler: EventHandler): () => void {
459
+ const unsubscribers = [
460
+ this.eventBus.subscribe('swarm:initialized', handler),
461
+ this.eventBus.subscribe('swarm:phase-changed', handler),
462
+ this.eventBus.subscribe('swarm:milestone-reached', handler),
463
+ this.eventBus.subscribe('swarm:error', handler)
464
+ ];
465
+
466
+ return () => {
467
+ unsubscribers.forEach(unsub => unsub());
468
+ };
469
+ }
470
+
471
+ // ==========================================================================
472
+ // Coordinator Access (ADR-003)
473
+ // ==========================================================================
474
+
475
+ /**
476
+ * Get the underlying UnifiedSwarmCoordinator for direct access.
477
+ * This is the canonical coordination engine as per ADR-003.
478
+ *
479
+ * Use this to access advanced features not exposed by the SwarmHub facade.
480
+ */
481
+ getCoordinator(): UnifiedSwarmCoordinator {
482
+ return this.coordinator;
483
+ }
484
+
485
+ // ==========================================================================
486
+ // Private Helpers
487
+ // ==========================================================================
488
+
489
+ private ensureInitialized(): void {
490
+ const state = this.coordinator.getState();
491
+ if (state.status === 'stopped' || state.status === 'initializing') {
492
+ throw new Error('SwarmHub is not initialized. Call initialize() first.');
493
+ }
494
+ }
495
+
496
+ private convertToCoordinatorConfig(): any {
497
+ return {
498
+ topology: {
499
+ type: 'hierarchical' as const,
500
+ maxAgents: 15,
501
+ replicationFactor: 2,
502
+ partitionStrategy: 'hash' as const,
503
+ failoverEnabled: true,
504
+ autoRebalance: true,
505
+ },
506
+ consensus: {
507
+ algorithm: 'raft' as const,
508
+ threshold: 0.66,
509
+ timeoutMs: 5000,
510
+ maxRounds: 10,
511
+ requireQuorum: true,
512
+ },
513
+ messageBus: {
514
+ maxQueueSize: 10000,
515
+ processingIntervalMs: 10,
516
+ ackTimeoutMs: 5000,
517
+ retryAttempts: 3,
518
+ enablePersistence: false,
519
+ compressionEnabled: false,
520
+ },
521
+ maxAgents: 15,
522
+ maxTasks: 1000,
523
+ heartbeatIntervalMs: 5000,
524
+ healthCheckIntervalMs: 5000,
525
+ taskTimeoutMs: 300000,
526
+ autoScaling: true,
527
+ autoRecovery: true,
528
+ };
529
+ }
530
+
531
+ private createPhaseDefinitions(): Map<PhaseId, PhaseDefinition> {
532
+ const phases = new Map<PhaseId, PhaseDefinition>();
533
+
534
+ phases.set('phase-1-foundation', {
535
+ id: 'phase-1-foundation',
536
+ name: 'Foundation',
537
+ description: 'Security architecture, core design, and infrastructure setup',
538
+ weeks: [1, 2],
539
+ activeAgents: ['agent-1', 'agent-2', 'agent-3', 'agent-4', 'agent-5', 'agent-6'],
540
+ goals: [
541
+ 'Initialize swarm coordination',
542
+ 'Complete security architecture review',
543
+ 'Begin CVE fixes (CVE-1, CVE-2, CVE-3)',
544
+ 'Design core DDD architecture',
545
+ 'Modernize type system'
546
+ ],
547
+ milestones: []
548
+ });
549
+
550
+ phases.set('phase-2-core', {
551
+ id: 'phase-2-core',
552
+ name: 'Core Systems',
553
+ description: 'Core implementation, memory unification, and swarm coordination',
554
+ weeks: [3, 6],
555
+ activeAgents: ['agent-1', 'agent-5', 'agent-6', 'agent-7', 'agent-8', 'agent-9', 'agent-13'],
556
+ goals: [
557
+ 'Complete core module implementation',
558
+ 'Unify memory system with AgentDB (150x improvement)',
559
+ 'Merge 4 coordination systems into single SwarmCoordinator',
560
+ 'Optimize MCP server',
561
+ 'Implement TDD London School tests'
562
+ ],
563
+ milestones: []
564
+ });
565
+
566
+ phases.set('phase-3-integration', {
567
+ id: 'phase-3-integration',
568
+ name: 'Integration',
569
+ description: '@sparkleideas/agentic-flow integration, CLI modernization, and neural features',
570
+ weeks: [7, 10],
571
+ activeAgents: ['agent-1', 'agent-10', 'agent-11', 'agent-12', 'agent-13', 'agent-14'],
572
+ goals: [
573
+ 'Complete @sparkleideas/agentic-flow@alpha integration',
574
+ 'Modernize CLI and hooks system',
575
+ 'Integrate Neural/SONA learning',
576
+ 'Run integration tests',
577
+ 'Initial performance benchmarks'
578
+ ],
579
+ milestones: []
580
+ });
581
+
582
+ phases.set('phase-4-release', {
583
+ id: 'phase-4-release',
584
+ name: 'Optimization & Release',
585
+ description: 'Performance optimization, deployment, and v3.0.0 release',
586
+ weeks: [11, 14],
587
+ activeAgents: [
588
+ 'agent-1', 'agent-2', 'agent-3', 'agent-4', 'agent-5', 'agent-6',
589
+ 'agent-7', 'agent-8', 'agent-9', 'agent-10', 'agent-11', 'agent-12',
590
+ 'agent-13', 'agent-14', 'agent-15'
591
+ ],
592
+ goals: [
593
+ 'Achieve 2.49x-7.47x Flash Attention speedup',
594
+ 'Verify 150x-12,500x AgentDB search improvement',
595
+ 'Complete deployment pipeline',
596
+ 'Final test coverage push (>90%)',
597
+ 'Release v3.0.0'
598
+ ],
599
+ milestones: []
600
+ });
601
+
602
+ return phases;
603
+ }
604
+
605
+ private initializeMilestones(): void {
606
+ const allMilestones: MilestoneDefinition[] = [
607
+ {
608
+ id: 'ms-security-architecture',
609
+ name: 'Security Architecture Complete',
610
+ description: 'All security reviews and CVE fixes implemented',
611
+ criteria: [
612
+ { description: 'CVE-1 fixed', met: false, evidence: null },
613
+ { description: 'CVE-2 fixed', met: false, evidence: null },
614
+ { description: 'CVE-3 fixed', met: false, evidence: null },
615
+ { description: 'Security tests passing', met: false, evidence: null }
616
+ ],
617
+ status: 'pending',
618
+ completedAt: null
619
+ },
620
+ {
621
+ id: 'ms-core-architecture',
622
+ name: 'Core Architecture Complete',
623
+ description: 'DDD structure implemented with all core modules',
624
+ criteria: [
625
+ { description: 'DDD bounded contexts defined', met: false, evidence: null },
626
+ { description: 'Core modules implemented', met: false, evidence: null },
627
+ { description: 'Type system modernized', met: false, evidence: null }
628
+ ],
629
+ status: 'pending',
630
+ completedAt: null
631
+ },
632
+ {
633
+ id: 'ms-memory-unification',
634
+ name: 'Memory Unification Complete',
635
+ description: 'Single memory service with AgentDB backend achieving 150x improvement',
636
+ criteria: [
637
+ { description: 'AgentDB integrated', met: false, evidence: null },
638
+ { description: '150x search improvement verified', met: false, evidence: null },
639
+ { description: 'Hybrid backend working', met: false, evidence: null }
640
+ ],
641
+ status: 'pending',
642
+ completedAt: null
643
+ },
644
+ {
645
+ id: 'ms-swarm-coordination',
646
+ name: 'Swarm Coordination Unified',
647
+ description: 'Single SwarmCoordinator merging 4 systems',
648
+ criteria: [
649
+ { description: 'Single CoordinationEngine', met: false, evidence: null },
650
+ { description: 'Pluggable strategies', met: false, evidence: null },
651
+ { description: '50% code reduction', met: false, evidence: null }
652
+ ],
653
+ status: 'pending',
654
+ completedAt: null
655
+ },
656
+ {
657
+ id: 'ms-agentic-integration',
658
+ name: '@sparkleideas/agentic-flow Integration Complete',
659
+ description: 'Deep integration with @sparkleideas/agentic-flow@alpha eliminating duplicate code',
660
+ criteria: [
661
+ { description: 'Agent class extends @sparkleideas/agentic-flow', met: false, evidence: null },
662
+ { description: 'Swarm uses @sparkleideas/agentic-flow system', met: false, evidence: null },
663
+ { description: '<5,000 lines of orchestration code', met: false, evidence: null }
664
+ ],
665
+ status: 'pending',
666
+ completedAt: null
667
+ },
668
+ {
669
+ id: 'ms-performance-targets',
670
+ name: 'Performance Targets Met',
671
+ description: 'All performance targets achieved and verified',
672
+ criteria: [
673
+ { description: '2.49x-7.47x Flash Attention speedup', met: false, evidence: null },
674
+ { description: '150x-12,500x AgentDB search', met: false, evidence: null },
675
+ { description: '50-75% memory reduction', met: false, evidence: null },
676
+ { description: '<500ms startup time', met: false, evidence: null }
677
+ ],
678
+ status: 'pending',
679
+ completedAt: null
680
+ },
681
+ {
682
+ id: 'ms-v3-release',
683
+ name: 'V3.0.0 Released',
684
+ description: 'Claude-Flow v3.0.0 published to npm',
685
+ criteria: [
686
+ { description: 'All tests passing (>90% coverage)', met: false, evidence: null },
687
+ { description: 'Documentation complete', met: false, evidence: null },
688
+ { description: 'npm package published', met: false, evidence: null },
689
+ { description: 'GitHub release created', met: false, evidence: null }
690
+ ],
691
+ status: 'pending',
692
+ completedAt: null
693
+ }
694
+ ];
695
+
696
+ for (const milestone of allMilestones) {
697
+ this.milestones.set(milestone.id, milestone);
698
+ }
699
+
700
+ for (const [phaseId, phase] of this.phases) {
701
+ switch (phaseId) {
702
+ case 'phase-1-foundation':
703
+ phase.milestones = [
704
+ this.milestones.get('ms-security-architecture')!,
705
+ this.milestones.get('ms-core-architecture')!
706
+ ];
707
+ break;
708
+ case 'phase-2-core':
709
+ phase.milestones = [
710
+ this.milestones.get('ms-memory-unification')!,
711
+ this.milestones.get('ms-swarm-coordination')!
712
+ ];
713
+ break;
714
+ case 'phase-3-integration':
715
+ phase.milestones = [
716
+ this.milestones.get('ms-agentic-integration')!
717
+ ];
718
+ break;
719
+ case 'phase-4-release':
720
+ phase.milestones = [
721
+ this.milestones.get('ms-performance-targets')!,
722
+ this.milestones.get('ms-v3-release')!
723
+ ];
724
+ break;
725
+ }
726
+ }
727
+ }
728
+ }
729
+
730
+ // =============================================================================
731
+ // Factory Functions - COMPATIBILITY LAYER (ADR-003)
732
+ // =============================================================================
733
+
734
+ /**
735
+ * @deprecated Use createUnifiedSwarmCoordinator() instead.
736
+ * This factory is maintained for backward compatibility only.
737
+ *
738
+ * Migration:
739
+ * ```typescript
740
+ * // OLD:
741
+ * const hub = createSwarmHub();
742
+ *
743
+ * // NEW:
744
+ * import { createUnifiedSwarmCoordinator } from '@sparkleideas/swarm';
745
+ * const coordinator = createUnifiedSwarmCoordinator();
746
+ * ```
747
+ */
748
+ export function createSwarmHub(eventBus?: IEventBus): ISwarmHub {
749
+ console.warn('[DEPRECATION] createSwarmHub() is deprecated. Use createUnifiedSwarmCoordinator() instead.');
750
+ return new SwarmHub(eventBus);
751
+ }
752
+
753
+ let globalSwarmHub: ISwarmHub | null = null;
754
+
755
+ /**
756
+ * @deprecated Use UnifiedSwarmCoordinator singleton pattern instead.
757
+ * This function is maintained for backward compatibility only.
758
+ */
759
+ export function getSwarmHub(): ISwarmHub {
760
+ console.warn('[DEPRECATION] getSwarmHub() is deprecated. Use UnifiedSwarmCoordinator directly.');
761
+ if (!globalSwarmHub) {
762
+ globalSwarmHub = createSwarmHub();
763
+ }
764
+ return globalSwarmHub;
765
+ }
766
+
767
+ /**
768
+ * @deprecated Use coordinator.shutdown() directly instead.
769
+ */
770
+ export function resetSwarmHub(): void {
771
+ console.warn('[DEPRECATION] resetSwarmHub() is deprecated. Call shutdown() on your coordinator instance.');
772
+ if (globalSwarmHub?.isInitialized()) {
773
+ globalSwarmHub.shutdown();
774
+ }
775
+ globalSwarmHub = null;
776
+ }