@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,544 @@
1
+ /**
2
+ * V3 Agent Registry
3
+ * Manages registration, lifecycle, and capabilities of all 15 agents
4
+ *
5
+ * Based on ADR-002 (DDD) and 15-Agent Swarm Architecture
6
+ */
7
+
8
+ import {
9
+ AgentId,
10
+ AgentRole,
11
+ AgentDomain,
12
+ AgentStatus,
13
+ AgentDefinition,
14
+ AgentState,
15
+ AgentCapability,
16
+ AgentMetrics,
17
+ TaskType,
18
+ TaskId,
19
+ SwarmEvent,
20
+ EventHandler
21
+ } from '../shared/types';
22
+ import {
23
+ IEventBus,
24
+ agentSpawnedEvent,
25
+ agentStatusChangedEvent,
26
+ agentErrorEvent
27
+ } from '../shared/events';
28
+
29
+ // =============================================================================
30
+ // Agent Registry Interface
31
+ // =============================================================================
32
+
33
+ export interface IAgentRegistry {
34
+ // Registration
35
+ register(definition: AgentDefinition): void;
36
+ unregister(agentId: AgentId): boolean;
37
+ isRegistered(agentId: AgentId): boolean;
38
+
39
+ // Lifecycle
40
+ spawn(agentId: AgentId): Promise<AgentState>;
41
+ terminate(agentId: AgentId): Promise<boolean>;
42
+
43
+ // State Management
44
+ getState(agentId: AgentId): AgentState | undefined;
45
+ updateStatus(agentId: AgentId, status: AgentStatus): void;
46
+ assignTask(agentId: AgentId, taskId: TaskId): void;
47
+ completeTask(agentId: AgentId, taskId: TaskId): void;
48
+
49
+ // Queries
50
+ getDefinition(agentId: AgentId): AgentDefinition | undefined;
51
+ getAllAgents(): AgentDefinition[];
52
+ getActiveAgents(): AgentState[];
53
+ getAgentsByDomain(domain: AgentDomain): AgentDefinition[];
54
+ getAgentsByCapability(taskType: TaskType): AgentDefinition[];
55
+
56
+ // Health
57
+ heartbeat(agentId: AgentId): void;
58
+ getHealthStatus(): Map<AgentId, HealthStatus>;
59
+
60
+ // Events
61
+ onAgentEvent(handler: EventHandler): () => void;
62
+ }
63
+
64
+ export interface HealthStatus {
65
+ agentId: AgentId;
66
+ healthy: boolean;
67
+ lastHeartbeat: number;
68
+ consecutiveMisses: number;
69
+ status: AgentStatus;
70
+ }
71
+
72
+ // =============================================================================
73
+ // Agent Registry Implementation
74
+ // =============================================================================
75
+
76
+ export class AgentRegistry implements IAgentRegistry {
77
+ private definitions: Map<AgentId, AgentDefinition> = new Map();
78
+ private states: Map<AgentId, AgentState> = new Map();
79
+ private healthChecks: Map<AgentId, HealthStatus> = new Map();
80
+ private eventBus: IEventBus;
81
+ private healthCheckInterval: number = 5000;
82
+ private healthCheckTimer: ReturnType<typeof setInterval> | null = null;
83
+ private maxMissedHeartbeats: number = 3;
84
+
85
+ constructor(eventBus: IEventBus) {
86
+ this.eventBus = eventBus;
87
+ this.registerDefaultAgents();
88
+ }
89
+
90
+ // ==========================================================================
91
+ // Registration
92
+ // ==========================================================================
93
+
94
+ register(definition: AgentDefinition): void {
95
+ if (this.definitions.has(definition.id)) {
96
+ throw new Error(`Agent ${definition.id} is already registered`);
97
+ }
98
+
99
+ this.definitions.set(definition.id, definition);
100
+
101
+ this.healthChecks.set(definition.id, {
102
+ agentId: definition.id,
103
+ healthy: false,
104
+ lastHeartbeat: 0,
105
+ consecutiveMisses: 0,
106
+ status: 'idle'
107
+ });
108
+ }
109
+
110
+ unregister(agentId: AgentId): boolean {
111
+ if (this.states.has(agentId)) {
112
+ throw new Error(`Cannot unregister active agent ${agentId}`);
113
+ }
114
+
115
+ this.healthChecks.delete(agentId);
116
+ return this.definitions.delete(agentId);
117
+ }
118
+
119
+ isRegistered(agentId: AgentId): boolean {
120
+ return this.definitions.has(agentId);
121
+ }
122
+
123
+ // ==========================================================================
124
+ // Lifecycle
125
+ // ==========================================================================
126
+
127
+ async spawn(agentId: AgentId): Promise<AgentState> {
128
+ const definition = this.definitions.get(agentId);
129
+ if (!definition) {
130
+ throw new Error(`Agent ${agentId} is not registered`);
131
+ }
132
+
133
+ if (this.states.has(agentId)) {
134
+ throw new Error(`Agent ${agentId} is already spawned`);
135
+ }
136
+
137
+ const state: AgentState = {
138
+ id: agentId,
139
+ role: definition.role,
140
+ status: 'idle',
141
+ currentTask: null,
142
+ completedTasks: [],
143
+ metrics: this.createInitialMetrics(),
144
+ lastHeartbeat: Date.now()
145
+ };
146
+
147
+ this.states.set(agentId, state);
148
+
149
+ const healthStatus = this.healthChecks.get(agentId)!;
150
+ healthStatus.healthy = true;
151
+ healthStatus.lastHeartbeat = Date.now();
152
+ healthStatus.status = 'idle';
153
+
154
+ await this.eventBus.emit(agentSpawnedEvent(agentId, definition.role));
155
+
156
+ return state;
157
+ }
158
+
159
+ async terminate(agentId: AgentId): Promise<boolean> {
160
+ const state = this.states.get(agentId);
161
+ if (!state) {
162
+ return false;
163
+ }
164
+
165
+ if (state.currentTask) {
166
+ throw new Error(`Cannot terminate agent ${agentId} with active task ${state.currentTask}`);
167
+ }
168
+
169
+ this.states.delete(agentId);
170
+
171
+ const healthStatus = this.healthChecks.get(agentId);
172
+ if (healthStatus) {
173
+ healthStatus.healthy = false;
174
+ healthStatus.status = 'idle';
175
+ }
176
+
177
+ await this.eventBus.emit(agentStatusChangedEvent(agentId, state.status, 'terminated'));
178
+
179
+ return true;
180
+ }
181
+
182
+ // ==========================================================================
183
+ // State Management
184
+ // ==========================================================================
185
+
186
+ getState(agentId: AgentId): AgentState | undefined {
187
+ return this.states.get(agentId);
188
+ }
189
+
190
+ updateStatus(agentId: AgentId, status: AgentStatus): void {
191
+ const state = this.states.get(agentId);
192
+ if (!state) {
193
+ throw new Error(`Agent ${agentId} is not spawned`);
194
+ }
195
+
196
+ const previousStatus = state.status;
197
+ state.status = status;
198
+
199
+ const healthStatus = this.healthChecks.get(agentId);
200
+ if (healthStatus) {
201
+ healthStatus.status = status;
202
+ }
203
+
204
+ this.eventBus.emitSync(agentStatusChangedEvent(agentId, previousStatus, status));
205
+ }
206
+
207
+ assignTask(agentId: AgentId, taskId: TaskId): void {
208
+ const state = this.states.get(agentId);
209
+ if (!state) {
210
+ throw new Error(`Agent ${agentId} is not spawned`);
211
+ }
212
+
213
+ if (state.currentTask) {
214
+ throw new Error(`Agent ${agentId} already has task ${state.currentTask}`);
215
+ }
216
+
217
+ state.currentTask = taskId;
218
+ this.updateStatus(agentId, 'active');
219
+ }
220
+
221
+ completeTask(agentId: AgentId, taskId: TaskId): void {
222
+ const state = this.states.get(agentId);
223
+ if (!state) {
224
+ throw new Error(`Agent ${agentId} is not spawned`);
225
+ }
226
+
227
+ if (state.currentTask !== taskId) {
228
+ throw new Error(`Agent ${agentId} current task is ${state.currentTask}, not ${taskId}`);
229
+ }
230
+
231
+ state.completedTasks.push(taskId);
232
+ state.currentTask = null;
233
+ state.metrics.tasksCompleted++;
234
+
235
+ this.updateStatus(agentId, 'idle');
236
+ }
237
+
238
+ // ==========================================================================
239
+ // Queries
240
+ // ==========================================================================
241
+
242
+ getDefinition(agentId: AgentId): AgentDefinition | undefined {
243
+ return this.definitions.get(agentId);
244
+ }
245
+
246
+ getAllAgents(): AgentDefinition[] {
247
+ return Array.from(this.definitions.values());
248
+ }
249
+
250
+ getActiveAgents(): AgentState[] {
251
+ return Array.from(this.states.values()).filter(s => s.status === 'active');
252
+ }
253
+
254
+ getAgentsByDomain(domain: AgentDomain): AgentDefinition[] {
255
+ return Array.from(this.definitions.values()).filter(d => d.domain === domain);
256
+ }
257
+
258
+ getAgentsByCapability(taskType: TaskType): AgentDefinition[] {
259
+ return Array.from(this.definitions.values()).filter(d =>
260
+ d.capabilities.some(c => c.supportedTaskTypes.includes(taskType))
261
+ );
262
+ }
263
+
264
+ // ==========================================================================
265
+ // Health Management
266
+ // ==========================================================================
267
+
268
+ heartbeat(agentId: AgentId): void {
269
+ const state = this.states.get(agentId);
270
+ if (state) {
271
+ state.lastHeartbeat = Date.now();
272
+ }
273
+
274
+ const healthStatus = this.healthChecks.get(agentId);
275
+ if (healthStatus) {
276
+ healthStatus.lastHeartbeat = Date.now();
277
+ healthStatus.consecutiveMisses = 0;
278
+ healthStatus.healthy = true;
279
+ }
280
+ }
281
+
282
+ getHealthStatus(): Map<AgentId, HealthStatus> {
283
+ return new Map(this.healthChecks);
284
+ }
285
+
286
+ startHealthChecks(): void {
287
+ if (this.healthCheckTimer) {
288
+ return;
289
+ }
290
+
291
+ this.healthCheckTimer = setInterval(() => {
292
+ this.performHealthCheck();
293
+ }, this.healthCheckInterval);
294
+ }
295
+
296
+ stopHealthChecks(): void {
297
+ if (this.healthCheckTimer) {
298
+ clearInterval(this.healthCheckTimer);
299
+ this.healthCheckTimer = null;
300
+ }
301
+ }
302
+
303
+ private performHealthCheck(): void {
304
+ const now = Date.now();
305
+
306
+ for (const [agentId, healthStatus] of this.healthChecks) {
307
+ const state = this.states.get(agentId);
308
+ if (!state) {
309
+ continue;
310
+ }
311
+
312
+ const timeSinceHeartbeat = now - healthStatus.lastHeartbeat;
313
+
314
+ if (timeSinceHeartbeat > this.healthCheckInterval) {
315
+ healthStatus.consecutiveMisses++;
316
+
317
+ if (healthStatus.consecutiveMisses >= this.maxMissedHeartbeats) {
318
+ healthStatus.healthy = false;
319
+ this.updateStatus(agentId, 'error');
320
+
321
+ this.eventBus.emitSync(agentErrorEvent(
322
+ agentId,
323
+ new Error(`Agent ${agentId} missed ${healthStatus.consecutiveMisses} heartbeats`)
324
+ ));
325
+ }
326
+ }
327
+ }
328
+ }
329
+
330
+ // ==========================================================================
331
+ // Events
332
+ // ==========================================================================
333
+
334
+ onAgentEvent(handler: EventHandler): () => void {
335
+ const unsubscribers = [
336
+ this.eventBus.subscribe('agent:spawned', handler),
337
+ this.eventBus.subscribe('agent:status-changed', handler),
338
+ this.eventBus.subscribe('agent:task-assigned', handler),
339
+ this.eventBus.subscribe('agent:task-completed', handler),
340
+ this.eventBus.subscribe('agent:error', handler)
341
+ ];
342
+
343
+ return () => {
344
+ unsubscribers.forEach(unsub => unsub());
345
+ };
346
+ }
347
+
348
+ // ==========================================================================
349
+ // Default Agent Registration
350
+ // ==========================================================================
351
+
352
+ private registerDefaultAgents(): void {
353
+ const agentDefinitions: AgentDefinition[] = [
354
+ {
355
+ id: 'agent-1',
356
+ role: 'queen-coordinator',
357
+ domain: 'core',
358
+ description: 'Orchestration & GitHub Issue management for all 15 agents',
359
+ capabilities: [
360
+ { name: 'orchestration', description: 'Coordinate all agents', supportedTaskTypes: ['architecture-design'] },
361
+ { name: 'github-management', description: 'Manage GitHub issues and PRs', supportedTaskTypes: ['documentation'] }
362
+ ],
363
+ dependencies: [],
364
+ priority: 1
365
+ },
366
+ {
367
+ id: 'agent-2',
368
+ role: 'security-architect',
369
+ domain: 'security',
370
+ description: 'Security architecture review and design',
371
+ capabilities: [
372
+ { name: 'security-design', description: 'Design security architecture', supportedTaskTypes: ['security-audit', 'architecture-design'] }
373
+ ],
374
+ dependencies: [],
375
+ priority: 2
376
+ },
377
+ {
378
+ id: 'agent-3',
379
+ role: 'security-implementer',
380
+ domain: 'security',
381
+ description: 'CVE fixes and security code implementation',
382
+ capabilities: [
383
+ { name: 'security-implementation', description: 'Implement security fixes', supportedTaskTypes: ['security-fix', 'implementation'] }
384
+ ],
385
+ dependencies: ['agent-2'],
386
+ priority: 2
387
+ },
388
+ {
389
+ id: 'agent-4',
390
+ role: 'security-tester',
391
+ domain: 'security',
392
+ description: 'Security testing using TDD London School methodology',
393
+ capabilities: [
394
+ { name: 'security-testing', description: 'Write and run security tests', supportedTaskTypes: ['security-test', 'test-writing'] }
395
+ ],
396
+ dependencies: ['agent-2'],
397
+ priority: 2
398
+ },
399
+ {
400
+ id: 'agent-5',
401
+ role: 'core-architect',
402
+ domain: 'core',
403
+ description: 'Core module DDD architecture design',
404
+ capabilities: [
405
+ { name: 'architecture', description: 'Design core architecture', supportedTaskTypes: ['architecture-design'] }
406
+ ],
407
+ dependencies: ['agent-2'],
408
+ priority: 3
409
+ },
410
+ {
411
+ id: 'agent-6',
412
+ role: 'core-implementer',
413
+ domain: 'core',
414
+ description: 'Core module implementation and type system modernization',
415
+ capabilities: [
416
+ { name: 'core-implementation', description: 'Implement core modules', supportedTaskTypes: ['implementation'] }
417
+ ],
418
+ dependencies: ['agent-5'],
419
+ priority: 3
420
+ },
421
+ {
422
+ id: 'agent-7',
423
+ role: 'memory-specialist',
424
+ domain: 'core',
425
+ description: 'Memory system unification with AgentDB (150x-12500x improvement)',
426
+ capabilities: [
427
+ { name: 'memory-optimization', description: 'Optimize memory systems', supportedTaskTypes: ['memory-optimization', 'implementation'] }
428
+ ],
429
+ dependencies: ['agent-5'],
430
+ priority: 4
431
+ },
432
+ {
433
+ id: 'agent-8',
434
+ role: 'swarm-specialist',
435
+ domain: 'core',
436
+ description: 'Single SwarmCoordinator (merge 4 systems)',
437
+ capabilities: [
438
+ { name: 'swarm-coordination', description: 'Design swarm coordination', supportedTaskTypes: ['swarm-coordination', 'implementation'] }
439
+ ],
440
+ dependencies: ['agent-5'],
441
+ priority: 4
442
+ },
443
+ {
444
+ id: 'agent-9',
445
+ role: 'mcp-specialist',
446
+ domain: 'core',
447
+ description: 'MCP server optimization and enhancement',
448
+ capabilities: [
449
+ { name: 'mcp-optimization', description: 'Optimize MCP server', supportedTaskTypes: ['mcp-enhancement', 'implementation'] }
450
+ ],
451
+ dependencies: ['agent-5'],
452
+ priority: 4
453
+ },
454
+ {
455
+ id: 'agent-10',
456
+ role: 'integration-architect',
457
+ domain: 'integration',
458
+ description: '@sparkleideas/agentic-flow@alpha deep integration',
459
+ capabilities: [
460
+ { name: 'integration', description: 'Integrate with @sparkleideas/agentic-flow', supportedTaskTypes: ['integration', 'architecture-design'] }
461
+ ],
462
+ dependencies: ['agent-5', 'agent-7', 'agent-8', 'agent-9'],
463
+ priority: 5
464
+ },
465
+ {
466
+ id: 'agent-11',
467
+ role: 'cli-hooks-developer',
468
+ domain: 'integration',
469
+ description: 'CLI modernization and hooks system development',
470
+ capabilities: [
471
+ { name: 'cli-development', description: 'Develop CLI and hooks', supportedTaskTypes: ['cli-development', 'implementation'] }
472
+ ],
473
+ dependencies: ['agent-9', 'agent-10'],
474
+ priority: 5
475
+ },
476
+ {
477
+ id: 'agent-12',
478
+ role: 'neural-learning-dev',
479
+ domain: 'integration',
480
+ description: 'Neural and SONA learning system integration',
481
+ capabilities: [
482
+ { name: 'neural-training', description: 'Implement neural features', supportedTaskTypes: ['neural-training', 'implementation'] }
483
+ ],
484
+ dependencies: ['agent-7', 'agent-10'],
485
+ priority: 5
486
+ },
487
+ {
488
+ id: 'agent-13',
489
+ role: 'tdd-test-engineer',
490
+ domain: 'quality',
491
+ description: 'TDD London School methodology implementation',
492
+ capabilities: [
493
+ { name: 'testing', description: 'Write comprehensive tests', supportedTaskTypes: ['test-writing'] }
494
+ ],
495
+ dependencies: [],
496
+ priority: 3
497
+ },
498
+ {
499
+ id: 'agent-14',
500
+ role: 'performance-engineer',
501
+ domain: 'performance',
502
+ description: 'Benchmarking and performance optimization (2.49x-7.47x target)',
503
+ capabilities: [
504
+ { name: 'benchmarking', description: 'Run performance benchmarks', supportedTaskTypes: ['benchmark'] }
505
+ ],
506
+ dependencies: ['agent-7', 'agent-8'],
507
+ priority: 6
508
+ },
509
+ {
510
+ id: 'agent-15',
511
+ role: 'release-engineer',
512
+ domain: 'deployment',
513
+ description: 'Deployment pipeline and release management',
514
+ capabilities: [
515
+ { name: 'deployment', description: 'Manage releases', supportedTaskTypes: ['deployment', 'documentation'] }
516
+ ],
517
+ dependencies: ['agent-10', 'agent-13', 'agent-14'],
518
+ priority: 7
519
+ }
520
+ ];
521
+
522
+ for (const definition of agentDefinitions) {
523
+ this.register(definition);
524
+ }
525
+ }
526
+
527
+ private createInitialMetrics(): AgentMetrics {
528
+ return {
529
+ tasksCompleted: 0,
530
+ tasksFailed: 0,
531
+ averageTaskDuration: 0,
532
+ utilization: 0,
533
+ startTime: Date.now()
534
+ };
535
+ }
536
+ }
537
+
538
+ // =============================================================================
539
+ // Factory Function
540
+ // =============================================================================
541
+
542
+ export function createAgentRegistry(eventBus: IEventBus): IAgentRegistry {
543
+ return new AgentRegistry(eventBus);
544
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Coordination Components
3
+ * Agent registry, task orchestration, and swarm hub
4
+ */
5
+
6
+ export {
7
+ AgentRegistry,
8
+ createAgentRegistry,
9
+ type IAgentRegistry,
10
+ } from './agent-registry.js';
11
+
12
+ export {
13
+ TaskOrchestrator,
14
+ createTaskOrchestrator,
15
+ type ITaskOrchestrator,
16
+ type TaskSpec,
17
+ } from './task-orchestrator.js';
18
+
19
+ export {
20
+ SwarmHub,
21
+ createSwarmHub,
22
+ type ISwarmHub,
23
+ } from './swarm-hub.js';