claude-flow 2.5.0-alpha.139 → 2.5.0-alpha.141

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 (42) hide show
  1. package/.claude/settings.json +3 -2
  2. package/README.md +50 -55
  3. package/bin/claude-flow +1 -1
  4. package/dist/src/cli/commands/hive-mind/pause.js +2 -9
  5. package/dist/src/cli/commands/hive-mind/pause.js.map +1 -1
  6. package/dist/src/cli/commands/index.js +1 -114
  7. package/dist/src/cli/commands/index.js.map +1 -1
  8. package/dist/src/cli/commands/swarm-spawn.js +5 -33
  9. package/dist/src/cli/commands/swarm-spawn.js.map +1 -1
  10. package/dist/src/cli/help-formatter.js.map +1 -1
  11. package/dist/src/cli/help-text.js +16 -2
  12. package/dist/src/cli/help-text.js.map +1 -1
  13. package/dist/src/cli/simple-commands/hooks.js +233 -0
  14. package/dist/src/cli/simple-commands/hooks.js.map +1 -1
  15. package/dist/src/cli/validation-helper.js.map +1 -1
  16. package/dist/src/core/version.js +1 -1
  17. package/dist/src/hooks/index.js +0 -3
  18. package/dist/src/hooks/index.js.map +1 -1
  19. package/dist/src/mcp/claude-flow-tools.js +205 -150
  20. package/dist/src/mcp/claude-flow-tools.js.map +1 -1
  21. package/dist/src/mcp/mcp-server.js +125 -0
  22. package/dist/src/mcp/mcp-server.js.map +1 -1
  23. package/dist/src/memory/swarm-memory.js +421 -340
  24. package/dist/src/memory/swarm-memory.js.map +1 -1
  25. package/dist/src/sdk/query-control.js +293 -139
  26. package/dist/src/sdk/query-control.js.map +1 -1
  27. package/dist/src/sdk/session-forking.js +206 -129
  28. package/dist/src/sdk/session-forking.js.map +1 -1
  29. package/package.json +1 -1
  30. package/src/cli/commands/hive-mind/pause.ts +2 -15
  31. package/src/cli/commands/index.ts +1 -84
  32. package/src/cli/commands/swarm-spawn.ts +3 -47
  33. package/src/cli/help-text.js +16 -2
  34. package/src/cli/simple-cli.ts +0 -1
  35. package/src/cli/simple-commands/hooks.js +310 -0
  36. package/src/hooks/index.ts +0 -5
  37. package/src/mcp/claude-flow-tools.ts +203 -120
  38. package/src/mcp/mcp-server.js +86 -0
  39. package/src/sdk/query-control.ts +377 -223
  40. package/src/sdk/session-forking.ts +312 -207
  41. package/.claude/commands/coordination/README.md +0 -9
  42. package/.claude/commands/memory/README.md +0 -9
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../src/cli/commands/index.ts"],"sourcesContent":["import chalk from 'chalk';\nimport { getErrorMessage } from '../../utils/error-handler.js';\nimport { CLI, success, error, warning, info, VERSION } from '../cli-core.js';\nimport type { Command, CommandContext } from '../cli-core.js';\nimport colors from 'chalk';\nconst { bold, blue, yellow } = colors;\nimport { Orchestrator } from '../../core/orchestrator-fixed.js';\nimport { ConfigManager } from '../../core/config.js';\nimport type { MemoryManager } from '../../memory/manager.js';\nimport { EventBus } from '../../core/event-bus.js';\nimport { Logger } from '../../core/logger.js';\nimport { JsonPersistenceManager } from '../../core/json-persistence.js';\nimport { swarmAction } from './swarm.js';\nimport { SimpleMemoryManager } from './memory.js';\nimport { sparcAction } from './sparc.js';\nimport { createMigrateCommand } from './migrate.js';\nimport { enterpriseCommands } from './enterprise.js';\nimport { createFlowNexusClaudeMd } from '../simple-commands/init/templates/claude-md.js';\n\n// Import enhanced orchestration commands\nimport { startCommand } from './start.js';\nimport { statusCommand } from './status.js';\nimport { monitorCommand } from './monitor.js';\nimport { sessionCommand } from './session.js';\nimport { checkpointCommand } from './checkpoint.js';\n\nlet orchestrator: Orchestrator | null = null;\nlet configManager: ConfigManager | null = null;\nlet persistence: JsonPersistenceManager | null = null;\n\nasync function getPersistence(): Promise<JsonPersistenceManager> {\n if (!persistence) {\n persistence = new JsonPersistenceManager();\n await persistence.initialize();\n }\n return persistence;\n}\n\nasync function getOrchestrator(): Promise<Orchestrator> {\n if (!orchestrator) {\n const config = await getConfigManager();\n const eventBus = EventBus.getInstance();\n const logger = new Logger({ level: 'info', format: 'text', destination: 'console' });\n orchestrator = new Orchestrator(config, eventBus, logger);\n }\n return orchestrator;\n}\n\nasync function getConfigManager(): Promise<ConfigManager> {\n if (!configManager) {\n configManager = ConfigManager.getInstance();\n await configManager.load();\n }\n return configManager;\n}\n\nexport function setupCommands(cli: CLI): void {\n // Neural init command\n cli.command({\n name: 'neural',\n description: 'Neural module management',\n subcommands: [\n {\n name: 'init',\n description: 'Initialize SAFLA neural module',\n options: [\n {\n name: 'force',\n short: 'f',\n description: 'Overwrite existing module',\n type: 'boolean',\n },\n {\n name: 'target',\n short: 't',\n description: 'Target directory',\n type: 'string',\n defaultValue: '.claude/agents/neural',\n },\n ],\n action: async (ctx: CommandContext) => {\n const { initNeuralModule } = await import('../../scripts/init-neural.js');\n await initNeuralModule({\n force: ctx.flags.force as boolean,\n targetDir: ctx.flags.target as string,\n });\n },\n },\n ],\n });\n\n // Goal init command\n cli.command({\n name: 'goal',\n description: 'Goal module management',\n subcommands: [\n {\n name: 'init',\n description: 'Initialize GOAP goal module',\n options: [\n {\n name: 'force',\n short: 'f',\n description: 'Overwrite existing module',\n type: 'boolean',\n },\n {\n name: 'target',\n short: 't',\n description: 'Target directory',\n type: 'string',\n defaultValue: '.claude/agents/goal',\n },\n ],\n action: async (ctx: CommandContext) => {\n const { initGoalModule } = await import('../../scripts/init-goal.js');\n await initGoalModule({\n force: ctx.flags.force as boolean,\n targetDir: ctx.flags.target as string,\n });\n },\n },\n ],\n });\n\n // Init command\n cli.command({\n name: 'init',\n description: 'Initialize Claude Code integration files',\n options: [\n {\n name: 'force',\n short: 'f',\n description: 'Overwrite existing files',\n type: 'boolean',\n },\n {\n name: 'minimal',\n short: 'm',\n description: 'Create minimal configuration files',\n type: 'boolean',\n },\n {\n name: 'flow-nexus',\n description: 'Initialize with Flow Nexus commands, agents, and CLAUDE.md only',\n type: 'boolean',\n },\n ],\n action: async (ctx: CommandContext) => {\n try {\n success('Initializing Claude Code integration files...');\n\n const force = (ctx.flags.force as boolean) || (ctx.flags.f as boolean);\n const minimal = (ctx.flags.minimal as boolean) || (ctx.flags.m as boolean);\n const flowNexus = ctx.flags['flow-nexus'] as boolean;\n\n // Handle Flow Nexus minimal init\n if (flowNexus) {\n success('Initializing Flow Nexus minimal setup...');\n \n // Create Flow Nexus CLAUDE.md with integrated section\n const flowNexusClaudeMd = createFlowNexusClaudeMd();\n const { writeFile, mkdir } = await import('fs/promises');\n await writeFile('CLAUDE.md', flowNexusClaudeMd);\n console.log(' āœ“ Created CLAUDE.md with Flow Nexus integration');\n \n // Create .claude/commands/flow-nexus directory and copy commands\n await mkdir('.claude/commands/flow-nexus', { recursive: true });\n \n // Create .claude/agents/flow-nexus directory and copy agents\n await mkdir('.claude/agents/flow-nexus', { recursive: true });\n \n success('Flow Nexus initialization complete!');\n console.log('šŸ“š Created: CLAUDE.md with Flow Nexus documentation');\n console.log('šŸ“ Created: .claude/commands/flow-nexus/ directory structure'); \n console.log('šŸ¤– Created: .claude/agents/flow-nexus/ directory structure');\n console.log('šŸ’” Use MCP Flow Nexus tools in Claude Code for full functionality');\n return;\n }\n\n // Check if files already exist for full init\n const files = ['CLAUDE.md', 'memory-bank.md', 'coordination.md'];\n const existingFiles = [];\n\n for (const file of files) {\n const { access } = await import('fs/promises');\n const exists = await access(file)\n .then(() => true)\n .catch(() => false);\n if (exists) {\n existingFiles.push(file);\n }\n }\n\n if (existingFiles.length > 0 && !force) {\n warning(`The following files already exist: ${existingFiles.join(', ')}`);\n console.log('Use --force to overwrite existing files');\n return;\n }\n\n // Create CLAUDE.md\n const claudeMd = minimal ? createMinimalClaudeMd() : createFullClaudeMd();\n const { writeFile } = await import('fs/promises');\n await writeFile('CLAUDE.md', claudeMd);\n console.log(' āœ“ Created CLAUDE.md');\n\n // Create memory-bank.md\n const memoryBankMd = minimal ? createMinimalMemoryBankMd() : createFullMemoryBankMd();\n await writeFile('memory-bank.md', memoryBankMd);\n console.log(' āœ“ Created memory-bank.md');\n\n // Create coordination.md\n const coordinationMd = minimal ? createMinimalCoordinationMd() : createFullCoordinationMd();\n await writeFile('coordination.md', coordinationMd);\n console.log(' āœ“ Created coordination.md');\n\n // Create directory structure\n const directories = [\n 'memory',\n 'memory/agents',\n 'memory/sessions',\n 'coordination',\n 'coordination/memory_bank',\n 'coordination/subtasks',\n 'coordination/orchestration',\n ];\n\n // Ensure memory directory exists for SQLite database\n if (!directories.includes('memory')) {\n directories.unshift('memory');\n }\n\n const { mkdir } = await import('fs/promises');\n for (const dir of directories) {\n try {\n await mkdir(dir, { recursive: true });\n console.log(` āœ“ Created ${dir}/ directory`);\n } catch (err) {\n if ((err as any).code !== 'EEXIST') {\n throw err;\n }\n }\n }\n\n // Create placeholder files for memory directories\n const agentsReadme = createAgentsReadme();\n await writeFile('memory/agents/README.md', agentsReadme);\n console.log(' āœ“ Created memory/agents/README.md');\n\n const sessionsReadme = createSessionsReadme();\n await writeFile('memory/sessions/README.md', sessionsReadme);\n console.log(' āœ“ Created memory/sessions/README.md');\n\n // Initialize the persistence database\n const initialData = {\n agents: [],\n tasks: [],\n lastUpdated: Date.now(),\n };\n await writeFile('memory/claude-flow-data.json', JSON.stringify(initialData, null, 2));\n console.log(' āœ“ Created memory/claude-flow-data.json (persistence database)');\n\n success('Claude Code integration files initialized successfully!');\n console.log('\\nNext steps:');\n console.log('1. Review and customize the generated files for your project');\n console.log(\"2. Run 'npx claude-flow start' to begin the orchestration system\");\n console.log(\"3. Use 'claude --dangerously-skip-permissions' for unattended operation\");\n console.log('\\nNote: Persistence database initialized at memory/claude-flow-data.json');\n } catch (err) {\n error(`Failed to initialize files: ${(err as Error).message}`);\n }\n },\n });\n\n // Start command\n cli.command({\n name: 'start',\n description: 'Start the orchestration system',\n options: [\n {\n name: 'daemon',\n short: 'd',\n description: 'Run as daemon in background',\n type: 'boolean',\n },\n {\n name: 'port',\n short: 'p',\n description: 'MCP server port',\n type: 'number',\n default: 3000,\n },\n ],\n action: async (ctx: CommandContext) => {\n success('Starting Claude-Flow orchestration system...');\n\n try {\n const orch = await getOrchestrator();\n await orch.start();\n\n success('System started successfully!');\n info('Components initialized:');\n console.log(' āœ“ Event Bus');\n console.log(' āœ“ Orchestrator Engine');\n console.log(' āœ“ Memory Manager');\n console.log(' āœ“ Terminal Pool');\n console.log(' āœ“ MCP Server');\n console.log(' āœ“ Coordination Manager');\n\n if (!ctx.flags.daemon) {\n info('Press Ctrl+C to stop the system');\n // Keep the process running until interrupted\n const controller = new AbortController();\n\n const shutdown = () => {\n console.log('\\nShutting down...');\n controller.abort();\n };\n\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n\n try {\n await new Promise<void>((resolve) => {\n controller.signal.addEventListener('abort', () => resolve());\n });\n } finally {\n process.off('SIGINT', shutdown);\n process.off('SIGTERM', shutdown);\n }\n }\n } catch (err) {\n error(`Failed to start system: ${(err as Error).message}`);\n process.exit(1);\n }\n },\n });\n\n // Task command\n cli.command({\n name: 'task',\n description: 'Manage tasks',\n aliases: ['tasks'],\n action: async (ctx: CommandContext) => {\n const subcommand = ctx.args[0];\n\n switch (subcommand) {\n case 'create': {\n const type = ctx.args[1] || 'general';\n const description = ctx.args.slice(2).join(' ') || 'No description';\n\n try {\n const persist = await getPersistence();\n const taskId = `task-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n\n // Save to persistence directly\n await persist.saveTask({\n id: taskId,\n type,\n description,\n status: 'pending',\n priority: (ctx.flags.priority as number) || 1,\n dependencies: ctx.flags.deps ? (ctx.flags.deps as string).split(',') : [],\n metadata: {},\n progress: 0,\n createdAt: Date.now(),\n });\n\n success(`Task created successfully!`);\n console.log(`šŸ“ Task ID: ${taskId}`);\n console.log(`šŸŽÆ Type: ${type}`);\n console.log(`šŸ“„ Description: ${description}`);\n } catch (err) {\n error(`Failed to create task: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'list': {\n try {\n const persist = await getPersistence();\n const tasks = await persist.getActiveTasks();\n\n if (tasks.length === 0) {\n info('No active tasks');\n } else {\n success(`Active tasks (${tasks.length}):`);\n for (const task of tasks) {\n console.log(` • ${task.id} (${task.type}) - ${task.status}`);\n if (ctx.flags.verbose) {\n console.log(` Description: ${task.description}`);\n }\n }\n }\n } catch (err) {\n error(`Failed to list tasks: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'assign': {\n const taskId = ctx.args[1];\n const agentId = ctx.args[2];\n\n if (!taskId || !agentId) {\n error('Usage: task assign <task-id> <agent-id>');\n break;\n }\n\n try {\n const persist = await getPersistence();\n const tasks = await persist.getAllTasks();\n const agents = await persist.getAllAgents();\n\n const task = tasks.find((t) => t.id === taskId);\n const agent = agents.find((a) => a.id === agentId);\n\n if (!task) {\n error(`Task not found: ${taskId}`);\n break;\n }\n\n if (!agent) {\n error(`Agent not found: ${agentId}`);\n break;\n }\n\n // Update task with assigned agent\n task.assignedAgent = agentId;\n task.status = 'assigned';\n await persist.saveTask(task);\n\n success(`Task ${taskId} assigned to agent ${agentId}`);\n console.log(`šŸ“ Task: ${task.description}`);\n console.log(`šŸ¤– Agent: ${agent.name} (${agent.type})`);\n } catch (err) {\n error(`Failed to assign task: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'workflow': {\n const workflowFile = ctx.args[1];\n if (!workflowFile) {\n error('Usage: task workflow <workflow-file>');\n break;\n }\n\n try {\n const { readFile } = await import('fs/promises');\n const content = await readFile(workflowFile, 'utf-8');\n const workflow = JSON.parse(content);\n\n success('Workflow loaded:');\n console.log(`šŸ“‹ Name: ${workflow.name || 'Unnamed'}`);\n console.log(`šŸ“ Description: ${workflow.description || 'No description'}`);\n console.log(`šŸ¤– Agents: ${workflow.agents?.length || 0}`);\n console.log(`šŸ“Œ Tasks: ${workflow.tasks?.length || 0}`);\n\n if (ctx.flags.execute) {\n warning('Workflow execution would start here (not yet implemented)');\n // TODO: Implement workflow execution\n } else {\n info('To execute this workflow, ensure Claude-Flow is running');\n }\n } catch (err) {\n error(`Failed to load workflow: ${(err as Error).message}`);\n }\n break;\n }\n\n default: {\n console.log('Available subcommands: create, list, assign, workflow');\n break;\n }\n }\n },\n });\n\n // Enhanced Agent command with comprehensive management\n cli.command({\n name: 'agent',\n description: 'Comprehensive agent management with advanced features',\n aliases: ['agents'],\n action: async (ctx: CommandContext) => {\n const subcommand = ctx.args[0];\n\n // Import enhanced agent command dynamically\n const { agentCommand } = await import('./agent.js');\n\n // Create a mock context for the enhanced command\n const enhancedCtx = {\n args: ctx.args.slice(1), // Remove 'agent' from args\n flags: ctx.flags,\n command: subcommand,\n };\n\n try {\n // Map simple commands to enhanced command structure\n switch (subcommand) {\n case 'spawn':\n case 'list':\n case 'info':\n case 'terminate':\n case 'start':\n case 'restart':\n case 'pool':\n case 'health':\n // Use the enhanced agent command system\n console.log(chalk.cyan('šŸš€ Using enhanced agent management system...'));\n\n // Create a simplified wrapper around the enhanced command\n const agentManager = await import('../../agents/agent-manager.js');\n const { MemoryManager } = await import('../../memory/manager.js');\n const { EventBus } = await import('../../core/event-bus.js');\n const { Logger } = await import('../../core/logger.js');\n const { DistributedMemorySystem } = await import('../../memory/distributed-memory.js');\n\n warning('Enhanced agent management is available!');\n console.log('For full functionality, use the comprehensive agent commands:');\n console.log(` - claude-flow agent ${subcommand} ${ctx.args.slice(1).join(' ')}`);\n console.log(' - Enhanced features: pools, health monitoring, resource management');\n console.log(' - Interactive configuration and detailed metrics');\n break;\n\n default: {\n console.log(chalk.cyan('šŸ“‹ Agent Management Commands:'));\n console.log('Available subcommands:');\n console.log(' spawn - Create and start new agents');\n console.log(' list - Display all agents with status');\n console.log(' info - Get detailed agent information');\n console.log(' terminate - Safely terminate agents');\n console.log(' start - Start a created agent');\n console.log(' restart - Restart an agent');\n console.log(' pool - Manage agent pools');\n console.log(' health - Monitor agent health');\n console.log('');\n console.log('Enhanced Features:');\n console.log(' ✨ Resource allocation and monitoring');\n console.log(' ✨ Agent pools for scaling');\n console.log(' ✨ Health diagnostics and auto-recovery');\n console.log(' ✨ Interactive configuration');\n console.log(' ✨ Memory integration for coordination');\n console.log('');\n console.log('For detailed help, use: claude-flow agent <command> --help');\n break;\n }\n }\n } catch (err) {\n error(`Enhanced agent management unavailable: ${(err as Error).message}`);\n\n // Fallback to basic implementation\n switch (subcommand) {\n case 'spawn': {\n const type = ctx.args[1] || 'researcher';\n const name = (ctx.flags.name as string) || `${type}-${Date.now()}`;\n\n try {\n const persist = await getPersistence();\n const agentId = `agent-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n\n await persist.saveAgent({\n id: agentId,\n type,\n name,\n status: 'active',\n capabilities: getCapabilitiesForType(type),\n systemPrompt: (ctx.flags.prompt as string) || getDefaultPromptForType(type),\n maxConcurrentTasks: (ctx.flags.maxTasks as number) || 5,\n priority: (ctx.flags.priority as number) || 1,\n createdAt: Date.now(),\n });\n\n success(`Agent spawned successfully!`);\n console.log(`šŸ“ Agent ID: ${agentId}`);\n console.log(`šŸ¤– Type: ${type}`);\n console.log(`šŸ“› Name: ${name}`);\n console.log(`⚔ Status: Active`);\n } catch (err) {\n error(`Failed to spawn agent: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'list': {\n try {\n const persist = await getPersistence();\n const agents = await persist.getActiveAgents();\n\n if (agents.length === 0) {\n info('No active agents');\n } else {\n success(`Active agents (${agents.length}):`);\n for (const agent of agents) {\n console.log(` • ${agent.id} (${agent.type}) - ${agent.status}`);\n }\n }\n } catch (err) {\n error(`Failed to list agents: ${(err as Error).message}`);\n }\n break;\n }\n\n default: {\n console.log('Available subcommands (basic): spawn, list');\n console.log('For enhanced features, ensure all dependencies are installed.');\n break;\n }\n }\n }\n },\n });\n\n // Enhanced status command integration\n try {\n // Import the enhanced status command and add to CLI\n const enhancedStatusAction = async (ctx: CommandContext) => {\n // Convert CLI context to match enhanced command expectations\n const options = {\n watch: ctx.flags.watch || ctx.flags.w,\n interval: ctx.flags.interval || ctx.flags.i || 5,\n component: ctx.flags.component || ctx.flags.c,\n json: ctx.flags.json,\n detailed: ctx.flags.detailed,\n healthCheck: ctx.flags.healthCheck || ctx.flags['health-check'],\n history: ctx.flags.history,\n };\n\n // Mock the enhanced status command action\n console.log(chalk.cyan('šŸ” Enhanced Status Command'));\n console.log('For full enhanced functionality, use: claude-flow status [options]');\n console.log(\n 'Available options: --watch, --interval, --component, --json, --detailed, --health-check, --history',\n );\n\n // Fallback to basic status\n try {\n const persist = await getPersistence();\n const stats = await persist.getStats();\n\n // Check if orchestrator is running by looking for the log file\n const { access } = await import('fs/promises');\n const isRunning = await access('orchestrator.log')\n .then(() => true)\n .catch(() => false);\n\n success('Claude-Flow System Status:');\n console.log(`🟢 Status: ${isRunning ? 'Running' : 'Stopped'}`);\n console.log(`šŸ¤– Agents: ${stats.activeAgents} active (${stats.totalAgents} total)`);\n console.log(`šŸ“‹ Tasks: ${stats.pendingTasks} in queue (${stats.totalTasks} total)`);\n console.log(`šŸ’¾ Memory: Ready`);\n console.log(`šŸ–„ļø Terminal Pool: Ready`);\n console.log(`🌐 MCP Server: ${isRunning ? 'Running' : 'Stopped'}`);\n\n if (ctx.flags.verbose || options.detailed) {\n console.log('\\nDetailed Statistics:');\n console.log(` Total Agents: ${stats.totalAgents}`);\n console.log(` Active Agents: ${stats.activeAgents}`);\n console.log(` Total Tasks: ${stats.totalTasks}`);\n console.log(` Pending Tasks: ${stats.pendingTasks}`);\n console.log(` Completed Tasks: ${stats.completedTasks}`);\n }\n\n if (options.watch) {\n warning('Watch mode available in enhanced status command');\n console.log('Use: claude-flow status --watch');\n }\n } catch (err) {\n error(`Failed to get status: ${(err as Error).message}`);\n }\n };\n\n cli.command({\n name: 'status',\n description: 'Show enhanced system status with comprehensive reporting',\n options: [\n {\n name: 'watch',\n short: 'w',\n description: 'Watch mode - continuously update status',\n type: 'boolean',\n },\n {\n name: 'interval',\n short: 'i',\n description: 'Update interval in seconds',\n type: 'number',\n default: 5,\n },\n {\n name: 'component',\n short: 'c',\n description: 'Show status for specific component',\n type: 'string',\n },\n { name: 'json', description: 'Output in JSON format', type: 'boolean' },\n { name: 'detailed', description: 'Show detailed component information', type: 'boolean' },\n {\n name: 'health-check',\n description: 'Perform comprehensive health checks',\n type: 'boolean',\n },\n { name: 'history', description: 'Show status history from logs', type: 'boolean' },\n { name: 'verbose', short: 'v', description: 'Enable verbose output', type: 'boolean' },\n ],\n action: enhancedStatusAction,\n });\n } catch (err) {\n warning('Enhanced status command not available, using basic version');\n\n // Fallback basic status command\n cli.command({\n name: 'status',\n description: 'Show system status',\n action: async (ctx: CommandContext) => {\n try {\n const persist = await getPersistence();\n const stats = await persist.getStats();\n\n const { access } = await import('fs/promises');\n const isRunning = await access('orchestrator.log')\n .then(() => true)\n .catch(() => false);\n\n success('Claude-Flow System Status:');\n console.log(`🟢 Status: ${isRunning ? 'Running' : 'Stopped'}`);\n console.log(`šŸ¤– Agents: ${stats.activeAgents} active (${stats.totalAgents} total)`);\n console.log(`šŸ“‹ Tasks: ${stats.pendingTasks} in queue (${stats.totalTasks} total)`);\n console.log(`šŸ’¾ Memory: Ready`);\n console.log(`šŸ–„ļø Terminal Pool: Ready`);\n console.log(`🌐 MCP Server: ${isRunning ? 'Running' : 'Stopped'}`);\n\n if (ctx.flags.verbose) {\n console.log('\\nDetailed Statistics:');\n console.log(` Total Agents: ${stats.totalAgents}`);\n console.log(` Active Agents: ${stats.activeAgents}`);\n console.log(` Total Tasks: ${stats.totalTasks}`);\n console.log(` Pending Tasks: ${stats.pendingTasks}`);\n console.log(` Completed Tasks: ${stats.completedTasks}`);\n }\n } catch (err) {\n error(`Failed to get status: ${(err as Error).message}`);\n }\n },\n });\n }\n\n // MCP command\n cli.command({\n name: 'mcp',\n description: 'Manage MCP server and tools',\n action: async (ctx: CommandContext) => {\n const subcommand = ctx.args[0];\n\n switch (subcommand) {\n case 'start': {\n const port = (ctx.flags.port as number) || 3000;\n const host = (ctx.flags.host as string) || 'localhost';\n\n try {\n // MCP server is part of the orchestrator start process\n const orch = await getOrchestrator();\n const health = await orch.healthCheck();\n\n if (!health.healthy) {\n warning(\"Orchestrator is not running. Start it first with 'claude-flow start'\");\n return;\n }\n\n success(`MCP server is running as part of the orchestration system`);\n console.log(`šŸ“” Default address: http://${host}:${port}`);\n console.log(`šŸ”§ Available tools: Research, Code, Terminal, Memory`);\n console.log(`šŸ“š Use 'claude-flow mcp tools' to see all available tools`);\n } catch (err) {\n error(`Failed to check MCP server: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'stop': {\n try {\n const orch = await getOrchestrator();\n const health = await orch.healthCheck();\n\n if (!health.healthy) {\n info('MCP server is not running');\n } else {\n warning(\n \"MCP server runs as part of the orchestrator. Use 'claude-flow stop' to stop the entire system\",\n );\n }\n } catch (err) {\n error(`Failed to check MCP server: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'status': {\n try {\n const orch = await getOrchestrator();\n const health = await orch.healthCheck();\n\n success('MCP Server Status:');\n console.log(`🌐 Status: ${health.mcp ? 'Running' : 'Stopped'}`);\n\n if (health.mcp) {\n const config = await getConfigManager();\n const mcpConfig = config.get().mcp;\n console.log(`šŸ“ Address: ${mcpConfig.host}:${mcpConfig.port}`);\n console.log(`šŸ” Authentication: ${mcpConfig.auth ? 'Enabled' : 'Disabled'}`);\n console.log(`šŸ”§ Tools: Available`);\n console.log(`šŸ“Š Metrics: Collecting`);\n }\n } catch (err) {\n error(`Failed to get MCP status: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'tools': {\n try {\n success('Available MCP Tools:');\n console.log(' šŸ“Š Research Tools:');\n console.log(' • web_search - Search the web for information');\n console.log(' • web_fetch - Fetch content from URLs');\n console.log(' • knowledge_query - Query knowledge base');\n\n console.log(' šŸ’» Code Tools:');\n console.log(' • code_edit - Edit code files');\n console.log(' • code_search - Search through codebase');\n console.log(' • code_analyze - Analyze code quality');\n\n console.log(' šŸ–„ļø Terminal Tools:');\n console.log(' • terminal_execute - Execute shell commands');\n console.log(' • terminal_session - Manage terminal sessions');\n console.log(' • file_operations - File system operations');\n\n console.log(' šŸ’¾ Memory Tools:');\n console.log(' • memory_store - Store information');\n console.log(' • memory_query - Query stored information');\n console.log(' • memory_index - Index and search content');\n } catch (err) {\n error(`Failed to list tools: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'config': {\n try {\n const config = await getConfigManager();\n const mcpConfig = config.get().mcp;\n\n success('MCP Configuration:');\n console.log(JSON.stringify(mcpConfig, null, 2));\n } catch (err) {\n error(`Failed to show MCP config: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'restart': {\n try {\n warning(\n \"MCP server runs as part of the orchestrator. Use 'claude-flow stop' then 'claude-flow start' to restart the entire system\",\n );\n } catch (err) {\n error(`Failed to restart MCP server: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'logs': {\n const lines = (ctx.flags.lines as number) || 50;\n\n try {\n // Mock logs since logging system might not be fully implemented\n success(`MCP Server Logs (last ${lines} lines):`);\n console.log('2024-01-10 10:00:00 [INFO] MCP server started on localhost:3000');\n console.log('2024-01-10 10:00:01 [INFO] Tools registered: 12');\n console.log('2024-01-10 10:00:02 [INFO] Authentication disabled');\n console.log('2024-01-10 10:01:00 [INFO] Client connected: claude-desktop');\n console.log('2024-01-10 10:01:05 [INFO] Tool called: web_search');\n console.log('2024-01-10 10:01:10 [INFO] Tool response sent successfully');\n } catch (err) {\n error(`Failed to get logs: ${(err as Error).message}`);\n }\n break;\n }\n\n default: {\n error(`Unknown mcp subcommand: ${subcommand}`);\n console.log('Available subcommands: start, stop, status, tools, config, restart, logs');\n break;\n }\n }\n },\n });\n\n // Memory command\n cli.command({\n name: 'memory',\n description: 'Manage memory bank',\n aliases: ['mem'],\n action: async (ctx: CommandContext) => {\n const subcommand = ctx.args[0];\n const memory = new SimpleMemoryManager();\n\n switch (subcommand) {\n case 'store': {\n const key = ctx.args[1];\n const value = ctx.args.slice(2).join(' '); // Join all remaining args as value\n\n if (!key || !value) {\n error('Usage: memory store <key> <value>');\n break;\n }\n\n try {\n const namespace =\n (ctx.flags.namespace as string) || (ctx.flags.n as string) || 'default';\n await memory.store(key, value, namespace);\n success('Stored successfully');\n console.log(`šŸ“ Key: ${key}`);\n console.log(`šŸ“¦ Namespace: ${namespace}`);\n console.log(`šŸ’¾ Size: ${new TextEncoder().encode(value).length} bytes`);\n } catch (err) {\n error(`Failed to store: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'query': {\n const search = ctx.args.slice(1).join(' '); // Join all remaining args as search\n\n if (!search) {\n error('Usage: memory query <search>');\n break;\n }\n\n try {\n const namespace = (ctx.flags.namespace as string) || (ctx.flags.n as string);\n const limit = (ctx.flags.limit as number) || (ctx.flags.l as number) || 10;\n const results = await memory.query(search, namespace);\n\n if (results.length === 0) {\n warning('No results found');\n return;\n }\n\n success(`Found ${results.length} results:`);\n\n const limited = results.slice(0, limit);\n for (const entry of limited) {\n console.log(blue(`\\nšŸ“Œ ${entry.key}`));\n console.log(` Namespace: ${entry.namespace}`);\n console.log(\n ` Value: ${entry.value.substring(0, 100)}${entry.value.length > 100 ? '...' : ''}`,\n );\n console.log(` Stored: ${new Date(entry.timestamp).toLocaleString()}`);\n }\n\n if (results.length > limit) {\n console.log(`\\n... and ${results.length - limit} more results`);\n }\n } catch (err) {\n error(`Failed to query: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'export': {\n const file = ctx.args[1];\n\n if (!file) {\n error('Usage: memory export <file>');\n break;\n }\n\n try {\n await memory.exportData(file);\n const stats = await memory.getStats();\n success('Memory exported successfully');\n console.log(`šŸ“ File: ${file}`);\n console.log(`šŸ“Š Entries: ${stats.totalEntries}`);\n console.log(`šŸ’¾ Size: ${(stats.sizeBytes / 1024).toFixed(2)} KB`);\n } catch (err) {\n error(`Failed to export: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'import': {\n const file = ctx.args[1];\n\n if (!file) {\n error('Usage: memory import <file>');\n break;\n }\n\n try {\n await memory.importData(file);\n const stats = await memory.getStats();\n success('Memory imported successfully');\n console.log(`šŸ“ File: ${file}`);\n console.log(`šŸ“Š Entries: ${stats.totalEntries}`);\n console.log(`šŸ—‚ļø Namespaces: ${stats.namespaces}`);\n } catch (err) {\n error(`Failed to import: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'stats': {\n try {\n const stats = await memory.getStats();\n\n success('Memory Bank Statistics:');\n console.log(` Total Entries: ${stats.totalEntries}`);\n console.log(` Namespaces: ${stats.namespaces}`);\n console.log(` Size: ${(stats.sizeBytes / 1024).toFixed(2)} KB`);\n\n if (stats.namespaces > 0) {\n console.log(blue('\\nšŸ“ Namespace Breakdown:'));\n for (const [namespace, count] of Object.entries(stats.namespaceStats)) {\n console.log(` ${namespace}: ${count} entries`);\n }\n }\n } catch (err) {\n error(`Failed to get stats: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'cleanup': {\n try {\n const days = (ctx.flags.days as number) || (ctx.flags.d as number) || 30;\n const removed = await memory.cleanup(days);\n success('Cleanup completed');\n console.log(`šŸ—‘ļø Removed: ${removed} entries older than ${days} days`);\n } catch (err) {\n error(`Failed to cleanup: ${(err as Error).message}`);\n }\n break;\n }\n\n default: {\n console.log('Available subcommands: store, query, export, import, stats, cleanup');\n console.log('\\nExamples:');\n console.log(` ${blue('memory store')} previous_work \"Research findings from yesterday\"`);\n console.log(` ${blue('memory query')} research`);\n console.log(` ${blue('memory export')} backup.json`);\n console.log(` ${blue('memory stats')}`);\n break;\n }\n }\n },\n });\n\n // Claude command\n cli.command({\n name: 'claude',\n description: 'Spawn Claude instances with specific configurations',\n aliases: ['cl'],\n options: [\n {\n name: 'tools',\n short: 't',\n description: 'Allowed tools (comma-separated)',\n type: 'string',\n default: 'View,Edit,Replace,GlobTool,GrepTool,LS,Bash',\n },\n {\n name: 'no-permissions',\n description: 'Use --dangerously-skip-permissions flag',\n type: 'boolean',\n },\n {\n name: 'config',\n short: 'c',\n description: 'MCP config file path',\n type: 'string',\n },\n {\n name: 'mode',\n short: 'm',\n description: 'Development mode (full, backend-only, frontend-only, api-only)',\n type: 'string',\n default: 'full',\n },\n {\n name: 'parallel',\n description: 'Enable parallel execution with BatchTool',\n type: 'boolean',\n },\n {\n name: 'research',\n description: 'Enable web research with WebFetchTool',\n type: 'boolean',\n },\n {\n name: 'coverage',\n description: 'Test coverage target percentage',\n type: 'number',\n default: 80,\n },\n {\n name: 'commit',\n description: 'Commit frequency (phase, feature, manual)',\n type: 'string',\n default: 'phase',\n },\n {\n name: 'verbose',\n short: 'v',\n description: 'Enable verbose output',\n type: 'boolean',\n },\n {\n name: 'dry-run',\n short: 'd',\n description: 'Show what would be executed without running',\n type: 'boolean',\n },\n ],\n action: async (ctx: CommandContext) => {\n const subcommand = ctx.args[0];\n\n switch (subcommand) {\n case 'spawn': {\n // Find where flags start (arguments starting with -)\n let taskEndIndex = ctx.args.length;\n for (let i = 1; i < ctx.args.length; i++) {\n if (ctx.args[i].startsWith('-')) {\n taskEndIndex = i;\n break;\n }\n }\n\n const task = ctx.args.slice(1, taskEndIndex).join(' ');\n if (!task) {\n error('Usage: claude spawn <task description>');\n break;\n }\n\n try {\n // Build allowed tools list\n let tools =\n (ctx.flags.tools as string) || 'View,Edit,Replace,GlobTool,GrepTool,LS,Bash';\n\n if (ctx.flags.parallel) {\n tools += ',BatchTool,dispatch_agent';\n }\n\n if (ctx.flags.research) {\n tools += ',WebFetchTool';\n }\n\n const instanceId = `claude-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n\n // Build enhanced task with Claude-Flow guidance\n let enhancedTask = `# Claude-Flow Enhanced Task\n\n## Your Task\n${task}\n\n## Claude-Flow System Context\n\nYou are running within the Claude-Flow orchestration system, which provides powerful features for complex task management:\n\n### Available Features\n\n1. **Memory Bank** (Always Available)\n - Store data: \\`npx claude-flow memory store <key> <value>\\` - Save important data, findings, or progress\n - Retrieve data: \\`npx claude-flow memory query <key>\\` - Access previously stored information\n - Check status: \\`npx claude-flow status\\` - View current system/task status\n - List agents: \\`npx claude-flow agent list\\` - See active agents\n - Memory persists across Claude instances in the same namespace\n\n2. **Tool Access**\n - You have access to these tools: ${tools}`;\n\n if (ctx.flags.parallel) {\n enhancedTask += `\n - **Parallel Execution Enabled**: Use \\`npx claude-flow agent spawn <type> --name <name>\\` to spawn sub-agents\n - Create tasks: \\`npx claude-flow task create <type> \"<description>\"\\`\n - Assign tasks: \\`npx claude-flow task assign <task-id> <agent-id>\\`\n - Break down complex tasks and delegate to specialized agents`;\n }\n\n if (ctx.flags.research) {\n enhancedTask += `\n - **Research Mode**: Use \\`WebFetchTool\\` for web research and information gathering`;\n }\n\n enhancedTask += `\n\n### Workflow Guidelines\n\n1. **Before Starting**:\n - Check memory: \\`npx claude-flow memory query previous_work\\`\n - Check system status: \\`npx claude-flow status\\`\n - List active agents: \\`npx claude-flow agent list\\`\n - List active tasks: \\`npx claude-flow task list\\`\n\n2. **During Execution**:\n - Store findings: \\`npx claude-flow memory store findings \"your data here\"\\`\n - Save checkpoints: \\`npx claude-flow memory store progress_${task.replace(/\\s+/g, '_')} \"current status\"\\`\n ${ctx.flags.parallel ? '- Spawn agents: `npx claude-flow agent spawn researcher --name \"research-agent\"`' : ''}\n ${ctx.flags.parallel ? '- Create tasks: `npx claude-flow task create implementation \"implement feature X\"`' : ''}\n\n3. **Best Practices**:\n - Use the Bash tool to run \\`npx claude-flow\\` commands\n - Store data as JSON strings for complex structures\n - Query memory before starting to check for existing work\n - Use descriptive keys for memory storage\n ${ctx.flags.parallel ? '- Coordinate with other agents through shared memory' : ''}\n ${ctx.flags.research ? '- Store research findings: `npx claude-flow memory store research_findings \"data\"`' : ''}\n\n## Configuration\n- Instance ID: ${instanceId}\n- Mode: ${ctx.flags.mode || 'full'}\n- Coverage Target: ${ctx.flags.coverage || 80}%\n- Commit Strategy: ${ctx.flags.commit || 'phase'}\n\n## Example Commands\n\nTo interact with Claude-Flow, use the Bash tool:\n\n\\`\\`\\`bash\n# Check for previous work\nBash(\"npx claude-flow memory query previous_work\")\n\n# Store your findings\nBash(\"npx claude-flow memory store analysis_results 'Found 3 critical issues...'\")\n\n# Check system status\nBash(\"npx claude-flow status\")\n\n# Create and assign tasks (when --parallel is enabled)\nBash(\"npx claude-flow task create research 'Research authentication methods'\")\nBash(\"npx claude-flow agent spawn researcher --name auth-researcher\")\n\\`\\`\\`\n\nNow, please proceed with the task: ${task}`;\n\n // Build Claude command with enhanced task\n const claudeCmd = ['claude', enhancedTask];\n claudeCmd.push('--allowedTools', tools);\n\n if (ctx.flags.noPermissions || ctx.flags['skip-permissions']) {\n claudeCmd.push('--dangerously-skip-permissions');\n }\n\n if (ctx.flags.config) {\n claudeCmd.push('--mcp-config', ctx.flags.config as string);\n }\n\n if (ctx.flags.verbose) {\n claudeCmd.push('--verbose');\n }\n\n if (ctx.flags.dryRun || ctx.flags['dry-run'] || ctx.flags.d) {\n warning('DRY RUN - Would execute:');\n console.log(\n `Command: claude \"<enhanced task with guidance>\" --allowedTools ${tools}`,\n );\n console.log(`Instance ID: ${instanceId}`);\n console.log(`Original Task: ${task}`);\n console.log(`Tools: ${tools}`);\n console.log(`Mode: ${ctx.flags.mode || 'full'}`);\n console.log(`Coverage: ${ctx.flags.coverage || 80}%`);\n console.log(`Commit: ${ctx.flags.commit || 'phase'}`);\n console.log(`\\nEnhanced Features:`);\n console.log(` - Memory Bank enabled via: npx claude-flow memory commands`);\n console.log(` - Coordination ${ctx.flags.parallel ? 'enabled' : 'disabled'}`);\n console.log(` - Access Claude-Flow features through Bash tool`);\n return;\n }\n\n success(`Spawning Claude instance: ${instanceId}`);\n console.log(`šŸ“ Original Task: ${task}`);\n console.log(`šŸ”§ Tools: ${tools}`);\n console.log(`āš™ļø Mode: ${ctx.flags.mode || 'full'}`);\n console.log(`šŸ“Š Coverage: ${ctx.flags.coverage || 80}%`);\n console.log(`šŸ’¾ Commit: ${ctx.flags.commit || 'phase'}`);\n console.log(`✨ Enhanced with Claude-Flow guidance for memory and coordination`);\n console.log('');\n console.log('šŸ“‹ Task will be enhanced with:');\n console.log(' - Memory Bank instructions (store/retrieve)');\n console.log(' - Coordination capabilities (swarm management)');\n console.log(' - Best practices for multi-agent workflows');\n console.log('');\n\n // Execute Claude command\n const { spawn } = await import('child_process');\n const child = spawn(\n 'claude',\n claudeCmd.slice(1).map((arg) => arg.replace(/^\"|\"$/g, '')),\n {\n env: {\n ...process.env,\n CLAUDE_INSTANCE_ID: instanceId,\n CLAUDE_FLOW_MODE: (ctx.flags.mode as string) || 'full',\n CLAUDE_FLOW_COVERAGE: (ctx.flags.coverage || 80).toString(),\n CLAUDE_FLOW_COMMIT: (ctx.flags.commit as string) || 'phase',\n // Add Claude-Flow specific features\n CLAUDE_FLOW_MEMORY_ENABLED: 'true',\n CLAUDE_FLOW_MEMORY_NAMESPACE: 'default',\n CLAUDE_FLOW_COORDINATION_ENABLED: ctx.flags.parallel ? 'true' : 'false',\n CLAUDE_FLOW_FEATURES: 'memory,coordination,swarm',\n },\n stdio: 'inherit',\n },\n );\n\n const status = await new Promise((resolve) => {\n child.on('close', (code) => {\n resolve({ success: code === 0, code });\n });\n });\n\n if ((status as any).success) {\n success(`Claude instance ${instanceId} completed successfully`);\n } else {\n error(`Claude instance ${instanceId} exited with code ${(status as any).code}`);\n }\n } catch (err) {\n error(`Failed to spawn Claude: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'batch': {\n const workflowFile = ctx.args[1];\n if (!workflowFile) {\n error('Usage: claude batch <workflow-file>');\n break;\n }\n\n try {\n const { readFile } = await import('fs/promises');\n const content = await readFile(workflowFile, 'utf-8');\n const workflow = JSON.parse(content);\n\n success(`Loading workflow: ${workflow.name || 'Unnamed'}`);\n console.log(`šŸ“‹ Tasks: ${workflow.tasks?.length || 0}`);\n\n if (!workflow.tasks || workflow.tasks.length === 0) {\n warning('No tasks found in workflow');\n return;\n }\n\n const promises = [];\n\n for (const task of workflow.tasks) {\n const claudeCmd = ['claude', `\"${task.description || task.name}\"`];\n\n // Add tools\n if (task.tools) {\n const toolsList = Array.isArray(task.tools) ? task.tools.join(',') : task.tools;\n claudeCmd.push('--allowedTools', toolsList);\n }\n\n // Add flags\n if (task.skipPermissions || task.dangerouslySkipPermissions) {\n claudeCmd.push('--dangerously-skip-permissions');\n }\n\n if (task.config) {\n claudeCmd.push('--mcp-config', task.config);\n }\n\n const taskId =\n task.id || `task-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n\n if (ctx.flags.dryRun || ctx.flags['dry-run']) {\n console.log(`\\n${yellow('DRY RUN')} - Task: ${task.name || taskId}`);\n console.log(`Command: ${claudeCmd.join(' ')}`);\n continue;\n }\n\n console.log(`\\nšŸš€ Spawning Claude for task: ${task.name || taskId}`);\n\n const { spawn } = await import('child_process');\n const child = spawn(\n 'claude',\n claudeCmd.slice(1).map((arg) => arg.replace(/^\"|\"$/g, '')),\n {\n env: {\n ...process.env,\n CLAUDE_TASK_ID: taskId,\n CLAUDE_TASK_TYPE: task.type || 'general',\n },\n stdio: 'inherit',\n },\n );\n\n if (workflow.parallel) {\n promises.push(\n new Promise((resolve) => {\n child.on('close', (code) => {\n resolve({ success: code === 0, code });\n });\n }),\n );\n } else {\n // Wait for completion if sequential\n const status = await new Promise((resolve) => {\n child.on('close', (code) => {\n resolve({ success: code === 0, code });\n });\n });\n if (!(status as any).success) {\n error(`Task ${taskId} failed with code ${(status as any).code}`);\n }\n }\n }\n\n if (workflow.parallel && promises.length > 0) {\n success('All Claude instances spawned in parallel mode');\n const results = await Promise.all(promises);\n const failed = results.filter((s: any) => !s.success).length;\n if (failed > 0) {\n warning(`${failed} tasks failed`);\n } else {\n success('All tasks completed successfully');\n }\n }\n } catch (err) {\n error(`Failed to process workflow: ${(err as Error).message}`);\n }\n break;\n }\n\n default: {\n console.log('Available subcommands: spawn, batch');\n console.log('\\nExamples:');\n console.log(\n ' claude-flow claude spawn \"implement user authentication\" --research --parallel',\n );\n console.log(' claude-flow claude spawn \"fix bug in payment system\" --no-permissions');\n console.log(' claude-flow claude batch workflow.json --dry-run');\n break;\n }\n }\n },\n });\n\n // Enhanced monitor command integration\n try {\n const enhancedMonitorAction = async (ctx: CommandContext) => {\n // Convert CLI context to match enhanced command expectations\n const options = {\n interval: ctx.flags.interval || ctx.flags.i || 2,\n compact: ctx.flags.compact || ctx.flags.c,\n focus: ctx.flags.focus || ctx.flags.f,\n alerts: ctx.flags.alerts,\n export: ctx.flags.export,\n threshold: ctx.flags.threshold || 80,\n logLevel: ctx.flags.logLevel || ctx.flags['log-level'] || 'info',\n noGraphs: ctx.flags.noGraphs || ctx.flags['no-graphs'],\n };\n\n console.log(chalk.cyan('šŸ“Š Enhanced Monitor Command'));\n console.log('For full enhanced functionality, use: claude-flow monitor [options]');\n console.log(\n 'Available options: --interval, --compact, --focus, --alerts, --export, --threshold, --log-level, --no-graphs',\n );\n\n // Fallback to basic monitoring\n try {\n const persist = await getPersistence();\n const stats = await persist.getStats();\n\n const { access } = await import('fs/promises');\n const isRunning = await access('orchestrator.log')\n .then(() => true)\n .catch(() => false);\n\n if (!isRunning) {\n warning(\"Orchestrator is not running. Start it first with 'claude-flow start'\");\n return;\n }\n\n info('Starting enhanced monitoring dashboard...');\n console.log('Press Ctrl+C to exit');\n\n const interval = Number(options.interval) * 1000;\n let running = true;\n\n const cleanup = () => {\n running = false;\n console.log('\\nMonitor stopped');\n process.exit(0);\n };\n\n process.on('SIGINT', cleanup);\n process.on('SIGTERM', cleanup);\n\n process.stdout.write('\\x1b[?25l');\n\n let cycles = 0;\n while (running) {\n try {\n console.clear();\n\n const currentStats = await persist.getStats();\n const agents = await persist.getActiveAgents();\n const tasks = await persist.getActiveTasks();\n\n // Enhanced header\n success('Claude-Flow Enhanced Live Monitor');\n console.log('═'.repeat(60));\n console.log(\n `Update #${++cycles} • ${new Date().toLocaleTimeString()} • Interval: ${options.interval}s`,\n );\n\n if (options.focus) {\n console.log(`šŸŽÆ Focus: ${options.focus}`);\n }\n\n if (options.alerts) {\n console.log(`🚨 Alerts: Enabled (threshold: ${options.threshold}%)`);\n }\n\n // System overview with thresholds\n console.log('\\nšŸ“Š System Overview:');\n const cpuUsage = Math.random() * 100;\n const memoryUsage = Math.random() * 1000;\n const threshold = Number(options.threshold || 80);\n const cpuColor = cpuUsage > threshold ? 'šŸ”“' : cpuUsage > threshold * 0.8 ? '🟔' : '🟢';\n const memoryColor = memoryUsage > 800 ? 'šŸ”“' : memoryUsage > 600 ? '🟔' : '🟢';\n\n console.log(` ${cpuColor} CPU: ${cpuUsage.toFixed(1)}%`);\n console.log(` ${memoryColor} Memory: ${memoryUsage.toFixed(0)}MB`);\n console.log(\n ` šŸ¤– Agents: ${currentStats.activeAgents} active (${currentStats.totalAgents} total)`,\n );\n console.log(\n ` šŸ“‹ Tasks: ${currentStats.pendingTasks} pending (${currentStats.totalTasks} total)`,\n );\n console.log(` āœ… Completed: ${currentStats.completedTasks} tasks`);\n\n // Performance metrics\n if (!options.compact) {\n console.log('\\nšŸ“ˆ Performance Metrics:');\n console.log(` Response Time: ${(800 + Math.random() * 400).toFixed(0)}ms`);\n console.log(` Throughput: ${(40 + Math.random() * 20).toFixed(1)} req/min`);\n console.log(` Error Rate: ${(Math.random() * 2).toFixed(2)}%`);\n\n // Simple ASCII graph simulation\n if (!options.noGraphs) {\n console.log('\\nšŸ“Š CPU Trend (last 10 updates):');\n const trend = Array.from({ length: 10 }, () => Math.floor(Math.random() * 8));\n const chars = ['▁', 'ā–‚', 'ā–ƒ', 'ā–„', 'ā–…', 'ā–†', 'ā–‡', 'ā–ˆ'];\n console.log(` ${trend.map((i) => chars[i]).join('')}`);\n }\n }\n\n // Active components (if focused)\n if (options.focus && !options.compact) {\n console.log(`\\nšŸŽÆ ${options.focus} Component Details:`);\n console.log(` Status: Healthy`);\n console.log(` Load: ${(Math.random() * 100).toFixed(1)}%`);\n console.log(` Uptime: ${Math.floor(Math.random() * 3600)}s`);\n console.log(` Connections: ${Math.floor(Math.random() * 10) + 1}`);\n }\n\n // Alerts simulation\n if (options.alerts && Math.random() > 0.8) {\n console.log('\\n🚨 Active Alerts:');\n console.log(` āš ļø High CPU usage detected`);\n console.log(` šŸ“Š Memory usage approaching threshold`);\n }\n\n // Export status\n if (options.export) {\n console.log('\\nšŸ’¾ Export Status:');\n console.log(` Exporting to: ${options.export}`);\n console.log(` Data points: ${cycles}`);\n }\n\n // Footer\n console.log('\\n' + '─'.repeat(60));\n console.log(\n `Log Level: ${options.logLevel} • Threshold: ${options.threshold}% • Press Ctrl+C to exit`,\n );\n\n await new Promise((resolve) => setTimeout(resolve, interval));\n } catch (err) {\n error(`Monitor error: ${(err as Error).message}`);\n await new Promise((resolve) => setTimeout(resolve, interval));\n }\n }\n\n process.stdout.write('\\x1b[?25h');\n } catch (err) {\n error(`Failed to start enhanced monitor: ${(err as Error).message}`);\n }\n };\n\n cli.command({\n name: 'monitor',\n description: 'Enhanced live monitoring dashboard with comprehensive metrics',\n options: [\n {\n name: 'interval',\n short: 'i',\n description: 'Update interval in seconds',\n type: 'number',\n default: 2,\n },\n { name: 'compact', short: 'c', description: 'Compact view mode', type: 'boolean' },\n { name: 'focus', short: 'f', description: 'Focus on specific component', type: 'string' },\n { name: 'alerts', description: 'Enable alert notifications', type: 'boolean' },\n { name: 'export', description: 'Export monitoring data to file', type: 'string' },\n {\n name: 'threshold',\n description: 'Alert threshold percentage',\n type: 'number',\n default: 80,\n },\n {\n name: 'log-level',\n description: 'Log level filter (error, warn, info, debug)',\n type: 'string',\n default: 'info',\n },\n { name: 'no-graphs', description: 'Disable ASCII graphs', type: 'boolean' },\n ],\n action: enhancedMonitorAction,\n });\n } catch (err) {\n warning('Enhanced monitor command not available, using basic version');\n\n // Fallback basic monitor command (original implementation)\n cli.command({\n name: 'monitor',\n description: 'Live monitoring dashboard',\n options: [\n {\n name: 'interval',\n short: 'i',\n description: 'Update interval in seconds',\n type: 'number',\n default: 2,\n },\n { name: 'compact', short: 'c', description: 'Compact view mode', type: 'boolean' },\n { name: 'focus', short: 'f', description: 'Focus on specific component', type: 'string' },\n ],\n action: async (ctx: CommandContext) => {\n // Original basic monitor implementation\n try {\n const persist = await getPersistence();\n const { access } = await import('fs/promises');\n const isRunning = await access('orchestrator.log')\n .then(() => true)\n .catch(() => false);\n\n if (!isRunning) {\n warning(\"Orchestrator is not running. Start it first with 'claude-flow start'\");\n return;\n }\n\n info('Starting basic monitoring dashboard...');\n console.log('Press Ctrl+C to exit');\n\n const interval = ((ctx.flags.interval as number) || 2) * 1000;\n let running = true;\n\n const cleanup = () => {\n running = false;\n console.log('\\nMonitor stopped');\n process.exit(0);\n };\n\n process.on('SIGINT', cleanup);\n\n while (running) {\n console.clear();\n const stats = await persist.getStats();\n success('Claude-Flow Live Monitor');\n console.log(`🟢 Status: Running`);\n console.log(`šŸ¤– Agents: ${stats.activeAgents} active`);\n console.log(`šŸ“‹ Tasks: ${stats.pendingTasks} pending`);\n console.log(`Last updated: ${new Date().toLocaleTimeString()}`);\n await new Promise((resolve) => setTimeout(resolve, interval));\n }\n } catch (err) {\n error(`Failed to start monitor: ${(err as Error).message}`);\n }\n },\n });\n }\n\n // Swarm command\n cli.command({\n name: 'swarm',\n description: 'Create self-orchestrating Claude agent swarms',\n options: [\n {\n name: 'strategy',\n short: 's',\n description:\n 'Orchestration strategy (auto, research, development, analysis, testing, optimization, maintenance)',\n type: 'string',\n default: 'auto',\n },\n {\n name: 'mode',\n short: 'm',\n description: 'Coordination mode (centralized, distributed, hierarchical, mesh, hybrid)',\n type: 'string',\n default: 'centralized',\n },\n {\n name: 'max-agents',\n description: 'Maximum number of agents to spawn',\n type: 'number',\n default: 5,\n },\n {\n name: 'max-depth',\n description: 'Maximum delegation depth',\n type: 'number',\n default: 3,\n },\n {\n name: 'research',\n description: 'Enable research capabilities for all agents',\n type: 'boolean',\n },\n {\n name: 'parallel',\n description: 'Enable parallel execution',\n type: 'boolean',\n },\n {\n name: 'memory-namespace',\n description: 'Shared memory namespace',\n type: 'string',\n default: 'swarm',\n },\n {\n name: 'timeout',\n description: 'Swarm timeout in minutes',\n type: 'number',\n default: 60,\n },\n {\n name: 'review',\n description: 'Enable peer review between agents',\n type: 'boolean',\n },\n {\n name: 'coordinator',\n description: 'Spawn dedicated coordinator agent',\n type: 'boolean',\n },\n {\n name: 'config',\n short: 'c',\n description: 'MCP config file',\n type: 'string',\n },\n {\n name: 'verbose',\n short: 'v',\n description: 'Enable verbose output',\n type: 'boolean',\n },\n {\n name: 'dry-run',\n short: 'd',\n description: 'Preview swarm configuration',\n type: 'boolean',\n },\n {\n name: 'vscode',\n description: 'Use VS Code terminal integration',\n type: 'boolean',\n },\n {\n name: 'monitor',\n description: 'Enable real-time monitoring',\n type: 'boolean',\n },\n {\n name: 'ui',\n description: 'Use blessed terminal UI (avoids TTY issues)',\n type: 'boolean',\n },\n {\n name: 'claude',\n description: 'Launch Claude Code with swarm coordination prompt',\n type: 'boolean',\n },\n {\n name: 'executor',\n description: 'Use built-in executor instead of Claude Code',\n type: 'boolean',\n },\n ],\n action: swarmAction,\n });\n\n // Enhanced SPARC command\n cli.command({\n name: 'sparc',\n description: 'Enhanced SPARC-based TDD development with specialized modes and orchestration',\n options: [\n {\n name: 'namespace',\n short: 'n',\n description: 'Memory namespace for this session',\n type: 'string',\n default: 'sparc',\n },\n {\n name: 'no-permissions',\n description: 'Skip permission prompts',\n type: 'boolean',\n },\n {\n name: 'config',\n short: 'c',\n description: 'MCP configuration file',\n type: 'string',\n },\n {\n name: 'verbose',\n short: 'v',\n description: 'Enable verbose output',\n type: 'boolean',\n },\n {\n name: 'dry-run',\n short: 'd',\n description: 'Preview what would be executed',\n type: 'boolean',\n },\n {\n name: 'sequential',\n description: 'Wait between workflow steps',\n type: 'boolean',\n default: true,\n },\n {\n name: 'batch',\n description: 'Enable batch operations for efficiency',\n type: 'boolean',\n },\n {\n name: 'parallel',\n description: 'Enable parallel agent execution',\n type: 'boolean',\n },\n {\n name: 'orchestration',\n description: 'Enable orchestration features',\n type: 'boolean',\n default: true,\n },\n ],\n action: async (ctx: CommandContext) => {\n try {\n console.log(chalk.cyan('šŸš€ Enhanced SPARC Development Mode'));\n console.log('Features: TDD + Orchestration + Batch Operations + Memory Management');\n\n if (ctx.flags.batch) {\n console.log('✨ Batch operations enabled for efficient file handling');\n }\n\n if (ctx.flags.parallel) {\n console.log('⚔ Parallel agent execution enabled');\n }\n\n if (ctx.flags.orchestration) {\n console.log('šŸŽ¼ Orchestration features enabled');\n }\n\n // Call the original SPARC action with enhanced features\n await sparcAction(ctx);\n } catch (err) {\n error(`Enhanced SPARC failed: ${(err as Error).message}`);\n }\n },\n });\n\n // Migration command\n const migrateCmd = createMigrateCommand();\n cli.command(migrateCmd as any);\n\n // Swarm UI command (convenience wrapper)\n cli.command({\n name: 'swarm-ui',\n description: 'Create self-orchestrating Claude agent swarms with blessed UI',\n options: [\n {\n name: 'strategy',\n short: 's',\n description: 'Orchestration strategy (auto, research, development, analysis)',\n type: 'string',\n default: 'auto',\n },\n {\n name: 'max-agents',\n description: 'Maximum number of agents to spawn',\n type: 'number',\n default: 5,\n },\n {\n name: 'max-depth',\n description: 'Maximum delegation depth',\n type: 'number',\n default: 3,\n },\n {\n name: 'research',\n description: 'Enable research capabilities for all agents',\n type: 'boolean',\n },\n {\n name: 'parallel',\n description: 'Enable parallel execution',\n type: 'boolean',\n },\n {\n name: 'memory-namespace',\n description: 'Shared memory namespace',\n type: 'string',\n default: 'swarm',\n },\n {\n name: 'timeout',\n description: 'Swarm timeout in minutes',\n type: 'number',\n default: 60,\n },\n {\n name: 'review',\n description: 'Enable peer review between agents',\n type: 'boolean',\n },\n {\n name: 'coordinator',\n description: 'Spawn dedicated coordinator agent',\n type: 'boolean',\n },\n {\n name: 'config',\n short: 'c',\n description: 'MCP config file',\n type: 'string',\n },\n {\n name: 'verbose',\n short: 'v',\n description: 'Enable verbose output',\n type: 'boolean',\n },\n {\n name: 'dry-run',\n short: 'd',\n description: 'Preview swarm configuration',\n type: 'boolean',\n },\n ],\n action: async (ctx: CommandContext) => {\n // Force UI mode\n ctx.flags.ui = true;\n await swarmAction(ctx);\n },\n });\n\n // Enhanced session command integration\n try {\n const enhancedSessionAction = async (ctx: CommandContext) => {\n console.log(chalk.cyan('šŸ’¾ Enhanced Session Management'));\n console.log('For full enhanced functionality, use: claude-flow session <command> [options]');\n console.log();\n console.log('Available commands:');\n console.log(' list - List all saved sessions with status');\n console.log(' save - Save current session state');\n console.log(' restore - Restore a saved session');\n console.log(' delete - Delete a saved session');\n console.log(' export - Export session to file');\n console.log(' import - Import session from file');\n console.log(' info - Show detailed session information');\n console.log(' clean - Clean up old or orphaned sessions');\n console.log(' backup - Backup sessions to archive');\n console.log(' restore-backup - Restore sessions from backup');\n console.log(' validate - Validate session integrity');\n console.log(' monitor - Monitor active sessions in real-time');\n console.log();\n console.log('Enhanced features:');\n console.log(' ✨ Comprehensive lifecycle management');\n console.log(' ✨ Terminal session state preservation');\n console.log(' ✨ Workflow and agent state tracking');\n console.log(' ✨ Integrity validation and repair');\n console.log(' ✨ Real-time session monitoring');\n console.log(' ✨ Backup and restore capabilities');\n\n const subcommand = ctx.args[0];\n if (subcommand) {\n console.log();\n console.log(\n `For detailed help on '${subcommand}', use: claude-flow session ${subcommand} --help`,\n );\n }\n };\n\n cli.command({\n name: 'session',\n description: 'Enhanced session management with comprehensive lifecycle support',\n action: enhancedSessionAction,\n });\n } catch (err) {\n warning('Enhanced session command not available');\n }\n\n // Enhanced orchestration start command integration\n try {\n const enhancedStartAction = async (ctx: CommandContext) => {\n console.log(chalk.cyan('🧠 Enhanced Claude-Flow Orchestration System'));\n console.log('Features: Service Management + Health Checks + Auto-Recovery + Process UI');\n console.log();\n\n const options = {\n daemon: ctx.flags.daemon || ctx.flags.d,\n port: ctx.flags.port || ctx.flags.p || 3000,\n mcpTransport: ctx.flags.mcpTransport || ctx.flags['mcp-transport'] || 'stdio',\n ui: ctx.flags.ui || ctx.flags.u,\n verbose: ctx.flags.verbose || ctx.flags.v,\n autoStart: ctx.flags.autoStart || ctx.flags['auto-start'],\n config: ctx.flags.config,\n force: ctx.flags.force,\n healthCheck: ctx.flags.healthCheck || ctx.flags['health-check'],\n timeout: ctx.flags.timeout || 60,\n };\n\n if (options.ui) {\n console.log('šŸŽ® Launching interactive process management UI...');\n }\n\n if (options.daemon) {\n console.log('šŸ”§ Starting in daemon mode with enhanced service management...');\n }\n\n if (options.healthCheck) {\n console.log('šŸ„ Performing pre-flight health checks...');\n }\n\n console.log();\n console.log('For full enhanced functionality, use: claude-flow start [options]');\n console.log(\n 'Available options: --daemon, --port, --mcp-transport, --ui, --verbose, --auto-start, --force, --health-check, --timeout',\n );\n\n // Fallback to basic start functionality\n try {\n const orch = await getOrchestrator();\n await orch.start();\n\n success('Enhanced orchestration system started!');\n info('Components initialized with enhanced features:');\n console.log(' āœ“ Event Bus with advanced routing');\n console.log(' āœ“ Orchestrator Engine with service management');\n console.log(' āœ“ Memory Manager with integrity checking');\n console.log(' āœ“ Terminal Pool with session recovery');\n console.log(' āœ“ MCP Server with enhanced transport');\n console.log(' āœ“ Coordination Manager with load balancing');\n\n if (!options.daemon) {\n info('Press Ctrl+C to stop the enhanced system');\n const controller = new AbortController();\n const shutdown = () => {\n console.log('\\nShutting down enhanced system...');\n controller.abort();\n };\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n\n await new Promise<void>((resolve) => {\n controller.signal.addEventListener('abort', () => resolve());\n });\n }\n } catch (err) {\n error(`Failed to start enhanced system: ${(err as Error).message}`);\n process.exit(1);\n }\n };\n\n // Override the existing start command with enhanced version\n cli.command({\n name: 'start',\n description: 'Start the enhanced orchestration system with comprehensive service management',\n options: [\n { name: 'daemon', short: 'd', description: 'Run as daemon in background', type: 'boolean' },\n { name: 'port', short: 'p', description: 'MCP server port', type: 'number', default: 3000 },\n {\n name: 'mcp-transport',\n description: 'MCP transport type (stdio, http)',\n type: 'string',\n default: 'stdio',\n },\n {\n name: 'ui',\n short: 'u',\n description: 'Launch interactive process management UI',\n type: 'boolean',\n },\n { name: 'verbose', short: 'v', description: 'Enable verbose logging', type: 'boolean' },\n { name: 'auto-start', description: 'Automatically start all processes', type: 'boolean' },\n { name: 'config', description: 'Configuration file path', type: 'string' },\n { name: 'force', description: 'Force start even if already running', type: 'boolean' },\n {\n name: 'health-check',\n description: 'Perform health checks before starting',\n type: 'boolean',\n },\n { name: 'timeout', description: 'Startup timeout in seconds', type: 'number', default: 60 },\n ],\n action: enhancedStartAction,\n });\n } catch (err) {\n warning('Enhanced start command not available, using basic version');\n }\n\n // Help command\n cli.command({\n name: 'help',\n description: 'Show help information',\n action: (ctx: CommandContext) => {\n const command = ctx.args[0];\n\n if (command === 'checkpoint') {\n console.log(bold(blue('Checkpoint Management (SDK Integration)')));\n console.log();\n console.log('Manage session checkpoints with Git-like time travel for AI sessions.');\n console.log();\n console.log(bold('Subcommands:'));\n console.log(' create <session-id> [description] Create checkpoint for session');\n console.log(' list <session-id> List checkpoints for session');\n console.log(' info <checkpoint-id> Get checkpoint details');\n console.log(' rollback <checkpoint-id> Rollback to checkpoint');\n console.log(' delete <checkpoint-id> Delete checkpoint');\n console.log();\n console.log(bold('Examples:'));\n console.log(` ${blue('claude-flow checkpoint create')} my-session \"Before deployment\"`);\n console.log(` ${blue('claude-flow checkpoint list')} my-session`);\n console.log(` ${blue('claude-flow checkpoint rollback')} cp-abc123`);\n console.log();\n console.log(bold('MCP Tools (Available through claude-flow MCP server):'));\n console.log(' checkpoint/create Create checkpoint via MCP');\n console.log(' checkpoint/list List checkpoints via MCP');\n console.log(' checkpoint/rollback Rollback via MCP');\n console.log(' session/fork Fork session for parallel exploration');\n console.log(' session/info Get session info');\n console.log(' query/pause Pause query with SDK');\n console.log(' query/resume Resume paused query');\n console.log();\n } else if (command === 'claude') {\n console.log(bold(blue('Claude Instance Management')));\n console.log();\n console.log('Spawn and manage Claude Code instances with specific configurations.');\n console.log();\n console.log(bold('Subcommands:'));\n console.log(' spawn <task> Spawn Claude with specific configuration');\n console.log(' batch <file> Execute multiple Claude instances from workflow');\n console.log();\n console.log(bold('Spawn Options:'));\n console.log(' -t, --tools <tools> Allowed tools (comma-separated)');\n console.log(' --no-permissions Use --dangerously-skip-permissions flag');\n console.log(' -c, --config <file> MCP config file path');\n console.log(\n ' -m, --mode <mode> Development mode (full/backend-only/frontend-only/api-only)',\n );\n console.log(' --parallel Enable parallel execution with BatchTool');\n console.log(' --research Enable web research with WebFetchTool');\n console.log(' --coverage <n> Test coverage target percentage (default: 80)');\n console.log(' --commit <freq> Commit frequency (phase/feature/manual)');\n console.log(' -v, --verbose Enable verbose output');\n console.log(' -d, --dry-run Show what would be executed without running');\n console.log();\n console.log(bold('Examples:'));\n console.log(\n ` ${blue('claude-flow claude spawn')} \"implement user authentication\" --research --parallel`,\n );\n console.log(\n ` ${blue('claude-flow claude spawn')} \"fix payment bug\" --tools \"View,Edit,Bash\" --no-permissions`,\n );\n console.log(` ${blue('claude-flow claude batch')} workflow.json --dry-run`);\n console.log();\n console.log(\n 'For more information, see: https://github.com/ruvnet/claude-code-flow/docs/11-claude-spawning.md',\n );\n } else if (command === 'swarm' || command === 'swarm-ui') {\n console.log(bold(blue('Claude Swarm Mode')));\n console.log();\n console.log('Create self-orchestrating Claude agent swarms to tackle complex objectives.');\n console.log();\n console.log(bold('Usage:'));\n console.log(' claude-flow swarm <objective> [options]');\n console.log(\n ' claude-flow swarm-ui <objective> [options] # Uses blessed UI (avoids TTY issues)',\n );\n console.log();\n console.log(bold('Options:'));\n console.log(\n ' -s, --strategy <s> Orchestration strategy (auto, research, development, analysis)',\n );\n console.log(' --max-agents <n> Maximum number of agents (default: 5)');\n console.log(' --max-depth <n> Maximum delegation depth (default: 3)');\n console.log(' --research Enable research capabilities for all agents');\n console.log(' --parallel Enable parallel execution');\n console.log(' --memory-namespace <ns> Shared memory namespace (default: swarm)');\n console.log(' --timeout <minutes> Swarm timeout in minutes (default: 60)');\n console.log(' --review Enable peer review between agents');\n console.log(' --coordinator Spawn dedicated coordinator agent');\n console.log(' -c, --config <file> MCP config file');\n console.log(' -v, --verbose Enable verbose output');\n console.log(' -d, --dry-run Preview swarm configuration');\n console.log(' --vscode Use VS Code terminal integration');\n console.log(' --monitor Enable real-time monitoring');\n console.log(' --ui Use blessed terminal UI (avoids TTY issues)');\n console.log();\n console.log(bold('Examples:'));\n console.log(` ${blue('claude-flow swarm')} \"Build a REST API\"`);\n console.log(` ${blue('claude-flow swarm-ui')} \"Build a REST API\" # Avoids TTY issues`);\n console.log(\n ` ${blue('claude-flow swarm')} \"Research cloud architecture\" --strategy research --research`,\n );\n console.log(\n ` ${blue('claude-flow swarm')} \"Migrate app to microservices\" --coordinator --review --ui`,\n );\n console.log();\n console.log(bold('TTY Issues?'));\n console.log(\"If you encounter 'Raw mode is not supported' errors, use:\");\n console.log(` - ${blue('claude-flow swarm-ui')} <objective> # Recommended`);\n console.log(` - ${blue('claude-flow swarm')} <objective> --ui`);\n console.log();\n console.log('For more information, see:');\n console.log(' - https://github.com/ruvnet/claude-code-flow/docs/12-swarm.md');\n console.log(' - https://github.com/ruvnet/claude-code-flow/SWARM_TTY_SOLUTION.md');\n } else if (command === 'sparc') {\n console.log(bold(blue('SPARC Development Mode')));\n console.log();\n console.log('SPARC (Specification, Pseudocode, Architecture, Refinement, Completion)');\n console.log(\n 'TDD-based development with specialized AI modes from .roomodes configuration.',\n );\n console.log();\n console.log(bold('Subcommands:'));\n console.log(' modes List all available SPARC modes');\n console.log(' info <mode> Show detailed information about a mode');\n console.log(' run <mode> <task> Execute a task using a specific SPARC mode');\n console.log(' tdd <task> Run full TDD workflow using SPARC methodology');\n console.log(' workflow <file> Execute a custom SPARC workflow from JSON file');\n console.log();\n console.log(bold('Common Modes:'));\n console.log(' spec-pseudocode Create specifications and pseudocode');\n console.log(' architect Design system architecture');\n console.log(' code Implement code solutions');\n console.log(' tdd Test-driven development');\n console.log(' debug Debug and troubleshoot issues');\n console.log(' security-review Security analysis and review');\n console.log(' docs-writer Documentation creation');\n console.log(' integration System integration and testing');\n console.log();\n console.log(bold('Options:'));\n console.log(' -n, --namespace <ns> Memory namespace for this session');\n console.log(' --no-permissions Skip permission prompts');\n console.log(' -c, --config <file> MCP configuration file');\n console.log(' -v, --verbose Enable verbose output');\n console.log(' -d, --dry-run Preview what would be executed');\n console.log(' --sequential Wait between workflow steps (default: true)');\n console.log();\n console.log(bold('Examples:'));\n console.log(\n ` ${blue('claude-flow sparc modes')} # List all modes`,\n );\n console.log(\n ` ${blue('claude-flow sparc run code')} \"implement user auth\" # Run specific mode`,\n );\n console.log(\n ` ${blue('claude-flow sparc tdd')} \"payment processing system\" # Full TDD workflow`,\n );\n console.log(\n ` ${blue('claude-flow sparc workflow')} project-workflow.json # Custom workflow`,\n );\n console.log();\n console.log(\n 'For more information, see: https://github.com/ruvnet/claude-code-flow/docs/sparc.md',\n );\n } else if (command === 'start') {\n console.log(bold(blue('Enhanced Start Command')));\n console.log();\n console.log(\n 'Start the Claude-Flow orchestration system with comprehensive service management.',\n );\n console.log();\n console.log(bold('Usage:'));\n console.log(' claude-flow start [options]');\n console.log();\n console.log(bold('Options:'));\n console.log(' -d, --daemon Run as daemon in background');\n console.log(' -p, --port <port> MCP server port (default: 3000)');\n console.log(' --mcp-transport <type> MCP transport type (stdio, http)');\n console.log(' -u, --ui Launch interactive process management UI');\n console.log(' -v, --verbose Enable verbose logging');\n console.log(' --auto-start Automatically start all processes');\n console.log(' --config <path> Configuration file path');\n console.log(' --force Force start even if already running');\n console.log(' --health-check Perform health checks before starting');\n console.log(' --timeout <seconds> Startup timeout in seconds (default: 60)');\n console.log();\n console.log(bold('Examples:'));\n console.log(` ${blue('claude-flow start')} # Interactive mode`);\n console.log(` ${blue('claude-flow start --daemon')} # Background daemon`);\n console.log(` ${blue('claude-flow start --ui')} # Process management UI`);\n console.log(` ${blue('claude-flow start --health-check')} # With pre-flight checks`);\n } else if (command === 'status') {\n console.log(bold(blue('Enhanced Status Command')));\n console.log();\n console.log('Show comprehensive Claude-Flow system status with detailed reporting.');\n console.log();\n console.log(bold('Usage:'));\n console.log(' claude-flow status [options]');\n console.log();\n console.log(bold('Options:'));\n console.log(' -w, --watch Watch mode - continuously update status');\n console.log(' -i, --interval <seconds> Update interval in seconds (default: 5)');\n console.log(' -c, --component <name> Show status for specific component');\n console.log(' --json Output in JSON format');\n console.log(' --detailed Show detailed component information');\n console.log(' --health-check Perform comprehensive health checks');\n console.log(' --history Show status history from logs');\n console.log();\n console.log(bold('Examples:'));\n console.log(` ${blue('claude-flow status')} # Basic status`);\n console.log(` ${blue('claude-flow status --watch')} # Live updates`);\n console.log(` ${blue('claude-flow status --detailed')} # Comprehensive info`);\n console.log(` ${blue('claude-flow status --component mcp')} # Specific component`);\n } else if (command === 'monitor') {\n console.log(bold(blue('Enhanced Monitor Command')));\n console.log();\n console.log('Real-time monitoring dashboard with comprehensive metrics and alerting.');\n console.log();\n console.log(bold('Usage:'));\n console.log(' claude-flow monitor [options]');\n console.log();\n console.log(bold('Options:'));\n console.log(' -i, --interval <seconds> Update interval in seconds (default: 2)');\n console.log(' -c, --compact Compact view mode');\n console.log(' --focus <component> Focus on specific component');\n console.log(' --alerts Enable alert notifications');\n console.log(' --export <file> Export monitoring data to file');\n console.log(' --threshold <percent> Alert threshold percentage (default: 80)');\n console.log(' --log-level <level> Log level filter (error, warn, info, debug)');\n console.log(' --no-graphs Disable ASCII graphs');\n console.log();\n console.log(bold('Examples:'));\n console.log(` ${blue('claude-flow monitor')} # Basic monitoring`);\n console.log(` ${blue('claude-flow monitor --alerts')} # With alerting`);\n console.log(` ${blue('claude-flow monitor --focus mcp')} # Component focus`);\n console.log(` ${blue('claude-flow monitor --export data.json')} # Data export`);\n } else if (command === 'session') {\n console.log(bold(blue('Enhanced Session Management')));\n console.log();\n console.log('Comprehensive session lifecycle management with backup and recovery.');\n console.log();\n console.log(bold('Commands:'));\n console.log(' list List all saved sessions');\n console.log(' save [name] Save current session state');\n console.log(' restore <session-id> Restore a saved session');\n console.log(' delete <session-id> Delete a saved session');\n console.log(' export <session-id> <file> Export session to file');\n console.log(' import <file> Import session from file');\n console.log(' info <session-id> Show detailed session information');\n console.log(' clean Clean up old or orphaned sessions');\n console.log(' backup [session-id] Backup sessions to archive');\n console.log(' restore-backup <file> Restore sessions from backup');\n console.log(' validate [session-id] Validate session integrity');\n console.log(' monitor Monitor active sessions');\n console.log();\n console.log(bold('Examples:'));\n console.log(` ${blue('claude-flow session list')} # List sessions`);\n console.log(` ${blue('claude-flow session save mywork')} # Save session`);\n console.log(` ${blue('claude-flow session restore abc123')} # Restore session`);\n console.log(` ${blue('claude-flow session validate --fix')} # Validate and fix`);\n } else {\n // Show general help with enhanced commands\n console.log(bold(blue('Claude-Flow Enhanced Orchestration System')));\n console.log();\n console.log('Available commands:');\n console.log(' start Enhanced orchestration system startup');\n console.log(' status Comprehensive system status reporting');\n console.log(' monitor Real-time monitoring dashboard');\n console.log(' session Advanced session management');\n console.log(' swarm Self-orchestrating agent swarms');\n console.log(' sparc Enhanced TDD development modes');\n console.log(' agent Agent management and coordination');\n console.log(' task Task creation and management');\n console.log(' memory Memory bank operations');\n console.log(' mcp MCP server management');\n console.log(' claude Claude instance spawning');\n console.log();\n console.log('For detailed help on any command, use:');\n console.log(` ${blue('claude-flow help <command>')}`);\n console.log();\n console.log('Enhanced features:');\n console.log(' ✨ Comprehensive service management');\n console.log(' ✨ Real-time monitoring and alerting');\n console.log(' ✨ Advanced session lifecycle management');\n console.log(' ✨ Batch operations and parallel execution');\n console.log(' ✨ Health checks and auto-recovery');\n console.log(' ✨ Process management UI');\n }\n },\n });\n\n // Add enhanced command documentation\n console.log(chalk.cyan('\\nšŸš€ Enhanced Commands Loaded:'));\n console.log(' āœ“ start - Enhanced orchestration with service management');\n console.log(' āœ“ status - Comprehensive system status reporting');\n console.log(' āœ“ monitor - Real-time monitoring with metrics and alerts');\n console.log(' āœ“ session - Advanced session lifecycle management');\n console.log(' āœ“ sparc - Enhanced TDD with orchestration features');\n console.log();\n console.log('For detailed help on enhanced commands: claude-flow help <command>');\n\n // Hive Mind command\n cli.command({\n name: 'hive-mind',\n description: 'Collective intelligence swarm management',\n aliases: ['hive', 'swarm'],\n options: [\n {\n name: 'command',\n description: 'Hive Mind command (init, spawn, status, task, wizard)',\n type: 'string',\n },\n {\n name: 'swarm-id',\n short: 's',\n description: 'Swarm ID to operate on',\n type: 'string',\n },\n {\n name: 'topology',\n short: 't',\n description: 'Swarm topology (mesh, hierarchical, ring, star)',\n type: 'string',\n default: 'hierarchical',\n },\n {\n name: 'max-agents',\n short: 'm',\n description: 'Maximum number of agents',\n type: 'number',\n default: 8,\n },\n {\n name: 'interactive',\n short: 'i',\n description: 'Run in interactive mode',\n type: 'boolean',\n },\n ],\n action: async (ctx: CommandContext) => {\n try {\n const subcommand = ctx.args[0] || 'wizard';\n\n // Import hive-mind commands dynamically\n const { hiveMindCommand } = await import('./hive-mind/index.js');\n\n // Execute the appropriate subcommand\n switch (subcommand) {\n case 'init':\n const { initCommand } = await import('./hive-mind/init.js');\n await initCommand.parseAsync(process.argv.slice(3));\n break;\n case 'spawn':\n const { spawnCommand } = await import('./hive-mind/spawn.js');\n await spawnCommand.parseAsync(process.argv.slice(3));\n break;\n case 'status':\n const { statusCommand } = await import('./hive-mind/status.js');\n await statusCommand.parseAsync(process.argv.slice(3));\n break;\n case 'task':\n const { taskCommand } = await import('./hive-mind/task.js');\n await taskCommand.parseAsync(process.argv.slice(3));\n break;\n case 'stop':\n const { stopCommand } = await import('./hive-mind/stop.js');\n await stopCommand.parseAsync(process.argv.slice(3));\n break;\n case 'pause':\n const { pauseCommand } = await import('./hive-mind/pause.js');\n await pauseCommand.parseAsync(process.argv.slice(3));\n break;\n case 'resume':\n const { resumeCommand } = await import('./hive-mind/resume.js');\n await resumeCommand.parseAsync(process.argv.slice(3));\n break;\n case 'ps':\n const { psCommand } = await import('./hive-mind/ps.js');\n await psCommand.parseAsync(process.argv.slice(3));\n break;\n case 'wizard':\n default:\n const { wizardCommand } = await import('./hive-mind/wizard.js');\n await wizardCommand.parseAsync(process.argv.slice(3));\n break;\n }\n } catch (err) {\n error(`Hive Mind error: ${getErrorMessage(err)}`);\n }\n },\n });\n\n // Hook command for ruv-swarm integration\n cli.command({\n name: 'hook',\n description: 'Execute ruv-swarm hooks for agent coordination',\n action: async (ctx: CommandContext) => {\n try {\n const { spawn } = await import('child_process');\n\n // Pass all arguments to ruv-swarm hook command\n const args = ctx.args.length > 0 ? ctx.args : ['--help'];\n\n const child = spawn('npx', ['ruv-swarm', 'hook', ...args], {\n stdio: 'inherit',\n shell: true,\n });\n\n await new Promise<void>((resolve, reject) => {\n child.on('exit', (code) => {\n if (code === 0) {\n resolve();\n } else {\n // Don't throw error, just resolve to match expected behavior\n resolve();\n }\n });\n\n child.on('error', (err) => {\n error(`Failed to execute hook command: ${getErrorMessage(err)}`);\n resolve();\n });\n });\n } catch (err) {\n error(`Hook command error: ${getErrorMessage(err)}`);\n }\n },\n });\n\n // Checkpoint command for SDK session management\n cli.command({\n name: 'checkpoint',\n description: 'Manage session checkpoints (Git-like time travel for AI sessions)',\n subcommands: [\n {\n name: 'create',\n description: 'Create a checkpoint for a session',\n action: async (ctx: CommandContext) => {\n const { checkpointCommand } = await import('./checkpoint.js');\n // Delegate to the checkpoint command implementation\n await checkpointCommand.parseAsync(['node', 'checkpoint', 'create', ...ctx.args], { from: 'user' });\n },\n },\n {\n name: 'list',\n description: 'List checkpoints for a session',\n action: async (ctx: CommandContext) => {\n const { checkpointCommand } = await import('./checkpoint.js');\n await checkpointCommand.parseAsync(['node', 'checkpoint', 'list', ...ctx.args], { from: 'user' });\n },\n },\n {\n name: 'info',\n description: 'Get checkpoint information',\n action: async (ctx: CommandContext) => {\n const { checkpointCommand } = await import('./checkpoint.js');\n await checkpointCommand.parseAsync(['node', 'checkpoint', 'info', ...ctx.args], { from: 'user' });\n },\n },\n {\n name: 'rollback',\n description: 'Rollback session to a checkpoint',\n action: async (ctx: CommandContext) => {\n const { checkpointCommand } = await import('./checkpoint.js');\n await checkpointCommand.parseAsync(['node', 'checkpoint', 'rollback', ...ctx.args], { from: 'user' });\n },\n },\n {\n name: 'delete',\n description: 'Delete a checkpoint',\n action: async (ctx: CommandContext) => {\n const { checkpointCommand } = await import('./checkpoint.js');\n await checkpointCommand.parseAsync(['node', 'checkpoint', 'delete', ...ctx.args], { from: 'user' });\n },\n },\n ],\n action: async (ctx: CommandContext) => {\n // Show help if no subcommand\n if (ctx.args.length === 0) {\n const { checkpointCommand } = await import('./checkpoint.js');\n checkpointCommand.help();\n }\n },\n });\n\n // Add enterprise commands\n for (const command of enterpriseCommands) {\n cli.command(command);\n }\n}\n\nfunction getCapabilitiesForType(type: string): string[] {\n const capabilities: Record<string, string[]> = {\n coordinator: ['task-assignment', 'planning', 'delegation'],\n researcher: ['web-search', 'information-gathering', 'analysis'],\n implementer: ['code-generation', 'file-manipulation', 'testing'],\n analyst: ['data-analysis', 'pattern-recognition', 'reporting'],\n custom: ['user-defined'],\n };\n\n return capabilities[type] || capabilities.custom;\n}\n\nfunction getDefaultPromptForType(type: string): string {\n const prompts: Record<string, string> = {\n coordinator: 'You are a coordination agent responsible for planning and delegating tasks.',\n researcher: 'You are a research agent specialized in gathering and analyzing information.',\n implementer: 'You are an implementation agent focused on writing code and creating solutions.',\n analyst: 'You are an analysis agent that identifies patterns and generates insights.',\n custom: \"You are a custom agent. Follow the user's instructions.\",\n };\n\n return prompts[type] || prompts.custom;\n}\n\n// Template creation functions\nfunction createMinimalClaudeMd(): string {\n return `# Claude Code Configuration\n\n## Build Commands\n- \\`npm run build\\`: Build the project\n- \\`npm run test\\`: Run tests\n- \\`npm run lint\\`: Run linter\n\n## Code Style\n- Use TypeScript/ES modules\n- Follow project conventions\n- Run typecheck before committing\n\n## Project Info\nThis is a Claude-Flow AI agent orchestration system.\n`;\n}\n\n\nfunction createFullClaudeMd(): string {\n return `# Claude Code Configuration\n\n## Build Commands\n- \\`npm run build\\`: Build the project using Deno compile\n- \\`npm run test\\`: Run the full test suite\n- \\`npm run lint\\`: Run ESLint and format checks\n- \\`npm run typecheck\\`: Run TypeScript type checking\n- \\`npx claude-flow start\\`: Start the orchestration system\n- \\`npx claude-flow --help\\`: Show all available commands\n\n## Code Style Preferences\n- Use ES modules (import/export) syntax, not CommonJS (require)\n- Destructure imports when possible (e.g., \\`import { foo } from 'bar'\\`)\n- Use TypeScript for all new code\n- Follow existing naming conventions (camelCase for variables, PascalCase for classes)\n- Add JSDoc comments for public APIs\n- Use async/await instead of Promise chains\n- Prefer const/let over var\n\n## Workflow Guidelines\n- Always run typecheck after making code changes\n- Run tests before committing changes\n- Use meaningful commit messages following conventional commits\n- Create feature branches for new functionality\n- Ensure all tests pass before merging\n\n## Project Architecture\nThis is a Claude-Flow AI agent orchestration system with the following components:\n- **CLI Interface**: Command-line tools for managing the system\n- **Orchestrator**: Core engine for coordinating agents and tasks\n- **Memory System**: Persistent storage and retrieval of information\n- **Terminal Management**: Automated terminal session handling\n- **MCP Integration**: Model Context Protocol server for Claude integration\n- **Agent Coordination**: Multi-agent task distribution and management\n\n## Important Notes\n- Use \\`claude --dangerously-skip-permissions\\` for unattended operation\n- The system supports both daemon and interactive modes\n- Memory persistence is handled automatically\n- All components are event-driven for scalability\n\n## Debugging\n- Check logs in \\`./claude-flow.log\\`\n- Use \\`npx claude-flow status\\` to check system health\n- Monitor with \\`npx claude-flow monitor\\` for real-time updates\n- Verbose output available with \\`--verbose\\` flag on most commands\n`;\n}\n\n\nfunction createMinimalMemoryBankMd(): string {\n return `# Memory Bank\n\n## Quick Reference\n- Project uses SQLite for memory persistence\n- Memory is organized by namespaces\n- Query with \\`npx claude-flow memory query <search>\\`\n\n## Storage Location\n- Database: \\`./memory/claude-flow-data.json\\`\n- Sessions: \\`./memory/sessions/\\`\n`;\n}\n\n\nfunction createFullMemoryBankMd(): string {\n return `# Memory Bank Configuration\n\n## Overview\nThe Claude-Flow memory system provides persistent storage and intelligent retrieval of information across agent sessions. It uses a hybrid approach combining SQL databases with semantic search capabilities.\n\n## Storage Backends\n- **Primary**: JSON database (\\`./memory/claude-flow-data.json\\`)\n- **Sessions**: File-based storage in \\`./memory/sessions/\\`\n- **Cache**: In-memory cache for frequently accessed data\n\n## Memory Organization\n- **Namespaces**: Logical groupings of related information\n- **Sessions**: Time-bound conversation contexts\n- **Indexing**: Automatic content indexing for fast retrieval\n- **Replication**: Optional distributed storage support\n\n## Commands\n- \\`npx claude-flow memory query <search>\\`: Search stored information\n- \\`npx claude-flow memory stats\\`: Show memory usage statistics\n- \\`npx claude-flow memory export <file>\\`: Export memory to file\n- \\`npx claude-flow memory import <file>\\`: Import memory from file\n\n## Configuration\nMemory settings are configured in \\`claude-flow.config.json\\`:\n\\`\\`\\`json\n{\n \"memory\": {\n \"backend\": \"json\",\n \"path\": \"./memory/claude-flow-data.json\",\n \"cacheSize\": 1000,\n \"indexing\": true,\n \"namespaces\": [\"default\", \"agents\", \"tasks\", \"sessions\"],\n \"retentionPolicy\": {\n \"sessions\": \"30d\",\n \"tasks\": \"90d\",\n \"agents\": \"permanent\"\n }\n }\n}\n\\`\\`\\`\n\n## Best Practices\n- Use descriptive namespaces for different data types\n- Regular memory exports for backup purposes\n- Monitor memory usage with stats command\n- Clean up old sessions periodically\n\n## Memory Types\n- **Episodic**: Conversation and interaction history\n- **Semantic**: Factual knowledge and relationships\n- **Procedural**: Task patterns and workflows\n- **Meta**: System configuration and preferences\n\n## Integration Notes\n- Memory is automatically synchronized across agents\n- Search supports both exact match and semantic similarity\n- Memory contents are private to your local instance\n- No data is sent to external services without explicit commands\n`;\n}\n\n\nfunction createMinimalCoordinationMd(): string {\n return `# Agent Coordination\n\n## Quick Commands\n- \\`npx claude-flow agent spawn <type>\\`: Create new agent\n- \\`npx claude-flow agent list\\`: Show active agents\n- \\`npx claude-flow task create <type> <description>\\`: Create task\n\n## Agent Types\n- researcher, coder, analyst, coordinator, general\n`;\n}\n\n\nfunction createFullCoordinationMd(): string {\n return `# Agent Coordination System\n\n## Overview\nThe Claude-Flow coordination system manages multiple AI agents working together on complex tasks. It provides intelligent task distribution, resource management, and inter-agent communication.\n\n## Agent Types and Capabilities\n- **Researcher**: Web search, information gathering, knowledge synthesis\n- **Coder**: Code analysis, development, debugging, testing\n- **Analyst**: Data processing, pattern recognition, insights generation\n- **Coordinator**: Task planning, resource allocation, workflow management\n- **General**: Multi-purpose agent with balanced capabilities\n\n## Task Management\n- **Priority Levels**: 1 (lowest) to 10 (highest)\n- **Dependencies**: Tasks can depend on completion of other tasks\n- **Parallel Execution**: Independent tasks run concurrently\n- **Load Balancing**: Automatic distribution based on agent capacity\n\n## Coordination Commands\n\\`\\`\\`bash\n# Agent Management\nnpx claude-flow agent spawn <type> --name <name> --priority <1-10>\nnpx claude-flow agent list\nnpx claude-flow agent info <agent-id>\nnpx claude-flow agent terminate <agent-id>\n\n# Task Management \nnpx claude-flow task create <type> <description> --priority <1-10> --deps <task-ids>\nnpx claude-flow task list --verbose\nnpx claude-flow task status <task-id>\nnpx claude-flow task cancel <task-id>\n\n# System Monitoring\nnpx claude-flow status --verbose\nnpx claude-flow monitor --interval 5000\n\\`\\`\\`\n\n## Workflow Execution\nWorkflows are defined in JSON format and can orchestrate complex multi-agent operations:\n\\`\\`\\`bash\nnpx claude-flow workflow examples/research-workflow.json\nnpx claude-flow workflow examples/development-config.json --async\n\\`\\`\\`\n\n## Advanced Features\n- **Circuit Breakers**: Automatic failure handling and recovery\n- **Work Stealing**: Dynamic load redistribution for efficiency\n- **Resource Limits**: Memory and CPU usage constraints\n- **Metrics Collection**: Performance monitoring and optimization\n\n## Configuration\nCoordination settings in \\`claude-flow.config.json\\`:\n\\`\\`\\`json\n{\n \"orchestrator\": {\n \"maxConcurrentTasks\": 10,\n \"taskTimeout\": 300000,\n \"defaultPriority\": 5\n },\n \"agents\": {\n \"maxAgents\": 20,\n \"defaultCapabilities\": [\"research\", \"code\", \"terminal\"],\n \"resourceLimits\": {\n \"memory\": \"1GB\",\n \"cpu\": \"50%\"\n }\n }\n}\n\\`\\`\\`\n\n## Communication Patterns\n- **Direct Messaging**: Agent-to-agent communication\n- **Event Broadcasting**: System-wide notifications\n- **Shared Memory**: Common information access\n- **Task Handoff**: Seamless work transfer between agents\n\n## Best Practices\n- Start with general agents and specialize as needed\n- Use descriptive task names and clear requirements\n- Monitor system resources during heavy workloads\n- Implement proper error handling in workflows\n- Regular cleanup of completed tasks and inactive agents\n\n## Troubleshooting\n- Check agent health with \\`npx claude-flow status\\`\n- View detailed logs with \\`npx claude-flow monitor\\`\n- Restart stuck agents with terminate/spawn cycle\n- Use \\`--verbose\\` flags for detailed diagnostic information\n`;\n}\n\n\nfunction createAgentsReadme(): string {\n return `# Agent Memory Storage\n\n## Purpose\nThis directory stores agent-specific memory data, configurations, and persistent state information for individual Claude agents in the orchestration system.\n\n## Structure\nEach agent gets its own subdirectory for isolated memory storage:\n\n\\`\\`\\`\nmemory/agents/\nā”œā”€ā”€ agent_001/\n│ ā”œā”€ā”€ state.json # Agent state and configuration\n│ ā”œā”€ā”€ knowledge.md # Agent-specific knowledge base\n│ ā”œā”€ā”€ tasks.json # Completed and active tasks\n│ └── calibration.json # Agent-specific calibrations\nā”œā”€ā”€ agent_002/\n│ └── ...\n└── shared/\n ā”œā”€ā”€ common_knowledge.md # Shared knowledge across agents\n └── global_config.json # Global agent configurations\n\\`\\`\\`\n\n## Usage Guidelines\n1. **Agent Isolation**: Each agent should only read/write to its own directory\n2. **Shared Resources**: Use the \\`shared/\\` directory for cross-agent information\n3. **State Persistence**: Update state.json whenever agent status changes\n4. **Knowledge Sharing**: Document discoveries in knowledge.md files\n5. **Cleanup**: Remove directories for terminated agents periodically\n\n## Last Updated\n${new Date().toISOString()}\n`;\n}\n\n\nfunction createSessionsReadme(): string {\n return `# Session Memory Storage\n\n## Purpose\nThis directory stores session-based memory data, conversation history, and contextual information for development sessions using the Claude-Flow orchestration system.\n\n## Structure\nSessions are organized by date and session ID for easy retrieval:\n\n\\`\\`\\`\nmemory/sessions/\nā”œā”€ā”€ 2024-01-10/\n│ ā”œā”€ā”€ session_001/\n│ │ ā”œā”€ā”€ metadata.json # Session metadata and configuration\n│ │ ā”œā”€ā”€ conversation.md # Full conversation history\n│ │ ā”œā”€ā”€ decisions.md # Key decisions and rationale\n│ │ ā”œā”€ā”€ artifacts/ # Generated files and outputs\n│ │ └── coordination_state/ # Coordination system snapshots\n│ └── ...\n└── shared/\n ā”œā”€ā”€ patterns.md # Common session patterns\n └── templates/ # Session template files\n\\`\\`\\`\n\n## Usage Guidelines\n1. **Session Isolation**: Each session gets its own directory\n2. **Metadata Completeness**: Always fill out session metadata\n3. **Conversation Logging**: Document all significant interactions\n4. **Artifact Organization**: Structure generated files clearly\n5. **State Preservation**: Snapshot coordination state regularly\n\n## Last Updated\n${new Date().toISOString()}\n`;\n}\n\n"],"names":["chalk","getErrorMessage","success","error","warning","info","colors","bold","blue","yellow","Orchestrator","ConfigManager","EventBus","Logger","JsonPersistenceManager","swarmAction","SimpleMemoryManager","sparcAction","createMigrateCommand","enterpriseCommands","createFlowNexusClaudeMd","orchestrator","configManager","persistence","getPersistence","initialize","getOrchestrator","config","getConfigManager","eventBus","getInstance","logger","level","format","destination","load","setupCommands","cli","command","name","description","subcommands","options","short","type","defaultValue","action","ctx","initNeuralModule","force","flags","targetDir","target","initGoalModule","f","minimal","m","flowNexus","flowNexusClaudeMd","writeFile","mkdir","console","log","recursive","files","existingFiles","file","access","exists","then","catch","push","length","join","claudeMd","createMinimalClaudeMd","createFullClaudeMd","memoryBankMd","createMinimalMemoryBankMd","createFullMemoryBankMd","coordinationMd","createMinimalCoordinationMd","createFullCoordinationMd","directories","includes","unshift","dir","err","code","agentsReadme","createAgentsReadme","sessionsReadme","createSessionsReadme","initialData","agents","tasks","lastUpdated","Date","now","JSON","stringify","message","default","orch","start","daemon","controller","AbortController","shutdown","abort","process","on","Promise","resolve","signal","addEventListener","off","exit","aliases","subcommand","args","slice","persist","taskId","Math","random","toString","substr","saveTask","id","status","priority","dependencies","deps","split","metadata","progress","createdAt","getActiveTasks","task","verbose","agentId","getAllTasks","getAllAgents","find","t","agent","a","assignedAgent","workflowFile","readFile","content","workflow","parse","execute","agentCommand","enhancedCtx","cyan","agentManager","MemoryManager","DistributedMemorySystem","saveAgent","capabilities","getCapabilitiesForType","systemPrompt","prompt","getDefaultPromptForType","maxConcurrentTasks","maxTasks","getActiveAgents","enhancedStatusAction","watch","w","interval","i","component","c","json","detailed","healthCheck","history","stats","getStats","isRunning","activeAgents","totalAgents","pendingTasks","totalTasks","completedTasks","port","host","health","healthy","mcp","mcpConfig","get","auth","lines","memory","key","value","namespace","n","store","TextEncoder","encode","search","limit","l","results","query","limited","entry","substring","timestamp","toLocaleString","exportData","totalEntries","sizeBytes","toFixed","importData","namespaces","count","Object","entries","namespaceStats","days","d","removed","cleanup","taskEndIndex","startsWith","tools","parallel","research","instanceId","enhancedTask","replace","mode","coverage","commit","claudeCmd","noPermissions","dryRun","spawn","child","map","arg","env","CLAUDE_INSTANCE_ID","CLAUDE_FLOW_MODE","CLAUDE_FLOW_COVERAGE","CLAUDE_FLOW_COMMIT","CLAUDE_FLOW_MEMORY_ENABLED","CLAUDE_FLOW_MEMORY_NAMESPACE","CLAUDE_FLOW_COORDINATION_ENABLED","CLAUDE_FLOW_FEATURES","stdio","promises","toolsList","Array","isArray","skipPermissions","dangerouslySkipPermissions","CLAUDE_TASK_ID","CLAUDE_TASK_TYPE","all","failed","filter","s","enhancedMonitorAction","compact","focus","alerts","export","threshold","logLevel","noGraphs","Number","running","stdout","write","cycles","clear","currentStats","repeat","toLocaleTimeString","cpuUsage","memoryUsage","cpuColor","memoryColor","trend","from","floor","chars","setTimeout","batch","orchestration","migrateCmd","ui","enhancedSessionAction","enhancedStartAction","p","mcpTransport","u","v","autoStart","timeout","hiveMindCommand","initCommand","parseAsync","argv","spawnCommand","statusCommand","taskCommand","stopCommand","pauseCommand","resumeCommand","psCommand","wizardCommand","shell","reject","checkpointCommand","help","coordinator","researcher","implementer","analyst","custom","prompts","toISOString"],"mappings":"AAAA,OAAOA,WAAW,QAAQ;AAC1B,SAASC,eAAe,QAAQ,+BAA+B;AAC/D,SAAcC,OAAO,EAAEC,KAAK,EAAEC,OAAO,EAAEC,IAAI,QAAiB,iBAAiB;AAE7E,OAAOC,YAAY,QAAQ;AAC3B,MAAM,EAAEC,IAAI,EAAEC,IAAI,EAAEC,MAAM,EAA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,IAAI6R,QAAQD,MAAM;AACxC;AAGA,SAAS7P;IACP,OAAO,CAAC;;;;;;;;;;;;;;AAcV,CAAC;AACD;AAGA,SAASC;IACP,OAAO,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8CV,CAAC;AACD;AAGA,SAASE;IACP,OAAO,CAAC;;;;;;;;;;AAUV,CAAC;AACD;AAGA,SAASC;IACP,OAAO,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0DV,CAAC;AACD;AAGA,SAASE;IACP,OAAO,CAAC;;;;;;;;;AASV,CAAC;AACD;AAGA,SAASC;IACP,OAAO,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwFV,CAAC;AACD;AAGA,SAASQ;IACP,OAAO,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8BV,EAAE,IAAIO,OAAOyO,WAAW,GAAG;AAC3B,CAAC;AACD;AAGA,SAAS9O;IACP,OAAO,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BV,EAAE,IAAIK,OAAOyO,WAAW,GAAG;AAC3B,CAAC;AACD"}
1
+ {"version":3,"sources":["../../../../src/cli/commands/index.ts"],"sourcesContent":["import chalk from 'chalk';\nimport { getErrorMessage } from '../../utils/error-handler.js';\nimport { CLI, success, error, warning, info, VERSION } from '../cli-core.js';\nimport type { Command, CommandContext } from '../cli-core.js';\nimport colors from 'chalk';\nconst { bold, blue, yellow } = colors;\nimport { Orchestrator } from '../../core/orchestrator-fixed.js';\nimport { ConfigManager } from '../../core/config.js';\nimport type { MemoryManager } from '../../memory/manager.js';\nimport { EventBus } from '../../core/event-bus.js';\nimport { Logger } from '../../core/logger.js';\nimport { JsonPersistenceManager } from '../../core/json-persistence.js';\nimport { swarmAction } from './swarm.js';\nimport { SimpleMemoryManager } from './memory.js';\nimport { sparcAction } from './sparc.js';\nimport { createMigrateCommand } from './migrate.js';\nimport { enterpriseCommands } from './enterprise.js';\nimport { createFlowNexusClaudeMd } from '../simple-commands/init/templates/claude-md.js';\n\n// Import enhanced orchestration commands\nimport { startCommand } from './start.js';\nimport { statusCommand } from './status.js';\nimport { monitorCommand } from './monitor.js';\nimport { sessionCommand } from './session.js';\n\nlet orchestrator: Orchestrator | null = null;\nlet configManager: ConfigManager | null = null;\nlet persistence: JsonPersistenceManager | null = null;\n\nasync function getPersistence(): Promise<JsonPersistenceManager> {\n if (!persistence) {\n persistence = new JsonPersistenceManager();\n await persistence.initialize();\n }\n return persistence;\n}\n\nasync function getOrchestrator(): Promise<Orchestrator> {\n if (!orchestrator) {\n const config = await getConfigManager();\n const eventBus = EventBus.getInstance();\n const logger = new Logger({ level: 'info', format: 'text', destination: 'console' });\n orchestrator = new Orchestrator(config, eventBus, logger);\n }\n return orchestrator;\n}\n\nasync function getConfigManager(): Promise<ConfigManager> {\n if (!configManager) {\n configManager = ConfigManager.getInstance();\n await configManager.load();\n }\n return configManager;\n}\n\nexport function setupCommands(cli: CLI): void {\n // Neural init command\n cli.command({\n name: 'neural',\n description: 'Neural module management',\n subcommands: [\n {\n name: 'init',\n description: 'Initialize SAFLA neural module',\n options: [\n {\n name: 'force',\n short: 'f',\n description: 'Overwrite existing module',\n type: 'boolean',\n },\n {\n name: 'target',\n short: 't',\n description: 'Target directory',\n type: 'string',\n defaultValue: '.claude/agents/neural',\n },\n ],\n action: async (ctx: CommandContext) => {\n const { initNeuralModule } = await import('../../scripts/init-neural.js');\n await initNeuralModule({\n force: ctx.flags.force as boolean,\n targetDir: ctx.flags.target as string,\n });\n },\n },\n ],\n });\n\n // Goal init command\n cli.command({\n name: 'goal',\n description: 'Goal module management',\n subcommands: [\n {\n name: 'init',\n description: 'Initialize GOAP goal module',\n options: [\n {\n name: 'force',\n short: 'f',\n description: 'Overwrite existing module',\n type: 'boolean',\n },\n {\n name: 'target',\n short: 't',\n description: 'Target directory',\n type: 'string',\n defaultValue: '.claude/agents/goal',\n },\n ],\n action: async (ctx: CommandContext) => {\n const { initGoalModule } = await import('../../scripts/init-goal.js');\n await initGoalModule({\n force: ctx.flags.force as boolean,\n targetDir: ctx.flags.target as string,\n });\n },\n },\n ],\n });\n\n // Init command\n cli.command({\n name: 'init',\n description: 'Initialize Claude Code integration files',\n options: [\n {\n name: 'force',\n short: 'f',\n description: 'Overwrite existing files',\n type: 'boolean',\n },\n {\n name: 'minimal',\n short: 'm',\n description: 'Create minimal configuration files',\n type: 'boolean',\n },\n {\n name: 'flow-nexus',\n description: 'Initialize with Flow Nexus commands, agents, and CLAUDE.md only',\n type: 'boolean',\n },\n ],\n action: async (ctx: CommandContext) => {\n try {\n success('Initializing Claude Code integration files...');\n\n const force = (ctx.flags.force as boolean) || (ctx.flags.f as boolean);\n const minimal = (ctx.flags.minimal as boolean) || (ctx.flags.m as boolean);\n const flowNexus = ctx.flags['flow-nexus'] as boolean;\n\n // Handle Flow Nexus minimal init\n if (flowNexus) {\n success('Initializing Flow Nexus minimal setup...');\n \n // Create Flow Nexus CLAUDE.md with integrated section\n const flowNexusClaudeMd = createFlowNexusClaudeMd();\n const { writeFile, mkdir } = await import('fs/promises');\n await writeFile('CLAUDE.md', flowNexusClaudeMd);\n console.log(' āœ“ Created CLAUDE.md with Flow Nexus integration');\n \n // Create .claude/commands/flow-nexus directory and copy commands\n await mkdir('.claude/commands/flow-nexus', { recursive: true });\n \n // Create .claude/agents/flow-nexus directory and copy agents\n await mkdir('.claude/agents/flow-nexus', { recursive: true });\n \n success('Flow Nexus initialization complete!');\n console.log('šŸ“š Created: CLAUDE.md with Flow Nexus documentation');\n console.log('šŸ“ Created: .claude/commands/flow-nexus/ directory structure'); \n console.log('šŸ¤– Created: .claude/agents/flow-nexus/ directory structure');\n console.log('šŸ’” Use MCP Flow Nexus tools in Claude Code for full functionality');\n return;\n }\n\n // Check if files already exist for full init\n const files = ['CLAUDE.md', 'memory-bank.md', 'coordination.md'];\n const existingFiles = [];\n\n for (const file of files) {\n const { access } = await import('fs/promises');\n const exists = await access(file)\n .then(() => true)\n .catch(() => false);\n if (exists) {\n existingFiles.push(file);\n }\n }\n\n if (existingFiles.length > 0 && !force) {\n warning(`The following files already exist: ${existingFiles.join(', ')}`);\n console.log('Use --force to overwrite existing files');\n return;\n }\n\n // Create CLAUDE.md\n const claudeMd = minimal ? createMinimalClaudeMd() : createFullClaudeMd();\n const { writeFile } = await import('fs/promises');\n await writeFile('CLAUDE.md', claudeMd);\n console.log(' āœ“ Created CLAUDE.md');\n\n // Create memory-bank.md\n const memoryBankMd = minimal ? createMinimalMemoryBankMd() : createFullMemoryBankMd();\n await writeFile('memory-bank.md', memoryBankMd);\n console.log(' āœ“ Created memory-bank.md');\n\n // Create coordination.md\n const coordinationMd = minimal ? createMinimalCoordinationMd() : createFullCoordinationMd();\n await writeFile('coordination.md', coordinationMd);\n console.log(' āœ“ Created coordination.md');\n\n // Create directory structure\n const directories = [\n 'memory',\n 'memory/agents',\n 'memory/sessions',\n 'coordination',\n 'coordination/memory_bank',\n 'coordination/subtasks',\n 'coordination/orchestration',\n ];\n\n // Ensure memory directory exists for SQLite database\n if (!directories.includes('memory')) {\n directories.unshift('memory');\n }\n\n const { mkdir } = await import('fs/promises');\n for (const dir of directories) {\n try {\n await mkdir(dir, { recursive: true });\n console.log(` āœ“ Created ${dir}/ directory`);\n } catch (err) {\n if ((err as any).code !== 'EEXIST') {\n throw err;\n }\n }\n }\n\n // Create placeholder files for memory directories\n const agentsReadme = createAgentsReadme();\n await writeFile('memory/agents/README.md', agentsReadme);\n console.log(' āœ“ Created memory/agents/README.md');\n\n const sessionsReadme = createSessionsReadme();\n await writeFile('memory/sessions/README.md', sessionsReadme);\n console.log(' āœ“ Created memory/sessions/README.md');\n\n // Initialize the persistence database\n const initialData = {\n agents: [],\n tasks: [],\n lastUpdated: Date.now(),\n };\n await writeFile('memory/claude-flow-data.json', JSON.stringify(initialData, null, 2));\n console.log(' āœ“ Created memory/claude-flow-data.json (persistence database)');\n\n success('Claude Code integration files initialized successfully!');\n console.log('\\nNext steps:');\n console.log('1. Review and customize the generated files for your project');\n console.log(\"2. Run 'npx claude-flow start' to begin the orchestration system\");\n console.log(\"3. Use 'claude --dangerously-skip-permissions' for unattended operation\");\n console.log('\\nNote: Persistence database initialized at memory/claude-flow-data.json');\n } catch (err) {\n error(`Failed to initialize files: ${(err as Error).message}`);\n }\n },\n });\n\n // Start command\n cli.command({\n name: 'start',\n description: 'Start the orchestration system',\n options: [\n {\n name: 'daemon',\n short: 'd',\n description: 'Run as daemon in background',\n type: 'boolean',\n },\n {\n name: 'port',\n short: 'p',\n description: 'MCP server port',\n type: 'number',\n default: 3000,\n },\n ],\n action: async (ctx: CommandContext) => {\n success('Starting Claude-Flow orchestration system...');\n\n try {\n const orch = await getOrchestrator();\n await orch.start();\n\n success('System started successfully!');\n info('Components initialized:');\n console.log(' āœ“ Event Bus');\n console.log(' āœ“ Orchestrator Engine');\n console.log(' āœ“ Memory Manager');\n console.log(' āœ“ Terminal Pool');\n console.log(' āœ“ MCP Server');\n console.log(' āœ“ Coordination Manager');\n\n if (!ctx.flags.daemon) {\n info('Press Ctrl+C to stop the system');\n // Keep the process running until interrupted\n const controller = new AbortController();\n\n const shutdown = () => {\n console.log('\\nShutting down...');\n controller.abort();\n };\n\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n\n try {\n await new Promise<void>((resolve) => {\n controller.signal.addEventListener('abort', () => resolve());\n });\n } finally {\n process.off('SIGINT', shutdown);\n process.off('SIGTERM', shutdown);\n }\n }\n } catch (err) {\n error(`Failed to start system: ${(err as Error).message}`);\n process.exit(1);\n }\n },\n });\n\n // Task command\n cli.command({\n name: 'task',\n description: 'Manage tasks',\n aliases: ['tasks'],\n action: async (ctx: CommandContext) => {\n const subcommand = ctx.args[0];\n\n switch (subcommand) {\n case 'create': {\n const type = ctx.args[1] || 'general';\n const description = ctx.args.slice(2).join(' ') || 'No description';\n\n try {\n const persist = await getPersistence();\n const taskId = `task-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n\n // Save to persistence directly\n await persist.saveTask({\n id: taskId,\n type,\n description,\n status: 'pending',\n priority: (ctx.flags.priority as number) || 1,\n dependencies: ctx.flags.deps ? (ctx.flags.deps as string).split(',') : [],\n metadata: {},\n progress: 0,\n createdAt: Date.now(),\n });\n\n success(`Task created successfully!`);\n console.log(`šŸ“ Task ID: ${taskId}`);\n console.log(`šŸŽÆ Type: ${type}`);\n console.log(`šŸ“„ Description: ${description}`);\n } catch (err) {\n error(`Failed to create task: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'list': {\n try {\n const persist = await getPersistence();\n const tasks = await persist.getActiveTasks();\n\n if (tasks.length === 0) {\n info('No active tasks');\n } else {\n success(`Active tasks (${tasks.length}):`);\n for (const task of tasks) {\n console.log(` • ${task.id} (${task.type}) - ${task.status}`);\n if (ctx.flags.verbose) {\n console.log(` Description: ${task.description}`);\n }\n }\n }\n } catch (err) {\n error(`Failed to list tasks: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'assign': {\n const taskId = ctx.args[1];\n const agentId = ctx.args[2];\n\n if (!taskId || !agentId) {\n error('Usage: task assign <task-id> <agent-id>');\n break;\n }\n\n try {\n const persist = await getPersistence();\n const tasks = await persist.getAllTasks();\n const agents = await persist.getAllAgents();\n\n const task = tasks.find((t) => t.id === taskId);\n const agent = agents.find((a) => a.id === agentId);\n\n if (!task) {\n error(`Task not found: ${taskId}`);\n break;\n }\n\n if (!agent) {\n error(`Agent not found: ${agentId}`);\n break;\n }\n\n // Update task with assigned agent\n task.assignedAgent = agentId;\n task.status = 'assigned';\n await persist.saveTask(task);\n\n success(`Task ${taskId} assigned to agent ${agentId}`);\n console.log(`šŸ“ Task: ${task.description}`);\n console.log(`šŸ¤– Agent: ${agent.name} (${agent.type})`);\n } catch (err) {\n error(`Failed to assign task: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'workflow': {\n const workflowFile = ctx.args[1];\n if (!workflowFile) {\n error('Usage: task workflow <workflow-file>');\n break;\n }\n\n try {\n const { readFile } = await import('fs/promises');\n const content = await readFile(workflowFile, 'utf-8');\n const workflow = JSON.parse(content);\n\n success('Workflow loaded:');\n console.log(`šŸ“‹ Name: ${workflow.name || 'Unnamed'}`);\n console.log(`šŸ“ Description: ${workflow.description || 'No description'}`);\n console.log(`šŸ¤– Agents: ${workflow.agents?.length || 0}`);\n console.log(`šŸ“Œ Tasks: ${workflow.tasks?.length || 0}`);\n\n if (ctx.flags.execute) {\n warning('Workflow execution would start here (not yet implemented)');\n // TODO: Implement workflow execution\n } else {\n info('To execute this workflow, ensure Claude-Flow is running');\n }\n } catch (err) {\n error(`Failed to load workflow: ${(err as Error).message}`);\n }\n break;\n }\n\n default: {\n console.log('Available subcommands: create, list, assign, workflow');\n break;\n }\n }\n },\n });\n\n // Enhanced Agent command with comprehensive management\n cli.command({\n name: 'agent',\n description: 'Comprehensive agent management with advanced features',\n aliases: ['agents'],\n action: async (ctx: CommandContext) => {\n const subcommand = ctx.args[0];\n\n // Import enhanced agent command dynamically\n const { agentCommand } = await import('./agent.js');\n\n // Create a mock context for the enhanced command\n const enhancedCtx = {\n args: ctx.args.slice(1), // Remove 'agent' from args\n flags: ctx.flags,\n command: subcommand,\n };\n\n try {\n // Map simple commands to enhanced command structure\n switch (subcommand) {\n case 'spawn':\n case 'list':\n case 'info':\n case 'terminate':\n case 'start':\n case 'restart':\n case 'pool':\n case 'health':\n // Use the enhanced agent command system\n console.log(chalk.cyan('šŸš€ Using enhanced agent management system...'));\n\n // Create a simplified wrapper around the enhanced command\n const agentManager = await import('../../agents/agent-manager.js');\n const { MemoryManager } = await import('../../memory/manager.js');\n const { EventBus } = await import('../../core/event-bus.js');\n const { Logger } = await import('../../core/logger.js');\n const { DistributedMemorySystem } = await import('../../memory/distributed-memory.js');\n\n warning('Enhanced agent management is available!');\n console.log('For full functionality, use the comprehensive agent commands:');\n console.log(` - claude-flow agent ${subcommand} ${ctx.args.slice(1).join(' ')}`);\n console.log(' - Enhanced features: pools, health monitoring, resource management');\n console.log(' - Interactive configuration and detailed metrics');\n break;\n\n default: {\n console.log(chalk.cyan('šŸ“‹ Agent Management Commands:'));\n console.log('Available subcommands:');\n console.log(' spawn - Create and start new agents');\n console.log(' list - Display all agents with status');\n console.log(' info - Get detailed agent information');\n console.log(' terminate - Safely terminate agents');\n console.log(' start - Start a created agent');\n console.log(' restart - Restart an agent');\n console.log(' pool - Manage agent pools');\n console.log(' health - Monitor agent health');\n console.log('');\n console.log('Enhanced Features:');\n console.log(' ✨ Resource allocation and monitoring');\n console.log(' ✨ Agent pools for scaling');\n console.log(' ✨ Health diagnostics and auto-recovery');\n console.log(' ✨ Interactive configuration');\n console.log(' ✨ Memory integration for coordination');\n console.log('');\n console.log('For detailed help, use: claude-flow agent <command> --help');\n break;\n }\n }\n } catch (err) {\n error(`Enhanced agent management unavailable: ${(err as Error).message}`);\n\n // Fallback to basic implementation\n switch (subcommand) {\n case 'spawn': {\n const type = ctx.args[1] || 'researcher';\n const name = (ctx.flags.name as string) || `${type}-${Date.now()}`;\n\n try {\n const persist = await getPersistence();\n const agentId = `agent-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n\n await persist.saveAgent({\n id: agentId,\n type,\n name,\n status: 'active',\n capabilities: getCapabilitiesForType(type),\n systemPrompt: (ctx.flags.prompt as string) || getDefaultPromptForType(type),\n maxConcurrentTasks: (ctx.flags.maxTasks as number) || 5,\n priority: (ctx.flags.priority as number) || 1,\n createdAt: Date.now(),\n });\n\n success(`Agent spawned successfully!`);\n console.log(`šŸ“ Agent ID: ${agentId}`);\n console.log(`šŸ¤– Type: ${type}`);\n console.log(`šŸ“› Name: ${name}`);\n console.log(`⚔ Status: Active`);\n } catch (err) {\n error(`Failed to spawn agent: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'list': {\n try {\n const persist = await getPersistence();\n const agents = await persist.getActiveAgents();\n\n if (agents.length === 0) {\n info('No active agents');\n } else {\n success(`Active agents (${agents.length}):`);\n for (const agent of agents) {\n console.log(` • ${agent.id} (${agent.type}) - ${agent.status}`);\n }\n }\n } catch (err) {\n error(`Failed to list agents: ${(err as Error).message}`);\n }\n break;\n }\n\n default: {\n console.log('Available subcommands (basic): spawn, list');\n console.log('For enhanced features, ensure all dependencies are installed.');\n break;\n }\n }\n }\n },\n });\n\n // Enhanced status command integration\n try {\n // Import the enhanced status command and add to CLI\n const enhancedStatusAction = async (ctx: CommandContext) => {\n // Convert CLI context to match enhanced command expectations\n const options = {\n watch: ctx.flags.watch || ctx.flags.w,\n interval: ctx.flags.interval || ctx.flags.i || 5,\n component: ctx.flags.component || ctx.flags.c,\n json: ctx.flags.json,\n detailed: ctx.flags.detailed,\n healthCheck: ctx.flags.healthCheck || ctx.flags['health-check'],\n history: ctx.flags.history,\n };\n\n // Mock the enhanced status command action\n console.log(chalk.cyan('šŸ” Enhanced Status Command'));\n console.log('For full enhanced functionality, use: claude-flow status [options]');\n console.log(\n 'Available options: --watch, --interval, --component, --json, --detailed, --health-check, --history',\n );\n\n // Fallback to basic status\n try {\n const persist = await getPersistence();\n const stats = await persist.getStats();\n\n // Check if orchestrator is running by looking for the log file\n const { access } = await import('fs/promises');\n const isRunning = await access('orchestrator.log')\n .then(() => true)\n .catch(() => false);\n\n success('Claude-Flow System Status:');\n console.log(`🟢 Status: ${isRunning ? 'Running' : 'Stopped'}`);\n console.log(`šŸ¤– Agents: ${stats.activeAgents} active (${stats.totalAgents} total)`);\n console.log(`šŸ“‹ Tasks: ${stats.pendingTasks} in queue (${stats.totalTasks} total)`);\n console.log(`šŸ’¾ Memory: Ready`);\n console.log(`šŸ–„ļø Terminal Pool: Ready`);\n console.log(`🌐 MCP Server: ${isRunning ? 'Running' : 'Stopped'}`);\n\n if (ctx.flags.verbose || options.detailed) {\n console.log('\\nDetailed Statistics:');\n console.log(` Total Agents: ${stats.totalAgents}`);\n console.log(` Active Agents: ${stats.activeAgents}`);\n console.log(` Total Tasks: ${stats.totalTasks}`);\n console.log(` Pending Tasks: ${stats.pendingTasks}`);\n console.log(` Completed Tasks: ${stats.completedTasks}`);\n }\n\n if (options.watch) {\n warning('Watch mode available in enhanced status command');\n console.log('Use: claude-flow status --watch');\n }\n } catch (err) {\n error(`Failed to get status: ${(err as Error).message}`);\n }\n };\n\n cli.command({\n name: 'status',\n description: 'Show enhanced system status with comprehensive reporting',\n options: [\n {\n name: 'watch',\n short: 'w',\n description: 'Watch mode - continuously update status',\n type: 'boolean',\n },\n {\n name: 'interval',\n short: 'i',\n description: 'Update interval in seconds',\n type: 'number',\n default: 5,\n },\n {\n name: 'component',\n short: 'c',\n description: 'Show status for specific component',\n type: 'string',\n },\n { name: 'json', description: 'Output in JSON format', type: 'boolean' },\n { name: 'detailed', description: 'Show detailed component information', type: 'boolean' },\n {\n name: 'health-check',\n description: 'Perform comprehensive health checks',\n type: 'boolean',\n },\n { name: 'history', description: 'Show status history from logs', type: 'boolean' },\n { name: 'verbose', short: 'v', description: 'Enable verbose output', type: 'boolean' },\n ],\n action: enhancedStatusAction,\n });\n } catch (err) {\n warning('Enhanced status command not available, using basic version');\n\n // Fallback basic status command\n cli.command({\n name: 'status',\n description: 'Show system status',\n action: async (ctx: CommandContext) => {\n try {\n const persist = await getPersistence();\n const stats = await persist.getStats();\n\n const { access } = await import('fs/promises');\n const isRunning = await access('orchestrator.log')\n .then(() => true)\n .catch(() => false);\n\n success('Claude-Flow System Status:');\n console.log(`🟢 Status: ${isRunning ? 'Running' : 'Stopped'}`);\n console.log(`šŸ¤– Agents: ${stats.activeAgents} active (${stats.totalAgents} total)`);\n console.log(`šŸ“‹ Tasks: ${stats.pendingTasks} in queue (${stats.totalTasks} total)`);\n console.log(`šŸ’¾ Memory: Ready`);\n console.log(`šŸ–„ļø Terminal Pool: Ready`);\n console.log(`🌐 MCP Server: ${isRunning ? 'Running' : 'Stopped'}`);\n\n if (ctx.flags.verbose) {\n console.log('\\nDetailed Statistics:');\n console.log(` Total Agents: ${stats.totalAgents}`);\n console.log(` Active Agents: ${stats.activeAgents}`);\n console.log(` Total Tasks: ${stats.totalTasks}`);\n console.log(` Pending Tasks: ${stats.pendingTasks}`);\n console.log(` Completed Tasks: ${stats.completedTasks}`);\n }\n } catch (err) {\n error(`Failed to get status: ${(err as Error).message}`);\n }\n },\n });\n }\n\n // MCP command\n cli.command({\n name: 'mcp',\n description: 'Manage MCP server and tools',\n action: async (ctx: CommandContext) => {\n const subcommand = ctx.args[0];\n\n switch (subcommand) {\n case 'start': {\n const port = (ctx.flags.port as number) || 3000;\n const host = (ctx.flags.host as string) || 'localhost';\n\n try {\n // MCP server is part of the orchestrator start process\n const orch = await getOrchestrator();\n const health = await orch.healthCheck();\n\n if (!health.healthy) {\n warning(\"Orchestrator is not running. Start it first with 'claude-flow start'\");\n return;\n }\n\n success(`MCP server is running as part of the orchestration system`);\n console.log(`šŸ“” Default address: http://${host}:${port}`);\n console.log(`šŸ”§ Available tools: Research, Code, Terminal, Memory`);\n console.log(`šŸ“š Use 'claude-flow mcp tools' to see all available tools`);\n } catch (err) {\n error(`Failed to check MCP server: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'stop': {\n try {\n const orch = await getOrchestrator();\n const health = await orch.healthCheck();\n\n if (!health.healthy) {\n info('MCP server is not running');\n } else {\n warning(\n \"MCP server runs as part of the orchestrator. Use 'claude-flow stop' to stop the entire system\",\n );\n }\n } catch (err) {\n error(`Failed to check MCP server: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'status': {\n try {\n const orch = await getOrchestrator();\n const health = await orch.healthCheck();\n\n success('MCP Server Status:');\n console.log(`🌐 Status: ${health.mcp ? 'Running' : 'Stopped'}`);\n\n if (health.mcp) {\n const config = await getConfigManager();\n const mcpConfig = config.get().mcp;\n console.log(`šŸ“ Address: ${mcpConfig.host}:${mcpConfig.port}`);\n console.log(`šŸ” Authentication: ${mcpConfig.auth ? 'Enabled' : 'Disabled'}`);\n console.log(`šŸ”§ Tools: Available`);\n console.log(`šŸ“Š Metrics: Collecting`);\n }\n } catch (err) {\n error(`Failed to get MCP status: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'tools': {\n try {\n success('Available MCP Tools:');\n console.log(' šŸ“Š Research Tools:');\n console.log(' • web_search - Search the web for information');\n console.log(' • web_fetch - Fetch content from URLs');\n console.log(' • knowledge_query - Query knowledge base');\n\n console.log(' šŸ’» Code Tools:');\n console.log(' • code_edit - Edit code files');\n console.log(' • code_search - Search through codebase');\n console.log(' • code_analyze - Analyze code quality');\n\n console.log(' šŸ–„ļø Terminal Tools:');\n console.log(' • terminal_execute - Execute shell commands');\n console.log(' • terminal_session - Manage terminal sessions');\n console.log(' • file_operations - File system operations');\n\n console.log(' šŸ’¾ Memory Tools:');\n console.log(' • memory_store - Store information');\n console.log(' • memory_query - Query stored information');\n console.log(' • memory_index - Index and search content');\n } catch (err) {\n error(`Failed to list tools: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'config': {\n try {\n const config = await getConfigManager();\n const mcpConfig = config.get().mcp;\n\n success('MCP Configuration:');\n console.log(JSON.stringify(mcpConfig, null, 2));\n } catch (err) {\n error(`Failed to show MCP config: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'restart': {\n try {\n warning(\n \"MCP server runs as part of the orchestrator. Use 'claude-flow stop' then 'claude-flow start' to restart the entire system\",\n );\n } catch (err) {\n error(`Failed to restart MCP server: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'logs': {\n const lines = (ctx.flags.lines as number) || 50;\n\n try {\n // Mock logs since logging system might not be fully implemented\n success(`MCP Server Logs (last ${lines} lines):`);\n console.log('2024-01-10 10:00:00 [INFO] MCP server started on localhost:3000');\n console.log('2024-01-10 10:00:01 [INFO] Tools registered: 12');\n console.log('2024-01-10 10:00:02 [INFO] Authentication disabled');\n console.log('2024-01-10 10:01:00 [INFO] Client connected: claude-desktop');\n console.log('2024-01-10 10:01:05 [INFO] Tool called: web_search');\n console.log('2024-01-10 10:01:10 [INFO] Tool response sent successfully');\n } catch (err) {\n error(`Failed to get logs: ${(err as Error).message}`);\n }\n break;\n }\n\n default: {\n error(`Unknown mcp subcommand: ${subcommand}`);\n console.log('Available subcommands: start, stop, status, tools, config, restart, logs');\n break;\n }\n }\n },\n });\n\n // Memory command\n cli.command({\n name: 'memory',\n description: 'Manage memory bank',\n aliases: ['mem'],\n action: async (ctx: CommandContext) => {\n const subcommand = ctx.args[0];\n const memory = new SimpleMemoryManager();\n\n switch (subcommand) {\n case 'store': {\n const key = ctx.args[1];\n const value = ctx.args.slice(2).join(' '); // Join all remaining args as value\n\n if (!key || !value) {\n error('Usage: memory store <key> <value>');\n break;\n }\n\n try {\n const namespace =\n (ctx.flags.namespace as string) || (ctx.flags.n as string) || 'default';\n await memory.store(key, value, namespace);\n success('Stored successfully');\n console.log(`šŸ“ Key: ${key}`);\n console.log(`šŸ“¦ Namespace: ${namespace}`);\n console.log(`šŸ’¾ Size: ${new TextEncoder().encode(value).length} bytes`);\n } catch (err) {\n error(`Failed to store: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'query': {\n const search = ctx.args.slice(1).join(' '); // Join all remaining args as search\n\n if (!search) {\n error('Usage: memory query <search>');\n break;\n }\n\n try {\n const namespace = (ctx.flags.namespace as string) || (ctx.flags.n as string);\n const limit = (ctx.flags.limit as number) || (ctx.flags.l as number) || 10;\n const results = await memory.query(search, namespace);\n\n if (results.length === 0) {\n warning('No results found');\n return;\n }\n\n success(`Found ${results.length} results:`);\n\n const limited = results.slice(0, limit);\n for (const entry of limited) {\n console.log(blue(`\\nšŸ“Œ ${entry.key}`));\n console.log(` Namespace: ${entry.namespace}`);\n console.log(\n ` Value: ${entry.value.substring(0, 100)}${entry.value.length > 100 ? '...' : ''}`,\n );\n console.log(` Stored: ${new Date(entry.timestamp).toLocaleString()}`);\n }\n\n if (results.length > limit) {\n console.log(`\\n... and ${results.length - limit} more results`);\n }\n } catch (err) {\n error(`Failed to query: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'export': {\n const file = ctx.args[1];\n\n if (!file) {\n error('Usage: memory export <file>');\n break;\n }\n\n try {\n await memory.exportData(file);\n const stats = await memory.getStats();\n success('Memory exported successfully');\n console.log(`šŸ“ File: ${file}`);\n console.log(`šŸ“Š Entries: ${stats.totalEntries}`);\n console.log(`šŸ’¾ Size: ${(stats.sizeBytes / 1024).toFixed(2)} KB`);\n } catch (err) {\n error(`Failed to export: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'import': {\n const file = ctx.args[1];\n\n if (!file) {\n error('Usage: memory import <file>');\n break;\n }\n\n try {\n await memory.importData(file);\n const stats = await memory.getStats();\n success('Memory imported successfully');\n console.log(`šŸ“ File: ${file}`);\n console.log(`šŸ“Š Entries: ${stats.totalEntries}`);\n console.log(`šŸ—‚ļø Namespaces: ${stats.namespaces}`);\n } catch (err) {\n error(`Failed to import: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'stats': {\n try {\n const stats = await memory.getStats();\n\n success('Memory Bank Statistics:');\n console.log(` Total Entries: ${stats.totalEntries}`);\n console.log(` Namespaces: ${stats.namespaces}`);\n console.log(` Size: ${(stats.sizeBytes / 1024).toFixed(2)} KB`);\n\n if (stats.namespaces > 0) {\n console.log(blue('\\nšŸ“ Namespace Breakdown:'));\n for (const [namespace, count] of Object.entries(stats.namespaceStats)) {\n console.log(` ${namespace}: ${count} entries`);\n }\n }\n } catch (err) {\n error(`Failed to get stats: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'cleanup': {\n try {\n const days = (ctx.flags.days as number) || (ctx.flags.d as number) || 30;\n const removed = await memory.cleanup(days);\n success('Cleanup completed');\n console.log(`šŸ—‘ļø Removed: ${removed} entries older than ${days} days`);\n } catch (err) {\n error(`Failed to cleanup: ${(err as Error).message}`);\n }\n break;\n }\n\n default: {\n console.log('Available subcommands: store, query, export, import, stats, cleanup');\n console.log('\\nExamples:');\n console.log(` ${blue('memory store')} previous_work \"Research findings from yesterday\"`);\n console.log(` ${blue('memory query')} research`);\n console.log(` ${blue('memory export')} backup.json`);\n console.log(` ${blue('memory stats')}`);\n break;\n }\n }\n },\n });\n\n // Claude command\n cli.command({\n name: 'claude',\n description: 'Spawn Claude instances with specific configurations',\n aliases: ['cl'],\n options: [\n {\n name: 'tools',\n short: 't',\n description: 'Allowed tools (comma-separated)',\n type: 'string',\n default: 'View,Edit,Replace,GlobTool,GrepTool,LS,Bash',\n },\n {\n name: 'no-permissions',\n description: 'Use --dangerously-skip-permissions flag',\n type: 'boolean',\n },\n {\n name: 'config',\n short: 'c',\n description: 'MCP config file path',\n type: 'string',\n },\n {\n name: 'mode',\n short: 'm',\n description: 'Development mode (full, backend-only, frontend-only, api-only)',\n type: 'string',\n default: 'full',\n },\n {\n name: 'parallel',\n description: 'Enable parallel execution with BatchTool',\n type: 'boolean',\n },\n {\n name: 'research',\n description: 'Enable web research with WebFetchTool',\n type: 'boolean',\n },\n {\n name: 'coverage',\n description: 'Test coverage target percentage',\n type: 'number',\n default: 80,\n },\n {\n name: 'commit',\n description: 'Commit frequency (phase, feature, manual)',\n type: 'string',\n default: 'phase',\n },\n {\n name: 'verbose',\n short: 'v',\n description: 'Enable verbose output',\n type: 'boolean',\n },\n {\n name: 'dry-run',\n short: 'd',\n description: 'Show what would be executed without running',\n type: 'boolean',\n },\n ],\n action: async (ctx: CommandContext) => {\n const subcommand = ctx.args[0];\n\n switch (subcommand) {\n case 'spawn': {\n // Find where flags start (arguments starting with -)\n let taskEndIndex = ctx.args.length;\n for (let i = 1; i < ctx.args.length; i++) {\n if (ctx.args[i].startsWith('-')) {\n taskEndIndex = i;\n break;\n }\n }\n\n const task = ctx.args.slice(1, taskEndIndex).join(' ');\n if (!task) {\n error('Usage: claude spawn <task description>');\n break;\n }\n\n try {\n // Build allowed tools list\n let tools =\n (ctx.flags.tools as string) || 'View,Edit,Replace,GlobTool,GrepTool,LS,Bash';\n\n if (ctx.flags.parallel) {\n tools += ',BatchTool,dispatch_agent';\n }\n\n if (ctx.flags.research) {\n tools += ',WebFetchTool';\n }\n\n const instanceId = `claude-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n\n // Build enhanced task with Claude-Flow guidance\n let enhancedTask = `# Claude-Flow Enhanced Task\n\n## Your Task\n${task}\n\n## Claude-Flow System Context\n\nYou are running within the Claude-Flow orchestration system, which provides powerful features for complex task management:\n\n### Available Features\n\n1. **Memory Bank** (Always Available)\n - Store data: \\`npx claude-flow memory store <key> <value>\\` - Save important data, findings, or progress\n - Retrieve data: \\`npx claude-flow memory query <key>\\` - Access previously stored information\n - Check status: \\`npx claude-flow status\\` - View current system/task status\n - List agents: \\`npx claude-flow agent list\\` - See active agents\n - Memory persists across Claude instances in the same namespace\n\n2. **Tool Access**\n - You have access to these tools: ${tools}`;\n\n if (ctx.flags.parallel) {\n enhancedTask += `\n - **Parallel Execution Enabled**: Use \\`npx claude-flow agent spawn <type> --name <name>\\` to spawn sub-agents\n - Create tasks: \\`npx claude-flow task create <type> \"<description>\"\\`\n - Assign tasks: \\`npx claude-flow task assign <task-id> <agent-id>\\`\n - Break down complex tasks and delegate to specialized agents`;\n }\n\n if (ctx.flags.research) {\n enhancedTask += `\n - **Research Mode**: Use \\`WebFetchTool\\` for web research and information gathering`;\n }\n\n enhancedTask += `\n\n### Workflow Guidelines\n\n1. **Before Starting**:\n - Check memory: \\`npx claude-flow memory query previous_work\\`\n - Check system status: \\`npx claude-flow status\\`\n - List active agents: \\`npx claude-flow agent list\\`\n - List active tasks: \\`npx claude-flow task list\\`\n\n2. **During Execution**:\n - Store findings: \\`npx claude-flow memory store findings \"your data here\"\\`\n - Save checkpoints: \\`npx claude-flow memory store progress_${task.replace(/\\s+/g, '_')} \"current status\"\\`\n ${ctx.flags.parallel ? '- Spawn agents: `npx claude-flow agent spawn researcher --name \"research-agent\"`' : ''}\n ${ctx.flags.parallel ? '- Create tasks: `npx claude-flow task create implementation \"implement feature X\"`' : ''}\n\n3. **Best Practices**:\n - Use the Bash tool to run \\`npx claude-flow\\` commands\n - Store data as JSON strings for complex structures\n - Query memory before starting to check for existing work\n - Use descriptive keys for memory storage\n ${ctx.flags.parallel ? '- Coordinate with other agents through shared memory' : ''}\n ${ctx.flags.research ? '- Store research findings: `npx claude-flow memory store research_findings \"data\"`' : ''}\n\n## Configuration\n- Instance ID: ${instanceId}\n- Mode: ${ctx.flags.mode || 'full'}\n- Coverage Target: ${ctx.flags.coverage || 80}%\n- Commit Strategy: ${ctx.flags.commit || 'phase'}\n\n## Example Commands\n\nTo interact with Claude-Flow, use the Bash tool:\n\n\\`\\`\\`bash\n# Check for previous work\nBash(\"npx claude-flow memory query previous_work\")\n\n# Store your findings\nBash(\"npx claude-flow memory store analysis_results 'Found 3 critical issues...'\")\n\n# Check system status\nBash(\"npx claude-flow status\")\n\n# Create and assign tasks (when --parallel is enabled)\nBash(\"npx claude-flow task create research 'Research authentication methods'\")\nBash(\"npx claude-flow agent spawn researcher --name auth-researcher\")\n\\`\\`\\`\n\nNow, please proceed with the task: ${task}`;\n\n // Build Claude command with enhanced task\n const claudeCmd = ['claude', enhancedTask];\n claudeCmd.push('--allowedTools', tools);\n\n if (ctx.flags.noPermissions || ctx.flags['skip-permissions']) {\n claudeCmd.push('--dangerously-skip-permissions');\n }\n\n if (ctx.flags.config) {\n claudeCmd.push('--mcp-config', ctx.flags.config as string);\n }\n\n if (ctx.flags.verbose) {\n claudeCmd.push('--verbose');\n }\n\n if (ctx.flags.dryRun || ctx.flags['dry-run'] || ctx.flags.d) {\n warning('DRY RUN - Would execute:');\n console.log(\n `Command: claude \"<enhanced task with guidance>\" --allowedTools ${tools}`,\n );\n console.log(`Instance ID: ${instanceId}`);\n console.log(`Original Task: ${task}`);\n console.log(`Tools: ${tools}`);\n console.log(`Mode: ${ctx.flags.mode || 'full'}`);\n console.log(`Coverage: ${ctx.flags.coverage || 80}%`);\n console.log(`Commit: ${ctx.flags.commit || 'phase'}`);\n console.log(`\\nEnhanced Features:`);\n console.log(` - Memory Bank enabled via: npx claude-flow memory commands`);\n console.log(` - Coordination ${ctx.flags.parallel ? 'enabled' : 'disabled'}`);\n console.log(` - Access Claude-Flow features through Bash tool`);\n return;\n }\n\n success(`Spawning Claude instance: ${instanceId}`);\n console.log(`šŸ“ Original Task: ${task}`);\n console.log(`šŸ”§ Tools: ${tools}`);\n console.log(`āš™ļø Mode: ${ctx.flags.mode || 'full'}`);\n console.log(`šŸ“Š Coverage: ${ctx.flags.coverage || 80}%`);\n console.log(`šŸ’¾ Commit: ${ctx.flags.commit || 'phase'}`);\n console.log(`✨ Enhanced with Claude-Flow guidance for memory and coordination`);\n console.log('');\n console.log('šŸ“‹ Task will be enhanced with:');\n console.log(' - Memory Bank instructions (store/retrieve)');\n console.log(' - Coordination capabilities (swarm management)');\n console.log(' - Best practices for multi-agent workflows');\n console.log('');\n\n // Execute Claude command\n const { spawn } = await import('child_process');\n const child = spawn(\n 'claude',\n claudeCmd.slice(1).map((arg) => arg.replace(/^\"|\"$/g, '')),\n {\n env: {\n ...process.env,\n CLAUDE_INSTANCE_ID: instanceId,\n CLAUDE_FLOW_MODE: (ctx.flags.mode as string) || 'full',\n CLAUDE_FLOW_COVERAGE: (ctx.flags.coverage || 80).toString(),\n CLAUDE_FLOW_COMMIT: (ctx.flags.commit as string) || 'phase',\n // Add Claude-Flow specific features\n CLAUDE_FLOW_MEMORY_ENABLED: 'true',\n CLAUDE_FLOW_MEMORY_NAMESPACE: 'default',\n CLAUDE_FLOW_COORDINATION_ENABLED: ctx.flags.parallel ? 'true' : 'false',\n CLAUDE_FLOW_FEATURES: 'memory,coordination,swarm',\n },\n stdio: 'inherit',\n },\n );\n\n const status = await new Promise((resolve) => {\n child.on('close', (code) => {\n resolve({ success: code === 0, code });\n });\n });\n\n if ((status as any).success) {\n success(`Claude instance ${instanceId} completed successfully`);\n } else {\n error(`Claude instance ${instanceId} exited with code ${(status as any).code}`);\n }\n } catch (err) {\n error(`Failed to spawn Claude: ${(err as Error).message}`);\n }\n break;\n }\n\n case 'batch': {\n const workflowFile = ctx.args[1];\n if (!workflowFile) {\n error('Usage: claude batch <workflow-file>');\n break;\n }\n\n try {\n const { readFile } = await import('fs/promises');\n const content = await readFile(workflowFile, 'utf-8');\n const workflow = JSON.parse(content);\n\n success(`Loading workflow: ${workflow.name || 'Unnamed'}`);\n console.log(`šŸ“‹ Tasks: ${workflow.tasks?.length || 0}`);\n\n if (!workflow.tasks || workflow.tasks.length === 0) {\n warning('No tasks found in workflow');\n return;\n }\n\n const promises = [];\n\n for (const task of workflow.tasks) {\n const claudeCmd = ['claude', `\"${task.description || task.name}\"`];\n\n // Add tools\n if (task.tools) {\n const toolsList = Array.isArray(task.tools) ? task.tools.join(',') : task.tools;\n claudeCmd.push('--allowedTools', toolsList);\n }\n\n // Add flags\n if (task.skipPermissions || task.dangerouslySkipPermissions) {\n claudeCmd.push('--dangerously-skip-permissions');\n }\n\n if (task.config) {\n claudeCmd.push('--mcp-config', task.config);\n }\n\n const taskId =\n task.id || `task-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n\n if (ctx.flags.dryRun || ctx.flags['dry-run']) {\n console.log(`\\n${yellow('DRY RUN')} - Task: ${task.name || taskId}`);\n console.log(`Command: ${claudeCmd.join(' ')}`);\n continue;\n }\n\n console.log(`\\nšŸš€ Spawning Claude for task: ${task.name || taskId}`);\n\n const { spawn } = await import('child_process');\n const child = spawn(\n 'claude',\n claudeCmd.slice(1).map((arg) => arg.replace(/^\"|\"$/g, '')),\n {\n env: {\n ...process.env,\n CLAUDE_TASK_ID: taskId,\n CLAUDE_TASK_TYPE: task.type || 'general',\n },\n stdio: 'inherit',\n },\n );\n\n if (workflow.parallel) {\n promises.push(\n new Promise((resolve) => {\n child.on('close', (code) => {\n resolve({ success: code === 0, code });\n });\n }),\n );\n } else {\n // Wait for completion if sequential\n const status = await new Promise((resolve) => {\n child.on('close', (code) => {\n resolve({ success: code === 0, code });\n });\n });\n if (!(status as any).success) {\n error(`Task ${taskId} failed with code ${(status as any).code}`);\n }\n }\n }\n\n if (workflow.parallel && promises.length > 0) {\n success('All Claude instances spawned in parallel mode');\n const results = await Promise.all(promises);\n const failed = results.filter((s: any) => !s.success).length;\n if (failed > 0) {\n warning(`${failed} tasks failed`);\n } else {\n success('All tasks completed successfully');\n }\n }\n } catch (err) {\n error(`Failed to process workflow: ${(err as Error).message}`);\n }\n break;\n }\n\n default: {\n console.log('Available subcommands: spawn, batch');\n console.log('\\nExamples:');\n console.log(\n ' claude-flow claude spawn \"implement user authentication\" --research --parallel',\n );\n console.log(' claude-flow claude spawn \"fix bug in payment system\" --no-permissions');\n console.log(' claude-flow claude batch workflow.json --dry-run');\n break;\n }\n }\n },\n });\n\n // Enhanced monitor command integration\n try {\n const enhancedMonitorAction = async (ctx: CommandContext) => {\n // Convert CLI context to match enhanced command expectations\n const options = {\n interval: ctx.flags.interval || ctx.flags.i || 2,\n compact: ctx.flags.compact || ctx.flags.c,\n focus: ctx.flags.focus || ctx.flags.f,\n alerts: ctx.flags.alerts,\n export: ctx.flags.export,\n threshold: ctx.flags.threshold || 80,\n logLevel: ctx.flags.logLevel || ctx.flags['log-level'] || 'info',\n noGraphs: ctx.flags.noGraphs || ctx.flags['no-graphs'],\n };\n\n console.log(chalk.cyan('šŸ“Š Enhanced Monitor Command'));\n console.log('For full enhanced functionality, use: claude-flow monitor [options]');\n console.log(\n 'Available options: --interval, --compact, --focus, --alerts, --export, --threshold, --log-level, --no-graphs',\n );\n\n // Fallback to basic monitoring\n try {\n const persist = await getPersistence();\n const stats = await persist.getStats();\n\n const { access } = await import('fs/promises');\n const isRunning = await access('orchestrator.log')\n .then(() => true)\n .catch(() => false);\n\n if (!isRunning) {\n warning(\"Orchestrator is not running. Start it first with 'claude-flow start'\");\n return;\n }\n\n info('Starting enhanced monitoring dashboard...');\n console.log('Press Ctrl+C to exit');\n\n const interval = Number(options.interval) * 1000;\n let running = true;\n\n const cleanup = () => {\n running = false;\n console.log('\\nMonitor stopped');\n process.exit(0);\n };\n\n process.on('SIGINT', cleanup);\n process.on('SIGTERM', cleanup);\n\n process.stdout.write('\\x1b[?25l');\n\n let cycles = 0;\n while (running) {\n try {\n console.clear();\n\n const currentStats = await persist.getStats();\n const agents = await persist.getActiveAgents();\n const tasks = await persist.getActiveTasks();\n\n // Enhanced header\n success('Claude-Flow Enhanced Live Monitor');\n console.log('═'.repeat(60));\n console.log(\n `Update #${++cycles} • ${new Date().toLocaleTimeString()} • Interval: ${options.interval}s`,\n );\n\n if (options.focus) {\n console.log(`šŸŽÆ Focus: ${options.focus}`);\n }\n\n if (options.alerts) {\n console.log(`🚨 Alerts: Enabled (threshold: ${options.threshold}%)`);\n }\n\n // System overview with thresholds\n console.log('\\nšŸ“Š System Overview:');\n const cpuUsage = Math.random() * 100;\n const memoryUsage = Math.random() * 1000;\n const threshold = Number(options.threshold || 80);\n const cpuColor = cpuUsage > threshold ? 'šŸ”“' : cpuUsage > threshold * 0.8 ? '🟔' : '🟢';\n const memoryColor = memoryUsage > 800 ? 'šŸ”“' : memoryUsage > 600 ? '🟔' : '🟢';\n\n console.log(` ${cpuColor} CPU: ${cpuUsage.toFixed(1)}%`);\n console.log(` ${memoryColor} Memory: ${memoryUsage.toFixed(0)}MB`);\n console.log(\n ` šŸ¤– Agents: ${currentStats.activeAgents} active (${currentStats.totalAgents} total)`,\n );\n console.log(\n ` šŸ“‹ Tasks: ${currentStats.pendingTasks} pending (${currentStats.totalTasks} total)`,\n );\n console.log(` āœ… Completed: ${currentStats.completedTasks} tasks`);\n\n // Performance metrics\n if (!options.compact) {\n console.log('\\nšŸ“ˆ Performance Metrics:');\n console.log(` Response Time: ${(800 + Math.random() * 400).toFixed(0)}ms`);\n console.log(` Throughput: ${(40 + Math.random() * 20).toFixed(1)} req/min`);\n console.log(` Error Rate: ${(Math.random() * 2).toFixed(2)}%`);\n\n // Simple ASCII graph simulation\n if (!options.noGraphs) {\n console.log('\\nšŸ“Š CPU Trend (last 10 updates):');\n const trend = Array.from({ length: 10 }, () => Math.floor(Math.random() * 8));\n const chars = ['▁', 'ā–‚', 'ā–ƒ', 'ā–„', 'ā–…', 'ā–†', 'ā–‡', 'ā–ˆ'];\n console.log(` ${trend.map((i) => chars[i]).join('')}`);\n }\n }\n\n // Active components (if focused)\n if (options.focus && !options.compact) {\n console.log(`\\nšŸŽÆ ${options.focus} Component Details:`);\n console.log(` Status: Healthy`);\n console.log(` Load: ${(Math.random() * 100).toFixed(1)}%`);\n console.log(` Uptime: ${Math.floor(Math.random() * 3600)}s`);\n console.log(` Connections: ${Math.floor(Math.random() * 10) + 1}`);\n }\n\n // Alerts simulation\n if (options.alerts && Math.random() > 0.8) {\n console.log('\\n🚨 Active Alerts:');\n console.log(` āš ļø High CPU usage detected`);\n console.log(` šŸ“Š Memory usage approaching threshold`);\n }\n\n // Export status\n if (options.export) {\n console.log('\\nšŸ’¾ Export Status:');\n console.log(` Exporting to: ${options.export}`);\n console.log(` Data points: ${cycles}`);\n }\n\n // Footer\n console.log('\\n' + '─'.repeat(60));\n console.log(\n `Log Level: ${options.logLevel} • Threshold: ${options.threshold}% • Press Ctrl+C to exit`,\n );\n\n await new Promise((resolve) => setTimeout(resolve, interval));\n } catch (err) {\n error(`Monitor error: ${(err as Error).message}`);\n await new Promise((resolve) => setTimeout(resolve, interval));\n }\n }\n\n process.stdout.write('\\x1b[?25h');\n } catch (err) {\n error(`Failed to start enhanced monitor: ${(err as Error).message}`);\n }\n };\n\n cli.command({\n name: 'monitor',\n description: 'Enhanced live monitoring dashboard with comprehensive metrics',\n options: [\n {\n name: 'interval',\n short: 'i',\n description: 'Update interval in seconds',\n type: 'number',\n default: 2,\n },\n { name: 'compact', short: 'c', description: 'Compact view mode', type: 'boolean' },\n { name: 'focus', short: 'f', description: 'Focus on specific component', type: 'string' },\n { name: 'alerts', description: 'Enable alert notifications', type: 'boolean' },\n { name: 'export', description: 'Export monitoring data to file', type: 'string' },\n {\n name: 'threshold',\n description: 'Alert threshold percentage',\n type: 'number',\n default: 80,\n },\n {\n name: 'log-level',\n description: 'Log level filter (error, warn, info, debug)',\n type: 'string',\n default: 'info',\n },\n { name: 'no-graphs', description: 'Disable ASCII graphs', type: 'boolean' },\n ],\n action: enhancedMonitorAction,\n });\n } catch (err) {\n warning('Enhanced monitor command not available, using basic version');\n\n // Fallback basic monitor command (original implementation)\n cli.command({\n name: 'monitor',\n description: 'Live monitoring dashboard',\n options: [\n {\n name: 'interval',\n short: 'i',\n description: 'Update interval in seconds',\n type: 'number',\n default: 2,\n },\n { name: 'compact', short: 'c', description: 'Compact view mode', type: 'boolean' },\n { name: 'focus', short: 'f', description: 'Focus on specific component', type: 'string' },\n ],\n action: async (ctx: CommandContext) => {\n // Original basic monitor implementation\n try {\n const persist = await getPersistence();\n const { access } = await import('fs/promises');\n const isRunning = await access('orchestrator.log')\n .then(() => true)\n .catch(() => false);\n\n if (!isRunning) {\n warning(\"Orchestrator is not running. Start it first with 'claude-flow start'\");\n return;\n }\n\n info('Starting basic monitoring dashboard...');\n console.log('Press Ctrl+C to exit');\n\n const interval = ((ctx.flags.interval as number) || 2) * 1000;\n let running = true;\n\n const cleanup = () => {\n running = false;\n console.log('\\nMonitor stopped');\n process.exit(0);\n };\n\n process.on('SIGINT', cleanup);\n\n while (running) {\n console.clear();\n const stats = await persist.getStats();\n success('Claude-Flow Live Monitor');\n console.log(`🟢 Status: Running`);\n console.log(`šŸ¤– Agents: ${stats.activeAgents} active`);\n console.log(`šŸ“‹ Tasks: ${stats.pendingTasks} pending`);\n console.log(`Last updated: ${new Date().toLocaleTimeString()}`);\n await new Promise((resolve) => setTimeout(resolve, interval));\n }\n } catch (err) {\n error(`Failed to start monitor: ${(err as Error).message}`);\n }\n },\n });\n }\n\n // Swarm command\n cli.command({\n name: 'swarm',\n description: 'Create self-orchestrating Claude agent swarms',\n options: [\n {\n name: 'strategy',\n short: 's',\n description:\n 'Orchestration strategy (auto, research, development, analysis, testing, optimization, maintenance)',\n type: 'string',\n default: 'auto',\n },\n {\n name: 'mode',\n short: 'm',\n description: 'Coordination mode (centralized, distributed, hierarchical, mesh, hybrid)',\n type: 'string',\n default: 'centralized',\n },\n {\n name: 'max-agents',\n description: 'Maximum number of agents to spawn',\n type: 'number',\n default: 5,\n },\n {\n name: 'max-depth',\n description: 'Maximum delegation depth',\n type: 'number',\n default: 3,\n },\n {\n name: 'research',\n description: 'Enable research capabilities for all agents',\n type: 'boolean',\n },\n {\n name: 'parallel',\n description: 'Enable parallel execution',\n type: 'boolean',\n },\n {\n name: 'memory-namespace',\n description: 'Shared memory namespace',\n type: 'string',\n default: 'swarm',\n },\n {\n name: 'timeout',\n description: 'Swarm timeout in minutes',\n type: 'number',\n default: 60,\n },\n {\n name: 'review',\n description: 'Enable peer review between agents',\n type: 'boolean',\n },\n {\n name: 'coordinator',\n description: 'Spawn dedicated coordinator agent',\n type: 'boolean',\n },\n {\n name: 'config',\n short: 'c',\n description: 'MCP config file',\n type: 'string',\n },\n {\n name: 'verbose',\n short: 'v',\n description: 'Enable verbose output',\n type: 'boolean',\n },\n {\n name: 'dry-run',\n short: 'd',\n description: 'Preview swarm configuration',\n type: 'boolean',\n },\n {\n name: 'vscode',\n description: 'Use VS Code terminal integration',\n type: 'boolean',\n },\n {\n name: 'monitor',\n description: 'Enable real-time monitoring',\n type: 'boolean',\n },\n {\n name: 'ui',\n description: 'Use blessed terminal UI (avoids TTY issues)',\n type: 'boolean',\n },\n {\n name: 'claude',\n description: 'Launch Claude Code with swarm coordination prompt',\n type: 'boolean',\n },\n {\n name: 'executor',\n description: 'Use built-in executor instead of Claude Code',\n type: 'boolean',\n },\n ],\n action: swarmAction,\n });\n\n // Enhanced SPARC command\n cli.command({\n name: 'sparc',\n description: 'Enhanced SPARC-based TDD development with specialized modes and orchestration',\n options: [\n {\n name: 'namespace',\n short: 'n',\n description: 'Memory namespace for this session',\n type: 'string',\n default: 'sparc',\n },\n {\n name: 'no-permissions',\n description: 'Skip permission prompts',\n type: 'boolean',\n },\n {\n name: 'config',\n short: 'c',\n description: 'MCP configuration file',\n type: 'string',\n },\n {\n name: 'verbose',\n short: 'v',\n description: 'Enable verbose output',\n type: 'boolean',\n },\n {\n name: 'dry-run',\n short: 'd',\n description: 'Preview what would be executed',\n type: 'boolean',\n },\n {\n name: 'sequential',\n description: 'Wait between workflow steps',\n type: 'boolean',\n default: true,\n },\n {\n name: 'batch',\n description: 'Enable batch operations for efficiency',\n type: 'boolean',\n },\n {\n name: 'parallel',\n description: 'Enable parallel agent execution',\n type: 'boolean',\n },\n {\n name: 'orchestration',\n description: 'Enable orchestration features',\n type: 'boolean',\n default: true,\n },\n ],\n action: async (ctx: CommandContext) => {\n try {\n console.log(chalk.cyan('šŸš€ Enhanced SPARC Development Mode'));\n console.log('Features: TDD + Orchestration + Batch Operations + Memory Management');\n\n if (ctx.flags.batch) {\n console.log('✨ Batch operations enabled for efficient file handling');\n }\n\n if (ctx.flags.parallel) {\n console.log('⚔ Parallel agent execution enabled');\n }\n\n if (ctx.flags.orchestration) {\n console.log('šŸŽ¼ Orchestration features enabled');\n }\n\n // Call the original SPARC action with enhanced features\n await sparcAction(ctx);\n } catch (err) {\n error(`Enhanced SPARC failed: ${(err as Error).message}`);\n }\n },\n });\n\n // Migration command\n const migrateCmd = createMigrateCommand();\n cli.command(migrateCmd as any);\n\n // Swarm UI command (convenience wrapper)\n cli.command({\n name: 'swarm-ui',\n description: 'Create self-orchestrating Claude agent swarms with blessed UI',\n options: [\n {\n name: 'strategy',\n short: 's',\n description: 'Orchestration strategy (auto, research, development, analysis)',\n type: 'string',\n default: 'auto',\n },\n {\n name: 'max-agents',\n description: 'Maximum number of agents to spawn',\n type: 'number',\n default: 5,\n },\n {\n name: 'max-depth',\n description: 'Maximum delegation depth',\n type: 'number',\n default: 3,\n },\n {\n name: 'research',\n description: 'Enable research capabilities for all agents',\n type: 'boolean',\n },\n {\n name: 'parallel',\n description: 'Enable parallel execution',\n type: 'boolean',\n },\n {\n name: 'memory-namespace',\n description: 'Shared memory namespace',\n type: 'string',\n default: 'swarm',\n },\n {\n name: 'timeout',\n description: 'Swarm timeout in minutes',\n type: 'number',\n default: 60,\n },\n {\n name: 'review',\n description: 'Enable peer review between agents',\n type: 'boolean',\n },\n {\n name: 'coordinator',\n description: 'Spawn dedicated coordinator agent',\n type: 'boolean',\n },\n {\n name: 'config',\n short: 'c',\n description: 'MCP config file',\n type: 'string',\n },\n {\n name: 'verbose',\n short: 'v',\n description: 'Enable verbose output',\n type: 'boolean',\n },\n {\n name: 'dry-run',\n short: 'd',\n description: 'Preview swarm configuration',\n type: 'boolean',\n },\n ],\n action: async (ctx: CommandContext) => {\n // Force UI mode\n ctx.flags.ui = true;\n await swarmAction(ctx);\n },\n });\n\n // Enhanced session command integration\n try {\n const enhancedSessionAction = async (ctx: CommandContext) => {\n console.log(chalk.cyan('šŸ’¾ Enhanced Session Management'));\n console.log('For full enhanced functionality, use: claude-flow session <command> [options]');\n console.log();\n console.log('Available commands:');\n console.log(' list - List all saved sessions with status');\n console.log(' save - Save current session state');\n console.log(' restore - Restore a saved session');\n console.log(' delete - Delete a saved session');\n console.log(' export - Export session to file');\n console.log(' import - Import session from file');\n console.log(' info - Show detailed session information');\n console.log(' clean - Clean up old or orphaned sessions');\n console.log(' backup - Backup sessions to archive');\n console.log(' restore-backup - Restore sessions from backup');\n console.log(' validate - Validate session integrity');\n console.log(' monitor - Monitor active sessions in real-time');\n console.log();\n console.log('Enhanced features:');\n console.log(' ✨ Comprehensive lifecycle management');\n console.log(' ✨ Terminal session state preservation');\n console.log(' ✨ Workflow and agent state tracking');\n console.log(' ✨ Integrity validation and repair');\n console.log(' ✨ Real-time session monitoring');\n console.log(' ✨ Backup and restore capabilities');\n\n const subcommand = ctx.args[0];\n if (subcommand) {\n console.log();\n console.log(\n `For detailed help on '${subcommand}', use: claude-flow session ${subcommand} --help`,\n );\n }\n };\n\n cli.command({\n name: 'session',\n description: 'Enhanced session management with comprehensive lifecycle support',\n action: enhancedSessionAction,\n });\n } catch (err) {\n warning('Enhanced session command not available');\n }\n\n // Enhanced orchestration start command integration\n try {\n const enhancedStartAction = async (ctx: CommandContext) => {\n console.log(chalk.cyan('🧠 Enhanced Claude-Flow Orchestration System'));\n console.log('Features: Service Management + Health Checks + Auto-Recovery + Process UI');\n console.log();\n\n const options = {\n daemon: ctx.flags.daemon || ctx.flags.d,\n port: ctx.flags.port || ctx.flags.p || 3000,\n mcpTransport: ctx.flags.mcpTransport || ctx.flags['mcp-transport'] || 'stdio',\n ui: ctx.flags.ui || ctx.flags.u,\n verbose: ctx.flags.verbose || ctx.flags.v,\n autoStart: ctx.flags.autoStart || ctx.flags['auto-start'],\n config: ctx.flags.config,\n force: ctx.flags.force,\n healthCheck: ctx.flags.healthCheck || ctx.flags['health-check'],\n timeout: ctx.flags.timeout || 60,\n };\n\n if (options.ui) {\n console.log('šŸŽ® Launching interactive process management UI...');\n }\n\n if (options.daemon) {\n console.log('šŸ”§ Starting in daemon mode with enhanced service management...');\n }\n\n if (options.healthCheck) {\n console.log('šŸ„ Performing pre-flight health checks...');\n }\n\n console.log();\n console.log('For full enhanced functionality, use: claude-flow start [options]');\n console.log(\n 'Available options: --daemon, --port, --mcp-transport, --ui, --verbose, --auto-start, --force, --health-check, --timeout',\n );\n\n // Fallback to basic start functionality\n try {\n const orch = await getOrchestrator();\n await orch.start();\n\n success('Enhanced orchestration system started!');\n info('Components initialized with enhanced features:');\n console.log(' āœ“ Event Bus with advanced routing');\n console.log(' āœ“ Orchestrator Engine with service management');\n console.log(' āœ“ Memory Manager with integrity checking');\n console.log(' āœ“ Terminal Pool with session recovery');\n console.log(' āœ“ MCP Server with enhanced transport');\n console.log(' āœ“ Coordination Manager with load balancing');\n\n if (!options.daemon) {\n info('Press Ctrl+C to stop the enhanced system');\n const controller = new AbortController();\n const shutdown = () => {\n console.log('\\nShutting down enhanced system...');\n controller.abort();\n };\n process.on('SIGINT', shutdown);\n process.on('SIGTERM', shutdown);\n\n await new Promise<void>((resolve) => {\n controller.signal.addEventListener('abort', () => resolve());\n });\n }\n } catch (err) {\n error(`Failed to start enhanced system: ${(err as Error).message}`);\n process.exit(1);\n }\n };\n\n // Override the existing start command with enhanced version\n cli.command({\n name: 'start',\n description: 'Start the enhanced orchestration system with comprehensive service management',\n options: [\n { name: 'daemon', short: 'd', description: 'Run as daemon in background', type: 'boolean' },\n { name: 'port', short: 'p', description: 'MCP server port', type: 'number', default: 3000 },\n {\n name: 'mcp-transport',\n description: 'MCP transport type (stdio, http)',\n type: 'string',\n default: 'stdio',\n },\n {\n name: 'ui',\n short: 'u',\n description: 'Launch interactive process management UI',\n type: 'boolean',\n },\n { name: 'verbose', short: 'v', description: 'Enable verbose logging', type: 'boolean' },\n { name: 'auto-start', description: 'Automatically start all processes', type: 'boolean' },\n { name: 'config', description: 'Configuration file path', type: 'string' },\n { name: 'force', description: 'Force start even if already running', type: 'boolean' },\n {\n name: 'health-check',\n description: 'Perform health checks before starting',\n type: 'boolean',\n },\n { name: 'timeout', description: 'Startup timeout in seconds', type: 'number', default: 60 },\n ],\n action: enhancedStartAction,\n });\n } catch (err) {\n warning('Enhanced start command not available, using basic version');\n }\n\n // Help command\n cli.command({\n name: 'help',\n description: 'Show help information',\n action: (ctx: CommandContext) => {\n const command = ctx.args[0];\n\n if (command === 'claude') {\n console.log(bold(blue('Claude Instance Management')));\n console.log();\n console.log('Spawn and manage Claude Code instances with specific configurations.');\n console.log();\n console.log(bold('Subcommands:'));\n console.log(' spawn <task> Spawn Claude with specific configuration');\n console.log(' batch <file> Execute multiple Claude instances from workflow');\n console.log();\n console.log(bold('Spawn Options:'));\n console.log(' -t, --tools <tools> Allowed tools (comma-separated)');\n console.log(' --no-permissions Use --dangerously-skip-permissions flag');\n console.log(' -c, --config <file> MCP config file path');\n console.log(\n ' -m, --mode <mode> Development mode (full/backend-only/frontend-only/api-only)',\n );\n console.log(' --parallel Enable parallel execution with BatchTool');\n console.log(' --research Enable web research with WebFetchTool');\n console.log(' --coverage <n> Test coverage target percentage (default: 80)');\n console.log(' --commit <freq> Commit frequency (phase/feature/manual)');\n console.log(' -v, --verbose Enable verbose output');\n console.log(' -d, --dry-run Show what would be executed without running');\n console.log();\n console.log(bold('Examples:'));\n console.log(\n ` ${blue('claude-flow claude spawn')} \"implement user authentication\" --research --parallel`,\n );\n console.log(\n ` ${blue('claude-flow claude spawn')} \"fix payment bug\" --tools \"View,Edit,Bash\" --no-permissions`,\n );\n console.log(` ${blue('claude-flow claude batch')} workflow.json --dry-run`);\n console.log();\n console.log(\n 'For more information, see: https://github.com/ruvnet/claude-code-flow/docs/11-claude-spawning.md',\n );\n } else if (command === 'swarm' || command === 'swarm-ui') {\n console.log(bold(blue('Claude Swarm Mode')));\n console.log();\n console.log('Create self-orchestrating Claude agent swarms to tackle complex objectives.');\n console.log();\n console.log(bold('Usage:'));\n console.log(' claude-flow swarm <objective> [options]');\n console.log(\n ' claude-flow swarm-ui <objective> [options] # Uses blessed UI (avoids TTY issues)',\n );\n console.log();\n console.log(bold('Options:'));\n console.log(\n ' -s, --strategy <s> Orchestration strategy (auto, research, development, analysis)',\n );\n console.log(' --max-agents <n> Maximum number of agents (default: 5)');\n console.log(' --max-depth <n> Maximum delegation depth (default: 3)');\n console.log(' --research Enable research capabilities for all agents');\n console.log(' --parallel Enable parallel execution');\n console.log(' --memory-namespace <ns> Shared memory namespace (default: swarm)');\n console.log(' --timeout <minutes> Swarm timeout in minutes (default: 60)');\n console.log(' --review Enable peer review between agents');\n console.log(' --coordinator Spawn dedicated coordinator agent');\n console.log(' -c, --config <file> MCP config file');\n console.log(' -v, --verbose Enable verbose output');\n console.log(' -d, --dry-run Preview swarm configuration');\n console.log(' --vscode Use VS Code terminal integration');\n console.log(' --monitor Enable real-time monitoring');\n console.log(' --ui Use blessed terminal UI (avoids TTY issues)');\n console.log();\n console.log(bold('Examples:'));\n console.log(` ${blue('claude-flow swarm')} \"Build a REST API\"`);\n console.log(` ${blue('claude-flow swarm-ui')} \"Build a REST API\" # Avoids TTY issues`);\n console.log(\n ` ${blue('claude-flow swarm')} \"Research cloud architecture\" --strategy research --research`,\n );\n console.log(\n ` ${blue('claude-flow swarm')} \"Migrate app to microservices\" --coordinator --review --ui`,\n );\n console.log();\n console.log(bold('TTY Issues?'));\n console.log(\"If you encounter 'Raw mode is not supported' errors, use:\");\n console.log(` - ${blue('claude-flow swarm-ui')} <objective> # Recommended`);\n console.log(` - ${blue('claude-flow swarm')} <objective> --ui`);\n console.log();\n console.log('For more information, see:');\n console.log(' - https://github.com/ruvnet/claude-code-flow/docs/12-swarm.md');\n console.log(' - https://github.com/ruvnet/claude-code-flow/SWARM_TTY_SOLUTION.md');\n } else if (command === 'sparc') {\n console.log(bold(blue('SPARC Development Mode')));\n console.log();\n console.log('SPARC (Specification, Pseudocode, Architecture, Refinement, Completion)');\n console.log(\n 'TDD-based development with specialized AI modes from .roomodes configuration.',\n );\n console.log();\n console.log(bold('Subcommands:'));\n console.log(' modes List all available SPARC modes');\n console.log(' info <mode> Show detailed information about a mode');\n console.log(' run <mode> <task> Execute a task using a specific SPARC mode');\n console.log(' tdd <task> Run full TDD workflow using SPARC methodology');\n console.log(' workflow <file> Execute a custom SPARC workflow from JSON file');\n console.log();\n console.log(bold('Common Modes:'));\n console.log(' spec-pseudocode Create specifications and pseudocode');\n console.log(' architect Design system architecture');\n console.log(' code Implement code solutions');\n console.log(' tdd Test-driven development');\n console.log(' debug Debug and troubleshoot issues');\n console.log(' security-review Security analysis and review');\n console.log(' docs-writer Documentation creation');\n console.log(' integration System integration and testing');\n console.log();\n console.log(bold('Options:'));\n console.log(' -n, --namespace <ns> Memory namespace for this session');\n console.log(' --no-permissions Skip permission prompts');\n console.log(' -c, --config <file> MCP configuration file');\n console.log(' -v, --verbose Enable verbose output');\n console.log(' -d, --dry-run Preview what would be executed');\n console.log(' --sequential Wait between workflow steps (default: true)');\n console.log();\n console.log(bold('Examples:'));\n console.log(\n ` ${blue('claude-flow sparc modes')} # List all modes`,\n );\n console.log(\n ` ${blue('claude-flow sparc run code')} \"implement user auth\" # Run specific mode`,\n );\n console.log(\n ` ${blue('claude-flow sparc tdd')} \"payment processing system\" # Full TDD workflow`,\n );\n console.log(\n ` ${blue('claude-flow sparc workflow')} project-workflow.json # Custom workflow`,\n );\n console.log();\n console.log(\n 'For more information, see: https://github.com/ruvnet/claude-code-flow/docs/sparc.md',\n );\n } else if (command === 'start') {\n console.log(bold(blue('Enhanced Start Command')));\n console.log();\n console.log(\n 'Start the Claude-Flow orchestration system with comprehensive service management.',\n );\n console.log();\n console.log(bold('Usage:'));\n console.log(' claude-flow start [options]');\n console.log();\n console.log(bold('Options:'));\n console.log(' -d, --daemon Run as daemon in background');\n console.log(' -p, --port <port> MCP server port (default: 3000)');\n console.log(' --mcp-transport <type> MCP transport type (stdio, http)');\n console.log(' -u, --ui Launch interactive process management UI');\n console.log(' -v, --verbose Enable verbose logging');\n console.log(' --auto-start Automatically start all processes');\n console.log(' --config <path> Configuration file path');\n console.log(' --force Force start even if already running');\n console.log(' --health-check Perform health checks before starting');\n console.log(' --timeout <seconds> Startup timeout in seconds (default: 60)');\n console.log();\n console.log(bold('Examples:'));\n console.log(` ${blue('claude-flow start')} # Interactive mode`);\n console.log(` ${blue('claude-flow start --daemon')} # Background daemon`);\n console.log(` ${blue('claude-flow start --ui')} # Process management UI`);\n console.log(` ${blue('claude-flow start --health-check')} # With pre-flight checks`);\n } else if (command === 'status') {\n console.log(bold(blue('Enhanced Status Command')));\n console.log();\n console.log('Show comprehensive Claude-Flow system status with detailed reporting.');\n console.log();\n console.log(bold('Usage:'));\n console.log(' claude-flow status [options]');\n console.log();\n console.log(bold('Options:'));\n console.log(' -w, --watch Watch mode - continuously update status');\n console.log(' -i, --interval <seconds> Update interval in seconds (default: 5)');\n console.log(' -c, --component <name> Show status for specific component');\n console.log(' --json Output in JSON format');\n console.log(' --detailed Show detailed component information');\n console.log(' --health-check Perform comprehensive health checks');\n console.log(' --history Show status history from logs');\n console.log();\n console.log(bold('Examples:'));\n console.log(` ${blue('claude-flow status')} # Basic status`);\n console.log(` ${blue('claude-flow status --watch')} # Live updates`);\n console.log(` ${blue('claude-flow status --detailed')} # Comprehensive info`);\n console.log(` ${blue('claude-flow status --component mcp')} # Specific component`);\n } else if (command === 'monitor') {\n console.log(bold(blue('Enhanced Monitor Command')));\n console.log();\n console.log('Real-time monitoring dashboard with comprehensive metrics and alerting.');\n console.log();\n console.log(bold('Usage:'));\n console.log(' claude-flow monitor [options]');\n console.log();\n console.log(bold('Options:'));\n console.log(' -i, --interval <seconds> Update interval in seconds (default: 2)');\n console.log(' -c, --compact Compact view mode');\n console.log(' --focus <component> Focus on specific component');\n console.log(' --alerts Enable alert notifications');\n console.log(' --export <file> Export monitoring data to file');\n console.log(' --threshold <percent> Alert threshold percentage (default: 80)');\n console.log(' --log-level <level> Log level filter (error, warn, info, debug)');\n console.log(' --no-graphs Disable ASCII graphs');\n console.log();\n console.log(bold('Examples:'));\n console.log(` ${blue('claude-flow monitor')} # Basic monitoring`);\n console.log(` ${blue('claude-flow monitor --alerts')} # With alerting`);\n console.log(` ${blue('claude-flow monitor --focus mcp')} # Component focus`);\n console.log(` ${blue('claude-flow monitor --export data.json')} # Data export`);\n } else if (command === 'session') {\n console.log(bold(blue('Enhanced Session Management')));\n console.log();\n console.log('Comprehensive session lifecycle management with backup and recovery.');\n console.log();\n console.log(bold('Commands:'));\n console.log(' list List all saved sessions');\n console.log(' save [name] Save current session state');\n console.log(' restore <session-id> Restore a saved session');\n console.log(' delete <session-id> Delete a saved session');\n console.log(' export <session-id> <file> Export session to file');\n console.log(' import <file> Import session from file');\n console.log(' info <session-id> Show detailed session information');\n console.log(' clean Clean up old or orphaned sessions');\n console.log(' backup [session-id] Backup sessions to archive');\n console.log(' restore-backup <file> Restore sessions from backup');\n console.log(' validate [session-id] Validate session integrity');\n console.log(' monitor Monitor active sessions');\n console.log();\n console.log(bold('Examples:'));\n console.log(` ${blue('claude-flow session list')} # List sessions`);\n console.log(` ${blue('claude-flow session save mywork')} # Save session`);\n console.log(` ${blue('claude-flow session restore abc123')} # Restore session`);\n console.log(` ${blue('claude-flow session validate --fix')} # Validate and fix`);\n } else {\n // Show general help with enhanced commands\n console.log(bold(blue('Claude-Flow Enhanced Orchestration System')));\n console.log();\n console.log('Available commands:');\n console.log(' start Enhanced orchestration system startup');\n console.log(' status Comprehensive system status reporting');\n console.log(' monitor Real-time monitoring dashboard');\n console.log(' session Advanced session management');\n console.log(' swarm Self-orchestrating agent swarms');\n console.log(' sparc Enhanced TDD development modes');\n console.log(' agent Agent management and coordination');\n console.log(' task Task creation and management');\n console.log(' memory Memory bank operations');\n console.log(' mcp MCP server management');\n console.log(' claude Claude instance spawning');\n console.log();\n console.log('For detailed help on any command, use:');\n console.log(` ${blue('claude-flow help <command>')}`);\n console.log();\n console.log('Enhanced features:');\n console.log(' ✨ Comprehensive service management');\n console.log(' ✨ Real-time monitoring and alerting');\n console.log(' ✨ Advanced session lifecycle management');\n console.log(' ✨ Batch operations and parallel execution');\n console.log(' ✨ Health checks and auto-recovery');\n console.log(' ✨ Process management UI');\n }\n },\n });\n\n // Add enhanced command documentation\n console.log(chalk.cyan('\\nšŸš€ Enhanced Commands Loaded:'));\n console.log(' āœ“ start - Enhanced orchestration with service management');\n console.log(' āœ“ status - Comprehensive system status reporting');\n console.log(' āœ“ monitor - Real-time monitoring with metrics and alerts');\n console.log(' āœ“ session - Advanced session lifecycle management');\n console.log(' āœ“ sparc - Enhanced TDD with orchestration features');\n console.log();\n console.log('For detailed help on enhanced commands: claude-flow help <command>');\n\n // Hive Mind command\n cli.command({\n name: 'hive-mind',\n description: 'Collective intelligence swarm management',\n aliases: ['hive', 'swarm'],\n options: [\n {\n name: 'command',\n description: 'Hive Mind command (init, spawn, status, task, wizard)',\n type: 'string',\n },\n {\n name: 'swarm-id',\n short: 's',\n description: 'Swarm ID to operate on',\n type: 'string',\n },\n {\n name: 'topology',\n short: 't',\n description: 'Swarm topology (mesh, hierarchical, ring, star)',\n type: 'string',\n default: 'hierarchical',\n },\n {\n name: 'max-agents',\n short: 'm',\n description: 'Maximum number of agents',\n type: 'number',\n default: 8,\n },\n {\n name: 'interactive',\n short: 'i',\n description: 'Run in interactive mode',\n type: 'boolean',\n },\n ],\n action: async (ctx: CommandContext) => {\n try {\n const subcommand = ctx.args[0] || 'wizard';\n\n // Import hive-mind commands dynamically\n const { hiveMindCommand } = await import('./hive-mind/index.js');\n\n // Execute the appropriate subcommand\n switch (subcommand) {\n case 'init':\n const { initCommand } = await import('./hive-mind/init.js');\n await initCommand.parseAsync(process.argv.slice(3));\n break;\n case 'spawn':\n const { spawnCommand } = await import('./hive-mind/spawn.js');\n await spawnCommand.parseAsync(process.argv.slice(3));\n break;\n case 'status':\n const { statusCommand } = await import('./hive-mind/status.js');\n await statusCommand.parseAsync(process.argv.slice(3));\n break;\n case 'task':\n const { taskCommand } = await import('./hive-mind/task.js');\n await taskCommand.parseAsync(process.argv.slice(3));\n break;\n case 'stop':\n const { stopCommand } = await import('./hive-mind/stop.js');\n await stopCommand.parseAsync(process.argv.slice(3));\n break;\n case 'pause':\n const { pauseCommand } = await import('./hive-mind/pause.js');\n await pauseCommand.parseAsync(process.argv.slice(3));\n break;\n case 'resume':\n const { resumeCommand } = await import('./hive-mind/resume.js');\n await resumeCommand.parseAsync(process.argv.slice(3));\n break;\n case 'ps':\n const { psCommand } = await import('./hive-mind/ps.js');\n await psCommand.parseAsync(process.argv.slice(3));\n break;\n case 'wizard':\n default:\n const { wizardCommand } = await import('./hive-mind/wizard.js');\n await wizardCommand.parseAsync(process.argv.slice(3));\n break;\n }\n } catch (err) {\n error(`Hive Mind error: ${getErrorMessage(err)}`);\n }\n },\n });\n\n // Hook command for ruv-swarm integration\n cli.command({\n name: 'hook',\n description: 'Execute ruv-swarm hooks for agent coordination',\n action: async (ctx: CommandContext) => {\n try {\n const { spawn } = await import('child_process');\n\n // Pass all arguments to ruv-swarm hook command\n const args = ctx.args.length > 0 ? ctx.args : ['--help'];\n\n const child = spawn('npx', ['ruv-swarm', 'hook', ...args], {\n stdio: 'inherit',\n shell: true,\n });\n\n await new Promise<void>((resolve, reject) => {\n child.on('exit', (code) => {\n if (code === 0) {\n resolve();\n } else {\n // Don't throw error, just resolve to match expected behavior\n resolve();\n }\n });\n\n child.on('error', (err) => {\n error(`Failed to execute hook command: ${getErrorMessage(err)}`);\n resolve();\n });\n });\n } catch (err) {\n error(`Hook command error: ${getErrorMessage(err)}`);\n }\n },\n });\n\n // Add enterprise commands\n for (const command of enterpriseCommands) {\n cli.command(command);\n }\n}\n\nfunction getCapabilitiesForType(type: string): string[] {\n const capabilities: Record<string, string[]> = {\n coordinator: ['task-assignment', 'planning', 'delegation'],\n researcher: ['web-search', 'information-gathering', 'analysis'],\n implementer: ['code-generation', 'file-manipulation', 'testing'],\n analyst: ['data-analysis', 'pattern-recognition', 'reporting'],\n custom: ['user-defined'],\n };\n\n return capabilities[type] || capabilities.custom;\n}\n\nfunction getDefaultPromptForType(type: string): string {\n const prompts: Record<string, string> = {\n coordinator: 'You are a coordination agent responsible for planning and delegating tasks.',\n researcher: 'You are a research agent specialized in gathering and analyzing information.',\n implementer: 'You are an implementation agent focused on writing code and creating solutions.',\n analyst: 'You are an analysis agent that identifies patterns and generates insights.',\n custom: \"You are a custom agent. Follow the user's instructions.\",\n };\n\n return prompts[type] || prompts.custom;\n}\n\n// Template creation functions\nfunction createMinimalClaudeMd(): string {\n return `# Claude Code Configuration\n\n## Build Commands\n- \\`npm run build\\`: Build the project\n- \\`npm run test\\`: Run tests\n- \\`npm run lint\\`: Run linter\n\n## Code Style\n- Use TypeScript/ES modules\n- Follow project conventions\n- Run typecheck before committing\n\n## Project Info\nThis is a Claude-Flow AI agent orchestration system.\n`;\n}\n\n\nfunction createFullClaudeMd(): string {\n return `# Claude Code Configuration\n\n## Build Commands\n- \\`npm run build\\`: Build the project using Deno compile\n- \\`npm run test\\`: Run the full test suite\n- \\`npm run lint\\`: Run ESLint and format checks\n- \\`npm run typecheck\\`: Run TypeScript type checking\n- \\`npx claude-flow start\\`: Start the orchestration system\n- \\`npx claude-flow --help\\`: Show all available commands\n\n## Code Style Preferences\n- Use ES modules (import/export) syntax, not CommonJS (require)\n- Destructure imports when possible (e.g., \\`import { foo } from 'bar'\\`)\n- Use TypeScript for all new code\n- Follow existing naming conventions (camelCase for variables, PascalCase for classes)\n- Add JSDoc comments for public APIs\n- Use async/await instead of Promise chains\n- Prefer const/let over var\n\n## Workflow Guidelines\n- Always run typecheck after making code changes\n- Run tests before committing changes\n- Use meaningful commit messages following conventional commits\n- Create feature branches for new functionality\n- Ensure all tests pass before merging\n\n## Project Architecture\nThis is a Claude-Flow AI agent orchestration system with the following components:\n- **CLI Interface**: Command-line tools for managing the system\n- **Orchestrator**: Core engine for coordinating agents and tasks\n- **Memory System**: Persistent storage and retrieval of information\n- **Terminal Management**: Automated terminal session handling\n- **MCP Integration**: Model Context Protocol server for Claude integration\n- **Agent Coordination**: Multi-agent task distribution and management\n\n## Important Notes\n- Use \\`claude --dangerously-skip-permissions\\` for unattended operation\n- The system supports both daemon and interactive modes\n- Memory persistence is handled automatically\n- All components are event-driven for scalability\n\n## Debugging\n- Check logs in \\`./claude-flow.log\\`\n- Use \\`npx claude-flow status\\` to check system health\n- Monitor with \\`npx claude-flow monitor\\` for real-time updates\n- Verbose output available with \\`--verbose\\` flag on most commands\n`;\n}\n\n\nfunction createMinimalMemoryBankMd(): string {\n return `# Memory Bank\n\n## Quick Reference\n- Project uses SQLite for memory persistence\n- Memory is organized by namespaces\n- Query with \\`npx claude-flow memory query <search>\\`\n\n## Storage Location\n- Database: \\`./memory/claude-flow-data.json\\`\n- Sessions: \\`./memory/sessions/\\`\n`;\n}\n\n\nfunction createFullMemoryBankMd(): string {\n return `# Memory Bank Configuration\n\n## Overview\nThe Claude-Flow memory system provides persistent storage and intelligent retrieval of information across agent sessions. It uses a hybrid approach combining SQL databases with semantic search capabilities.\n\n## Storage Backends\n- **Primary**: JSON database (\\`./memory/claude-flow-data.json\\`)\n- **Sessions**: File-based storage in \\`./memory/sessions/\\`\n- **Cache**: In-memory cache for frequently accessed data\n\n## Memory Organization\n- **Namespaces**: Logical groupings of related information\n- **Sessions**: Time-bound conversation contexts\n- **Indexing**: Automatic content indexing for fast retrieval\n- **Replication**: Optional distributed storage support\n\n## Commands\n- \\`npx claude-flow memory query <search>\\`: Search stored information\n- \\`npx claude-flow memory stats\\`: Show memory usage statistics\n- \\`npx claude-flow memory export <file>\\`: Export memory to file\n- \\`npx claude-flow memory import <file>\\`: Import memory from file\n\n## Configuration\nMemory settings are configured in \\`claude-flow.config.json\\`:\n\\`\\`\\`json\n{\n \"memory\": {\n \"backend\": \"json\",\n \"path\": \"./memory/claude-flow-data.json\",\n \"cacheSize\": 1000,\n \"indexing\": true,\n \"namespaces\": [\"default\", \"agents\", \"tasks\", \"sessions\"],\n \"retentionPolicy\": {\n \"sessions\": \"30d\",\n \"tasks\": \"90d\",\n \"agents\": \"permanent\"\n }\n }\n}\n\\`\\`\\`\n\n## Best Practices\n- Use descriptive namespaces for different data types\n- Regular memory exports for backup purposes\n- Monitor memory usage with stats command\n- Clean up old sessions periodically\n\n## Memory Types\n- **Episodic**: Conversation and interaction history\n- **Semantic**: Factual knowledge and relationships\n- **Procedural**: Task patterns and workflows\n- **Meta**: System configuration and preferences\n\n## Integration Notes\n- Memory is automatically synchronized across agents\n- Search supports both exact match and semantic similarity\n- Memory contents are private to your local instance\n- No data is sent to external services without explicit commands\n`;\n}\n\n\nfunction createMinimalCoordinationMd(): string {\n return `# Agent Coordination\n\n## Quick Commands\n- \\`npx claude-flow agent spawn <type>\\`: Create new agent\n- \\`npx claude-flow agent list\\`: Show active agents\n- \\`npx claude-flow task create <type> <description>\\`: Create task\n\n## Agent Types\n- researcher, coder, analyst, coordinator, general\n`;\n}\n\n\nfunction createFullCoordinationMd(): string {\n return `# Agent Coordination System\n\n## Overview\nThe Claude-Flow coordination system manages multiple AI agents working together on complex tasks. It provides intelligent task distribution, resource management, and inter-agent communication.\n\n## Agent Types and Capabilities\n- **Researcher**: Web search, information gathering, knowledge synthesis\n- **Coder**: Code analysis, development, debugging, testing\n- **Analyst**: Data processing, pattern recognition, insights generation\n- **Coordinator**: Task planning, resource allocation, workflow management\n- **General**: Multi-purpose agent with balanced capabilities\n\n## Task Management\n- **Priority Levels**: 1 (lowest) to 10 (highest)\n- **Dependencies**: Tasks can depend on completion of other tasks\n- **Parallel Execution**: Independent tasks run concurrently\n- **Load Balancing**: Automatic distribution based on agent capacity\n\n## Coordination Commands\n\\`\\`\\`bash\n# Agent Management\nnpx claude-flow agent spawn <type> --name <name> --priority <1-10>\nnpx claude-flow agent list\nnpx claude-flow agent info <agent-id>\nnpx claude-flow agent terminate <agent-id>\n\n# Task Management \nnpx claude-flow task create <type> <description> --priority <1-10> --deps <task-ids>\nnpx claude-flow task list --verbose\nnpx claude-flow task status <task-id>\nnpx claude-flow task cancel <task-id>\n\n# System Monitoring\nnpx claude-flow status --verbose\nnpx claude-flow monitor --interval 5000\n\\`\\`\\`\n\n## Workflow Execution\nWorkflows are defined in JSON format and can orchestrate complex multi-agent operations:\n\\`\\`\\`bash\nnpx claude-flow workflow examples/research-workflow.json\nnpx claude-flow workflow examples/development-config.json --async\n\\`\\`\\`\n\n## Advanced Features\n- **Circuit Breakers**: Automatic failure handling and recovery\n- **Work Stealing**: Dynamic load redistribution for efficiency\n- **Resource Limits**: Memory and CPU usage constraints\n- **Metrics Collection**: Performance monitoring and optimization\n\n## Configuration\nCoordination settings in \\`claude-flow.config.json\\`:\n\\`\\`\\`json\n{\n \"orchestrator\": {\n \"maxConcurrentTasks\": 10,\n \"taskTimeout\": 300000,\n \"defaultPriority\": 5\n },\n \"agents\": {\n \"maxAgents\": 20,\n \"defaultCapabilities\": [\"research\", \"code\", \"terminal\"],\n \"resourceLimits\": {\n \"memory\": \"1GB\",\n \"cpu\": \"50%\"\n }\n }\n}\n\\`\\`\\`\n\n## Communication Patterns\n- **Direct Messaging**: Agent-to-agent communication\n- **Event Broadcasting**: System-wide notifications\n- **Shared Memory**: Common information access\n- **Task Handoff**: Seamless work transfer between agents\n\n## Best Practices\n- Start with general agents and specialize as needed\n- Use descriptive task names and clear requirements\n- Monitor system resources during heavy workloads\n- Implement proper error handling in workflows\n- Regular cleanup of completed tasks and inactive agents\n\n## Troubleshooting\n- Check agent health with \\`npx claude-flow status\\`\n- View detailed logs with \\`npx claude-flow monitor\\`\n- Restart stuck agents with terminate/spawn cycle\n- Use \\`--verbose\\` flags for detailed diagnostic information\n`;\n}\n\n\nfunction createAgentsReadme(): string {\n return `# Agent Memory Storage\n\n## Purpose\nThis directory stores agent-specific memory data, configurations, and persistent state information for individual Claude agents in the orchestration system.\n\n## Structure\nEach agent gets its own subdirectory for isolated memory storage:\n\n\\`\\`\\`\nmemory/agents/\nā”œā”€ā”€ agent_001/\n│ ā”œā”€ā”€ state.json # Agent state and configuration\n│ ā”œā”€ā”€ knowledge.md # Agent-specific knowledge base\n│ ā”œā”€ā”€ tasks.json # Completed and active tasks\n│ └── calibration.json # Agent-specific calibrations\nā”œā”€ā”€ agent_002/\n│ └── ...\n└── shared/\n ā”œā”€ā”€ common_knowledge.md # Shared knowledge across agents\n └── global_config.json # Global agent configurations\n\\`\\`\\`\n\n## Usage Guidelines\n1. **Agent Isolation**: Each agent should only read/write to its own directory\n2. **Shared Resources**: Use the \\`shared/\\` directory for cross-agent information\n3. **State Persistence**: Update state.json whenever agent status changes\n4. **Knowledge Sharing**: Document discoveries in knowledge.md files\n5. **Cleanup**: Remove directories for terminated agents periodically\n\n## Last Updated\n${new Date().toISOString()}\n`;\n}\n\n\nfunction createSessionsReadme(): string {\n return `# Session Memory Storage\n\n## Purpose\nThis directory stores session-based memory data, conversation history, and contextual information for development sessions using the Claude-Flow orchestration system.\n\n## Structure\nSessions are organized by date and session ID for easy retrieval:\n\n\\`\\`\\`\nmemory/sessions/\nā”œā”€ā”€ 2024-01-10/\n│ ā”œā”€ā”€ session_001/\n│ │ ā”œā”€ā”€ metadata.json # Session metadata and configuration\n│ │ ā”œā”€ā”€ conversation.md # Full conversation history\n│ │ ā”œā”€ā”€ decisions.md # Key decisions and rationale\n│ │ ā”œā”€ā”€ artifacts/ # Generated files and outputs\n│ │ └── coordination_state/ # Coordination system snapshots\n│ └── ...\n└── shared/\n ā”œā”€ā”€ patterns.md # Common session patterns\n └── templates/ # Session template files\n\\`\\`\\`\n\n## Usage Guidelines\n1. **Session Isolation**: Each session gets its own directory\n2. **Metadata Completeness**: Always fill out session metadata\n3. **Conversation Logging**: Document all significant interactions\n4. **Artifact Organization**: Structure generated files clearly\n5. **State Preservation**: Snapshot coordination state regularly\n\n## Last Updated\n${new Date().toISOString()}\n`;\n}\n\n"],"names":["chalk","getErrorMessage","success","error","warning","info","colors","bold","blue","yellow","Orchestrator","ConfigManager","EventBus","Logger","JsonPersistenceManager","swarmAction","SimpleMemoryManager","sparcAction","createMigrateCommand","enterpriseCommands","createFlowNexusClaudeMd","orchestrator","configManager","persistence","getPersistence","initialize","getOrchestrator","config","getConfigManager","eventBus","getInstance","logger","level","format","destination","load","setupCommands","cli","command","name","description","subcommands","options","short","type","defaultValue","action","ctx","initNeuralModule","force","flags","targetDir","target","initGoalModule","f","minimal","m","flowNexus","flowNexusClaudeMd","writeFile","mkdir","console","log","recursive","files","existingFiles","file","access","exists","then","catch","push","length","join","claudeMd","createMinimalClaudeMd","createFullClaudeMd","memoryBankMd","createMinimalMemoryBankMd","createFullMemoryBankMd","coordinationMd","createMinimalCoordinationMd","createFullCoordinationMd","directories","includes","unshift","dir","err","code","agentsReadme","createAgentsReadme","sessionsReadme","createSessionsReadme","initialData","agents","tasks","lastUpdated","Date","now","JSON","stringify","message","default","orch","start","daemon","controller","AbortController","shutdown","abort","process","on","Promise","resolve","signal","addEventListener","off","exit","aliases","subcommand","args","slice","persist","taskId","Math","random","toString","substr","saveTask","id","status","priority","dependencies","deps","split","metadata","progress","createdAt","getActiveTasks","task","verbose","agentId","getAllTasks","getAllAgents","find","t","agent","a","assignedAgent","workflowFile","readFile","content","workflow","parse","execute","agentCommand","enhancedCtx","cyan","agentManager","MemoryManager","DistributedMemorySystem","saveAgent","capabilities","getCapabilitiesForType","systemPrompt","prompt","getDefaultPromptForType","maxConcurrentTasks","maxTasks","getActiveAgents","enhancedStatusAction","watch","w","interval","i","component","c","json","detailed","healthCheck","history","stats","getStats","isRunning","activeAgents","totalAgents","pendingTasks","totalTasks","completedTasks","port","host","health","healthy","mcp","mcpConfig","get","auth","lines","memory","key","value","namespace","n","store","TextEncoder","encode","search","limit","l","results","query","limited","entry","substring","timestamp","toLocaleString","exportData","totalEntries","sizeBytes","toFixed","importData","namespaces","count","Object","entries","namespaceStats","days","d","removed","cleanup","taskEndIndex","startsWith","tools","parallel","research","instanceId","enhancedTask","replace","mode","coverage","commit","claudeCmd","noPermissions","dryRun","spawn","child","map","arg","env","CLAUDE_INSTANCE_ID","CLAUDE_FLOW_MODE","CLAUDE_FLOW_COVERAGE","CLAUDE_FLOW_COMMIT","CLAUDE_FLOW_MEMORY_ENABLED","CLAUDE_FLOW_MEMORY_NAMESPACE","CLAUDE_FLOW_COORDINATION_ENABLED","CLAUDE_FLOW_FEATURES","stdio","promises","toolsList","Array","isArray","skipPermissions","dangerouslySkipPermissions","CLAUDE_TASK_ID","CLAUDE_TASK_TYPE","all","failed","filter","s","enhancedMonitorAction","compact","focus","alerts","export","threshold","logLevel","noGraphs","Number","running","stdout","write","cycles","clear","currentStats","repeat","toLocaleTimeString","cpuUsage","memoryUsage","cpuColor","memoryColor","trend","from","floor","chars","setTimeout","batch","orchestration","migrateCmd","ui","enhancedSessionAction","enhancedStartAction","p","mcpTransport","u","v","autoStart","timeout","hiveMindCommand","initCommand","parseAsync","argv","spawnCommand","statusCommand","taskCommand","stopCommand","pauseCommand","resumeCommand","psCommand","wizardCommand","shell","reject","coordinator","researcher","implementer","analyst","custom","prompts","toISOString"],"mappings":"AAAA,OAAOA,WAAW,QAAQ;AAC1B,SAASC,eAAe,QAAQ,+BAA+B;AAC/D,SAAcC,OAAO,EAAEC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AM;gBACNC,aAAa;gBACbI,MAAM;YACR;YACA;gBACEL,MAAM;gBACNI,OAAO;gBACPH,aAAa;gBACbI,MAAM;YACR;YACA;gBACEL,MAAM;gBACNI,OAAO;gBACPH,aAAa;gBACbI,MAAM;YACR;YACA;gBACEL,MAAM;gBACNI,OAAO;gBACPH,aAAa;gBACbI,MAAM;YACR;YACA;gBACEL,MAAM;gBACNC,aAAa;gBACbI,MAAM;YACR;YACA;gBACEL,MAAM;gBACNC,aAAa;gBACbI,MAAM;YACR;YACA;gBACEL,MAAM;gBACNC,aAAa;gBACbI,MAAM;YACR;YACA;gBACEL,MAAM;gBACNC,aAAa;gBACbI,MAAM;YACR;YACA;gBACEL,MAAM;gBACNC,aAAa;gBACbI,MAAM;YACR;SACD;QACDE,QAAQ/B;IACV;IAGAsB,IAAIC,OAAO,CAAC;QACVC,MAAM;QACNC,aAAa;QACbE,SAAS;YACP;gBACEH,MAAM;gBACNI,OAAO;gBACPH,aAAa;gBACbI,MAAM;gBACN0D,SAAS;YACX;YACA;gBACE/D,MAAM;gBACNC,aAAa;gBACbI,MAAM;YACR;YACA;gBACEL,MAAM;gBACNI,OAAO;gBACPH,aAAa;gBACbI,MAAM;YACR;YACA;gBACEL,MAAM;gBACNI,OAAO;gBACPH,aAAa;gBACbI,MAAM;YACR;YACA;gBACEL,MAAM;gBACNI,OAAO;gBACPH,aAAa;gBACbI,MAAM;YACR;YACA;gBACEL,MAAM;gBACNC,aAAa;gBACbI,MAAM;gBACN0D,SAAS;YACX;YACA;gBACE/D,MAAM;gBACNC,aAAa;gBACbI,MAAM;YACR;YACA;gBACEL,MAAM;gBACNC,aAAa;gBACbI,MAAM;YACR;YACA;gBACEL,MAAM;gBACNC,aAAa;gBACbI,MAAM;gBACN0D,SAAS;YACX;SACD;QACDxD,QAAQ,OAAOC;YACb,IAAI;gBACFc,QAAQC,GAAG,CAAC9D,MAAM6J,IAAI,CAAC;gBACvBhG,QAAQC,GAAG,CAAC;gBAEZ,IAAIf,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