@claude-flow/cli 3.0.0-alpha.13 → 3.0.0-alpha.14

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 (102) hide show
  1. package/package.json +12 -4
  2. package/.agentic-flow/intelligence.json +0 -17
  3. package/.claude-flow/agents/store.json +0 -16
  4. package/.claude-flow/daemon-state.json +0 -123
  5. package/.claude-flow/daemon-test.log +0 -0
  6. package/.claude-flow/daemon.log +0 -0
  7. package/.claude-flow/daemon2.log +0 -0
  8. package/.claude-flow/daemon3.log +0 -0
  9. package/.claude-flow/hive-mind/state.json +0 -51
  10. package/.claude-flow/metrics/agent-metrics.json +0 -1
  11. package/.claude-flow/metrics/codebase-map.json +0 -11
  12. package/.claude-flow/metrics/consolidation.json +0 -6
  13. package/.claude-flow/metrics/performance.json +0 -87
  14. package/.claude-flow/metrics/security-audit.json +0 -10
  15. package/.claude-flow/metrics/task-metrics.json +0 -10
  16. package/.claude-flow/metrics/test-gaps.json +0 -6
  17. package/__tests__/README.md +0 -140
  18. package/__tests__/TEST_SUMMARY.md +0 -144
  19. package/__tests__/cli.test.ts +0 -558
  20. package/__tests__/commands.test.ts +0 -726
  21. package/__tests__/config-adapter.test.ts +0 -362
  22. package/__tests__/config-loading.test.ts +0 -106
  23. package/__tests__/coverage/.tmp/coverage-0.json +0 -1
  24. package/__tests__/coverage/.tmp/coverage-1.json +0 -1
  25. package/__tests__/coverage/.tmp/coverage-2.json +0 -1
  26. package/__tests__/coverage/.tmp/coverage-3.json +0 -1
  27. package/__tests__/coverage/.tmp/coverage-4.json +0 -1
  28. package/__tests__/coverage/.tmp/coverage-5.json +0 -1
  29. package/__tests__/mcp-client.test.ts +0 -480
  30. package/__tests__/p1-commands.test.ts +0 -1064
  31. package/agents/architect.yaml +0 -11
  32. package/agents/coder.yaml +0 -11
  33. package/agents/reviewer.yaml +0 -10
  34. package/agents/security-architect.yaml +0 -10
  35. package/agents/tester.yaml +0 -10
  36. package/docs/CONFIG_LOADING.md +0 -236
  37. package/docs/IMPLEMENTATION_COMPLETE.md +0 -421
  38. package/docs/MCP_CLIENT_GUIDE.md +0 -620
  39. package/docs/REFACTORING_SUMMARY.md +0 -247
  40. package/scripts/publish.sh +0 -46
  41. package/src/commands/agent.ts +0 -955
  42. package/src/commands/claims.ts +0 -317
  43. package/src/commands/completions.ts +0 -558
  44. package/src/commands/config.ts +0 -452
  45. package/src/commands/daemon.ts +0 -621
  46. package/src/commands/deployment.ts +0 -323
  47. package/src/commands/doctor.ts +0 -382
  48. package/src/commands/embeddings.ts +0 -686
  49. package/src/commands/hive-mind.ts +0 -928
  50. package/src/commands/hooks.ts +0 -2603
  51. package/src/commands/index.ts +0 -154
  52. package/src/commands/init.ts +0 -597
  53. package/src/commands/mcp.ts +0 -753
  54. package/src/commands/memory.ts +0 -1161
  55. package/src/commands/migrate.ts +0 -447
  56. package/src/commands/neural.ts +0 -253
  57. package/src/commands/performance.ts +0 -292
  58. package/src/commands/plugins.ts +0 -316
  59. package/src/commands/process.ts +0 -695
  60. package/src/commands/providers.ts +0 -259
  61. package/src/commands/security.ts +0 -288
  62. package/src/commands/session.ts +0 -891
  63. package/src/commands/start.ts +0 -457
  64. package/src/commands/status.ts +0 -736
  65. package/src/commands/swarm.ts +0 -648
  66. package/src/commands/task.ts +0 -792
  67. package/src/commands/workflow.ts +0 -742
  68. package/src/config-adapter.ts +0 -210
  69. package/src/index.ts +0 -443
  70. package/src/infrastructure/in-memory-repositories.ts +0 -310
  71. package/src/init/claudemd-generator.ts +0 -631
  72. package/src/init/executor.ts +0 -762
  73. package/src/init/helpers-generator.ts +0 -628
  74. package/src/init/index.ts +0 -60
  75. package/src/init/mcp-generator.ts +0 -83
  76. package/src/init/settings-generator.ts +0 -284
  77. package/src/init/statusline-generator.ts +0 -211
  78. package/src/init/types.ts +0 -447
  79. package/src/mcp-client.ts +0 -241
  80. package/src/mcp-server.ts +0 -577
  81. package/src/mcp-tools/agent-tools.ts +0 -466
  82. package/src/mcp-tools/config-tools.ts +0 -370
  83. package/src/mcp-tools/hive-mind-tools.ts +0 -521
  84. package/src/mcp-tools/hooks-tools.ts +0 -1888
  85. package/src/mcp-tools/index.ts +0 -16
  86. package/src/mcp-tools/memory-tools.ts +0 -270
  87. package/src/mcp-tools/session-tools.ts +0 -359
  88. package/src/mcp-tools/swarm-tools.ts +0 -105
  89. package/src/mcp-tools/task-tools.ts +0 -347
  90. package/src/mcp-tools/types.ts +0 -33
  91. package/src/mcp-tools/workflow-tools.ts +0 -573
  92. package/src/output.ts +0 -639
  93. package/src/parser.ts +0 -417
  94. package/src/prompt.ts +0 -619
  95. package/src/services/index.ts +0 -15
  96. package/src/services/worker-daemon.ts +0 -726
  97. package/src/suggest.ts +0 -245
  98. package/src/types.ts +0 -287
  99. package/tmp.json +0 -0
  100. package/tsconfig.json +0 -16
  101. package/tsconfig.tsbuildinfo +0 -1
  102. package/vitest.config.ts +0 -13
@@ -1,928 +0,0 @@
1
- /**
2
- * V3 CLI Hive Mind Command
3
- * Queen-led consensus-based multi-agent coordination
4
- */
5
-
6
- import type { Command, CommandContext, CommandResult } from '../types.js';
7
- import { output } from '../output.js';
8
- import { select, confirm, input } from '../prompt.js';
9
- import { callMCPTool, MCPClientError } from '../mcp-client.js';
10
-
11
- // Hive topologies
12
- const TOPOLOGIES = [
13
- { value: 'hierarchical', label: 'Hierarchical', hint: 'Queen-led with worker agents' },
14
- { value: 'mesh', label: 'Mesh', hint: 'Peer-to-peer coordination' },
15
- { value: 'hierarchical-mesh', label: 'Hierarchical Mesh', hint: 'Queen + peer communication (recommended)' },
16
- { value: 'adaptive', label: 'Adaptive', hint: 'Dynamic topology based on task' }
17
- ];
18
-
19
- // Consensus strategies
20
- const CONSENSUS_STRATEGIES = [
21
- { value: 'byzantine', label: 'Byzantine Fault Tolerant', hint: '2/3 majority, handles malicious actors' },
22
- { value: 'raft', label: 'Raft', hint: 'Leader-based consensus' },
23
- { value: 'gossip', label: 'Gossip', hint: 'Eventually consistent, scalable' },
24
- { value: 'crdt', label: 'CRDT', hint: 'Conflict-free replicated data' },
25
- { value: 'quorum', label: 'Quorum', hint: 'Simple majority voting' }
26
- ];
27
-
28
- // Init subcommand
29
- const initCommand: Command = {
30
- name: 'init',
31
- description: 'Initialize a hive mind',
32
- options: [
33
- {
34
- name: 'topology',
35
- short: 't',
36
- description: 'Hive topology',
37
- type: 'string',
38
- choices: TOPOLOGIES.map(t => t.value),
39
- default: 'hierarchical-mesh'
40
- },
41
- {
42
- name: 'consensus',
43
- short: 'c',
44
- description: 'Consensus strategy',
45
- type: 'string',
46
- choices: CONSENSUS_STRATEGIES.map(s => s.value),
47
- default: 'byzantine'
48
- },
49
- {
50
- name: 'max-agents',
51
- short: 'm',
52
- description: 'Maximum agents',
53
- type: 'number',
54
- default: 15
55
- },
56
- {
57
- name: 'persist',
58
- short: 'p',
59
- description: 'Enable persistent state',
60
- type: 'boolean',
61
- default: true
62
- },
63
- {
64
- name: 'memory-backend',
65
- description: 'Memory backend (agentdb, sqlite, hybrid)',
66
- type: 'string',
67
- default: 'hybrid'
68
- }
69
- ],
70
- examples: [
71
- { command: 'claude-flow hive-mind init -t hierarchical-mesh', description: 'Init hierarchical mesh' },
72
- { command: 'claude-flow hive-mind init -c byzantine -m 20', description: 'Init with Byzantine consensus' }
73
- ],
74
- action: async (ctx: CommandContext): Promise<CommandResult> => {
75
- let topology = ctx.flags.topology as string;
76
- let consensus = ctx.flags.consensus as string;
77
-
78
- if (ctx.interactive && !ctx.flags.topology) {
79
- topology = await select({
80
- message: 'Select hive topology:',
81
- options: TOPOLOGIES,
82
- default: 'hierarchical-mesh'
83
- });
84
- }
85
-
86
- if (ctx.interactive && !ctx.flags.consensus) {
87
- consensus = await select({
88
- message: 'Select consensus strategy:',
89
- options: CONSENSUS_STRATEGIES,
90
- default: 'byzantine'
91
- });
92
- }
93
-
94
- const config = {
95
- topology: topology || 'hierarchical-mesh',
96
- consensus: consensus || 'byzantine',
97
- maxAgents: ctx.flags.maxAgents as number || 15,
98
- persist: ctx.flags.persist as boolean,
99
- memoryBackend: ctx.flags.memoryBackend as string || 'hybrid'
100
- };
101
-
102
- output.writeln();
103
- output.writeln(output.bold('Initializing Hive Mind'));
104
-
105
- const spinner = output.createSpinner({ text: 'Setting up hive infrastructure...', spinner: 'dots' });
106
- spinner.start();
107
-
108
- try {
109
- const result = await callMCPTool<{
110
- hiveId: string;
111
- topology: string;
112
- consensus: string;
113
- queenId: string;
114
- status: 'initialized' | 'ready';
115
- config: typeof config;
116
- }>('hive-mind/init', config);
117
-
118
- spinner.succeed('Hive Mind initialized');
119
-
120
- if (ctx.flags.format === 'json') {
121
- output.printJson(result);
122
- return { success: true, data: result };
123
- }
124
-
125
- output.writeln();
126
- output.printBox(
127
- [
128
- `Hive ID: ${result.hiveId ?? 'default'}`,
129
- `Queen ID: ${result.queenId ?? 'N/A'}`,
130
- `Topology: ${result.topology ?? config.topology}`,
131
- `Consensus: ${result.consensus ?? config.consensus}`,
132
- `Max Agents: ${config.maxAgents}`,
133
- `Memory: ${config.memoryBackend}`,
134
- `Status: ${output.success(result.status ?? 'initialized')}`
135
- ].join('\n'),
136
- 'Hive Mind Configuration'
137
- );
138
-
139
- output.writeln();
140
- output.printInfo('Queen agent is ready to coordinate worker agents');
141
- output.writeln(output.dim(' Use "claude-flow hive-mind spawn" to add workers'));
142
-
143
- return { success: true, data: result };
144
- } catch (error) {
145
- spinner.fail('Failed to initialize');
146
- if (error instanceof MCPClientError) {
147
- output.printError(`Init error: ${error.message}`);
148
- } else {
149
- output.printError(`Unexpected error: ${String(error)}`);
150
- }
151
- return { success: false, exitCode: 1 };
152
- }
153
- }
154
- };
155
-
156
- // Spawn subcommand
157
- const spawnCommand: Command = {
158
- name: 'spawn',
159
- description: 'Spawn worker agents into the hive',
160
- options: [
161
- {
162
- name: 'count',
163
- short: 'n',
164
- description: 'Number of workers to spawn',
165
- type: 'number',
166
- default: 1
167
- },
168
- {
169
- name: 'type',
170
- short: 't',
171
- description: 'Agent type',
172
- type: 'string',
173
- default: 'worker'
174
- },
175
- {
176
- name: 'capabilities',
177
- short: 'c',
178
- description: 'Comma-separated capabilities',
179
- type: 'string'
180
- },
181
- {
182
- name: 'priority',
183
- short: 'p',
184
- description: 'Agent priority (low, normal, high)',
185
- type: 'string',
186
- default: 'normal'
187
- }
188
- ],
189
- examples: [
190
- { command: 'claude-flow hive-mind spawn -n 5', description: 'Spawn 5 workers' },
191
- { command: 'claude-flow hive-mind spawn -t coder -c "coding,testing"', description: 'Spawn coder with capabilities' }
192
- ],
193
- action: async (ctx: CommandContext): Promise<CommandResult> => {
194
- const count = ctx.flags.count as number;
195
- const type = ctx.flags.type as string;
196
- const capabilities = ctx.flags.capabilities ? (ctx.flags.capabilities as string).split(',') : [];
197
- const priority = ctx.flags.priority as string;
198
-
199
- output.printInfo(`Spawning ${count} ${type} agent(s)...`);
200
-
201
- try {
202
- const result = await callMCPTool<{
203
- spawned: Array<{
204
- id: string;
205
- type: string;
206
- status: string;
207
- assignedQueen: string;
208
- }>;
209
- total: number;
210
- hiveStatus: {
211
- activeAgents: number;
212
- maxAgents: number;
213
- queenLoad: string;
214
- };
215
- }>('hive-mind/spawn', {
216
- count,
217
- agentType: type,
218
- capabilities,
219
- priority,
220
- });
221
-
222
- if (ctx.flags.format === 'json') {
223
- output.printJson(result);
224
- return { success: true, data: result };
225
- }
226
-
227
- output.writeln();
228
- output.printTable({
229
- columns: [
230
- { key: 'id', header: 'Agent ID', width: 20 },
231
- { key: 'type', header: 'Type', width: 12 },
232
- { key: 'status', header: 'Status', width: 12, format: formatAgentStatus },
233
- { key: 'assignedQueen', header: 'Queen', width: 15 }
234
- ],
235
- data: result.spawned
236
- });
237
-
238
- output.writeln();
239
- output.printSuccess(`Spawned ${result.spawned.length} agent(s)`);
240
- output.writeln(output.dim(` Hive: ${result.hiveStatus.activeAgents}/${result.hiveStatus.maxAgents} agents, Queen load: ${result.hiveStatus.queenLoad}`));
241
-
242
- return { success: true, data: result };
243
- } catch (error) {
244
- if (error instanceof MCPClientError) {
245
- output.printError(`Spawn error: ${error.message}`);
246
- } else {
247
- output.printError(`Unexpected error: ${String(error)}`);
248
- }
249
- return { success: false, exitCode: 1 };
250
- }
251
- }
252
- };
253
-
254
- // Status subcommand
255
- const statusCommand: Command = {
256
- name: 'status',
257
- description: 'Show hive mind status',
258
- options: [
259
- {
260
- name: 'detailed',
261
- short: 'd',
262
- description: 'Show detailed metrics',
263
- type: 'boolean',
264
- default: false
265
- },
266
- {
267
- name: 'watch',
268
- short: 'w',
269
- description: 'Watch for changes',
270
- type: 'boolean',
271
- default: false
272
- }
273
- ],
274
- action: async (ctx: CommandContext): Promise<CommandResult> => {
275
- const detailed = ctx.flags.detailed as boolean;
276
-
277
- try {
278
- const result = await callMCPTool<{
279
- hiveId?: string;
280
- id?: string;
281
- initialized?: boolean;
282
- status?: 'active' | 'idle' | 'degraded' | 'offline' | 'running' | 'stopped';
283
- topology?: string;
284
- consensus?: string;
285
- queen?: {
286
- id?: string;
287
- agentId?: string;
288
- status?: string;
289
- load?: number;
290
- tasksQueued?: number;
291
- };
292
- workers?: Array<{
293
- id?: string;
294
- agentId?: string;
295
- type?: string;
296
- agentType?: string;
297
- status?: string;
298
- currentTask?: string;
299
- tasksCompleted?: number;
300
- } | string>;
301
- metrics?: {
302
- totalTasks?: number;
303
- completedTasks?: number;
304
- failedTasks?: number;
305
- avgTaskTime?: number;
306
- consensusRounds?: number;
307
- memoryUsage?: string;
308
- };
309
- health?: {
310
- overall?: string;
311
- queen?: string;
312
- workers?: string;
313
- consensus?: string;
314
- memory?: string;
315
- };
316
- }>('hive-mind/status', {
317
- includeMetrics: detailed,
318
- includeWorkers: true,
319
- });
320
-
321
- if (ctx.flags.format === 'json') {
322
- output.printJson(result);
323
- return { success: true, data: result };
324
- }
325
-
326
- // Handle both simple and complex response formats - cast to flexible type
327
- const flexResult = result as Record<string, unknown>;
328
- const hiveId = result.hiveId ?? (flexResult.id as string) ?? 'default';
329
- const status = result.status ?? ((flexResult.initialized as boolean) ? 'running' : 'stopped');
330
- const queen = result.queen ?? { id: 'N/A', status: 'unknown', load: 0, tasksQueued: 0 };
331
- const flexQueen = queen as Record<string, unknown>;
332
- const queenId = typeof queen === 'object' ? (queen.id ?? (flexQueen.agentId as string) ?? 'N/A') : String(queen);
333
- const queenLoad = typeof queen === 'object' ? (queen.load ?? 0) : 0;
334
- const queenTasks = typeof queen === 'object' ? (queen.tasksQueued ?? 0) : 0;
335
- const queenStatus = typeof queen === 'object' ? (queen.status ?? 'active') : 'active';
336
-
337
- output.writeln();
338
- output.printBox(
339
- [
340
- `Hive ID: ${hiveId}`,
341
- `Status: ${formatHiveStatus(String(status))}`,
342
- `Topology: ${result.topology ?? 'mesh'}`,
343
- `Consensus: ${result.consensus ?? 'byzantine'}`,
344
- '',
345
- `Queen: ${queenId}`,
346
- ` Status: ${formatAgentStatus(queenStatus)}`,
347
- ` Load: ${(queenLoad * 100).toFixed(1)}%`,
348
- ` Queued Tasks: ${queenTasks}`
349
- ].join('\n'),
350
- 'Hive Mind Status'
351
- );
352
-
353
- // Handle workers array - could be worker objects or just IDs
354
- const workers = result.workers ?? [];
355
- const workerData = Array.isArray(workers) ? workers.map(w => {
356
- if (typeof w === 'string') {
357
- return { id: w, type: 'worker', status: 'idle', currentTask: '-', tasksCompleted: 0 };
358
- }
359
- const flexWorker = w as Record<string, unknown>;
360
- return {
361
- id: w.id ?? (flexWorker.agentId as string) ?? 'unknown',
362
- type: w.type ?? (flexWorker.agentType as string) ?? 'worker',
363
- status: w.status ?? 'idle',
364
- currentTask: w.currentTask ?? '-',
365
- tasksCompleted: w.tasksCompleted ?? 0
366
- };
367
- }) : [];
368
-
369
- output.writeln();
370
- output.writeln(output.bold('Worker Agents'));
371
- if (workerData.length === 0) {
372
- output.printInfo('No workers in hive. Use "claude-flow hive-mind spawn" to add workers.');
373
- } else {
374
- output.printTable({
375
- columns: [
376
- { key: 'id', header: 'ID', width: 20 },
377
- { key: 'type', header: 'Type', width: 12 },
378
- { key: 'status', header: 'Status', width: 10, format: formatAgentStatus },
379
- { key: 'currentTask', header: 'Current Task', width: 20, format: (v: unknown) => String(v || '-') },
380
- { key: 'tasksCompleted', header: 'Completed', width: 10, align: 'right' }
381
- ],
382
- data: workerData
383
- });
384
- }
385
-
386
- if (detailed) {
387
- const metrics = result.metrics ?? { totalTasks: 0, completedTasks: 0, failedTasks: 0, avgTaskTime: 0, consensusRounds: 0, memoryUsage: '0 MB' };
388
- output.writeln();
389
- output.writeln(output.bold('Metrics'));
390
- output.printTable({
391
- columns: [
392
- { key: 'metric', header: 'Metric', width: 20 },
393
- { key: 'value', header: 'Value', width: 15, align: 'right' }
394
- ],
395
- data: [
396
- { metric: 'Total Tasks', value: metrics.totalTasks ?? 0 },
397
- { metric: 'Completed', value: metrics.completedTasks ?? 0 },
398
- { metric: 'Failed', value: metrics.failedTasks ?? 0 },
399
- { metric: 'Avg Task Time', value: `${(metrics.avgTaskTime ?? 0).toFixed(1)}ms` },
400
- { metric: 'Consensus Rounds', value: metrics.consensusRounds ?? 0 },
401
- { metric: 'Memory Usage', value: metrics.memoryUsage ?? '0 MB' }
402
- ]
403
- });
404
-
405
- const health = result.health ?? { overall: 'healthy', queen: 'healthy', workers: 'healthy', consensus: 'healthy', memory: 'healthy' };
406
- output.writeln();
407
- output.writeln(output.bold('Health'));
408
- output.printList([
409
- `Overall: ${formatHealth(health.overall ?? 'healthy')}`,
410
- `Queen: ${formatHealth(health.queen ?? 'healthy')}`,
411
- `Workers: ${formatHealth(health.workers ?? 'healthy')}`,
412
- `Consensus: ${formatHealth(health.consensus ?? 'healthy')}`,
413
- `Memory: ${formatHealth(health.memory ?? 'healthy')}`
414
- ]);
415
- }
416
-
417
- return { success: true, data: result };
418
- } catch (error) {
419
- if (error instanceof MCPClientError) {
420
- output.printError(`Status error: ${error.message}`);
421
- } else {
422
- output.printError(`Unexpected error: ${String(error)}`);
423
- }
424
- return { success: false, exitCode: 1 };
425
- }
426
- }
427
- };
428
-
429
- // Task subcommand
430
- const taskCommand: Command = {
431
- name: 'task',
432
- description: 'Submit tasks to the hive',
433
- options: [
434
- {
435
- name: 'description',
436
- short: 'd',
437
- description: 'Task description',
438
- type: 'string'
439
- },
440
- {
441
- name: 'priority',
442
- short: 'p',
443
- description: 'Task priority',
444
- type: 'string',
445
- choices: ['low', 'normal', 'high', 'critical'],
446
- default: 'normal'
447
- },
448
- {
449
- name: 'require-consensus',
450
- short: 'c',
451
- description: 'Require consensus for completion',
452
- type: 'boolean',
453
- default: false
454
- },
455
- {
456
- name: 'timeout',
457
- description: 'Task timeout in seconds',
458
- type: 'number',
459
- default: 300
460
- }
461
- ],
462
- examples: [
463
- { command: 'claude-flow hive-mind task -d "Implement auth module"', description: 'Submit task' },
464
- { command: 'claude-flow hive-mind task -d "Security review" -p critical -c', description: 'Critical task with consensus' }
465
- ],
466
- action: async (ctx: CommandContext): Promise<CommandResult> => {
467
- let description = ctx.flags.description as string || ctx.args.join(' ');
468
-
469
- if (!description && ctx.interactive) {
470
- description = await input({
471
- message: 'Task description:',
472
- validate: (v) => v.length > 0 || 'Description is required'
473
- });
474
- }
475
-
476
- if (!description) {
477
- output.printError('Task description is required');
478
- return { success: false, exitCode: 1 };
479
- }
480
-
481
- const priority = ctx.flags.priority as string;
482
- const requireConsensus = ctx.flags.requireConsensus as boolean;
483
- const timeout = ctx.flags.timeout as number;
484
-
485
- output.printInfo('Submitting task to hive...');
486
-
487
- try {
488
- const result = await callMCPTool<{
489
- taskId: string;
490
- description: string;
491
- status: string;
492
- assignedTo: string[];
493
- priority: string;
494
- requiresConsensus: boolean;
495
- estimatedTime: string;
496
- }>('hive-mind/task', {
497
- description,
498
- priority,
499
- requireConsensus,
500
- timeout,
501
- });
502
-
503
- if (ctx.flags.format === 'json') {
504
- output.printJson(result);
505
- return { success: true, data: result };
506
- }
507
-
508
- output.writeln();
509
- output.printBox(
510
- [
511
- `Task ID: ${result.taskId}`,
512
- `Status: ${formatAgentStatus(result.status)}`,
513
- `Priority: ${formatPriority(priority)}`,
514
- `Assigned: ${result.assignedTo.join(', ')}`,
515
- `Consensus: ${result.requiresConsensus ? 'Yes' : 'No'}`,
516
- `Est. Time: ${result.estimatedTime}`
517
- ].join('\n'),
518
- 'Task Submitted'
519
- );
520
-
521
- output.writeln();
522
- output.printSuccess('Task submitted to hive');
523
- output.writeln(output.dim(` Track with: claude-flow hive-mind task-status ${result.taskId}`));
524
-
525
- return { success: true, data: result };
526
- } catch (error) {
527
- if (error instanceof MCPClientError) {
528
- output.printError(`Task submission error: ${error.message}`);
529
- } else {
530
- output.printError(`Unexpected error: ${String(error)}`);
531
- }
532
- return { success: false, exitCode: 1 };
533
- }
534
- }
535
- };
536
-
537
- // Optimize memory subcommand
538
- const optimizeMemoryCommand: Command = {
539
- name: 'optimize-memory',
540
- description: 'Optimize hive memory and patterns',
541
- options: [
542
- {
543
- name: 'aggressive',
544
- short: 'a',
545
- description: 'Aggressive optimization',
546
- type: 'boolean',
547
- default: false
548
- },
549
- {
550
- name: 'threshold',
551
- description: 'Quality threshold for pattern retention',
552
- type: 'number',
553
- default: 0.7
554
- }
555
- ],
556
- action: async (ctx: CommandContext): Promise<CommandResult> => {
557
- const aggressive = ctx.flags.aggressive as boolean;
558
- const threshold = ctx.flags.threshold as number;
559
-
560
- output.printInfo('Optimizing hive memory...');
561
-
562
- const spinner = output.createSpinner({ text: 'Analyzing patterns...', spinner: 'dots' });
563
- spinner.start();
564
-
565
- try {
566
- const result = await callMCPTool<{
567
- optimized: boolean;
568
- before: { patterns: number; memory: string };
569
- after: { patterns: number; memory: string };
570
- removed: number;
571
- consolidated: number;
572
- timeMs: number;
573
- }>('hive-mind/optimize-memory', {
574
- aggressive,
575
- qualityThreshold: threshold,
576
- });
577
-
578
- spinner.succeed('Memory optimized');
579
-
580
- if (ctx.flags.format === 'json') {
581
- output.printJson(result);
582
- return { success: true, data: result };
583
- }
584
-
585
- output.writeln();
586
- output.printTable({
587
- columns: [
588
- { key: 'metric', header: 'Metric', width: 20 },
589
- { key: 'before', header: 'Before', width: 15, align: 'right' },
590
- { key: 'after', header: 'After', width: 15, align: 'right' }
591
- ],
592
- data: [
593
- { metric: 'Patterns', before: result.before.patterns, after: result.after.patterns },
594
- { metric: 'Memory', before: result.before.memory, after: result.after.memory }
595
- ]
596
- });
597
-
598
- output.writeln();
599
- output.printList([
600
- `Patterns removed: ${result.removed}`,
601
- `Patterns consolidated: ${result.consolidated}`,
602
- `Optimization time: ${result.timeMs}ms`
603
- ]);
604
-
605
- return { success: true, data: result };
606
- } catch (error) {
607
- spinner.fail('Optimization failed');
608
- if (error instanceof MCPClientError) {
609
- output.printError(`Optimization error: ${error.message}`);
610
- } else {
611
- output.printError(`Unexpected error: ${String(error)}`);
612
- }
613
- return { success: false, exitCode: 1 };
614
- }
615
- }
616
- };
617
-
618
- // Join subcommand
619
- const joinCommand: Command = {
620
- name: 'join',
621
- description: 'Join an agent to the hive mind',
622
- options: [
623
- { name: 'agent-id', short: 'a', description: 'Agent ID to join', type: 'string' },
624
- { name: 'role', short: 'r', description: 'Agent role (worker, specialist, scout)', type: 'string', default: 'worker' }
625
- ],
626
- action: async (ctx: CommandContext): Promise<CommandResult> => {
627
- const agentId = ctx.args[0] || ctx.flags['agent-id'] as string || ctx.flags.agentId as string;
628
- if (!agentId) {
629
- output.printError('Agent ID is required. Use --agent-id or -a flag, or provide as argument.');
630
- return { success: false, exitCode: 1 };
631
- }
632
- try {
633
- const result = await callMCPTool<{ success: boolean; agentId: string; totalWorkers: number; error?: string }>('hive-mind/join', { agentId, role: ctx.flags.role });
634
- if (!result.success) { output.printError(result.error || 'Failed'); return { success: false, exitCode: 1 }; }
635
- output.printSuccess(`Agent ${agentId} joined hive (${result.totalWorkers} workers)`);
636
- return { success: true, data: result };
637
- } catch (error) { output.printError(`Join error: ${error instanceof MCPClientError ? error.message : String(error)}`); return { success: false, exitCode: 1 }; }
638
- }
639
- };
640
-
641
- // Leave subcommand
642
- const leaveCommand: Command = {
643
- name: 'leave',
644
- description: 'Remove an agent from the hive mind',
645
- options: [{ name: 'agent-id', short: 'a', description: 'Agent ID to remove', type: 'string' }],
646
- action: async (ctx: CommandContext): Promise<CommandResult> => {
647
- const agentId = ctx.args[0] || ctx.flags['agent-id'] as string || ctx.flags.agentId as string;
648
- if (!agentId) { output.printError('Agent ID required.'); return { success: false, exitCode: 1 }; }
649
- try {
650
- const result = await callMCPTool<{ success: boolean; agentId: string; remainingWorkers: number; error?: string }>('hive-mind/leave', { agentId });
651
- if (!result.success) { output.printError(result.error || 'Failed'); return { success: false, exitCode: 1 }; }
652
- output.printSuccess(`Agent ${agentId} left hive (${result.remainingWorkers} remaining)`);
653
- return { success: true, data: result };
654
- } catch (error) { output.printError(`Leave error: ${error instanceof MCPClientError ? error.message : String(error)}`); return { success: false, exitCode: 1 }; }
655
- }
656
- };
657
-
658
- // Consensus subcommand
659
- const consensusCommand: Command = {
660
- name: 'consensus',
661
- description: 'Manage consensus proposals and voting',
662
- options: [
663
- { name: 'action', short: 'a', description: 'Consensus action', type: 'string', choices: ['propose', 'vote', 'status', 'list'], default: 'list' },
664
- { name: 'proposal-id', short: 'p', description: 'Proposal ID', type: 'string' },
665
- { name: 'type', short: 't', description: 'Proposal type', type: 'string' },
666
- { name: 'value', description: 'Proposal value', type: 'string' },
667
- { name: 'vote', short: 'v', description: 'Vote (yes/no)', type: 'string' },
668
- { name: 'voter-id', description: 'Voter agent ID', type: 'string' }
669
- ],
670
- action: async (ctx: CommandContext): Promise<CommandResult> => {
671
- const action = ctx.flags.action as string || 'list';
672
- try {
673
- const result = await callMCPTool<Record<string, unknown>>('hive-mind/consensus', { action, proposalId: ctx.flags.proposalId, type: ctx.flags.type, value: ctx.flags.value, vote: ctx.flags.vote === 'yes', voterId: ctx.flags.voterId });
674
- if (ctx.flags.format === 'json') { output.printJson(result); return { success: true, data: result }; }
675
- if (action === 'list') {
676
- output.writeln(output.bold('\nPending Proposals'));
677
- const pending = (result.pending as Array<Record<string, unknown>>) || [];
678
- if (pending.length === 0) output.printInfo('No pending proposals');
679
- else output.printTable({ columns: [{ key: 'proposalId', header: 'ID', width: 30 }, { key: 'type', header: 'Type', width: 12 }], data: pending });
680
- } else if (action === 'propose') { output.printSuccess(`Proposal created: ${result.proposalId}`); }
681
- else if (action === 'vote') { output.printSuccess(`Vote recorded (For: ${result.votesFor}, Against: ${result.votesAgainst})`); }
682
- return { success: true, data: result };
683
- } catch (error) { output.printError(`Consensus error: ${error instanceof MCPClientError ? error.message : String(error)}`); return { success: false, exitCode: 1 }; }
684
- }
685
- };
686
-
687
- // Broadcast subcommand
688
- const broadcastCommand: Command = {
689
- name: 'broadcast',
690
- description: 'Broadcast a message to all workers in the hive',
691
- options: [
692
- { name: 'message', short: 'm', description: 'Message to broadcast', type: 'string', required: true },
693
- { name: 'priority', short: 'p', description: 'Message priority', type: 'string', choices: ['low', 'normal', 'high', 'critical'], default: 'normal' },
694
- { name: 'from', short: 'f', description: 'Sender agent ID', type: 'string' }
695
- ],
696
- action: async (ctx: CommandContext): Promise<CommandResult> => {
697
- const message = ctx.args.join(' ') || ctx.flags.message as string;
698
- if (!message) { output.printError('Message required. Use --message or -m flag.'); return { success: false, exitCode: 1 }; }
699
- try {
700
- const result = await callMCPTool<{ success: boolean; messageId: string; recipients: number; error?: string }>('hive-mind/broadcast', { message, priority: ctx.flags.priority, fromId: ctx.flags.from });
701
- if (!result.success) { output.printError(result.error || 'Failed'); return { success: false, exitCode: 1 }; }
702
- output.printSuccess(`Message broadcast to ${result.recipients} workers (ID: ${result.messageId})`);
703
- return { success: true, data: result };
704
- } catch (error) { output.printError(`Broadcast error: ${error instanceof MCPClientError ? error.message : String(error)}`); return { success: false, exitCode: 1 }; }
705
- }
706
- };
707
-
708
- // Memory subcommand
709
- const memorySubCommand: Command = {
710
- name: 'memory',
711
- description: 'Access hive shared memory',
712
- options: [
713
- { name: 'action', short: 'a', description: 'Memory action', type: 'string', choices: ['get', 'set', 'delete', 'list'], default: 'list' },
714
- { name: 'key', short: 'k', description: 'Memory key', type: 'string' },
715
- { name: 'value', short: 'v', description: 'Value to store', type: 'string' }
716
- ],
717
- action: async (ctx: CommandContext): Promise<CommandResult> => {
718
- const action = ctx.flags.action as string || 'list';
719
- const key = ctx.flags.key as string;
720
- const value = ctx.flags.value as string;
721
- if ((action === 'get' || action === 'delete') && !key) { output.printError('Key required for get/delete.'); return { success: false, exitCode: 1 }; }
722
- if (action === 'set' && (!key || value === undefined)) { output.printError('Key and value required for set.'); return { success: false, exitCode: 1 }; }
723
- try {
724
- const result = await callMCPTool<Record<string, unknown>>('hive-mind/memory', { action, key, value });
725
- if (ctx.flags.format === 'json') { output.printJson(result); return { success: true, data: result }; }
726
- if (action === 'list') {
727
- const keys = (result.keys as string[]) || [];
728
- output.writeln(output.bold(`\nShared Memory (${result.count} keys)`));
729
- if (keys.length === 0) output.printInfo('No keys in shared memory');
730
- else output.printList(keys.map(k => output.highlight(k)));
731
- } else if (action === 'get') {
732
- output.writeln(output.bold(`\nKey: ${key}`));
733
- output.writeln(result.exists ? `Value: ${JSON.stringify(result.value, null, 2)}` : 'Key not found');
734
- } else if (action === 'set') { output.printSuccess(`Set ${key} in shared memory`); }
735
- else if (action === 'delete') { output.printSuccess(result.deleted ? `Deleted ${key}` : `Key ${key} did not exist`); }
736
- return { success: true, data: result };
737
- } catch (error) { output.printError(`Memory error: ${error instanceof MCPClientError ? error.message : String(error)}`); return { success: false, exitCode: 1 }; }
738
- }
739
- };
740
-
741
- // Shutdown subcommand
742
- const shutdownCommand: Command = {
743
- name: 'shutdown',
744
- description: 'Shutdown the hive mind',
745
- options: [
746
- {
747
- name: 'force',
748
- short: 'f',
749
- description: 'Force shutdown',
750
- type: 'boolean',
751
- default: false
752
- },
753
- {
754
- name: 'save-state',
755
- short: 's',
756
- description: 'Save state before shutdown',
757
- type: 'boolean',
758
- default: true
759
- }
760
- ],
761
- action: async (ctx: CommandContext): Promise<CommandResult> => {
762
- const force = ctx.flags.force as boolean;
763
- const saveState = ctx.flags.saveState as boolean;
764
-
765
- if (!force && ctx.interactive) {
766
- const confirmed = await confirm({
767
- message: 'Shutdown the hive mind? All agents will be terminated.',
768
- default: false
769
- });
770
-
771
- if (!confirmed) {
772
- output.printInfo('Operation cancelled');
773
- return { success: true };
774
- }
775
- }
776
-
777
- output.printInfo('Shutting down hive mind...');
778
-
779
- const spinner = output.createSpinner({ text: 'Graceful shutdown in progress...', spinner: 'dots' });
780
- spinner.start();
781
-
782
- try {
783
- const result = await callMCPTool<{
784
- shutdown: boolean;
785
- agentsTerminated: number;
786
- stateSaved: boolean;
787
- shutdownTime: string;
788
- }>('hive-mind/shutdown', {
789
- force,
790
- saveState,
791
- });
792
-
793
- spinner.succeed('Hive mind shutdown complete');
794
-
795
- output.writeln();
796
- output.printList([
797
- `Agents terminated: ${result.agentsTerminated}`,
798
- `State saved: ${result.stateSaved ? 'Yes' : 'No'}`,
799
- `Shutdown time: ${result.shutdownTime}`
800
- ]);
801
-
802
- return { success: true, data: result };
803
- } catch (error) {
804
- spinner.fail('Shutdown failed');
805
- if (error instanceof MCPClientError) {
806
- output.printError(`Shutdown error: ${error.message}`);
807
- } else {
808
- output.printError(`Unexpected error: ${String(error)}`);
809
- }
810
- return { success: false, exitCode: 1 };
811
- }
812
- }
813
- };
814
-
815
- // Main hive-mind command
816
- export const hiveMindCommand: Command = {
817
- name: 'hive-mind',
818
- aliases: ['hive'],
819
- description: 'Queen-led consensus-based multi-agent coordination',
820
- subcommands: [initCommand, spawnCommand, statusCommand, taskCommand, joinCommand, leaveCommand, consensusCommand, broadcastCommand, memorySubCommand, optimizeMemoryCommand, shutdownCommand],
821
- options: [],
822
- examples: [
823
- { command: 'claude-flow hive-mind init -t hierarchical-mesh', description: 'Initialize hive' },
824
- { command: 'claude-flow hive-mind spawn -n 5', description: 'Spawn workers' },
825
- { command: 'claude-flow hive-mind task -d "Build feature"', description: 'Submit task' }
826
- ],
827
- action: async (): Promise<CommandResult> => {
828
- output.writeln();
829
- output.writeln(output.bold('Hive Mind - Consensus-Based Multi-Agent Coordination'));
830
- output.writeln();
831
- output.writeln('Usage: claude-flow hive-mind <subcommand> [options]');
832
- output.writeln();
833
- output.writeln('Subcommands:');
834
- output.printList([
835
- `${output.highlight('init')} - Initialize hive mind`,
836
- `${output.highlight('spawn')} - Spawn worker agents`,
837
- `${output.highlight('status')} - Show hive status`,
838
- `${output.highlight('task')} - Submit task to hive`,
839
- `${output.highlight('join')} - Join an agent to the hive`,
840
- `${output.highlight('leave')} - Remove an agent from the hive`,
841
- `${output.highlight('consensus')} - Manage consensus proposals`,
842
- `${output.highlight('broadcast')} - Broadcast message to workers`,
843
- `${output.highlight('memory')} - Access shared memory`,
844
- `${output.highlight('optimize-memory')} - Optimize patterns and memory`,
845
- `${output.highlight('shutdown')} - Shutdown the hive`
846
- ]);
847
- output.writeln();
848
- output.writeln('Features:');
849
- output.printList([
850
- 'Queen-led hierarchical coordination',
851
- 'Byzantine fault tolerant consensus',
852
- 'HNSW-accelerated pattern matching',
853
- 'Cross-session memory persistence',
854
- 'Automatic load balancing'
855
- ]);
856
-
857
- return { success: true };
858
- }
859
- };
860
-
861
- // Helper functions
862
- function formatAgentStatus(status: unknown): string {
863
- const statusStr = String(status);
864
- switch (statusStr) {
865
- case 'active':
866
- case 'ready':
867
- case 'running':
868
- return output.success(statusStr);
869
- case 'idle':
870
- case 'waiting':
871
- return output.dim(statusStr);
872
- case 'busy':
873
- return output.highlight(statusStr);
874
- case 'error':
875
- case 'failed':
876
- return output.error(statusStr);
877
- default:
878
- return statusStr;
879
- }
880
- }
881
-
882
- function formatHiveStatus(status: string): string {
883
- switch (status) {
884
- case 'active':
885
- return output.success(status);
886
- case 'idle':
887
- return output.dim(status);
888
- case 'degraded':
889
- return output.warning(status);
890
- case 'offline':
891
- return output.error(status);
892
- default:
893
- return status;
894
- }
895
- }
896
-
897
- function formatHealth(health: string): string {
898
- switch (health) {
899
- case 'healthy':
900
- case 'good':
901
- return output.success(health);
902
- case 'warning':
903
- case 'degraded':
904
- return output.warning(health);
905
- case 'critical':
906
- case 'unhealthy':
907
- return output.error(health);
908
- default:
909
- return health;
910
- }
911
- }
912
-
913
- function formatPriority(priority: string): string {
914
- switch (priority) {
915
- case 'critical':
916
- return output.error(priority.toUpperCase());
917
- case 'high':
918
- return output.warning(priority);
919
- case 'normal':
920
- return priority;
921
- case 'low':
922
- return output.dim(priority);
923
- default:
924
- return priority;
925
- }
926
- }
927
-
928
- export default hiveMindCommand;