claude-flow 2.5.0-alpha.133 → 2.5.0-alpha.136

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.
@@ -109,6 +109,6 @@
109
109
  "includeCoAuthoredBy": true,
110
110
  "enabledMcpjsonServers": ["claude-flow", "ruv-swarm"],
111
111
  "statusLine": {
112
- "command": "/home/codespace/.claude/statusline-command.sh"
112
+ "command": "~/.claude/statusline-command.sh"
113
113
  }
114
114
  }
package/bin/claude-flow CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/bin/sh
2
2
  # Claude-Flow Smart Dispatcher - Detects and uses the best available runtime
3
3
 
4
- VERSION="2.5.0-alpha.133"
4
+ VERSION="2.5.0-alpha.136"
5
5
 
6
6
  # Determine the correct path based on how the script is invoked
7
7
  if [ -L "$0" ]; then
@@ -1,6 +1,7 @@
1
1
  import { printSuccess, printError, printWarning } from '../../utils.js';
2
2
  import { existsSync } from 'fs';
3
3
  import process from 'process';
4
+ import os from 'os';
4
5
  import { spawn, execSync } from 'child_process';
5
6
  function runCommand(command, args, options = {}) {
6
7
  return new Promise((resolve, reject)=>{
@@ -1049,9 +1050,15 @@ async function enhancedClaudeFlowInit(flags, subArgs = []) {
1049
1050
  if (!dryRun1) {
1050
1051
  await fs.writeFile(`${claudeDir}/statusline-command.sh`, statuslineTemplate, 'utf8');
1051
1052
  await fs.chmod(`${claudeDir}/statusline-command.sh`, 0o755);
1052
- printSuccess('✓ Created .claude/statusline-command.sh for enhanced Claude Code statusline');
1053
+ const homeClaudeDir = path.join(os.homedir(), '.claude');
1054
+ await fs.mkdir(homeClaudeDir, {
1055
+ recursive: true
1056
+ });
1057
+ await fs.writeFile(path.join(homeClaudeDir, 'statusline-command.sh'), statuslineTemplate, 'utf8');
1058
+ await fs.chmod(path.join(homeClaudeDir, 'statusline-command.sh'), 0o755);
1059
+ printSuccess('✓ Created statusline-command.sh in both .claude/ and ~/.claude/');
1053
1060
  } else {
1054
- console.log('[DRY RUN] Would create .claude/statusline-command.sh');
1061
+ console.log('[DRY RUN] Would create .claude/statusline-command.sh and ~/.claude/statusline-command.sh');
1055
1062
  }
1056
1063
  } catch (err) {
1057
1064
  if (!dryRun1) {
@@ -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 { 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 { 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 `#!/bin/bash\n\n# Claude Code Status Line with Claude-Flow Integration\n# Displays model, directory, git branch, and real-time swarm metrics\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\necho -ne \"\\\\033[1m$MODEL\\\\033[0m in \\\\033[36m$DIR\\\\033[0m\"\n[ -n \"$BRANCH\" ] && echo -ne \" on \\\\033[33m⎇ $BRANCH\\\\033[0m\"\n\n# Claude-Flow integration\nFLOW_DIR=\"$CWD/.claude-flow\"\n\nif [ -d \"$FLOW_DIR\" ]; then\n echo -ne \" │\"\n\n # 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 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 echo -ne \" \\\\033[35m$TOPO_ICON\\\\033[0m\"\n\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 echo -ne \" \\\\033[35m🤖 $AGENT_COUNT\\\\033[0m\"\n fi\n fi\n fi\n\n # Real-time System Metrics\n if [ -f \"$FLOW_DIR/metrics/system-metrics.json\" ]; then\n LATEST=$(jq -r '.[-1]' \"$FLOW_DIR/metrics/system-metrics.json\" 2>/dev/null)\n\n if [ -n \"$LATEST\" ] && [ \"$LATEST\" != \"null\" ]; then\n MEM_PERCENT=$(echo \"$LATEST\" | jq -r '.memoryUsagePercent // 0' | awk '{printf \"%.0f\", $1}')\n if [ -n \"$MEM_PERCENT\" ] && [ \"$MEM_PERCENT\" != \"null\" ]; then\n if [ \"$MEM_PERCENT\" -lt 60 ]; then\n MEM_COLOR=\"\\\\033[32m\"\n elif [ \"$MEM_PERCENT\" -lt 80 ]; then\n MEM_COLOR=\"\\\\033[33m\"\n else\n MEM_COLOR=\"\\\\033[31m\"\n fi\n echo -ne \" \\${MEM_COLOR}💾 \\${MEM_PERCENT}%\\\\033[0m\"\n fi\n\n CPU_LOAD=$(echo \"$LATEST\" | jq -r '.cpuLoad // 0' | awk '{printf \"%.0f\", $1 * 100}')\n if [ -n \"$CPU_LOAD\" ] && [ \"$CPU_LOAD\" != \"null\" ]; then\n if [ \"$CPU_LOAD\" -lt 50 ]; then\n CPU_COLOR=\"\\\\033[32m\"\n elif [ \"$CPU_LOAD\" -lt 75 ]; then\n CPU_COLOR=\"\\\\033[33m\"\n else\n CPU_COLOR=\"\\\\033[31m\"\n fi\n echo -ne \" \\${CPU_COLOR}⚙ \\${CPU_LOAD}%\\\\033[0m\"\n fi\n fi\n fi\n\n # Performance Metrics\n if [ -f \"$FLOW_DIR/metrics/task-metrics.json\" ]; then\n METRICS=$(jq -r '\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 (reverse | reduce .[] as $task (0; if $task.success == true then . + 1 else 0 end)) as $streak |\n { success_rate: $success_rate, avg_duration: $avg_duration, streak: $streak, total: $total } | @json\n ' \"$FLOW_DIR/metrics/task-metrics.json\" 2>/dev/null)\n\n if [ -n \"$METRICS\" ] && [ \"$METRICS\" != \"null\" ]; then\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 if [ \"$SUCCESS_RATE\" -gt 80 ]; then\n SUCCESS_COLOR=\"\\\\033[32m\"\n elif [ \"$SUCCESS_RATE\" -ge 60 ]; then\n SUCCESS_COLOR=\"\\\\033[33m\"\n else\n SUCCESS_COLOR=\"\\\\033[31m\"\n fi\n echo -ne \" \\${SUCCESS_COLOR}🎯 \\${SUCCESS_RATE}%\\\\033[0m\"\n fi\n\n AVG_TIME=$(echo \"$METRICS\" | jq -r '.avg_duration // 0')\n if [ -n \"$AVG_TIME\" ] && [ \"$TOTAL_TASKS\" -gt 0 ]; then\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 echo -ne \" \\\\033[36m⏱️ $TIME_STR\\\\033[0m\"\n fi\n\n STREAK=$(echo \"$METRICS\" | jq -r '.streak // 0')\n if [ -n \"$STREAK\" ] && [ \"$STREAK\" -gt 0 ]; then\n echo -ne \" \\\\033[91m🔥 $STREAK\\\\033[0m\"\n fi\n fi\n fi\n\n # Active Tasks\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 echo -ne \" \\\\033[36m📋 $TASK_COUNT\\\\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 // 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 // Store parameters to avoid scope issues in async context\n const args = subArgs || [];\n const options = flags || {};\n\n // Import fs module for Node.js\n const fs = await import('fs/promises');\n const { chmod } = fs;\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 await fs.writeFile(`${claudeDir}/statusline-command.sh`, statuslineTemplate, 'utf8');\n await fs.chmod(`${claudeDir}/statusline-command.sh`, 0o755);\n printSuccess('✓ Created .claude/statusline-command.sh for enhanced Claude Code statusline');\n } else {\n console.log('[DRY RUN] Would create .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 }\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 // 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\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 console.log('✅ ✓ Agent system setup complete with 64 specialized agents');\n } else {\n console.log('⚠️ Agent system setup failed:', agentResult.error);\n }\n } else {\n console.log(' [DRY RUN] Would create agent system with 64 specialized agents');\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","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","hasVerificationFlags","verify","pair","flowNexusMinimalInit","basic","minimal","sparc","enhancedClaudeFlowInit","handleValidationCommand","handleRollbackCommand","handleListBackups","batchInitFlag","configFlag","config","handleBatchInit","useEnhanced","enhancedInitCommand","initForce","force","initMinimal","initSparc","roo","initDryRun","initOptimized","selectedModes","modes","split","initVerify","initPair","workingDir","PWD","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","f","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","result","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","chmod","filesToCheck","claudeDir","statuslineTemplate","__dirname","settingsLocal","permissions","allow","deny","mcpConfig","mcpServers","category","commands","Object","entries","categoryDir","categoryReadme","charAt","toUpperCase","cmd","doc","helpers","helper","content","standardDirs","FallbackMemoryStore","memoryStore","initialize","isUsingFallback","close","features","feature","rollbackRequired","agentResult","commandResult","enableMonitoring","hiveMindStatus","configured","database","rollbackResult","rollbackErr","createFlowNexusClaudeMd","flowNexusClaudeMd","fileURLToPath","dirname","__filename","url","sourceCommandsDir","commandFiles","readdir","copiedCommands","endsWith","sourcePath","destPath","sourceAgentsDir","agentFiles","copiedAgents","stack"],"mappings":"AACA,SAASA,YAAY,EAAEC,UAAU,EAAEC,YAAY,QAAc,iBAAiB;AAC9E,SAASC,UAAU,QAAQ,KAAK;AAChC,OAAOC,aAAa,UAAU;AAC9B,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;gB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AAQC,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,IAAIuQ,KAAK;QACrC7U,QAAQ2M,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 { 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 `#!/bin/bash\n\n# Claude Code Status Line with Claude-Flow Integration\n# Displays model, directory, git branch, and real-time swarm metrics\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\necho -ne \"\\\\033[1m$MODEL\\\\033[0m in \\\\033[36m$DIR\\\\033[0m\"\n[ -n \"$BRANCH\" ] && echo -ne \" on \\\\033[33m⎇ $BRANCH\\\\033[0m\"\n\n# Claude-Flow integration\nFLOW_DIR=\"$CWD/.claude-flow\"\n\nif [ -d \"$FLOW_DIR\" ]; then\n echo -ne \" │\"\n\n # 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 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 echo -ne \" \\\\033[35m$TOPO_ICON\\\\033[0m\"\n\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 echo -ne \" \\\\033[35m🤖 $AGENT_COUNT\\\\033[0m\"\n fi\n fi\n fi\n\n # Real-time System Metrics\n if [ -f \"$FLOW_DIR/metrics/system-metrics.json\" ]; then\n LATEST=$(jq -r '.[-1]' \"$FLOW_DIR/metrics/system-metrics.json\" 2>/dev/null)\n\n if [ -n \"$LATEST\" ] && [ \"$LATEST\" != \"null\" ]; then\n MEM_PERCENT=$(echo \"$LATEST\" | jq -r '.memoryUsagePercent // 0' | awk '{printf \"%.0f\", $1}')\n if [ -n \"$MEM_PERCENT\" ] && [ \"$MEM_PERCENT\" != \"null\" ]; then\n if [ \"$MEM_PERCENT\" -lt 60 ]; then\n MEM_COLOR=\"\\\\033[32m\"\n elif [ \"$MEM_PERCENT\" -lt 80 ]; then\n MEM_COLOR=\"\\\\033[33m\"\n else\n MEM_COLOR=\"\\\\033[31m\"\n fi\n echo -ne \" \\${MEM_COLOR}💾 \\${MEM_PERCENT}%\\\\033[0m\"\n fi\n\n CPU_LOAD=$(echo \"$LATEST\" | jq -r '.cpuLoad // 0' | awk '{printf \"%.0f\", $1 * 100}')\n if [ -n \"$CPU_LOAD\" ] && [ \"$CPU_LOAD\" != \"null\" ]; then\n if [ \"$CPU_LOAD\" -lt 50 ]; then\n CPU_COLOR=\"\\\\033[32m\"\n elif [ \"$CPU_LOAD\" -lt 75 ]; then\n CPU_COLOR=\"\\\\033[33m\"\n else\n CPU_COLOR=\"\\\\033[31m\"\n fi\n echo -ne \" \\${CPU_COLOR}⚙ \\${CPU_LOAD}%\\\\033[0m\"\n fi\n fi\n fi\n\n # Performance Metrics\n if [ -f \"$FLOW_DIR/metrics/task-metrics.json\" ]; then\n METRICS=$(jq -r '\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 (reverse | reduce .[] as $task (0; if $task.success == true then . + 1 else 0 end)) as $streak |\n { success_rate: $success_rate, avg_duration: $avg_duration, streak: $streak, total: $total } | @json\n ' \"$FLOW_DIR/metrics/task-metrics.json\" 2>/dev/null)\n\n if [ -n \"$METRICS\" ] && [ \"$METRICS\" != \"null\" ]; then\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 if [ \"$SUCCESS_RATE\" -gt 80 ]; then\n SUCCESS_COLOR=\"\\\\033[32m\"\n elif [ \"$SUCCESS_RATE\" -ge 60 ]; then\n SUCCESS_COLOR=\"\\\\033[33m\"\n else\n SUCCESS_COLOR=\"\\\\033[31m\"\n fi\n echo -ne \" \\${SUCCESS_COLOR}🎯 \\${SUCCESS_RATE}%\\\\033[0m\"\n fi\n\n AVG_TIME=$(echo \"$METRICS\" | jq -r '.avg_duration // 0')\n if [ -n \"$AVG_TIME\" ] && [ \"$TOTAL_TASKS\" -gt 0 ]; then\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 echo -ne \" \\\\033[36m⏱️ $TIME_STR\\\\033[0m\"\n fi\n\n STREAK=$(echo \"$METRICS\" | jq -r '.streak // 0')\n if [ -n \"$STREAK\" ] && [ \"$STREAK\" -gt 0 ]; then\n echo -ne \" \\\\033[91m🔥 $STREAK\\\\033[0m\"\n fi\n fi\n fi\n\n # Active Tasks\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 echo -ne \" \\\\033[36m📋 $TASK_COUNT\\\\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 // 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 // Store parameters to avoid scope issues in async context\n const args = subArgs || [];\n const options = flags || {};\n\n // Import fs module for Node.js\n const fs = await import('fs/promises');\n const { chmod } = fs;\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 }\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 // 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\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 console.log('✅ ✓ Agent system setup complete with 64 specialized agents');\n } else {\n console.log('⚠️ Agent system setup failed:', agentResult.error);\n }\n } else {\n console.log(' [DRY RUN] Would create agent system with 64 specialized agents');\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","os","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","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","hasVerificationFlags","verify","pair","flowNexusMinimalInit","basic","minimal","sparc","enhancedClaudeFlowInit","handleValidationCommand","handleRollbackCommand","handleListBackups","batchInitFlag","configFlag","config","handleBatchInit","useEnhanced","enhancedInitCommand","initForce","force","initMinimal","initSparc","roo","initDryRun","initOptimized","selectedModes","modes","split","initVerify","initPair","workingDir","PWD","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","f","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","result","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","chmod","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","FallbackMemoryStore","memoryStore","initialize","isUsingFallback","close","features","feature","rollbackRequired","agentResult","commandResult","enableMonitoring","hiveMindStatus","configured","database","rollbackResult","rollbackErr","createFlowNexusClaudeMd","flowNexusClaudeMd","fileURLToPath","dirname","__filename","url","sourceCommandsDir","commandFiles","readdir","copiedCommands","endsWith","sourcePath","destPath","sourceAgentsDir","agentFiles","copiedAgents","stack"],"mappings":"AACA,SAASA,YAAY,EAAEC,UAAU,EAAEC,YAAY,QAAc,iBAAiB;AAC9E,SAASC,UAAU,QAAQ,KAAK;AAChC,OAAOC,aAAa,UAAU;AAC9B,OAAOC,QAAQ,KAAK;AACpB,SAASC,KAAK,EAAEC,QAAQ,QAA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