@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.
- package/MIGRATION.md +472 -0
- package/README.md +634 -0
- package/__tests__/consensus.test.ts +577 -0
- package/__tests__/coordinator.test.ts +501 -0
- package/__tests__/queen-coordinator.test.ts +1335 -0
- package/__tests__/topology.test.ts +621 -0
- package/package.json +32 -0
- package/src/agent-pool.ts +476 -0
- package/src/application/commands/create-task.command.ts +124 -0
- package/src/application/commands/spawn-agent.command.ts +122 -0
- package/src/application/index.ts +30 -0
- package/src/application/services/swarm-application-service.ts +200 -0
- package/src/attention-coordinator.ts +1000 -0
- package/src/consensus/byzantine.ts +431 -0
- package/src/consensus/gossip.ts +513 -0
- package/src/consensus/index.ts +267 -0
- package/src/consensus/raft.ts +443 -0
- package/src/coordination/agent-registry.ts +544 -0
- package/src/coordination/index.ts +23 -0
- package/src/coordination/swarm-hub.ts +776 -0
- package/src/coordination/task-orchestrator.ts +605 -0
- package/src/domain/entities/agent.d.ts +151 -0
- package/src/domain/entities/agent.d.ts.map +1 -0
- package/src/domain/entities/agent.js +280 -0
- package/src/domain/entities/agent.js.map +1 -0
- package/src/domain/entities/agent.ts +370 -0
- package/src/domain/entities/task.d.ts +133 -0
- package/src/domain/entities/task.d.ts.map +1 -0
- package/src/domain/entities/task.js +261 -0
- package/src/domain/entities/task.js.map +1 -0
- package/src/domain/entities/task.ts +319 -0
- package/src/domain/index.ts +41 -0
- package/src/domain/repositories/agent-repository.interface.d.ts +57 -0
- package/src/domain/repositories/agent-repository.interface.d.ts.map +1 -0
- package/src/domain/repositories/agent-repository.interface.js +9 -0
- package/src/domain/repositories/agent-repository.interface.js.map +1 -0
- package/src/domain/repositories/agent-repository.interface.ts +69 -0
- package/src/domain/repositories/task-repository.interface.d.ts +61 -0
- package/src/domain/repositories/task-repository.interface.d.ts.map +1 -0
- package/src/domain/repositories/task-repository.interface.js +9 -0
- package/src/domain/repositories/task-repository.interface.js.map +1 -0
- package/src/domain/repositories/task-repository.interface.ts +75 -0
- package/src/domain/services/coordination-service.ts +320 -0
- package/src/federation-hub.d.ts +284 -0
- package/src/federation-hub.d.ts.map +1 -0
- package/src/federation-hub.js +692 -0
- package/src/federation-hub.js.map +1 -0
- package/src/federation-hub.ts +979 -0
- package/src/index.ts +348 -0
- package/src/message-bus.ts +607 -0
- package/src/queen-coordinator.ts +2025 -0
- package/src/shared/events.ts +285 -0
- package/src/shared/types.ts +389 -0
- package/src/topology-manager.ts +656 -0
- package/src/types.ts +545 -0
- package/src/unified-coordinator.ts +1844 -0
- package/src/workers/index.ts +65 -0
- package/src/workers/worker-dispatch.d.ts +234 -0
- package/src/workers/worker-dispatch.d.ts.map +1 -0
- package/src/workers/worker-dispatch.js +842 -0
- package/src/workers/worker-dispatch.js.map +1 -0
- package/src/workers/worker-dispatch.ts +1076 -0
- package/tmp.json +0 -0
- package/tsconfig.json +9 -0
- package/vitest.config.ts +20 -0
package/README.md
ADDED
|
@@ -0,0 +1,634 @@
|
|
|
1
|
+
# @claude-flow/swarm
|
|
2
|
+
|
|
3
|
+
[](https://www.npmjs.com/package/@claude-flow/swarm)
|
|
4
|
+
[](https://www.npmjs.com/package/@claude-flow/swarm)
|
|
5
|
+
[](https://opensource.org/licenses/MIT)
|
|
6
|
+
[](https://www.typescriptlang.org/)
|
|
7
|
+
[](https://github.com/ruvnet/claude-flow)
|
|
8
|
+
[](https://github.com/ruvnet/claude-flow)
|
|
9
|
+
|
|
10
|
+
> V3 Unified Swarm Coordination Module implementing ADR-003: Single Coordination Engine with Hive-Mind Intelligence
|
|
11
|
+
|
|
12
|
+
## Architecture (ADR-003)
|
|
13
|
+
|
|
14
|
+
This module provides a **complete multi-agent coordination system** with hive-mind capabilities:
|
|
15
|
+
|
|
16
|
+
### Key Components
|
|
17
|
+
|
|
18
|
+
```
|
|
19
|
+
@claude-flow/swarm
|
|
20
|
+
├── UnifiedSwarmCoordinator ⭐ CANONICAL ENGINE
|
|
21
|
+
│ ├── Configurable agent count (default 15, max 100+)
|
|
22
|
+
│ ├── Domain-based task routing
|
|
23
|
+
│ ├── Parallel execution across domains
|
|
24
|
+
│ ├── Multiple consensus algorithms
|
|
25
|
+
│ ├── 4 topology types (mesh, hierarchical, centralized, hybrid)
|
|
26
|
+
│ └── Performance: <100ms coordination
|
|
27
|
+
│
|
|
28
|
+
├── QueenCoordinator 👑 HIVE-MIND INTELLIGENCE
|
|
29
|
+
│ ├── Strategic task analysis & decomposition
|
|
30
|
+
│ ├── Agent capability-based delegation
|
|
31
|
+
│ ├── Swarm health monitoring & bottleneck detection
|
|
32
|
+
│ ├── 5 consensus types (majority, supermajority, unanimous, weighted, queen-override)
|
|
33
|
+
│ └── Learning from outcomes
|
|
34
|
+
│
|
|
35
|
+
├── AttentionCoordinator 🧠 ATTENTION MECHANISMS
|
|
36
|
+
│ ├── Flash Attention (2.49x-7.47x speedup)
|
|
37
|
+
│ ├── Multi-Head Attention (8 heads)
|
|
38
|
+
│ ├── Linear Attention (O(n) complexity)
|
|
39
|
+
│ ├── Hyperbolic Attention (Poincaré hierarchies)
|
|
40
|
+
│ ├── Mixture of Experts (MoE) routing
|
|
41
|
+
│ └── GraphRoPE (topology-aware positioning)
|
|
42
|
+
│
|
|
43
|
+
├── FederationHub 🌐 CROSS-SWARM COORDINATION
|
|
44
|
+
│ ├── Ephemeral agent spawning with TTL
|
|
45
|
+
│ ├── Cross-swarm messaging
|
|
46
|
+
│ ├── Federation-wide consensus voting
|
|
47
|
+
│ └── Auto-cleanup & heartbeat tracking
|
|
48
|
+
│
|
|
49
|
+
├── ConsensusEngines 🗳️ DISTRIBUTED AGREEMENT
|
|
50
|
+
│ ├── Raft (leader election, log replication)
|
|
51
|
+
│ ├── Byzantine (fault-tolerant, 2/3 supermajority)
|
|
52
|
+
│ └── Gossip (epidemic protocol for large swarms)
|
|
53
|
+
│
|
|
54
|
+
└── SwarmHub (deprecated) - Thin facade for backward compatibility
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
## ⚠️ Agent Count: Configurable, Not Limited
|
|
58
|
+
|
|
59
|
+
The default 15-agent architecture is a **recommendation**, not a hard limit:
|
|
60
|
+
|
|
61
|
+
```typescript
|
|
62
|
+
// Default: 15-agent V3 architecture
|
|
63
|
+
const coordinator = createUnifiedSwarmCoordinator({
|
|
64
|
+
topology: { type: 'hierarchical', maxAgents: 15 },
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
// Scale up: 50 agents
|
|
68
|
+
const largeCoordinator = createUnifiedSwarmCoordinator({
|
|
69
|
+
topology: { type: 'mesh', maxAgents: 50 },
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
// Maximum: 100+ agents (DEFAULT_MAX_AGENTS = 100)
|
|
73
|
+
const enterpriseCoordinator = createUnifiedSwarmCoordinator({
|
|
74
|
+
topology: { type: 'hybrid', maxAgents: 100 },
|
|
75
|
+
});
|
|
76
|
+
```
|
|
77
|
+
|
|
78
|
+
## Quick Start (Recommended)
|
|
79
|
+
|
|
80
|
+
```typescript
|
|
81
|
+
import { createUnifiedSwarmCoordinator } from '@claude-flow/swarm';
|
|
82
|
+
|
|
83
|
+
// Create coordinator
|
|
84
|
+
const coordinator = createUnifiedSwarmCoordinator({
|
|
85
|
+
topology: { type: 'hierarchical', maxAgents: 15 },
|
|
86
|
+
consensus: { algorithm: 'raft', threshold: 0.66 },
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
// Initialize
|
|
90
|
+
await coordinator.initialize();
|
|
91
|
+
|
|
92
|
+
// Spawn 15-agent hierarchy
|
|
93
|
+
const agents = await coordinator.spawnFullHierarchy();
|
|
94
|
+
console.log(`Spawned ${agents.size} agents across 5 domains`);
|
|
95
|
+
|
|
96
|
+
// Submit tasks to specific domains
|
|
97
|
+
const securityTaskId = await coordinator.submitTask({
|
|
98
|
+
type: 'review',
|
|
99
|
+
name: 'CVE Security Audit',
|
|
100
|
+
priority: 'critical',
|
|
101
|
+
maxRetries: 3,
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
await coordinator.assignTaskToDomain(securityTaskId, 'security');
|
|
105
|
+
|
|
106
|
+
// Parallel execution across domains
|
|
107
|
+
const results = await coordinator.executeParallel([
|
|
108
|
+
{ task: { type: 'coding', name: 'Core Implementation' }, domain: 'core' },
|
|
109
|
+
{ task: { type: 'testing', name: 'Security Tests' }, domain: 'security' },
|
|
110
|
+
{ task: { type: 'documentation', name: 'API Docs' }, domain: 'integration' },
|
|
111
|
+
]);
|
|
112
|
+
|
|
113
|
+
console.log(`Completed ${results.filter(r => r.success).length} tasks in parallel`);
|
|
114
|
+
|
|
115
|
+
// Get swarm status
|
|
116
|
+
const status = coordinator.getStatus();
|
|
117
|
+
console.log('Domain Status:', status.domains);
|
|
118
|
+
console.log('Metrics:', status.metrics);
|
|
119
|
+
|
|
120
|
+
// Shutdown
|
|
121
|
+
await coordinator.shutdown();
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
## 15-Agent Domain Architecture
|
|
125
|
+
|
|
126
|
+
The coordinator manages 5 domains with specific agent assignments:
|
|
127
|
+
|
|
128
|
+
| Domain | Agents | Capabilities |
|
|
129
|
+
|--------|--------|--------------|
|
|
130
|
+
| **Queen** | 1 | Top-level coordination, consensus, planning |
|
|
131
|
+
| **Security** | 2-4 | Security architecture, CVE fixes, threat modeling |
|
|
132
|
+
| **Core** | 5-9 | DDD design, memory unification, type modernization |
|
|
133
|
+
| **Integration** | 10-12 | agentic-flow integration, CLI, neural features |
|
|
134
|
+
| **Support** | 13-15 | TDD testing, performance, deployment |
|
|
135
|
+
|
|
136
|
+
### Domain-Based Task Routing
|
|
137
|
+
|
|
138
|
+
```typescript
|
|
139
|
+
// Route tasks to optimal domains
|
|
140
|
+
await coordinator.assignTaskToDomain(securityTask, 'security');
|
|
141
|
+
await coordinator.assignTaskToDomain(coreTask, 'core');
|
|
142
|
+
await coordinator.assignTaskToDomain(integrationTask, 'integration');
|
|
143
|
+
|
|
144
|
+
// Get agents by domain
|
|
145
|
+
const securityAgents = coordinator.getAgentsByDomain('security');
|
|
146
|
+
console.log(`Security domain has ${securityAgents.length} agents`);
|
|
147
|
+
|
|
148
|
+
// Get domain status
|
|
149
|
+
const status = coordinator.getStatus();
|
|
150
|
+
status.domains.forEach(domain => {
|
|
151
|
+
console.log(`${domain.name}: ${domain.availableAgents}/${domain.agentCount} available`);
|
|
152
|
+
});
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
## Parallel Execution
|
|
156
|
+
|
|
157
|
+
Execute tasks across multiple domains simultaneously for maximum throughput:
|
|
158
|
+
|
|
159
|
+
```typescript
|
|
160
|
+
const tasks = [
|
|
161
|
+
{ task: { type: 'coding', name: 'Implement Auth' }, domain: 'core' },
|
|
162
|
+
{ task: { type: 'testing', name: 'Security Tests' }, domain: 'security' },
|
|
163
|
+
{ task: { type: 'review', name: 'Code Review' }, domain: 'support' },
|
|
164
|
+
];
|
|
165
|
+
|
|
166
|
+
const results = await coordinator.executeParallel(tasks);
|
|
167
|
+
|
|
168
|
+
// Check results
|
|
169
|
+
results.forEach(result => {
|
|
170
|
+
if (result.success) {
|
|
171
|
+
console.log(`✅ ${result.domain}: ${result.durationMs}ms`);
|
|
172
|
+
} else {
|
|
173
|
+
console.error(`❌ ${result.domain}: ${result.error?.message}`);
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
```
|
|
177
|
+
|
|
178
|
+
## Topology Support
|
|
179
|
+
|
|
180
|
+
Choose the coordination pattern that fits your needs:
|
|
181
|
+
|
|
182
|
+
| Topology | Best For | Scalability | Latency |
|
|
183
|
+
|----------|----------|-------------|---------|
|
|
184
|
+
| **Hierarchical** | Queen-led swarms | O(n), up to 100+ | 15-35ms |
|
|
185
|
+
| **Mesh** | Distributed workloads | O(n²), up to 20 | 10-40ms |
|
|
186
|
+
| **Centralized** | Simple coordination | O(n), up to 50 | 10-20ms |
|
|
187
|
+
| **Hybrid** | Large mixed workloads | O(n), up to 200 | 20-50ms |
|
|
188
|
+
|
|
189
|
+
### Hierarchical (Default)
|
|
190
|
+
```typescript
|
|
191
|
+
const coordinator = createUnifiedSwarmCoordinator({
|
|
192
|
+
topology: { type: 'hierarchical', maxAgents: 15 },
|
|
193
|
+
});
|
|
194
|
+
```
|
|
195
|
+
- Queen agent coordinates domain leads
|
|
196
|
+
- Domain leads manage worker agents
|
|
197
|
+
- Best for domain-organized V3 architecture
|
|
198
|
+
|
|
199
|
+
### Mesh
|
|
200
|
+
```typescript
|
|
201
|
+
const coordinator = createUnifiedSwarmCoordinator({
|
|
202
|
+
topology: { type: 'mesh', maxAgents: 20 },
|
|
203
|
+
});
|
|
204
|
+
```
|
|
205
|
+
- Limited peer-to-peer connections (max ~10 per node)
|
|
206
|
+
- No central coordinator
|
|
207
|
+
- Best for distributed workloads under 20 agents
|
|
208
|
+
|
|
209
|
+
### Centralized
|
|
210
|
+
```typescript
|
|
211
|
+
const coordinator = createUnifiedSwarmCoordinator({
|
|
212
|
+
topology: { type: 'centralized', maxAgents: 50 },
|
|
213
|
+
});
|
|
214
|
+
```
|
|
215
|
+
- Single coordinator hub manages all agents
|
|
216
|
+
- Simplest to reason about
|
|
217
|
+
- Best for small to medium swarms
|
|
218
|
+
|
|
219
|
+
### Hybrid (Best for Scale)
|
|
220
|
+
```typescript
|
|
221
|
+
const coordinator = createUnifiedSwarmCoordinator({
|
|
222
|
+
topology: { type: 'hybrid', maxAgents: 100 },
|
|
223
|
+
});
|
|
224
|
+
```
|
|
225
|
+
- Mesh workers + hierarchical coordinators
|
|
226
|
+
- Combines benefits of both patterns
|
|
227
|
+
- Best for large-scale enterprise deployments
|
|
228
|
+
|
|
229
|
+
## Consensus Algorithms
|
|
230
|
+
|
|
231
|
+
Choose how agents reach agreement:
|
|
232
|
+
|
|
233
|
+
### Raft (Default)
|
|
234
|
+
```typescript
|
|
235
|
+
const coordinator = createUnifiedSwarmCoordinator({
|
|
236
|
+
consensus: { algorithm: 'raft', threshold: 0.66 },
|
|
237
|
+
});
|
|
238
|
+
```
|
|
239
|
+
- Leader-based consensus
|
|
240
|
+
- Strong consistency guarantees
|
|
241
|
+
- Target: <100ms consensus time
|
|
242
|
+
|
|
243
|
+
### Byzantine Fault Tolerance
|
|
244
|
+
```typescript
|
|
245
|
+
const coordinator = createUnifiedSwarmCoordinator({
|
|
246
|
+
consensus: { algorithm: 'byzantine', threshold: 0.66 },
|
|
247
|
+
});
|
|
248
|
+
```
|
|
249
|
+
- Handles malicious agents
|
|
250
|
+
- Byzantine fault tolerance
|
|
251
|
+
- Higher overhead but more secure
|
|
252
|
+
|
|
253
|
+
### Gossip Protocol
|
|
254
|
+
```typescript
|
|
255
|
+
const coordinator = createUnifiedSwarmCoordinator({
|
|
256
|
+
consensus: { algorithm: 'gossip', threshold: 0.66 },
|
|
257
|
+
});
|
|
258
|
+
```
|
|
259
|
+
- Eventual consistency
|
|
260
|
+
- Low overhead
|
|
261
|
+
- Best for large swarms
|
|
262
|
+
|
|
263
|
+
## Performance Targets
|
|
264
|
+
|
|
265
|
+
The coordinator is optimized for V3 performance requirements:
|
|
266
|
+
|
|
267
|
+
| Metric | Target | Actual |
|
|
268
|
+
|--------|--------|--------|
|
|
269
|
+
| Coordination Latency | <100ms | Verified in tests |
|
|
270
|
+
| Consensus Time | <100ms | Verified in tests |
|
|
271
|
+
| Message Throughput | >1000 msgs/sec | Verified in tests |
|
|
272
|
+
| Agent Utilization | >85% | Achieved via parallel execution |
|
|
273
|
+
|
|
274
|
+
### Performance Monitoring
|
|
275
|
+
|
|
276
|
+
```typescript
|
|
277
|
+
const report = coordinator.getPerformanceReport();
|
|
278
|
+
|
|
279
|
+
console.log('Coordination Latency:', {
|
|
280
|
+
p50: report.coordinationLatencyP50,
|
|
281
|
+
p99: report.coordinationLatencyP99,
|
|
282
|
+
});
|
|
283
|
+
|
|
284
|
+
console.log('Throughput:', {
|
|
285
|
+
messagesPerSec: report.messagesPerSecond,
|
|
286
|
+
tasksPerSec: report.taskThroughput,
|
|
287
|
+
});
|
|
288
|
+
|
|
289
|
+
console.log('Utilization:', {
|
|
290
|
+
agentUtilization: report.agentUtilization,
|
|
291
|
+
consensusSuccessRate: report.consensusSuccessRate,
|
|
292
|
+
});
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
## Backward Compatibility (SwarmHub)
|
|
296
|
+
|
|
297
|
+
For existing code using `SwarmHub`, the compatibility layer is maintained:
|
|
298
|
+
|
|
299
|
+
```typescript
|
|
300
|
+
import { createSwarmHub } from '@claude-flow/swarm';
|
|
301
|
+
|
|
302
|
+
// ⚠️ DEPRECATED: Use createUnifiedSwarmCoordinator() instead
|
|
303
|
+
const hub = createSwarmHub();
|
|
304
|
+
await hub.initialize();
|
|
305
|
+
|
|
306
|
+
// SwarmHub delegates all operations to UnifiedSwarmCoordinator
|
|
307
|
+
const coordinator = hub.getCoordinator();
|
|
308
|
+
|
|
309
|
+
// Use coordinator for advanced features
|
|
310
|
+
await coordinator.executeParallel(tasks);
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
### Migration from SwarmHub
|
|
314
|
+
|
|
315
|
+
```typescript
|
|
316
|
+
// OLD (deprecated)
|
|
317
|
+
import { createSwarmHub } from '@claude-flow/swarm';
|
|
318
|
+
const hub = createSwarmHub();
|
|
319
|
+
await hub.initialize();
|
|
320
|
+
await hub.spawnAllAgents();
|
|
321
|
+
|
|
322
|
+
// NEW (recommended)
|
|
323
|
+
import { createUnifiedSwarmCoordinator } from '@claude-flow/swarm';
|
|
324
|
+
const coordinator = createUnifiedSwarmCoordinator();
|
|
325
|
+
await coordinator.initialize();
|
|
326
|
+
await coordinator.spawnFullHierarchy();
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
## Hive-Mind Intelligence (Queen Coordinator)
|
|
330
|
+
|
|
331
|
+
The Queen Coordinator provides intelligent task orchestration:
|
|
332
|
+
|
|
333
|
+
```typescript
|
|
334
|
+
import { createQueenCoordinator } from '@claude-flow/swarm';
|
|
335
|
+
|
|
336
|
+
const queen = createQueenCoordinator({
|
|
337
|
+
swarmCoordinator: coordinator,
|
|
338
|
+
// Optional: connect to neural learning system
|
|
339
|
+
// neuralSystem: myNeuralSystem,
|
|
340
|
+
// memoryService: myMemoryService,
|
|
341
|
+
});
|
|
342
|
+
|
|
343
|
+
// Analyze a complex task
|
|
344
|
+
const analysis = await queen.analyzeTask({
|
|
345
|
+
id: 'task-1',
|
|
346
|
+
type: 'security-audit',
|
|
347
|
+
description: 'Comprehensive CVE audit of authentication system',
|
|
348
|
+
});
|
|
349
|
+
|
|
350
|
+
console.log('Task Analysis:', {
|
|
351
|
+
complexity: analysis.complexity, // 'low' | 'medium' | 'high' | 'critical'
|
|
352
|
+
estimatedDuration: analysis.estimatedDuration,
|
|
353
|
+
requiredCapabilities: analysis.requiredCapabilities,
|
|
354
|
+
suggestedSubtasks: analysis.subtasks,
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
// Delegate to optimal agents
|
|
358
|
+
const plan = await queen.delegateToAgents(task, analysis);
|
|
359
|
+
console.log('Delegation Plan:', {
|
|
360
|
+
primaryAgent: plan.primaryAgent,
|
|
361
|
+
backupAgents: plan.backupAgents,
|
|
362
|
+
parallelAssignments: plan.parallelAssignments,
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
// Monitor swarm health
|
|
366
|
+
const health = await queen.monitorSwarmHealth();
|
|
367
|
+
console.log('Health Report:', {
|
|
368
|
+
overallStatus: health.status,
|
|
369
|
+
bottlenecks: health.bottlenecks,
|
|
370
|
+
alerts: health.alerts,
|
|
371
|
+
recommendations: health.recommendations,
|
|
372
|
+
});
|
|
373
|
+
|
|
374
|
+
// Coordinate consensus with 5 types
|
|
375
|
+
const decision = await queen.coordinateConsensus({
|
|
376
|
+
type: 'deployment',
|
|
377
|
+
value: { version: '3.0.0', environment: 'production' },
|
|
378
|
+
consensusType: 'supermajority', // 'majority' | 'supermajority' | 'unanimous' | 'weighted' | 'queen-override'
|
|
379
|
+
});
|
|
380
|
+
```
|
|
381
|
+
|
|
382
|
+
## Attention Mechanisms
|
|
383
|
+
|
|
384
|
+
Six attention mechanisms for intelligent agent coordination:
|
|
385
|
+
|
|
386
|
+
```typescript
|
|
387
|
+
import { createAttentionCoordinator } from '@claude-flow/swarm';
|
|
388
|
+
|
|
389
|
+
const attention = createAttentionCoordinator({
|
|
390
|
+
topology: coordinator.getTopology(),
|
|
391
|
+
});
|
|
392
|
+
|
|
393
|
+
// Flash Attention - 2.49x-7.47x speedup for long sequences
|
|
394
|
+
const flashResult = await attention.coordinate(agents, task, { type: 'flash' });
|
|
395
|
+
|
|
396
|
+
// Multi-Head Attention - 8 parallel attention heads
|
|
397
|
+
const multiHeadResult = await attention.coordinate(agents, task, { type: 'multi-head' });
|
|
398
|
+
|
|
399
|
+
// Linear Attention - O(n) complexity for very long sequences
|
|
400
|
+
const linearResult = await attention.coordinate(agents, task, { type: 'linear' });
|
|
401
|
+
|
|
402
|
+
// Hyperbolic Attention - Poincaré distance for hierarchies
|
|
403
|
+
const hyperbolicResult = await attention.coordinate(agents, task, { type: 'hyperbolic' });
|
|
404
|
+
|
|
405
|
+
// Mixture of Experts - Route to top-k best agents
|
|
406
|
+
const moeResult = await attention.coordinate(agents, task, {
|
|
407
|
+
type: 'moe',
|
|
408
|
+
topK: 3,
|
|
409
|
+
loadBalancing: true,
|
|
410
|
+
});
|
|
411
|
+
|
|
412
|
+
// GraphRoPE - Topology-aware position encoding
|
|
413
|
+
const graphResult = await attention.coordinate(agents, task, { type: 'graph-rope' });
|
|
414
|
+
```
|
|
415
|
+
|
|
416
|
+
## Federation Hub (Cross-Swarm Coordination)
|
|
417
|
+
|
|
418
|
+
Coordinate multiple swarms with ephemeral agents:
|
|
419
|
+
|
|
420
|
+
```typescript
|
|
421
|
+
import { createFederationHub, getDefaultFederationHub } from '@claude-flow/swarm';
|
|
422
|
+
|
|
423
|
+
// Get singleton hub or create custom
|
|
424
|
+
const hub = getDefaultFederationHub();
|
|
425
|
+
// or: const hub = createFederationHub({ maxSwarms: 10 });
|
|
426
|
+
|
|
427
|
+
// Register swarms
|
|
428
|
+
await hub.registerSwarm('swarm-security', {
|
|
429
|
+
coordinator: securityCoordinator,
|
|
430
|
+
capabilities: ['security-audit', 'penetration-testing'],
|
|
431
|
+
});
|
|
432
|
+
|
|
433
|
+
await hub.registerSwarm('swarm-dev', {
|
|
434
|
+
coordinator: devCoordinator,
|
|
435
|
+
capabilities: ['coding', 'testing', 'review'],
|
|
436
|
+
});
|
|
437
|
+
|
|
438
|
+
// Spawn ephemeral agent (auto-cleanup after TTL)
|
|
439
|
+
const { agentId } = await hub.spawnEphemeral({
|
|
440
|
+
swarmId: 'swarm-security',
|
|
441
|
+
ttlMs: 300000, // 5 minutes
|
|
442
|
+
task: { type: 'quick-audit', target: 'auth-module' },
|
|
443
|
+
});
|
|
444
|
+
|
|
445
|
+
// Cross-swarm messaging
|
|
446
|
+
await hub.sendMessage({
|
|
447
|
+
from: 'swarm-dev',
|
|
448
|
+
to: 'swarm-security',
|
|
449
|
+
type: 'audit-request',
|
|
450
|
+
payload: { module: 'auth', priority: 'high' },
|
|
451
|
+
});
|
|
452
|
+
|
|
453
|
+
// Federation-wide consensus
|
|
454
|
+
const vote = await hub.proposeConsensus({
|
|
455
|
+
topic: 'release-v3',
|
|
456
|
+
options: ['approve', 'reject', 'defer'],
|
|
457
|
+
timeout: 30000,
|
|
458
|
+
});
|
|
459
|
+
|
|
460
|
+
// Get federation stats
|
|
461
|
+
const stats = hub.getStats();
|
|
462
|
+
console.log('Federation:', {
|
|
463
|
+
swarms: stats.swarmCount,
|
|
464
|
+
ephemeralAgents: stats.ephemeralAgentCount,
|
|
465
|
+
messagesSent: stats.messageCount,
|
|
466
|
+
});
|
|
467
|
+
```
|
|
468
|
+
|
|
469
|
+
## Advanced Features
|
|
470
|
+
|
|
471
|
+
### Agent Pool Management
|
|
472
|
+
|
|
473
|
+
```typescript
|
|
474
|
+
// Get domain-specific pool
|
|
475
|
+
const corePool = coordinator.getDomainPool('core');
|
|
476
|
+
const stats = corePool?.getPoolStats();
|
|
477
|
+
|
|
478
|
+
console.log('Core Domain Pool:', {
|
|
479
|
+
total: stats?.total,
|
|
480
|
+
available: stats?.available,
|
|
481
|
+
busy: stats?.busy,
|
|
482
|
+
});
|
|
483
|
+
|
|
484
|
+
// Auto-scaling is built-in
|
|
485
|
+
// - Scale up at 80% utilization
|
|
486
|
+
// - Scale down at 20% utilization
|
|
487
|
+
```
|
|
488
|
+
|
|
489
|
+
### Custom Agent Registration
|
|
490
|
+
|
|
491
|
+
```typescript
|
|
492
|
+
// Register agent with automatic domain assignment
|
|
493
|
+
const { agentId, domain } = await coordinator.registerAgentWithDomain(
|
|
494
|
+
{
|
|
495
|
+
name: 'security-agent-2',
|
|
496
|
+
type: 'specialist',
|
|
497
|
+
status: 'idle',
|
|
498
|
+
capabilities: {
|
|
499
|
+
codeReview: true,
|
|
500
|
+
securityAudit: true,
|
|
501
|
+
},
|
|
502
|
+
// ... other agent properties
|
|
503
|
+
},
|
|
504
|
+
2 // Agent number 2 → security domain
|
|
505
|
+
);
|
|
506
|
+
|
|
507
|
+
console.log(`Registered ${agentId} in ${domain} domain`);
|
|
508
|
+
```
|
|
509
|
+
|
|
510
|
+
### Event Monitoring
|
|
511
|
+
|
|
512
|
+
```typescript
|
|
513
|
+
coordinator.on('agent.joined', (event) => {
|
|
514
|
+
console.log('Agent joined:', event.data.agentId);
|
|
515
|
+
});
|
|
516
|
+
|
|
517
|
+
coordinator.on('task.completed', (event) => {
|
|
518
|
+
console.log('Task completed:', event.data.taskId);
|
|
519
|
+
});
|
|
520
|
+
|
|
521
|
+
coordinator.on('consensus.achieved', (event) => {
|
|
522
|
+
console.log('Consensus achieved:', event.data.approvalRate);
|
|
523
|
+
});
|
|
524
|
+
|
|
525
|
+
coordinator.on('swarm.initialized', (event) => {
|
|
526
|
+
console.log('Swarm initialized:', event.data.swarmId);
|
|
527
|
+
});
|
|
528
|
+
```
|
|
529
|
+
|
|
530
|
+
## API Reference
|
|
531
|
+
|
|
532
|
+
### UnifiedSwarmCoordinator
|
|
533
|
+
|
|
534
|
+
#### Lifecycle
|
|
535
|
+
- `initialize(): Promise<void>` - Initialize coordinator
|
|
536
|
+
- `shutdown(): Promise<void>` - Shutdown coordinator
|
|
537
|
+
- `pause(): Promise<void>` - Pause operations
|
|
538
|
+
- `resume(): Promise<void>` - Resume operations
|
|
539
|
+
|
|
540
|
+
#### Agent Management
|
|
541
|
+
- `registerAgent(agent): Promise<string>` - Register agent
|
|
542
|
+
- `registerAgentWithDomain(agent, number): Promise<{agentId, domain}>` - Register with domain
|
|
543
|
+
- `unregisterAgent(id): Promise<void>` - Unregister agent
|
|
544
|
+
- `spawnFullHierarchy(): Promise<Map<number, {agentId, domain}>>` - Spawn 15 agents
|
|
545
|
+
- `getAgent(id): AgentState | undefined` - Get agent by ID
|
|
546
|
+
- `getAllAgents(): AgentState[]` - Get all agents
|
|
547
|
+
- `getAgentsByDomain(domain): AgentState[]` - Get agents in domain
|
|
548
|
+
|
|
549
|
+
#### Task Management
|
|
550
|
+
- `submitTask(task): Promise<string>` - Submit task
|
|
551
|
+
- `assignTaskToDomain(taskId, domain): Promise<string | undefined>` - Assign to domain
|
|
552
|
+
- `executeParallel(tasks): Promise<ParallelExecutionResult[]>` - Parallel execution
|
|
553
|
+
- `cancelTask(taskId): Promise<void>` - Cancel task
|
|
554
|
+
- `getTask(id): TaskDefinition | undefined` - Get task by ID
|
|
555
|
+
|
|
556
|
+
#### Coordination
|
|
557
|
+
- `proposeConsensus(value): Promise<ConsensusResult>` - Propose consensus
|
|
558
|
+
- `broadcastMessage(payload, priority): Promise<void>` - Broadcast message
|
|
559
|
+
|
|
560
|
+
#### Monitoring
|
|
561
|
+
- `getState(): CoordinatorState` - Get current state
|
|
562
|
+
- `getMetrics(): CoordinatorMetrics` - Get metrics
|
|
563
|
+
- `getPerformanceReport(): PerformanceReport` - Get performance stats
|
|
564
|
+
- `getStatus(): {swarmId, status, domains, metrics}` - Get comprehensive status
|
|
565
|
+
|
|
566
|
+
## Integration with agentic-flow@alpha
|
|
567
|
+
|
|
568
|
+
This module can integrate with agentic-flow@alpha for enhanced capabilities:
|
|
569
|
+
|
|
570
|
+
```typescript
|
|
571
|
+
import { createUnifiedSwarmCoordinator } from '@claude-flow/swarm';
|
|
572
|
+
import { AgenticFlowBridge } from '@claude-flow/integration';
|
|
573
|
+
|
|
574
|
+
// Connect to agentic-flow for enhanced features
|
|
575
|
+
const bridge = new AgenticFlowBridge({
|
|
576
|
+
agenticFlow: { version: 'alpha' },
|
|
577
|
+
});
|
|
578
|
+
|
|
579
|
+
const coordinator = createUnifiedSwarmCoordinator({
|
|
580
|
+
topology: { type: 'hierarchical', maxAgents: 15 },
|
|
581
|
+
// Enable agentic-flow features via bridge
|
|
582
|
+
extensions: {
|
|
583
|
+
transport: bridge.getQuicTransport(), // QUIC 0-RTT
|
|
584
|
+
learning: bridge.getSwarmLearningOptimizer(),
|
|
585
|
+
},
|
|
586
|
+
});
|
|
587
|
+
```
|
|
588
|
+
|
|
589
|
+
### Available from agentic-flow@alpha
|
|
590
|
+
|
|
591
|
+
| Feature | Status | Description |
|
|
592
|
+
|---------|--------|-------------|
|
|
593
|
+
| QUIC Transport | 🔌 Via bridge | 0-RTT connections, 50-70% faster |
|
|
594
|
+
| Swarm Learning Optimizer | 🔌 Via bridge | Auto topology recommendations |
|
|
595
|
+
| E2B Sandbox Agents | 🔌 Via bridge | Isolated execution environments |
|
|
596
|
+
| P2P with GunDB/IPFS | 🔌 Via bridge | Free decentralized coordination |
|
|
597
|
+
| WASM Acceleration | ⏳ Planned | HNSW indexing, semantic routing |
|
|
598
|
+
|
|
599
|
+
## Roadmap: Future Enhancements
|
|
600
|
+
|
|
601
|
+
Based on agentic-flow@alpha capabilities that could be integrated:
|
|
602
|
+
|
|
603
|
+
### Priority 1 (High Impact)
|
|
604
|
+
- [ ] Native QUIC transport with HTTP/2 fallback
|
|
605
|
+
- [ ] Swarm learning optimizer for auto-topology
|
|
606
|
+
- [ ] Free P2P provider integration (GunDB, IPFS)
|
|
607
|
+
|
|
608
|
+
### Priority 2 (Medium Impact)
|
|
609
|
+
- [ ] WASM-accelerated member indexing
|
|
610
|
+
- [ ] E2B sandbox agent specialization
|
|
611
|
+
- [ ] Enhanced message types with fuel/memory budgets
|
|
612
|
+
|
|
613
|
+
### Priority 3 (Nice to Have)
|
|
614
|
+
- [ ] Advanced gossip variants
|
|
615
|
+
- [ ] CRDT synchronization
|
|
616
|
+
- [ ] Production-grade Ed25519/X25519 cryptography
|
|
617
|
+
|
|
618
|
+
## Contributing
|
|
619
|
+
|
|
620
|
+
This module follows ADR-003: Single Coordination Engine. When contributing:
|
|
621
|
+
|
|
622
|
+
1. **All coordination logic** goes in `UnifiedSwarmCoordinator`
|
|
623
|
+
2. **SwarmHub** is a thin facade - no new logic there
|
|
624
|
+
3. **Domain-based routing** should be used for organized hierarchies
|
|
625
|
+
4. **Performance targets** must be maintained (<100ms coordination)
|
|
626
|
+
5. **New features** should integrate via the extensions API
|
|
627
|
+
|
|
628
|
+
## License
|
|
629
|
+
|
|
630
|
+
MIT
|
|
631
|
+
|
|
632
|
+
---
|
|
633
|
+
|
|
634
|
+
**ADR-003 Compliance**: This module implements a single canonical coordination engine with hive-mind intelligence, 6 attention mechanisms, federation support, and backward compatibility via facade pattern.
|