claude-flow 2.7.3 ā 2.7.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +45 -0
- package/bin/claude-flow +1 -1
- package/dist/src/cli/help-formatter.js +0 -3
- package/dist/src/cli/help-formatter.js.map +1 -1
- package/dist/src/cli/simple-cli.js +104 -0
- package/dist/src/cli/simple-cli.js.map +1 -1
- package/dist/src/cli/simple-commands/mcp.js +252 -246
- package/dist/src/cli/simple-commands/mcp.js.map +1 -1
- package/dist/src/cli/simple-commands/memory.js +13 -1
- package/dist/src/cli/simple-commands/memory.js.map +1 -1
- package/dist/src/cli/validation-helper.js.map +1 -1
- package/dist/src/utils/key-redactor.js.map +1 -1
- package/dist/src/utils/metrics-reader.js +41 -29
- package/dist/src/utils/metrics-reader.js.map +1 -1
- package/package.json +1 -1
- package/src/cli/simple-commands/mcp.js +267 -255
- package/src/cli/simple-commands/memory.js +19 -3
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/cli/simple-commands/mcp.js"],"sourcesContent":["// mcp.js - MCP server management commands\nimport { printSuccess, printError, printWarning } from '../utils.js';\n\nexport async function mcpCommand(subArgs, flags) {\n const mcpCmd = subArgs[0];\n\n switch (mcpCmd) {\n case 'status':\n await showMcpStatus(subArgs, flags);\n break;\n\n case 'start':\n await startMcpServer(subArgs, flags);\n break;\n\n case 'stop':\n await stopMcpServer(subArgs, flags);\n break;\n\n case 'tools':\n await listMcpTools(subArgs, flags);\n break;\n\n case 'auth':\n await manageMcpAuth(subArgs, flags);\n break;\n\n case 'config':\n await showMcpConfig(subArgs, flags);\n break;\n\n default:\n showMcpHelp();\n }\n}\n\nasync function showMcpStatus(subArgs, flags) {\n printSuccess('MCP Server Status:');\n console.log('š Status: Stopped (orchestrator not running)');\n console.log('š§ Configuration: Default settings');\n console.log('š Connections: 0 active');\n console.log('š” Tools: Ready to load');\n console.log('š Authentication: Not configured');\n}\n\nasync function startMcpServer(subArgs, flags) {\n const autoOrchestrator = subArgs.includes('--auto-orchestrator') || flags.autoOrchestrator;\n const daemon = subArgs.includes('--daemon') || flags.daemon;\n const stdio = subArgs.includes('--stdio') || flags.stdio || true; // Default to stdio mode\n\n if (stdio) {\n // Start MCP server in stdio mode (like ruv-swarm)\n printSuccess('Starting Claude Flow MCP server in stdio mode...');\n\n if (autoOrchestrator) {\n console.log('š Auto-starting orchestrator...');\n console.log('š§ Neural network capabilities: ENABLED');\n console.log('š§ WASM SIMD optimization: ACTIVE');\n console.log('š Performance monitoring: ENABLED');\n console.log('š Swarm coordination: READY');\n }\n\n // Import and start the MCP server\n try {\n const { fileURLToPath } = await import('url');\n const path = await import('path');\n const { spawn } = await import('child_process');\n\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = path.dirname(__filename);\n // TODO: Switch to new TypeScript server (server-standalone.js) after fixing import resolution\n // For now, using old mcp-server.js for local testing\n // Phase 4 tools will be available after NPM publish\n const mcpServerPath = path.join(__dirname, '../../mcp/mcp-server.js');\n\n // Check if the file exists, and log the path for debugging\n const fs = await import('fs');\n if (!fs.existsSync(mcpServerPath)) {\n console.error(`MCP server file not found at: ${mcpServerPath}`);\n console.error(`Current directory: ${process.cwd()}`);\n console.error(`Script directory: ${__dirname}`);\n throw new Error(`MCP server file not found: ${mcpServerPath}`);\n }\n\n // Start the MCP server process\n const serverProcess = spawn('node', [mcpServerPath], {\n stdio: 'inherit',\n env: {\n ...process.env,\n CLAUDE_FLOW_AUTO_ORCHESTRATOR: autoOrchestrator ? 'true' : 'false',\n CLAUDE_FLOW_NEURAL_ENABLED: 'true',\n CLAUDE_FLOW_WASM_ENABLED: 'true',\n },\n });\n\n serverProcess.on('exit', (code) => {\n if (code !== 0) {\n console.error(`MCP server exited with code ${code}`);\n }\n });\n\n // Keep the process alive\n await new Promise(() => {}); // Never resolves, keeps server running\n } catch (error) {\n console.error('Failed to start MCP server:', error.message);\n\n // Fallback to status display\n console.log('š MCP server would start with:');\n console.log(' Protocol: stdio');\n console.log(' Tools: 87 Claude-Flow integration tools');\n console.log(' Orchestrator: ' + (autoOrchestrator ? 'AUTO-STARTED' : 'Manual'));\n console.log(' Mode: ' + (daemon ? 'DAEMON' : 'Interactive'));\n }\n } else {\n // HTTP mode (for future implementation)\n const port = getFlag(subArgs, '--port') || flags.port || 3000;\n const host = getFlag(subArgs, '--host') || flags.host || 'localhost';\n\n printSuccess(`Starting Claude Flow MCP server on ${host}:${port}...`);\n console.log('š HTTP mode not yet implemented, use --stdio for full functionality');\n }\n}\n\nasync function stopMcpServer(subArgs, flags) {\n printSuccess('Stopping MCP server...');\n console.log('š Server would be gracefully shut down');\n console.log('š Active connections would be closed');\n console.log('š¾ State would be persisted');\n}\n\nasync function listMcpTools(subArgs, flags) {\n const verbose = subArgs.includes('--verbose') || subArgs.includes('-v') || flags.verbose;\n const category = getFlag(subArgs, '--category') || flags.category;\n\n printSuccess('Claude-Flow MCP Tools & Resources (87 total):');\n\n if (!category || category === 'swarm') {\n console.log('\\nš SWARM COORDINATION (12 tools):');\n console.log(' ⢠swarm_init Initialize swarm with topology');\n console.log(' ⢠agent_spawn Create specialized AI agents');\n console.log(' ⢠task_orchestrate Orchestrate complex workflows');\n console.log(' ⢠swarm_status Monitor swarm health/performance');\n console.log(' ⢠agent_list List active agents & capabilities');\n console.log(' ⢠agent_metrics Agent performance metrics');\n console.log(' ⢠swarm_monitor Real-time swarm monitoring');\n console.log(' ⢠topology_optimize Auto-optimize swarm topology');\n console.log(' ⢠load_balance Distribute tasks efficiently');\n console.log(' ⢠coordination_sync Sync agent coordination');\n console.log(' ⢠swarm_scale Auto-scale agent count');\n console.log(' ⢠swarm_destroy Gracefully shutdown swarm');\n }\n\n if (!category || category === 'neural') {\n console.log('\\nš§ NEURAL NETWORKS & AI (15 tools):');\n console.log(' ⢠neural_status Check neural network status');\n console.log(' ⢠neural_train Train neural patterns');\n console.log(' ⢠neural_patterns Analyze cognitive patterns');\n console.log(' ⢠neural_predict Make AI predictions');\n console.log(' ⢠model_load Load pre-trained models');\n console.log(' ⢠model_save Save trained models');\n console.log(' ⢠wasm_optimize WASM SIMD optimization');\n console.log(' ⢠inference_run Run neural inference');\n console.log(' ⢠pattern_recognize Pattern recognition');\n console.log(' ⢠cognitive_analyze Cognitive behavior analysis');\n console.log(' ⢠learning_adapt Adaptive learning');\n console.log(' ⢠neural_compress Compress neural models');\n console.log(' ⢠ensemble_create Create model ensembles');\n console.log(' ⢠transfer_learn Transfer learning');\n console.log(' ⢠neural_explain AI explainability');\n }\n\n if (!category || category === 'memory') {\n console.log('\\nš¾ MEMORY & PERSISTENCE (12 tools):');\n console.log(' ⢠memory_usage Store/retrieve persistent data');\n console.log(' ⢠memory_search Search memory with patterns');\n console.log(' ⢠memory_persist Cross-session persistence');\n console.log(' ⢠memory_namespace Namespace management');\n console.log(' ⢠memory_backup Backup memory stores');\n console.log(' ⢠memory_restore Restore from backups');\n console.log(' ⢠memory_compress Compress memory data');\n console.log(' ⢠memory_sync Sync across instances');\n console.log(' ⢠cache_manage Manage coordination cache');\n console.log(' ⢠state_snapshot Create state snapshots');\n console.log(' ⢠context_restore Restore execution context');\n console.log(' ⢠memory_analytics Analyze memory usage');\n }\n\n if (!category || category === 'analysis') {\n console.log('\\nš ANALYSIS & MONITORING (13 tools):');\n console.log(' ⢠task_status Check task execution status');\n console.log(' ⢠task_results Get task completion results');\n console.log(' ⢠benchmark_run Performance benchmarks');\n console.log(' ⢠bottleneck_analyze Identify bottlenecks');\n console.log(' ⢠performance_report Generate performance reports');\n console.log(' ⢠token_usage Analyze token consumption');\n console.log(' ⢠metrics_collect Collect system metrics');\n console.log(' ⢠trend_analysis Analyze performance trends');\n console.log(' ⢠cost_analysis Cost and resource analysis');\n console.log(' ⢠quality_assess Quality assessment');\n console.log(' ⢠error_analysis Error pattern analysis');\n console.log(' ⢠usage_stats Usage statistics');\n console.log(' ⢠health_check System health monitoring');\n }\n\n if (!category || category === 'workflow') {\n console.log('\\nš§ WORKFLOW & AUTOMATION (11 tools):');\n console.log(' ⢠workflow_create Create custom workflows');\n console.log(' ⢠workflow_execute Execute predefined workflows');\n console.log(' ⢠workflow_export Export workflow definitions');\n console.log(' ⢠sparc_mode Run SPARC development modes');\n console.log(' ⢠automation_setup Setup automation rules');\n console.log(' ⢠pipeline_create Create CI/CD pipelines');\n console.log(' ⢠scheduler_manage Manage task scheduling');\n console.log(' ⢠trigger_setup Setup event triggers');\n console.log(' ⢠workflow_template Manage workflow templates');\n console.log(' ⢠batch_process Batch processing');\n console.log(' ⢠parallel_execute Execute tasks in parallel');\n }\n\n if (!category || category === 'github') {\n console.log('\\nš GITHUB INTEGRATION (8 tools):');\n console.log(' ⢠github_repo_analyze Repository analysis');\n console.log(' ⢠github_pr_manage Pull request management');\n console.log(' ⢠github_issue_track Issue tracking & triage');\n console.log(' ⢠github_release_coord Release coordination');\n console.log(' ⢠github_workflow_auto Workflow automation');\n console.log(' ⢠github_code_review Automated code review');\n console.log(' ⢠github_sync_coord Multi-repo sync coordination');\n console.log(' ⢠github_metrics Repository metrics');\n }\n\n if (!category || category === 'daa') {\n console.log('\\nš¤ DAA (Dynamic Agent Architecture) (8 tools):');\n console.log(' ⢠daa_agent_create Create dynamic agents');\n console.log(' ⢠daa_capability_match Match capabilities to tasks');\n console.log(' ⢠daa_resource_alloc Resource allocation');\n console.log(' ⢠daa_lifecycle_manage Agent lifecycle management');\n console.log(' ⢠daa_communication Inter-agent communication');\n console.log(' ⢠daa_consensus Consensus mechanisms');\n console.log(' ⢠daa_fault_tolerance Fault tolerance & recovery');\n console.log(' ⢠daa_optimization Performance optimization');\n }\n\n if (!category || category === 'system') {\n console.log('\\nāļø SYSTEM & UTILITIES (8 tools):');\n console.log(' ⢠terminal_execute Execute terminal commands');\n console.log(' ⢠config_manage Configuration management');\n console.log(' ⢠features_detect Feature detection');\n console.log(' ⢠security_scan Security scanning');\n console.log(' ⢠backup_create Create system backups');\n console.log(' ⢠restore_system System restoration');\n console.log(' ⢠log_analysis Log analysis & insights');\n console.log(' ⢠diagnostic_run System diagnostics');\n }\n\n if (verbose) {\n console.log('\\nš DETAILED TOOL INFORMATION:');\n console.log(' š„ HIGH-PRIORITY TOOLS:');\n console.log(\n ' swarm_init: Initialize coordination with 4 topologies (hierarchical, mesh, ring, star)',\n );\n console.log(\n ' agent_spawn: 8 agent types (researcher, coder, analyst, architect, tester, coordinator, reviewer, optimizer)',\n );\n console.log(' neural_train: Train 27 neural models with WASM SIMD acceleration');\n console.log(\n ' memory_usage: 5 operations (store, retrieve, list, delete, search) with TTL & namespacing',\n );\n console.log(' performance_report: Real-time metrics with 24h/7d/30d timeframes');\n\n console.log('\\n ā” PERFORMANCE FEATURES:');\n console.log(' ⢠2.8-4.4x speed improvement with parallel execution');\n console.log(' ⢠32.3% token reduction through optimization');\n console.log(' ⢠84.8% SWE-Bench solve rate with swarm coordination');\n console.log(' ⢠WASM neural processing with SIMD optimization');\n console.log(' ⢠Cross-session memory persistence');\n\n console.log('\\n š INTEGRATION CAPABILITIES:');\n console.log(' ⢠Full ruv-swarm feature parity (rebranded)');\n console.log(' ⢠Claude Code native tool integration');\n console.log(' ⢠GitHub Actions workflow automation');\n console.log(' ⢠SPARC methodology with 17 modes');\n console.log(' ⢠MCP protocol compatibility');\n }\n\n console.log('\\nš” Status: 87 tools & resources available when server is running');\n console.log('šÆ Categories: swarm, neural, memory, analysis, workflow, github, daa, system');\n console.log('š Compatibility: ruv-swarm + DAA + Claude-Flow unified platform');\n console.log('\\nš” Usage: claude-flow mcp tools --category=<category> --verbose');\n}\n\nasync function manageMcpAuth(subArgs, flags) {\n const authCmd = subArgs[1];\n\n switch (authCmd) {\n case 'setup':\n printSuccess('Setting up MCP authentication...');\n console.log('š Authentication configuration:');\n console.log(' Type: API Key based');\n console.log(' Scope: Claude-Flow tools');\n console.log(' Security: TLS encrypted');\n break;\n\n case 'status':\n printSuccess('MCP Authentication Status:');\n console.log('š Status: Not configured');\n console.log('š API Keys: 0 active');\n console.log('š”ļø Security: Default settings');\n break;\n\n case 'rotate':\n printSuccess('Rotating MCP authentication keys...');\n console.log('š New API keys would be generated');\n console.log('ā»ļø Old keys would be deprecated gracefully');\n break;\n\n default:\n console.log('Auth commands: setup, status, rotate');\n console.log('Examples:');\n console.log(' claude-flow mcp auth setup');\n console.log(' claude-flow mcp auth status');\n }\n}\n\nasync function showMcpConfig(subArgs, flags) {\n printSuccess('Claude-Flow MCP Server Configuration:');\n console.log('\\nš Server Settings:');\n console.log(' Host: localhost');\n console.log(' Port: 3000');\n console.log(' Protocol: HTTP/STDIO');\n console.log(' Timeout: 30000ms');\n console.log(' Auto-Orchestrator: Enabled');\n\n console.log('\\nš§ Tool Configuration:');\n console.log(' Available Tools: 87 total');\n console.log(' Categories: 8 (swarm, neural, memory, analysis, workflow, github, daa, system)');\n console.log(' Authentication: API Key + OAuth');\n console.log(' Rate Limiting: 1000 req/min');\n console.log(' WASM Support: Enabled with SIMD');\n\n console.log('\\nš§ Neural Network Settings:');\n console.log(' Models: 27 pre-trained models available');\n console.log(' Training: Real-time adaptive learning');\n console.log(' Inference: WASM optimized');\n console.log(' Pattern Recognition: Enabled');\n\n console.log('\\nš Swarm Configuration:');\n console.log(' Max Agents: 10 per swarm');\n console.log(' Topologies: hierarchical, mesh, ring, star');\n console.log(' Coordination: Real-time with hooks');\n console.log(' Memory: Cross-session persistence');\n\n console.log('\\nš Security Settings:');\n console.log(' TLS: Enabled in production');\n console.log(' CORS: Configured for Claude Code');\n console.log(' API Key Rotation: 30 days');\n console.log(' Audit Logging: Enabled');\n\n console.log('\\nš Integration Settings:');\n console.log(' ruv-swarm Compatibility: 100%');\n console.log(' DAA Integration: Enabled');\n console.log(' GitHub Actions: Connected');\n console.log(' SPARC Modes: 17 available');\n\n console.log('\\nš Configuration Files:');\n console.log(' Main Config: ./mcp_config/claude-flow.json');\n console.log(' Neural Models: ./models/');\n console.log(' Memory Store: ./memory/');\n console.log(' Logs: ./logs/mcp/');\n}\n\nfunction getFlag(args, flagName) {\n const index = args.indexOf(flagName);\n return index !== -1 && index + 1 < args.length ? args[index + 1] : null;\n}\n\nfunction showMcpHelp() {\n console.log('š§ Claude-Flow MCP Server Commands:');\n console.log();\n console.log('COMMANDS:');\n console.log(' status Show MCP server status');\n console.log(' start [options] Start MCP server with orchestrator');\n console.log(' stop Stop MCP server gracefully');\n console.log(' tools [options] List available tools & resources');\n console.log(' auth <setup|status|rotate> Manage authentication');\n console.log(' config Show comprehensive configuration');\n console.log();\n console.log('START OPTIONS:');\n console.log(' --port <port> Server port (default: 3000)');\n console.log(' --host <host> Server host (default: localhost)');\n console.log(' --auto-orchestrator Auto-start orchestrator with neural/WASM');\n console.log(' --daemon Run in background daemon mode');\n console.log(' --enable-neural Enable neural network features');\n console.log(' --enable-wasm Enable WASM SIMD optimization');\n console.log();\n console.log('TOOLS OPTIONS:');\n console.log(\n ' --category <cat> Filter by category (swarm, neural, memory, etc.)',\n );\n console.log(' --verbose, -v Show detailed tool information');\n console.log(' --examples Show usage examples');\n console.log();\n console.log('CATEGORIES:');\n console.log(' swarm š Swarm coordination (12 tools)');\n console.log(' neural š§ Neural networks & AI (15 tools)');\n console.log(' memory š¾ Memory & persistence (12 tools)');\n console.log(' analysis š Analysis & monitoring (13 tools)');\n console.log(' workflow š§ Workflow & automation (11 tools)');\n console.log(' github š GitHub integration (8 tools)');\n console.log(' daa š¤ Dynamic Agent Architecture (8 tools)');\n console.log(' system āļø System & utilities (8 tools)');\n console.log();\n console.log('EXAMPLES:');\n console.log(' claude-flow mcp status');\n console.log(' claude-flow mcp start --auto-orchestrator --daemon');\n console.log(' claude-flow mcp tools --category=neural --verbose');\n console.log(' claude-flow mcp tools --category=swarm');\n console.log(' claude-flow mcp config');\n console.log(' claude-flow mcp auth setup');\n console.log();\n console.log('šÆ Total: 87 tools & resources available');\n console.log('š Full ruv-swarm + DAA + Claude-Flow integration');\n}\n"],"names":["printSuccess","mcpCommand","subArgs","flags","mcpCmd","showMcpStatus","startMcpServer","stopMcpServer","listMcpTools","manageMcpAuth","showMcpConfig","showMcpHelp","console","log","autoOrchestrator","includes","daemon","stdio","fileURLToPath","path","spawn","__filename","url","__dirname","dirname","mcpServerPath","join","fs","existsSync","error","process","cwd","Error","serverProcess","env","CLAUDE_FLOW_AUTO_ORCHESTRATOR","CLAUDE_FLOW_NEURAL_ENABLED","CLAUDE_FLOW_WASM_ENABLED","on","code","Promise","message","port","getFlag","host","verbose","category","authCmd","args","flagName","index","indexOf","length"],"mappings":"AACA,SAASA,YAAY,QAAkC,cAAc;AAErE,OAAO,eAAeC,WAAWC,OAAO,EAAEC,KAAK;IAC7C,MAAMC,SAASF,OAAO,CAAC,EAAE;IAEzB,OAAQE;QACN,KAAK;YACH,MAAMC,cAAcH,SAASC;YAC7B;QAEF,KAAK;YACH,MAAMG,eAAeJ,SAASC;YAC9B;QAEF,KAAK;YACH,MAAMI,cAAcL,SAASC;YAC7B;QAEF,KAAK;YACH,MAAMK,aAAaN,SAASC;YAC5B;QAEF,KAAK;YACH,MAAMM,cAAcP,SAASC;YAC7B;QAEF,KAAK;YACH,MAAMO,cAAcR,SAASC;YAC7B;QAEF;YACEQ;IACJ;AACF;AAEA,eAAeN,cAAcH,OAAO,EAAEC,KAAK;IACzCH,aAAa;IACbY,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;AACd;AAEA,eAAeP,eAAeJ,OAAO,EAAEC,KAAK;IAC1C,MAAMW,mBAAmBZ,QAAQa,QAAQ,CAAC,0BAA0BZ,MAAMW,gBAAgB;IAC1F,MAAME,SAASd,QAAQa,QAAQ,CAAC,eAAeZ,MAAMa,MAAM;IAC3D,MAAMC,QAAQf,QAAQa,QAAQ,CAAC,cAAcZ,MAAMc,KAAK,IAAI;IAE5D,IAAIA,OAAO;QAETjB,aAAa;QAEb,IAAIc,kBAAkB;YACpBF,QAAQC,GAAG,CA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C,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CACT;IAEFD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;AACd"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/cli/simple-commands/mcp.js"],"sourcesContent":["// mcp.js - MCP server management commands\nimport { printSuccess, printError, printWarning } from '../utils.js';\n\n// Module-level state to track stdio mode\nlet isStdioMode = false;\n\n// Smart logging helpers that respect stdio mode\n// In stdio mode: route to stderr to keep stdout clean for JSON-RPC\n// In HTTP mode: route to stdout for normal behavior\nconst log = (...args) => (isStdioMode ? console.error(...args) : console.log(...args));\nconst success = (msg) => (isStdioMode ? console.error(`ā
${msg}`) : printSuccess(msg));\nconst error = (msg) => (isStdioMode ? console.error(`ā ${msg}`) : printError(msg));\nconst warning = (msg) => (isStdioMode ? console.error(`ā ļø ${msg}`) : printWarning(msg));\n\nexport async function mcpCommand(subArgs, flags) {\n const mcpCmd = subArgs[0];\n\n switch (mcpCmd) {\n case 'status':\n await showMcpStatus(subArgs, flags);\n break;\n\n case 'start':\n await startMcpServer(subArgs, flags);\n break;\n\n case 'stop':\n await stopMcpServer(subArgs, flags);\n break;\n\n case 'tools':\n await listMcpTools(subArgs, flags);\n break;\n\n case 'auth':\n await manageMcpAuth(subArgs, flags);\n break;\n\n case 'config':\n await showMcpConfig(subArgs, flags);\n break;\n\n default:\n showMcpHelp();\n }\n}\n\nasync function showMcpStatus(subArgs, flags) {\n success('MCP Server Status:');\n log('š Status: Stopped (orchestrator not running)');\n log('š§ Configuration: Default settings');\n log('š Connections: 0 active');\n log('š” Tools: Ready to load');\n log('š Authentication: Not configured');\n}\n\nasync function startMcpServer(subArgs, flags) {\n const autoOrchestrator = subArgs.includes('--auto-orchestrator') || flags.autoOrchestrator;\n const daemon = subArgs.includes('--daemon') || flags.daemon;\n const stdio = subArgs.includes('--stdio') || flags.stdio || true; // Default to stdio mode\n\n // Set module-level stdio flag for all helper functions\n isStdioMode = stdio;\n\n if (stdio) {\n // Start MCP server in stdio mode (like ruv-swarm)\n success('Starting Claude Flow MCP server in stdio mode...');\n\n if (autoOrchestrator) {\n log('š Auto-starting orchestrator...');\n log('š§ Neural network capabilities: ENABLED');\n log('š§ WASM SIMD optimization: ACTIVE');\n log('š Performance monitoring: ENABLED');\n log('š Swarm coordination: READY');\n }\n\n // Import and start the MCP server\n try {\n const { fileURLToPath } = await import('url');\n const path = await import('path');\n const { spawn } = await import('child_process');\n\n const __filename = fileURLToPath(import.meta.url);\n const __dirname = path.dirname(__filename);\n // TODO: Switch to new TypeScript server (server-standalone.js) after fixing import resolution\n // For now, using old mcp-server.js for local testing\n // Phase 4 tools will be available after NPM publish\n const mcpServerPath = path.join(__dirname, '../../mcp/mcp-server.js');\n\n // Check if the file exists, and log the path for debugging\n const fs = await import('fs');\n if (!fs.existsSync(mcpServerPath)) {\n error(`MCP server file not found at: ${mcpServerPath}`);\n error(`Current directory: ${process.cwd()}`);\n error(`Script directory: ${__dirname}`);\n throw new Error(`MCP server file not found: ${mcpServerPath}`);\n }\n\n // Start the MCP server process\n const serverProcess = spawn('node', [mcpServerPath], {\n stdio: 'inherit',\n env: {\n ...process.env,\n CLAUDE_FLOW_AUTO_ORCHESTRATOR: autoOrchestrator ? 'true' : 'false',\n CLAUDE_FLOW_NEURAL_ENABLED: 'true',\n CLAUDE_FLOW_WASM_ENABLED: 'true',\n },\n });\n\n serverProcess.on('exit', (code) => {\n if (code !== 0) {\n error(`MCP server exited with code ${code}`);\n }\n });\n\n // Keep the process alive\n await new Promise(() => {}); // Never resolves, keeps server running\n } catch (err) {\n error('Failed to start MCP server: ' + err.message);\n\n // Fallback to status display\n log('š MCP server would start with:');\n log(' Protocol: stdio');\n log(' Tools: 87 Claude-Flow integration tools');\n log(' Orchestrator: ' + (autoOrchestrator ? 'AUTO-STARTED' : 'Manual'));\n log(' Mode: ' + (daemon ? 'DAEMON' : 'Interactive'));\n }\n } else {\n // HTTP mode (for future implementation)\n const port = getFlag(subArgs, '--port') || flags.port || 3000;\n const host = getFlag(subArgs, '--host') || flags.host || 'localhost';\n\n success(`Starting Claude Flow MCP server on ${host}:${port}...`);\n log('š HTTP mode not yet implemented, use --stdio for full functionality');\n }\n}\n\nasync function stopMcpServer(subArgs, flags) {\n success('Stopping MCP server...');\n log('š Server would be gracefully shut down');\n log('š Active connections would be closed');\n log('š¾ State would be persisted');\n}\n\nasync function listMcpTools(subArgs, flags) {\n const verbose = subArgs.includes('--verbose') || subArgs.includes('-v') || flags.verbose;\n const category = getFlag(subArgs, '--category') || flags.category;\n\n success('Claude-Flow MCP Tools & Resources (87 total):');\n\n if (!category || category === 'swarm') {\n log('\\nš SWARM COORDINATION (12 tools):');\n log(' ⢠swarm_init Initialize swarm with topology');\n log(' ⢠agent_spawn Create specialized AI agents');\n log(' ⢠task_orchestrate Orchestrate complex workflows');\n log(' ⢠swarm_status Monitor swarm health/performance');\n log(' ⢠agent_list List active agents & capabilities');\n log(' ⢠agent_metrics Agent performance metrics');\n log(' ⢠swarm_monitor Real-time swarm monitoring');\n log(' ⢠topology_optimize Auto-optimize swarm topology');\n log(' ⢠load_balance Distribute tasks efficiently');\n log(' ⢠coordination_sync Sync agent coordination');\n log(' ⢠swarm_scale Auto-scale agent count');\n log(' ⢠swarm_destroy Gracefully shutdown swarm');\n }\n\n if (!category || category === 'neural') {\n log('\\nš§ NEURAL NETWORKS & AI (15 tools):');\n log(' ⢠neural_status Check neural network status');\n log(' ⢠neural_train Train neural patterns');\n log(' ⢠neural_patterns Analyze cognitive patterns');\n log(' ⢠neural_predict Make AI predictions');\n log(' ⢠model_load Load pre-trained models');\n log(' ⢠model_save Save trained models');\n log(' ⢠wasm_optimize WASM SIMD optimization');\n log(' ⢠inference_run Run neural inference');\n log(' ⢠pattern_recognize Pattern recognition');\n log(' ⢠cognitive_analyze Cognitive behavior analysis');\n log(' ⢠learning_adapt Adaptive learning');\n log(' ⢠neural_compress Compress neural models');\n log(' ⢠ensemble_create Create model ensembles');\n log(' ⢠transfer_learn Transfer learning');\n log(' ⢠neural_explain AI explainability');\n }\n\n if (!category || category === 'memory') {\n log('\\nš¾ MEMORY & PERSISTENCE (12 tools):');\n log(' ⢠memory_usage Store/retrieve persistent data');\n log(' ⢠memory_search Search memory with patterns');\n log(' ⢠memory_persist Cross-session persistence');\n log(' ⢠memory_namespace Namespace management');\n log(' ⢠memory_backup Backup memory stores');\n log(' ⢠memory_restore Restore from backups');\n log(' ⢠memory_compress Compress memory data');\n log(' ⢠memory_sync Sync across instances');\n log(' ⢠cache_manage Manage coordination cache');\n log(' ⢠state_snapshot Create state snapshots');\n log(' ⢠context_restore Restore execution context');\n log(' ⢠memory_analytics Analyze memory usage');\n }\n\n if (!category || category === 'analysis') {\n log('\\nš ANALYSIS & MONITORING (13 tools):');\n log(' ⢠task_status Check task execution status');\n log(' ⢠task_results Get task completion results');\n log(' ⢠benchmark_run Performance benchmarks');\n log(' ⢠bottleneck_analyze Identify bottlenecks');\n log(' ⢠performance_report Generate performance reports');\n log(' ⢠token_usage Analyze token consumption');\n log(' ⢠metrics_collect Collect system metrics');\n log(' ⢠trend_analysis Analyze performance trends');\n log(' ⢠cost_analysis Cost and resource analysis');\n log(' ⢠quality_assess Quality assessment');\n log(' ⢠error_analysis Error pattern analysis');\n log(' ⢠usage_stats Usage statistics');\n log(' ⢠health_check System health monitoring');\n }\n\n if (!category || category === 'workflow') {\n log('\\nš§ WORKFLOW & AUTOMATION (11 tools):');\n log(' ⢠workflow_create Create custom workflows');\n log(' ⢠workflow_execute Execute predefined workflows');\n log(' ⢠workflow_export Export workflow definitions');\n log(' ⢠sparc_mode Run SPARC development modes');\n log(' ⢠automation_setup Setup automation rules');\n log(' ⢠pipeline_create Create CI/CD pipelines');\n log(' ⢠scheduler_manage Manage task scheduling');\n log(' ⢠trigger_setup Setup event triggers');\n log(' ⢠workflow_template Manage workflow templates');\n log(' ⢠batch_process Batch processing');\n log(' ⢠parallel_execute Execute tasks in parallel');\n }\n\n if (!category || category === 'github') {\n log('\\nš GITHUB INTEGRATION (8 tools):');\n log(' ⢠github_repo_analyze Repository analysis');\n log(' ⢠github_pr_manage Pull request management');\n log(' ⢠github_issue_track Issue tracking & triage');\n log(' ⢠github_release_coord Release coordination');\n log(' ⢠github_workflow_auto Workflow automation');\n log(' ⢠github_code_review Automated code review');\n log(' ⢠github_sync_coord Multi-repo sync coordination');\n log(' ⢠github_metrics Repository metrics');\n }\n\n if (!category || category === 'daa') {\n log('\\nš¤ DAA (Dynamic Agent Architecture) (8 tools):');\n log(' ⢠daa_agent_create Create dynamic agents');\n log(' ⢠daa_capability_match Match capabilities to tasks');\n log(' ⢠daa_resource_alloc Resource allocation');\n log(' ⢠daa_lifecycle_manage Agent lifecycle management');\n log(' ⢠daa_communication Inter-agent communication');\n log(' ⢠daa_consensus Consensus mechanisms');\n log(' ⢠daa_fault_tolerance Fault tolerance & recovery');\n log(' ⢠daa_optimization Performance optimization');\n }\n\n if (!category || category === 'system') {\n log('\\nāļø SYSTEM & UTILITIES (8 tools):');\n log(' ⢠terminal_execute Execute terminal commands');\n log(' ⢠config_manage Configuration management');\n log(' ⢠features_detect Feature detection');\n log(' ⢠security_scan Security scanning');\n log(' ⢠backup_create Create system backups');\n log(' ⢠restore_system System restoration');\n log(' ⢠log_analysis Log analysis & insights');\n log(' ⢠diagnostic_run System diagnostics');\n }\n\n if (verbose) {\n log('\\nš DETAILED TOOL INFORMATION:');\n log(' š„ HIGH-PRIORITY TOOLS:');\n log(\n ' swarm_init: Initialize coordination with 4 topologies (hierarchical, mesh, ring, star)',\n );\n log(\n ' agent_spawn: 8 agent types (researcher, coder, analyst, architect, tester, coordinator, reviewer, optimizer)',\n );\n log(' neural_train: Train 27 neural models with WASM SIMD acceleration');\n log(\n ' memory_usage: 5 operations (store, retrieve, list, delete, search) with TTL & namespacing',\n );\n log(' performance_report: Real-time metrics with 24h/7d/30d timeframes');\n\n log('\\n ā” PERFORMANCE FEATURES:');\n log(' ⢠2.8-4.4x speed improvement with parallel execution');\n log(' ⢠32.3% token reduction through optimization');\n log(' ⢠84.8% SWE-Bench solve rate with swarm coordination');\n log(' ⢠WASM neural processing with SIMD optimization');\n log(' ⢠Cross-session memory persistence');\n\n log('\\n š INTEGRATION CAPABILITIES:');\n log(' ⢠Full ruv-swarm feature parity (rebranded)');\n log(' ⢠Claude Code native tool integration');\n log(' ⢠GitHub Actions workflow automation');\n log(' ⢠SPARC methodology with 17 modes');\n log(' ⢠MCP protocol compatibility');\n }\n\n log('\\nš” Status: 87 tools & resources available when server is running');\n log('šÆ Categories: swarm, neural, memory, analysis, workflow, github, daa, system');\n log('š Compatibility: ruv-swarm + DAA + Claude-Flow unified platform');\n log('\\nš” Usage: claude-flow mcp tools --category=<category> --verbose');\n}\n\nasync function manageMcpAuth(subArgs, flags) {\n const authCmd = subArgs[1];\n\n switch (authCmd) {\n case 'setup':\n success('Setting up MCP authentication...');\n log('š Authentication configuration:');\n log(' Type: API Key based');\n log(' Scope: Claude-Flow tools');\n log(' Security: TLS encrypted');\n break;\n\n case 'status':\n success('MCP Authentication Status:');\n log('š Status: Not configured');\n log('š API Keys: 0 active');\n log('š”ļø Security: Default settings');\n break;\n\n case 'rotate':\n success('Rotating MCP authentication keys...');\n log('š New API keys would be generated');\n log('ā»ļø Old keys would be deprecated gracefully');\n break;\n\n default:\n log('Auth commands: setup, status, rotate');\n log('Examples:');\n log(' claude-flow mcp auth setup');\n log(' claude-flow mcp auth status');\n }\n}\n\nasync function showMcpConfig(subArgs, flags) {\n success('Claude-Flow MCP Server Configuration:');\n log('\\nš Server Settings:');\n log(' Host: localhost');\n log(' Port: 3000');\n log(' Protocol: HTTP/STDIO');\n log(' Timeout: 30000ms');\n log(' Auto-Orchestrator: Enabled');\n\n log('\\nš§ Tool Configuration:');\n log(' Available Tools: 87 total');\n log(' Categories: 8 (swarm, neural, memory, analysis, workflow, github, daa, system)');\n log(' Authentication: API Key + OAuth');\n log(' Rate Limiting: 1000 req/min');\n log(' WASM Support: Enabled with SIMD');\n\n log('\\nš§ Neural Network Settings:');\n log(' Models: 27 pre-trained models available');\n log(' Training: Real-time adaptive learning');\n log(' Inference: WASM optimized');\n log(' Pattern Recognition: Enabled');\n\n log('\\nš Swarm Configuration:');\n log(' Max Agents: 10 per swarm');\n log(' Topologies: hierarchical, mesh, ring, star');\n log(' Coordination: Real-time with hooks');\n log(' Memory: Cross-session persistence');\n\n log('\\nš Security Settings:');\n log(' TLS: Enabled in production');\n log(' CORS: Configured for Claude Code');\n log(' API Key Rotation: 30 days');\n log(' Audit Logging: Enabled');\n\n log('\\nš Integration Settings:');\n log(' ruv-swarm Compatibility: 100%');\n log(' DAA Integration: Enabled');\n log(' GitHub Actions: Connected');\n log(' SPARC Modes: 17 available');\n\n log('\\nš Configuration Files:');\n log(' Main Config: ./mcp_config/claude-flow.json');\n log(' Neural Models: ./models/');\n log(' Memory Store: ./memory/');\n log(' Logs: ./logs/mcp/');\n}\n\nfunction getFlag(args, flagName) {\n const index = args.indexOf(flagName);\n return index !== -1 && index + 1 < args.length ? args[index + 1] : null;\n}\n\nfunction showMcpHelp() {\n log('š§ Claude-Flow MCP Server Commands:');\n log();\n log('COMMANDS:');\n log(' status Show MCP server status');\n log(' start [options] Start MCP server with orchestrator');\n log(' stop Stop MCP server gracefully');\n log(' tools [options] List available tools & resources');\n log(' auth <setup|status|rotate> Manage authentication');\n log(' config Show comprehensive configuration');\n log();\n log('START OPTIONS:');\n log(' --port <port> Server port (default: 3000)');\n log(' --host <host> Server host (default: localhost)');\n log(' --auto-orchestrator Auto-start orchestrator with neural/WASM');\n log(' --daemon Run in background daemon mode');\n log(' --enable-neural Enable neural network features');\n log(' --enable-wasm Enable WASM SIMD optimization');\n log();\n log('TOOLS OPTIONS:');\n log(' --category <cat> Filter by category (swarm, neural, memory, etc.)');\n log(' --verbose, -v Show detailed tool information');\n log(' --examples Show usage examples');\n log();\n log('CATEGORIES:');\n log(' swarm š Swarm coordination (12 tools)');\n log(' neural š§ Neural networks & AI (15 tools)');\n log(' memory š¾ Memory & persistence (12 tools)');\n log(' analysis š Analysis & monitoring (13 tools)');\n log(' workflow š§ Workflow & automation (11 tools)');\n log(' github š GitHub integration (8 tools)');\n log(' daa š¤ Dynamic Agent Architecture (8 tools)');\n log(' system āļø System & utilities (8 tools)');\n log();\n log('EXAMPLES:');\n log(' claude-flow mcp status');\n log(' claude-flow mcp start --auto-orchestrator --daemon');\n log(' claude-flow mcp tools --category=neural --verbose');\n log(' claude-flow mcp tools --category=swarm');\n log(' claude-flow mcp config');\n log(' claude-flow mcp auth setup');\n log();\n log('šÆ Total: 87 tools & resources available');\n log('š Full ruv-swarm + DAA + Claude-Flow integration');\n}\n"],"names":["printSuccess","printError","printWarning","isStdioMode","log","args","console","error","success","msg","warning","mcpCommand","subArgs","flags","mcpCmd","showMcpStatus","startMcpServer","stopMcpServer","listMcpTools","manageMcpAuth","showMcpConfig","showMcpHelp","autoOrchestrator","includes","daemon","stdio","fileURLToPath","path","spawn","__filename","url","__dirname","dirname","mcpServerPath","join","fs","existsSync","process","cwd","Error","serverProcess","env","CLAUDE_FLOW_AUTO_ORCHESTRATOR","CLAUDE_FLOW_NEURAL_ENABLED","CLAUDE_FLOW_WASM_ENABLED","on","code","Promise","err","message","port","getFlag","host","verbose","category","authCmd","flagName","index","indexOf","length"],"mappings":"AACA,SAASA,YAAY,EAAEC,UAAU,EAAEC,YAAY,QAAQ,cAAc;AAGrE,IAAIC,cAAc;AAKlB,MAAMC,MAAM,CAAC,GAAGC,OAAUF,cAAcG,QAAQC,KAAK,IAAIF,QAAQC,QAAQF,GAAG,IAAIC;AAChF,MAAMG,UAAU,CAACC,MAASN,cAAcG,QAAQC,KAAK,CAAC,CAAC,EAAE,EAAEE,KAAK,IAAIT,aAAaS;AACjF,MAAMF,QAAQ,CAACE,MAASN,cAAcG,QAAQC,KAAK,CAAC,CAAC,EAAE,EAAEE,KAAK,IAAIR,WAAWQ;AAC7E,MAAMC,UAAU,CAACD,MAASN,cAAcG,QAAQC,KAAK,CAAC,CAAC,IAAI,EAAEE,KAAK,IAAIP,aAAaO;AAEnF,OAAO,eAAeE,WAAWC,OAAO,EAAEC,KAAK;IAC7C,MAAMC,SAASF,OAAO,CAAC,EAAE;IAEzB,OAAQE;QACN,KAAK;YACH,MAAMC,cAAcH,SAASC;YAC7B;QAEF,KAAK;YACH,MAAMG,eAAeJ,SAASC;YAC9B;QAEF,KAAK;YACH,MAAMI,cAAcL,SAASC;YAC7B;QAEF,KAAK;YACH,MAAMK,aAAaN,SAASC;YAC5B;QAEF,KAAK;YACH,MAAMM,cAAcP,SAASC;YAC7B;QAEF,KAAK;YACH,MAAMO,cAAcR,SAASC;YAC7B;QAEF;YACEQ;IACJ;AACF;AAEA,eAAeN,cAAcH,OAAO,EAAEC,KAAK;IACzCL,QAAQ;IACRJ,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA,IAAI;AACN;AAEA,eAAeY,eAAeJ,OAAO,EAAE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AAEA,SAASpC;IACPjB,IAAI;IACJA;IACAA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA;IACAA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA;IACAA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA;IACAA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA;IACAA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA,IAAI;IACJA;IACAA,IAAI;IACJA,IAAI;AACN"}
|
|
@@ -319,7 +319,19 @@ async function detectMemoryMode(flags, subArgs) {
|
|
|
319
319
|
return 'basic';
|
|
320
320
|
}
|
|
321
321
|
const initialized = await isReasoningBankInitialized();
|
|
322
|
-
|
|
322
|
+
if (initialized) {
|
|
323
|
+
return 'reasoningbank';
|
|
324
|
+
}
|
|
325
|
+
try {
|
|
326
|
+
const { initializeReasoningBank } = await import('../../reasoningbank/reasoningbank-adapter.js');
|
|
327
|
+
await initializeReasoningBank();
|
|
328
|
+
printInfo('šļø Initialized SQLite backend (.swarm/memory.db)');
|
|
329
|
+
return 'reasoningbank';
|
|
330
|
+
} catch (error) {
|
|
331
|
+
printWarning(`ā ļø SQLite unavailable, using JSON fallback`);
|
|
332
|
+
printWarning(` Reason: ${error.message}`);
|
|
333
|
+
return 'basic';
|
|
334
|
+
}
|
|
323
335
|
}
|
|
324
336
|
async function isReasoningBankInitialized() {
|
|
325
337
|
try {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../../src/cli/simple-commands/memory.js"],"sourcesContent":["// memory.js - Memory management commands\nimport { printSuccess, printError, printWarning, printInfo } from '../utils.js';\nimport { promises as fs } from 'fs';\nimport { cwd, exit, existsSync } from '../node-compat.js';\nimport { getUnifiedMemory } from '../../memory/unified-memory-manager.js';\nimport { KeyRedactor } from '../../utils/key-redactor.js';\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\nexport async function memoryCommand(subArgs, flags) {\n const memorySubcommand = subArgs[0];\n const memoryStore = './memory/memory-store.json';\n\n // Extract namespace from flags or subArgs\n const namespace = flags?.namespace || flags?.ns || getNamespaceFromArgs(subArgs) || 'default';\n\n // Check for redaction flag\n const enableRedaction = flags?.redact || subArgs.includes('--redact') || subArgs.includes('--secure');\n\n // NEW: Detect memory mode (basic, reasoningbank, auto)\n const mode = await detectMemoryMode(flags, subArgs);\n\n // Helper to load memory data\n async function loadMemory() {\n try {\n const content = await fs.readFile(memoryStore, 'utf8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n }\n\n // Helper to save memory data\n async function saveMemory(data) {\n await fs.mkdir('./memory', { recursive: true });\n await fs.writeFile(memoryStore, JSON.stringify(data, null, 2, 'utf8'));\n }\n\n // NEW: Handle ReasoningBank-specific commands\n if (mode === 'reasoningbank' && ['init', 'status', 'consolidate', 'demo', 'test', 'benchmark'].includes(memorySubcommand)) {\n return await handleReasoningBankCommand(memorySubcommand, subArgs, flags);\n }\n\n // NEW: Handle new mode management commands\n if (['detect', 'mode', 'migrate'].includes(memorySubcommand)) {\n return await handleModeCommand(memorySubcommand, subArgs, flags);\n }\n\n // NEW: Delegate to ReasoningBank for regular commands if mode is set\n if (mode === 'reasoningbank' && ['store', 'query', 'list'].includes(memorySubcommand)) {\n return await handleReasoningBankCommand(memorySubcommand, subArgs, flags);\n }\n\n switch (memorySubcommand) {\n case 'store':\n await storeMemory(subArgs, loadMemory, saveMemory, namespace, enableRedaction);\n break;\n\n case 'query':\n await queryMemory(subArgs, loadMemory, namespace, enableRedaction);\n break;\n\n case 'stats':\n await showMemoryStats(loadMemory);\n break;\n\n case 'export':\n await exportMemory(subArgs, loadMemory, namespace);\n break;\n\n case 'import':\n await importMemory(subArgs, saveMemory, loadMemory);\n break;\n\n case 'clear':\n await clearMemory(subArgs, saveMemory, namespace);\n break;\n\n case 'list':\n await listNamespaces(loadMemory);\n break;\n\n default:\n showMemoryHelp();\n }\n}\n\nasync function storeMemory(subArgs, loadMemory, saveMemory, namespace, enableRedaction = false) {\n const key = subArgs[1];\n let value = subArgs.slice(2).join(' ');\n\n if (!key || !value) {\n printError('Usage: memory store <key> <value> [--namespace <ns>] [--redact]');\n return;\n }\n\n try {\n // Apply redaction if enabled\n let redactedValue = value;\n let securityWarnings = [];\n\n if (enableRedaction) {\n redactedValue = KeyRedactor.redact(value, true);\n const validation = KeyRedactor.validate(value);\n\n if (!validation.safe) {\n securityWarnings = validation.warnings;\n printWarning('š Redaction enabled: Sensitive data detected and redacted');\n securityWarnings.forEach(warning => console.log(` ā ļø ${warning}`));\n }\n } else {\n // Even if redaction is not explicitly enabled, validate and warn\n const validation = KeyRedactor.validate(value);\n if (!validation.safe) {\n printWarning('ā ļø Potential sensitive data detected! Use --redact flag for automatic redaction');\n validation.warnings.forEach(warning => console.log(` ā ļø ${warning}`));\n console.log(' š” Tip: Add --redact flag to automatically redact API keys');\n }\n }\n\n const data = await loadMemory();\n\n if (!data[namespace]) {\n data[namespace] = [];\n }\n\n // Remove existing entry with same key\n data[namespace] = data[namespace].filter((e) => e.key !== key);\n\n // Add new entry with redacted value\n data[namespace].push({\n key,\n value: redactedValue,\n namespace,\n timestamp: Date.now(),\n redacted: enableRedaction && securityWarnings.length > 0,\n });\n\n await saveMemory(data);\n printSuccess(enableRedaction && securityWarnings.length > 0 ? 'š Stored successfully (with redaction)' : 'ā
Stored successfully');\n console.log(`š Key: ${key}`);\n console.log(`š¦ Namespace: ${namespace}`);\n console.log(`š¾ Size: ${new TextEncoder().encode(redactedValue).length} bytes`);\n if (enableRedaction && securityWarnings.length > 0) {\n console.log(`š Security: ${securityWarnings.length} sensitive pattern(s) redacted`);\n }\n } catch (err) {\n printError(`Failed to store: ${err.message}`);\n }\n}\n\nasync function queryMemory(subArgs, loadMemory, namespace, enableRedaction = false) {\n const search = subArgs.slice(1).join(' ');\n\n if (!search) {\n printError('Usage: memory query <search> [--namespace <ns>] [--redact]');\n return;\n }\n\n try {\n const data = await loadMemory();\n const results = [];\n\n for (const [ns, entries] of Object.entries(data)) {\n if (namespace && ns !== namespace) continue;\n\n for (const entry of entries) {\n if (entry.key.includes(search) || entry.value.includes(search)) {\n results.push(entry);\n }\n }\n }\n\n if (results.length === 0) {\n printWarning('No results found');\n return;\n }\n\n printSuccess(`Found ${results.length} results:`);\n\n // Sort by timestamp (newest first)\n results.sort((a, b) => b.timestamp - a.timestamp);\n\n for (const entry of results.slice(0, 10)) {\n console.log(`\\nš ${entry.key}`);\n console.log(` Namespace: ${entry.namespace}`);\n\n // Apply redaction to displayed value if requested\n let displayValue = entry.value;\n if (enableRedaction) {\n displayValue = KeyRedactor.redact(displayValue, true);\n }\n\n console.log(\n ` Value: ${displayValue.substring(0, 100)}${displayValue.length > 100 ? '...' : ''}`,\n );\n console.log(` Stored: ${new Date(entry.timestamp).toLocaleString()}`);\n\n // Show redaction status\n if (entry.redacted) {\n console.log(` š Status: Redacted on storage`);\n } else if (enableRedaction) {\n console.log(` š Status: Redacted for display`);\n }\n }\n\n if (results.length > 10) {\n console.log(`\\n... and ${results.length - 10} more results`);\n }\n } catch (err) {\n printError(`Failed to query: ${err.message}`);\n }\n}\n\nasync function showMemoryStats(loadMemory) {\n try {\n const data = await loadMemory();\n let totalEntries = 0;\n const namespaceStats = {};\n\n for (const [namespace, entries] of Object.entries(data)) {\n namespaceStats[namespace] = entries.length;\n totalEntries += entries.length;\n }\n\n printSuccess('Memory Bank Statistics:');\n console.log(` Total Entries: ${totalEntries}`);\n console.log(` Namespaces: ${Object.keys(data).length}`);\n console.log(\n ` Size: ${(new TextEncoder().encode(JSON.stringify(data)).length / 1024).toFixed(2)} KB`,\n );\n\n if (Object.keys(data).length > 0) {\n console.log('\\nš Namespace Breakdown:');\n for (const [namespace, count] of Object.entries(namespaceStats)) {\n console.log(` ${namespace}: ${count} entries`);\n }\n }\n } catch (err) {\n printError(`Failed to get stats: ${err.message}`);\n }\n}\n\nasync function exportMemory(subArgs, loadMemory, namespace) {\n const filename = subArgs[1] || `memory-export-${Date.now()}.json`;\n\n try {\n const data = await loadMemory();\n\n let exportData = data;\n if (namespace) {\n exportData = { [namespace]: data[namespace] || [] };\n }\n\n await fs.writeFile(filename, JSON.stringify(exportData, null, 2, 'utf8'));\n printSuccess(`Memory exported to ${filename}`);\n\n let totalEntries = 0;\n for (const entries of Object.values(exportData)) {\n totalEntries += entries.length;\n }\n console.log(\n `š¦ Exported ${totalEntries} entries from ${Object.keys(exportData).length} namespace(s)`,\n );\n } catch (err) {\n printError(`Failed to export memory: ${err.message}`);\n }\n}\n\nasync function importMemory(subArgs, saveMemory, loadMemory) {\n const filename = subArgs[1];\n\n if (!filename) {\n printError('Usage: memory import <filename>');\n return;\n }\n\n try {\n const importContent = await fs.readFile(filename, 'utf8');\n const importData = JSON.parse(importContent);\n\n // Load existing memory\n const existingData = await loadMemory();\n\n // Merge imported data\n let totalImported = 0;\n for (const [namespace, entries] of Object.entries(importData)) {\n if (!existingData[namespace]) {\n existingData[namespace] = [];\n }\n\n // Add entries that don't already exist (by key)\n const existingKeys = new Set(existingData[namespace].map((e) => e.key));\n const newEntries = entries.filter((e) => !existingKeys.has(e.key));\n\n existingData[namespace].push(...newEntries);\n totalImported += newEntries.length;\n }\n\n await saveMemory(existingData);\n printSuccess(`Imported ${totalImported} new entries from ${filename}`);\n } catch (err) {\n printError(`Failed to import memory: ${err.message}`);\n }\n}\n\nasync function clearMemory(subArgs, saveMemory, namespace) {\n if (!namespace || namespace === 'default') {\n const nsFromArgs = getNamespaceFromArgs(subArgs);\n if (!nsFromArgs) {\n printError('Usage: memory clear --namespace <namespace>');\n printWarning('This will clear all entries in the specified namespace');\n return;\n }\n namespace = nsFromArgs;\n }\n\n try {\n // Helper to load memory data\n async function loadMemory() {\n try {\n const content = await fs.readFile('./memory/memory-store.json', 'utf8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n }\n \n const data = await loadMemory();\n\n if (!data[namespace]) {\n printWarning(`Namespace '${namespace}' does not exist`);\n return;\n }\n\n const entryCount = data[namespace].length;\n delete data[namespace];\n\n await saveMemory(data);\n printSuccess(`Cleared ${entryCount} entries from namespace '${namespace}'`);\n } catch (err) {\n printError(`Failed to clear memory: ${err.message}`);\n }\n}\n\nasync function listNamespaces(loadMemory) {\n try {\n const data = await loadMemory();\n const namespaces = Object.keys(data);\n\n if (namespaces.length === 0) {\n printWarning('No namespaces found');\n return;\n }\n\n printSuccess('Available namespaces:');\n for (const namespace of namespaces) {\n const count = data[namespace].length;\n console.log(` ${namespace} (${count} entries)`);\n }\n } catch (err) {\n printError(`Failed to list namespaces: ${err.message}`);\n }\n}\n\nfunction getNamespaceFromArgs(subArgs) {\n const namespaceIndex = subArgs.indexOf('--namespace');\n if (namespaceIndex !== -1 && namespaceIndex + 1 < subArgs.length) {\n return subArgs[namespaceIndex + 1];\n }\n\n const nsIndex = subArgs.indexOf('--ns');\n if (nsIndex !== -1 && nsIndex + 1 < subArgs.length) {\n return subArgs[nsIndex + 1];\n }\n\n return null;\n}\n\n// Helper to load memory data (needed for import function)\nasync function loadMemory() {\n try {\n const content = await fs.readFile('./memory/memory-store.json', 'utf8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n}\n\n// NEW: Mode detection function\nasync function detectMemoryMode(flags, subArgs) {\n // Explicit ReasoningBank flag takes precedence\n if (flags?.reasoningbank || flags?.rb || subArgs.includes('--reasoningbank') || subArgs.includes('--rb')) {\n return 'reasoningbank';\n }\n\n // Auto mode: detect if ReasoningBank is initialized\n if (flags?.auto || subArgs.includes('--auto')) {\n const initialized = await isReasoningBankInitialized();\n return initialized ? 'reasoningbank' : 'basic';\n }\n\n // Explicit basic mode flag\n if (flags?.basic || subArgs.includes('--basic')) {\n return 'basic';\n }\n\n // Default: AUTO MODE (smart selection with JSON fallback)\n // Automatically use ReasoningBank if initialized, otherwise fall back to basic mode\n const initialized = await isReasoningBankInitialized();\n return initialized ? 'reasoningbank' : 'basic';\n}\n\n// NEW: Check if ReasoningBank is initialized\nasync function isReasoningBankInitialized() {\n try {\n // Check if .swarm/memory.db exists\n const dbPath = '.swarm/memory.db';\n await fs.access(dbPath);\n return true;\n } catch {\n return false;\n }\n}\n\n// NEW: Handle ReasoningBank commands\nasync function handleReasoningBankCommand(command, subArgs, flags) {\n const initialized = await isReasoningBankInitialized();\n\n // Lazy load the adapter (ES modules)\n const { initializeReasoningBank, storeMemory, queryMemories, listMemories, getStatus, checkReasoningBankTables, migrateReasoningBank, cleanup } = await import('../../reasoningbank/reasoningbank-adapter.js');\n\n // Special handling for 'init' command\n if (command === 'init') {\n const dbPath = '.swarm/memory.db';\n\n if (initialized) {\n // Database exists - check if migration is needed\n printInfo('š Checking existing database for ReasoningBank schema...\\n');\n\n try {\n // Set the database path for ReasoningBank\n process.env.CLAUDE_FLOW_DB_PATH = dbPath;\n\n const tableCheck = await checkReasoningBankTables();\n\n if (tableCheck.exists) {\n printSuccess('ā
ReasoningBank already complete');\n console.log('Database: .swarm/memory.db');\n console.log('All ReasoningBank tables present\\n');\n console.log('Use --reasoningbank flag with memory commands to enable AI features');\n return;\n }\n\n // Missing tables found - run migration\n console.log(`š Migrating database: ${tableCheck.missingTables.length} tables missing`);\n console.log(` Missing: ${tableCheck.missingTables.join(', ')}\\n`);\n\n const migrationResult = await migrateReasoningBank();\n\n if (migrationResult.success) {\n printSuccess(`ā Migration complete: added ${migrationResult.addedTables?.length || 0} tables`);\n console.log('\\nNext steps:');\n console.log(' 1. Store memories: memory store key \"value\" --reasoningbank');\n console.log(' 2. Query memories: memory query \"search\" --reasoningbank');\n console.log(' 3. Check status: memory status --reasoningbank');\n } else {\n printError(`ā Migration failed: ${migrationResult.message}`);\n console.log('Try running: init --force to reinitialize');\n }\n } catch (error) {\n printError('ā Migration check failed');\n console.error(error.message);\n console.log('\\nTry running: init --force to reinitialize');\n } finally {\n // Cleanup after migration check\n cleanup();\n // Force exit to prevent hanging from embedding cache timers\n setTimeout(() => process.exit(0), 100);\n }\n return;\n }\n\n // Fresh initialization\n printInfo('š§ Initializing ReasoningBank...');\n console.log('This will create: .swarm/memory.db\\n');\n\n try {\n await initializeReasoningBank();\n printSuccess('ā
ReasoningBank initialized successfully!');\n console.log('\\nNext steps:');\n console.log(' 1. Store memories: memory store key \"value\" --reasoningbank');\n console.log(' 2. Query memories: memory query \"search\" --reasoningbank');\n console.log(' 3. Check status: memory status --reasoningbank');\n } catch (error) {\n printError('ā Failed to initialize ReasoningBank');\n console.error(error.message);\n } finally {\n // Cleanup after init\n cleanup();\n // Force exit to prevent hanging from embedding cache timers\n setTimeout(() => process.exit(0), 100);\n }\n return;\n }\n\n // All other commands require initialization\n if (!initialized) {\n printError('ā ReasoningBank not initialized');\n console.log('\\nTo use ReasoningBank mode, first run:');\n console.log(' memory init --reasoningbank\\n');\n return;\n }\n\n printInfo(`š§ Using ReasoningBank mode...`);\n\n try {\n // Handle different commands\n switch (command) {\n case 'store':\n await handleReasoningBankStore(subArgs, flags, storeMemory);\n break;\n\n case 'query':\n await handleReasoningBankQuery(subArgs, flags, queryMemories);\n break;\n\n case 'list':\n await handleReasoningBankList(subArgs, flags, listMemories);\n break;\n\n case 'status':\n await handleReasoningBankStatus(getStatus);\n break;\n\n case 'consolidate':\n case 'demo':\n case 'test':\n case 'benchmark':\n // These still use CLI commands\n const cmd = `npx agentic-flow reasoningbank ${command}`;\n const { stdout } = await execAsync(cmd, { timeout: 60000 });\n if (stdout) console.log(stdout);\n break;\n\n default:\n printError(`Unknown ReasoningBank command: ${command}`);\n }\n } catch (error) {\n printError(`ā ReasoningBank command failed`);\n console.error(error.message);\n } finally {\n // Always cleanup database connection\n cleanup();\n\n // Force process exit after cleanup (embedding cache timers prevent natural exit)\n // This is necessary because agentic-flow's embedding cache uses setTimeout\n // which keeps the event loop alive\n setTimeout(() => {\n process.exit(0);\n }, 100);\n }\n}\n\n// NEW: Handle ReasoningBank store\nasync function handleReasoningBankStore(subArgs, flags, storeMemory) {\n const key = subArgs[1];\n const value = subArgs.slice(2).join(' ');\n\n if (!key || !value) {\n printError('Usage: memory store <key> <value> --reasoningbank');\n return;\n }\n\n try {\n const namespace = flags?.namespace || flags?.ns || getArgValue(subArgs, '--namespace') || 'default';\n\n const memoryId = await storeMemory(key, value, {\n namespace,\n agent: 'memory-agent',\n domain: namespace,\n });\n\n printSuccess('ā
Stored successfully in ReasoningBank');\n console.log(`š Key: ${key}`);\n console.log(`š§ Memory ID: ${memoryId}`);\n console.log(`š¦ Namespace: ${namespace}`);\n console.log(`š¾ Size: ${new TextEncoder().encode(value).length} bytes`);\n console.log(`š Semantic search: enabled`);\n } catch (error) {\n printError(`Failed to store: ${error.message}`);\n }\n}\n\n// NEW: Handle ReasoningBank query\nasync function handleReasoningBankQuery(subArgs, flags, queryMemories) {\n const search = subArgs.slice(1).join(' ');\n\n if (!search) {\n printError('Usage: memory query <search> --reasoningbank');\n return;\n }\n\n try {\n const namespace = flags?.namespace || flags?.ns || getArgValue(subArgs, '--namespace');\n const results = await queryMemories(search, {\n domain: namespace || 'general',\n limit: 10,\n });\n\n if (results.length === 0) {\n printWarning('No results found');\n return;\n }\n\n printSuccess(`Found ${results.length} results (semantic search):`);\n\n for (const entry of results) {\n console.log(`\\nš ${entry.key}`);\n console.log(` Namespace: ${entry.namespace}`);\n console.log(` Value: ${entry.value.substring(0, 100)}${entry.value.length > 100 ? '...' : ''}`);\n console.log(` Confidence: ${(entry.confidence * 100).toFixed(1)}%`);\n console.log(` Usage: ${entry.usage_count} times`);\n if (entry.score) {\n console.log(` Match Score: ${(entry.score * 100).toFixed(1)}%`);\n }\n console.log(` Stored: ${new Date(entry.created_at).toLocaleString()}`);\n }\n } catch (error) {\n printError(`Failed to query: ${error.message}`);\n }\n}\n\n// NEW: Handle ReasoningBank list\nasync function handleReasoningBankList(subArgs, flags, listMemories) {\n try {\n const sort = flags?.sort || getArgValue(subArgs, '--sort') || 'created_at';\n const limit = parseInt(flags?.limit || getArgValue(subArgs, '--limit') || '10');\n\n const results = await listMemories({ sort, limit });\n\n if (results.length === 0) {\n printWarning('No memories found');\n return;\n }\n\n printSuccess(`ReasoningBank memories (${results.length} shown):`);\n\n for (const entry of results) {\n console.log(`\\nš ${entry.key}`);\n console.log(` Value: ${entry.value.substring(0, 80)}${entry.value.length > 80 ? '...' : ''}`);\n console.log(` Confidence: ${(entry.confidence * 100).toFixed(1)}% | Usage: ${entry.usage_count}`);\n }\n } catch (error) {\n printError(`Failed to list: ${error.message}`);\n }\n}\n\n// NEW: Handle ReasoningBank status\nasync function handleReasoningBankStatus(getStatus) {\n try {\n const stats = await getStatus();\n\n printSuccess('š ReasoningBank Status:');\n console.log(` Total memories: ${stats.total_memories}`);\n console.log(` Average confidence: ${(stats.avg_confidence * 100).toFixed(1)}%`);\n console.log(` Total usage: ${stats.total_usage}`);\n console.log(` Embeddings: ${stats.total_embeddings}`);\n console.log(` Trajectories: ${stats.total_trajectories}`);\n } catch (error) {\n printError(`Failed to get status: ${error.message}`);\n }\n}\n\n// NEW: Build agentic-flow reasoningbank command\nfunction buildReasoningBankCommand(command, subArgs, flags) {\n const parts = ['npx', 'agentic-flow', 'reasoningbank'];\n\n // Map memory commands to reasoningbank commands\n const commandMap = {\n store: 'store',\n query: 'query',\n list: 'list',\n status: 'status',\n consolidate: 'consolidate',\n demo: 'demo',\n test: 'test',\n benchmark: 'benchmark',\n };\n\n parts.push(commandMap[command] || command);\n\n // Add arguments (skip the command itself)\n const args = subArgs.slice(1);\n args.forEach((arg) => {\n if (!arg.startsWith('--reasoningbank') && !arg.startsWith('--rb') && !arg.startsWith('--auto')) {\n parts.push(`\"${arg}\"`);\n }\n });\n\n // Add required --agent parameter\n parts.push('--agent', 'memory-agent');\n\n return parts.join(' ');\n}\n\n// NEW: Handle mode management commands\nasync function handleModeCommand(command, subArgs, flags) {\n switch (command) {\n case 'detect':\n await detectModes();\n break;\n\n case 'mode':\n await showCurrentMode();\n break;\n\n case 'migrate':\n await migrateMemory(subArgs, flags);\n break;\n\n default:\n printError(`Unknown mode command: ${command}`);\n }\n}\n\n// NEW: Detect and show available memory modes\nasync function detectModes() {\n printInfo('š Detecting memory modes...\\n');\n\n // Check basic mode\n const basicAvailable = await checkBasicMode();\n console.log(basicAvailable ? 'ā
Basic Mode (active)' : 'ā Basic Mode (unavailable)');\n if (basicAvailable) {\n console.log(' Location: ./memory/memory-store.json');\n console.log(' Features: Simple key-value storage, fast');\n }\n\n console.log('');\n\n // Check ReasoningBank mode\n const rbAvailable = await isReasoningBankInitialized();\n console.log(rbAvailable ? 'ā
ReasoningBank Mode (available)' : 'ā ļø ReasoningBank Mode (not initialized)');\n if (rbAvailable) {\n console.log(' Location: .swarm/memory.db');\n console.log(' Features: AI-powered semantic search, learning');\n } else {\n console.log(' To enable: memory init --reasoningbank');\n }\n\n console.log('\\nš” Usage:');\n console.log(' Basic: memory store key \"value\"');\n console.log(' ReasoningBank: memory store key \"value\" --reasoningbank');\n console.log(' Auto-detect: memory query search --auto');\n}\n\n// NEW: Check if basic mode is available\nasync function checkBasicMode() {\n try {\n const memoryDir = './memory';\n await fs.access(memoryDir);\n return true;\n } catch {\n // Create directory if it doesn't exist\n try {\n await fs.mkdir(memoryDir, { recursive: true });\n return true;\n } catch {\n return false;\n }\n }\n}\n\n// NEW: Show current default mode\nasync function showCurrentMode() {\n const rbInitialized = await isReasoningBankInitialized();\n\n printInfo('š Current Memory Configuration:\\n');\n console.log('Default Mode: AUTO (smart selection with JSON fallback)');\n console.log('Available Modes:');\n console.log(' ⢠Basic Mode: Always available (JSON storage)');\n console.log(` ⢠ReasoningBank Mode: ${rbInitialized ? 'Initialized ā
(will be used by default)' : 'Not initialized ā ļø (JSON fallback active)'}`);\n\n console.log('\\nš” Mode Behavior:');\n console.log(' (no flag) ā AUTO: Use ReasoningBank if initialized, else JSON');\n console.log(' --reasoningbank or --rb ā Force ReasoningBank mode');\n console.log(' --basic ā Force JSON mode');\n console.log(' --auto ā Same as default (explicit)');\n}\n\n// NEW: Migrate memory between modes\nasync function migrateMemory(subArgs, flags) {\n const targetMode = flags?.to || getArgValue(subArgs, '--to');\n\n if (!targetMode || !['basic', 'reasoningbank'].includes(targetMode)) {\n printError('Usage: memory migrate --to <basic|reasoningbank>');\n return;\n }\n\n printInfo(`š Migrating to ${targetMode} mode...\\n`);\n\n if (targetMode === 'reasoningbank') {\n // Migrate basic ā ReasoningBank\n const rbInitialized = await isReasoningBankInitialized();\n if (!rbInitialized) {\n printError('ā ReasoningBank not initialized');\n console.log('First run: memory init --reasoningbank\\n');\n return;\n }\n\n printWarning('ā ļø Migration from basic to ReasoningBank is not yet implemented');\n console.log('This feature is coming in v2.7.1\\n');\n console.log('For now, you can:');\n console.log(' 1. Export basic memory: memory export backup.json');\n console.log(' 2. Manually import to ReasoningBank');\n } else {\n // Migrate ReasoningBank ā basic\n printWarning('ā ļø Migration from ReasoningBank to basic is not yet implemented');\n console.log('This feature is coming in v2.7.1\\n');\n }\n}\n\n// Helper to get argument value\nfunction getArgValue(args, flag) {\n const index = args.indexOf(flag);\n if (index !== -1 && index + 1 < args.length) {\n return args[index + 1];\n }\n return null;\n}\n\nfunction showMemoryHelp() {\n console.log('Memory commands:');\n console.log(' store <key> <value> Store a key-value pair');\n console.log(' query <search> Search for entries');\n console.log(' stats Show memory statistics');\n console.log(' export [filename] Export memory to file');\n console.log(' import <filename> Import memory from file');\n console.log(' clear --namespace <ns> Clear a namespace');\n console.log(' list List all namespaces');\n console.log();\n console.log('š§ ReasoningBank Commands (NEW in v2.7.0):');\n console.log(' init --reasoningbank Initialize ReasoningBank (AI-powered memory)');\n console.log(' status --reasoningbank Show ReasoningBank statistics');\n console.log(' detect Show available memory modes');\n console.log(' mode Show current memory configuration');\n console.log(' migrate --to <mode> Migrate between basic/reasoningbank');\n console.log();\n console.log('Options:');\n console.log(' --namespace <ns> Specify namespace for operations');\n console.log(' --ns <ns> Short form of --namespace');\n console.log(' --redact š Enable API key redaction (security feature)');\n console.log(' --secure Alias for --redact');\n console.log();\n console.log('šÆ Mode Selection:');\n console.log(' (no flag) AUTO MODE (default) - Uses ReasoningBank if initialized, else JSON fallback');\n console.log(' --reasoningbank, --rb Force ReasoningBank mode (AI-powered)');\n console.log(' --basic Force Basic mode (JSON storage)');\n console.log(' --auto Explicit auto-detect (same as default)');\n console.log();\n console.log('š Security Features (v2.6.0):');\n console.log(' API Key Protection: Automatically detects and redacts sensitive data');\n console.log(' Patterns Detected: Anthropic, OpenRouter, Gemini, Bearer tokens, etc.');\n console.log(' Auto-Validation: Warns when storing unredacted sensitive data');\n console.log(' Display Redaction: Redact sensitive data when querying with --redact');\n console.log();\n console.log('Examples:');\n console.log(' # Basic mode (default - backward compatible)');\n console.log(' memory store previous_work \"Research findings from yesterday\"');\n console.log(' memory store api_config \"key=sk-ant-...\" --redact # š Redacts API key');\n console.log(' memory query research --namespace sparc');\n console.log();\n console.log(' # ReasoningBank mode (AI-powered, opt-in)');\n console.log(' memory init --reasoningbank # One-time setup');\n console.log(' memory store api_pattern \"Always use env vars\" --reasoningbank');\n console.log(' memory query \"API configuration\" --reasoningbank # Semantic search!');\n console.log(' memory status --reasoningbank # Show AI metrics');\n console.log();\n console.log(' # Auto-detect mode (smart selection)');\n console.log(' memory query config --auto # Uses ReasoningBank if available');\n console.log();\n console.log(' # Mode management');\n console.log(' memory detect # Show available modes');\n console.log(' memory mode # Show current configuration');\n console.log();\n console.log('š” Tips:');\n console.log(' ⢠AUTO MODE (default): Automatically uses best available storage');\n console.log(' ⢠ReasoningBank: AI-powered semantic search (learns from patterns)');\n console.log(' ⢠JSON fallback: Always available, fast, simple key-value storage');\n console.log(' ⢠Initialize ReasoningBank once: \"memory init --reasoningbank\"');\n console.log(' ⢠Always use --redact when storing API keys or secrets!');\n}\n"],"names":["printSuccess","printError","printWarning","printInfo","promises","fs","KeyRedactor","exec","promisify","execAsync","memoryCommand","subArgs","flags","memorySubcommand","memoryStore","namespace","ns","getNamespaceFromArgs","enableRedaction","redact","includes","mode","detectMemoryMode","loadMemory","content","readFile","JSON","parse","saveMemory","data","mkdir","recursive","writeFile","stringify","handleReasoningBankCommand","handleModeCommand","storeMemory","queryMemory","showMemoryStats","exportMemory","importMemory","clearMemory","listNamespaces","showMemoryHelp","key","value","slice","join","redactedValue","securityWarnings","validation","validate","safe","warnings","forEach","warning","console","log","filter","e","push","timestamp","Date","now","redacted","length","TextEncoder","encode","err","message","search","results","entries","Object","entry","sort","a","b","displayValue","substring","toLocaleString","totalEntries","namespaceStats","keys","toFixed","count","filename","exportData","values","importContent","importData","existingData","totalImported","existingKeys","Set","map","newEntries","has","nsFromArgs","entryCount","namespaces","namespaceIndex","indexOf","nsIndex","reasoningbank","rb","auto","initialized","isReasoningBankInitialized","basic","dbPath","access","command","initializeReasoningBank","queryMemories","listMemories","getStatus","checkReasoningBankTables","migrateReasoningBank","cleanup","process","env","CLAUDE_FLOW_DB_PATH","tableCheck","exists","missingTables","migrationResult","success","addedTables","error","setTimeout","exit","handleReasoningBankStore","handleReasoningBankQuery","handleReasoningBankList","handleReasoningBankStatus","cmd","stdout","timeout","getArgValue","memoryId","agent","domain","limit","confidence","usage_count","score","created_at","parseInt","stats","total_memories","avg_confidence","total_usage","total_embeddings","total_trajectories","buildReasoningBankCommand","parts","commandMap","store","query","list","status","consolidate","demo","test","benchmark","args","arg","startsWith","detectModes","showCurrentMode","migrateMemory","basicAvailable","checkBasicMode","rbAvailable","memoryDir","rbInitialized","targetMode","to","flag","index"],"mappings":"AACA,SAASA,YAAY,EAAEC,UAAU,EAAEC,YAAY,EAAEC,SAAS,QAAQ,cAAc;AAChF,SAASC,YAAYC,EAAE,QAAQ,KAAK;AAGpC,SAASC,WAAW,QAAQ,8BAA8B;AAC1D,SAASC,IAAI,QAAQ,gBAAgB;AACrC,SAASC,SAAS,QAAQ,OAAO;AAEjC,MAAMC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C;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;AACd"}
|
|
1
|
+
{"version":3,"sources":["../../../../src/cli/simple-commands/memory.js"],"sourcesContent":["// memory.js - Memory management commands\nimport { printSuccess, printError, printWarning, printInfo } from '../utils.js';\nimport { promises as fs } from 'fs';\nimport { cwd, exit, existsSync } from '../node-compat.js';\nimport { getUnifiedMemory } from '../../memory/unified-memory-manager.js';\nimport { KeyRedactor } from '../../utils/key-redactor.js';\nimport { exec } from 'child_process';\nimport { promisify } from 'util';\n\nconst execAsync = promisify(exec);\n\nexport async function memoryCommand(subArgs, flags) {\n const memorySubcommand = subArgs[0];\n const memoryStore = './memory/memory-store.json';\n\n // Extract namespace from flags or subArgs\n const namespace = flags?.namespace || flags?.ns || getNamespaceFromArgs(subArgs) || 'default';\n\n // Check for redaction flag\n const enableRedaction = flags?.redact || subArgs.includes('--redact') || subArgs.includes('--secure');\n\n // NEW: Detect memory mode (basic, reasoningbank, auto)\n const mode = await detectMemoryMode(flags, subArgs);\n\n // Helper to load memory data\n async function loadMemory() {\n try {\n const content = await fs.readFile(memoryStore, 'utf8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n }\n\n // Helper to save memory data\n async function saveMemory(data) {\n await fs.mkdir('./memory', { recursive: true });\n await fs.writeFile(memoryStore, JSON.stringify(data, null, 2, 'utf8'));\n }\n\n // NEW: Handle ReasoningBank-specific commands\n if (mode === 'reasoningbank' && ['init', 'status', 'consolidate', 'demo', 'test', 'benchmark'].includes(memorySubcommand)) {\n return await handleReasoningBankCommand(memorySubcommand, subArgs, flags);\n }\n\n // NEW: Handle new mode management commands\n if (['detect', 'mode', 'migrate'].includes(memorySubcommand)) {\n return await handleModeCommand(memorySubcommand, subArgs, flags);\n }\n\n // NEW: Delegate to ReasoningBank for regular commands if mode is set\n if (mode === 'reasoningbank' && ['store', 'query', 'list'].includes(memorySubcommand)) {\n return await handleReasoningBankCommand(memorySubcommand, subArgs, flags);\n }\n\n switch (memorySubcommand) {\n case 'store':\n await storeMemory(subArgs, loadMemory, saveMemory, namespace, enableRedaction);\n break;\n\n case 'query':\n await queryMemory(subArgs, loadMemory, namespace, enableRedaction);\n break;\n\n case 'stats':\n await showMemoryStats(loadMemory);\n break;\n\n case 'export':\n await exportMemory(subArgs, loadMemory, namespace);\n break;\n\n case 'import':\n await importMemory(subArgs, saveMemory, loadMemory);\n break;\n\n case 'clear':\n await clearMemory(subArgs, saveMemory, namespace);\n break;\n\n case 'list':\n await listNamespaces(loadMemory);\n break;\n\n default:\n showMemoryHelp();\n }\n}\n\nasync function storeMemory(subArgs, loadMemory, saveMemory, namespace, enableRedaction = false) {\n const key = subArgs[1];\n let value = subArgs.slice(2).join(' ');\n\n if (!key || !value) {\n printError('Usage: memory store <key> <value> [--namespace <ns>] [--redact]');\n return;\n }\n\n try {\n // Apply redaction if enabled\n let redactedValue = value;\n let securityWarnings = [];\n\n if (enableRedaction) {\n redactedValue = KeyRedactor.redact(value, true);\n const validation = KeyRedactor.validate(value);\n\n if (!validation.safe) {\n securityWarnings = validation.warnings;\n printWarning('š Redaction enabled: Sensitive data detected and redacted');\n securityWarnings.forEach(warning => console.log(` ā ļø ${warning}`));\n }\n } else {\n // Even if redaction is not explicitly enabled, validate and warn\n const validation = KeyRedactor.validate(value);\n if (!validation.safe) {\n printWarning('ā ļø Potential sensitive data detected! Use --redact flag for automatic redaction');\n validation.warnings.forEach(warning => console.log(` ā ļø ${warning}`));\n console.log(' š” Tip: Add --redact flag to automatically redact API keys');\n }\n }\n\n const data = await loadMemory();\n\n if (!data[namespace]) {\n data[namespace] = [];\n }\n\n // Remove existing entry with same key\n data[namespace] = data[namespace].filter((e) => e.key !== key);\n\n // Add new entry with redacted value\n data[namespace].push({\n key,\n value: redactedValue,\n namespace,\n timestamp: Date.now(),\n redacted: enableRedaction && securityWarnings.length > 0,\n });\n\n await saveMemory(data);\n printSuccess(enableRedaction && securityWarnings.length > 0 ? 'š Stored successfully (with redaction)' : 'ā
Stored successfully');\n console.log(`š Key: ${key}`);\n console.log(`š¦ Namespace: ${namespace}`);\n console.log(`š¾ Size: ${new TextEncoder().encode(redactedValue).length} bytes`);\n if (enableRedaction && securityWarnings.length > 0) {\n console.log(`š Security: ${securityWarnings.length} sensitive pattern(s) redacted`);\n }\n } catch (err) {\n printError(`Failed to store: ${err.message}`);\n }\n}\n\nasync function queryMemory(subArgs, loadMemory, namespace, enableRedaction = false) {\n const search = subArgs.slice(1).join(' ');\n\n if (!search) {\n printError('Usage: memory query <search> [--namespace <ns>] [--redact]');\n return;\n }\n\n try {\n const data = await loadMemory();\n const results = [];\n\n for (const [ns, entries] of Object.entries(data)) {\n if (namespace && ns !== namespace) continue;\n\n for (const entry of entries) {\n if (entry.key.includes(search) || entry.value.includes(search)) {\n results.push(entry);\n }\n }\n }\n\n if (results.length === 0) {\n printWarning('No results found');\n return;\n }\n\n printSuccess(`Found ${results.length} results:`);\n\n // Sort by timestamp (newest first)\n results.sort((a, b) => b.timestamp - a.timestamp);\n\n for (const entry of results.slice(0, 10)) {\n console.log(`\\nš ${entry.key}`);\n console.log(` Namespace: ${entry.namespace}`);\n\n // Apply redaction to displayed value if requested\n let displayValue = entry.value;\n if (enableRedaction) {\n displayValue = KeyRedactor.redact(displayValue, true);\n }\n\n console.log(\n ` Value: ${displayValue.substring(0, 100)}${displayValue.length > 100 ? '...' : ''}`,\n );\n console.log(` Stored: ${new Date(entry.timestamp).toLocaleString()}`);\n\n // Show redaction status\n if (entry.redacted) {\n console.log(` š Status: Redacted on storage`);\n } else if (enableRedaction) {\n console.log(` š Status: Redacted for display`);\n }\n }\n\n if (results.length > 10) {\n console.log(`\\n... and ${results.length - 10} more results`);\n }\n } catch (err) {\n printError(`Failed to query: ${err.message}`);\n }\n}\n\nasync function showMemoryStats(loadMemory) {\n try {\n const data = await loadMemory();\n let totalEntries = 0;\n const namespaceStats = {};\n\n for (const [namespace, entries] of Object.entries(data)) {\n namespaceStats[namespace] = entries.length;\n totalEntries += entries.length;\n }\n\n printSuccess('Memory Bank Statistics:');\n console.log(` Total Entries: ${totalEntries}`);\n console.log(` Namespaces: ${Object.keys(data).length}`);\n console.log(\n ` Size: ${(new TextEncoder().encode(JSON.stringify(data)).length / 1024).toFixed(2)} KB`,\n );\n\n if (Object.keys(data).length > 0) {\n console.log('\\nš Namespace Breakdown:');\n for (const [namespace, count] of Object.entries(namespaceStats)) {\n console.log(` ${namespace}: ${count} entries`);\n }\n }\n } catch (err) {\n printError(`Failed to get stats: ${err.message}`);\n }\n}\n\nasync function exportMemory(subArgs, loadMemory, namespace) {\n const filename = subArgs[1] || `memory-export-${Date.now()}.json`;\n\n try {\n const data = await loadMemory();\n\n let exportData = data;\n if (namespace) {\n exportData = { [namespace]: data[namespace] || [] };\n }\n\n await fs.writeFile(filename, JSON.stringify(exportData, null, 2, 'utf8'));\n printSuccess(`Memory exported to ${filename}`);\n\n let totalEntries = 0;\n for (const entries of Object.values(exportData)) {\n totalEntries += entries.length;\n }\n console.log(\n `š¦ Exported ${totalEntries} entries from ${Object.keys(exportData).length} namespace(s)`,\n );\n } catch (err) {\n printError(`Failed to export memory: ${err.message}`);\n }\n}\n\nasync function importMemory(subArgs, saveMemory, loadMemory) {\n const filename = subArgs[1];\n\n if (!filename) {\n printError('Usage: memory import <filename>');\n return;\n }\n\n try {\n const importContent = await fs.readFile(filename, 'utf8');\n const importData = JSON.parse(importContent);\n\n // Load existing memory\n const existingData = await loadMemory();\n\n // Merge imported data\n let totalImported = 0;\n for (const [namespace, entries] of Object.entries(importData)) {\n if (!existingData[namespace]) {\n existingData[namespace] = [];\n }\n\n // Add entries that don't already exist (by key)\n const existingKeys = new Set(existingData[namespace].map((e) => e.key));\n const newEntries = entries.filter((e) => !existingKeys.has(e.key));\n\n existingData[namespace].push(...newEntries);\n totalImported += newEntries.length;\n }\n\n await saveMemory(existingData);\n printSuccess(`Imported ${totalImported} new entries from ${filename}`);\n } catch (err) {\n printError(`Failed to import memory: ${err.message}`);\n }\n}\n\nasync function clearMemory(subArgs, saveMemory, namespace) {\n if (!namespace || namespace === 'default') {\n const nsFromArgs = getNamespaceFromArgs(subArgs);\n if (!nsFromArgs) {\n printError('Usage: memory clear --namespace <namespace>');\n printWarning('This will clear all entries in the specified namespace');\n return;\n }\n namespace = nsFromArgs;\n }\n\n try {\n // Helper to load memory data\n async function loadMemory() {\n try {\n const content = await fs.readFile('./memory/memory-store.json', 'utf8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n }\n \n const data = await loadMemory();\n\n if (!data[namespace]) {\n printWarning(`Namespace '${namespace}' does not exist`);\n return;\n }\n\n const entryCount = data[namespace].length;\n delete data[namespace];\n\n await saveMemory(data);\n printSuccess(`Cleared ${entryCount} entries from namespace '${namespace}'`);\n } catch (err) {\n printError(`Failed to clear memory: ${err.message}`);\n }\n}\n\nasync function listNamespaces(loadMemory) {\n try {\n const data = await loadMemory();\n const namespaces = Object.keys(data);\n\n if (namespaces.length === 0) {\n printWarning('No namespaces found');\n return;\n }\n\n printSuccess('Available namespaces:');\n for (const namespace of namespaces) {\n const count = data[namespace].length;\n console.log(` ${namespace} (${count} entries)`);\n }\n } catch (err) {\n printError(`Failed to list namespaces: ${err.message}`);\n }\n}\n\nfunction getNamespaceFromArgs(subArgs) {\n const namespaceIndex = subArgs.indexOf('--namespace');\n if (namespaceIndex !== -1 && namespaceIndex + 1 < subArgs.length) {\n return subArgs[namespaceIndex + 1];\n }\n\n const nsIndex = subArgs.indexOf('--ns');\n if (nsIndex !== -1 && nsIndex + 1 < subArgs.length) {\n return subArgs[nsIndex + 1];\n }\n\n return null;\n}\n\n// Helper to load memory data (needed for import function)\nasync function loadMemory() {\n try {\n const content = await fs.readFile('./memory/memory-store.json', 'utf8');\n return JSON.parse(content);\n } catch {\n return {};\n }\n}\n\n// NEW: Mode detection function\nasync function detectMemoryMode(flags, subArgs) {\n // Explicit ReasoningBank flag takes precedence\n if (flags?.reasoningbank || flags?.rb || subArgs.includes('--reasoningbank') || subArgs.includes('--rb')) {\n return 'reasoningbank';\n }\n\n // Auto mode: detect if ReasoningBank is initialized\n if (flags?.auto || subArgs.includes('--auto')) {\n const initialized = await isReasoningBankInitialized();\n return initialized ? 'reasoningbank' : 'basic';\n }\n\n // Explicit basic mode flag\n if (flags?.basic || subArgs.includes('--basic')) {\n return 'basic';\n }\n\n // Default: AUTO MODE with SQLite preference\n // Try to use ReasoningBank (SQLite) by default, initialize if needed\n const initialized = await isReasoningBankInitialized();\n\n if (initialized) {\n return 'reasoningbank';\n }\n\n // Not initialized yet - try to auto-initialize on first use\n try {\n const { initializeReasoningBank } = await import('../../reasoningbank/reasoningbank-adapter.js');\n await initializeReasoningBank();\n printInfo('šļø Initialized SQLite backend (.swarm/memory.db)');\n return 'reasoningbank';\n } catch (error) {\n // SQLite initialization failed - fall back to JSON\n printWarning(`ā ļø SQLite unavailable, using JSON fallback`);\n printWarning(` Reason: ${error.message}`);\n return 'basic';\n }\n}\n\n// NEW: Check if ReasoningBank is initialized\nasync function isReasoningBankInitialized() {\n try {\n // Check if .swarm/memory.db exists\n const dbPath = '.swarm/memory.db';\n await fs.access(dbPath);\n return true;\n } catch {\n return false;\n }\n}\n\n// NEW: Handle ReasoningBank commands\nasync function handleReasoningBankCommand(command, subArgs, flags) {\n const initialized = await isReasoningBankInitialized();\n\n // Lazy load the adapter (ES modules)\n const { initializeReasoningBank, storeMemory, queryMemories, listMemories, getStatus, checkReasoningBankTables, migrateReasoningBank, cleanup } = await import('../../reasoningbank/reasoningbank-adapter.js');\n\n // Special handling for 'init' command\n if (command === 'init') {\n const dbPath = '.swarm/memory.db';\n\n if (initialized) {\n // Database exists - check if migration is needed\n printInfo('š Checking existing database for ReasoningBank schema...\\n');\n\n try {\n // Set the database path for ReasoningBank\n process.env.CLAUDE_FLOW_DB_PATH = dbPath;\n\n const tableCheck = await checkReasoningBankTables();\n\n if (tableCheck.exists) {\n printSuccess('ā
ReasoningBank already complete');\n console.log('Database: .swarm/memory.db');\n console.log('All ReasoningBank tables present\\n');\n console.log('Use --reasoningbank flag with memory commands to enable AI features');\n return;\n }\n\n // Missing tables found - run migration\n console.log(`š Migrating database: ${tableCheck.missingTables.length} tables missing`);\n console.log(` Missing: ${tableCheck.missingTables.join(', ')}\\n`);\n\n const migrationResult = await migrateReasoningBank();\n\n if (migrationResult.success) {\n printSuccess(`ā Migration complete: added ${migrationResult.addedTables?.length || 0} tables`);\n console.log('\\nNext steps:');\n console.log(' 1. Store memories: memory store key \"value\" --reasoningbank');\n console.log(' 2. Query memories: memory query \"search\" --reasoningbank');\n console.log(' 3. Check status: memory status --reasoningbank');\n } else {\n printError(`ā Migration failed: ${migrationResult.message}`);\n console.log('Try running: init --force to reinitialize');\n }\n } catch (error) {\n printError('ā Migration check failed');\n console.error(error.message);\n console.log('\\nTry running: init --force to reinitialize');\n } finally {\n // Cleanup after migration check\n cleanup();\n // Force exit to prevent hanging from embedding cache timers\n setTimeout(() => process.exit(0), 100);\n }\n return;\n }\n\n // Fresh initialization\n printInfo('š§ Initializing ReasoningBank...');\n console.log('This will create: .swarm/memory.db\\n');\n\n try {\n await initializeReasoningBank();\n printSuccess('ā
ReasoningBank initialized successfully!');\n console.log('\\nNext steps:');\n console.log(' 1. Store memories: memory store key \"value\" --reasoningbank');\n console.log(' 2. Query memories: memory query \"search\" --reasoningbank');\n console.log(' 3. Check status: memory status --reasoningbank');\n } catch (error) {\n printError('ā Failed to initialize ReasoningBank');\n console.error(error.message);\n } finally {\n // Cleanup after init\n cleanup();\n // Force exit to prevent hanging from embedding cache timers\n setTimeout(() => process.exit(0), 100);\n }\n return;\n }\n\n // All other commands require initialization\n if (!initialized) {\n printError('ā ReasoningBank not initialized');\n console.log('\\nTo use ReasoningBank mode, first run:');\n console.log(' memory init --reasoningbank\\n');\n return;\n }\n\n printInfo(`š§ Using ReasoningBank mode...`);\n\n try {\n // Handle different commands\n switch (command) {\n case 'store':\n await handleReasoningBankStore(subArgs, flags, storeMemory);\n break;\n\n case 'query':\n await handleReasoningBankQuery(subArgs, flags, queryMemories);\n break;\n\n case 'list':\n await handleReasoningBankList(subArgs, flags, listMemories);\n break;\n\n case 'status':\n await handleReasoningBankStatus(getStatus);\n break;\n\n case 'consolidate':\n case 'demo':\n case 'test':\n case 'benchmark':\n // These still use CLI commands\n const cmd = `npx agentic-flow reasoningbank ${command}`;\n const { stdout } = await execAsync(cmd, { timeout: 60000 });\n if (stdout) console.log(stdout);\n break;\n\n default:\n printError(`Unknown ReasoningBank command: ${command}`);\n }\n } catch (error) {\n printError(`ā ReasoningBank command failed`);\n console.error(error.message);\n } finally {\n // Always cleanup database connection\n cleanup();\n\n // Force process exit after cleanup (embedding cache timers prevent natural exit)\n // This is necessary because agentic-flow's embedding cache uses setTimeout\n // which keeps the event loop alive\n setTimeout(() => {\n process.exit(0);\n }, 100);\n }\n}\n\n// NEW: Handle ReasoningBank store\nasync function handleReasoningBankStore(subArgs, flags, storeMemory) {\n const key = subArgs[1];\n const value = subArgs.slice(2).join(' ');\n\n if (!key || !value) {\n printError('Usage: memory store <key> <value> --reasoningbank');\n return;\n }\n\n try {\n const namespace = flags?.namespace || flags?.ns || getArgValue(subArgs, '--namespace') || 'default';\n\n const memoryId = await storeMemory(key, value, {\n namespace,\n agent: 'memory-agent',\n domain: namespace,\n });\n\n printSuccess('ā
Stored successfully in ReasoningBank');\n console.log(`š Key: ${key}`);\n console.log(`š§ Memory ID: ${memoryId}`);\n console.log(`š¦ Namespace: ${namespace}`);\n console.log(`š¾ Size: ${new TextEncoder().encode(value).length} bytes`);\n console.log(`š Semantic search: enabled`);\n } catch (error) {\n printError(`Failed to store: ${error.message}`);\n }\n}\n\n// NEW: Handle ReasoningBank query\nasync function handleReasoningBankQuery(subArgs, flags, queryMemories) {\n const search = subArgs.slice(1).join(' ');\n\n if (!search) {\n printError('Usage: memory query <search> --reasoningbank');\n return;\n }\n\n try {\n const namespace = flags?.namespace || flags?.ns || getArgValue(subArgs, '--namespace');\n const results = await queryMemories(search, {\n domain: namespace || 'general',\n limit: 10,\n });\n\n if (results.length === 0) {\n printWarning('No results found');\n return;\n }\n\n printSuccess(`Found ${results.length} results (semantic search):`);\n\n for (const entry of results) {\n console.log(`\\nš ${entry.key}`);\n console.log(` Namespace: ${entry.namespace}`);\n console.log(` Value: ${entry.value.substring(0, 100)}${entry.value.length > 100 ? '...' : ''}`);\n console.log(` Confidence: ${(entry.confidence * 100).toFixed(1)}%`);\n console.log(` Usage: ${entry.usage_count} times`);\n if (entry.score) {\n console.log(` Match Score: ${(entry.score * 100).toFixed(1)}%`);\n }\n console.log(` Stored: ${new Date(entry.created_at).toLocaleString()}`);\n }\n } catch (error) {\n printError(`Failed to query: ${error.message}`);\n }\n}\n\n// NEW: Handle ReasoningBank list\nasync function handleReasoningBankList(subArgs, flags, listMemories) {\n try {\n const sort = flags?.sort || getArgValue(subArgs, '--sort') || 'created_at';\n const limit = parseInt(flags?.limit || getArgValue(subArgs, '--limit') || '10');\n\n const results = await listMemories({ sort, limit });\n\n if (results.length === 0) {\n printWarning('No memories found');\n return;\n }\n\n printSuccess(`ReasoningBank memories (${results.length} shown):`);\n\n for (const entry of results) {\n console.log(`\\nš ${entry.key}`);\n console.log(` Value: ${entry.value.substring(0, 80)}${entry.value.length > 80 ? '...' : ''}`);\n console.log(` Confidence: ${(entry.confidence * 100).toFixed(1)}% | Usage: ${entry.usage_count}`);\n }\n } catch (error) {\n printError(`Failed to list: ${error.message}`);\n }\n}\n\n// NEW: Handle ReasoningBank status\nasync function handleReasoningBankStatus(getStatus) {\n try {\n const stats = await getStatus();\n\n printSuccess('š ReasoningBank Status:');\n console.log(` Total memories: ${stats.total_memories}`);\n console.log(` Average confidence: ${(stats.avg_confidence * 100).toFixed(1)}%`);\n console.log(` Total usage: ${stats.total_usage}`);\n console.log(` Embeddings: ${stats.total_embeddings}`);\n console.log(` Trajectories: ${stats.total_trajectories}`);\n } catch (error) {\n printError(`Failed to get status: ${error.message}`);\n }\n}\n\n// NEW: Build agentic-flow reasoningbank command\nfunction buildReasoningBankCommand(command, subArgs, flags) {\n const parts = ['npx', 'agentic-flow', 'reasoningbank'];\n\n // Map memory commands to reasoningbank commands\n const commandMap = {\n store: 'store',\n query: 'query',\n list: 'list',\n status: 'status',\n consolidate: 'consolidate',\n demo: 'demo',\n test: 'test',\n benchmark: 'benchmark',\n };\n\n parts.push(commandMap[command] || command);\n\n // Add arguments (skip the command itself)\n const args = subArgs.slice(1);\n args.forEach((arg) => {\n if (!arg.startsWith('--reasoningbank') && !arg.startsWith('--rb') && !arg.startsWith('--auto')) {\n parts.push(`\"${arg}\"`);\n }\n });\n\n // Add required --agent parameter\n parts.push('--agent', 'memory-agent');\n\n return parts.join(' ');\n}\n\n// NEW: Handle mode management commands\nasync function handleModeCommand(command, subArgs, flags) {\n switch (command) {\n case 'detect':\n await detectModes();\n break;\n\n case 'mode':\n await showCurrentMode();\n break;\n\n case 'migrate':\n await migrateMemory(subArgs, flags);\n break;\n\n default:\n printError(`Unknown mode command: ${command}`);\n }\n}\n\n// NEW: Detect and show available memory modes\nasync function detectModes() {\n printInfo('š Detecting memory modes...\\n');\n\n // Check basic mode\n const basicAvailable = await checkBasicMode();\n console.log(basicAvailable ? 'ā
Basic Mode (active)' : 'ā Basic Mode (unavailable)');\n if (basicAvailable) {\n console.log(' Location: ./memory/memory-store.json');\n console.log(' Features: Simple key-value storage, fast');\n }\n\n console.log('');\n\n // Check ReasoningBank mode\n const rbAvailable = await isReasoningBankInitialized();\n console.log(rbAvailable ? 'ā
ReasoningBank Mode (available)' : 'ā ļø ReasoningBank Mode (not initialized)');\n if (rbAvailable) {\n console.log(' Location: .swarm/memory.db');\n console.log(' Features: AI-powered semantic search, learning');\n } else {\n console.log(' To enable: memory init --reasoningbank');\n }\n\n console.log('\\nš” Usage:');\n console.log(' Basic: memory store key \"value\"');\n console.log(' ReasoningBank: memory store key \"value\" --reasoningbank');\n console.log(' Auto-detect: memory query search --auto');\n}\n\n// NEW: Check if basic mode is available\nasync function checkBasicMode() {\n try {\n const memoryDir = './memory';\n await fs.access(memoryDir);\n return true;\n } catch {\n // Create directory if it doesn't exist\n try {\n await fs.mkdir(memoryDir, { recursive: true });\n return true;\n } catch {\n return false;\n }\n }\n}\n\n// NEW: Show current default mode\nasync function showCurrentMode() {\n const rbInitialized = await isReasoningBankInitialized();\n\n printInfo('š Current Memory Configuration:\\n');\n console.log('Default Mode: AUTO (smart selection with JSON fallback)');\n console.log('Available Modes:');\n console.log(' ⢠Basic Mode: Always available (JSON storage)');\n console.log(` ⢠ReasoningBank Mode: ${rbInitialized ? 'Initialized ā
(will be used by default)' : 'Not initialized ā ļø (JSON fallback active)'}`);\n\n console.log('\\nš” Mode Behavior:');\n console.log(' (no flag) ā AUTO: Use ReasoningBank if initialized, else JSON');\n console.log(' --reasoningbank or --rb ā Force ReasoningBank mode');\n console.log(' --basic ā Force JSON mode');\n console.log(' --auto ā Same as default (explicit)');\n}\n\n// NEW: Migrate memory between modes\nasync function migrateMemory(subArgs, flags) {\n const targetMode = flags?.to || getArgValue(subArgs, '--to');\n\n if (!targetMode || !['basic', 'reasoningbank'].includes(targetMode)) {\n printError('Usage: memory migrate --to <basic|reasoningbank>');\n return;\n }\n\n printInfo(`š Migrating to ${targetMode} mode...\\n`);\n\n if (targetMode === 'reasoningbank') {\n // Migrate basic ā ReasoningBank\n const rbInitialized = await isReasoningBankInitialized();\n if (!rbInitialized) {\n printError('ā ReasoningBank not initialized');\n console.log('First run: memory init --reasoningbank\\n');\n return;\n }\n\n printWarning('ā ļø Migration from basic to ReasoningBank is not yet implemented');\n console.log('This feature is coming in v2.7.1\\n');\n console.log('For now, you can:');\n console.log(' 1. Export basic memory: memory export backup.json');\n console.log(' 2. Manually import to ReasoningBank');\n } else {\n // Migrate ReasoningBank ā basic\n printWarning('ā ļø Migration from ReasoningBank to basic is not yet implemented');\n console.log('This feature is coming in v2.7.1\\n');\n }\n}\n\n// Helper to get argument value\nfunction getArgValue(args, flag) {\n const index = args.indexOf(flag);\n if (index !== -1 && index + 1 < args.length) {\n return args[index + 1];\n }\n return null;\n}\n\nfunction showMemoryHelp() {\n console.log('Memory commands:');\n console.log(' store <key> <value> Store a key-value pair');\n console.log(' query <search> Search for entries');\n console.log(' stats Show memory statistics');\n console.log(' export [filename] Export memory to file');\n console.log(' import <filename> Import memory from file');\n console.log(' clear --namespace <ns> Clear a namespace');\n console.log(' list List all namespaces');\n console.log();\n console.log('š§ ReasoningBank Commands (NEW in v2.7.0):');\n console.log(' init --reasoningbank Initialize ReasoningBank (AI-powered memory)');\n console.log(' status --reasoningbank Show ReasoningBank statistics');\n console.log(' detect Show available memory modes');\n console.log(' mode Show current memory configuration');\n console.log(' migrate --to <mode> Migrate between basic/reasoningbank');\n console.log();\n console.log('Options:');\n console.log(' --namespace <ns> Specify namespace for operations');\n console.log(' --ns <ns> Short form of --namespace');\n console.log(' --redact š Enable API key redaction (security feature)');\n console.log(' --secure Alias for --redact');\n console.log();\n console.log('šÆ Mode Selection:');\n console.log(' (no flag) AUTO MODE (default) - Uses ReasoningBank if initialized, else JSON fallback');\n console.log(' --reasoningbank, --rb Force ReasoningBank mode (AI-powered)');\n console.log(' --basic Force Basic mode (JSON storage)');\n console.log(' --auto Explicit auto-detect (same as default)');\n console.log();\n console.log('š Security Features (v2.6.0):');\n console.log(' API Key Protection: Automatically detects and redacts sensitive data');\n console.log(' Patterns Detected: Anthropic, OpenRouter, Gemini, Bearer tokens, etc.');\n console.log(' Auto-Validation: Warns when storing unredacted sensitive data');\n console.log(' Display Redaction: Redact sensitive data when querying with --redact');\n console.log();\n console.log('Examples:');\n console.log(' # Basic mode (default - backward compatible)');\n console.log(' memory store previous_work \"Research findings from yesterday\"');\n console.log(' memory store api_config \"key=sk-ant-...\" --redact # š Redacts API key');\n console.log(' memory query research --namespace sparc');\n console.log();\n console.log(' # ReasoningBank mode (AI-powered, opt-in)');\n console.log(' memory init --reasoningbank # One-time setup');\n console.log(' memory store api_pattern \"Always use env vars\" --reasoningbank');\n console.log(' memory query \"API configuration\" --reasoningbank # Semantic search!');\n console.log(' memory status --reasoningbank # Show AI metrics');\n console.log();\n console.log(' # Auto-detect mode (smart selection)');\n console.log(' memory query config --auto # Uses ReasoningBank if available');\n console.log();\n console.log(' # Mode management');\n console.log(' memory detect # Show available modes');\n console.log(' memory mode # Show current configuration');\n console.log();\n console.log('š” Tips:');\n console.log(' ⢠AUTO MODE (default): Automatically uses best available storage');\n console.log(' ⢠ReasoningBank: AI-powered semantic search (learns from patterns)');\n console.log(' ⢠JSON fallback: Always available, fast, simple key-value storage');\n console.log(' ⢠Initialize ReasoningBank once: \"memory init --reasoningbank\"');\n console.log(' ⢠Always use --redact when storing API keys or secrets!');\n}\n"],"names":["printSuccess","printError","printWarning","printInfo","promises","fs","KeyRedactor","exec","promisify","execAsync","memoryCommand","subArgs","flags","memorySubcommand","memoryStore","namespace","ns","getNamespaceFromArgs","enableRedaction","redact","includes","mode","detectMemoryMode","loadMemory","content","readFile","JSON","parse","saveMemory","data","mkdir","recursive","writeFile","stringify","handleReasoningBankCommand","handleModeCommand","storeMemory","queryMemory","showMemoryStats","exportMemory","importMemory","clearMemory","listNamespaces","showMemoryHelp","key","value","slice","join","redactedValue","securityWarnings","validation","validate","safe","warnings","forEach","warning","console","log","filter","e","push","timestamp","Date","now","redacted","length","TextEncoder","encode","err","message","search","results","entries","Object","entry","sort","a","b","displayValue","substring","toLocaleString","totalEntries","namespaceStats","keys","toFixed","count","filename","exportData","values","importContent","importData","existingData","totalImported","existingKeys","Set","map","newEntries","has","nsFromArgs","entryCount","namespaces","namespaceIndex","indexOf","nsIndex","reasoningbank","rb","auto","initialized","isReasoningBankInitialized","basic","initializeReasoningBank","error","dbPath","access","command","queryMemories","listMemories","getStatus","checkReasoningBankTables","migrateReasoningBank","cleanup","process","env","CLAUDE_FLOW_DB_PATH","tableCheck","exists","missingTables","migrationResult","success","addedTables","setTimeout","exit","handleReasoningBankStore","handleReasoningBankQuery","handleReasoningBankList","handleReasoningBankStatus","cmd","stdout","timeout","getArgValue","memoryId","agent","domain","limit","confidence","usage_count","score","created_at","parseInt","stats","total_memories","avg_confidence","total_usage","total_embeddings","total_trajectories","buildReasoningBankCommand","parts","commandMap","store","query","list","status","consolidate","demo","test","benchmark","args","arg","startsWith","detectModes","showCurrentMode","migrateMemory","basicAvailable","checkBasicMode","rbAvailable","memoryDir","rbInitialized","targetMode","to","flag","index"],"mappings":"AACA,SAASA,YAAY,EAAEC,UAAU,EAAEC,YAAY,EAAEC,SAAS,QAAQ,cAAc;AAChF,SAASC,YAAYC,EAAE,QAAQ,KAAK;AAGpC,SAASC,WAAW,QAAQ,8BAA8B;AAC1D,SAASC,IAAI,QAAQ,gBAAgB;AACrC,SAASC,SAAS,QAAQ,OAAO;AAEjC,MAAMC,YAAYD,UAAUD;AAE5B,OAAO,eAAeG,cAAcC,OAAO,EAAEC,KAAK;IAChD,MAAMC,mBAAmBF,OAAO,CAAC,EAAE;IACnC,MAAMG,cAAc;IAGpB,MAAMC,YAAYH,OAAOG,aAAaH,OAAOI,MAAMC,qBAAqBN,YAAY;IAGpF,MAAMO,kBAAkBN,OAAOO,UAAUR,QAAQS,QAAQ,CAAC,eAAeT,QAAQS,QAAQ,CAAC;IAG1F,MAAMC,OAAO,MAAMC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C;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG;IACXD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;AACd"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/cli/validation-helper.
|
|
1
|
+
{"version":3,"sources":["../../../src/cli/validation-helper.ts"],"sourcesContent":["/**\n * CLI Parameter Validation Helper\n * Provides standardized error messages for invalid parameters\n */\n\nimport { HelpFormatter } from './help-formatter.js';\n\nexport class ValidationHelper {\n /**\n * Validate enum parameter\n */\n static validateEnum(\n value: string,\n paramName: string,\n validOptions: string[],\n commandPath: string,\n ): void {\n if (!validOptions.includes(value)) {\n console.error(\n HelpFormatter.formatValidationError(value, paramName, validOptions, commandPath),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate numeric parameter\n */\n static validateNumber(\n value: string,\n paramName: string,\n min?: number,\n max?: number,\n commandPath?: string,\n ): number {\n const num = parseInt(value, 10);\n\n if (isNaN(num)) {\n console.error(\n HelpFormatter.formatError(\n `'${value}' is not a valid number for ${paramName}.`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n if (min !== undefined && num < min) {\n console.error(\n HelpFormatter.formatError(\n `${paramName} must be at least ${min}. Got: ${num}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n if (max !== undefined && num > max) {\n console.error(\n HelpFormatter.formatError(\n `${paramName} must be at most ${max}. Got: ${num}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n return num;\n }\n\n /**\n * Validate required parameter\n */\n static validateRequired(value: any, paramName: string, commandPath?: string): void {\n if (!value || (typeof value === 'string' && value.trim() === '')) {\n console.error(\n HelpFormatter.formatError(\n `Missing required parameter: ${paramName}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate file path exists\n */\n static async validateFilePath(\n path: string,\n paramName: string,\n commandPath?: string,\n ): Promise<void> {\n try {\n const fs = await import('fs/promises');\n await fs.access(path);\n } catch (error) {\n console.error(\n HelpFormatter.formatError(\n `File not found for ${paramName}: ${path}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate boolean flag\n */\n static validateBoolean(value: string, paramName: string, commandPath?: string): boolean {\n const lowerValue = value.toLowerCase();\n if (lowerValue === 'true' || lowerValue === '1' || lowerValue === 'yes') {\n return true;\n }\n if (lowerValue === 'false' || lowerValue === '0' || lowerValue === 'no') {\n return false;\n }\n\n console.error(\n HelpFormatter.formatError(\n `'${value}' is not a valid boolean for ${paramName}. Use: true, false, yes, no, 1, or 0.`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n}\n"],"names":["HelpFormatter","ValidationHelper","validateEnum","value","paramName","validOptions","commandPath","includes","console","error","formatValidationError","process","exit","validateNumber","min","max","num","parseInt","isNaN","formatError","undefined","validateRequired","trim","validateFilePath","path","fs","access","validateBoolean","lowerValue","toLowerCase"],"mappings":"AAKA,SAASA,aAAa,QAAQ,sBAAsB;AAEpD,OAAO,MAAMC;IAIX,OAAOC,aACLC,KAAa,EACbC,SAAiB,EACjBC,YAAsB,EACtBC,WAAmB,EACb;QACN,IAAI,CAACD,aAAaE,QAAQ,CAACJ,QAAQ;YACjCK,QAAQC,KAAK,CACXT,cAAcU,qBAAqB,CAACP,OAAOC,W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AEf,UAAU,EAAE,EAAEoB,MAAM,EAC1ClB,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;IACF;IAKA,OAAOe,gBAAgBxB,KAAa,EAAEC,SAAiB,EAAEE,WAAoB,EAAW;QACtF,MAAMsB,aAAazB,MAAM0B,WAAW;QACpC,IAAID,eAAe,UAAUA,eAAe,OAAOA,eAAe,OAAO;YACvE,OAAO;QACT;QACA,IAAIA,eAAe,WAAWA,eAAe,OAAOA,eAAe,MAAM;YACvE,OAAO;QACT;QAEApB,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,CAAC,EAAEhB,MAAM,6BAA6B,EAAEC,UAAU,qCAAqC,CAAC,EACzFE,eAAe;QAGnBK,QAAQC,IAAI,CAAC;IACf;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/key-redactor.
|
|
1
|
+
{"version":3,"sources":["../../../src/utils/key-redactor.ts"],"sourcesContent":["/**\n * API Key Redaction Utility\n * Prevents sensitive data from leaking into logs, memory, or git commits\n */\n\nexport interface RedactionConfig {\n patterns: RegExp[];\n replacement: string;\n maskLength: number;\n}\n\nexport class KeyRedactor {\n private static readonly API_KEY_PATTERNS = [\n // Anthropic API keys\n /sk-ant-[a-zA-Z0-9_-]{95,}/gi,\n\n // OpenRouter API keys\n /sk-or-[a-zA-Z0-9_-]{32,}/gi,\n\n // Google/Gemini API keys\n /AIza[a-zA-Z0-9_-]{35}/gi,\n\n // Generic API keys\n /[a-zA-Z0-9_-]{20,}API[a-zA-Z0-9_-]{20,}/gi,\n\n // Bearer tokens\n /Bearer\\s+[a-zA-Z0-9_\\-\\.]{20,}/gi,\n\n // Environment variable format\n /([A-Z_]+_API_KEY|[A-Z_]+_TOKEN|[A-Z_]+_SECRET)=[\"']?([^\"'\\s]+)[\"']?/gi,\n\n // Supabase keys\n /eyJ[a-zA-Z0-9_-]*\\.eyJ[a-zA-Z0-9_-]*\\.[a-zA-Z0-9_-]*/gi,\n ];\n\n private static readonly SENSITIVE_FIELDS = [\n 'apiKey',\n 'api_key',\n 'token',\n 'secret',\n 'password',\n 'private_key',\n 'privateKey',\n 'accessToken',\n 'access_token',\n 'refreshToken',\n 'refresh_token',\n ];\n\n /**\n * Redact API keys and sensitive data from text\n */\n static redact(text: string, showPrefix = true): string {\n if (!text) return text;\n\n let redacted = text;\n\n // Redact using patterns\n this.API_KEY_PATTERNS.forEach(pattern => {\n redacted = redacted.replace(pattern, (match) => {\n if (showPrefix && match.length > 8) {\n const prefix = match.substring(0, 8);\n return `${prefix}...[REDACTED]`;\n }\n return '[REDACTED_API_KEY]';\n });\n });\n\n return redacted;\n }\n\n /**\n * Redact sensitive fields in objects\n */\n static redactObject<T extends Record<string, any>>(obj: T, deep = true): T {\n if (!obj || typeof obj !== 'object') return obj;\n\n const redacted = { ...obj };\n\n Object.keys(redacted).forEach(key => {\n const lowerKey = key.toLowerCase();\n\n // Check if field name is sensitive\n const isSensitive = this.SENSITIVE_FIELDS.some(field =>\n lowerKey.includes(field)\n );\n\n if (isSensitive && typeof redacted[key] === 'string') {\n const value = redacted[key] as string;\n if (value && value.length > 8) {\n redacted[key] = `${value.substring(0, 4)}...[REDACTED]` as any;\n } else {\n redacted[key] = '[REDACTED]' as any;\n }\n } else if (deep && typeof redacted[key] === 'object' && redacted[key] !== null) {\n redacted[key] = this.redactObject(redacted[key], deep);\n } else if (typeof redacted[key] === 'string') {\n // Redact any API keys in string values\n redacted[key] = this.redact(redacted[key]) as any;\n }\n });\n\n return redacted;\n }\n\n /**\n * Sanitize text for safe logging\n */\n static sanitize(text: string): string {\n return this.redact(text, true);\n }\n\n /**\n * Sanitize command arguments\n */\n static sanitizeArgs(args: string[]): string[] {\n return args.map(arg => {\n // Check if arg is a flag value pair\n if (arg.includes('key') || arg.includes('token') || arg.includes('secret')) {\n return this.redact(arg);\n }\n return arg;\n });\n }\n\n /**\n * Check if text contains unredacted sensitive data\n */\n static containsSensitiveData(text: string): boolean {\n return this.API_KEY_PATTERNS.some(pattern => pattern.test(text));\n }\n\n /**\n * Validate that text is safe for logging/storage\n */\n static validate(text: string): { safe: boolean; warnings: string[] } {\n const warnings: string[] = [];\n\n this.API_KEY_PATTERNS.forEach((pattern, index) => {\n if (pattern.test(text)) {\n warnings.push(`Potential API key detected (pattern ${index + 1})`);\n }\n });\n\n return {\n safe: warnings.length === 0,\n warnings,\n };\n }\n\n /**\n * Redact environment variables\n */\n static redactEnv(env: Record<string, string | undefined>): Record<string, string> {\n const redacted: Record<string, string> = {};\n\n Object.keys(env).forEach(key => {\n const value = env[key];\n if (!value) {\n redacted[key] = '';\n return;\n }\n\n const lowerKey = key.toLowerCase();\n const isSensitive = lowerKey.includes('key') ||\n lowerKey.includes('token') ||\n lowerKey.includes('secret') ||\n lowerKey.includes('password');\n\n if (isSensitive) {\n redacted[key] = value.length > 8\n ? `${value.substring(0, 4)}...[REDACTED]`\n : '[REDACTED]';\n } else {\n redacted[key] = value;\n }\n });\n\n return redacted;\n }\n}\n\n// Export singleton instance\nexport const redactor = KeyRedactor;\n"],"names":["KeyRedactor","API_KEY_PATTERNS","SENSITIVE_FIELDS","redact","text","showPrefix","redacted","forEach","pattern","replace","match","length","prefix","substring","redactObject","obj","deep","Object","keys","key","lowerKey","toLowerCase","isSensitive","some","field","includes","value","sanitize","sanitizeArgs","args","map","arg","containsSensitiveData","test","validate","warnings","index","push","safe","redactEnv","env","redactor"],"mappings":"AAWA,OAAO,MAAMA;IACX,OAAwBC,mBAAmB;QAEzC;QAGA;QAGA;QAGA;QAGA;QAGA;QAGA;KACD,CAAC;IAEF,OAAwBC,mBAAmB;QACzC;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;KACD,CAAC;IAKF,OAAOC,OAAOC,IAAY,EAAEC,aAAa,IAAI,EAAU;QACrD,IAAI,CAACD,MAAM,OAAOA;QAElB,IAAIE,WAAWF;QAGf,IAAI,CAACH,gBAAgB,CAACM,OAAO,CAACC,CAAAA;YAC5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