claude-flow 2.5.0-alpha.131 → 2.5.0-alpha.132

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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.131"
4
+ VERSION="2.5.0-alpha.132"
5
5
 
6
6
  # Determine the correct path based on how the script is invoked
7
7
  if [ -L "$0" ]; then
@@ -85,4 +85,9 @@ export class HelpFormatter {
85
85
  }
86
86
  }
87
87
 
88
+ //# sourceMappingURL=help-formatter.js.map/\s+/g, ' ');
89
+ return text;
90
+ }
91
+ }
92
+
88
93
  //# sourceMappingURL=help-formatter.js.map
@@ -85,6 +85,11 @@ async function setupMcpServers(dryRun1 = false) {
85
85
  name: 'flow-nexus',
86
86
  command: 'npx flow-nexus@latest mcp start',
87
87
  description: 'Flow Nexus Complete MCP server for advanced AI orchestration'
88
+ },
89
+ {
90
+ name: 'agentic-payments',
91
+ command: 'npx agentic-payments@latest mcp',
92
+ description: 'Agentic Payments MCP server for autonomous agent payment authorization'
88
93
  }
89
94
  ];
90
95
  for (const server of servers){
@@ -413,6 +418,7 @@ export async function initCommand(subArgs, flags) {
413
418
  console.log(' claude mcp add claude-flow npx claude-flow@alpha mcp start');
414
419
  console.log(' claude mcp add ruv-swarm npx ruv-swarm mcp start');
415
420
  console.log(' claude mcp add flow-nexus npx flow-nexus@latest mcp start');
421
+ console.log(' claude mcp add agentic-payments npx agentic-payments@latest mcp');
416
422
  }
417
423
  }
418
424
  } catch (err) {
@@ -940,6 +946,14 @@ async function enhancedClaudeFlowInit(flags, subArgs = []) {
940
946
  'start'
941
947
  ],
942
948
  type: 'stdio'
949
+ },
950
+ 'agentic-payments': {
951
+ command: 'npx',
952
+ args: [
953
+ 'agentic-payments@latest',
954
+ 'mcp'
955
+ ],
956
+ type: 'stdio'
943
957
  }
944
958
  }
945
959
  };
@@ -1121,6 +1135,7 @@ ${commands.map((cmd)=>`- [${cmd}](./${cmd}.md)`).join('\n')}
1121
1135
  console.log(' claude mcp add claude-flow npx claude-flow@alpha mcp start');
1122
1136
  console.log(' claude mcp add ruv-swarm npx ruv-swarm@latest mcp start');
1123
1137
  console.log(' claude mcp add flow-nexus npx flow-nexus@latest mcp start');
1138
+ console.log(' claude mcp add agentic-payments npx agentic-payments@latest mcp');
1124
1139
  console.log('\n šŸ’” MCP servers are defined in .mcp.json (project scope)');
1125
1140
  }
1126
1141
  } else if (!dryRun1 && !isClaudeCodeInstalled()) {
@@ -1131,6 +1146,7 @@ ${commands.map((cmd)=>`- [${cmd}](./${cmd}.md)`).join('\n')}
1131
1146
  console.log(' claude mcp add claude-flow@alpha npx claude-flow@alpha mcp start');
1132
1147
  console.log(' claude mcp add ruv-swarm npx ruv-swarm@latest mcp start');
1133
1148
  console.log(' claude mcp add flow-nexus npx flow-nexus@latest mcp start');
1149
+ console.log(' claude mcp add agentic-payments npx agentic-payments@latest mcp');
1134
1150
  console.log('\n šŸ’” MCP servers are defined in .mcp.json (project scope)');
1135
1151
  }
1136
1152
  console.log('\nšŸ¤– Setting up agent system...');
@@ -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\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\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 }\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 // Create settings.local.json with default MCP permissions\n const settingsLocal = {\n permissions: {\n allow: ['mcp__ruv-swarm', 'mcp__claude-flow@alpha', 'mcp__flow-nexus'],\n deny: [],\n },\n };\n\n if (!dryRun) {\n await fs.writeFile(\n `${claudeDir}/settings.local.json`, JSON.stringify(settingsLocal, null, 2, 'utf8'),\n );\n printSuccess('āœ“ Created .claude/settings.local.json with default MCP permissions');\n } else {\n console.log(\n '[DRY RUN] Would create .claude/settings.local.json with default MCP permissions',\n );\n }\n\n // Create .mcp.json at project root for MCP server configuration\n const mcpConfig = {\n mcpServers: {\n 'claude-flow@alpha': {\n command: 'npx',\n args: ['claude-flow@alpha', 'mcp', 'start'],\n type: 'stdio',\n },\n 'ruv-swarm': {\n command: 'npx',\n args: ['ruv-swarm@latest', 'mcp', 'start'],\n type: 'stdio',\n },\n 'flow-nexus': {\n command: 'npx',\n args: ['flow-nexus@latest', 'mcp', 'start'],\n type: 'stdio',\n },\n },\n };\n\n if (!dryRun) {\n await fs.writeFile(`${workingDir}/.mcp.json`, JSON.stringify(mcpConfig, null, 2, 'utf8'));\n printSuccess('āœ“ Created .mcp.json at project root for MCP server configuration');\n } else {\n console.log('[DRY RUN] Would create .mcp.json at project root for MCP server configuration');\n }\n\n // Removed claude-flow@alpha.config.json creation per user request\n\n // Create command documentation\n for (const [category, commands] of Object.entries(COMMAND_STRUCTURE)) {\n const categoryDir = `${claudeDir}/commands/${category}`;\n\n if (!dryRun) {\n await fs.mkdir(categoryDir, { recursive: true });\n\n // Create category README\n const categoryReadme = `# ${category.charAt(0).toUpperCase() + category.slice(1)} Commands\n\nCommands for ${category} operations in Claude Flow.\n\n## Available Commands\n\n${commands.map((cmd) => `- [${cmd}](./${cmd}.md)`).join('\\n')}\n`;\n await fs.writeFile(`${categoryDir}/README.md`, categoryReadme, 'utf8');\n\n // Create individual command docs\n for (const command of commands) {\n const doc = createCommandDoc(category, command);\n if (doc) {\n await fs.writeFile(`${categoryDir}/${command}.md`, doc, 'utf8');\n }\n }\n\n console.log(` āœ“ Created ${commands.length} ${category} command docs`);\n } else {\n console.log(`[DRY RUN] Would create ${commands.length} ${category} command docs`);\n }\n }\n\n // Create wrapper scripts using the dedicated function\n if (!dryRun) {\n await createLocalExecutable(workingDir, dryRun);\n } else {\n console.log('[DRY RUN] Would create wrapper scripts');\n }\n\n // Create helper scripts\n const helpers = ['setup-mcp.sh', 'quick-start.sh', 'github-setup.sh', 'github-safe.js', 'standard-checkpoint-hooks.sh', 'checkpoint-manager.sh'];\n for (const helper of helpers) {\n if (!dryRun) {\n const content = createHelperScript(helper);\n if (content) {\n await fs.writeFile(`${claudeDir}/helpers/${helper}`, content, 'utf8');\n await fs.chmod(`${claudeDir}/helpers/${helper}`, 0o755);\n }\n }\n }\n\n if (!dryRun) {\n printSuccess(`āœ“ Created ${helpers.length} helper scripts`);\n } else {\n console.log(`[DRY RUN] Would create ${helpers.length} helper scripts`);\n }\n\n // Create standard directories from original init\n const standardDirs = [\n 'memory',\n 'memory/agents',\n 'memory/sessions',\n 'coordination',\n 'coordination/memory_bank',\n 'coordination/subtasks',\n 'coordination/orchestration',\n '.swarm', // Add .swarm directory for shared memory\n '.hive-mind', // Add .hive-mind directory for hive-mind system\n '.claude/checkpoints', // Add checkpoints directory for Git checkpoint system\n ];\n\n for (const dir of standardDirs) {\n if (!dryRun) {\n await fs.mkdir(`${workingDir}/${dir}`, { recursive: true });\n }\n }\n\n if (!dryRun) {\n printSuccess('āœ“ Created standard directory structure');\n\n // Initialize memory system\n const initialData = { agents: [], tasks: [], lastUpdated: Date.now() };\n await fs.writeFile(\n `${workingDir}/memory/claude-flow@alpha-data.json`, JSON.stringify(initialData, null, 2, 'utf8'),\n );\n\n // Create README files\n await fs.writeFile(`${workingDir}/memory/agents/README.md`, createAgentsReadme(), 'utf8');\n await fs.writeFile(`${workingDir}/memory/sessions/README.md`, createSessionsReadme(), 'utf8');\n\n printSuccess('āœ“ Initialized memory system');\n\n // Initialize memory database with fallback support\n try {\n // 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('\\n šŸ’” MCP servers are defined in .mcp.json (project scope)');\n }\n } else if (!dryRun && !isClaudeCodeInstalled()) {\n console.log('\\nāš ļø Claude Code CLI not detected!');\n console.log('\\n šŸ“„ To install Claude Code:');\n console.log(' npm install -g @anthropic-ai/claude-code');\n console.log('\\n šŸ“‹ After installing, add MCP servers:');\n console.log(' claude mcp add claude-flow@alpha npx claude-flow@alpha mcp start');\n console.log(' claude mcp add ruv-swarm npx ruv-swarm@latest mcp start');\n console.log(' claude mcp add flow-nexus npx flow-nexus@latest mcp start');\n console.log('\\n šŸ’” MCP servers are defined in .mcp.json (project scope)');\n }\n\n // Create agent directories and copy all agent files\n console.log('\\nšŸ¤– Setting up agent system...');\n if (!dryRun) {\n await createAgentDirectories(workingDir, dryRun);\n const agentResult = await copyAgentFiles(workingDir, {\n force: force,\n dryRun: dryRun\n });\n \n if (agentResult.success) {\n await validateAgentSystem(workingDir);\n \n // Copy command files including Flow Nexus commands\n console.log('\\nšŸ“š Setting up command system...');\n const commandResult = await copyCommandFiles(workingDir, {\n force: force,\n dryRun: dryRun\n });\n \n if (commandResult.success) {\n console.log('āœ… āœ“ Command system setup complete with Flow Nexus integration');\n } else {\n console.log('āš ļø Command system setup failed:', commandResult.error);\n }\n \n 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","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","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","__dirname","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,EA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AGqO,QAAQ,CAACuE,YAAY;oBAC9C,MAAM5S,GAAG+F,SAAS,CAAC8M,UAAU/B;oBAC7BkC;gBACF;YACF;YAEA1Q,QAAQC,GAAG,CAAC,CAAC,WAAW,EAAEyQ,aAAa,uBAAuB,CAAC;QACjE,EAAE,OAAOpQ,KAAK;YACZN,QAAQC,GAAG,CAAC,2CAA2CK,IAAIC,OAAO;QACpE;QAEAP,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC;QACZD,QAAQC,GAAG,CAAC;IAEd,EAAE,OAAOK,KAAK;QACZN,QAAQC,GAAG,CAAC,CAAC,oCAAoC,EAAEK,IAAIC,OAAO,EAAE;QAChEP,QAAQC,GAAG,CAAC,gBAAgBK,IAAIqQ,KAAK;QACrC3U,QAAQ0M,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 { 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\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 // 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","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","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","__dirname","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,OAA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agentic-payments', {
155
+ name: 'agentic-payments',
156
+ server: 'npx agentic-payments@latest mcp',
157
+ functions: [
158
+ {
159
+ name: 'create_active_mandate',
160
+ description: 'Create Active Mandate for autonomous payment authorization',
161
+ parameters: {
162
+ agent: 'string',
163
+ holder: 'string',
164
+ amount: 'number',
165
+ currency: 'string',
166
+ period: 'string',
167
+ kind: 'string'
168
+ },
169
+ required: [
170
+ 'agent',
171
+ 'holder',
172
+ 'amount',
173
+ 'currency',
174
+ 'period',
175
+ 'kind'
176
+ ]
177
+ },
178
+ {
179
+ name: 'sign_mandate',
180
+ description: 'Sign mandate with Ed25519 cryptographic proof',
181
+ parameters: {
182
+ mandate: 'object',
183
+ private_key: 'string'
184
+ },
185
+ required: [
186
+ 'mandate',
187
+ 'private_key'
188
+ ]
189
+ },
190
+ {
191
+ name: 'verify_mandate',
192
+ description: 'Verify mandate signature and execution guards',
193
+ parameters: {
194
+ signed_mandate: 'object',
195
+ check_guards: 'boolean'
196
+ },
197
+ required: [
198
+ 'signed_mandate'
199
+ ]
200
+ },
201
+ {
202
+ name: 'revoke_mandate',
203
+ description: 'Revoke mandate by ID',
204
+ parameters: {
205
+ mandate_id: 'string',
206
+ reason: 'string'
207
+ },
208
+ required: [
209
+ 'mandate_id'
210
+ ]
211
+ },
212
+ {
213
+ name: 'generate_agent_identity',
214
+ description: 'Generate Ed25519 keypair for agent',
215
+ parameters: {
216
+ include_private_key: 'boolean'
217
+ },
218
+ required: []
219
+ },
220
+ {
221
+ name: 'create_intent_mandate',
222
+ description: 'Create intent-based payment mandate',
223
+ parameters: {
224
+ merchant_id: 'string',
225
+ customer_id: 'string',
226
+ intent: 'string',
227
+ max_amount: 'number'
228
+ },
229
+ required: [
230
+ 'merchant_id',
231
+ 'customer_id',
232
+ 'intent',
233
+ 'max_amount'
234
+ ]
235
+ },
236
+ {
237
+ name: 'create_cart_mandate',
238
+ description: 'Create cart-based payment mandate',
239
+ parameters: {
240
+ merchant_id: 'string',
241
+ customer_id: 'string',
242
+ items: 'array'
243
+ },
244
+ required: [
245
+ 'merchant_id',
246
+ 'customer_id',
247
+ 'items'
248
+ ]
249
+ }
250
+ ],
251
+ status: 'disconnected'
252
+ });
154
253
  }
155
254
  async discoverTools() {
156
255
  for (const [name, tool] of this.tools){
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/core/MCPIntegrator.ts"],"sourcesContent":["/**\n * MCPIntegrator - Manages MCP tool coordination\n * Provides integration with external MCP tools and orchestration services\n */\n\nexport interface MCPTool {\n name: string;\n server: string;\n functions: MCPFunction[];\n status: 'connected' | 'disconnected' | 'error';\n lastPing?: Date;\n}\n\nexport interface MCPFunction {\n name: string;\n description: string;\n parameters: any;\n required: string[];\n}\n\nexport interface MCPCommand {\n tool: string;\n function: string;\n parameters: any;\n timeout?: number;\n}\n\nexport interface MCPResult {\n success: boolean;\n data?: any;\n error?: string;\n metadata?: {\n executionTime: number;\n tool: string;\n function: string;\n };\n}\n\nexport class MCPIntegrator {\n private tools: Map<string, MCPTool> = new Map();\n private initialized: boolean = false;\n\n constructor() {\n this.registerDefaultTools();\n }\n\n /**\n * Initialize MCP integrator and discover available tools\n */\n async initialize(): Promise<void> {\n await this.discoverTools();\n await this.testConnections();\n this.initialized = true;\n }\n\n /**\n * Register default MCP tools\n */\n private registerDefaultTools(): void {\n // Claude Flow MCP tools\n this.tools.set('claude-flow', {\n name: 'claude-flow',\n server: 'npx claude-flow@alpha mcp start',\n functions: [\n {\n name: 'swarm_init',\n description: 'Initialize swarm with topology',\n parameters: { topology: 'string', maxAgents: 'number', strategy: 'string' },\n required: ['topology']\n },\n {\n name: 'agent_spawn',\n description: 'Spawn specialized agents',\n parameters: { type: 'string', capabilities: 'array', name: 'string' },\n required: ['type']\n },\n {\n name: 'task_orchestrate',\n description: 'Orchestrate complex tasks',\n parameters: { task: 'string', strategy: 'string', priority: 'string' },\n required: ['task']\n },\n {\n name: 'memory_usage',\n description: 'Manage coordination memory',\n parameters: { action: 'string', key: 'string', value: 'string', namespace: 'string' },\n required: ['action']\n },\n {\n name: 'swarm_status',\n description: 'Get swarm status and metrics',\n parameters: { detailed: 'boolean' },\n required: []\n }\n ],\n status: 'disconnected'\n });\n\n // ruv-swarm MCP tools (optional)\n this.tools.set('ruv-swarm', {\n name: 'ruv-swarm',\n server: 'npx ruv-swarm mcp start',\n functions: [\n {\n name: 'swarm_init',\n description: 'Initialize RUV swarm',\n parameters: { topology: 'string', maxAgents: 'number', strategy: 'string' },\n required: ['topology']\n },\n {\n name: 'neural_status',\n description: 'Get neural network status',\n parameters: { agentId: 'string' },\n required: []\n },\n {\n name: 'benchmark_run',\n description: 'Run performance benchmarks',\n parameters: { type: 'string', iterations: 'number' },\n required: []\n }\n ],\n status: 'disconnected'\n });\n\n // Flow Nexus MCP tools (optional)\n this.tools.set('flow-nexus', {\n name: 'flow-nexus',\n server: 'npx flow-nexus@latest mcp start',\n functions: [\n {\n name: 'swarm_init',\n description: 'Initialize Flow Nexus swarm',\n parameters: { topology: 'string', maxAgents: 'number', strategy: 'string' },\n required: ['topology']\n },\n {\n name: 'sandbox_create',\n description: 'Create execution sandbox',\n parameters: { template: 'string', env_vars: 'object' },\n required: ['template']\n },\n {\n name: 'neural_train',\n description: 'Train neural networks',\n parameters: { config: 'object', tier: 'string' },\n required: ['config']\n }\n ],\n status: 'disconnected'\n });\n }\n\n /**\n * Discover available MCP tools\n */\n private async discoverTools(): Promise<void> {\n // In a real implementation, this would probe for available MCP servers\n // For now, we'll simulate the discovery process\n\n for (const [name, tool] of this.tools) {\n try {\n // Simulate tool discovery\n const isAvailable = await this.checkToolAvailability(name);\n tool.status = isAvailable ? 'connected' : 'disconnected';\n tool.lastPing = new Date();\n } catch (error) {\n tool.status = 'error';\n console.warn(`Failed to discover MCP tool ${name}:`, error);\n }\n }\n }\n\n /**\n * Check if a specific tool is available\n */\n private async checkToolAvailability(toolName: string): Promise<boolean> {\n // Simulate availability check\n // In real implementation, this would try to connect to the MCP server\n return Math.random() > 0.3; // 70% availability simulation\n }\n\n /**\n * Test connections to all tools\n */\n private async testConnections(): Promise<void> {\n for (const [name, tool] of this.tools) {\n if (tool.status === 'connected') {\n try {\n // Simulate connection test\n await new Promise(resolve => setTimeout(resolve, 100));\n console.log(`āœ“ MCP tool ${name} connected successfully`);\n } catch (error) {\n tool.status = 'error';\n console.warn(`āœ— MCP tool ${name} connection failed:`, error);\n }\n }\n }\n }\n\n /**\n * Execute MCP command\n */\n async executeCommand(command: MCPCommand): Promise<MCPResult> {\n const startTime = Date.now();\n\n try {\n const tool = this.tools.get(command.tool);\n if (!tool) {\n return {\n success: false,\n error: `Unknown MCP tool: ${command.tool}`,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n\n if (tool.status !== 'connected') {\n return {\n success: false,\n error: `MCP tool ${command.tool} is not connected (status: ${tool.status})`,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n\n // Validate function exists\n const func = tool.functions.find(f => f.name === command.function);\n if (!func) {\n return {\n success: false,\n error: `Function ${command.function} not found in tool ${command.tool}`,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n\n // Validate required parameters\n const missingParams = func.required.filter(param => !(param in command.parameters));\n if (missingParams.length > 0) {\n return {\n success: false,\n error: `Missing required parameters: ${missingParams.join(', ')}`,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n\n // Execute the command (simulation)\n const result = await this.simulateCommandExecution(command);\n\n return {\n success: true,\n data: result,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n }\n\n /**\n * Simulate command execution (replace with real MCP calls in production)\n */\n private async simulateCommandExecution(command: MCPCommand): Promise<any> {\n // Simulate processing time\n await new Promise(resolve => setTimeout(resolve, 200 + Math.random() * 800));\n\n // Return different results based on function\n switch (command.function) {\n case 'swarm_init':\n return {\n swarmId: `swarm-${Date.now()}`,\n topology: command.parameters.topology,\n maxAgents: command.parameters.maxAgents || 8,\n status: 'initialized'\n };\n\n case 'agent_spawn':\n return {\n agentId: `agent-${Date.now()}`,\n type: command.parameters.type,\n capabilities: command.parameters.capabilities || [],\n status: 'spawned'\n };\n\n case 'task_orchestrate':\n return {\n taskId: `task-${Date.now()}`,\n task: command.parameters.task,\n strategy: command.parameters.strategy || 'adaptive',\n status: 'orchestrating'\n };\n\n case 'memory_usage':\n if (command.parameters.action === 'store') {\n return { stored: true, key: command.parameters.key };\n } else if (command.parameters.action === 'retrieve') {\n return { found: Math.random() > 0.3, value: 'simulated-value' };\n }\n return { action: command.parameters.action, success: true };\n\n case 'swarm_status':\n return {\n activeAgents: Math.floor(Math.random() * 8) + 1,\n topology: 'mesh',\n health: 'good',\n metrics: {\n throughput: Math.random() * 100,\n latency: Math.random() * 50 + 10\n }\n };\n\n case 'neural_status':\n return {\n modelLoaded: true,\n accuracy: 0.85 + Math.random() * 0.1,\n trainingProgress: Math.random() * 100\n };\n\n case 'benchmark_run':\n return {\n benchmarks: [\n { name: 'cpu', value: Math.random() * 100, unit: 'ms' },\n { name: 'memory', value: Math.random() * 512, unit: 'MB' },\n { name: 'network', value: Math.random() * 50, unit: 'ms' }\n ]\n };\n\n default:\n return { function: command.function, executed: true };\n }\n }\n\n /**\n * Get available tools\n */\n getAvailableTools(): MCPTool[] {\n return Array.from(this.tools.values());\n }\n\n /**\n * Get connected tools\n */\n getConnectedTools(): MCPTool[] {\n return Array.from(this.tools.values()).filter(tool => tool.status === 'connected');\n }\n\n /**\n * Get tool by name\n */\n getTool(name: string): MCPTool | undefined {\n return this.tools.get(name);\n }\n\n /**\n * Check if a tool is available\n */\n isToolAvailable(name: string): boolean {\n const tool = this.tools.get(name);\n return tool?.status === 'connected' || false;\n }\n\n /**\n * Get tool functions\n */\n getToolFunctions(toolName: string): MCPFunction[] {\n const tool = this.tools.get(toolName);\n return tool?.functions || [];\n }\n\n /**\n * Initialize swarm coordination using MCP tools\n */\n async initializeSwarmCoordination(config: {\n topology: string;\n maxAgents: number;\n strategy: string;\n }): Promise<MCPResult> {\n // Try claude-flow first, then fallback to other tools\n const toolPriority = ['claude-flow', 'ruv-swarm', 'flow-nexus'];\n\n for (const toolName of toolPriority) {\n if (this.isToolAvailable(toolName)) {\n return await this.executeCommand({\n tool: toolName,\n function: 'swarm_init',\n parameters: config\n });\n }\n }\n\n return {\n success: false,\n error: 'No MCP tools available for swarm initialization',\n metadata: {\n executionTime: 0,\n tool: 'none',\n function: 'swarm_init'\n }\n };\n }\n\n /**\n * Coordinate memory across swarm using MCP tools\n */\n async coordinateMemory(action: string, key: string, value?: string, namespace?: string): Promise<MCPResult> {\n const command: MCPCommand = {\n tool: 'claude-flow',\n function: 'memory_usage',\n parameters: { action, key, value, namespace: namespace || 'coordination' }\n };\n\n return await this.executeCommand(command);\n }\n\n /**\n * Spawn agents using MCP tools\n */\n async spawnAgent(type: string, capabilities?: string[], name?: string): Promise<MCPResult> {\n const command: MCPCommand = {\n tool: 'claude-flow',\n function: 'agent_spawn',\n parameters: { type, capabilities, name }\n };\n\n return await this.executeCommand(command);\n }\n\n /**\n * Orchestrate tasks using MCP tools\n */\n async orchestrateTask(task: string, strategy?: string, priority?: string): Promise<MCPResult> {\n const command: MCPCommand = {\n tool: 'claude-flow',\n function: 'task_orchestrate',\n parameters: { task, strategy, priority }\n };\n\n return await this.executeCommand(command);\n }\n\n /**\n * Get swarm status using MCP tools\n */\n async getSwarmStatus(detailed: boolean = false): Promise<MCPResult> {\n const command: MCPCommand = {\n tool: 'claude-flow',\n function: 'swarm_status',\n parameters: { detailed }\n };\n\n return await this.executeCommand(command);\n }\n\n /**\n * Refresh tool connections\n */\n async refreshConnections(): Promise<void> {\n await this.discoverTools();\n await this.testConnections();\n }\n\n /**\n * Register a custom tool\n */\n registerTool(tool: MCPTool): void {\n this.tools.set(tool.name, tool);\n }\n\n /**\n * Unregister a tool\n */\n unregisterTool(name: string): boolean {\n return this.tools.delete(name);\n }\n\n /**\n * Get integration status\n */\n getIntegrationStatus(): {\n initialized: boolean;\n totalTools: number;\n connectedTools: number;\n availableFunctions: number;\n } {\n const tools = Array.from(this.tools.values());\n const connectedTools = tools.filter(tool => tool.status === 'connected');\n const availableFunctions = connectedTools.reduce((sum, tool) => sum + tool.functions.length, 0);\n\n return {\n initialized: this.initialized,\n totalTools: tools.length,\n connectedTools: connectedTools.length,\n availableFunctions\n };\n }\n}"],"names":["MCPIntegrator","tools","Map","initialized","registerDefaultTools","initialize","discoverTools","testConnections","set","name","server","functions","description","parameters","topology","maxAgents","strategy","required","type","capabilities","task","priority","action","key","value","namespace","detailed","status","agentId","iterations","template","env_vars","config","tier","tool","isAvailable","checkToolAvailability","lastPing","Date","error","console","warn","toolName","Math","random","Promise","resolve","setTimeout","log","executeCommand","command","startTime","now","get","success","metadata","executionTime","function","func","find","f","missingParams","filter","param","length","join","result","simulateCommandExecution","data","Error","message","String","swarmId","taskId","stored","found","activeAgents","floor","health","metrics","throughput","latency","modelLoaded","accuracy","trainingProgress","benchmarks","unit","executed","getAvailableTools","Array","from","values","getConnectedTools","getTool","isToolAvailable","getToolFunctions","initializeSwarmCoordination","toolPriority","coordinateMemory","spawnAgent","orchestrateTask","getSwarmStatus","refreshConnections","registerTool","unregisterTool","delete","getIntegrationStatus","connectedTools","availableFunctions","reduce","sum","totalTools"],"mappings":"AAsCA,OAAO,MAAMA;IACHC,QAA8B,IAAIC,MAAM;IACxCC,cAAuB,MAAM;IAErC,aAAc;QACZ,IAAI,CAACC,oBAAoB;IAC3B;IAKA,MAAMC,aAA4B;QAChC,MAAM,IAAI,CAACC,aAAa;QACxB,MAAM,IAAI,CAACC,eAAe;QAC1B,IAAI,CAACJ,WAAW,GAAG;IACrB;IAKQC,uBAA6B;QAEnC,IAAI,CAACH,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C5D,MAAMiF,qBAAqBD,eAAeE,MAAM,CAAC,CAACC,KAAK5E,OAAS4E,MAAM5E,KAAKvB,SAAS,CAACqD,MAAM,EAAE;QAE7F,OAAO;YACL7D,aAAa,IAAI,CAACA,WAAW;YAC7B4G,YAAY9G,MAAM+D,MAAM;YACxB2C,gBAAgBA,eAAe3C,MAAM;YACrC4C;QACF;IACF;AACF"}
1
+ {"version":3,"sources":["../../../src/core/MCPIntegrator.ts"],"sourcesContent":["/**\n * MCPIntegrator - Manages MCP tool coordination\n * Provides integration with external MCP tools and orchestration services\n */\n\nexport interface MCPTool {\n name: string;\n server: string;\n functions: MCPFunction[];\n status: 'connected' | 'disconnected' | 'error';\n lastPing?: Date;\n}\n\nexport interface MCPFunction {\n name: string;\n description: string;\n parameters: any;\n required: string[];\n}\n\nexport interface MCPCommand {\n tool: string;\n function: string;\n parameters: any;\n timeout?: number;\n}\n\nexport interface MCPResult {\n success: boolean;\n data?: any;\n error?: string;\n metadata?: {\n executionTime: number;\n tool: string;\n function: string;\n };\n}\n\nexport class MCPIntegrator {\n private tools: Map<string, MCPTool> = new Map();\n private initialized: boolean = false;\n\n constructor() {\n this.registerDefaultTools();\n }\n\n /**\n * Initialize MCP integrator and discover available tools\n */\n async initialize(): Promise<void> {\n await this.discoverTools();\n await this.testConnections();\n this.initialized = true;\n }\n\n /**\n * Register default MCP tools\n */\n private registerDefaultTools(): void {\n // Claude Flow MCP tools\n this.tools.set('claude-flow', {\n name: 'claude-flow',\n server: 'npx claude-flow@alpha mcp start',\n functions: [\n {\n name: 'swarm_init',\n description: 'Initialize swarm with topology',\n parameters: { topology: 'string', maxAgents: 'number', strategy: 'string' },\n required: ['topology']\n },\n {\n name: 'agent_spawn',\n description: 'Spawn specialized agents',\n parameters: { type: 'string', capabilities: 'array', name: 'string' },\n required: ['type']\n },\n {\n name: 'task_orchestrate',\n description: 'Orchestrate complex tasks',\n parameters: { task: 'string', strategy: 'string', priority: 'string' },\n required: ['task']\n },\n {\n name: 'memory_usage',\n description: 'Manage coordination memory',\n parameters: { action: 'string', key: 'string', value: 'string', namespace: 'string' },\n required: ['action']\n },\n {\n name: 'swarm_status',\n description: 'Get swarm status and metrics',\n parameters: { detailed: 'boolean' },\n required: []\n }\n ],\n status: 'disconnected'\n });\n\n // ruv-swarm MCP tools (optional)\n this.tools.set('ruv-swarm', {\n name: 'ruv-swarm',\n server: 'npx ruv-swarm mcp start',\n functions: [\n {\n name: 'swarm_init',\n description: 'Initialize RUV swarm',\n parameters: { topology: 'string', maxAgents: 'number', strategy: 'string' },\n required: ['topology']\n },\n {\n name: 'neural_status',\n description: 'Get neural network status',\n parameters: { agentId: 'string' },\n required: []\n },\n {\n name: 'benchmark_run',\n description: 'Run performance benchmarks',\n parameters: { type: 'string', iterations: 'number' },\n required: []\n }\n ],\n status: 'disconnected'\n });\n\n // Flow Nexus MCP tools (optional)\n this.tools.set('flow-nexus', {\n name: 'flow-nexus',\n server: 'npx flow-nexus@latest mcp start',\n functions: [\n {\n name: 'swarm_init',\n description: 'Initialize Flow Nexus swarm',\n parameters: { topology: 'string', maxAgents: 'number', strategy: 'string' },\n required: ['topology']\n },\n {\n name: 'sandbox_create',\n description: 'Create execution sandbox',\n parameters: { template: 'string', env_vars: 'object' },\n required: ['template']\n },\n {\n name: 'neural_train',\n description: 'Train neural networks',\n parameters: { config: 'object', tier: 'string' },\n required: ['config']\n }\n ],\n status: 'disconnected'\n });\n\n // Agentic Payments MCP tools (optional)\n this.tools.set('agentic-payments', {\n name: 'agentic-payments',\n server: 'npx agentic-payments@latest mcp',\n functions: [\n {\n name: 'create_active_mandate',\n description: 'Create Active Mandate for autonomous payment authorization',\n parameters: { agent: 'string', holder: 'string', amount: 'number', currency: 'string', period: 'string', kind: 'string' },\n required: ['agent', 'holder', 'amount', 'currency', 'period', 'kind']\n },\n {\n name: 'sign_mandate',\n description: 'Sign mandate with Ed25519 cryptographic proof',\n parameters: { mandate: 'object', private_key: 'string' },\n required: ['mandate', 'private_key']\n },\n {\n name: 'verify_mandate',\n description: 'Verify mandate signature and execution guards',\n parameters: { signed_mandate: 'object', check_guards: 'boolean' },\n required: ['signed_mandate']\n },\n {\n name: 'revoke_mandate',\n description: 'Revoke mandate by ID',\n parameters: { mandate_id: 'string', reason: 'string' },\n required: ['mandate_id']\n },\n {\n name: 'generate_agent_identity',\n description: 'Generate Ed25519 keypair for agent',\n parameters: { include_private_key: 'boolean' },\n required: []\n },\n {\n name: 'create_intent_mandate',\n description: 'Create intent-based payment mandate',\n parameters: { merchant_id: 'string', customer_id: 'string', intent: 'string', max_amount: 'number' },\n required: ['merchant_id', 'customer_id', 'intent', 'max_amount']\n },\n {\n name: 'create_cart_mandate',\n description: 'Create cart-based payment mandate',\n parameters: { merchant_id: 'string', customer_id: 'string', items: 'array' },\n required: ['merchant_id', 'customer_id', 'items']\n }\n ],\n status: 'disconnected'\n });\n }\n\n /**\n * Discover available MCP tools\n */\n private async discoverTools(): Promise<void> {\n // In a real implementation, this would probe for available MCP servers\n // For now, we'll simulate the discovery process\n\n for (const [name, tool] of this.tools) {\n try {\n // Simulate tool discovery\n const isAvailable = await this.checkToolAvailability(name);\n tool.status = isAvailable ? 'connected' : 'disconnected';\n tool.lastPing = new Date();\n } catch (error) {\n tool.status = 'error';\n console.warn(`Failed to discover MCP tool ${name}:`, error);\n }\n }\n }\n\n /**\n * Check if a specific tool is available\n */\n private async checkToolAvailability(toolName: string): Promise<boolean> {\n // Simulate availability check\n // In real implementation, this would try to connect to the MCP server\n return Math.random() > 0.3; // 70% availability simulation\n }\n\n /**\n * Test connections to all tools\n */\n private async testConnections(): Promise<void> {\n for (const [name, tool] of this.tools) {\n if (tool.status === 'connected') {\n try {\n // Simulate connection test\n await new Promise(resolve => setTimeout(resolve, 100));\n console.log(`āœ“ MCP tool ${name} connected successfully`);\n } catch (error) {\n tool.status = 'error';\n console.warn(`āœ— MCP tool ${name} connection failed:`, error);\n }\n }\n }\n }\n\n /**\n * Execute MCP command\n */\n async executeCommand(command: MCPCommand): Promise<MCPResult> {\n const startTime = Date.now();\n\n try {\n const tool = this.tools.get(command.tool);\n if (!tool) {\n return {\n success: false,\n error: `Unknown MCP tool: ${command.tool}`,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n\n if (tool.status !== 'connected') {\n return {\n success: false,\n error: `MCP tool ${command.tool} is not connected (status: ${tool.status})`,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n\n // Validate function exists\n const func = tool.functions.find(f => f.name === command.function);\n if (!func) {\n return {\n success: false,\n error: `Function ${command.function} not found in tool ${command.tool}`,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n\n // Validate required parameters\n const missingParams = func.required.filter(param => !(param in command.parameters));\n if (missingParams.length > 0) {\n return {\n success: false,\n error: `Missing required parameters: ${missingParams.join(', ')}`,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n\n // Execute the command (simulation)\n const result = await this.simulateCommandExecution(command);\n\n return {\n success: true,\n data: result,\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error),\n metadata: {\n executionTime: Date.now() - startTime,\n tool: command.tool,\n function: command.function\n }\n };\n }\n }\n\n /**\n * Simulate command execution (replace with real MCP calls in production)\n */\n private async simulateCommandExecution(command: MCPCommand): Promise<any> {\n // Simulate processing time\n await new Promise(resolve => setTimeout(resolve, 200 + Math.random() * 800));\n\n // Return different results based on function\n switch (command.function) {\n case 'swarm_init':\n return {\n swarmId: `swarm-${Date.now()}`,\n topology: command.parameters.topology,\n maxAgents: command.parameters.maxAgents || 8,\n status: 'initialized'\n };\n\n case 'agent_spawn':\n return {\n agentId: `agent-${Date.now()}`,\n type: command.parameters.type,\n capabilities: command.parameters.capabilities || [],\n status: 'spawned'\n };\n\n case 'task_orchestrate':\n return {\n taskId: `task-${Date.now()}`,\n task: command.parameters.task,\n strategy: command.parameters.strategy || 'adaptive',\n status: 'orchestrating'\n };\n\n case 'memory_usage':\n if (command.parameters.action === 'store') {\n return { stored: true, key: command.parameters.key };\n } else if (command.parameters.action === 'retrieve') {\n return { found: Math.random() > 0.3, value: 'simulated-value' };\n }\n return { action: command.parameters.action, success: true };\n\n case 'swarm_status':\n return {\n activeAgents: Math.floor(Math.random() * 8) + 1,\n topology: 'mesh',\n health: 'good',\n metrics: {\n throughput: Math.random() * 100,\n latency: Math.random() * 50 + 10\n }\n };\n\n case 'neural_status':\n return {\n modelLoaded: true,\n accuracy: 0.85 + Math.random() * 0.1,\n trainingProgress: Math.random() * 100\n };\n\n case 'benchmark_run':\n return {\n benchmarks: [\n { name: 'cpu', value: Math.random() * 100, unit: 'ms' },\n { name: 'memory', value: Math.random() * 512, unit: 'MB' },\n { name: 'network', value: Math.random() * 50, unit: 'ms' }\n ]\n };\n\n default:\n return { function: command.function, executed: true };\n }\n }\n\n /**\n * Get available tools\n */\n getAvailableTools(): MCPTool[] {\n return Array.from(this.tools.values());\n }\n\n /**\n * Get connected tools\n */\n getConnectedTools(): MCPTool[] {\n return Array.from(this.tools.values()).filter(tool => tool.status === 'connected');\n }\n\n /**\n * Get tool by name\n */\n getTool(name: string): MCPTool | undefined {\n return this.tools.get(name);\n }\n\n /**\n * Check if a tool is available\n */\n isToolAvailable(name: string): boolean {\n const tool = this.tools.get(name);\n return tool?.status === 'connected' || false;\n }\n\n /**\n * Get tool functions\n */\n getToolFunctions(toolName: string): MCPFunction[] {\n const tool = this.tools.get(toolName);\n return tool?.functions || [];\n }\n\n /**\n * Initialize swarm coordination using MCP tools\n */\n async initializeSwarmCoordination(config: {\n topology: string;\n maxAgents: number;\n strategy: string;\n }): Promise<MCPResult> {\n // Try claude-flow first, then fallback to other tools\n const toolPriority = ['claude-flow', 'ruv-swarm', 'flow-nexus'];\n\n for (const toolName of toolPriority) {\n if (this.isToolAvailable(toolName)) {\n return await this.executeCommand({\n tool: toolName,\n function: 'swarm_init',\n parameters: config\n });\n }\n }\n\n return {\n success: false,\n error: 'No MCP tools available for swarm initialization',\n metadata: {\n executionTime: 0,\n tool: 'none',\n function: 'swarm_init'\n }\n };\n }\n\n /**\n * Coordinate memory across swarm using MCP tools\n */\n async coordinateMemory(action: string, key: string, value?: string, namespace?: string): Promise<MCPResult> {\n const command: MCPCommand = {\n tool: 'claude-flow',\n function: 'memory_usage',\n parameters: { action, key, value, namespace: namespace || 'coordination' }\n };\n\n return await this.executeCommand(command);\n }\n\n /**\n * Spawn agents using MCP tools\n */\n async spawnAgent(type: string, capabilities?: string[], name?: string): Promise<MCPResult> {\n const command: MCPCommand = {\n tool: 'claude-flow',\n function: 'agent_spawn',\n parameters: { type, capabilities, name }\n };\n\n return await this.executeCommand(command);\n }\n\n /**\n * Orchestrate tasks using MCP tools\n */\n async orchestrateTask(task: string, strategy?: string, priority?: string): Promise<MCPResult> {\n const command: MCPCommand = {\n tool: 'claude-flow',\n function: 'task_orchestrate',\n parameters: { task, strategy, priority }\n };\n\n return await this.executeCommand(command);\n }\n\n /**\n * Get swarm status using MCP tools\n */\n async getSwarmStatus(detailed: boolean = false): Promise<MCPResult> {\n const command: MCPCommand = {\n tool: 'claude-flow',\n function: 'swarm_status',\n parameters: { detailed }\n };\n\n return await this.executeCommand(command);\n }\n\n /**\n * Refresh tool connections\n */\n async refreshConnections(): Promise<void> {\n await this.discoverTools();\n await this.testConnections();\n }\n\n /**\n * Register a custom tool\n */\n registerTool(tool: MCPTool): void {\n this.tools.set(tool.name, tool);\n }\n\n /**\n * Unregister a tool\n */\n unregisterTool(name: string): boolean {\n return this.tools.delete(name);\n }\n\n /**\n * Get integration status\n */\n getIntegrationStatus(): {\n initialized: boolean;\n totalTools: number;\n connectedTools: number;\n availableFunctions: number;\n } {\n const tools = Array.from(this.tools.values());\n const connectedTools = tools.filter(tool => tool.status === 'connected');\n const availableFunctions = connectedTools.reduce((sum, tool) => sum + tool.functions.length, 0);\n\n return {\n initialized: this.initialized,\n totalTools: tools.length,\n connectedTools: connectedTools.length,\n availableFunctions\n };\n }\n}"],"names":["MCPIntegrator","tools","Map","initialized","registerDefaultTools","initialize","discoverTools","testConnections","set","name","server","functions","description","parameters","topology","maxAgents","strategy","required","type","capabilities","task","priority","action","key","value","namespace","detailed","status","agentId","iterations","template","env_vars","config","tier","agent","holder","amount","currency","period","kind","mandate","private_key","signed_mandate","check_guards","mandate_id","reason","include_private_key","merchant_id","customer_id","intent","max_amount","items","tool","isAvailable","checkToolAvailability","lastPing","Date","error","console","warn","toolName","Math","random","Promise","resolve","setTimeout","log","executeCommand","command","startTime","now","get","success","metadata","executionTime","function","func","find","f","missingParams","filter","param","length","join","result","simulateCommandExecution","data","Error","message","String","swarmId","taskId","stored","found","activeAgents","floor","health","metrics","throughput","latency","modelLoaded","accuracy","trainingProgress","benchmarks","unit","executed","getAvailableTools","Array","from","values","getConnectedTools","getTool","isToolAvailable","getToolFunctions","initializeSwarmCoordination","toolPriority","coordinateMemory","spawnAgent","orchestrateTask","getSwarmStatus","refreshConnections","registerTool","unregisterTool","delete","getIntegrationStatus","connectedTools","availableFunctions","reduce","sum","totalTools"],"mappings":"AAsCA,OAAO,MAAMA;IACHC,QAA8B,IAAIC,MAAM;IACxCC,cAAuB,MAAM;IAErC,aAAc;QACZ,IAAI,CAACC,oBAAoB;IAC3B;IAKA,MAAMC,aAA4B;QAChC,MAAM,IAAI,CAACC,aAAa;QACxB,MAAM,IAAI,CAACC,eAAe;QAC1B,IAAI,CAACJ,WAAW,GAAG;IACrB;IAKQC,uBAA6B;QAEnC,IAAI,CAACH,KAAK,CAACO,GAAG,CAAC,eAAe;YAC5BC,MAAM;YACNC,QAAQ;YACRC,WAAW;gBACT;oBACEF,MAAM;oBACNG,aAAa;oBACbC,YAAY;wBAAEC,UAAU;wBAAUC,WAAW;wBAAUC,UAAU;oBAAS;oBAC1EC,UAAU;wBAAC;qBAAW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ts"],"sourcesContent":["/**\n * Centralized version management\n * Reads version from package.json to ensure consistency\n */\n\nimport { readFileSync } from 'fs';\nimport { join, dirname } from 'path';\nimport { fileURLToPath } from 'url';\n\n// Get the directory of this module\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n// Read version from package.json\nlet VERSION: string;\nlet BUILD_DATE: string;\n\ntry {\n // Navigate to project root and read package.json\n const packageJsonPath = join(__dirname, '../../package.json');\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));\n VERSION = packageJson.version;\n BUILD_DATE = new Date().toISOString().split('T')[0];\n} catch (error) {\n // Fallback version if package.json can't be read\n console.warn('Warning: Could not read version from package.json, using fallback');\n VERSION = '2.0.0-alpha.91';\n BUILD_DATE = new Date().toISOString().split('T')[0];\n}\n\nexport { VERSION, BUILD_DATE };\n\n// Helper function to get formatted version string\nexport function getVersionString(includeV = true): string {\n return includeV ? `v${VERSION}` : VERSION;\n}\n\n// Helper function for version display in CLI\nexport function displayVersion(): void {\n console.log(getVersionString());\n}"],"names":["readFileSync","join","dirname","fileURLToPath","__filename","url","__dirname","VERSION","BUILD_DATE","packageJsonPath","packageJson","JSON","parse","version","Date","toISOString","split","error","console","warn","getVersionString","includeV","displayVersion","log"],"mappings":"AAKA,SAASA,YAAY,QAAQ,KAAK;AAClC,SAASC,IAAI,EAAEC,OAAO,QAAQ,OAAO;AACrC,SAASC,aAAa,QAAQ,MAAM;AAGpC,MAAMC,aAAaD,cAAc,YAAYE,GAAG;AAChD,MAAMC,YAAYJ,QAAQE;AAG1B,IAAIG;AACJ,IAAIC;AAEJ,IAAI;IAEF,MAAMC,kBAAkBR,KAAKK,WAAW;IACxC,MAAMI,cAAcC,KAAKC,KAAK,CAACZ,aAAaS,iBAAiB;IAC7DF,UAAUG,YAAYG,OAAO;IAC7BL,aAAa,IAAIM,OAAOC,WAAW,GAAGC,KAAK,CAAC,IAAI,CAAC,EAAE;AACrD,EAAE,OAAOC,OAAO;IAEdC,QAAQC,IAAI,CAAC;IACbZ,UAAU;IACVC,aAAa,IAAIM,OAAOC,WAAW,GAAGC,KAAK,CAAC,IAAI,CAAC,EAAE;AACrD;AAEA,SAAST,OAAO,EAAEC,UAAU,GAAG;AAG/B,OAAO,SAASY,iBAAiBC,WAAW,IAAI;IAC9C,OAAOA,WAAW,CAAC,CAAC,EAAEd,SAAS,GAAGA;AACpC;AAGA,OAAO,SAASe;IACdJ,QAAQK,GAAG,CAACH;AACd"}
1
+ {"version":3,"sources":["../../../src/core/version.js"],"sourcesContent":["/**\n * Centralized version management (JavaScript version)\n * Reads version from package.json to ensure consistency\n */\n\nimport { readFileSync } from 'fs';\nimport { join, dirname } from 'path';\nimport { fileURLToPath } from 'url';\n\n// Get the directory of this module\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = dirname(__filename);\n\n// Read version from package.json\nlet VERSION;\nlet BUILD_DATE;\n\ntry {\n // Navigate to project root and read package.json\n const packageJsonPath = join(__dirname, '../../package.json');\n const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));\n VERSION = packageJson.version;\n BUILD_DATE = new Date().toISOString().split('T')[0];\n} catch (error) {\n // Fallback version if package.json can't be read\n console.warn('Warning: Could not read version from package.json, using fallback');\n VERSION = '2.0.0-alpha.101';\n BUILD_DATE = new Date().toISOString().split('T')[0];\n}\n\nexport { VERSION, BUILD_DATE };\n\n// Helper function to get formatted version string\nexport function getVersionString(includeV = true) {\n return includeV ? `v${VERSION}` : VERSION;\n}\n\n// Helper function for version display in CLI\nexport function displayVersion() {\n console.log(getVersionString());\n}"],"names":["readFileSync","join","dirname","fileURLToPath","__filename","url","__dirname","VERSION","BUILD_DATE","packageJsonPath","packageJson","JSON","parse","version","Date","toISOString","split","error","console","warn","getVersionString","includeV","displayVersion","log"],"mappings":"AAKA,SAASA,YAAY,QAAQ,KAAK;AAClC,SAASC,IAAI,EAAEC,OAAO,QAAQ,OAAO;AACrC,SAASC,aAAa,QAAQ,MAAM;AAGpC,MAAMC,aAAaD,cAAc,YAAYE,GAAG;AAChD,MAAMC,YAAYJ,QAAQE;AAG1B,IAAIG;AACJ,IAAIC;AAEJ,IAAI;IAEF,MAAMC,kBAAkBR,KAAKK,WAAW;IACxC,MAAMI,cAAcC,KAAKC,KAAK,CAACZ,aAAaS,iBAAiB;IAC7DF,UAAUG,YAAYG,OAAO;IAC7BL,aAAa,IAAIM,OAAOC,WAAW,GAAGC,KAAK,CAAC,IAAI,CAAC,EAAE;AACrD,EAAE,OAAOC,OAAO;IAEdC,QAAQC,IAAI,CAAC;IACbZ,UAAU;IACVC,aAAa,IAAIM,OAAOC,WAAW,GAAGC,KAAK,CAAC,IAAI,CAAC,EAAE;AACrD;AAEA,SAAST,OAAO,EAAEC,UAAU,GAAG;AAG/B,OAAO,SAASY,iBAAiBC,WAAW,IAAI;IAC9C,OAAOA,WAAW,CAAC,CAAC,EAAEd,SAAS,GAAGA;AACpC;AAGA,OAAO,SAASe;IACdJ,QAAQK,GAAG,CAACH;AACd"}H;AACd"}
@@ -166,14 +166,4 @@ export class MetricsReader {
166
166
  }
167
167
  }
168
168
 
169
- //# sourceMappingURL=metrics-reader.js.map processCount: 0,
170
- orchestratorRunning: false,
171
- port: null,
172
- connections: 0
173
- };
174
- }
175
- }
176
- };
177
- export { MetricsReader };
178
-
179
169
  //# sourceMappingURL=metrics-reader.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "claude-flow",
3
- "version": "2.5.0-alpha.131",
3
+ "version": "2.5.0-alpha.132",
4
4
  "description": "Enterprise-grade AI agent orchestration with ruv-swarm integration",
5
5
  "mcpName": "io.github.ruvnet/claude-flow",
6
6
  "main": "cli.mjs",
@@ -115,6 +115,11 @@ async function setupMcpServers(dryRun = false) {
115
115
  command: 'npx flow-nexus@latest mcp start',
116
116
  description: 'Flow Nexus Complete MCP server for advanced AI orchestration',
117
117
  },
118
+ {
119
+ name: 'agentic-payments',
120
+ command: 'npx agentic-payments@latest mcp',
121
+ description: 'Agentic Payments MCP server for autonomous agent payment authorization',
122
+ },
118
123
  ];
119
124
 
120
125
  for (const server of servers) {
@@ -540,6 +545,7 @@ export async function initCommand(subArgs, flags) {
540
545
  console.log(' claude mcp add claude-flow npx claude-flow@alpha mcp start');
541
546
  console.log(' claude mcp add ruv-swarm npx ruv-swarm mcp start');
542
547
  console.log(' claude mcp add flow-nexus npx flow-nexus@latest mcp start');
548
+ console.log(' claude mcp add agentic-payments npx agentic-payments@latest mcp');
543
549
  }
544
550
  }
545
551
  } catch (err) {
@@ -1203,6 +1209,11 @@ async function enhancedClaudeFlowInit(flags, subArgs = []) {
1203
1209
  args: ['flow-nexus@latest', 'mcp', 'start'],
1204
1210
  type: 'stdio',
1205
1211
  },
1212
+ 'agentic-payments': {
1213
+ command: 'npx',
1214
+ args: ['agentic-payments@latest', 'mcp'],
1215
+ type: 'stdio',
1216
+ },
1206
1217
  },
1207
1218
  };
1208
1219
 
@@ -1414,6 +1425,7 @@ ${commands.map((cmd) => `- [${cmd}](./${cmd}.md)`).join('\n')}
1414
1425
  console.log(' claude mcp add claude-flow npx claude-flow@alpha mcp start');
1415
1426
  console.log(' claude mcp add ruv-swarm npx ruv-swarm@latest mcp start');
1416
1427
  console.log(' claude mcp add flow-nexus npx flow-nexus@latest mcp start');
1428
+ console.log(' claude mcp add agentic-payments npx agentic-payments@latest mcp');
1417
1429
  console.log('\n šŸ’” MCP servers are defined in .mcp.json (project scope)');
1418
1430
  }
1419
1431
  } else if (!dryRun && !isClaudeCodeInstalled()) {
@@ -1424,6 +1436,7 @@ ${commands.map((cmd) => `- [${cmd}](./${cmd}.md)`).join('\n')}
1424
1436
  console.log(' claude mcp add claude-flow@alpha npx claude-flow@alpha mcp start');
1425
1437
  console.log(' claude mcp add ruv-swarm npx ruv-swarm@latest mcp start');
1426
1438
  console.log(' claude mcp add flow-nexus npx flow-nexus@latest mcp start');
1439
+ console.log(' claude mcp add agentic-payments npx agentic-payments@latest mcp');
1427
1440
  console.log('\n šŸ’” MCP servers are defined in .mcp.json (project scope)');
1428
1441
  }
1429
1442
 
@@ -149,6 +149,57 @@ export class MCPIntegrator {
149
149
  ],
150
150
  status: 'disconnected'
151
151
  });
152
+
153
+ // Agentic Payments MCP tools (optional)
154
+ this.tools.set('agentic-payments', {
155
+ name: 'agentic-payments',
156
+ server: 'npx agentic-payments@latest mcp',
157
+ functions: [
158
+ {
159
+ name: 'create_active_mandate',
160
+ description: 'Create Active Mandate for autonomous payment authorization',
161
+ parameters: { agent: 'string', holder: 'string', amount: 'number', currency: 'string', period: 'string', kind: 'string' },
162
+ required: ['agent', 'holder', 'amount', 'currency', 'period', 'kind']
163
+ },
164
+ {
165
+ name: 'sign_mandate',
166
+ description: 'Sign mandate with Ed25519 cryptographic proof',
167
+ parameters: { mandate: 'object', private_key: 'string' },
168
+ required: ['mandate', 'private_key']
169
+ },
170
+ {
171
+ name: 'verify_mandate',
172
+ description: 'Verify mandate signature and execution guards',
173
+ parameters: { signed_mandate: 'object', check_guards: 'boolean' },
174
+ required: ['signed_mandate']
175
+ },
176
+ {
177
+ name: 'revoke_mandate',
178
+ description: 'Revoke mandate by ID',
179
+ parameters: { mandate_id: 'string', reason: 'string' },
180
+ required: ['mandate_id']
181
+ },
182
+ {
183
+ name: 'generate_agent_identity',
184
+ description: 'Generate Ed25519 keypair for agent',
185
+ parameters: { include_private_key: 'boolean' },
186
+ required: []
187
+ },
188
+ {
189
+ name: 'create_intent_mandate',
190
+ description: 'Create intent-based payment mandate',
191
+ parameters: { merchant_id: 'string', customer_id: 'string', intent: 'string', max_amount: 'number' },
192
+ required: ['merchant_id', 'customer_id', 'intent', 'max_amount']
193
+ },
194
+ {
195
+ name: 'create_cart_mandate',
196
+ description: 'Create cart-based payment mandate',
197
+ parameters: { merchant_id: 'string', customer_id: 'string', items: 'array' },
198
+ required: ['merchant_id', 'customer_id', 'items']
199
+ }
200
+ ],
201
+ status: 'disconnected'
202
+ });
152
203
  }
153
204
 
154
205
  /**