claude-flow 2.7.25 β 2.7.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +306 -0
- package/bin/claude-flow +60 -6
- package/dist/src/cli/help-formatter.js +0 -5
- package/dist/src/cli/simple-cli.js +0 -104
- package/dist/src/cli/simple-cli.js.map +1 -1
- package/dist/src/cli/simple-commands/config.js +257 -115
- package/dist/src/cli/simple-commands/config.js.map +1 -1
- package/dist/src/cli/simple-commands/init/index.js +0 -16
- package/dist/src/cli/simple-commands/init/index.js.map +1 -1
- package/dist/src/cli/simple-commands/memory.js +16 -1
- package/dist/src/cli/simple-commands/memory.js.map +1 -1
- package/dist/src/cli/validation-helper.js.map +1 -1
- package/dist/src/core/MCPIntegrator.js +0 -99
- package/dist/src/core/MCPIntegrator.js.map +1 -1
- package/dist/src/core/version.js +1 -1
- package/dist/src/memory/swarm-memory.js +348 -416
- package/dist/src/memory/swarm-memory.js.map +1 -1
- package/dist/src/utils/metrics-reader.js +10 -0
- package/docs/TRANSFORMER_INITIALIZATION_ISSUE.md +89 -17
- package/docs/V2.7.25_RELEASE_NOTES.md +249 -0
- package/docs/V2.7.26_RELEASE_SUMMARY.md +454 -0
- package/docs/V2.7.27_RELEASE_NOTES.md +208 -0
- package/docs/V2.7.27_TEST_REPORT.md +259 -0
- package/docs/V2.7.28_RELEASE_NOTES.md +205 -0
- package/package.json +2 -2
- package/src/cli/simple-commands/init/index.js +0 -13
- package/src/cli/simple-commands/memory.js +16 -1
- package/src/core/MCPIntegrator.ts +0 -51
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../../src/cli/simple-commands/init/index.js"],"sourcesContent":["// init/index.js - Initialize Claude Code integration files\nimport { printSuccess, printError, printWarning, exit } from '../../utils.js';\nimport { existsSync } from 'fs';\nimport process from 'process';\nimport os from 'os';\nimport { spawn, execSync } from 'child_process';\nimport { promisify } from 'util';\n\n// Helper to replace Deno.Command\nfunction runCommand(command, args, options = {}) {\n return new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n cwd: options.cwd,\n env: { ...process.env, ...options.env },\n stdio: options.stdout === 'inherit' ? 'inherit' : 'pipe'\n });\n \n let stdout = '';\n let stderr = '';\n \n if (options.stdout !== 'inherit') {\n child.stdout.on('data', (data) => { stdout += data; });\n child.stderr.on('data', (data) => { stderr += data; });\n }\n \n child.on('close', (code) => {\n if (code === 0) {\n resolve({ success: true, code, stdout, stderr });\n } else {\n reject(new Error(`Command failed with exit code ${code}`));\n }\n });\n \n child.on('error', reject);\n });\n}\nimport { createLocalExecutable } from './executable-wrapper.js';\nimport { createSparcStructureManually } from './sparc-structure.js';\nimport { createClaudeSlashCommands } from './claude-commands/slash-commands.js';\nimport { createOptimizedClaudeSlashCommands } from './claude-commands/optimized-slash-commands.js';\n// execSync imported above as execSyncOriginal\\nconst execSync = execSyncOriginal;\nimport { promises as fs } from 'fs';\nimport { copyTemplates } from './template-copier.js';\nimport { copyRevisedTemplates, validateTemplatesExist } from './copy-revised-templates.js';\nimport { copyAgentFiles, createAgentDirectories, validateAgentSystem, copyCommandFiles } from './agent-copier.js';\nimport { copySkillFiles, createSkillDirectories, validateSkillSystem } from './skills-copier.js';\nimport { showInitHelp } from './help.js';\nimport { batchInitCommand, batchInitFromConfig, validateBatchOptions } from './batch-init.js';\nimport { ValidationSystem, runFullValidation } from './validation/index.js';\nimport { RollbackSystem, createAtomicOperation } from './rollback/index.js';\nimport {\n createEnhancedClaudeMd,\n createEnhancedSettingsJson,\n createWrapperScript,\n createCommandDoc,\n createHelperScript,\n COMMAND_STRUCTURE,\n} from './templates/enhanced-templates.js';\nimport { createOptimizedSparcClaudeMd } from './templates/claude-md.js';\nimport { getIsolatedNpxEnv } from '../../../utils/npx-isolated-cache.js';\nimport { updateGitignore, needsGitignoreUpdate } from './gitignore-updater.js';\nimport {\n createFullClaudeMd,\n createSparcClaudeMd,\n createMinimalClaudeMd,\n} from './templates/claude-md.js';\nimport {\n createVerificationClaudeMd,\n createVerificationSettingsJson,\n} from './templates/verification-claude-md.js';\nimport {\n createFullMemoryBankMd,\n createMinimalMemoryBankMd,\n} from './templates/memory-bank-md.js';\nimport {\n createFullCoordinationMd,\n createMinimalCoordinationMd,\n} from './templates/coordination-md.js';\nimport { createAgentsReadme, createSessionsReadme } from './templates/readme-files.js';\nimport { \n initializeHiveMind, \n getHiveMindStatus,\n rollbackHiveMindInit\n} from './hive-mind-init.js';\n\n/**\n * Check if Claude Code CLI is installed\n */\nfunction isClaudeCodeInstalled() {\n try {\n execSync('which claude', { stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Set up MCP servers in Claude Code\n */\nasync function setupMcpServers(dryRun = false) {\n console.log('\\nπ Setting up MCP servers for Claude Code...');\n\n const servers = [\n {\n name: 'claude-flow',\n command: 'npx claude-flow@alpha mcp start',\n description: 'Claude Flow MCP server with swarm orchestration (alpha)',\n },\n {\n name: 'ruv-swarm',\n command: 'npx ruv-swarm mcp start',\n description: 'ruv-swarm MCP server for enhanced coordination',\n },\n {\n name: 'flow-nexus',\n command: 'npx flow-nexus@latest mcp start',\n description: 'Flow Nexus Complete MCP server for advanced AI orchestration',\n },\n {\n name: 'agentic-payments',\n command: 'npx agentic-payments@latest mcp',\n description: 'Agentic Payments MCP server for autonomous agent payment authorization',\n },\n ];\n\n for (const server of servers) {\n try {\n if (!dryRun) {\n console.log(` π Adding ${server.name}...`);\n execSync(`claude mcp add ${server.name} ${server.command}`, { stdio: 'inherit' });\n console.log(` β
Added ${server.name} - ${server.description}`);\n } else {\n console.log(` [DRY RUN] Would add ${server.name} - ${server.description}`);\n }\n } catch (err) {\n console.log(` β οΈ Failed to add ${server.name}: ${err.message}`);\n console.log(\n ` You can add it manually with: claude mcp add ${server.name} ${server.command}`,\n );\n }\n }\n\n if (!dryRun) {\n console.log('\\n π Verifying MCP servers...');\n try {\n execSync('claude mcp list', { stdio: 'inherit' });\n } catch (err) {\n console.log(' β οΈ Could not verify MCP servers');\n }\n }\n}\n\n/**\n * Create statusline script content (embedded fallback for binary builds)\n */\nfunction createStatuslineScript() {\n return `\n#!/bin/bash\n\n# Read JSON input from stdin\nINPUT=$(cat)\nMODEL=$(echo \"$INPUT\" | jq -r \\'.model.display_name // \"Claude\"\\')\nCWD=$(echo \"$INPUT\" | jq -r \\'.workspace.current_dir // .cwd\\')\nDIR=$(basename \"$CWD\")\n\n# Replace claude-code-flow with branded name\nif [ \"$DIR\" = \"claude-code-flow\" ]; then\n DIR=\"π Claude Flow\"\nfi\n\n# Get git branch\nBRANCH=$(cd \"$CWD\" 2>/dev/null && git branch --show-current 2>/dev/null)\n\n# Start building statusline\nprintf \"\\\\033[1m$MODEL\\\\033[0m in \\\\033[36m$DIR\\\\033[0m\"\n[ -n \"$BRANCH\" ] && printf \" on \\\\033[33mβ $BRANCH\\\\033[0m\"\n\n# Claude-Flow integration\nFLOW_DIR=\"$CWD/.claude-flow\"\n\nif [ -d \"$FLOW_DIR\" ]; then\n printf \" β\"\n\n # 1. Swarm Configuration & Topology\n if [ -f \"$FLOW_DIR/swarm-config.json\" ]; then\n STRATEGY=$(jq -r \\'.defaultStrategy // empty\\' \"$FLOW_DIR/swarm-config.json\" 2>/dev/null)\n if [ -n \"$STRATEGY\" ]; then\n # Map strategy to topology icon\n case \"$STRATEGY\" in\n \"balanced\") TOPO_ICON=\"β‘mesh\" ;;\n \"conservative\") TOPO_ICON=\"β‘hier\" ;;\n \"aggressive\") TOPO_ICON=\"β‘ring\" ;;\n *) TOPO_ICON=\"β‘$STRATEGY\" ;;\n esac\n printf \" \\\\033[35m$TOPO_ICON\\\\033[0m\"\n\n # Count agent profiles as \"configured agents\"\n AGENT_COUNT=$(jq -r \\'.agentProfiles | length\\' \"$FLOW_DIR/swarm-config.json\" 2>/dev/null)\n if [ -n \"$AGENT_COUNT\" ] && [ \"$AGENT_COUNT\" != \"null\" ] && [ \"$AGENT_COUNT\" -gt 0 ]; then\n printf \" \\\\033[35mπ€ $AGENT_COUNT\\\\033[0m\"\n fi\n fi\n fi\n\n # 2. Real-time System Metrics\n if [ -f \"$FLOW_DIR/metrics/system-metrics.json\" ]; then\n # Get latest metrics (last entry in array)\n LATEST=$(jq -r \\'.[-1]\\' \"$FLOW_DIR/metrics/system-metrics.json\" 2>/dev/null)\n\n if [ -n \"$LATEST\" ] && [ \"$LATEST\" != \"null\" ]; then\n # Memory usage\n MEM_PERCENT=$(echo \"$LATEST\" | jq -r \\'.memoryUsagePercent // 0\\' | awk \\'{printf \"%.0f\", $1}\\')\n if [ -n \"$MEM_PERCENT\" ] && [ \"$MEM_PERCENT\" != \"null\" ]; then\n # Color-coded memory (green <60%, yellow 60-80%, red >80%)\n if [ \"$MEM_PERCENT\" -lt 60 ]; then\n MEM_COLOR=\"\\\\033[32m\" # Green\n elif [ \"$MEM_PERCENT\" -lt 80 ]; then\n MEM_COLOR=\"\\\\033[33m\" # Yellow\n else\n MEM_COLOR=\"\\\\033[31m\" # Red\n fi\n printf \" \\${MEM_COLOR}πΎ \\${MEM_PERCENT}%\\\\033[0m\"\n fi\n\n # CPU load\n CPU_LOAD=$(echo \"$LATEST\" | jq -r \\'.cpuLoad // 0\\' | awk \\'{printf \"%.0f\", $1 * 100}\\')\n if [ -n \"$CPU_LOAD\" ] && [ \"$CPU_LOAD\" != \"null\" ]; then\n # Color-coded CPU (green <50%, yellow 50-75%, red >75%)\n if [ \"$CPU_LOAD\" -lt 50 ]; then\n CPU_COLOR=\"\\\\033[32m\" # Green\n elif [ \"$CPU_LOAD\" -lt 75 ]; then\n CPU_COLOR=\"\\\\033[33m\" # Yellow\n else\n CPU_COLOR=\"\\\\033[31m\" # Red\n fi\n printf \" \\${CPU_COLOR}β \\${CPU_LOAD}%\\\\033[0m\"\n fi\n fi\n fi\n\n # 3. Session State\n if [ -f \"$FLOW_DIR/session-state.json\" ]; then\n SESSION_ID=$(jq -r \\'.sessionId // empty\\' \"$FLOW_DIR/session-state.json\" 2>/dev/null)\n ACTIVE=$(jq -r \\'.active // false\\' \"$FLOW_DIR/session-state.json\" 2>/dev/null)\n\n if [ \"$ACTIVE\" = \"true\" ] && [ -n \"$SESSION_ID\" ]; then\n # Show abbreviated session ID\n SHORT_ID=$(echo \"$SESSION_ID\" | cut -d\\'-\\' -f1)\n printf \" \\\\033[34mπ $SHORT_ID\\\\033[0m\"\n fi\n fi\n\n # 4. Performance Metrics from task-metrics.json\n if [ -f \"$FLOW_DIR/metrics/task-metrics.json\" ]; then\n # Parse task metrics for success rate, avg time, and streak\n METRICS=$(jq -r \\'\n # Calculate metrics\n (map(select(.success == true)) | length) as $successful |\n (length) as $total |\n (if $total > 0 then ($successful / $total * 100) else 0 end) as $success_rate |\n (map(.duration // 0) | add / length) as $avg_duration |\n # Calculate streak (consecutive successes from end)\n (reverse |\n reduce .[] as $task (0;\n if $task.success == true then . + 1 else 0 end\n )\n ) as $streak |\n {\n success_rate: $success_rate,\n avg_duration: $avg_duration,\n streak: $streak,\n total: $total\n } | @json\n \\' \"$FLOW_DIR/metrics/task-metrics.json\" 2>/dev/null)\n\n if [ -n \"$METRICS\" ] && [ \"$METRICS\" != \"null\" ]; then\n # Success Rate\n SUCCESS_RATE=$(echo \"$METRICS\" | jq -r \\'.success_rate // 0\\' | awk \\'{printf \"%.0f\", $1}\\')\n TOTAL_TASKS=$(echo \"$METRICS\" | jq -r \\'.total // 0\\')\n\n if [ -n \"$SUCCESS_RATE\" ] && [ \"$TOTAL_TASKS\" -gt 0 ]; then\n # Color-code: Green (>80%), Yellow (60-80%), Red (<60%)\n if [ \"$SUCCESS_RATE\" -gt 80 ]; then\n SUCCESS_COLOR=\"\\\\033[32m\" # Green\n elif [ \"$SUCCESS_RATE\" -ge 60 ]; then\n SUCCESS_COLOR=\"\\\\033[33m\" # Yellow\n else\n SUCCESS_COLOR=\"\\\\033[31m\" # Red\n fi\n printf \" \\${SUCCESS_COLOR}π― \\${SUCCESS_RATE}%\\\\033[0m\"\n fi\n\n # Average Time\n AVG_TIME=$(echo \"$METRICS\" | jq -r \\'.avg_duration // 0\\')\n if [ -n \"$AVG_TIME\" ] && [ \"$TOTAL_TASKS\" -gt 0 ]; then\n # Format smartly: seconds, minutes, or hours\n if [ $(echo \"$AVG_TIME < 60\" | bc -l 2>/dev/null || echo 0) -eq 1 ]; then\n TIME_STR=$(echo \"$AVG_TIME\" | awk \\'{printf \"%.1fs\", $1}\\')\n elif [ $(echo \"$AVG_TIME < 3600\" | bc -l 2>/dev/null || echo 0) -eq 1 ]; then\n TIME_STR=$(echo \"$AVG_TIME\" | awk \\'{printf \"%.1fm\", $1/60}\\')\n else\n TIME_STR=$(echo \"$AVG_TIME\" | awk \\'{printf \"%.1fh\", $1/3600}\\')\n fi\n printf \" \\\\033[36mβ±οΈ $TIME_STR\\\\033[0m\"\n fi\n\n # Streak (only show if > 0)\n STREAK=$(echo \"$METRICS\" | jq -r \\'.streak // 0\\')\n if [ -n \"$STREAK\" ] && [ \"$STREAK\" -gt 0 ]; then\n printf \" \\\\033[91mπ₯ $STREAK\\\\033[0m\"\n fi\n fi\n fi\n\n # 5. Active Tasks (check for task files)\n if [ -d \"$FLOW_DIR/tasks\" ]; then\n TASK_COUNT=$(find \"$FLOW_DIR/tasks\" -name \"*.json\" -type f 2>/dev/null | wc -l)\n if [ \"$TASK_COUNT\" -gt 0 ]; then\n printf \" \\\\033[36mπ $TASK_COUNT\\\\033[0m\"\n fi\n fi\n\n # 6. Check for hooks activity\n if [ -f \"$FLOW_DIR/hooks-state.json\" ]; then\n HOOKS_ACTIVE=$(jq -r \\'.enabled // false\\' \"$FLOW_DIR/hooks-state.json\" 2>/dev/null)\n if [ \"$HOOKS_ACTIVE\" = \"true\" ]; then\n printf \" \\\\033[35mπ\\\\033[0m\"\n fi\n fi\nfi\n\necho\n`;\n}\n\nexport async function initCommand(subArgs, flags) {\n // Show help if requested\n if (flags.help || flags.h || subArgs.includes('--help') || subArgs.includes('-h')) {\n showInitHelp();\n return;\n }\n\n // Handle --env flag for .env template generation\n if (flags.env || subArgs.includes('--env')) {\n const { generateEnvTemplate } = await import('../env-template.js');\n const workingDir = process.env.PWD || process.cwd();\n const force = flags.force || flags.f;\n\n console.log('π Generating .env template file...\\n');\n const result = await generateEnvTemplate(workingDir, force);\n\n if (result.created) {\n console.log('\\nπ Next steps:');\n console.log('1. Open .env file and add your API keys');\n console.log('2. Get keys from:');\n console.log(' β’ Anthropic: https://console.anthropic.com/settings/keys');\n console.log(' β’ OpenRouter: https://openrouter.ai/keys');\n console.log('3. Enable memory: claude-flow agent run coder \"task\" --enable-memory\\n');\n console.log('π‘ See docs/REASONINGBANK-COST-OPTIMIZATION.md for cost savings tips');\n } else if (result.exists) {\n console.log('π‘ To overwrite: claude-flow init --env --force');\n }\n\n return;\n }\n\n // Check for verification flags first\n const hasVerificationFlags = subArgs.includes('--verify') || subArgs.includes('--pair') ||\n flags.verify || flags.pair;\n\n // Handle Flow Nexus minimal init\n if (flags['flow-nexus']) {\n return await flowNexusMinimalInit(flags, subArgs);\n }\n\n // Default to enhanced Claude Flow v2 init unless other modes are specified\n // Use --basic flag for old behavior, or verification flags for verification mode\n if (!flags.basic && !flags.minimal && !flags.sparc && !hasVerificationFlags) {\n return await enhancedClaudeFlowInit(flags, subArgs);\n }\n\n // Check for validation and rollback commands\n if (subArgs.includes('--validate') || subArgs.includes('--validate-only')) {\n return handleValidationCommand(subArgs, flags);\n }\n\n if (subArgs.includes('--rollback')) {\n return handleRollbackCommand(subArgs, flags);\n }\n\n if (subArgs.includes('--list-backups')) {\n return handleListBackups(subArgs, flags);\n }\n\n // Check for batch operations\n const batchInitFlag = flags['batch-init'] || subArgs.includes('--batch-init');\n const configFlag = flags.config || subArgs.includes('--config');\n\n if (batchInitFlag || configFlag) {\n return handleBatchInit(subArgs, flags);\n }\n\n // Check if enhanced initialization is requested\n const useEnhanced = subArgs.includes('--enhanced') || subArgs.includes('--safe');\n\n if (useEnhanced) {\n return enhancedInitCommand(subArgs, flags);\n }\n\n // Parse init options\n const initForce = subArgs.includes('--force') || subArgs.includes('-f') || flags.force;\n const initMinimal = subArgs.includes('--minimal') || subArgs.includes('-m') || flags.minimal;\n const initSparc = flags.roo || (subArgs && subArgs.includes('--roo')); // SPARC only with --roo flag\n const initDryRun = subArgs.includes('--dry-run') || subArgs.includes('-d') || flags.dryRun;\n const initOptimized = initSparc && initForce; // Use optimized templates when both flags are present\n const selectedModes = flags.modes ? flags.modes.split(',') : null; // Support selective mode initialization\n \n // Check for verification and pair programming flags\n const initVerify = subArgs.includes('--verify') || flags.verify;\n const initPair = subArgs.includes('--pair') || flags.pair;\n\n // Get the actual working directory (where the command was run from)\n // Use PWD environment variable which preserves the original directory\n const workingDir = process.env.PWD || cwd();\n console.log(`π Initializing in: ${workingDir}`);\n\n // Change to the working directory to ensure all file operations happen there\n try {\n process.chdir(workingDir);\n } catch (err) {\n printWarning(`Could not change to directory ${workingDir}: ${err.message}`);\n }\n\n try {\n printSuccess('Initializing Claude Code integration files...');\n\n // Check if files already exist in the working directory\n const files = ['CLAUDE.md', 'memory-bank.md', 'coordination.md'];\n const existingFiles = [];\n\n for (const file of files) {\n try {\n await fs.stat(`${workingDir}/${file}`);\n existingFiles.push(file);\n } catch {\n // File doesn't exist, which is what we want\n }\n }\n\n if (existingFiles.length > 0 && !initForce) {\n printWarning(`The following files already exist: ${existingFiles.join(', ')}`);\n console.log('Use --force to overwrite existing files');\n return;\n }\n\n // Use template copier to copy all template files\n const templateOptions = {\n sparc: initSparc,\n minimal: initMinimal,\n optimized: initOptimized,\n dryRun: initDryRun,\n force: initForce,\n selectedModes: selectedModes,\n verify: initVerify,\n pair: initPair,\n };\n\n // If verification flags are set, always use generated templates for CLAUDE.md and settings.json\n if (initVerify || initPair) {\n console.log(' π Creating verification-focused configuration...');\n \n // Create verification CLAUDE.md\n if (!initDryRun) {\n const { createVerificationClaudeMd, createVerificationSettingsJson } = await import('./templates/verification-claude-md.js');\n await fs.writeFile(`${workingDir}/CLAUDE.md`, createVerificationClaudeMd(), 'utf8');\n \n // Create .claude directory and settings\n await fs.mkdir(`${workingDir}/.claude`, { recursive: true });\n await fs.writeFile(`${workingDir}/.claude/settings.json`, createVerificationSettingsJson(), 'utf8');\n console.log(' β
Created verification-focused CLAUDE.md and settings.json');\n } else {\n console.log(' [DRY RUN] Would create verification-focused CLAUDE.md and settings.json');\n }\n \n // Copy other template files from repository if available\n const validation = validateTemplatesExist();\n if (validation.valid) {\n const revisedResults = await copyRevisedTemplates(workingDir, {\n force: initForce,\n dryRun: initDryRun,\n verbose: false,\n sparc: initSparc\n });\n }\n \n // Also create standard memory and coordination files\n const copyResults = await copyTemplates(workingDir, {\n ...templateOptions,\n skipClaudeMd: true, // Don't overwrite the verification CLAUDE.md\n skipSettings: true // Don't overwrite the verification settings.json\n });\n \n } else {\n // Standard template copying logic\n const validation = validateTemplatesExist();\n if (validation.valid) {\n console.log(' π Copying revised template files...');\n const revisedResults = await copyRevisedTemplates(workingDir, {\n force: initForce,\n dryRun: initDryRun,\n verbose: true,\n sparc: initSparc\n });\n\n if (revisedResults.success) {\n console.log(` β
Copied ${revisedResults.copiedFiles.length} template files`);\n if (revisedResults.skippedFiles.length > 0) {\n console.log(` βοΈ Skipped ${revisedResults.skippedFiles.length} existing files`);\n }\n } else {\n console.log(' β οΈ Some template files could not be copied:');\n revisedResults.errors.forEach(err => console.log(` - ${err}`));\n }\n } else {\n // Fall back to generated templates\n console.log(' β οΈ Revised templates not available, using generated templates');\n const copyResults = await copyTemplates(workingDir, templateOptions);\n\n if (!copyResults.success) {\n printError('Failed to copy templates:');\n copyResults.errors.forEach(err => console.log(` β ${err}`));\n return;\n }\n }\n }\n\n // Agent setup moved to end of function where execution is guaranteed\n\n // Directory structure is created by template copier\n\n // SPARC files are created by template copier when --sparc flag is used\n\n // Memory README files and persistence database are created by template copier\n\n // Create local claude-flow@alpha executable wrapper\n if (!initDryRun) {\n await createLocalExecutable(workingDir);\n } else {\n console.log(' [DRY RUN] Would create local claude-flow@alpha executable wrapper');\n }\n\n // SPARC initialization\n if (initSparc) {\n console.log('\\nπ Initializing SPARC development environment...');\n\n if (initDryRun) {\n console.log(' [DRY RUN] Would run: npx -y create-sparc init --force');\n console.log(' [DRY RUN] Would create SPARC environment with all modes');\n console.log(\n ' [DRY RUN] Would create Claude slash commands' +\n (initOptimized ? ' (Batchtools-optimized)' : ''),\n );\n if (selectedModes) {\n console.log(\n ` [DRY RUN] Would create commands for selected modes: ${selectedModes.join(', ')}`,\n );\n }\n } else {\n // Check if create-sparc exists and run it\n let sparcInitialized = false;\n try {\n // Use isolated NPX cache to prevent concurrent conflicts\n console.log(' π Running: npx -y create-sparc init --force');\n const createSparcResult = await runCommand('npx', ['-y', 'create-sparc', 'init', '--force'], {\n cwd: workingDir,\n stdout: 'inherit',\n stderr: 'inherit',\n env: getIsolatedNpxEnv({\n PWD: workingDir,\n }),\n });\n\n if (createSparcResult.success) {\n console.log(' β
SPARC environment initialized successfully');\n sparcInitialized = true;\n } else {\n printWarning('create-sparc failed, creating basic SPARC structure manually...');\n\n // Fallback: create basic SPARC structure manually\n await createSparcStructureManually();\n sparcInitialized = true; // Manual creation still counts as initialized\n }\n } catch (err) {\n printWarning('create-sparc not available, creating basic SPARC structure manually...');\n\n // Fallback: create basic SPARC structure manually\n await createSparcStructureManually();\n sparcInitialized = true; // Manual creation still counts as initialized\n }\n\n // Always create Claude slash commands after SPARC initialization\n if (sparcInitialized) {\n try {\n if (initOptimized) {\n await createOptimizedClaudeSlashCommands(workingDir, selectedModes);\n } else {\n await createClaudeSlashCommands(workingDir);\n }\n } catch (err) {\n // Legacy slash command creation - silently skip if it fails\n // SPARC slash commands are already created successfully above\n }\n }\n }\n }\n\n if (initDryRun) {\n printSuccess(\"π Dry run completed! Here's what would be created:\");\n console.log('\\nπ Summary of planned initialization:');\n console.log(\n ` β’ Configuration: ${initOptimized ? 'Batchtools-optimized SPARC' : initSparc ? 'SPARC-enhanced' : 'Standard'}`,\n );\n console.log(\n ` β’ Template type: ${initOptimized ? 'Optimized for parallel processing' : 'Standard'}`,\n );\n console.log(' β’ Core files: CLAUDE.md, memory-bank.md, coordination.md');\n console.log(' β’ Directory structure: memory/, coordination/, .claude/');\n console.log(' β’ Local executable: ./claude-flow@alpha');\n if (initSparc) {\n console.log(\n ` β’ Claude Code slash commands: ${selectedModes ? selectedModes.length : 'All'} SPARC mode commands`,\n );\n console.log(' β’ SPARC environment with all development modes');\n }\n if (initOptimized) {\n console.log(' β’ Batchtools optimization: Enabled for parallel processing');\n console.log(' β’ Performance enhancements: Smart batching, concurrent operations');\n }\n console.log('\\nπ To proceed with initialization, run the same command without --dry-run');\n } else {\n printSuccess('π Claude Code integration files initialized successfully!');\n\n if (initOptimized) {\n console.log('\\nβ‘ Batchtools Optimization Enabled!');\n console.log(' β’ Parallel processing capabilities activated');\n console.log(' β’ Performance improvements: 250-500% faster operations');\n console.log(' β’ Smart batching and concurrent operations available');\n }\n\n console.log('\\nπ What was created:');\n console.log(\n ` β
CLAUDE.md (${initOptimized ? 'Batchtools-optimized' : initSparc ? 'SPARC-enhanced' : 'Standard configuration'})`,\n );\n console.log(\n ` β
memory-bank.md (${initOptimized ? 'With parallel processing' : 'Standard memory system'})`,\n );\n console.log(\n ` β
coordination.md (${initOptimized ? 'Enhanced with batchtools' : 'Standard coordination'})`,\n );\n console.log(' β
Directory structure with memory/ and coordination/');\n console.log(' β
Local executable at ./claude-flow@alpha');\n console.log(' β
Persistence database at memory/claude-flow@alpha-data.json');\n console.log(' β
Agent system with 64 specialized agents in .claude/agents/');\n\n if (initSparc) {\n const modeCount = selectedModes ? selectedModes.length : '20+';\n console.log(` β
Claude Code slash commands (${modeCount} SPARC modes)`);\n console.log(' β
Complete SPARC development environment');\n }\n\n console.log('\\nπ Next steps:');\n console.log('1. Review and customize the generated files for your project');\n console.log(\"2. Run './claude-flow@alpha start' to begin the orchestration system\");\n console.log(\"3. Use './claude-flow@alpha' instead of 'npx claude-flow@alpha' for all commands\");\n console.log(\"4. Use 'claude --dangerously-skip-permissions' for unattended operation\");\n\n if (initSparc) {\n console.log(\n '5. Use Claude Code slash commands: /sparc, /sparc-architect, /sparc-tdd, etc.',\n );\n console.log(\"6. Explore SPARC modes with './claude-flow@alpha sparc modes'\");\n console.log('7. Try TDD workflow with \\'./claude-flow@alpha sparc tdd \"your task\"\\'');\n\n if (initOptimized) {\n console.log('8. Use batchtools commands: /batchtools, /performance for optimization');\n console.log('9. Enable parallel processing with --parallel flags');\n console.log(\"10. Monitor performance with './claude-flow@alpha performance monitor'\");\n }\n }\n\n // Update .gitignore\n const gitignoreResult = await updateGitignore(workingDir, initForce, initDryRun);\n if (gitignoreResult.success) {\n if (!initDryRun) {\n console.log(` β
${gitignoreResult.message}`);\n } else {\n console.log(` ${gitignoreResult.message}`);\n }\n } else {\n console.log(` β οΈ ${gitignoreResult.message}`);\n }\n\n console.log('\\nπ‘ Tips:');\n console.log(\" β’ Type '/' in Claude Code to see all available slash commands\");\n console.log(\" β’ Use './claude-flow@alpha status' to check system health\");\n console.log(\" β’ Store important context with './claude-flow@alpha memory store'\");\n\n if (initOptimized) {\n console.log(' β’ Use --parallel flags for concurrent operations');\n console.log(' β’ Enable batch processing for multiple related tasks');\n console.log(' β’ Monitor performance with real-time metrics');\n }\n\n // Initialize hive-mind system for standard init\n console.log('\\nπ§ Initializing basic hive-mind system...');\n try {\n const hiveMindOptions = {\n config: {\n integration: {\n claudeCode: { enabled: isClaudeCodeInstalled() },\n mcpTools: { enabled: true }\n },\n monitoring: { enabled: false } // Basic setup for standard init\n }\n };\n \n const hiveMindResult = await initializeHiveMind(workingDir, hiveMindOptions, false);\n \n if (hiveMindResult.success) {\n console.log(' β
Basic hive-mind system initialized');\n console.log(' π‘ Use \"npx claude-flow@alpha hive-mind\" for advanced features');\n } else {\n console.log(` β οΈ Hive-mind setup skipped: ${hiveMindResult.error}`);\n }\n } catch (err) {\n console.log(` β οΈ Hive-mind setup skipped: ${err.message}`);\n }\n\n // Check for Claude Code and set up MCP servers (always enabled by default)\n if (!initDryRun && isClaudeCodeInstalled()) {\n console.log('\\nπ Claude Code CLI detected!');\n const skipMcp = subArgs && subArgs.includes && subArgs.includes('--skip-mcp');\n\n if (!skipMcp) {\n await setupMcpServers(initDryRun);\n } else {\n console.log(' βΉοΈ Skipping MCP setup (--skip-mcp flag used)');\n }\n } else if (!initDryRun && !isClaudeCodeInstalled()) {\n console.log('\\nβ οΈ Claude Code CLI not detected!');\n console.log(' π₯ Install with: npm install -g @anthropic-ai/claude-code');\n console.log(' π Then add MCP servers manually with:');\n console.log(' claude mcp add claude-flow npx claude-flow@alpha mcp start');\n console.log(' claude mcp add ruv-swarm npx ruv-swarm mcp start');\n console.log(' claude mcp add flow-nexus npx flow-nexus@latest mcp start');\n console.log(' claude mcp add agentic-payments npx agentic-payments@latest mcp');\n }\n }\n } catch (err) {\n printError(`Failed to initialize files: ${err.message}`);\n }\n}\n\n// Handle batch initialization\nasync function handleBatchInit(subArgs, flags) {\n try {\n // Options parsing from flags and subArgs\n const options = {\n parallel: !flags['no-parallel'] && flags.parallel !== false,\n sparc: flags.sparc || flags.s,\n minimal: flags.minimal || flags.m,\n force: flags.force || flags.f,\n maxConcurrency: flags['max-concurrent'] || 5,\n progressTracking: true,\n template: flags.template,\n environments: flags.environments\n ? flags.environments.split(',').map((env) => env.trim())\n : ['dev'],\n };\n\n // Validate options\n const validationErrors = validateBatchOptions(options);\n if (validationErrors.length > 0) {\n printError('Batch options validation failed:');\n validationErrors.forEach((error) => console.error(` - ${error}`));\n return;\n }\n\n // Config file mode\n if (flags.config) {\n const configFile = flags.config;\n printSuccess(`Loading batch configuration from: ${configFile}`);\n const results = await batchInitFromConfig(configFile, options);\n if (results) {\n printSuccess('Batch initialization from config completed');\n }\n return;\n }\n\n // Batch init mode\n if (flags['batch-init']) {\n const projectsString = flags['batch-init'];\n const projects = projectsString.split(',').map((project) => project.trim());\n\n if (projects.length === 0) {\n printError('No projects specified for batch initialization');\n return;\n }\n\n printSuccess(`Initializing ${projects.length} projects in batch mode`);\n const results = await batchInitCommand(projects, options);\n\n if (results) {\n const successful = results.filter((r) => r.success).length;\n const failed = results.filter((r) => !r.success).length;\n\n if (failed === 0) {\n printSuccess(`All ${successful} projects initialized successfully`);\n } else {\n printWarning(`${successful} projects succeeded, ${failed} failed`);\n }\n }\n return;\n }\n\n printError('No batch operation specified. Use --batch-init <projects> or --config <file>');\n } catch (err) {\n printError(`Batch initialization failed: ${err.message}`);\n }\n}\n\n/**\n * Enhanced initialization command with validation and rollback\n */\nasync function enhancedInitCommand(subArgs, flags) {\n console.log('π‘οΈ Starting enhanced initialization with validation and rollback...');\n\n // Store parameters to avoid scope issues in async context\n const args = subArgs || [];\n const options = flags || {};\n\n // Get the working directory\n const workingDir = process.env.PWD || process.cwd();\n\n // Initialize systems\n const rollbackSystem = new RollbackSystem(workingDir);\n const validationSystem = new ValidationSystem(workingDir);\n\n let atomicOp = null;\n\n try {\n // Parse options\n const initOptions = {\n force: args.includes('--force') || args.includes('-f') || options.force,\n minimal: args.includes('--minimal') || args.includes('-m') || options.minimal,\n sparc: args.includes('--sparc') || args.includes('-s') || options.sparc,\n skipPreValidation: args.includes('--skip-pre-validation'),\n skipBackup: args.includes('--skip-backup'),\n validateOnly: args.includes('--validate-only'),\n };\n\n // Phase 1: Pre-initialization validation\n if (!initOptions.skipPreValidation) {\n console.log('\\nπ Phase 1: Pre-initialization validation...');\n const preValidation = await validationSystem.validatePreInit(initOptions);\n\n if (!preValidation.success) {\n printError('Pre-initialization validation failed:');\n preValidation.errors.forEach((error) => console.error(` β ${error}`));\n return;\n }\n\n if (preValidation.warnings.length > 0) {\n printWarning('Pre-initialization warnings:');\n preValidation.warnings.forEach((warning) => console.warn(` β οΈ ${warning}`));\n }\n\n printSuccess('Pre-initialization validation passed');\n }\n\n // Stop here if validation-only mode\n if (options.validateOnly) {\n console.log('\\nβ
Validation-only mode completed');\n return;\n }\n\n // Phase 2: Create backup\n if (!options.skipBackup) {\n console.log('\\nπΎ Phase 2: Creating backup...');\n const backupResult = await rollbackSystem.createPreInitBackup();\n\n if (!backupResult.success) {\n printError('Backup creation failed:');\n backupResult.errors.forEach((error) => console.error(` β ${error}`));\n return;\n }\n }\n\n // Phase 3: Initialize with atomic operations\n console.log('\\nπ§ Phase 3: Atomic initialization...');\n atomicOp = createAtomicOperation(rollbackSystem, 'enhanced-init');\n\n const atomicBegin = await atomicOp.begin();\n if (!atomicBegin) {\n printError('Failed to begin atomic operation');\n return;\n }\n\n // Perform initialization steps with checkpoints\n await performInitializationWithCheckpoints(rollbackSystem, options, workingDir, dryRun);\n\n // Phase 4: Post-initialization validation\n console.log('\\nβ
Phase 4: Post-initialization validation...');\n const postValidation = await validationSystem.validatePostInit();\n\n if (!postValidation.success) {\n printError('Post-initialization validation failed:');\n postValidation.errors.forEach((error) => console.error(` β ${error}`));\n\n // Attempt automatic rollback\n console.log('\\nπ Attempting automatic rollback...');\n await atomicOp.rollback();\n printWarning('Initialization rolled back due to validation failure');\n return;\n }\n\n // Phase 5: Configuration validation\n console.log('\\nπ§ Phase 5: Configuration validation...');\n const configValidation = await validationSystem.validateConfiguration();\n\n if (configValidation.warnings.length > 0) {\n printWarning('Configuration warnings:');\n configValidation.warnings.forEach((warning) => console.warn(` β οΈ ${warning}`));\n }\n\n // Phase 6: Health checks\n console.log('\\nπ₯ Phase 6: System health checks...');\n const healthChecks = await validationSystem.runHealthChecks();\n\n if (healthChecks.warnings.length > 0) {\n printWarning('Health check warnings:');\n healthChecks.warnings.forEach((warning) => console.warn(` β οΈ ${warning}`));\n }\n\n // Commit atomic operation\n await atomicOp.commit();\n\n // Generate and display validation report\n const fullValidation = await runFullValidation(workingDir, {\n postInit: true,\n skipPreInit: options.skipPreValidation,\n });\n\n console.log('\\nπ Validation Report:');\n console.log(fullValidation.report);\n\n printSuccess('π Enhanced initialization completed successfully!');\n console.log('\\nβ¨ Your SPARC environment is fully validated and ready to use');\n } catch (error) {\n printError(`Enhanced initialization failed: ${error.message}`);\n\n // Attempt rollback if atomic operation is active\n if (atomicOp && !atomicOp.completed) {\n console.log('\\nπ Performing emergency rollback...');\n try {\n await atomicOp.rollback();\n printWarning('Emergency rollback completed');\n } catch (rollbackError) {\n printError(`Rollback also failed: ${rollbackError.message}`);\n }\n }\n }\n}\n\n/**\n * Handle validation commands\n */\nasync function handleValidationCommand(subArgs, flags) {\n const workingDir = process.env.PWD || process.cwd();\n\n console.log('π Running validation checks...');\n\n const options = {\n skipPreInit: subArgs.includes('--skip-pre-init'),\n skipConfig: subArgs.includes('--skip-config'),\n skipModeTest: subArgs.includes('--skip-mode-test'),\n postInit: !subArgs.includes('--pre-init-only'),\n };\n\n try {\n const validationResults = await runFullValidation(workingDir, options);\n\n console.log('\\nπ Validation Results:');\n console.log(validationResults.report);\n\n if (validationResults.success) {\n printSuccess('β
All validation checks passed');\n } else {\n printError('β Some validation checks failed');\n process.exit(1);\n }\n } catch (error) {\n printError(`Validation failed: ${error.message}`);\n process.exit(1);\n }\n}\n\n/**\n * Handle rollback commands\n */\nasync function handleRollbackCommand(subArgs, flags) {\n const workingDir = process.env.PWD || process.cwd();\n const rollbackSystem = new RollbackSystem(workingDir);\n\n try {\n // Check for specific rollback options\n if (subArgs.includes('--full')) {\n console.log('π Performing full rollback...');\n const result = await rollbackSystem.performFullRollback();\n\n if (result.success) {\n printSuccess('Full rollback completed successfully');\n } else {\n printError('Full rollback failed:');\n result.errors.forEach((error) => console.error(` β ${error}`));\n }\n } else if (subArgs.includes('--partial')) {\n const phaseIndex = subArgs.findIndex((arg) => arg === '--phase');\n if (phaseIndex !== -1 && subArgs[phaseIndex + 1]) {\n const phase = subArgs[phaseIndex + 1];\n console.log(`π Performing partial rollback for phase: ${phase}`);\n\n const result = await rollbackSystem.performPartialRollback(phase);\n\n if (result.success) {\n printSuccess(`Partial rollback completed for phase: ${phase}`);\n } else {\n printError(`Partial rollback failed for phase: ${phase}`);\n result.errors.forEach((error) => console.error(` β ${error}`));\n }\n } else {\n printError('Partial rollback requires --phase <phase-name>');\n }\n } else {\n // Interactive rollback point selection\n const rollbackPoints = await rollbackSystem.listRollbackPoints();\n\n if (rollbackPoints.rollbackPoints.length === 0) {\n printWarning('No rollback points available');\n return;\n }\n\n console.log('\\nπ Available rollback points:');\n rollbackPoints.rollbackPoints.forEach((point, index) => {\n const date = new Date(point.timestamp).toLocaleString();\n console.log(` ${index + 1}. ${point.type} - ${date}`);\n });\n\n // For now, rollback to the most recent point\n const latest = rollbackPoints.rollbackPoints[0];\n if (latest) {\n console.log(\n `\\nπ Rolling back to: ${latest.type} (${new Date(latest.timestamp).toLocaleString()})`,\n );\n const result = await rollbackSystem.performFullRollback(latest.backupId);\n\n if (result.success) {\n printSuccess('Rollback completed successfully');\n } else {\n printError('Rollback failed');\n }\n }\n }\n } catch (error) {\n printError(`Rollback operation failed: ${error.message}`);\n }\n}\n\n/**\n * Handle list backups command\n */\nasync function handleListBackups(subArgs, flags) {\n const workingDir = process.env.PWD || process.cwd();\n const rollbackSystem = new RollbackSystem(workingDir);\n\n try {\n const rollbackPoints = await rollbackSystem.listRollbackPoints();\n\n console.log('\\nπ Rollback Points and Backups:');\n\n if (rollbackPoints.rollbackPoints.length === 0) {\n console.log(' No rollback points available');\n } else {\n console.log('\\nπ Rollback Points:');\n rollbackPoints.rollbackPoints.forEach((point, index) => {\n const date = new Date(point.timestamp).toLocaleString();\n console.log(` ${index + 1}. ${point.type} - ${date} (${point.backupId || 'No backup'})`);\n });\n }\n\n if (rollbackPoints.checkpoints.length > 0) {\n console.log('\\nπ Checkpoints:');\n rollbackPoints.checkpoints.slice(-5).forEach((checkpoint, index) => {\n const date = new Date(checkpoint.timestamp).toLocaleString();\n console.log(` ${index + 1}. ${checkpoint.phase} - ${date} (${checkpoint.status})`);\n });\n }\n } catch (error) {\n printError(`Failed to list backups: ${error.message}`);\n }\n}\n\n/**\n * Perform initialization with checkpoints\n */\nasync function performInitializationWithCheckpoints(\n rollbackSystem,\n options,\n workingDir,\n dryRun = false,\n) {\n const phases = [\n { name: 'file-creation', action: () => createInitialFiles(options, workingDir, dryRun) },\n { name: 'directory-structure', action: () => createDirectoryStructure(workingDir, dryRun) },\n { name: 'memory-setup', action: () => setupMemorySystem(workingDir, dryRun) },\n { name: 'coordination-setup', action: () => setupCoordinationSystem(workingDir, dryRun) },\n { name: 'executable-creation', action: () => createLocalExecutable(workingDir, dryRun) },\n ];\n\n if (options.sparc) {\n phases.push(\n { name: 'sparc-init', action: () => createSparcStructureManually() },\n { name: 'claude-commands', action: () => createClaudeSlashCommands(workingDir) },\n );\n }\n\n for (const phase of phases) {\n console.log(` π§ ${phase.name}...`);\n\n // Create checkpoint before phase\n await rollbackSystem.createCheckpoint(phase.name, {\n timestamp: Date.now(),\n phase: phase.name,\n });\n\n try {\n await phase.action();\n console.log(` β
${phase.name} completed`);\n } catch (error) {\n console.error(` β ${phase.name} failed: ${error.message}`);\n throw error;\n }\n }\n}\n\n// Helper functions for atomic initialization\nasync function createInitialFiles(options, workingDir, dryRun = false) {\n if (!dryRun) {\n const claudeMd = options.sparc\n ? createSparcClaudeMd()\n : options.minimal\n ? createMinimalClaudeMd()\n : createFullClaudeMd();\n await fs.writeFile(`${workingDir}/CLAUDE.md`, claudeMd, 'utf8');\n\n const memoryBankMd = options.minimal ? createMinimalMemoryBankMd() : createFullMemoryBankMd();\n await fs.writeFile(`${workingDir}/memory-bank.md`, memoryBankMd, 'utf8');\n\n const coordinationMd = options.minimal\n ? createMinimalCoordinationMd()\n : createFullCoordinationMd();\n await fs.writeFile(`${workingDir}/coordination.md`, coordinationMd, 'utf8');\n }\n}\n\nasync function createDirectoryStructure(workingDir, dryRun = false) {\n const directories = [\n 'memory',\n 'memory/agents',\n 'memory/sessions',\n 'coordination',\n 'coordination/memory_bank',\n 'coordination/subtasks',\n 'coordination/orchestration',\n '.claude',\n '.claude/commands',\n '.claude/logs',\n ];\n\n if (!dryRun) {\n for (const dir of directories) {\n await fs.mkdir(`${workingDir}/${dir}`, { recursive: true });\n }\n }\n}\n\nasync function setupMemorySystem(workingDir, dryRun = false) {\n if (!dryRun) {\n const initialData = { agents: [], tasks: [], lastUpdated: Date.now() };\n await fs.writeFile(\n `${workingDir}/memory/claude-flow@alpha-data.json`, JSON.stringify(initialData, null, 2), 'utf8'\n );\n\n await fs.writeFile(`${workingDir}/memory/agents/README.md`, createAgentsReadme(), 'utf8');\n await fs.writeFile(`${workingDir}/memory/sessions/README.md`, createSessionsReadme(), 'utf8');\n }\n}\n\nasync function setupCoordinationSystem(workingDir, dryRun = false) {\n // Coordination system is already set up by createDirectoryStructure\n // This is a placeholder for future coordination setup logic\n}\n\n/**\n * Setup monitoring and telemetry for token tracking\n */\nasync function setupMonitoring(workingDir) {\n console.log(' π Configuring token usage tracking...');\n \n const fs = await import('fs/promises');\n const path = await import('path');\n \n try {\n // Create .claude-flow@alpha directory for tracking data\n const trackingDir = path.join(workingDir, '.claude-flow@alpha');\n await fs.mkdir(trackingDir, { recursive: true });\n \n // Create initial token usage file\n const tokenUsageFile = path.join(trackingDir, 'token-usage.json');\n const initialData = {\n total: 0,\n input: 0,\n output: 0,\n byAgent: {},\n lastUpdated: new Date().toISOString()\n };\n \n await fs.writeFile(tokenUsageFile, JSON.stringify(initialData, null, 2));\n printSuccess(' β Created token usage tracking file');\n \n // Add telemetry configuration to .claude/settings.json if it exists\n const settingsPath = path.join(workingDir, '.claude', 'settings.json');\n try {\n const settingsContent = await fs.readFile(settingsPath, 'utf8');\n const settings = JSON.parse(settingsContent);\n \n // Add telemetry hook\n if (!settings.hooks) settings.hooks = {};\n if (!settings.hooks['post-task']) settings.hooks['post-task'] = [];\n \n // Add token tracking hook\n const tokenTrackingHook = 'npx claude-flow@alpha internal track-tokens --session-id {{session_id}} --tokens {{token_usage}}';\n if (!settings.hooks['post-task'].includes(tokenTrackingHook)) {\n settings.hooks['post-task'].push(tokenTrackingHook);\n }\n \n await fs.writeFile(settingsPath, JSON.stringify(settings, null, 2));\n printSuccess(' β Added token tracking hooks to settings');\n } catch (err) {\n console.log(' β οΈ Could not update settings.json:', err.message);\n }\n \n // Create monitoring configuration\n const monitoringConfig = {\n enabled: true,\n telemetry: {\n claudeCode: {\n env: 'CLAUDE_CODE_ENABLE_TELEMETRY',\n value: '1',\n description: 'Enable Claude Code OpenTelemetry metrics'\n }\n },\n tracking: {\n tokens: true,\n costs: true,\n agents: true,\n sessions: true\n },\n storage: {\n location: '.claude-flow@alpha/token-usage.json',\n format: 'json',\n rotation: 'monthly'\n }\n };\n \n const configPath = path.join(trackingDir, 'monitoring.config.json');\n await fs.writeFile(configPath, JSON.stringify(monitoringConfig, null, 2));\n printSuccess(' β Created monitoring configuration');\n \n // Create shell profile snippet for environment variable\n const envSnippet = `\n# Claude Flow Token Tracking\n# Add this to your shell profile (.bashrc, .zshrc, etc.)\nexport CLAUDE_CODE_ENABLE_TELEMETRY=1\n\n# Optional: Set custom metrics path\n# export CLAUDE_METRICS_PATH=\"$HOME/.claude/metrics\"\n`;\n \n const envPath = path.join(trackingDir, 'env-setup.sh');\n await fs.writeFile(envPath, envSnippet.trim());\n printSuccess(' β Created environment setup script');\n \n console.log('\\n π To enable Claude Code telemetry:');\n console.log(' 1. Add to your shell profile: export CLAUDE_CODE_ENABLE_TELEMETRY=1');\n console.log(' 2. Or run: source .claude-flow@alpha/env-setup.sh');\n console.log('\\n π‘ Token usage will be tracked in .claude-flow@alpha/token-usage.json');\n console.log(' Run: claude-flow@alpha analysis token-usage --breakdown --cost-analysis');\n \n } catch (err) {\n printError(` Failed to setup monitoring: ${err.message}`);\n }\n}\n\n/**\n * Enhanced Claude Flow v2.0.0 initialization\n */\nasync function enhancedClaudeFlowInit(flags, subArgs = []) {\n console.log('π Initializing Claude Flow v2.0.0 with enhanced features...');\n\n const workingDir = process.cwd();\n const force = flags.force || flags.f;\n const dryRun = flags.dryRun || flags['dry-run'] || flags.d;\n const initSparc = flags.roo || (subArgs && subArgs.includes('--roo')); // SPARC only with --roo flag\n\n // Parse --agent flag for specialized agent setup\n const agentType = flags.agent || (subArgs && subArgs.find(arg => arg.startsWith('--agent='))?.split('=')[1]);\n const initReasoning = agentType === 'reasoning' || (subArgs && subArgs.includes('--agent') && subArgs.includes('reasoning'));\n\n // Store parameters to avoid scope issues in async context\n const args = subArgs || [];\n const options = flags || {};\n\n // Import fs, path, and os modules for Node.js\n const fs = await import('fs/promises');\n const { chmod } = fs;\n const path = await import('path');\n const os = await import('os');\n\n try {\n // Check existing files\n const existingFiles = [];\n const filesToCheck = [\n 'CLAUDE.md',\n '.claude/settings.json',\n '.mcp.json',\n // Removed claude-flow@alpha.config.json per user request\n ];\n\n for (const file of filesToCheck) {\n if (existsSync(`${workingDir}/${file}`)) {\n existingFiles.push(file);\n }\n }\n\n if (existingFiles.length > 0 && !force) {\n printWarning(`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 if (!dryRun) {\n await fs.writeFile(`${workingDir}/CLAUDE.md`, createOptimizedSparcClaudeMd(), 'utf8');\n printSuccess('β Created CLAUDE.md (Claude Flow v2.0.0 - Optimized)');\n } else {\n console.log('[DRY RUN] Would create CLAUDE.md (Claude Flow v2.0.0 - Optimized)');\n }\n\n // Create .claude directory structure\n const claudeDir = `${workingDir}/.claude`;\n if (!dryRun) {\n await fs.mkdir(claudeDir, { recursive: true });\n await fs.mkdir(`${claudeDir}/commands`, { recursive: true });\n await fs.mkdir(`${claudeDir}/helpers`, { recursive: true });\n printSuccess('β Created .claude directory structure');\n } else {\n console.log('[DRY RUN] Would create .claude directory structure');\n }\n\n // Create settings.json\n if (!dryRun) {\n await fs.writeFile(`${claudeDir}/settings.json`, createEnhancedSettingsJson(), 'utf8');\n printSuccess('β Created .claude/settings.json with hooks and MCP configuration');\n } else {\n console.log('[DRY RUN] Would create .claude/settings.json');\n }\n\n // Copy statusline script\n try {\n let statuslineTemplate;\n try {\n // Try to read from templates directory first\n statuslineTemplate = await fs.readFile(\n path.join(__dirname, 'templates', 'statusline-command.sh'),\n 'utf8'\n );\n } catch {\n // Fallback to embedded content (for binary builds)\n statuslineTemplate = createStatuslineScript();\n }\n\n if (!dryRun) {\n // Write to project .claude directory\n await fs.writeFile(`${claudeDir}/statusline-command.sh`, statuslineTemplate, 'utf8');\n await fs.chmod(`${claudeDir}/statusline-command.sh`, 0o755);\n\n // Also write to home ~/.claude directory for global use\n const homeClaudeDir = path.join(os.homedir(), '.claude');\n await fs.mkdir(homeClaudeDir, { recursive: true });\n await fs.writeFile(path.join(homeClaudeDir, 'statusline-command.sh'), statuslineTemplate, 'utf8');\n await fs.chmod(path.join(homeClaudeDir, 'statusline-command.sh'), 0o755);\n\n printSuccess('β Created statusline-command.sh in both .claude/ and ~/.claude/');\n } else {\n console.log('[DRY RUN] Would create .claude/statusline-command.sh and ~/.claude/statusline-command.sh');\n }\n } catch (err) {\n // Not critical, just skip\n if (!dryRun) {\n console.log(' β οΈ Could not create statusline script, skipping...');\n console.log(` βΉοΈ Error: ${err.message}`);\n }\n }\n\n // Create settings.local.json with default MCP permissions\n const settingsLocal = {\n permissions: {\n allow: ['mcp__ruv-swarm', 'mcp__claude-flow@alpha', 'mcp__flow-nexus'],\n deny: [],\n },\n };\n\n if (!dryRun) {\n await fs.writeFile(\n `${claudeDir}/settings.local.json`, JSON.stringify(settingsLocal, null, 2, 'utf8'),\n );\n printSuccess('β Created .claude/settings.local.json with default MCP permissions');\n } else {\n console.log(\n '[DRY RUN] Would create .claude/settings.local.json with default MCP permissions',\n );\n }\n\n // Create .mcp.json at project root for MCP server configuration\n const mcpConfig = {\n mcpServers: {\n 'claude-flow@alpha': {\n command: 'npx',\n args: ['claude-flow@alpha', 'mcp', 'start'],\n type: 'stdio',\n },\n 'ruv-swarm': {\n command: 'npx',\n args: ['ruv-swarm@latest', 'mcp', 'start'],\n type: 'stdio',\n },\n 'flow-nexus': {\n command: 'npx',\n args: ['flow-nexus@latest', 'mcp', 'start'],\n type: 'stdio',\n },\n 'agentic-payments': {\n command: 'npx',\n args: ['agentic-payments@latest', 'mcp'],\n type: 'stdio',\n },\n },\n };\n\n if (!dryRun) {\n await fs.writeFile(`${workingDir}/.mcp.json`, JSON.stringify(mcpConfig, null, 2, 'utf8'));\n printSuccess('β Created .mcp.json at project root for MCP server configuration');\n } else {\n console.log('[DRY RUN] Would create .mcp.json at project root for MCP server configuration');\n }\n\n // Removed claude-flow@alpha.config.json creation per user request\n\n // Create command documentation\n for (const [category, commands] of Object.entries(COMMAND_STRUCTURE)) {\n const categoryDir = `${claudeDir}/commands/${category}`;\n\n if (!dryRun) {\n await fs.mkdir(categoryDir, { recursive: true });\n\n // Create category README\n const categoryReadme = `# ${category.charAt(0).toUpperCase() + category.slice(1)} Commands\n\nCommands for ${category} operations in Claude Flow.\n\n## Available Commands\n\n${commands.map((cmd) => `- [${cmd}](./${cmd}.md)`).join('\\n')}\n`;\n await fs.writeFile(`${categoryDir}/README.md`, categoryReadme, 'utf8');\n\n // Create individual command docs\n for (const command of commands) {\n const doc = createCommandDoc(category, command);\n if (doc) {\n await fs.writeFile(`${categoryDir}/${command}.md`, doc, 'utf8');\n }\n }\n\n console.log(` β Created ${commands.length} ${category} command docs`);\n } else {\n console.log(`[DRY RUN] Would create ${commands.length} ${category} command docs`);\n }\n }\n\n // Create wrapper scripts using the dedicated function\n if (!dryRun) {\n await createLocalExecutable(workingDir, dryRun);\n } else {\n console.log('[DRY RUN] Would create wrapper scripts');\n }\n\n // Create helper scripts\n const helpers = ['setup-mcp.sh', 'quick-start.sh', 'github-setup.sh', 'github-safe.js', 'standard-checkpoint-hooks.sh', 'checkpoint-manager.sh'];\n for (const helper of helpers) {\n if (!dryRun) {\n const content = createHelperScript(helper);\n if (content) {\n await fs.writeFile(`${claudeDir}/helpers/${helper}`, content, 'utf8');\n await fs.chmod(`${claudeDir}/helpers/${helper}`, 0o755);\n }\n }\n }\n\n if (!dryRun) {\n printSuccess(`β Created ${helpers.length} helper scripts`);\n } else {\n console.log(`[DRY RUN] Would create ${helpers.length} helper scripts`);\n }\n\n // Create standard directories from original init\n const standardDirs = [\n 'memory',\n 'memory/agents',\n 'memory/sessions',\n 'coordination',\n 'coordination/memory_bank',\n 'coordination/subtasks',\n 'coordination/orchestration',\n '.swarm', // Add .swarm directory for shared memory\n '.hive-mind', // Add .hive-mind directory for hive-mind system\n '.claude/checkpoints', // Add checkpoints directory for Git checkpoint system\n ];\n\n for (const dir of standardDirs) {\n if (!dryRun) {\n await fs.mkdir(`${workingDir}/${dir}`, { recursive: true });\n }\n }\n\n if (!dryRun) {\n printSuccess('β Created standard directory structure');\n\n // Initialize memory system\n const initialData = { agents: [], tasks: [], lastUpdated: Date.now() };\n await fs.writeFile(\n `${workingDir}/memory/claude-flow@alpha-data.json`, JSON.stringify(initialData, null, 2, 'utf8'),\n );\n\n // Create README files\n await fs.writeFile(`${workingDir}/memory/agents/README.md`, createAgentsReadme(), 'utf8');\n await fs.writeFile(`${workingDir}/memory/sessions/README.md`, createSessionsReadme(), 'utf8');\n\n printSuccess('β Initialized memory system');\n\n // Initialize memory database with fallback support\n try {\n // Check if database exists BEFORE creating it\n const dbPath = '.swarm/memory.db';\n const { existsSync } = await import('fs');\n const dbExistedBefore = existsSync(dbPath);\n\n // Handle ReasoningBank migration BEFORE FallbackMemoryStore initialization\n // This prevents schema conflicts with old databases\n if (dbExistedBefore) {\n console.log(' π Checking existing database for ReasoningBank schema...');\n\n try {\n const {\n initializeReasoningBank,\n checkReasoningBankTables,\n migrateReasoningBank\n } = await import('../../../reasoningbank/reasoningbank-adapter.js');\n\n // Set the database path for ReasoningBank\n process.env.CLAUDE_FLOW_DB_PATH = dbPath;\n\n const tableCheck = await checkReasoningBankTables();\n\n if (tableCheck.exists) {\n console.log(' β
ReasoningBank schema already complete');\n } else if (force) {\n // User used --force flag, migrate the database\n console.log(` π Migrating database: ${tableCheck.missingTables.length} tables missing`);\n console.log(` Missing: ${tableCheck.missingTables.join(', ')}`);\n\n const migrationResult = await migrateReasoningBank();\n\n if (migrationResult.success) {\n printSuccess(` β Migration complete: added ${migrationResult.addedTables?.length || 0} tables`);\n console.log(' Use --reasoningbank flag to enable AI-powered memory features');\n } else {\n console.log(` β οΈ Migration failed: ${migrationResult.message}`);\n console.log(' Basic memory will work, use: memory init --reasoningbank to retry');\n }\n } else {\n // Database exists with missing tables but no --force flag\n console.log(` βΉοΈ Database has ${tableCheck.missingTables.length} missing ReasoningBank tables`);\n console.log(` Missing: ${tableCheck.missingTables.join(', ')}`);\n console.log(' Use --force to migrate existing database');\n console.log(' Or use: memory init --reasoningbank');\n }\n } catch (rbErr) {\n console.log(` β οΈ ReasoningBank check failed: ${rbErr.message}`);\n console.log(' Will attempt normal initialization...');\n }\n }\n\n // Import and initialize FallbackMemoryStore to create the database\n const { FallbackMemoryStore } = await import('../../../memory/fallback-store.js');\n const memoryStore = new FallbackMemoryStore();\n await memoryStore.initialize();\n\n if (memoryStore.isUsingFallback()) {\n printSuccess('β Initialized memory system (in-memory fallback for npx compatibility)');\n console.log(\n ' π‘ For persistent storage, install locally: npm install claude-flow@alpha',\n );\n } else {\n printSuccess('β Initialized memory database (.swarm/memory.db)');\n\n // Initialize ReasoningBank schema for fresh databases\n if (!dbExistedBefore) {\n try {\n const {\n initializeReasoningBank\n } = await import('../../../reasoningbank/reasoningbank-adapter.js');\n\n // Set the database path for ReasoningBank\n process.env.CLAUDE_FLOW_DB_PATH = dbPath;\n\n console.log(' π§ Initializing ReasoningBank schema...');\n await initializeReasoningBank();\n printSuccess(' β ReasoningBank schema initialized (use --reasoningbank flag for AI-powered memory)');\n } catch (rbErr) {\n console.log(` β οΈ ReasoningBank initialization failed: ${rbErr.message}`);\n console.log(' Basic memory will work, use: memory init --reasoningbank to retry');\n }\n }\n }\n\n memoryStore.close();\n } catch (err) {\n console.log(` β οΈ Could not initialize memory system: ${err.message}`);\n console.log(' Memory will be initialized on first use');\n }\n\n // Initialize comprehensive hive-mind system\n console.log('\\nπ§ Initializing Hive Mind System...');\n try {\n const hiveMindOptions = {\n config: {\n integration: {\n claudeCode: { enabled: isClaudeCodeInstalled() },\n mcpTools: { enabled: true }\n },\n monitoring: { enabled: flags.monitoring || false }\n }\n };\n \n const hiveMindResult = await initializeHiveMind(workingDir, hiveMindOptions, dryRun);\n \n if (hiveMindResult.success) {\n printSuccess(`β Hive Mind System initialized with ${hiveMindResult.features.length} features`);\n \n // Log individual features\n hiveMindResult.features.forEach(feature => {\n console.log(` β’ ${feature}`);\n });\n } else {\n console.log(` β οΈ Hive Mind initialization failed: ${hiveMindResult.error}`);\n if (hiveMindResult.rollbackRequired) {\n console.log(' π Automatic rollback may be required');\n }\n }\n } catch (err) {\n console.log(` β οΈ Could not initialize hive-mind system: ${err.message}`);\n }\n }\n\n // Update .gitignore with Claude Flow entries\n const gitignoreResult = await updateGitignore(workingDir, force, dryRun);\n if (gitignoreResult.success) {\n if (!dryRun) {\n printSuccess(`β ${gitignoreResult.message}`);\n } else {\n console.log(gitignoreResult.message);\n }\n } else {\n console.log(` β οΈ ${gitignoreResult.message}`);\n }\n\n // SPARC initialization (only with --roo flag)\n let sparcInitialized = false;\n if (initSparc) {\n console.log('\\nπ Initializing SPARC development environment...');\n try {\n // Run create-sparc\n console.log(' π Running: npx -y create-sparc init --force');\n execSync('npx -y create-sparc init --force', {\n cwd: workingDir,\n stdio: 'inherit',\n });\n sparcInitialized = true;\n printSuccess('β
SPARC environment initialized successfully');\n } catch (err) {\n console.log(` β οΈ Could not run create-sparc: ${err.message}`);\n console.log(' SPARC features will be limited to basic functionality');\n }\n }\n\n // Create Claude slash commands for SPARC\n if (sparcInitialized && !dryRun) {\n console.log('\\nπ Creating Claude Code slash commands...');\n await createClaudeSlashCommands(workingDir);\n }\n\n // Check for Claude Code and set up MCP servers (always enabled by default)\n if (!dryRun && isClaudeCodeInstalled()) {\n console.log('\\nπ Claude Code CLI detected!');\n const skipMcp =\n (options && options['skip-mcp']) ||\n (subArgs && subArgs.includes && subArgs.includes('--skip-mcp'));\n\n if (!skipMcp) {\n await setupMcpServers(dryRun);\n } else {\n console.log(' βΉοΈ Skipping MCP setup (--skip-mcp flag used)');\n console.log('\\n π To add MCP servers manually:');\n console.log(' claude mcp add claude-flow npx claude-flow@alpha mcp start');\n console.log(' claude mcp add ruv-swarm npx ruv-swarm@latest mcp start');\n console.log(' claude mcp add flow-nexus npx flow-nexus@latest mcp start');\n console.log(' claude mcp add agentic-payments npx agentic-payments@latest mcp');\n console.log('\\n π‘ MCP servers are defined in .mcp.json (project scope)');\n }\n } else if (!dryRun && !isClaudeCodeInstalled()) {\n console.log('\\nβ οΈ Claude Code CLI not detected!');\n console.log('\\n π₯ To install Claude Code:');\n console.log(' npm install -g @anthropic-ai/claude-code');\n console.log('\\n π After installing, add MCP servers:');\n console.log(' claude mcp add claude-flow@alpha npx claude-flow@alpha mcp start');\n console.log(' claude mcp add ruv-swarm npx ruv-swarm@latest mcp start');\n console.log(' claude mcp add flow-nexus npx flow-nexus@latest mcp start');\n console.log(' claude mcp add agentic-payments npx agentic-payments@latest mcp');\n console.log('\\n π‘ MCP servers are defined in .mcp.json (project scope)');\n }\n\n // Create agent directories and copy all agent files\n console.log('\\nπ€ Setting up agent system...');\n if (!dryRun) {\n await createAgentDirectories(workingDir, dryRun);\n const agentResult = await copyAgentFiles(workingDir, {\n force: force,\n dryRun: dryRun\n });\n\n if (agentResult.success) {\n await validateAgentSystem(workingDir);\n\n // Copy command files including Flow Nexus commands\n console.log('\\nπ Setting up command system...');\n const commandResult = await copyCommandFiles(workingDir, {\n force: force,\n dryRun: dryRun\n });\n\n if (commandResult.success) {\n console.log('β
β Command system setup complete with Flow Nexus integration');\n } else {\n console.log('β οΈ Command system setup failed:', commandResult.error);\n }\n\n // Copy skill files including skill-builder\n console.log('\\nπ― Setting up skill system...');\n const skillResult = await copySkillFiles(workingDir, {\n force: force,\n dryRun: dryRun\n });\n\n if (skillResult.success) {\n await validateSkillSystem(workingDir);\n console.log('β
β Skill system setup complete with skill-builder');\n } else {\n console.log('β οΈ Skill system setup failed:', skillResult.error);\n }\n\n console.log('β
β Agent system setup complete with 64 specialized agents');\n } else {\n console.log('β οΈ Agent system setup failed:', agentResult.error);\n }\n\n // Setup reasoning agents if --agent reasoning flag is used\n if (initReasoning) {\n console.log('\\nπ§ Setting up reasoning agents with ReasoningBank integration...');\n try {\n const reasoningAgentsDir = `${workingDir}/.claude/agents/reasoning`;\n await fs.mkdir(reasoningAgentsDir, { recursive: true });\n\n // Import path module\n const path = await import('path');\n const { fileURLToPath } = await import('url');\n const { dirname, join } = path.default;\n\n // Get the source reasoning agents directory\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n const sourceReasoningDir = join(__dirname, '../../../../.claude/agents/reasoning');\n\n // Copy reasoning agent files\n try {\n const reasoningFiles = await fs.readdir(sourceReasoningDir);\n let copiedReasoningAgents = 0;\n\n for (const file of reasoningFiles) {\n if (file.endsWith('.md')) {\n const sourcePath = join(sourceReasoningDir, file);\n const destPath = join(reasoningAgentsDir, file);\n const content = await fs.readFile(sourcePath, 'utf8');\n await fs.writeFile(destPath, content);\n copiedReasoningAgents++;\n }\n }\n\n printSuccess(`β Copied ${copiedReasoningAgents} reasoning agent files`);\n console.log(' π Reasoning agents available:');\n console.log(' β’ goal-planner - Goal-Oriented Action Planning specialist');\n console.log(' β’ sublinear-goal-planner - Sub-linear complexity goal planning');\n console.log(' π‘ Use: npx agentic-flow --agent goal-planner --task \"your task\"');\n console.log(' π Documentation: .claude/agents/reasoning/README.md');\n } catch (err) {\n console.log(` β οΈ Could not copy reasoning agents: ${err.message}`);\n console.log(' Reasoning agents may not be available yet');\n }\n } catch (err) {\n console.log(` β οΈ Reasoning agent setup failed: ${err.message}`);\n }\n }\n } else {\n console.log(' [DRY RUN] Would create agent system with 64 specialized agents');\n if (initReasoning) {\n console.log(' [DRY RUN] Would also setup reasoning agents with ReasoningBank integration');\n }\n }\n\n // Optional: Setup monitoring and telemetry\n const enableMonitoring = flags.monitoring || flags['enable-monitoring'];\n if (enableMonitoring && !dryRun) {\n console.log('\\nπ Setting up monitoring and telemetry...');\n await setupMonitoring(workingDir);\n }\n \n // Final instructions with hive-mind status\n console.log('\\nπ Claude Flow v2.0.0 initialization complete!');\n \n // Display hive-mind status\n const hiveMindStatus = getHiveMindStatus(workingDir);\n console.log('\\nπ§ Hive Mind System Status:');\n console.log(` Configuration: ${hiveMindStatus.configured ? 'β
Ready' : 'β Missing'}`);\n console.log(` Database: ${hiveMindStatus.database === 'sqlite' ? 'β
SQLite' : hiveMindStatus.database === 'fallback' ? 'β οΈ JSON Fallback' : 'β Not initialized'}`);\n console.log(` Directory Structure: ${hiveMindStatus.directories ? 'β
Created' : 'β Missing'}`);\n \n console.log('\\nπ Quick Start:');\n if (isClaudeCodeInstalled()) {\n console.log('1. View available commands: ls .claude/commands/');\n console.log('2. Start a swarm: npx claude-flow@alpha swarm \"your objective\" --claude');\n console.log('3. Use hive-mind: npx claude-flow@alpha hive-mind spawn \"command\" --claude');\n console.log('4. Use MCP tools in Claude Code for enhanced coordination');\n if (hiveMindStatus.configured) {\n console.log('5. Initialize first swarm: npx claude-flow@alpha hive-mind init');\n }\n } else {\n console.log('1. Install Claude Code: npm install -g @anthropic-ai/claude-code');\n console.log('2. Add MCP servers (see instructions above)');\n console.log('3. View available commands: ls .claude/commands/');\n console.log('4. Start a swarm: npx claude-flow@alpha swarm \"your objective\" --claude');\n console.log('5. Use hive-mind: npx claude-flow@alpha hive-mind spawn \"command\" --claude');\n if (hiveMindStatus.configured) {\n console.log('6. Initialize first swarm: npx claude-flow@alpha hive-mind init');\n }\n }\n console.log('\\nπ‘ Tips:');\n console.log('β’ Check .claude/commands/ for detailed documentation');\n console.log('β’ Use --help with any command for options');\n console.log('β’ Run commands with --claude flag for best Claude Code integration');\n console.log('β’ Enable GitHub integration with .claude/helpers/github-setup.sh');\n console.log('β’ Git checkpoints are automatically enabled in settings.json');\n console.log('β’ Use .claude/helpers/checkpoint-manager.sh for easy rollback');\n } catch (err) {\n printError(`Failed to initialize Claude Flow v2.0.0: ${err.message}`);\n \n // Attempt hive-mind rollback if it was partially initialized\n try {\n const hiveMindStatus = getHiveMindStatus(workingDir);\n if (hiveMindStatus.directories || hiveMindStatus.configured) {\n console.log('\\nπ Attempting hive-mind system rollback...');\n const rollbackResult = await rollbackHiveMindInit(workingDir);\n if (rollbackResult.success) {\n console.log(' β
Hive-mind rollback completed');\n } else {\n console.log(` β οΈ Hive-mind rollback failed: ${rollbackResult.error}`);\n }\n }\n } catch (rollbackErr) {\n console.log(` β οΈ Rollback error: ${rollbackErr.message}`);\n }\n }\n}\n\n/**\n * Flow Nexus minimal initialization - only creates Flow Nexus CLAUDE.md, commands, and agents\n */\nasync function flowNexusMinimalInit(flags, subArgs) {\n console.log('π Flow Nexus: Initializing minimal setup...');\n \n try {\n const force = flags.force || flags.f;\n \n // Import functions we need\n const { createFlowNexusClaudeMd } = await import('./templates/claude-md.js');\n const { promises: fs } = await import('fs');\n \n // Create Flow Nexus CLAUDE.md\n console.log('π Creating Flow Nexus CLAUDE.md...');\n const flowNexusClaudeMd = createFlowNexusClaudeMd();\n await fs.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 console.log('π Setting up Flow Nexus commands...');\n await fs.mkdir('.claude/commands/flow-nexus', { recursive: true });\n \n // Copy Flow Nexus command files\n const { fileURLToPath } = await import('url');\n const { dirname, join } = await import('path');\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n const sourceCommandsDir = join(__dirname, '../../../../.claude/commands/flow-nexus');\n try {\n const commandFiles = await fs.readdir(sourceCommandsDir);\n let copiedCommands = 0;\n \n for (const file of commandFiles) {\n if (file.endsWith('.md')) {\n const sourcePath = `${sourceCommandsDir}/${file}`;\n const destPath = `.claude/commands/flow-nexus/${file}`;\n const content = await fs.readFile(sourcePath, 'utf8');\n await fs.writeFile(destPath, content);\n copiedCommands++;\n }\n }\n \n console.log(` β
Copied ${copiedCommands} Flow Nexus command files`);\n } catch (err) {\n console.log(' β οΈ Could not copy Flow Nexus commands:', err.message);\n }\n \n // Create .claude/agents/flow-nexus directory and copy agents\n console.log('π€ Setting up Flow Nexus agents...');\n await fs.mkdir('.claude/agents/flow-nexus', { recursive: true });\n \n // Copy Flow Nexus agent files\n const sourceAgentsDir = join(__dirname, '../../../../.claude/agents/flow-nexus');\n try {\n const agentFiles = await fs.readdir(sourceAgentsDir);\n let copiedAgents = 0;\n \n for (const file of agentFiles) {\n if (file.endsWith('.md')) {\n const sourcePath = `${sourceAgentsDir}/${file}`;\n const destPath = `.claude/agents/flow-nexus/${file}`;\n const content = await fs.readFile(sourcePath, 'utf8');\n await fs.writeFile(destPath, content);\n copiedAgents++;\n }\n }\n \n console.log(` β
Copied ${copiedAgents} Flow Nexus agent files`);\n } catch (err) {\n console.log(' β οΈ Could not copy Flow Nexus agents:', err.message);\n }\n \n console.log('\\nπ Flow Nexus minimal initialization complete!');\n console.log('π Created: CLAUDE.md with Flow Nexus documentation');\n console.log('π Created: .claude/commands/flow-nexus/ directory with command documentation');\n console.log('π€ Created: .claude/agents/flow-nexus/ directory with specialized agents');\n console.log('');\n console.log('π‘ Quick Start:');\n console.log(' 1. Register: mcp__flow-nexus__user_register({ email, password })');\n console.log(' 2. Login: mcp__flow-nexus__user_login({ email, password })');\n console.log(' 3. Deploy: mcp__flow-nexus__swarm_init({ topology: \"mesh\", maxAgents: 5 })');\n console.log('');\n console.log('π Use Flow Nexus MCP tools in Claude Code for full functionality');\n \n } catch (err) {\n console.log(`β Flow Nexus initialization failed: ${err.message}`);\n console.log('Stack trace:', err.stack);\n process.exit(1);\n }\n}\n"],"names":["printSuccess","printError","printWarning","existsSync","process","spawn","execSync","runCommand","command","args","options","Promise","resolve","reject","child","cwd","env","stdio","stdout","stderr","on","data","code","success","Error","createLocalExecutable","createSparcStructureManually","createClaudeSlashCommands","createOptimizedClaudeSlashCommands","promises","fs","copyTemplates","copyRevisedTemplates","validateTemplatesExist","copyAgentFiles","createAgentDirectories","validateAgentSystem","copyCommandFiles","copySkillFiles","validateSkillSystem","showInitHelp","batchInitCommand","batchInitFromConfig","validateBatchOptions","ValidationSystem","runFullValidation","RollbackSystem","createAtomicOperation","createEnhancedSettingsJson","createCommandDoc","createHelperScript","COMMAND_STRUCTURE","createOptimizedSparcClaudeMd","getIsolatedNpxEnv","updateGitignore","createFullClaudeMd","createSparcClaudeMd","createMinimalClaudeMd","createFullMemoryBankMd","createMinimalMemoryBankMd","createFullCoordinationMd","createMinimalCoordinationMd","createAgentsReadme","createSessionsReadme","initializeHiveMind","getHiveMindStatus","rollbackHiveMindInit","isClaudeCodeInstalled","setupMcpServers","dryRun","console","log","servers","name","description","server","err","message","createStatuslineScript","initCommand","subArgs","flags","help","h","includes","generateEnvTemplate","workingDir","PWD","force","f","result","created","exists","hasVerificationFlags","verify","pair","flowNexusMinimalInit","basic","minimal","sparc","enhancedClaudeFlowInit","handleValidationCommand","handleRollbackCommand","handleListBackups","batchInitFlag","configFlag","config","handleBatchInit","useEnhanced","enhancedInitCommand","initForce","initMinimal","initSparc","roo","initDryRun","initOptimized","selectedModes","modes","split","initVerify","initPair","chdir","files","existingFiles","file","stat","push","length","join","templateOptions","optimized","createVerificationClaudeMd","createVerificationSettingsJson","writeFile","mkdir","recursive","validation","valid","revisedResults","verbose","copyResults","skipClaudeMd","skipSettings","copiedFiles","skippedFiles","errors","forEach","sparcInitialized","createSparcResult","modeCount","gitignoreResult","hiveMindOptions","integration","claudeCode","enabled","mcpTools","monitoring","hiveMindResult","error","skipMcp","parallel","s","m","maxConcurrency","progressTracking","template","environments","map","trim","validationErrors","configFile","results","projectsString","projects","project","successful","filter","r","failed","rollbackSystem","validationSystem","atomicOp","initOptions","skipPreValidation","skipBackup","validateOnly","preValidation","validatePreInit","warnings","warning","warn","backupResult","createPreInitBackup","atomicBegin","begin","performInitializationWithCheckpoints","postValidation","validatePostInit","rollback","configValidation","validateConfiguration","healthChecks","runHealthChecks","commit","fullValidation","postInit","skipPreInit","report","completed","rollbackError","skipConfig","skipModeTest","validationResults","exit","performFullRollback","phaseIndex","findIndex","arg","phase","performPartialRollback","rollbackPoints","listRollbackPoints","point","index","date","Date","timestamp","toLocaleString","type","latest","backupId","checkpoints","slice","checkpoint","status","phases","action","createInitialFiles","createDirectoryStructure","setupMemorySystem","setupCoordinationSystem","createCheckpoint","now","claudeMd","memoryBankMd","coordinationMd","directories","dir","initialData","agents","tasks","lastUpdated","JSON","stringify","setupMonitoring","path","trackingDir","tokenUsageFile","total","input","output","byAgent","toISOString","settingsPath","settingsContent","readFile","settings","parse","hooks","tokenTrackingHook","monitoringConfig","telemetry","value","tracking","tokens","costs","sessions","storage","location","format","rotation","configPath","envSnippet","envPath","d","agentType","agent","find","startsWith","initReasoning","chmod","os","filesToCheck","claudeDir","statuslineTemplate","__dirname","homeClaudeDir","homedir","settingsLocal","permissions","allow","deny","mcpConfig","mcpServers","category","commands","Object","entries","categoryDir","categoryReadme","charAt","toUpperCase","cmd","doc","helpers","helper","content","standardDirs","dbPath","dbExistedBefore","initializeReasoningBank","checkReasoningBankTables","migrateReasoningBank","CLAUDE_FLOW_DB_PATH","tableCheck","missingTables","migrationResult","addedTables","rbErr","FallbackMemoryStore","memoryStore","initialize","isUsingFallback","close","features","feature","rollbackRequired","agentResult","commandResult","skillResult","reasoningAgentsDir","fileURLToPath","dirname","default","__filename","url","sourceReasoningDir","reasoningFiles","readdir","copiedReasoningAgents","endsWith","sourcePath","destPath","enableMonitoring","hiveMindStatus","configured","database","rollbackResult","rollbackErr","createFlowNexusClaudeMd","flowNexusClaudeMd","sourceCommandsDir","commandFiles","copiedCommands","sourceAgentsDir","agentFiles","copiedAgents","stack"],"mappings":"AACA,SAASA,YAAY,EAAEC,UAAU,EAAEC,YAAY,QAAc,iBAAiB;AAC9E,SAASC,UAAU,QAAQ,KAAK;AAChC,OAAOC,aAAa,UAAU;AAE9B,SAASC,KAAK,EAAEC,QAAQ,QAAQ,gBAAgB;AAIhD,SAASC,WAAWC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AAQ,CAACsF,YAAY;oBAC9C,MAAMjU,GAAGuG,SAAS,CAAC2N,UAAUpC;oBAC7BkD;gBACF;YACF;YAEAxS,QAAQC,GAAG,CAAC,CAAC,WAAW,EAAEuS,aAAa,uBAAuB,CAAC;QACjE,EAAE,OAAOlS,KAAK;YACZN,QAAQC,GAAG,CAAC,2CAA2CK,IAAIC,OAAO;QACpE;QAEAP,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC;IAEd,EAAE,OAAOK,KAAK;QACZN,QAAQC,GAAG,CAAC,CAAC,oCAAoC,EAAEK,IAAIC,OAAO,EAAE;QAChEP,QAAQC,GAAG,CAAC,gBAAgBK,IAAImS,KAAK;QACrC3W,QAAQiN,IAAI,CAAC;IACf;AACF"}
|
|
1
|
+
{"version":3,"sources":["../../../../../src/cli/simple-commands/init/index.js"],"sourcesContent":["// init/index.js - Initialize Claude Code integration files\nimport { printSuccess, printError, printWarning, exit } from '../../utils.js';\nimport { existsSync } from 'fs';\nimport process from 'process';\nimport os from 'os';\nimport { spawn, execSync } from 'child_process';\nimport { promisify } from 'util';\n\n// Helper to replace Deno.Command\nfunction runCommand(command, args, options = {}) {\n return new Promise((resolve, reject) => {\n const child = spawn(command, args, {\n cwd: options.cwd,\n env: { ...process.env, ...options.env },\n stdio: options.stdout === 'inherit' ? 'inherit' : 'pipe'\n });\n \n let stdout = '';\n let stderr = '';\n \n if (options.stdout !== 'inherit') {\n child.stdout.on('data', (data) => { stdout += data; });\n child.stderr.on('data', (data) => { stderr += data; });\n }\n \n child.on('close', (code) => {\n if (code === 0) {\n resolve({ success: true, code, stdout, stderr });\n } else {\n reject(new Error(`Command failed with exit code ${code}`));\n }\n });\n \n child.on('error', reject);\n });\n}\nimport { createLocalExecutable } from './executable-wrapper.js';\nimport { createSparcStructureManually } from './sparc-structure.js';\nimport { createClaudeSlashCommands } from './claude-commands/slash-commands.js';\nimport { createOptimizedClaudeSlashCommands } from './claude-commands/optimized-slash-commands.js';\n// execSync imported above as execSyncOriginal\\nconst execSync = execSyncOriginal;\nimport { promises as fs } from 'fs';\nimport { copyTemplates } from './template-copier.js';\nimport { copyRevisedTemplates, validateTemplatesExist } from './copy-revised-templates.js';\nimport { copyAgentFiles, createAgentDirectories, validateAgentSystem, copyCommandFiles } from './agent-copier.js';\nimport { copySkillFiles, createSkillDirectories, validateSkillSystem } from './skills-copier.js';\nimport { showInitHelp } from './help.js';\nimport { batchInitCommand, batchInitFromConfig, validateBatchOptions } from './batch-init.js';\nimport { ValidationSystem, runFullValidation } from './validation/index.js';\nimport { RollbackSystem, createAtomicOperation } from './rollback/index.js';\nimport {\n createEnhancedClaudeMd,\n createEnhancedSettingsJson,\n createWrapperScript,\n createCommandDoc,\n createHelperScript,\n COMMAND_STRUCTURE,\n} from './templates/enhanced-templates.js';\nimport { createOptimizedSparcClaudeMd } from './templates/claude-md.js';\nimport { getIsolatedNpxEnv } from '../../../utils/npx-isolated-cache.js';\nimport { updateGitignore, needsGitignoreUpdate } from './gitignore-updater.js';\nimport {\n createFullClaudeMd,\n createSparcClaudeMd,\n createMinimalClaudeMd,\n} from './templates/claude-md.js';\nimport {\n createVerificationClaudeMd,\n createVerificationSettingsJson,\n} from './templates/verification-claude-md.js';\nimport {\n createFullMemoryBankMd,\n createMinimalMemoryBankMd,\n} from './templates/memory-bank-md.js';\nimport {\n createFullCoordinationMd,\n createMinimalCoordinationMd,\n} from './templates/coordination-md.js';\nimport { createAgentsReadme, createSessionsReadme } from './templates/readme-files.js';\nimport { \n initializeHiveMind, \n getHiveMindStatus,\n rollbackHiveMindInit\n} from './hive-mind-init.js';\n\n/**\n * Check if Claude Code CLI is installed\n */\nfunction isClaudeCodeInstalled() {\n try {\n execSync('which claude', { stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Set up MCP servers in Claude Code\n */\nasync function setupMcpServers(dryRun = false) {\n console.log('\\nπ Setting up MCP servers for Claude Code...');\n\n const servers = [\n {\n name: 'claude-flow',\n command: 'npx claude-flow@alpha mcp start',\n description: 'Claude Flow MCP server with swarm orchestration (alpha)',\n },\n {\n name: 'ruv-swarm',\n command: 'npx ruv-swarm mcp start',\n description: 'ruv-swarm MCP server for enhanced coordination',\n },\n {\n name: 'flow-nexus',\n command: 'npx flow-nexus@latest mcp start',\n description: 'Flow Nexus Complete MCP server for advanced AI orchestration',\n },\n ];\n\n for (const server of servers) {\n try {\n if (!dryRun) {\n console.log(` π Adding ${server.name}...`);\n execSync(`claude mcp add ${server.name} ${server.command}`, { stdio: 'inherit' });\n console.log(` β
Added ${server.name} - ${server.description}`);\n } else {\n console.log(` [DRY RUN] Would add ${server.name} - ${server.description}`);\n }\n } catch (err) {\n console.log(` β οΈ Failed to add ${server.name}: ${err.message}`);\n console.log(\n ` You can add it manually with: claude mcp add ${server.name} ${server.command}`,\n );\n }\n }\n\n if (!dryRun) {\n console.log('\\n π Verifying MCP servers...');\n try {\n execSync('claude mcp list', { stdio: 'inherit' });\n } catch (err) {\n console.log(' β οΈ Could not verify MCP servers');\n }\n }\n}\n\n/**\n * Create statusline script content (embedded fallback for binary builds)\n */\nfunction createStatuslineScript() {\n return `\n#!/bin/bash\n\n# Read JSON input from stdin\nINPUT=$(cat)\nMODEL=$(echo \"$INPUT\" | jq -r \\'.model.display_name // \"Claude\"\\')\nCWD=$(echo \"$INPUT\" | jq -r \\'.workspace.current_dir // .cwd\\')\nDIR=$(basename \"$CWD\")\n\n# Replace claude-code-flow with branded name\nif [ \"$DIR\" = \"claude-code-flow\" ]; then\n DIR=\"π Claude Flow\"\nfi\n\n# Get git branch\nBRANCH=$(cd \"$CWD\" 2>/dev/null && git branch --show-current 2>/dev/null)\n\n# Start building statusline\nprintf \"\\\\033[1m$MODEL\\\\033[0m in \\\\033[36m$DIR\\\\033[0m\"\n[ -n \"$BRANCH\" ] && printf \" on \\\\033[33mβ $BRANCH\\\\033[0m\"\n\n# Claude-Flow integration\nFLOW_DIR=\"$CWD/.claude-flow\"\n\nif [ -d \"$FLOW_DIR\" ]; then\n printf \" β\"\n\n # 1. Swarm Configuration & Topology\n if [ -f \"$FLOW_DIR/swarm-config.json\" ]; then\n STRATEGY=$(jq -r \\'.defaultStrategy // empty\\' \"$FLOW_DIR/swarm-config.json\" 2>/dev/null)\n if [ -n \"$STRATEGY\" ]; then\n # Map strategy to topology icon\n case \"$STRATEGY\" in\n \"balanced\") TOPO_ICON=\"β‘mesh\" ;;\n \"conservative\") TOPO_ICON=\"β‘hier\" ;;\n \"aggressive\") TOPO_ICON=\"β‘ring\" ;;\n *) TOPO_ICON=\"β‘$STRATEGY\" ;;\n esac\n printf \" \\\\033[35m$TOPO_ICON\\\\033[0m\"\n\n # Count agent profiles as \"configured agents\"\n AGENT_COUNT=$(jq -r \\'.agentProfiles | length\\' \"$FLOW_DIR/swarm-config.json\" 2>/dev/null)\n if [ -n \"$AGENT_COUNT\" ] && [ \"$AGENT_COUNT\" != \"null\" ] && [ \"$AGENT_COUNT\" -gt 0 ]; then\n printf \" \\\\033[35mπ€ $AGENT_COUNT\\\\033[0m\"\n fi\n fi\n fi\n\n # 2. Real-time System Metrics\n if [ -f \"$FLOW_DIR/metrics/system-metrics.json\" ]; then\n # Get latest metrics (last entry in array)\n LATEST=$(jq -r \\'.[-1]\\' \"$FLOW_DIR/metrics/system-metrics.json\" 2>/dev/null)\n\n if [ -n \"$LATEST\" ] && [ \"$LATEST\" != \"null\" ]; then\n # Memory usage\n MEM_PERCENT=$(echo \"$LATEST\" | jq -r \\'.memoryUsagePercent // 0\\' | awk \\'{printf \"%.0f\", $1}\\')\n if [ -n \"$MEM_PERCENT\" ] && [ \"$MEM_PERCENT\" != \"null\" ]; then\n # Color-coded memory (green <60%, yellow 60-80%, red >80%)\n if [ \"$MEM_PERCENT\" -lt 60 ]; then\n MEM_COLOR=\"\\\\033[32m\" # Green\n elif [ \"$MEM_PERCENT\" -lt 80 ]; then\n MEM_COLOR=\"\\\\033[33m\" # Yellow\n else\n MEM_COLOR=\"\\\\033[31m\" # Red\n fi\n printf \" \\${MEM_COLOR}πΎ \\${MEM_PERCENT}%\\\\033[0m\"\n fi\n\n # CPU load\n CPU_LOAD=$(echo \"$LATEST\" | jq -r \\'.cpuLoad // 0\\' | awk \\'{printf \"%.0f\", $1 * 100}\\')\n if [ -n \"$CPU_LOAD\" ] && [ \"$CPU_LOAD\" != \"null\" ]; then\n # Color-coded CPU (green <50%, yellow 50-75%, red >75%)\n if [ \"$CPU_LOAD\" -lt 50 ]; then\n CPU_COLOR=\"\\\\033[32m\" # Green\n elif [ \"$CPU_LOAD\" -lt 75 ]; then\n CPU_COLOR=\"\\\\033[33m\" # Yellow\n else\n CPU_COLOR=\"\\\\033[31m\" # Red\n fi\n printf \" \\${CPU_COLOR}β \\${CPU_LOAD}%\\\\033[0m\"\n fi\n fi\n fi\n\n # 3. Session State\n if [ -f \"$FLOW_DIR/session-state.json\" ]; then\n SESSION_ID=$(jq -r \\'.sessionId // empty\\' \"$FLOW_DIR/session-state.json\" 2>/dev/null)\n ACTIVE=$(jq -r \\'.active // false\\' \"$FLOW_DIR/session-state.json\" 2>/dev/null)\n\n if [ \"$ACTIVE\" = \"true\" ] && [ -n \"$SESSION_ID\" ]; then\n # Show abbreviated session ID\n SHORT_ID=$(echo \"$SESSION_ID\" | cut -d\\'-\\' -f1)\n printf \" \\\\033[34mπ $SHORT_ID\\\\033[0m\"\n fi\n fi\n\n # 4. Performance Metrics from task-metrics.json\n if [ -f \"$FLOW_DIR/metrics/task-metrics.json\" ]; then\n # Parse task metrics for success rate, avg time, and streak\n METRICS=$(jq -r \\'\n # Calculate metrics\n (map(select(.success == true)) | length) as $successful |\n (length) as $total |\n (if $total > 0 then ($successful / $total * 100) else 0 end) as $success_rate |\n (map(.duration // 0) | add / length) as $avg_duration |\n # Calculate streak (consecutive successes from end)\n (reverse |\n reduce .[] as $task (0;\n if $task.success == true then . + 1 else 0 end\n )\n ) as $streak |\n {\n success_rate: $success_rate,\n avg_duration: $avg_duration,\n streak: $streak,\n total: $total\n } | @json\n \\' \"$FLOW_DIR/metrics/task-metrics.json\" 2>/dev/null)\n\n if [ -n \"$METRICS\" ] && [ \"$METRICS\" != \"null\" ]; then\n # Success Rate\n SUCCESS_RATE=$(echo \"$METRICS\" | jq -r \\'.success_rate // 0\\' | awk \\'{printf \"%.0f\", $1}\\')\n TOTAL_TASKS=$(echo \"$METRICS\" | jq -r \\'.total // 0\\')\n\n if [ -n \"$SUCCESS_RATE\" ] && [ \"$TOTAL_TASKS\" -gt 0 ]; then\n # Color-code: Green (>80%), Yellow (60-80%), Red (<60%)\n if [ \"$SUCCESS_RATE\" -gt 80 ]; then\n SUCCESS_COLOR=\"\\\\033[32m\" # Green\n elif [ \"$SUCCESS_RATE\" -ge 60 ]; then\n SUCCESS_COLOR=\"\\\\033[33m\" # Yellow\n else\n SUCCESS_COLOR=\"\\\\033[31m\" # Red\n fi\n printf \" \\${SUCCESS_COLOR}π― \\${SUCCESS_RATE}%\\\\033[0m\"\n fi\n\n # Average Time\n AVG_TIME=$(echo \"$METRICS\" | jq -r \\'.avg_duration // 0\\')\n if [ -n \"$AVG_TIME\" ] && [ \"$TOTAL_TASKS\" -gt 0 ]; then\n # Format smartly: seconds, minutes, or hours\n if [ $(echo \"$AVG_TIME < 60\" | bc -l 2>/dev/null || echo 0) -eq 1 ]; then\n TIME_STR=$(echo \"$AVG_TIME\" | awk \\'{printf \"%.1fs\", $1}\\')\n elif [ $(echo \"$AVG_TIME < 3600\" | bc -l 2>/dev/null || echo 0) -eq 1 ]; then\n TIME_STR=$(echo \"$AVG_TIME\" | awk \\'{printf \"%.1fm\", $1/60}\\')\n else\n TIME_STR=$(echo \"$AVG_TIME\" | awk \\'{printf \"%.1fh\", $1/3600}\\')\n fi\n printf \" \\\\033[36mβ±οΈ $TIME_STR\\\\033[0m\"\n fi\n\n # Streak (only show if > 0)\n STREAK=$(echo \"$METRICS\" | jq -r \\'.streak // 0\\')\n if [ -n \"$STREAK\" ] && [ \"$STREAK\" -gt 0 ]; then\n printf \" \\\\033[91mπ₯ $STREAK\\\\033[0m\"\n fi\n fi\n fi\n\n # 5. Active Tasks (check for task files)\n if [ -d \"$FLOW_DIR/tasks\" ]; then\n TASK_COUNT=$(find \"$FLOW_DIR/tasks\" -name \"*.json\" -type f 2>/dev/null | wc -l)\n if [ \"$TASK_COUNT\" -gt 0 ]; then\n printf \" \\\\033[36mπ $TASK_COUNT\\\\033[0m\"\n fi\n fi\n\n # 6. Check for hooks activity\n if [ -f \"$FLOW_DIR/hooks-state.json\" ]; then\n HOOKS_ACTIVE=$(jq -r \\'.enabled // false\\' \"$FLOW_DIR/hooks-state.json\" 2>/dev/null)\n if [ \"$HOOKS_ACTIVE\" = \"true\" ]; then\n printf \" \\\\033[35mπ\\\\033[0m\"\n fi\n fi\nfi\n\necho\n`;\n}\n\nexport async function initCommand(subArgs, flags) {\n // Show help if requested\n if (flags.help || flags.h || subArgs.includes('--help') || subArgs.includes('-h')) {\n showInitHelp();\n return;\n }\n\n // Handle --env flag for .env template generation\n if (flags.env || subArgs.includes('--env')) {\n const { generateEnvTemplate } = await import('../env-template.js');\n const workingDir = process.env.PWD || process.cwd();\n const force = flags.force || flags.f;\n\n console.log('π Generating .env template file...\\n');\n const result = await generateEnvTemplate(workingDir, force);\n\n if (result.created) {\n console.log('\\nπ Next steps:');\n console.log('1. Open .env file and add your API keys');\n console.log('2. Get keys from:');\n console.log(' β’ Anthropic: https://console.anthropic.com/settings/keys');\n console.log(' β’ OpenRouter: https://openrouter.ai/keys');\n console.log('3. Enable memory: claude-flow agent run coder \"task\" --enable-memory\\n');\n console.log('π‘ See docs/REASONINGBANK-COST-OPTIMIZATION.md for cost savings tips');\n } else if (result.exists) {\n console.log('π‘ To overwrite: claude-flow init --env --force');\n }\n\n return;\n }\n\n // Check for verification flags first\n const hasVerificationFlags = subArgs.includes('--verify') || subArgs.includes('--pair') ||\n flags.verify || flags.pair;\n\n // Handle Flow Nexus minimal init\n if (flags['flow-nexus']) {\n return await flowNexusMinimalInit(flags, subArgs);\n }\n\n // Default to enhanced Claude Flow v2 init unless other modes are specified\n // Use --basic flag for old behavior, or verification flags for verification mode\n if (!flags.basic && !flags.minimal && !flags.sparc && !hasVerificationFlags) {\n return await enhancedClaudeFlowInit(flags, subArgs);\n }\n\n // Check for validation and rollback commands\n if (subArgs.includes('--validate') || subArgs.includes('--validate-only')) {\n return handleValidationCommand(subArgs, flags);\n }\n\n if (subArgs.includes('--rollback')) {\n return handleRollbackCommand(subArgs, flags);\n }\n\n if (subArgs.includes('--list-backups')) {\n return handleListBackups(subArgs, flags);\n }\n\n // Check for batch operations\n const batchInitFlag = flags['batch-init'] || subArgs.includes('--batch-init');\n const configFlag = flags.config || subArgs.includes('--config');\n\n if (batchInitFlag || configFlag) {\n return handleBatchInit(subArgs, flags);\n }\n\n // Check if enhanced initialization is requested\n const useEnhanced = subArgs.includes('--enhanced') || subArgs.includes('--safe');\n\n if (useEnhanced) {\n return enhancedInitCommand(subArgs, flags);\n }\n\n // Parse init options\n const initForce = subArgs.includes('--force') || subArgs.includes('-f') || flags.force;\n const initMinimal = subArgs.includes('--minimal') || subArgs.includes('-m') || flags.minimal;\n const initSparc = flags.roo || (subArgs && subArgs.includes('--roo')); // SPARC only with --roo flag\n const initDryRun = subArgs.includes('--dry-run') || subArgs.includes('-d') || flags.dryRun;\n const initOptimized = initSparc && initForce; // Use optimized templates when both flags are present\n const selectedModes = flags.modes ? flags.modes.split(',') : null; // Support selective mode initialization\n \n // Check for verification and pair programming flags\n const initVerify = subArgs.includes('--verify') || flags.verify;\n const initPair = subArgs.includes('--pair') || flags.pair;\n\n // Get the actual working directory (where the command was run from)\n // Use PWD environment variable which preserves the original directory\n const workingDir = process.env.PWD || cwd();\n console.log(`π Initializing in: ${workingDir}`);\n\n // Change to the working directory to ensure all file operations happen there\n try {\n process.chdir(workingDir);\n } catch (err) {\n printWarning(`Could not change to directory ${workingDir}: ${err.message}`);\n }\n\n try {\n printSuccess('Initializing Claude Code integration files...');\n\n // Check if files already exist in the working directory\n const files = ['CLAUDE.md', 'memory-bank.md', 'coordination.md'];\n const existingFiles = [];\n\n for (const file of files) {\n try {\n await fs.stat(`${workingDir}/${file}`);\n existingFiles.push(file);\n } catch {\n // File doesn't exist, which is what we want\n }\n }\n\n if (existingFiles.length > 0 && !initForce) {\n printWarning(`The following files already exist: ${existingFiles.join(', ')}`);\n console.log('Use --force to overwrite existing files');\n return;\n }\n\n // Use template copier to copy all template files\n const templateOptions = {\n sparc: initSparc,\n minimal: initMinimal,\n optimized: initOptimized,\n dryRun: initDryRun,\n force: initForce,\n selectedModes: selectedModes,\n verify: initVerify,\n pair: initPair,\n };\n\n // If verification flags are set, always use generated templates for CLAUDE.md and settings.json\n if (initVerify || initPair) {\n console.log(' π Creating verification-focused configuration...');\n \n // Create verification CLAUDE.md\n if (!initDryRun) {\n const { createVerificationClaudeMd, createVerificationSettingsJson } = await import('./templates/verification-claude-md.js');\n await fs.writeFile(`${workingDir}/CLAUDE.md`, createVerificationClaudeMd(), 'utf8');\n \n // Create .claude directory and settings\n await fs.mkdir(`${workingDir}/.claude`, { recursive: true });\n await fs.writeFile(`${workingDir}/.claude/settings.json`, createVerificationSettingsJson(), 'utf8');\n console.log(' β
Created verification-focused CLAUDE.md and settings.json');\n } else {\n console.log(' [DRY RUN] Would create verification-focused CLAUDE.md and settings.json');\n }\n \n // Copy other template files from repository if available\n const validation = validateTemplatesExist();\n if (validation.valid) {\n const revisedResults = await copyRevisedTemplates(workingDir, {\n force: initForce,\n dryRun: initDryRun,\n verbose: false,\n sparc: initSparc\n });\n }\n \n // Also create standard memory and coordination files\n const copyResults = await copyTemplates(workingDir, {\n ...templateOptions,\n skipClaudeMd: true, // Don't overwrite the verification CLAUDE.md\n skipSettings: true // Don't overwrite the verification settings.json\n });\n \n } else {\n // Standard template copying logic\n const validation = validateTemplatesExist();\n if (validation.valid) {\n console.log(' π Copying revised template files...');\n const revisedResults = await copyRevisedTemplates(workingDir, {\n force: initForce,\n dryRun: initDryRun,\n verbose: true,\n sparc: initSparc\n });\n\n if (revisedResults.success) {\n console.log(` β
Copied ${revisedResults.copiedFiles.length} template files`);\n if (revisedResults.skippedFiles.length > 0) {\n console.log(` βοΈ Skipped ${revisedResults.skippedFiles.length} existing files`);\n }\n } else {\n console.log(' β οΈ Some template files could not be copied:');\n revisedResults.errors.forEach(err => console.log(` - ${err}`));\n }\n } else {\n // Fall back to generated templates\n console.log(' β οΈ Revised templates not available, using generated templates');\n const copyResults = await copyTemplates(workingDir, templateOptions);\n\n if (!copyResults.success) {\n printError('Failed to copy templates:');\n copyResults.errors.forEach(err => console.log(` β ${err}`));\n return;\n }\n }\n }\n\n // Agent setup moved to end of function where execution is guaranteed\n\n // Directory structure is created by template copier\n\n // SPARC files are created by template copier when --sparc flag is used\n\n // Memory README files and persistence database are created by template copier\n\n // Create local claude-flow@alpha executable wrapper\n if (!initDryRun) {\n await createLocalExecutable(workingDir);\n } else {\n console.log(' [DRY RUN] Would create local claude-flow@alpha executable wrapper');\n }\n\n // SPARC initialization\n if (initSparc) {\n console.log('\\nπ Initializing SPARC development environment...');\n\n if (initDryRun) {\n console.log(' [DRY RUN] Would run: npx -y create-sparc init --force');\n console.log(' [DRY RUN] Would create SPARC environment with all modes');\n console.log(\n ' [DRY RUN] Would create Claude slash commands' +\n (initOptimized ? ' (Batchtools-optimized)' : ''),\n );\n if (selectedModes) {\n console.log(\n ` [DRY RUN] Would create commands for selected modes: ${selectedModes.join(', ')}`,\n );\n }\n } else {\n // Check if create-sparc exists and run it\n let sparcInitialized = false;\n try {\n // Use isolated NPX cache to prevent concurrent conflicts\n console.log(' π Running: npx -y create-sparc init --force');\n const createSparcResult = await runCommand('npx', ['-y', 'create-sparc', 'init', '--force'], {\n cwd: workingDir,\n stdout: 'inherit',\n stderr: 'inherit',\n env: getIsolatedNpxEnv({\n PWD: workingDir,\n }),\n });\n\n if (createSparcResult.success) {\n console.log(' β
SPARC environment initialized successfully');\n sparcInitialized = true;\n } else {\n printWarning('create-sparc failed, creating basic SPARC structure manually...');\n\n // Fallback: create basic SPARC structure manually\n await createSparcStructureManually();\n sparcInitialized = true; // Manual creation still counts as initialized\n }\n } catch (err) {\n printWarning('create-sparc not available, creating basic SPARC structure manually...');\n\n // Fallback: create basic SPARC structure manually\n await createSparcStructureManually();\n sparcInitialized = true; // Manual creation still counts as initialized\n }\n\n // Always create Claude slash commands after SPARC initialization\n if (sparcInitialized) {\n try {\n if (initOptimized) {\n await createOptimizedClaudeSlashCommands(workingDir, selectedModes);\n } else {\n await createClaudeSlashCommands(workingDir);\n }\n } catch (err) {\n // Legacy slash command creation - silently skip if it fails\n // SPARC slash commands are already created successfully above\n }\n }\n }\n }\n\n if (initDryRun) {\n printSuccess(\"π Dry run completed! Here's what would be created:\");\n console.log('\\nπ Summary of planned initialization:');\n console.log(\n ` β’ Configuration: ${initOptimized ? 'Batchtools-optimized SPARC' : initSparc ? 'SPARC-enhanced' : 'Standard'}`,\n );\n console.log(\n ` β’ Template type: ${initOptimized ? 'Optimized for parallel processing' : 'Standard'}`,\n );\n console.log(' β’ Core files: CLAUDE.md, memory-bank.md, coordination.md');\n console.log(' β’ Directory structure: memory/, coordination/, .claude/');\n console.log(' β’ Local executable: ./claude-flow@alpha');\n if (initSparc) {\n console.log(\n ` β’ Claude Code slash commands: ${selectedModes ? selectedModes.length : 'All'} SPARC mode commands`,\n );\n console.log(' β’ SPARC environment with all development modes');\n }\n if (initOptimized) {\n console.log(' β’ Batchtools optimization: Enabled for parallel processing');\n console.log(' β’ Performance enhancements: Smart batching, concurrent operations');\n }\n console.log('\\nπ To proceed with initialization, run the same command without --dry-run');\n } else {\n printSuccess('π Claude Code integration files initialized successfully!');\n\n if (initOptimized) {\n console.log('\\nβ‘ Batchtools Optimization Enabled!');\n console.log(' β’ Parallel processing capabilities activated');\n console.log(' β’ Performance improvements: 250-500% faster operations');\n console.log(' β’ Smart batching and concurrent operations available');\n }\n\n console.log('\\nπ What was created:');\n console.log(\n ` β
CLAUDE.md (${initOptimized ? 'Batchtools-optimized' : initSparc ? 'SPARC-enhanced' : 'Standard configuration'})`,\n );\n console.log(\n ` β
memory-bank.md (${initOptimized ? 'With parallel processing' : 'Standard memory system'})`,\n );\n console.log(\n ` β
coordination.md (${initOptimized ? 'Enhanced with batchtools' : 'Standard coordination'})`,\n );\n console.log(' β
Directory structure with memory/ and coordination/');\n console.log(' β
Local executable at ./claude-flow@alpha');\n console.log(' β
Persistence database at memory/claude-flow@alpha-data.json');\n console.log(' β
Agent system with 64 specialized agents in .claude/agents/');\n\n if (initSparc) {\n const modeCount = selectedModes ? selectedModes.length : '20+';\n console.log(` β
Claude Code slash commands (${modeCount} SPARC modes)`);\n console.log(' β
Complete SPARC development environment');\n }\n\n console.log('\\nπ Next steps:');\n console.log('1. Review and customize the generated files for your project');\n console.log(\"2. Run './claude-flow@alpha start' to begin the orchestration system\");\n console.log(\"3. Use './claude-flow@alpha' instead of 'npx claude-flow@alpha' for all commands\");\n console.log(\"4. Use 'claude --dangerously-skip-permissions' for unattended operation\");\n\n if (initSparc) {\n console.log(\n '5. Use Claude Code slash commands: /sparc, /sparc-architect, /sparc-tdd, etc.',\n );\n console.log(\"6. Explore SPARC modes with './claude-flow@alpha sparc modes'\");\n console.log('7. Try TDD workflow with \\'./claude-flow@alpha sparc tdd \"your task\"\\'');\n\n if (initOptimized) {\n console.log('8. Use batchtools commands: /batchtools, /performance for optimization');\n console.log('9. Enable parallel processing with --parallel flags');\n console.log(\"10. Monitor performance with './claude-flow@alpha performance monitor'\");\n }\n }\n\n // Update .gitignore\n const gitignoreResult = await updateGitignore(workingDir, initForce, initDryRun);\n if (gitignoreResult.success) {\n if (!initDryRun) {\n console.log(` β
${gitignoreResult.message}`);\n } else {\n console.log(` ${gitignoreResult.message}`);\n }\n } else {\n console.log(` β οΈ ${gitignoreResult.message}`);\n }\n\n console.log('\\nπ‘ Tips:');\n console.log(\" β’ Type '/' in Claude Code to see all available slash commands\");\n console.log(\" β’ Use './claude-flow@alpha status' to check system health\");\n console.log(\" β’ Store important context with './claude-flow@alpha memory store'\");\n\n if (initOptimized) {\n console.log(' β’ Use --parallel flags for concurrent operations');\n console.log(' β’ Enable batch processing for multiple related tasks');\n console.log(' β’ Monitor performance with real-time metrics');\n }\n\n // Initialize hive-mind system for standard init\n console.log('\\nπ§ Initializing basic hive-mind system...');\n try {\n const hiveMindOptions = {\n config: {\n integration: {\n claudeCode: { enabled: isClaudeCodeInstalled() },\n mcpTools: { enabled: true }\n },\n monitoring: { enabled: false } // Basic setup for standard init\n }\n };\n \n const hiveMindResult = await initializeHiveMind(workingDir, hiveMindOptions, false);\n \n if (hiveMindResult.success) {\n console.log(' β
Basic hive-mind system initialized');\n console.log(' π‘ Use \"npx claude-flow@alpha hive-mind\" for advanced features');\n } else {\n console.log(` β οΈ Hive-mind setup skipped: ${hiveMindResult.error}`);\n }\n } catch (err) {\n console.log(` β οΈ Hive-mind setup skipped: ${err.message}`);\n }\n\n // Check for Claude Code and set up MCP servers (always enabled by default)\n if (!initDryRun && isClaudeCodeInstalled()) {\n console.log('\\nπ Claude Code CLI detected!');\n const skipMcp = subArgs && subArgs.includes && subArgs.includes('--skip-mcp');\n\n if (!skipMcp) {\n await setupMcpServers(initDryRun);\n } else {\n console.log(' βΉοΈ Skipping MCP setup (--skip-mcp flag used)');\n }\n } else if (!initDryRun && !isClaudeCodeInstalled()) {\n console.log('\\nβ οΈ Claude Code CLI not detected!');\n console.log(' π₯ Install with: npm install -g @anthropic-ai/claude-code');\n console.log(' π Then add MCP servers manually with:');\n console.log(' claude mcp add claude-flow npx claude-flow@alpha mcp start');\n console.log(' claude mcp add ruv-swarm npx ruv-swarm mcp start');\n console.log(' claude mcp add flow-nexus npx flow-nexus@latest mcp start');\n }\n }\n } catch (err) {\n printError(`Failed to initialize files: ${err.message}`);\n }\n}\n\n// Handle batch initialization\nasync function handleBatchInit(subArgs, flags) {\n try {\n // Options parsing from flags and subArgs\n const options = {\n parallel: !flags['no-parallel'] && flags.parallel !== false,\n sparc: flags.sparc || flags.s,\n minimal: flags.minimal || flags.m,\n force: flags.force || flags.f,\n maxConcurrency: flags['max-concurrent'] || 5,\n progressTracking: true,\n template: flags.template,\n environments: flags.environments\n ? flags.environments.split(',').map((env) => env.trim())\n : ['dev'],\n };\n\n // Validate options\n const validationErrors = validateBatchOptions(options);\n if (validationErrors.length > 0) {\n printError('Batch options validation failed:');\n validationErrors.forEach((error) => console.error(` - ${error}`));\n return;\n }\n\n // Config file mode\n if (flags.config) {\n const configFile = flags.config;\n printSuccess(`Loading batch configuration from: ${configFile}`);\n const results = await batchInitFromConfig(configFile, options);\n if (results) {\n printSuccess('Batch initialization from config completed');\n }\n return;\n }\n\n // Batch init mode\n if (flags['batch-init']) {\n const projectsString = flags['batch-init'];\n const projects = projectsString.split(',').map((project) => project.trim());\n\n if (projects.length === 0) {\n printError('No projects specified for batch initialization');\n return;\n }\n\n printSuccess(`Initializing ${projects.length} projects in batch mode`);\n const results = await batchInitCommand(projects, options);\n\n if (results) {\n const successful = results.filter((r) => r.success).length;\n const failed = results.filter((r) => !r.success).length;\n\n if (failed === 0) {\n printSuccess(`All ${successful} projects initialized successfully`);\n } else {\n printWarning(`${successful} projects succeeded, ${failed} failed`);\n }\n }\n return;\n }\n\n printError('No batch operation specified. Use --batch-init <projects> or --config <file>');\n } catch (err) {\n printError(`Batch initialization failed: ${err.message}`);\n }\n}\n\n/**\n * Enhanced initialization command with validation and rollback\n */\nasync function enhancedInitCommand(subArgs, flags) {\n console.log('π‘οΈ Starting enhanced initialization with validation and rollback...');\n\n // Store parameters to avoid scope issues in async context\n const args = subArgs || [];\n const options = flags || {};\n\n // Get the working directory\n const workingDir = process.env.PWD || process.cwd();\n\n // Initialize systems\n const rollbackSystem = new RollbackSystem(workingDir);\n const validationSystem = new ValidationSystem(workingDir);\n\n let atomicOp = null;\n\n try {\n // Parse options\n const initOptions = {\n force: args.includes('--force') || args.includes('-f') || options.force,\n minimal: args.includes('--minimal') || args.includes('-m') || options.minimal,\n sparc: args.includes('--sparc') || args.includes('-s') || options.sparc,\n skipPreValidation: args.includes('--skip-pre-validation'),\n skipBackup: args.includes('--skip-backup'),\n validateOnly: args.includes('--validate-only'),\n };\n\n // Phase 1: Pre-initialization validation\n if (!initOptions.skipPreValidation) {\n console.log('\\nπ Phase 1: Pre-initialization validation...');\n const preValidation = await validationSystem.validatePreInit(initOptions);\n\n if (!preValidation.success) {\n printError('Pre-initialization validation failed:');\n preValidation.errors.forEach((error) => console.error(` β ${error}`));\n return;\n }\n\n if (preValidation.warnings.length > 0) {\n printWarning('Pre-initialization warnings:');\n preValidation.warnings.forEach((warning) => console.warn(` β οΈ ${warning}`));\n }\n\n printSuccess('Pre-initialization validation passed');\n }\n\n // Stop here if validation-only mode\n if (options.validateOnly) {\n console.log('\\nβ
Validation-only mode completed');\n return;\n }\n\n // Phase 2: Create backup\n if (!options.skipBackup) {\n console.log('\\nπΎ Phase 2: Creating backup...');\n const backupResult = await rollbackSystem.createPreInitBackup();\n\n if (!backupResult.success) {\n printError('Backup creation failed:');\n backupResult.errors.forEach((error) => console.error(` β ${error}`));\n return;\n }\n }\n\n // Phase 3: Initialize with atomic operations\n console.log('\\nπ§ Phase 3: Atomic initialization...');\n atomicOp = createAtomicOperation(rollbackSystem, 'enhanced-init');\n\n const atomicBegin = await atomicOp.begin();\n if (!atomicBegin) {\n printError('Failed to begin atomic operation');\n return;\n }\n\n // Perform initialization steps with checkpoints\n await performInitializationWithCheckpoints(rollbackSystem, options, workingDir, dryRun);\n\n // Phase 4: Post-initialization validation\n console.log('\\nβ
Phase 4: Post-initialization validation...');\n const postValidation = await validationSystem.validatePostInit();\n\n if (!postValidation.success) {\n printError('Post-initialization validation failed:');\n postValidation.errors.forEach((error) => console.error(` β ${error}`));\n\n // Attempt automatic rollback\n console.log('\\nπ Attempting automatic rollback...');\n await atomicOp.rollback();\n printWarning('Initialization rolled back due to validation failure');\n return;\n }\n\n // Phase 5: Configuration validation\n console.log('\\nπ§ Phase 5: Configuration validation...');\n const configValidation = await validationSystem.validateConfiguration();\n\n if (configValidation.warnings.length > 0) {\n printWarning('Configuration warnings:');\n configValidation.warnings.forEach((warning) => console.warn(` β οΈ ${warning}`));\n }\n\n // Phase 6: Health checks\n console.log('\\nπ₯ Phase 6: System health checks...');\n const healthChecks = await validationSystem.runHealthChecks();\n\n if (healthChecks.warnings.length > 0) {\n printWarning('Health check warnings:');\n healthChecks.warnings.forEach((warning) => console.warn(` β οΈ ${warning}`));\n }\n\n // Commit atomic operation\n await atomicOp.commit();\n\n // Generate and display validation report\n const fullValidation = await runFullValidation(workingDir, {\n postInit: true,\n skipPreInit: options.skipPreValidation,\n });\n\n console.log('\\nπ Validation Report:');\n console.log(fullValidation.report);\n\n printSuccess('π Enhanced initialization completed successfully!');\n console.log('\\nβ¨ Your SPARC environment is fully validated and ready to use');\n } catch (error) {\n printError(`Enhanced initialization failed: ${error.message}`);\n\n // Attempt rollback if atomic operation is active\n if (atomicOp && !atomicOp.completed) {\n console.log('\\nπ Performing emergency rollback...');\n try {\n await atomicOp.rollback();\n printWarning('Emergency rollback completed');\n } catch (rollbackError) {\n printError(`Rollback also failed: ${rollbackError.message}`);\n }\n }\n }\n}\n\n/**\n * Handle validation commands\n */\nasync function handleValidationCommand(subArgs, flags) {\n const workingDir = process.env.PWD || process.cwd();\n\n console.log('π Running validation checks...');\n\n const options = {\n skipPreInit: subArgs.includes('--skip-pre-init'),\n skipConfig: subArgs.includes('--skip-config'),\n skipModeTest: subArgs.includes('--skip-mode-test'),\n postInit: !subArgs.includes('--pre-init-only'),\n };\n\n try {\n const validationResults = await runFullValidation(workingDir, options);\n\n console.log('\\nπ Validation Results:');\n console.log(validationResults.report);\n\n if (validationResults.success) {\n printSuccess('β
All validation checks passed');\n } else {\n printError('β Some validation checks failed');\n process.exit(1);\n }\n } catch (error) {\n printError(`Validation failed: ${error.message}`);\n process.exit(1);\n }\n}\n\n/**\n * Handle rollback commands\n */\nasync function handleRollbackCommand(subArgs, flags) {\n const workingDir = process.env.PWD || process.cwd();\n const rollbackSystem = new RollbackSystem(workingDir);\n\n try {\n // Check for specific rollback options\n if (subArgs.includes('--full')) {\n console.log('π Performing full rollback...');\n const result = await rollbackSystem.performFullRollback();\n\n if (result.success) {\n printSuccess('Full rollback completed successfully');\n } else {\n printError('Full rollback failed:');\n result.errors.forEach((error) => console.error(` β ${error}`));\n }\n } else if (subArgs.includes('--partial')) {\n const phaseIndex = subArgs.findIndex((arg) => arg === '--phase');\n if (phaseIndex !== -1 && subArgs[phaseIndex + 1]) {\n const phase = subArgs[phaseIndex + 1];\n console.log(`π Performing partial rollback for phase: ${phase}`);\n\n const result = await rollbackSystem.performPartialRollback(phase);\n\n if (result.success) {\n printSuccess(`Partial rollback completed for phase: ${phase}`);\n } else {\n printError(`Partial rollback failed for phase: ${phase}`);\n result.errors.forEach((error) => console.error(` β ${error}`));\n }\n } else {\n printError('Partial rollback requires --phase <phase-name>');\n }\n } else {\n // Interactive rollback point selection\n const rollbackPoints = await rollbackSystem.listRollbackPoints();\n\n if (rollbackPoints.rollbackPoints.length === 0) {\n printWarning('No rollback points available');\n return;\n }\n\n console.log('\\nπ Available rollback points:');\n rollbackPoints.rollbackPoints.forEach((point, index) => {\n const date = new Date(point.timestamp).toLocaleString();\n console.log(` ${index + 1}. ${point.type} - ${date}`);\n });\n\n // For now, rollback to the most recent point\n const latest = rollbackPoints.rollbackPoints[0];\n if (latest) {\n console.log(\n `\\nπ Rolling back to: ${latest.type} (${new Date(latest.timestamp).toLocaleString()})`,\n );\n const result = await rollbackSystem.performFullRollback(latest.backupId);\n\n if (result.success) {\n printSuccess('Rollback completed successfully');\n } else {\n printError('Rollback failed');\n }\n }\n }\n } catch (error) {\n printError(`Rollback operation failed: ${error.message}`);\n }\n}\n\n/**\n * Handle list backups command\n */\nasync function handleListBackups(subArgs, flags) {\n const workingDir = process.env.PWD || process.cwd();\n const rollbackSystem = new RollbackSystem(workingDir);\n\n try {\n const rollbackPoints = await rollbackSystem.listRollbackPoints();\n\n console.log('\\nπ Rollback Points and Backups:');\n\n if (rollbackPoints.rollbackPoints.length === 0) {\n console.log(' No rollback points available');\n } else {\n console.log('\\nπ Rollback Points:');\n rollbackPoints.rollbackPoints.forEach((point, index) => {\n const date = new Date(point.timestamp).toLocaleString();\n console.log(` ${index + 1}. ${point.type} - ${date} (${point.backupId || 'No backup'})`);\n });\n }\n\n if (rollbackPoints.checkpoints.length > 0) {\n console.log('\\nπ Checkpoints:');\n rollbackPoints.checkpoints.slice(-5).forEach((checkpoint, index) => {\n const date = new Date(checkpoint.timestamp).toLocaleString();\n console.log(` ${index + 1}. ${checkpoint.phase} - ${date} (${checkpoint.status})`);\n });\n }\n } catch (error) {\n printError(`Failed to list backups: ${error.message}`);\n }\n}\n\n/**\n * Perform initialization with checkpoints\n */\nasync function performInitializationWithCheckpoints(\n rollbackSystem,\n options,\n workingDir,\n dryRun = false,\n) {\n const phases = [\n { name: 'file-creation', action: () => createInitialFiles(options, workingDir, dryRun) },\n { name: 'directory-structure', action: () => createDirectoryStructure(workingDir, dryRun) },\n { name: 'memory-setup', action: () => setupMemorySystem(workingDir, dryRun) },\n { name: 'coordination-setup', action: () => setupCoordinationSystem(workingDir, dryRun) },\n { name: 'executable-creation', action: () => createLocalExecutable(workingDir, dryRun) },\n ];\n\n if (options.sparc) {\n phases.push(\n { name: 'sparc-init', action: () => createSparcStructureManually() },\n { name: 'claude-commands', action: () => createClaudeSlashCommands(workingDir) },\n );\n }\n\n for (const phase of phases) {\n console.log(` π§ ${phase.name}...`);\n\n // Create checkpoint before phase\n await rollbackSystem.createCheckpoint(phase.name, {\n timestamp: Date.now(),\n phase: phase.name,\n });\n\n try {\n await phase.action();\n console.log(` β
${phase.name} completed`);\n } catch (error) {\n console.error(` β ${phase.name} failed: ${error.message}`);\n throw error;\n }\n }\n}\n\n// Helper functions for atomic initialization\nasync function createInitialFiles(options, workingDir, dryRun = false) {\n if (!dryRun) {\n const claudeMd = options.sparc\n ? createSparcClaudeMd()\n : options.minimal\n ? createMinimalClaudeMd()\n : createFullClaudeMd();\n await fs.writeFile(`${workingDir}/CLAUDE.md`, claudeMd, 'utf8');\n\n const memoryBankMd = options.minimal ? createMinimalMemoryBankMd() : createFullMemoryBankMd();\n await fs.writeFile(`${workingDir}/memory-bank.md`, memoryBankMd, 'utf8');\n\n const coordinationMd = options.minimal\n ? createMinimalCoordinationMd()\n : createFullCoordinationMd();\n await fs.writeFile(`${workingDir}/coordination.md`, coordinationMd, 'utf8');\n }\n}\n\nasync function createDirectoryStructure(workingDir, dryRun = false) {\n const directories = [\n 'memory',\n 'memory/agents',\n 'memory/sessions',\n 'coordination',\n 'coordination/memory_bank',\n 'coordination/subtasks',\n 'coordination/orchestration',\n '.claude',\n '.claude/commands',\n '.claude/logs',\n ];\n\n if (!dryRun) {\n for (const dir of directories) {\n await fs.mkdir(`${workingDir}/${dir}`, { recursive: true });\n }\n }\n}\n\nasync function setupMemorySystem(workingDir, dryRun = false) {\n if (!dryRun) {\n const initialData = { agents: [], tasks: [], lastUpdated: Date.now() };\n await fs.writeFile(\n `${workingDir}/memory/claude-flow@alpha-data.json`, JSON.stringify(initialData, null, 2), 'utf8'\n );\n\n await fs.writeFile(`${workingDir}/memory/agents/README.md`, createAgentsReadme(), 'utf8');\n await fs.writeFile(`${workingDir}/memory/sessions/README.md`, createSessionsReadme(), 'utf8');\n }\n}\n\nasync function setupCoordinationSystem(workingDir, dryRun = false) {\n // Coordination system is already set up by createDirectoryStructure\n // This is a placeholder for future coordination setup logic\n}\n\n/**\n * Setup monitoring and telemetry for token tracking\n */\nasync function setupMonitoring(workingDir) {\n console.log(' π Configuring token usage tracking...');\n \n const fs = await import('fs/promises');\n const path = await import('path');\n \n try {\n // Create .claude-flow@alpha directory for tracking data\n const trackingDir = path.join(workingDir, '.claude-flow@alpha');\n await fs.mkdir(trackingDir, { recursive: true });\n \n // Create initial token usage file\n const tokenUsageFile = path.join(trackingDir, 'token-usage.json');\n const initialData = {\n total: 0,\n input: 0,\n output: 0,\n byAgent: {},\n lastUpdated: new Date().toISOString()\n };\n \n await fs.writeFile(tokenUsageFile, JSON.stringify(initialData, null, 2));\n printSuccess(' β Created token usage tracking file');\n \n // Add telemetry configuration to .claude/settings.json if it exists\n const settingsPath = path.join(workingDir, '.claude', 'settings.json');\n try {\n const settingsContent = await fs.readFile(settingsPath, 'utf8');\n const settings = JSON.parse(settingsContent);\n \n // Add telemetry hook\n if (!settings.hooks) settings.hooks = {};\n if (!settings.hooks['post-task']) settings.hooks['post-task'] = [];\n \n // Add token tracking hook\n const tokenTrackingHook = 'npx claude-flow@alpha internal track-tokens --session-id {{session_id}} --tokens {{token_usage}}';\n if (!settings.hooks['post-task'].includes(tokenTrackingHook)) {\n settings.hooks['post-task'].push(tokenTrackingHook);\n }\n \n await fs.writeFile(settingsPath, JSON.stringify(settings, null, 2));\n printSuccess(' β Added token tracking hooks to settings');\n } catch (err) {\n console.log(' β οΈ Could not update settings.json:', err.message);\n }\n \n // Create monitoring configuration\n const monitoringConfig = {\n enabled: true,\n telemetry: {\n claudeCode: {\n env: 'CLAUDE_CODE_ENABLE_TELEMETRY',\n value: '1',\n description: 'Enable Claude Code OpenTelemetry metrics'\n }\n },\n tracking: {\n tokens: true,\n costs: true,\n agents: true,\n sessions: true\n },\n storage: {\n location: '.claude-flow@alpha/token-usage.json',\n format: 'json',\n rotation: 'monthly'\n }\n };\n \n const configPath = path.join(trackingDir, 'monitoring.config.json');\n await fs.writeFile(configPath, JSON.stringify(monitoringConfig, null, 2));\n printSuccess(' β Created monitoring configuration');\n \n // Create shell profile snippet for environment variable\n const envSnippet = `\n# Claude Flow Token Tracking\n# Add this to your shell profile (.bashrc, .zshrc, etc.)\nexport CLAUDE_CODE_ENABLE_TELEMETRY=1\n\n# Optional: Set custom metrics path\n# export CLAUDE_METRICS_PATH=\"$HOME/.claude/metrics\"\n`;\n \n const envPath = path.join(trackingDir, 'env-setup.sh');\n await fs.writeFile(envPath, envSnippet.trim());\n printSuccess(' β Created environment setup script');\n \n console.log('\\n π To enable Claude Code telemetry:');\n console.log(' 1. Add to your shell profile: export CLAUDE_CODE_ENABLE_TELEMETRY=1');\n console.log(' 2. Or run: source .claude-flow@alpha/env-setup.sh');\n console.log('\\n π‘ Token usage will be tracked in .claude-flow@alpha/token-usage.json');\n console.log(' Run: claude-flow@alpha analysis token-usage --breakdown --cost-analysis');\n \n } catch (err) {\n printError(` Failed to setup monitoring: ${err.message}`);\n }\n}\n\n/**\n * Enhanced Claude Flow v2.0.0 initialization\n */\nasync function enhancedClaudeFlowInit(flags, subArgs = []) {\n console.log('π Initializing Claude Flow v2.0.0 with enhanced features...');\n\n const workingDir = process.cwd();\n const force = flags.force || flags.f;\n const dryRun = flags.dryRun || flags['dry-run'] || flags.d;\n const initSparc = flags.roo || (subArgs && subArgs.includes('--roo')); // SPARC only with --roo flag\n\n // Parse --agent flag for specialized agent setup\n const agentType = flags.agent || (subArgs && subArgs.find(arg => arg.startsWith('--agent='))?.split('=')[1]);\n const initReasoning = agentType === 'reasoning' || (subArgs && subArgs.includes('--agent') && subArgs.includes('reasoning'));\n\n // Store parameters to avoid scope issues in async context\n const args = subArgs || [];\n const options = flags || {};\n\n // Import fs, path, and os modules for Node.js\n const fs = await import('fs/promises');\n const { chmod } = fs;\n const path = await import('path');\n const os = await import('os');\n\n try {\n // Check existing files\n const existingFiles = [];\n const filesToCheck = [\n 'CLAUDE.md',\n '.claude/settings.json',\n '.mcp.json',\n // Removed claude-flow@alpha.config.json per user request\n ];\n\n for (const file of filesToCheck) {\n if (existsSync(`${workingDir}/${file}`)) {\n existingFiles.push(file);\n }\n }\n\n if (existingFiles.length > 0 && !force) {\n printWarning(`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 if (!dryRun) {\n await fs.writeFile(`${workingDir}/CLAUDE.md`, createOptimizedSparcClaudeMd(), 'utf8');\n printSuccess('β Created CLAUDE.md (Claude Flow v2.0.0 - Optimized)');\n } else {\n console.log('[DRY RUN] Would create CLAUDE.md (Claude Flow v2.0.0 - Optimized)');\n }\n\n // Create .claude directory structure\n const claudeDir = `${workingDir}/.claude`;\n if (!dryRun) {\n await fs.mkdir(claudeDir, { recursive: true });\n await fs.mkdir(`${claudeDir}/commands`, { recursive: true });\n await fs.mkdir(`${claudeDir}/helpers`, { recursive: true });\n printSuccess('β Created .claude directory structure');\n } else {\n console.log('[DRY RUN] Would create .claude directory structure');\n }\n\n // Create settings.json\n if (!dryRun) {\n await fs.writeFile(`${claudeDir}/settings.json`, createEnhancedSettingsJson(), 'utf8');\n printSuccess('β Created .claude/settings.json with hooks and MCP configuration');\n } else {\n console.log('[DRY RUN] Would create .claude/settings.json');\n }\n\n // Copy statusline script\n try {\n let statuslineTemplate;\n try {\n // Try to read from templates directory first\n statuslineTemplate = await fs.readFile(\n path.join(__dirname, 'templates', 'statusline-command.sh'),\n 'utf8'\n );\n } catch {\n // Fallback to embedded content (for binary builds)\n statuslineTemplate = createStatuslineScript();\n }\n\n if (!dryRun) {\n // Write to project .claude directory\n await fs.writeFile(`${claudeDir}/statusline-command.sh`, statuslineTemplate, 'utf8');\n await fs.chmod(`${claudeDir}/statusline-command.sh`, 0o755);\n\n // Also write to home ~/.claude directory for global use\n const homeClaudeDir = path.join(os.homedir(), '.claude');\n await fs.mkdir(homeClaudeDir, { recursive: true });\n await fs.writeFile(path.join(homeClaudeDir, 'statusline-command.sh'), statuslineTemplate, 'utf8');\n await fs.chmod(path.join(homeClaudeDir, 'statusline-command.sh'), 0o755);\n\n printSuccess('β Created statusline-command.sh in both .claude/ and ~/.claude/');\n } else {\n console.log('[DRY RUN] Would create .claude/statusline-command.sh and ~/.claude/statusline-command.sh');\n }\n } catch (err) {\n // Not critical, just skip\n if (!dryRun) {\n console.log(' β οΈ Could not create statusline script, skipping...');\n console.log(` βΉοΈ Error: ${err.message}`);\n }\n }\n\n // Create settings.local.json with default MCP permissions\n const settingsLocal = {\n permissions: {\n allow: ['mcp__ruv-swarm', 'mcp__claude-flow@alpha', 'mcp__flow-nexus'],\n deny: [],\n },\n };\n\n if (!dryRun) {\n await fs.writeFile(\n `${claudeDir}/settings.local.json`, JSON.stringify(settingsLocal, null, 2, 'utf8'),\n );\n printSuccess('β Created .claude/settings.local.json with default MCP permissions');\n } else {\n console.log(\n '[DRY RUN] Would create .claude/settings.local.json with default MCP permissions',\n );\n }\n\n // Create .mcp.json at project root for MCP server configuration\n const mcpConfig = {\n mcpServers: {\n 'claude-flow@alpha': {\n command: 'npx',\n args: ['claude-flow@alpha', 'mcp', 'start'],\n type: 'stdio',\n },\n 'ruv-swarm': {\n command: 'npx',\n args: ['ruv-swarm@latest', 'mcp', 'start'],\n type: 'stdio',\n },\n 'flow-nexus': {\n command: 'npx',\n args: ['flow-nexus@latest', 'mcp', 'start'],\n type: 'stdio',\n },\n },\n };\n\n if (!dryRun) {\n await fs.writeFile(`${workingDir}/.mcp.json`, JSON.stringify(mcpConfig, null, 2, 'utf8'));\n printSuccess('β Created .mcp.json at project root for MCP server configuration');\n } else {\n console.log('[DRY RUN] Would create .mcp.json at project root for MCP server configuration');\n }\n\n // Removed claude-flow@alpha.config.json creation per user request\n\n // Create command documentation\n for (const [category, commands] of Object.entries(COMMAND_STRUCTURE)) {\n const categoryDir = `${claudeDir}/commands/${category}`;\n\n if (!dryRun) {\n await fs.mkdir(categoryDir, { recursive: true });\n\n // Create category README\n const categoryReadme = `# ${category.charAt(0).toUpperCase() + category.slice(1)} Commands\n\nCommands for ${category} operations in Claude Flow.\n\n## Available Commands\n\n${commands.map((cmd) => `- [${cmd}](./${cmd}.md)`).join('\\n')}\n`;\n await fs.writeFile(`${categoryDir}/README.md`, categoryReadme, 'utf8');\n\n // Create individual command docs\n for (const command of commands) {\n const doc = createCommandDoc(category, command);\n if (doc) {\n await fs.writeFile(`${categoryDir}/${command}.md`, doc, 'utf8');\n }\n }\n\n console.log(` β Created ${commands.length} ${category} command docs`);\n } else {\n console.log(`[DRY RUN] Would create ${commands.length} ${category} command docs`);\n }\n }\n\n // Create wrapper scripts using the dedicated function\n if (!dryRun) {\n await createLocalExecutable(workingDir, dryRun);\n } else {\n console.log('[DRY RUN] Would create wrapper scripts');\n }\n\n // Create helper scripts\n const helpers = ['setup-mcp.sh', 'quick-start.sh', 'github-setup.sh', 'github-safe.js', 'standard-checkpoint-hooks.sh', 'checkpoint-manager.sh'];\n for (const helper of helpers) {\n if (!dryRun) {\n const content = createHelperScript(helper);\n if (content) {\n await fs.writeFile(`${claudeDir}/helpers/${helper}`, content, 'utf8');\n await fs.chmod(`${claudeDir}/helpers/${helper}`, 0o755);\n }\n }\n }\n\n if (!dryRun) {\n printSuccess(`β Created ${helpers.length} helper scripts`);\n } else {\n console.log(`[DRY RUN] Would create ${helpers.length} helper scripts`);\n }\n\n // Create standard directories from original init\n const standardDirs = [\n 'memory',\n 'memory/agents',\n 'memory/sessions',\n 'coordination',\n 'coordination/memory_bank',\n 'coordination/subtasks',\n 'coordination/orchestration',\n '.swarm', // Add .swarm directory for shared memory\n '.hive-mind', // Add .hive-mind directory for hive-mind system\n '.claude/checkpoints', // Add checkpoints directory for Git checkpoint system\n ];\n\n for (const dir of standardDirs) {\n if (!dryRun) {\n await fs.mkdir(`${workingDir}/${dir}`, { recursive: true });\n }\n }\n\n if (!dryRun) {\n printSuccess('β Created standard directory structure');\n\n // Initialize memory system\n const initialData = { agents: [], tasks: [], lastUpdated: Date.now() };\n await fs.writeFile(\n `${workingDir}/memory/claude-flow@alpha-data.json`, JSON.stringify(initialData, null, 2, 'utf8'),\n );\n\n // Create README files\n await fs.writeFile(`${workingDir}/memory/agents/README.md`, createAgentsReadme(), 'utf8');\n await fs.writeFile(`${workingDir}/memory/sessions/README.md`, createSessionsReadme(), 'utf8');\n\n printSuccess('β Initialized memory system');\n\n // Initialize memory database with fallback support\n try {\n // Check if database exists BEFORE creating it\n const dbPath = '.swarm/memory.db';\n const { existsSync } = await import('fs');\n const dbExistedBefore = existsSync(dbPath);\n\n // Handle ReasoningBank migration BEFORE FallbackMemoryStore initialization\n // This prevents schema conflicts with old databases\n if (dbExistedBefore) {\n console.log(' π Checking existing database for ReasoningBank schema...');\n\n try {\n const {\n initializeReasoningBank,\n checkReasoningBankTables,\n migrateReasoningBank\n } = await import('../../../reasoningbank/reasoningbank-adapter.js');\n\n // Set the database path for ReasoningBank\n process.env.CLAUDE_FLOW_DB_PATH = dbPath;\n\n const tableCheck = await checkReasoningBankTables();\n\n if (tableCheck.exists) {\n console.log(' β
ReasoningBank schema already complete');\n } else if (force) {\n // User used --force flag, migrate the database\n console.log(` π Migrating database: ${tableCheck.missingTables.length} tables missing`);\n console.log(` Missing: ${tableCheck.missingTables.join(', ')}`);\n\n const migrationResult = await migrateReasoningBank();\n\n if (migrationResult.success) {\n printSuccess(` β Migration complete: added ${migrationResult.addedTables?.length || 0} tables`);\n console.log(' Use --reasoningbank flag to enable AI-powered memory features');\n } else {\n console.log(` β οΈ Migration failed: ${migrationResult.message}`);\n console.log(' Basic memory will work, use: memory init --reasoningbank to retry');\n }\n } else {\n // Database exists with missing tables but no --force flag\n console.log(` βΉοΈ Database has ${tableCheck.missingTables.length} missing ReasoningBank tables`);\n console.log(` Missing: ${tableCheck.missingTables.join(', ')}`);\n console.log(' Use --force to migrate existing database');\n console.log(' Or use: memory init --reasoningbank');\n }\n } catch (rbErr) {\n console.log(` β οΈ ReasoningBank check failed: ${rbErr.message}`);\n console.log(' Will attempt normal initialization...');\n }\n }\n\n // Import and initialize FallbackMemoryStore to create the database\n const { FallbackMemoryStore } = await import('../../../memory/fallback-store.js');\n const memoryStore = new FallbackMemoryStore();\n await memoryStore.initialize();\n\n if (memoryStore.isUsingFallback()) {\n printSuccess('β Initialized memory system (in-memory fallback for npx compatibility)');\n console.log(\n ' π‘ For persistent storage, install locally: npm install claude-flow@alpha',\n );\n } else {\n printSuccess('β Initialized memory database (.swarm/memory.db)');\n\n // Initialize ReasoningBank schema for fresh databases\n if (!dbExistedBefore) {\n try {\n const {\n initializeReasoningBank\n } = await import('../../../reasoningbank/reasoningbank-adapter.js');\n\n // Set the database path for ReasoningBank\n process.env.CLAUDE_FLOW_DB_PATH = dbPath;\n\n console.log(' π§ Initializing ReasoningBank schema...');\n await initializeReasoningBank();\n printSuccess(' β ReasoningBank schema initialized (use --reasoningbank flag for AI-powered memory)');\n } catch (rbErr) {\n console.log(` β οΈ ReasoningBank initialization failed: ${rbErr.message}`);\n console.log(' Basic memory will work, use: memory init --reasoningbank to retry');\n }\n }\n }\n\n memoryStore.close();\n } catch (err) {\n console.log(` β οΈ Could not initialize memory system: ${err.message}`);\n console.log(' Memory will be initialized on first use');\n }\n\n // Initialize comprehensive hive-mind system\n console.log('\\nπ§ Initializing Hive Mind System...');\n try {\n const hiveMindOptions = {\n config: {\n integration: {\n claudeCode: { enabled: isClaudeCodeInstalled() },\n mcpTools: { enabled: true }\n },\n monitoring: { enabled: flags.monitoring || false }\n }\n };\n \n const hiveMindResult = await initializeHiveMind(workingDir, hiveMindOptions, dryRun);\n \n if (hiveMindResult.success) {\n printSuccess(`β Hive Mind System initialized with ${hiveMindResult.features.length} features`);\n \n // Log individual features\n hiveMindResult.features.forEach(feature => {\n console.log(` β’ ${feature}`);\n });\n } else {\n console.log(` β οΈ Hive Mind initialization failed: ${hiveMindResult.error}`);\n if (hiveMindResult.rollbackRequired) {\n console.log(' π Automatic rollback may be required');\n }\n }\n } catch (err) {\n console.log(` β οΈ Could not initialize hive-mind system: ${err.message}`);\n }\n }\n\n // Update .gitignore with Claude Flow entries\n const gitignoreResult = await updateGitignore(workingDir, force, dryRun);\n if (gitignoreResult.success) {\n if (!dryRun) {\n printSuccess(`β ${gitignoreResult.message}`);\n } else {\n console.log(gitignoreResult.message);\n }\n } else {\n console.log(` β οΈ ${gitignoreResult.message}`);\n }\n\n // SPARC initialization (only with --roo flag)\n let sparcInitialized = false;\n if (initSparc) {\n console.log('\\nπ Initializing SPARC development environment...');\n try {\n // Run create-sparc\n console.log(' π Running: npx -y create-sparc init --force');\n execSync('npx -y create-sparc init --force', {\n cwd: workingDir,\n stdio: 'inherit',\n });\n sparcInitialized = true;\n printSuccess('β
SPARC environment initialized successfully');\n } catch (err) {\n console.log(` β οΈ Could not run create-sparc: ${err.message}`);\n console.log(' SPARC features will be limited to basic functionality');\n }\n }\n\n // Create Claude slash commands for SPARC\n if (sparcInitialized && !dryRun) {\n console.log('\\nπ Creating Claude Code slash commands...');\n await createClaudeSlashCommands(workingDir);\n }\n\n // Check for Claude Code and set up MCP servers (always enabled by default)\n if (!dryRun && isClaudeCodeInstalled()) {\n console.log('\\nπ Claude Code CLI detected!');\n const skipMcp =\n (options && options['skip-mcp']) ||\n (subArgs && subArgs.includes && subArgs.includes('--skip-mcp'));\n\n if (!skipMcp) {\n await setupMcpServers(dryRun);\n } else {\n console.log(' βΉοΈ Skipping MCP setup (--skip-mcp flag used)');\n console.log('\\n π To add MCP servers manually:');\n console.log(' claude mcp add claude-flow npx claude-flow@alpha mcp start');\n console.log(' claude mcp add ruv-swarm npx ruv-swarm@latest mcp start');\n console.log(' claude mcp add flow-nexus npx flow-nexus@latest mcp start');\n console.log('\\n π‘ MCP servers are defined in .mcp.json (project scope)');\n }\n } else if (!dryRun && !isClaudeCodeInstalled()) {\n console.log('\\nβ οΈ Claude Code CLI not detected!');\n console.log('\\n π₯ To install Claude Code:');\n console.log(' npm install -g @anthropic-ai/claude-code');\n console.log('\\n π After installing, add MCP servers:');\n console.log(' claude mcp add claude-flow@alpha npx claude-flow@alpha mcp start');\n console.log(' claude mcp add ruv-swarm npx ruv-swarm@latest mcp start');\n console.log(' claude mcp add flow-nexus npx flow-nexus@latest mcp start');\n console.log('\\n π‘ MCP servers are defined in .mcp.json (project scope)');\n }\n\n // Create agent directories and copy all agent files\n console.log('\\nπ€ Setting up agent system...');\n if (!dryRun) {\n await createAgentDirectories(workingDir, dryRun);\n const agentResult = await copyAgentFiles(workingDir, {\n force: force,\n dryRun: dryRun\n });\n\n if (agentResult.success) {\n await validateAgentSystem(workingDir);\n\n // Copy command files including Flow Nexus commands\n console.log('\\nπ Setting up command system...');\n const commandResult = await copyCommandFiles(workingDir, {\n force: force,\n dryRun: dryRun\n });\n\n if (commandResult.success) {\n console.log('β
β Command system setup complete with Flow Nexus integration');\n } else {\n console.log('β οΈ Command system setup failed:', commandResult.error);\n }\n\n // Copy skill files including skill-builder\n console.log('\\nπ― Setting up skill system...');\n const skillResult = await copySkillFiles(workingDir, {\n force: force,\n dryRun: dryRun\n });\n\n if (skillResult.success) {\n await validateSkillSystem(workingDir);\n console.log('β
β Skill system setup complete with skill-builder');\n } else {\n console.log('β οΈ Skill system setup failed:', skillResult.error);\n }\n\n console.log('β
β Agent system setup complete with 64 specialized agents');\n } else {\n console.log('β οΈ Agent system setup failed:', agentResult.error);\n }\n\n // Setup reasoning agents if --agent reasoning flag is used\n if (initReasoning) {\n console.log('\\nπ§ Setting up reasoning agents with ReasoningBank integration...');\n try {\n const reasoningAgentsDir = `${workingDir}/.claude/agents/reasoning`;\n await fs.mkdir(reasoningAgentsDir, { recursive: true });\n\n // Import path module\n const path = await import('path');\n const { fileURLToPath } = await import('url');\n const { dirname, join } = path.default;\n\n // Get the source reasoning agents directory\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n const sourceReasoningDir = join(__dirname, '../../../../.claude/agents/reasoning');\n\n // Copy reasoning agent files\n try {\n const reasoningFiles = await fs.readdir(sourceReasoningDir);\n let copiedReasoningAgents = 0;\n\n for (const file of reasoningFiles) {\n if (file.endsWith('.md')) {\n const sourcePath = join(sourceReasoningDir, file);\n const destPath = join(reasoningAgentsDir, file);\n const content = await fs.readFile(sourcePath, 'utf8');\n await fs.writeFile(destPath, content);\n copiedReasoningAgents++;\n }\n }\n\n printSuccess(`β Copied ${copiedReasoningAgents} reasoning agent files`);\n console.log(' π Reasoning agents available:');\n console.log(' β’ goal-planner - Goal-Oriented Action Planning specialist');\n console.log(' β’ sublinear-goal-planner - Sub-linear complexity goal planning');\n console.log(' π‘ Use: npx agentic-flow --agent goal-planner --task \"your task\"');\n console.log(' π Documentation: .claude/agents/reasoning/README.md');\n } catch (err) {\n console.log(` β οΈ Could not copy reasoning agents: ${err.message}`);\n console.log(' Reasoning agents may not be available yet');\n }\n } catch (err) {\n console.log(` β οΈ Reasoning agent setup failed: ${err.message}`);\n }\n }\n } else {\n console.log(' [DRY RUN] Would create agent system with 64 specialized agents');\n if (initReasoning) {\n console.log(' [DRY RUN] Would also setup reasoning agents with ReasoningBank integration');\n }\n }\n\n // Optional: Setup monitoring and telemetry\n const enableMonitoring = flags.monitoring || flags['enable-monitoring'];\n if (enableMonitoring && !dryRun) {\n console.log('\\nπ Setting up monitoring and telemetry...');\n await setupMonitoring(workingDir);\n }\n \n // Final instructions with hive-mind status\n console.log('\\nπ Claude Flow v2.0.0 initialization complete!');\n \n // Display hive-mind status\n const hiveMindStatus = getHiveMindStatus(workingDir);\n console.log('\\nπ§ Hive Mind System Status:');\n console.log(` Configuration: ${hiveMindStatus.configured ? 'β
Ready' : 'β Missing'}`);\n console.log(` Database: ${hiveMindStatus.database === 'sqlite' ? 'β
SQLite' : hiveMindStatus.database === 'fallback' ? 'β οΈ JSON Fallback' : 'β Not initialized'}`);\n console.log(` Directory Structure: ${hiveMindStatus.directories ? 'β
Created' : 'β Missing'}`);\n \n console.log('\\nπ Quick Start:');\n if (isClaudeCodeInstalled()) {\n console.log('1. View available commands: ls .claude/commands/');\n console.log('2. Start a swarm: npx claude-flow@alpha swarm \"your objective\" --claude');\n console.log('3. Use hive-mind: npx claude-flow@alpha hive-mind spawn \"command\" --claude');\n console.log('4. Use MCP tools in Claude Code for enhanced coordination');\n if (hiveMindStatus.configured) {\n console.log('5. Initialize first swarm: npx claude-flow@alpha hive-mind init');\n }\n } else {\n console.log('1. Install Claude Code: npm install -g @anthropic-ai/claude-code');\n console.log('2. Add MCP servers (see instructions above)');\n console.log('3. View available commands: ls .claude/commands/');\n console.log('4. Start a swarm: npx claude-flow@alpha swarm \"your objective\" --claude');\n console.log('5. Use hive-mind: npx claude-flow@alpha hive-mind spawn \"command\" --claude');\n if (hiveMindStatus.configured) {\n console.log('6. Initialize first swarm: npx claude-flow@alpha hive-mind init');\n }\n }\n console.log('\\nπ‘ Tips:');\n console.log('β’ Check .claude/commands/ for detailed documentation');\n console.log('β’ Use --help with any command for options');\n console.log('β’ Run commands with --claude flag for best Claude Code integration');\n console.log('β’ Enable GitHub integration with .claude/helpers/github-setup.sh');\n console.log('β’ Git checkpoints are automatically enabled in settings.json');\n console.log('β’ Use .claude/helpers/checkpoint-manager.sh for easy rollback');\n } catch (err) {\n printError(`Failed to initialize Claude Flow v2.0.0: ${err.message}`);\n \n // Attempt hive-mind rollback if it was partially initialized\n try {\n const hiveMindStatus = getHiveMindStatus(workingDir);\n if (hiveMindStatus.directories || hiveMindStatus.configured) {\n console.log('\\nπ Attempting hive-mind system rollback...');\n const rollbackResult = await rollbackHiveMindInit(workingDir);\n if (rollbackResult.success) {\n console.log(' β
Hive-mind rollback completed');\n } else {\n console.log(` β οΈ Hive-mind rollback failed: ${rollbackResult.error}`);\n }\n }\n } catch (rollbackErr) {\n console.log(` β οΈ Rollback error: ${rollbackErr.message}`);\n }\n }\n}\n\n/**\n * Flow Nexus minimal initialization - only creates Flow Nexus CLAUDE.md, commands, and agents\n */\nasync function flowNexusMinimalInit(flags, subArgs) {\n console.log('π Flow Nexus: Initializing minimal setup...');\n \n try {\n const force = flags.force || flags.f;\n \n // Import functions we need\n const { createFlowNexusClaudeMd } = await import('./templates/claude-md.js');\n const { promises: fs } = await import('fs');\n \n // Create Flow Nexus CLAUDE.md\n console.log('π Creating Flow Nexus CLAUDE.md...');\n const flowNexusClaudeMd = createFlowNexusClaudeMd();\n await fs.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 console.log('π Setting up Flow Nexus commands...');\n await fs.mkdir('.claude/commands/flow-nexus', { recursive: true });\n \n // Copy Flow Nexus command files\n const { fileURLToPath } = await import('url');\n const { dirname, join } = await import('path');\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = dirname(__filename);\n const sourceCommandsDir = join(__dirname, '../../../../.claude/commands/flow-nexus');\n try {\n const commandFiles = await fs.readdir(sourceCommandsDir);\n let copiedCommands = 0;\n \n for (const file of commandFiles) {\n if (file.endsWith('.md')) {\n const sourcePath = `${sourceCommandsDir}/${file}`;\n const destPath = `.claude/commands/flow-nexus/${file}`;\n const content = await fs.readFile(sourcePath, 'utf8');\n await fs.writeFile(destPath, content);\n copiedCommands++;\n }\n }\n \n console.log(` β
Copied ${copiedCommands} Flow Nexus command files`);\n } catch (err) {\n console.log(' β οΈ Could not copy Flow Nexus commands:', err.message);\n }\n \n // Create .claude/agents/flow-nexus directory and copy agents\n console.log('π€ Setting up Flow Nexus agents...');\n await fs.mkdir('.claude/agents/flow-nexus', { recursive: true });\n \n // Copy Flow Nexus agent files\n const sourceAgentsDir = join(__dirname, '../../../../.claude/agents/flow-nexus');\n try {\n const agentFiles = await fs.readdir(sourceAgentsDir);\n let copiedAgents = 0;\n \n for (const file of agentFiles) {\n if (file.endsWith('.md')) {\n const sourcePath = `${sourceAgentsDir}/${file}`;\n const destPath = `.claude/agents/flow-nexus/${file}`;\n const content = await fs.readFile(sourcePath, 'utf8');\n await fs.writeFile(destPath, content);\n copiedAgents++;\n }\n }\n \n console.log(` β
Copied ${copiedAgents} Flow Nexus agent files`);\n } catch (err) {\n console.log(' β οΈ Could not copy Flow Nexus agents:', err.message);\n }\n \n console.log('\\nπ Flow Nexus minimal initialization complete!');\n console.log('π Created: CLAUDE.md with Flow Nexus documentation');\n console.log('π Created: .claude/commands/flow-nexus/ directory with command documentation');\n console.log('π€ Created: .claude/agents/flow-nexus/ directory with specialized agents');\n console.log('');\n console.log('π‘ Quick Start:');\n console.log(' 1. Register: mcp__flow-nexus__user_register({ email, password })');\n console.log(' 2. Login: mcp__flow-nexus__user_login({ email, password })');\n console.log(' 3. Deploy: mcp__flow-nexus__swarm_init({ topology: \"mesh\", maxAgents: 5 })');\n console.log('');\n console.log('π Use Flow Nexus MCP tools in Claude Code for full functionality');\n \n } catch (err) {\n console.log(`β Flow Nexus initialization failed: ${err.message}`);\n console.log('Stack trace:', err.stack);\n process.exit(1);\n }\n}\n"],"names":["printSuccess","printError","printWarning","existsSync","process","spawn","execSync","runCommand","command","args","options","Promise","resolve","reject","child","cwd","env","stdio","stdout","stderr","on","data","code","success","Error","createLocalExecutable","createSparcStructureManually","createClaudeSlashCommands","createOptimizedClaudeSlashCommands","promises","fs","copyTemplates","copyRevisedTemplates","validateTemplatesExist","copyAgentFiles","createAgentDirectories","validateAgentSystem","copyCommandFiles","copySkillFiles","validateSkillSystem","showInitHelp","batchInitCommand","batchInitFromConfig","validateBatchOptions","ValidationSystem","runFullValidation","RollbackSystem","createAtomicOperation","createEnhancedSettingsJson","createCommandDoc","createHelperScript","COMMAND_STRUCTURE","createOptimizedSparcClaudeMd","getIsolatedNpxEnv","updateGitignore","createFullClaudeMd","createSparcClaudeMd","createMinimalClaudeMd","createFullMemoryBankMd","createMinimalMemoryBankMd","createFullCoordinationMd","createMinimalCoordinationMd","createAgentsReadme","createSessionsReadme","initializeHiveMind","getHiveMindStatus","rollbackHiveMindInit","isClaudeCodeInstalled","setupMcpServers","dryRun","console","log","servers","name","description","server","err","message","createStatuslineScript","initCommand","subArgs","flags","help","h","includes","generateEnvTemplate","workingDir","PWD","force","f","result","created","exists","hasVerificationFlags","verify","pair","flowNexusMinimalInit","basic","minimal","sparc","enhancedClaudeFlowInit","handleValidationCommand","handleRollbackCommand","handleListBackups","batchInitFlag","configFlag","config","handleBatchInit","useEnhanced","enhancedInitCommand","initForce","initMinimal","initSparc","roo","initDryRun","initOptimized","selectedModes","modes","split","initVerify","initPair","chdir","files","existingFiles","file","stat","push","length","join","templateOptions","optimized","createVerificationClaudeMd","createVerificationSettingsJson","writeFile","mkdir","recursive","validation","valid","revisedResults","verbose","copyResults","skipClaudeMd","skipSettings","copiedFiles","skippedFiles","errors","forEach","sparcInitialized","createSparcResult","modeCount","gitignoreResult","hiveMindOptions","integration","claudeCode","enabled","mcpTools","monitoring","hiveMindResult","error","skipMcp","parallel","s","m","maxConcurrency","progressTracking","template","environments","map","trim","validationErrors","configFile","results","projectsString","projects","project","successful","filter","r","failed","rollbackSystem","validationSystem","atomicOp","initOptions","skipPreValidation","skipBackup","validateOnly","preValidation","validatePreInit","warnings","warning","warn","backupResult","createPreInitBackup","atomicBegin","begin","performInitializationWithCheckpoints","postValidation","validatePostInit","rollback","configValidation","validateConfiguration","healthChecks","runHealthChecks","commit","fullValidation","postInit","skipPreInit","report","completed","rollbackError","skipConfig","skipModeTest","validationResults","exit","performFullRollback","phaseIndex","findIndex","arg","phase","performPartialRollback","rollbackPoints","listRollbackPoints","point","index","date","Date","timestamp","toLocaleString","type","latest","backupId","checkpoints","slice","checkpoint","status","phases","action","createInitialFiles","createDirectoryStructure","setupMemorySystem","setupCoordinationSystem","createCheckpoint","now","claudeMd","memoryBankMd","coordinationMd","directories","dir","initialData","agents","tasks","lastUpdated","JSON","stringify","setupMonitoring","path","trackingDir","tokenUsageFile","total","input","output","byAgent","toISOString","settingsPath","settingsContent","readFile","settings","parse","hooks","tokenTrackingHook","monitoringConfig","telemetry","value","tracking","tokens","costs","sessions","storage","location","format","rotation","configPath","envSnippet","envPath","d","agentType","agent","find","startsWith","initReasoning","chmod","os","filesToCheck","claudeDir","statuslineTemplate","__dirname","homeClaudeDir","homedir","settingsLocal","permissions","allow","deny","mcpConfig","mcpServers","category","commands","Object","entries","categoryDir","categoryReadme","charAt","toUpperCase","cmd","doc","helpers","helper","content","standardDirs","dbPath","dbExistedBefore","initializeReasoningBank","checkReasoningBankTables","migrateReasoningBank","CLAUDE_FLOW_DB_PATH","tableCheck","missingTables","migrationResult","addedTables","rbErr","FallbackMemoryStore","memoryStore","initialize","isUsingFallback","close","features","feature","rollbackRequired","agentResult","commandResult","skillResult","reasoningAgentsDir","fileURLToPath","dirname","default","__filename","url","sourceReasoningDir","reasoningFiles","readdir","copiedReasoningAgents","endsWith","sourcePath","destPath","enableMonitoring","hiveMindStatus","configured","database","rollbackResult","rollbackErr","createFlowNexusClaudeMd","flowNexusClaudeMd","sourceCommandsDir","commandFiles","copiedCommands","sourceAgentsDir","agentFiles","copiedAgents","stack"],"mappings":"AACA,SAASA,YAAY,EAAEC,UAAU,EAAEC,YAAY,QAAc,iBAAiB;AAC9E,SAASC,UAAU,QAAQ,KAAK;AAChC,OAAOC,aAAa,UAAU;AAE9B,SAASC,KAAK,EAAEC,QAAQ,QAAQ,gBAAgB;AAIhD,SAASC,WAAWC,OAAO,EAAEC,IAAI,EAAEC,UAAU,CAAC,CAAC;IAC7C,OAAO,IAAIC,QAAQ,CAACC,SAASC;QAC3B,MAAMC,QAAQT,MAAMG,SAASC,MAAM;YACjCM,KAAKL,QAAQK,GAAG;YAChBC,KAAK;gBAAE,GAAGZ,QAAQY,GAAG;gBAAE,GAAGN,QAAQM,GAAG;YAAC;YACtCC,OAAOP,QAAQQ,MAAM,KAAK,YAAY,YAAY;QACpD;QAEA,IAAIA,SAAS;QACb,IAAIC,SAAS;QAEb,IAAIT,QAAQQ,MAAM,KAAK,WAAW;YAChCJ,MAAMI,MAAM,CAACE,EAAE,CAAC,QAAQ,CAACC;gBAAWH,UAAUG;YAAM;YACpDP,MAAMK,MAAM,CAACC,EAAE,CAAC,QAAQ,CAACC;gBAAWF,UAAUE;YAAM;QACtD;QAEAP,MAAMM,EAAE,CAAC,SAAS,CAACE;YACjB,IAAIA,SAAS,GAAG;gBAC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