@sparkleideas/swarm 3.0.0-alpha.10

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
package/MIGRATION.md ADDED
@@ -0,0 +1,472 @@
1
+ # SwarmHub → UnifiedSwarmCoordinator Migration Guide
2
+
3
+ Quick reference for migrating from `SwarmHub` to `UnifiedSwarmCoordinator`
4
+
5
+ ## Why Migrate?
6
+
7
+ **ADR-003** establishes `UnifiedSwarmCoordinator` as the **single canonical coordination engine**. `SwarmHub` is now a thin compatibility layer maintained only for backward compatibility.
8
+
9
+ ### Benefits of Migrating
10
+
11
+ - ✅ Direct access to full coordinator API
12
+ - ✅ Better performance (no facade overhead)
13
+ - ✅ Advanced features (domain routing, parallel execution)
14
+ - ✅ Future-proof (SwarmHub will be removed in v3.1.0+)
15
+ - ✅ Cleaner code
16
+
17
+ ## Quick Migration
18
+
19
+ ### Import Changes
20
+
21
+ ```typescript
22
+ // OLD (deprecated)
23
+ import { createSwarmHub } from '@claude-flow/swarm';
24
+
25
+ // NEW (recommended)
26
+ import { createUnifiedSwarmCoordinator } from '@claude-flow/swarm';
27
+ ```
28
+
29
+ ### Initialization
30
+
31
+ ```typescript
32
+ // OLD
33
+ const hub = createSwarmHub();
34
+ await hub.initialize();
35
+
36
+ // NEW
37
+ const coordinator = createUnifiedSwarmCoordinator({
38
+ topology: { type: 'hierarchical', maxAgents: 15 },
39
+ consensus: { algorithm: 'raft', threshold: 0.66 },
40
+ });
41
+ await coordinator.initialize();
42
+ ```
43
+
44
+ ### Spawning Agents
45
+
46
+ ```typescript
47
+ // OLD
48
+ await hub.spawnAllAgents();
49
+
50
+ // NEW (more powerful)
51
+ const agents = await coordinator.spawnFullHierarchy();
52
+ // Returns Map<number, {agentId, domain}>
53
+ ```
54
+
55
+ ### Task Management
56
+
57
+ ```typescript
58
+ // OLD
59
+ const task = hub.submitTask({ name: 'Task', type: 'coding' });
60
+
61
+ // NEW (same API)
62
+ const taskId = await coordinator.submitTask({
63
+ type: 'coding',
64
+ name: 'Task',
65
+ priority: 'normal',
66
+ maxRetries: 3,
67
+ });
68
+ ```
69
+
70
+ ### Advanced Features (New)
71
+
72
+ ```typescript
73
+ // Domain-based routing (not available in SwarmHub)
74
+ await coordinator.assignTaskToDomain(taskId, 'security');
75
+
76
+ // Parallel execution across domains
77
+ const results = await coordinator.executeParallel([
78
+ { task: { type: 'coding', name: 'Core' }, domain: 'core' },
79
+ { task: { type: 'testing', name: 'Tests' }, domain: 'security' },
80
+ { task: { type: 'review', name: 'Review' }, domain: 'support' },
81
+ ]);
82
+
83
+ // Get domain-specific status
84
+ const status = coordinator.getStatus();
85
+ status.domains.forEach(domain => {
86
+ console.log(`${domain.name}: ${domain.availableAgents} available`);
87
+ });
88
+ ```
89
+
90
+ ### Shutdown
91
+
92
+ ```typescript
93
+ // OLD
94
+ await hub.shutdown();
95
+
96
+ // NEW (same API)
97
+ await coordinator.shutdown();
98
+ ```
99
+
100
+ ## Complete Example
101
+
102
+ ### Before (SwarmHub)
103
+
104
+ ```typescript
105
+ import { createSwarmHub } from '@claude-flow/swarm';
106
+
107
+ async function runSwarm() {
108
+ const hub = createSwarmHub();
109
+ await hub.initialize();
110
+
111
+ const agents = await hub.spawnAllAgents();
112
+ console.log(`Spawned ${agents.size} agents`);
113
+
114
+ const task = hub.submitTask({
115
+ name: 'Security Review',
116
+ type: 'review',
117
+ });
118
+
119
+ const nextTask = hub.assignNextTask('agent-2');
120
+ if (nextTask) {
121
+ hub.completeTask(nextTask.id, { success: true });
122
+ }
123
+
124
+ await hub.shutdown();
125
+ }
126
+ ```
127
+
128
+ ### After (UnifiedSwarmCoordinator)
129
+
130
+ ```typescript
131
+ import { createUnifiedSwarmCoordinator } from '@claude-flow/swarm';
132
+
133
+ async function runSwarm() {
134
+ const coordinator = createUnifiedSwarmCoordinator({
135
+ topology: { type: 'hierarchical', maxAgents: 15 },
136
+ consensus: { algorithm: 'raft', threshold: 0.66 },
137
+ });
138
+
139
+ await coordinator.initialize();
140
+
141
+ // Spawn 15-agent hierarchy across 5 domains
142
+ const agents = await coordinator.spawnFullHierarchy();
143
+ console.log(`Spawned ${agents.size} agents across 5 domains`);
144
+
145
+ // Submit task
146
+ const taskId = await coordinator.submitTask({
147
+ type: 'review',
148
+ name: 'Security Review',
149
+ priority: 'high',
150
+ maxRetries: 3,
151
+ });
152
+
153
+ // Route to security domain
154
+ await coordinator.assignTaskToDomain(taskId, 'security');
155
+
156
+ // Get comprehensive status
157
+ const status = coordinator.getStatus();
158
+ console.log('Metrics:', status.metrics);
159
+ console.log('Domain Status:', status.domains);
160
+
161
+ await coordinator.shutdown();
162
+ }
163
+ ```
164
+
165
+ ## API Mapping
166
+
167
+ | SwarmHub Method | UnifiedSwarmCoordinator Method | Notes |
168
+ |----------------|-------------------------------|-------|
169
+ | `initialize()` | `initialize()` | Same API |
170
+ | `shutdown()` | `shutdown()` | Same API |
171
+ | `isInitialized()` | Check `getState().status` | Slightly different |
172
+ | `spawnAgent(id)` | `registerAgent(agent)` | Different API |
173
+ | `spawnAllAgents()` | `spawnFullHierarchy()` | Better return type |
174
+ | `spawnAgentsByDomain(d)` | `getAgentsByDomain(d)` + register | Different approach |
175
+ | `terminateAgent(id)` | `unregisterAgent(id)` | Same API |
176
+ | `submitTask(spec)` | `submitTask(task)` | Similar API |
177
+ | `assignNextTask(agentId)` | Use task orchestration | Different pattern |
178
+ | `completeTask(id, result)` | Handle via events | Different pattern |
179
+ | `getState()` | `getState()` | Same API |
180
+ | `getMetrics()` | `getMetrics()` | Same API |
181
+ | N/A | `assignTaskToDomain(id, domain)` | **New feature** |
182
+ | N/A | `executeParallel(tasks)` | **New feature** |
183
+ | N/A | `getStatus()` | **New feature** |
184
+
185
+ ## Compatibility Layer (Temporary)
186
+
187
+ If you can't migrate immediately, use the compatibility layer:
188
+
189
+ ```typescript
190
+ import { createSwarmHub } from '@claude-flow/swarm';
191
+
192
+ const hub = createSwarmHub();
193
+ await hub.initialize();
194
+
195
+ // Access the underlying coordinator for advanced features
196
+ const coordinator = hub.getCoordinator();
197
+
198
+ // Use coordinator directly for new features
199
+ await coordinator.executeParallel([
200
+ { task: task1, domain: 'core' },
201
+ { task: task2, domain: 'security' },
202
+ ]);
203
+
204
+ // Continue using hub for legacy API
205
+ const agents = await hub.spawnAllAgents();
206
+ ```
207
+
208
+ ## New Features Only in UnifiedSwarmCoordinator
209
+
210
+ ### 1. Domain-Based Routing
211
+
212
+ ```typescript
213
+ // Route tasks to specific domains
214
+ await coordinator.assignTaskToDomain(securityTaskId, 'security');
215
+ await coordinator.assignTaskToDomain(coreTaskId, 'core');
216
+ await coordinator.assignTaskToDomain(integrationTaskId, 'integration');
217
+ ```
218
+
219
+ ### 2. Parallel Execution
220
+
221
+ ```typescript
222
+ const results = await coordinator.executeParallel([
223
+ { task: { type: 'coding', name: 'Impl Auth' }, domain: 'core' },
224
+ { task: { type: 'testing', name: 'Security Tests' }, domain: 'security' },
225
+ { task: { type: 'review', name: 'Code Review' }, domain: 'support' },
226
+ ]);
227
+
228
+ // Check results
229
+ results.forEach(r => {
230
+ console.log(`${r.domain}: ${r.success ? '✅' : '❌'} (${r.durationMs}ms)`);
231
+ });
232
+ ```
233
+
234
+ ### 3. Domain Status
235
+
236
+ ```typescript
237
+ const status = coordinator.getStatus();
238
+
239
+ status.domains.forEach(domain => {
240
+ console.log(`${domain.name}:`, {
241
+ agentCount: domain.agentCount,
242
+ available: domain.availableAgents,
243
+ busy: domain.busyAgents,
244
+ queued: domain.tasksQueued,
245
+ completed: domain.tasksCompleted,
246
+ });
247
+ });
248
+ ```
249
+
250
+ ### 4. Performance Reporting
251
+
252
+ ```typescript
253
+ const report = coordinator.getPerformanceReport();
254
+
255
+ console.log({
256
+ coordinationLatencyP50: report.coordinationLatencyP50,
257
+ coordinationLatencyP99: report.coordinationLatencyP99,
258
+ messagesPerSecond: report.messagesPerSecond,
259
+ taskThroughput: report.taskThroughput,
260
+ agentUtilization: report.agentUtilization,
261
+ consensusSuccessRate: report.consensusSuccessRate,
262
+ });
263
+ ```
264
+
265
+ ### 5. Agent Domain Management
266
+
267
+ ```typescript
268
+ // Register agent with automatic domain assignment
269
+ const { agentId, domain } = await coordinator.registerAgentWithDomain(
270
+ agentData,
271
+ 2 // Agent number → determines domain
272
+ );
273
+
274
+ // Get all agents in a domain
275
+ const securityAgents = coordinator.getAgentsByDomain('security');
276
+ ```
277
+
278
+ ## TypeScript Types
279
+
280
+ ### UnifiedSwarmCoordinator Config
281
+
282
+ ```typescript
283
+ interface CoordinatorConfig {
284
+ topology: {
285
+ type: 'mesh' | 'hierarchical' | 'centralized' | 'hybrid';
286
+ maxAgents: number;
287
+ replicationFactor?: number;
288
+ partitionStrategy?: 'hash' | 'range';
289
+ failoverEnabled?: boolean;
290
+ autoRebalance?: boolean;
291
+ };
292
+ consensus: {
293
+ algorithm: 'raft' | 'byzantine' | 'gossip' | 'paxos';
294
+ threshold: number;
295
+ timeoutMs?: number;
296
+ maxRounds?: number;
297
+ requireQuorum?: boolean;
298
+ };
299
+ messageBus?: {
300
+ maxQueueSize?: number;
301
+ processingIntervalMs?: number;
302
+ ackTimeoutMs?: number;
303
+ retryAttempts?: number;
304
+ };
305
+ maxAgents?: number;
306
+ maxTasks?: number;
307
+ heartbeatIntervalMs?: number;
308
+ healthCheckIntervalMs?: number;
309
+ taskTimeoutMs?: number;
310
+ autoScaling?: boolean;
311
+ autoRecovery?: boolean;
312
+ }
313
+ ```
314
+
315
+ ### Domain Types
316
+
317
+ ```typescript
318
+ type AgentDomain = 'queen' | 'security' | 'core' | 'integration' | 'support';
319
+
320
+ interface DomainStatus {
321
+ name: AgentDomain;
322
+ agentCount: number;
323
+ availableAgents: number;
324
+ busyAgents: number;
325
+ tasksQueued: number;
326
+ tasksCompleted: number;
327
+ }
328
+
329
+ interface ParallelExecutionResult {
330
+ taskId: string;
331
+ domain: AgentDomain;
332
+ success: boolean;
333
+ result?: unknown;
334
+ error?: Error;
335
+ durationMs: number;
336
+ }
337
+ ```
338
+
339
+ ## Common Pitfalls
340
+
341
+ ### 1. Different Task Submission API
342
+
343
+ ```typescript
344
+ // ❌ SwarmHub API (spec object)
345
+ hub.submitTask({ name: 'Task', type: 'coding' });
346
+
347
+ // ✅ UnifiedSwarmCoordinator API (full task definition)
348
+ coordinator.submitTask({
349
+ type: 'coding',
350
+ name: 'Task',
351
+ priority: 'normal',
352
+ maxRetries: 3,
353
+ });
354
+ ```
355
+
356
+ ### 2. Agent Registration
357
+
358
+ ```typescript
359
+ // ❌ SwarmHub (simple ID)
360
+ hub.spawnAgent('agent-1');
361
+
362
+ // ✅ UnifiedSwarmCoordinator (full state)
363
+ coordinator.registerAgent({
364
+ name: 'agent-1',
365
+ type: 'worker',
366
+ status: 'idle',
367
+ capabilities: { /* ... */ },
368
+ metrics: { /* ... */ },
369
+ workload: 0,
370
+ health: 1.0,
371
+ // ...
372
+ });
373
+ ```
374
+
375
+ ### 3. Task Assignment
376
+
377
+ ```typescript
378
+ // ❌ SwarmHub (pull model)
379
+ const task = hub.assignNextTask(agentId);
380
+
381
+ // ✅ UnifiedSwarmCoordinator (push model)
382
+ const taskId = await coordinator.submitTask(taskDef);
383
+ await coordinator.assignTaskToDomain(taskId, 'security');
384
+ ```
385
+
386
+ ## Testing
387
+
388
+ ### Unit Tests
389
+
390
+ ```typescript
391
+ import { createUnifiedSwarmCoordinator } from '@claude-flow/swarm';
392
+
393
+ describe('UnifiedSwarmCoordinator', () => {
394
+ let coordinator;
395
+
396
+ beforeEach(async () => {
397
+ coordinator = createUnifiedSwarmCoordinator({
398
+ topology: { type: 'hierarchical', maxAgents: 15 },
399
+ });
400
+ await coordinator.initialize();
401
+ });
402
+
403
+ afterEach(async () => {
404
+ await coordinator.shutdown();
405
+ });
406
+
407
+ it('should spawn 15-agent hierarchy', async () => {
408
+ const agents = await coordinator.spawnFullHierarchy();
409
+ expect(agents.size).toBe(15);
410
+ });
411
+
412
+ it('should route tasks to domains', async () => {
413
+ const taskId = await coordinator.submitTask({
414
+ type: 'review',
415
+ name: 'Security Audit',
416
+ priority: 'high',
417
+ maxRetries: 3,
418
+ });
419
+
420
+ const agentId = await coordinator.assignTaskToDomain(taskId, 'security');
421
+ expect(agentId).toBeDefined();
422
+ });
423
+ });
424
+ ```
425
+
426
+ ## Deprecation Timeline
427
+
428
+ | Version | SwarmHub Status | Action Required |
429
+ |---------|----------------|-----------------|
430
+ | v3.0.0-alpha | Deprecated with warnings | Start migrating |
431
+ | v3.0.0-beta | Legacy compatibility mode | Complete migration |
432
+ | v3.0.0 | Final deprecation notices | Migration recommended |
433
+ | v3.1.0+ | **REMOVED** | Must use UnifiedSwarmCoordinator |
434
+
435
+ ## Getting Help
436
+
437
+ - **Documentation**: See `@claude-flow/swarm/README.md`
438
+ - **Examples**: See `/v3/examples/swarm-coordinator.ts`
439
+ - **Implementation**: See `/v3/docs/ADR-003-implementation-status.md`
440
+ - **Issues**: Report at GitHub
441
+
442
+ ## Summary
443
+
444
+ ### Do This ✅
445
+
446
+ ```typescript
447
+ import { createUnifiedSwarmCoordinator } from '@claude-flow/swarm';
448
+
449
+ const coordinator = createUnifiedSwarmCoordinator({
450
+ topology: { type: 'hierarchical', maxAgents: 15 },
451
+ consensus: { algorithm: 'raft', threshold: 0.66 },
452
+ });
453
+
454
+ await coordinator.initialize();
455
+ const agents = await coordinator.spawnFullHierarchy();
456
+ await coordinator.executeParallel(tasks);
457
+ ```
458
+
459
+ ### Not This ❌
460
+
461
+ ```typescript
462
+ import { createSwarmHub } from '@claude-flow/swarm';
463
+
464
+ const hub = createSwarmHub();
465
+ await hub.initialize();
466
+ await hub.spawnAllAgents();
467
+ // Missing domain routing, parallel execution, etc.
468
+ ```
469
+
470
+ ---
471
+
472
+ **Questions?** The `UnifiedSwarmCoordinator` is the future. Migrate today! 🚀