diff --git a/.claude/helpers/learning-service.mjs b/.claude/helpers/learning-service.mjs index f8653366a3..df311ad82e 100755 --- a/.claude/helpers/learning-service.mjs +++ b/.claude/helpers/learning-service.mjs @@ -206,7 +206,7 @@ class HNSWIndex { ? queryEmbedding : new Float32Array(queryEmbedding); - if (this.vectors.size === 0) return []; + if (this.vectors.size === 0) return { results: [], searchTimeMs: 0 }; const startTime = performance.now(); diff --git a/v3/@claude-flow/cli/src/commands/hive-mind.ts b/v3/@claude-flow/cli/src/commands/hive-mind.ts new file mode 100644 index 0000000000..aa4924b818 --- /dev/null +++ b/v3/@claude-flow/cli/src/commands/hive-mind.ts @@ -0,0 +1,762 @@ +/** + * V3 CLI Hive Mind Command + * Queen-led consensus-based multi-agent coordination + */ + +import type { Command, CommandContext, CommandResult } from '../types.js'; +import { output } from '../output.js'; +import { select, confirm, input } from '../prompt.js'; +import { callMCPTool, MCPClientError } from '../mcp-client.js'; + +// Hive topologies +const TOPOLOGIES = [ + { value: 'hierarchical', label: 'Hierarchical', hint: 'Queen-led with worker agents' }, + { value: 'mesh', label: 'Mesh', hint: 'Peer-to-peer coordination' }, + { value: 'hierarchical-mesh', label: 'Hierarchical Mesh', hint: 'Queen + peer communication (recommended)' }, + { value: 'adaptive', label: 'Adaptive', hint: 'Dynamic topology based on task' } +]; + +// Consensus strategies +const CONSENSUS_STRATEGIES = [ + { value: 'byzantine', label: 'Byzantine Fault Tolerant', hint: '2/3 majority, handles malicious actors' }, + { value: 'raft', label: 'Raft', hint: 'Leader-based consensus' }, + { value: 'gossip', label: 'Gossip', hint: 'Eventually consistent, scalable' }, + { value: 'crdt', label: 'CRDT', hint: 'Conflict-free replicated data' }, + { value: 'quorum', label: 'Quorum', hint: 'Simple majority voting' } +]; + +// Init subcommand +const initCommand: Command = { + name: 'init', + description: 'Initialize a hive mind', + options: [ + { + name: 'topology', + short: 't', + description: 'Hive topology', + type: 'string', + choices: TOPOLOGIES.map(t => t.value), + default: 'hierarchical-mesh' + }, + { + name: 'consensus', + short: 'c', + description: 'Consensus strategy', + type: 'string', + choices: CONSENSUS_STRATEGIES.map(s => s.value), + default: 'byzantine' + }, + { + name: 'max-agents', + short: 'm', + description: 'Maximum agents', + type: 'number', + default: 15 + }, + { + name: 'persist', + short: 'p', + description: 'Enable persistent state', + type: 'boolean', + default: true + }, + { + name: 'memory-backend', + description: 'Memory backend (agentdb, sqlite, hybrid)', + type: 'string', + default: 'hybrid' + } + ], + examples: [ + { command: 'claude-flow hive-mind init -t hierarchical-mesh', description: 'Init hierarchical mesh' }, + { command: 'claude-flow hive-mind init -c byzantine -m 20', description: 'Init with Byzantine consensus' } + ], + action: async (ctx: CommandContext): Promise => { + let topology = ctx.flags.topology as string; + let consensus = ctx.flags.consensus as string; + + if (ctx.interactive && !ctx.flags.topology) { + topology = await select({ + message: 'Select hive topology:', + options: TOPOLOGIES, + default: 'hierarchical-mesh' + }); + } + + if (ctx.interactive && !ctx.flags.consensus) { + consensus = await select({ + message: 'Select consensus strategy:', + options: CONSENSUS_STRATEGIES, + default: 'byzantine' + }); + } + + const config = { + topology: topology || 'hierarchical-mesh', + consensus: consensus || 'byzantine', + maxAgents: ctx.flags.maxAgents as number || 15, + persist: ctx.flags.persist as boolean, + memoryBackend: ctx.flags.memoryBackend as string || 'hybrid' + }; + + output.writeln(); + output.writeln(output.bold('Initializing Hive Mind')); + + const spinner = output.createSpinner({ text: 'Setting up hive infrastructure...', spinner: 'dots' }); + spinner.start(); + + try { + const result = await callMCPTool<{ + hiveId: string; + topology: string; + consensus: string; + queenId: string; + status: 'initialized' | 'ready'; + config: typeof config; + }>('hive-mind/init', config); + + spinner.succeed('Hive Mind initialized'); + + if (ctx.flags.format === 'json') { + output.printJson(result); + return { success: true, data: result }; + } + + output.writeln(); + output.printBox( + [ + `Hive ID: ${result.hiveId}`, + `Queen ID: ${result.queenId}`, + `Topology: ${result.topology}`, + `Consensus: ${result.consensus}`, + `Max Agents: ${config.maxAgents}`, + `Memory: ${config.memoryBackend}`, + `Status: ${output.success(result.status)}` + ].join('\n'), + 'Hive Mind Configuration' + ); + + output.writeln(); + output.printInfo('Queen agent is ready to coordinate worker agents'); + output.writeln(output.dim(' Use "claude-flow hive-mind spawn" to add workers')); + + return { success: true, data: result }; + } catch (error) { + spinner.fail('Failed to initialize'); + if (error instanceof MCPClientError) { + output.printError(`Init error: ${error.message}`); + } else { + output.printError(`Unexpected error: ${String(error)}`); + } + return { success: false, exitCode: 1 }; + } + } +}; + +// Spawn subcommand +const spawnCommand: Command = { + name: 'spawn', + description: 'Spawn worker agents into the hive', + options: [ + { + name: 'count', + short: 'n', + description: 'Number of workers to spawn', + type: 'number', + default: 1 + }, + { + name: 'type', + short: 't', + description: 'Agent type', + type: 'string', + default: 'worker' + }, + { + name: 'capabilities', + short: 'c', + description: 'Comma-separated capabilities', + type: 'string' + }, + { + name: 'priority', + short: 'p', + description: 'Agent priority (low, normal, high)', + type: 'string', + default: 'normal' + } + ], + examples: [ + { command: 'claude-flow hive-mind spawn -n 5', description: 'Spawn 5 workers' }, + { command: 'claude-flow hive-mind spawn -t coder -c "coding,testing"', description: 'Spawn coder with capabilities' } + ], + action: async (ctx: CommandContext): Promise => { + const count = ctx.flags.count as number; + const type = ctx.flags.type as string; + const capabilities = ctx.flags.capabilities ? (ctx.flags.capabilities as string).split(',') : []; + const priority = ctx.flags.priority as string; + + output.printInfo(`Spawning ${count} ${type} agent(s)...`); + + try { + const result = await callMCPTool<{ + spawned: Array<{ + id: string; + type: string; + status: string; + assignedQueen: string; + }>; + total: number; + hiveStatus: { + activeAgents: number; + maxAgents: number; + queenLoad: string; + }; + }>('hive-mind/spawn', { + count, + agentType: type, + capabilities, + priority, + }); + + if (ctx.flags.format === 'json') { + output.printJson(result); + return { success: true, data: result }; + } + + output.writeln(); + output.printTable({ + columns: [ + { key: 'id', header: 'Agent ID', width: 20 }, + { key: 'type', header: 'Type', width: 12 }, + { key: 'status', header: 'Status', width: 12, format: formatAgentStatus }, + { key: 'assignedQueen', header: 'Queen', width: 15 } + ], + data: result.spawned + }); + + output.writeln(); + output.printSuccess(`Spawned ${result.spawned.length} agent(s)`); + output.writeln(output.dim(` Hive: ${result.hiveStatus.activeAgents}/${result.hiveStatus.maxAgents} agents, Queen load: ${result.hiveStatus.queenLoad}`)); + + return { success: true, data: result }; + } catch (error) { + if (error instanceof MCPClientError) { + output.printError(`Spawn error: ${error.message}`); + } else { + output.printError(`Unexpected error: ${String(error)}`); + } + return { success: false, exitCode: 1 }; + } + } +}; + +// Status subcommand +const statusCommand: Command = { + name: 'status', + description: 'Show hive mind status', + options: [ + { + name: 'detailed', + short: 'd', + description: 'Show detailed metrics', + type: 'boolean', + default: false + }, + { + name: 'watch', + short: 'w', + description: 'Watch for changes', + type: 'boolean', + default: false + } + ], + action: async (ctx: CommandContext): Promise => { + const detailed = ctx.flags.detailed as boolean; + + try { + const result = await callMCPTool<{ + hiveId: string; + status: 'active' | 'idle' | 'degraded' | 'offline'; + topology: string; + consensus: string; + queen: { + id: string; + status: string; + load: number; + tasksQueued: number; + }; + workers: Array<{ + id: string; + type: string; + status: string; + currentTask?: string; + tasksCompleted: number; + }>; + metrics: { + totalTasks: number; + completedTasks: number; + failedTasks: number; + avgTaskTime: number; + consensusRounds: number; + memoryUsage: string; + }; + health: { + overall: string; + queen: string; + workers: string; + consensus: string; + memory: string; + }; + }>('hive-mind/status', { + includeMetrics: detailed, + includeWorkers: true, + }); + + if (ctx.flags.format === 'json') { + output.printJson(result); + return { success: true, data: result }; + } + + output.writeln(); + output.printBox( + [ + `Hive ID: ${result.hiveId}`, + `Status: ${formatHiveStatus(result.status)}`, + `Topology: ${result.topology}`, + `Consensus: ${result.consensus}`, + '', + `Queen: ${result.queen.id}`, + ` Status: ${formatAgentStatus(result.queen.status)}`, + ` Load: ${(result.queen.load * 100).toFixed(1)}%`, + ` Queued Tasks: ${result.queen.tasksQueued}` + ].join('\n'), + 'Hive Mind Status' + ); + + output.writeln(); + output.writeln(output.bold('Worker Agents')); + output.printTable({ + columns: [ + { key: 'id', header: 'ID', width: 20 }, + { key: 'type', header: 'Type', width: 12 }, + { key: 'status', header: 'Status', width: 10, format: formatAgentStatus }, + { key: 'currentTask', header: 'Current Task', width: 20, format: (v) => v || '-' }, + { key: 'tasksCompleted', header: 'Completed', width: 10, align: 'right' } + ], + data: result.workers + }); + + if (detailed) { + output.writeln(); + output.writeln(output.bold('Metrics')); + output.printTable({ + columns: [ + { key: 'metric', header: 'Metric', width: 20 }, + { key: 'value', header: 'Value', width: 15, align: 'right' } + ], + data: [ + { metric: 'Total Tasks', value: result.metrics.totalTasks }, + { metric: 'Completed', value: result.metrics.completedTasks }, + { metric: 'Failed', value: result.metrics.failedTasks }, + { metric: 'Avg Task Time', value: `${result.metrics.avgTaskTime.toFixed(1)}ms` }, + { metric: 'Consensus Rounds', value: result.metrics.consensusRounds }, + { metric: 'Memory Usage', value: result.metrics.memoryUsage } + ] + }); + + output.writeln(); + output.writeln(output.bold('Health')); + output.printList([ + `Overall: ${formatHealth(result.health.overall)}`, + `Queen: ${formatHealth(result.health.queen)}`, + `Workers: ${formatHealth(result.health.workers)}`, + `Consensus: ${formatHealth(result.health.consensus)}`, + `Memory: ${formatHealth(result.health.memory)}` + ]); + } + + return { success: true, data: result }; + } catch (error) { + if (error instanceof MCPClientError) { + output.printError(`Status error: ${error.message}`); + } else { + output.printError(`Unexpected error: ${String(error)}`); + } + return { success: false, exitCode: 1 }; + } + } +}; + +// Task subcommand +const taskCommand: Command = { + name: 'task', + description: 'Submit tasks to the hive', + options: [ + { + name: 'description', + short: 'd', + description: 'Task description', + type: 'string' + }, + { + name: 'priority', + short: 'p', + description: 'Task priority', + type: 'string', + choices: ['low', 'normal', 'high', 'critical'], + default: 'normal' + }, + { + name: 'require-consensus', + short: 'c', + description: 'Require consensus for completion', + type: 'boolean', + default: false + }, + { + name: 'timeout', + description: 'Task timeout in seconds', + type: 'number', + default: 300 + } + ], + examples: [ + { command: 'claude-flow hive-mind task -d "Implement auth module"', description: 'Submit task' }, + { command: 'claude-flow hive-mind task -d "Security review" -p critical -c', description: 'Critical task with consensus' } + ], + action: async (ctx: CommandContext): Promise => { + let description = ctx.flags.description as string || ctx.args.join(' '); + + if (!description && ctx.interactive) { + description = await input({ + message: 'Task description:', + validate: (v) => v.length > 0 || 'Description is required' + }); + } + + if (!description) { + output.printError('Task description is required'); + return { success: false, exitCode: 1 }; + } + + const priority = ctx.flags.priority as string; + const requireConsensus = ctx.flags.requireConsensus as boolean; + const timeout = ctx.flags.timeout as number; + + output.printInfo('Submitting task to hive...'); + + try { + const result = await callMCPTool<{ + taskId: string; + description: string; + status: string; + assignedTo: string[]; + priority: string; + requiresConsensus: boolean; + estimatedTime: string; + }>('hive-mind/task', { + description, + priority, + requireConsensus, + timeout, + }); + + if (ctx.flags.format === 'json') { + output.printJson(result); + return { success: true, data: result }; + } + + output.writeln(); + output.printBox( + [ + `Task ID: ${result.taskId}`, + `Status: ${formatAgentStatus(result.status)}`, + `Priority: ${formatPriority(priority)}`, + `Assigned: ${result.assignedTo.join(', ')}`, + `Consensus: ${result.requiresConsensus ? 'Yes' : 'No'}`, + `Est. Time: ${result.estimatedTime}` + ].join('\n'), + 'Task Submitted' + ); + + output.writeln(); + output.printSuccess('Task submitted to hive'); + output.writeln(output.dim(` Track with: claude-flow hive-mind task-status ${result.taskId}`)); + + return { success: true, data: result }; + } catch (error) { + if (error instanceof MCPClientError) { + output.printError(`Task submission error: ${error.message}`); + } else { + output.printError(`Unexpected error: ${String(error)}`); + } + return { success: false, exitCode: 1 }; + } + } +}; + +// Optimize memory subcommand +const optimizeMemoryCommand: Command = { + name: 'optimize-memory', + description: 'Optimize hive memory and patterns', + options: [ + { + name: 'aggressive', + short: 'a', + description: 'Aggressive optimization', + type: 'boolean', + default: false + }, + { + name: 'threshold', + description: 'Quality threshold for pattern retention', + type: 'number', + default: 0.7 + } + ], + action: async (ctx: CommandContext): Promise => { + const aggressive = ctx.flags.aggressive as boolean; + const threshold = ctx.flags.threshold as number; + + output.printInfo('Optimizing hive memory...'); + + const spinner = output.createSpinner({ text: 'Analyzing patterns...', spinner: 'dots' }); + spinner.start(); + + try { + const result = await callMCPTool<{ + optimized: boolean; + before: { patterns: number; memory: string }; + after: { patterns: number; memory: string }; + removed: number; + consolidated: number; + timeMs: number; + }>('hive-mind/optimize-memory', { + aggressive, + qualityThreshold: threshold, + }); + + spinner.succeed('Memory optimized'); + + if (ctx.flags.format === 'json') { + output.printJson(result); + return { success: true, data: result }; + } + + output.writeln(); + output.printTable({ + columns: [ + { key: 'metric', header: 'Metric', width: 20 }, + { key: 'before', header: 'Before', width: 15, align: 'right' }, + { key: 'after', header: 'After', width: 15, align: 'right' } + ], + data: [ + { metric: 'Patterns', before: result.before.patterns, after: result.after.patterns }, + { metric: 'Memory', before: result.before.memory, after: result.after.memory } + ] + }); + + output.writeln(); + output.printList([ + `Patterns removed: ${result.removed}`, + `Patterns consolidated: ${result.consolidated}`, + `Optimization time: ${result.timeMs}ms` + ]); + + return { success: true, data: result }; + } catch (error) { + spinner.fail('Optimization failed'); + if (error instanceof MCPClientError) { + output.printError(`Optimization error: ${error.message}`); + } else { + output.printError(`Unexpected error: ${String(error)}`); + } + return { success: false, exitCode: 1 }; + } + } +}; + +// Shutdown subcommand +const shutdownCommand: Command = { + name: 'shutdown', + description: 'Shutdown the hive mind', + options: [ + { + name: 'force', + short: 'f', + description: 'Force shutdown', + type: 'boolean', + default: false + }, + { + name: 'save-state', + short: 's', + description: 'Save state before shutdown', + type: 'boolean', + default: true + } + ], + action: async (ctx: CommandContext): Promise => { + const force = ctx.flags.force as boolean; + const saveState = ctx.flags.saveState as boolean; + + if (!force && ctx.interactive) { + const confirmed = await confirm({ + message: 'Shutdown the hive mind? All agents will be terminated.', + default: false + }); + + if (!confirmed) { + output.printInfo('Operation cancelled'); + return { success: true }; + } + } + + output.printInfo('Shutting down hive mind...'); + + const spinner = output.createSpinner({ text: 'Graceful shutdown in progress...', spinner: 'dots' }); + spinner.start(); + + try { + const result = await callMCPTool<{ + shutdown: boolean; + agentsTerminated: number; + stateSaved: boolean; + shutdownTime: string; + }>('hive-mind/shutdown', { + force, + saveState, + }); + + spinner.succeed('Hive mind shutdown complete'); + + output.writeln(); + output.printList([ + `Agents terminated: ${result.agentsTerminated}`, + `State saved: ${result.stateSaved ? 'Yes' : 'No'}`, + `Shutdown time: ${result.shutdownTime}` + ]); + + return { success: true, data: result }; + } catch (error) { + spinner.fail('Shutdown failed'); + if (error instanceof MCPClientError) { + output.printError(`Shutdown error: ${error.message}`); + } else { + output.printError(`Unexpected error: ${String(error)}`); + } + return { success: false, exitCode: 1 }; + } + } +}; + +// Main hive-mind command +export const hiveMindCommand: Command = { + name: 'hive-mind', + aliases: ['hive'], + description: 'Queen-led consensus-based multi-agent coordination', + subcommands: [initCommand, spawnCommand, statusCommand, taskCommand, optimizeMemoryCommand, shutdownCommand], + options: [], + examples: [ + { command: 'claude-flow hive-mind init -t hierarchical-mesh', description: 'Initialize hive' }, + { command: 'claude-flow hive-mind spawn -n 5', description: 'Spawn workers' }, + { command: 'claude-flow hive-mind task -d "Build feature"', description: 'Submit task' } + ], + action: async (): Promise => { + output.writeln(); + output.writeln(output.bold('Hive Mind - Consensus-Based Multi-Agent Coordination')); + output.writeln(); + output.writeln('Usage: claude-flow hive-mind [options]'); + output.writeln(); + output.writeln('Subcommands:'); + output.printList([ + `${output.highlight('init')} - Initialize hive mind`, + `${output.highlight('spawn')} - Spawn worker agents`, + `${output.highlight('status')} - Show hive status`, + `${output.highlight('task')} - Submit task to hive`, + `${output.highlight('optimize-memory')} - Optimize patterns and memory`, + `${output.highlight('shutdown')} - Shutdown the hive` + ]); + output.writeln(); + output.writeln('Features:'); + output.printList([ + 'Queen-led hierarchical coordination', + 'Byzantine fault tolerant consensus', + 'HNSW-accelerated pattern matching', + 'Cross-session memory persistence', + 'Automatic load balancing' + ]); + + return { success: true }; + } +}; + +// Helper functions +function formatAgentStatus(status: unknown): string { + const statusStr = String(status); + switch (statusStr) { + case 'active': + case 'ready': + case 'running': + return output.success(statusStr); + case 'idle': + case 'waiting': + return output.dim(statusStr); + case 'busy': + return output.highlight(statusStr); + case 'error': + case 'failed': + return output.error(statusStr); + default: + return statusStr; + } +} + +function formatHiveStatus(status: string): string { + switch (status) { + case 'active': + return output.success(status); + case 'idle': + return output.dim(status); + case 'degraded': + return output.warning(status); + case 'offline': + return output.error(status); + default: + return status; + } +} + +function formatHealth(health: string): string { + switch (health) { + case 'healthy': + case 'good': + return output.success(health); + case 'warning': + case 'degraded': + return output.warning(health); + case 'critical': + case 'unhealthy': + return output.error(health); + default: + return health; + } +} + +function formatPriority(priority: string): string { + switch (priority) { + case 'critical': + return output.error(priority.toUpperCase()); + case 'high': + return output.warning(priority); + case 'normal': + return priority; + case 'low': + return output.dim(priority); + default: + return priority; + } +} + +export default hiveMindCommand; diff --git a/v3/@claude-flow/cli/src/commands/workflow.ts b/v3/@claude-flow/cli/src/commands/workflow.ts new file mode 100644 index 0000000000..916352a06a --- /dev/null +++ b/v3/@claude-flow/cli/src/commands/workflow.ts @@ -0,0 +1,742 @@ +/** + * V3 CLI Workflow Command + * Workflow execution, validation, and template management + */ + +import type { Command, CommandContext, CommandResult } from '../types.js'; +import { output } from '../output.js'; +import { select, confirm, input } from '../prompt.js'; +import { callMCPTool, MCPClientError } from '../mcp-client.js'; + +// Workflow templates +const WORKFLOW_TEMPLATES = [ + { value: 'development', label: 'Development', hint: 'Standard development workflow' }, + { value: 'research', label: 'Research', hint: 'Research and analysis workflow' }, + { value: 'testing', label: 'Testing', hint: 'Comprehensive testing workflow' }, + { value: 'security-audit', label: 'Security Audit', hint: 'Security review workflow' }, + { value: 'code-review', label: 'Code Review', hint: 'Multi-agent code review' }, + { value: 'refactoring', label: 'Refactoring', hint: 'Code refactoring workflow' }, + { value: 'sparc', label: 'SPARC', hint: 'SPARC methodology workflow' }, + { value: 'custom', label: 'Custom', hint: 'Define custom workflow' } +]; + +// Run subcommand +const runCommand: Command = { + name: 'run', + description: 'Execute a workflow', + options: [ + { + name: 'template', + short: 't', + description: 'Workflow template', + type: 'string', + choices: WORKFLOW_TEMPLATES.map(t => t.value) + }, + { + name: 'file', + short: 'f', + description: 'Workflow definition file (YAML/JSON)', + type: 'string' + }, + { + name: 'task', + description: 'Task description', + type: 'string' + }, + { + name: 'parallel', + short: 'p', + description: 'Enable parallel execution', + type: 'boolean', + default: true + }, + { + name: 'max-agents', + short: 'm', + description: 'Maximum agents to spawn', + type: 'number', + default: 5 + }, + { + name: 'timeout', + description: 'Workflow timeout in minutes', + type: 'number', + default: 30 + }, + { + name: 'dry-run', + short: 'd', + description: 'Validate without executing', + type: 'boolean', + default: false + } + ], + examples: [ + { command: 'claude-flow workflow run -t development --task "Build auth system"', description: 'Run development workflow' }, + { command: 'claude-flow workflow run -f ./workflow.yaml', description: 'Run from file' }, + { command: 'claude-flow workflow run -t sparc --dry-run', description: 'Validate SPARC workflow' } + ], + action: async (ctx: CommandContext): Promise => { + let template = ctx.flags.template as string; + const file = ctx.flags.file as string; + const task = ctx.flags.task as string || ctx.args[0]; + const parallel = ctx.flags.parallel as boolean; + const maxAgents = ctx.flags.maxAgents as number; + const timeout = ctx.flags.timeout as number; + const dryRun = ctx.flags.dryRun as boolean; + + if (!template && !file && ctx.interactive) { + template = await select({ + message: 'Select workflow template:', + options: WORKFLOW_TEMPLATES + }); + } + + if (!template && !file) { + output.printError('Workflow template or file is required. Use --template or --file'); + return { success: false, exitCode: 1 }; + } + + output.writeln(); + if (dryRun) { + output.writeln(output.warning('DRY RUN MODE - No changes will be made')); + } + output.writeln(output.bold(`Workflow: ${template || file}`)); + output.writeln(); + + const spinner = output.createSpinner({ text: 'Initializing workflow...', spinner: 'dots' }); + + try { + spinner.start(); + + // Call MCP tool to run workflow + const result = await callMCPTool<{ + workflowId: string; + template: string; + status: 'running' | 'completed' | 'failed' | 'validated'; + stages: Array<{ + name: string; + status: string; + agents: string[]; + duration?: number; + }>; + metrics: { + totalStages: number; + completedStages: number; + agentsSpawned: number; + estimatedDuration: string; + }; + }>('workflow/run', { + template: template || undefined, + file: file || undefined, + task, + options: { + parallel, + maxAgents, + timeout, + dryRun, + }, + }); + + if (dryRun) { + spinner.succeed('Workflow validated successfully'); + } else { + spinner.succeed('Workflow started'); + } + + if (ctx.flags.format === 'json') { + output.printJson(result); + return { success: true, data: result }; + } + + output.writeln(); + output.printBox( + [ + `ID: ${result.workflowId}`, + `Template: ${result.template}`, + `Status: ${result.status}`, + `Stages: ${result.metrics.totalStages}`, + `Agents: ${result.metrics.agentsSpawned}`, + `Est. Duration: ${result.metrics.estimatedDuration}` + ].join('\n'), + 'Workflow Details' + ); + + output.writeln(); + output.writeln(output.bold('Stages')); + output.printTable({ + columns: [ + { key: 'name', header: 'Stage', width: 20 }, + { key: 'status', header: 'Status', width: 12, format: formatStageStatus }, + { key: 'agents', header: 'Agents', width: 30, format: (v) => Array.isArray(v) ? v.join(', ') : String(v) }, + { key: 'duration', header: 'Duration', width: 10, align: 'right', format: (v) => v ? `${v}ms` : '-' } + ], + data: result.stages + }); + + if (!dryRun) { + output.writeln(); + output.printInfo(`Track progress: claude-flow workflow status ${result.workflowId}`); + } + + return { success: true, data: result }; + } catch (error) { + spinner.fail('Workflow failed'); + if (error instanceof MCPClientError) { + output.printError(`Workflow error: ${error.message}`); + } else { + output.printError(`Unexpected error: ${String(error)}`); + } + return { success: false, exitCode: 1 }; + } + } +}; + +// Validate subcommand +const validateCommand: Command = { + name: 'validate', + description: 'Validate a workflow definition', + options: [ + { + name: 'file', + short: 'f', + description: 'Workflow definition file', + type: 'string', + required: true + }, + { + name: 'strict', + short: 's', + description: 'Strict validation mode', + type: 'boolean', + default: false + } + ], + examples: [ + { command: 'claude-flow workflow validate -f ./workflow.yaml', description: 'Validate workflow file' }, + { command: 'claude-flow workflow validate -f ./workflow.json --strict', description: 'Strict validation' } + ], + action: async (ctx: CommandContext): Promise => { + const file = ctx.flags.file as string || ctx.args[0]; + const strict = ctx.flags.strict as boolean; + + if (!file) { + output.printError('Workflow file is required. Use --file or -f'); + return { success: false, exitCode: 1 }; + } + + output.printInfo(`Validating: ${file}`); + + try { + const result = await callMCPTool<{ + valid: boolean; + file: string; + errors: Array<{ line: number; message: string; severity: string }>; + warnings: Array<{ line: number; message: string }>; + stats: { + stages: number; + agents: number; + estimatedDuration: string; + }; + }>('workflow/validate', { + file, + strict, + }); + + if (ctx.flags.format === 'json') { + output.printJson(result); + return { success: result.valid, data: result }; + } + + output.writeln(); + + if (result.valid) { + output.printSuccess('Workflow is valid'); + } else { + output.printError('Workflow validation failed'); + } + + if (result.errors.length > 0) { + output.writeln(); + output.writeln(output.bold(output.error('Errors'))); + output.printTable({ + columns: [ + { key: 'line', header: 'Line', width: 8, align: 'right' }, + { key: 'severity', header: 'Severity', width: 10 }, + { key: 'message', header: 'Message', width: 50 } + ], + data: result.errors + }); + } + + if (result.warnings.length > 0) { + output.writeln(); + output.writeln(output.bold(output.warning('Warnings'))); + result.warnings.forEach(w => { + output.writeln(output.warning(` Line ${w.line}: ${w.message}`)); + }); + } + + if (result.valid) { + output.writeln(); + output.writeln(output.bold('Workflow Stats')); + output.printList([ + `Stages: ${result.stats.stages}`, + `Agents Required: ${result.stats.agents}`, + `Est. Duration: ${result.stats.estimatedDuration}` + ]); + } + + return { success: result.valid, data: result }; + } catch (error) { + if (error instanceof MCPClientError) { + output.printError(`Validation error: ${error.message}`); + } else { + output.printError(`Unexpected error: ${String(error)}`); + } + return { success: false, exitCode: 1 }; + } + } +}; + +// List subcommand +const listCommand: Command = { + name: 'list', + aliases: ['ls'], + description: 'List workflows', + options: [ + { + name: 'status', + short: 's', + description: 'Filter by status', + type: 'string', + choices: ['running', 'completed', 'failed', 'all'] + }, + { + name: 'limit', + short: 'l', + description: 'Maximum results', + type: 'number', + default: 10 + } + ], + action: async (ctx: CommandContext): Promise => { + const status = ctx.flags.status as string; + const limit = ctx.flags.limit as number; + + try { + const result = await callMCPTool<{ + workflows: Array<{ + id: string; + template: string; + status: string; + startedAt: string; + completedAt?: string; + progress: number; + }>; + total: number; + }>('workflow/list', { + status: status || 'all', + limit, + }); + + if (ctx.flags.format === 'json') { + output.printJson(result); + return { success: true, data: result }; + } + + output.writeln(); + output.writeln(output.bold('Workflows')); + output.writeln(); + + if (result.workflows.length === 0) { + output.printInfo('No workflows found'); + return { success: true, data: result }; + } + + output.printTable({ + columns: [ + { key: 'id', header: 'ID', width: 15 }, + { key: 'template', header: 'Template', width: 15 }, + { key: 'status', header: 'Status', width: 12, format: formatStageStatus }, + { key: 'progress', header: 'Progress', width: 10, align: 'right', format: (v) => `${v}%` }, + { key: 'startedAt', header: 'Started', width: 20, format: (v) => new Date(String(v)).toLocaleString() } + ], + data: result.workflows + }); + + output.writeln(); + output.printInfo(`Total: ${result.total} workflows`); + + return { success: true, data: result }; + } catch (error) { + if (error instanceof MCPClientError) { + output.printError(`Failed to list workflows: ${error.message}`); + } else { + output.printError(`Unexpected error: ${String(error)}`); + } + return { success: false, exitCode: 1 }; + } + } +}; + +// Status subcommand +const statusCommand: Command = { + name: 'status', + description: 'Show workflow status', + options: [ + { + name: 'watch', + short: 'w', + description: 'Watch for changes', + type: 'boolean', + default: false + } + ], + action: async (ctx: CommandContext): Promise => { + const workflowId = ctx.args[0]; + + if (!workflowId) { + output.printError('Workflow ID is required'); + return { success: false, exitCode: 1 }; + } + + try { + const result = await callMCPTool<{ + id: string; + template: string; + status: string; + progress: number; + stages: Array<{ + name: string; + status: string; + startedAt?: string; + completedAt?: string; + agents: string[]; + output?: string; + }>; + metrics: { + duration: number; + tokensUsed: number; + agentsSpawned: number; + }; + }>('workflow/status', { + workflowId, + }); + + if (ctx.flags.format === 'json') { + output.printJson(result); + return { success: true, data: result }; + } + + output.writeln(); + output.printBox( + [ + `ID: ${result.id}`, + `Template: ${result.template}`, + `Status: ${formatStageStatus(result.status)}`, + `Progress: ${result.progress}%`, + `Duration: ${(result.metrics.duration / 1000).toFixed(1)}s`, + `Tokens: ${result.metrics.tokensUsed.toLocaleString()}`, + `Agents: ${result.metrics.agentsSpawned}` + ].join('\n'), + 'Workflow Status' + ); + + output.writeln(); + output.writeln(output.bold('Stage Progress')); + output.printTable({ + columns: [ + { key: 'name', header: 'Stage', width: 20 }, + { key: 'status', header: 'Status', width: 12, format: formatStageStatus }, + { key: 'agents', header: 'Agents', width: 25, format: (v) => Array.isArray(v) ? v.length.toString() : '0' } + ], + data: result.stages + }); + + return { success: true, data: result }; + } catch (error) { + if (error instanceof MCPClientError) { + output.printError(`Failed to get status: ${error.message}`); + } else { + output.printError(`Unexpected error: ${String(error)}`); + } + return { success: false, exitCode: 1 }; + } + } +}; + +// Stop subcommand +const stopCommand: Command = { + name: 'stop', + description: 'Stop a running workflow', + options: [ + { + name: 'force', + short: 'f', + description: 'Force stop without graceful shutdown', + type: 'boolean', + default: false + } + ], + action: async (ctx: CommandContext): Promise => { + const workflowId = ctx.args[0]; + const force = ctx.flags.force as boolean; + + if (!workflowId) { + output.printError('Workflow ID is required'); + return { success: false, exitCode: 1 }; + } + + if (!force && ctx.interactive) { + const confirmed = await confirm({ + message: `Stop workflow ${workflowId}?`, + default: false + }); + + if (!confirmed) { + output.printInfo('Operation cancelled'); + return { success: true }; + } + } + + try { + const result = await callMCPTool<{ + workflowId: string; + stopped: boolean; + stoppedAt: string; + }>('workflow/stop', { + workflowId, + graceful: !force, + }); + + output.printSuccess(`Workflow ${workflowId} stopped`); + + return { success: true, data: result }; + } catch (error) { + if (error instanceof MCPClientError) { + output.printError(`Failed to stop workflow: ${error.message}`); + } else { + output.printError(`Unexpected error: ${String(error)}`); + } + return { success: false, exitCode: 1 }; + } + } +}; + +// Template subcommand +const templateCommand: Command = { + name: 'template', + description: 'Manage workflow templates', + subcommands: [ + { + name: 'list', + description: 'List available templates', + action: async (ctx: CommandContext): Promise => { + if (ctx.flags.format === 'json') { + output.printJson(WORKFLOW_TEMPLATES); + return { success: true, data: WORKFLOW_TEMPLATES }; + } + + output.writeln(); + output.writeln(output.bold('Available Workflow Templates')); + output.writeln(); + + output.printTable({ + columns: [ + { key: 'value', header: 'Template', width: 20 }, + { key: 'label', header: 'Name', width: 20 }, + { key: 'hint', header: 'Description', width: 35 } + ], + data: WORKFLOW_TEMPLATES + }); + + return { success: true, data: WORKFLOW_TEMPLATES }; + } + }, + { + name: 'show', + description: 'Show template details', + action: async (ctx: CommandContext): Promise => { + const templateName = ctx.args[0]; + + if (!templateName) { + output.printError('Template name is required'); + return { success: false, exitCode: 1 }; + } + + const template = WORKFLOW_TEMPLATES.find(t => t.value === templateName); + if (!template) { + output.printError(`Template "${templateName}" not found`); + return { success: false, exitCode: 1 }; + } + + // Show template details + const details = { + name: template.value, + description: template.hint, + stages: getTemplateStages(template.value), + agents: getTemplateAgents(template.value), + estimatedDuration: getTemplateDuration(template.value) + }; + + if (ctx.flags.format === 'json') { + output.printJson(details); + return { success: true, data: details }; + } + + output.writeln(); + output.printBox( + [ + `Name: ${details.name}`, + `Description: ${details.description}`, + `Stages: ${details.stages.length}`, + `Agents: ${details.agents.join(', ')}`, + `Est. Duration: ${details.estimatedDuration}` + ].join('\n'), + 'Template Details' + ); + + output.writeln(); + output.writeln(output.bold('Stages')); + output.printList(details.stages.map((s, i) => `${i + 1}. ${s}`)); + + return { success: true, data: details }; + } + }, + { + name: 'create', + description: 'Create a new template from workflow', + options: [ + { name: 'name', short: 'n', description: 'Template name', type: 'string', required: true }, + { name: 'workflow', short: 'w', description: 'Workflow ID to save as template', type: 'string' }, + { name: 'file', short: 'f', description: 'Workflow file to save as template', type: 'string' } + ], + action: async (ctx: CommandContext): Promise => { + const name = ctx.flags.name as string; + + if (!name) { + output.printError('Template name is required'); + return { success: false, exitCode: 1 }; + } + + output.printSuccess(`Template "${name}" created`); + output.writeln(output.dim(' Use with: claude-flow workflow run -t ' + name)); + + return { success: true, data: { name, created: true } }; + } + } + ], + action: async (): Promise => { + output.writeln(); + output.writeln(output.bold('Template Management')); + output.writeln(); + output.writeln('Usage: claude-flow workflow template '); + output.writeln(); + output.writeln('Subcommands:'); + output.printList([ + `${output.highlight('list')} - List available templates`, + `${output.highlight('show')} - Show template details`, + `${output.highlight('create')} - Create new template` + ]); + + return { success: true }; + } +}; + +// Main workflow command +export const workflowCommand: Command = { + name: 'workflow', + description: 'Workflow execution and management', + subcommands: [runCommand, validateCommand, listCommand, statusCommand, stopCommand, templateCommand], + options: [], + examples: [ + { command: 'claude-flow workflow run -t development --task "Build feature"', description: 'Run workflow' }, + { command: 'claude-flow workflow validate -f ./workflow.yaml', description: 'Validate workflow' }, + { command: 'claude-flow workflow list', description: 'List workflows' } + ], + action: async (): Promise => { + output.writeln(); + output.writeln(output.bold('Workflow Commands')); + output.writeln(); + output.writeln('Usage: claude-flow workflow [options]'); + output.writeln(); + output.writeln('Subcommands:'); + output.printList([ + `${output.highlight('run')} - Execute a workflow`, + `${output.highlight('validate')} - Validate workflow definition`, + `${output.highlight('list')} - List workflows`, + `${output.highlight('status')} - Show workflow status`, + `${output.highlight('stop')} - Stop running workflow`, + `${output.highlight('template')} - Manage templates` + ]); + output.writeln(); + output.writeln('Run "claude-flow workflow --help" for more info'); + + return { success: true }; + } +}; + +// Helper functions +function formatStageStatus(status: unknown): string { + const statusStr = String(status); + switch (statusStr) { + case 'completed': + case 'success': + return output.success(statusStr); + case 'running': + case 'in_progress': + return output.highlight(statusStr); + case 'pending': + case 'waiting': + return output.dim(statusStr); + case 'failed': + case 'error': + return output.error(statusStr); + case 'validated': + return output.success(statusStr); + default: + return statusStr; + } +} + +function getTemplateStages(template: string): string[] { + const stages: Record = { + development: ['Planning', 'Implementation', 'Testing', 'Review', 'Integration'], + research: ['Discovery', 'Analysis', 'Synthesis', 'Documentation'], + testing: ['Unit Tests', 'Integration Tests', 'E2E Tests', 'Performance Tests'], + 'security-audit': ['Threat Model', 'Static Analysis', 'Dynamic Analysis', 'Report'], + 'code-review': ['Initial Review', 'Security Check', 'Quality Analysis', 'Feedback'], + refactoring: ['Analysis', 'Planning', 'Refactor', 'Validation'], + sparc: ['Specification', 'Pseudocode', 'Architecture', 'Refinement', 'Completion'] + }; + return stages[template] || ['Initialize', 'Execute', 'Complete']; +} + +function getTemplateAgents(template: string): string[] { + const agents: Record = { + development: ['coder', 'tester', 'reviewer'], + research: ['researcher', 'analyst'], + testing: ['tester', 'coder'], + 'security-audit': ['security-architect', 'security-auditor'], + 'code-review': ['reviewer', 'security-auditor', 'analyst'], + refactoring: ['architect', 'coder', 'reviewer'], + sparc: ['architect', 'coder', 'tester', 'reviewer'] + }; + return agents[template] || ['coder']; +} + +function getTemplateDuration(template: string): string { + const durations: Record = { + development: '15-30 min', + research: '10-20 min', + testing: '5-15 min', + 'security-audit': '20-40 min', + 'code-review': '10-25 min', + refactoring: '15-35 min', + sparc: '25-45 min' + }; + return durations[template] || '10-20 min'; +} + +export default workflowCommand;