Skip to content

armgit / ruflo

Public Imported from GitHub
0

🌊 The original agent harness. Deploy intelligent multi-player swarms, coordinate autonomous workflows, and build conversational AI systems. Features adaptive memory, self-learning intelligence, federation, vector RAG integration, and native Claude Code / Codex / Hermes and many more Integrated

fix: Graceful fallback for NODE_MODULE_VERSION mismatch in better-sqlite3 (#901)

rUv8f54a3785e8d
diff --git a/.claude-flow/metrics/performance.json b/.claude-flow/metrics/performance.json
index 808d1ecda0..bacecacf45 100644
--- a/.claude-flow/metrics/performance.json
+++ b/.claude-flow/metrics/performance.json
@@ -1,7 +1,7 @@
{
- "startTime": 1764085702305,
- "sessionId": "session-1764085702305",
- "lastActivity": 1764085702305,
+ "startTime": 1765242134287,
+ "sessionId": "session-1765242134287",
+ "lastActivity": 1765242134287,
"sessionDuration": 0,
"totalTasks": 1,
"successfulTasks": 1,
diff --git a/.claude-flow/metrics/system-metrics.json b/.claude-flow/metrics/system-metrics.json
index a12ddec44a..7c7f8f5312 100644
--- a/.claude-flow/metrics/system-metrics.json
+++ b/.claude-flow/metrics/system-metrics.json
@@ -1,230 +1,386 @@
[
{
- "timestamp": 1764443118641,
+ "timestamp": 1765241193678,
"memoryTotal": 67427545088,
- "memoryUsed": 4526211072,
- "memoryFree": 62901334016,
- "memoryUsagePercent": 6.712703341183222,
- "memoryEfficiency": 93.28729665881677,
+ "memoryUsed": 4292812800,
+ "memoryFree": 63134732288,
+ "memoryUsagePercent": 6.36655656734563,
+ "memoryEfficiency": 93.63344343265437,
"cpuCount": 16,
- "cpuLoad": 0.259375,
+ "cpuLoad": 0.253125,
"platform": "linux",
- "uptime": 177.34
+ "uptime": 408.35
},
{
- "timestamp": 1764443148671,
+ "timestamp": 1765241223690,
"memoryTotal": 67427545088,
- "memoryUsed": 4628029440,
- "memoryFree": 62799515648,
- "memoryUsagePercent": 6.863707456589051,
- "memoryEfficiency": 93.13629254341095,
+ "memoryUsed": 4259700736,
+ "memoryFree": 63167844352,
+ "memoryUsagePercent": 6.317448945294752,
+ "memoryEfficiency": 93.68255105470524,
"cpuCount": 16,
- "cpuLoad": 0.178125,
+ "cpuLoad": 0.176875,
"platform": "linux",
- "uptime": 207.37
+ "uptime": 438.36
},
{
- "timestamp": 1764443178703,
+ "timestamp": 1765241253721,
"memoryTotal": 67427545088,
- "memoryUsed": 4621324288,
- "memoryFree": 62806220800,
- "memoryUsagePercent": 6.853763223870435,
- "memoryEfficiency": 93.14623677612957,
+ "memoryUsed": 4558282752,
+ "memoryFree": 62869262336,
+ "memoryUsagePercent": 6.7602679973755,
+ "memoryEfficiency": 93.23973200262449,
"cpuCount": 16,
- "cpuLoad": 0.13125,
+ "cpuLoad": 0.140625,
"platform": "linux",
- "uptime": 237.4
+ "uptime": 468.39
},
{
- "timestamp": 1764443208733,
+ "timestamp": 1765241283750,
"memoryTotal": 67427545088,
- "memoryUsed": 4663009280,
- "memoryFree": 62764535808,
- "memoryUsagePercent": 6.9155851275829265,
- "memoryEfficiency": 93.08441487241707,
+ "memoryUsed": 4304105472,
+ "memoryFree": 63123439616,
+ "memoryUsagePercent": 6.383304429047048,
+ "memoryEfficiency": 93.61669557095296,
"cpuCount": 16,
- "cpuLoad": 0.100625,
+ "cpuLoad": 0.12625,
"platform": "linux",
- "uptime": 267.43
+ "uptime": 498.42
},
{
- "timestamp": 1764443238763,
+ "timestamp": 1765241313780,
"memoryTotal": 67427545088,
- "memoryUsed": 4755054592,
- "memoryFree": 62672490496,
- "memoryUsagePercent": 7.05209508338789,
- "memoryEfficiency": 92.94790491661212,
+ "memoryUsed": 4377559040,
+ "memoryFree": 63049986048,
+ "memoryUsagePercent": 6.4922414634654535,
+ "memoryEfficiency": 93.50775853653455,
"cpuCount": 16,
- "cpuLoad": 0.109375,
+ "cpuLoad": 0.121875,
"platform": "linux",
- "uptime": 297.46
+ "uptime": 528.45
},
{
- "timestamp": 1764443268793,
+ "timestamp": 1765241343811,
"memoryTotal": 67427545088,
- "memoryUsed": 5195075584,
- "memoryFree": 62232469504,
- "memoryUsagePercent": 7.704678521544693,
- "memoryEfficiency": 92.2953214784553,
+ "memoryUsed": 4361338880,
+ "memoryFree": 63066206208,
+ "memoryUsagePercent": 6.468185775276256,
+ "memoryEfficiency": 93.53181422472375,
"cpuCount": 16,
- "cpuLoad": 0.209375,
+ "cpuLoad": 0.13,
"platform": "linux",
- "uptime": 327.49
+ "uptime": 558.48
},
{
- "timestamp": 1764443298823,
+ "timestamp": 1765241373840,
"memoryTotal": 67427545088,
- "memoryUsed": 4843319296,
- "memoryFree": 62584225792,
- "memoryUsagePercent": 7.182998119950773,
- "memoryEfficiency": 92.81700188004923,
+ "memoryUsed": 4211683328,
+ "memoryFree": 63215861760,
+ "memoryUsagePercent": 6.246235603718499,
+ "memoryEfficiency": 93.7537643962815,
"cpuCount": 16,
- "cpuLoad": 0.231875,
+ "cpuLoad": 0.104375,
"platform": "linux",
- "uptime": 357.52
+ "uptime": 588.51
},
{
- "timestamp": 1764443328853,
+ "timestamp": 1765241403871,
"memoryTotal": 67427545088,
- "memoryUsed": 4796481536,
- "memoryFree": 62631063552,
- "memoryUsagePercent": 7.113534282970098,
- "memoryEfficiency": 92.8864657170299,
+ "memoryUsed": 4296138752,
+ "memoryFree": 63131406336,
+ "memoryUsagePercent": 6.371489198358163,
+ "memoryEfficiency": 93.62851080164184,
"cpuCount": 16,
- "cpuLoad": 0.218125,
+ "cpuLoad": 0.12875,
"platform": "linux",
- "uptime": 387.55
+ "uptime": 618.55
},
{
- "timestamp": 1764443358884,
+ "timestamp": 1765241433902,
"memoryTotal": 67427545088,
- "memoryUsed": 4781649920,
- "memoryFree": 62645895168,
- "memoryUsagePercent": 7.0915379074819445,
- "memoryEfficiency": 92.90846209251805,
+ "memoryUsed": 4229894144,
+ "memoryFree": 63197650944,
+ "memoryUsagePercent": 6.273243580912736,
+ "memoryEfficiency": 93.72675641908727,
"cpuCount": 16,
- "cpuLoad": 0.1725,
+ "cpuLoad": 0.08125,
"platform": "linux",
- "uptime": 417.58
+ "uptime": 648.58
},
{
- "timestamp": 1764443388913,
+ "timestamp": 1765241463932,
"memoryTotal": 67427545088,
- "memoryUsed": 4931756032,
- "memoryFree": 62495789056,
- "memoryUsagePercent": 7.314156292600512,
- "memoryEfficiency": 92.68584370739948,
+ "memoryUsed": 4268711936,
+ "memoryFree": 63158833152,
+ "memoryUsagePercent": 6.330813216510974,
+ "memoryEfficiency": 93.66918678348902,
"cpuCount": 16,
- "cpuLoad": 0.195,
+ "cpuLoad": 0.05625,
"platform": "linux",
- "uptime": 447.61
+ "uptime": 678.61
},
{
- "timestamp": 1764443418943,
+ "timestamp": 1765241493961,
"memoryTotal": 67427545088,
- "memoryUsed": 4773167104,
- "memoryFree": 62654377984,
- "memoryUsagePercent": 7.078957268532493,
- "memoryEfficiency": 92.92104273146751,
+ "memoryUsed": 4543492096,
+ "memoryFree": 62884052992,
+ "memoryUsagePercent": 6.738332368574694,
+ "memoryEfficiency": 93.26166763142531,
"cpuCount": 16,
- "cpuLoad": 0.125625,
+ "cpuLoad": 0.046875,
"platform": "linux",
- "uptime": 477.64
+ "uptime": 708.64
},
{
- "timestamp": 1764443448974,
+ "timestamp": 1765241523968,
"memoryTotal": 67427545088,
- "memoryUsed": 4828106752,
- "memoryFree": 62599438336,
- "memoryUsagePercent": 7.160436800270298,
- "memoryEfficiency": 92.8395631997297,
+ "memoryUsed": 4400599040,
+ "memoryFree": 63026946048,
+ "memoryUsagePercent": 6.526411475097838,
+ "memoryEfficiency": 93.47358852490217,
"cpuCount": 16,
- "cpuLoad": 0.11125,
+ "cpuLoad": 0.05375,
"platform": "linux",
- "uptime": 507.67
+ "uptime": 738.64
},
{
- "timestamp": 1764443478998,
+ "timestamp": 1765241553997,
"memoryTotal": 67427545088,
- "memoryUsed": 4833415168,
- "memoryFree": 62594129920,
- "memoryUsagePercent": 7.1683095709504,
- "memoryEfficiency": 92.8316904290496,
+ "memoryUsed": 4355014656,
+ "memoryFree": 63072530432,
+ "memoryUsagePercent": 6.458806486749963,
+ "memoryEfficiency": 93.54119351325004,
"cpuCount": 16,
- "cpuLoad": 0.096875,
+ "cpuLoad": 0.05125,
"platform": "linux",
- "uptime": 537.7
+ "uptime": 768.67
},
{
- "timestamp": 1764443508999,
+ "timestamp": 1765241584026,
"memoryTotal": 67427545088,
- "memoryUsed": 5782851584,
- "memoryFree": 61644693504,
- "memoryUsagePercent": 8.57639348496638,
- "memoryEfficiency": 91.42360651503363,
+ "memoryUsed": 4439920640,
+ "memoryFree": 62987624448,
+ "memoryUsagePercent": 6.5847282949504375,
+ "memoryEfficiency": 93.41527170504956,
"cpuCount": 16,
- "cpuLoad": 0.120625,
+ "cpuLoad": 0.046875,
"platform": "linux",
- "uptime": 567.7
+ "uptime": 798.7
},
{
- "timestamp": 1764443539030,
+ "timestamp": 1765241614056,
"memoryTotal": 67427545088,
- "memoryUsed": 4989267968,
- "memoryFree": 62438277120,
- "memoryUsagePercent": 7.399450716303675,
- "memoryEfficiency": 92.60054928369632,
+ "memoryUsed": 4403597312,
+ "memoryFree": 63023947776,
+ "memoryUsagePercent": 6.5308581326115975,
+ "memoryEfficiency": 93.4691418673884,
"cpuCount": 16,
- "cpuLoad": 0.1125,
+ "cpuLoad": 0.060625,
"platform": "linux",
- "uptime": 597.73
+ "uptime": 828.73
},
{
- "timestamp": 1764443569060,
+ "timestamp": 1765241644059,
"memoryTotal": 67427545088,
- "memoryUsed": 4937060352,
- "memoryFree": 62490484736,
- "memoryUsagePercent": 7.322022988611879,
- "memoryEfficiency": 92.67797701138812,
+ "memoryUsed": 4590108672,
+ "memoryFree": 62837436416,
+ "memoryUsagePercent": 6.807468173443699,
+ "memoryEfficiency": 93.1925318265563,
"cpuCount": 16,
- "cpuLoad": 0.13375,
+ "cpuLoad": 0.04875,
+ "platform": "linux",
+ "uptime": 858.73
+ },
+ {
+ "timestamp": 1765241674089,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 4393177088,
+ "memoryFree": 63034368000,
+ "memoryUsagePercent": 6.515404175350659,
+ "memoryEfficiency": 93.48459582464935,
+ "cpuCount": 16,
+ "cpuLoad": 0.05625,
+ "platform": "linux",
+ "uptime": 888.76
+ },
+ {
+ "timestamp": 1765241704119,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 4539330560,
+ "memoryFree": 62888214528,
+ "memoryUsagePercent": 6.732160505140293,
+ "memoryEfficiency": 93.26783949485971,
+ "cpuCount": 16,
+ "cpuLoad": 0.071875,
+ "platform": "linux",
+ "uptime": 918.79
+ },
+ {
+ "timestamp": 1765241734150,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 4579733504,
+ "memoryFree": 62847811584,
+ "memoryUsagePercent": 6.792081037538841,
+ "memoryEfficiency": 93.20791896246116,
+ "cpuCount": 16,
+ "cpuLoad": 0.07,
+ "platform": "linux",
+ "uptime": 948.82
+ },
+ {
+ "timestamp": 1765241764180,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 4533415936,
+ "memoryFree": 62894129152,
+ "memoryUsagePercent": 6.723388683487465,
+ "memoryEfficiency": 93.27661131651253,
+ "cpuCount": 16,
+ "cpuLoad": 0.084375,
+ "platform": "linux",
+ "uptime": 978.85
+ },
+ {
+ "timestamp": 1765241794199,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 4450623488,
+ "memoryFree": 62976921600,
+ "memoryUsagePercent": 6.600601404354068,
+ "memoryEfficiency": 93.39939859564593,
+ "cpuCount": 16,
+ "cpuLoad": 0.09,
"platform": "linux",
- "uptime": 627.76
+ "uptime": 1008.87
},
{
- "timestamp": 1764443599090,
+ "timestamp": 1765241824200,
"memoryTotal": 67427545088,
- "memoryUsed": 4706615296,
- "memoryFree": 62720929792,
- "memoryUsagePercent": 6.980256050931967,
- "memoryEfficiency": 93.01974394906803,
+ "memoryUsed": 4529553408,
+ "memoryFree": 62897991680,
+ "memoryUsagePercent": 6.717660270870694,
+ "memoryEfficiency": 93.2823397291293,
"cpuCount": 16,
- "cpuLoad": 0.09125,
+ "cpuLoad": 0.10125,
"platform": "linux",
- "uptime": 657.79
+ "uptime": 1038.87
},
{
- "timestamp": 1764443629122,
+ "timestamp": 1765241854230,
"memoryTotal": 67427545088,
- "memoryUsed": 4843249664,
- "memoryFree": 62584295424,
- "memoryUsagePercent": 7.182894850582285,
- "memoryEfficiency": 92.81710514941771,
+ "memoryUsed": 4582232064,
+ "memoryFree": 62845313024,
+ "memoryUsagePercent": 6.795786585466974,
+ "memoryEfficiency": 93.20421341453303,
"cpuCount": 16,
- "cpuLoad": 0.083125,
+ "cpuLoad": 0.110625,
"platform": "linux",
- "uptime": 687.82
+ "uptime": 1068.9
},
{
- "timestamp": 1764443659151,
+ "timestamp": 1765241884251,
"memoryTotal": 67427545088,
- "memoryUsed": 4970213376,
- "memoryFree": 62457331712,
- "memoryUsagePercent": 7.371191357350103,
- "memoryEfficiency": 92.6288086426499,
+ "memoryUsed": 4526825472,
+ "memoryFree": 62900719616,
+ "memoryUsagePercent": 6.71361454149342,
+ "memoryEfficiency": 93.28638545850659,
"cpuCount": 16,
- "cpuLoad": 0.091875,
+ "cpuLoad": 0.121875,
+ "platform": "linux",
+ "uptime": 1098.93
+ },
+ {
+ "timestamp": 1765241914281,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 4365619200,
+ "memoryFree": 63061925888,
+ "memoryUsagePercent": 6.474533804103961,
+ "memoryEfficiency": 93.52546619589604,
+ "cpuCount": 16,
+ "cpuLoad": 0.104375,
+ "platform": "linux",
+ "uptime": 1128.95
+ },
+ {
+ "timestamp": 1765241944309,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 4671909888,
+ "memoryFree": 62755635200,
+ "memoryUsagePercent": 6.928785382743312,
+ "memoryEfficiency": 93.07121461725669,
+ "cpuCount": 16,
+ "cpuLoad": 0.125,
+ "platform": "linux",
+ "uptime": 1158.98
+ },
+ {
+ "timestamp": 1765241974338,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 4567203840,
+ "memoryFree": 62860341248,
+ "memoryUsagePercent": 6.77349862587956,
+ "memoryEfficiency": 93.22650137412045,
+ "cpuCount": 16,
+ "cpuLoad": 0.12,
+ "platform": "linux",
+ "uptime": 1189.01
+ },
+ {
+ "timestamp": 1765242004368,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 4589809664,
+ "memoryFree": 62837735424,
+ "memoryUsagePercent": 6.807024722626069,
+ "memoryEfficiency": 93.19297527737393,
+ "cpuCount": 16,
+ "cpuLoad": 0.134375,
+ "platform": "linux",
+ "uptime": 1219.04
+ },
+ {
+ "timestamp": 1765242034376,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 4587638784,
+ "memoryFree": 62839906304,
+ "memoryUsagePercent": 6.803805148196707,
+ "memoryEfficiency": 93.1961948518033,
+ "cpuCount": 16,
+ "cpuLoad": 0.145,
+ "platform": "linux",
+ "uptime": 1249.05
+ },
+ {
+ "timestamp": 1765242064407,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 4504956928,
+ "memoryFree": 62922588160,
+ "memoryUsagePercent": 6.681181885119145,
+ "memoryEfficiency": 93.31881811488086,
+ "cpuCount": 16,
+ "cpuLoad": 0.104375,
+ "platform": "linux",
+ "uptime": 1279.08
+ },
+ {
+ "timestamp": 1765242094407,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 4624789504,
+ "memoryFree": 62802755584,
+ "memoryUsagePercent": 6.858902393619945,
+ "memoryEfficiency": 93.14109760638006,
+ "cpuCount": 16,
+ "cpuLoad": 0.084375,
+ "platform": "linux",
+ "uptime": 1309.08
+ },
+ {
+ "timestamp": 1765242124437,
+ "memoryTotal": 67427545088,
+ "memoryUsed": 4723195904,
+ "memoryFree": 62704349184,
+ "memoryUsagePercent": 7.004846309969813,
+ "memoryEfficiency": 92.9951536900302,
+ "cpuCount": 16,
+ "cpuLoad": 0.13375,
"platform": "linux",
- "uptime": 717.85
+ "uptime": 1339.11
}
]
\ No newline at end of file
diff --git a/.claude-flow/metrics/task-metrics.json b/.claude-flow/metrics/task-metrics.json
index 9f0029ec3b..785f5543bd 100644
--- a/.claude-flow/metrics/task-metrics.json
+++ b/.claude-flow/metrics/task-metrics.json
@@ -1,10 +1,10 @@
[
{
- "id": "cmd-hooks-1764085702404",
+ "id": "cmd-hooks-1765242134387",
"type": "hooks",
"success": true,
- "duration": 7.052818000000002,
- "timestamp": 1764085702412,
+ "duration": 7.085351000000003,
+ "timestamp": 1765242134395,
"metadata": {}
}
]
\ No newline at end of file
diff --git a/bin/claude-flow b/bin/claude-flow
index 8f5ed2f787..b75e49b871 100755
--- a/bin/claude-flow
+++ b/bin/claude-flow
@@ -2,7 +2,7 @@
# Claude-Flow Smart Dispatcher - Detects and uses the best available runtime
# Enhanced with NPX cache error handling and retry logic
-VERSION="2.7.41"
+VERSION="2.7.42"
# Determine the correct path based on how the script is invoked
if [ -L "$0" ]; then
diff --git a/dist-cjs/src/cli/simple-cli.js b/dist-cjs/src/cli/simple-cli.js
index af5a4c0edd..ace546b80e 100644
--- a/dist-cjs/src/cli/simple-cli.js
+++ b/dist-cjs/src/cli/simple-cli.js
@@ -1,47 +1,18 @@
-#!/usr/bin/env node
+#!/usr/bin/env -S deno run --allow-all
+import { promises as fs } from 'node:fs';
import { executeCommand, hasCommand, showCommandHelp, listCommands } from './command-registry.js';
import { parseFlags } from './utils.js';
-import { args, cwd, isMainModule, exit, readTextFile, writeTextFile, mkdirAsync, errors } from './node-compat.js';
-import { spawn } from 'child_process';
-import process from 'process';
-import readline from 'readline';
-import { getMainHelp, getCommandHelp, getStandardizedCommandHelp } from './help-text.js';
import { VERSION } from '../core/version.js';
-const LEGACY_AGENT_MAPPING = {
- analyst: 'code-analyzer',
- coordinator: 'task-orchestrator',
- optimizer: 'perf-analyzer',
- documenter: 'api-docs',
- monitor: 'performance-benchmarker',
- specialist: 'system-architect',
- architect: 'system-architect'
-};
-function resolveLegacyAgentType(legacyType) {
- return LEGACY_AGENT_MAPPING[legacyType] || legacyType;
-}
-function printHelp(plain = false) {
- console.log(getMainHelp(plain));
-}
-function printCommandHelp(command) {
- const standardCommands = [
- 'agent',
- 'sparc',
- 'memory'
- ];
- if (standardCommands.includes(command)) {
- const help = getStandardizedCommandHelp(command);
- console.log(help);
- } else {
- const help = getCommandHelp(command);
- console.log(help);
- }
-}
-function printLegacyHelp() {
+function printHelp() {
console.log(`
🌊 Claude-Flow v${VERSION} - Enterprise-Grade AI Agent Orchestration Platform
-🎯 ENTERPRISE FEATURES: Complete ruv-swarm integration with 90+ MCP tools, neural networking, and production-ready infrastructure
-⚡ ALPHA 85: Advanced automation capabilities & stream-JSON chaining for multi-agent pipelines
+🎯 NEW IN v2.6.0: Multi-Provider Execution Engine with Agentic-Flow Integration
+ • 66+ specialized agents with multi-provider support (Anthropic, OpenRouter, ONNX, Gemini)
+ • 99% cost savings with OpenRouter, 352x faster local edits with Agent Booster
+ • Complete backwards compatibility with existing features
+
+🎯 ENTERPRISE FEATURES: Complete ruv-swarm integration with 27 MCP tools, neural networking, and production-ready infrastructure
USAGE:
claude-flow <command> [options]
@@ -77,9 +48,10 @@ USAGE:
init [--sparc] # Initialize with enterprise environment + ruv-swarm
start [--ui] [--swarm] # Start orchestration with swarm intelligence
spawn <type> [--name] # Create AI agent with swarm coordination
- agent <subcommand> # Advanced agent management with neural patterns
+ agent <subcommand> # 🆕 Multi-provider agent execution + management
sparc <subcommand> # 17 SPARC modes with neural enhancement
memory <subcommand> # Cross-session persistent memory with neural learning
+ config <subcommand> # 🆕 Provider configuration management
status # Comprehensive system status with performance metrics
🤖 NEURAL AGENT TYPES (ruv-swarm Integration):
@@ -94,20 +66,25 @@ USAGE:
🎮 ENTERPRISE QUICK START:
# Initialize enterprise environment
- npx [email protected] init --sparc
-
+ npx [email protected] init --sparc
+
+ # 🆕 Execute agents with multi-provider support
+ ./claude-flow agent run coder "Build REST API with auth" --provider anthropic
+ ./claude-flow agent run researcher "Research React 19" --provider openrouter # 99% cost savings
+ ./claude-flow agent agents # List all 66+ available agents
+
# Start enterprise orchestration with swarm intelligence
./claude-flow start --ui --swarm
-
+
# Deploy intelligent multi-agent development workflow
./claude-flow swarm "build enterprise API" --strategy development --parallel --monitor
-
+
# GitHub workflow automation
./claude-flow github pr-manager "coordinate release with automated testing"
-
+
# Neural memory management
./claude-flow memory store "architecture" "microservices with API gateway pattern"
-
+
# Real-time system monitoring
./claude-flow status --verbose
@@ -175,8 +152,8 @@ function printSuccess(message) {
function printWarning(message) {
console.warn(`⚠️ Warning: ${message}`);
}
-function showHelpWithCommands(plain = false) {
- printHelp(plain);
+function showHelpWithCommands() {
+ printHelp();
console.log('\nRegistered Commands:');
const commands = listCommands();
for (const command of commands){
@@ -185,58 +162,14 @@ function showHelpWithCommands(plain = false) {
console.log('\nUse "claude-flow help <command>" for detailed usage information');
}
async function main() {
+ const args = Deno.args;
if (args.length === 0) {
- printHelp(usePlainHelp);
+ printHelp();
return;
}
const command = args[0];
const { flags, args: parsedArgs } = parseFlags(args.slice(1));
- const usePlainHelp = args.includes('--plain');
- let enhancedFlags = flags;
- try {
- const { detectExecutionEnvironment, applySmartDefaults } = await import('./utils/environment-detector.js');
- enhancedFlags = applySmartDefaults(flags);
- enhancedFlags._environment = detectExecutionEnvironment({
- skipWarnings: true
- });
- } catch (e) {
- enhancedFlags = flags;
- }
- if (command !== 'help' && command !== '--help' && command !== '-h' && (enhancedFlags.help || enhancedFlags.h)) {
- const detailedHelp = getCommandHelp(command);
- if (detailedHelp && !detailedHelp.includes('Help not available')) {
- printCommandHelp(command);
- } else if (hasCommand(command)) {
- showCommandHelp(command);
- } else {
- printError(`Unknown command: ${command}`);
- console.log('\nRun "claude-flow --help" to see available commands.');
- }
- return;
- }
switch(command){
- case 'env-check':
- case 'environment':
- if (enhancedFlags._environment) {
- const env = enhancedFlags._environment;
- console.log(`\n🖥️ Environment Detection Results:`);
- console.log(` Terminal: ${env.terminalType}`);
- console.log(` Interactive: ${env.isInteractive ? 'Yes' : 'No'}`);
- console.log(` TTY Support: ${env.supportsRawMode ? 'Yes' : 'No'}`);
- console.log(` Detected: ${env.isVSCode ? 'VS Code' : env.isCI ? 'CI/CD' : env.isDocker ? 'Docker' : env.isSSH ? 'SSH' : 'Standard Terminal'}`);
- if (env.recommendedFlags.length > 0) {
- console.log(`\n💡 Recommended flags:`);
- console.log(` ${env.recommendedFlags.join(' ')}`);
- }
- if (enhancedFlags.appliedDefaults && enhancedFlags.appliedDefaults.length > 0) {
- console.log(`\n✅ Auto-applied:`);
- console.log(` ${enhancedFlags.appliedDefaults.join(' ')}`);
- }
- console.log();
- } else {
- console.log('Environment detection not available');
- }
- return;
case 'version':
case '--version':
case '-v':
@@ -246,14 +179,9 @@ async function main() {
case '--help':
case '-h':
if (parsedArgs.length > 0) {
- const detailedHelp = getCommandHelp(parsedArgs[0]);
- if (detailedHelp && !detailedHelp.includes('Help not available')) {
- printCommandHelp(parsedArgs[0]);
- } else {
- showCommandHelp(parsedArgs[0]);
- }
+ showCommandHelp(parsedArgs[0]);
} else {
- printHelp(usePlainHelp);
+ showHelpWithCommands();
}
return;
}
@@ -263,7 +191,6 @@ async function main() {
return;
} catch (err) {
printError(err.message);
- console.log(`\nRun "claude-flow ${command} --help" for usage information.`);
return;
}
}
@@ -283,12 +210,11 @@ async function main() {
console.log('📊 Real-time monitoring would display here');
break;
case 'spawn':
- const rawSpawnType = subArgs[0] || 'general';
- const spawnType = resolveLegacyAgentType(rawSpawnType);
+ const spawnType = subArgs[0] || 'general';
const spawnName = flags.name || `agent-${Date.now()}`;
printSuccess(`Spawning ${spawnType} agent: ${spawnName}`);
console.log('🤖 Agent would be created with the following configuration:');
- console.log(` Type: ${spawnType}${rawSpawnType !== spawnType ? ` (resolved from: ${rawSpawnType})` : ''}`);
+ console.log(` Type: ${spawnType}`);
console.log(` Name: ${spawnName}`);
console.log(' Capabilities: Research, Analysis, Code Generation');
console.log(' Status: Ready');
@@ -313,7 +239,7 @@ async function main() {
console.log(' • Max Pool Size: 10');
console.log(' • Idle Timeout: 5 minutes');
console.log(' • Shell: /bin/bash');
- console.log(' • Working Directory: ' + cwd());
+ console.log(' • Working Directory: ' + process.cwd());
console.log(' Performance:');
console.log(' • Average Response Time: N/A');
console.log(' • Terminal Creation Time: N/A');
@@ -362,7 +288,7 @@ async function main() {
const terminalConfig = {
name: nameIndex >= 0 ? subArgs[nameIndex + 1] : 'terminal-' + Date.now(),
shell: shellIndex >= 0 ? subArgs[shellIndex + 1] : 'bash',
- workingDirectory: wdIndex >= 0 ? subArgs[wdIndex + 1] : cwd(),
+ workingDirectory: wdIndex >= 0 ? subArgs[wdIndex + 1] : process.cwd(),
env: envIndex >= 0 ? subArgs[envIndex + 1] : '',
persistent: persistentIndex >= 0
};
@@ -1319,9 +1245,10 @@ ${flags1.mode === 'full' || !flags1.mode ? `Full-stack development covering all
console.log('Debug - Executing command:');
console.log(`claude ${claudeArgs.map((arg)=>arg.includes(' ') || arg.includes('\n') ? `"${arg}"` : arg).join(' ')}`);
}
- const child = spawn('claude', claudeArgs, {
+ const command = new Deno.Command('claude', {
+ args: claudeArgs,
env: {
- ...process.env,
+ ...Deno.env.toObject(),
CLAUDE_INSTANCE_ID: instanceId,
CLAUDE_FLOW_MODE: flags1.mode || 'full',
CLAUDE_FLOW_COVERAGE: (flags1.coverage || 80).toString(),
@@ -1331,18 +1258,17 @@ ${flags1.mode === 'full' || !flags1.mode ? `Full-stack development covering all
CLAUDE_FLOW_COORDINATION_ENABLED: flags1.parallel ? 'true' : 'false',
CLAUDE_FLOW_FEATURES: 'memory,coordination,swarm'
},
- stdio: 'inherit'
- });
- await new Promise((resolve)=>{
- child.on('exit', (code)=>{
- if (code === 0) {
- printSuccess(`Claude instance ${instanceId} completed successfully`);
- } else {
- printError(`Claude instance ${instanceId} exited with code ${code}`);
- }
- resolve();
- });
+ stdin: 'inherit',
+ stdout: 'inherit',
+ stderr: 'inherit'
});
+ const child = command.spawn();
+ const status = await child.status;
+ if (status.success) {
+ printSuccess(`Claude instance ${instanceId} completed successfully`);
+ } else {
+ printError(`Claude instance ${instanceId} exited with code ${status.code}`);
+ }
} catch (err) {
printError(`Failed to spawn Claude: ${err.message}`);
console.log('Make sure you have the Claude CLI installed.');
@@ -1895,7 +1821,7 @@ ${flags1.mode === 'full' || !flags1.mode ? `Full-stack development covering all
console.log('\nDid you mean:');
suggestions.forEach((cmd)=>console.log(` claude-flow ${cmd}`));
}
- exit(1);
+ process.exit(1);
}
}
async function startRepl() {
@@ -1973,7 +1899,7 @@ Shortcuts:
},
config: async (key)=>{
try {
- const config = JSON.parse(await readTextFile('claude-flow.config.json'));
+ const config = JSON.parse(await fs.readFile('claude-flow.config.json', 'utf-8'));
if (key) {
const keys = key.split('.');
let value = config;
@@ -2001,25 +1927,21 @@ Shortcuts:
if (trimmed.startsWith('!')) {
const shellCmd = trimmed.substring(1);
try {
- await new Promise((resolve)=>{
- const proc = spawn('sh', [
+ const command = new Deno.Command('sh', {
+ args: [
'-c',
shellCmd
- ], {
- stdio: [
- 'inherit',
- 'pipe',
- 'pipe'
- ]
- });
- proc.stdout.on('data', (data)=>{
- console.log(data.toString());
- });
- proc.stderr.on('data', (data)=>{
- console.error(data.toString());
- });
- proc.on('exit', resolve);
+ ],
+ stdout: 'piped',
+ stderr: 'piped'
});
+ const { stdout, stderr } = await command.output();
+ if (stdout.length > 0) {
+ console.log(new TextDecoder().decode(stdout));
+ }
+ if (stderr.length > 0) {
+ console.error(new TextDecoder().decode(stderr));
+ }
} catch (err) {
console.error(`Shell error: ${err.message}`);
}
@@ -2039,7 +1961,7 @@ Shortcuts:
const parts = trimmed.split(' ');
const command = parts[0];
const args = parts.slice(1);
- if (replCommands[command]) {
+ if (command in replCommands) {
await replCommands[command](...args);
return true;
}
@@ -2060,8 +1982,7 @@ Shortcuts:
const subCmd = args[0];
switch(subCmd){
case 'spawn':
- const rawType = args[1] || 'researcher';
- const type = resolveLegacyAgentType(rawType);
+ const type = args[1] || 'researcher';
const name = args[2] || `agent-${Date.now()}`;
const agent = {
id: `agent-${Date.now()}`,
@@ -2266,33 +2187,18 @@ Shortcuts:
console.log('Terminal commands: create, list, exec, attach, detach');
}
}
- const rl = readline.createInterface({
- input: process.stdin,
- output: process.stdout
- });
- function updatePrompt() {
- rl.setPrompt(replState.currentSession ? `claude-flow:${replState.currentSession}> ` : 'claude-flow> ');
- }
- updatePrompt();
- rl.prompt();
- rl.on('line', async (input)=>{
- input = input.trim();
+ const decoder = new TextDecoder();
+ const encoder = new TextEncoder();
+ while(true){
+ const prompt = replState.currentSession ? `claude-flow:${replState.currentSession}> ` : 'claude-flow> ';
+ await Deno.stdout.write(encoder.encode(prompt));
+ const buf = new Uint8Array(1024);
+ const n = await Deno.stdin.read(buf);
+ if (n === null) break;
+ const input = decoder.decode(buf.subarray(0, n)).trim();
const shouldContinue = await processReplCommand(input);
- if (!shouldContinue) {
- rl.close();
- } else {
- updatePrompt();
- rl.prompt();
- }
- });
- rl.on('SIGINT', ()=>{
- console.log('\nExiting Claude-Flow...');
- rl.close();
- process.exit(0);
- });
- return new Promise((resolve)=>{
- rl.on('close', resolve);
- });
+ if (!shouldContinue) break;
+ }
}
function createMinimalClaudeMd() {
return `# Claude Code Integration
@@ -2609,30 +2515,30 @@ async function createSparcStructureManually() {
];
for (const dir of rooDirectories){
try {
- await mkdirAsync(dir, {
+ await Deno.mkdir(dir, {
recursive: true
});
console.log(` ✓ Created ${dir}/`);
} catch (err) {
- if (!(err instanceof errors.AlreadyExists)) {
+ if (!(err instanceof Deno.errors.AlreadyExists)) {
throw err;
}
}
}
let roomodesContent;
try {
- roomodesContent = await readTextFile('.roomodes');
+ roomodesContent = await fs.readFile('.roomodes');
console.log(' ✓ Using existing .roomodes configuration');
} catch {
roomodesContent = createBasicRoomodesConfig();
- await writeTextFile('.roomodes', roomodesContent);
+ await fs.writeFile('.roomodes', roomodesContent);
console.log(' ✓ Created .roomodes configuration');
}
const basicWorkflow = createBasicSparcWorkflow();
- await writeTextFile('.roo/workflows/basic-tdd.json', basicWorkflow);
+ await fs.writeFile('.roo/workflows/basic-tdd.json', basicWorkflow);
console.log(' ✓ Created .roo/workflows/basic-tdd.json');
const rooReadme = createRooReadme();
- await writeTextFile('.roo/README.md', rooReadme);
+ await fs.writeFile('.roo/README.md', rooReadme);
console.log(' ✓ Created .roo/README.md');
console.log(' ✅ Basic SPARC structure created successfully');
} catch (err) {
@@ -3060,6 +2966,110 @@ This SPARC-enabled project follows a systematic development approach:
- Document architectural decisions in memory for future reference
- Regular security reviews for any authentication or data handling code
+For more information about SPARC methodology, see: https://github.com/ruvnet/claude-code-flow/docs/sparc.md
+`;
+}
+if (import.meta.url === `file://${process.argv[1]}`) {
+ await main();
+}
+
+//# sourceMappingURL=simple-cli.js.map sparc run spec-pseudocode "User profile management feature"
+
+# 2. Design architecture
+npx claude-flow sparc run architect "Profile service architecture with data validation"
+
+# 3. Implement with TDD
+npx claude-flow sparc tdd "user profile CRUD operations"
+
+# 4. Security review
+npx claude-flow sparc run security-review "profile data access and validation"
+
+# 5. Integration testing
+npx claude-flow sparc run integration "profile service with authentication system"
+
+# 6. Documentation
+npx claude-flow sparc run docs-writer "profile service API documentation"
+\`\`\`
+
+### Bug Fix Workflow
+\`\`\`bash
+# 1. Debug and analyze
+npx claude-flow sparc run debug "authentication token expiration issue"
+
+# 2. Write regression tests
+npx claude-flow sparc run tdd "token refresh mechanism tests"
+
+# 3. Implement fix
+npx claude-flow sparc run code "fix token refresh in authentication service"
+
+# 4. Security review
+npx claude-flow sparc run security-review "token handling security implications"
+\`\`\`
+
+## Configuration Files
+
+### SPARC Configuration
+- **\`.roomodes\`**: SPARC mode definitions and configurations
+- **\`.roo/\`**: Templates, workflows, and mode-specific rules
+
+### Claude-Flow Configuration
+- **\`memory/\`**: Persistent memory and session data
+- **\`coordination/\`**: Multi-agent coordination settings
+
+## Git Workflow Integration
+
+### Commit Strategy with SPARC
+- **Specification commits**: After completing requirements analysis
+- **Architecture commits**: After design phase completion
+- **TDD commits**: After each Red-Green-Refactor cycle
+- **Integration commits**: After successful component integration
+- **Documentation commits**: After completing documentation updates
+
+### Branch Strategy
+- **\`feature/sparc-<feature-name>\`**: Feature development with SPARC methodology
+- **\`hotfix/sparc-<issue>\`**: Bug fixes using SPARC debugging workflow
+- **\`refactor/sparc-<component>\`**: Refactoring using optimization mode
+
+## Troubleshooting
+
+### Common SPARC Issues
+- **Mode not found**: Check \`.roomodes\` file exists and is valid JSON
+- **Memory persistence**: Ensure \`memory/\` directory has write permissions
+- **Tool access**: Verify required tools are available for the selected mode
+- **Namespace conflicts**: Use unique memory namespaces for different features
+
+### Debug Commands
+\`\`\`bash
+# Check SPARC configuration
+npx claude-flow sparc modes
+
+# Verify memory system
+npx claude-flow memory stats
+
+# Check system status
+npx claude-flow status
+
+# View detailed mode information
+npx claude-flow sparc info <mode-name>
+\`\`\`
+
+## Project Architecture
+
+This SPARC-enabled project follows a systematic development approach:
+- **Clear separation of concerns** through modular design
+- **Test-driven development** ensuring reliability and maintainability
+- **Iterative refinement** for continuous improvement
+- **Comprehensive documentation** for team collaboration
+- **AI-assisted development** through specialized SPARC modes
+
+## Important Notes
+
+- Always run tests before committing (\`npm run test\`)
+- Use SPARC memory system to maintain context across sessions
+- Follow the Red-Green-Refactor cycle during TDD phases
+- Document architectural decisions in memory for future reference
+- Regular security reviews for any authentication or data handling code
+
For more information about SPARC methodology, see: https://github.com/ruvnet/claude-code-flow/docs/sparc.md
`;
}
diff --git a/dist-cjs/src/cli/simple-cli.js.map b/dist-cjs/src/cli/simple-cli.js.map
index 17942c3906..1496d94d8b 100644
--- a/dist-cjs/src/cli/simple-cli.js.map
+++ b/dist-cjs/src/cli/simple-cli.js.map
@@ -1 +1 @@
-{"version":3,"sources":["../../../src/cli/simple-cli.js"],"sourcesContent":["#!/usr/bin/env node\n/**\n * Simple CLI wrapper for Claude-Flow (JavaScript version)\n * This version avoids TypeScript issues in node_modules\n */\n\nimport {\n executeCommand,\n hasCommand,\n showCommandHelp,\n showAllCommands,\n listCommands,\n} from './command-registry.js';\nimport { parseFlags } from './utils.js';\nimport {\n args,\n cwd,\n isMainModule,\n exit,\n readTextFile,\n writeTextFile,\n mkdirAsync,\n errors,\n} from './node-compat.js';\nimport { spawn } from 'child_process';\nimport process from 'process';\nimport readline from 'readline';\nimport { getMainHelp, getCommandHelp, getStandardizedCommandHelp } from './help-text.js';\nimport { VERSION } from '../core/version.js';\n\n// Legacy agent type mapping for backward compatibility\nconst LEGACY_AGENT_MAPPING = {\n analyst: 'code-analyzer',\n coordinator: 'task-orchestrator', \n optimizer: 'perf-analyzer',\n documenter: 'api-docs',\n monitor: 'performance-benchmarker',\n specialist: 'system-architect',\n architect: 'system-architect',\n};\n\n// Resolve legacy agent types to current equivalents\nfunction resolveLegacyAgentType(legacyType) {\n return LEGACY_AGENT_MAPPING[legacyType] || legacyType;\n}\n\nfunction printHelp(plain = false) {\n console.log(getMainHelp(plain));\n}\n\nfunction printCommandHelp(command) {\n // Try standardized help first\n const standardCommands = ['agent', 'sparc', 'memory'];\n if (standardCommands.includes(command)) {\n const help = getStandardizedCommandHelp(command);\n console.log(help);\n } else {\n const help = getCommandHelp(command);\n console.log(help);\n }\n}\n\n// Legacy help function for backward compatibility\nfunction printLegacyHelp() {\n console.log(`\n🌊 Claude-Flow v${VERSION} - Enterprise-Grade AI Agent Orchestration Platform\n\n🎯 ENTERPRISE FEATURES: Complete ruv-swarm integration with 90+ MCP tools, neural networking, and production-ready infrastructure\n⚡ ALPHA 85: Advanced automation capabilities & stream-JSON chaining for multi-agent pipelines\n\nUSAGE:\n claude-flow <command> [options]\n\n🚀 INSTALLATION & ENTERPRISE SETUP:\n npx [email protected] init --sparc # Enterprise SPARC + ruv-swarm integration\n \n The --sparc flag creates:\n • Complete ruv-swarm integration with 27 MCP tools\n • Neural network processing with WASM optimization\n • Multi-agent coordination (hierarchical, mesh, ring, star topologies)\n • Cross-session memory and persistent learning\n • GitHub workflow automation (6 specialized modes)\n • Production-ready Docker infrastructure\n • Enterprise security and compliance features\n\n🧠 SWARM INTELLIGENCE COMMANDS (v2.0.0):\n swarm \"objective\" [--strategy] [--mode] [--max-agents N] [--parallel] [--monitor]\n --strategy: research, development, analysis, testing, optimization, maintenance\n --mode: centralized, distributed, hierarchical, mesh, hybrid\n --parallel: Enable parallel execution (2.8-4.4x speed improvement)\n --monitor: Real-time swarm monitoring and performance tracking\n\n🐙 GITHUB WORKFLOW AUTOMATION (v2.0.0):\n github gh-coordinator # GitHub workflow orchestration and coordination\n github pr-manager # Pull request management with multi-reviewer coordination\n github issue-tracker # Issue management and project coordination\n github release-manager # Release coordination and deployment pipelines\n github repo-architect # Repository structure optimization\n github sync-coordinator # Multi-package synchronization and version alignment\n\n🏗️ CORE ENTERPRISE COMMANDS:\n init [--sparc] # Initialize with enterprise environment + ruv-swarm\n start [--ui] [--swarm] # Start orchestration with swarm intelligence\n spawn <type> [--name] # Create AI agent with swarm coordination\n agent <subcommand> # Advanced agent management with neural patterns\n sparc <subcommand> # 17 SPARC modes with neural enhancement\n memory <subcommand> # Cross-session persistent memory with neural learning\n status # Comprehensive system status with performance metrics\n\n🤖 NEURAL AGENT TYPES (ruv-swarm Integration):\n researcher # Research with web access and data analysis\n coder # Code development with neural patterns\n analyst # Performance analysis and optimization\n architect # System design with enterprise patterns\n tester # Comprehensive testing with automation\n coordinator # Multi-agent orchestration and workflow management\n reviewer # Code review with security and quality checks\n optimizer # Performance optimization and bottleneck analysis\n\n🎮 ENTERPRISE QUICK START:\n # Initialize enterprise environment\n npx [email protected] init --sparc\n \n # Start enterprise orchestration with swarm intelligence\n ./claude-flow start --ui --swarm\n \n # Deploy intelligent multi-agent development workflow\n ./claude-flow swarm \"build enterprise API\" --strategy development --parallel --monitor\n \n # GitHub workflow automation\n ./claude-flow github pr-manager \"coordinate release with automated testing\"\n \n # Neural memory management\n ./claude-flow memory store \"architecture\" \"microservices with API gateway pattern\"\n \n # Real-time system monitoring\n ./claude-flow status --verbose\n\n🏢 ENTERPRISE COMMAND CATEGORIES:\n Core Intelligence: swarm, agent, sparc, memory, neural\n GitHub Automation: github (6 specialized modes)\n Development: init, start, status, config, workflow\n Infrastructure: mcp, terminal, session, docker\n Enterprise: project, deploy, cloud, security, analytics, audit\n\n🧠 NEURAL NETWORK FEATURES (v2.0.0):\n • WASM-powered cognitive patterns with SIMD optimization\n • 27 MCP tools for comprehensive workflow automation\n • Cross-session learning and adaptation\n • Real-time performance monitoring (sub-10ms response times)\n • 32.3% token usage reduction through intelligent coordination\n • Self-healing workflows with automatic error recovery\n\n📊 ENTERPRISE PERFORMANCE METRICS:\n • 84.8% SWE-Bench solve rate through coordinated intelligence\n • 2.8-4.4x speed improvement with parallel execution\n • 60% Docker build performance improvement\n • 100% test success rate with comprehensive validation\n • Sub-10ms MCP response times\n\n🔗 INTEGRATION & COMPATIBILITY:\n • Node.js 20+ optimization for enterprise environments\n • Complete Claude Code integration with enhanced capabilities\n • Multi-platform support (Windows, macOS, Linux)\n • Enterprise security with access control and audit logging\n • Cross-package synchronization and dependency management\n\nGET DETAILED HELP:\n claude-flow help <command> # Command-specific enterprise documentation\n claude-flow <command> --help # Alternative help syntax\n \n Examples:\n claude-flow help swarm # Swarm intelligence coordination\n claude-flow help github # GitHub workflow automation\n claude-flow help neural # Neural network processing\n claude-flow help enterprise # Enterprise features and compliance\n\nCOMMON OPTIONS:\n --verbose, -v Enable detailed output with performance metrics\n --help Show command help with enterprise features\n --config <path> Use custom enterprise configuration\n --parallel Enable parallel execution (default for swarms)\n --monitor Real-time monitoring and performance tracking\n\n📚 Documentation: https://github.com/ruvnet/claude-code-flow\n🐝 ruv-swarm: https://github.com/ruvnet/ruv-FANN/tree/main/ruv-swarm\n\n🚀 Enterprise-Grade AI Agent Orchestration - Built with ❤️ by rUv for the Claude community\n`);\n}\n\nfunction printVersion() {\n console.log(`Claude-Flow v${VERSION}`);\n}\n\nfunction printError(message) {\n console.error(`❌ Error: ${message}`);\n}\n\nfunction printSuccess(message) {\n console.log(`✅ ${message}`);\n}\n\nfunction printWarning(message) {\n console.warn(`⚠️ Warning: ${message}`);\n}\n\nfunction showHelpWithCommands(plain = false) {\n printHelp(plain);\n console.log('\\nRegistered Commands:');\n const commands = listCommands();\n for (const command of commands) {\n console.log(` ${command.name.padEnd(12)} ${command.description}`);\n }\n console.log('\\nUse \"claude-flow help <command>\" for detailed usage information');\n}\n\nasync function main() {\n // args is imported from node-compat.js\n\n if (args.length === 0) {\n printHelp(usePlainHelp);\n return;\n }\n\n const command = args[0];\n const { flags, args: parsedArgs } = parseFlags(args.slice(1));\n\n // Check for --plain flag for help early\n const usePlainHelp = args.includes('--plain');\n\n // Apply environment-based smart defaults\n let enhancedFlags = flags;\n try {\n const { detectExecutionEnvironment, applySmartDefaults } = await import(\n './utils/environment-detector.js'\n );\n enhancedFlags = applySmartDefaults(flags);\n\n // Store environment info for commands that need it\n enhancedFlags._environment = detectExecutionEnvironment({ skipWarnings: true });\n } catch (e) {\n // If environment detector fails, continue with original flags\n enhancedFlags = flags;\n }\n\n // Check if user is asking for help on a specific command\n if (\n command !== 'help' &&\n command !== '--help' &&\n command !== '-h' &&\n (enhancedFlags.help || enhancedFlags.h)\n ) {\n const detailedHelp = getCommandHelp(command);\n if (detailedHelp && !detailedHelp.includes('Help not available')) {\n printCommandHelp(command);\n } else if (hasCommand(command)) {\n showCommandHelp(command);\n } else {\n printError(`Unknown command: ${command}`);\n console.log('\\nRun \"claude-flow --help\" to see available commands.');\n }\n return;\n }\n\n // Handle special commands first\n switch (command) {\n case 'env-check':\n case 'environment':\n if (enhancedFlags._environment) {\n const env = enhancedFlags._environment;\n console.log(`\\n🖥️ Environment Detection Results:`);\n console.log(` Terminal: ${env.terminalType}`);\n console.log(` Interactive: ${env.isInteractive ? 'Yes' : 'No'}`);\n console.log(` TTY Support: ${env.supportsRawMode ? 'Yes' : 'No'}`);\n console.log(\n ` Detected: ${env.isVSCode ? 'VS Code' : env.isCI ? 'CI/CD' : env.isDocker ? 'Docker' : env.isSSH ? 'SSH' : 'Standard Terminal'}`,\n );\n if (env.recommendedFlags.length > 0) {\n console.log(`\\n💡 Recommended flags:`);\n console.log(` ${env.recommendedFlags.join(' ')}`);\n }\n if (enhancedFlags.appliedDefaults && enhancedFlags.appliedDefaults.length > 0) {\n console.log(`\\n✅ Auto-applied:`);\n console.log(` ${enhancedFlags.appliedDefaults.join(' ')}`);\n }\n console.log();\n } else {\n console.log('Environment detection not available');\n }\n return;\n case 'version':\n case '--version':\n case '-v':\n printVersion();\n return;\n\n case 'help':\n case '--help':\n case '-h':\n if (parsedArgs.length > 0) {\n // Try our detailed help first\n const detailedHelp = getCommandHelp(parsedArgs[0]);\n if (detailedHelp && !detailedHelp.includes('Help not available')) {\n printCommandHelp(parsedArgs[0]);\n } else {\n // Fall back to command registry help\n showCommandHelp(parsedArgs[0]);\n }\n } else {\n printHelp(usePlainHelp);\n }\n return;\n }\n\n // Check if this is a registered modular command\n if (hasCommand(command)) {\n try {\n await executeCommand(command, parsedArgs, flags);\n return;\n } catch (err) {\n printError(err.message);\n console.log(`\\nRun \"claude-flow ${command} --help\" for usage information.`);\n return;\n }\n }\n\n // Legacy command handling (to be refactored)\n const subArgs = parsedArgs; // Use parsed args for legacy commands\n\n switch (command) {\n case 'status':\n printSuccess('Claude-Flow System Status:');\n console.log('🟡 Status: Not Running (orchestrator not started)');\n console.log('🤖 Agents: 0 active');\n console.log('📋 Tasks: 0 in queue');\n console.log('💾 Memory: Ready');\n console.log('🖥️ Terminal Pool: Ready');\n console.log('🌐 MCP Server: Stopped');\n break;\n\n case 'monitor':\n printSuccess('Starting system monitor...');\n console.log('📊 Real-time monitoring would display here');\n break;\n\n case 'spawn':\n // Convenience alias for agent spawn\n const rawSpawnType = subArgs[0] || 'general';\n const spawnType = resolveLegacyAgentType(rawSpawnType);\n const spawnName = flags.name || `agent-${Date.now()}`;\n\n printSuccess(`Spawning ${spawnType} agent: ${spawnName}`);\n console.log('🤖 Agent would be created with the following configuration:');\n console.log(` Type: ${spawnType}${rawSpawnType !== spawnType ? ` (resolved from: ${rawSpawnType})` : ''}`);\n console.log(` Name: ${spawnName}`);\n console.log(' Capabilities: Research, Analysis, Code Generation');\n console.log(' Status: Ready');\n console.log('\\n📋 Note: Full agent spawning requires orchestrator to be running');\n break;\n\n case 'terminal':\n const terminalCmd = subArgs[0];\n switch (terminalCmd) {\n case 'pool':\n const poolCmd = subArgs[1];\n const detailed = subArgs.includes('--detailed') || subArgs.includes('-d');\n\n if (poolCmd === 'status') {\n printSuccess('Terminal Pool Status:');\n console.log('🖥️ Status: Ready');\n console.log('📊 Pool Size: 10 (default)');\n console.log('🟢 Active Terminals: 0');\n console.log('⏸️ Idle Terminals: 0');\n console.log('📈 Total Created: 0');\n\n if (detailed) {\n console.log('\\n📋 Detailed Information:');\n console.log(' Configuration:');\n console.log(' • Max Pool Size: 10');\n console.log(' • Idle Timeout: 5 minutes');\n console.log(' • Shell: /bin/bash');\n console.log(' • Working Directory: ' + cwd());\n console.log(' Performance:');\n console.log(' • Average Response Time: N/A');\n console.log(' • Terminal Creation Time: N/A');\n console.log(' • Memory Usage: N/A');\n console.log(' Health:');\n console.log(' • Pool Health: Healthy');\n console.log(' • Last Health Check: Just now');\n }\n } else if (poolCmd === 'list') {\n printSuccess('Terminal Pool Sessions:');\n console.log('📋 No active terminal sessions');\n } else if (poolCmd === 'create') {\n printSuccess('Creating new terminal session...');\n console.log('🆔 Terminal ID: term-' + Date.now());\n console.log('🖥️ Status: Created');\n console.log('🐚 Shell: /bin/bash');\n } else if (poolCmd === 'terminate') {\n const termId = subArgs[2];\n if (termId) {\n printSuccess(`Terminating terminal: ${termId}`);\n console.log('✅ Terminal terminated successfully');\n } else {\n printError('Usage: terminal pool terminate <terminal-id>');\n }\n } else if (poolCmd === 'stats') {\n // Pool statistics command\n printSuccess('Terminal Pool Statistics:');\n console.log('📊 Utilization: 0%');\n console.log('⚡ Performance Metrics:');\n console.log(' • Average Command Time: N/A');\n console.log(' • Total Commands: 0');\n console.log(' • Failed Commands: 0');\n console.log('♻️ Recycling Stats:');\n console.log(' • Terminals Recycled: 0');\n console.log(' • Average Lifetime: N/A');\n } else {\n console.log('Terminal pool commands: status, list, create, terminate, stats');\n console.log('Options: --detailed, -d');\n }\n break;\n\n case 'create':\n // Advanced terminal creation\n const nameIndex = subArgs.indexOf('--name');\n const shellIndex = subArgs.indexOf('--shell');\n const wdIndex = subArgs.indexOf('--working-directory');\n const envIndex = subArgs.indexOf('--env');\n const persistentIndex = subArgs.indexOf('--persistent');\n\n const terminalConfig = {\n name: nameIndex >= 0 ? subArgs[nameIndex + 1] : 'terminal-' + Date.now(),\n shell: shellIndex >= 0 ? subArgs[shellIndex + 1] : 'bash',\n workingDirectory: wdIndex >= 0 ? subArgs[wdIndex + 1] : cwd(),\n env: envIndex >= 0 ? subArgs[envIndex + 1] : '',\n persistent: persistentIndex >= 0,\n };\n\n printSuccess('Creating terminal session...');\n console.log(`🆔 Terminal ID: ${terminalConfig.name}`);\n console.log(`🐚 Shell: ${terminalConfig.shell}`);\n console.log(`📁 Working Directory: ${terminalConfig.workingDirectory}`);\n if (terminalConfig.env) {\n console.log(`🔧 Environment: ${terminalConfig.env}`);\n }\n if (terminalConfig.persistent) {\n console.log('💾 Persistent: Yes');\n }\n break;\n\n case 'execute':\n case 'exec':\n const execCmd = subArgs.slice(1).join(' ');\n const sessionFlag = subArgs.indexOf('--session');\n const timeoutFlag = subArgs.indexOf('--timeout');\n const backgroundFlag = subArgs.includes('--background');\n\n if (execCmd && sessionFlag < 0) {\n printSuccess(`Executing command: ${execCmd}`);\n console.log('🖥️ Command would execute in terminal pool');\n console.log('📝 Output would appear here');\n if (backgroundFlag) {\n console.log('🔄 Running in background');\n }\n } else if (sessionFlag >= 0) {\n const sessionId = subArgs[sessionFlag + 1];\n const cmdStart = subArgs.indexOf('\"');\n const cmdEnd = subArgs.lastIndexOf('\"');\n const command =\n cmdStart >= 0 && cmdEnd > cmdStart\n ? subArgs\n .slice(cmdStart, cmdEnd + 1)\n .join(' ')\n .slice(1, -1)\n : 'echo \"No command\"';\n\n printSuccess(`Executing in session ${sessionId}: ${command}`);\n if (timeoutFlag >= 0) {\n console.log(`⏱️ Timeout: ${subArgs[timeoutFlag + 1]}`);\n }\n } else {\n printError('Usage: terminal execute <command> [--session <id>] [--timeout <duration>]');\n }\n break;\n\n case 'batch-exec':\n // Batch command execution\n const batchSession = subArgs.find((arg) => !arg.startsWith('--'));\n const commandsFlag = subArgs.indexOf('--commands');\n const fileFlag = subArgs.indexOf('--file');\n\n if (commandsFlag >= 0) {\n const commands = subArgs[commandsFlag + 1].split(',');\n printSuccess(`Executing ${commands.length} commands in sequence`);\n commands.forEach((cmd, i) => {\n console.log(` ${i + 1}. ${cmd}`);\n });\n } else if (fileFlag >= 0) {\n printSuccess(`Executing commands from file: ${subArgs[fileFlag + 1]}`);\n } else {\n console.log('Usage: terminal batch-exec --commands \"cmd1,cmd2,cmd3\" [--session <id>]');\n }\n break;\n\n case 'list':\n // List all terminal sessions\n const listDetailed = subArgs.includes('--detailed');\n printSuccess('Active Terminal Sessions:');\n console.log('📋 No active terminal sessions');\n if (listDetailed) {\n console.log('\\nSystem Information:');\n console.log(' • Total Sessions Created: 0');\n console.log(' • Sessions Recycled: 0');\n console.log(' • Average Session Lifetime: N/A');\n }\n break;\n\n case 'info':\n // Get terminal info\n const infoSessionId = subArgs[1];\n if (infoSessionId) {\n printSuccess(`Terminal Information: ${infoSessionId}`);\n console.log('🆔 Session ID: ' + infoSessionId);\n console.log('📍 Status: Not found');\n console.log('🐚 Shell: N/A');\n console.log('📁 Working Directory: N/A');\n console.log('⏱️ Created: N/A');\n console.log('📊 Commands Executed: 0');\n } else {\n printError('Usage: terminal info <session-id>');\n }\n break;\n\n case 'attach':\n // Attach to terminal\n const attachId = subArgs[1];\n if (attachId) {\n printSuccess(`Attaching to terminal: ${attachId}`);\n console.log('🔗 Would enter interactive mode');\n console.log('💡 Press Ctrl+D to detach');\n } else {\n printError('Usage: terminal attach <session-id>');\n }\n break;\n\n case 'detach':\n // Detach from terminal\n const detachId = subArgs[1];\n if (detachId) {\n printSuccess(`Detaching from terminal: ${detachId}`);\n console.log('✅ Session continues running in background');\n } else {\n printError('Usage: terminal detach <session-id>');\n }\n break;\n\n case 'terminate':\n // Terminate terminal\n const terminateId = subArgs[1];\n const graceful = subArgs.includes('--graceful');\n if (terminateId) {\n printSuccess(`Terminating terminal: ${terminateId}`);\n if (graceful) {\n console.log('🕐 Graceful shutdown initiated');\n }\n console.log('✅ Terminal terminated');\n } else {\n printError('Usage: terminal terminate <session-id> [--graceful]');\n }\n break;\n\n case 'cleanup':\n // Cleanup idle terminals\n const idleTime = subArgs.find((arg) => arg.includes('--idle-longer-than'));\n printSuccess('Cleaning up idle terminals...');\n console.log('🧹 Scanning for idle sessions');\n if (idleTime) {\n console.log(`⏱️ Idle threshold: ${idleTime.split('=')[1] || '30m'}`);\n }\n console.log('✅ Cleanup complete: 0 terminals removed');\n break;\n\n case 'monitor':\n // Monitor terminal\n const monitorId = subArgs[1];\n if (monitorId) {\n printSuccess(`Monitoring terminal: ${monitorId}`);\n console.log('📊 Real-time metrics would display here');\n console.log(' • CPU: 0%');\n console.log(' • Memory: 0MB');\n console.log(' • I/O: 0 ops/s');\n } else {\n printError('Usage: terminal monitor <session-id>');\n }\n break;\n\n case 'record':\n // Record terminal session\n const recordId = subArgs[1];\n const outputFlag = subArgs.indexOf('--output');\n if (recordId && outputFlag >= 0) {\n printSuccess(`Recording terminal session: ${recordId}`);\n console.log(`📹 Output file: ${subArgs[outputFlag + 1]}`);\n console.log('🔴 Recording started');\n } else {\n printError('Usage: terminal record <session-id> --output <file>');\n }\n break;\n\n case 'replay':\n // Replay terminal session\n const replayFile = subArgs[1];\n if (replayFile) {\n printSuccess(`Replaying session from: ${replayFile}`);\n console.log('▶️ Playback would start here');\n console.log('⏸️ Controls: space=pause, arrows=seek, q=quit');\n } else {\n printError('Usage: terminal replay <recording-file>');\n }\n break;\n\n case 'share':\n // Share terminal session\n const shareId = subArgs[1];\n const accessLevel = subArgs.find((arg) => arg.includes('--access-level'));\n if (shareId) {\n printSuccess(`Sharing terminal session: ${shareId}`);\n console.log(`🔗 Share URL: https://claude-flow.local/terminal/${shareId}/view`);\n console.log(`🔐 Access: ${accessLevel ? accessLevel.split('=')[1] : 'read-only'}`);\n console.log('⏱️ Expires in: 2 hours');\n } else {\n printError('Usage: terminal share <session-id> [--access-level read|write]');\n }\n break;\n\n case 'multi-config':\n // Multi-terminal configuration\n const multiCmd = subArgs[1];\n if (multiCmd === 'create') {\n const configName = subArgs.find((arg) => !arg.startsWith('--'));\n printSuccess(`Creating multi-terminal configuration: ${configName || 'default'}`);\n console.log('📋 Configuration template created');\n } else {\n console.log('Usage: terminal multi-config create --name <name> --config <file>');\n }\n break;\n\n case 'multi-launch':\n // Launch multi-terminal environment\n const envName = subArgs[1];\n if (envName) {\n printSuccess(`Launching multi-terminal environment: ${envName}`);\n console.log('🚀 Starting terminals in dependency order...');\n console.log(' 1. database - Starting...');\n console.log(' 2. backend-api - Waiting for database...');\n console.log(' 3. frontend-app - Waiting for backend...');\n console.log('✅ All terminals launched successfully');\n } else {\n printError('Usage: terminal multi-launch <environment-name>');\n }\n break;\n\n case 'batch-create':\n // Batch create terminals\n const configFile = subArgs.find((arg) => arg.includes('--config'));\n printSuccess('Creating multiple terminal sessions...');\n if (configFile) {\n console.log(`📄 Loading config from: ${configFile.split('=')[1]}`);\n }\n console.log('✅ Created 3 terminal sessions');\n break;\n\n case 'session':\n // Legacy session command handling\n const sessionCmd = subArgs[1];\n if (sessionCmd === 'list') {\n printSuccess('Terminal Sessions:');\n console.log('📋 No active sessions');\n } else if (sessionCmd === 'info') {\n const sessionId = subArgs[2];\n if (sessionId) {\n printSuccess(`Session Info: ${sessionId}`);\n console.log('🆔 Session ID: ' + sessionId);\n console.log('📍 Status: Not found');\n } else {\n printError('Usage: terminal session info <session-id>');\n }\n } else {\n console.log('Terminal session commands: list, info');\n }\n break;\n\n default:\n console.log('Terminal commands:');\n console.log(' Basic:');\n console.log(' pool - Manage terminal pool (status, list, create, terminate)');\n console.log(' create - Create new terminal with options');\n console.log(' execute - Execute command in terminal');\n console.log(' list - List all active terminals');\n console.log(' info - Get terminal information');\n console.log(' Session Control:');\n console.log(' attach - Attach to terminal session');\n console.log(' detach - Detach from terminal');\n console.log(' terminate - Terminate terminal session');\n console.log(' cleanup - Clean up idle terminals');\n console.log(' Advanced:');\n console.log(' batch-exec - Execute multiple commands');\n console.log(' monitor - Monitor terminal metrics');\n console.log(' record - Record terminal session');\n console.log(' replay - Replay recorded session');\n console.log(' share - Share terminal session');\n console.log(' Multi-Terminal:');\n console.log(' multi-config - Create multi-terminal config');\n console.log(' multi-launch - Launch terminal environment');\n console.log(' batch-create - Create multiple terminals');\n console.log('\\nExamples:');\n console.log(' terminal pool status --detailed');\n console.log(' terminal create --name \"dev\" --shell bash --persistent');\n console.log(' terminal execute \"npm test\" --session dev --timeout 5m');\n console.log(' terminal batch-exec --commands \"cd /app,npm install,npm start\"');\n console.log(' terminal monitor dev --metrics cpu,memory');\n }\n break;\n\n case 'session':\n printSuccess('Terminal session manager ready');\n console.log('🖥️ Session operations would be handled here');\n break;\n\n case 'workflow':\n const workflowFile = subArgs[0];\n if (workflowFile) {\n printSuccess(`Executing workflow: ${workflowFile}`);\n console.log('🔄 Workflow execution would start here');\n } else {\n printError('Please specify a workflow file');\n }\n break;\n\n case 'repl':\n printSuccess('Starting interactive REPL mode...');\n await startRepl();\n break;\n\n case 'project':\n const projectCmd = subArgs[0];\n switch (projectCmd) {\n case 'create':\n const projectName = subArgs[1];\n if (!projectName) {\n printError('Usage: project create <name> [options]');\n break;\n }\n\n const isolationFlag = subArgs.indexOf('--isolation');\n const resourceQuotaFlag = subArgs.indexOf('--resource-quota');\n const securityProfileFlag = subArgs.indexOf('--security-profile');\n const templateFlag = subArgs.indexOf('--template');\n\n printSuccess(`Creating project: ${projectName}`);\n console.log('🏗️ Project Configuration:');\n console.log(` Name: ${projectName}`);\n console.log(\n ` Isolation: ${isolationFlag >= 0 ? subArgs[isolationFlag + 1] : 'standard'}`,\n );\n if (resourceQuotaFlag >= 0) {\n console.log(` Resource Quota: ${subArgs[resourceQuotaFlag + 1]}`);\n }\n console.log(\n ` Security Profile: ${securityProfileFlag >= 0 ? subArgs[securityProfileFlag + 1] : 'default'}`,\n );\n if (templateFlag >= 0) {\n console.log(` Template: ${subArgs[templateFlag + 1]}`);\n }\n\n // Create project directory structure\n console.log('\\n📁 Creating project structure:');\n console.log(` ✓ Created /projects/${projectName}/`);\n console.log(` ✓ Created /projects/${projectName}/agents/`);\n console.log(` ✓ Created /projects/${projectName}/workflows/`);\n console.log(` ✓ Created /projects/${projectName}/config/`);\n console.log(` ✓ Created /projects/${projectName}/data/`);\n console.log(` ✓ Created project-config.json`);\n console.log('\\n✅ Project created successfully!');\n break;\n\n case 'switch':\n const switchProject = subArgs[1];\n if (!switchProject) {\n printError('Usage: project switch <name>');\n break;\n }\n printSuccess(`Switching to project: ${switchProject}`);\n console.log('🔄 Loading project context...');\n console.log(' ✓ Project configuration loaded');\n console.log(' ✓ Agent states restored');\n console.log(' ✓ Workflow history loaded');\n console.log(`\\n📍 Active project: ${switchProject}`);\n break;\n\n case 'list':\n const showActive = subArgs.includes('--active');\n const withStats = subArgs.includes('--with-stats');\n\n printSuccess('Available projects:');\n const projects = [\n { name: 'microservices-platform', status: 'active', agents: 12, tasks: 45 },\n { name: 'ai-research', status: 'idle', agents: 3, tasks: 8 },\n { name: 'frontend-apps', status: 'archived', agents: 0, tasks: 0 },\n ];\n\n projects.forEach((project) => {\n if (showActive && project.status !== 'active') return;\n\n console.log(`\\n📦 ${project.name}`);\n console.log(` Status: ${project.status}`);\n if (withStats) {\n console.log(` Active Agents: ${project.agents}`);\n console.log(` Pending Tasks: ${project.tasks}`);\n }\n });\n break;\n\n case 'config':\n const configAction = subArgs[1];\n const configProject = subArgs[2];\n\n if (configAction === 'set' && configProject) {\n const configKey = subArgs[3];\n const configValue = subArgs.slice(4).join(' ');\n\n printSuccess(`Updating project configuration: ${configProject}`);\n console.log(` Setting: ${configKey} = ${configValue}`);\n console.log('✅ Configuration updated');\n } else if (configAction === 'get' && configProject) {\n const configKey = subArgs[3];\n console.log(`Project: ${configProject}`);\n console.log(`${configKey}: (configuration value)`);\n } else {\n console.log('Usage: project config set <project> <key> <value>');\n console.log(' project config get <project> <key>');\n }\n break;\n\n case 'monitor':\n const monitorProject = subArgs[1];\n if (!monitorProject) {\n printError('Usage: project monitor <name> [options]');\n break;\n }\n\n printSuccess(`Monitoring project: ${monitorProject}`);\n console.log('\\n📊 Real-time Metrics:');\n console.log(' Resource Usage:');\n console.log(' • CPU: 45%');\n console.log(' • Memory: 2.3GB / 4GB');\n console.log(' • Storage: 8.5GB / 20GB');\n console.log(' • Network: 23Mbps / 100Mbps');\n console.log(' Agent Performance:');\n console.log(' • Active Agents: 8');\n console.log(' • Average Response Time: 234ms');\n console.log(' • Task Success Rate: 94%');\n console.log(' Costs:');\n console.log(' • Today: $124.50');\n console.log(' • This Month: $2,845.00');\n break;\n\n case 'backup':\n const backupProject = subArgs[1];\n if (!backupProject) {\n printError('Usage: project backup <name> [options]');\n break;\n }\n\n const includeData = subArgs.includes('--include-data');\n const includeConfig = subArgs.includes('--include-config');\n const includeHistory = subArgs.includes('--include-history');\n const outputFlag = subArgs.indexOf('--output');\n\n printSuccess(`Creating backup for project: ${backupProject}`);\n console.log('🗄️ Backup Configuration:');\n console.log(` Include Data: ${includeData ? 'Yes' : 'No'}`);\n console.log(` Include Config: ${includeConfig ? 'Yes' : 'No'}`);\n console.log(` Include History: ${includeHistory ? 'Yes' : 'No'}`);\n\n console.log('\\n📦 Creating backup...');\n console.log(' ✓ Collecting project data');\n console.log(' ✓ Compressing files');\n console.log(' ✓ Encrypting backup');\n\n const outputFile =\n outputFlag >= 0\n ? subArgs[outputFlag + 1]\n : `${backupProject}-backup-${Date.now()}.tar.gz`;\n console.log(`\\n✅ Backup created: ${outputFile}`);\n console.log(' Size: 145MB');\n console.log(' Checksum: sha256:abcd1234...');\n break;\n\n case 'share':\n const shareFrom = subArgs[1];\n const shareTo = subArgs[2];\n\n if (!shareFrom || !shareTo) {\n printError('Usage: project share <from-project> <to-project> [options]');\n break;\n }\n\n const agentsFlag = subArgs.indexOf('--agents');\n const permissionsFlag = subArgs.indexOf('--permissions');\n const durationFlag = subArgs.indexOf('--duration');\n\n printSuccess(`Sharing resources from ${shareFrom} to ${shareTo}`);\n if (agentsFlag >= 0) {\n console.log(` Agents: ${subArgs[agentsFlag + 1]}`);\n }\n if (permissionsFlag >= 0) {\n console.log(` Permissions: ${subArgs[permissionsFlag + 1]}`);\n }\n if (durationFlag >= 0) {\n console.log(` Duration: ${subArgs[durationFlag + 1]}`);\n }\n console.log('\\n✅ Resource sharing configured');\n break;\n\n case 'federation':\n const fedCmd = subArgs[1];\n\n if (fedCmd === 'create') {\n const fedName = subArgs[2];\n const projectsFlag = subArgs.indexOf('--projects');\n\n if (!fedName) {\n printError('Usage: project federation create <name> --projects <project-list>');\n break;\n }\n\n printSuccess(`Creating federation: ${fedName}`);\n if (projectsFlag >= 0) {\n console.log(` Projects: ${subArgs[projectsFlag + 1]}`);\n }\n console.log(' Coordination Model: hierarchical');\n console.log(' Shared Resources: knowledge-base, artifact-registry');\n console.log('\\n✅ Federation created successfully');\n } else if (fedCmd === 'list') {\n printSuccess('Active federations:');\n console.log('\\n🏢 development-ecosystem');\n console.log(' Projects: backend-services, frontend-apps, infrastructure');\n console.log(' Coordinator: infrastructure');\n console.log(' Status: Active');\n } else {\n console.log('Federation commands: create, list, workflow');\n }\n break;\n\n default:\n console.log('Project commands:');\n console.log(' create - Create new project with isolation');\n console.log(' switch - Switch active project context');\n console.log(' list - List all projects');\n console.log(' config - Get/set project configuration');\n console.log(' monitor - Monitor project resources and performance');\n console.log(' backup - Create project backup');\n console.log(' share - Share resources between projects');\n console.log(' federation - Manage project federations');\n console.log('\\nExamples:');\n console.log(\n ' project create \"microservices\" --isolation strict --resource-quota \"agents:15,memory:4GB\"',\n );\n console.log(' project switch \"microservices\"');\n console.log(' project monitor \"microservices\" --real-time');\n }\n break;\n\n case 'cloud':\n const cloudCmd = subArgs[0];\n const cloudProvider = subArgs[1];\n\n switch (cloudCmd) {\n case 'aws':\n switch (cloudProvider) {\n case 'deploy':\n const awsServices = subArgs.indexOf('--services');\n const awsRegions = subArgs.indexOf('--regions');\n const awsHA = subArgs.includes('--ha-configuration');\n const awsCostOpt = subArgs.includes('--cost-optimization');\n\n printSuccess('Deploying Claude-Flow to AWS');\n console.log('☁️ AWS Deployment Configuration:');\n if (awsServices >= 0) {\n console.log(` Services: ${subArgs[awsServices + 1]}`);\n }\n if (awsRegions >= 0) {\n console.log(` Regions: ${subArgs[awsRegions + 1]}`);\n }\n console.log(` High Availability: ${awsHA ? 'Enabled' : 'Disabled'}`);\n console.log(` Cost Optimization: ${awsCostOpt ? 'Enabled' : 'Disabled'}`);\n\n console.log('\\n🚀 Deployment Progress:');\n console.log(' ✓ Creating ECS cluster');\n console.log(' ✓ Setting up Lambda functions');\n console.log(' ✓ Configuring RDS database');\n console.log(' ✓ Setting up S3 buckets');\n console.log(' ✓ Configuring CloudWatch monitoring');\n console.log(' ✓ Setting up load balancers');\n\n console.log('\\n✅ AWS deployment completed successfully');\n console.log(' Cluster ARN: arn:aws:ecs:us-east-1:123456789012:cluster/claude-flow');\n console.log(' API Gateway: https://api.aws.claude-flow.com');\n console.log(' Monitoring: https://console.aws.amazon.com/cloudwatch');\n break;\n\n case 'configure':\n printSuccess('Configuring AWS integration');\n console.log('🔧 AWS Configuration:');\n console.log(' ✓ IAM roles and policies');\n console.log(' ✓ VPC and security groups');\n console.log(' ✓ Auto-scaling policies');\n console.log(' ✓ Backup and disaster recovery');\n console.log(' ✓ Cost monitoring and alerts');\n break;\n\n case 'status':\n printSuccess('AWS Infrastructure Status');\n console.log('\\n🏗️ Infrastructure Health:');\n console.log(' ECS Cluster: 3/3 instances healthy');\n console.log(' Lambda Functions: 12/12 active');\n console.log(' RDS Database: Available (Multi-AZ)');\n console.log(' S3 Buckets: 5 buckets, 2.3TB stored');\n console.log(' CloudWatch: 47 metrics, 0 alarms');\n\n console.log('\\n💰 Cost Summary (This Month):');\n console.log(' Compute (ECS/Lambda): $1,245.50');\n console.log(' Storage (S3/EBS): $342.25');\n console.log(' Network: $87.30');\n console.log(' Total: $1,675.05');\n break;\n\n default:\n console.log('AWS commands: deploy, configure, status');\n }\n break;\n\n case 'azure':\n switch (cloudProvider) {\n case 'deploy':\n const azureServices = subArgs.indexOf('--services');\n const azureRegions = subArgs.indexOf('--regions');\n const azureIntegration = subArgs.includes('--integration-with-aws');\n\n printSuccess('Deploying Claude-Flow to Azure');\n console.log('☁️ Azure Deployment Configuration:');\n if (azureServices >= 0) {\n console.log(` Services: ${subArgs[azureServices + 1]}`);\n }\n if (azureRegions >= 0) {\n console.log(` Regions: ${subArgs[azureRegions + 1]}`);\n }\n console.log(` AWS Integration: ${azureIntegration ? 'Enabled' : 'Disabled'}`);\n\n console.log('\\n🚀 Deployment Progress:');\n console.log(' ✓ Creating AKS cluster');\n console.log(' ✓ Setting up Azure Functions');\n console.log(' ✓ Configuring Cosmos DB');\n console.log(' ✓ Setting up Blob Storage');\n console.log(' ✓ Configuring Azure Monitor');\n console.log(' ✓ Setting up Application Gateway');\n\n console.log('\\n✅ Azure deployment completed successfully');\n console.log(' Resource Group: claude-flow-production');\n console.log(' API Gateway: https://api.azure.claude-flow.com');\n console.log(' Monitoring: https://portal.azure.com');\n break;\n\n case 'configure':\n printSuccess('Configuring Azure integration');\n console.log('🔧 Azure Configuration:');\n console.log(' ✓ Service principals and RBAC');\n console.log(' ✓ Virtual networks and NSGs');\n console.log(' ✓ Auto-scaling rules');\n console.log(' ✓ Backup and site recovery');\n console.log(' ✓ Cost management and budgets');\n break;\n\n case 'status':\n printSuccess('Azure Infrastructure Status');\n console.log('\\n🏗️ Infrastructure Health:');\n console.log(' AKS Cluster: 3/3 nodes ready');\n console.log(' Azure Functions: 8/8 active');\n console.log(' Cosmos DB: Available (Global)');\n console.log(' Blob Storage: 3 containers, 1.8TB stored');\n console.log(' Azure Monitor: 35 metrics, 0 alerts');\n\n console.log('\\n💰 Cost Summary (This Month):');\n console.log(' Compute (AKS/Functions): $985.40');\n console.log(' Storage (Blob/Cosmos): $267.85');\n console.log(' Network: $63.20');\n console.log(' Total: $1,316.45');\n break;\n\n default:\n console.log('Azure commands: deploy, configure, status');\n }\n break;\n\n case 'gcp':\n switch (cloudProvider) {\n case 'deploy':\n const gcpServices = subArgs.indexOf('--services');\n const gcpRegions = subArgs.indexOf('--regions');\n const multiCloud = subArgs.includes('--multi-cloud-networking');\n\n printSuccess('Deploying Claude-Flow to Google Cloud');\n console.log('☁️ GCP Deployment Configuration:');\n if (gcpServices >= 0) {\n console.log(` Services: ${subArgs[gcpServices + 1]}`);\n }\n if (gcpRegions >= 0) {\n console.log(` Regions: ${subArgs[gcpRegions + 1]}`);\n }\n console.log(` Multi-Cloud Networking: ${multiCloud ? 'Enabled' : 'Disabled'}`);\n\n console.log('\\n🚀 Deployment Progress:');\n console.log(' ✓ Creating GKE cluster');\n console.log(' ✓ Setting up Cloud Functions');\n console.log(' ✓ Configuring Cloud SQL');\n console.log(' ✓ Setting up Cloud Storage');\n console.log(' ✓ Configuring Cloud Monitoring');\n console.log(' ✓ Setting up Cloud Load Balancing');\n\n console.log('\\n✅ GCP deployment completed successfully');\n console.log(' Project ID: claude-flow-production');\n console.log(' API Gateway: https://api.gcp.claude-flow.com');\n console.log(' Monitoring: https://console.cloud.google.com');\n break;\n\n case 'configure':\n printSuccess('Configuring GCP integration');\n console.log('🔧 GCP Configuration:');\n console.log(' ✓ Service accounts and IAM');\n console.log(' ✓ VPC networks and firewall rules');\n console.log(' ✓ Auto-scaling policies');\n console.log(' ✓ Backup and disaster recovery');\n console.log(' ✓ Budget alerts and cost optimization');\n break;\n\n case 'status':\n printSuccess('GCP Infrastructure Status');\n console.log('\\n🏗️ Infrastructure Health:');\n console.log(' GKE Cluster: 3/3 nodes ready');\n console.log(' Cloud Functions: 10/10 active');\n console.log(' Cloud SQL: Available (HA)');\n console.log(' Cloud Storage: 4 buckets, 2.1TB stored');\n console.log(' Cloud Monitoring: 42 metrics, 0 incidents');\n\n console.log('\\n💰 Cost Summary (This Month):');\n console.log(' Compute (GKE/Functions): $1,125.30');\n console.log(' Storage (Cloud Storage/SQL): $298.75');\n console.log(' Network: $71.45');\n console.log(' Total: $1,495.50');\n break;\n\n default:\n console.log('GCP commands: deploy, configure, status');\n }\n break;\n\n case 'multi-cloud':\n const multiCloudCmd = subArgs[1];\n\n switch (multiCloudCmd) {\n case 'deploy':\n printSuccess('Deploying multi-cloud Claude-Flow architecture');\n console.log('🌐 Multi-Cloud Deployment:');\n console.log(' Primary: AWS (us-east-1)');\n console.log(' Secondary: Azure (eastus)');\n console.log(' Tertiary: GCP (us-central1)');\n\n console.log('\\n🔗 Cross-Cloud Networking:');\n console.log(' ✓ VPN connections established');\n console.log(' ✓ DNS and load balancing configured');\n console.log(' ✓ Data replication setup');\n console.log(' ✓ Unified monitoring deployed');\n\n console.log('\\n✅ Multi-cloud deployment completed');\n console.log(' Global endpoint: https://global.claude-flow.com');\n console.log(' Failover time: < 30 seconds');\n console.log(' Data consistency: Eventually consistent');\n break;\n\n case 'status':\n printSuccess('Multi-Cloud Infrastructure Status');\n console.log('\\n🌐 Global Infrastructure:');\n console.log(' AWS (Primary): 🟢 Healthy');\n console.log(' Azure (Secondary): 🟢 Healthy');\n console.log(' GCP (Tertiary): 🟢 Healthy');\n\n console.log('\\n📊 Traffic Distribution:');\n console.log(' AWS: 45% (2,341 req/min)');\n console.log(' Azure: 35% (1,823 req/min)');\n console.log(' GCP: 20% (1,042 req/min)');\n\n console.log('\\n💰 Total Cost (This Month): $4,487.00');\n break;\n\n case 'failover':\n const failoverTarget = subArgs[2];\n if (!failoverTarget) {\n printError('Usage: cloud multi-cloud failover <target-cloud>');\n break;\n }\n\n printWarning(`Initiating failover to ${failoverTarget}`);\n console.log('🔄 Failover Process:');\n console.log(' ✓ Health check failed on primary');\n console.log(' ✓ Traffic routing to secondary');\n console.log(' ✓ Database replication verified');\n console.log(' ✓ DNS updates propagated');\n\n console.log(`\\n✅ Failover to ${failoverTarget} completed in 23 seconds`);\n break;\n\n default:\n console.log('Multi-cloud commands: deploy, status, failover');\n }\n break;\n\n case 'kubernetes':\n const k8sCmd = subArgs[1];\n\n switch (k8sCmd) {\n case 'deploy':\n printSuccess('Deploying Claude-Flow to Kubernetes');\n console.log('⚙️ Kubernetes Deployment:');\n console.log(' Namespace: claude-flow');\n console.log(' Replicas: 3');\n console.log(' Resources: 1Gi memory, 500m CPU per pod');\n\n console.log('\\n📦 Deploying Components:');\n console.log(' ✓ Orchestrator deployment');\n console.log(' ✓ MCP server deployment');\n console.log(' ✓ Memory bank deployment');\n console.log(' ✓ Load balancer service');\n console.log(' ✓ Ingress controller');\n console.log(' ✓ ConfigMaps and Secrets');\n\n console.log('\\n✅ Kubernetes deployment completed');\n console.log(' Pods: 3/3 running');\n console.log(' Service: claude-flow-orchestrator-service');\n console.log(' Ingress: https://k8s.claude-flow.com');\n break;\n\n case 'scale':\n const replicas = subArgs[2] || '5';\n printSuccess(`Scaling Claude-Flow to ${replicas} replicas`);\n console.log('📈 Scaling Progress:');\n console.log(` Current replicas: 3`);\n console.log(` Target replicas: ${replicas}`);\n console.log(' ✓ Updating deployment');\n console.log(' ✓ Rolling update in progress');\n console.log(` ✓ Scaled to ${replicas} replicas successfully`);\n break;\n\n case 'status':\n printSuccess('Kubernetes Cluster Status');\n console.log('\\n⚙️ Cluster Information:');\n console.log(' Namespace: claude-flow');\n console.log(' Deployments: 3/3 ready');\n console.log(' Pods: 3/3 running');\n console.log(' Services: 2 active');\n console.log(' ConfigMaps: 2');\n console.log(' Secrets: 1');\n\n console.log('\\n📊 Resource Usage:');\n console.log(' CPU: 1.2/3.0 cores (40%)');\n console.log(' Memory: 2.1/3.0 GB (70%)');\n console.log(' Storage: 8.5/50 GB (17%)');\n break;\n\n default:\n console.log('Kubernetes commands: deploy, scale, status');\n }\n break;\n\n default:\n console.log('Cloud commands:');\n console.log(' aws - Amazon Web Services integration');\n console.log(' azure - Microsoft Azure integration');\n console.log(' gcp - Google Cloud Platform integration');\n console.log(' multi-cloud - Multi-cloud deployment and management');\n console.log(' kubernetes - Kubernetes deployment and management');\n console.log('\\nExamples:');\n console.log(\n ' cloud aws deploy --services \"ecs,lambda,rds\" --regions \"us-east-1,us-west-2\"',\n );\n console.log(' cloud azure deploy --services \"aks,functions,cosmos-db\"');\n console.log(' cloud gcp deploy --services \"gke,cloud-functions,cloud-sql\"');\n console.log(' cloud multi-cloud deploy');\n console.log(' cloud kubernetes deploy');\n }\n break;\n\n case 'claude':\n const claudeCmd = subArgs[0];\n switch (claudeCmd) {\n case 'spawn':\n // Extract task description and flags\n let taskEndIndex = subArgs.length;\n for (let i = 1; i < subArgs.length; i++) {\n if (subArgs[i].startsWith('-')) {\n taskEndIndex = i;\n break;\n }\n }\n\n const task = subArgs.slice(1, taskEndIndex).join(' ');\n if (!task) {\n printError('Usage: claude spawn <task description> [options]');\n break;\n }\n\n // Parse flags\n const flags = {};\n for (let i = taskEndIndex; i < subArgs.length; i++) {\n const arg = subArgs[i];\n if (arg === '--tools' || arg === '-t') {\n flags.tools = subArgs[++i];\n } else if (arg === '--no-permissions') {\n flags.noPermissions = true;\n } else if (arg === '--config' || arg === '-c') {\n flags.config = subArgs[++i];\n } else if (arg === '--mode' || arg === '-m') {\n flags.mode = subArgs[++i];\n } else if (arg === '--parallel') {\n flags.parallel = true;\n } else if (arg === '--research') {\n flags.research = true;\n } else if (arg === '--coverage') {\n flags.coverage = parseInt(subArgs[++i]);\n } else if (arg === '--commit') {\n flags.commit = subArgs[++i];\n } else if (arg === '--verbose' || arg === '-v') {\n flags.verbose = true;\n } else if (arg === '--dry-run' || arg === '-d') {\n flags.dryRun = true;\n }\n }\n\n // Build tools list\n let tools = flags.tools || 'View,Edit,Replace,GlobTool,GrepTool,LS,Bash';\n if (flags.parallel) {\n tools += ',BatchTool,dispatch_agent';\n }\n if (flags.research) {\n tools += ',WebFetchTool';\n }\n\n const instanceId = `claude-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n\n if (flags.dryRun) {\n printWarning('DRY RUN - Would execute:');\n console.log(`Command: claude \"<enhanced task with guidance>\" --allowedTools ${tools}`);\n console.log(`Instance ID: ${instanceId}`);\n console.log(`Task: ${task}`);\n console.log(`Tools: ${tools}`);\n console.log(`Mode: ${flags.mode || 'full'}`);\n console.log(`Coverage: ${flags.coverage || 80}%`);\n console.log(`Commit: ${flags.commit || 'phase'}`);\n console.log(`\\nEnhanced Features:`);\n console.log(` - Memory Bank enabled via: npx claude-flow memory commands`);\n console.log(` - Coordination ${flags.parallel ? 'enabled' : 'disabled'}`);\n console.log(` - Access Claude-Flow features through Bash tool`);\n } else {\n printSuccess(`Spawning Claude instance: ${instanceId}`);\n console.log(`📝 Original Task: ${task}`);\n console.log(`🔧 Tools: ${tools}`);\n console.log(`⚙️ Mode: ${flags.mode || 'full'}`);\n console.log(`📊 Coverage: ${flags.coverage || 80}%`);\n console.log(`💾 Commit: ${flags.commit || 'phase'}`);\n console.log(`✨ Enhanced with Claude-Flow guidance for memory and coordination`);\n console.log('');\n console.log('📋 Task will be enhanced with:');\n console.log(' - Memory Bank instructions (store/retrieve)');\n console.log(' - Coordination capabilities (swarm management)');\n console.log(' - Best practices for multi-agent workflows');\n console.log('');\n\n // Build the actual claude command with enhanced guidance\n let enhancedTask = `# Task Assignment\n\n## Your Primary Task\n${task}\n\n## Development Environment\n\nYou are working in a development environment with advanced orchestration capabilities available if needed.\n\n### Project Context\n- Working Directory: ${process.cwd()}\n- Instance ID: ${instanceId}\n- Development Mode: ${flags.mode || 'full'}\n${flags.coverage ? `- Test Coverage Target: ${flags.coverage}%` : ''}\n${flags.commit ? `- Git Commit Strategy: ${flags.commit}` : ''}\n${flags.config ? `- MCP Config: ${flags.config}` : ''}\n\n### Available Tools\n- You have access to these tools: ${tools}\n${flags.tools ? `- Custom tools specified: ${flags.tools}` : ''}\n\n### Optional Orchestration Features\n\nIf this task requires complex coordination, memory persistence, or multi-agent collaboration, you can use the claude-flow system:\n\n1. **Persistent Memory** (if needed for your task)\n - Store project data: \\`npx claude-flow memory store <key> \"<value>\"\\`\n - Retrieve stored data: \\`npx claude-flow memory query <key>\\`\n - Export/Import memory: \\`npx claude-flow memory export/import <file>\\`\n\n2. **Task Coordination** (if working on complex multi-part tasks)\n - Check task status: \\`npx claude-flow status\\`\n - Monitor progress: \\`npx claude-flow monitor\\`\n - List active tasks: \\`npx claude-flow task list\\`\n\n3. **Multi-Agent Collaboration** (if task benefits from parallelization)\n - Spawn specialized agents: \\`npx claude-flow agent spawn <type> --name <name>\\`\n - Create subtasks: \\`npx claude-flow task create <type> \"<description>\"\\`\n - Coordinate work: \\`npx claude-flow task assign <task-id> <agent-id>\\``;\n\n if (flags.parallel) {\n enhancedTask += `\n\n **Parallel Execution Enabled**: The orchestration system can help coordinate parallel work if needed.`;\n }\n\n if (flags.research) {\n enhancedTask += `\n\n **Research Mode**: Web research tools are available for information gathering.`;\n }\n\n enhancedTask += `\n\n### Task Execution Guidelines\n\n1. **Focus on Your Primary Objective**:\n - Understand the specific requirements of the task\n - Plan your approach based on the project's needs\n - Use appropriate tools and practices for the technology stack\n ${flags.mode === 'backend-only' ? ' - Focus on backend implementation' : ''}\n ${flags.mode === 'frontend-only' ? ' - Focus on frontend implementation' : ''}\n ${flags.mode === 'api-only' ? ' - Focus on API design and implementation' : ''}\n\n2. **Development Best Practices**:\n - Write clean, maintainable code following project conventions\n - Include appropriate tests and documentation\n - Use version control effectively\n ${flags.coverage ? ` - Ensure test coverage meets ${flags.coverage}% target` : ''}\n ${flags.commit === 'phase' ? ' - Commit changes after completing major phases' : ''}\n ${flags.commit === 'feature' ? ' - Commit changes after each feature is complete' : ''}\n ${flags.commit === 'manual' ? ' - Only commit when explicitly requested' : ''}\n\n3. **Leverage Orchestration When Beneficial**:\n - For complex tasks requiring persistent state, use the memory bank\n - For multi-part projects, use task coordination features\n - For parallelizable work, consider multi-agent approaches\n ${flags.parallel ? ' - Parallel capabilities are enabled for this task' : ''}\n ${flags.research ? ' - Research tools are available if needed' : ''}\n ${flags.noPermissions ? ' - Running with --no-permissions mode' : ''}\n ${flags.verbose ? ' - Verbose mode enabled for detailed output' : ''}\n\n## Getting Started\n\nBegin working on your task. The orchestration features are available as tools to help you be more effective, but your primary focus should be on delivering the requested functionality.\n\n### Quick Reference (if using orchestration features)\n\n\\`\\`\\`bash\n# Example: Storing project-specific data\nBash(\"npx claude-flow memory store project_config '{\\\\\"name\\\\\": \\\\\"my-app\\\\\", \\\\\"version\\\\\": \\\\\"1.0.0\\\\\"}'\")\n\n# Example: Checking for previous work\nBash(\"npx claude-flow memory query previous_implementation\")\n\n# Example: Creating subtasks for complex projects\nBash(\"npx claude-flow task create frontend 'Build React components'\")\nBash(\"npx claude-flow task create backend 'Implement API endpoints'\")\n\\`\\`\\`\n\nRemember: These are optional tools. Use them when they add value to your development process.\n\n## Development Mode: ${flags.mode || 'full'}\n${flags.mode === 'backend-only' ? `Focus on server-side implementation, APIs, and business logic.` : ''}\n${flags.mode === 'frontend-only' ? `Focus on client-side implementation, UI/UX, and user interactions.` : ''}\n${flags.mode === 'api-only' ? `Focus on API design, documentation, and endpoint implementation.` : ''}\n${flags.mode === 'full' || !flags.mode ? `Full-stack development covering all aspects of the application.` : ''}\n\n`;\n\n const claudeArgs = [enhancedTask];\n claudeArgs.push('--allowedTools', tools);\n\n // DEBUG: Log what we're about to pass\n console.log('\\n🔍 DEBUG - Command Construction:');\n console.log(`First arg length: ${claudeArgs[0].length} chars`);\n console.log(`First 100 chars: ${claudeArgs[0].substring(0, 100)}...`);\n console.log(`Args count: ${claudeArgs.length}`);\n\n if (flags.noPermissions) {\n claudeArgs.push('--dangerously-skip-permissions');\n }\n\n if (flags.config) {\n claudeArgs.push('--mcp-config', flags.config);\n }\n\n if (flags.verbose) {\n claudeArgs.push('--verbose');\n }\n\n // Execute the actual claude command\n try {\n // Debug: Log the actual command being executed\n if (flags.verbose) {\n console.log('Debug - Executing command:');\n console.log(\n `claude ${claudeArgs.map((arg) => (arg.includes(' ') || arg.includes('\\n') ? `\"${arg}\"` : arg)).join(' ')}`,\n );\n }\n\n const child = spawn('claude', claudeArgs, {\n env: {\n ...process.env,\n CLAUDE_INSTANCE_ID: instanceId,\n CLAUDE_FLOW_MODE: flags.mode || 'full',\n CLAUDE_FLOW_COVERAGE: (flags.coverage || 80).toString(),\n CLAUDE_FLOW_COMMIT: flags.commit || 'phase',\n // Add claude-flow specific features\n CLAUDE_FLOW_MEMORY_ENABLED: 'true',\n CLAUDE_FLOW_MEMORY_NAMESPACE: 'default',\n CLAUDE_FLOW_COORDINATION_ENABLED: flags.parallel ? 'true' : 'false',\n CLAUDE_FLOW_FEATURES: 'memory,coordination,swarm',\n },\n stdio: 'inherit',\n });\n\n // Wait for process to exit\n await new Promise((resolve) => {\n child.on('exit', (code) => {\n if (code === 0) {\n printSuccess(`Claude instance ${instanceId} completed successfully`);\n } else {\n printError(`Claude instance ${instanceId} exited with code ${code}`);\n }\n resolve();\n });\n });\n } catch (err) {\n printError(`Failed to spawn Claude: ${err.message}`);\n console.log('Make sure you have the Claude CLI installed.');\n }\n }\n break;\n\n case 'batch':\n const workflowFile = subArgs[1];\n if (!workflowFile) {\n printError('Usage: claude batch <workflow-file>');\n break;\n }\n printSuccess(`Loading workflow: ${workflowFile}`);\n console.log('📋 Batch execution would process workflow file');\n break;\n\n default:\n console.log('Claude commands: spawn, batch');\n console.log('\\nExamples:');\n console.log(\n ' claude-flow claude spawn \"implement user authentication\" --research --parallel',\n );\n console.log(' claude-flow claude spawn \"fix bug in payment system\" --no-permissions');\n console.log(' claude-flow claude batch workflow.json --dry-run');\n }\n break;\n\n case 'deploy':\n const deployCmd = subArgs[0];\n switch (deployCmd) {\n case 'ha-cluster':\n const nodes = subArgs.find((arg) => arg.includes('--nodes'));\n const regions = subArgs.find((arg) => arg.includes('--regions'));\n const replicationFactor = subArgs.find((arg) => arg.includes('--replication-factor'));\n\n printSuccess('Deploying High Availability Cluster...');\n console.log('🏗️ HA Configuration:');\n console.log(` Nodes: ${nodes ? nodes.split('=')[1] : '3'}`);\n console.log(\n ` Regions: ${regions ? regions.split('=')[1] : 'us-east-1,us-west-2,eu-west-1'}`,\n );\n console.log(\n ` Replication Factor: ${replicationFactor ? replicationFactor.split('=')[1] : '2'}`,\n );\n console.log(' Load Balancer: nginx');\n console.log(' Health Checks: comprehensive');\n\n console.log('\\n🚀 Deployment Progress:');\n console.log(' ✓ Provisioning nodes in us-east-1');\n console.log(' ✓ Provisioning nodes in us-west-2');\n console.log(' ✓ Provisioning nodes in eu-west-1');\n console.log(' ✓ Configuring load balancer');\n console.log(' ✓ Setting up health checks');\n console.log(' ✓ Establishing replication');\n console.log('\\n✅ HA cluster deployed successfully!');\n console.log(' Cluster endpoint: https://claude-flow-ha.example.com');\n break;\n\n case 'scaling':\n const scalingAction = subArgs[1];\n\n if (scalingAction === 'configure') {\n printSuccess('Configuring Auto-Scaling...');\n console.log('📈 Scaling Configuration:');\n console.log(' Min Instances: 2');\n console.log(' Max Instances: 50');\n console.log(' Scale Up Threshold: CPU:70%, Memory:80%');\n console.log(' Scale Down Threshold: CPU:30%, Memory:40%');\n console.log(' Cool-down Periods: Up:300s, Down:600s');\n console.log('\\n✅ Auto-scaling configured');\n } else if (scalingAction === 'predictive') {\n printSuccess('Enabling Predictive Scaling...');\n console.log('🔮 Predictive Configuration:');\n console.log(' Forecast Horizon: 1 hour');\n console.log(' Learning Period: 7 days');\n console.log(' Confidence Threshold: 0.8');\n console.log(' ML Model: LSTM-based forecasting');\n console.log('\\n✅ Predictive scaling enabled');\n } else {\n console.log('Scaling commands: configure, predictive, status');\n }\n break;\n\n case 'security':\n const securityAction = subArgs[1];\n\n if (securityAction === 'harden') {\n printSuccess('Applying Security Hardening...');\n console.log('🔒 Security Configuration:');\n console.log(' Profile: enterprise');\n console.log(' Encryption: all-traffic, at-rest');\n console.log(' Authentication: multi-factor');\n console.log(' Authorization: RBAC');\n console.log(' Audit Logging: comprehensive');\n console.log(' Compliance: SOC2, GDPR, HIPAA');\n\n console.log('\\n🛡️ Applying security measures:');\n console.log(' ✓ Enabling encryption at rest');\n console.log(' ✓ Configuring TLS 1.3 minimum');\n console.log(' ✓ Setting up MFA requirements');\n console.log(' ✓ Implementing RBAC policies');\n console.log(' ✓ Enabling audit logging');\n console.log(' ✓ Applying compliance controls');\n console.log('\\n✅ Security hardening complete');\n } else if (securityAction === 'monitor') {\n printSuccess('Security Monitoring Active');\n console.log('🔍 Real-time Security Status:');\n console.log(' Threat Level: Low');\n console.log(' Active Sessions: 42');\n console.log(' Failed Auth Attempts: 3 (last 24h)');\n console.log(' Anomalies Detected: 0');\n console.log(' Compliance Status: ✅ Compliant');\n } else {\n console.log('Security commands: harden, policy, rbac, monitor');\n }\n break;\n\n case 'kubernetes':\n case 'k8s':\n printSuccess('Deploying to Kubernetes...');\n console.log('☸️ Kubernetes Deployment:');\n console.log(' Namespace: claude-flow');\n console.log(' Replicas: 3');\n console.log(' Image: claude-flow/orchestrator:latest');\n console.log(' Service Type: LoadBalancer');\n\n console.log('\\n📦 Creating resources:');\n console.log(' ✓ Created namespace/claude-flow');\n console.log(' ✓ Created deployment/claude-flow-orchestrator');\n console.log(' ✓ Created service/claude-flow-orchestrator-service');\n console.log(' ✓ Created configmap/claude-flow-config');\n console.log(' ✓ Created secret/claude-flow-secrets');\n console.log('\\n✅ Kubernetes deployment complete');\n console.log(' Service endpoint: http://a1b2c3d4.elb.amazonaws.com');\n break;\n\n default:\n console.log('Deploy commands:');\n console.log(' ha-cluster - Deploy high availability cluster');\n console.log(' scaling - Configure auto-scaling');\n console.log(' security - Security hardening and monitoring');\n console.log(' kubernetes - Deploy to Kubernetes cluster');\n console.log('\\nExamples:');\n console.log(' deploy ha-cluster --nodes=3 --regions=\"us-east-1,us-west-2\"');\n console.log(' deploy scaling configure --min=2 --max=50');\n console.log(' deploy security harden --profile enterprise');\n }\n break;\n\n case 'analytics':\n const analyticsCmd = subArgs[0];\n switch (analyticsCmd) {\n case 'performance':\n printSuccess('Performance Analytics Report');\n console.log('\\n📊 System Performance (Last 30 Days):');\n console.log(' Agent Productivity:');\n console.log(' • Tasks Completed: 12,847');\n console.log(' • Average Task Time: 3.4 minutes');\n console.log(' • Success Rate: 94.2%');\n console.log(' Resource Efficiency:');\n console.log(' • CPU Utilization: 67% average');\n console.log(' • Memory Usage: 2.8GB average');\n console.log(' • Cost per Task: $0.024');\n console.log(' Trends:');\n console.log(' • Performance: ↑ 12% improvement');\n console.log(' • Efficiency: ↑ 8% improvement');\n console.log(' • Costs: ↓ 15% reduction');\n break;\n\n case 'business-impact':\n printSuccess('Business Impact Analysis');\n console.log('\\n💼 Business Metrics:');\n console.log(' Productivity Gains:');\n console.log(' • Development Velocity: +45%');\n console.log(' • Time to Market: -30%');\n console.log(' • Defect Rate: -62%');\n console.log(' Cost Savings:');\n console.log(' • Monthly Savings: $24,500');\n console.log(' • ROI: 312%');\n console.log(' • Payback Period: 3.2 months');\n console.log(' Quality Improvements:');\n console.log(' • Code Coverage: 92%');\n console.log(' • Customer Satisfaction: +18%');\n break;\n\n case 'cost':\n const costCmd = subArgs[1];\n if (costCmd === 'analyze') {\n printSuccess('Cost Analysis Report');\n console.log('\\n💰 Cost Breakdown:');\n console.log(' By Project:');\n console.log(' • microservices-platform: $8,234 (41%)');\n console.log(' • ai-research: $5,123 (26%)');\n console.log(' • frontend-apps: $3,456 (17%)');\n console.log(' • other: $3,187 (16%)');\n console.log(' By Resource:');\n console.log(' • Compute: $12,450 (62%)');\n console.log(' • Storage: $4,230 (21%)');\n console.log(' • Network: $2,120 (11%)');\n console.log(' • Other: $1,200 (6%)');\n console.log(' Optimization Opportunities:');\n console.log(' • Use spot instances: Save $3,200/month');\n console.log(' • Optimize storage: Save $800/month');\n console.log(' • Schedule off-peak: Save $1,500/month');\n } else {\n console.log('Cost commands: analyze, optimize, budget');\n }\n break;\n\n default:\n console.log('Analytics commands:');\n console.log(' performance - System performance analytics');\n console.log(' business-impact - Business impact analysis');\n console.log(' cost - Cost analysis and optimization');\n console.log(' capacity - Capacity planning');\n console.log('\\nExamples:');\n console.log(' analytics performance --time-range 30d');\n console.log(' analytics cost analyze --granularity project');\n }\n break;\n\n case 'security':\n const securityCmd = subArgs[0];\n switch (securityCmd) {\n case 'status':\n printSuccess('Enterprise Security Status');\n console.log('\\n🔐 Authentication:');\n console.log(' Method: Token-based (JWT)');\n console.log(' MFA: Enabled (TOTP, SMS, Hardware Keys)');\n console.log(' Sessions: 42 active');\n console.log(' Session Timeout: 4 hours');\n\n console.log('\\n🛡️ Authorization:');\n console.log(' Model: Role-Based Access Control (RBAC)');\n console.log(' Roles: 5 defined (admin, developer, operator, auditor, viewer)');\n console.log(' Permissions: 47 granular permissions');\n console.log(' Policy Engine: Active');\n\n console.log('\\n🚦 Rate Limiting:');\n console.log(' Global Limit: 1000 req/min');\n console.log(' Per-User Limit: 100 req/min');\n console.log(' Burst Capacity: 200 requests');\n console.log(' Current Usage: 245 req/min (24.5%)');\n\n console.log('\\n⚡ Circuit Breakers:');\n console.log(' Total Breakers: 12');\n console.log(' Status: 10 closed, 1 half-open, 1 open');\n console.log(' Last Triggered: api-gateway (2 minutes ago)');\n\n console.log('\\n📝 Audit Logging:');\n console.log(' Status: Active');\n console.log(' Storage: Encrypted S3 bucket');\n console.log(' Retention: 7 years');\n console.log(' Events Today: 48,234');\n console.log(' Compliance: SOC2, GDPR, HIPAA compliant');\n break;\n\n case 'auth':\n const authAction = subArgs[1];\n\n if (authAction === 'configure') {\n printSuccess('Configuring Authentication...');\n console.log('🔐 Authentication Configuration:');\n console.log(' Method: JWT with RS256');\n console.log(' Token Expiry: 4 hours');\n console.log(' Refresh Token: 30 days');\n console.log(' MFA Required: Yes');\n console.log(' Password Policy:');\n console.log(' • Minimum length: 12 characters');\n console.log(' • Complexity: Upper, lower, numbers, symbols');\n console.log(' • History: Last 12 passwords');\n console.log(' • Expiry: 90 days');\n console.log('\\n✅ Authentication configured');\n } else if (authAction === 'sessions') {\n printSuccess('Active Sessions:');\n console.log('\\n🔑 Current Sessions:');\n console.log('┌─────────────────┬──────────┬──────────────┬─────────────┬───────────┐');\n console.log('│ User │ Role │ IP Address │ Login Time │ MFA │');\n console.log('├─────────────────┼──────────┼──────────────┼─────────────┼───────────┤');\n console.log('│ [email protected] │ admin │ 10.0.1.45 │ 2h ago │ Hardware │');\n console.log('│ [email protected] │ developer│ 10.0.2.123 │ 45m ago │ TOTP │');\n console.log('│ [email protected]│ operator │ 10.0.1.200 │ 1h ago │ SMS │');\n console.log('└─────────────────┴──────────┴──────────────┴─────────────┴───────────┘');\n } else if (authAction === 'mfa') {\n printSuccess('Multi-Factor Authentication Status:');\n console.log(' Enforcement: Required for all users');\n console.log(' Methods Available:');\n console.log(' • TOTP (Time-based One-Time Password)');\n console.log(' • SMS (Text message)');\n console.log(' • Hardware Keys (FIDO2/WebAuthn)');\n console.log(' • Backup Codes');\n console.log(' Users with MFA: 98% (147/150)');\n } else {\n console.log('Auth commands: configure, sessions, mfa, tokens');\n }\n break;\n\n case 'rbac':\n const rbacAction = subArgs[1];\n\n if (rbacAction === 'roles') {\n printSuccess('RBAC Roles:');\n console.log('\\n👥 Defined Roles:');\n console.log('\\n📛 admin (3 users)');\n console.log(' Permissions: * (all permissions)');\n console.log(' Conditions: MFA required, IP restriction');\n\n console.log('\\n📛 developer (45 users)');\n console.log(' Permissions:');\n console.log(' • projects:read,write');\n console.log(' • agents:spawn,monitor');\n console.log(' • tasks:create,monitor');\n console.log(' Conditions: Time window 06:00-22:00');\n\n console.log('\\n📛 operator (12 users)');\n console.log(' Permissions:');\n console.log(' • system:monitor');\n console.log(' • agents:list,info');\n console.log(' • tasks:list,status');\n\n console.log('\\n📛 auditor (5 users)');\n console.log(' Permissions:');\n console.log(' • audit:read');\n console.log(' • system:logs');\n console.log(' • reports:generate');\n\n console.log('\\n📛 viewer (85 users)');\n console.log(' Permissions:');\n console.log(' • *:read (read-only access)');\n } else if (rbacAction === 'assign') {\n const user = subArgs[2];\n const role = subArgs[3];\n if (user && role) {\n printSuccess(`Assigning role ${role} to user ${user}`);\n console.log('✅ Role assignment complete');\n console.log(' Effective immediately');\n console.log(' Audit log entry created');\n } else {\n printError('Usage: security rbac assign <user> <role>');\n }\n } else {\n console.log('RBAC commands: roles, permissions, assign, revoke');\n }\n break;\n\n case 'rate-limit':\n const rateLimitAction = subArgs[1];\n\n if (rateLimitAction === 'status') {\n printSuccess('Rate Limiting Status:');\n console.log('\\n📊 Current Limits:');\n console.log(' Global:');\n console.log(' • Limit: 1000 requests/minute');\n console.log(' • Current: 245 requests/minute (24.5%)');\n console.log(' • Available: 755 requests');\n console.log(' Per-User:');\n console.log(' • Default: 100 requests/minute');\n console.log(' • Premium: 500 requests/minute');\n console.log(' Per-Endpoint:');\n console.log(' • /api/agents/spawn: 10/minute');\n console.log(' • /api/tasks/create: 50/minute');\n console.log(' • /api/memory/query: 200/minute');\n\n console.log('\\n🚨 Recent Violations:');\n console.log(' • user123: 2 violations (15 min ago)');\n console.log(' • api-client-7: 1 violation (1 hour ago)');\n } else if (rateLimitAction === 'configure') {\n printSuccess('Configuring Rate Limits...');\n console.log(' Global limit: 1000 req/min');\n console.log(' Burst capacity: 200 requests');\n console.log(' Cooldown period: 60 seconds');\n console.log(' Headers: X-RateLimit-* enabled');\n console.log('\\n✅ Rate limiting configured');\n } else {\n console.log('Rate limit commands: status, configure, reset');\n }\n break;\n\n case 'circuit-breaker':\n const cbAction = subArgs[1];\n\n if (cbAction === 'status') {\n printSuccess('Circuit Breaker Status:');\n console.log('\\n⚡ Active Circuit Breakers:');\n console.log('┌──────────────────┬─────────┬──────────┬───────────┬─────────────┐');\n console.log('│ Service │ State │ Failures │ Successes │ Last Change │');\n console.log('├──────────────────┼─────────┼──────────┼───────────┼─────────────┤');\n console.log('│ api-gateway │ OPEN │ 15 │ 0 │ 2m ago │');\n console.log('│ auth-service │ CLOSED │ 0 │ 1,234 │ 1h ago │');\n console.log('│ memory-service │ CLOSED │ 1 │ 5,678 │ 3h ago │');\n console.log('│ agent-manager │ HALF │ 3 │ 45 │ 5m ago │');\n console.log('└──────────────────┴─────────┴──────────┴───────────┴─────────────┘');\n\n console.log('\\n📈 Configuration:');\n console.log(' Failure Threshold: 10 failures');\n console.log(' Success Threshold: 5 successes');\n console.log(' Timeout: 60 seconds');\n console.log(' Half-Open Requests: 3 max');\n } else if (cbAction === 'reset') {\n const service = subArgs[2];\n if (service) {\n printSuccess(`Resetting circuit breaker: ${service}`);\n console.log('✅ Circuit breaker reset to CLOSED state');\n } else {\n console.log('All circuit breakers reset');\n }\n } else {\n console.log('Circuit breaker commands: status, reset, configure');\n }\n break;\n\n case 'audit':\n const auditAction = subArgs[1];\n\n if (auditAction === 'status') {\n printSuccess('Audit Logging Status:');\n console.log(' Status: Active');\n console.log(' Storage Backend: AWS S3 (encrypted)');\n console.log(' Retention Period: 7 years');\n console.log(' Compliance: SOC2, GDPR, HIPAA');\n console.log('\\n📊 Statistics (Last 24h):');\n console.log(' Total Events: 48,234');\n console.log(' Authentication: 1,234');\n console.log(' Authorization: 15,678');\n console.log(' Data Access: 23,456');\n console.log(' Configuration Changes: 89');\n console.log(' Security Events: 12');\n } else if (auditAction === 'search') {\n const query = subArgs.slice(2).join(' ');\n printSuccess(`Searching audit logs: \"${query || 'recent'}\"`);\n console.log('\\n📋 Recent Audit Events:');\n console.log(\n '2024-01-10 14:23:45 | AUTH_SUCCESS | [email protected] | Login from 10.0.1.45',\n );\n console.log('2024-01-10 14:24:12 | PERMISSION_GRANTED | [email protected] | agents.spawn');\n console.log('2024-01-10 14:24:13 | AGENT_CREATED | [email protected] | agent-12345');\n console.log(\n '2024-01-10 14:25:01 | CONFIG_CHANGED | [email protected] | terminal.poolSize: 10->20',\n );\n console.log(\n '2024-01-10 14:26:30 | PERMISSION_DENIED | [email protected] | admin.users.delete',\n );\n } else if (auditAction === 'export') {\n printSuccess('Exporting audit logs...');\n console.log(' Time range: Last 30 days');\n console.log(' Format: JSON (encrypted)');\n console.log(' Destination: audit-export-20240110.json.enc');\n console.log('\\n✅ Export complete: 145,234 events');\n } else {\n console.log('Audit commands: status, search, export, configure');\n }\n break;\n\n case 'compliance':\n printSuccess('Compliance Status:');\n console.log('\\n🏛️ Active Compliance Frameworks:');\n console.log('\\n✅ SOC2 Type II');\n console.log(' Last Audit: 2023-10-15');\n console.log(' Next Audit: 2024-04-15');\n console.log(' Status: Compliant');\n console.log(' Controls: 89/89 passing');\n\n console.log('\\n✅ GDPR (General Data Protection Regulation)');\n console.log(' Data Protection Officer: Jane Smith');\n console.log(' Privacy Impact Assessments: 12 completed');\n console.log(' Data Subject Requests: 3 pending, 45 completed');\n console.log(' Status: Compliant');\n\n console.log('\\n✅ HIPAA (Health Insurance Portability Act)');\n console.log(' BAA Agreements: 5 active');\n console.log(' PHI Encryption: AES-256 at rest, TLS 1.3 in transit');\n console.log(' Access Controls: Implemented');\n console.log(' Status: Compliant');\n\n console.log('\\n📋 Required Actions:');\n console.log(' • Complete Q1 security training (Due: Jan 31)');\n console.log(' • Update data retention policies (Due: Feb 15)');\n break;\n\n case 'test':\n printSuccess('Running Security Test Suite...');\n console.log('\\n🧪 Security Tests:');\n console.log(' ✅ Authentication: Token validation working');\n console.log(' ✅ Authorization: RBAC policies enforced');\n console.log(' ✅ Rate Limiting: Limits properly enforced');\n console.log(' ✅ Circuit Breakers: Failing services isolated');\n console.log(' ✅ Audit Logging: All events captured');\n console.log(' ✅ Encryption: TLS 1.3 verified');\n console.log(' ✅ Session Management: Timeouts working');\n console.log(' ⚠️ MFA Bypass: 3 users without MFA');\n console.log('\\n📊 Security Score: 94/100');\n console.log(' Recommendations:');\n console.log(' • Enforce MFA for all users');\n console.log(' • Update TLS certificates (expire in 45 days)');\n console.log(' • Review inactive user accounts');\n break;\n\n default:\n console.log('Security commands:');\n console.log(' status - Show security status overview');\n console.log(' auth - Authentication management');\n console.log(' rbac - Role-based access control');\n console.log(' rate-limit - Rate limiting configuration');\n console.log(' circuit-breaker - Circuit breaker management');\n console.log(' audit - Audit log management');\n console.log(' compliance - Compliance status');\n console.log(' test - Run security tests');\n console.log('\\nExamples:');\n console.log(' security auth configure');\n console.log(' security rbac assign [email protected] developer');\n console.log(' security audit search \"failed login\"');\n console.log(' security circuit-breaker reset api-gateway');\n }\n break;\n\n case 'backup':\n const backupCmd = subArgs[0];\n switch (backupCmd) {\n case 'configure':\n printSuccess('Configuring Backup Strategy...');\n console.log('🗄️ Backup Configuration:');\n console.log(' Strategy: 3-2-1 (3 copies, 2 media, 1 offsite)');\n console.log(' Locations:');\n console.log(' • Primary: AWS S3 (us-east-1)');\n console.log(' • Secondary: Azure Blob (eastus)');\n console.log(' • Tertiary: Local NAS');\n console.log(' Schedule:');\n console.log(' • Full: Weekly (Sunday 2 AM)');\n console.log(' • Incremental: Every 6 hours');\n console.log(' • Differential: Daily (2 AM)');\n console.log(' Encryption: AES-256');\n console.log(' Compression: LZ4');\n console.log(' Verification: Automatic');\n console.log('\\n✅ Backup strategy configured');\n break;\n\n case 'dr':\n const drAction = subArgs[1];\n if (drAction === 'configure') {\n printSuccess('Configuring Disaster Recovery...');\n console.log('🚨 DR Configuration:');\n console.log(' RPO (Recovery Point Objective): 1 hour');\n console.log(' RTO (Recovery Time Objective): 15 minutes');\n console.log(' Replication: Real-time to secondary region');\n console.log(' Failover: Automatic with manual override');\n console.log(' Testing: Monthly DR drills');\n console.log('\\n✅ Disaster recovery configured');\n } else if (drAction === 'test') {\n printSuccess('Running DR Test...');\n console.log('🧪 DR Test Progress:');\n console.log(' ✓ Initiating failover simulation');\n console.log(' ✓ Switching to DR site');\n console.log(' ✓ Verifying data integrity');\n console.log(' ✓ Testing application functionality');\n console.log(' ✓ Measuring RTO: 12 minutes');\n console.log(' ✓ Failing back to primary');\n console.log('\\n✅ DR test completed successfully');\n } else {\n console.log('DR commands: configure, test, status');\n }\n break;\n\n case 'restore':\n const restorePoint = subArgs[1];\n if (!restorePoint) {\n printError('Usage: backup restore <backup-id|timestamp>');\n break;\n }\n\n printSuccess(`Restoring from backup: ${restorePoint}`);\n console.log('🔄 Restore Progress:');\n console.log(' ✓ Located backup in S3');\n console.log(' ✓ Verifying backup integrity');\n console.log(' ✓ Downloading backup data');\n console.log(' ✓ Decrypting backup');\n console.log(' ✓ Restoring application data');\n console.log(' ✓ Restoring configuration');\n console.log(' ✓ Verifying restored data');\n console.log('\\n✅ Restore completed successfully');\n break;\n\n default:\n console.log('Backup commands:');\n console.log(' configure - Configure backup strategy');\n console.log(' dr - Disaster recovery management');\n console.log(' restore - Restore from backup');\n console.log(' list - List available backups');\n console.log('\\nExamples:');\n console.log(' backup configure --strategy 3-2-1');\n console.log(' backup dr test');\n console.log(' backup restore \"backup-20240110-023000\"');\n }\n break;\n\n default:\n printError(`Unknown command: ${command}`);\n console.log('Run \"claude-flow help\" for available commands');\n\n // Suggest similar commands\n const commonCommands = [\n 'agent',\n 'task',\n 'spawn',\n 'init',\n 'start',\n 'status',\n 'memory',\n 'sparc',\n 'help',\n ];\n const suggestions = commonCommands.filter(\n (cmd) => cmd.startsWith(command.toLowerCase()) || cmd.includes(command.toLowerCase()),\n );\n\n if (suggestions.length > 0) {\n console.log('\\nDid you mean:');\n suggestions.forEach((cmd) => console.log(` claude-flow ${cmd}`));\n }\n\n exit(1);\n }\n}\n\n// REPL Implementation\nasync function startRepl() {\n console.log('🧠 Claude-Flow Interactive Shell v' + VERSION);\n console.log('Type \"help\" for available commands, \"exit\" to quit\\n');\n\n const replState = {\n history: [],\n historyIndex: -1,\n currentSession: null,\n context: {\n agents: [],\n tasks: [],\n terminals: [],\n memory: {},\n },\n };\n\n // REPL command handlers\n const replCommands = {\n help: () => {\n console.log(`\n📚 Available REPL Commands:\n \nSystem:\n status - Show system status\n config [key] - Show configuration (or specific key)\n clear - Clear the screen\n history - Show command history\n exit/quit - Exit REPL mode\n\nAgents:\n agent spawn <type> [name] - Spawn new agent\n agent list - List active agents\n agent info <id> - Show agent details\n agent terminate <id> - Terminate agent\n\nTasks:\n task create <type> <desc> - Create new task\n task list - List active tasks\n task assign <task> <agent> - Assign task to agent\n task status <id> - Show task status\n\nMemory:\n memory store <key> <value> - Store data in memory\n memory get <key> - Retrieve data from memory\n memory list - List all memory keys\n memory clear - Clear all memory\n\nTerminal:\n terminal create [name] - Create terminal session\n terminal list - List terminals\n terminal exec <cmd> - Execute command\n terminal attach <id> - Attach to terminal\n\nShortcuts:\n !<command> - Execute shell command\n /<search> - Search command history\n ↑/↓ - Navigate command history\n`);\n },\n\n status: () => {\n console.log('🟢 Claude-Flow Status:');\n console.log(` Agents: ${replState.context.agents.length} active`);\n console.log(` Tasks: ${replState.context.tasks.length} in queue`);\n console.log(` Terminals: ${replState.context.terminals.length} active`);\n console.log(` Memory Keys: ${Object.keys(replState.context.memory).length}`);\n },\n\n clear: () => {\n console.clear();\n console.log('🧠 Claude-Flow Interactive Shell v' + VERSION);\n },\n\n history: () => {\n console.log('📜 Command History:');\n replState.history.forEach((cmd, i) => {\n console.log(` ${i + 1}: ${cmd}`);\n });\n },\n\n config: async (key) => {\n try {\n const config = JSON.parse(await readTextFile('claude-flow.config.json'));\n if (key) {\n const keys = key.split('.');\n let value = config;\n for (const k of keys) {\n value = value[k];\n }\n console.log(`${key}: ${JSON.stringify(value, null, 2)}`);\n } else {\n console.log(JSON.stringify(config, null, 2));\n }\n } catch {\n console.log('No configuration file found. Using defaults.');\n }\n },\n };\n\n // Process REPL commands\n async function processReplCommand(input) {\n const trimmed = input.trim();\n if (!trimmed) return true;\n\n // Add to history\n replState.history.push(trimmed);\n replState.historyIndex = replState.history.length;\n\n // Handle special commands\n if (trimmed === 'exit' || trimmed === 'quit') {\n console.log('👋 Exiting Claude-Flow REPL...');\n return false;\n }\n\n // Handle shell commands\n if (trimmed.startsWith('!')) {\n const shellCmd = trimmed.substring(1);\n try {\n await new Promise((resolve) => {\n const proc = spawn('sh', ['-c', shellCmd], {\n stdio: ['inherit', 'pipe', 'pipe'],\n });\n\n proc.stdout.on('data', (data) => {\n console.log(data.toString());\n });\n\n proc.stderr.on('data', (data) => {\n console.error(data.toString());\n });\n\n proc.on('exit', resolve);\n });\n } catch (err) {\n console.error(`Shell error: ${err.message}`);\n }\n return true;\n }\n\n // Handle search\n if (trimmed.startsWith('/')) {\n const search = trimmed.substring(1);\n const matches = replState.history.filter((cmd) => cmd.includes(search));\n if (matches.length > 0) {\n console.log('🔍 Search results:');\n matches.forEach((cmd) => console.log(` ${cmd}`));\n } else {\n console.log('No matches found');\n }\n return true;\n }\n\n // Parse command and arguments\n const parts = trimmed.split(' ');\n const command = parts[0];\n const args = parts.slice(1);\n\n // Handle built-in REPL commands\n if (replCommands[command]) {\n await replCommands[command](...args);\n return true;\n }\n\n // Handle multi-word commands\n if (command === 'agent') {\n await handleAgentCommand(args, replState);\n } else if (command === 'task') {\n await handleTaskCommand(args, replState);\n } else if (command === 'memory') {\n await handleMemoryCommand(args, replState);\n } else if (command === 'terminal') {\n await handleTerminalCommand(args, replState);\n } else {\n console.log(`Unknown command: ${command}. Type \"help\" for available commands.`);\n }\n\n return true;\n }\n\n // Agent command handler\n async function handleAgentCommand(args, state) {\n const subCmd = args[0];\n switch (subCmd) {\n case 'spawn':\n const rawType = args[1] || 'researcher';\n const type = resolveLegacyAgentType(rawType);\n const name = args[2] || `agent-${Date.now()}`;\n const agent = {\n id: `agent-${Date.now()}`,\n type,\n name,\n status: 'active',\n created: new Date().toISOString(),\n };\n state.context.agents.push(agent);\n printSuccess(`Spawned ${type} agent: ${name} (${agent.id})`);\n break;\n\n case 'list':\n if (state.context.agents.length === 0) {\n console.log('No active agents');\n } else {\n console.log('Active agents:');\n state.context.agents.forEach((agent) => {\n console.log(` ${agent.id} - ${agent.name} (${agent.type}) - ${agent.status}`);\n });\n }\n break;\n\n case 'info':\n const agentId = args[1];\n const foundAgent = state.context.agents.find((a) => a.id === agentId || a.name === agentId);\n if (foundAgent) {\n console.log(`Agent: ${foundAgent.name}`);\n console.log(` ID: ${foundAgent.id}`);\n console.log(` Type: ${foundAgent.type}`);\n console.log(` Status: ${foundAgent.status}`);\n console.log(` Created: ${foundAgent.created}`);\n } else {\n printError(`Agent not found: ${agentId}`);\n }\n break;\n\n case 'terminate':\n const termId = args[1];\n const index = state.context.agents.findIndex((a) => a.id === termId || a.name === termId);\n if (index >= 0) {\n const removed = state.context.agents.splice(index, 1)[0];\n printSuccess(`Terminated agent: ${removed.name}`);\n } else {\n printError(`Agent not found: ${termId}`);\n }\n break;\n\n default:\n console.log('Agent commands: spawn, list, info, terminate');\n }\n }\n\n // Task command handler\n async function handleTaskCommand(args, state) {\n const subCmd = args[0];\n switch (subCmd) {\n case 'create':\n const type = args[1] || 'general';\n const description = args.slice(2).join(' ') || 'No description';\n const task = {\n id: `task-${Date.now()}`,\n type,\n description,\n status: 'pending',\n created: new Date().toISOString(),\n };\n state.context.tasks.push(task);\n printSuccess(`Created task: ${task.id}`);\n console.log(` Type: ${type}`);\n console.log(` Description: ${description}`);\n break;\n\n case 'list':\n if (state.context.tasks.length === 0) {\n console.log('No active tasks');\n } else {\n console.log('Active tasks:');\n state.context.tasks.forEach((task) => {\n console.log(` ${task.id} - ${task.type} - ${task.status}`);\n console.log(` ${task.description}`);\n });\n }\n break;\n\n case 'assign':\n const taskId = args[1];\n const assignAgentId = args[2];\n const foundTask = state.context.tasks.find((t) => t.id === taskId);\n const assignAgent = state.context.agents.find(\n (a) => a.id === assignAgentId || a.name === assignAgentId,\n );\n\n if (foundTask && assignAgent) {\n foundTask.assignedTo = assignAgent.id;\n foundTask.status = 'assigned';\n printSuccess(`Assigned task ${taskId} to agent ${assignAgent.name}`);\n } else {\n printError('Task or agent not found');\n }\n break;\n\n case 'status':\n const statusId = args[1];\n const statusTask = state.context.tasks.find((t) => t.id === statusId);\n if (statusTask) {\n console.log(`Task: ${statusTask.id}`);\n console.log(` Type: ${statusTask.type}`);\n console.log(` Status: ${statusTask.status}`);\n console.log(` Description: ${statusTask.description}`);\n if (statusTask.assignedTo) {\n console.log(` Assigned to: ${statusTask.assignedTo}`);\n }\n console.log(` Created: ${statusTask.created}`);\n } else {\n printError(`Task not found: ${statusId}`);\n }\n break;\n\n default:\n console.log('Task commands: create, list, assign, status');\n }\n }\n\n // Memory command handler\n async function handleMemoryCommand(args, state) {\n const subCmd = args[0];\n switch (subCmd) {\n case 'store':\n const key = args[1];\n const value = args.slice(2).join(' ');\n if (key && value) {\n state.context.memory[key] = value;\n printSuccess(`Stored: ${key} = ${value}`);\n } else {\n printError('Usage: memory store <key> <value>');\n }\n break;\n\n case 'get':\n const getKey = args[1];\n if (getKey && state.context.memory[getKey]) {\n console.log(`${getKey}: ${state.context.memory[getKey]}`);\n } else {\n console.log(`Key not found: ${getKey}`);\n }\n break;\n\n case 'list':\n const keys = Object.keys(state.context.memory);\n if (keys.length === 0) {\n console.log('No data in memory');\n } else {\n console.log('Memory keys:');\n keys.forEach((key) => {\n console.log(` ${key}: ${state.context.memory[key]}`);\n });\n }\n break;\n\n case 'clear':\n state.context.memory = {};\n printSuccess('Memory cleared');\n break;\n\n default:\n console.log('Memory commands: store, get, list, clear');\n }\n }\n\n // Terminal command handler\n async function handleTerminalCommand(args, state) {\n const subCmd = args[0];\n switch (subCmd) {\n case 'create':\n const name = args[1] || `term-${Date.now()}`;\n const terminal = {\n id: name,\n status: 'active',\n created: new Date().toISOString(),\n };\n state.context.terminals.push(terminal);\n printSuccess(`Created terminal: ${name}`);\n break;\n\n case 'list':\n if (state.context.terminals.length === 0) {\n console.log('No active terminals');\n } else {\n console.log('Active terminals:');\n state.context.terminals.forEach((term) => {\n console.log(` ${term.id} - ${term.status}`);\n });\n }\n break;\n\n case 'exec':\n const cmd = args.slice(1).join(' ');\n if (cmd) {\n console.log(`Executing: ${cmd}`);\n console.log('(Command execution simulated in REPL)');\n } else {\n printError('Usage: terminal exec <command>');\n }\n break;\n\n case 'attach':\n const attachId = args[1];\n if (attachId) {\n state.currentSession = attachId;\n console.log(`Attached to terminal: ${attachId}`);\n console.log('(Type \"terminal detach\" to detach)');\n } else {\n printError('Usage: terminal attach <id>');\n }\n break;\n\n case 'detach':\n if (state.currentSession) {\n console.log(`Detached from terminal: ${state.currentSession}`);\n state.currentSession = null;\n } else {\n console.log('Not attached to any terminal');\n }\n break;\n\n default:\n console.log('Terminal commands: create, list, exec, attach, detach');\n }\n }\n\n // Main REPL loop with Node.js readline\n const rl = readline.createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n // Set prompt based on session\n function updatePrompt() {\n rl.setPrompt(\n replState.currentSession ? `claude-flow:${replState.currentSession}> ` : 'claude-flow> ',\n );\n }\n\n updatePrompt();\n rl.prompt();\n\n // Handle each line of input\n rl.on('line', async (input) => {\n input = input.trim();\n\n // Process command\n const shouldContinue = await processReplCommand(input);\n if (!shouldContinue) {\n rl.close();\n } else {\n updatePrompt();\n rl.prompt();\n }\n });\n\n // Handle CTRL+C\n rl.on('SIGINT', () => {\n console.log('\\nExiting Claude-Flow...');\n rl.close();\n process.exit(0);\n });\n\n // Wait for REPL to close\n return new Promise((resolve) => {\n rl.on('close', resolve);\n });\n}\n\n// Helper functions for init command\nfunction createMinimalClaudeMd() {\n return `# Claude Code Integration\n\nThis file provides guidance to Claude when working with this codebase.\n\n## Project Overview\n[Describe your project here]\n\n## Key Conventions\n- Code style guidelines\n- Naming conventions\n- Architecture patterns\n\n## Important Notes\n- Special considerations\n- Areas to be careful with\n`;\n}\n\nfunction createFullClaudeMd() {\n return `# Claude Code Integration Guide\n\nThis document provides comprehensive guidance to Claude when working with this codebase.\n\n## Project Overview\n[Provide a detailed description of your project, its purpose, and main features]\n\n## Architecture\n[Describe the overall architecture, main components, and how they interact]\n\n## Code Conventions\n- **Naming**: [Describe naming conventions for files, functions, variables, etc.]\n- **Style**: [Code formatting preferences, linting rules]\n- **Patterns**: [Design patterns used in the project]\n- **Testing**: [Testing approach and requirements]\n\n## Directory Structure\n\\`\\`\\`\nproject/\n├── src/ # Source code\n├── tests/ # Test files\n├── docs/ # Documentation\n└── ... # Other directories\n\\`\\`\\`\n\n## Development Workflow\n1. [Step-by-step development process]\n2. [How to run tests]\n3. [How to build/deploy]\n\n## Important Considerations\n- [Security considerations]\n- [Performance requirements]\n- [Compatibility requirements]\n\n## Common Tasks\n- **Add a new feature**: [Instructions]\n- **Fix a bug**: [Process]\n- **Update documentation**: [Guidelines]\n\n## Dependencies\n[List key dependencies and their purposes]\n\n## Troubleshooting\n[Common issues and solutions]\n`;\n}\n\nfunction createMinimalMemoryBankMd() {\n return `# Memory Bank\n\nSession memory and context storage.\n\n## Current Session\n- Started: ${new Date().toISOString()}\n- Context: [Current work context]\n\n## Key Information\n- [Important facts to remember]\n\n## Progress Log\n- [Track progress here]\n`;\n}\n\nfunction createFullMemoryBankMd() {\n return `# Memory Bank\n\nThis file serves as persistent memory storage for Claude across sessions.\n\n## Session Information\n- **Current Session**: Started ${new Date().toISOString()}\n- **Project Phase**: [Development/Testing/Production]\n- **Active Tasks**: [List current tasks]\n\n## Project Context\n### Technical Stack\n- Languages: [List languages used]\n- Frameworks: [List frameworks]\n- Tools: [Development tools]\n\n### Architecture Decisions\n- [Record key architectural decisions]\n- [Rationale for technology choices]\n\n## Important Information\n### API Keys and Secrets\n- [Never store actual secrets here, just references]\n\n### External Services\n- [List integrated services]\n- [Configuration requirements]\n\n### Database Schema\n- [Current schema version]\n- [Recent migrations]\n\n## Progress Tracking\n### Completed Tasks\n- [x] [Completed task 1]\n- [x] [Completed task 2]\n\n### In Progress\n- [ ] [Current task 1]\n- [ ] [Current task 2]\n\n### Upcoming\n- [ ] [Future task 1]\n- [ ] [Future task 2]\n\n## Code Patterns\n### Established Patterns\n\\`\\`\\`javascript\n// Example pattern\n\\`\\`\\`\n\n### Anti-patterns to Avoid\n- [List anti-patterns]\n\n## Meeting Notes\n### [Date]\n- Participants: [Names]\n- Decisions: [Key decisions]\n- Action items: [Tasks assigned]\n\n## Debugging History\n### Issue: [Issue name]\n- **Date**: [Date]\n- **Symptoms**: [What was observed]\n- **Root Cause**: [What caused it]\n- **Solution**: [How it was fixed]\n\n## Performance Metrics\n- [Baseline metrics]\n- [Optimization goals]\n\n## Documentation Links\n- [API Documentation]: [URL]\n- [Design Documents]: [URL]\n- [Issue Tracker]: [URL]\n`;\n}\n\nfunction createMinimalCoordinationMd() {\n return `# Coordination\n\nTask and workflow coordination.\n\n## Active Tasks\n1. [Current task]\n\n## Workflow\n- [ ] Step 1\n- [ ] Step 2\n\n## Resources\n- [Available resources]\n`;\n}\n\nfunction createFullCoordinationMd() {\n return `# Coordination Center\n\nCentral coordination for multi-agent collaboration and task management.\n\n## Active Agents\n| Agent ID | Type | Status | Assigned Tasks | Last Active |\n|----------|------|--------|----------------|-------------|\n| [ID] | [Type] | [Status] | [Tasks] | [Timestamp] |\n\n## Task Queue\n### High Priority\n1. **[Task Name]**\n - Description: [What needs to be done]\n - Assigned to: [Agent ID]\n - Dependencies: [Other tasks]\n - Deadline: [Date/Time]\n\n### Medium Priority\n1. [Task details]\n\n### Low Priority\n1. [Task details]\n\n## Workflow Definitions\n### [Workflow Name]\n\\`\\`\\`yaml\nname: [Workflow Name]\ndescription: [What this workflow does]\nsteps:\n - name: [Step 1]\n agent: [Agent type]\n action: [What to do]\n - name: [Step 2]\n agent: [Agent type]\n action: [What to do]\n depends_on: [Step 1]\n\\`\\`\\`\n\n## Resource Allocation\n### Computational Resources\n- CPU: [Usage/Limits]\n- Memory: [Usage/Limits]\n- Storage: [Usage/Limits]\n\n### External Resources\n- API Rate Limits: [Service: limit]\n- Database Connections: [Current/Max]\n\n## Communication Channels\n### Inter-Agent Messages\n- [Agent A → Agent B]: [Message type]\n\n### External Communications\n- Webhooks: [Configured webhooks]\n- Notifications: [Notification settings]\n\n## Synchronization Points\n- [Sync Point 1]: [Description]\n- [Sync Point 2]: [Description]\n\n## Conflict Resolution\n### Strategy\n- [How conflicts are resolved]\n\n### Recent Conflicts\n- [Date]: [Conflict description] → [Resolution]\n\n## Performance Metrics\n### Task Completion\n- Average time: [Time]\n- Success rate: [Percentage]\n\n### Agent Efficiency\n- [Agent Type]: [Metrics]\n\n## Scheduled Maintenance\n- [Date/Time]: [What will be done]\n\n## Emergency Procedures\n### System Overload\n1. [Step 1]\n2. [Step 2]\n\n### Agent Failure\n1. [Recovery procedure]\n`;\n}\n\nfunction createAgentsReadme() {\n return `# Agents Directory\n\nThis directory stores agent-specific memory and state information.\n\n## Structure\nEach agent gets its own subdirectory named by agent ID:\n- \\`agent-001/\\`: First agent's memory\n- \\`agent-002/\\`: Second agent's memory\n- etc.\n\n## Files per Agent\n- \\`profile.json\\`: Agent configuration and capabilities\n- \\`memory.md\\`: Agent's working memory\n- \\`tasks.json\\`: Assigned tasks and their status\n- \\`metrics.json\\`: Performance metrics\n\n## Usage\nFiles in this directory are automatically managed by the Claude-Flow system.\n`;\n}\n\nfunction createSessionsReadme() {\n return `# Sessions Directory\n\nThis directory stores session-specific information and terminal states.\n\n## Structure\nEach session gets a unique directory:\n- \\`session-[timestamp]/\\`: Session data\n - \\`metadata.json\\`: Session metadata\n - \\`terminal.log\\`: Terminal output\n - \\`commands.history\\`: Command history\n - \\`state.json\\`: Session state snapshot\n\n## Retention Policy\nSessions are retained for 30 days by default, then archived or deleted based on configuration.\n\n## Usage\nThe Claude-Flow system automatically manages session files. Do not modify these files manually.\n`;\n}\n\n// Helper function to create SPARC structure manually\nasync function createSparcStructureManually() {\n try {\n // Create .roo directory structure\n const rooDirectories = [\n '.roo',\n '.roo/templates',\n '.roo/workflows',\n '.roo/modes',\n '.roo/configs',\n ];\n\n for (const dir of rooDirectories) {\n try {\n await mkdirAsync(dir, { recursive: true });\n console.log(` ✓ Created ${dir}/`);\n } catch (err) {\n if (!(err instanceof errors.AlreadyExists)) {\n throw err;\n }\n }\n }\n\n // Create .roomodes file (copy from existing if available, or create basic version)\n let roomodesContent;\n try {\n // Check if .roomodes already exists and read it\n roomodesContent = await readTextFile('.roomodes');\n console.log(' ✓ Using existing .roomodes configuration');\n } catch {\n // Create basic .roomodes configuration\n roomodesContent = createBasicRoomodesConfig();\n await writeTextFile('.roomodes', roomodesContent);\n console.log(' ✓ Created .roomodes configuration');\n }\n\n // Create basic workflow templates\n const basicWorkflow = createBasicSparcWorkflow();\n await writeTextFile('.roo/workflows/basic-tdd.json', basicWorkflow);\n console.log(' ✓ Created .roo/workflows/basic-tdd.json');\n\n // Create README for .roo directory\n const rooReadme = createRooReadme();\n await writeTextFile('.roo/README.md', rooReadme);\n console.log(' ✓ Created .roo/README.md');\n\n console.log(' ✅ Basic SPARC structure created successfully');\n } catch (err) {\n console.log(` ❌ Failed to create SPARC structure: ${err.message}`);\n }\n}\n\nfunction createBasicRoomodesConfig() {\n return JSON.stringify(\n {\n customModes: [\n {\n slug: 'architect',\n name: '🏗️ Architect',\n roleDefinition:\n 'You design scalable, secure, and modular architectures based on functional specs and user needs. You define responsibilities across services, APIs, and components.',\n customInstructions:\n 'Create architecture mermaid diagrams, data flows, and integration points. Ensure no part of the design includes secrets or hardcoded env values. Emphasize modular boundaries and maintain extensibility.',\n groups: ['read', 'edit'],\n source: 'project',\n },\n {\n slug: 'code',\n name: '🧠 Auto-Coder',\n roleDefinition:\n 'You write clean, efficient, modular code based on pseudocode and architecture. You use configuration for environments and break large components into maintainable files.',\n customInstructions:\n 'Write modular code using clean architecture principles. Never hardcode secrets or environment values. Split code into files < 500 lines. Use config files or environment abstractions. Use \\\\`new_task\\\\` for subtasks and finish with \\\\`attempt_completion\\\\`.',\n groups: ['read', 'edit', 'browser', 'mcp', 'command'],\n source: 'project',\n },\n {\n slug: 'tdd',\n name: '🧪 Tester (TDD)',\n roleDefinition:\n 'You implement Test-Driven Development (TDD, London School), writing tests first and refactoring after minimal implementation passes.',\n customInstructions:\n 'Write failing tests first. Implement only enough code to pass. Refactor after green. Ensure tests do not hardcode secrets. Keep files < 500 lines.',\n groups: ['read', 'edit', 'browser', 'mcp', 'command'],\n source: 'project',\n },\n {\n slug: 'spec-pseudocode',\n name: '📋 Specification Writer',\n roleDefinition:\n 'You capture full project context—functional requirements, edge cases, constraints—and translate that into modular pseudocode with TDD anchors.',\n customInstructions:\n 'Write pseudocode as a series of md files with phase_number_name.md and flow logic that includes clear structure for future coding and testing. Split complex logic across modules.',\n groups: ['read', 'edit'],\n source: 'project',\n },\n {\n slug: 'integration',\n name: '🔗 System Integrator',\n roleDefinition:\n 'You merge the outputs of all modes into a working, tested, production-ready system. You ensure consistency, cohesion, and modularity.',\n customInstructions:\n 'Verify interface compatibility, shared modules, and env config standards. Split integration logic across domains as needed. Use \\\\`new_task\\\\` for preflight testing.',\n groups: ['read', 'edit', 'browser', 'mcp', 'command'],\n source: 'project',\n },\n {\n slug: 'debug',\n name: '🪲 Debugger',\n roleDefinition:\n 'You troubleshoot runtime bugs, logic errors, or integration failures by tracing, inspecting, and analyzing behavior.',\n customInstructions:\n 'Use logs, traces, and stack analysis to isolate bugs. Avoid changing env configuration directly. Keep fixes modular.',\n groups: ['read', 'edit', 'browser', 'mcp', 'command'],\n source: 'project',\n },\n ],\n },\n null,\n 2,\n );\n}\n\nfunction createBasicSparcWorkflow() {\n return JSON.stringify(\n {\n name: 'Basic TDD Workflow',\n description: 'A simple SPARC-based TDD workflow for development',\n sequential: true,\n steps: [\n {\n mode: 'spec-pseudocode',\n description: 'Create detailed specifications and pseudocode',\n phase: 'specification',\n },\n {\n mode: 'tdd',\n description: 'Write failing tests (Red phase)',\n phase: 'red',\n },\n {\n mode: 'code',\n description: 'Implement minimal code to pass tests (Green phase)',\n phase: 'green',\n },\n {\n mode: 'tdd',\n description: 'Refactor and optimize (Refactor phase)',\n phase: 'refactor',\n },\n {\n mode: 'integration',\n description: 'Integrate and verify complete solution',\n phase: 'integration',\n },\n ],\n },\n null,\n 2,\n );\n}\n\nfunction createRooReadme() {\n return `# .roo Directory - SPARC Development Environment\n\nThis directory contains the SPARC (Specification, Pseudocode, Architecture, Refinement, Completion) development environment configuration and templates.\n\n## Directory Structure\n\n\\`\\`\\`\n.roo/\n├── README.md # This file\n├── templates/ # Template files for common patterns\n├── workflows/ # Predefined SPARC workflows\n│ └── basic-tdd.json # Basic TDD workflow\n├── modes/ # Custom mode definitions (optional)\n└── configs/ # Configuration files\n\\`\\`\\`\n\n## SPARC Methodology\n\nSPARC is a systematic approach to software development:\n\n1. **Specification**: Define clear requirements and constraints\n2. **Pseudocode**: Create detailed logic flows and algorithms \n3. **Architecture**: Design system structure and components\n4. **Refinement**: Implement, test, and optimize using TDD\n5. **Completion**: Integrate, document, and validate\n\n## Usage with Claude-Flow\n\nUse the claude-flow SPARC commands to leverage this environment:\n\n\\`\\`\\`bash\n# List available modes\nclaude-flow sparc modes\n\n# Run specific mode\nclaude-flow sparc run code \"implement user authentication\"\n\n# Execute full TDD workflow \nclaude-flow sparc tdd \"payment processing system\"\n\n# Use custom workflow\nclaude-flow sparc workflow .roo/workflows/basic-tdd.json\n\\`\\`\\`\n\n## Configuration\n\nThe main configuration is in \\`.roomodes\\` at the project root. This directory provides additional templates and workflows to support the SPARC development process.\n\n## Customization\n\nYou can customize this environment by:\n- Adding new workflow templates to \\`workflows/\\`\n- Creating mode-specific templates in \\`templates/\\`\n- Adding project-specific configurations in \\`configs/\\`\n\nFor more information, see: https://github.com/ruvnet/claude-code-flow/docs/sparc.md\n`;\n}\n\nfunction createSparcClaudeMd() {\n return `# Claude Code Configuration - SPARC Development Environment\n\n## Project Overview\nThis project uses the SPARC (Specification, Pseudocode, Architecture, Refinement, Completion) methodology for systematic Test-Driven Development with AI assistance through Claude-Flow orchestration.\n\n## SPARC Development Commands\n\n### Core SPARC Commands\n- \\`npx claude-flow sparc modes\\`: List all available SPARC development modes\n- \\`npx claude-flow sparc run <mode> \"<task>\"\\`: Execute specific SPARC mode for a task\n- \\`npx claude-flow sparc tdd \"<feature>\"\\`: Run complete TDD workflow using SPARC methodology\n- \\`npx claude-flow sparc info <mode>\\`: Get detailed information about a specific mode\n\n### Standard Build Commands\n- \\`npm run build\\`: Build the project\n- \\`npm run test\\`: Run the test suite\n- \\`npm run lint\\`: Run linter and format checks\n- \\`npm run typecheck\\`: Run TypeScript type checking\n\n## SPARC Methodology Workflow\n\n### 1. Specification Phase\n\\`\\`\\`bash\n# Create detailed specifications and requirements\nnpx claude-flow sparc run spec-pseudocode \"Define user authentication requirements\"\n\\`\\`\\`\n- Define clear functional requirements\n- Document edge cases and constraints\n- Create user stories and acceptance criteria\n- Establish non-functional requirements\n\n### 2. Pseudocode Phase\n\\`\\`\\`bash\n# Develop algorithmic logic and data flows\nnpx claude-flow sparc run spec-pseudocode \"Create authentication flow pseudocode\"\n\\`\\`\\`\n- Break down complex logic into steps\n- Define data structures and interfaces\n- Plan error handling and edge cases\n- Create modular, testable components\n\n### 3. Architecture Phase\n\\`\\`\\`bash\n# Design system architecture and component structure\nnpx claude-flow sparc run architect \"Design authentication service architecture\"\n\\`\\`\\`\n- Create system diagrams and component relationships\n- Define API contracts and interfaces\n- Plan database schemas and data flows\n- Establish security and scalability patterns\n\n### 4. Refinement Phase (TDD Implementation)\n\\`\\`\\`bash\n# Execute Test-Driven Development cycle\nnpx claude-flow sparc tdd \"implement user authentication system\"\n\\`\\`\\`\n\n**TDD Cycle:**\n1. **Red**: Write failing tests first\n2. **Green**: Implement minimal code to pass tests\n3. **Refactor**: Optimize and clean up code\n4. **Repeat**: Continue until feature is complete\n\n### 5. Completion Phase\n\\`\\`\\`bash\n# Integration, documentation, and validation\nnpx claude-flow sparc run integration \"integrate authentication with user management\"\n\\`\\`\\`\n- Integrate all components\n- Perform end-to-end testing\n- Create comprehensive documentation\n- Validate against original requirements\n\n## SPARC Mode Reference\n\n### Development Modes\n- **\\`architect\\`**: System design and architecture planning\n- **\\`code\\`**: Clean, modular code implementation\n- **\\`tdd\\`**: Test-driven development and testing\n- **\\`spec-pseudocode\\`**: Requirements and algorithmic planning\n- **\\`integration\\`**: System integration and coordination\n\n### Quality Assurance Modes\n- **\\`debug\\`**: Troubleshooting and bug resolution\n- **\\`security-review\\`**: Security analysis and vulnerability assessment\n- **\\`refinement-optimization-mode\\`**: Performance optimization and refactoring\n\n### Support Modes\n- **\\`docs-writer\\`**: Documentation creation and maintenance\n- **\\`devops\\`**: Deployment and infrastructure management\n- **\\`mcp\\`**: External service integration\n\n## Code Style and Best Practices\n\n### SPARC Development Principles\n- **Modular Design**: Keep files under 500 lines, break into logical components\n- **Environment Safety**: Never hardcode secrets or environment-specific values\n- **Test-First**: Always write tests before implementation (Red-Green-Refactor)\n- **Clean Architecture**: Separate concerns, use dependency injection\n- **Documentation**: Maintain clear, up-to-date documentation\n\n### Coding Standards\n- Use TypeScript for type safety and better tooling\n- Follow consistent naming conventions (camelCase for variables, PascalCase for classes)\n- Implement proper error handling and logging\n- Use async/await for asynchronous operations\n- Prefer composition over inheritance\n\n### Memory and State Management\n- Use claude-flow memory system for persistent state across sessions\n- Store progress and findings using namespaced keys\n- Query previous work before starting new tasks\n- Export/import memory for backup and sharing\n\n## SPARC Memory Integration\n\n### Memory Commands for SPARC Development\n\\`\\`\\`bash\n# Store project specifications\nnpx claude-flow memory store spec_auth \"User authentication requirements and constraints\"\n\n# Store architectural decisions\nnpx claude-flow memory store arch_decisions \"Database schema and API design choices\"\n\n# Store test results and coverage\nnpx claude-flow memory store test_coverage \"Authentication module: 95% coverage, all tests passing\"\n\n# Query previous work\nnpx claude-flow memory query auth_implementation\n\n# Export project memory\nnpx claude-flow memory export project_backup.json\n\\`\\`\\`\n\n### Memory Namespaces\n- **\\`spec\\`**: Requirements and specifications\n- **\\`arch\\`**: Architecture and design decisions\n- **\\`impl\\`**: Implementation notes and code patterns\n- **\\`test\\`**: Test results and coverage reports\n- **\\`debug\\`**: Bug reports and resolution notes\n\n## Workflow Examples\n\n### Feature Development Workflow\n\\`\\`\\`bash\n# 1. Start with specification\nnpx claude-flow sparc run spec-pseudocode \"User profile management feature\"\n\n# 2. Design architecture\nnpx claude-flow sparc run architect \"Profile service architecture with data validation\"\n\n# 3. Implement with TDD\nnpx claude-flow sparc tdd \"user profile CRUD operations\"\n\n# 4. Security review\nnpx claude-flow sparc run security-review \"profile data access and validation\"\n\n# 5. Integration testing\nnpx claude-flow sparc run integration \"profile service with authentication system\"\n\n# 6. Documentation\nnpx claude-flow sparc run docs-writer \"profile service API documentation\"\n\\`\\`\\`\n\n### Bug Fix Workflow\n\\`\\`\\`bash\n# 1. Debug and analyze\nnpx claude-flow sparc run debug \"authentication token expiration issue\"\n\n# 2. Write regression tests\nnpx claude-flow sparc run tdd \"token refresh mechanism tests\"\n\n# 3. Implement fix\nnpx claude-flow sparc run code \"fix token refresh in authentication service\"\n\n# 4. Security review\nnpx claude-flow sparc run security-review \"token handling security implications\"\n\\`\\`\\`\n\n## Configuration Files\n\n### SPARC Configuration\n- **\\`.roomodes\\`**: SPARC mode definitions and configurations\n- **\\`.roo/\\`**: Templates, workflows, and mode-specific rules\n\n### Claude-Flow Configuration\n- **\\`memory/\\`**: Persistent memory and session data\n- **\\`coordination/\\`**: Multi-agent coordination settings\n\n## Git Workflow Integration\n\n### Commit Strategy with SPARC\n- **Specification commits**: After completing requirements analysis\n- **Architecture commits**: After design phase completion\n- **TDD commits**: After each Red-Green-Refactor cycle\n- **Integration commits**: After successful component integration\n- **Documentation commits**: After completing documentation updates\n\n### Branch Strategy\n- **\\`feature/sparc-<feature-name>\\`**: Feature development with SPARC methodology\n- **\\`hotfix/sparc-<issue>\\`**: Bug fixes using SPARC debugging workflow\n- **\\`refactor/sparc-<component>\\`**: Refactoring using optimization mode\n\n## Troubleshooting\n\n### Common SPARC Issues\n- **Mode not found**: Check \\`.roomodes\\` file exists and is valid JSON\n- **Memory persistence**: Ensure \\`memory/\\` directory has write permissions\n- **Tool access**: Verify required tools are available for the selected mode\n- **Namespace conflicts**: Use unique memory namespaces for different features\n\n### Debug Commands\n\\`\\`\\`bash\n# Check SPARC configuration\nnpx claude-flow sparc modes\n\n# Verify memory system\nnpx claude-flow memory stats\n\n# Check system status\nnpx claude-flow status\n\n# View detailed mode information\nnpx claude-flow sparc info <mode-name>\n\\`\\`\\`\n\n## Project Architecture\n\nThis SPARC-enabled project follows a systematic development approach:\n- **Clear separation of concerns** through modular design\n- **Test-driven development** ensuring reliability and maintainability\n- **Iterative refinement** for continuous improvement\n- **Comprehensive documentation** for team collaboration\n- **AI-assisted development** through specialized SPARC modes\n\n## Important Notes\n\n- Always run tests before committing (\\`npm run test\\`)\n- Use SPARC memory system to maintain context across sessions\n- Follow the Red-Green-Refactor cycle during TDD phases\n- Document architectural decisions in memory for future reference\n- Regular security reviews for any authentication or data handling code\n\nFor more information about SPARC methodology, see: https://github.com/ruvnet/claude-code-flow/docs/sparc.md\n`;\n}\n\nif (isMainModule(import.meta.url)) {\n await main();\n}\n"],"names":["executeCommand","hasCommand","showCommandHelp","listCommands","parseFlags","args","cwd","isMainModule","exit","readTextFile","writeTextFile","mkdirAsync","errors","spawn","process","readline","getMainHelp","getCommandHelp","getStandardizedCommandHelp","VERSION","LEGACY_AGENT_MAPPING","analyst","coordinator","optimizer","documenter","monitor","specialist","architect","resolveLegacyAgentType","legacyType","printHelp","plain","console","log","printCommandHelp","command","standardCommands","includes","help","printLegacyHelp","printVersion","printError","message","error","printSuccess","printWarning","warn","showHelpWithCommands","commands","name","padEnd","description","main","length","usePlainHelp","flags","parsedArgs","slice","enhancedFlags","detectExecutionEnvironment","applySmartDefaults","_environment","skipWarnings","e","h","detailedHelp","env","terminalType","isInteractive","supportsRawMode","isVSCode","isCI","isDocker","isSSH","recommendedFlags","join","appliedDefaults","err","subArgs","rawSpawnType","spawnType","spawnName","Date","now","terminalCmd","poolCmd","detailed","termId","nameIndex","indexOf","shellIndex","wdIndex","envIndex","persistentIndex","terminalConfig","shell","workingDirectory","persistent","execCmd","sessionFlag","timeoutFlag","backgroundFlag","sessionId","cmdStart","cmdEnd","lastIndexOf","batchSession","find","arg","startsWith","commandsFlag","fileFlag","split","forEach","cmd","i","listDetailed","infoSessionId","attachId","detachId","terminateId","graceful","idleTime","monitorId","recordId","outputFlag","replayFile","shareId","accessLevel","multiCmd","configName","envName","configFile","sessionCmd","workflowFile","startRepl","projectCmd","projectName","isolationFlag","resourceQuotaFlag","securityProfileFlag","templateFlag","switchProject","showActive","withStats","projects","status","agents","tasks","project","configAction","configProject","configKey","configValue","monitorProject","backupProject","includeData","includeConfig","includeHistory","outputFile","shareFrom","shareTo","agentsFlag","permissionsFlag","durationFlag","fedCmd","fedName","projectsFlag","cloudCmd","cloudProvider","awsServices","awsRegions","awsHA","awsCostOpt","azureServices","azureRegions","azureIntegration","gcpServices","gcpRegions","multiCloud","multiCloudCmd","failoverTarget","k8sCmd","replicas","claudeCmd","taskEndIndex","task","tools","noPermissions","config","mode","parallel","research","coverage","parseInt","commit","verbose","dryRun","instanceId","Math","random","toString","substr","enhancedTask","claudeArgs","push","substring","map","child","CLAUDE_INSTANCE_ID","CLAUDE_FLOW_MODE","CLAUDE_FLOW_COVERAGE","CLAUDE_FLOW_COMMIT","CLAUDE_FLOW_MEMORY_ENABLED","CLAUDE_FLOW_MEMORY_NAMESPACE","CLAUDE_FLOW_COORDINATION_ENABLED","CLAUDE_FLOW_FEATURES","stdio","Promise","resolve","on","code","deployCmd","nodes","regions","replicationFactor","scalingAction","securityAction","analyticsCmd","costCmd","securityCmd","authAction","rbacAction","user","role","rateLimitAction","cbAction","service","auditAction","query","backupCmd","drAction","restorePoint","commonCommands","suggestions","filter","toLowerCase","replState","history","historyIndex","currentSession","context","terminals","memory","replCommands","Object","keys","clear","key","JSON","parse","value","k","stringify","processReplCommand","input","trimmed","trim","shellCmd","proc","stdout","data","stderr","search","matches","parts","handleAgentCommand","handleTaskCommand","handleMemoryCommand","handleTerminalCommand","state","subCmd","rawType","type","agent","id","created","toISOString","agentId","foundAgent","a","index","findIndex","removed","splice","taskId","assignAgentId","foundTask","t","assignAgent","assignedTo","statusId","statusTask","getKey","terminal","term","rl","createInterface","stdin","output","updatePrompt","setPrompt","prompt","shouldContinue","close","createMinimalClaudeMd","createFullClaudeMd","createMinimalMemoryBankMd","createFullMemoryBankMd","createMinimalCoordinationMd","createFullCoordinationMd","createAgentsReadme","createSessionsReadme","createSparcStructureManually","rooDirectories","dir","recursive","AlreadyExists","roomodesContent","createBasicRoomodesConfig","basicWorkflow","createBasicSparcWorkflow","rooReadme","createRooReadme","customModes","slug","roleDefinition","customInstructions","groups","source","sequential","steps","phase","createSparcClaudeMd","url"],"mappings":";AAMA,SACEA,cAAc,EACdC,UAAU,EACVC,eAAe,EAEfC,YAAY,QACP,wBAAwB;AAC/B,SAASC,UAAU,QAAQ,aAAa;AACxC,SACEC,IAAI,EACJC,GAAG,EACHC,YAAY,EACZC,IAAI,EACJC,YAAY,EACZC,aAAa,EACbC,UAAU,EACVC,MAAM,QACD,mBAAmB;AAC1B,SAASC,KAAK,QAAQ,gBAAgB;AACtC,OAAOC,aAAa,UAAU;AAC9B,OAAOC,cAAc,WAAW;AAChC,SAASC,WAAW,EAAEC,cAAc,EAAEC,0BAA0B,QAAQ,iBAAiB;AACzF,SAASC,OAAO,QAAQ,qBAAqB;AAG7C,MAAMC,uBAAuB;IAC3BC,SAAS;IACTC,aAAa;IACbC,WAAW;IACXC,YAAY;IACZC,SAAS;IACTC,YAAY;IACZC,WAAW;AACb;AAGA,SAASC,uBAAuBC,UAAU;IACxC,OAAOT,oBAAoB,CAACS,WAAW,IAAIA;AAC7C;AAEA,SAASC,UAAUC,QAAQ,KAAK;IAC9BC,QAAQC,GAAG,CAACjB,YAAYe;AAC1B;AAEA,SAASG,iBAAiBC,OAAO;IAE/B,MAAMC,mBAAmB;QAAC;QAAS;QAAS;KAAS;IACrD,IAAIA,iBAAiBC,QAAQ,CAACF,UAAU;QACtC,MAAMG,OAAOpB,2BAA2BiB;QACxCH,QAAQC,GAAG,CAACK;IACd,OAAO;QACL,MAAMA,OAAOrB,eAAekB;QAC5BH,QAAQC,GAAG,CAACK;IACd;AACF;AAGA,SAASC;IACPP,QAAQC,GAAG,CAAC,CAAC;gBACC,EAAEd,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoPV,CAAC;AACD;AAEA,IAAIhV,aAAa,YAAYiV,GAAG,GAAG;IACjC,MAAMpS;AACR"}
\ No newline at end of file
+{"version":3,"sources":["../../../src/cli/simple-cli.ts"],"sourcesContent":["#!/usr/bin/env -S deno run --allow-all\n/**\n * Simple CLI wrapper for Claude-Flow (JavaScript version)\n * This version avoids TypeScript issues in node_modules\n */\n\nimport { promises as fs } from 'node:fs';\nimport {\n executeCommand,\n hasCommand,\n showCommandHelp,\n showAllCommands,\n listCommands,\n} from './command-registry.js';\nimport { parseFlags } from './utils.js';\nimport { VERSION } from '../core/version.js';\n\nfunction printHelp() {\n console.log(`\n🌊 Claude-Flow v${VERSION} - Enterprise-Grade AI Agent Orchestration Platform\n\n🎯 NEW IN v2.6.0: Multi-Provider Execution Engine with Agentic-Flow Integration\n • 66+ specialized agents with multi-provider support (Anthropic, OpenRouter, ONNX, Gemini)\n • 99% cost savings with OpenRouter, 352x faster local edits with Agent Booster\n • Complete backwards compatibility with existing features\n\n🎯 ENTERPRISE FEATURES: Complete ruv-swarm integration with 27 MCP tools, neural networking, and production-ready infrastructure\n\nUSAGE:\n claude-flow <command> [options]\n\n🚀 INSTALLATION & ENTERPRISE SETUP:\n npx [email protected] init --sparc # Enterprise SPARC + ruv-swarm integration\n \n The --sparc flag creates:\n • Complete ruv-swarm integration with 27 MCP tools\n • Neural network processing with WASM optimization\n • Multi-agent coordination (hierarchical, mesh, ring, star topologies)\n • Cross-session memory and persistent learning\n • GitHub workflow automation (6 specialized modes)\n • Production-ready Docker infrastructure\n • Enterprise security and compliance features\n\n🧠 SWARM INTELLIGENCE COMMANDS (v2.0.0):\n swarm \"objective\" [--strategy] [--mode] [--max-agents N] [--parallel] [--monitor]\n --strategy: research, development, analysis, testing, optimization, maintenance\n --mode: centralized, distributed, hierarchical, mesh, hybrid\n --parallel: Enable parallel execution (2.8-4.4x speed improvement)\n --monitor: Real-time swarm monitoring and performance tracking\n\n🐙 GITHUB WORKFLOW AUTOMATION (v2.0.0):\n github gh-coordinator # GitHub workflow orchestration and coordination\n github pr-manager # Pull request management with multi-reviewer coordination\n github issue-tracker # Issue management and project coordination\n github release-manager # Release coordination and deployment pipelines\n github repo-architect # Repository structure optimization\n github sync-coordinator # Multi-package synchronization and version alignment\n\n🏗️ CORE ENTERPRISE COMMANDS:\n init [--sparc] # Initialize with enterprise environment + ruv-swarm\n start [--ui] [--swarm] # Start orchestration with swarm intelligence\n spawn <type> [--name] # Create AI agent with swarm coordination\n agent <subcommand> # 🆕 Multi-provider agent execution + management\n sparc <subcommand> # 17 SPARC modes with neural enhancement\n memory <subcommand> # Cross-session persistent memory with neural learning\n config <subcommand> # 🆕 Provider configuration management\n status # Comprehensive system status with performance metrics\n\n🤖 NEURAL AGENT TYPES (ruv-swarm Integration):\n researcher # Research with web access and data analysis\n coder # Code development with neural patterns\n analyst # Performance analysis and optimization\n architect # System design with enterprise patterns\n tester # Comprehensive testing with automation\n coordinator # Multi-agent orchestration and workflow management\n reviewer # Code review with security and quality checks\n optimizer # Performance optimization and bottleneck analysis\n\n🎮 ENTERPRISE QUICK START:\n # Initialize enterprise environment\n npx [email protected] init --sparc\n\n # 🆕 Execute agents with multi-provider support\n ./claude-flow agent run coder \"Build REST API with auth\" --provider anthropic\n ./claude-flow agent run researcher \"Research React 19\" --provider openrouter # 99% cost savings\n ./claude-flow agent agents # List all 66+ available agents\n\n # Start enterprise orchestration with swarm intelligence\n ./claude-flow start --ui --swarm\n\n # Deploy intelligent multi-agent development workflow\n ./claude-flow swarm \"build enterprise API\" --strategy development --parallel --monitor\n\n # GitHub workflow automation\n ./claude-flow github pr-manager \"coordinate release with automated testing\"\n\n # Neural memory management\n ./claude-flow memory store \"architecture\" \"microservices with API gateway pattern\"\n\n # Real-time system monitoring\n ./claude-flow status --verbose\n\n🏢 ENTERPRISE COMMAND CATEGORIES:\n Core Intelligence: swarm, agent, sparc, memory, neural\n GitHub Automation: github (6 specialized modes)\n Development: init, start, status, config, workflow\n Infrastructure: mcp, terminal, session, docker\n Enterprise: project, deploy, cloud, security, analytics, audit\n\n🧠 NEURAL NETWORK FEATURES (v2.0.0):\n • WASM-powered cognitive patterns with SIMD optimization\n • 27 MCP tools for comprehensive workflow automation\n • Cross-session learning and adaptation\n • Real-time performance monitoring (sub-10ms response times)\n • 32.3% token usage reduction through intelligent coordination\n • Self-healing workflows with automatic error recovery\n\n📊 ENTERPRISE PERFORMANCE METRICS:\n • 84.8% SWE-Bench solve rate through coordinated intelligence\n • 2.8-4.4x speed improvement with parallel execution\n • 60% Docker build performance improvement\n • 100% test success rate with comprehensive validation\n • Sub-10ms MCP response times\n\n🔗 INTEGRATION & COMPATIBILITY:\n • Node.js 20+ optimization for enterprise environments\n • Complete Claude Code integration with enhanced capabilities\n • Multi-platform support (Windows, macOS, Linux)\n • Enterprise security with access control and audit logging\n • Cross-package synchronization and dependency management\n\nGET DETAILED HELP:\n claude-flow help <command> # Command-specific enterprise documentation\n claude-flow <command> --help # Alternative help syntax\n \n Examples:\n claude-flow help swarm # Swarm intelligence coordination\n claude-flow help github # GitHub workflow automation\n claude-flow help neural # Neural network processing\n claude-flow help enterprise # Enterprise features and compliance\n\nCOMMON OPTIONS:\n --verbose, -v Enable detailed output with performance metrics\n --help Show command help with enterprise features\n --config <path> Use custom enterprise configuration\n --parallel Enable parallel execution (default for swarms)\n --monitor Real-time monitoring and performance tracking\n\n📚 Documentation: https://github.com/ruvnet/claude-code-flow\n🐝 ruv-swarm: https://github.com/ruvnet/ruv-FANN/tree/main/ruv-swarm\n\n🚀 Enterprise-Grade AI Agent Orchestration - Built with ❤️ by rUv for the Claude community\n`);\n}\n\nfunction printVersion() {\n console.log(`Claude-Flow v${VERSION}`);\n}\n\nfunction printError(message: string) {\n console.error(`❌ Error: ${message}`);\n}\n\nfunction printSuccess(message: string) {\n console.log(`✅ ${message}`);\n}\n\nfunction printWarning(message: string) {\n console.warn(`⚠️ Warning: ${message}`);\n}\n\nfunction showHelpWithCommands() {\n printHelp();\n console.log('\\nRegistered Commands:');\n const commands = listCommands();\n for (const command of commands) {\n console.log(` ${command.name.padEnd(12)} ${command.description}`);\n }\n console.log('\\nUse \"claude-flow help <command>\" for detailed usage information');\n}\n\nasync function main() {\n const args = Deno.args;\n\n if (args.length === 0) {\n printHelp();\n return;\n }\n\n const command = args[0];\n const { flags, args: parsedArgs } = parseFlags(args.slice(1));\n\n // Handle special commands first\n switch (command) {\n case 'version':\n case '--version':\n case '-v':\n printVersion();\n return;\n\n case 'help':\n case '--help':\n case '-h':\n if (parsedArgs.length > 0) {\n showCommandHelp(parsedArgs[0]);\n } else {\n showHelpWithCommands();\n }\n return;\n }\n\n // Check if this is a registered modular command\n if (hasCommand(command)) {\n try {\n await executeCommand(command, parsedArgs, flags);\n return;\n } catch (err: unknown) {\n printError((err as Error).message);\n return;\n }\n }\n\n // Legacy command handling (to be refactored)\n const subArgs = parsedArgs; // Use parsed args for legacy commands\n\n switch (command) {\n case 'status':\n printSuccess('Claude-Flow System Status:');\n console.log('🟡 Status: Not Running (orchestrator not started)');\n console.log('🤖 Agents: 0 active');\n console.log('📋 Tasks: 0 in queue');\n console.log('💾 Memory: Ready');\n console.log('🖥️ Terminal Pool: Ready');\n console.log('🌐 MCP Server: Stopped');\n break;\n\n case 'monitor':\n printSuccess('Starting system monitor...');\n console.log('📊 Real-time monitoring would display here');\n break;\n\n case 'spawn':\n // Convenience alias for agent spawn\n const spawnType = subArgs[0] || 'general';\n const spawnName = (flags as any).name || `agent-${Date.now()}`;\n\n printSuccess(`Spawning ${spawnType} agent: ${spawnName}`);\n console.log('🤖 Agent would be created with the following configuration:');\n console.log(` Type: ${spawnType}`);\n console.log(` Name: ${spawnName}`);\n console.log(' Capabilities: Research, Analysis, Code Generation');\n console.log(' Status: Ready');\n console.log('\\n📋 Note: Full agent spawning requires orchestrator to be running');\n break;\n\n case 'terminal':\n const terminalCmd = subArgs[0];\n switch (terminalCmd) {\n case 'pool':\n const poolCmd = subArgs[1];\n const detailed = subArgs.includes('--detailed') || subArgs.includes('-d');\n\n if (poolCmd === 'status') {\n printSuccess('Terminal Pool Status:');\n console.log('🖥️ Status: Ready');\n console.log('📊 Pool Size: 10 (default)');\n console.log('🟢 Active Terminals: 0');\n console.log('⏸️ Idle Terminals: 0');\n console.log('📈 Total Created: 0');\n\n if (detailed) {\n console.log('\\n📋 Detailed Information:');\n console.log(' Configuration:');\n console.log(' • Max Pool Size: 10');\n console.log(' • Idle Timeout: 5 minutes');\n console.log(' • Shell: /bin/bash');\n console.log(' • Working Directory: ' + process.cwd());\n console.log(' Performance:');\n console.log(' • Average Response Time: N/A');\n console.log(' • Terminal Creation Time: N/A');\n console.log(' • Memory Usage: N/A');\n console.log(' Health:');\n console.log(' • Pool Health: Healthy');\n console.log(' • Last Health Check: Just now');\n }\n } else if (poolCmd === 'list') {\n printSuccess('Terminal Pool Sessions:');\n console.log('📋 No active terminal sessions');\n } else if (poolCmd === 'create') {\n printSuccess('Creating new terminal session...');\n console.log('🆔 Terminal ID: term-' + Date.now());\n console.log('🖥️ Status: Created');\n console.log('🐚 Shell: /bin/bash');\n } else if (poolCmd === 'terminate') {\n const termId = subArgs[2];\n if (termId) {\n printSuccess(`Terminating terminal: ${termId}`);\n console.log('✅ Terminal terminated successfully');\n } else {\n printError('Usage: terminal pool terminate <terminal-id>');\n }\n } else if (poolCmd === 'stats') {\n // Pool statistics command\n printSuccess('Terminal Pool Statistics:');\n console.log('📊 Utilization: 0%');\n console.log('⚡ Performance Metrics:');\n console.log(' • Average Command Time: N/A');\n console.log(' • Total Commands: 0');\n console.log(' • Failed Commands: 0');\n console.log('♻️ Recycling Stats:');\n console.log(' • Terminals Recycled: 0');\n console.log(' • Average Lifetime: N/A');\n } else {\n console.log('Terminal pool commands: status, list, create, terminate, stats');\n console.log('Options: --detailed, -d');\n }\n break;\n\n case 'create':\n // Advanced terminal creation\n const nameIndex = subArgs.indexOf('--name');\n const shellIndex = subArgs.indexOf('--shell');\n const wdIndex = subArgs.indexOf('--working-directory');\n const envIndex = subArgs.indexOf('--env');\n const persistentIndex = subArgs.indexOf('--persistent');\n\n const terminalConfig = {\n name: nameIndex >= 0 ? subArgs[nameIndex + 1] : 'terminal-' + Date.now(),\n shell: shellIndex >= 0 ? subArgs[shellIndex + 1] : 'bash',\n workingDirectory: wdIndex >= 0 ? subArgs[wdIndex + 1] : process.cwd(),\n env: envIndex >= 0 ? subArgs[envIndex + 1] : '',\n persistent: persistentIndex >= 0,\n };\n\n printSuccess('Creating terminal session...');\n console.log(`🆔 Terminal ID: ${terminalConfig.name}`);\n console.log(`🐚 Shell: ${terminalConfig.shell}`);\n console.log(`📁 Working Directory: ${terminalConfig.workingDirectory}`);\n if (terminalConfig.env) {\n console.log(`🔧 Environment: ${terminalConfig.env}`);\n }\n if (terminalConfig.persistent) {\n console.log('💾 Persistent: Yes');\n }\n break;\n\n case 'execute':\n case 'exec':\n const execCmd = subArgs.slice(1).join(' ');\n const sessionFlag = subArgs.indexOf('--session');\n const timeoutFlag = subArgs.indexOf('--timeout');\n const backgroundFlag = subArgs.includes('--background');\n\n if (execCmd && sessionFlag < 0) {\n printSuccess(`Executing command: ${execCmd}`);\n console.log('🖥️ Command would execute in terminal pool');\n console.log('📝 Output would appear here');\n if (backgroundFlag) {\n console.log('🔄 Running in background');\n }\n } else if (sessionFlag >= 0) {\n const sessionId = subArgs[sessionFlag + 1];\n const cmdStart = subArgs.indexOf('\"');\n const cmdEnd = subArgs.lastIndexOf('\"');\n const command =\n cmdStart >= 0 && cmdEnd > cmdStart\n ? subArgs\n .slice(cmdStart, cmdEnd + 1)\n .join(' ')\n .slice(1, -1)\n : 'echo \"No command\"';\n\n printSuccess(`Executing in session ${sessionId}: ${command}`);\n if (timeoutFlag >= 0) {\n console.log(`⏱️ Timeout: ${subArgs[timeoutFlag + 1]}`);\n }\n } else {\n printError('Usage: terminal execute <command> [--session <id>] [--timeout <duration>]');\n }\n break;\n\n case 'batch-exec':\n // Batch command execution\n const batchSession = subArgs.find((arg) => !arg.startsWith('--'));\n const commandsFlag = subArgs.indexOf('--commands');\n const fileFlag = subArgs.indexOf('--file');\n\n if (commandsFlag >= 0) {\n const commands = subArgs[commandsFlag + 1].split(',');\n printSuccess(`Executing ${commands.length} commands in sequence`);\n commands.forEach((cmd: string, i: number) => {\n console.log(` ${i + 1}. ${cmd}`);\n });\n } else if (fileFlag >= 0) {\n printSuccess(`Executing commands from file: ${subArgs[fileFlag + 1]}`);\n } else {\n console.log('Usage: terminal batch-exec --commands \"cmd1,cmd2,cmd3\" [--session <id>]');\n }\n break;\n\n case 'list':\n // List all terminal sessions\n const listDetailed = subArgs.includes('--detailed');\n printSuccess('Active Terminal Sessions:');\n console.log('📋 No active terminal sessions');\n if (listDetailed) {\n console.log('\\nSystem Information:');\n console.log(' • Total Sessions Created: 0');\n console.log(' • Sessions Recycled: 0');\n console.log(' • Average Session Lifetime: N/A');\n }\n break;\n\n case 'info':\n // Get terminal info\n const infoSessionId = subArgs[1];\n if (infoSessionId) {\n printSuccess(`Terminal Information: ${infoSessionId}`);\n console.log('🆔 Session ID: ' + infoSessionId);\n console.log('📍 Status: Not found');\n console.log('🐚 Shell: N/A');\n console.log('📁 Working Directory: N/A');\n console.log('⏱️ Created: N/A');\n console.log('📊 Commands Executed: 0');\n } else {\n printError('Usage: terminal info <session-id>');\n }\n break;\n\n case 'attach':\n // Attach to terminal\n const attachId = subArgs[1];\n if (attachId) {\n printSuccess(`Attaching to terminal: ${attachId}`);\n console.log('🔗 Would enter interactive mode');\n console.log('💡 Press Ctrl+D to detach');\n } else {\n printError('Usage: terminal attach <session-id>');\n }\n break;\n\n case 'detach':\n // Detach from terminal\n const detachId = subArgs[1];\n if (detachId) {\n printSuccess(`Detaching from terminal: ${detachId}`);\n console.log('✅ Session continues running in background');\n } else {\n printError('Usage: terminal detach <session-id>');\n }\n break;\n\n case 'terminate':\n // Terminate terminal\n const terminateId = subArgs[1];\n const graceful = subArgs.includes('--graceful');\n if (terminateId) {\n printSuccess(`Terminating terminal: ${terminateId}`);\n if (graceful) {\n console.log('🕐 Graceful shutdown initiated');\n }\n console.log('✅ Terminal terminated');\n } else {\n printError('Usage: terminal terminate <session-id> [--graceful]');\n }\n break;\n\n case 'cleanup':\n // Cleanup idle terminals\n const idleTime = subArgs.find((arg) => arg.includes('--idle-longer-than'));\n printSuccess('Cleaning up idle terminals...');\n console.log('🧹 Scanning for idle sessions');\n if (idleTime) {\n console.log(`⏱️ Idle threshold: ${idleTime.split('=')[1] || '30m'}`);\n }\n console.log('✅ Cleanup complete: 0 terminals removed');\n break;\n\n case 'monitor':\n // Monitor terminal\n const monitorId = subArgs[1];\n if (monitorId) {\n printSuccess(`Monitoring terminal: ${monitorId}`);\n console.log('📊 Real-time metrics would display here');\n console.log(' • CPU: 0%');\n console.log(' • Memory: 0MB');\n console.log(' • I/O: 0 ops/s');\n } else {\n printError('Usage: terminal monitor <session-id>');\n }\n break;\n\n case 'record':\n // Record terminal session\n const recordId = subArgs[1];\n const outputFlag = subArgs.indexOf('--output');\n if (recordId && outputFlag >= 0) {\n printSuccess(`Recording terminal session: ${recordId}`);\n console.log(`📹 Output file: ${subArgs[outputFlag + 1]}`);\n console.log('🔴 Recording started');\n } else {\n printError('Usage: terminal record <session-id> --output <file>');\n }\n break;\n\n case 'replay':\n // Replay terminal session\n const replayFile = subArgs[1];\n if (replayFile) {\n printSuccess(`Replaying session from: ${replayFile}`);\n console.log('▶️ Playback would start here');\n console.log('⏸️ Controls: space=pause, arrows=seek, q=quit');\n } else {\n printError('Usage: terminal replay <recording-file>');\n }\n break;\n\n case 'share':\n // Share terminal session\n const shareId = subArgs[1];\n const accessLevel = subArgs.find((arg) => arg.includes('--access-level'));\n if (shareId) {\n printSuccess(`Sharing terminal session: ${shareId}`);\n console.log(`🔗 Share URL: https://claude-flow.local/terminal/${shareId}/view`);\n console.log(`🔐 Access: ${accessLevel ? accessLevel.split('=')[1] : 'read-only'}`);\n console.log('⏱️ Expires in: 2 hours');\n } else {\n printError('Usage: terminal share <session-id> [--access-level read|write]');\n }\n break;\n\n case 'multi-config':\n // Multi-terminal configuration\n const multiCmd = subArgs[1];\n if (multiCmd === 'create') {\n const configName = subArgs.find((arg) => !arg.startsWith('--'));\n printSuccess(`Creating multi-terminal configuration: ${configName || 'default'}`);\n console.log('📋 Configuration template created');\n } else {\n console.log('Usage: terminal multi-config create --name <name> --config <file>');\n }\n break;\n\n case 'multi-launch':\n // Launch multi-terminal environment\n const envName = subArgs[1];\n if (envName) {\n printSuccess(`Launching multi-terminal environment: ${envName}`);\n console.log('🚀 Starting terminals in dependency order...');\n console.log(' 1. database - Starting...');\n console.log(' 2. backend-api - Waiting for database...');\n console.log(' 3. frontend-app - Waiting for backend...');\n console.log('✅ All terminals launched successfully');\n } else {\n printError('Usage: terminal multi-launch <environment-name>');\n }\n break;\n\n case 'batch-create':\n // Batch create terminals\n const configFile = subArgs.find((arg) => arg.includes('--config'));\n printSuccess('Creating multiple terminal sessions...');\n if (configFile) {\n console.log(`📄 Loading config from: ${configFile.split('=')[1]}`);\n }\n console.log('✅ Created 3 terminal sessions');\n break;\n\n case 'session':\n // Legacy session command handling\n const sessionCmd = subArgs[1];\n if (sessionCmd === 'list') {\n printSuccess('Terminal Sessions:');\n console.log('📋 No active sessions');\n } else if (sessionCmd === 'info') {\n const sessionId = subArgs[2];\n if (sessionId) {\n printSuccess(`Session Info: ${sessionId}`);\n console.log('🆔 Session ID: ' + sessionId);\n console.log('📍 Status: Not found');\n } else {\n printError('Usage: terminal session info <session-id>');\n }\n } else {\n console.log('Terminal session commands: list, info');\n }\n break;\n\n default:\n console.log('Terminal commands:');\n console.log(' Basic:');\n console.log(' pool - Manage terminal pool (status, list, create, terminate)');\n console.log(' create - Create new terminal with options');\n console.log(' execute - Execute command in terminal');\n console.log(' list - List all active terminals');\n console.log(' info - Get terminal information');\n console.log(' Session Control:');\n console.log(' attach - Attach to terminal session');\n console.log(' detach - Detach from terminal');\n console.log(' terminate - Terminate terminal session');\n console.log(' cleanup - Clean up idle terminals');\n console.log(' Advanced:');\n console.log(' batch-exec - Execute multiple commands');\n console.log(' monitor - Monitor terminal metrics');\n console.log(' record - Record terminal session');\n console.log(' replay - Replay recorded session');\n console.log(' share - Share terminal session');\n console.log(' Multi-Terminal:');\n console.log(' multi-config - Create multi-terminal config');\n console.log(' multi-launch - Launch terminal environment');\n console.log(' batch-create - Create multiple terminals');\n console.log('\\nExamples:');\n console.log(' terminal pool status --detailed');\n console.log(' terminal create --name \"dev\" --shell bash --persistent');\n console.log(' terminal execute \"npm test\" --session dev --timeout 5m');\n console.log(' terminal batch-exec --commands \"cd /app,npm install,npm start\"');\n console.log(' terminal monitor dev --metrics cpu,memory');\n }\n break;\n\n case 'session':\n printSuccess('Terminal session manager ready');\n console.log('🖥️ Session operations would be handled here');\n break;\n\n case 'workflow':\n const workflowFile = subArgs[0];\n if (workflowFile) {\n printSuccess(`Executing workflow: ${workflowFile}`);\n console.log('🔄 Workflow execution would start here');\n } else {\n printError('Please specify a workflow file');\n }\n break;\n\n case 'repl':\n printSuccess('Starting interactive REPL mode...');\n await startRepl();\n break;\n\n case 'project':\n const projectCmd = subArgs[0];\n switch (projectCmd) {\n case 'create':\n const projectName = subArgs[1];\n if (!projectName) {\n printError('Usage: project create <name> [options]');\n break;\n }\n\n const isolationFlag = subArgs.indexOf('--isolation');\n const resourceQuotaFlag = subArgs.indexOf('--resource-quota');\n const securityProfileFlag = subArgs.indexOf('--security-profile');\n const templateFlag = subArgs.indexOf('--template');\n\n printSuccess(`Creating project: ${projectName}`);\n console.log('🏗️ Project Configuration:');\n console.log(` Name: ${projectName}`);\n console.log(\n ` Isolation: ${isolationFlag >= 0 ? subArgs[isolationFlag + 1] : 'standard'}`,\n );\n if (resourceQuotaFlag >= 0) {\n console.log(` Resource Quota: ${subArgs[resourceQuotaFlag + 1]}`);\n }\n console.log(\n ` Security Profile: ${securityProfileFlag >= 0 ? subArgs[securityProfileFlag + 1] : 'default'}`,\n );\n if (templateFlag >= 0) {\n console.log(` Template: ${subArgs[templateFlag + 1]}`);\n }\n\n // Create project directory structure\n console.log('\\n📁 Creating project structure:');\n console.log(` ✓ Created /projects/${projectName}/`);\n console.log(` ✓ Created /projects/${projectName}/agents/`);\n console.log(` ✓ Created /projects/${projectName}/workflows/`);\n console.log(` ✓ Created /projects/${projectName}/config/`);\n console.log(` ✓ Created /projects/${projectName}/data/`);\n console.log(` ✓ Created project-config.json`);\n console.log('\\n✅ Project created successfully!');\n break;\n\n case 'switch':\n const switchProject = subArgs[1];\n if (!switchProject) {\n printError('Usage: project switch <name>');\n break;\n }\n printSuccess(`Switching to project: ${switchProject}`);\n console.log('🔄 Loading project context...');\n console.log(' ✓ Project configuration loaded');\n console.log(' ✓ Agent states restored');\n console.log(' ✓ Workflow history loaded');\n console.log(`\\n📍 Active project: ${switchProject}`);\n break;\n\n case 'list':\n const showActive = subArgs.includes('--active');\n const withStats = subArgs.includes('--with-stats');\n\n printSuccess('Available projects:');\n const projects = [\n { name: 'microservices-platform', status: 'active', agents: 12, tasks: 45 },\n { name: 'ai-research', status: 'idle', agents: 3, tasks: 8 },\n { name: 'frontend-apps', status: 'archived', agents: 0, tasks: 0 },\n ];\n\n projects.forEach((project) => {\n if (showActive && project.status !== 'active') return;\n\n console.log(`\\n📦 ${project.name}`);\n console.log(` Status: ${project.status}`);\n if (withStats) {\n console.log(` Active Agents: ${project.agents}`);\n console.log(` Pending Tasks: ${project.tasks}`);\n }\n });\n break;\n\n case 'config':\n const configAction = subArgs[1];\n const configProject = subArgs[2];\n\n if (configAction === 'set' && configProject) {\n const configKey = subArgs[3];\n const configValue = subArgs.slice(4).join(' ');\n\n printSuccess(`Updating project configuration: ${configProject}`);\n console.log(` Setting: ${configKey} = ${configValue}`);\n console.log('✅ Configuration updated');\n } else if (configAction === 'get' && configProject) {\n const configKey = subArgs[3];\n console.log(`Project: ${configProject}`);\n console.log(`${configKey}: (configuration value)`);\n } else {\n console.log('Usage: project config set <project> <key> <value>');\n console.log(' project config get <project> <key>');\n }\n break;\n\n case 'monitor':\n const monitorProject = subArgs[1];\n if (!monitorProject) {\n printError('Usage: project monitor <name> [options]');\n break;\n }\n\n printSuccess(`Monitoring project: ${monitorProject}`);\n console.log('\\n📊 Real-time Metrics:');\n console.log(' Resource Usage:');\n console.log(' • CPU: 45%');\n console.log(' • Memory: 2.3GB / 4GB');\n console.log(' • Storage: 8.5GB / 20GB');\n console.log(' • Network: 23Mbps / 100Mbps');\n console.log(' Agent Performance:');\n console.log(' • Active Agents: 8');\n console.log(' • Average Response Time: 234ms');\n console.log(' • Task Success Rate: 94%');\n console.log(' Costs:');\n console.log(' • Today: $124.50');\n console.log(' • This Month: $2,845.00');\n break;\n\n case 'backup':\n const backupProject = subArgs[1];\n if (!backupProject) {\n printError('Usage: project backup <name> [options]');\n break;\n }\n\n const includeData = subArgs.includes('--include-data');\n const includeConfig = subArgs.includes('--include-config');\n const includeHistory = subArgs.includes('--include-history');\n const outputFlag = subArgs.indexOf('--output');\n\n printSuccess(`Creating backup for project: ${backupProject}`);\n console.log('🗄️ Backup Configuration:');\n console.log(` Include Data: ${includeData ? 'Yes' : 'No'}`);\n console.log(` Include Config: ${includeConfig ? 'Yes' : 'No'}`);\n console.log(` Include History: ${includeHistory ? 'Yes' : 'No'}`);\n\n console.log('\\n📦 Creating backup...');\n console.log(' ✓ Collecting project data');\n console.log(' ✓ Compressing files');\n console.log(' ✓ Encrypting backup');\n\n const outputFile =\n outputFlag >= 0\n ? subArgs[outputFlag + 1]\n : `${backupProject}-backup-${Date.now()}.tar.gz`;\n console.log(`\\n✅ Backup created: ${outputFile}`);\n console.log(' Size: 145MB');\n console.log(' Checksum: sha256:abcd1234...');\n break;\n\n case 'share':\n const shareFrom = subArgs[1];\n const shareTo = subArgs[2];\n\n if (!shareFrom || !shareTo) {\n printError('Usage: project share <from-project> <to-project> [options]');\n break;\n }\n\n const agentsFlag = subArgs.indexOf('--agents');\n const permissionsFlag = subArgs.indexOf('--permissions');\n const durationFlag = subArgs.indexOf('--duration');\n\n printSuccess(`Sharing resources from ${shareFrom} to ${shareTo}`);\n if (agentsFlag >= 0) {\n console.log(` Agents: ${subArgs[agentsFlag + 1]}`);\n }\n if (permissionsFlag >= 0) {\n console.log(` Permissions: ${subArgs[permissionsFlag + 1]}`);\n }\n if (durationFlag >= 0) {\n console.log(` Duration: ${subArgs[durationFlag + 1]}`);\n }\n console.log('\\n✅ Resource sharing configured');\n break;\n\n case 'federation':\n const fedCmd = subArgs[1];\n\n if (fedCmd === 'create') {\n const fedName = subArgs[2];\n const projectsFlag = subArgs.indexOf('--projects');\n\n if (!fedName) {\n printError('Usage: project federation create <name> --projects <project-list>');\n break;\n }\n\n printSuccess(`Creating federation: ${fedName}`);\n if (projectsFlag >= 0) {\n console.log(` Projects: ${subArgs[projectsFlag + 1]}`);\n }\n console.log(' Coordination Model: hierarchical');\n console.log(' Shared Resources: knowledge-base, artifact-registry');\n console.log('\\n✅ Federation created successfully');\n } else if (fedCmd === 'list') {\n printSuccess('Active federations:');\n console.log('\\n🏢 development-ecosystem');\n console.log(' Projects: backend-services, frontend-apps, infrastructure');\n console.log(' Coordinator: infrastructure');\n console.log(' Status: Active');\n } else {\n console.log('Federation commands: create, list, workflow');\n }\n break;\n\n default:\n console.log('Project commands:');\n console.log(' create - Create new project with isolation');\n console.log(' switch - Switch active project context');\n console.log(' list - List all projects');\n console.log(' config - Get/set project configuration');\n console.log(' monitor - Monitor project resources and performance');\n console.log(' backup - Create project backup');\n console.log(' share - Share resources between projects');\n console.log(' federation - Manage project federations');\n console.log('\\nExamples:');\n console.log(\n ' project create \"microservices\" --isolation strict --resource-quota \"agents:15,memory:4GB\"',\n );\n console.log(' project switch \"microservices\"');\n console.log(' project monitor \"microservices\" --real-time');\n }\n break;\n\n case 'cloud':\n const cloudCmd = subArgs[0];\n const cloudProvider = subArgs[1];\n\n switch (cloudCmd) {\n case 'aws':\n switch (cloudProvider) {\n case 'deploy':\n const awsServices = subArgs.indexOf('--services');\n const awsRegions = subArgs.indexOf('--regions');\n const awsHA = subArgs.includes('--ha-configuration');\n const awsCostOpt = subArgs.includes('--cost-optimization');\n\n printSuccess('Deploying Claude-Flow to AWS');\n console.log('☁️ AWS Deployment Configuration:');\n if (awsServices >= 0) {\n console.log(` Services: ${subArgs[awsServices + 1]}`);\n }\n if (awsRegions >= 0) {\n console.log(` Regions: ${subArgs[awsRegions + 1]}`);\n }\n console.log(` High Availability: ${awsHA ? 'Enabled' : 'Disabled'}`);\n console.log(` Cost Optimization: ${awsCostOpt ? 'Enabled' : 'Disabled'}`);\n\n console.log('\\n🚀 Deployment Progress:');\n console.log(' ✓ Creating ECS cluster');\n console.log(' ✓ Setting up Lambda functions');\n console.log(' ✓ Configuring RDS database');\n console.log(' ✓ Setting up S3 buckets');\n console.log(' ✓ Configuring CloudWatch monitoring');\n console.log(' ✓ Setting up load balancers');\n\n console.log('\\n✅ AWS deployment completed successfully');\n console.log(' Cluster ARN: arn:aws:ecs:us-east-1:123456789012:cluster/claude-flow');\n console.log(' API Gateway: https://api.aws.claude-flow.com');\n console.log(' Monitoring: https://console.aws.amazon.com/cloudwatch');\n break;\n\n case 'configure':\n printSuccess('Configuring AWS integration');\n console.log('🔧 AWS Configuration:');\n console.log(' ✓ IAM roles and policies');\n console.log(' ✓ VPC and security groups');\n console.log(' ✓ Auto-scaling policies');\n console.log(' ✓ Backup and disaster recovery');\n console.log(' ✓ Cost monitoring and alerts');\n break;\n\n case 'status':\n printSuccess('AWS Infrastructure Status');\n console.log('\\n🏗️ Infrastructure Health:');\n console.log(' ECS Cluster: 3/3 instances healthy');\n console.log(' Lambda Functions: 12/12 active');\n console.log(' RDS Database: Available (Multi-AZ)');\n console.log(' S3 Buckets: 5 buckets, 2.3TB stored');\n console.log(' CloudWatch: 47 metrics, 0 alarms');\n\n console.log('\\n💰 Cost Summary (This Month):');\n console.log(' Compute (ECS/Lambda): $1,245.50');\n console.log(' Storage (S3/EBS): $342.25');\n console.log(' Network: $87.30');\n console.log(' Total: $1,675.05');\n break;\n\n default:\n console.log('AWS commands: deploy, configure, status');\n }\n break;\n\n case 'azure':\n switch (cloudProvider) {\n case 'deploy':\n const azureServices = subArgs.indexOf('--services');\n const azureRegions = subArgs.indexOf('--regions');\n const azureIntegration = subArgs.includes('--integration-with-aws');\n\n printSuccess('Deploying Claude-Flow to Azure');\n console.log('☁️ Azure Deployment Configuration:');\n if (azureServices >= 0) {\n console.log(` Services: ${subArgs[azureServices + 1]}`);\n }\n if (azureRegions >= 0) {\n console.log(` Regions: ${subArgs[azureRegions + 1]}`);\n }\n console.log(` AWS Integration: ${azureIntegration ? 'Enabled' : 'Disabled'}`);\n\n console.log('\\n🚀 Deployment Progress:');\n console.log(' ✓ Creating AKS cluster');\n console.log(' ✓ Setting up Azure Functions');\n console.log(' ✓ Configuring Cosmos DB');\n console.log(' ✓ Setting up Blob Storage');\n console.log(' ✓ Configuring Azure Monitor');\n console.log(' ✓ Setting up Application Gateway');\n\n console.log('\\n✅ Azure deployment completed successfully');\n console.log(' Resource Group: claude-flow-production');\n console.log(' API Gateway: https://api.azure.claude-flow.com');\n console.log(' Monitoring: https://portal.azure.com');\n break;\n\n case 'configure':\n printSuccess('Configuring Azure integration');\n console.log('🔧 Azure Configuration:');\n console.log(' ✓ Service principals and RBAC');\n console.log(' ✓ Virtual networks and NSGs');\n console.log(' ✓ Auto-scaling rules');\n console.log(' ✓ Backup and site recovery');\n console.log(' ✓ Cost management and budgets');\n break;\n\n case 'status':\n printSuccess('Azure Infrastructure Status');\n console.log('\\n🏗️ Infrastructure Health:');\n console.log(' AKS Cluster: 3/3 nodes ready');\n console.log(' Azure Functions: 8/8 active');\n console.log(' Cosmos DB: Available (Global)');\n console.log(' Blob Storage: 3 containers, 1.8TB stored');\n console.log(' Azure Monitor: 35 metrics, 0 alerts');\n\n console.log('\\n💰 Cost Summary (This Month):');\n console.log(' Compute (AKS/Functions): $985.40');\n console.log(' Storage (Blob/Cosmos): $267.85');\n console.log(' Network: $63.20');\n console.log(' Total: $1,316.45');\n break;\n\n default:\n console.log('Azure commands: deploy, configure, status');\n }\n break;\n\n case 'gcp':\n switch (cloudProvider) {\n case 'deploy':\n const gcpServices = subArgs.indexOf('--services');\n const gcpRegions = subArgs.indexOf('--regions');\n const multiCloud = subArgs.includes('--multi-cloud-networking');\n\n printSuccess('Deploying Claude-Flow to Google Cloud');\n console.log('☁️ GCP Deployment Configuration:');\n if (gcpServices >= 0) {\n console.log(` Services: ${subArgs[gcpServices + 1]}`);\n }\n if (gcpRegions >= 0) {\n console.log(` Regions: ${subArgs[gcpRegions + 1]}`);\n }\n console.log(` Multi-Cloud Networking: ${multiCloud ? 'Enabled' : 'Disabled'}`);\n\n console.log('\\n🚀 Deployment Progress:');\n console.log(' ✓ Creating GKE cluster');\n console.log(' ✓ Setting up Cloud Functions');\n console.log(' ✓ Configuring Cloud SQL');\n console.log(' ✓ Setting up Cloud Storage');\n console.log(' ✓ Configuring Cloud Monitoring');\n console.log(' ✓ Setting up Cloud Load Balancing');\n\n console.log('\\n✅ GCP deployment completed successfully');\n console.log(' Project ID: claude-flow-production');\n console.log(' API Gateway: https://api.gcp.claude-flow.com');\n console.log(' Monitoring: https://console.cloud.google.com');\n break;\n\n case 'configure':\n printSuccess('Configuring GCP integration');\n console.log('🔧 GCP Configuration:');\n console.log(' ✓ Service accounts and IAM');\n console.log(' ✓ VPC networks and firewall rules');\n console.log(' ✓ Auto-scaling policies');\n console.log(' ✓ Backup and disaster recovery');\n console.log(' ✓ Budget alerts and cost optimization');\n break;\n\n case 'status':\n printSuccess('GCP Infrastructure Status');\n console.log('\\n🏗️ Infrastructure Health:');\n console.log(' GKE Cluster: 3/3 nodes ready');\n console.log(' Cloud Functions: 10/10 active');\n console.log(' Cloud SQL: Available (HA)');\n console.log(' Cloud Storage: 4 buckets, 2.1TB stored');\n console.log(' Cloud Monitoring: 42 metrics, 0 incidents');\n\n console.log('\\n💰 Cost Summary (This Month):');\n console.log(' Compute (GKE/Functions): $1,125.30');\n console.log(' Storage (Cloud Storage/SQL): $298.75');\n console.log(' Network: $71.45');\n console.log(' Total: $1,495.50');\n break;\n\n default:\n console.log('GCP commands: deploy, configure, status');\n }\n break;\n\n case 'multi-cloud':\n const multiCloudCmd = subArgs[1];\n\n switch (multiCloudCmd) {\n case 'deploy':\n printSuccess('Deploying multi-cloud Claude-Flow architecture');\n console.log('🌐 Multi-Cloud Deployment:');\n console.log(' Primary: AWS (us-east-1)');\n console.log(' Secondary: Azure (eastus)');\n console.log(' Tertiary: GCP (us-central1)');\n\n console.log('\\n🔗 Cross-Cloud Networking:');\n console.log(' ✓ VPN connections established');\n console.log(' ✓ DNS and load balancing configured');\n console.log(' ✓ Data replication setup');\n console.log(' ✓ Unified monitoring deployed');\n\n console.log('\\n✅ Multi-cloud deployment completed');\n console.log(' Global endpoint: https://global.claude-flow.com');\n console.log(' Failover time: < 30 seconds');\n console.log(' Data consistency: Eventually consistent');\n break;\n\n case 'status':\n printSuccess('Multi-Cloud Infrastructure Status');\n console.log('\\n🌐 Global Infrastructure:');\n console.log(' AWS (Primary): 🟢 Healthy');\n console.log(' Azure (Secondary): 🟢 Healthy');\n console.log(' GCP (Tertiary): 🟢 Healthy');\n\n console.log('\\n📊 Traffic Distribution:');\n console.log(' AWS: 45% (2,341 req/min)');\n console.log(' Azure: 35% (1,823 req/min)');\n console.log(' GCP: 20% (1,042 req/min)');\n\n console.log('\\n💰 Total Cost (This Month): $4,487.00');\n break;\n\n case 'failover':\n const failoverTarget = subArgs[2];\n if (!failoverTarget) {\n printError('Usage: cloud multi-cloud failover <target-cloud>');\n break;\n }\n\n printWarning(`Initiating failover to ${failoverTarget}`);\n console.log('🔄 Failover Process:');\n console.log(' ✓ Health check failed on primary');\n console.log(' ✓ Traffic routing to secondary');\n console.log(' ✓ Database replication verified');\n console.log(' ✓ DNS updates propagated');\n\n console.log(`\\n✅ Failover to ${failoverTarget} completed in 23 seconds`);\n break;\n\n default:\n console.log('Multi-cloud commands: deploy, status, failover');\n }\n break;\n\n case 'kubernetes':\n const k8sCmd = subArgs[1];\n\n switch (k8sCmd) {\n case 'deploy':\n printSuccess('Deploying Claude-Flow to Kubernetes');\n console.log('⚙️ Kubernetes Deployment:');\n console.log(' Namespace: claude-flow');\n console.log(' Replicas: 3');\n console.log(' Resources: 1Gi memory, 500m CPU per pod');\n\n console.log('\\n📦 Deploying Components:');\n console.log(' ✓ Orchestrator deployment');\n console.log(' ✓ MCP server deployment');\n console.log(' ✓ Memory bank deployment');\n console.log(' ✓ Load balancer service');\n console.log(' ✓ Ingress controller');\n console.log(' ✓ ConfigMaps and Secrets');\n\n console.log('\\n✅ Kubernetes deployment completed');\n console.log(' Pods: 3/3 running');\n console.log(' Service: claude-flow-orchestrator-service');\n console.log(' Ingress: https://k8s.claude-flow.com');\n break;\n\n case 'scale':\n const replicas = subArgs[2] || '5';\n printSuccess(`Scaling Claude-Flow to ${replicas} replicas`);\n console.log('📈 Scaling Progress:');\n console.log(` Current replicas: 3`);\n console.log(` Target replicas: ${replicas}`);\n console.log(' ✓ Updating deployment');\n console.log(' ✓ Rolling update in progress');\n console.log(` ✓ Scaled to ${replicas} replicas successfully`);\n break;\n\n case 'status':\n printSuccess('Kubernetes Cluster Status');\n console.log('\\n⚙️ Cluster Information:');\n console.log(' Namespace: claude-flow');\n console.log(' Deployments: 3/3 ready');\n console.log(' Pods: 3/3 running');\n console.log(' Services: 2 active');\n console.log(' ConfigMaps: 2');\n console.log(' Secrets: 1');\n\n console.log('\\n📊 Resource Usage:');\n console.log(' CPU: 1.2/3.0 cores (40%)');\n console.log(' Memory: 2.1/3.0 GB (70%)');\n console.log(' Storage: 8.5/50 GB (17%)');\n break;\n\n default:\n console.log('Kubernetes commands: deploy, scale, status');\n }\n break;\n\n default:\n console.log('Cloud commands:');\n console.log(' aws - Amazon Web Services integration');\n console.log(' azure - Microsoft Azure integration');\n console.log(' gcp - Google Cloud Platform integration');\n console.log(' multi-cloud - Multi-cloud deployment and management');\n console.log(' kubernetes - Kubernetes deployment and management');\n console.log('\\nExamples:');\n console.log(\n ' cloud aws deploy --services \"ecs,lambda,rds\" --regions \"us-east-1,us-west-2\"',\n );\n console.log(' cloud azure deploy --services \"aks,functions,cosmos-db\"');\n console.log(' cloud gcp deploy --services \"gke,cloud-functions,cloud-sql\"');\n console.log(' cloud multi-cloud deploy');\n console.log(' cloud kubernetes deploy');\n }\n break;\n\n case 'claude':\n const claudeCmd = subArgs[0];\n switch (claudeCmd) {\n case 'spawn':\n // Extract task description and flags\n let taskEndIndex = subArgs.length;\n for (let i = 1; i < subArgs.length; i++) {\n if (subArgs[i].startsWith('-')) {\n taskEndIndex = i;\n break;\n }\n }\n\n const task = subArgs.slice(1, taskEndIndex).join(' ');\n if (!task) {\n printError('Usage: claude spawn <task description> [options]');\n break;\n }\n\n // Parse flags\n const flags: Record<string, any> = {};\n for (let i = taskEndIndex; i < subArgs.length; i++) {\n const arg = subArgs[i];\n if (arg === '--tools' || arg === '-t') {\n flags.tools = subArgs[++i];\n } else if (arg === '--no-permissions') {\n flags.noPermissions = true;\n } else if (arg === '--config' || arg === '-c') {\n flags.config = subArgs[++i];\n } else if (arg === '--mode' || arg === '-m') {\n flags.mode = subArgs[++i];\n } else if (arg === '--parallel') {\n flags.parallel = true;\n } else if (arg === '--research') {\n flags.research = true;\n } else if (arg === '--coverage') {\n flags.coverage = parseInt(subArgs[++i]);\n } else if (arg === '--commit') {\n flags.commit = subArgs[++i];\n } else if (arg === '--verbose' || arg === '-v') {\n flags.verbose = true;\n } else if (arg === '--dry-run' || arg === '-d') {\n flags.dryRun = true;\n }\n }\n\n // Build tools list\n let tools = flags.tools || 'View,Edit,Replace,GlobTool,GrepTool,LS,Bash';\n if (flags.parallel) {\n tools += ',BatchTool,dispatch_agent';\n }\n if (flags.research) {\n tools += ',WebFetchTool';\n }\n\n const instanceId = `claude-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n\n if (flags.dryRun) {\n printWarning('DRY RUN - Would execute:');\n console.log(`Command: claude \"<enhanced task with guidance>\" --allowedTools ${tools}`);\n console.log(`Instance ID: ${instanceId}`);\n console.log(`Task: ${task}`);\n console.log(`Tools: ${tools}`);\n console.log(`Mode: ${flags.mode || 'full'}`);\n console.log(`Coverage: ${flags.coverage || 80}%`);\n console.log(`Commit: ${flags.commit || 'phase'}`);\n console.log(`\\nEnhanced Features:`);\n console.log(` - Memory Bank enabled via: npx claude-flow memory commands`);\n console.log(` - Coordination ${flags.parallel ? 'enabled' : 'disabled'}`);\n console.log(` - Access Claude-Flow features through Bash tool`);\n } else {\n printSuccess(`Spawning Claude instance: ${instanceId}`);\n console.log(`📝 Original Task: ${task}`);\n console.log(`🔧 Tools: ${tools}`);\n console.log(`⚙️ Mode: ${flags.mode || 'full'}`);\n console.log(`📊 Coverage: ${flags.coverage || 80}%`);\n console.log(`💾 Commit: ${flags.commit || 'phase'}`);\n console.log(`✨ Enhanced with Claude-Flow guidance for memory and coordination`);\n console.log('');\n console.log('📋 Task will be enhanced with:');\n console.log(' - Memory Bank instructions (store/retrieve)');\n console.log(' - Coordination capabilities (swarm management)');\n console.log(' - Best practices for multi-agent workflows');\n console.log('');\n\n // Build the actual claude command with enhanced guidance\n let enhancedTask = `# Task Assignment\n\n## Your Primary Task\n${task}\n\n## Development Environment\n\nYou are working in a development environment with advanced orchestration capabilities available if needed.\n\n### Project Context\n- Working Directory: ${process.cwd()}\n- Instance ID: ${instanceId}\n- Development Mode: ${flags.mode || 'full'}\n${flags.coverage ? `- Test Coverage Target: ${flags.coverage}%` : ''}\n${flags.commit ? `- Git Commit Strategy: ${flags.commit}` : ''}\n${flags.config ? `- MCP Config: ${flags.config}` : ''}\n\n### Available Tools\n- You have access to these tools: ${tools}\n${flags.tools ? `- Custom tools specified: ${flags.tools}` : ''}\n\n### Optional Orchestration Features\n\nIf this task requires complex coordination, memory persistence, or multi-agent collaboration, you can use the claude-flow system:\n\n1. **Persistent Memory** (if needed for your task)\n - Store project data: \\`npx claude-flow memory store <key> \"<value>\"\\`\n - Retrieve stored data: \\`npx claude-flow memory query <key>\\`\n - Export/Import memory: \\`npx claude-flow memory export/import <file>\\`\n\n2. **Task Coordination** (if working on complex multi-part tasks)\n - Check task status: \\`npx claude-flow status\\`\n - Monitor progress: \\`npx claude-flow monitor\\`\n - List active tasks: \\`npx claude-flow task list\\`\n\n3. **Multi-Agent Collaboration** (if task benefits from parallelization)\n - Spawn specialized agents: \\`npx claude-flow agent spawn <type> --name <name>\\`\n - Create subtasks: \\`npx claude-flow task create <type> \"<description>\"\\`\n - Coordinate work: \\`npx claude-flow task assign <task-id> <agent-id>\\``;\n\n if (flags.parallel) {\n enhancedTask += `\n\n **Parallel Execution Enabled**: The orchestration system can help coordinate parallel work if needed.`;\n }\n\n if (flags.research) {\n enhancedTask += `\n\n **Research Mode**: Web research tools are available for information gathering.`;\n }\n\n enhancedTask += `\n\n### Task Execution Guidelines\n\n1. **Focus on Your Primary Objective**:\n - Understand the specific requirements of the task\n - Plan your approach based on the project's needs\n - Use appropriate tools and practices for the technology stack\n ${flags.mode === 'backend-only' ? ' - Focus on backend implementation' : ''}\n ${flags.mode === 'frontend-only' ? ' - Focus on frontend implementation' : ''}\n ${flags.mode === 'api-only' ? ' - Focus on API design and implementation' : ''}\n\n2. **Development Best Practices**:\n - Write clean, maintainable code following project conventions\n - Include appropriate tests and documentation\n - Use version control effectively\n ${flags.coverage ? ` - Ensure test coverage meets ${flags.coverage}% target` : ''}\n ${flags.commit === 'phase' ? ' - Commit changes after completing major phases' : ''}\n ${flags.commit === 'feature' ? ' - Commit changes after each feature is complete' : ''}\n ${flags.commit === 'manual' ? ' - Only commit when explicitly requested' : ''}\n\n3. **Leverage Orchestration When Beneficial**:\n - For complex tasks requiring persistent state, use the memory bank\n - For multi-part projects, use task coordination features\n - For parallelizable work, consider multi-agent approaches\n ${flags.parallel ? ' - Parallel capabilities are enabled for this task' : ''}\n ${flags.research ? ' - Research tools are available if needed' : ''}\n ${flags.noPermissions ? ' - Running with --no-permissions mode' : ''}\n ${flags.verbose ? ' - Verbose mode enabled for detailed output' : ''}\n\n## Getting Started\n\nBegin working on your task. The orchestration features are available as tools to help you be more effective, but your primary focus should be on delivering the requested functionality.\n\n### Quick Reference (if using orchestration features)\n\n\\`\\`\\`bash\n# Example: Storing project-specific data\nBash(\"npx claude-flow memory store project_config '{\\\\\"name\\\\\": \\\\\"my-app\\\\\", \\\\\"version\\\\\": \\\\\"1.0.0\\\\\"}'\")\n\n# Example: Checking for previous work\nBash(\"npx claude-flow memory query previous_implementation\")\n\n# Example: Creating subtasks for complex projects\nBash(\"npx claude-flow task create frontend 'Build React components'\")\nBash(\"npx claude-flow task create backend 'Implement API endpoints'\")\n\\`\\`\\`\n\nRemember: These are optional tools. Use them when they add value to your development process.\n\n## Development Mode: ${flags.mode || 'full'}\n${flags.mode === 'backend-only' ? `Focus on server-side implementation, APIs, and business logic.` : ''}\n${flags.mode === 'frontend-only' ? `Focus on client-side implementation, UI/UX, and user interactions.` : ''}\n${flags.mode === 'api-only' ? `Focus on API design, documentation, and endpoint implementation.` : ''}\n${flags.mode === 'full' || !flags.mode ? `Full-stack development covering all aspects of the application.` : ''}\n\n`;\n\n const claudeArgs = [enhancedTask];\n claudeArgs.push('--allowedTools', tools);\n\n // DEBUG: Log what we're about to pass\n console.log('\\n🔍 DEBUG - Command Construction:');\n console.log(`First arg length: ${claudeArgs[0].length} chars`);\n console.log(`First 100 chars: ${claudeArgs[0].substring(0, 100)}...`);\n console.log(`Args count: ${claudeArgs.length}`);\n\n if (flags.noPermissions) {\n claudeArgs.push('--dangerously-skip-permissions');\n }\n\n if (flags.config) {\n claudeArgs.push('--mcp-config', flags.config);\n }\n\n if (flags.verbose) {\n claudeArgs.push('--verbose');\n }\n\n // Execute the actual claude command\n try {\n // Debug: Log the actual command being executed\n if (flags.verbose) {\n console.log('Debug - Executing command:');\n console.log(\n `claude ${claudeArgs.map((arg) => (arg.includes(' ') || arg.includes('\\n') ? `\"${arg}\"` : arg)).join(' ')}`,\n );\n }\n\n const command = new Deno.Command('claude', {\n args: claudeArgs,\n env: {\n ...Deno.env.toObject(),\n CLAUDE_INSTANCE_ID: instanceId,\n CLAUDE_FLOW_MODE: flags.mode || 'full',\n CLAUDE_FLOW_COVERAGE: (flags.coverage || 80).toString(),\n CLAUDE_FLOW_COMMIT: flags.commit || 'phase',\n // Add claude-flow specific features\n CLAUDE_FLOW_MEMORY_ENABLED: 'true',\n CLAUDE_FLOW_MEMORY_NAMESPACE: 'default',\n CLAUDE_FLOW_COORDINATION_ENABLED: flags.parallel ? 'true' : 'false',\n CLAUDE_FLOW_FEATURES: 'memory,coordination,swarm',\n },\n stdin: 'inherit',\n stdout: 'inherit',\n stderr: 'inherit',\n });\n\n const child = command.spawn();\n const status = await child.status;\n\n if (status.success) {\n printSuccess(`Claude instance ${instanceId} completed successfully`);\n } else {\n printError(`Claude instance ${instanceId} exited with code ${status.code}`);\n }\n } catch (err: unknown) {\n printError(`Failed to spawn Claude: ${(err as Error).message}`);\n console.log('Make sure you have the Claude CLI installed.');\n }\n }\n break;\n\n case 'batch':\n const workflowFile = subArgs[1];\n if (!workflowFile) {\n printError('Usage: claude batch <workflow-file>');\n break;\n }\n printSuccess(`Loading workflow: ${workflowFile}`);\n console.log('📋 Batch execution would process workflow file');\n break;\n\n default:\n console.log('Claude commands: spawn, batch');\n console.log('\\nExamples:');\n console.log(\n ' claude-flow claude spawn \"implement user authentication\" --research --parallel',\n );\n console.log(' claude-flow claude spawn \"fix bug in payment system\" --no-permissions');\n console.log(' claude-flow claude batch workflow.json --dry-run');\n }\n break;\n\n case 'deploy':\n const deployCmd = subArgs[0];\n switch (deployCmd) {\n case 'ha-cluster':\n const nodes = subArgs.find((arg) => arg.includes('--nodes'));\n const regions = subArgs.find((arg) => arg.includes('--regions'));\n const replicationFactor = subArgs.find((arg) => arg.includes('--replication-factor'));\n\n printSuccess('Deploying High Availability Cluster...');\n console.log('🏗️ HA Configuration:');\n console.log(` Nodes: ${nodes ? nodes.split('=')[1] : '3'}`);\n console.log(\n ` Regions: ${regions ? regions.split('=')[1] : 'us-east-1,us-west-2,eu-west-1'}`,\n );\n console.log(\n ` Replication Factor: ${replicationFactor ? replicationFactor.split('=')[1] : '2'}`,\n );\n console.log(' Load Balancer: nginx');\n console.log(' Health Checks: comprehensive');\n\n console.log('\\n🚀 Deployment Progress:');\n console.log(' ✓ Provisioning nodes in us-east-1');\n console.log(' ✓ Provisioning nodes in us-west-2');\n console.log(' ✓ Provisioning nodes in eu-west-1');\n console.log(' ✓ Configuring load balancer');\n console.log(' ✓ Setting up health checks');\n console.log(' ✓ Establishing replication');\n console.log('\\n✅ HA cluster deployed successfully!');\n console.log(' Cluster endpoint: https://claude-flow-ha.example.com');\n break;\n\n case 'scaling':\n const scalingAction = subArgs[1];\n\n if (scalingAction === 'configure') {\n printSuccess('Configuring Auto-Scaling...');\n console.log('📈 Scaling Configuration:');\n console.log(' Min Instances: 2');\n console.log(' Max Instances: 50');\n console.log(' Scale Up Threshold: CPU:70%, Memory:80%');\n console.log(' Scale Down Threshold: CPU:30%, Memory:40%');\n console.log(' Cool-down Periods: Up:300s, Down:600s');\n console.log('\\n✅ Auto-scaling configured');\n } else if (scalingAction === 'predictive') {\n printSuccess('Enabling Predictive Scaling...');\n console.log('🔮 Predictive Configuration:');\n console.log(' Forecast Horizon: 1 hour');\n console.log(' Learning Period: 7 days');\n console.log(' Confidence Threshold: 0.8');\n console.log(' ML Model: LSTM-based forecasting');\n console.log('\\n✅ Predictive scaling enabled');\n } else {\n console.log('Scaling commands: configure, predictive, status');\n }\n break;\n\n case 'security':\n const securityAction = subArgs[1];\n\n if (securityAction === 'harden') {\n printSuccess('Applying Security Hardening...');\n console.log('🔒 Security Configuration:');\n console.log(' Profile: enterprise');\n console.log(' Encryption: all-traffic, at-rest');\n console.log(' Authentication: multi-factor');\n console.log(' Authorization: RBAC');\n console.log(' Audit Logging: comprehensive');\n console.log(' Compliance: SOC2, GDPR, HIPAA');\n\n console.log('\\n🛡️ Applying security measures:');\n console.log(' ✓ Enabling encryption at rest');\n console.log(' ✓ Configuring TLS 1.3 minimum');\n console.log(' ✓ Setting up MFA requirements');\n console.log(' ✓ Implementing RBAC policies');\n console.log(' ✓ Enabling audit logging');\n console.log(' ✓ Applying compliance controls');\n console.log('\\n✅ Security hardening complete');\n } else if (securityAction === 'monitor') {\n printSuccess('Security Monitoring Active');\n console.log('🔍 Real-time Security Status:');\n console.log(' Threat Level: Low');\n console.log(' Active Sessions: 42');\n console.log(' Failed Auth Attempts: 3 (last 24h)');\n console.log(' Anomalies Detected: 0');\n console.log(' Compliance Status: ✅ Compliant');\n } else {\n console.log('Security commands: harden, policy, rbac, monitor');\n }\n break;\n\n case 'kubernetes':\n case 'k8s':\n printSuccess('Deploying to Kubernetes...');\n console.log('☸️ Kubernetes Deployment:');\n console.log(' Namespace: claude-flow');\n console.log(' Replicas: 3');\n console.log(' Image: claude-flow/orchestrator:latest');\n console.log(' Service Type: LoadBalancer');\n\n console.log('\\n📦 Creating resources:');\n console.log(' ✓ Created namespace/claude-flow');\n console.log(' ✓ Created deployment/claude-flow-orchestrator');\n console.log(' ✓ Created service/claude-flow-orchestrator-service');\n console.log(' ✓ Created configmap/claude-flow-config');\n console.log(' ✓ Created secret/claude-flow-secrets');\n console.log('\\n✅ Kubernetes deployment complete');\n console.log(' Service endpoint: http://a1b2c3d4.elb.amazonaws.com');\n break;\n\n default:\n console.log('Deploy commands:');\n console.log(' ha-cluster - Deploy high availability cluster');\n console.log(' scaling - Configure auto-scaling');\n console.log(' security - Security hardening and monitoring');\n console.log(' kubernetes - Deploy to Kubernetes cluster');\n console.log('\\nExamples:');\n console.log(' deploy ha-cluster --nodes=3 --regions=\"us-east-1,us-west-2\"');\n console.log(' deploy scaling configure --min=2 --max=50');\n console.log(' deploy security harden --profile enterprise');\n }\n break;\n\n case 'analytics':\n const analyticsCmd = subArgs[0];\n switch (analyticsCmd) {\n case 'performance':\n printSuccess('Performance Analytics Report');\n console.log('\\n📊 System Performance (Last 30 Days):');\n console.log(' Agent Productivity:');\n console.log(' • Tasks Completed: 12,847');\n console.log(' • Average Task Time: 3.4 minutes');\n console.log(' • Success Rate: 94.2%');\n console.log(' Resource Efficiency:');\n console.log(' • CPU Utilization: 67% average');\n console.log(' • Memory Usage: 2.8GB average');\n console.log(' • Cost per Task: $0.024');\n console.log(' Trends:');\n console.log(' • Performance: ↑ 12% improvement');\n console.log(' • Efficiency: ↑ 8% improvement');\n console.log(' • Costs: ↓ 15% reduction');\n break;\n\n case 'business-impact':\n printSuccess('Business Impact Analysis');\n console.log('\\n💼 Business Metrics:');\n console.log(' Productivity Gains:');\n console.log(' • Development Velocity: +45%');\n console.log(' • Time to Market: -30%');\n console.log(' • Defect Rate: -62%');\n console.log(' Cost Savings:');\n console.log(' • Monthly Savings: $24,500');\n console.log(' • ROI: 312%');\n console.log(' • Payback Period: 3.2 months');\n console.log(' Quality Improvements:');\n console.log(' • Code Coverage: 92%');\n console.log(' • Customer Satisfaction: +18%');\n break;\n\n case 'cost':\n const costCmd = subArgs[1];\n if (costCmd === 'analyze') {\n printSuccess('Cost Analysis Report');\n console.log('\\n💰 Cost Breakdown:');\n console.log(' By Project:');\n console.log(' • microservices-platform: $8,234 (41%)');\n console.log(' • ai-research: $5,123 (26%)');\n console.log(' • frontend-apps: $3,456 (17%)');\n console.log(' • other: $3,187 (16%)');\n console.log(' By Resource:');\n console.log(' • Compute: $12,450 (62%)');\n console.log(' • Storage: $4,230 (21%)');\n console.log(' • Network: $2,120 (11%)');\n console.log(' • Other: $1,200 (6%)');\n console.log(' Optimization Opportunities:');\n console.log(' • Use spot instances: Save $3,200/month');\n console.log(' • Optimize storage: Save $800/month');\n console.log(' • Schedule off-peak: Save $1,500/month');\n } else {\n console.log('Cost commands: analyze, optimize, budget');\n }\n break;\n\n default:\n console.log('Analytics commands:');\n console.log(' performance - System performance analytics');\n console.log(' business-impact - Business impact analysis');\n console.log(' cost - Cost analysis and optimization');\n console.log(' capacity - Capacity planning');\n console.log('\\nExamples:');\n console.log(' analytics performance --time-range 30d');\n console.log(' analytics cost analyze --granularity project');\n }\n break;\n\n case 'security':\n const securityCmd = subArgs[0];\n switch (securityCmd) {\n case 'status':\n printSuccess('Enterprise Security Status');\n console.log('\\n🔐 Authentication:');\n console.log(' Method: Token-based (JWT)');\n console.log(' MFA: Enabled (TOTP, SMS, Hardware Keys)');\n console.log(' Sessions: 42 active');\n console.log(' Session Timeout: 4 hours');\n\n console.log('\\n🛡️ Authorization:');\n console.log(' Model: Role-Based Access Control (RBAC)');\n console.log(' Roles: 5 defined (admin, developer, operator, auditor, viewer)');\n console.log(' Permissions: 47 granular permissions');\n console.log(' Policy Engine: Active');\n\n console.log('\\n🚦 Rate Limiting:');\n console.log(' Global Limit: 1000 req/min');\n console.log(' Per-User Limit: 100 req/min');\n console.log(' Burst Capacity: 200 requests');\n console.log(' Current Usage: 245 req/min (24.5%)');\n\n console.log('\\n⚡ Circuit Breakers:');\n console.log(' Total Breakers: 12');\n console.log(' Status: 10 closed, 1 half-open, 1 open');\n console.log(' Last Triggered: api-gateway (2 minutes ago)');\n\n console.log('\\n📝 Audit Logging:');\n console.log(' Status: Active');\n console.log(' Storage: Encrypted S3 bucket');\n console.log(' Retention: 7 years');\n console.log(' Events Today: 48,234');\n console.log(' Compliance: SOC2, GDPR, HIPAA compliant');\n break;\n\n case 'auth':\n const authAction = subArgs[1];\n\n if (authAction === 'configure') {\n printSuccess('Configuring Authentication...');\n console.log('🔐 Authentication Configuration:');\n console.log(' Method: JWT with RS256');\n console.log(' Token Expiry: 4 hours');\n console.log(' Refresh Token: 30 days');\n console.log(' MFA Required: Yes');\n console.log(' Password Policy:');\n console.log(' • Minimum length: 12 characters');\n console.log(' • Complexity: Upper, lower, numbers, symbols');\n console.log(' • History: Last 12 passwords');\n console.log(' • Expiry: 90 days');\n console.log('\\n✅ Authentication configured');\n } else if (authAction === 'sessions') {\n printSuccess('Active Sessions:');\n console.log('\\n🔑 Current Sessions:');\n console.log('┌─────────────────┬──────────┬──────────────┬─────────────┬───────────┐');\n console.log('│ User │ Role │ IP Address │ Login Time │ MFA │');\n console.log('├─────────────────┼──────────┼──────────────┼─────────────┼───────────┤');\n console.log('│ [email protected] │ admin │ 10.0.1.45 │ 2h ago │ Hardware │');\n console.log('│ [email protected] │ developer│ 10.0.2.123 │ 45m ago │ TOTP │');\n console.log('│ [email protected]│ operator │ 10.0.1.200 │ 1h ago │ SMS │');\n console.log('└─────────────────┴──────────┴──────────────┴─────────────┴───────────┘');\n } else if (authAction === 'mfa') {\n printSuccess('Multi-Factor Authentication Status:');\n console.log(' Enforcement: Required for all users');\n console.log(' Methods Available:');\n console.log(' • TOTP (Time-based One-Time Password)');\n console.log(' • SMS (Text message)');\n console.log(' • Hardware Keys (FIDO2/WebAuthn)');\n console.log(' • Backup Codes');\n console.log(' Users with MFA: 98% (147/150)');\n } else {\n console.log('Auth commands: configure, sessions, mfa, tokens');\n }\n break;\n\n case 'rbac':\n const rbacAction = subArgs[1];\n\n if (rbacAction === 'roles') {\n printSuccess('RBAC Roles:');\n console.log('\\n👥 Defined Roles:');\n console.log('\\n📛 admin (3 users)');\n console.log(' Permissions: * (all permissions)');\n console.log(' Conditions: MFA required, IP restriction');\n\n console.log('\\n📛 developer (45 users)');\n console.log(' Permissions:');\n console.log(' • projects:read,write');\n console.log(' • agents:spawn,monitor');\n console.log(' • tasks:create,monitor');\n console.log(' Conditions: Time window 06:00-22:00');\n\n console.log('\\n📛 operator (12 users)');\n console.log(' Permissions:');\n console.log(' • system:monitor');\n console.log(' • agents:list,info');\n console.log(' • tasks:list,status');\n\n console.log('\\n📛 auditor (5 users)');\n console.log(' Permissions:');\n console.log(' • audit:read');\n console.log(' • system:logs');\n console.log(' • reports:generate');\n\n console.log('\\n📛 viewer (85 users)');\n console.log(' Permissions:');\n console.log(' • *:read (read-only access)');\n } else if (rbacAction === 'assign') {\n const user = subArgs[2];\n const role = subArgs[3];\n if (user && role) {\n printSuccess(`Assigning role ${role} to user ${user}`);\n console.log('✅ Role assignment complete');\n console.log(' Effective immediately');\n console.log(' Audit log entry created');\n } else {\n printError('Usage: security rbac assign <user> <role>');\n }\n } else {\n console.log('RBAC commands: roles, permissions, assign, revoke');\n }\n break;\n\n case 'rate-limit':\n const rateLimitAction = subArgs[1];\n\n if (rateLimitAction === 'status') {\n printSuccess('Rate Limiting Status:');\n console.log('\\n📊 Current Limits:');\n console.log(' Global:');\n console.log(' • Limit: 1000 requests/minute');\n console.log(' • Current: 245 requests/minute (24.5%)');\n console.log(' • Available: 755 requests');\n console.log(' Per-User:');\n console.log(' • Default: 100 requests/minute');\n console.log(' • Premium: 500 requests/minute');\n console.log(' Per-Endpoint:');\n console.log(' • /api/agents/spawn: 10/minute');\n console.log(' • /api/tasks/create: 50/minute');\n console.log(' • /api/memory/query: 200/minute');\n\n console.log('\\n🚨 Recent Violations:');\n console.log(' • user123: 2 violations (15 min ago)');\n console.log(' • api-client-7: 1 violation (1 hour ago)');\n } else if (rateLimitAction === 'configure') {\n printSuccess('Configuring Rate Limits...');\n console.log(' Global limit: 1000 req/min');\n console.log(' Burst capacity: 200 requests');\n console.log(' Cooldown period: 60 seconds');\n console.log(' Headers: X-RateLimit-* enabled');\n console.log('\\n✅ Rate limiting configured');\n } else {\n console.log('Rate limit commands: status, configure, reset');\n }\n break;\n\n case 'circuit-breaker':\n const cbAction = subArgs[1];\n\n if (cbAction === 'status') {\n printSuccess('Circuit Breaker Status:');\n console.log('\\n⚡ Active Circuit Breakers:');\n console.log('┌──────────────────┬─────────┬──────────┬───────────┬─────────────┐');\n console.log('│ Service │ State │ Failures │ Successes │ Last Change │');\n console.log('├──────────────────┼─────────┼──────────┼───────────┼─────────────┤');\n console.log('│ api-gateway │ OPEN │ 15 │ 0 │ 2m ago │');\n console.log('│ auth-service │ CLOSED │ 0 │ 1,234 │ 1h ago │');\n console.log('│ memory-service │ CLOSED │ 1 │ 5,678 │ 3h ago │');\n console.log('│ agent-manager │ HALF │ 3 │ 45 │ 5m ago │');\n console.log('└──────────────────┴─────────┴──────────┴───────────┴─────────────┘');\n\n console.log('\\n📈 Configuration:');\n console.log(' Failure Threshold: 10 failures');\n console.log(' Success Threshold: 5 successes');\n console.log(' Timeout: 60 seconds');\n console.log(' Half-Open Requests: 3 max');\n } else if (cbAction === 'reset') {\n const service = subArgs[2];\n if (service) {\n printSuccess(`Resetting circuit breaker: ${service}`);\n console.log('✅ Circuit breaker reset to CLOSED state');\n } else {\n console.log('All circuit breakers reset');\n }\n } else {\n console.log('Circuit breaker commands: status, reset, configure');\n }\n break;\n\n case 'audit':\n const auditAction = subArgs[1];\n\n if (auditAction === 'status') {\n printSuccess('Audit Logging Status:');\n console.log(' Status: Active');\n console.log(' Storage Backend: AWS S3 (encrypted)');\n console.log(' Retention Period: 7 years');\n console.log(' Compliance: SOC2, GDPR, HIPAA');\n console.log('\\n📊 Statistics (Last 24h):');\n console.log(' Total Events: 48,234');\n console.log(' Authentication: 1,234');\n console.log(' Authorization: 15,678');\n console.log(' Data Access: 23,456');\n console.log(' Configuration Changes: 89');\n console.log(' Security Events: 12');\n } else if (auditAction === 'search') {\n const query = subArgs.slice(2).join(' ');\n printSuccess(`Searching audit logs: \"${query || 'recent'}\"`);\n console.log('\\n📋 Recent Audit Events:');\n console.log(\n '2024-01-10 14:23:45 | AUTH_SUCCESS | [email protected] | Login from 10.0.1.45',\n );\n console.log('2024-01-10 14:24:12 | PERMISSION_GRANTED | [email protected] | agents.spawn');\n console.log('2024-01-10 14:24:13 | AGENT_CREATED | [email protected] | agent-12345');\n console.log(\n '2024-01-10 14:25:01 | CONFIG_CHANGED | [email protected] | terminal.poolSize: 10->20',\n );\n console.log(\n '2024-01-10 14:26:30 | PERMISSION_DENIED | [email protected] | admin.users.delete',\n );\n } else if (auditAction === 'export') {\n printSuccess('Exporting audit logs...');\n console.log(' Time range: Last 30 days');\n console.log(' Format: JSON (encrypted)');\n console.log(' Destination: audit-export-20240110.json.enc');\n console.log('\\n✅ Export complete: 145,234 events');\n } else {\n console.log('Audit commands: status, search, export, configure');\n }\n break;\n\n case 'compliance':\n printSuccess('Compliance Status:');\n console.log('\\n🏛️ Active Compliance Frameworks:');\n console.log('\\n✅ SOC2 Type II');\n console.log(' Last Audit: 2023-10-15');\n console.log(' Next Audit: 2024-04-15');\n console.log(' Status: Compliant');\n console.log(' Controls: 89/89 passing');\n\n console.log('\\n✅ GDPR (General Data Protection Regulation)');\n console.log(' Data Protection Officer: Jane Smith');\n console.log(' Privacy Impact Assessments: 12 completed');\n console.log(' Data Subject Requests: 3 pending, 45 completed');\n console.log(' Status: Compliant');\n\n console.log('\\n✅ HIPAA (Health Insurance Portability Act)');\n console.log(' BAA Agreements: 5 active');\n console.log(' PHI Encryption: AES-256 at rest, TLS 1.3 in transit');\n console.log(' Access Controls: Implemented');\n console.log(' Status: Compliant');\n\n console.log('\\n📋 Required Actions:');\n console.log(' • Complete Q1 security training (Due: Jan 31)');\n console.log(' • Update data retention policies (Due: Feb 15)');\n break;\n\n case 'test':\n printSuccess('Running Security Test Suite...');\n console.log('\\n🧪 Security Tests:');\n console.log(' ✅ Authentication: Token validation working');\n console.log(' ✅ Authorization: RBAC policies enforced');\n console.log(' ✅ Rate Limiting: Limits properly enforced');\n console.log(' ✅ Circuit Breakers: Failing services isolated');\n console.log(' ✅ Audit Logging: All events captured');\n console.log(' ✅ Encryption: TLS 1.3 verified');\n console.log(' ✅ Session Management: Timeouts working');\n console.log(' ⚠️ MFA Bypass: 3 users without MFA');\n console.log('\\n📊 Security Score: 94/100');\n console.log(' Recommendations:');\n console.log(' • Enforce MFA for all users');\n console.log(' • Update TLS certificates (expire in 45 days)');\n console.log(' • Review inactive user accounts');\n break;\n\n default:\n console.log('Security commands:');\n console.log(' status - Show security status overview');\n console.log(' auth - Authentication management');\n console.log(' rbac - Role-based access control');\n console.log(' rate-limit - Rate limiting configuration');\n console.log(' circuit-breaker - Circuit breaker management');\n console.log(' audit - Audit log management');\n console.log(' compliance - Compliance status');\n console.log(' test - Run security tests');\n console.log('\\nExamples:');\n console.log(' security auth configure');\n console.log(' security rbac assign [email protected] developer');\n console.log(' security audit search \"failed login\"');\n console.log(' security circuit-breaker reset api-gateway');\n }\n break;\n\n case 'backup':\n const backupCmd = subArgs[0];\n switch (backupCmd) {\n case 'configure':\n printSuccess('Configuring Backup Strategy...');\n console.log('🗄️ Backup Configuration:');\n console.log(' Strategy: 3-2-1 (3 copies, 2 media, 1 offsite)');\n console.log(' Locations:');\n console.log(' • Primary: AWS S3 (us-east-1)');\n console.log(' • Secondary: Azure Blob (eastus)');\n console.log(' • Tertiary: Local NAS');\n console.log(' Schedule:');\n console.log(' • Full: Weekly (Sunday 2 AM)');\n console.log(' • Incremental: Every 6 hours');\n console.log(' • Differential: Daily (2 AM)');\n console.log(' Encryption: AES-256');\n console.log(' Compression: LZ4');\n console.log(' Verification: Automatic');\n console.log('\\n✅ Backup strategy configured');\n break;\n\n case 'dr':\n const drAction = subArgs[1];\n if (drAction === 'configure') {\n printSuccess('Configuring Disaster Recovery...');\n console.log('🚨 DR Configuration:');\n console.log(' RPO (Recovery Point Objective): 1 hour');\n console.log(' RTO (Recovery Time Objective): 15 minutes');\n console.log(' Replication: Real-time to secondary region');\n console.log(' Failover: Automatic with manual override');\n console.log(' Testing: Monthly DR drills');\n console.log('\\n✅ Disaster recovery configured');\n } else if (drAction === 'test') {\n printSuccess('Running DR Test...');\n console.log('🧪 DR Test Progress:');\n console.log(' ✓ Initiating failover simulation');\n console.log(' ✓ Switching to DR site');\n console.log(' ✓ Verifying data integrity');\n console.log(' ✓ Testing application functionality');\n console.log(' ✓ Measuring RTO: 12 minutes');\n console.log(' ✓ Failing back to primary');\n console.log('\\n✅ DR test completed successfully');\n } else {\n console.log('DR commands: configure, test, status');\n }\n break;\n\n case 'restore':\n const restorePoint = subArgs[1];\n if (!restorePoint) {\n printError('Usage: backup restore <backup-id|timestamp>');\n break;\n }\n\n printSuccess(`Restoring from backup: ${restorePoint}`);\n console.log('🔄 Restore Progress:');\n console.log(' ✓ Located backup in S3');\n console.log(' ✓ Verifying backup integrity');\n console.log(' ✓ Downloading backup data');\n console.log(' ✓ Decrypting backup');\n console.log(' ✓ Restoring application data');\n console.log(' ✓ Restoring configuration');\n console.log(' ✓ Verifying restored data');\n console.log('\\n✅ Restore completed successfully');\n break;\n\n default:\n console.log('Backup commands:');\n console.log(' configure - Configure backup strategy');\n console.log(' dr - Disaster recovery management');\n console.log(' restore - Restore from backup');\n console.log(' list - List available backups');\n console.log('\\nExamples:');\n console.log(' backup configure --strategy 3-2-1');\n console.log(' backup dr test');\n console.log(' backup restore \"backup-20240110-023000\"');\n }\n break;\n\n default:\n printError(`Unknown command: ${command}`);\n console.log('Run \"claude-flow help\" for available commands');\n\n // Suggest similar commands\n const commonCommands = [\n 'agent',\n 'task',\n 'spawn',\n 'init',\n 'start',\n 'status',\n 'memory',\n 'sparc',\n 'help',\n ];\n const suggestions = commonCommands.filter(\n (cmd) => cmd.startsWith(command.toLowerCase()) || cmd.includes(command.toLowerCase()),\n );\n\n if (suggestions.length > 0) {\n console.log('\\nDid you mean:');\n suggestions.forEach((cmd) => console.log(` claude-flow ${cmd}`));\n }\n\n process.exit(1);\n }\n}\n\n// REPL Implementation\nasync function startRepl() {\n console.log('🧠 Claude-Flow Interactive Shell v' + VERSION);\n console.log('Type \"help\" for available commands, \"exit\" to quit\\n');\n\n const replState = {\n history: [] as string[],\n historyIndex: -1,\n currentSession: null,\n context: {\n agents: [] as any[],\n tasks: [] as any[],\n terminals: [] as any[],\n memory: {} as Record<string, any>,\n },\n };\n\n // REPL command handlers\n const replCommands = {\n help: () => {\n console.log(`\n📚 Available REPL Commands:\n \nSystem:\n status - Show system status\n config [key] - Show configuration (or specific key)\n clear - Clear the screen\n history - Show command history\n exit/quit - Exit REPL mode\n\nAgents:\n agent spawn <type> [name] - Spawn new agent\n agent list - List active agents\n agent info <id> - Show agent details\n agent terminate <id> - Terminate agent\n\nTasks:\n task create <type> <desc> - Create new task\n task list - List active tasks\n task assign <task> <agent> - Assign task to agent\n task status <id> - Show task status\n\nMemory:\n memory store <key> <value> - Store data in memory\n memory get <key> - Retrieve data from memory\n memory list - List all memory keys\n memory clear - Clear all memory\n\nTerminal:\n terminal create [name] - Create terminal session\n terminal list - List terminals\n terminal exec <cmd> - Execute command\n terminal attach <id> - Attach to terminal\n\nShortcuts:\n !<command> - Execute shell command\n /<search> - Search command history\n ↑/↓ - Navigate command history\n`);\n },\n\n status: () => {\n console.log('🟢 Claude-Flow Status:');\n console.log(` Agents: ${replState.context.agents.length} active`);\n console.log(` Tasks: ${replState.context.tasks.length} in queue`);\n console.log(` Terminals: ${replState.context.terminals.length} active`);\n console.log(` Memory Keys: ${Object.keys(replState.context.memory).length}`);\n },\n\n clear: () => {\n console.clear();\n console.log('🧠 Claude-Flow Interactive Shell v' + VERSION);\n },\n\n history: () => {\n console.log('📜 Command History:');\n replState.history.forEach((cmd, i) => {\n console.log(` ${i + 1}: ${cmd}`);\n });\n },\n\n config: async (key: string) => {\n try {\n const config = JSON.parse(await fs.readFile('claude-flow.config.json', 'utf-8'));\n if (key) {\n const keys = key.split('.');\n let value = config;\n for (const k of keys) {\n value = value[k];\n }\n console.log(`${key}: ${JSON.stringify(value, null, 2)}`);\n } else {\n console.log(JSON.stringify(config, null, 2));\n }\n } catch {\n console.log('No configuration file found. Using defaults.');\n }\n },\n };\n\n // Process REPL commands\n async function processReplCommand(input: string) {\n const trimmed = input.trim();\n if (!trimmed) return true;\n\n // Add to history\n replState.history.push(trimmed);\n replState.historyIndex = replState.history.length;\n\n // Handle special commands\n if (trimmed === 'exit' || trimmed === 'quit') {\n console.log('👋 Exiting Claude-Flow REPL...');\n return false;\n }\n\n // Handle shell commands\n if (trimmed.startsWith('!')) {\n const shellCmd = trimmed.substring(1);\n try {\n const command = new Deno.Command('sh', {\n args: ['-c', shellCmd],\n stdout: 'piped',\n stderr: 'piped',\n });\n const { stdout, stderr } = await command.output();\n if (stdout.length > 0) {\n console.log(new TextDecoder().decode(stdout));\n }\n if (stderr.length > 0) {\n console.error(new TextDecoder().decode(stderr));\n }\n } catch (err: unknown) {\n console.error(`Shell error: ${(err as Error).message}`);\n }\n return true;\n }\n\n // Handle search\n if (trimmed.startsWith('/')) {\n const search = trimmed.substring(1);\n const matches = replState.history.filter((cmd) => cmd.includes(search));\n if (matches.length > 0) {\n console.log('🔍 Search results:');\n matches.forEach((cmd) => console.log(` ${cmd}`));\n } else {\n console.log('No matches found');\n }\n return true;\n }\n\n // Parse command and arguments\n const parts = trimmed.split(' ');\n const command = parts[0];\n const args = parts.slice(1);\n\n // Handle built-in REPL commands\n if (command in replCommands) {\n await (replCommands as any)[command](...args);\n return true;\n }\n\n // Handle multi-word commands\n if (command === 'agent') {\n await handleAgentCommand(args, replState);\n } else if (command === 'task') {\n await handleTaskCommand(args, replState);\n } else if (command === 'memory') {\n await handleMemoryCommand(args, replState);\n } else if (command === 'terminal') {\n await handleTerminalCommand(args, replState);\n } else {\n console.log(`Unknown command: ${command}. Type \"help\" for available commands.`);\n }\n\n return true;\n }\n\n // Agent command handler\n async function handleAgentCommand(args: string[], state: any) {\n const subCmd = args[0];\n switch (subCmd) {\n case 'spawn':\n const type = args[1] || 'researcher';\n const name = args[2] || `agent-${Date.now()}`;\n const agent = {\n id: `agent-${Date.now()}`,\n type,\n name,\n status: 'active',\n created: new Date().toISOString(),\n };\n state.context.agents.push(agent);\n printSuccess(`Spawned ${type} agent: ${name} (${agent.id})`);\n break;\n\n case 'list':\n if (state.context.agents.length === 0) {\n console.log('No active agents');\n } else {\n console.log('Active agents:');\n state.context.agents.forEach((agent: any) => {\n console.log(` ${agent.id} - ${agent.name} (${agent.type}) - ${agent.status}`);\n });\n }\n break;\n\n case 'info':\n const agentId = args[1];\n const foundAgent = state.context.agents.find(\n (a: any) => a.id === agentId || a.name === agentId,\n );\n if (foundAgent) {\n console.log(`Agent: ${foundAgent.name}`);\n console.log(` ID: ${foundAgent.id}`);\n console.log(` Type: ${foundAgent.type}`);\n console.log(` Status: ${foundAgent.status}`);\n console.log(` Created: ${foundAgent.created}`);\n } else {\n printError(`Agent not found: ${agentId}`);\n }\n break;\n\n case 'terminate':\n const termId = args[1];\n const index = state.context.agents.findIndex(\n (a: any) => a.id === termId || a.name === termId,\n );\n if (index >= 0) {\n const removed = state.context.agents.splice(index, 1)[0];\n printSuccess(`Terminated agent: ${removed.name}`);\n } else {\n printError(`Agent not found: ${termId}`);\n }\n break;\n\n default:\n console.log('Agent commands: spawn, list, info, terminate');\n }\n }\n\n // Task command handler\n async function handleTaskCommand(args: string[], state: any) {\n const subCmd = args[0];\n switch (subCmd) {\n case 'create':\n const type = args[1] || 'general';\n const description = args.slice(2).join(' ') || 'No description';\n const task = {\n id: `task-${Date.now()}`,\n type,\n description,\n status: 'pending',\n created: new Date().toISOString(),\n };\n state.context.tasks.push(task);\n printSuccess(`Created task: ${task.id}`);\n console.log(` Type: ${type}`);\n console.log(` Description: ${description}`);\n break;\n\n case 'list':\n if (state.context.tasks.length === 0) {\n console.log('No active tasks');\n } else {\n console.log('Active tasks:');\n state.context.tasks.forEach((task: any) => {\n console.log(` ${task.id} - ${task.type} - ${task.status}`);\n console.log(` ${task.description}`);\n });\n }\n break;\n\n case 'assign':\n const taskId = args[1];\n const assignAgentId = args[2];\n const foundTask = state.context.tasks.find((t: any) => t.id === taskId);\n const assignAgent = state.context.agents.find(\n (a: any) => a.id === assignAgentId || a.name === assignAgentId,\n );\n\n if (foundTask && assignAgent) {\n foundTask.assignedTo = assignAgent.id;\n foundTask.status = 'assigned';\n printSuccess(`Assigned task ${taskId} to agent ${assignAgent.name}`);\n } else {\n printError('Task or agent not found');\n }\n break;\n\n case 'status':\n const statusId = args[1];\n const statusTask = state.context.tasks.find((t: any) => t.id === statusId);\n if (statusTask) {\n console.log(`Task: ${statusTask.id}`);\n console.log(` Type: ${statusTask.type}`);\n console.log(` Status: ${statusTask.status}`);\n console.log(` Description: ${statusTask.description}`);\n if (statusTask.assignedTo) {\n console.log(` Assigned to: ${statusTask.assignedTo}`);\n }\n console.log(` Created: ${statusTask.created}`);\n } else {\n printError(`Task not found: ${statusId}`);\n }\n break;\n\n default:\n console.log('Task commands: create, list, assign, status');\n }\n }\n\n // Memory command handler\n async function handleMemoryCommand(args: string[], state: any) {\n const subCmd = args[0];\n switch (subCmd) {\n case 'store':\n const key = args[1];\n const value = args.slice(2).join(' ');\n if (key && value) {\n state.context.memory[key] = value;\n printSuccess(`Stored: ${key} = ${value}`);\n } else {\n printError('Usage: memory store <key> <value>');\n }\n break;\n\n case 'get':\n const getKey = args[1];\n if (getKey && state.context.memory[getKey]) {\n console.log(`${getKey}: ${state.context.memory[getKey]}`);\n } else {\n console.log(`Key not found: ${getKey}`);\n }\n break;\n\n case 'list':\n const keys = Object.keys(state.context.memory);\n if (keys.length === 0) {\n console.log('No data in memory');\n } else {\n console.log('Memory keys:');\n keys.forEach((key) => {\n console.log(` ${key}: ${state.context.memory[key]}`);\n });\n }\n break;\n\n case 'clear':\n state.context.memory = {};\n printSuccess('Memory cleared');\n break;\n\n default:\n console.log('Memory commands: store, get, list, clear');\n }\n }\n\n // Terminal command handler\n async function handleTerminalCommand(args: string[], state: any) {\n const subCmd = args[0];\n switch (subCmd) {\n case 'create':\n const name = args[1] || `term-${Date.now()}`;\n const terminal = {\n id: name,\n status: 'active',\n created: new Date().toISOString(),\n };\n state.context.terminals.push(terminal);\n printSuccess(`Created terminal: ${name}`);\n break;\n\n case 'list':\n if (state.context.terminals.length === 0) {\n console.log('No active terminals');\n } else {\n console.log('Active terminals:');\n state.context.terminals.forEach((term: any) => {\n console.log(` ${term.id} - ${term.status}`);\n });\n }\n break;\n\n case 'exec':\n const cmd = args.slice(1).join(' ');\n if (cmd) {\n console.log(`Executing: ${cmd}`);\n console.log('(Command execution simulated in REPL)');\n } else {\n printError('Usage: terminal exec <command>');\n }\n break;\n\n case 'attach':\n const attachId = args[1];\n if (attachId) {\n state.currentSession = attachId;\n console.log(`Attached to terminal: ${attachId}`);\n console.log('(Type \"terminal detach\" to detach)');\n } else {\n printError('Usage: terminal attach <id>');\n }\n break;\n\n case 'detach':\n if (state.currentSession) {\n console.log(`Detached from terminal: ${state.currentSession}`);\n state.currentSession = null;\n } else {\n console.log('Not attached to any terminal');\n }\n break;\n\n default:\n console.log('Terminal commands: create, list, exec, attach, detach');\n }\n }\n\n // Main REPL loop\n const decoder = new TextDecoder();\n const encoder = new TextEncoder();\n\n while (true) {\n // Show prompt\n const prompt = replState.currentSession\n ? `claude-flow:${replState.currentSession}> `\n : 'claude-flow> ';\n await Deno.stdout.write(encoder.encode(prompt));\n\n // Read input\n const buf = new Uint8Array(1024);\n const n = await Deno.stdin.read(buf);\n if (n === null) break;\n\n const input = decoder.decode(buf.subarray(0, n)).trim();\n\n // Process command\n const shouldContinue = await processReplCommand(input);\n if (!shouldContinue) break;\n }\n}\n\n// Helper functions for init command\nfunction createMinimalClaudeMd() {\n return `# Claude Code Integration\n\nThis file provides guidance to Claude when working with this codebase.\n\n## Project Overview\n[Describe your project here]\n\n## Key Conventions\n- Code style guidelines\n- Naming conventions\n- Architecture patterns\n\n## Important Notes\n- Special considerations\n- Areas to be careful with\n`;\n}\n\nfunction createFullClaudeMd() {\n return `# Claude Code Integration Guide\n\nThis document provides comprehensive guidance to Claude when working with this codebase.\n\n## Project Overview\n[Provide a detailed description of your project, its purpose, and main features]\n\n## Architecture\n[Describe the overall architecture, main components, and how they interact]\n\n## Code Conventions\n- **Naming**: [Describe naming conventions for files, functions, variables, etc.]\n- **Style**: [Code formatting preferences, linting rules]\n- **Patterns**: [Design patterns used in the project]\n- **Testing**: [Testing approach and requirements]\n\n## Directory Structure\n\\`\\`\\`\nproject/\n├── src/ # Source code\n├── tests/ # Test files\n├── docs/ # Documentation\n└── ... # Other directories\n\\`\\`\\`\n\n## Development Workflow\n1. [Step-by-step development process]\n2. [How to run tests]\n3. [How to build/deploy]\n\n## Important Considerations\n- [Security considerations]\n- [Performance requirements]\n- [Compatibility requirements]\n\n## Common Tasks\n- **Add a new feature**: [Instructions]\n- **Fix a bug**: [Process]\n- **Update documentation**: [Guidelines]\n\n## Dependencies\n[List key dependencies and their purposes]\n\n## Troubleshooting\n[Common issues and solutions]\n`;\n}\n\nfunction createMinimalMemoryBankMd() {\n return `# Memory Bank\n\nSession memory and context storage.\n\n## Current Session\n- Started: ${new Date().toISOString()}\n- Context: [Current work context]\n\n## Key Information\n- [Important facts to remember]\n\n## Progress Log\n- [Track progress here]\n`;\n}\n\nfunction createFullMemoryBankMd() {\n return `# Memory Bank\n\nThis file serves as persistent memory storage for Claude across sessions.\n\n## Session Information\n- **Current Session**: Started ${new Date().toISOString()}\n- **Project Phase**: [Development/Testing/Production]\n- **Active Tasks**: [List current tasks]\n\n## Project Context\n### Technical Stack\n- Languages: [List languages used]\n- Frameworks: [List frameworks]\n- Tools: [Development tools]\n\n### Architecture Decisions\n- [Record key architectural decisions]\n- [Rationale for technology choices]\n\n## Important Information\n### API Keys and Secrets\n- [Never store actual secrets here, just references]\n\n### External Services\n- [List integrated services]\n- [Configuration requirements]\n\n### Database Schema\n- [Current schema version]\n- [Recent migrations]\n\n## Progress Tracking\n### Completed Tasks\n- [x] [Completed task 1]\n- [x] [Completed task 2]\n\n### In Progress\n- [ ] [Current task 1]\n- [ ] [Current task 2]\n\n### Upcoming\n- [ ] [Future task 1]\n- [ ] [Future task 2]\n\n## Code Patterns\n### Established Patterns\n\\`\\`\\`javascript\n// Example pattern\n\\`\\`\\`\n\n### Anti-patterns to Avoid\n- [List anti-patterns]\n\n## Meeting Notes\n### [Date]\n- Participants: [Names]\n- Decisions: [Key decisions]\n- Action items: [Tasks assigned]\n\n## Debugging History\n### Issue: [Issue name]\n- **Date**: [Date]\n- **Symptoms**: [What was observed]\n- **Root Cause**: [What caused it]\n- **Solution**: [How it was fixed]\n\n## Performance Metrics\n- [Baseline metrics]\n- [Optimization goals]\n\n## Documentation Links\n- [API Documentation]: [URL]\n- [Design Documents]: [URL]\n- [Issue Tracker]: [URL]\n`;\n}\n\nfunction createMinimalCoordinationMd() {\n return `# Coordination\n\nTask and workflow coordination.\n\n## Active Tasks\n1. [Current task]\n\n## Workflow\n- [ ] Step 1\n- [ ] Step 2\n\n## Resources\n- [Available resources]\n`;\n}\n\nfunction createFullCoordinationMd() {\n return `# Coordination Center\n\nCentral coordination for multi-agent collaboration and task management.\n\n## Active Agents\n| Agent ID | Type | Status | Assigned Tasks | Last Active |\n|----------|------|--------|----------------|-------------|\n| [ID] | [Type] | [Status] | [Tasks] | [Timestamp] |\n\n## Task Queue\n### High Priority\n1. **[Task Name]**\n - Description: [What needs to be done]\n - Assigned to: [Agent ID]\n - Dependencies: [Other tasks]\n - Deadline: [Date/Time]\n\n### Medium Priority\n1. [Task details]\n\n### Low Priority\n1. [Task details]\n\n## Workflow Definitions\n### [Workflow Name]\n\\`\\`\\`yaml\nname: [Workflow Name]\ndescription: [What this workflow does]\nsteps:\n - name: [Step 1]\n agent: [Agent type]\n action: [What to do]\n - name: [Step 2]\n agent: [Agent type]\n action: [What to do]\n depends_on: [Step 1]\n\\`\\`\\`\n\n## Resource Allocation\n### Computational Resources\n- CPU: [Usage/Limits]\n- Memory: [Usage/Limits]\n- Storage: [Usage/Limits]\n\n### External Resources\n- API Rate Limits: [Service: limit]\n- Database Connections: [Current/Max]\n\n## Communication Channels\n### Inter-Agent Messages\n- [Agent A → Agent B]: [Message type]\n\n### External Communications\n- Webhooks: [Configured webhooks]\n- Notifications: [Notification settings]\n\n## Synchronization Points\n- [Sync Point 1]: [Description]\n- [Sync Point 2]: [Description]\n\n## Conflict Resolution\n### Strategy\n- [How conflicts are resolved]\n\n### Recent Conflicts\n- [Date]: [Conflict description] → [Resolution]\n\n## Performance Metrics\n### Task Completion\n- Average time: [Time]\n- Success rate: [Percentage]\n\n### Agent Efficiency\n- [Agent Type]: [Metrics]\n\n## Scheduled Maintenance\n- [Date/Time]: [What will be done]\n\n## Emergency Procedures\n### System Overload\n1. [Step 1]\n2. [Step 2]\n\n### Agent Failure\n1. [Recovery procedure]\n`;\n}\n\nfunction createAgentsReadme() {\n return `# Agents Directory\n\nThis directory stores agent-specific memory and state information.\n\n## Structure\nEach agent gets its own subdirectory named by agent ID:\n- \\`agent-001/\\`: First agent's memory\n- \\`agent-002/\\`: Second agent's memory\n- etc.\n\n## Files per Agent\n- \\`profile.json\\`: Agent configuration and capabilities\n- \\`memory.md\\`: Agent's working memory\n- \\`tasks.json\\`: Assigned tasks and their status\n- \\`metrics.json\\`: Performance metrics\n\n## Usage\nFiles in this directory are automatically managed by the Claude-Flow system.\n`;\n}\n\nfunction createSessionsReadme() {\n return `# Sessions Directory\n\nThis directory stores session-specific information and terminal states.\n\n## Structure\nEach session gets a unique directory:\n- \\`session-[timestamp]/\\`: Session data\n - \\`metadata.json\\`: Session metadata\n - \\`terminal.log\\`: Terminal output\n - \\`commands.history\\`: Command history\n - \\`state.json\\`: Session state snapshot\n\n## Retention Policy\nSessions are retained for 30 days by default, then archived or deleted based on configuration.\n\n## Usage\nThe Claude-Flow system automatically manages session files. Do not modify these files manually.\n`;\n}\n\n// Helper function to create SPARC structure manually\nasync function createSparcStructureManually() {\n try {\n // Create .roo directory structure\n const rooDirectories = [\n '.roo',\n '.roo/templates',\n '.roo/workflows',\n '.roo/modes',\n '.roo/configs',\n ];\n\n for (const dir of rooDirectories) {\n try {\n await Deno.mkdir(dir, { recursive: true });\n console.log(` ✓ Created ${dir}/`);\n } catch (err) {\n if (!(err instanceof Deno.errors.AlreadyExists)) {\n throw err;\n }\n }\n }\n\n // Create .roomodes file (copy from existing if available, or create basic version)\n let roomodesContent;\n try {\n // Check if .roomodes already exists and read it\n roomodesContent = await fs.readFile('.roomodes');\n console.log(' ✓ Using existing .roomodes configuration');\n } catch {\n // Create basic .roomodes configuration\n roomodesContent = createBasicRoomodesConfig();\n await fs.writeFile('.roomodes', roomodesContent);\n console.log(' ✓ Created .roomodes configuration');\n }\n\n // Create basic workflow templates\n const basicWorkflow = createBasicSparcWorkflow();\n await fs.writeFile('.roo/workflows/basic-tdd.json', basicWorkflow);\n console.log(' ✓ Created .roo/workflows/basic-tdd.json');\n\n // Create README for .roo directory\n const rooReadme = createRooReadme();\n await fs.writeFile('.roo/README.md', rooReadme);\n console.log(' ✓ Created .roo/README.md');\n\n console.log(' ✅ Basic SPARC structure created successfully');\n } catch (err: unknown) {\n console.log(` ❌ Failed to create SPARC structure: ${(err as Error).message}`);\n }\n}\n\nfunction createBasicRoomodesConfig() {\n return JSON.stringify(\n {\n customModes: [\n {\n slug: 'architect',\n name: '🏗️ Architect',\n roleDefinition:\n 'You design scalable, secure, and modular architectures based on functional specs and user needs. You define responsibilities across services, APIs, and components.',\n customInstructions:\n 'Create architecture mermaid diagrams, data flows, and integration points. Ensure no part of the design includes secrets or hardcoded env values. Emphasize modular boundaries and maintain extensibility.',\n groups: ['read', 'edit'],\n source: 'project',\n },\n {\n slug: 'code',\n name: '🧠 Auto-Coder',\n roleDefinition:\n 'You write clean, efficient, modular code based on pseudocode and architecture. You use configuration for environments and break large components into maintainable files.',\n customInstructions:\n 'Write modular code using clean architecture principles. Never hardcode secrets or environment values. Split code into files < 500 lines. Use config files or environment abstractions. Use \\\\`new_task\\\\` for subtasks and finish with \\\\`attempt_completion\\\\`.',\n groups: ['read', 'edit', 'browser', 'mcp', 'command'],\n source: 'project',\n },\n {\n slug: 'tdd',\n name: '🧪 Tester (TDD)',\n roleDefinition:\n 'You implement Test-Driven Development (TDD, London School), writing tests first and refactoring after minimal implementation passes.',\n customInstructions:\n 'Write failing tests first. Implement only enough code to pass. Refactor after green. Ensure tests do not hardcode secrets. Keep files < 500 lines.',\n groups: ['read', 'edit', 'browser', 'mcp', 'command'],\n source: 'project',\n },\n {\n slug: 'spec-pseudocode',\n name: '📋 Specification Writer',\n roleDefinition:\n 'You capture full project context—functional requirements, edge cases, constraints—and translate that into modular pseudocode with TDD anchors.',\n customInstructions:\n 'Write pseudocode as a series of md files with phase_number_name.md and flow logic that includes clear structure for future coding and testing. Split complex logic across modules.',\n groups: ['read', 'edit'],\n source: 'project',\n },\n {\n slug: 'integration',\n name: '🔗 System Integrator',\n roleDefinition:\n 'You merge the outputs of all modes into a working, tested, production-ready system. You ensure consistency, cohesion, and modularity.',\n customInstructions:\n 'Verify interface compatibility, shared modules, and env config standards. Split integration logic across domains as needed. Use \\\\`new_task\\\\` for preflight testing.',\n groups: ['read', 'edit', 'browser', 'mcp', 'command'],\n source: 'project',\n },\n {\n slug: 'debug',\n name: '🪲 Debugger',\n roleDefinition:\n 'You troubleshoot runtime bugs, logic errors, or integration failures by tracing, inspecting, and analyzing behavior.',\n customInstructions:\n 'Use logs, traces, and stack analysis to isolate bugs. Avoid changing env configuration directly. Keep fixes modular.',\n groups: ['read', 'edit', 'browser', 'mcp', 'command'],\n source: 'project',\n },\n ],\n },\n null,\n 2,\n );\n}\n\nfunction createBasicSparcWorkflow() {\n return JSON.stringify(\n {\n name: 'Basic TDD Workflow',\n description: 'A simple SPARC-based TDD workflow for development',\n sequential: true,\n steps: [\n {\n mode: 'spec-pseudocode',\n description: 'Create detailed specifications and pseudocode',\n phase: 'specification',\n },\n {\n mode: 'tdd',\n description: 'Write failing tests (Red phase)',\n phase: 'red',\n },\n {\n mode: 'code',\n description: 'Implement minimal code to pass tests (Green phase)',\n phase: 'green',\n },\n {\n mode: 'tdd',\n description: 'Refactor and optimize (Refactor phase)',\n phase: 'refactor',\n },\n {\n mode: 'integration',\n description: 'Integrate and verify complete solution',\n phase: 'integration',\n },\n ],\n },\n null,\n 2,\n );\n}\n\nfunction createRooReadme() {\n return `# .roo Directory - SPARC Development Environment\n\nThis directory contains the SPARC (Specification, Pseudocode, Architecture, Refinement, Completion) development environment configuration and templates.\n\n## Directory Structure\n\n\\`\\`\\`\n.roo/\n├── README.md # This file\n├── templates/ # Template files for common patterns\n├── workflows/ # Predefined SPARC workflows\n│ └── basic-tdd.json # Basic TDD workflow\n├── modes/ # Custom mode definitions (optional)\n└── configs/ # Configuration files\n\\`\\`\\`\n\n## SPARC Methodology\n\nSPARC is a systematic approach to software development:\n\n1. **Specification**: Define clear requirements and constraints\n2. **Pseudocode**: Create detailed logic flows and algorithms \n3. **Architecture**: Design system structure and components\n4. **Refinement**: Implement, test, and optimize using TDD\n5. **Completion**: Integrate, document, and validate\n\n## Usage with Claude-Flow\n\nUse the claude-flow SPARC commands to leverage this environment:\n\n\\`\\`\\`bash\n# List available modes\nclaude-flow sparc modes\n\n# Run specific mode\nclaude-flow sparc run code \"implement user authentication\"\n\n# Execute full TDD workflow \nclaude-flow sparc tdd \"payment processing system\"\n\n# Use custom workflow\nclaude-flow sparc workflow .roo/workflows/basic-tdd.json\n\\`\\`\\`\n\n## Configuration\n\nThe main configuration is in \\`.roomodes\\` at the project root. This directory provides additional templates and workflows to support the SPARC development process.\n\n## Customization\n\nYou can customize this environment by:\n- Adding new workflow templates to \\`workflows/\\`\n- Creating mode-specific templates in \\`templates/\\`\n- Adding project-specific configurations in \\`configs/\\`\n\nFor more information, see: https://github.com/ruvnet/claude-code-flow/docs/sparc.md\n`;\n}\n\nfunction createSparcClaudeMd() {\n return `# Claude Code Configuration - SPARC Development Environment\n\n## Project Overview\nThis project uses the SPARC (Specification, Pseudocode, Architecture, Refinement, Completion) methodology for systematic Test-Driven Development with AI assistance through Claude-Flow orchestration.\n\n## SPARC Development Commands\n\n### Core SPARC Commands\n- \\`npx claude-flow sparc modes\\`: List all available SPARC development modes\n- \\`npx claude-flow sparc run <mode> \"<task>\"\\`: Execute specific SPARC mode for a task\n- \\`npx claude-flow sparc tdd \"<feature>\"\\`: Run complete TDD workflow using SPARC methodology\n- \\`npx claude-flow sparc info <mode>\\`: Get detailed information about a specific mode\n\n### Standard Build Commands\n- \\`npm run build\\`: Build the project\n- \\`npm run test\\`: Run the test suite\n- \\`npm run lint\\`: Run linter and format checks\n- \\`npm run typecheck\\`: Run TypeScript type checking\n\n## SPARC Methodology Workflow\n\n### 1. Specification Phase\n\\`\\`\\`bash\n# Create detailed specifications and requirements\nnpx claude-flow sparc run spec-pseudocode \"Define user authentication requirements\"\n\\`\\`\\`\n- Define clear functional requirements\n- Document edge cases and constraints\n- Create user stories and acceptance criteria\n- Establish non-functional requirements\n\n### 2. Pseudocode Phase\n\\`\\`\\`bash\n# Develop algorithmic logic and data flows\nnpx claude-flow sparc run spec-pseudocode \"Create authentication flow pseudocode\"\n\\`\\`\\`\n- Break down complex logic into steps\n- Define data structures and interfaces\n- Plan error handling and edge cases\n- Create modular, testable components\n\n### 3. Architecture Phase\n\\`\\`\\`bash\n# Design system architecture and component structure\nnpx claude-flow sparc run architect \"Design authentication service architecture\"\n\\`\\`\\`\n- Create system diagrams and component relationships\n- Define API contracts and interfaces\n- Plan database schemas and data flows\n- Establish security and scalability patterns\n\n### 4. Refinement Phase (TDD Implementation)\n\\`\\`\\`bash\n# Execute Test-Driven Development cycle\nnpx claude-flow sparc tdd \"implement user authentication system\"\n\\`\\`\\`\n\n**TDD Cycle:**\n1. **Red**: Write failing tests first\n2. **Green**: Implement minimal code to pass tests\n3. **Refactor**: Optimize and clean up code\n4. **Repeat**: Continue until feature is complete\n\n### 5. Completion Phase\n\\`\\`\\`bash\n# Integration, documentation, and validation\nnpx claude-flow sparc run integration \"integrate authentication with user management\"\n\\`\\`\\`\n- Integrate all components\n- Perform end-to-end testing\n- Create comprehensive documentation\n- Validate against original requirements\n\n## SPARC Mode Reference\n\n### Development Modes\n- **\\`architect\\`**: System design and architecture planning\n- **\\`code\\`**: Clean, modular code implementation\n- **\\`tdd\\`**: Test-driven development and testing\n- **\\`spec-pseudocode\\`**: Requirements and algorithmic planning\n- **\\`integration\\`**: System integration and coordination\n\n### Quality Assurance Modes\n- **\\`debug\\`**: Troubleshooting and bug resolution\n- **\\`security-review\\`**: Security analysis and vulnerability assessment\n- **\\`refinement-optimization-mode\\`**: Performance optimization and refactoring\n\n### Support Modes\n- **\\`docs-writer\\`**: Documentation creation and maintenance\n- **\\`devops\\`**: Deployment and infrastructure management\n- **\\`mcp\\`**: External service integration\n\n## Code Style and Best Practices\n\n### SPARC Development Principles\n- **Modular Design**: Keep files under 500 lines, break into logical components\n- **Environment Safety**: Never hardcode secrets or environment-specific values\n- **Test-First**: Always write tests before implementation (Red-Green-Refactor)\n- **Clean Architecture**: Separate concerns, use dependency injection\n- **Documentation**: Maintain clear, up-to-date documentation\n\n### Coding Standards\n- Use TypeScript for type safety and better tooling\n- Follow consistent naming conventions (camelCase for variables, PascalCase for classes)\n- Implement proper error handling and logging\n- Use async/await for asynchronous operations\n- Prefer composition over inheritance\n\n### Memory and State Management\n- Use claude-flow memory system for persistent state across sessions\n- Store progress and findings using namespaced keys\n- Query previous work before starting new tasks\n- Export/import memory for backup and sharing\n\n## SPARC Memory Integration\n\n### Memory Commands for SPARC Development\n\\`\\`\\`bash\n# Store project specifications\nnpx claude-flow memory store spec_auth \"User authentication requirements and constraints\"\n\n# Store architectural decisions\nnpx claude-flow memory store arch_decisions \"Database schema and API design choices\"\n\n# Store test results and coverage\nnpx claude-flow memory store test_coverage \"Authentication module: 95% coverage, all tests passing\"\n\n# Query previous work\nnpx claude-flow memory query auth_implementation\n\n# Export project memory\nnpx claude-flow memory export project_backup.json\n\\`\\`\\`\n\n### Memory Namespaces\n- **\\`spec\\`**: Requirements and specifications\n- **\\`arch\\`**: Architecture and design decisions\n- **\\`impl\\`**: Implementation notes and code patterns\n- **\\`test\\`**: Test results and coverage reports\n- **\\`debug\\`**: Bug reports and resolution notes\n\n## Workflow Examples\n\n### Feature Development Workflow\n\\`\\`\\`bash\n# 1. Start with specification\nnpx claude-flow sparc run spec-pseudocode \"User profile management feature\"\n\n# 2. Design architecture\nnpx claude-flow sparc run architect \"Profile service architecture with data validation\"\n\n# 3. Implement with TDD\nnpx claude-flow sparc tdd \"user profile CRUD operations\"\n\n# 4. Security review\nnpx claude-flow sparc run security-review \"profile data access and validation\"\n\n# 5. Integration testing\nnpx claude-flow sparc run integration \"profile service with authentication system\"\n\n# 6. Documentation\nnpx claude-flow sparc run docs-writer \"profile service API documentation\"\n\\`\\`\\`\n\n### Bug Fix Workflow\n\\`\\`\\`bash\n# 1. Debug and analyze\nnpx claude-flow sparc run debug \"authentication token expiration issue\"\n\n# 2. Write regression tests\nnpx claude-flow sparc run tdd \"token refresh mechanism tests\"\n\n# 3. Implement fix\nnpx claude-flow sparc run code \"fix token refresh in authentication service\"\n\n# 4. Security review\nnpx claude-flow sparc run security-review \"token handling security implications\"\n\\`\\`\\`\n\n## Configuration Files\n\n### SPARC Configuration\n- **\\`.roomodes\\`**: SPARC mode definitions and configurations\n- **\\`.roo/\\`**: Templates, workflows, and mode-specific rules\n\n### Claude-Flow Configuration\n- **\\`memory/\\`**: Persistent memory and session data\n- **\\`coordination/\\`**: Multi-agent coordination settings\n\n## Git Workflow Integration\n\n### Commit Strategy with SPARC\n- **Specification commits**: After completing requirements analysis\n- **Architecture commits**: After design phase completion\n- **TDD commits**: After each Red-Green-Refactor cycle\n- **Integration commits**: After successful component integration\n- **Documentation commits**: After completing documentation updates\n\n### Branch Strategy\n- **\\`feature/sparc-<feature-name>\\`**: Feature development with SPARC methodology\n- **\\`hotfix/sparc-<issue>\\`**: Bug fixes using SPARC debugging workflow\n- **\\`refactor/sparc-<component>\\`**: Refactoring using optimization mode\n\n## Troubleshooting\n\n### Common SPARC Issues\n- **Mode not found**: Check \\`.roomodes\\` file exists and is valid JSON\n- **Memory persistence**: Ensure \\`memory/\\` directory has write permissions\n- **Tool access**: Verify required tools are available for the selected mode\n- **Namespace conflicts**: Use unique memory namespaces for different features\n\n### Debug Commands\n\\`\\`\\`bash\n# Check SPARC configuration\nnpx claude-flow sparc modes\n\n# Verify memory system\nnpx claude-flow memory stats\n\n# Check system status\nnpx claude-flow status\n\n# View detailed mode information\nnpx claude-flow sparc info <mode-name>\n\\`\\`\\`\n\n## Project Architecture\n\nThis SPARC-enabled project follows a systematic development approach:\n- **Clear separation of concerns** through modular design\n- **Test-driven development** ensuring reliability and maintainability\n- **Iterative refinement** for continuous improvement\n- **Comprehensive documentation** for team collaboration\n- **AI-assisted development** through specialized SPARC modes\n\n## Important Notes\n\n- Always run tests before committing (\\`npm run test\\`)\n- Use SPARC memory system to maintain context across sessions\n- Follow the Red-Green-Refactor cycle during TDD phases\n- Document architectural decisions in memory for future reference\n- Regular security reviews for any authentication or data handling code\n\nFor more information about SPARC methodology, see: https://github.com/ruvnet/claude-code-flow/docs/sparc.md\n`;\n}\n\n// Run main if executed directly\nif (import.meta.url === `file://${process.argv[1]}`) {\n await main();\n}\n"],"names":["promises","fs","executeCommand","hasCommand","showCommandHelp","listCommands","parseFlags","VERSION","printHelp","console","log","printVersion","printError","message","error","printSuccess","printWarning","warn","showHelpWithCommands","commands","command","name","padEnd","description","main","args","Deno","length","flags","parsedArgs","slice","err","subArgs","spawnType","spawnName","Date","now","terminalCmd","poolCmd","detailed","includes","process","cwd","termId","nameIndex","indexOf","shellIndex","wdIndex","envIndex","persistentIndex","terminalConfig","shell","workingDirectory","env","persistent","execCmd","join","sessionFlag","timeoutFlag","backgroundFlag","sessionId","cmdStart","cmdEnd","lastIndexOf","batchSession","find","arg","startsWith","commandsFlag","fileFlag","split","forEach","cmd","i","listDetailed","infoSessionId","attachId","detachId","terminateId","graceful","idleTime","monitorId","recordId","outputFlag","replayFile","shareId","accessLevel","multiCmd","configName","envName","configFile","sessionCmd","workflowFile","startRepl","projectCmd","projectName","isolationFlag","resourceQuotaFlag","securityProfileFlag","templateFlag","switchProject","showActive","withStats","projects","status","agents","tasks","project","configAction","configProject","configKey","configValue","monitorProject","backupProject","includeData","includeConfig","includeHistory","outputFile","shareFrom","shareTo","agentsFlag","permissionsFlag","durationFlag","fedCmd","fedName","projectsFlag","cloudCmd","cloudProvider","awsServices","awsRegions","awsHA","awsCostOpt","azureServices","azureRegions","azureIntegration","gcpServices","gcpRegions","multiCloud","multiCloudCmd","failoverTarget","k8sCmd","replicas","claudeCmd","taskEndIndex","task","tools","noPermissions","config","mode","parallel","research","coverage","parseInt","commit","verbose","dryRun","instanceId","Math","random","toString","substr","enhancedTask","claudeArgs","push","substring","map","Command","toObject","CLAUDE_INSTANCE_ID","CLAUDE_FLOW_MODE","CLAUDE_FLOW_COVERAGE","CLAUDE_FLOW_COMMIT","CLAUDE_FLOW_MEMORY_ENABLED","CLAUDE_FLOW_MEMORY_NAMESPACE","CLAUDE_FLOW_COORDINATION_ENABLED","CLAUDE_FLOW_FEATURES","stdin","stdout","stderr","child","spawn","success","code","deployCmd","nodes","regions","replicationFactor","scalingAction","securityAction","analyticsCmd","costCmd","securityCmd","authAction","rbacAction","user","role","rateLimitAction","cbAction","service","auditAction","query","backupCmd","drAction","restorePoint","commonCommands","suggestions","filter","toLowerCase","exit","replState","history","historyIndex","currentSession","context","terminals","memory","replCommands","help","Object","keys","clear","key","JSON","parse","readFile","value","k","stringify","processReplCommand","input","trimmed","trim","shellCmd","output","TextDecoder","decode","search","matches","parts","handleAgentCommand","handleTaskCommand","handleMemoryCommand","handleTerminalCommand","state","subCmd","type","agent","id","created","toISOString","agentId","foundAgent","a","index","findIndex","removed","splice","taskId","assignAgentId","foundTask","t","assignAgent","assignedTo","statusId","statusTask","getKey","terminal","term","decoder","encoder","TextEncoder","prompt","write","encode","buf","Uint8Array","n","read","subarray","shouldContinue","createMinimalClaudeMd","createFullClaudeMd","createMinimalMemoryBankMd","createFullMemoryBankMd","createMinimalCoordinationMd","createFullCoordinationMd","createAgentsReadme","createSessionsReadme","createSparcStructureManually","rooDirectories","dir","mkdir","recursive","errors","AlreadyExists","roomodesContent","createBasicRoomodesConfig","writeFile","basicWorkflow","createBasicSparcWorkflow","rooReadme","createRooReadme","customModes","slug","roleDefinition","customInstructions","groups","source","sequential","steps","phase","createSparcClaudeMd","url","argv"],"mappings":";AAMA,SAASA,YAAYC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OAAOxE,KAAKI,SAAS,CACnB;QACEtN,MAAM;QACNE,aAAa;QACbiS,YAAY;QACZC,OAAO;YACL;gBACEvJ,MAAM;gBACN3I,aAAa;gBACbmS,OAAO;YACT;YACA;gBACExJ,MAAM;gBACN3I,aAAa;gBACbmS,OAAO;YACT;YACA;gBACExJ,MAAM;gBACN3I,aAAa;gBACbmS,OAAO;YACT;YACA;gBACExJ,MAAM;gBACN3I,aAAa;gBACbmS,OAAO;YACT;YACA;gBACExJ,MAAM;gBACN3I,aAAa;gBACbmS,OAAO;YACT;SACD;IACH,GACA,MACA;AAEJ;AAEA,SAAST;IACP,OAAO,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDV,CAAC;AACD;AAEA,SAASU;IACP,OAAO,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAoPV,CAAC;AACD;AAEA,IAAIhV,aAAa,YAAYiV,GAAG,GAAG;IACjC,MAAMpS;AACR"}
\ No newline at end of file
diff --git a/dist-cjs/src/cli/simple-commands/hive-mind.js b/dist-cjs/src/cli/simple-commands/hive-mind.js
index 03f693577f..8d918a191c 100644
--- a/dist-cjs/src/cli/simple-commands/hive-mind.js
+++ b/dist-cjs/src/cli/simple-commands/hive-mind.js
@@ -12,14 +12,23 @@ let sqliteAvailable = false;
async function loadSqlite() {
if (Database !== null) return sqliteAvailable;
try {
- const sqlite = await import('better-sqlite3');
- Database = sqlite.default;
+ const { createRequire } = await import('module');
+ const require = createRequire(import.meta.url);
+ Database = require('better-sqlite3');
const testDb = new Database(':memory:');
testDb.close();
sqliteAvailable = true;
- } catch (err) {
- sqliteAvailable = false;
- Database = null;
+ } catch (requireErr) {
+ try {
+ const sqlite = await import('better-sqlite3');
+ Database = sqlite.default || sqlite;
+ const testDb = new Database(':memory:');
+ testDb.close();
+ sqliteAvailable = true;
+ } catch (err) {
+ sqliteAvailable = false;
+ Database = null;
+ }
}
return sqliteAvailable;
}
@@ -494,6 +503,14 @@ async function spawnSwarmWizard() {
return swarmResult;
}
async function spawnSwarm(args, flags) {
+ const hasSqlite = await loadSqlite();
+ if (!hasSqlite) {
+ console.error(chalk.red('Error: SQLite is required for hive-mind spawn'));
+ console.log(chalk.yellow('Please ensure better-sqlite3 is properly installed:'));
+ console.log(chalk.gray(' npm install better-sqlite3'));
+ console.log(chalk.gray(' # or for ARM64/M1: npm rebuild better-sqlite3'));
+ return;
+ }
const objective = args.join(' ').trim();
const isNonInteractive = flags['non-interactive'] || flags.nonInteractive;
if (!objective && !flags.wizard) {
@@ -1048,6 +1065,11 @@ async function showStatus(flags) {
}
}
async function showConsensus(flags) {
+ const hasSqlite = await loadSqlite();
+ if (!hasSqlite) {
+ console.error(chalk.red('Error: SQLite is required for this command'));
+ return;
+ }
try {
const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');
const db = new Database(dbPath);
@@ -1111,6 +1133,11 @@ async function showConsensus(flags) {
}
}
async function showMetrics(flags) {
+ const hasSqlite = await loadSqlite();
+ if (!hasSqlite) {
+ console.error(chalk.red('Error: SQLite is required for this command'));
+ return;
+ }
try {
const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');
const db = new Database(dbPath);
@@ -1442,6 +1469,11 @@ export async function hiveMindCommand(args, flags) {
}
}
async function listMemories() {
+ const hasSqlite = await loadSqlite();
+ if (!hasSqlite) {
+ console.error(chalk.red('Error: SQLite is required for this command'));
+ return;
+ }
try {
console.log(chalk.blue('\n📋 Collective Memory Store\n'));
const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');
@@ -1487,6 +1519,11 @@ async function listMemories() {
}
}
async function searchMemories() {
+ const hasSqlite = await loadSqlite();
+ if (!hasSqlite) {
+ console.error(chalk.red('Error: SQLite is required for this command'));
+ return;
+ }
try {
const { searchTerm } = await inquirer.prompt([
{
diff --git a/dist-cjs/src/cli/simple-commands/hive-mind.js.map b/dist-cjs/src/cli/simple-commands/hive-mind.js.map
index 2ed9199ded..5fede0df96 100644
--- a/dist-cjs/src/cli/simple-commands/hive-mind.js.map
+++ b/dist-cjs/src/cli/simple-commands/hive-mind.js.map
@@ -1 +1 @@
-{"version":3,"sources":["../../../../src/cli/simple-commands/hive-mind.js"],"sourcesContent":["/**\n * Hive Mind command for Claude-Flow v2.0.0\n * Advanced swarm intelligence with collective decision-making\n */\n\nimport { spawn } from 'child_process';\nimport { existsSync, mkdirSync } from 'fs';\nimport { writeFile, readFile } from 'fs/promises';\nimport path from 'path';\nimport readline from 'readline';\nimport inquirer from 'inquirer';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { args, cwd, exit, writeTextFile, readTextFile, mkdirAsync } from '../node-compat.js';\nimport {\n isInteractive,\n isRawModeSupported,\n warnNonInteractive,\n checkNonInteractiveAuth,\n} from '../utils/interactive-detector.js';\nimport {\n safeInteractive,\n nonInteractiveProgress,\n nonInteractiveSelect,\n} from '../utils/safe-interactive.js';\n\n// Import SQLite for persistence - dynamically loaded to handle missing bindings\nlet Database = null;\nlet sqliteAvailable = false;\n\n// Try to load better-sqlite3, but don't fail if bindings aren't available\nasync function loadSqlite() {\n if (Database !== null) return sqliteAvailable;\n try {\n const sqlite = await import('better-sqlite3');\n Database = sqlite.default;\n // Test if bindings work by creating a temp in-memory database\n const testDb = new Database(':memory:');\n testDb.close();\n sqliteAvailable = true;\n } catch (err) {\n sqliteAvailable = false;\n Database = null;\n }\n return sqliteAvailable;\n}\n\n// Import help formatter\nimport { HelpFormatter } from '../help-formatter.js';\n\n// Import MCP tool wrappers\nimport { MCPToolWrapper } from './hive-mind/mcp-wrapper.js';\nimport { HiveMindCore } from './hive-mind/core.js';\nimport { QueenCoordinator } from './hive-mind/queen.js';\nimport { CollectiveMemory } from './hive-mind/memory.js';\nimport { SwarmCommunication } from './hive-mind/communication.js';\nimport { HiveMindSessionManager } from './hive-mind/session-manager.js';\nimport { createAutoSaveMiddleware } from './hive-mind/auto-save-middleware.js';\nimport { HiveMindMetricsReader } from './hive-mind/metrics-reader.js';\n\nfunction showHiveMindHelp() {\n console.log(`\n${chalk.yellow('🧠 Claude Flow Hive Mind System')}\n\n${chalk.bold('USAGE:')}\n claude-flow hive-mind [subcommand] [options]\n\n${chalk.bold('SUBCOMMANDS:')}\n ${chalk.green('init')} Initialize hive mind system\n ${chalk.green('spawn')} Spawn hive mind swarm for a task\n ${chalk.green('status')} Show hive mind status\n ${chalk.green('resume')} Resume a paused hive mind session\n ${chalk.green('stop')} Stop a running hive mind session\n ${chalk.green('sessions')} List all hive mind sessions\n ${chalk.green('consensus')} View consensus decisions\n ${chalk.green('memory')} Manage collective memory\n ${chalk.green('metrics')} View performance metrics\n ${chalk.green('wizard')} Interactive hive mind wizard with Claude Code spawning\n\n${chalk.bold('EXAMPLES:')}\n ${chalk.gray('# Initialize hive mind')}\n claude-flow hive-mind init\n\n ${chalk.gray('# Spawn swarm with interactive wizard')}\n claude-flow hive-mind spawn\n\n ${chalk.gray('# Quick spawn with objective')}\n claude-flow hive-mind spawn \"Build microservices architecture\"\n\n ${chalk.gray('# View current status')}\n claude-flow hive-mind status\n\n ${chalk.gray('# Interactive wizard with Claude Code spawning')}\n claude-flow hive-mind wizard\n\n ${chalk.gray('# Spawn with Claude Code coordination')}\n claude-flow hive-mind spawn \"Build REST API\" --claude\n\n ${chalk.gray('# Auto-spawn coordinated Claude Code instances')}\n claude-flow hive-mind spawn \"Research AI trends\" --auto-spawn --verbose\n\n ${chalk.gray('# List all sessions')}\n claude-flow hive-mind sessions\n\n ${chalk.gray('# Resume a paused session')}\n claude-flow hive-mind resume session-1234567890-abc123\n\n${chalk.bold('KEY FEATURES:')}\n ${chalk.cyan('🐝')} Queen-led coordination with worker specialization\n ${chalk.cyan('🧠')} Collective memory and knowledge sharing\n ${chalk.cyan('🤝')} Consensus building for critical decisions\n ${chalk.cyan('⚡')} Parallel task execution with auto-scaling\n ${chalk.cyan('🔄')} Work stealing and load balancing\n ${chalk.cyan('📊')} Real-time metrics and performance tracking\n ${chalk.cyan('🛡️')} Fault tolerance and self-healing\n ${chalk.cyan('🔒')} Secure communication between agents\n\n${chalk.bold('OPTIONS:')}\n --queen-type <type> Queen coordinator type (strategic, tactical, adaptive)\n --max-workers <n> Maximum worker agents (default: 8)\n --consensus <type> Consensus algorithm (majority, weighted, byzantine)\n --memory-size <mb> Collective memory size in MB (default: 100)\n --auto-scale Enable auto-scaling based on workload\n --encryption Enable encrypted communication\n --monitor Real-time monitoring dashboard\n --verbose Detailed logging\n --claude Generate Claude Code spawn commands with coordination\n --spawn Alias for --claude\n --auto-spawn Automatically spawn Claude Code instances\n --execute Execute Claude Code spawn commands immediately\n\n${chalk.bold('For more information:')}\n${chalk.blue('https://github.com/ruvnet/claude-flow/tree/main/docs/hive-mind')}\n`);\n}\n\n/**\n * Initialize hive mind system\n */\nasync function initHiveMind(flags) {\n const spinner = ora('Initializing Hive Mind system...').start();\n\n try {\n // Create hive mind directory structure\n const hiveMindDir = path.join(cwd(), '.hive-mind');\n if (!existsSync(hiveMindDir)) {\n mkdirSync(hiveMindDir, { recursive: true });\n }\n\n // Check SQLite availability\n const hasSqlite = await loadSqlite();\n\n if (!hasSqlite) {\n // Fall back to JSON-based initialization\n spinner.text = 'Initializing Hive Mind with JSON fallback...';\n\n const fallbackPath = path.join(hiveMindDir, 'memory.json');\n const fallbackData = {\n metadata: {\n type: 'fallback',\n initialized: new Date().toISOString(),\n version: '2.0.0',\n warning: 'Using JSON fallback - SQLite bindings not available'\n },\n swarms: [],\n agents: [],\n tasks: [],\n collective_memory: [],\n consensus_votes: [],\n messages: []\n };\n\n await writeFile(fallbackPath, JSON.stringify(fallbackData, null, 2), 'utf8');\n\n spinner.succeed('Hive Mind initialized with JSON fallback');\n console.log(chalk.yellow('\\n⚠️ Note: SQLite native bindings not available'));\n console.log(chalk.gray(' Using JSON fallback for data persistence'));\n console.log(chalk.gray(' For full SQLite features, install locally: npm install claude-flow'));\n return;\n }\n\n // Initialize SQLite database\n const dbPath = path.join(hiveMindDir, 'hive.db');\n const db = new Database(dbPath);\n\n // Create tables\n db.exec(`\n CREATE TABLE IF NOT EXISTS swarms (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n objective TEXT,\n status TEXT DEFAULT 'active',\n queen_type TEXT DEFAULT 'strategic',\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n updated_at DATETIME DEFAULT CURRENT_TIMESTAMP\n );\n \n CREATE TABLE IF NOT EXISTS agents (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n name TEXT NOT NULL,\n type TEXT NOT NULL,\n role TEXT,\n status TEXT DEFAULT 'idle',\n capabilities TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS tasks (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n agent_id TEXT,\n description TEXT,\n status TEXT DEFAULT 'pending',\n priority INTEGER DEFAULT 5,\n result TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n completed_at DATETIME,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id),\n FOREIGN KEY (agent_id) REFERENCES agents(id)\n );\n \n CREATE TABLE IF NOT EXISTS collective_memory (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n key TEXT NOT NULL,\n value TEXT,\n type TEXT DEFAULT 'knowledge',\n confidence REAL DEFAULT 1.0,\n created_by TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n accessed_at DATETIME,\n access_count INTEGER DEFAULT 0,\n compressed INTEGER DEFAULT 0,\n size INTEGER DEFAULT 0,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS consensus_decisions (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n topic TEXT NOT NULL,\n decision TEXT,\n votes TEXT,\n algorithm TEXT DEFAULT 'majority',\n confidence REAL,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n `);\n\n db.close();\n\n // Create configuration file\n const config = {\n version: '2.0.0',\n initialized: new Date().toISOString(),\n defaults: {\n queenType: 'strategic',\n maxWorkers: 8,\n consensusAlgorithm: 'majority',\n memorySize: 100,\n autoScale: true,\n encryption: false,\n },\n mcpTools: {\n enabled: true,\n parallel: true,\n timeout: 60000,\n },\n };\n\n await writeFile(path.join(hiveMindDir, 'config.json'), JSON.stringify(config, null, 2));\n\n spinner.succeed('Hive Mind system initialized successfully!');\n\n console.log('\\n' + chalk.green('✓') + ' Created .hive-mind directory');\n console.log(chalk.green('✓') + ' Initialized SQLite database');\n console.log(chalk.green('✓') + ' Created configuration file');\n console.log('\\n' + chalk.yellow('Next steps:'));\n console.log(\n ' 1. Run ' + chalk.cyan('claude-flow hive-mind spawn') + ' to create your first swarm',\n );\n console.log(\n ' 2. Use ' + chalk.cyan('claude-flow hive-mind wizard') + ' for interactive setup',\n );\n } catch (error) {\n spinner.fail('Failed to initialize Hive Mind system');\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Interactive wizard for hive mind operations\n */\n// Wrapped wizard function that handles non-interactive environments\nconst hiveMindWizard = safeInteractive(\n // Interactive version\n async function (flags = {}) {\n console.log(chalk.yellow('\\n🧙 Hive Mind Interactive Wizard\\n'));\n\n const { action } = await inquirer.prompt([\n {\n type: 'list',\n name: 'action',\n message: 'What would you like to do?',\n choices: [\n { name: '🐝 Create new swarm', value: 'spawn' },\n { name: '📊 View swarm status', value: 'status' },\n { name: '🧠 Manage collective memory', value: 'memory' },\n { name: '🤝 View consensus decisions', value: 'consensus' },\n { name: '📈 Performance metrics', value: 'metrics' },\n { name: '🔧 Configure hive mind', value: 'config' },\n { name: '❌ Exit', value: 'exit' },\n ],\n },\n ]);\n\n switch (action) {\n case 'spawn':\n await spawnSwarmWizard();\n break;\n case 'status':\n await showStatus({});\n break;\n case 'memory':\n await manageMemoryWizard();\n break;\n case 'consensus':\n await showConsensus({});\n break;\n case 'metrics':\n await showMetrics({});\n break;\n case 'config':\n await configureWizard();\n break;\n case 'exit':\n console.log(chalk.gray('Exiting wizard...'));\n break;\n }\n },\n // Non-interactive fallback\n async function (flags = {}) {\n console.log(chalk.yellow('\\n🧙 Hive Mind - Non-Interactive Mode\\n'));\n\n // Default to creating a swarm with sensible defaults\n console.log(chalk.cyan('Creating new swarm with default settings...'));\n console.log(chalk.gray('Use command-line flags to customize:'));\n console.log(chalk.gray(' --objective \"Your task\" Set swarm objective'));\n console.log(chalk.gray(' --queen-type strategic Set queen type'));\n console.log(chalk.gray(' --max-workers 8 Set worker count'));\n console.log();\n\n const objective = flags.objective || 'General task coordination';\n const config = {\n name: flags.name || `swarm-${Date.now()}`,\n queenType: flags.queenType || flags['queen-type'] || 'strategic',\n maxWorkers: parseInt(flags.maxWorkers || flags['max-workers'] || '8'),\n consensusAlgorithm: flags.consensus || flags.consensusAlgorithm || 'majority',\n autoScale: flags.autoScale || flags['auto-scale'] || false,\n namespace: flags.namespace || 'default',\n verbose: flags.verbose || false,\n encryption: flags.encryption || false,\n };\n\n await spawnSwarm([objective], {\n ...flags,\n name: config.name,\n queenType: config.queenType,\n maxWorkers: config.maxWorkers,\n consensusAlgorithm: config.consensusAlgorithm,\n autoScale: config.autoScale,\n encryption: config.encryption,\n nonInteractive: true,\n });\n },\n);\n\n/**\n * Spawn swarm wizard\n */\nasync function spawnSwarmWizard() {\n const answers = await inquirer.prompt([\n {\n type: 'input',\n name: 'objective',\n message: 'What is the swarm objective?',\n validate: (input) => input.trim().length > 0 || 'Please enter an objective',\n },\n {\n type: 'input',\n name: 'name',\n message: 'Swarm name (optional):',\n default: (answers) => `swarm-${Date.now()}`,\n },\n {\n type: 'list',\n name: 'queenType',\n message: 'Select queen coordinator type:',\n choices: [\n { name: 'Strategic - High-level planning and coordination', value: 'strategic' },\n { name: 'Tactical - Detailed task management', value: 'tactical' },\n { name: 'Adaptive - Learns and adapts strategies', value: 'adaptive' },\n ],\n default: 'strategic',\n },\n {\n type: 'number',\n name: 'maxWorkers',\n message: 'Maximum number of worker agents:',\n default: 8,\n validate: (input) => (input > 0 && input <= 20) || 'Please enter a number between 1 and 20',\n },\n {\n type: 'checkbox',\n name: 'workerTypes',\n message: 'Select worker agent types:',\n choices: [\n { name: 'Researcher', value: 'researcher', checked: true },\n { name: 'Coder', value: 'coder', checked: true },\n { name: 'Analyst', value: 'analyst', checked: true },\n { name: 'Tester', value: 'tester', checked: true },\n { name: 'Architect', value: 'architect' },\n { name: 'Reviewer', value: 'reviewer' },\n { name: 'Optimizer', value: 'optimizer' },\n { name: 'Documenter', value: 'documenter' },\n ],\n },\n {\n type: 'list',\n name: 'consensusAlgorithm',\n message: 'Consensus algorithm for decisions:',\n choices: [\n { name: 'Majority - Simple majority voting', value: 'majority' },\n { name: 'Weighted - Expertise-weighted voting', value: 'weighted' },\n { name: 'Byzantine - Fault-tolerant consensus', value: 'byzantine' },\n ],\n default: 'majority',\n },\n {\n type: 'confirm',\n name: 'autoScale',\n message: 'Enable auto-scaling?',\n default: true,\n },\n {\n type: 'confirm',\n name: 'monitor',\n message: 'Launch monitoring dashboard?',\n default: true,\n },\n {\n type: 'confirm',\n name: 'spawnClaude',\n message: 'Spawn Claude Code instance with hive-mind coordination?',\n default: true,\n },\n ]);\n\n // Spawn the swarm with collected parameters\n const swarmResult = await spawnSwarm([answers.objective], {\n name: answers.name,\n queenType: answers.queenType,\n 'queen-type': answers.queenType,\n maxWorkers: answers.maxWorkers,\n 'max-workers': answers.maxWorkers,\n workerTypes: answers.workerTypes.join(','),\n consensus: answers.consensusAlgorithm,\n autoScale: answers.autoScale,\n 'auto-scale': answers.autoScale,\n monitor: answers.monitor,\n namespace: answers.namespace || 'default',\n verbose: answers.verbose || false,\n spawnClaude: answers.spawnClaude, // Pass the Claude spawning preference\n });\n\n // If Claude Code spawning was requested, launch it using the same function as --claude flag\n if (answers.spawnClaude && swarmResult && swarmResult.swarmId) {\n // Create workers array in the same format expected by spawnClaudeCodeInstances\n const workers = answers.workerTypes.map((type, index) => ({\n id: `worker-${index + 1}`,\n type,\n role: 'worker',\n status: 'active',\n capabilities: getAgentCapabilities(type)\n }));\n \n // Create flags object with the wizard settings\n const claudeFlags = {\n queenType: answers.queenType,\n consensus: answers.consensusAlgorithm,\n autoScale: answers.autoScale,\n monitor: answers.monitor,\n namespace: answers.namespace || 'default',\n verbose: answers.verbose || false\n };\n \n // Use the same Claude spawning function as the --claude flag\n console.log(chalk.cyan(`\\n🎯 Objective from wizard: \"${answers.objective}\"`));\n await spawnClaudeCodeInstances(\n swarmResult.swarmId,\n answers.name,\n answers.objective,\n workers,\n claudeFlags\n );\n }\n \n return swarmResult;\n}\n\n/**\n * Spawn a hive mind swarm\n */\nasync function spawnSwarm(args, flags) {\n const objective = args.join(' ').trim();\n\n // Check for non-interactive mode FIRST\n const isNonInteractive = flags['non-interactive'] || flags.nonInteractive;\n \n if (!objective && !flags.wizard) {\n if (isNonInteractive) {\n console.error(chalk.red('Error: Objective required in non-interactive mode'));\n console.log('Usage: claude-flow hive-mind spawn \"Your objective\" --non-interactive');\n } else {\n console.error(chalk.red('Error: Please provide an objective or use --wizard flag'));\n console.log('Example: claude-flow hive-mind spawn \"Build REST API\"');\n }\n return;\n }\n \n // Log non-interactive mode status\n if (isNonInteractive && flags.verbose) {\n console.log(chalk.cyan('🤖 Running in non-interactive mode'));\n }\n\n // Validate parameters\n if (flags.verbose) {\n console.log(chalk.gray('🔍 Debug: Parsed flags:'));\n console.log(chalk.gray(JSON.stringify(flags, null, 2)));\n }\n\n // Validate queen type\n const validQueenTypes = ['strategic', 'tactical', 'adaptive'];\n const queenType = flags.queenType || flags['queen-type'] || 'strategic';\n if (!validQueenTypes.includes(queenType)) {\n console.error(chalk.red(`Error: Invalid queen type '${queenType}'. Must be one of: ${validQueenTypes.join(', ')}`));\n return;\n }\n\n // Validate max workers\n const maxWorkers = parseInt(flags.maxWorkers || flags['max-workers'] || '8');\n if (isNaN(maxWorkers) || maxWorkers < 1 || maxWorkers > 20) {\n console.error(chalk.red('Error: max-workers must be a number between 1 and 20'));\n return;\n }\n\n // Validate consensus algorithm\n const validConsensusTypes = ['majority', 'weighted', 'byzantine'];\n const consensusAlgorithm = flags.consensus || flags.consensusAlgorithm || 'majority';\n if (!validConsensusTypes.includes(consensusAlgorithm)) {\n console.error(chalk.red(`Error: Invalid consensus algorithm '${consensusAlgorithm}'. Must be one of: ${validConsensusTypes.join(', ')}`));\n return;\n }\n\n const spinner = ora('Spawning Hive Mind swarm...').start();\n\n try {\n // Initialize hive mind core with error handling\n let hiveMind;\n try {\n spinner.text = 'Initializing Hive Mind Core...';\n hiveMind = new HiveMindCore({\n objective,\n name: flags.name || `hive-${Date.now()}`,\n queenType: flags.queenType || flags['queen-type'] || 'strategic',\n maxWorkers: parseInt(flags.maxWorkers || flags['max-workers'] || '8'),\n consensusAlgorithm: flags.consensus || flags.consensusAlgorithm || 'majority',\n autoScale: flags.autoScale !== undefined ? flags.autoScale : (flags['auto-scale'] !== undefined ? flags['auto-scale'] : true),\n namespace: flags.namespace || 'default',\n encryption: flags.encryption || false,\n });\n } catch (error) {\n console.error('HiveMindCore initialization failed:', error);\n throw new Error(`Failed to initialize HiveMindCore: ${error.message}`);\n }\n\n spinner.text = 'Setting up database connection...';\n // Initialize database connection\n const dbDir = path.join(cwd(), '.hive-mind');\n const dbPath = path.join(dbDir, 'hive.db');\n\n // Ensure .hive-mind directory exists\n if (!existsSync(dbDir)) {\n mkdirSync(dbDir, { recursive: true });\n }\n\n // Check if database file exists and try to create a clean one if needed\n let db;\n try {\n spinner.text = 'Creating database connection...';\n db = new Database(dbPath);\n // Test the database with a simple query\n db.prepare('SELECT 1').get();\n spinner.text = 'Database connection established';\n } catch (error) {\n console.warn('Database issue detected, recreating...', error.message);\n spinner.text = 'Recreating database...';\n // Remove corrupted database\n if (existsSync(dbPath)) {\n try {\n const fs = await import('fs');\n fs.unlinkSync(dbPath);\n } catch (e) {\n console.warn('Could not remove corrupted database:', e.message);\n }\n }\n // Create new database\n db = new Database(dbPath);\n }\n\n // Initialize database schema if not exists\n spinner.text = 'Creating database schema...';\n try {\n db.exec(`\n CREATE TABLE IF NOT EXISTS swarms (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n objective TEXT,\n queen_type TEXT,\n status TEXT DEFAULT 'active',\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n updated_at DATETIME\n );\n \n CREATE TABLE IF NOT EXISTS agents (\n id TEXT PRIMARY KEY,\n swarm_id TEXT NOT NULL,\n name TEXT NOT NULL,\n type TEXT NOT NULL,\n role TEXT NOT NULL,\n status TEXT DEFAULT 'idle',\n capabilities TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS tasks (\n id TEXT PRIMARY KEY,\n swarm_id TEXT NOT NULL,\n agent_id TEXT,\n description TEXT,\n status TEXT DEFAULT 'pending',\n priority INTEGER DEFAULT 5,\n result TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n completed_at DATETIME,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id),\n FOREIGN KEY (agent_id) REFERENCES agents(id)\n );\n \n CREATE TABLE IF NOT EXISTS collective_memory (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n key TEXT NOT NULL,\n value TEXT,\n type TEXT DEFAULT 'knowledge',\n confidence REAL DEFAULT 1.0,\n created_by TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n accessed_at DATETIME,\n access_count INTEGER DEFAULT 0,\n compressed INTEGER DEFAULT 0,\n size INTEGER DEFAULT 0,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS consensus_decisions (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n topic TEXT NOT NULL,\n decision TEXT,\n votes TEXT,\n algorithm TEXT DEFAULT 'majority',\n confidence REAL,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS sessions (\n id TEXT PRIMARY KEY,\n swarm_id TEXT NOT NULL,\n swarm_name TEXT NOT NULL,\n objective TEXT,\n status TEXT DEFAULT 'active',\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n paused_at DATETIME,\n resumed_at DATETIME,\n completion_percentage REAL DEFAULT 0,\n checkpoint_data TEXT,\n metadata TEXT,\n parent_pid INTEGER,\n child_pids TEXT,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS session_checkpoints (\n id TEXT PRIMARY KEY,\n session_id TEXT NOT NULL,\n checkpoint_name TEXT NOT NULL,\n checkpoint_data TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (session_id) REFERENCES sessions(id)\n );\n \n CREATE TABLE IF NOT EXISTS session_logs (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL,\n timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,\n log_level TEXT DEFAULT 'info',\n message TEXT,\n agent_id TEXT,\n data TEXT,\n FOREIGN KEY (session_id) REFERENCES sessions(id)\n );\n `);\n spinner.text = 'Database schema created successfully';\n } catch (error) {\n console.error('Database schema creation failed:', error);\n throw new Error(`Failed to create database schema: ${error.message}`);\n }\n\n // Create swarm record with safe ID generation\n spinner.text = 'Creating swarm record...';\n const timestamp = Date.now();\n const randomPart = Math.random().toString(36).substring(2, 11); // Use substring instead of substr\n const swarmId = `swarm-${timestamp}-${randomPart}`;\n try {\n db.prepare(\n `\n INSERT INTO swarms (id, name, objective, queen_type)\n VALUES (?, ?, ?, ?)\n `,\n ).run(swarmId, hiveMind.config.name, objective, hiveMind.config.queenType);\n } catch (error) {\n console.error('Failed to create swarm record:', error);\n throw new Error(`Failed to create swarm record: ${error.message}`);\n }\n\n // Create session for this swarm\n spinner.text = 'Creating session tracking...';\n const sessionManager = new HiveMindSessionManager();\n const sessionId = await sessionManager.createSession(swarmId, hiveMind.config.name, objective, {\n queenType: hiveMind.config.queenType,\n maxWorkers: hiveMind.config.maxWorkers,\n consensusAlgorithm: hiveMind.config.consensusAlgorithm,\n autoScale: hiveMind.config.autoScale,\n encryption: hiveMind.config.encryption,\n workerTypes: flags.workerTypes,\n });\n\n spinner.text = 'Session tracking established...';\n\n // Initialize auto-save middleware (use the same session manager)\n const autoSave = createAutoSaveMiddleware(sessionId, sessionManager, {\n saveInterval: 30000, // Save every 30 seconds\n autoStart: true,\n });\n\n // Close session manager after auto-save is set up\n // sessionManager.close(); // Don't close yet as auto-save needs it\n\n // Track initial swarm creation\n autoSave.trackChange('swarm_created', {\n swarmId,\n swarmName: hiveMind.config.name,\n objective,\n workerCount: hiveMind.config.maxWorkers,\n });\n\n spinner.text = 'Initializing Queen coordinator...';\n\n // Initialize Queen\n const queen = new QueenCoordinator({\n swarmId,\n type: hiveMind.config.queenType,\n objective,\n });\n\n // Spawn Queen agent\n const queenAgent = {\n id: `queen-${swarmId}`,\n swarmId,\n name: 'Queen Coordinator',\n type: 'coordinator',\n role: 'queen',\n status: 'active',\n capabilities: JSON.stringify(['coordination', 'planning', 'decision-making']),\n };\n\n db.prepare(\n `\n INSERT INTO agents (id, swarm_id, name, type, role, status, capabilities)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n `,\n ).run(...Object.values(queenAgent));\n\n spinner.text = 'Spawning worker agents...';\n\n // Determine worker types\n const workerTypes = flags.workerTypes\n ? flags.workerTypes.split(',')\n : ['researcher', 'coder', 'analyst', 'tester'];\n\n // Spawn worker agents\n const workers = [];\n for (let i = 0; i < Math.min(workerTypes.length, hiveMind.config.maxWorkers); i++) {\n const workerType = workerTypes[i % workerTypes.length];\n const workerId = `worker-${swarmId}-${i}`;\n\n const worker = {\n id: workerId,\n swarmId,\n name: `${workerType.charAt(0).toUpperCase() + workerType.slice(1)} Worker ${i + 1}`,\n type: workerType,\n role: 'worker',\n status: 'idle',\n capabilities: JSON.stringify(getAgentCapabilities(workerType)),\n };\n\n workers.push(worker);\n\n db.prepare(\n `\n INSERT INTO agents (id, swarm_id, name, type, role, status, capabilities)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n `,\n ).run(...Object.values(worker));\n\n // Track agent spawning for auto-save\n autoSave.trackAgentActivity(workerId, 'spawned', {\n type: workerType,\n name: worker.name,\n });\n }\n\n spinner.text = 'Initializing collective memory...';\n\n // Initialize collective memory\n const memory = new CollectiveMemory({\n swarmId,\n maxSize: flags.memorySize || 100,\n });\n\n // Store initial context\n memory.store('objective', objective, 'context');\n memory.store('queen_type', hiveMind.config.queenType, 'config');\n memory.store('worker_count', workers.length, 'metrics');\n memory.store('session_id', sessionId, 'system');\n\n spinner.text = 'Establishing communication channels...';\n\n // Initialize communication system\n const communication = new SwarmCommunication({\n swarmId,\n encryption: hiveMind.config.encryption,\n });\n\n db.close();\n\n spinner.succeed('Hive Mind swarm spawned successfully!');\n\n // Display swarm summary\n console.log('\\n' + chalk.bold('🐝 Swarm Summary:'));\n console.log(chalk.gray('─'.repeat(50)));\n console.log(chalk.cyan('Swarm ID:'), swarmId);\n console.log(chalk.cyan('Session ID:'), sessionId);\n console.log(chalk.cyan('Name:'), hiveMind.config.name);\n console.log(chalk.cyan('Objective:'), objective);\n console.log(chalk.cyan('Queen Type:'), hiveMind.config.queenType);\n console.log(chalk.cyan('Workers:'), workers.length);\n console.log(chalk.cyan('Worker Types:'), workerTypes.join(', '));\n console.log(chalk.cyan('Consensus:'), hiveMind.config.consensusAlgorithm);\n console.log(chalk.cyan('Auto-scaling:'), hiveMind.config.autoScale ? 'Enabled' : 'Disabled');\n console.log(chalk.gray('─'.repeat(50)));\n\n // Launch monitoring if requested\n if (flags.monitor) {\n console.log('\\n' + chalk.yellow('Launching monitoring dashboard...'));\n // TODO: Implement monitoring dashboard\n }\n\n // Enhanced coordination instructions with MCP tools\n console.log('\\n' + chalk.green('✓') + ' Swarm is ready for coordination');\n console.log(chalk.gray('Use \"claude-flow hive-mind status\" to view swarm activity'));\n console.log(chalk.gray('Session auto-save enabled - progress saved every 30 seconds'));\n console.log(chalk.blue('💡 To pause:') + ' Press Ctrl+C to safely pause and resume later');\n console.log(chalk.blue('💡 To resume:') + ' claude-flow hive-mind resume ' + sessionId);\n\n // Set up SIGINT handler for automatic session pausing\n let isExiting = false;\n const sigintHandler = async () => {\n if (isExiting) return;\n isExiting = true;\n\n console.log('\\n\\n' + chalk.yellow('⏸️ Pausing session...'));\n \n try {\n // Save current checkpoint using the existing session manager\n // const sessionManager = new HiveMindSessionManager(); // Use existing one\n \n // Create checkpoint data\n const checkpointData = {\n timestamp: new Date().toISOString(),\n swarmId,\n objective,\n workerCount: workers.length,\n workerTypes,\n status: 'paused_by_user',\n reason: 'User pressed Ctrl+C',\n };\n \n // Save checkpoint\n await sessionManager.saveCheckpoint(sessionId, 'auto-pause', checkpointData);\n \n // Pause the session\n await sessionManager.pauseSession(sessionId);\n \n // Close session manager\n sessionManager.close();\n \n console.log(chalk.green('✓') + ' Session paused successfully');\n console.log(chalk.cyan('\\nTo resume this session, run:'));\n console.log(chalk.bold(` claude-flow hive-mind resume ${sessionId}`));\n console.log();\n \n // Clean up auto-save if active\n if (global.autoSaveInterval) {\n clearInterval(global.autoSaveInterval);\n }\n \n process.exit(0);\n } catch (error) {\n console.error(chalk.red('Error pausing session:'), error.message);\n process.exit(1);\n }\n };\n\n // Register SIGINT handler\n process.on('SIGINT', sigintHandler);\n process.on('SIGTERM', sigintHandler);\n\n // Offer to spawn Claude Code instances with coordination instructions\n // Spawn Claude if --claude or --spawn flag is set\n if (flags.claude || flags.spawn) {\n await spawnClaudeCodeInstances(swarmId, hiveMind.config.name, objective, workers, flags);\n } else {\n console.log(\n '\\n' +\n chalk.blue('💡 Pro Tip:') +\n ' Add --claude to spawn coordinated Claude Code instances',\n );\n console.log(chalk.gray(' claude-flow hive-mind spawn \"objective\" --claude'));\n }\n\n // Return swarm info for wizard use\n return { swarmId, hiveMind };\n } catch (error) {\n spinner.fail('Failed to spawn Hive Mind swarm');\n console.error(chalk.red('Error:'), error.message);\n\n // If error contains \"sha3\", provide specific guidance\n if (error.message.includes('sha3') || error.message.includes('SHA3')) {\n console.error('\\n🔍 SHA3 Function Error Detected');\n console.error('This appears to be a SQLite extension or better-sqlite3 configuration issue.');\n console.error('\\nPossible solutions:');\n console.error('1. Try removing the corrupted database: rm -rf .hive-mind/');\n console.error('2. Reinstall better-sqlite3: npm reinstall better-sqlite3');\n console.error('3. Check if any SQLite extensions are conflicting');\n console.error('\\n🚨 Detailed error:');\n console.error(error.stack || error.message);\n }\n\n exit(1);\n }\n}\n\n/**\n * Get agent capabilities based on type\n */\nfunction getAgentCapabilities(type) {\n const capabilities = {\n researcher: ['web-search', 'data-gathering', 'analysis', 'synthesis'],\n coder: ['code-generation', 'implementation', 'refactoring', 'debugging'],\n analyst: ['data-analysis', 'pattern-recognition', 'reporting', 'visualization'],\n tester: ['test-generation', 'quality-assurance', 'bug-detection', 'validation'],\n architect: ['system-design', 'architecture', 'planning', 'documentation'],\n reviewer: ['code-review', 'quality-check', 'feedback', 'improvement'],\n optimizer: ['performance-tuning', 'optimization', 'profiling', 'enhancement'],\n documenter: ['documentation', 'explanation', 'tutorial-creation', 'knowledge-base'],\n };\n\n return capabilities[type] || ['general'];\n}\n\n/**\n * Show hive mind status\n */\nasync function showStatus(flags) {\n try {\n const hiveMindDir = path.join(cwd(), '.hive-mind');\n const dbPath = path.join(hiveMindDir, 'hive.db');\n const fallbackPath = path.join(hiveMindDir, 'memory.json');\n\n // Check if hive-mind is initialized at all\n if (!existsSync(hiveMindDir)) {\n console.error(chalk.red('Error: Hive Mind not initialized'));\n console.log('Run \"claude-flow hive-mind init\" first');\n return;\n }\n\n // Check SQLite availability\n const hasSqlite = await loadSqlite();\n\n // If SQLite database exists but bindings aren't available\n if (existsSync(dbPath) && !hasSqlite) {\n console.log(chalk.yellow('⚠️ SQLite native bindings not available'));\n console.log(chalk.gray(' This is normal when using npx or remote execution'));\n console.log('');\n\n // Try to show basic status from fallback JSON\n if (existsSync(fallbackPath)) {\n try {\n const fallbackData = JSON.parse(await readFile(fallbackPath, 'utf8'));\n console.log(chalk.bold('🐝 Hive Mind Status (from fallback memory)'));\n console.log(chalk.cyan(' Database:'), chalk.yellow('JSON fallback'));\n console.log(chalk.cyan(' Swarms:'), fallbackData.swarms?.length || 0);\n console.log(chalk.cyan(' Agents:'), fallbackData.agents?.length || 0);\n console.log('');\n console.log(chalk.gray('💡 For full SQLite features, install locally:'));\n console.log(chalk.gray(' npm install claude-flow'));\n return;\n } catch {\n // Fallback file exists but couldn't be read\n }\n }\n\n // Show minimal status\n console.log(chalk.bold('🐝 Hive Mind Status'));\n console.log(chalk.cyan(' Initialized:'), chalk.green('Yes'));\n console.log(chalk.cyan(' Database:'), chalk.yellow('SQLite (unavailable in npx mode)'));\n console.log('');\n console.log(chalk.gray('💡 For full functionality, install locally:'));\n console.log(chalk.gray(' npm install claude-flow'));\n return;\n }\n\n if (!existsSync(dbPath)) {\n // Check for fallback JSON database\n if (existsSync(fallbackPath)) {\n try {\n const fallbackData = JSON.parse(await readFile(fallbackPath, 'utf8'));\n console.log(chalk.bold('🐝 Hive Mind Status (JSON fallback mode)'));\n console.log(chalk.cyan(' Database:'), chalk.yellow('JSON fallback'));\n console.log(chalk.cyan(' Swarms:'), fallbackData.swarms?.length || 0);\n console.log(chalk.cyan(' Agents:'), fallbackData.agents?.length || 0);\n console.log(chalk.cyan(' Tasks:'), fallbackData.tasks?.length || 0);\n return;\n } catch {\n console.error(chalk.red('Error: Hive Mind not initialized'));\n console.log('Run \"claude-flow hive-mind init\" first');\n return;\n }\n }\n console.error(chalk.red('Error: Hive Mind not initialized'));\n console.log('Run \"claude-flow hive-mind init\" first');\n return;\n }\n\n // Use the metrics reader for real data\n const metricsReader = new HiveMindMetricsReader(dbPath);\n const swarms = metricsReader.getActiveSwarms();\n\n if (swarms.length === 0) {\n console.log(chalk.gray('No active swarms found'));\n metricsReader.close();\n return;\n }\n\n console.log(chalk.bold('\\n🐝 Active Hive Mind Swarms\\n'));\n\n for (const swarm of swarms) {\n console.log(chalk.yellow('═'.repeat(60)));\n console.log(chalk.cyan('Swarm:'), swarm.name);\n console.log(chalk.cyan('ID:'), swarm.id);\n console.log(chalk.cyan('Objective:'), swarm.objective);\n console.log(chalk.cyan('Queen Type:'), swarm.queen_type);\n console.log(chalk.cyan('Status:'), chalk.green(swarm.status));\n console.log(chalk.cyan('Created:'), new Date(swarm.created_at).toLocaleString());\n \n // Show real agent count\n console.log(chalk.cyan('Total Agents:'), swarm.agent_count || 0);\n\n console.log('\\n' + chalk.bold('Agents:'));\n\n // Group by role using real agent data\n const agents = swarm.agents || [];\n const queen = agents.find((a) => a.role === 'queen');\n const workers = agents.filter((a) => a.role === 'worker');\n\n if (queen) {\n console.log(' ' + chalk.magenta('👑 Queen:'), queen.name, chalk.gray(`(${queen.status})`));\n } else {\n console.log(' ' + chalk.gray('No queen assigned yet'));\n }\n\n console.log(' ' + chalk.blue('🐝 Workers:'));\n if (workers.length > 0) {\n workers.forEach((worker) => {\n const statusColor =\n worker.status === 'active' ? 'green' : worker.status === 'busy' ? 'yellow' : 'gray';\n console.log(` - ${worker.name} (${worker.type}) ${chalk[statusColor](worker.status)}`);\n });\n } else {\n console.log(' ' + chalk.gray('No workers spawned yet'));\n }\n\n // Get real task statistics\n const taskStats = swarm.task_metrics || {\n total: 0,\n completed: 0,\n in_progress: 0,\n pending: 0,\n failed: 0\n };\n\n console.log('\\n' + chalk.bold('Tasks:'));\n console.log(` Total: ${taskStats.total}`);\n console.log(` Completed: ${chalk.green(taskStats.completed || 0)}`);\n console.log(` In Progress: ${chalk.yellow(taskStats.in_progress || 0)}`);\n console.log(` Pending: ${chalk.gray(taskStats.pending || 0)}`);\n console.log(` ${chalk.bold('Completion:')} ${swarm.completion_percentage || 0}%`);\n\n // Show real memory count\n console.log('\\n' + chalk.bold('Collective Memory:'));\n console.log(` Entries: ${swarm.memory_count || 0}`);\n\n // Show real consensus count\n console.log('\\n' + chalk.bold('Consensus Decisions:'));\n console.log(` Total: ${swarm.consensus_count || 0}`);\n }\n\n console.log(chalk.yellow('═'.repeat(60)) + '\\n');\n\n metricsReader.close();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Show consensus decisions\n */\nasync function showConsensus(flags) {\n try {\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n const db = new Database(dbPath);\n\n const decisions = db\n .prepare(\n `\n SELECT cd.*, s.name as swarm_name\n FROM consensus_decisions cd\n JOIN swarms s ON cd.swarm_id = s.id\n ORDER BY cd.created_at DESC\n LIMIT 20\n `,\n )\n .all();\n\n if (decisions.length === 0) {\n console.log(chalk.gray('No consensus decisions found'));\n db.close();\n return;\n }\n\n console.log(chalk.bold('\\n🤝 Recent Consensus Decisions\\n'));\n\n decisions.forEach((decision) => {\n console.log(chalk.yellow('─'.repeat(50)));\n console.log(chalk.cyan('Swarm:'), decision.swarm_name);\n console.log(chalk.cyan('Topic:'), decision.topic);\n console.log(chalk.cyan('Decision:'), decision.decision);\n console.log(chalk.cyan('Algorithm:'), decision.algorithm);\n console.log(chalk.cyan('Confidence:'), `${(decision.confidence * 100).toFixed(1)}%`);\n console.log(chalk.cyan('Time:'), new Date(decision.created_at).toLocaleString());\n\n if (decision.votes) {\n const votes = JSON.parse(decision.votes);\n console.log(chalk.cyan('Votes:'));\n\n // Handle vote summary format (for/against/abstain/details)\n if (votes.for !== undefined || votes.against !== undefined || votes.abstain !== undefined) {\n console.log(` - for: ${votes.for || 0}`);\n console.log(` - against: ${votes.against || 0}`);\n console.log(` - abstain: ${votes.abstain || 0}`);\n\n // Display vote details properly if they exist\n if (votes.details && Array.isArray(votes.details)) {\n console.log(' - details:');\n votes.details.forEach((detail, index) => {\n if (typeof detail === 'object') {\n // Extract available fields\n const agent =\n detail.agentId ||\n detail.agent ||\n detail.id ||\n detail.name ||\n `agent-${index + 1}`;\n const vote = detail.vote || detail.choice || detail.decision || 'unknown';\n const reason = detail.reason || detail.justification || detail.rationale;\n\n // Build display string\n let displayString = ` ${index + 1}. Agent: ${agent}, Vote: ${vote}`;\n\n // Add reason if available\n if (reason && reason !== 'N/A' && reason !== '') {\n displayString += `, Reason: ${reason}`;\n }\n\n console.log(displayString);\n } else {\n console.log(` ${index + 1}. ${detail}`);\n }\n });\n }\n } else {\n // Handle individual agent votes format\n Object.entries(votes).forEach(([agent, vote]) => {\n console.log(` - ${agent}: ${vote}`);\n });\n }\n }\n });\n\n console.log(chalk.yellow('─'.repeat(50)) + '\\n');\n\n db.close();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Show performance metrics\n */\nasync function showMetrics(flags) {\n try {\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n const db = new Database(dbPath);\n\n // Get overall metrics\n const overallStats = db\n .prepare(\n `\n SELECT \n (SELECT COUNT(*) FROM swarms) as total_swarms,\n (SELECT COUNT(*) FROM agents) as total_agents,\n (SELECT COUNT(*) FROM tasks) as total_tasks,\n (SELECT COUNT(*) FROM tasks WHERE status = 'completed') as completed_tasks\n `,\n )\n .get();\n\n console.log(chalk.bold('\\n📊 Hive Mind Performance Metrics\\n'));\n\n // Get task status breakdown\n const taskBreakdown = db\n .prepare(\n `\n SELECT \n status,\n COUNT(*) as count\n FROM tasks\n GROUP BY status\n ORDER BY count DESC\n `,\n )\n .all();\n\n console.log(chalk.cyan('Overall Statistics:'));\n console.log(` Total Swarms: ${overallStats.total_swarms}`);\n console.log(` Total Agents: ${overallStats.total_agents}`);\n console.log(` Total Tasks: ${overallStats.total_tasks}`);\n console.log(` Completed Tasks: ${overallStats.completed_tasks}`);\n console.log(\n ` Success Rate: ${\n overallStats.total_tasks > 0\n ? ((overallStats.completed_tasks / overallStats.total_tasks) * 100).toFixed(1) + '%'\n : 'N/A'\n }`,\n );\n\n if (taskBreakdown.length > 0) {\n console.log('\\n' + chalk.cyan('Task Status Breakdown:'));\n taskBreakdown.forEach((status) => {\n const percentage =\n overallStats.total_tasks > 0\n ? ((status.count / overallStats.total_tasks) * 100).toFixed(1)\n : '0';\n const statusColor =\n status.status === 'completed'\n ? 'green'\n : status.status === 'in_progress'\n ? 'yellow'\n : status.status === 'failed'\n ? 'red'\n : 'gray';\n console.log(\n ` ${chalk[statusColor](status.status.charAt(0).toUpperCase() + status.status.slice(1))}: ${status.count} (${percentage}%)`,\n );\n });\n }\n\n // Get agent performance (check for completed_at column)\n let agentPerf = [];\n try {\n // Check if completed_at exists\n const hasCompletedAt = db\n .prepare(\n `\n SELECT COUNT(*) as count FROM pragma_table_info('tasks') \n WHERE name = 'completed_at'\n `,\n )\n .get();\n\n if (hasCompletedAt && hasCompletedAt.count > 0) {\n agentPerf = db\n .prepare(\n `\n SELECT \n a.name,\n a.type,\n COUNT(t.id) as tasks_assigned,\n SUM(CASE WHEN t.status = 'completed' THEN 1 ELSE 0 END) as tasks_completed,\n AVG(CASE WHEN t.completed_at IS NOT NULL \n THEN (julianday(t.completed_at) - julianday(t.created_at)) * 24 * 60 \n ELSE NULL END) as avg_completion_minutes\n FROM agents a\n LEFT JOIN tasks t ON a.id = t.agent_id\n GROUP BY a.id\n HAVING tasks_assigned > 0\n ORDER BY tasks_completed DESC\n LIMIT 10\n `,\n )\n .all();\n } else {\n // Simpler query without completed_at\n agentPerf = db\n .prepare(\n `\n SELECT \n a.name,\n a.type,\n COUNT(t.id) as tasks_assigned,\n SUM(CASE WHEN t.status = 'completed' THEN 1 ELSE 0 END) as tasks_completed,\n NULL as avg_completion_minutes\n FROM agents a\n LEFT JOIN tasks t ON a.id = t.agent_id\n GROUP BY a.id\n HAVING tasks_assigned > 0\n ORDER BY tasks_completed DESC\n LIMIT 10\n `,\n )\n .all();\n }\n } catch (error) {\n console.warn('Could not get agent performance:', error.message);\n }\n\n if (agentPerf.length > 0) {\n console.log('\\n' + chalk.cyan('Top Performing Agents:'));\n agentPerf.forEach((agent, index) => {\n const successRate =\n agent.tasks_assigned > 0\n ? ((agent.tasks_completed / agent.tasks_assigned) * 100).toFixed(1)\n : '0';\n console.log(` ${index + 1}. ${agent.name} (${agent.type})`);\n console.log(\n ` Tasks: ${agent.tasks_completed}/${agent.tasks_assigned} (${successRate}%)`,\n );\n if (agent.avg_completion_minutes) {\n console.log(` Avg Time: ${agent.avg_completion_minutes.toFixed(1)} minutes`);\n }\n });\n }\n\n // Get swarm performance\n const swarmPerf = db\n .prepare(\n `\n SELECT \n s.name,\n s.objective,\n (SELECT COUNT(*) FROM agents a WHERE a.swarm_id = s.id) as agent_count,\n (SELECT COUNT(*) FROM tasks t WHERE t.swarm_id = s.id) as task_count,\n (SELECT COUNT(*) FROM tasks t WHERE t.swarm_id = s.id AND t.status = 'completed') as completed_count,\n (SELECT COUNT(*) FROM collective_memory cm WHERE cm.swarm_id = s.id) as memory_entries,\n (SELECT COUNT(*) FROM consensus_decisions cd WHERE cd.swarm_id = s.id) as consensus_count\n FROM swarms s\n WHERE s.status = 'active'\n ORDER BY s.created_at DESC\n LIMIT 5\n `,\n )\n .all();\n\n if (swarmPerf.length > 0) {\n console.log('\\n' + chalk.cyan('Active Swarm Performance:'));\n swarmPerf.forEach((swarm) => {\n const successRate =\n swarm.task_count > 0\n ? ((swarm.completed_count / swarm.task_count) * 100).toFixed(1)\n : '0';\n console.log(`\\n ${chalk.yellow(swarm.name)}`);\n console.log(` Objective: ${swarm.objective.substring(0, 50)}...`);\n console.log(\n ` Agents: ${swarm.agent_count}, Tasks: ${swarm.completed_count}/${swarm.task_count} (${successRate}%)`,\n );\n console.log(\n ` Memory: ${swarm.memory_entries} entries, Consensus: ${swarm.consensus_count} decisions`,\n );\n });\n }\n\n // Get performance insights\n let avgTaskTime = { avg_minutes: null };\n try {\n // Check if completed_at exists\n const hasCompletedAt = db\n .prepare(\n `\n SELECT COUNT(*) as count FROM pragma_table_info('tasks') \n WHERE name = 'completed_at'\n `,\n )\n .get();\n\n if (hasCompletedAt && hasCompletedAt.count > 0) {\n avgTaskTime = db\n .prepare(\n `\n SELECT \n AVG(CASE WHEN completed_at IS NOT NULL \n THEN (julianday(completed_at) - julianday(created_at)) * 24 * 60 \n ELSE NULL END) as avg_minutes\n FROM tasks\n WHERE status = 'completed'\n `,\n )\n .get();\n }\n } catch (error) {\n console.warn('Could not calculate average task time:', error.message);\n }\n\n // Get agent type performance\n let agentTypePerf = [];\n try {\n // Check if completed_at exists\n const hasCompletedAt = db\n .prepare(\n `\n SELECT COUNT(*) as count FROM pragma_table_info('tasks') \n WHERE name = 'completed_at'\n `,\n )\n .get();\n\n if (hasCompletedAt && hasCompletedAt.count > 0) {\n agentTypePerf = db\n .prepare(\n `\n SELECT \n a.type,\n COUNT(t.id) as total_tasks,\n SUM(CASE WHEN t.status = 'completed' THEN 1 ELSE 0 END) as completed_tasks,\n AVG(CASE WHEN t.completed_at IS NOT NULL \n THEN (julianday(t.completed_at) - julianday(t.created_at)) * 24 * 60 \n ELSE NULL END) as avg_completion_minutes\n FROM agents a\n LEFT JOIN tasks t ON a.id = t.agent_id\n GROUP BY a.type\n HAVING total_tasks > 0\n ORDER BY completed_tasks DESC\n `,\n )\n .all();\n } else {\n // Simpler query without completed_at\n agentTypePerf = db\n .prepare(\n `\n SELECT \n a.type,\n COUNT(t.id) as total_tasks,\n SUM(CASE WHEN t.status = 'completed' THEN 1 ELSE 0 END) as completed_tasks,\n NULL as avg_completion_minutes\n FROM agents a\n LEFT JOIN tasks t ON a.id = t.agent_id\n GROUP BY a.type\n HAVING total_tasks > 0\n ORDER BY completed_tasks DESC\n `,\n )\n .all();\n }\n } catch (error) {\n console.warn('Could not get agent type performance:', error.message);\n }\n\n if (avgTaskTime.avg_minutes) {\n console.log('\\n' + chalk.cyan('Performance Insights:'));\n console.log(` Average Task Completion Time: ${avgTaskTime.avg_minutes.toFixed(1)} minutes`);\n\n if (agentTypePerf.length > 0) {\n console.log('\\n' + chalk.cyan('Agent Type Performance:'));\n agentTypePerf.forEach((type) => {\n const successRate =\n type.total_tasks > 0\n ? ((type.completed_tasks / type.total_tasks) * 100).toFixed(1)\n : '0';\n console.log(\n ` ${type.type.charAt(0).toUpperCase() + type.type.slice(1)}: ${type.completed_tasks}/${type.total_tasks} (${successRate}%)`,\n );\n if (type.avg_completion_minutes) {\n console.log(` Average time: ${type.avg_completion_minutes.toFixed(1)} minutes`);\n }\n });\n }\n }\n\n console.log('\\n');\n db.close();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Manage collective memory wizard\n */\nasync function manageMemoryWizard() {\n console.log(chalk.blue('\\n🧠 Collective Memory Management\\n'));\n\n const { action } = await inquirer.prompt([\n {\n type: 'list',\n name: 'action',\n message: 'What would you like to do with collective memory?',\n choices: [\n { name: '📋 View all memories', value: 'list' },\n { name: '🔍 Search memories', value: 'search' },\n { name: '💾 Store new memory', value: 'store' },\n { name: '📊 Memory statistics', value: 'stats' },\n { name: '🗑️ Clean old memories', value: 'clean' },\n { name: '📤 Export memory backup', value: 'export' },\n { name: '⬅️ Back to main menu', value: 'back' },\n ],\n },\n ]);\n\n switch (action) {\n case 'list':\n await listMemories();\n break;\n case 'search':\n await searchMemories();\n break;\n case 'store':\n await storeMemoryWizard();\n break;\n case 'stats':\n await showMemoryStats();\n break;\n case 'clean':\n await cleanMemories();\n break;\n case 'export':\n await exportMemoryBackup();\n break;\n case 'back':\n await hiveMindWizard();\n return;\n }\n\n // Ask if user wants to continue\n const { continue: continueAction } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'continue',\n message: 'Would you like to perform another memory operation?',\n default: true,\n },\n ]);\n\n if (continueAction) {\n await manageMemoryWizard();\n }\n}\n\n/**\n * Configure hive mind wizard\n */\nasync function configureWizard() {\n // TODO: Implement configuration wizard\n console.log(chalk.yellow('Configuration wizard coming soon...'));\n}\n\n/**\n * Main hive mind command handler\n */\nexport async function hiveMindCommand(args, flags) {\n const subcommand = args[0];\n const subArgs = args.slice(1);\n\n // Handle help flags\n if (\n !subcommand ||\n subcommand === '--help' ||\n subcommand === '-h' ||\n subcommand === 'help' ||\n flags.help\n ) {\n showHiveMindHelp();\n return;\n }\n\n // Warn about non-interactive environments for certain commands\n if ((subcommand === 'spawn' && (flags.claude || flags.spawn)) || subcommand === 'wizard') {\n warnNonInteractive('hive-mind ' + subcommand);\n }\n\n switch (subcommand) {\n case 'init':\n await initHiveMind(flags);\n break;\n\n case 'spawn':\n // Check for non-interactive mode FIRST (like alpha.83)\n if (flags['non-interactive'] || flags.nonInteractive) {\n // In non-interactive mode, skip wizard and use defaults\n if (subArgs.length === 0) {\n console.error(chalk.red('Error: Objective required in non-interactive mode'));\n console.log('Usage: claude-flow hive-mind spawn \"Your objective\" --non-interactive');\n return;\n }\n await spawnSwarm(subArgs, flags);\n } else if (flags.wizard || subArgs.length === 0) {\n await spawnSwarmWizard();\n } else {\n await spawnSwarm(subArgs, flags);\n }\n break;\n\n case 'status':\n await showStatus(flags);\n break;\n\n case 'sessions':\n await showSessions(flags);\n break;\n\n case 'resume':\n await resumeSession(subArgs, flags);\n break;\n\n case 'stop':\n await stopSession(subArgs, flags);\n break;\n\n case 'consensus':\n await showConsensus(flags);\n break;\n\n case 'memory':\n await manageMemoryWizard();\n break;\n\n case 'metrics':\n await showMetrics(flags);\n break;\n\n case 'wizard':\n await hiveMindWizard(flags);\n break;\n\n case 'help':\n case '--help':\n case '-h':\n showHiveMindHelp();\n break;\n\n default:\n console.error(chalk.red(`Unknown subcommand: ${subcommand}`));\n console.log('Run \"claude-flow hive-mind help\" for usage information');\n exit(1);\n }\n}\n\n/**\n * List all memories in the collective memory store\n */\nasync function listMemories() {\n try {\n console.log(chalk.blue('\\n📋 Collective Memory Store\\n'));\n\n // Read directly from hive.db collective_memory table\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n const db = new Database(dbPath);\n\n const memories = db\n .prepare(\n `\n SELECT cm.*, s.name as swarm_name\n FROM collective_memory cm\n LEFT JOIN swarms s ON cm.swarm_id = s.id\n ORDER BY cm.created_at DESC\n LIMIT 50\n `,\n )\n .all();\n\n db.close();\n\n if (!memories || memories.length === 0) {\n console.log(chalk.yellow('No memories found in the collective store.'));\n console.log(\n chalk.gray('Try storing some memories first using the \"💾 Store new memory\" option.'),\n );\n return;\n }\n\n console.log(chalk.gray(`Found ${memories.length} memories in the collective store:\\n`));\n\n memories.forEach((memory, index) => {\n console.log(chalk.cyan(`${index + 1}. ${memory.key}`));\n console.log(` Swarm: ${memory.swarm_name || memory.swarm_id}`);\n console.log(` Type: ${memory.type || 'knowledge'}`);\n console.log(` Created: ${new Date(memory.created_at).toLocaleString()}`);\n console.log(` Created by: ${memory.created_by || 'system'}`);\n \n // Parse and display value\n let displayValue = memory.value;\n try {\n const parsed = JSON.parse(memory.value);\n displayValue = JSON.stringify(parsed);\n } catch {\n // Keep as string\n }\n \n if (displayValue.length > 100) {\n console.log(` Value: ${displayValue.substring(0, 100)}...`);\n } else {\n console.log(` Value: ${displayValue}`);\n }\n \n if (memory.confidence !== null && memory.confidence !== 1) {\n console.log(` Confidence: ${(memory.confidence * 100).toFixed(1)}%`);\n }\n \n console.log('');\n });\n } catch (error) {\n console.error(chalk.red('Error listing memories:'), error.message);\n console.log(chalk.gray('This might be because no memories have been stored yet.'));\n }\n}\n\n/**\n * Search memories by keyword\n */\nasync function searchMemories() {\n try {\n const { searchTerm } = await inquirer.prompt([\n {\n type: 'input',\n name: 'searchTerm',\n message: 'Enter search term:',\n validate: (input) => input.length > 0,\n },\n ]);\n\n console.log(chalk.blue(`\\n🔍 Searching for: \"${searchTerm}\"\\n`));\n\n // Search directly in hive.db collective_memory table\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n const db = new Database(dbPath);\n\n const searchPattern = `%${searchTerm}%`;\n const memories = db\n .prepare(\n `\n SELECT cm.*, s.name as swarm_name\n FROM collective_memory cm\n LEFT JOIN swarms s ON cm.swarm_id = s.id\n WHERE cm.key LIKE ? OR cm.value LIKE ? OR cm.type LIKE ?\n ORDER BY cm.created_at DESC\n LIMIT 50\n `,\n )\n .all(searchPattern, searchPattern, searchPattern);\n\n db.close();\n\n if (!memories || memories.length === 0) {\n console.log(chalk.yellow('No memories found matching your search.'));\n return;\n }\n\n console.log(chalk.gray(`Found ${memories.length} memories matching \"${searchTerm}\":\\n`));\n\n memories.forEach((memory, index) => {\n console.log(chalk.green(`${index + 1}. ${memory.key}`));\n console.log(` Swarm: ${memory.swarm_name || memory.swarm_id}`);\n console.log(` Type: ${memory.type || 'knowledge'}`);\n console.log(` Created: ${new Date(memory.created_at).toLocaleString()}`);\n \n // Parse and display value with highlighting\n let displayValue = memory.value;\n try {\n const parsed = JSON.parse(memory.value);\n displayValue = JSON.stringify(parsed, null, 2);\n } catch {\n // Keep as string\n }\n \n console.log(` Value: ${displayValue}`);\n console.log('');\n });\n } catch (error) {\n console.error(chalk.red('Error searching memories:'), error.message);\n }\n}\n\n/**\n * Store new memory wizard\n */\nasync function storeMemoryWizard() {\n try {\n const answers = await inquirer.prompt([\n {\n type: 'input',\n name: 'key',\n message: 'Memory key (identifier):',\n validate: (input) => input.length > 0,\n },\n {\n type: 'list',\n name: 'category',\n message: 'Memory category:',\n choices: [\n 'consensus',\n 'decision',\n 'pattern',\n 'learning',\n 'coordination',\n 'performance',\n 'configuration',\n 'general',\n ],\n },\n {\n type: 'editor',\n name: 'value',\n message: 'Memory content (JSON or text):',\n },\n ]);\n\n const mcpWrapper = await getMcpWrapper();\n let memoryValue;\n\n // Try to parse as JSON, fall back to string\n try {\n memoryValue = JSON.parse(answers.value);\n } catch {\n memoryValue = answers.value;\n }\n\n await mcpWrapper.storeMemory('hive-mind', answers.key, memoryValue, answers.category);\n\n console.log(chalk.green(`\\n✅ Memory stored successfully!`));\n console.log(`Key: ${answers.key}`);\n console.log(`Category: ${answers.category}`);\n } catch (error) {\n console.error(chalk.red('Error storing memory:'), error.message);\n }\n}\n\n/**\n * Show memory statistics\n */\nasync function showMemoryStats() {\n try {\n console.log(chalk.blue('\\n📊 Memory Statistics\\n'));\n\n const mcpWrapper = await getMcpWrapper();\n\n // Search for all memories with an empty pattern to get everything\n const searchResult = await mcpWrapper.searchMemory('hive-mind', '');\n\n // Handle different possible response structures\n let memories = [];\n if (searchResult && Array.isArray(searchResult.results)) {\n memories = searchResult.results;\n } else if (searchResult && Array.isArray(searchResult)) {\n memories = searchResult;\n } else if (searchResult && searchResult.data && Array.isArray(searchResult.data)) {\n memories = searchResult.data;\n }\n\n if (!memories || memories.length === 0) {\n console.log(chalk.yellow('No memories found.'));\n console.log(chalk.gray('Use \"Store new memory\" to create your first memory.'));\n return;\n }\n\n // Calculate statistics\n const stats = {\n total: memories.length,\n categories: {},\n oldestDate: null,\n newestDate: null,\n totalSize: 0,\n };\n\n memories.forEach((memory) => {\n // Count by category\n const category = memory.category || memory.type || 'general';\n stats.categories[category] = (stats.categories[category] || 0) + 1;\n\n // Track dates\n const date = new Date(memory.timestamp || Date.now());\n if (!stats.oldestDate || date < stats.oldestDate) {\n stats.oldestDate = date;\n }\n if (!stats.newestDate || date > stats.newestDate) {\n stats.newestDate = date;\n }\n\n // Estimate size\n stats.totalSize += JSON.stringify(memory).length;\n });\n\n console.log(chalk.cyan('Total memories:'), stats.total);\n console.log(chalk.cyan('Estimated size:'), `${(stats.totalSize / 1024).toFixed(2)} KB`);\n console.log(\n chalk.cyan('Date range:'),\n `${stats.oldestDate?.toLocaleDateString()} - ${stats.newestDate?.toLocaleDateString()}`,\n );\n\n console.log(chalk.cyan('\\nBy category:'));\n Object.entries(stats.categories).forEach(([category, count]) => {\n console.log(` ${category}: ${count}`);\n });\n } catch (error) {\n console.error(chalk.red('Error getting memory stats:'), error.message);\n }\n}\n\n/**\n * Clean old memories\n */\nasync function cleanMemories() {\n try {\n const { days } = await inquirer.prompt([\n {\n type: 'number',\n name: 'days',\n message: 'Remove memories older than how many days?',\n default: 30,\n validate: (input) => input > 0,\n },\n ]);\n\n const { confirm } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'confirm',\n message: `Are you sure you want to delete memories older than ${days} days?`,\n default: false,\n },\n ]);\n\n if (!confirm) {\n console.log(chalk.yellow('Operation cancelled.'));\n return;\n }\n\n const mcpWrapper = await getMcpWrapper();\n\n // Get all memories first\n const searchResult = await mcpWrapper.searchMemory('hive-mind', '');\n\n // Handle different possible response structures\n let memories = [];\n if (searchResult && Array.isArray(searchResult.results)) {\n memories = searchResult.results;\n } else if (searchResult && Array.isArray(searchResult)) {\n memories = searchResult;\n } else if (searchResult && searchResult.data && Array.isArray(searchResult.data)) {\n memories = searchResult.data;\n }\n\n const cutoffDate = new Date();\n cutoffDate.setDate(cutoffDate.getDate() - days);\n\n // Filter memories older than cutoff date\n const oldMemories = memories.filter((memory) => {\n const memoryDate = new Date(memory.timestamp || 0);\n return memoryDate < cutoffDate;\n });\n\n if (oldMemories.length === 0) {\n console.log(chalk.yellow('\\n🎉 No old memories found to clean.'));\n return;\n }\n\n console.log(chalk.green(`\\n✅ Found ${oldMemories.length} old memories to clean.`));\n console.log(chalk.gray('Note: Individual memory deletion not yet implemented in MCPWrapper.'));\n console.log(chalk.gray('Consider implementing batch deletion or memory lifecycle management.'));\n } catch (error) {\n console.error(chalk.red('Error cleaning memories:'), error.message);\n }\n}\n\n/**\n * Export memory backup\n */\nasync function exportMemoryBackup() {\n try {\n const { filename } = await inquirer.prompt([\n {\n type: 'input',\n name: 'filename',\n message: 'Export filename:',\n default: `hive-mind-memory-backup-${new Date().toISOString().split('T')[0]}.json`,\n },\n ]);\n\n const mcpWrapper = await getMcpWrapper();\n\n // Get all memories using search\n const searchResult = await mcpWrapper.searchMemory('hive-mind', '');\n\n // Handle different possible response structures\n let memories = [];\n if (searchResult && Array.isArray(searchResult.results)) {\n memories = searchResult.results;\n } else if (searchResult && Array.isArray(searchResult)) {\n memories = searchResult;\n } else if (searchResult && searchResult.data && Array.isArray(searchResult.data)) {\n memories = searchResult.data;\n }\n\n const backup = {\n exportDate: new Date().toISOString(),\n version: '1.0',\n totalMemories: memories.length,\n namespace: 'hive-mind',\n memories: memories,\n };\n\n const fs = await import('fs');\n fs.writeFileSync(filename, JSON.stringify(backup, null, 2));\n\n console.log(chalk.green(`\\n✅ Memory backup exported to: ${filename}`));\n console.log(chalk.cyan(`Exported ${memories.length} memories`));\n } catch (error) {\n console.error(chalk.red('Error exporting memory backup:'), error.message);\n }\n}\n\n/**\n * Get active session ID for a swarm\n */\nasync function getActiveSessionId(swarmId) {\n const sessionManager = new HiveMindSessionManager();\n try {\n const sessions = await sessionManager.getActiveSessions();\n const activeSession = sessions.find(s => s.swarm_id === swarmId && s.status === 'active');\n return activeSession ? activeSession.id : null;\n } finally {\n sessionManager.close();\n }\n}\n\n/**\n * Spawn Claude Code with Hive Mind coordination instructions\n */\nasync function spawnClaudeCodeInstances(swarmId, swarmName, objective, workers, flags) {\n console.log('\\n' + chalk.bold('🚀 Launching Claude Code with Hive Mind Coordination'));\n console.log(chalk.gray('─'.repeat(60)));\n\n const spinner = ora('Preparing Hive Mind coordination prompt...').start();\n\n try {\n // Generate comprehensive Hive Mind prompt\n const workerGroups = groupWorkersByType(workers);\n const hiveMindPrompt = generateHiveMindPrompt(\n swarmId,\n swarmName,\n objective,\n workers,\n workerGroups,\n flags,\n );\n\n spinner.succeed('Hive Mind coordination prompt ready!');\n\n // Display coordination summary\n console.log('\\n' + chalk.bold('🧠 Hive Mind Configuration'));\n console.log(chalk.gray('─'.repeat(60)));\n console.log(chalk.cyan('Swarm ID:'), swarmId);\n console.log(chalk.cyan('Objective:'), objective);\n console.log(chalk.cyan('Queen Type:'), flags.queenType || 'strategic');\n console.log(chalk.cyan('Worker Count:'), workers.length);\n console.log(chalk.cyan('Worker Types:'), Object.keys(workerGroups).join(', '));\n console.log(chalk.cyan('Consensus Algorithm:'), flags.consensus || 'majority');\n console.log(chalk.cyan('MCP Tools:'), 'Full Claude-Flow integration enabled');\n\n try {\n // ALWAYS save the prompt file first (fix for issue #330)\n // Ensure sessions directory exists\n const sessionsDir = path.join('.hive-mind', 'sessions');\n await mkdirAsync(sessionsDir, { recursive: true });\n\n const promptFile = path.join(sessionsDir, `hive-mind-prompt-${swarmId}.txt`);\n await writeFile(promptFile, hiveMindPrompt, 'utf8');\n console.log(chalk.green(`\\n✓ Hive Mind prompt saved to: ${promptFile}`));\n\n // Check if claude command exists\n const { spawn: childSpawn, execSync } = await import('child_process');\n let claudeAvailable = false;\n\n try {\n execSync('which claude', { stdio: 'ignore' });\n claudeAvailable = true;\n } catch {\n console.log(chalk.yellow('\\n⚠️ Claude Code CLI not found in PATH'));\n console.log(chalk.gray('Install it with: npm install -g @anthropic-ai/claude-code'));\n console.log(chalk.gray('\\nFalling back to displaying instructions...'));\n }\n\n if (claudeAvailable && !flags.dryRun) {\n // Inject memory coordination protocol into CLAUDE.md\n try {\n const { injectMemoryProtocol, enhanceHiveMindPrompt } = await import('./inject-memory-protocol.js');\n await injectMemoryProtocol();\n \n // Enhance the prompt with memory coordination instructions\n hiveMindPrompt = enhanceHiveMindPrompt(hiveMindPrompt, workers);\n console.log(chalk.green('📝 Memory coordination protocol injected into CLAUDE.md'));\n } catch (err) {\n // If injection module not available, continue with original prompt\n console.log(chalk.yellow('⚠️ Memory protocol injection not available, using standard prompt'));\n }\n \n // Check if we should run in non-interactive mode\n // Respect --non-interactive flag regardless of --claude\n const isNonInteractive = flags['non-interactive'] || flags.nonInteractive;\n \n // Build arguments in correct order: flags first, then prompt\n const claudeArgs = [];\n \n // Add non-interactive flags FIRST if needed\n if (isNonInteractive) {\n claudeArgs.push('-p'); // Print mode\n claudeArgs.push('--output-format', 'stream-json'); // JSON streaming \n claudeArgs.push('--verbose'); // Verbose output\n console.log(chalk.cyan('🤖 Running in non-interactive mode'));\n }\n\n // Add auto-permission flag BEFORE the prompt\n if (flags['dangerously-skip-permissions'] !== false && !flags['no-auto-permissions']) {\n claudeArgs.push('--dangerously-skip-permissions');\n if (!isNonInteractive) {\n console.log(\n chalk.yellow(\n '🔓 Using --dangerously-skip-permissions by default for seamless hive-mind execution',\n ),\n );\n }\n }\n \n // Add the prompt as the LAST argument\n claudeArgs.push(hiveMindPrompt);\n\n // Spawn claude with properly ordered arguments\n const claudeProcess = childSpawn('claude', claudeArgs, {\n stdio: 'inherit',\n shell: false,\n });\n\n // Track child process PID in session\n const sessionManager = new HiveMindSessionManager();\n const sessionId = await getActiveSessionId(swarmId);\n if (sessionId && claudeProcess.pid) {\n sessionManager.addChildPid(sessionId, claudeProcess.pid);\n }\n\n // Set up SIGINT handler for automatic session pausing\n let isExiting = false;\n const sigintHandler = async () => {\n if (isExiting) return;\n isExiting = true;\n\n console.log('\\n\\n' + chalk.yellow('⏸️ Pausing session and terminating Claude Code...'));\n \n try {\n // Terminate Claude Code process\n if (claudeProcess && !claudeProcess.killed) {\n claudeProcess.kill('SIGTERM');\n }\n\n // Save checkpoint and pause session\n if (sessionId) {\n const checkpointData = {\n timestamp: new Date().toISOString(),\n swarmId,\n objective,\n status: 'paused_by_user',\n reason: 'User pressed Ctrl+C during Claude Code execution',\n claudePid: claudeProcess.pid,\n };\n \n await sessionManager.saveCheckpoint(sessionId, 'auto-pause-claude', checkpointData);\n await sessionManager.pauseSession(sessionId);\n \n console.log(chalk.green('✓') + ' Session paused successfully');\n console.log(chalk.cyan('\\nTo resume this session, run:'));\n console.log(chalk.bold(` claude-flow hive-mind resume ${sessionId}`));\n }\n \n sessionManager.close();\n process.exit(0);\n } catch (error) {\n console.error(chalk.red('Error pausing session:'), error.message);\n sessionManager.close();\n process.exit(1);\n }\n };\n\n // Register SIGINT handler\n process.on('SIGINT', sigintHandler);\n process.on('SIGTERM', sigintHandler);\n\n // Handle stdout\n if (claudeProcess.stdout) {\n claudeProcess.stdout.on('data', (data) => {\n console.log(data.toString());\n });\n }\n\n // Handle stderr\n if (claudeProcess.stderr) {\n claudeProcess.stderr.on('data', (data) => {\n console.error(chalk.red(data.toString()));\n });\n }\n\n // Handle process exit\n claudeProcess.on('exit', (code) => {\n // Remove child PID from session\n if (sessionId && claudeProcess.pid) {\n sessionManager.removeChildPid(sessionId, claudeProcess.pid);\n sessionManager.close();\n }\n\n if (code === 0) {\n console.log(chalk.green('\\n✓ Claude Code completed successfully'));\n } else if (code !== null) {\n console.log(chalk.red(`\\n✗ Claude Code exited with code ${code}`));\n }\n });\n\n console.log(chalk.green('\\n✓ Claude Code launched with Hive Mind coordination'));\n console.log(chalk.blue(' The Queen coordinator will orchestrate all worker agents'));\n console.log(\n chalk.blue(' Use MCP tools for collective intelligence and task distribution'),\n );\n console.log(chalk.gray(` Prompt file saved at: ${promptFile}`));\n } else if (flags.dryRun) {\n console.log(chalk.blue('\\nDry run - would execute Claude Code with prompt:'));\n console.log(chalk.gray('Prompt length:'), hiveMindPrompt.length, 'characters');\n console.log(chalk.gray('\\nFirst 500 characters of prompt:'));\n console.log(chalk.yellow(hiveMindPrompt.substring(0, 500) + '...'));\n console.log(chalk.gray(`\\nFull prompt saved to: ${promptFile}`));\n } else {\n // Claude not available - show instructions with already saved prompt\n console.log(chalk.yellow('\\n📋 Manual Execution Instructions:'));\n console.log(chalk.gray('─'.repeat(50)));\n console.log(chalk.gray('1. Install Claude Code:'));\n console.log(chalk.green(' npm install -g @anthropic-ai/claude-code'));\n console.log(chalk.gray('\\n2. Run with the saved prompt:'));\n console.log(chalk.green(` claude < ${promptFile}`));\n console.log(chalk.gray('\\n3. Or copy the prompt manually:'));\n console.log(chalk.green(` cat ${promptFile} | claude`));\n console.log(chalk.gray('\\n4. With auto-permissions:'));\n console.log(chalk.green(` claude --dangerously-skip-permissions < ${promptFile}`));\n }\n } catch (error) {\n console.error(chalk.red('\\nFailed to launch Claude Code:'), error.message);\n\n // Save prompt as fallback\n const promptFile = `hive-mind-prompt-${swarmId}-fallback.txt`;\n await writeFile(promptFile, hiveMindPrompt, 'utf8');\n console.log(chalk.green(`\\n✓ Prompt saved to: ${promptFile}`));\n console.log(chalk.yellow('\\nYou can run Claude Code manually with the saved prompt'));\n }\n\n console.log('\\n' + chalk.bold('💡 Pro Tips:'));\n console.log(chalk.gray('─'.repeat(30)));\n console.log('• Use --auto-spawn to launch instances automatically');\n console.log('• Add --verbose for detailed coordination context');\n console.log('• Monitor with: claude-flow hive-mind status');\n console.log('• Share memories: mcp__ruv-swarm__memory_usage');\n } catch (error) {\n spinner.fail('Failed to prepare Claude Code coordination');\n console.error(chalk.red('Error:'), error.message);\n }\n}\n\n/**\n * Generate comprehensive Hive Mind prompt for Claude Code\n */\nfunction generateHiveMindPrompt(swarmId, swarmName, objective, workers, workerGroups, flags) {\n console.log(chalk.cyan(`\\n🔍 generateHiveMindPrompt received objective: \"${objective}\"`));\n const currentTime = new Date().toISOString();\n const workerTypes = Object.keys(workerGroups);\n const queenType = flags.queenType || 'strategic';\n const consensusAlgorithm = flags.consensus || 'majority';\n\n return `🧠 HIVE MIND COLLECTIVE INTELLIGENCE SYSTEM\n═══════════════════════════════════════════════\n\nYou are the Queen coordinator of a Hive Mind swarm with collective intelligence capabilities.\n\nHIVE MIND CONFIGURATION:\n📌 Swarm ID: ${swarmId}\n📌 Swarm Name: ${swarmName}\n🎯 Objective: ${objective}\n👑 Queen Type: ${queenType}\n🐝 Worker Count: ${workers.length}\n🤝 Consensus Algorithm: ${consensusAlgorithm}\n⏰ Initialized: ${currentTime}\n\nWORKER DISTRIBUTION:\n${workerTypes.map((type) => `• ${type}: ${workerGroups[type].length} agents`).join('\\n')}\n\n🔧 AVAILABLE MCP TOOLS FOR HIVE MIND COORDINATION:\n\n1️⃣ **COLLECTIVE INTELLIGENCE**\n mcp__claude-flow__consensus_vote - Democratic decision making\n mcp__claude-flow__memory_share - Share knowledge across the hive\n mcp__claude-flow__neural_sync - Synchronize neural patterns\n mcp__claude-flow__swarm_think - Collective problem solving\n\n2️⃣ **QUEEN COORDINATION**\n mcp__claude-flow__queen_command - Issue directives to workers\n mcp__claude-flow__queen_monitor - Monitor swarm health\n mcp__claude-flow__queen_delegate - Delegate complex tasks\n mcp__claude-flow__queen_aggregate - Aggregate worker results\n\n3️⃣ **WORKER MANAGEMENT**\n mcp__claude-flow__agent_spawn - Create specialized workers\n mcp__claude-flow__agent_assign - Assign tasks to workers\n mcp__claude-flow__agent_communicate - Inter-agent communication\n mcp__claude-flow__agent_metrics - Track worker performance\n\n4️⃣ **TASK ORCHESTRATION**\n mcp__claude-flow__task_create - Create hierarchical tasks\n mcp__claude-flow__task_distribute - Distribute work efficiently\n mcp__claude-flow__task_monitor - Track task progress\n mcp__claude-flow__task_aggregate - Combine task results\n\n5️⃣ **MEMORY & LEARNING**\n mcp__claude-flow__memory_store - Store collective knowledge\n mcp__claude-flow__memory_retrieve - Access shared memory\n mcp__claude-flow__neural_train - Learn from experiences\n mcp__claude-flow__pattern_recognize - Identify patterns\n\n📋 HIVE MIND EXECUTION PROTOCOL:\n\nAs the Queen coordinator, you must:\n\n1. **INITIALIZE THE HIVE** (CRITICAL: Use Claude Code's Task Tool for Agents):\n \n Step 1: Optional MCP Coordination Setup (Single Message):\n [MCP Tools - Coordination Only]:\n ${workerTypes.map((type) => ` mcp__claude-flow__agent_spawn { \"type\": \"${type}\", \"count\": ${workerGroups[type].length} }`).join('\\n')}\n mcp__claude-flow__memory_store { \"key\": \"hive/objective\", \"value\": \"${objective}\" }\n mcp__claude-flow__memory_store { \"key\": \"hive/queen\", \"value\": \"${queenType}\" }\n mcp__claude-flow__swarm_think { \"topic\": \"initial_strategy\" }\n \n Step 2: REQUIRED - Spawn ACTUAL Agents with Claude Code's Task Tool (Single Message):\n [Claude Code Task Tool - CONCURRENT Agent Execution]:\n ${workerTypes.map((type) => ` Task(\"${type.charAt(0).toUpperCase() + type.slice(1)} Agent\", \"You are a ${type} in the hive. Coordinate via hooks. ${getWorkerTypeInstructions(type).split('\\n')[0]}\", \"${type}\")`).join('\\n')}\n \n Step 3: Batch ALL Todos Together (Single TodoWrite Call):\n TodoWrite { \"todos\": [\n { \"id\": \"1\", \"content\": \"Initialize hive mind collective\", \"status\": \"in_progress\", \"priority\": \"high\" },\n { \"id\": \"2\", \"content\": \"Establish consensus protocols\", \"status\": \"pending\", \"priority\": \"high\" },\n { \"id\": \"3\", \"content\": \"Distribute initial tasks to workers\", \"status\": \"pending\", \"priority\": \"high\" },\n { \"id\": \"4\", \"content\": \"Set up collective memory\", \"status\": \"pending\", \"priority\": \"high\" },\n { \"id\": \"5\", \"content\": \"Monitor worker health\", \"status\": \"pending\", \"priority\": \"medium\" },\n { \"id\": \"6\", \"content\": \"Aggregate worker outputs\", \"status\": \"pending\", \"priority\": \"medium\" },\n { \"id\": \"7\", \"content\": \"Learn from patterns\", \"status\": \"pending\", \"priority\": \"low\" },\n { \"id\": \"8\", \"content\": \"Optimize performance\", \"status\": \"pending\", \"priority\": \"low\" }\n ] }\n\n2. **ESTABLISH COLLECTIVE INTELLIGENCE**:\n - Use consensus_vote for major decisions\n - Share all discoveries via memory_share\n - Synchronize learning with neural_sync\n - Coordinate strategy with swarm_think\n\n3. **QUEEN LEADERSHIP PATTERNS**:\n ${\n queenType === 'strategic'\n ? `\n - Focus on high-level planning and coordination\n - Delegate implementation details to workers\n - Monitor overall progress and adjust strategy\n - Make executive decisions when consensus fails`\n : ''\n }\n ${\n queenType === 'tactical'\n ? `\n - Manage detailed task breakdowns and assignments\n - Closely monitor worker progress and efficiency\n - Optimize resource allocation and load balancing\n - Intervene directly when workers need guidance`\n : ''\n }\n ${\n queenType === 'adaptive'\n ? `\n - Learn from swarm performance and adapt strategies\n - Experiment with different coordination patterns\n - Use neural training to improve over time\n - Balance between strategic and tactical approaches`\n : ''\n }\n\n4. **WORKER COORDINATION**:\n - Spawn workers based on task requirements\n - Assign tasks according to worker specializations\n - Enable peer-to-peer communication for collaboration\n - Monitor and rebalance workloads as needed\n\n5. **CONSENSUS MECHANISMS**:\n ${consensusAlgorithm === 'majority' ? '- Decisions require >50% worker agreement' : ''}\n ${consensusAlgorithm === 'unanimous' ? '- All workers must agree for major decisions' : ''}\n ${consensusAlgorithm === 'weighted' ? '- Worker votes weighted by expertise and performance' : ''}\n ${consensusAlgorithm === 'quorum' ? '- Decisions require 2/3 worker participation' : ''}\n\n6. **COLLECTIVE MEMORY**:\n - Store all important decisions in shared memory\n - Tag memories with worker IDs and timestamps\n - Use memory namespaces: hive/, queen/, workers/, tasks/\n - Implement memory consensus for critical data\n\n7. **PERFORMANCE OPTIMIZATION**:\n - Monitor swarm metrics continuously\n - Identify and resolve bottlenecks\n - Train neural networks on successful patterns\n - Scale worker count based on workload\n\n💡 HIVE MIND BEST PRACTICES:\n\n✅ ALWAYS use BatchTool for parallel operations\n✅ Store decisions in collective memory immediately\n✅ Use consensus for critical path decisions\n✅ Monitor worker health and reassign if needed\n✅ Learn from failures and adapt strategies\n✅ Maintain constant inter-agent communication\n✅ Aggregate results before final delivery\n\n❌ NEVER make unilateral decisions without consensus\n❌ NEVER let workers operate in isolation\n❌ NEVER ignore performance metrics\n❌ NEVER skip memory synchronization\n❌ NEVER abandon failing workers\n\n🎯 OBJECTIVE EXECUTION STRATEGY:\n\nFor the objective: \"${objective}\"\n\n1. Break down into major phases using swarm_think\n2. Create specialized worker teams for each phase\n3. Establish success criteria and checkpoints\n4. Implement feedback loops and adaptation\n5. Aggregate and synthesize all worker outputs\n6. Deliver comprehensive solution with consensus\n\n⚡ CRITICAL: CONCURRENT EXECUTION WITH CLAUDE CODE'S TASK TOOL:\n\nThe Hive Mind MUST use Claude Code's Task tool for actual agent execution:\n\n✅ CORRECT Pattern:\n[Single Message - All Agents Spawned Concurrently]:\n Task(\"Researcher\", \"Research patterns and best practices...\", \"researcher\")\n Task(\"Coder\", \"Implement core features...\", \"coder\")\n Task(\"Tester\", \"Create comprehensive tests...\", \"tester\")\n Task(\"Analyst\", \"Analyze performance metrics...\", \"analyst\")\n TodoWrite { todos: [8-10 todos ALL in ONE call] }\n\n❌ WRONG Pattern:\nMessage 1: Task(\"agent1\", ...)\nMessage 2: Task(\"agent2\", ...)\nMessage 3: TodoWrite { single todo }\n// This breaks parallel coordination!\n\nRemember:\n- Use Claude Code's Task tool to spawn ALL agents in ONE message\n- MCP tools are ONLY for coordination setup, not agent execution\n- Batch ALL TodoWrite operations (5-10+ todos minimum)\n- Execute ALL file operations concurrently\n- Store multiple memories simultaneously\n\n🚀 BEGIN HIVE MIND EXECUTION:\n\nInitialize the swarm now with the configuration above. Use your collective intelligence to solve the objective efficiently. The Queen must coordinate, workers must collaborate, and the hive must think as one.\n\nRemember: You are not just coordinating agents - you are orchestrating a collective intelligence that is greater than the sum of its parts.`;\n}\n\n/**\n * Generate comprehensive coordination instructions for Claude Code instances\n */\nfunction generateCoordinationInstructions(swarmId, swarmName, objective, workers) {\n return {\n swarmId,\n swarmName,\n objective,\n hiveMindEndpoint: 'ws://localhost:3000/hive-mind',\n mcpTools: [\n 'mcp__ruv-swarm__memory_usage',\n 'mcp__ruv-swarm__swarm_monitor',\n 'mcp__ruv-swarm__task_orchestrate',\n 'mcp__ruv-swarm__neural_train',\n 'mcp__ruv-swarm__consensus_vote',\n 'mcp__ruv-swarm__agent_spawn',\n 'mcp__ruv-swarm__swarm_status',\n ],\n coordinationProtocol: {\n memoryNamespace: `hive-mind-${swarmId}`,\n consensusThreshold: 0.7,\n taskUpdateInterval: 30000,\n healthCheckInterval: 60000,\n },\n workerCapabilities: workers.map((w) => ({\n id: w.id,\n type: w.type,\n capabilities: JSON.parse(w.capabilities),\n })),\n };\n}\n\n/**\n * Group workers by type for specialized spawning\n */\nfunction groupWorkersByType(workers) {\n return workers.reduce((groups, worker) => {\n if (!groups[worker.type]) {\n groups[worker.type] = [];\n }\n groups[worker.type].push(worker);\n return groups;\n }, {});\n}\n\n/**\n * Create Claude Code spawn command with coordination context\n */\nfunction createClaudeCodeSpawnCommand(\n swarmId,\n swarmName,\n objective,\n workerType,\n typeWorkers,\n instructions,\n) {\n const context = `You are a ${workerType} agent in the \"${swarmName}\" Hive Mind swarm.\n\n🎯 MISSION: ${objective}\n\n🐝 SWARM COORDINATION:\n- Swarm ID: ${swarmId}\n- Your Role: ${workerType.toUpperCase()} specialist\n- Team Size: ${typeWorkers.length} ${workerType}(s)\n- Coordination: Hive Mind collective intelligence\n\n🧠 MANDATORY COORDINATION PROTOCOL:\n1. BEFORE starting work:\n mcp__ruv-swarm__memory_usage {\"action\": \"retrieve\", \"key\": \"hive-mind-${swarmId}/status\"}\n mcp__ruv-swarm__swarm_status {\"swarmId\": \"${swarmId}\"}\n\n2. DURING work (after each major step):\n mcp__ruv-swarm__memory_usage {\"action\": \"store\", \"key\": \"hive-mind-${swarmId}/${workerType}/progress\", \"value\": {\"step\": \"X\", \"status\": \"Y\", \"findings\": \"Z\"}}\n mcp__ruv-swarm__task_orchestrate {\"swarmId\": \"${swarmId}\", \"update\": {\"agentId\": \"your-id\", \"progress\": \"details\"}}\n\n3. FOR decisions requiring consensus:\n mcp__ruv-swarm__consensus_vote {\"swarmId\": \"${swarmId}\", \"topic\": \"decision topic\", \"vote\": \"your choice\", \"rationale\": \"reasoning\"}\n\n4. WHEN sharing insights:\n mcp__ruv-swarm__memory_usage {\"action\": \"store\", \"key\": \"hive-mind-${swarmId}/insights/${workerType}\", \"value\": {\"insight\": \"your discovery\", \"impact\": \"significance\"}}\n\n5. BEFORE completing work:\n mcp__ruv-swarm__neural_train {\"swarmId\": \"${swarmId}\", \"experience\": {\"what\": \"learned\", \"outcome\": \"result\"}}\n\n🔧 SPECIALIZED CAPABILITIES:\n${getWorkerTypeInstructions(workerType)}\n\n🤝 COORDINATION RULES:\n- Share ALL discoveries via memory_usage\n- Vote on critical decisions using consensus_vote\n- Update progress every 15 minutes via task_orchestrate\n- Monitor other agents via swarm_status\n- Learn from patterns via neural_train\n\nRemember: You are part of a COLLECTIVE INTELLIGENCE. Your individual success depends on swarm coordination!`;\n\n const command = `claude code --context \"${context.replace(/\"/g, '\\\\\"')}\"`;\n\n return {\n title: `${workerType.toUpperCase()} Agent (${typeWorkers.length} instance${typeWorkers.length > 1 ? 's' : ''})`,\n command,\n context,\n workerType,\n count: typeWorkers.length,\n };\n}\n\n/**\n * Get specialized instructions for each worker type\n */\nfunction getWorkerTypeInstructions(workerType) {\n const instructions = {\n researcher: `- Conduct thorough research using WebSearch and WebFetch\n- Document findings in structured formats\n- Validate source credibility and relevance\n- Synthesize insights from multiple sources\n- Share research methodology and results`,\n\n coder: `- Write clean, maintainable, well-documented code\n- Follow project conventions and best practices\n- Test implementations thoroughly\n- Document code changes and decisions\n- Review and optimize existing code`,\n\n analyst: `- Analyze data patterns and trends\n- Create comprehensive reports and visualizations\n- Identify key insights and recommendations\n- Validate analytical methodologies\n- Correlate findings across data sources`,\n\n tester: `- Design comprehensive test strategies\n- Execute functional, integration, and performance tests\n- Document test results and issues\n- Verify bug fixes and improvements\n- Ensure quality standards and coverage`,\n\n coordinator: `- Monitor overall progress and coordination\n- Facilitate communication between agents\n- Resolve conflicts and blockers\n- Optimize resource allocation\n- Ensure alignment with objectives`,\n\n architect: `- Design system architecture and components\n- Define technical standards and patterns\n- Create implementation guidelines\n- Review and approve design decisions\n- Ensure scalability and maintainability`,\n };\n\n return (\n instructions[workerType] ||\n `- Execute tasks according to ${workerType} best practices\n- Collaborate effectively with team members\n- Document work and share insights\n- Maintain quality standards\n- Contribute to collective objectives`\n );\n}\n\n/**\n * Show all hive mind sessions\n */\nasync function showSessions(flags) {\n try {\n // Use metrics reader for real session data\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n \n if (!existsSync(dbPath)) {\n console.log(chalk.gray('No hive mind database found'));\n return;\n }\n \n const metricsReader = new HiveMindMetricsReader(dbPath);\n const sessions = metricsReader.getActiveSessions();\n\n if (sessions.length === 0) {\n console.log(chalk.gray('No active or paused sessions found'));\n metricsReader.close();\n return;\n }\n\n console.log(chalk.bold('\\n🗂️ Hive Mind Sessions\\n'));\n\n sessions.forEach((session, index) => {\n const statusColor =\n session.status === 'active' ? 'green' : session.status === 'paused' ? 'yellow' : 'gray';\n const statusIcon =\n session.status === 'active' ? '🟢' : session.status === 'paused' ? '🟡' : '⚫';\n\n console.log(chalk.yellow('═'.repeat(60)));\n console.log(`${statusIcon} ${chalk.bold(session.swarm_name || session.id)}`);\n console.log(chalk.cyan('Session ID:'), session.id);\n console.log(chalk.cyan('Status:'), chalk[statusColor](session.status));\n console.log(chalk.cyan('Objective:'), session.objective || 'Not set');\n console.log(chalk.cyan('Progress:'), `${session.completion_percentage || 0}%`);\n console.log(chalk.cyan('Created:'), new Date(session.created_at).toLocaleString());\n console.log(chalk.cyan('Last Updated:'), new Date(session.updated_at).toLocaleString());\n\n if (session.paused_at) {\n console.log(chalk.cyan('Paused At:'), new Date(session.paused_at).toLocaleString());\n }\n\n console.log('\\n' + chalk.bold('Real Progress:'));\n console.log(` Agents: ${session.agent_count || 0}`);\n console.log(` Tasks: ${session.completed_tasks || 0}/${session.task_count || 0}`);\n console.log(` In Progress: ${session.in_progress_tasks || 0}`);\n console.log(` Pending: ${session.pending_tasks || 0}`);\n\n if (session.checkpoint_data) {\n console.log('\\n' + chalk.bold('Last Checkpoint:'));\n const checkpointStr = typeof session.checkpoint_data === 'string' \n ? session.checkpoint_data \n : JSON.stringify(session.checkpoint_data, null, 2);\n console.log(\n chalk.gray(checkpointStr.substring(0, 200) + (checkpointStr.length > 200 ? '...' : '')),\n );\n }\n });\n\n console.log(chalk.yellow('═'.repeat(60)) + '\\n');\n\n console.log(chalk.blue('💡 Tips:'));\n console.log(' • Resume a session: claude-flow hive-mind resume <session-id>');\n console.log(' • View session details: claude-flow hive-mind status');\n\n metricsReader.close();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Resume a paused hive mind session\n */\nasync function resumeSession(args, flags) {\n const sessionId = args[0];\n\n if (!sessionId) {\n console.error(chalk.red('Error: Please provide a session ID'));\n console.log('Usage: claude-flow hive-mind resume <session-id>');\n console.log('Run \"claude-flow hive-mind sessions\" to see available sessions');\n return;\n }\n\n const spinner = ora('Resuming Hive Mind session...').start();\n\n try {\n const sessionManager = new HiveMindSessionManager();\n\n // Get session details\n const session = await sessionManager.getSession(sessionId);\n\n if (!session) {\n spinner.fail(`Session ${sessionId} not found`);\n console.log('\\nRun \"claude-flow hive-mind sessions\" to see available sessions');\n sessionManager.close();\n return;\n }\n\n // Allow resuming any session regardless of status\n spinner.text = `Resuming session from status: ${session.status}...`;\n\n if (session.status === 'stopped') {\n spinner.text = 'Restarting stopped session with original configuration...';\n }\n\n // Resume the session\n const resumedSession = await sessionManager.resumeSession(sessionId);\n\n spinner.succeed('Session resumed successfully!');\n\n // Display session summary\n console.log('\\n' + chalk.bold('📋 Resumed Session Summary:'));\n console.log(chalk.gray('─'.repeat(50)));\n console.log(chalk.cyan('Session ID:'), sessionId);\n console.log(chalk.cyan('Swarm Name:'), resumedSession.swarm_name);\n console.log(chalk.cyan('Objective:'), resumedSession.objective);\n console.log(chalk.cyan('Progress:'), `${resumedSession.statistics.completionPercentage}%`);\n console.log(\n chalk.cyan('Active Agents:'),\n `${resumedSession.statistics.activeAgents}/${resumedSession.statistics.totalAgents}`,\n );\n console.log(\n chalk.cyan('Tasks:'),\n `${resumedSession.statistics.completedTasks}/${resumedSession.statistics.totalTasks} completed`,\n );\n console.log(chalk.gray('─'.repeat(50)));\n\n // Show task breakdown\n console.log('\\n' + chalk.bold('📊 Task Status:'));\n console.log(` ✅ Completed: ${resumedSession.statistics.completedTasks}`);\n console.log(` 🔄 In Progress: ${resumedSession.statistics.inProgressTasks}`);\n console.log(` ⏳ Pending: ${resumedSession.statistics.pendingTasks}`);\n\n // Show recent activity\n if (resumedSession.recentLogs && resumedSession.recentLogs.length > 0) {\n console.log('\\n' + chalk.bold('📜 Recent Activity:'));\n resumedSession.recentLogs.slice(0, 5).forEach((log) => {\n const timestamp = new Date(log.timestamp).toLocaleTimeString();\n console.log(` [${timestamp}] ${log.message}`);\n });\n }\n\n // Restore checkpoint if available\n if (resumedSession.checkpoint_data) {\n console.log('\\n' + chalk.bold('♻️ Restoring from checkpoint...'));\n console.log(chalk.gray('Checkpoint data available for restoration'));\n }\n\n sessionManager.close();\n\n // Offer to spawn Claude Code with restored context\n if (flags.claude || flags.spawn) {\n console.log('\\n' + chalk.yellow('🚀 Launching Claude Code with restored context...'));\n\n // Generate prompt with session context\n const restoredPrompt = generateRestoredSessionPrompt(resumedSession);\n\n // Launch Claude Code with restored context\n await launchClaudeWithContext(restoredPrompt, flags, sessionId);\n } else {\n console.log(\n '\\n' +\n chalk.blue('💡 Pro Tip:') +\n ' Add --claude to spawn Claude Code with restored context',\n );\n console.log(chalk.gray(' claude-flow hive-mind resume ' + sessionId + ' --claude'));\n }\n } catch (error) {\n spinner.fail('Failed to resume session');\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Stop a hive mind session\n */\nasync function stopSession(args, flags) {\n const sessionId = args[0];\n\n if (!sessionId) {\n console.error(chalk.red('Error: Please provide a session ID'));\n console.log('Usage: claude-flow hive-mind stop <session-id>');\n console.log('Run \"claude-flow hive-mind sessions\" to see available sessions');\n return;\n }\n\n const spinner = ora('Stopping Hive Mind session...').start();\n\n try {\n const sessionManager = new HiveMindSessionManager();\n\n // Get session details\n const session = await sessionManager.getSession(sessionId);\n\n if (!session) {\n spinner.fail(`Session ${sessionId} not found`);\n console.log('\\nRun \"claude-flow hive-mind sessions\" to see available sessions');\n sessionManager.close();\n return;\n }\n\n // Stop the session\n await sessionManager.stopSession(sessionId);\n\n spinner.succeed('Session stopped successfully!');\n\n // Display session summary\n console.log('\\n' + chalk.bold('🛑 Stopped Session Summary:'));\n console.log(chalk.gray('─'.repeat(50)));\n console.log(chalk.cyan('Session ID:'), sessionId);\n console.log(chalk.cyan('Swarm Name:'), session.swarm_name || 'Unknown');\n console.log(chalk.cyan('Final Status:'), 'Stopped');\n console.log(\n chalk.cyan('Active Agents:'),\n session.statistics ? session.statistics.activeAgents : 0,\n );\n console.log(chalk.gray('─'.repeat(50)));\n\n console.log('\\n' + chalk.yellow('💡 Session has been stopped and all processes cleaned up.'));\n console.log(\n chalk.gray('To resume this session later, use: claude-flow hive-mind resume ' + sessionId),\n );\n\n sessionManager.close();\n } catch (error) {\n spinner.fail('Failed to stop session');\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Generate prompt for restored session\n */\nfunction generateRestoredSessionPrompt(session) {\n // Get all agents, not just active ones\n const allAgents = session.agents || [];\n const activeAgents = allAgents.filter((a) => a.status === 'active' || a.status === 'busy');\n const idleAgents = allAgents.filter((a) => a.status === 'idle');\n \n // Get all tasks categorized by status\n const allTasks = session.tasks || [];\n const completedTasks = allTasks.filter((t) => t.status === 'completed');\n const inProgressTasks = allTasks.filter((t) => t.status === 'in_progress');\n const pendingTasks = allTasks.filter((t) => t.status === 'pending');\n \n // Calculate session duration\n const sessionStart = new Date(session.created_at);\n const sessionPaused = session.paused_at ? new Date(session.paused_at) : new Date();\n const duration = Math.round((sessionPaused - sessionStart) / 1000 / 60); // minutes\n \n // Get more checkpoint history\n const checkpointHistory = session.checkpoints || [];\n \n // Get more activity logs\n const activityLogs = session.recentLogs || [];\n \n // Format agent details with their current tasks\n const formatAgentDetails = (agents) => {\n if (!agents.length) return 'No agents found';\n return agents.map(agent => {\n const agentTasks = allTasks.filter(t => t.agent_id === agent.id);\n const currentTask = agentTasks.find(t => t.status === 'in_progress');\n return `• ${agent.name} (${agent.type}) - ${agent.status}${currentTask ? `\\n └─ Working on: ${currentTask.description}` : ''}`;\n }).join('\\n');\n };\n \n // Format task details with more information\n const formatTaskDetails = (tasks, limit = 15) => {\n if (!tasks.length) return 'No tasks found';\n const displayTasks = tasks.slice(0, limit);\n return displayTasks.map(task => {\n const agent = allAgents.find(a => a.id === task.agent_id);\n return `• [${task.priority?.toUpperCase() || 'NORMAL'}] ${task.description}${agent ? ` (Assigned to: ${agent.name})` : ''}${task.created_at ? ` - Created: ${new Date(task.created_at).toLocaleTimeString()}` : ''}`;\n }).join('\\n') + (tasks.length > limit ? `\\n... and ${tasks.length - limit} more tasks` : '');\n };\n \n // Format checkpoint details\n const formatCheckpoints = (checkpoints, limit = 5) => {\n if (!checkpoints.length) return 'No checkpoints found';\n const displayCheckpoints = checkpoints.slice(0, limit);\n return displayCheckpoints.map(cp => \n `• ${cp.checkpoint_name} - ${new Date(cp.created_at).toLocaleString()}`\n ).join('\\n');\n };\n \n // Format activity logs with more detail\n const formatActivityLogs = (logs, limit = 20) => {\n if (!logs.length) return 'No activity logs found';\n const displayLogs = logs.slice(0, limit);\n return displayLogs.map(log => {\n const timestamp = new Date(log.timestamp).toLocaleTimeString();\n const agent = log.agent_id ? allAgents.find(a => a.id === log.agent_id) : null;\n return `[${timestamp}] ${log.message}${agent ? ` (by ${agent.name})` : ''}${log.data ? ` - ${JSON.stringify(log.data)}` : ''}`;\n }).join('\\n');\n };\n \n // Extract metadata if available\n const metadata = session.metadata || {};\n const metadataStr = Object.keys(metadata).length > 0 ? \n Object.entries(metadata).map(([k, v]) => `• ${k}: ${typeof v === 'object' ? JSON.stringify(v) : v}`).join('\\n') : \n 'No metadata available';\n\n return `🔄 RESUMING HIVE MIND SESSION\n═══════════════════════════════════\n\nYou are resuming a Hive Mind session with comprehensive context:\n\n📋 SESSION DETAILS:\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n📌 Session ID: ${session.id}\n📌 Swarm ID: ${session.swarm_id}\n📌 Swarm Name: ${session.swarm_name}\n🎯 Objective: ${session.objective}\n📊 Overall Progress: ${session.statistics.completionPercentage}% complete\n⏱️ Session Duration: ${duration} minutes\n📅 Created: ${new Date(session.created_at).toLocaleString()}\n⏸️ Paused: ${session.paused_at ? new Date(session.paused_at).toLocaleString() : 'N/A'}\n▶️ Resumed: ${new Date().toLocaleString()}\n🔄 Status: ${session.status}\n\n📊 TASK STATISTICS:\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n• Total Tasks: ${session.statistics.totalTasks}\n• Completed: ${completedTasks.length} (${session.statistics.totalTasks > 0 ? Math.round((completedTasks.length / session.statistics.totalTasks) * 100) : 0}%)\n• In Progress: ${inProgressTasks.length}\n• Pending: ${pendingTasks.length}\n\n👥 SWARM COMPOSITION (${allAgents.length} agents):\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nActive Agents (${activeAgents.length}):\n${formatAgentDetails(activeAgents)}\n\nIdle Agents (${idleAgents.length}):\n${formatAgentDetails(idleAgents)}\n\n📝 COMPLETED TASKS (${completedTasks.length}):\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n${formatTaskDetails(completedTasks, 10)}\n\n🔄 IN-PROGRESS TASKS (${inProgressTasks.length}):\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n${formatTaskDetails(inProgressTasks)}\n\n⏳ PENDING TASKS (${pendingTasks.length}):\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n${formatTaskDetails(pendingTasks)}\n\n💾 CHECKPOINT HISTORY (${checkpointHistory.length} total):\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n${formatCheckpoints(checkpointHistory)}\n\n📊 SESSION METADATA:\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n${metadataStr}\n\n💾 LAST CHECKPOINT DATA:\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n${session.checkpoint_data ? JSON.stringify(session.checkpoint_data, null, 2) : 'No checkpoint data available'}\n\n📜 ACTIVITY LOG (Last ${Math.min(20, activityLogs.length)} entries):\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n${formatActivityLogs(activityLogs, 20)}\n\n🎯 RESUMPTION PROTOCOL:\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n1. **RESTORE CONTEXT**:\n - Review all checkpoint data and activity history above\n - Use mcp__claude-flow__memory_usage to retrieve collective memory\n - Check agent statuses and reassign tasks if needed\n - Verify all in-progress tasks are still valid\n\n2. **CONTINUE EXECUTION**:\n - Resume in-progress tasks with their assigned agents\n - Process pending tasks based on priority (CRITICAL > HIGH > NORMAL > LOW)\n - Maintain agent coordination through memory sharing\n - Update progress tracking after each task completion\n\n3. **COORDINATION REQUIREMENTS**:\n - Use mcp__claude-flow__memory_usage for all cross-agent communication\n - Apply consensus mechanisms for important decisions\n - Maintain swarm topology: ${session.swarm?.topology || 'unknown'}\n - Keep session checkpoint data updated regularly\n\n4. **MEMORY CONTEXT**:\n - Session memory namespace: session-${session.id}\n - Swarm memory namespace: swarm-${session.swarm_id}\n - Use these namespaces to access historical decisions and context\n\nResume the hive mind operation with full context awareness and continue working towards the objective.`;\n}\n\n/**\n * Launch Claude Code with context\n */\nasync function launchClaudeWithContext(prompt, flags, sessionId) {\n try {\n // ALWAYS save the prompt file first (fix for issue #330)\n // Ensure sessions directory exists\n const sessionsDir = path.join('.hive-mind', 'sessions');\n await mkdirAsync(sessionsDir, { recursive: true });\n const promptFile = path.join(sessionsDir, `hive-mind-resume-${sessionId}-${Date.now()}.txt`);\n await writeFile(promptFile, prompt);\n console.log(chalk.green(`\\n✓ Session context saved to: ${promptFile}`));\n\n const { spawn: childSpawn, execSync } = await import('child_process');\n let claudeAvailable = false;\n\n try {\n execSync('which claude', { stdio: 'ignore' });\n claudeAvailable = true;\n } catch {\n console.log(chalk.yellow('\\n⚠️ Claude Code CLI not found'));\n console.log(chalk.gray('Install Claude Code: npm install -g @anthropic-ai/claude-code'));\n console.log(chalk.gray(`Run with: claude < ${promptFile}`));\n return;\n }\n\n if (claudeAvailable && !flags.dryRun) {\n // Debug logging to track spawn calls\n console.log(chalk.blue('\\n🔍 Debug: About to spawn Claude Code process...'));\n console.log(chalk.gray(` Session ID: ${sessionId}`));\n console.log(chalk.gray(` Process ID: ${process.pid}`));\n \n // Remove --print to allow interactive session (same as initial spawn)\n const claudeArgs = [prompt];\n\n // Add --dangerously-skip-permissions by default for hive-mind operations\n // unless explicitly disabled with --no-auto-permissions\n if (!flags['no-auto-permissions']) {\n claudeArgs.push('--dangerously-skip-permissions');\n console.log(\n chalk.yellow(\n '🔓 Using --dangerously-skip-permissions by default for seamless hive-mind execution',\n ),\n );\n }\n\n console.log(chalk.blue('🔍 Debug: Spawning with args:'), claudeArgs.slice(0, 1).map(a => a.substring(0, 50) + '...'));\n \n // Use 'inherit' for interactive session (same as initial spawn)\n const claudeProcess = childSpawn('claude', claudeArgs, {\n stdio: 'inherit',\n shell: false,\n });\n \n console.log(chalk.blue('🔍 Debug: Claude process spawned with PID:'), claudeProcess.pid);\n\n // Track child process PID in session (same as initial spawn)\n const sessionManager = new HiveMindSessionManager();\n if (claudeProcess.pid) {\n const sessions = await sessionManager.getActiveSessions();\n const currentSession = sessions.find(s => s.id === sessionId);\n if (currentSession) {\n await sessionManager.addChildPid(currentSession.id, claudeProcess.pid);\n }\n }\n\n // Set up SIGINT handler for automatic session pausing (same as initial spawn)\n let isExiting = false;\n const sigintHandler = async () => {\n if (isExiting) return;\n isExiting = true;\n\n console.log('\\n\\n' + chalk.yellow('⏸️ Pausing session and terminating Claude Code...'));\n \n try {\n // Terminate Claude Code process if still running\n if (claudeProcess && !claudeProcess.killed) {\n claudeProcess.kill('SIGTERM');\n }\n \n // Clean up and close session manager\n sessionManager.close();\n \n console.log(chalk.green('✓') + ' Session paused successfully');\n console.log(chalk.cyan('\\nTo resume this session, run:'));\n console.log(chalk.bold(` claude-flow hive-mind resume ${sessionId}`));\n console.log();\n \n process.exit(0);\n } catch (error) {\n console.error(chalk.red('Error during shutdown:'), error.message);\n process.exit(1);\n }\n };\n\n process.on('SIGINT', sigintHandler);\n process.on('SIGTERM', sigintHandler);\n\n // Handle process exit (same as initial spawn)\n claudeProcess.on('exit', async (code, signal) => {\n if (!isExiting) {\n console.log('\\n' + chalk.yellow('Claude Code has exited'));\n \n // Clean up signal handlers\n process.removeListener('SIGINT', sigintHandler);\n process.removeListener('SIGTERM', sigintHandler);\n \n // Close session manager\n sessionManager.close();\n \n process.exit(code || 0);\n }\n });\n\n console.log(chalk.green('\\n✓ Claude Code launched with restored session context'));\n console.log(chalk.gray(` Prompt file saved at: ${promptFile}`));\n }\n } catch (error) {\n console.error(chalk.red('Failed to launch Claude Code:'), error.message);\n }\n}\n\n/**\n * Get MCP wrapper instance\n */\nasync function getMcpWrapper() {\n const { MCPToolWrapper } = await import('./hive-mind/mcp-wrapper.js');\n return new MCPToolWrapper();\n}\n\n// Export for testing\nexport { showHiveMindHelp, initHiveMind, spawnSwarm, showStatus };\n"],"names":["existsSync","mkdirSync","writeFile","readFile","path","inquirer","chalk","ora","cwd","exit","mkdirAsync","warnNonInteractive","safeInteractive","Database","sqliteAvailable","loadSqlite","sqlite","default","testDb","close","err","HiveMindCore","QueenCoordinator","CollectiveMemory","SwarmCommunication","HiveMindSessionManager","createAutoSaveMiddleware","HiveMindMetricsReader","showHiveMindHelp","console","log","yellow","bold","green","gray","cyan","blue","initHiveMind","flags","spinner","start","hiveMindDir","join","recursive","hasSqlite","text","fallbackPath","fallbackData","metadata","type","initialized","Date","toISOString","version","warning","swarms","agents","tasks","collective_memory","consensus_votes","messages","JSON","stringify","succeed","dbPath","db","exec","config","defaults","queenType","maxWorkers","consensusAlgorithm","memorySize","autoScale","encryption","mcpTools","enabled","parallel","timeout","error","fail","red","message","hiveMindWizard","action","prompt","name","choices","value","spawnSwarmWizard","showStatus","manageMemoryWizard","showConsensus","showMetrics","configureWizard","objective","now","parseInt","consensus","namespace","verbose","spawnSwarm","nonInteractive","answers","validate","input","trim","length","checked","swarmResult","workerTypes","monitor","spawnClaude","swarmId","workers","map","index","id","role","status","capabilities","getAgentCapabilities","claudeFlags","spawnClaudeCodeInstances","args","isNonInteractive","wizard","validQueenTypes","includes","isNaN","validConsensusTypes","hiveMind","undefined","Error","dbDir","prepare","get","warn","fs","unlinkSync","e","timestamp","randomPart","Math","random","toString","substring","run","sessionManager","sessionId","createSession","autoSave","saveInterval","autoStart","trackChange","swarmName","workerCount","queen","queenAgent","Object","values","split","i","min","workerType","workerId","worker","charAt","toUpperCase","slice","push","trackAgentActivity","memory","maxSize","store","communication","repeat","isExiting","sigintHandler","checkpointData","reason","saveCheckpoint","pauseSession","global","autoSaveInterval","clearInterval","process","on","claude","spawn","stack","researcher","coder","analyst","tester","architect","reviewer","optimizer","documenter","parse","metricsReader","getActiveSwarms","swarm","queen_type","created_at","toLocaleString","agent_count","find","a","filter","magenta","forEach","statusColor","taskStats","task_metrics","total","completed","in_progress","pending","failed","completion_percentage","memory_count","consensus_count","decisions","all","decision","swarm_name","topic","algorithm","confidence","toFixed","votes","for","against","abstain","details","Array","isArray","detail","agent","agentId","vote","choice","justification","rationale","displayString","entries","overallStats","taskBreakdown","total_swarms","total_agents","total_tasks","completed_tasks","percentage","count","agentPerf","hasCompletedAt","successRate","tasks_assigned","tasks_completed","avg_completion_minutes","swarmPerf","task_count","completed_count","memory_entries","avgTaskTime","avg_minutes","agentTypePerf","listMemories","searchMemories","storeMemoryWizard","showMemoryStats","cleanMemories","exportMemoryBackup","continue","continueAction","hiveMindCommand","subcommand","subArgs","help","showSessions","resumeSession","stopSession","memories","key","swarm_id","created_by","displayValue","parsed","searchTerm","searchPattern","mcpWrapper","getMcpWrapper","memoryValue","storeMemory","category","searchResult","searchMemory","results","data","stats","categories","oldestDate","newestDate","totalSize","date","toLocaleDateString","days","confirm","cutoffDate","setDate","getDate","oldMemories","memoryDate","filename","backup","exportDate","totalMemories","writeFileSync","getActiveSessionId","sessions","getActiveSessions","activeSession","s","workerGroups","groupWorkersByType","hiveMindPrompt","generateHiveMindPrompt","keys","sessionsDir","promptFile","childSpawn","execSync","claudeAvailable","stdio","dryRun","injectMemoryProtocol","enhanceHiveMindPrompt","claudeArgs","claudeProcess","shell","pid","addChildPid","killed","kill","claudePid","stdout","stderr","code","removeChildPid","currentTime","getWorkerTypeInstructions","generateCoordinationInstructions","hiveMindEndpoint","coordinationProtocol","memoryNamespace","consensusThreshold","taskUpdateInterval","healthCheckInterval","workerCapabilities","w","reduce","groups","createClaudeCodeSpawnCommand","typeWorkers","instructions","context","command","replace","title","coordinator","session","statusIcon","updated_at","paused_at","in_progress_tasks","pending_tasks","checkpoint_data","checkpointStr","getSession","resumedSession","statistics","completionPercentage","activeAgents","totalAgents","completedTasks","totalTasks","inProgressTasks","pendingTasks","recentLogs","toLocaleTimeString","restoredPrompt","generateRestoredSessionPrompt","launchClaudeWithContext","allAgents","idleAgents","allTasks","t","sessionStart","sessionPaused","duration","round","checkpointHistory","checkpoints","activityLogs","formatAgentDetails","agentTasks","agent_id","currentTask","description","formatTaskDetails","limit","displayTasks","task","priority","formatCheckpoints","displayCheckpoints","cp","checkpoint_name","formatActivityLogs","logs","displayLogs","metadataStr","k","v","topology","currentSession","signal","removeListener","MCPToolWrapper"],"mappings":"AAMA,SAASA,UAAU,EAAEC,SAAS,QAAQ,KAAK;AAC3C,SAASC,SAAS,EAAEC,QAAQ,QAAQ,cAAc;AAClD,OAAOC,UAAU,OAAO;AAExB,OAAOC,cAAc,WAAW;AAChC,OAAOC,WAAW,QAAQ;AAC1B,OAAOC,SAAS,MAAM;AACtB,SAAeC,GAAG,EAAEC,IAAI,EAA+BC,UAAU,QAAQ,oBAAoB;AAC7F,SAGEC,kBAAkB,QAEb,mCAAmC;AAC1C,SACEC,eAAe,QAGV,+BAA+B;AAGtC,IAAIC,WAAW;AACf,IAAIC,kBAAkB;AAGtB,eAAeC;IACb,IAAIF,aAAa,MAAM,OAAOC;IAC9B,IAAI;QACF,MAAME,SAAS,MAAM,MAAM,CAAC;QAC5BH,WAAWG,OAAOC,OAAO;QAEzB,MAAMC,SAAS,IAAIL,SAAS;QAC5B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AACxB,MAAM6B,IAAI,CAAC;oBACvBN,QAAQC,GAAG,CAACxB,MAAM0B,IAAI,CAAC,CAAC,+BAA+B,EAAEqH,WAAW;oBACpExH,QAAQC,GAAG;oBAEX4J,QAAQjL,IAAI,CAAC;gBACf,EAAE,OAAOsE,OAAO;oBACdlD,QAAQkD,KAAK,CAACzE,MAAM2E,GAAG,CAAC,2BAA2BF,MAAMG,OAAO;oBAChEwG,QAAQjL,IAAI,CAAC;gBACf;YACF;YAEAiL,QAAQC,EAAE,CAAC,UAAUT;YACrBQ,QAAQC,EAAE,CAAC,WAAWT;YAGtBiK,cAAcxJ,EAAE,CAAC,QAAQ,OAAOiK,MAAM+E;gBACpC,IAAI,CAAC1P,WAAW;oBACdpJ,QAAQC,GAAG,CAAC,OAAOxB,MAAMyB,MAAM,CAAC;oBAGhC2J,QAAQkP,cAAc,CAAC,UAAU1P;oBACjCQ,QAAQkP,cAAc,CAAC,WAAW1P;oBAGlC9B,eAAejI,KAAK;oBAEpBuK,QAAQjL,IAAI,CAACmV,QAAQ;gBACvB;YACF;YAEA/T,QAAQC,GAAG,CAACxB,MAAM2B,KAAK,CAAC;YACxBJ,QAAQC,GAAG,CAACxB,MAAM4B,IAAI,CAAC,CAAC,wBAAwB,EAAEwS,YAAY;QAChE;IACF,EAAE,OAAO3P,OAAO;QACdlD,QAAQkD,KAAK,CAACzE,MAAM2E,GAAG,CAAC,kCAAkCF,MAAMG,OAAO;IACzE;AACF;AAKA,eAAekN;IACb,MAAM,EAAEyI,cAAc,EAAE,GAAG,MAAM,MAAM,CAAC;IACxC,OAAO,IAAIA;AACb;AAGA,SAASjZ,gBAAgB,EAAES,YAAY,EAAEgE,UAAU,EAAEX,UAAU,GAAG"}
\ No newline at end of file
+{"version":3,"sources":["../../../../src/cli/simple-commands/hive-mind.js"],"sourcesContent":["/**\n * Hive Mind command for Claude-Flow v2.0.0\n * Advanced swarm intelligence with collective decision-making\n */\n\nimport { spawn } from 'child_process';\nimport { existsSync, mkdirSync } from 'fs';\nimport { writeFile, readFile } from 'fs/promises';\nimport path from 'path';\nimport readline from 'readline';\nimport inquirer from 'inquirer';\nimport chalk from 'chalk';\nimport ora from 'ora';\nimport { args, cwd, exit, writeTextFile, readTextFile, mkdirAsync } from '../node-compat.js';\nimport {\n isInteractive,\n isRawModeSupported,\n warnNonInteractive,\n checkNonInteractiveAuth,\n} from '../utils/interactive-detector.js';\nimport {\n safeInteractive,\n nonInteractiveProgress,\n nonInteractiveSelect,\n} from '../utils/safe-interactive.js';\n\n// Import SQLite for persistence - dynamically loaded to handle missing bindings\nlet Database = null;\nlet sqliteAvailable = false;\n\n// Try to load better-sqlite3, but don't fail if bindings aren't available\nasync function loadSqlite() {\n if (Database !== null) return sqliteAvailable;\n try {\n // Try createRequire first for CommonJS modules (better-sqlite3 is CommonJS)\n const { createRequire } = await import('module');\n const require = createRequire(import.meta.url);\n Database = require('better-sqlite3');\n // Test if bindings work by creating a temp in-memory database\n const testDb = new Database(':memory:');\n testDb.close();\n sqliteAvailable = true;\n } catch (requireErr) {\n // Fallback to dynamic import if createRequire fails\n try {\n const sqlite = await import('better-sqlite3');\n Database = sqlite.default || sqlite;\n const testDb = new Database(':memory:');\n testDb.close();\n sqliteAvailable = true;\n } catch (err) {\n sqliteAvailable = false;\n Database = null;\n }\n }\n return sqliteAvailable;\n}\n\n// Import help formatter\nimport { HelpFormatter } from '../help-formatter.js';\n\n// Import MCP tool wrappers\nimport { MCPToolWrapper } from './hive-mind/mcp-wrapper.js';\nimport { HiveMindCore } from './hive-mind/core.js';\nimport { QueenCoordinator } from './hive-mind/queen.js';\nimport { CollectiveMemory } from './hive-mind/memory.js';\nimport { SwarmCommunication } from './hive-mind/communication.js';\nimport { HiveMindSessionManager } from './hive-mind/session-manager.js';\nimport { createAutoSaveMiddleware } from './hive-mind/auto-save-middleware.js';\nimport { HiveMindMetricsReader } from './hive-mind/metrics-reader.js';\n\nfunction showHiveMindHelp() {\n console.log(`\n${chalk.yellow('🧠 Claude Flow Hive Mind System')}\n\n${chalk.bold('USAGE:')}\n claude-flow hive-mind [subcommand] [options]\n\n${chalk.bold('SUBCOMMANDS:')}\n ${chalk.green('init')} Initialize hive mind system\n ${chalk.green('spawn')} Spawn hive mind swarm for a task\n ${chalk.green('status')} Show hive mind status\n ${chalk.green('resume')} Resume a paused hive mind session\n ${chalk.green('stop')} Stop a running hive mind session\n ${chalk.green('sessions')} List all hive mind sessions\n ${chalk.green('consensus')} View consensus decisions\n ${chalk.green('memory')} Manage collective memory\n ${chalk.green('metrics')} View performance metrics\n ${chalk.green('wizard')} Interactive hive mind wizard with Claude Code spawning\n\n${chalk.bold('EXAMPLES:')}\n ${chalk.gray('# Initialize hive mind')}\n claude-flow hive-mind init\n\n ${chalk.gray('# Spawn swarm with interactive wizard')}\n claude-flow hive-mind spawn\n\n ${chalk.gray('# Quick spawn with objective')}\n claude-flow hive-mind spawn \"Build microservices architecture\"\n\n ${chalk.gray('# View current status')}\n claude-flow hive-mind status\n\n ${chalk.gray('# Interactive wizard with Claude Code spawning')}\n claude-flow hive-mind wizard\n\n ${chalk.gray('# Spawn with Claude Code coordination')}\n claude-flow hive-mind spawn \"Build REST API\" --claude\n\n ${chalk.gray('# Auto-spawn coordinated Claude Code instances')}\n claude-flow hive-mind spawn \"Research AI trends\" --auto-spawn --verbose\n\n ${chalk.gray('# List all sessions')}\n claude-flow hive-mind sessions\n\n ${chalk.gray('# Resume a paused session')}\n claude-flow hive-mind resume session-1234567890-abc123\n\n${chalk.bold('KEY FEATURES:')}\n ${chalk.cyan('🐝')} Queen-led coordination with worker specialization\n ${chalk.cyan('🧠')} Collective memory and knowledge sharing\n ${chalk.cyan('🤝')} Consensus building for critical decisions\n ${chalk.cyan('⚡')} Parallel task execution with auto-scaling\n ${chalk.cyan('🔄')} Work stealing and load balancing\n ${chalk.cyan('📊')} Real-time metrics and performance tracking\n ${chalk.cyan('🛡️')} Fault tolerance and self-healing\n ${chalk.cyan('🔒')} Secure communication between agents\n\n${chalk.bold('OPTIONS:')}\n --queen-type <type> Queen coordinator type (strategic, tactical, adaptive)\n --max-workers <n> Maximum worker agents (default: 8)\n --consensus <type> Consensus algorithm (majority, weighted, byzantine)\n --memory-size <mb> Collective memory size in MB (default: 100)\n --auto-scale Enable auto-scaling based on workload\n --encryption Enable encrypted communication\n --monitor Real-time monitoring dashboard\n --verbose Detailed logging\n --claude Generate Claude Code spawn commands with coordination\n --spawn Alias for --claude\n --auto-spawn Automatically spawn Claude Code instances\n --execute Execute Claude Code spawn commands immediately\n\n${chalk.bold('For more information:')}\n${chalk.blue('https://github.com/ruvnet/claude-flow/tree/main/docs/hive-mind')}\n`);\n}\n\n/**\n * Initialize hive mind system\n */\nasync function initHiveMind(flags) {\n const spinner = ora('Initializing Hive Mind system...').start();\n\n try {\n // Create hive mind directory structure\n const hiveMindDir = path.join(cwd(), '.hive-mind');\n if (!existsSync(hiveMindDir)) {\n mkdirSync(hiveMindDir, { recursive: true });\n }\n\n // Check SQLite availability\n const hasSqlite = await loadSqlite();\n\n if (!hasSqlite) {\n // Fall back to JSON-based initialization\n spinner.text = 'Initializing Hive Mind with JSON fallback...';\n\n const fallbackPath = path.join(hiveMindDir, 'memory.json');\n const fallbackData = {\n metadata: {\n type: 'fallback',\n initialized: new Date().toISOString(),\n version: '2.0.0',\n warning: 'Using JSON fallback - SQLite bindings not available'\n },\n swarms: [],\n agents: [],\n tasks: [],\n collective_memory: [],\n consensus_votes: [],\n messages: []\n };\n\n await writeFile(fallbackPath, JSON.stringify(fallbackData, null, 2), 'utf8');\n\n spinner.succeed('Hive Mind initialized with JSON fallback');\n console.log(chalk.yellow('\\n⚠️ Note: SQLite native bindings not available'));\n console.log(chalk.gray(' Using JSON fallback for data persistence'));\n console.log(chalk.gray(' For full SQLite features, install locally: npm install claude-flow'));\n return;\n }\n\n // Initialize SQLite database\n const dbPath = path.join(hiveMindDir, 'hive.db');\n const db = new Database(dbPath);\n\n // Create tables\n db.exec(`\n CREATE TABLE IF NOT EXISTS swarms (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n objective TEXT,\n status TEXT DEFAULT 'active',\n queen_type TEXT DEFAULT 'strategic',\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n updated_at DATETIME DEFAULT CURRENT_TIMESTAMP\n );\n \n CREATE TABLE IF NOT EXISTS agents (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n name TEXT NOT NULL,\n type TEXT NOT NULL,\n role TEXT,\n status TEXT DEFAULT 'idle',\n capabilities TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS tasks (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n agent_id TEXT,\n description TEXT,\n status TEXT DEFAULT 'pending',\n priority INTEGER DEFAULT 5,\n result TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n completed_at DATETIME,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id),\n FOREIGN KEY (agent_id) REFERENCES agents(id)\n );\n \n CREATE TABLE IF NOT EXISTS collective_memory (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n key TEXT NOT NULL,\n value TEXT,\n type TEXT DEFAULT 'knowledge',\n confidence REAL DEFAULT 1.0,\n created_by TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n accessed_at DATETIME,\n access_count INTEGER DEFAULT 0,\n compressed INTEGER DEFAULT 0,\n size INTEGER DEFAULT 0,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS consensus_decisions (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n topic TEXT NOT NULL,\n decision TEXT,\n votes TEXT,\n algorithm TEXT DEFAULT 'majority',\n confidence REAL,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n `);\n\n db.close();\n\n // Create configuration file\n const config = {\n version: '2.0.0',\n initialized: new Date().toISOString(),\n defaults: {\n queenType: 'strategic',\n maxWorkers: 8,\n consensusAlgorithm: 'majority',\n memorySize: 100,\n autoScale: true,\n encryption: false,\n },\n mcpTools: {\n enabled: true,\n parallel: true,\n timeout: 60000,\n },\n };\n\n await writeFile(path.join(hiveMindDir, 'config.json'), JSON.stringify(config, null, 2));\n\n spinner.succeed('Hive Mind system initialized successfully!');\n\n console.log('\\n' + chalk.green('✓') + ' Created .hive-mind directory');\n console.log(chalk.green('✓') + ' Initialized SQLite database');\n console.log(chalk.green('✓') + ' Created configuration file');\n console.log('\\n' + chalk.yellow('Next steps:'));\n console.log(\n ' 1. Run ' + chalk.cyan('claude-flow hive-mind spawn') + ' to create your first swarm',\n );\n console.log(\n ' 2. Use ' + chalk.cyan('claude-flow hive-mind wizard') + ' for interactive setup',\n );\n } catch (error) {\n spinner.fail('Failed to initialize Hive Mind system');\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Interactive wizard for hive mind operations\n */\n// Wrapped wizard function that handles non-interactive environments\nconst hiveMindWizard = safeInteractive(\n // Interactive version\n async function (flags = {}) {\n console.log(chalk.yellow('\\n🧙 Hive Mind Interactive Wizard\\n'));\n\n const { action } = await inquirer.prompt([\n {\n type: 'list',\n name: 'action',\n message: 'What would you like to do?',\n choices: [\n { name: '🐝 Create new swarm', value: 'spawn' },\n { name: '📊 View swarm status', value: 'status' },\n { name: '🧠 Manage collective memory', value: 'memory' },\n { name: '🤝 View consensus decisions', value: 'consensus' },\n { name: '📈 Performance metrics', value: 'metrics' },\n { name: '🔧 Configure hive mind', value: 'config' },\n { name: '❌ Exit', value: 'exit' },\n ],\n },\n ]);\n\n switch (action) {\n case 'spawn':\n await spawnSwarmWizard();\n break;\n case 'status':\n await showStatus({});\n break;\n case 'memory':\n await manageMemoryWizard();\n break;\n case 'consensus':\n await showConsensus({});\n break;\n case 'metrics':\n await showMetrics({});\n break;\n case 'config':\n await configureWizard();\n break;\n case 'exit':\n console.log(chalk.gray('Exiting wizard...'));\n break;\n }\n },\n // Non-interactive fallback\n async function (flags = {}) {\n console.log(chalk.yellow('\\n🧙 Hive Mind - Non-Interactive Mode\\n'));\n\n // Default to creating a swarm with sensible defaults\n console.log(chalk.cyan('Creating new swarm with default settings...'));\n console.log(chalk.gray('Use command-line flags to customize:'));\n console.log(chalk.gray(' --objective \"Your task\" Set swarm objective'));\n console.log(chalk.gray(' --queen-type strategic Set queen type'));\n console.log(chalk.gray(' --max-workers 8 Set worker count'));\n console.log();\n\n const objective = flags.objective || 'General task coordination';\n const config = {\n name: flags.name || `swarm-${Date.now()}`,\n queenType: flags.queenType || flags['queen-type'] || 'strategic',\n maxWorkers: parseInt(flags.maxWorkers || flags['max-workers'] || '8'),\n consensusAlgorithm: flags.consensus || flags.consensusAlgorithm || 'majority',\n autoScale: flags.autoScale || flags['auto-scale'] || false,\n namespace: flags.namespace || 'default',\n verbose: flags.verbose || false,\n encryption: flags.encryption || false,\n };\n\n await spawnSwarm([objective], {\n ...flags,\n name: config.name,\n queenType: config.queenType,\n maxWorkers: config.maxWorkers,\n consensusAlgorithm: config.consensusAlgorithm,\n autoScale: config.autoScale,\n encryption: config.encryption,\n nonInteractive: true,\n });\n },\n);\n\n/**\n * Spawn swarm wizard\n */\nasync function spawnSwarmWizard() {\n const answers = await inquirer.prompt([\n {\n type: 'input',\n name: 'objective',\n message: 'What is the swarm objective?',\n validate: (input) => input.trim().length > 0 || 'Please enter an objective',\n },\n {\n type: 'input',\n name: 'name',\n message: 'Swarm name (optional):',\n default: (answers) => `swarm-${Date.now()}`,\n },\n {\n type: 'list',\n name: 'queenType',\n message: 'Select queen coordinator type:',\n choices: [\n { name: 'Strategic - High-level planning and coordination', value: 'strategic' },\n { name: 'Tactical - Detailed task management', value: 'tactical' },\n { name: 'Adaptive - Learns and adapts strategies', value: 'adaptive' },\n ],\n default: 'strategic',\n },\n {\n type: 'number',\n name: 'maxWorkers',\n message: 'Maximum number of worker agents:',\n default: 8,\n validate: (input) => (input > 0 && input <= 20) || 'Please enter a number between 1 and 20',\n },\n {\n type: 'checkbox',\n name: 'workerTypes',\n message: 'Select worker agent types:',\n choices: [\n { name: 'Researcher', value: 'researcher', checked: true },\n { name: 'Coder', value: 'coder', checked: true },\n { name: 'Analyst', value: 'analyst', checked: true },\n { name: 'Tester', value: 'tester', checked: true },\n { name: 'Architect', value: 'architect' },\n { name: 'Reviewer', value: 'reviewer' },\n { name: 'Optimizer', value: 'optimizer' },\n { name: 'Documenter', value: 'documenter' },\n ],\n },\n {\n type: 'list',\n name: 'consensusAlgorithm',\n message: 'Consensus algorithm for decisions:',\n choices: [\n { name: 'Majority - Simple majority voting', value: 'majority' },\n { name: 'Weighted - Expertise-weighted voting', value: 'weighted' },\n { name: 'Byzantine - Fault-tolerant consensus', value: 'byzantine' },\n ],\n default: 'majority',\n },\n {\n type: 'confirm',\n name: 'autoScale',\n message: 'Enable auto-scaling?',\n default: true,\n },\n {\n type: 'confirm',\n name: 'monitor',\n message: 'Launch monitoring dashboard?',\n default: true,\n },\n {\n type: 'confirm',\n name: 'spawnClaude',\n message: 'Spawn Claude Code instance with hive-mind coordination?',\n default: true,\n },\n ]);\n\n // Spawn the swarm with collected parameters\n const swarmResult = await spawnSwarm([answers.objective], {\n name: answers.name,\n queenType: answers.queenType,\n 'queen-type': answers.queenType,\n maxWorkers: answers.maxWorkers,\n 'max-workers': answers.maxWorkers,\n workerTypes: answers.workerTypes.join(','),\n consensus: answers.consensusAlgorithm,\n autoScale: answers.autoScale,\n 'auto-scale': answers.autoScale,\n monitor: answers.monitor,\n namespace: answers.namespace || 'default',\n verbose: answers.verbose || false,\n spawnClaude: answers.spawnClaude, // Pass the Claude spawning preference\n });\n\n // If Claude Code spawning was requested, launch it using the same function as --claude flag\n if (answers.spawnClaude && swarmResult && swarmResult.swarmId) {\n // Create workers array in the same format expected by spawnClaudeCodeInstances\n const workers = answers.workerTypes.map((type, index) => ({\n id: `worker-${index + 1}`,\n type,\n role: 'worker',\n status: 'active',\n capabilities: getAgentCapabilities(type)\n }));\n \n // Create flags object with the wizard settings\n const claudeFlags = {\n queenType: answers.queenType,\n consensus: answers.consensusAlgorithm,\n autoScale: answers.autoScale,\n monitor: answers.monitor,\n namespace: answers.namespace || 'default',\n verbose: answers.verbose || false\n };\n \n // Use the same Claude spawning function as the --claude flag\n console.log(chalk.cyan(`\\n🎯 Objective from wizard: \"${answers.objective}\"`));\n await spawnClaudeCodeInstances(\n swarmResult.swarmId,\n answers.name,\n answers.objective,\n workers,\n claudeFlags\n );\n }\n \n return swarmResult;\n}\n\n/**\n * Spawn a hive mind swarm\n */\nasync function spawnSwarm(args, flags) {\n // Load SQLite before using Database constructor\n const hasSqlite = await loadSqlite();\n if (!hasSqlite) {\n console.error(chalk.red('Error: SQLite is required for hive-mind spawn'));\n console.log(chalk.yellow('Please ensure better-sqlite3 is properly installed:'));\n console.log(chalk.gray(' npm install better-sqlite3'));\n console.log(chalk.gray(' # or for ARM64/M1: npm rebuild better-sqlite3'));\n return;\n }\n\n const objective = args.join(' ').trim();\n\n // Check for non-interactive mode FIRST\n const isNonInteractive = flags['non-interactive'] || flags.nonInteractive;\n \n if (!objective && !flags.wizard) {\n if (isNonInteractive) {\n console.error(chalk.red('Error: Objective required in non-interactive mode'));\n console.log('Usage: claude-flow hive-mind spawn \"Your objective\" --non-interactive');\n } else {\n console.error(chalk.red('Error: Please provide an objective or use --wizard flag'));\n console.log('Example: claude-flow hive-mind spawn \"Build REST API\"');\n }\n return;\n }\n \n // Log non-interactive mode status\n if (isNonInteractive && flags.verbose) {\n console.log(chalk.cyan('🤖 Running in non-interactive mode'));\n }\n\n // Validate parameters\n if (flags.verbose) {\n console.log(chalk.gray('🔍 Debug: Parsed flags:'));\n console.log(chalk.gray(JSON.stringify(flags, null, 2)));\n }\n\n // Validate queen type\n const validQueenTypes = ['strategic', 'tactical', 'adaptive'];\n const queenType = flags.queenType || flags['queen-type'] || 'strategic';\n if (!validQueenTypes.includes(queenType)) {\n console.error(chalk.red(`Error: Invalid queen type '${queenType}'. Must be one of: ${validQueenTypes.join(', ')}`));\n return;\n }\n\n // Validate max workers\n const maxWorkers = parseInt(flags.maxWorkers || flags['max-workers'] || '8');\n if (isNaN(maxWorkers) || maxWorkers < 1 || maxWorkers > 20) {\n console.error(chalk.red('Error: max-workers must be a number between 1 and 20'));\n return;\n }\n\n // Validate consensus algorithm\n const validConsensusTypes = ['majority', 'weighted', 'byzantine'];\n const consensusAlgorithm = flags.consensus || flags.consensusAlgorithm || 'majority';\n if (!validConsensusTypes.includes(consensusAlgorithm)) {\n console.error(chalk.red(`Error: Invalid consensus algorithm '${consensusAlgorithm}'. Must be one of: ${validConsensusTypes.join(', ')}`));\n return;\n }\n\n const spinner = ora('Spawning Hive Mind swarm...').start();\n\n try {\n // Initialize hive mind core with error handling\n let hiveMind;\n try {\n spinner.text = 'Initializing Hive Mind Core...';\n hiveMind = new HiveMindCore({\n objective,\n name: flags.name || `hive-${Date.now()}`,\n queenType: flags.queenType || flags['queen-type'] || 'strategic',\n maxWorkers: parseInt(flags.maxWorkers || flags['max-workers'] || '8'),\n consensusAlgorithm: flags.consensus || flags.consensusAlgorithm || 'majority',\n autoScale: flags.autoScale !== undefined ? flags.autoScale : (flags['auto-scale'] !== undefined ? flags['auto-scale'] : true),\n namespace: flags.namespace || 'default',\n encryption: flags.encryption || false,\n });\n } catch (error) {\n console.error('HiveMindCore initialization failed:', error);\n throw new Error(`Failed to initialize HiveMindCore: ${error.message}`);\n }\n\n spinner.text = 'Setting up database connection...';\n // Initialize database connection\n const dbDir = path.join(cwd(), '.hive-mind');\n const dbPath = path.join(dbDir, 'hive.db');\n\n // Ensure .hive-mind directory exists\n if (!existsSync(dbDir)) {\n mkdirSync(dbDir, { recursive: true });\n }\n\n // Check if database file exists and try to create a clean one if needed\n let db;\n try {\n spinner.text = 'Creating database connection...';\n db = new Database(dbPath);\n // Test the database with a simple query\n db.prepare('SELECT 1').get();\n spinner.text = 'Database connection established';\n } catch (error) {\n console.warn('Database issue detected, recreating...', error.message);\n spinner.text = 'Recreating database...';\n // Remove corrupted database\n if (existsSync(dbPath)) {\n try {\n const fs = await import('fs');\n fs.unlinkSync(dbPath);\n } catch (e) {\n console.warn('Could not remove corrupted database:', e.message);\n }\n }\n // Create new database\n db = new Database(dbPath);\n }\n\n // Initialize database schema if not exists\n spinner.text = 'Creating database schema...';\n try {\n db.exec(`\n CREATE TABLE IF NOT EXISTS swarms (\n id TEXT PRIMARY KEY,\n name TEXT NOT NULL,\n objective TEXT,\n queen_type TEXT,\n status TEXT DEFAULT 'active',\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n updated_at DATETIME\n );\n \n CREATE TABLE IF NOT EXISTS agents (\n id TEXT PRIMARY KEY,\n swarm_id TEXT NOT NULL,\n name TEXT NOT NULL,\n type TEXT NOT NULL,\n role TEXT NOT NULL,\n status TEXT DEFAULT 'idle',\n capabilities TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS tasks (\n id TEXT PRIMARY KEY,\n swarm_id TEXT NOT NULL,\n agent_id TEXT,\n description TEXT,\n status TEXT DEFAULT 'pending',\n priority INTEGER DEFAULT 5,\n result TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n completed_at DATETIME,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id),\n FOREIGN KEY (agent_id) REFERENCES agents(id)\n );\n \n CREATE TABLE IF NOT EXISTS collective_memory (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n key TEXT NOT NULL,\n value TEXT,\n type TEXT DEFAULT 'knowledge',\n confidence REAL DEFAULT 1.0,\n created_by TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n accessed_at DATETIME,\n access_count INTEGER DEFAULT 0,\n compressed INTEGER DEFAULT 0,\n size INTEGER DEFAULT 0,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS consensus_decisions (\n id TEXT PRIMARY KEY,\n swarm_id TEXT,\n topic TEXT NOT NULL,\n decision TEXT,\n votes TEXT,\n algorithm TEXT DEFAULT 'majority',\n confidence REAL,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS sessions (\n id TEXT PRIMARY KEY,\n swarm_id TEXT NOT NULL,\n swarm_name TEXT NOT NULL,\n objective TEXT,\n status TEXT DEFAULT 'active',\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n paused_at DATETIME,\n resumed_at DATETIME,\n completion_percentage REAL DEFAULT 0,\n checkpoint_data TEXT,\n metadata TEXT,\n parent_pid INTEGER,\n child_pids TEXT,\n FOREIGN KEY (swarm_id) REFERENCES swarms(id)\n );\n \n CREATE TABLE IF NOT EXISTS session_checkpoints (\n id TEXT PRIMARY KEY,\n session_id TEXT NOT NULL,\n checkpoint_name TEXT NOT NULL,\n checkpoint_data TEXT,\n created_at DATETIME DEFAULT CURRENT_TIMESTAMP,\n FOREIGN KEY (session_id) REFERENCES sessions(id)\n );\n \n CREATE TABLE IF NOT EXISTS session_logs (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n session_id TEXT NOT NULL,\n timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,\n log_level TEXT DEFAULT 'info',\n message TEXT,\n agent_id TEXT,\n data TEXT,\n FOREIGN KEY (session_id) REFERENCES sessions(id)\n );\n `);\n spinner.text = 'Database schema created successfully';\n } catch (error) {\n console.error('Database schema creation failed:', error);\n throw new Error(`Failed to create database schema: ${error.message}`);\n }\n\n // Create swarm record with safe ID generation\n spinner.text = 'Creating swarm record...';\n const timestamp = Date.now();\n const randomPart = Math.random().toString(36).substring(2, 11); // Use substring instead of substr\n const swarmId = `swarm-${timestamp}-${randomPart}`;\n try {\n db.prepare(\n `\n INSERT INTO swarms (id, name, objective, queen_type)\n VALUES (?, ?, ?, ?)\n `,\n ).run(swarmId, hiveMind.config.name, objective, hiveMind.config.queenType);\n } catch (error) {\n console.error('Failed to create swarm record:', error);\n throw new Error(`Failed to create swarm record: ${error.message}`);\n }\n\n // Create session for this swarm\n spinner.text = 'Creating session tracking...';\n const sessionManager = new HiveMindSessionManager();\n const sessionId = await sessionManager.createSession(swarmId, hiveMind.config.name, objective, {\n queenType: hiveMind.config.queenType,\n maxWorkers: hiveMind.config.maxWorkers,\n consensusAlgorithm: hiveMind.config.consensusAlgorithm,\n autoScale: hiveMind.config.autoScale,\n encryption: hiveMind.config.encryption,\n workerTypes: flags.workerTypes,\n });\n\n spinner.text = 'Session tracking established...';\n\n // Initialize auto-save middleware (use the same session manager)\n const autoSave = createAutoSaveMiddleware(sessionId, sessionManager, {\n saveInterval: 30000, // Save every 30 seconds\n autoStart: true,\n });\n\n // Close session manager after auto-save is set up\n // sessionManager.close(); // Don't close yet as auto-save needs it\n\n // Track initial swarm creation\n autoSave.trackChange('swarm_created', {\n swarmId,\n swarmName: hiveMind.config.name,\n objective,\n workerCount: hiveMind.config.maxWorkers,\n });\n\n spinner.text = 'Initializing Queen coordinator...';\n\n // Initialize Queen\n const queen = new QueenCoordinator({\n swarmId,\n type: hiveMind.config.queenType,\n objective,\n });\n\n // Spawn Queen agent\n const queenAgent = {\n id: `queen-${swarmId}`,\n swarmId,\n name: 'Queen Coordinator',\n type: 'coordinator',\n role: 'queen',\n status: 'active',\n capabilities: JSON.stringify(['coordination', 'planning', 'decision-making']),\n };\n\n db.prepare(\n `\n INSERT INTO agents (id, swarm_id, name, type, role, status, capabilities)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n `,\n ).run(...Object.values(queenAgent));\n\n spinner.text = 'Spawning worker agents...';\n\n // Determine worker types\n const workerTypes = flags.workerTypes\n ? flags.workerTypes.split(',')\n : ['researcher', 'coder', 'analyst', 'tester'];\n\n // Spawn worker agents\n const workers = [];\n for (let i = 0; i < Math.min(workerTypes.length, hiveMind.config.maxWorkers); i++) {\n const workerType = workerTypes[i % workerTypes.length];\n const workerId = `worker-${swarmId}-${i}`;\n\n const worker = {\n id: workerId,\n swarmId,\n name: `${workerType.charAt(0).toUpperCase() + workerType.slice(1)} Worker ${i + 1}`,\n type: workerType,\n role: 'worker',\n status: 'idle',\n capabilities: JSON.stringify(getAgentCapabilities(workerType)),\n };\n\n workers.push(worker);\n\n db.prepare(\n `\n INSERT INTO agents (id, swarm_id, name, type, role, status, capabilities)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n `,\n ).run(...Object.values(worker));\n\n // Track agent spawning for auto-save\n autoSave.trackAgentActivity(workerId, 'spawned', {\n type: workerType,\n name: worker.name,\n });\n }\n\n spinner.text = 'Initializing collective memory...';\n\n // Initialize collective memory\n const memory = new CollectiveMemory({\n swarmId,\n maxSize: flags.memorySize || 100,\n });\n\n // Store initial context\n memory.store('objective', objective, 'context');\n memory.store('queen_type', hiveMind.config.queenType, 'config');\n memory.store('worker_count', workers.length, 'metrics');\n memory.store('session_id', sessionId, 'system');\n\n spinner.text = 'Establishing communication channels...';\n\n // Initialize communication system\n const communication = new SwarmCommunication({\n swarmId,\n encryption: hiveMind.config.encryption,\n });\n\n db.close();\n\n spinner.succeed('Hive Mind swarm spawned successfully!');\n\n // Display swarm summary\n console.log('\\n' + chalk.bold('🐝 Swarm Summary:'));\n console.log(chalk.gray('─'.repeat(50)));\n console.log(chalk.cyan('Swarm ID:'), swarmId);\n console.log(chalk.cyan('Session ID:'), sessionId);\n console.log(chalk.cyan('Name:'), hiveMind.config.name);\n console.log(chalk.cyan('Objective:'), objective);\n console.log(chalk.cyan('Queen Type:'), hiveMind.config.queenType);\n console.log(chalk.cyan('Workers:'), workers.length);\n console.log(chalk.cyan('Worker Types:'), workerTypes.join(', '));\n console.log(chalk.cyan('Consensus:'), hiveMind.config.consensusAlgorithm);\n console.log(chalk.cyan('Auto-scaling:'), hiveMind.config.autoScale ? 'Enabled' : 'Disabled');\n console.log(chalk.gray('─'.repeat(50)));\n\n // Launch monitoring if requested\n if (flags.monitor) {\n console.log('\\n' + chalk.yellow('Launching monitoring dashboard...'));\n // TODO: Implement monitoring dashboard\n }\n\n // Enhanced coordination instructions with MCP tools\n console.log('\\n' + chalk.green('✓') + ' Swarm is ready for coordination');\n console.log(chalk.gray('Use \"claude-flow hive-mind status\" to view swarm activity'));\n console.log(chalk.gray('Session auto-save enabled - progress saved every 30 seconds'));\n console.log(chalk.blue('💡 To pause:') + ' Press Ctrl+C to safely pause and resume later');\n console.log(chalk.blue('💡 To resume:') + ' claude-flow hive-mind resume ' + sessionId);\n\n // Set up SIGINT handler for automatic session pausing\n let isExiting = false;\n const sigintHandler = async () => {\n if (isExiting) return;\n isExiting = true;\n\n console.log('\\n\\n' + chalk.yellow('⏸️ Pausing session...'));\n \n try {\n // Save current checkpoint using the existing session manager\n // const sessionManager = new HiveMindSessionManager(); // Use existing one\n \n // Create checkpoint data\n const checkpointData = {\n timestamp: new Date().toISOString(),\n swarmId,\n objective,\n workerCount: workers.length,\n workerTypes,\n status: 'paused_by_user',\n reason: 'User pressed Ctrl+C',\n };\n \n // Save checkpoint\n await sessionManager.saveCheckpoint(sessionId, 'auto-pause', checkpointData);\n \n // Pause the session\n await sessionManager.pauseSession(sessionId);\n \n // Close session manager\n sessionManager.close();\n \n console.log(chalk.green('✓') + ' Session paused successfully');\n console.log(chalk.cyan('\\nTo resume this session, run:'));\n console.log(chalk.bold(` claude-flow hive-mind resume ${sessionId}`));\n console.log();\n \n // Clean up auto-save if active\n if (global.autoSaveInterval) {\n clearInterval(global.autoSaveInterval);\n }\n \n process.exit(0);\n } catch (error) {\n console.error(chalk.red('Error pausing session:'), error.message);\n process.exit(1);\n }\n };\n\n // Register SIGINT handler\n process.on('SIGINT', sigintHandler);\n process.on('SIGTERM', sigintHandler);\n\n // Offer to spawn Claude Code instances with coordination instructions\n // Spawn Claude if --claude or --spawn flag is set\n if (flags.claude || flags.spawn) {\n await spawnClaudeCodeInstances(swarmId, hiveMind.config.name, objective, workers, flags);\n } else {\n console.log(\n '\\n' +\n chalk.blue('💡 Pro Tip:') +\n ' Add --claude to spawn coordinated Claude Code instances',\n );\n console.log(chalk.gray(' claude-flow hive-mind spawn \"objective\" --claude'));\n }\n\n // Return swarm info for wizard use\n return { swarmId, hiveMind };\n } catch (error) {\n spinner.fail('Failed to spawn Hive Mind swarm');\n console.error(chalk.red('Error:'), error.message);\n\n // If error contains \"sha3\", provide specific guidance\n if (error.message.includes('sha3') || error.message.includes('SHA3')) {\n console.error('\\n🔍 SHA3 Function Error Detected');\n console.error('This appears to be a SQLite extension or better-sqlite3 configuration issue.');\n console.error('\\nPossible solutions:');\n console.error('1. Try removing the corrupted database: rm -rf .hive-mind/');\n console.error('2. Reinstall better-sqlite3: npm reinstall better-sqlite3');\n console.error('3. Check if any SQLite extensions are conflicting');\n console.error('\\n🚨 Detailed error:');\n console.error(error.stack || error.message);\n }\n\n exit(1);\n }\n}\n\n/**\n * Get agent capabilities based on type\n */\nfunction getAgentCapabilities(type) {\n const capabilities = {\n researcher: ['web-search', 'data-gathering', 'analysis', 'synthesis'],\n coder: ['code-generation', 'implementation', 'refactoring', 'debugging'],\n analyst: ['data-analysis', 'pattern-recognition', 'reporting', 'visualization'],\n tester: ['test-generation', 'quality-assurance', 'bug-detection', 'validation'],\n architect: ['system-design', 'architecture', 'planning', 'documentation'],\n reviewer: ['code-review', 'quality-check', 'feedback', 'improvement'],\n optimizer: ['performance-tuning', 'optimization', 'profiling', 'enhancement'],\n documenter: ['documentation', 'explanation', 'tutorial-creation', 'knowledge-base'],\n };\n\n return capabilities[type] || ['general'];\n}\n\n/**\n * Show hive mind status\n */\nasync function showStatus(flags) {\n try {\n const hiveMindDir = path.join(cwd(), '.hive-mind');\n const dbPath = path.join(hiveMindDir, 'hive.db');\n const fallbackPath = path.join(hiveMindDir, 'memory.json');\n\n // Check if hive-mind is initialized at all\n if (!existsSync(hiveMindDir)) {\n console.error(chalk.red('Error: Hive Mind not initialized'));\n console.log('Run \"claude-flow hive-mind init\" first');\n return;\n }\n\n // Check SQLite availability\n const hasSqlite = await loadSqlite();\n\n // If SQLite database exists but bindings aren't available\n if (existsSync(dbPath) && !hasSqlite) {\n console.log(chalk.yellow('⚠️ SQLite native bindings not available'));\n console.log(chalk.gray(' This is normal when using npx or remote execution'));\n console.log('');\n\n // Try to show basic status from fallback JSON\n if (existsSync(fallbackPath)) {\n try {\n const fallbackData = JSON.parse(await readFile(fallbackPath, 'utf8'));\n console.log(chalk.bold('🐝 Hive Mind Status (from fallback memory)'));\n console.log(chalk.cyan(' Database:'), chalk.yellow('JSON fallback'));\n console.log(chalk.cyan(' Swarms:'), fallbackData.swarms?.length || 0);\n console.log(chalk.cyan(' Agents:'), fallbackData.agents?.length || 0);\n console.log('');\n console.log(chalk.gray('💡 For full SQLite features, install locally:'));\n console.log(chalk.gray(' npm install claude-flow'));\n return;\n } catch {\n // Fallback file exists but couldn't be read\n }\n }\n\n // Show minimal status\n console.log(chalk.bold('🐝 Hive Mind Status'));\n console.log(chalk.cyan(' Initialized:'), chalk.green('Yes'));\n console.log(chalk.cyan(' Database:'), chalk.yellow('SQLite (unavailable in npx mode)'));\n console.log('');\n console.log(chalk.gray('💡 For full functionality, install locally:'));\n console.log(chalk.gray(' npm install claude-flow'));\n return;\n }\n\n if (!existsSync(dbPath)) {\n // Check for fallback JSON database\n if (existsSync(fallbackPath)) {\n try {\n const fallbackData = JSON.parse(await readFile(fallbackPath, 'utf8'));\n console.log(chalk.bold('🐝 Hive Mind Status (JSON fallback mode)'));\n console.log(chalk.cyan(' Database:'), chalk.yellow('JSON fallback'));\n console.log(chalk.cyan(' Swarms:'), fallbackData.swarms?.length || 0);\n console.log(chalk.cyan(' Agents:'), fallbackData.agents?.length || 0);\n console.log(chalk.cyan(' Tasks:'), fallbackData.tasks?.length || 0);\n return;\n } catch {\n console.error(chalk.red('Error: Hive Mind not initialized'));\n console.log('Run \"claude-flow hive-mind init\" first');\n return;\n }\n }\n console.error(chalk.red('Error: Hive Mind not initialized'));\n console.log('Run \"claude-flow hive-mind init\" first');\n return;\n }\n\n // Use the metrics reader for real data\n const metricsReader = new HiveMindMetricsReader(dbPath);\n const swarms = metricsReader.getActiveSwarms();\n\n if (swarms.length === 0) {\n console.log(chalk.gray('No active swarms found'));\n metricsReader.close();\n return;\n }\n\n console.log(chalk.bold('\\n🐝 Active Hive Mind Swarms\\n'));\n\n for (const swarm of swarms) {\n console.log(chalk.yellow('═'.repeat(60)));\n console.log(chalk.cyan('Swarm:'), swarm.name);\n console.log(chalk.cyan('ID:'), swarm.id);\n console.log(chalk.cyan('Objective:'), swarm.objective);\n console.log(chalk.cyan('Queen Type:'), swarm.queen_type);\n console.log(chalk.cyan('Status:'), chalk.green(swarm.status));\n console.log(chalk.cyan('Created:'), new Date(swarm.created_at).toLocaleString());\n \n // Show real agent count\n console.log(chalk.cyan('Total Agents:'), swarm.agent_count || 0);\n\n console.log('\\n' + chalk.bold('Agents:'));\n\n // Group by role using real agent data\n const agents = swarm.agents || [];\n const queen = agents.find((a) => a.role === 'queen');\n const workers = agents.filter((a) => a.role === 'worker');\n\n if (queen) {\n console.log(' ' + chalk.magenta('👑 Queen:'), queen.name, chalk.gray(`(${queen.status})`));\n } else {\n console.log(' ' + chalk.gray('No queen assigned yet'));\n }\n\n console.log(' ' + chalk.blue('🐝 Workers:'));\n if (workers.length > 0) {\n workers.forEach((worker) => {\n const statusColor =\n worker.status === 'active' ? 'green' : worker.status === 'busy' ? 'yellow' : 'gray';\n console.log(` - ${worker.name} (${worker.type}) ${chalk[statusColor](worker.status)}`);\n });\n } else {\n console.log(' ' + chalk.gray('No workers spawned yet'));\n }\n\n // Get real task statistics\n const taskStats = swarm.task_metrics || {\n total: 0,\n completed: 0,\n in_progress: 0,\n pending: 0,\n failed: 0\n };\n\n console.log('\\n' + chalk.bold('Tasks:'));\n console.log(` Total: ${taskStats.total}`);\n console.log(` Completed: ${chalk.green(taskStats.completed || 0)}`);\n console.log(` In Progress: ${chalk.yellow(taskStats.in_progress || 0)}`);\n console.log(` Pending: ${chalk.gray(taskStats.pending || 0)}`);\n console.log(` ${chalk.bold('Completion:')} ${swarm.completion_percentage || 0}%`);\n\n // Show real memory count\n console.log('\\n' + chalk.bold('Collective Memory:'));\n console.log(` Entries: ${swarm.memory_count || 0}`);\n\n // Show real consensus count\n console.log('\\n' + chalk.bold('Consensus Decisions:'));\n console.log(` Total: ${swarm.consensus_count || 0}`);\n }\n\n console.log(chalk.yellow('═'.repeat(60)) + '\\n');\n\n metricsReader.close();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Show consensus decisions\n */\nasync function showConsensus(flags) {\n // Load SQLite before using Database constructor\n const hasSqlite = await loadSqlite();\n if (!hasSqlite) {\n console.error(chalk.red('Error: SQLite is required for this command'));\n return;\n }\n try {\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n const db = new Database(dbPath);\n\n const decisions = db\n .prepare(\n `\n SELECT cd.*, s.name as swarm_name\n FROM consensus_decisions cd\n JOIN swarms s ON cd.swarm_id = s.id\n ORDER BY cd.created_at DESC\n LIMIT 20\n `,\n )\n .all();\n\n if (decisions.length === 0) {\n console.log(chalk.gray('No consensus decisions found'));\n db.close();\n return;\n }\n\n console.log(chalk.bold('\\n🤝 Recent Consensus Decisions\\n'));\n\n decisions.forEach((decision) => {\n console.log(chalk.yellow('─'.repeat(50)));\n console.log(chalk.cyan('Swarm:'), decision.swarm_name);\n console.log(chalk.cyan('Topic:'), decision.topic);\n console.log(chalk.cyan('Decision:'), decision.decision);\n console.log(chalk.cyan('Algorithm:'), decision.algorithm);\n console.log(chalk.cyan('Confidence:'), `${(decision.confidence * 100).toFixed(1)}%`);\n console.log(chalk.cyan('Time:'), new Date(decision.created_at).toLocaleString());\n\n if (decision.votes) {\n const votes = JSON.parse(decision.votes);\n console.log(chalk.cyan('Votes:'));\n\n // Handle vote summary format (for/against/abstain/details)\n if (votes.for !== undefined || votes.against !== undefined || votes.abstain !== undefined) {\n console.log(` - for: ${votes.for || 0}`);\n console.log(` - against: ${votes.against || 0}`);\n console.log(` - abstain: ${votes.abstain || 0}`);\n\n // Display vote details properly if they exist\n if (votes.details && Array.isArray(votes.details)) {\n console.log(' - details:');\n votes.details.forEach((detail, index) => {\n if (typeof detail === 'object') {\n // Extract available fields\n const agent =\n detail.agentId ||\n detail.agent ||\n detail.id ||\n detail.name ||\n `agent-${index + 1}`;\n const vote = detail.vote || detail.choice || detail.decision || 'unknown';\n const reason = detail.reason || detail.justification || detail.rationale;\n\n // Build display string\n let displayString = ` ${index + 1}. Agent: ${agent}, Vote: ${vote}`;\n\n // Add reason if available\n if (reason && reason !== 'N/A' && reason !== '') {\n displayString += `, Reason: ${reason}`;\n }\n\n console.log(displayString);\n } else {\n console.log(` ${index + 1}. ${detail}`);\n }\n });\n }\n } else {\n // Handle individual agent votes format\n Object.entries(votes).forEach(([agent, vote]) => {\n console.log(` - ${agent}: ${vote}`);\n });\n }\n }\n });\n\n console.log(chalk.yellow('─'.repeat(50)) + '\\n');\n\n db.close();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Show performance metrics\n */\nasync function showMetrics(flags) {\n // Load SQLite before using Database constructor\n const hasSqlite = await loadSqlite();\n if (!hasSqlite) {\n console.error(chalk.red('Error: SQLite is required for this command'));\n return;\n }\n try {\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n const db = new Database(dbPath);\n\n // Get overall metrics\n const overallStats = db\n .prepare(\n `\n SELECT \n (SELECT COUNT(*) FROM swarms) as total_swarms,\n (SELECT COUNT(*) FROM agents) as total_agents,\n (SELECT COUNT(*) FROM tasks) as total_tasks,\n (SELECT COUNT(*) FROM tasks WHERE status = 'completed') as completed_tasks\n `,\n )\n .get();\n\n console.log(chalk.bold('\\n📊 Hive Mind Performance Metrics\\n'));\n\n // Get task status breakdown\n const taskBreakdown = db\n .prepare(\n `\n SELECT \n status,\n COUNT(*) as count\n FROM tasks\n GROUP BY status\n ORDER BY count DESC\n `,\n )\n .all();\n\n console.log(chalk.cyan('Overall Statistics:'));\n console.log(` Total Swarms: ${overallStats.total_swarms}`);\n console.log(` Total Agents: ${overallStats.total_agents}`);\n console.log(` Total Tasks: ${overallStats.total_tasks}`);\n console.log(` Completed Tasks: ${overallStats.completed_tasks}`);\n console.log(\n ` Success Rate: ${\n overallStats.total_tasks > 0\n ? ((overallStats.completed_tasks / overallStats.total_tasks) * 100).toFixed(1) + '%'\n : 'N/A'\n }`,\n );\n\n if (taskBreakdown.length > 0) {\n console.log('\\n' + chalk.cyan('Task Status Breakdown:'));\n taskBreakdown.forEach((status) => {\n const percentage =\n overallStats.total_tasks > 0\n ? ((status.count / overallStats.total_tasks) * 100).toFixed(1)\n : '0';\n const statusColor =\n status.status === 'completed'\n ? 'green'\n : status.status === 'in_progress'\n ? 'yellow'\n : status.status === 'failed'\n ? 'red'\n : 'gray';\n console.log(\n ` ${chalk[statusColor](status.status.charAt(0).toUpperCase() + status.status.slice(1))}: ${status.count} (${percentage}%)`,\n );\n });\n }\n\n // Get agent performance (check for completed_at column)\n let agentPerf = [];\n try {\n // Check if completed_at exists\n const hasCompletedAt = db\n .prepare(\n `\n SELECT COUNT(*) as count FROM pragma_table_info('tasks') \n WHERE name = 'completed_at'\n `,\n )\n .get();\n\n if (hasCompletedAt && hasCompletedAt.count > 0) {\n agentPerf = db\n .prepare(\n `\n SELECT \n a.name,\n a.type,\n COUNT(t.id) as tasks_assigned,\n SUM(CASE WHEN t.status = 'completed' THEN 1 ELSE 0 END) as tasks_completed,\n AVG(CASE WHEN t.completed_at IS NOT NULL \n THEN (julianday(t.completed_at) - julianday(t.created_at)) * 24 * 60 \n ELSE NULL END) as avg_completion_minutes\n FROM agents a\n LEFT JOIN tasks t ON a.id = t.agent_id\n GROUP BY a.id\n HAVING tasks_assigned > 0\n ORDER BY tasks_completed DESC\n LIMIT 10\n `,\n )\n .all();\n } else {\n // Simpler query without completed_at\n agentPerf = db\n .prepare(\n `\n SELECT \n a.name,\n a.type,\n COUNT(t.id) as tasks_assigned,\n SUM(CASE WHEN t.status = 'completed' THEN 1 ELSE 0 END) as tasks_completed,\n NULL as avg_completion_minutes\n FROM agents a\n LEFT JOIN tasks t ON a.id = t.agent_id\n GROUP BY a.id\n HAVING tasks_assigned > 0\n ORDER BY tasks_completed DESC\n LIMIT 10\n `,\n )\n .all();\n }\n } catch (error) {\n console.warn('Could not get agent performance:', error.message);\n }\n\n if (agentPerf.length > 0) {\n console.log('\\n' + chalk.cyan('Top Performing Agents:'));\n agentPerf.forEach((agent, index) => {\n const successRate =\n agent.tasks_assigned > 0\n ? ((agent.tasks_completed / agent.tasks_assigned) * 100).toFixed(1)\n : '0';\n console.log(` ${index + 1}. ${agent.name} (${agent.type})`);\n console.log(\n ` Tasks: ${agent.tasks_completed}/${agent.tasks_assigned} (${successRate}%)`,\n );\n if (agent.avg_completion_minutes) {\n console.log(` Avg Time: ${agent.avg_completion_minutes.toFixed(1)} minutes`);\n }\n });\n }\n\n // Get swarm performance\n const swarmPerf = db\n .prepare(\n `\n SELECT \n s.name,\n s.objective,\n (SELECT COUNT(*) FROM agents a WHERE a.swarm_id = s.id) as agent_count,\n (SELECT COUNT(*) FROM tasks t WHERE t.swarm_id = s.id) as task_count,\n (SELECT COUNT(*) FROM tasks t WHERE t.swarm_id = s.id AND t.status = 'completed') as completed_count,\n (SELECT COUNT(*) FROM collective_memory cm WHERE cm.swarm_id = s.id) as memory_entries,\n (SELECT COUNT(*) FROM consensus_decisions cd WHERE cd.swarm_id = s.id) as consensus_count\n FROM swarms s\n WHERE s.status = 'active'\n ORDER BY s.created_at DESC\n LIMIT 5\n `,\n )\n .all();\n\n if (swarmPerf.length > 0) {\n console.log('\\n' + chalk.cyan('Active Swarm Performance:'));\n swarmPerf.forEach((swarm) => {\n const successRate =\n swarm.task_count > 0\n ? ((swarm.completed_count / swarm.task_count) * 100).toFixed(1)\n : '0';\n console.log(`\\n ${chalk.yellow(swarm.name)}`);\n console.log(` Objective: ${swarm.objective.substring(0, 50)}...`);\n console.log(\n ` Agents: ${swarm.agent_count}, Tasks: ${swarm.completed_count}/${swarm.task_count} (${successRate}%)`,\n );\n console.log(\n ` Memory: ${swarm.memory_entries} entries, Consensus: ${swarm.consensus_count} decisions`,\n );\n });\n }\n\n // Get performance insights\n let avgTaskTime = { avg_minutes: null };\n try {\n // Check if completed_at exists\n const hasCompletedAt = db\n .prepare(\n `\n SELECT COUNT(*) as count FROM pragma_table_info('tasks') \n WHERE name = 'completed_at'\n `,\n )\n .get();\n\n if (hasCompletedAt && hasCompletedAt.count > 0) {\n avgTaskTime = db\n .prepare(\n `\n SELECT \n AVG(CASE WHEN completed_at IS NOT NULL \n THEN (julianday(completed_at) - julianday(created_at)) * 24 * 60 \n ELSE NULL END) as avg_minutes\n FROM tasks\n WHERE status = 'completed'\n `,\n )\n .get();\n }\n } catch (error) {\n console.warn('Could not calculate average task time:', error.message);\n }\n\n // Get agent type performance\n let agentTypePerf = [];\n try {\n // Check if completed_at exists\n const hasCompletedAt = db\n .prepare(\n `\n SELECT COUNT(*) as count FROM pragma_table_info('tasks') \n WHERE name = 'completed_at'\n `,\n )\n .get();\n\n if (hasCompletedAt && hasCompletedAt.count > 0) {\n agentTypePerf = db\n .prepare(\n `\n SELECT \n a.type,\n COUNT(t.id) as total_tasks,\n SUM(CASE WHEN t.status = 'completed' THEN 1 ELSE 0 END) as completed_tasks,\n AVG(CASE WHEN t.completed_at IS NOT NULL \n THEN (julianday(t.completed_at) - julianday(t.created_at)) * 24 * 60 \n ELSE NULL END) as avg_completion_minutes\n FROM agents a\n LEFT JOIN tasks t ON a.id = t.agent_id\n GROUP BY a.type\n HAVING total_tasks > 0\n ORDER BY completed_tasks DESC\n `,\n )\n .all();\n } else {\n // Simpler query without completed_at\n agentTypePerf = db\n .prepare(\n `\n SELECT \n a.type,\n COUNT(t.id) as total_tasks,\n SUM(CASE WHEN t.status = 'completed' THEN 1 ELSE 0 END) as completed_tasks,\n NULL as avg_completion_minutes\n FROM agents a\n LEFT JOIN tasks t ON a.id = t.agent_id\n GROUP BY a.type\n HAVING total_tasks > 0\n ORDER BY completed_tasks DESC\n `,\n )\n .all();\n }\n } catch (error) {\n console.warn('Could not get agent type performance:', error.message);\n }\n\n if (avgTaskTime.avg_minutes) {\n console.log('\\n' + chalk.cyan('Performance Insights:'));\n console.log(` Average Task Completion Time: ${avgTaskTime.avg_minutes.toFixed(1)} minutes`);\n\n if (agentTypePerf.length > 0) {\n console.log('\\n' + chalk.cyan('Agent Type Performance:'));\n agentTypePerf.forEach((type) => {\n const successRate =\n type.total_tasks > 0\n ? ((type.completed_tasks / type.total_tasks) * 100).toFixed(1)\n : '0';\n console.log(\n ` ${type.type.charAt(0).toUpperCase() + type.type.slice(1)}: ${type.completed_tasks}/${type.total_tasks} (${successRate}%)`,\n );\n if (type.avg_completion_minutes) {\n console.log(` Average time: ${type.avg_completion_minutes.toFixed(1)} minutes`);\n }\n });\n }\n }\n\n console.log('\\n');\n db.close();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Manage collective memory wizard\n */\nasync function manageMemoryWizard() {\n console.log(chalk.blue('\\n🧠 Collective Memory Management\\n'));\n\n const { action } = await inquirer.prompt([\n {\n type: 'list',\n name: 'action',\n message: 'What would you like to do with collective memory?',\n choices: [\n { name: '📋 View all memories', value: 'list' },\n { name: '🔍 Search memories', value: 'search' },\n { name: '💾 Store new memory', value: 'store' },\n { name: '📊 Memory statistics', value: 'stats' },\n { name: '🗑️ Clean old memories', value: 'clean' },\n { name: '📤 Export memory backup', value: 'export' },\n { name: '⬅️ Back to main menu', value: 'back' },\n ],\n },\n ]);\n\n switch (action) {\n case 'list':\n await listMemories();\n break;\n case 'search':\n await searchMemories();\n break;\n case 'store':\n await storeMemoryWizard();\n break;\n case 'stats':\n await showMemoryStats();\n break;\n case 'clean':\n await cleanMemories();\n break;\n case 'export':\n await exportMemoryBackup();\n break;\n case 'back':\n await hiveMindWizard();\n return;\n }\n\n // Ask if user wants to continue\n const { continue: continueAction } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'continue',\n message: 'Would you like to perform another memory operation?',\n default: true,\n },\n ]);\n\n if (continueAction) {\n await manageMemoryWizard();\n }\n}\n\n/**\n * Configure hive mind wizard\n */\nasync function configureWizard() {\n // TODO: Implement configuration wizard\n console.log(chalk.yellow('Configuration wizard coming soon...'));\n}\n\n/**\n * Main hive mind command handler\n */\nexport async function hiveMindCommand(args, flags) {\n const subcommand = args[0];\n const subArgs = args.slice(1);\n\n // Handle help flags\n if (\n !subcommand ||\n subcommand === '--help' ||\n subcommand === '-h' ||\n subcommand === 'help' ||\n flags.help\n ) {\n showHiveMindHelp();\n return;\n }\n\n // Warn about non-interactive environments for certain commands\n if ((subcommand === 'spawn' && (flags.claude || flags.spawn)) || subcommand === 'wizard') {\n warnNonInteractive('hive-mind ' + subcommand);\n }\n\n switch (subcommand) {\n case 'init':\n await initHiveMind(flags);\n break;\n\n case 'spawn':\n // Check for non-interactive mode FIRST (like alpha.83)\n if (flags['non-interactive'] || flags.nonInteractive) {\n // In non-interactive mode, skip wizard and use defaults\n if (subArgs.length === 0) {\n console.error(chalk.red('Error: Objective required in non-interactive mode'));\n console.log('Usage: claude-flow hive-mind spawn \"Your objective\" --non-interactive');\n return;\n }\n await spawnSwarm(subArgs, flags);\n } else if (flags.wizard || subArgs.length === 0) {\n await spawnSwarmWizard();\n } else {\n await spawnSwarm(subArgs, flags);\n }\n break;\n\n case 'status':\n await showStatus(flags);\n break;\n\n case 'sessions':\n await showSessions(flags);\n break;\n\n case 'resume':\n await resumeSession(subArgs, flags);\n break;\n\n case 'stop':\n await stopSession(subArgs, flags);\n break;\n\n case 'consensus':\n await showConsensus(flags);\n break;\n\n case 'memory':\n await manageMemoryWizard();\n break;\n\n case 'metrics':\n await showMetrics(flags);\n break;\n\n case 'wizard':\n await hiveMindWizard(flags);\n break;\n\n case 'help':\n case '--help':\n case '-h':\n showHiveMindHelp();\n break;\n\n default:\n console.error(chalk.red(`Unknown subcommand: ${subcommand}`));\n console.log('Run \"claude-flow hive-mind help\" for usage information');\n exit(1);\n }\n}\n\n/**\n * List all memories in the collective memory store\n */\nasync function listMemories() {\n // Load SQLite before using Database constructor\n const hasSqlite = await loadSqlite();\n if (!hasSqlite) {\n console.error(chalk.red('Error: SQLite is required for this command'));\n return;\n }\n try {\n console.log(chalk.blue('\\n📋 Collective Memory Store\\n'));\n\n // Read directly from hive.db collective_memory table\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n const db = new Database(dbPath);\n\n const memories = db\n .prepare(\n `\n SELECT cm.*, s.name as swarm_name\n FROM collective_memory cm\n LEFT JOIN swarms s ON cm.swarm_id = s.id\n ORDER BY cm.created_at DESC\n LIMIT 50\n `,\n )\n .all();\n\n db.close();\n\n if (!memories || memories.length === 0) {\n console.log(chalk.yellow('No memories found in the collective store.'));\n console.log(\n chalk.gray('Try storing some memories first using the \"💾 Store new memory\" option.'),\n );\n return;\n }\n\n console.log(chalk.gray(`Found ${memories.length} memories in the collective store:\\n`));\n\n memories.forEach((memory, index) => {\n console.log(chalk.cyan(`${index + 1}. ${memory.key}`));\n console.log(` Swarm: ${memory.swarm_name || memory.swarm_id}`);\n console.log(` Type: ${memory.type || 'knowledge'}`);\n console.log(` Created: ${new Date(memory.created_at).toLocaleString()}`);\n console.log(` Created by: ${memory.created_by || 'system'}`);\n \n // Parse and display value\n let displayValue = memory.value;\n try {\n const parsed = JSON.parse(memory.value);\n displayValue = JSON.stringify(parsed);\n } catch {\n // Keep as string\n }\n \n if (displayValue.length > 100) {\n console.log(` Value: ${displayValue.substring(0, 100)}...`);\n } else {\n console.log(` Value: ${displayValue}`);\n }\n \n if (memory.confidence !== null && memory.confidence !== 1) {\n console.log(` Confidence: ${(memory.confidence * 100).toFixed(1)}%`);\n }\n \n console.log('');\n });\n } catch (error) {\n console.error(chalk.red('Error listing memories:'), error.message);\n console.log(chalk.gray('This might be because no memories have been stored yet.'));\n }\n}\n\n/**\n * Search memories by keyword\n */\nasync function searchMemories() {\n // Load SQLite before using Database constructor\n const hasSqlite = await loadSqlite();\n if (!hasSqlite) {\n console.error(chalk.red('Error: SQLite is required for this command'));\n return;\n }\n try {\n const { searchTerm } = await inquirer.prompt([\n {\n type: 'input',\n name: 'searchTerm',\n message: 'Enter search term:',\n validate: (input) => input.length > 0,\n },\n ]);\n\n console.log(chalk.blue(`\\n🔍 Searching for: \"${searchTerm}\"\\n`));\n\n // Search directly in hive.db collective_memory table\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n const db = new Database(dbPath);\n\n const searchPattern = `%${searchTerm}%`;\n const memories = db\n .prepare(\n `\n SELECT cm.*, s.name as swarm_name\n FROM collective_memory cm\n LEFT JOIN swarms s ON cm.swarm_id = s.id\n WHERE cm.key LIKE ? OR cm.value LIKE ? OR cm.type LIKE ?\n ORDER BY cm.created_at DESC\n LIMIT 50\n `,\n )\n .all(searchPattern, searchPattern, searchPattern);\n\n db.close();\n\n if (!memories || memories.length === 0) {\n console.log(chalk.yellow('No memories found matching your search.'));\n return;\n }\n\n console.log(chalk.gray(`Found ${memories.length} memories matching \"${searchTerm}\":\\n`));\n\n memories.forEach((memory, index) => {\n console.log(chalk.green(`${index + 1}. ${memory.key}`));\n console.log(` Swarm: ${memory.swarm_name || memory.swarm_id}`);\n console.log(` Type: ${memory.type || 'knowledge'}`);\n console.log(` Created: ${new Date(memory.created_at).toLocaleString()}`);\n \n // Parse and display value with highlighting\n let displayValue = memory.value;\n try {\n const parsed = JSON.parse(memory.value);\n displayValue = JSON.stringify(parsed, null, 2);\n } catch {\n // Keep as string\n }\n \n console.log(` Value: ${displayValue}`);\n console.log('');\n });\n } catch (error) {\n console.error(chalk.red('Error searching memories:'), error.message);\n }\n}\n\n/**\n * Store new memory wizard\n */\nasync function storeMemoryWizard() {\n try {\n const answers = await inquirer.prompt([\n {\n type: 'input',\n name: 'key',\n message: 'Memory key (identifier):',\n validate: (input) => input.length > 0,\n },\n {\n type: 'list',\n name: 'category',\n message: 'Memory category:',\n choices: [\n 'consensus',\n 'decision',\n 'pattern',\n 'learning',\n 'coordination',\n 'performance',\n 'configuration',\n 'general',\n ],\n },\n {\n type: 'editor',\n name: 'value',\n message: 'Memory content (JSON or text):',\n },\n ]);\n\n const mcpWrapper = await getMcpWrapper();\n let memoryValue;\n\n // Try to parse as JSON, fall back to string\n try {\n memoryValue = JSON.parse(answers.value);\n } catch {\n memoryValue = answers.value;\n }\n\n await mcpWrapper.storeMemory('hive-mind', answers.key, memoryValue, answers.category);\n\n console.log(chalk.green(`\\n✅ Memory stored successfully!`));\n console.log(`Key: ${answers.key}`);\n console.log(`Category: ${answers.category}`);\n } catch (error) {\n console.error(chalk.red('Error storing memory:'), error.message);\n }\n}\n\n/**\n * Show memory statistics\n */\nasync function showMemoryStats() {\n try {\n console.log(chalk.blue('\\n📊 Memory Statistics\\n'));\n\n const mcpWrapper = await getMcpWrapper();\n\n // Search for all memories with an empty pattern to get everything\n const searchResult = await mcpWrapper.searchMemory('hive-mind', '');\n\n // Handle different possible response structures\n let memories = [];\n if (searchResult && Array.isArray(searchResult.results)) {\n memories = searchResult.results;\n } else if (searchResult && Array.isArray(searchResult)) {\n memories = searchResult;\n } else if (searchResult && searchResult.data && Array.isArray(searchResult.data)) {\n memories = searchResult.data;\n }\n\n if (!memories || memories.length === 0) {\n console.log(chalk.yellow('No memories found.'));\n console.log(chalk.gray('Use \"Store new memory\" to create your first memory.'));\n return;\n }\n\n // Calculate statistics\n const stats = {\n total: memories.length,\n categories: {},\n oldestDate: null,\n newestDate: null,\n totalSize: 0,\n };\n\n memories.forEach((memory) => {\n // Count by category\n const category = memory.category || memory.type || 'general';\n stats.categories[category] = (stats.categories[category] || 0) + 1;\n\n // Track dates\n const date = new Date(memory.timestamp || Date.now());\n if (!stats.oldestDate || date < stats.oldestDate) {\n stats.oldestDate = date;\n }\n if (!stats.newestDate || date > stats.newestDate) {\n stats.newestDate = date;\n }\n\n // Estimate size\n stats.totalSize += JSON.stringify(memory).length;\n });\n\n console.log(chalk.cyan('Total memories:'), stats.total);\n console.log(chalk.cyan('Estimated size:'), `${(stats.totalSize / 1024).toFixed(2)} KB`);\n console.log(\n chalk.cyan('Date range:'),\n `${stats.oldestDate?.toLocaleDateString()} - ${stats.newestDate?.toLocaleDateString()}`,\n );\n\n console.log(chalk.cyan('\\nBy category:'));\n Object.entries(stats.categories).forEach(([category, count]) => {\n console.log(` ${category}: ${count}`);\n });\n } catch (error) {\n console.error(chalk.red('Error getting memory stats:'), error.message);\n }\n}\n\n/**\n * Clean old memories\n */\nasync function cleanMemories() {\n try {\n const { days } = await inquirer.prompt([\n {\n type: 'number',\n name: 'days',\n message: 'Remove memories older than how many days?',\n default: 30,\n validate: (input) => input > 0,\n },\n ]);\n\n const { confirm } = await inquirer.prompt([\n {\n type: 'confirm',\n name: 'confirm',\n message: `Are you sure you want to delete memories older than ${days} days?`,\n default: false,\n },\n ]);\n\n if (!confirm) {\n console.log(chalk.yellow('Operation cancelled.'));\n return;\n }\n\n const mcpWrapper = await getMcpWrapper();\n\n // Get all memories first\n const searchResult = await mcpWrapper.searchMemory('hive-mind', '');\n\n // Handle different possible response structures\n let memories = [];\n if (searchResult && Array.isArray(searchResult.results)) {\n memories = searchResult.results;\n } else if (searchResult && Array.isArray(searchResult)) {\n memories = searchResult;\n } else if (searchResult && searchResult.data && Array.isArray(searchResult.data)) {\n memories = searchResult.data;\n }\n\n const cutoffDate = new Date();\n cutoffDate.setDate(cutoffDate.getDate() - days);\n\n // Filter memories older than cutoff date\n const oldMemories = memories.filter((memory) => {\n const memoryDate = new Date(memory.timestamp || 0);\n return memoryDate < cutoffDate;\n });\n\n if (oldMemories.length === 0) {\n console.log(chalk.yellow('\\n🎉 No old memories found to clean.'));\n return;\n }\n\n console.log(chalk.green(`\\n✅ Found ${oldMemories.length} old memories to clean.`));\n console.log(chalk.gray('Note: Individual memory deletion not yet implemented in MCPWrapper.'));\n console.log(chalk.gray('Consider implementing batch deletion or memory lifecycle management.'));\n } catch (error) {\n console.error(chalk.red('Error cleaning memories:'), error.message);\n }\n}\n\n/**\n * Export memory backup\n */\nasync function exportMemoryBackup() {\n try {\n const { filename } = await inquirer.prompt([\n {\n type: 'input',\n name: 'filename',\n message: 'Export filename:',\n default: `hive-mind-memory-backup-${new Date().toISOString().split('T')[0]}.json`,\n },\n ]);\n\n const mcpWrapper = await getMcpWrapper();\n\n // Get all memories using search\n const searchResult = await mcpWrapper.searchMemory('hive-mind', '');\n\n // Handle different possible response structures\n let memories = [];\n if (searchResult && Array.isArray(searchResult.results)) {\n memories = searchResult.results;\n } else if (searchResult && Array.isArray(searchResult)) {\n memories = searchResult;\n } else if (searchResult && searchResult.data && Array.isArray(searchResult.data)) {\n memories = searchResult.data;\n }\n\n const backup = {\n exportDate: new Date().toISOString(),\n version: '1.0',\n totalMemories: memories.length,\n namespace: 'hive-mind',\n memories: memories,\n };\n\n const fs = await import('fs');\n fs.writeFileSync(filename, JSON.stringify(backup, null, 2));\n\n console.log(chalk.green(`\\n✅ Memory backup exported to: ${filename}`));\n console.log(chalk.cyan(`Exported ${memories.length} memories`));\n } catch (error) {\n console.error(chalk.red('Error exporting memory backup:'), error.message);\n }\n}\n\n/**\n * Get active session ID for a swarm\n */\nasync function getActiveSessionId(swarmId) {\n const sessionManager = new HiveMindSessionManager();\n try {\n const sessions = await sessionManager.getActiveSessions();\n const activeSession = sessions.find(s => s.swarm_id === swarmId && s.status === 'active');\n return activeSession ? activeSession.id : null;\n } finally {\n sessionManager.close();\n }\n}\n\n/**\n * Spawn Claude Code with Hive Mind coordination instructions\n */\nasync function spawnClaudeCodeInstances(swarmId, swarmName, objective, workers, flags) {\n console.log('\\n' + chalk.bold('🚀 Launching Claude Code with Hive Mind Coordination'));\n console.log(chalk.gray('─'.repeat(60)));\n\n const spinner = ora('Preparing Hive Mind coordination prompt...').start();\n\n try {\n // Generate comprehensive Hive Mind prompt\n const workerGroups = groupWorkersByType(workers);\n const hiveMindPrompt = generateHiveMindPrompt(\n swarmId,\n swarmName,\n objective,\n workers,\n workerGroups,\n flags,\n );\n\n spinner.succeed('Hive Mind coordination prompt ready!');\n\n // Display coordination summary\n console.log('\\n' + chalk.bold('🧠 Hive Mind Configuration'));\n console.log(chalk.gray('─'.repeat(60)));\n console.log(chalk.cyan('Swarm ID:'), swarmId);\n console.log(chalk.cyan('Objective:'), objective);\n console.log(chalk.cyan('Queen Type:'), flags.queenType || 'strategic');\n console.log(chalk.cyan('Worker Count:'), workers.length);\n console.log(chalk.cyan('Worker Types:'), Object.keys(workerGroups).join(', '));\n console.log(chalk.cyan('Consensus Algorithm:'), flags.consensus || 'majority');\n console.log(chalk.cyan('MCP Tools:'), 'Full Claude-Flow integration enabled');\n\n try {\n // ALWAYS save the prompt file first (fix for issue #330)\n // Ensure sessions directory exists\n const sessionsDir = path.join('.hive-mind', 'sessions');\n await mkdirAsync(sessionsDir, { recursive: true });\n\n const promptFile = path.join(sessionsDir, `hive-mind-prompt-${swarmId}.txt`);\n await writeFile(promptFile, hiveMindPrompt, 'utf8');\n console.log(chalk.green(`\\n✓ Hive Mind prompt saved to: ${promptFile}`));\n\n // Check if claude command exists\n const { spawn: childSpawn, execSync } = await import('child_process');\n let claudeAvailable = false;\n\n try {\n execSync('which claude', { stdio: 'ignore' });\n claudeAvailable = true;\n } catch {\n console.log(chalk.yellow('\\n⚠️ Claude Code CLI not found in PATH'));\n console.log(chalk.gray('Install it with: npm install -g @anthropic-ai/claude-code'));\n console.log(chalk.gray('\\nFalling back to displaying instructions...'));\n }\n\n if (claudeAvailable && !flags.dryRun) {\n // Inject memory coordination protocol into CLAUDE.md\n try {\n const { injectMemoryProtocol, enhanceHiveMindPrompt } = await import('./inject-memory-protocol.js');\n await injectMemoryProtocol();\n \n // Enhance the prompt with memory coordination instructions\n hiveMindPrompt = enhanceHiveMindPrompt(hiveMindPrompt, workers);\n console.log(chalk.green('📝 Memory coordination protocol injected into CLAUDE.md'));\n } catch (err) {\n // If injection module not available, continue with original prompt\n console.log(chalk.yellow('⚠️ Memory protocol injection not available, using standard prompt'));\n }\n \n // Check if we should run in non-interactive mode\n // Respect --non-interactive flag regardless of --claude\n const isNonInteractive = flags['non-interactive'] || flags.nonInteractive;\n \n // Build arguments in correct order: flags first, then prompt\n const claudeArgs = [];\n \n // Add non-interactive flags FIRST if needed\n if (isNonInteractive) {\n claudeArgs.push('-p'); // Print mode\n claudeArgs.push('--output-format', 'stream-json'); // JSON streaming \n claudeArgs.push('--verbose'); // Verbose output\n console.log(chalk.cyan('🤖 Running in non-interactive mode'));\n }\n\n // Add auto-permission flag BEFORE the prompt\n if (flags['dangerously-skip-permissions'] !== false && !flags['no-auto-permissions']) {\n claudeArgs.push('--dangerously-skip-permissions');\n if (!isNonInteractive) {\n console.log(\n chalk.yellow(\n '🔓 Using --dangerously-skip-permissions by default for seamless hive-mind execution',\n ),\n );\n }\n }\n \n // Add the prompt as the LAST argument\n claudeArgs.push(hiveMindPrompt);\n\n // Spawn claude with properly ordered arguments\n const claudeProcess = childSpawn('claude', claudeArgs, {\n stdio: 'inherit',\n shell: false,\n });\n\n // Track child process PID in session\n const sessionManager = new HiveMindSessionManager();\n const sessionId = await getActiveSessionId(swarmId);\n if (sessionId && claudeProcess.pid) {\n sessionManager.addChildPid(sessionId, claudeProcess.pid);\n }\n\n // Set up SIGINT handler for automatic session pausing\n let isExiting = false;\n const sigintHandler = async () => {\n if (isExiting) return;\n isExiting = true;\n\n console.log('\\n\\n' + chalk.yellow('⏸️ Pausing session and terminating Claude Code...'));\n \n try {\n // Terminate Claude Code process\n if (claudeProcess && !claudeProcess.killed) {\n claudeProcess.kill('SIGTERM');\n }\n\n // Save checkpoint and pause session\n if (sessionId) {\n const checkpointData = {\n timestamp: new Date().toISOString(),\n swarmId,\n objective,\n status: 'paused_by_user',\n reason: 'User pressed Ctrl+C during Claude Code execution',\n claudePid: claudeProcess.pid,\n };\n \n await sessionManager.saveCheckpoint(sessionId, 'auto-pause-claude', checkpointData);\n await sessionManager.pauseSession(sessionId);\n \n console.log(chalk.green('✓') + ' Session paused successfully');\n console.log(chalk.cyan('\\nTo resume this session, run:'));\n console.log(chalk.bold(` claude-flow hive-mind resume ${sessionId}`));\n }\n \n sessionManager.close();\n process.exit(0);\n } catch (error) {\n console.error(chalk.red('Error pausing session:'), error.message);\n sessionManager.close();\n process.exit(1);\n }\n };\n\n // Register SIGINT handler\n process.on('SIGINT', sigintHandler);\n process.on('SIGTERM', sigintHandler);\n\n // Handle stdout\n if (claudeProcess.stdout) {\n claudeProcess.stdout.on('data', (data) => {\n console.log(data.toString());\n });\n }\n\n // Handle stderr\n if (claudeProcess.stderr) {\n claudeProcess.stderr.on('data', (data) => {\n console.error(chalk.red(data.toString()));\n });\n }\n\n // Handle process exit\n claudeProcess.on('exit', (code) => {\n // Remove child PID from session\n if (sessionId && claudeProcess.pid) {\n sessionManager.removeChildPid(sessionId, claudeProcess.pid);\n sessionManager.close();\n }\n\n if (code === 0) {\n console.log(chalk.green('\\n✓ Claude Code completed successfully'));\n } else if (code !== null) {\n console.log(chalk.red(`\\n✗ Claude Code exited with code ${code}`));\n }\n });\n\n console.log(chalk.green('\\n✓ Claude Code launched with Hive Mind coordination'));\n console.log(chalk.blue(' The Queen coordinator will orchestrate all worker agents'));\n console.log(\n chalk.blue(' Use MCP tools for collective intelligence and task distribution'),\n );\n console.log(chalk.gray(` Prompt file saved at: ${promptFile}`));\n } else if (flags.dryRun) {\n console.log(chalk.blue('\\nDry run - would execute Claude Code with prompt:'));\n console.log(chalk.gray('Prompt length:'), hiveMindPrompt.length, 'characters');\n console.log(chalk.gray('\\nFirst 500 characters of prompt:'));\n console.log(chalk.yellow(hiveMindPrompt.substring(0, 500) + '...'));\n console.log(chalk.gray(`\\nFull prompt saved to: ${promptFile}`));\n } else {\n // Claude not available - show instructions with already saved prompt\n console.log(chalk.yellow('\\n📋 Manual Execution Instructions:'));\n console.log(chalk.gray('─'.repeat(50)));\n console.log(chalk.gray('1. Install Claude Code:'));\n console.log(chalk.green(' npm install -g @anthropic-ai/claude-code'));\n console.log(chalk.gray('\\n2. Run with the saved prompt:'));\n console.log(chalk.green(` claude < ${promptFile}`));\n console.log(chalk.gray('\\n3. Or copy the prompt manually:'));\n console.log(chalk.green(` cat ${promptFile} | claude`));\n console.log(chalk.gray('\\n4. With auto-permissions:'));\n console.log(chalk.green(` claude --dangerously-skip-permissions < ${promptFile}`));\n }\n } catch (error) {\n console.error(chalk.red('\\nFailed to launch Claude Code:'), error.message);\n\n // Save prompt as fallback\n const promptFile = `hive-mind-prompt-${swarmId}-fallback.txt`;\n await writeFile(promptFile, hiveMindPrompt, 'utf8');\n console.log(chalk.green(`\\n✓ Prompt saved to: ${promptFile}`));\n console.log(chalk.yellow('\\nYou can run Claude Code manually with the saved prompt'));\n }\n\n console.log('\\n' + chalk.bold('💡 Pro Tips:'));\n console.log(chalk.gray('─'.repeat(30)));\n console.log('• Use --auto-spawn to launch instances automatically');\n console.log('• Add --verbose for detailed coordination context');\n console.log('• Monitor with: claude-flow hive-mind status');\n console.log('• Share memories: mcp__ruv-swarm__memory_usage');\n } catch (error) {\n spinner.fail('Failed to prepare Claude Code coordination');\n console.error(chalk.red('Error:'), error.message);\n }\n}\n\n/**\n * Generate comprehensive Hive Mind prompt for Claude Code\n */\nfunction generateHiveMindPrompt(swarmId, swarmName, objective, workers, workerGroups, flags) {\n console.log(chalk.cyan(`\\n🔍 generateHiveMindPrompt received objective: \"${objective}\"`));\n const currentTime = new Date().toISOString();\n const workerTypes = Object.keys(workerGroups);\n const queenType = flags.queenType || 'strategic';\n const consensusAlgorithm = flags.consensus || 'majority';\n\n return `🧠 HIVE MIND COLLECTIVE INTELLIGENCE SYSTEM\n═══════════════════════════════════════════════\n\nYou are the Queen coordinator of a Hive Mind swarm with collective intelligence capabilities.\n\nHIVE MIND CONFIGURATION:\n📌 Swarm ID: ${swarmId}\n📌 Swarm Name: ${swarmName}\n🎯 Objective: ${objective}\n👑 Queen Type: ${queenType}\n🐝 Worker Count: ${workers.length}\n🤝 Consensus Algorithm: ${consensusAlgorithm}\n⏰ Initialized: ${currentTime}\n\nWORKER DISTRIBUTION:\n${workerTypes.map((type) => `• ${type}: ${workerGroups[type].length} agents`).join('\\n')}\n\n🔧 AVAILABLE MCP TOOLS FOR HIVE MIND COORDINATION:\n\n1️⃣ **COLLECTIVE INTELLIGENCE**\n mcp__claude-flow__consensus_vote - Democratic decision making\n mcp__claude-flow__memory_share - Share knowledge across the hive\n mcp__claude-flow__neural_sync - Synchronize neural patterns\n mcp__claude-flow__swarm_think - Collective problem solving\n\n2️⃣ **QUEEN COORDINATION**\n mcp__claude-flow__queen_command - Issue directives to workers\n mcp__claude-flow__queen_monitor - Monitor swarm health\n mcp__claude-flow__queen_delegate - Delegate complex tasks\n mcp__claude-flow__queen_aggregate - Aggregate worker results\n\n3️⃣ **WORKER MANAGEMENT**\n mcp__claude-flow__agent_spawn - Create specialized workers\n mcp__claude-flow__agent_assign - Assign tasks to workers\n mcp__claude-flow__agent_communicate - Inter-agent communication\n mcp__claude-flow__agent_metrics - Track worker performance\n\n4️⃣ **TASK ORCHESTRATION**\n mcp__claude-flow__task_create - Create hierarchical tasks\n mcp__claude-flow__task_distribute - Distribute work efficiently\n mcp__claude-flow__task_monitor - Track task progress\n mcp__claude-flow__task_aggregate - Combine task results\n\n5️⃣ **MEMORY & LEARNING**\n mcp__claude-flow__memory_store - Store collective knowledge\n mcp__claude-flow__memory_retrieve - Access shared memory\n mcp__claude-flow__neural_train - Learn from experiences\n mcp__claude-flow__pattern_recognize - Identify patterns\n\n📋 HIVE MIND EXECUTION PROTOCOL:\n\nAs the Queen coordinator, you must:\n\n1. **INITIALIZE THE HIVE** (CRITICAL: Use Claude Code's Task Tool for Agents):\n \n Step 1: Optional MCP Coordination Setup (Single Message):\n [MCP Tools - Coordination Only]:\n ${workerTypes.map((type) => ` mcp__claude-flow__agent_spawn { \"type\": \"${type}\", \"count\": ${workerGroups[type].length} }`).join('\\n')}\n mcp__claude-flow__memory_store { \"key\": \"hive/objective\", \"value\": \"${objective}\" }\n mcp__claude-flow__memory_store { \"key\": \"hive/queen\", \"value\": \"${queenType}\" }\n mcp__claude-flow__swarm_think { \"topic\": \"initial_strategy\" }\n \n Step 2: REQUIRED - Spawn ACTUAL Agents with Claude Code's Task Tool (Single Message):\n [Claude Code Task Tool - CONCURRENT Agent Execution]:\n ${workerTypes.map((type) => ` Task(\"${type.charAt(0).toUpperCase() + type.slice(1)} Agent\", \"You are a ${type} in the hive. Coordinate via hooks. ${getWorkerTypeInstructions(type).split('\\n')[0]}\", \"${type}\")`).join('\\n')}\n \n Step 3: Batch ALL Todos Together (Single TodoWrite Call):\n TodoWrite { \"todos\": [\n { \"id\": \"1\", \"content\": \"Initialize hive mind collective\", \"status\": \"in_progress\", \"priority\": \"high\" },\n { \"id\": \"2\", \"content\": \"Establish consensus protocols\", \"status\": \"pending\", \"priority\": \"high\" },\n { \"id\": \"3\", \"content\": \"Distribute initial tasks to workers\", \"status\": \"pending\", \"priority\": \"high\" },\n { \"id\": \"4\", \"content\": \"Set up collective memory\", \"status\": \"pending\", \"priority\": \"high\" },\n { \"id\": \"5\", \"content\": \"Monitor worker health\", \"status\": \"pending\", \"priority\": \"medium\" },\n { \"id\": \"6\", \"content\": \"Aggregate worker outputs\", \"status\": \"pending\", \"priority\": \"medium\" },\n { \"id\": \"7\", \"content\": \"Learn from patterns\", \"status\": \"pending\", \"priority\": \"low\" },\n { \"id\": \"8\", \"content\": \"Optimize performance\", \"status\": \"pending\", \"priority\": \"low\" }\n ] }\n\n2. **ESTABLISH COLLECTIVE INTELLIGENCE**:\n - Use consensus_vote for major decisions\n - Share all discoveries via memory_share\n - Synchronize learning with neural_sync\n - Coordinate strategy with swarm_think\n\n3. **QUEEN LEADERSHIP PATTERNS**:\n ${\n queenType === 'strategic'\n ? `\n - Focus on high-level planning and coordination\n - Delegate implementation details to workers\n - Monitor overall progress and adjust strategy\n - Make executive decisions when consensus fails`\n : ''\n }\n ${\n queenType === 'tactical'\n ? `\n - Manage detailed task breakdowns and assignments\n - Closely monitor worker progress and efficiency\n - Optimize resource allocation and load balancing\n - Intervene directly when workers need guidance`\n : ''\n }\n ${\n queenType === 'adaptive'\n ? `\n - Learn from swarm performance and adapt strategies\n - Experiment with different coordination patterns\n - Use neural training to improve over time\n - Balance between strategic and tactical approaches`\n : ''\n }\n\n4. **WORKER COORDINATION**:\n - Spawn workers based on task requirements\n - Assign tasks according to worker specializations\n - Enable peer-to-peer communication for collaboration\n - Monitor and rebalance workloads as needed\n\n5. **CONSENSUS MECHANISMS**:\n ${consensusAlgorithm === 'majority' ? '- Decisions require >50% worker agreement' : ''}\n ${consensusAlgorithm === 'unanimous' ? '- All workers must agree for major decisions' : ''}\n ${consensusAlgorithm === 'weighted' ? '- Worker votes weighted by expertise and performance' : ''}\n ${consensusAlgorithm === 'quorum' ? '- Decisions require 2/3 worker participation' : ''}\n\n6. **COLLECTIVE MEMORY**:\n - Store all important decisions in shared memory\n - Tag memories with worker IDs and timestamps\n - Use memory namespaces: hive/, queen/, workers/, tasks/\n - Implement memory consensus for critical data\n\n7. **PERFORMANCE OPTIMIZATION**:\n - Monitor swarm metrics continuously\n - Identify and resolve bottlenecks\n - Train neural networks on successful patterns\n - Scale worker count based on workload\n\n💡 HIVE MIND BEST PRACTICES:\n\n✅ ALWAYS use BatchTool for parallel operations\n✅ Store decisions in collective memory immediately\n✅ Use consensus for critical path decisions\n✅ Monitor worker health and reassign if needed\n✅ Learn from failures and adapt strategies\n✅ Maintain constant inter-agent communication\n✅ Aggregate results before final delivery\n\n❌ NEVER make unilateral decisions without consensus\n❌ NEVER let workers operate in isolation\n❌ NEVER ignore performance metrics\n❌ NEVER skip memory synchronization\n❌ NEVER abandon failing workers\n\n🎯 OBJECTIVE EXECUTION STRATEGY:\n\nFor the objective: \"${objective}\"\n\n1. Break down into major phases using swarm_think\n2. Create specialized worker teams for each phase\n3. Establish success criteria and checkpoints\n4. Implement feedback loops and adaptation\n5. Aggregate and synthesize all worker outputs\n6. Deliver comprehensive solution with consensus\n\n⚡ CRITICAL: CONCURRENT EXECUTION WITH CLAUDE CODE'S TASK TOOL:\n\nThe Hive Mind MUST use Claude Code's Task tool for actual agent execution:\n\n✅ CORRECT Pattern:\n[Single Message - All Agents Spawned Concurrently]:\n Task(\"Researcher\", \"Research patterns and best practices...\", \"researcher\")\n Task(\"Coder\", \"Implement core features...\", \"coder\")\n Task(\"Tester\", \"Create comprehensive tests...\", \"tester\")\n Task(\"Analyst\", \"Analyze performance metrics...\", \"analyst\")\n TodoWrite { todos: [8-10 todos ALL in ONE call] }\n\n❌ WRONG Pattern:\nMessage 1: Task(\"agent1\", ...)\nMessage 2: Task(\"agent2\", ...)\nMessage 3: TodoWrite { single todo }\n// This breaks parallel coordination!\n\nRemember:\n- Use Claude Code's Task tool to spawn ALL agents in ONE message\n- MCP tools are ONLY for coordination setup, not agent execution\n- Batch ALL TodoWrite operations (5-10+ todos minimum)\n- Execute ALL file operations concurrently\n- Store multiple memories simultaneously\n\n🚀 BEGIN HIVE MIND EXECUTION:\n\nInitialize the swarm now with the configuration above. Use your collective intelligence to solve the objective efficiently. The Queen must coordinate, workers must collaborate, and the hive must think as one.\n\nRemember: You are not just coordinating agents - you are orchestrating a collective intelligence that is greater than the sum of its parts.`;\n}\n\n/**\n * Generate comprehensive coordination instructions for Claude Code instances\n */\nfunction generateCoordinationInstructions(swarmId, swarmName, objective, workers) {\n return {\n swarmId,\n swarmName,\n objective,\n hiveMindEndpoint: 'ws://localhost:3000/hive-mind',\n mcpTools: [\n 'mcp__ruv-swarm__memory_usage',\n 'mcp__ruv-swarm__swarm_monitor',\n 'mcp__ruv-swarm__task_orchestrate',\n 'mcp__ruv-swarm__neural_train',\n 'mcp__ruv-swarm__consensus_vote',\n 'mcp__ruv-swarm__agent_spawn',\n 'mcp__ruv-swarm__swarm_status',\n ],\n coordinationProtocol: {\n memoryNamespace: `hive-mind-${swarmId}`,\n consensusThreshold: 0.7,\n taskUpdateInterval: 30000,\n healthCheckInterval: 60000,\n },\n workerCapabilities: workers.map((w) => ({\n id: w.id,\n type: w.type,\n capabilities: JSON.parse(w.capabilities),\n })),\n };\n}\n\n/**\n * Group workers by type for specialized spawning\n */\nfunction groupWorkersByType(workers) {\n return workers.reduce((groups, worker) => {\n if (!groups[worker.type]) {\n groups[worker.type] = [];\n }\n groups[worker.type].push(worker);\n return groups;\n }, {});\n}\n\n/**\n * Create Claude Code spawn command with coordination context\n */\nfunction createClaudeCodeSpawnCommand(\n swarmId,\n swarmName,\n objective,\n workerType,\n typeWorkers,\n instructions,\n) {\n const context = `You are a ${workerType} agent in the \"${swarmName}\" Hive Mind swarm.\n\n🎯 MISSION: ${objective}\n\n🐝 SWARM COORDINATION:\n- Swarm ID: ${swarmId}\n- Your Role: ${workerType.toUpperCase()} specialist\n- Team Size: ${typeWorkers.length} ${workerType}(s)\n- Coordination: Hive Mind collective intelligence\n\n🧠 MANDATORY COORDINATION PROTOCOL:\n1. BEFORE starting work:\n mcp__ruv-swarm__memory_usage {\"action\": \"retrieve\", \"key\": \"hive-mind-${swarmId}/status\"}\n mcp__ruv-swarm__swarm_status {\"swarmId\": \"${swarmId}\"}\n\n2. DURING work (after each major step):\n mcp__ruv-swarm__memory_usage {\"action\": \"store\", \"key\": \"hive-mind-${swarmId}/${workerType}/progress\", \"value\": {\"step\": \"X\", \"status\": \"Y\", \"findings\": \"Z\"}}\n mcp__ruv-swarm__task_orchestrate {\"swarmId\": \"${swarmId}\", \"update\": {\"agentId\": \"your-id\", \"progress\": \"details\"}}\n\n3. FOR decisions requiring consensus:\n mcp__ruv-swarm__consensus_vote {\"swarmId\": \"${swarmId}\", \"topic\": \"decision topic\", \"vote\": \"your choice\", \"rationale\": \"reasoning\"}\n\n4. WHEN sharing insights:\n mcp__ruv-swarm__memory_usage {\"action\": \"store\", \"key\": \"hive-mind-${swarmId}/insights/${workerType}\", \"value\": {\"insight\": \"your discovery\", \"impact\": \"significance\"}}\n\n5. BEFORE completing work:\n mcp__ruv-swarm__neural_train {\"swarmId\": \"${swarmId}\", \"experience\": {\"what\": \"learned\", \"outcome\": \"result\"}}\n\n🔧 SPECIALIZED CAPABILITIES:\n${getWorkerTypeInstructions(workerType)}\n\n🤝 COORDINATION RULES:\n- Share ALL discoveries via memory_usage\n- Vote on critical decisions using consensus_vote\n- Update progress every 15 minutes via task_orchestrate\n- Monitor other agents via swarm_status\n- Learn from patterns via neural_train\n\nRemember: You are part of a COLLECTIVE INTELLIGENCE. Your individual success depends on swarm coordination!`;\n\n const command = `claude code --context \"${context.replace(/\"/g, '\\\\\"')}\"`;\n\n return {\n title: `${workerType.toUpperCase()} Agent (${typeWorkers.length} instance${typeWorkers.length > 1 ? 's' : ''})`,\n command,\n context,\n workerType,\n count: typeWorkers.length,\n };\n}\n\n/**\n * Get specialized instructions for each worker type\n */\nfunction getWorkerTypeInstructions(workerType) {\n const instructions = {\n researcher: `- Conduct thorough research using WebSearch and WebFetch\n- Document findings in structured formats\n- Validate source credibility and relevance\n- Synthesize insights from multiple sources\n- Share research methodology and results`,\n\n coder: `- Write clean, maintainable, well-documented code\n- Follow project conventions and best practices\n- Test implementations thoroughly\n- Document code changes and decisions\n- Review and optimize existing code`,\n\n analyst: `- Analyze data patterns and trends\n- Create comprehensive reports and visualizations\n- Identify key insights and recommendations\n- Validate analytical methodologies\n- Correlate findings across data sources`,\n\n tester: `- Design comprehensive test strategies\n- Execute functional, integration, and performance tests\n- Document test results and issues\n- Verify bug fixes and improvements\n- Ensure quality standards and coverage`,\n\n coordinator: `- Monitor overall progress and coordination\n- Facilitate communication between agents\n- Resolve conflicts and blockers\n- Optimize resource allocation\n- Ensure alignment with objectives`,\n\n architect: `- Design system architecture and components\n- Define technical standards and patterns\n- Create implementation guidelines\n- Review and approve design decisions\n- Ensure scalability and maintainability`,\n };\n\n return (\n instructions[workerType] ||\n `- Execute tasks according to ${workerType} best practices\n- Collaborate effectively with team members\n- Document work and share insights\n- Maintain quality standards\n- Contribute to collective objectives`\n );\n}\n\n/**\n * Show all hive mind sessions\n */\nasync function showSessions(flags) {\n try {\n // Use metrics reader for real session data\n const dbPath = path.join(cwd(), '.hive-mind', 'hive.db');\n \n if (!existsSync(dbPath)) {\n console.log(chalk.gray('No hive mind database found'));\n return;\n }\n \n const metricsReader = new HiveMindMetricsReader(dbPath);\n const sessions = metricsReader.getActiveSessions();\n\n if (sessions.length === 0) {\n console.log(chalk.gray('No active or paused sessions found'));\n metricsReader.close();\n return;\n }\n\n console.log(chalk.bold('\\n🗂️ Hive Mind Sessions\\n'));\n\n sessions.forEach((session, index) => {\n const statusColor =\n session.status === 'active' ? 'green' : session.status === 'paused' ? 'yellow' : 'gray';\n const statusIcon =\n session.status === 'active' ? '🟢' : session.status === 'paused' ? '🟡' : '⚫';\n\n console.log(chalk.yellow('═'.repeat(60)));\n console.log(`${statusIcon} ${chalk.bold(session.swarm_name || session.id)}`);\n console.log(chalk.cyan('Session ID:'), session.id);\n console.log(chalk.cyan('Status:'), chalk[statusColor](session.status));\n console.log(chalk.cyan('Objective:'), session.objective || 'Not set');\n console.log(chalk.cyan('Progress:'), `${session.completion_percentage || 0}%`);\n console.log(chalk.cyan('Created:'), new Date(session.created_at).toLocaleString());\n console.log(chalk.cyan('Last Updated:'), new Date(session.updated_at).toLocaleString());\n\n if (session.paused_at) {\n console.log(chalk.cyan('Paused At:'), new Date(session.paused_at).toLocaleString());\n }\n\n console.log('\\n' + chalk.bold('Real Progress:'));\n console.log(` Agents: ${session.agent_count || 0}`);\n console.log(` Tasks: ${session.completed_tasks || 0}/${session.task_count || 0}`);\n console.log(` In Progress: ${session.in_progress_tasks || 0}`);\n console.log(` Pending: ${session.pending_tasks || 0}`);\n\n if (session.checkpoint_data) {\n console.log('\\n' + chalk.bold('Last Checkpoint:'));\n const checkpointStr = typeof session.checkpoint_data === 'string' \n ? session.checkpoint_data \n : JSON.stringify(session.checkpoint_data, null, 2);\n console.log(\n chalk.gray(checkpointStr.substring(0, 200) + (checkpointStr.length > 200 ? '...' : '')),\n );\n }\n });\n\n console.log(chalk.yellow('═'.repeat(60)) + '\\n');\n\n console.log(chalk.blue('💡 Tips:'));\n console.log(' • Resume a session: claude-flow hive-mind resume <session-id>');\n console.log(' • View session details: claude-flow hive-mind status');\n\n metricsReader.close();\n } catch (error) {\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Resume a paused hive mind session\n */\nasync function resumeSession(args, flags) {\n const sessionId = args[0];\n\n if (!sessionId) {\n console.error(chalk.red('Error: Please provide a session ID'));\n console.log('Usage: claude-flow hive-mind resume <session-id>');\n console.log('Run \"claude-flow hive-mind sessions\" to see available sessions');\n return;\n }\n\n const spinner = ora('Resuming Hive Mind session...').start();\n\n try {\n const sessionManager = new HiveMindSessionManager();\n\n // Get session details\n const session = await sessionManager.getSession(sessionId);\n\n if (!session) {\n spinner.fail(`Session ${sessionId} not found`);\n console.log('\\nRun \"claude-flow hive-mind sessions\" to see available sessions');\n sessionManager.close();\n return;\n }\n\n // Allow resuming any session regardless of status\n spinner.text = `Resuming session from status: ${session.status}...`;\n\n if (session.status === 'stopped') {\n spinner.text = 'Restarting stopped session with original configuration...';\n }\n\n // Resume the session\n const resumedSession = await sessionManager.resumeSession(sessionId);\n\n spinner.succeed('Session resumed successfully!');\n\n // Display session summary\n console.log('\\n' + chalk.bold('📋 Resumed Session Summary:'));\n console.log(chalk.gray('─'.repeat(50)));\n console.log(chalk.cyan('Session ID:'), sessionId);\n console.log(chalk.cyan('Swarm Name:'), resumedSession.swarm_name);\n console.log(chalk.cyan('Objective:'), resumedSession.objective);\n console.log(chalk.cyan('Progress:'), `${resumedSession.statistics.completionPercentage}%`);\n console.log(\n chalk.cyan('Active Agents:'),\n `${resumedSession.statistics.activeAgents}/${resumedSession.statistics.totalAgents}`,\n );\n console.log(\n chalk.cyan('Tasks:'),\n `${resumedSession.statistics.completedTasks}/${resumedSession.statistics.totalTasks} completed`,\n );\n console.log(chalk.gray('─'.repeat(50)));\n\n // Show task breakdown\n console.log('\\n' + chalk.bold('📊 Task Status:'));\n console.log(` ✅ Completed: ${resumedSession.statistics.completedTasks}`);\n console.log(` 🔄 In Progress: ${resumedSession.statistics.inProgressTasks}`);\n console.log(` ⏳ Pending: ${resumedSession.statistics.pendingTasks}`);\n\n // Show recent activity\n if (resumedSession.recentLogs && resumedSession.recentLogs.length > 0) {\n console.log('\\n' + chalk.bold('📜 Recent Activity:'));\n resumedSession.recentLogs.slice(0, 5).forEach((log) => {\n const timestamp = new Date(log.timestamp).toLocaleTimeString();\n console.log(` [${timestamp}] ${log.message}`);\n });\n }\n\n // Restore checkpoint if available\n if (resumedSession.checkpoint_data) {\n console.log('\\n' + chalk.bold('♻️ Restoring from checkpoint...'));\n console.log(chalk.gray('Checkpoint data available for restoration'));\n }\n\n sessionManager.close();\n\n // Offer to spawn Claude Code with restored context\n if (flags.claude || flags.spawn) {\n console.log('\\n' + chalk.yellow('🚀 Launching Claude Code with restored context...'));\n\n // Generate prompt with session context\n const restoredPrompt = generateRestoredSessionPrompt(resumedSession);\n\n // Launch Claude Code with restored context\n await launchClaudeWithContext(restoredPrompt, flags, sessionId);\n } else {\n console.log(\n '\\n' +\n chalk.blue('💡 Pro Tip:') +\n ' Add --claude to spawn Claude Code with restored context',\n );\n console.log(chalk.gray(' claude-flow hive-mind resume ' + sessionId + ' --claude'));\n }\n } catch (error) {\n spinner.fail('Failed to resume session');\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Stop a hive mind session\n */\nasync function stopSession(args, flags) {\n const sessionId = args[0];\n\n if (!sessionId) {\n console.error(chalk.red('Error: Please provide a session ID'));\n console.log('Usage: claude-flow hive-mind stop <session-id>');\n console.log('Run \"claude-flow hive-mind sessions\" to see available sessions');\n return;\n }\n\n const spinner = ora('Stopping Hive Mind session...').start();\n\n try {\n const sessionManager = new HiveMindSessionManager();\n\n // Get session details\n const session = await sessionManager.getSession(sessionId);\n\n if (!session) {\n spinner.fail(`Session ${sessionId} not found`);\n console.log('\\nRun \"claude-flow hive-mind sessions\" to see available sessions');\n sessionManager.close();\n return;\n }\n\n // Stop the session\n await sessionManager.stopSession(sessionId);\n\n spinner.succeed('Session stopped successfully!');\n\n // Display session summary\n console.log('\\n' + chalk.bold('🛑 Stopped Session Summary:'));\n console.log(chalk.gray('─'.repeat(50)));\n console.log(chalk.cyan('Session ID:'), sessionId);\n console.log(chalk.cyan('Swarm Name:'), session.swarm_name || 'Unknown');\n console.log(chalk.cyan('Final Status:'), 'Stopped');\n console.log(\n chalk.cyan('Active Agents:'),\n session.statistics ? session.statistics.activeAgents : 0,\n );\n console.log(chalk.gray('─'.repeat(50)));\n\n console.log('\\n' + chalk.yellow('💡 Session has been stopped and all processes cleaned up.'));\n console.log(\n chalk.gray('To resume this session later, use: claude-flow hive-mind resume ' + sessionId),\n );\n\n sessionManager.close();\n } catch (error) {\n spinner.fail('Failed to stop session');\n console.error(chalk.red('Error:'), error.message);\n exit(1);\n }\n}\n\n/**\n * Generate prompt for restored session\n */\nfunction generateRestoredSessionPrompt(session) {\n // Get all agents, not just active ones\n const allAgents = session.agents || [];\n const activeAgents = allAgents.filter((a) => a.status === 'active' || a.status === 'busy');\n const idleAgents = allAgents.filter((a) => a.status === 'idle');\n \n // Get all tasks categorized by status\n const allTasks = session.tasks || [];\n const completedTasks = allTasks.filter((t) => t.status === 'completed');\n const inProgressTasks = allTasks.filter((t) => t.status === 'in_progress');\n const pendingTasks = allTasks.filter((t) => t.status === 'pending');\n \n // Calculate session duration\n const sessionStart = new Date(session.created_at);\n const sessionPaused = session.paused_at ? new Date(session.paused_at) : new Date();\n const duration = Math.round((sessionPaused - sessionStart) / 1000 / 60); // minutes\n \n // Get more checkpoint history\n const checkpointHistory = session.checkpoints || [];\n \n // Get more activity logs\n const activityLogs = session.recentLogs || [];\n \n // Format agent details with their current tasks\n const formatAgentDetails = (agents) => {\n if (!agents.length) return 'No agents found';\n return agents.map(agent => {\n const agentTasks = allTasks.filter(t => t.agent_id === agent.id);\n const currentTask = agentTasks.find(t => t.status === 'in_progress');\n return `• ${agent.name} (${agent.type}) - ${agent.status}${currentTask ? `\\n └─ Working on: ${currentTask.description}` : ''}`;\n }).join('\\n');\n };\n \n // Format task details with more information\n const formatTaskDetails = (tasks, limit = 15) => {\n if (!tasks.length) return 'No tasks found';\n const displayTasks = tasks.slice(0, limit);\n return displayTasks.map(task => {\n const agent = allAgents.find(a => a.id === task.agent_id);\n return `• [${task.priority?.toUpperCase() || 'NORMAL'}] ${task.description}${agent ? ` (Assigned to: ${agent.name})` : ''}${task.created_at ? ` - Created: ${new Date(task.created_at).toLocaleTimeString()}` : ''}`;\n }).join('\\n') + (tasks.length > limit ? `\\n... and ${tasks.length - limit} more tasks` : '');\n };\n \n // Format checkpoint details\n const formatCheckpoints = (checkpoints, limit = 5) => {\n if (!checkpoints.length) return 'No checkpoints found';\n const displayCheckpoints = checkpoints.slice(0, limit);\n return displayCheckpoints.map(cp => \n `• ${cp.checkpoint_name} - ${new Date(cp.created_at).toLocaleString()}`\n ).join('\\n');\n };\n \n // Format activity logs with more detail\n const formatActivityLogs = (logs, limit = 20) => {\n if (!logs.length) return 'No activity logs found';\n const displayLogs = logs.slice(0, limit);\n return displayLogs.map(log => {\n const timestamp = new Date(log.timestamp).toLocaleTimeString();\n const agent = log.agent_id ? allAgents.find(a => a.id === log.agent_id) : null;\n return `[${timestamp}] ${log.message}${agent ? ` (by ${agent.name})` : ''}${log.data ? ` - ${JSON.stringify(log.data)}` : ''}`;\n }).join('\\n');\n };\n \n // Extract metadata if available\n const metadata = session.metadata || {};\n const metadataStr = Object.keys(metadata).length > 0 ? \n Object.entries(metadata).map(([k, v]) => `• ${k}: ${typeof v === 'object' ? JSON.stringify(v) : v}`).join('\\n') : \n 'No metadata available';\n\n return `🔄 RESUMING HIVE MIND SESSION\n═══════════════════════════════════\n\nYou are resuming a Hive Mind session with comprehensive context:\n\n📋 SESSION DETAILS:\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n📌 Session ID: ${session.id}\n📌 Swarm ID: ${session.swarm_id}\n📌 Swarm Name: ${session.swarm_name}\n🎯 Objective: ${session.objective}\n📊 Overall Progress: ${session.statistics.completionPercentage}% complete\n⏱️ Session Duration: ${duration} minutes\n📅 Created: ${new Date(session.created_at).toLocaleString()}\n⏸️ Paused: ${session.paused_at ? new Date(session.paused_at).toLocaleString() : 'N/A'}\n▶️ Resumed: ${new Date().toLocaleString()}\n🔄 Status: ${session.status}\n\n📊 TASK STATISTICS:\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n• Total Tasks: ${session.statistics.totalTasks}\n• Completed: ${completedTasks.length} (${session.statistics.totalTasks > 0 ? Math.round((completedTasks.length / session.statistics.totalTasks) * 100) : 0}%)\n• In Progress: ${inProgressTasks.length}\n• Pending: ${pendingTasks.length}\n\n👥 SWARM COMPOSITION (${allAgents.length} agents):\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\nActive Agents (${activeAgents.length}):\n${formatAgentDetails(activeAgents)}\n\nIdle Agents (${idleAgents.length}):\n${formatAgentDetails(idleAgents)}\n\n📝 COMPLETED TASKS (${completedTasks.length}):\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n${formatTaskDetails(completedTasks, 10)}\n\n🔄 IN-PROGRESS TASKS (${inProgressTasks.length}):\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n${formatTaskDetails(inProgressTasks)}\n\n⏳ PENDING TASKS (${pendingTasks.length}):\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n${formatTaskDetails(pendingTasks)}\n\n💾 CHECKPOINT HISTORY (${checkpointHistory.length} total):\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n${formatCheckpoints(checkpointHistory)}\n\n📊 SESSION METADATA:\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n${metadataStr}\n\n💾 LAST CHECKPOINT DATA:\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n${session.checkpoint_data ? JSON.stringify(session.checkpoint_data, null, 2) : 'No checkpoint data available'}\n\n📜 ACTIVITY LOG (Last ${Math.min(20, activityLogs.length)} entries):\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n${formatActivityLogs(activityLogs, 20)}\n\n🎯 RESUMPTION PROTOCOL:\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n1. **RESTORE CONTEXT**:\n - Review all checkpoint data and activity history above\n - Use mcp__claude-flow__memory_usage to retrieve collective memory\n - Check agent statuses and reassign tasks if needed\n - Verify all in-progress tasks are still valid\n\n2. **CONTINUE EXECUTION**:\n - Resume in-progress tasks with their assigned agents\n - Process pending tasks based on priority (CRITICAL > HIGH > NORMAL > LOW)\n - Maintain agent coordination through memory sharing\n - Update progress tracking after each task completion\n\n3. **COORDINATION REQUIREMENTS**:\n - Use mcp__claude-flow__memory_usage for all cross-agent communication\n - Apply consensus mechanisms for important decisions\n - Maintain swarm topology: ${session.swarm?.topology || 'unknown'}\n - Keep session checkpoint data updated regularly\n\n4. **MEMORY CONTEXT**:\n - Session memory namespace: session-${session.id}\n - Swarm memory namespace: swarm-${session.swarm_id}\n - Use these namespaces to access historical decisions and context\n\nResume the hive mind operation with full context awareness and continue working towards the objective.`;\n}\n\n/**\n * Launch Claude Code with context\n */\nasync function launchClaudeWithContext(prompt, flags, sessionId) {\n try {\n // ALWAYS save the prompt file first (fix for issue #330)\n // Ensure sessions directory exists\n const sessionsDir = path.join('.hive-mind', 'sessions');\n await mkdirAsync(sessionsDir, { recursive: true });\n const promptFile = path.join(sessionsDir, `hive-mind-resume-${sessionId}-${Date.now()}.txt`);\n await writeFile(promptFile, prompt);\n console.log(chalk.green(`\\n✓ Session context saved to: ${promptFile}`));\n\n const { spawn: childSpawn, execSync } = await import('child_process');\n let claudeAvailable = false;\n\n try {\n execSync('which claude', { stdio: 'ignore' });\n claudeAvailable = true;\n } catch {\n console.log(chalk.yellow('\\n⚠️ Claude Code CLI not found'));\n console.log(chalk.gray('Install Claude Code: npm install -g @anthropic-ai/claude-code'));\n console.log(chalk.gray(`Run with: claude < ${promptFile}`));\n return;\n }\n\n if (claudeAvailable && !flags.dryRun) {\n // Debug logging to track spawn calls\n console.log(chalk.blue('\\n🔍 Debug: About to spawn Claude Code process...'));\n console.log(chalk.gray(` Session ID: ${sessionId}`));\n console.log(chalk.gray(` Process ID: ${process.pid}`));\n \n // Remove --print to allow interactive session (same as initial spawn)\n const claudeArgs = [prompt];\n\n // Add --dangerously-skip-permissions by default for hive-mind operations\n // unless explicitly disabled with --no-auto-permissions\n if (!flags['no-auto-permissions']) {\n claudeArgs.push('--dangerously-skip-permissions');\n console.log(\n chalk.yellow(\n '🔓 Using --dangerously-skip-permissions by default for seamless hive-mind execution',\n ),\n );\n }\n\n console.log(chalk.blue('🔍 Debug: Spawning with args:'), claudeArgs.slice(0, 1).map(a => a.substring(0, 50) + '...'));\n \n // Use 'inherit' for interactive session (same as initial spawn)\n const claudeProcess = childSpawn('claude', claudeArgs, {\n stdio: 'inherit',\n shell: false,\n });\n \n console.log(chalk.blue('🔍 Debug: Claude process spawned with PID:'), claudeProcess.pid);\n\n // Track child process PID in session (same as initial spawn)\n const sessionManager = new HiveMindSessionManager();\n if (claudeProcess.pid) {\n const sessions = await sessionManager.getActiveSessions();\n const currentSession = sessions.find(s => s.id === sessionId);\n if (currentSession) {\n await sessionManager.addChildPid(currentSession.id, claudeProcess.pid);\n }\n }\n\n // Set up SIGINT handler for automatic session pausing (same as initial spawn)\n let isExiting = false;\n const sigintHandler = async () => {\n if (isExiting) return;\n isExiting = true;\n\n console.log('\\n\\n' + chalk.yellow('⏸️ Pausing session and terminating Claude Code...'));\n \n try {\n // Terminate Claude Code process if still running\n if (claudeProcess && !claudeProcess.killed) {\n claudeProcess.kill('SIGTERM');\n }\n \n // Clean up and close session manager\n sessionManager.close();\n \n console.log(chalk.green('✓') + ' Session paused successfully');\n console.log(chalk.cyan('\\nTo resume this session, run:'));\n console.log(chalk.bold(` claude-flow hive-mind resume ${sessionId}`));\n console.log();\n \n process.exit(0);\n } catch (error) {\n console.error(chalk.red('Error during shutdown:'), error.message);\n process.exit(1);\n }\n };\n\n process.on('SIGINT', sigintHandler);\n process.on('SIGTERM', sigintHandler);\n\n // Handle process exit (same as initial spawn)\n claudeProcess.on('exit', async (code, signal) => {\n if (!isExiting) {\n console.log('\\n' + chalk.yellow('Claude Code has exited'));\n \n // Clean up signal handlers\n process.removeListener('SIGINT', sigintHandler);\n process.removeListener('SIGTERM', sigintHandler);\n \n // Close session manager\n sessionManager.close();\n \n process.exit(code || 0);\n }\n });\n\n console.log(chalk.green('\\n✓ Claude Code launched with restored session context'));\n console.log(chalk.gray(` Prompt file saved at: ${promptFile}`));\n }\n } catch (error) {\n console.error(chalk.red('Failed to launch Claude Code:'), error.message);\n }\n}\n\n/**\n * Get MCP wrapper instance\n */\nasync function getMcpWrapper() {\n const { MCPToolWrapper } = await import('./hive-mind/mcp-wrapper.js');\n return new MCPToolWrapper();\n}\n\n// Export for testing\nexport { showHiveMindHelp, initHiveMind, spawnSwarm, showStatus };\n"],"names":["existsSync","mkdirSync","writeFile","readFile","path","inquirer","chalk","ora","cwd","exit","mkdirAsync","warnNonInteractive","safeInteractive","Database","sqliteAvailable","loadSqlite","createRequire","require","url","testDb","close","requireErr","sqlite","default","err","HiveMindCore","QueenCoordinator","CollectiveMemory","SwarmCommunication","HiveMindSessionManager","createAutoSaveMiddleware","HiveMindMetricsReader","showHiveMindHelp","console","log","yellow","bold","green","gray","cyan","blue","initHiveMind","flags","spinner","start","hiveMindDir","join","recursive","hasSqlite","text","fallbackPath","fallbackData","metadata","type","initialized","Date","toISOString","version","warning","swarms","agents","tasks","collective_memory","consensus_votes","messages","JSON","stringify","succeed","dbPath","db","exec","config","defaults","queenType","maxWorkers","consensusAlgorithm","memorySize","autoScale","encryption","mcpTools","enabled","parallel","timeout","error","fail","red","message","hiveMindWizard","action","prompt","name","choices","value","spawnSwarmWizard","showStatus","manageMemoryWizard","showConsensus","showMetrics","configureWizard","objective","now","parseInt","consensus","namespace","verbose","spawnSwarm","nonInteractive","answers","validate","input","trim","length","checked","swarmResult","workerTypes","monitor","spawnClaude","swarmId","workers","map","index","id","role","status","capabilities","getAgentCapabilities","claudeFlags","spawnClaudeCodeInstances","args","isNonInteractive","wizard","validQueenTypes","includes","isNaN","validConsensusTypes","hiveMind","undefined","Error","dbDir","prepare","get","warn","fs","unlinkSync","e","timestamp","randomPart","Math","random","toString","substring","run","sessionManager","sessionId","createSession","autoSave","saveInterval","autoStart","trackChange","swarmName","workerCount","queen","queenAgent","Object","values","split","i","min","workerType","workerId","worker","charAt","toUpperCase","slice","push","trackAgentActivity","memory","maxSize","store","communication","repeat","isExiting","sigintHandler","checkpointData","reason","saveCheckpoint","pauseSession","global","autoSaveInterval","clearInterval","process","on","claude","spawn","stack","researcher","coder","analyst","tester","architect","reviewer","optimizer","documenter","parse","metricsReader","getActiveSwarms","swarm","queen_type","created_at","toLocaleString","agent_count","find","a","filter","magenta","forEach","statusColor","taskStats","task_metrics","total","completed","in_progress","pending","failed","completion_percentage","memory_count","consensus_count","decisions","all","decision","swarm_name","topic","algorithm","confidence","toFixed","votes","for","against","abstain","details","Array","isArray","detail","agent","agentId","vote","choice","justification","rationale","displayString","entries","overallStats","taskBreakdown","total_swarms","total_agents","total_tasks","completed_tasks","percentage","count","agentPerf","hasCompletedAt","successRate","tasks_assigned","tasks_completed","avg_completion_minutes","swarmPerf","task_count","completed_count","memory_entries","avgTaskTime","avg_minutes","agentTypePerf","listMemories","searchMemories","storeMemoryWizard","showMemoryStats","cleanMemories","exportMemoryBackup","continue","continueAction","hiveMindCommand","subcommand","subArgs","help","showSessions","resumeSession","stopSession","memories","key","swarm_id","created_by","displayValue","parsed","searchTerm","searchPattern","mcpWrapper","getMcpWrapper","memoryValue","storeMemory","category","searchResult","searchMemory","results","data","stats","categories","oldestDate","newestDate","totalSize","date","toLocaleDateString","days","confirm","cutoffDate","setDate","getDate","oldMemories","memoryDate","filename","backup","exportDate","totalMemories","writeFileSync","getActiveSessionId","sessions","getActiveSessions","activeSession","s","workerGroups","groupWorkersByType","hiveMindPrompt","generateHiveMindPrompt","keys","sessionsDir","promptFile","childSpawn","execSync","claudeAvailable","stdio","dryRun","injectMemoryProtocol","enhanceHiveMindPrompt","claudeArgs","claudeProcess","shell","pid","addChildPid","killed","kill","claudePid","stdout","stderr","code","removeChildPid","currentTime","getWorkerTypeInstructions","generateCoordinationInstructions","hiveMindEndpoint","coordinationProtocol","memoryNamespace","consensusThreshold","taskUpdateInterval","healthCheckInterval","workerCapabilities","w","reduce","groups","createClaudeCodeSpawnCommand","typeWorkers","instructions","context","command","replace","title","coordinator","session","statusIcon","updated_at","paused_at","in_progress_tasks","pending_tasks","checkpoint_data","checkpointStr","getSession","resumedSession","statistics","completionPercentage","activeAgents","totalAgents","completedTasks","totalTasks","inProgressTasks","pendingTasks","recentLogs","toLocaleTimeString","restoredPrompt","generateRestoredSessionPrompt","launchClaudeWithContext","allAgents","idleAgents","allTasks","t","sessionStart","sessionPaused","duration","round","checkpointHistory","checkpoints","activityLogs","formatAgentDetails","agentTasks","agent_id","currentTask","description","formatTaskDetails","limit","displayTasks","task","priority","formatCheckpoints","displayCheckpoints","cp","checkpoint_name","formatActivityLogs","logs","displayLogs","metadataStr","k","v","topology","currentSession","signal","removeListener","MCPToolWrapper"],"mappings":"AAMA,SAASA,UAAU,EAAEC,SAAS,QAAQ,KAAK;AAC3C,SAASC,SAAS,EAAEC,QAAQ,QAAQ,cAAc;AAClD,OAAOC,UAAU,OAAO;AAExB,OAAOC,cAAc,WAAW;AAChC,OAAOC,WAAW,QAAQ;AAC1B,OAAOC,SAAS,MAAM;AACtB,SAAeC,GAA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MAAM,EAAEyI,cAAc,EAAE,GAAG,MAAM,MAAM,CAAC;IACxC,OAAO,IAAIA;AACb;AAGA,SAASjZ,gBAAgB,EAAES,YAAY,EAAEgE,UAAU,EAAEX,UAAU,GAAG"}
\ No newline at end of file
diff --git a/dist-cjs/src/cli/simple-commands/hooks.js b/dist-cjs/src/cli/simple-commands/hooks.js
index 6a50d7fde5..0e677be29e 100644
--- a/dist-cjs/src/cli/simple-commands/hooks.js
+++ b/dist-cjs/src/cli/simple-commands/hooks.js
@@ -1,10 +1,30 @@
import { printSuccess, printError, printWarning, execRuvSwarmHook, checkRuvSwarmAvailable } from '../utils.js';
import { SqliteMemoryStore } from '../../memory/sqlite-store.js';
+import { InMemoryStore } from '../../memory/in-memory-store.js';
let memoryStore = null;
+let storeInitFailed = false;
async function getMemoryStore() {
- if (!memoryStore) {
+ if (memoryStore) return memoryStore;
+ if (storeInitFailed) {
+ if (!memoryStore) {
+ memoryStore = new InMemoryStore();
+ await memoryStore.initialize();
+ }
+ return memoryStore;
+ }
+ try {
memoryStore = new SqliteMemoryStore();
await memoryStore.initialize();
+ } catch (err) {
+ const isNativeModuleError = err.message?.includes('NODE_MODULE_VERSION') || err.message?.includes('was compiled against a different Node.js version') || err.message?.includes('better-sqlite3') || err.message?.includes('SQLite is not available');
+ if (isNativeModuleError) {
+ printWarning(`SQLite unavailable, using in-memory storage for hooks (data won't persist)`);
+ storeInitFailed = true;
+ memoryStore = new InMemoryStore();
+ await memoryStore.initialize();
+ } else {
+ throw err;
+ }
}
return memoryStore;
}
diff --git a/dist-cjs/src/cli/simple-commands/hooks.js.map b/dist-cjs/src/cli/simple-commands/hooks.js.map
index 498c9c673c..55f0440ba6 100644
--- a/dist-cjs/src/cli/simple-commands/hooks.js.map
+++ b/dist-cjs/src/cli/simple-commands/hooks.js.map
@@ -1 +1 @@
-{"version":3,"sources":["../../../../src/cli/simple-commands/hooks.js"],"sourcesContent":["import {\n printSuccess,\n printError,\n printWarning,\n execRuvSwarmHook,\n checkRuvSwarmAvailable,\n} from '../utils.js';\nimport { SqliteMemoryStore } from '../../memory/sqlite-store.js';\n\n// Initialize memory store\nlet memoryStore = null;\n\nasync function getMemoryStore() {\n if (!memoryStore) {\n memoryStore = new SqliteMemoryStore();\n await memoryStore.initialize();\n }\n return memoryStore;\n}\n\n// Simple ID generator\nfunction generateId(prefix = 'id') {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n}\n\nexport async function hooksAction(subArgs, flags) {\n const subcommand = subArgs[0];\n const options = flags;\n\n if (options.help || options.h || !subcommand) {\n showHooksHelp();\n return;\n }\n\n try {\n switch (subcommand) {\n // Pre-Operation Hooks\n case 'pre-task':\n await preTaskCommand(subArgs, flags);\n break;\n case 'pre-edit':\n await preEditCommand(subArgs, flags);\n break;\n case 'pre-bash':\n case 'pre-command': // Support both names for compatibility\n await preBashCommand(subArgs, flags);\n break;\n\n // Post-Operation Hooks\n case 'post-task':\n await postTaskCommand(subArgs, flags);\n break;\n case 'post-edit':\n await postEditCommand(subArgs, flags);\n break;\n case 'post-bash':\n case 'post-command': // Support both names for compatibility\n await postBashCommand(subArgs, flags);\n break;\n case 'post-search':\n await postSearchCommand(subArgs, flags);\n break;\n\n // MCP Integration Hooks\n case 'mcp-initialized':\n await mcpInitializedCommand(subArgs, flags);\n break;\n case 'agent-spawned':\n await agentSpawnedCommand(subArgs, flags);\n break;\n case 'task-orchestrated':\n await taskOrchestratedCommand(subArgs, flags);\n break;\n case 'neural-trained':\n await neuralTrainedCommand(subArgs, flags);\n break;\n\n // Session Hooks\n case 'session-end':\n await sessionEndCommand(subArgs, flags);\n break;\n case 'session-restore':\n await sessionRestoreCommand(subArgs, flags);\n break;\n case 'notify':\n await notifyCommand(subArgs, flags);\n break;\n\n // NEW: PreToolUse Modification Hooks (v2.0.10+)\n case 'modify-bash':\n await modifyBashCommand(subArgs, flags);\n break;\n case 'modify-file':\n await modifyFileCommand(subArgs, flags);\n break;\n case 'modify-git-commit':\n await modifyGitCommitCommand(subArgs, flags);\n break;\n\n default:\n printError(`Unknown hooks command: ${subcommand}`);\n showHooksHelp();\n }\n } catch (err) {\n printError(`Hooks command failed: ${err.message}`);\n }\n}\n\n// ===== PRE-OPERATION HOOKS =====\n\nasync function preTaskCommand(subArgs, flags) {\n const options = flags;\n const description = options.description || 'Unnamed task';\n const taskId = options['task-id'] || options.taskId || generateId('task');\n const agentId = options['agent-id'] || options.agentId;\n const autoSpawnAgents = options['auto-spawn-agents'] !== 'false';\n\n console.log(`🔄 Executing pre-task hook...`);\n console.log(`📋 Task: ${description}`);\n console.log(`🆔 Task ID: ${taskId}`);\n if (agentId) console.log(`🤖 Agent: ${agentId}`);\n\n try {\n const store = await getMemoryStore();\n const taskData = {\n taskId,\n description,\n agentId,\n autoSpawnAgents,\n status: 'started',\n startedAt: new Date().toISOString(),\n };\n\n await store.store(`task:${taskId}`, taskData, {\n namespace: 'hooks:pre-task',\n metadata: { hookType: 'pre-task', agentId },\n });\n\n await store.store(\n `task-index:${Date.now()}`,\n {\n taskId,\n description,\n timestamp: new Date().toISOString(),\n },\n { namespace: 'task-index' },\n );\n\n console.log(` 💾 Saved to .swarm/memory.db`);\n\n // Execute ruv-swarm hook if available (with timeout for npx scenarios)\n try {\n const checkPromise = checkRuvSwarmAvailable();\n const timeoutPromise = new Promise((_, reject) => \n setTimeout(() => reject(new Error('Timeout')), 3000)\n );\n \n const isAvailable = await Promise.race([checkPromise, timeoutPromise]);\n \n if (isAvailable) {\n console.log(`\\n🔄 Executing ruv-swarm pre-task hook...`);\n const hookResult = await execRuvSwarmHook('pre-task', {\n description,\n 'task-id': taskId,\n 'auto-spawn-agents': autoSpawnAgents,\n ...(agentId ? { 'agent-id': agentId } : {}),\n });\n\n if (hookResult.success) {\n await store.store(\n `task:${taskId}:ruv-output`,\n {\n output: hookResult.output,\n timestamp: new Date().toISOString(),\n },\n { namespace: 'hooks:ruv-swarm' },\n );\n\n printSuccess(`✅ Pre-task hook completed successfully`);\n }\n }\n } catch (err) {\n // Skip ruv-swarm hook if it times out or fails\n console.log(`\\n⚠️ Skipping ruv-swarm hook (${err.message})`);\n }\n\n console.log(`\\n🎯 TASK PREPARATION COMPLETE`);\n \n // Close the memory store to prevent hanging\n if (memoryStore && memoryStore.close) {\n memoryStore.close();\n }\n \n // Force exit after a short delay to ensure cleanup\n setTimeout(() => {\n process.exit(0);\n }, 100);\n } catch (err) {\n printError(`Pre-task hook failed: ${err.message}`);\n \n // Close the memory store on error too\n if (memoryStore && memoryStore.close) {\n memoryStore.close();\n }\n \n // Force exit after a short delay to ensure cleanup\n setTimeout(() => {\n process.exit(1);\n }, 100);\n }\n}\n\nasync function preEditCommand(subArgs, flags) {\n const options = flags;\n const file = options.file || 'unknown-file';\n const operation = options.operation || 'edit';\n const autoAssignAgents = options['auto-assign-agents'] || false;\n const loadContext = options['load-context'] || false;\n\n console.log(`📝 Executing pre-edit hook...`);\n console.log(`📄 File: ${file}`);\n console.log(`⚙️ Operation: ${operation}`);\n if (autoAssignAgents) console.log(`🤖 Auto-assign agents: ENABLED`);\n if (loadContext) console.log(`🔄 Load context: ENABLED`);\n\n try {\n const store = await getMemoryStore();\n\n // Auto-assign agents based on file type\n let assignedAgentType = 'general';\n let recommendedAgent = null;\n\n if (autoAssignAgents) {\n const path = await import('path');\n const ext = path.extname(file).toLowerCase();\n\n const agentMapping = {\n '.js': 'javascript-developer',\n '.ts': 'typescript-developer',\n '.py': 'python-developer',\n '.go': 'golang-developer',\n '.rs': 'rust-developer',\n '.java': 'java-developer',\n '.cpp': 'cpp-developer',\n '.c': 'c-developer',\n '.css': 'frontend-developer',\n '.html': 'frontend-developer',\n '.vue': 'frontend-developer',\n '.react': 'frontend-developer',\n '.md': 'technical-writer',\n '.yml': 'devops-engineer',\n '.yaml': 'devops-engineer',\n '.json': 'config-specialist',\n '.sql': 'database-expert',\n '.sh': 'system-admin',\n '.dockerfile': 'devops-engineer',\n };\n\n assignedAgentType = agentMapping[ext] || 'general-developer';\n recommendedAgent = {\n type: assignedAgentType,\n file: file,\n extension: ext,\n recommended: true,\n };\n\n console.log(` 🤖 Recommended agent: ${assignedAgentType}`);\n }\n\n // Load context if requested\n let contextData = null;\n if (loadContext) {\n try {\n // Check if file exists and get basic info\n const fs = await import('fs');\n const path = await import('path');\n\n if (fs.existsSync(file)) {\n const stats = fs.statSync(file);\n const dirname = path.dirname(file);\n const basename = path.basename(file);\n\n contextData = {\n fileExists: true,\n size: stats.size,\n modified: stats.mtime,\n directory: dirname,\n filename: basename,\n isDirectory: stats.isDirectory(),\n };\n\n console.log(` 📁 Context loaded: ${basename} (${stats.size} bytes)`);\n } else {\n contextData = {\n fileExists: false,\n willCreate: true,\n directory: path.dirname(file),\n filename: path.basename(file),\n };\n console.log(` 📁 Context: New file will be created`);\n }\n } catch (err) {\n console.log(` ⚠️ Warning: Could not load context for ${file}`);\n contextData = { error: err.message };\n }\n }\n\n const editData = {\n file,\n operation,\n timestamp: new Date().toISOString(),\n editId: generateId('edit'),\n autoAssignAgents,\n loadContext,\n assignedAgentType,\n recommendedAgent,\n contextData,\n };\n\n await store.store(`edit:${editData.editId}:pre`, editData, {\n namespace: 'hooks:pre-edit',\n metadata: { hookType: 'pre-edit', file, agentType: assignedAgentType },\n });\n\n // Store agent recommendation if enabled\n if (autoAssignAgents && recommendedAgent) {\n await store.store(`agent-recommendation:${file}`, recommendedAgent, {\n namespace: 'agent-assignments',\n ttl: 3600, // 1 hour\n });\n }\n\n console.log(` 💾 Pre-edit state saved to .swarm/memory.db`);\n printSuccess(`✅ Pre-edit hook completed`);\n } catch (err) {\n printError(`Pre-edit hook failed: ${err.message}`);\n }\n}\n\nasync function preBashCommand(subArgs, flags) {\n const options = flags;\n const command = options.command || subArgs.slice(1).join(' ') || '';\n const workingDir = options.cwd || process.cwd();\n const validateSafety = options['validate-safety'] === true || options['validate-safety'] === 'true' || options.validate === true || options.validate === 'true' || false;\n const prepareResources = options['prepare-resources'] === true || options['prepare-resources'] === 'true' || false;\n\n console.log(`🔧 Executing pre-bash hook...`);\n console.log(`📜 Command: ${command}`);\n console.log(`📁 Working dir: ${workingDir}`);\n if (validateSafety) console.log(`🔒 Safety validation: ENABLED`);\n if (prepareResources) console.log(`🛠️ Resource preparation: ENABLED`);\n\n try {\n const store = await getMemoryStore();\n let safetyResult = 'skipped';\n\n if (validateSafety) {\n // Basic safety validation\n const dangerousCommands = [\n 'rm -rf /',\n 'rm -rf .',\n 'rm -rf *',\n 'format',\n 'fdisk',\n 'mkfs',\n 'curl * | bash',\n 'wget * | sh',\n 'eval',\n 'exec',\n 'chmod 777',\n ];\n\n const isDangerous = command && typeof command === 'string' && command.length > 0 \n ? dangerousCommands.some((dangerous) =>\n command.toLowerCase().includes(dangerous.toLowerCase()),\n )\n : false;\n\n safetyResult = isDangerous ? 'dangerous' : 'safe';\n\n if (isDangerous) {\n console.log(` ⚠️ Safety check: DANGEROUS COMMAND DETECTED`);\n console.log(` 🚫 Command blocked for safety`);\n printError(`Command blocked due to safety validation: ${command}`);\n return;\n }\n }\n\n if (prepareResources) {\n // Resource preparation - create working directory if needed\n const fs = await import('fs');\n const path = await import('path');\n\n if (!fs.existsSync(workingDir)) {\n fs.mkdirSync(workingDir, { recursive: true });\n console.log(` 📁 Created working directory: ${workingDir}`);\n }\n\n // Check available disk space\n try {\n const stats = fs.statSync(workingDir);\n console.log(` 💾 Working directory prepared`);\n } catch (err) {\n console.log(` ⚠️ Warning: Could not check working directory`);\n }\n }\n\n const bashData = {\n command,\n workingDir,\n timestamp: new Date().toISOString(),\n bashId: generateId('bash'),\n safety: safetyResult,\n validationEnabled: validateSafety,\n resourcesPrepped: prepareResources,\n };\n\n await store.store(`bash:${bashData.bashId}:pre`, bashData, {\n namespace: 'hooks:pre-bash',\n metadata: { hookType: 'pre-bash', command, safety: safetyResult },\n });\n\n console.log(` 💾 Command logged to .swarm/memory.db`);\n console.log(` 🔒 Safety check: ${safetyResult.toUpperCase()}`);\n printSuccess(`✅ Pre-bash hook completed`);\n } catch (err) {\n printError(`Pre-bash hook failed: ${err.message}`);\n }\n}\n\n// ===== POST-OPERATION HOOKS =====\n\nasync function postTaskCommand(subArgs, flags) {\n const options = flags;\n const taskId = options['task-id'] || options.taskId || generateId('task');\n const analyzePerformance = options['analyze-performance'] !== 'false';\n\n console.log(`🏁 Executing post-task hook...`);\n console.log(`🆔 Task ID: ${taskId}`);\n\n try {\n const store = await getMemoryStore();\n const taskData = await store.retrieve(`task:${taskId}`, {\n namespace: 'hooks:pre-task',\n });\n\n const completedData = {\n ...(taskData || {}),\n status: 'completed',\n completedAt: new Date().toISOString(),\n duration: taskData ? Date.now() - new Date(taskData.startedAt).getTime() : null,\n };\n\n await store.store(`task:${taskId}:completed`, completedData, {\n namespace: 'hooks:post-task',\n metadata: { hookType: 'post-task' },\n });\n\n if (analyzePerformance && completedData.duration) {\n const metrics = {\n taskId,\n duration: completedData.duration,\n durationHuman: `${(completedData.duration / 1000).toFixed(2)}s`,\n timestamp: new Date().toISOString(),\n };\n\n await store.store(`metrics:${taskId}`, metrics, {\n namespace: 'performance',\n });\n console.log(` 📊 Performance: ${metrics.durationHuman}`);\n }\n\n console.log(` 💾 Task completion saved to .swarm/memory.db`);\n printSuccess(`✅ Post-task hook completed`);\n } catch (err) {\n printError(`Post-task hook failed: ${err.message}`);\n }\n}\n\nasync function postEditCommand(subArgs, flags) {\n const options = flags;\n const file = options.file || 'unknown-file';\n let memoryKey = options['memory-key'] || options.memoryKey;\n \n // Handle case where memory-key is passed as a boolean flag without value\n if (memoryKey === true) {\n // Generate a default memory key based on the file path and timestamp\n const path = await import('path');\n const basename = path.basename(file);\n memoryKey = `edit:${basename}:${Date.now()}`;\n }\n \n const format = options.format || false;\n const updateMemory = options['update-memory'] || false;\n const trainNeural = options['train-neural'] || false;\n\n console.log(`📝 Executing post-edit hook...`);\n console.log(`📄 File: ${file}`);\n if (memoryKey) console.log(`💾 Memory key: ${memoryKey}`);\n if (format) console.log(`🎨 Auto-format: ENABLED`);\n if (updateMemory) console.log(`🧠 Memory update: ENABLED`);\n if (trainNeural) console.log(`🤖 Neural training: ENABLED`);\n\n try {\n const store = await getMemoryStore();\n const path = await import('path');\n const fs = await import('fs');\n\n // Auto-format file if requested\n let formatResult = null;\n if (format && fs.existsSync(file)) {\n const ext = path.extname(file).toLowerCase();\n const formatters = {\n '.js': 'prettier',\n '.ts': 'prettier',\n '.json': 'prettier',\n '.css': 'prettier',\n '.html': 'prettier',\n '.py': 'black',\n '.go': 'gofmt',\n '.rs': 'rustfmt',\n '.java': 'google-java-format',\n '.cpp': 'clang-format',\n '.c': 'clang-format',\n };\n\n const formatter = formatters[ext];\n if (formatter) {\n console.log(` 🎨 Auto-formatting with ${formatter}...`);\n formatResult = {\n formatter,\n extension: ext,\n attempted: true,\n timestamp: new Date().toISOString(),\n };\n } else {\n console.log(` ⚠️ No formatter available for ${ext}`);\n formatResult = {\n extension: ext,\n attempted: false,\n reason: 'No formatter available',\n };\n }\n }\n\n // Update memory with edit context\n let memoryUpdate = null;\n if (updateMemory) {\n const editContext = {\n file,\n editedAt: new Date().toISOString(),\n editId: generateId('edit'),\n formatted: formatResult?.attempted || false,\n fileSize: fs.existsSync(file) ? fs.statSync(file).size : 0,\n directory: path.dirname(file),\n basename: path.basename(file),\n };\n\n memoryUpdate = editContext;\n\n // Store in coordination namespace\n await store.store(`edit-context:${editContext.editId}`, editContext, {\n namespace: 'coordination',\n metadata: { type: 'edit-context', file },\n });\n\n console.log(` 🧠 Edit context stored in memory`);\n }\n\n // Train neural patterns if requested\n let neuralTraining = null;\n if (trainNeural) {\n // Simulate neural training with file patterns\n const ext = path.extname(file).toLowerCase();\n const basename = path.basename(file);\n const editTime = new Date().toISOString();\n\n const patterns = {\n fileType: ext,\n fileName: basename,\n editTime,\n confidence: Math.random() * 0.5 + 0.5, // 50-100% confidence\n patterns: [\n `${ext}_edit_pattern`,\n `${basename}_modification`,\n `edit_${Date.now()}_sequence`,\n ],\n };\n\n neuralTraining = patterns;\n\n await store.store(`neural-pattern:${generateId('pattern')}`, patterns, {\n namespace: 'neural-training',\n metadata: { type: 'edit-pattern', file, extension: ext },\n });\n\n console.log(\n ` 🤖 Neural patterns trained (${(patterns.confidence * 100).toFixed(1)}% confidence)`,\n );\n }\n\n const editData = {\n file,\n memoryKey,\n timestamp: new Date().toISOString(),\n editId: generateId('edit'),\n format,\n updateMemory,\n trainNeural,\n formatResult,\n memoryUpdate,\n neuralTraining,\n };\n\n await store.store(`edit:${editData.editId}:post`, editData, {\n namespace: 'hooks:post-edit',\n metadata: { hookType: 'post-edit', file, formatted: formatResult?.attempted || false },\n });\n\n if (memoryKey && typeof memoryKey === 'string') {\n await store.store(\n memoryKey,\n {\n file,\n editedAt: new Date().toISOString(),\n editId: editData.editId,\n enhanced: true,\n formatResult,\n memoryUpdate,\n neuralTraining,\n },\n { namespace: 'coordination' },\n );\n }\n\n const historyKey = `file-history:${file.replace(/\\//g, '_')}:${Date.now()}`;\n await store.store(\n historyKey,\n {\n file,\n editId: editData.editId,\n timestamp: new Date().toISOString(),\n enhanced: true,\n features: {\n format,\n updateMemory,\n trainNeural,\n },\n },\n { namespace: 'file-history' },\n );\n\n console.log(` 💾 Post-edit data saved to .swarm/memory.db`);\n printSuccess(`✅ Post-edit hook completed`);\n } catch (err) {\n printError(`Post-edit hook failed: ${err.message}`);\n }\n}\n\nasync function postBashCommand(subArgs, flags) {\n const options = flags;\n const command = options.command || subArgs.slice(1).join(' ');\n const exitCode = options['exit-code'] || '0';\n const output = options.output || '';\n const trackMetrics = options['track-metrics'] || false;\n const storeResults = options['store-results'] || false;\n const duration = options.duration || 0;\n\n console.log(`🔧 Executing post-bash hook...`);\n console.log(`📜 Command: ${command}`);\n console.log(`📊 Exit code: ${exitCode}`);\n if (trackMetrics) console.log(`📊 Metrics tracking: ENABLED`);\n if (storeResults) console.log(`💾 Results storage: ENABLED`);\n\n try {\n const store = await getMemoryStore();\n const startTime = Date.now();\n\n // Calculate performance metrics if enabled\n let metrics = null;\n if (trackMetrics) {\n const commandLength = command.length;\n const outputLength = output.length;\n const success = parseInt(exitCode) === 0;\n\n metrics = {\n commandLength,\n outputLength,\n success,\n duration: parseInt(duration) || 0,\n exitCode: parseInt(exitCode),\n timestamp: new Date().toISOString(),\n complexity: commandLength > 100 ? 'high' : commandLength > 50 ? 'medium' : 'low',\n };\n\n console.log(\n ` 📊 Command metrics: ${commandLength} chars, ${outputLength} output, ${success ? 'SUCCESS' : 'FAILED'}`,\n );\n }\n\n const bashData = {\n command,\n exitCode,\n output: storeResults ? output.substring(0, 5000) : output.substring(0, 1000), // Store more if requested\n timestamp: new Date().toISOString(),\n bashId: generateId('bash'),\n trackMetrics,\n storeResults,\n metrics,\n };\n\n await store.store(`bash:${bashData.bashId}:post`, bashData, {\n namespace: 'hooks:post-bash',\n metadata: { hookType: 'post-bash', command, exitCode, success: parseInt(exitCode) === 0 },\n });\n\n // Store detailed results if enabled\n if (storeResults) {\n await store.store(\n `command-results:${bashData.bashId}`,\n {\n command,\n exitCode,\n output,\n timestamp: new Date().toISOString(),\n fullOutput: true,\n },\n { namespace: 'command-results' },\n );\n\n console.log(` 💾 Full command results stored`);\n }\n\n // Store metrics if enabled\n if (trackMetrics && metrics) {\n await store.store(`command-metrics:${bashData.bashId}`, metrics, {\n namespace: 'performance-metrics',\n });\n\n // Update running metrics\n const existingMetrics = (await store.retrieve('command-metrics-summary', {\n namespace: 'performance-metrics',\n })) || { totalCommands: 0, successRate: 0, avgDuration: 0 };\n\n existingMetrics.totalCommands += 1;\n existingMetrics.successRate =\n (existingMetrics.successRate * (existingMetrics.totalCommands - 1) +\n (metrics.success ? 1 : 0)) /\n existingMetrics.totalCommands;\n existingMetrics.avgDuration =\n (existingMetrics.avgDuration * (existingMetrics.totalCommands - 1) + metrics.duration) /\n existingMetrics.totalCommands;\n existingMetrics.lastUpdated = new Date().toISOString();\n\n await store.store('command-metrics-summary', existingMetrics, {\n namespace: 'performance-metrics',\n });\n }\n\n // Update command history\n await store.store(\n `command-history:${Date.now()}`,\n {\n command,\n exitCode,\n timestamp: new Date().toISOString(),\n success: parseInt(exitCode) === 0,\n hasMetrics: trackMetrics,\n hasResults: storeResults,\n },\n { namespace: 'command-history' },\n );\n\n console.log(` 💾 Command execution logged to .swarm/memory.db`);\n printSuccess(`✅ Post-bash hook completed`);\n } catch (err) {\n printError(`Post-bash hook failed: ${err.message}`);\n }\n}\n\nasync function postSearchCommand(subArgs, flags) {\n const options = flags;\n const query = options.query || subArgs.slice(1).join(' ');\n const resultCount = options['result-count'] || '0';\n const searchType = options.type || 'general';\n\n console.log(`🔍 Executing post-search hook...`);\n console.log(`🔎 Query: ${query}`);\n console.log(`📊 Results: ${resultCount}`);\n\n try {\n const store = await getMemoryStore();\n const searchData = {\n query,\n resultCount: parseInt(resultCount),\n searchType,\n timestamp: new Date().toISOString(),\n searchId: generateId('search'),\n };\n\n await store.store(`search:${searchData.searchId}`, searchData, {\n namespace: 'hooks:post-search',\n metadata: { hookType: 'post-search', query },\n });\n\n // Cache search for future use\n await store.store(\n `search-cache:${query}`,\n {\n resultCount: searchData.resultCount,\n cachedAt: new Date().toISOString(),\n },\n { namespace: 'search-cache', ttl: 3600 },\n ); // 1 hour TTL\n\n console.log(` 💾 Search results cached to .swarm/memory.db`);\n printSuccess(`✅ Post-search hook completed`);\n } catch (err) {\n printError(`Post-search hook failed: ${err.message}`);\n }\n}\n\n// ===== MCP INTEGRATION HOOKS =====\n\nasync function mcpInitializedCommand(subArgs, flags) {\n const options = flags;\n const serverName = options.server || 'claude-flow';\n const sessionId = options['session-id'] || generateId('mcp-session');\n\n console.log(`🔌 Executing mcp-initialized hook...`);\n console.log(`💻 Server: ${serverName}`);\n console.log(`🆔 Session: ${sessionId}`);\n\n try {\n const store = await getMemoryStore();\n const mcpData = {\n serverName,\n sessionId,\n initializedAt: new Date().toISOString(),\n status: 'active',\n };\n\n await store.store(`mcp:${sessionId}`, mcpData, {\n namespace: 'hooks:mcp-initialized',\n metadata: { hookType: 'mcp-initialized', server: serverName },\n });\n\n console.log(` 💾 MCP session saved to .swarm/memory.db`);\n printSuccess(`✅ MCP initialized hook completed`);\n } catch (err) {\n printError(`MCP initialized hook failed: ${err.message}`);\n }\n}\n\nasync function agentSpawnedCommand(subArgs, flags) {\n const options = flags;\n const agentType = options.type || 'generic';\n const agentName = options.name || generateId('agent');\n const swarmId = options['swarm-id'] || 'default';\n\n console.log(`🤖 Executing agent-spawned hook...`);\n console.log(`📛 Agent: ${agentName}`);\n console.log(`🏷️ Type: ${agentType}`);\n\n try {\n const store = await getMemoryStore();\n const agentData = {\n agentName,\n agentType,\n swarmId,\n spawnedAt: new Date().toISOString(),\n status: 'active',\n };\n\n await store.store(`agent:${agentName}`, agentData, {\n namespace: 'hooks:agent-spawned',\n metadata: { hookType: 'agent-spawned', type: agentType },\n });\n\n // Update agent roster\n await store.store(\n `agent-roster:${Date.now()}`,\n {\n agentName,\n action: 'spawned',\n timestamp: new Date().toISOString(),\n },\n { namespace: 'agent-roster' },\n );\n\n console.log(` 💾 Agent registered to .swarm/memory.db`);\n printSuccess(`✅ Agent spawned hook completed`);\n } catch (err) {\n printError(`Agent spawned hook failed: ${err.message}`);\n }\n}\n\nasync function taskOrchestratedCommand(subArgs, flags) {\n const options = flags;\n const taskId = options['task-id'] || generateId('orchestrated-task');\n const strategy = options.strategy || 'balanced';\n const priority = options.priority || 'medium';\n\n console.log(`🎭 Executing task-orchestrated hook...`);\n console.log(`🆔 Task: ${taskId}`);\n console.log(`📊 Strategy: ${strategy}`);\n\n try {\n const store = await getMemoryStore();\n const orchestrationData = {\n taskId,\n strategy,\n priority,\n orchestratedAt: new Date().toISOString(),\n status: 'orchestrated',\n };\n\n await store.store(`orchestration:${taskId}`, orchestrationData, {\n namespace: 'hooks:task-orchestrated',\n metadata: { hookType: 'task-orchestrated', strategy },\n });\n\n console.log(` 💾 Orchestration saved to .swarm/memory.db`);\n printSuccess(`✅ Task orchestrated hook completed`);\n } catch (err) {\n printError(`Task orchestrated hook failed: ${err.message}`);\n }\n}\n\nasync function neuralTrainedCommand(subArgs, flags) {\n const options = flags;\n const modelName = options.model || 'default-neural';\n const accuracy = options.accuracy || '0.0';\n const patterns = options.patterns || '0';\n\n console.log(`🧠 Executing neural-trained hook...`);\n console.log(`🤖 Model: ${modelName}`);\n console.log(`📊 Accuracy: ${accuracy}%`);\n\n try {\n const store = await getMemoryStore();\n const trainingData = {\n modelName,\n accuracy: parseFloat(accuracy),\n patternsLearned: parseInt(patterns),\n trainedAt: new Date().toISOString(),\n };\n\n await store.store(`neural:${modelName}:${Date.now()}`, trainingData, {\n namespace: 'hooks:neural-trained',\n metadata: { hookType: 'neural-trained', model: modelName },\n });\n\n console.log(` 💾 Training results saved to .swarm/memory.db`);\n printSuccess(`✅ Neural trained hook completed`);\n } catch (err) {\n printError(`Neural trained hook failed: ${err.message}`);\n }\n}\n\n// ===== SESSION HOOKS =====\n\nasync function sessionEndCommand(subArgs, flags) {\n const options = flags;\n const generateSummary = options['generate-summary'] !== 'false';\n const persistState = options['persist-state'] !== 'false';\n const exportMetrics = options['export-metrics'] || false;\n\n console.log(`🔚 Executing session-end hook...`);\n if (generateSummary) console.log(`📊 Summary generation: ENABLED`);\n if (persistState) console.log(`💾 State persistence: ENABLED`);\n if (exportMetrics) console.log(`📈 Metrics export: ENABLED`);\n\n try {\n const store = await getMemoryStore();\n const tasks = await store.list({ namespace: 'task-index', limit: 1000 });\n const edits = await store.list({ namespace: 'file-history', limit: 1000 });\n const commands = await store.list({ namespace: 'command-history', limit: 1000 });\n const agents = await store.list({ namespace: 'agent-roster', limit: 1000 });\n\n // Calculate session metrics\n let metrics = null;\n if (exportMetrics) {\n const now = new Date();\n const sessionStart = Math.min(\n ...tasks.map((t) => new Date(t.value.timestamp || now).getTime()),\n ...edits.map((e) => new Date(e.value.timestamp || now).getTime()),\n ...commands.map((c) => new Date(c.value.timestamp || now).getTime()),\n );\n\n const duration = now.getTime() - sessionStart;\n const successfulCommands = commands.filter((c) => c.value.success !== false).length;\n const commandSuccessRate = commands.length > 0 ? successfulCommands / commands.length : 1;\n\n metrics = {\n sessionDuration: duration,\n sessionDurationHuman: `${Math.round(duration / 1000 / 60)} minutes`,\n totalTasks: tasks.length,\n totalEdits: edits.length,\n totalCommands: commands.length,\n uniqueAgents: agents.length,\n commandSuccessRate: Math.round(commandSuccessRate * 100),\n avgTasksPerMinute: Math.round((tasks.length / (duration / 1000 / 60)) * 100) / 100,\n avgEditsPerMinute: Math.round((edits.length / (duration / 1000 / 60)) * 100) / 100,\n timestamp: now.toISOString(),\n };\n }\n\n const sessionData = {\n endedAt: new Date().toISOString(),\n totalTasks: tasks.length,\n totalEdits: edits.length,\n totalCommands: commands.length,\n uniqueAgents: agents.length,\n sessionId: generateId('session'),\n generateSummary,\n persistState,\n exportMetrics,\n metrics,\n };\n\n await store.store(`session:${sessionData.sessionId}`, sessionData, {\n namespace: 'sessions',\n metadata: { hookType: 'session-end' },\n });\n\n // Persist detailed state if requested\n if (persistState) {\n const detailedState = {\n sessionId: sessionData.sessionId,\n tasks: tasks.slice(0, 100), // Limit to prevent memory issues\n edits: edits.slice(0, 100),\n commands: commands.slice(0, 100),\n agents: agents.slice(0, 50),\n persistedAt: new Date().toISOString(),\n fullState: true,\n };\n\n await store.store(`session-state:${sessionData.sessionId}`, detailedState, {\n namespace: 'session-states',\n metadata: { type: 'full-state', sessionId: sessionData.sessionId },\n });\n\n console.log(` 💾 Full session state persisted`);\n }\n\n // Export metrics if requested\n if (exportMetrics && metrics) {\n await store.store(`session-metrics:${sessionData.sessionId}`, metrics, {\n namespace: 'session-metrics',\n metadata: { type: 'performance-metrics', sessionId: sessionData.sessionId },\n });\n\n console.log(` 📈 Session metrics exported`);\n }\n\n if (generateSummary) {\n console.log(`\\n📊 SESSION SUMMARY:`);\n console.log(` 📋 Tasks: ${sessionData.totalTasks}`);\n console.log(` ✏️ Edits: ${sessionData.totalEdits}`);\n console.log(` 🔧 Commands: ${sessionData.totalCommands}`);\n console.log(` 🤖 Agents: ${sessionData.uniqueAgents}`);\n\n if (metrics) {\n console.log(` ⏱️ Duration: ${metrics.sessionDurationHuman}`);\n console.log(` 📈 Success Rate: ${metrics.commandSuccessRate}%`);\n console.log(` 🏃 Tasks/min: ${metrics.avgTasksPerMinute}`);\n console.log(` ✏️ Edits/min: ${metrics.avgEditsPerMinute}`);\n }\n }\n\n console.log(` 💾 Session saved to .swarm/memory.db`);\n\n if (memoryStore) {\n memoryStore.close();\n memoryStore = null;\n }\n\n printSuccess(`✅ Session-end hook completed`);\n } catch (err) {\n printError(`Session-end hook failed: ${err.message}`);\n }\n}\n\nasync function sessionRestoreCommand(subArgs, flags) {\n const options = flags;\n const sessionId = options['session-id'] || 'latest';\n\n console.log(`🔄 Executing session-restore hook...`);\n console.log(`🆔 Session: ${sessionId}`);\n\n try {\n const store = await getMemoryStore();\n\n // Find session to restore\n let sessionData;\n if (sessionId === 'latest') {\n const sessions = await store.list({ namespace: 'sessions', limit: 1 });\n sessionData = sessions[0]?.value;\n } else {\n sessionData = await store.retrieve(`session:${sessionId}`, { namespace: 'sessions' });\n }\n\n if (sessionData) {\n console.log(`\\n📊 RESTORED SESSION:`);\n console.log(` 🆔 ID: ${sessionData.sessionId || 'unknown'}`);\n console.log(` 📋 Tasks: ${sessionData.totalTasks || 0}`);\n console.log(` ✏️ Edits: ${sessionData.totalEdits || 0}`);\n console.log(` ⏰ Ended: ${sessionData.endedAt || 'unknown'}`);\n\n // Store restoration event\n await store.store(\n `session-restore:${Date.now()}`,\n {\n restoredSessionId: sessionData.sessionId || sessionId,\n restoredAt: new Date().toISOString(),\n },\n { namespace: 'session-events' },\n );\n\n console.log(` 💾 Session restored from .swarm/memory.db`);\n printSuccess(`✅ Session restore completed`);\n } else {\n printWarning(`No session found with ID: ${sessionId}`);\n }\n } catch (err) {\n printError(`Session restore hook failed: ${err.message}`);\n }\n}\n\nasync function notifyCommand(subArgs, flags) {\n const options = flags;\n const message = options.message || subArgs.slice(1).join(' ');\n const level = options.level || 'info';\n const swarmStatus = options['swarm-status'] || 'active';\n\n console.log(`📢 Executing notify hook...`);\n console.log(`💬 Message: ${message}`);\n console.log(`📊 Level: ${level}`);\n\n try {\n const store = await getMemoryStore();\n const notificationData = {\n message,\n level,\n swarmStatus,\n timestamp: new Date().toISOString(),\n notifyId: generateId('notify'),\n };\n\n await store.store(`notification:${notificationData.notifyId}`, notificationData, {\n namespace: 'hooks:notify',\n metadata: { hookType: 'notify', level },\n });\n\n // Display notification\n const icon = level === 'error' ? '❌' : level === 'warning' ? '⚠️' : '✅';\n console.log(`\\n${icon} NOTIFICATION:`);\n console.log(` ${message}`);\n console.log(` 🐝 Swarm: ${swarmStatus}`);\n\n console.log(`\\n 💾 Notification saved to .swarm/memory.db`);\n printSuccess(`✅ Notify hook completed`);\n } catch (err) {\n printError(`Notify hook failed: ${err.message}`);\n }\n}\n\n// ===== PRETOOLUSE MODIFICATION HOOKS (v2.0.10+) =====\n\nasync function modifyBashCommand(subArgs, flags) {\n // Read JSON from stdin with timeout to detect if data is piped\n let input = '';\n let hasInput = false;\n\n const timeout = setTimeout(() => {\n if (!hasInput) {\n console.log('Usage: echo \\'{\"tool_input\":{\"command\":\"your command\"}}\\' | claude-flow hooks modify-bash');\n console.log('\\nThis hook reads JSON from stdin and outputs modified JSON.');\n console.log('It is designed for use with Claude Code v2.0.10+ PreToolUse feature.');\n console.log('\\nExample:');\n console.log(' echo \\'{\"tool_input\":{\"command\":\"rm test.txt\"}}\\' | claude-flow hooks modify-bash');\n process.exit(0);\n }\n }, 100); // 100ms timeout\n\n for await (const chunk of process.stdin) {\n hasInput = true;\n clearTimeout(timeout);\n input += chunk;\n }\n\n if (!input.trim()) {\n return; // Silently exit if no input\n }\n\n const toolInput = JSON.parse(input);\n const command = toolInput.tool_input?.command || '';\n\n if (!command) {\n console.log(input); // Pass through if no command\n return;\n }\n\n let modifiedCommand = command;\n const notes = [];\n\n // 1. Safety: Add -i flag to rm commands\n if (/^rm\\s/.test(command) && !/-[iI]/.test(command)) {\n modifiedCommand = command.replace(/^rm /, 'rm -i ');\n notes.push('[Safety: Added -i flag for interactive confirmation]');\n }\n\n // 2. Aliases\n if (/^ll(\\s|$)/.test(command)) {\n modifiedCommand = command.replace(/^ll/, 'ls -lah');\n notes.push('[Alias: ll → ls -lah]');\n } else if (/^la(\\s|$)/.test(command)) {\n modifiedCommand = command.replace(/^la/, 'ls -la');\n notes.push('[Alias: la → ls -la]');\n }\n\n // 3. Path correction: Redirect test files to /tmp\n if (/>\\s*test.*\\.(txt|log|tmp|json|md)/.test(command) && !/\\/tmp\\//.test(command)) {\n modifiedCommand = command.replace(/>\\s*(test[^/]*\\.(txt|log|tmp|json|md))/, '> /tmp/$1');\n notes.push('[Path: Redirected test file to /tmp/]');\n }\n\n // 4. Secret detection\n if (/(password|secret|token|api[-_]?key|auth)/i.test(command) && !/#\\s*SECRETS_OK/.test(command)) {\n notes.push('[Security: Command contains sensitive keywords. Add \"# SECRETS_OK\" to bypass]');\n }\n\n // Output modified JSON\n const output = {\n ...toolInput,\n tool_input: {\n ...toolInput.tool_input,\n command: modifiedCommand,\n },\n };\n\n if (notes.length > 0) {\n output.modification_notes = notes.join(' ');\n }\n\n console.log(JSON.stringify(output, null, 2));\n}\n\nasync function modifyFileCommand(subArgs, flags) {\n // Read JSON from stdin with timeout to detect if data is piped\n let input = '';\n let hasInput = false;\n\n const timeout = setTimeout(() => {\n if (!hasInput) {\n console.log('Usage: echo \\'{\"tool_input\":{\"file_path\":\"your/file.js\"}}\\' | claude-flow hooks modify-file');\n console.log('\\nThis hook reads JSON from stdin and outputs modified JSON.');\n console.log('It is designed for use with Claude Code v2.0.10+ PreToolUse feature.');\n console.log('\\nExample:');\n console.log(' echo \\'{\"tool_input\":{\"file_path\":\"test.js\"}}\\' | claude-flow hooks modify-file');\n process.exit(0);\n }\n }, 100); // 100ms timeout\n\n for await (const chunk of process.stdin) {\n hasInput = true;\n clearTimeout(timeout);\n input += chunk;\n }\n\n if (!input.trim()) {\n return; // Silently exit if no input\n }\n\n const toolInput = JSON.parse(input);\n const filePath = toolInput.tool_input?.file_path || toolInput.tool_input?.path || '';\n\n if (!filePath) {\n console.log(input); // Pass through if no file path\n return;\n }\n\n let modifiedPath = filePath;\n let shouldModify = false;\n const notes = [];\n\n // 1. Root folder protection\n const isRootFile = /^[^/]*\\.(js|ts|jsx|tsx|py|java|go|rs|cpp|c|h)$/.test(filePath) ||\n /^test.*\\.(txt|log|tmp|json|md)$/.test(filePath) ||\n /^(temp|tmp|working)/.test(filePath);\n\n if (isRootFile) {\n if (/test.*\\.(test|spec)\\.|\\.test\\.|\\.spec\\./.test(filePath)) {\n modifiedPath = `tests/${filePath}`;\n shouldModify = true;\n notes.push('[Organization: Moved test file to /tests/]');\n } else if (/test.*\\.md|temp.*\\.md|working.*\\.md|scratch.*\\.md/.test(filePath)) {\n modifiedPath = `docs/working/${filePath}`;\n shouldModify = true;\n notes.push('[Organization: Moved working document to /docs/working/]');\n } else if (/\\.(js|ts|jsx|tsx|py)$/.test(filePath)) {\n modifiedPath = `src/${filePath}`;\n shouldModify = true;\n notes.push('[Organization: Moved source file to /src/]');\n } else if (/^(temp|tmp|scratch)/.test(filePath)) {\n modifiedPath = `/tmp/${filePath}`;\n shouldModify = true;\n notes.push('[Organization: Redirected temporary file to /tmp/]');\n }\n }\n\n // 2. Format hints\n if (/\\.(ts|tsx|js|jsx)$/.test(modifiedPath)) {\n notes.push('[Tip: Auto-format with Prettier/ESLint recommended]');\n } else if (/\\.py$/.test(modifiedPath)) {\n notes.push('[Tip: Auto-format with Black/autopep8 recommended]');\n }\n\n // Output modified JSON\n const output = {\n ...toolInput,\n tool_input: {\n ...toolInput.tool_input,\n },\n };\n\n if (shouldModify) {\n if (toolInput.tool_input.file_path) {\n output.tool_input.file_path = modifiedPath;\n } else {\n output.tool_input.path = modifiedPath;\n }\n }\n\n if (notes.length > 0) {\n output.modification_notes = notes.join(' ');\n }\n\n console.log(JSON.stringify(output, null, 2));\n}\n\nasync function modifyGitCommitCommand(subArgs, flags) {\n // Read JSON from stdin with timeout to detect if data is piped\n let input = '';\n let hasInput = false;\n\n const timeout = setTimeout(() => {\n if (!hasInput) {\n console.log('Usage: echo \\'{\"tool_input\":{\"command\":\"git commit -m \\\\\"message\\\\\"\"}}\\' | claude-flow hooks modify-git-commit');\n console.log('\\nThis hook reads JSON from stdin and outputs modified JSON.');\n console.log('It is designed for use with Claude Code v2.0.10+ PreToolUse feature.');\n console.log('\\nExample:');\n console.log(' echo \\'{\"tool_input\":{\"command\":\"git commit -m \\\\\"fix bug\\\\\"\"}}\\' | claude-flow hooks modify-git-commit');\n process.exit(0);\n }\n }, 100); // 100ms timeout\n\n for await (const chunk of process.stdin) {\n hasInput = true;\n clearTimeout(timeout);\n input += chunk;\n }\n\n if (!input.trim()) {\n return; // Silently exit if no input\n }\n\n const toolInput = JSON.parse(input);\n const command = toolInput.tool_input?.command || '';\n\n if (!command || !/git commit/.test(command)) {\n console.log(input); // Pass through if not git commit\n return;\n }\n\n // Extract commit message\n const msgMatch = command.match(/-m\\s+[\"']([^\"']+)[\"']/) || command.match(/-m\\s+(\\S+)/);\n const commitMsg = msgMatch ? msgMatch[1] : '';\n\n if (!commitMsg || /^\\[(feat|fix|docs|style|refactor|test|chore|perf)\\]/.test(commitMsg)) {\n console.log(input); // Already formatted or no message\n return;\n }\n\n const notes = [];\n\n // Get current branch\n let branch = 'main';\n let ticket = '';\n try {\n const { execSync } = await import('child_process');\n branch = execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf8' }).trim();\n\n // Extract JIRA ticket\n const ticketMatch = branch.match(/[A-Z]+-[0-9]+/);\n if (ticketMatch) {\n ticket = ticketMatch[0];\n }\n } catch {\n // Git not available, continue\n }\n\n // Detect conventional commit type\n let type = 'chore';\n if (/^(add|implement|create|new)/i.test(commitMsg)) type = 'feat';\n else if (/^(fix|resolve|patch|correct)/i.test(commitMsg)) type = 'fix';\n else if (/^(update|modify|change|improve)/i.test(commitMsg)) type = 'refactor';\n else if (/^(doc|documentation|readme)/i.test(commitMsg)) type = 'docs';\n else if (/^(test|testing|spec)/i.test(commitMsg)) type = 'test';\n else if (/^(style|format|lint)/i.test(commitMsg)) type = 'style';\n else if (/^(perf|optimize|speed)/i.test(commitMsg)) type = 'perf';\n\n // Format message\n let formattedMsg = ticket\n ? `[${type}] ${commitMsg} (${ticket})`\n : `[${type}] ${commitMsg}`;\n\n // Add co-author\n if (!/Co-Authored-By/.test(command)) {\n formattedMsg += `\\n\\n🤖 Generated with Claude Flow\\nCo-Authored-By: claude-flow <[email protected]>`;\n }\n\n // Replace message in command\n const modifiedCommand = command.replace(\n /-m\\s+[\"'][^\"']+[\"']|-m\\s+\\S+/,\n `-m \"$(cat <<'EOF'\\n${formattedMsg}\\nEOF\\n)\"`\n );\n\n notes.push(`[Auto-formatted: ${type} type${ticket ? ` + ${ticket}` : ''}]`);\n\n // Output modified JSON\n const output = {\n ...toolInput,\n tool_input: {\n ...toolInput.tool_input,\n command: modifiedCommand,\n },\n modification_notes: notes.join(' '),\n };\n\n console.log(JSON.stringify(output, null, 2));\n}\n\nfunction showHooksHelp() {\n console.log('Claude Flow Hooks (with .swarm/memory.db persistence):\\n');\n\n console.log('Pre-Operation Hooks:');\n console.log(' pre-task Execute before starting a task');\n console.log(' pre-edit Validate before file modifications');\n console.log(' --auto-assign-agents Auto-assign agents based on file type');\n console.log(' --load-context Load file context');\n console.log(' pre-bash Check command safety (alias: pre-command)');\n console.log(' pre-command Same as pre-bash');\n console.log(' --validate-safety Enable safety validation');\n console.log(' --prepare-resources Prepare execution resources');\n\n console.log('\\nPost-Operation Hooks:');\n console.log(' post-task Execute after completing a task');\n console.log(' post-edit Auto-format and log edits');\n console.log(' --format Auto-format code');\n console.log(' --update-memory Update agent memory');\n console.log(' --train-neural Train neural patterns');\n console.log(' post-bash Log command execution (alias: post-command)');\n console.log(' post-command Same as post-bash');\n console.log(' --track-metrics Track performance metrics');\n console.log(' --store-results Store detailed results');\n console.log(' post-search Cache search results');\n\n console.log('\\nMCP Integration Hooks:');\n console.log(' mcp-initialized Persist MCP configuration');\n console.log(' agent-spawned Update agent roster');\n console.log(' task-orchestrated Monitor task progress');\n console.log(' neural-trained Save pattern improvements');\n\n console.log('\\nSession Hooks:');\n console.log(' session-end Generate summary and save state');\n console.log(' --generate-summary Generate session summary');\n console.log(' --persist-state Persist session state');\n console.log(' --export-metrics Export performance metrics');\n console.log(' session-restore Load previous session state');\n console.log(' notify Custom notifications');\n\n console.log('\\n===== NEW: PreToolUse Modification Hooks (v2.0.10+) =====');\n console.log(' modify-bash Modify Bash tool inputs (reads/writes JSON via stdin/stdout)');\n console.log(' • Safety: Adds -i flag to rm commands');\n console.log(' • Aliases: ll → ls -lah, la → ls -la');\n console.log(' • Path correction: Redirects test files to /tmp');\n console.log(' • Secret detection: Warns about sensitive keywords');\n console.log('');\n console.log(' modify-file Modify Write/Edit tool inputs (reads/writes JSON via stdin/stdout)');\n console.log(' • Root folder protection: Moves files to appropriate directories');\n console.log(' • Organization: Tests → /tests/, Sources → /src/, Docs → /docs/');\n console.log(' • Format hints: Suggests Prettier, Black, etc.');\n console.log('');\n console.log(' modify-git-commit Modify git commit messages (reads/writes JSON via stdin/stdout)');\n console.log(' • Conventional commits: Auto-adds [feat], [fix], [docs], etc.');\n console.log(' • Ticket extraction: Extracts JIRA tickets from branch names');\n console.log(' • Co-author: Adds Claude Flow co-author footer');\n\n console.log('\\nExamples:');\n console.log(' hooks pre-command --command \"npm test\" --validate-safety true');\n console.log(' hooks pre-edit --file \"src/app.js\" --auto-assign-agents true');\n console.log(' hooks post-command --command \"build\" --track-metrics true');\n console.log(' hooks post-edit --file \"src/app.js\" --format true --train-neural true');\n console.log(' hooks session-end --generate-summary true --export-metrics true');\n console.log(' hooks agent-spawned --name \"CodeReviewer\" --type \"reviewer\"');\n console.log(' hooks notify --message \"Build completed\" --level \"success\"');\n console.log('');\n console.log(' # New modification hooks (stdin/stdout JSON):');\n console.log(' echo \\'{\"tool_input\":{\"command\":\"rm test.txt\"}}\\' | hooks modify-bash');\n console.log(' echo \\'{\"tool_input\":{\"file_path\":\"test.js\"}}\\' | hooks modify-file');\n console.log(' echo \\'{\"tool_input\":{\"command\":\"git commit -m \\\\\"fix bug\\\\\"\"}}\\' | hooks modify-git-commit');\n\n console.log('\\nCompatibility:');\n console.log(' • pre-command and pre-bash are aliases');\n console.log(' • post-command and post-bash are aliases');\n console.log(' • Both --dash-case and camelCase parameters supported');\n console.log(' • All parameters from settings.json template supported');\n console.log(' • New modification hooks work with Claude Code v2.0.10+ PreToolUse feature');\n}\n\nexport default hooksAction;\n"],"names":["printSuccess","printError","printWarning","execRuvSwarmHook","checkRuvSwarmAvailable","SqliteMemoryStore","memoryStore","getMemoryStore","initialize","generateId","prefix","Date","now","Math","random","toString","substr","hooksAction","subArgs","flags","subcommand","options","help","h","showHooksHelp","preTaskCommand","preEditCommand","preBashCommand","postTaskCommand","postEditCommand","postBashCommand","postSearchCommand","mcpInitializedCommand","agentSpawnedCommand","taskOrchestratedCommand","neuralTrainedCommand","sessionEndCommand","sessionRestoreCommand","notifyCommand","modifyBashCommand","modifyFileCommand","modifyGitCommitCommand","err","message","description","taskId","agentId","autoSpawnAgents","console","log","store","taskData","status","startedAt","toISOString","namespace","metadata","hookType","timestamp","checkPromise","timeoutPromise","Promise","_","reject","setTimeout","Error","isAvailable","race","hookResult","success","output","close","process","exit","file","operation","autoAssignAgents","loadContext","assignedAgentType","recommendedAgent","path","ext","extname","toLowerCase","agentMapping","type","extension","recommended","contextData","fs","existsSync","stats","statSync","dirname","basename","fileExists","size","modified","mtime","directory","filename","isDirectory","willCreate","error","editData","editId","agentType","ttl","command","slice","join","workingDir","cwd","validateSafety","validate","prepareResources","safetyResult","dangerousCommands","isDangerous","length","some","dangerous","includes","mkdirSync","recursive","bashData","bashId","safety","validationEnabled","resourcesPrepped","toUpperCase","analyzePerformance","retrieve","completedData","completedAt","duration","getTime","metrics","durationHuman","toFixed","memoryKey","format","updateMemory","trainNeural","formatResult","formatters","formatter","attempted","reason","memoryUpdate","editContext","editedAt","formatted","fileSize","neuralTraining","editTime","patterns","fileType","fileName","confidence","enhanced","historyKey","replace","features","exitCode","trackMetrics","storeResults","startTime","commandLength","outputLength","parseInt","complexity","substring","fullOutput","existingMetrics","totalCommands","successRate","avgDuration","lastUpdated","hasMetrics","hasResults","query","resultCount","searchType","searchData","searchId","cachedAt","serverName","server","sessionId","mcpData","initializedAt","agentName","name","swarmId","agentData","spawnedAt","action","strategy","priority","orchestrationData","orchestratedAt","modelName","model","accuracy","trainingData","parseFloat","patternsLearned","trainedAt","generateSummary","persistState","exportMetrics","tasks","list","limit","edits","commands","agents","sessionStart","min","map","t","value","e","c","successfulCommands","filter","commandSuccessRate","sessionDuration","sessionDurationHuman","round","totalTasks","totalEdits","uniqueAgents","avgTasksPerMinute","avgEditsPerMinute","sessionData","endedAt","detailedState","persistedAt","fullState","sessions","restoredSessionId","restoredAt","level","swarmStatus","notificationData","notifyId","icon","input","hasInput","timeout","chunk","stdin","clearTimeout","trim","toolInput","JSON","parse","tool_input","modifiedCommand","notes","test","push","modification_notes","stringify","filePath","file_path","modifiedPath","shouldModify","isRootFile","msgMatch","match","commitMsg","branch","ticket","execSync","encoding","ticketMatch","formattedMsg"],"mappings":"AAAA,SACEA,YAAY,EACZC,UAAU,EACVC,YAAY,EACZC,gBAAgB,EAChBC,sBAAsB,QACjB,cAAc;AACrB,SAASC,iBAAiB,QAAQ,+BAA+B;AAGjE,IAAIC,cAAc;AAElB,eAAeC;IACb,IAAI,CAACD,aAAa;QAChBA,cAAc,IAAID;QAClB,MAAMC,YAAYE,UAAU;IAC9B;IACA,OAAOF;AACT;AAGA,SAASG,WAAWC,SAAS,IAAI;IAC/B,OAAO,GAAGA,OAAO,CAAC,EAAEC,KAAKC,GAAG,GAAG,CAAC,EAAEC,KAAKC,MAAM,GAAGC,QAAQ,CAAC,IAAIC,MAAM,CAAC,GAAG,IAAI;AAC7E;AAEA,OAAO,eAAeC,YAAYC,OAAO,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EZD,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,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;IAEZD,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,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IAEZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;AACd;AAEA,eAAehC,YAAY"}
\ No newline at end of file
+{"version":3,"sources":["../../../../src/cli/simple-commands/hooks.js"],"sourcesContent":["import {\n printSuccess,\n printError,\n printWarning,\n execRuvSwarmHook,\n checkRuvSwarmAvailable,\n} from '../utils.js';\nimport { SqliteMemoryStore } from '../../memory/sqlite-store.js';\nimport { InMemoryStore } from '../../memory/in-memory-store.js';\n\n// Initialize memory store\nlet memoryStore = null;\nlet storeInitFailed = false;\n\nasync function getMemoryStore() {\n if (memoryStore) return memoryStore;\n\n // If we already failed, return a working in-memory store\n if (storeInitFailed) {\n if (!memoryStore) {\n memoryStore = new InMemoryStore();\n await memoryStore.initialize();\n }\n return memoryStore;\n }\n\n try {\n memoryStore = new SqliteMemoryStore();\n await memoryStore.initialize();\n } catch (err) {\n // Check if it's a native module error (NODE_MODULE_VERSION mismatch)\n const isNativeModuleError =\n err.message?.includes('NODE_MODULE_VERSION') ||\n err.message?.includes('was compiled against a different Node.js version') ||\n err.message?.includes('better-sqlite3') ||\n err.message?.includes('SQLite is not available');\n\n if (isNativeModuleError) {\n printWarning(`SQLite unavailable, using in-memory storage for hooks (data won't persist)`);\n storeInitFailed = true;\n memoryStore = new InMemoryStore();\n await memoryStore.initialize();\n } else {\n throw err;\n }\n }\n\n return memoryStore;\n}\n\n// Simple ID generator\nfunction generateId(prefix = 'id') {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n}\n\nexport async function hooksAction(subArgs, flags) {\n const subcommand = subArgs[0];\n const options = flags;\n\n if (options.help || options.h || !subcommand) {\n showHooksHelp();\n return;\n }\n\n try {\n switch (subcommand) {\n // Pre-Operation Hooks\n case 'pre-task':\n await preTaskCommand(subArgs, flags);\n break;\n case 'pre-edit':\n await preEditCommand(subArgs, flags);\n break;\n case 'pre-bash':\n case 'pre-command': // Support both names for compatibility\n await preBashCommand(subArgs, flags);\n break;\n\n // Post-Operation Hooks\n case 'post-task':\n await postTaskCommand(subArgs, flags);\n break;\n case 'post-edit':\n await postEditCommand(subArgs, flags);\n break;\n case 'post-bash':\n case 'post-command': // Support both names for compatibility\n await postBashCommand(subArgs, flags);\n break;\n case 'post-search':\n await postSearchCommand(subArgs, flags);\n break;\n\n // MCP Integration Hooks\n case 'mcp-initialized':\n await mcpInitializedCommand(subArgs, flags);\n break;\n case 'agent-spawned':\n await agentSpawnedCommand(subArgs, flags);\n break;\n case 'task-orchestrated':\n await taskOrchestratedCommand(subArgs, flags);\n break;\n case 'neural-trained':\n await neuralTrainedCommand(subArgs, flags);\n break;\n\n // Session Hooks\n case 'session-end':\n await sessionEndCommand(subArgs, flags);\n break;\n case 'session-restore':\n await sessionRestoreCommand(subArgs, flags);\n break;\n case 'notify':\n await notifyCommand(subArgs, flags);\n break;\n\n // NEW: PreToolUse Modification Hooks (v2.0.10+)\n case 'modify-bash':\n await modifyBashCommand(subArgs, flags);\n break;\n case 'modify-file':\n await modifyFileCommand(subArgs, flags);\n break;\n case 'modify-git-commit':\n await modifyGitCommitCommand(subArgs, flags);\n break;\n\n default:\n printError(`Unknown hooks command: ${subcommand}`);\n showHooksHelp();\n }\n } catch (err) {\n printError(`Hooks command failed: ${err.message}`);\n }\n}\n\n// ===== PRE-OPERATION HOOKS =====\n\nasync function preTaskCommand(subArgs, flags) {\n const options = flags;\n const description = options.description || 'Unnamed task';\n const taskId = options['task-id'] || options.taskId || generateId('task');\n const agentId = options['agent-id'] || options.agentId;\n const autoSpawnAgents = options['auto-spawn-agents'] !== 'false';\n\n console.log(`🔄 Executing pre-task hook...`);\n console.log(`📋 Task: ${description}`);\n console.log(`🆔 Task ID: ${taskId}`);\n if (agentId) console.log(`🤖 Agent: ${agentId}`);\n\n try {\n const store = await getMemoryStore();\n const taskData = {\n taskId,\n description,\n agentId,\n autoSpawnAgents,\n status: 'started',\n startedAt: new Date().toISOString(),\n };\n\n await store.store(`task:${taskId}`, taskData, {\n namespace: 'hooks:pre-task',\n metadata: { hookType: 'pre-task', agentId },\n });\n\n await store.store(\n `task-index:${Date.now()}`,\n {\n taskId,\n description,\n timestamp: new Date().toISOString(),\n },\n { namespace: 'task-index' },\n );\n\n console.log(` 💾 Saved to .swarm/memory.db`);\n\n // Execute ruv-swarm hook if available (with timeout for npx scenarios)\n try {\n const checkPromise = checkRuvSwarmAvailable();\n const timeoutPromise = new Promise((_, reject) => \n setTimeout(() => reject(new Error('Timeout')), 3000)\n );\n \n const isAvailable = await Promise.race([checkPromise, timeoutPromise]);\n \n if (isAvailable) {\n console.log(`\\n🔄 Executing ruv-swarm pre-task hook...`);\n const hookResult = await execRuvSwarmHook('pre-task', {\n description,\n 'task-id': taskId,\n 'auto-spawn-agents': autoSpawnAgents,\n ...(agentId ? { 'agent-id': agentId } : {}),\n });\n\n if (hookResult.success) {\n await store.store(\n `task:${taskId}:ruv-output`,\n {\n output: hookResult.output,\n timestamp: new Date().toISOString(),\n },\n { namespace: 'hooks:ruv-swarm' },\n );\n\n printSuccess(`✅ Pre-task hook completed successfully`);\n }\n }\n } catch (err) {\n // Skip ruv-swarm hook if it times out or fails\n console.log(`\\n⚠️ Skipping ruv-swarm hook (${err.message})`);\n }\n\n console.log(`\\n🎯 TASK PREPARATION COMPLETE`);\n \n // Close the memory store to prevent hanging\n if (memoryStore && memoryStore.close) {\n memoryStore.close();\n }\n \n // Force exit after a short delay to ensure cleanup\n setTimeout(() => {\n process.exit(0);\n }, 100);\n } catch (err) {\n printError(`Pre-task hook failed: ${err.message}`);\n \n // Close the memory store on error too\n if (memoryStore && memoryStore.close) {\n memoryStore.close();\n }\n \n // Force exit after a short delay to ensure cleanup\n setTimeout(() => {\n process.exit(1);\n }, 100);\n }\n}\n\nasync function preEditCommand(subArgs, flags) {\n const options = flags;\n const file = options.file || 'unknown-file';\n const operation = options.operation || 'edit';\n const autoAssignAgents = options['auto-assign-agents'] || false;\n const loadContext = options['load-context'] || false;\n\n console.log(`📝 Executing pre-edit hook...`);\n console.log(`📄 File: ${file}`);\n console.log(`⚙️ Operation: ${operation}`);\n if (autoAssignAgents) console.log(`🤖 Auto-assign agents: ENABLED`);\n if (loadContext) console.log(`🔄 Load context: ENABLED`);\n\n try {\n const store = await getMemoryStore();\n\n // Auto-assign agents based on file type\n let assignedAgentType = 'general';\n let recommendedAgent = null;\n\n if (autoAssignAgents) {\n const path = await import('path');\n const ext = path.extname(file).toLowerCase();\n\n const agentMapping = {\n '.js': 'javascript-developer',\n '.ts': 'typescript-developer',\n '.py': 'python-developer',\n '.go': 'golang-developer',\n '.rs': 'rust-developer',\n '.java': 'java-developer',\n '.cpp': 'cpp-developer',\n '.c': 'c-developer',\n '.css': 'frontend-developer',\n '.html': 'frontend-developer',\n '.vue': 'frontend-developer',\n '.react': 'frontend-developer',\n '.md': 'technical-writer',\n '.yml': 'devops-engineer',\n '.yaml': 'devops-engineer',\n '.json': 'config-specialist',\n '.sql': 'database-expert',\n '.sh': 'system-admin',\n '.dockerfile': 'devops-engineer',\n };\n\n assignedAgentType = agentMapping[ext] || 'general-developer';\n recommendedAgent = {\n type: assignedAgentType,\n file: file,\n extension: ext,\n recommended: true,\n };\n\n console.log(` 🤖 Recommended agent: ${assignedAgentType}`);\n }\n\n // Load context if requested\n let contextData = null;\n if (loadContext) {\n try {\n // Check if file exists and get basic info\n const fs = await import('fs');\n const path = await import('path');\n\n if (fs.existsSync(file)) {\n const stats = fs.statSync(file);\n const dirname = path.dirname(file);\n const basename = path.basename(file);\n\n contextData = {\n fileExists: true,\n size: stats.size,\n modified: stats.mtime,\n directory: dirname,\n filename: basename,\n isDirectory: stats.isDirectory(),\n };\n\n console.log(` 📁 Context loaded: ${basename} (${stats.size} bytes)`);\n } else {\n contextData = {\n fileExists: false,\n willCreate: true,\n directory: path.dirname(file),\n filename: path.basename(file),\n };\n console.log(` 📁 Context: New file will be created`);\n }\n } catch (err) {\n console.log(` ⚠️ Warning: Could not load context for ${file}`);\n contextData = { error: err.message };\n }\n }\n\n const editData = {\n file,\n operation,\n timestamp: new Date().toISOString(),\n editId: generateId('edit'),\n autoAssignAgents,\n loadContext,\n assignedAgentType,\n recommendedAgent,\n contextData,\n };\n\n await store.store(`edit:${editData.editId}:pre`, editData, {\n namespace: 'hooks:pre-edit',\n metadata: { hookType: 'pre-edit', file, agentType: assignedAgentType },\n });\n\n // Store agent recommendation if enabled\n if (autoAssignAgents && recommendedAgent) {\n await store.store(`agent-recommendation:${file}`, recommendedAgent, {\n namespace: 'agent-assignments',\n ttl: 3600, // 1 hour\n });\n }\n\n console.log(` 💾 Pre-edit state saved to .swarm/memory.db`);\n printSuccess(`✅ Pre-edit hook completed`);\n } catch (err) {\n printError(`Pre-edit hook failed: ${err.message}`);\n }\n}\n\nasync function preBashCommand(subArgs, flags) {\n const options = flags;\n const command = options.command || subArgs.slice(1).join(' ') || '';\n const workingDir = options.cwd || process.cwd();\n const validateSafety = options['validate-safety'] === true || options['validate-safety'] === 'true' || options.validate === true || options.validate === 'true' || false;\n const prepareResources = options['prepare-resources'] === true || options['prepare-resources'] === 'true' || false;\n\n console.log(`🔧 Executing pre-bash hook...`);\n console.log(`📜 Command: ${command}`);\n console.log(`📁 Working dir: ${workingDir}`);\n if (validateSafety) console.log(`🔒 Safety validation: ENABLED`);\n if (prepareResources) console.log(`🛠️ Resource preparation: ENABLED`);\n\n try {\n const store = await getMemoryStore();\n let safetyResult = 'skipped';\n\n if (validateSafety) {\n // Basic safety validation\n const dangerousCommands = [\n 'rm -rf /',\n 'rm -rf .',\n 'rm -rf *',\n 'format',\n 'fdisk',\n 'mkfs',\n 'curl * | bash',\n 'wget * | sh',\n 'eval',\n 'exec',\n 'chmod 777',\n ];\n\n const isDangerous = command && typeof command === 'string' && command.length > 0 \n ? dangerousCommands.some((dangerous) =>\n command.toLowerCase().includes(dangerous.toLowerCase()),\n )\n : false;\n\n safetyResult = isDangerous ? 'dangerous' : 'safe';\n\n if (isDangerous) {\n console.log(` ⚠️ Safety check: DANGEROUS COMMAND DETECTED`);\n console.log(` 🚫 Command blocked for safety`);\n printError(`Command blocked due to safety validation: ${command}`);\n return;\n }\n }\n\n if (prepareResources) {\n // Resource preparation - create working directory if needed\n const fs = await import('fs');\n const path = await import('path');\n\n if (!fs.existsSync(workingDir)) {\n fs.mkdirSync(workingDir, { recursive: true });\n console.log(` 📁 Created working directory: ${workingDir}`);\n }\n\n // Check available disk space\n try {\n const stats = fs.statSync(workingDir);\n console.log(` 💾 Working directory prepared`);\n } catch (err) {\n console.log(` ⚠️ Warning: Could not check working directory`);\n }\n }\n\n const bashData = {\n command,\n workingDir,\n timestamp: new Date().toISOString(),\n bashId: generateId('bash'),\n safety: safetyResult,\n validationEnabled: validateSafety,\n resourcesPrepped: prepareResources,\n };\n\n await store.store(`bash:${bashData.bashId}:pre`, bashData, {\n namespace: 'hooks:pre-bash',\n metadata: { hookType: 'pre-bash', command, safety: safetyResult },\n });\n\n console.log(` 💾 Command logged to .swarm/memory.db`);\n console.log(` 🔒 Safety check: ${safetyResult.toUpperCase()}`);\n printSuccess(`✅ Pre-bash hook completed`);\n } catch (err) {\n printError(`Pre-bash hook failed: ${err.message}`);\n }\n}\n\n// ===== POST-OPERATION HOOKS =====\n\nasync function postTaskCommand(subArgs, flags) {\n const options = flags;\n const taskId = options['task-id'] || options.taskId || generateId('task');\n const analyzePerformance = options['analyze-performance'] !== 'false';\n\n console.log(`🏁 Executing post-task hook...`);\n console.log(`🆔 Task ID: ${taskId}`);\n\n try {\n const store = await getMemoryStore();\n const taskData = await store.retrieve(`task:${taskId}`, {\n namespace: 'hooks:pre-task',\n });\n\n const completedData = {\n ...(taskData || {}),\n status: 'completed',\n completedAt: new Date().toISOString(),\n duration: taskData ? Date.now() - new Date(taskData.startedAt).getTime() : null,\n };\n\n await store.store(`task:${taskId}:completed`, completedData, {\n namespace: 'hooks:post-task',\n metadata: { hookType: 'post-task' },\n });\n\n if (analyzePerformance && completedData.duration) {\n const metrics = {\n taskId,\n duration: completedData.duration,\n durationHuman: `${(completedData.duration / 1000).toFixed(2)}s`,\n timestamp: new Date().toISOString(),\n };\n\n await store.store(`metrics:${taskId}`, metrics, {\n namespace: 'performance',\n });\n console.log(` 📊 Performance: ${metrics.durationHuman}`);\n }\n\n console.log(` 💾 Task completion saved to .swarm/memory.db`);\n printSuccess(`✅ Post-task hook completed`);\n } catch (err) {\n printError(`Post-task hook failed: ${err.message}`);\n }\n}\n\nasync function postEditCommand(subArgs, flags) {\n const options = flags;\n const file = options.file || 'unknown-file';\n let memoryKey = options['memory-key'] || options.memoryKey;\n \n // Handle case where memory-key is passed as a boolean flag without value\n if (memoryKey === true) {\n // Generate a default memory key based on the file path and timestamp\n const path = await import('path');\n const basename = path.basename(file);\n memoryKey = `edit:${basename}:${Date.now()}`;\n }\n \n const format = options.format || false;\n const updateMemory = options['update-memory'] || false;\n const trainNeural = options['train-neural'] || false;\n\n console.log(`📝 Executing post-edit hook...`);\n console.log(`📄 File: ${file}`);\n if (memoryKey) console.log(`💾 Memory key: ${memoryKey}`);\n if (format) console.log(`🎨 Auto-format: ENABLED`);\n if (updateMemory) console.log(`🧠 Memory update: ENABLED`);\n if (trainNeural) console.log(`🤖 Neural training: ENABLED`);\n\n try {\n const store = await getMemoryStore();\n const path = await import('path');\n const fs = await import('fs');\n\n // Auto-format file if requested\n let formatResult = null;\n if (format && fs.existsSync(file)) {\n const ext = path.extname(file).toLowerCase();\n const formatters = {\n '.js': 'prettier',\n '.ts': 'prettier',\n '.json': 'prettier',\n '.css': 'prettier',\n '.html': 'prettier',\n '.py': 'black',\n '.go': 'gofmt',\n '.rs': 'rustfmt',\n '.java': 'google-java-format',\n '.cpp': 'clang-format',\n '.c': 'clang-format',\n };\n\n const formatter = formatters[ext];\n if (formatter) {\n console.log(` 🎨 Auto-formatting with ${formatter}...`);\n formatResult = {\n formatter,\n extension: ext,\n attempted: true,\n timestamp: new Date().toISOString(),\n };\n } else {\n console.log(` ⚠️ No formatter available for ${ext}`);\n formatResult = {\n extension: ext,\n attempted: false,\n reason: 'No formatter available',\n };\n }\n }\n\n // Update memory with edit context\n let memoryUpdate = null;\n if (updateMemory) {\n const editContext = {\n file,\n editedAt: new Date().toISOString(),\n editId: generateId('edit'),\n formatted: formatResult?.attempted || false,\n fileSize: fs.existsSync(file) ? fs.statSync(file).size : 0,\n directory: path.dirname(file),\n basename: path.basename(file),\n };\n\n memoryUpdate = editContext;\n\n // Store in coordination namespace\n await store.store(`edit-context:${editContext.editId}`, editContext, {\n namespace: 'coordination',\n metadata: { type: 'edit-context', file },\n });\n\n console.log(` 🧠 Edit context stored in memory`);\n }\n\n // Train neural patterns if requested\n let neuralTraining = null;\n if (trainNeural) {\n // Simulate neural training with file patterns\n const ext = path.extname(file).toLowerCase();\n const basename = path.basename(file);\n const editTime = new Date().toISOString();\n\n const patterns = {\n fileType: ext,\n fileName: basename,\n editTime,\n confidence: Math.random() * 0.5 + 0.5, // 50-100% confidence\n patterns: [\n `${ext}_edit_pattern`,\n `${basename}_modification`,\n `edit_${Date.now()}_sequence`,\n ],\n };\n\n neuralTraining = patterns;\n\n await store.store(`neural-pattern:${generateId('pattern')}`, patterns, {\n namespace: 'neural-training',\n metadata: { type: 'edit-pattern', file, extension: ext },\n });\n\n console.log(\n ` 🤖 Neural patterns trained (${(patterns.confidence * 100).toFixed(1)}% confidence)`,\n );\n }\n\n const editData = {\n file,\n memoryKey,\n timestamp: new Date().toISOString(),\n editId: generateId('edit'),\n format,\n updateMemory,\n trainNeural,\n formatResult,\n memoryUpdate,\n neuralTraining,\n };\n\n await store.store(`edit:${editData.editId}:post`, editData, {\n namespace: 'hooks:post-edit',\n metadata: { hookType: 'post-edit', file, formatted: formatResult?.attempted || false },\n });\n\n if (memoryKey && typeof memoryKey === 'string') {\n await store.store(\n memoryKey,\n {\n file,\n editedAt: new Date().toISOString(),\n editId: editData.editId,\n enhanced: true,\n formatResult,\n memoryUpdate,\n neuralTraining,\n },\n { namespace: 'coordination' },\n );\n }\n\n const historyKey = `file-history:${file.replace(/\\//g, '_')}:${Date.now()}`;\n await store.store(\n historyKey,\n {\n file,\n editId: editData.editId,\n timestamp: new Date().toISOString(),\n enhanced: true,\n features: {\n format,\n updateMemory,\n trainNeural,\n },\n },\n { namespace: 'file-history' },\n );\n\n console.log(` 💾 Post-edit data saved to .swarm/memory.db`);\n printSuccess(`✅ Post-edit hook completed`);\n } catch (err) {\n printError(`Post-edit hook failed: ${err.message}`);\n }\n}\n\nasync function postBashCommand(subArgs, flags) {\n const options = flags;\n const command = options.command || subArgs.slice(1).join(' ');\n const exitCode = options['exit-code'] || '0';\n const output = options.output || '';\n const trackMetrics = options['track-metrics'] || false;\n const storeResults = options['store-results'] || false;\n const duration = options.duration || 0;\n\n console.log(`🔧 Executing post-bash hook...`);\n console.log(`📜 Command: ${command}`);\n console.log(`📊 Exit code: ${exitCode}`);\n if (trackMetrics) console.log(`📊 Metrics tracking: ENABLED`);\n if (storeResults) console.log(`💾 Results storage: ENABLED`);\n\n try {\n const store = await getMemoryStore();\n const startTime = Date.now();\n\n // Calculate performance metrics if enabled\n let metrics = null;\n if (trackMetrics) {\n const commandLength = command.length;\n const outputLength = output.length;\n const success = parseInt(exitCode) === 0;\n\n metrics = {\n commandLength,\n outputLength,\n success,\n duration: parseInt(duration) || 0,\n exitCode: parseInt(exitCode),\n timestamp: new Date().toISOString(),\n complexity: commandLength > 100 ? 'high' : commandLength > 50 ? 'medium' : 'low',\n };\n\n console.log(\n ` 📊 Command metrics: ${commandLength} chars, ${outputLength} output, ${success ? 'SUCCESS' : 'FAILED'}`,\n );\n }\n\n const bashData = {\n command,\n exitCode,\n output: storeResults ? output.substring(0, 5000) : output.substring(0, 1000), // Store more if requested\n timestamp: new Date().toISOString(),\n bashId: generateId('bash'),\n trackMetrics,\n storeResults,\n metrics,\n };\n\n await store.store(`bash:${bashData.bashId}:post`, bashData, {\n namespace: 'hooks:post-bash',\n metadata: { hookType: 'post-bash', command, exitCode, success: parseInt(exitCode) === 0 },\n });\n\n // Store detailed results if enabled\n if (storeResults) {\n await store.store(\n `command-results:${bashData.bashId}`,\n {\n command,\n exitCode,\n output,\n timestamp: new Date().toISOString(),\n fullOutput: true,\n },\n { namespace: 'command-results' },\n );\n\n console.log(` 💾 Full command results stored`);\n }\n\n // Store metrics if enabled\n if (trackMetrics && metrics) {\n await store.store(`command-metrics:${bashData.bashId}`, metrics, {\n namespace: 'performance-metrics',\n });\n\n // Update running metrics\n const existingMetrics = (await store.retrieve('command-metrics-summary', {\n namespace: 'performance-metrics',\n })) || { totalCommands: 0, successRate: 0, avgDuration: 0 };\n\n existingMetrics.totalCommands += 1;\n existingMetrics.successRate =\n (existingMetrics.successRate * (existingMetrics.totalCommands - 1) +\n (metrics.success ? 1 : 0)) /\n existingMetrics.totalCommands;\n existingMetrics.avgDuration =\n (existingMetrics.avgDuration * (existingMetrics.totalCommands - 1) + metrics.duration) /\n existingMetrics.totalCommands;\n existingMetrics.lastUpdated = new Date().toISOString();\n\n await store.store('command-metrics-summary', existingMetrics, {\n namespace: 'performance-metrics',\n });\n }\n\n // Update command history\n await store.store(\n `command-history:${Date.now()}`,\n {\n command,\n exitCode,\n timestamp: new Date().toISOString(),\n success: parseInt(exitCode) === 0,\n hasMetrics: trackMetrics,\n hasResults: storeResults,\n },\n { namespace: 'command-history' },\n );\n\n console.log(` 💾 Command execution logged to .swarm/memory.db`);\n printSuccess(`✅ Post-bash hook completed`);\n } catch (err) {\n printError(`Post-bash hook failed: ${err.message}`);\n }\n}\n\nasync function postSearchCommand(subArgs, flags) {\n const options = flags;\n const query = options.query || subArgs.slice(1).join(' ');\n const resultCount = options['result-count'] || '0';\n const searchType = options.type || 'general';\n\n console.log(`🔍 Executing post-search hook...`);\n console.log(`🔎 Query: ${query}`);\n console.log(`📊 Results: ${resultCount}`);\n\n try {\n const store = await getMemoryStore();\n const searchData = {\n query,\n resultCount: parseInt(resultCount),\n searchType,\n timestamp: new Date().toISOString(),\n searchId: generateId('search'),\n };\n\n await store.store(`search:${searchData.searchId}`, searchData, {\n namespace: 'hooks:post-search',\n metadata: { hookType: 'post-search', query },\n });\n\n // Cache search for future use\n await store.store(\n `search-cache:${query}`,\n {\n resultCount: searchData.resultCount,\n cachedAt: new Date().toISOString(),\n },\n { namespace: 'search-cache', ttl: 3600 },\n ); // 1 hour TTL\n\n console.log(` 💾 Search results cached to .swarm/memory.db`);\n printSuccess(`✅ Post-search hook completed`);\n } catch (err) {\n printError(`Post-search hook failed: ${err.message}`);\n }\n}\n\n// ===== MCP INTEGRATION HOOKS =====\n\nasync function mcpInitializedCommand(subArgs, flags) {\n const options = flags;\n const serverName = options.server || 'claude-flow';\n const sessionId = options['session-id'] || generateId('mcp-session');\n\n console.log(`🔌 Executing mcp-initialized hook...`);\n console.log(`💻 Server: ${serverName}`);\n console.log(`🆔 Session: ${sessionId}`);\n\n try {\n const store = await getMemoryStore();\n const mcpData = {\n serverName,\n sessionId,\n initializedAt: new Date().toISOString(),\n status: 'active',\n };\n\n await store.store(`mcp:${sessionId}`, mcpData, {\n namespace: 'hooks:mcp-initialized',\n metadata: { hookType: 'mcp-initialized', server: serverName },\n });\n\n console.log(` 💾 MCP session saved to .swarm/memory.db`);\n printSuccess(`✅ MCP initialized hook completed`);\n } catch (err) {\n printError(`MCP initialized hook failed: ${err.message}`);\n }\n}\n\nasync function agentSpawnedCommand(subArgs, flags) {\n const options = flags;\n const agentType = options.type || 'generic';\n const agentName = options.name || generateId('agent');\n const swarmId = options['swarm-id'] || 'default';\n\n console.log(`🤖 Executing agent-spawned hook...`);\n console.log(`📛 Agent: ${agentName}`);\n console.log(`🏷️ Type: ${agentType}`);\n\n try {\n const store = await getMemoryStore();\n const agentData = {\n agentName,\n agentType,\n swarmId,\n spawnedAt: new Date().toISOString(),\n status: 'active',\n };\n\n await store.store(`agent:${agentName}`, agentData, {\n namespace: 'hooks:agent-spawned',\n metadata: { hookType: 'agent-spawned', type: agentType },\n });\n\n // Update agent roster\n await store.store(\n `agent-roster:${Date.now()}`,\n {\n agentName,\n action: 'spawned',\n timestamp: new Date().toISOString(),\n },\n { namespace: 'agent-roster' },\n );\n\n console.log(` 💾 Agent registered to .swarm/memory.db`);\n printSuccess(`✅ Agent spawned hook completed`);\n } catch (err) {\n printError(`Agent spawned hook failed: ${err.message}`);\n }\n}\n\nasync function taskOrchestratedCommand(subArgs, flags) {\n const options = flags;\n const taskId = options['task-id'] || generateId('orchestrated-task');\n const strategy = options.strategy || 'balanced';\n const priority = options.priority || 'medium';\n\n console.log(`🎭 Executing task-orchestrated hook...`);\n console.log(`🆔 Task: ${taskId}`);\n console.log(`📊 Strategy: ${strategy}`);\n\n try {\n const store = await getMemoryStore();\n const orchestrationData = {\n taskId,\n strategy,\n priority,\n orchestratedAt: new Date().toISOString(),\n status: 'orchestrated',\n };\n\n await store.store(`orchestration:${taskId}`, orchestrationData, {\n namespace: 'hooks:task-orchestrated',\n metadata: { hookType: 'task-orchestrated', strategy },\n });\n\n console.log(` 💾 Orchestration saved to .swarm/memory.db`);\n printSuccess(`✅ Task orchestrated hook completed`);\n } catch (err) {\n printError(`Task orchestrated hook failed: ${err.message}`);\n }\n}\n\nasync function neuralTrainedCommand(subArgs, flags) {\n const options = flags;\n const modelName = options.model || 'default-neural';\n const accuracy = options.accuracy || '0.0';\n const patterns = options.patterns || '0';\n\n console.log(`🧠 Executing neural-trained hook...`);\n console.log(`🤖 Model: ${modelName}`);\n console.log(`📊 Accuracy: ${accuracy}%`);\n\n try {\n const store = await getMemoryStore();\n const trainingData = {\n modelName,\n accuracy: parseFloat(accuracy),\n patternsLearned: parseInt(patterns),\n trainedAt: new Date().toISOString(),\n };\n\n await store.store(`neural:${modelName}:${Date.now()}`, trainingData, {\n namespace: 'hooks:neural-trained',\n metadata: { hookType: 'neural-trained', model: modelName },\n });\n\n console.log(` 💾 Training results saved to .swarm/memory.db`);\n printSuccess(`✅ Neural trained hook completed`);\n } catch (err) {\n printError(`Neural trained hook failed: ${err.message}`);\n }\n}\n\n// ===== SESSION HOOKS =====\n\nasync function sessionEndCommand(subArgs, flags) {\n const options = flags;\n const generateSummary = options['generate-summary'] !== 'false';\n const persistState = options['persist-state'] !== 'false';\n const exportMetrics = options['export-metrics'] || false;\n\n console.log(`🔚 Executing session-end hook...`);\n if (generateSummary) console.log(`📊 Summary generation: ENABLED`);\n if (persistState) console.log(`💾 State persistence: ENABLED`);\n if (exportMetrics) console.log(`📈 Metrics export: ENABLED`);\n\n try {\n const store = await getMemoryStore();\n const tasks = await store.list({ namespace: 'task-index', limit: 1000 });\n const edits = await store.list({ namespace: 'file-history', limit: 1000 });\n const commands = await store.list({ namespace: 'command-history', limit: 1000 });\n const agents = await store.list({ namespace: 'agent-roster', limit: 1000 });\n\n // Calculate session metrics\n let metrics = null;\n if (exportMetrics) {\n const now = new Date();\n const sessionStart = Math.min(\n ...tasks.map((t) => new Date(t.value.timestamp || now).getTime()),\n ...edits.map((e) => new Date(e.value.timestamp || now).getTime()),\n ...commands.map((c) => new Date(c.value.timestamp || now).getTime()),\n );\n\n const duration = now.getTime() - sessionStart;\n const successfulCommands = commands.filter((c) => c.value.success !== false).length;\n const commandSuccessRate = commands.length > 0 ? successfulCommands / commands.length : 1;\n\n metrics = {\n sessionDuration: duration,\n sessionDurationHuman: `${Math.round(duration / 1000 / 60)} minutes`,\n totalTasks: tasks.length,\n totalEdits: edits.length,\n totalCommands: commands.length,\n uniqueAgents: agents.length,\n commandSuccessRate: Math.round(commandSuccessRate * 100),\n avgTasksPerMinute: Math.round((tasks.length / (duration / 1000 / 60)) * 100) / 100,\n avgEditsPerMinute: Math.round((edits.length / (duration / 1000 / 60)) * 100) / 100,\n timestamp: now.toISOString(),\n };\n }\n\n const sessionData = {\n endedAt: new Date().toISOString(),\n totalTasks: tasks.length,\n totalEdits: edits.length,\n totalCommands: commands.length,\n uniqueAgents: agents.length,\n sessionId: generateId('session'),\n generateSummary,\n persistState,\n exportMetrics,\n metrics,\n };\n\n await store.store(`session:${sessionData.sessionId}`, sessionData, {\n namespace: 'sessions',\n metadata: { hookType: 'session-end' },\n });\n\n // Persist detailed state if requested\n if (persistState) {\n const detailedState = {\n sessionId: sessionData.sessionId,\n tasks: tasks.slice(0, 100), // Limit to prevent memory issues\n edits: edits.slice(0, 100),\n commands: commands.slice(0, 100),\n agents: agents.slice(0, 50),\n persistedAt: new Date().toISOString(),\n fullState: true,\n };\n\n await store.store(`session-state:${sessionData.sessionId}`, detailedState, {\n namespace: 'session-states',\n metadata: { type: 'full-state', sessionId: sessionData.sessionId },\n });\n\n console.log(` 💾 Full session state persisted`);\n }\n\n // Export metrics if requested\n if (exportMetrics && metrics) {\n await store.store(`session-metrics:${sessionData.sessionId}`, metrics, {\n namespace: 'session-metrics',\n metadata: { type: 'performance-metrics', sessionId: sessionData.sessionId },\n });\n\n console.log(` 📈 Session metrics exported`);\n }\n\n if (generateSummary) {\n console.log(`\\n📊 SESSION SUMMARY:`);\n console.log(` 📋 Tasks: ${sessionData.totalTasks}`);\n console.log(` ✏️ Edits: ${sessionData.totalEdits}`);\n console.log(` 🔧 Commands: ${sessionData.totalCommands}`);\n console.log(` 🤖 Agents: ${sessionData.uniqueAgents}`);\n\n if (metrics) {\n console.log(` ⏱️ Duration: ${metrics.sessionDurationHuman}`);\n console.log(` 📈 Success Rate: ${metrics.commandSuccessRate}%`);\n console.log(` 🏃 Tasks/min: ${metrics.avgTasksPerMinute}`);\n console.log(` ✏️ Edits/min: ${metrics.avgEditsPerMinute}`);\n }\n }\n\n console.log(` 💾 Session saved to .swarm/memory.db`);\n\n if (memoryStore) {\n memoryStore.close();\n memoryStore = null;\n }\n\n printSuccess(`✅ Session-end hook completed`);\n } catch (err) {\n printError(`Session-end hook failed: ${err.message}`);\n }\n}\n\nasync function sessionRestoreCommand(subArgs, flags) {\n const options = flags;\n const sessionId = options['session-id'] || 'latest';\n\n console.log(`🔄 Executing session-restore hook...`);\n console.log(`🆔 Session: ${sessionId}`);\n\n try {\n const store = await getMemoryStore();\n\n // Find session to restore\n let sessionData;\n if (sessionId === 'latest') {\n const sessions = await store.list({ namespace: 'sessions', limit: 1 });\n sessionData = sessions[0]?.value;\n } else {\n sessionData = await store.retrieve(`session:${sessionId}`, { namespace: 'sessions' });\n }\n\n if (sessionData) {\n console.log(`\\n📊 RESTORED SESSION:`);\n console.log(` 🆔 ID: ${sessionData.sessionId || 'unknown'}`);\n console.log(` 📋 Tasks: ${sessionData.totalTasks || 0}`);\n console.log(` ✏️ Edits: ${sessionData.totalEdits || 0}`);\n console.log(` ⏰ Ended: ${sessionData.endedAt || 'unknown'}`);\n\n // Store restoration event\n await store.store(\n `session-restore:${Date.now()}`,\n {\n restoredSessionId: sessionData.sessionId || sessionId,\n restoredAt: new Date().toISOString(),\n },\n { namespace: 'session-events' },\n );\n\n console.log(` 💾 Session restored from .swarm/memory.db`);\n printSuccess(`✅ Session restore completed`);\n } else {\n printWarning(`No session found with ID: ${sessionId}`);\n }\n } catch (err) {\n printError(`Session restore hook failed: ${err.message}`);\n }\n}\n\nasync function notifyCommand(subArgs, flags) {\n const options = flags;\n const message = options.message || subArgs.slice(1).join(' ');\n const level = options.level || 'info';\n const swarmStatus = options['swarm-status'] || 'active';\n\n console.log(`📢 Executing notify hook...`);\n console.log(`💬 Message: ${message}`);\n console.log(`📊 Level: ${level}`);\n\n try {\n const store = await getMemoryStore();\n const notificationData = {\n message,\n level,\n swarmStatus,\n timestamp: new Date().toISOString(),\n notifyId: generateId('notify'),\n };\n\n await store.store(`notification:${notificationData.notifyId}`, notificationData, {\n namespace: 'hooks:notify',\n metadata: { hookType: 'notify', level },\n });\n\n // Display notification\n const icon = level === 'error' ? '❌' : level === 'warning' ? '⚠️' : '✅';\n console.log(`\\n${icon} NOTIFICATION:`);\n console.log(` ${message}`);\n console.log(` 🐝 Swarm: ${swarmStatus}`);\n\n console.log(`\\n 💾 Notification saved to .swarm/memory.db`);\n printSuccess(`✅ Notify hook completed`);\n } catch (err) {\n printError(`Notify hook failed: ${err.message}`);\n }\n}\n\n// ===== PRETOOLUSE MODIFICATION HOOKS (v2.0.10+) =====\n\nasync function modifyBashCommand(subArgs, flags) {\n // Read JSON from stdin with timeout to detect if data is piped\n let input = '';\n let hasInput = false;\n\n const timeout = setTimeout(() => {\n if (!hasInput) {\n console.log('Usage: echo \\'{\"tool_input\":{\"command\":\"your command\"}}\\' | claude-flow hooks modify-bash');\n console.log('\\nThis hook reads JSON from stdin and outputs modified JSON.');\n console.log('It is designed for use with Claude Code v2.0.10+ PreToolUse feature.');\n console.log('\\nExample:');\n console.log(' echo \\'{\"tool_input\":{\"command\":\"rm test.txt\"}}\\' | claude-flow hooks modify-bash');\n process.exit(0);\n }\n }, 100); // 100ms timeout\n\n for await (const chunk of process.stdin) {\n hasInput = true;\n clearTimeout(timeout);\n input += chunk;\n }\n\n if (!input.trim()) {\n return; // Silently exit if no input\n }\n\n const toolInput = JSON.parse(input);\n const command = toolInput.tool_input?.command || '';\n\n if (!command) {\n console.log(input); // Pass through if no command\n return;\n }\n\n let modifiedCommand = command;\n const notes = [];\n\n // 1. Safety: Add -i flag to rm commands\n if (/^rm\\s/.test(command) && !/-[iI]/.test(command)) {\n modifiedCommand = command.replace(/^rm /, 'rm -i ');\n notes.push('[Safety: Added -i flag for interactive confirmation]');\n }\n\n // 2. Aliases\n if (/^ll(\\s|$)/.test(command)) {\n modifiedCommand = command.replace(/^ll/, 'ls -lah');\n notes.push('[Alias: ll → ls -lah]');\n } else if (/^la(\\s|$)/.test(command)) {\n modifiedCommand = command.replace(/^la/, 'ls -la');\n notes.push('[Alias: la → ls -la]');\n }\n\n // 3. Path correction: Redirect test files to /tmp\n if (/>\\s*test.*\\.(txt|log|tmp|json|md)/.test(command) && !/\\/tmp\\//.test(command)) {\n modifiedCommand = command.replace(/>\\s*(test[^/]*\\.(txt|log|tmp|json|md))/, '> /tmp/$1');\n notes.push('[Path: Redirected test file to /tmp/]');\n }\n\n // 4. Secret detection\n if (/(password|secret|token|api[-_]?key|auth)/i.test(command) && !/#\\s*SECRETS_OK/.test(command)) {\n notes.push('[Security: Command contains sensitive keywords. Add \"# SECRETS_OK\" to bypass]');\n }\n\n // Output modified JSON\n const output = {\n ...toolInput,\n tool_input: {\n ...toolInput.tool_input,\n command: modifiedCommand,\n },\n };\n\n if (notes.length > 0) {\n output.modification_notes = notes.join(' ');\n }\n\n console.log(JSON.stringify(output, null, 2));\n}\n\nasync function modifyFileCommand(subArgs, flags) {\n // Read JSON from stdin with timeout to detect if data is piped\n let input = '';\n let hasInput = false;\n\n const timeout = setTimeout(() => {\n if (!hasInput) {\n console.log('Usage: echo \\'{\"tool_input\":{\"file_path\":\"your/file.js\"}}\\' | claude-flow hooks modify-file');\n console.log('\\nThis hook reads JSON from stdin and outputs modified JSON.');\n console.log('It is designed for use with Claude Code v2.0.10+ PreToolUse feature.');\n console.log('\\nExample:');\n console.log(' echo \\'{\"tool_input\":{\"file_path\":\"test.js\"}}\\' | claude-flow hooks modify-file');\n process.exit(0);\n }\n }, 100); // 100ms timeout\n\n for await (const chunk of process.stdin) {\n hasInput = true;\n clearTimeout(timeout);\n input += chunk;\n }\n\n if (!input.trim()) {\n return; // Silently exit if no input\n }\n\n const toolInput = JSON.parse(input);\n const filePath = toolInput.tool_input?.file_path || toolInput.tool_input?.path || '';\n\n if (!filePath) {\n console.log(input); // Pass through if no file path\n return;\n }\n\n let modifiedPath = filePath;\n let shouldModify = false;\n const notes = [];\n\n // 1. Root folder protection\n const isRootFile = /^[^/]*\\.(js|ts|jsx|tsx|py|java|go|rs|cpp|c|h)$/.test(filePath) ||\n /^test.*\\.(txt|log|tmp|json|md)$/.test(filePath) ||\n /^(temp|tmp|working)/.test(filePath);\n\n if (isRootFile) {\n if (/test.*\\.(test|spec)\\.|\\.test\\.|\\.spec\\./.test(filePath)) {\n modifiedPath = `tests/${filePath}`;\n shouldModify = true;\n notes.push('[Organization: Moved test file to /tests/]');\n } else if (/test.*\\.md|temp.*\\.md|working.*\\.md|scratch.*\\.md/.test(filePath)) {\n modifiedPath = `docs/working/${filePath}`;\n shouldModify = true;\n notes.push('[Organization: Moved working document to /docs/working/]');\n } else if (/\\.(js|ts|jsx|tsx|py)$/.test(filePath)) {\n modifiedPath = `src/${filePath}`;\n shouldModify = true;\n notes.push('[Organization: Moved source file to /src/]');\n } else if (/^(temp|tmp|scratch)/.test(filePath)) {\n modifiedPath = `/tmp/${filePath}`;\n shouldModify = true;\n notes.push('[Organization: Redirected temporary file to /tmp/]');\n }\n }\n\n // 2. Format hints\n if (/\\.(ts|tsx|js|jsx)$/.test(modifiedPath)) {\n notes.push('[Tip: Auto-format with Prettier/ESLint recommended]');\n } else if (/\\.py$/.test(modifiedPath)) {\n notes.push('[Tip: Auto-format with Black/autopep8 recommended]');\n }\n\n // Output modified JSON\n const output = {\n ...toolInput,\n tool_input: {\n ...toolInput.tool_input,\n },\n };\n\n if (shouldModify) {\n if (toolInput.tool_input.file_path) {\n output.tool_input.file_path = modifiedPath;\n } else {\n output.tool_input.path = modifiedPath;\n }\n }\n\n if (notes.length > 0) {\n output.modification_notes = notes.join(' ');\n }\n\n console.log(JSON.stringify(output, null, 2));\n}\n\nasync function modifyGitCommitCommand(subArgs, flags) {\n // Read JSON from stdin with timeout to detect if data is piped\n let input = '';\n let hasInput = false;\n\n const timeout = setTimeout(() => {\n if (!hasInput) {\n console.log('Usage: echo \\'{\"tool_input\":{\"command\":\"git commit -m \\\\\"message\\\\\"\"}}\\' | claude-flow hooks modify-git-commit');\n console.log('\\nThis hook reads JSON from stdin and outputs modified JSON.');\n console.log('It is designed for use with Claude Code v2.0.10+ PreToolUse feature.');\n console.log('\\nExample:');\n console.log(' echo \\'{\"tool_input\":{\"command\":\"git commit -m \\\\\"fix bug\\\\\"\"}}\\' | claude-flow hooks modify-git-commit');\n process.exit(0);\n }\n }, 100); // 100ms timeout\n\n for await (const chunk of process.stdin) {\n hasInput = true;\n clearTimeout(timeout);\n input += chunk;\n }\n\n if (!input.trim()) {\n return; // Silently exit if no input\n }\n\n const toolInput = JSON.parse(input);\n const command = toolInput.tool_input?.command || '';\n\n if (!command || !/git commit/.test(command)) {\n console.log(input); // Pass through if not git commit\n return;\n }\n\n // Extract commit message\n const msgMatch = command.match(/-m\\s+[\"']([^\"']+)[\"']/) || command.match(/-m\\s+(\\S+)/);\n const commitMsg = msgMatch ? msgMatch[1] : '';\n\n if (!commitMsg || /^\\[(feat|fix|docs|style|refactor|test|chore|perf)\\]/.test(commitMsg)) {\n console.log(input); // Already formatted or no message\n return;\n }\n\n const notes = [];\n\n // Get current branch\n let branch = 'main';\n let ticket = '';\n try {\n const { execSync } = await import('child_process');\n branch = execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf8' }).trim();\n\n // Extract JIRA ticket\n const ticketMatch = branch.match(/[A-Z]+-[0-9]+/);\n if (ticketMatch) {\n ticket = ticketMatch[0];\n }\n } catch {\n // Git not available, continue\n }\n\n // Detect conventional commit type\n let type = 'chore';\n if (/^(add|implement|create|new)/i.test(commitMsg)) type = 'feat';\n else if (/^(fix|resolve|patch|correct)/i.test(commitMsg)) type = 'fix';\n else if (/^(update|modify|change|improve)/i.test(commitMsg)) type = 'refactor';\n else if (/^(doc|documentation|readme)/i.test(commitMsg)) type = 'docs';\n else if (/^(test|testing|spec)/i.test(commitMsg)) type = 'test';\n else if (/^(style|format|lint)/i.test(commitMsg)) type = 'style';\n else if (/^(perf|optimize|speed)/i.test(commitMsg)) type = 'perf';\n\n // Format message\n let formattedMsg = ticket\n ? `[${type}] ${commitMsg} (${ticket})`\n : `[${type}] ${commitMsg}`;\n\n // Add co-author\n if (!/Co-Authored-By/.test(command)) {\n formattedMsg += `\\n\\n🤖 Generated with Claude Flow\\nCo-Authored-By: claude-flow <[email protected]>`;\n }\n\n // Replace message in command\n const modifiedCommand = command.replace(\n /-m\\s+[\"'][^\"']+[\"']|-m\\s+\\S+/,\n `-m \"$(cat <<'EOF'\\n${formattedMsg}\\nEOF\\n)\"`\n );\n\n notes.push(`[Auto-formatted: ${type} type${ticket ? ` + ${ticket}` : ''}]`);\n\n // Output modified JSON\n const output = {\n ...toolInput,\n tool_input: {\n ...toolInput.tool_input,\n command: modifiedCommand,\n },\n modification_notes: notes.join(' '),\n };\n\n console.log(JSON.stringify(output, null, 2));\n}\n\nfunction showHooksHelp() {\n console.log('Claude Flow Hooks (with .swarm/memory.db persistence):\\n');\n\n console.log('Pre-Operation Hooks:');\n console.log(' pre-task Execute before starting a task');\n console.log(' pre-edit Validate before file modifications');\n console.log(' --auto-assign-agents Auto-assign agents based on file type');\n console.log(' --load-context Load file context');\n console.log(' pre-bash Check command safety (alias: pre-command)');\n console.log(' pre-command Same as pre-bash');\n console.log(' --validate-safety Enable safety validation');\n console.log(' --prepare-resources Prepare execution resources');\n\n console.log('\\nPost-Operation Hooks:');\n console.log(' post-task Execute after completing a task');\n console.log(' post-edit Auto-format and log edits');\n console.log(' --format Auto-format code');\n console.log(' --update-memory Update agent memory');\n console.log(' --train-neural Train neural patterns');\n console.log(' post-bash Log command execution (alias: post-command)');\n console.log(' post-command Same as post-bash');\n console.log(' --track-metrics Track performance metrics');\n console.log(' --store-results Store detailed results');\n console.log(' post-search Cache search results');\n\n console.log('\\nMCP Integration Hooks:');\n console.log(' mcp-initialized Persist MCP configuration');\n console.log(' agent-spawned Update agent roster');\n console.log(' task-orchestrated Monitor task progress');\n console.log(' neural-trained Save pattern improvements');\n\n console.log('\\nSession Hooks:');\n console.log(' session-end Generate summary and save state');\n console.log(' --generate-summary Generate session summary');\n console.log(' --persist-state Persist session state');\n console.log(' --export-metrics Export performance metrics');\n console.log(' session-restore Load previous session state');\n console.log(' notify Custom notifications');\n\n console.log('\\n===== NEW: PreToolUse Modification Hooks (v2.0.10+) =====');\n console.log(' modify-bash Modify Bash tool inputs (reads/writes JSON via stdin/stdout)');\n console.log(' • Safety: Adds -i flag to rm commands');\n console.log(' • Aliases: ll → ls -lah, la → ls -la');\n console.log(' • Path correction: Redirects test files to /tmp');\n console.log(' • Secret detection: Warns about sensitive keywords');\n console.log('');\n console.log(' modify-file Modify Write/Edit tool inputs (reads/writes JSON via stdin/stdout)');\n console.log(' • Root folder protection: Moves files to appropriate directories');\n console.log(' • Organization: Tests → /tests/, Sources → /src/, Docs → /docs/');\n console.log(' • Format hints: Suggests Prettier, Black, etc.');\n console.log('');\n console.log(' modify-git-commit Modify git commit messages (reads/writes JSON via stdin/stdout)');\n console.log(' • Conventional commits: Auto-adds [feat], [fix], [docs], etc.');\n console.log(' • Ticket extraction: Extracts JIRA tickets from branch names');\n console.log(' • Co-author: Adds Claude Flow co-author footer');\n\n console.log('\\nExamples:');\n console.log(' hooks pre-command --command \"npm test\" --validate-safety true');\n console.log(' hooks pre-edit --file \"src/app.js\" --auto-assign-agents true');\n console.log(' hooks post-command --command \"build\" --track-metrics true');\n console.log(' hooks post-edit --file \"src/app.js\" --format true --train-neural true');\n console.log(' hooks session-end --generate-summary true --export-metrics true');\n console.log(' hooks agent-spawned --name \"CodeReviewer\" --type \"reviewer\"');\n console.log(' hooks notify --message \"Build completed\" --level \"success\"');\n console.log('');\n console.log(' # New modification hooks (stdin/stdout JSON):');\n console.log(' echo \\'{\"tool_input\":{\"command\":\"rm test.txt\"}}\\' | hooks modify-bash');\n console.log(' echo \\'{\"tool_input\":{\"file_path\":\"test.js\"}}\\' | hooks modify-file');\n console.log(' echo \\'{\"tool_input\":{\"command\":\"git commit -m \\\\\"fix bug\\\\\"\"}}\\' | hooks modify-git-commit');\n\n console.log('\\nCompatibility:');\n console.log(' • pre-command and pre-bash are aliases');\n console.log(' • post-command and post-bash are aliases');\n console.log(' • Both --dash-case and camelCase parameters supported');\n console.log(' • All parameters from settings.json template supported');\n console.log(' • New modification hooks work with Claude Code v2.0.10+ PreToolUse feature');\n}\n\nexport default hooksAction;\n"],"names":["printSuccess","printError","printWarning","execRuvSwarmHook","checkRuvSwarmAvailable","SqliteMemoryStore","InMemoryStore","memoryStore","storeInitFailed","getMemoryStore","initialize","err","isNativeModuleError","message","includes","generateId","prefix","Date","now","Math","random","toString","substr","hooksAction","subArgs","flags","subcommand","options","help","h","showHooksHelp","preTaskCommand","preEditCommand","preBashCommand","postTaskCommand","postEditCommand","postBashCommand","postSearchCommand","mcpInitializedCommand","agentSpawnedCommand","taskOrchestratedCommand","neuralTrainedCommand","sessionEndCommand","sessionRestoreCommand","notifyCommand","modifyBashCommand","modifyFileCommand","modifyGitCommitCommand","description","taskId","agentId","autoSpawnAgents","console","log","store","taskData","status","startedAt","toISOString","namespace","metadata","hookType","timestamp","checkPromise","timeoutPromise","Promise","_","reject","setTimeout","Error","isAvailable","race","hookResult","success","output","close","process","exit","file","operation","autoAssignAgents","loadContext","assignedAgentType","recommendedAgent","path","ext","extname","toLowerCase","agentMapping","type","extension","recommended","contextData","fs","existsSync","stats","statSync","dirname","basename","fileExists","size","modified","mtime","directory","filename","isDirectory","willCreate","error","editData","editId","agentType","ttl","command","slice","join","workingDir","cwd","validateSafety","validate","prepareResources","safetyResult","dangerousCommands","isDangerous","length","some","dangerous","mkdirSync","recursive","bashData","bashId","safety","validationEnabled","resourcesPrepped","toUpperCase","analyzePerformance","retrieve","completedData","completedAt","duration","getTime","metrics","durationHuman","toFixed","memoryKey","format","updateMemory","trainNeural","formatResult","formatters","formatter","attempted","reason","memoryUpdate","editContext","editedAt","formatted","fileSize","neuralTraining","editTime","patterns","fileType","fileName","confidence","enhanced","historyKey","replace","features","exitCode","trackMetrics","storeResults","startTime","commandLength","outputLength","parseInt","complexity","substring","fullOutput","existingMetrics","totalCommands","successRate","avgDuration","lastUpdated","hasMetrics","hasResults","query","resultCount","searchType","searchData","searchId","cachedAt","serverName","server","sessionId","mcpData","initializedAt","agentName","name","swarmId","agentData","spawnedAt","action","strategy","priority","orchestrationData","orchestratedAt","modelName","model","accuracy","trainingData","parseFloat","patternsLearned","trainedAt","generateSummary","persistState","exportMetrics","tasks","list","limit","edits","commands","agents","sessionStart","min","map","t","value","e","c","successfulCommands","filter","commandSuccessRate","sessionDuration","sessionDurationHuman","round","totalTasks","totalEdits","uniqueAgents","avgTasksPerMinute","avgEditsPerMinute","sessionData","endedAt","detailedState","persistedAt","fullState","sessions","restoredSessionId","restoredAt","level","swarmStatus","notificationData","notifyId","icon","input","hasInput","timeout","chunk","stdin","clearTimeout","trim","toolInput","JSON","parse","tool_input","modifiedCommand","notes","test","push","modification_notes","stringify","filePath","file_path","modifiedPath","shouldModify","isRootFile","msgMatch","match","commitMsg","branch","ticket","execSync","encoding","ticketMatch","formattedMsg"],"mappings":"AAAA,SACEA,YAAY,EACZC,UAAU,EACVC,YAAY,EACZC,gBAAgB,EAChBC,sBAAsB,QACjB,cAAc;AACrB,SAASC,iBAAiB,QAAQ,+BAA+B;AACjE,SAASC,aAAa,QAAQ,kCAAkC;AAGhE,IA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;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,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IAEZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;AACd;AAEA,eAAe9B,YAAY"}
\ No newline at end of file
diff --git a/dist-cjs/src/core/DatabaseManager.js b/dist-cjs/src/core/DatabaseManager.js
index 49700ee53e..d2d202c25c 100644
--- a/dist-cjs/src/core/DatabaseManager.js
+++ b/dist-cjs/src/core/DatabaseManager.js
@@ -1,5 +1,15 @@
import * as fs from 'fs-extra';
import * as path from 'path';
+import { isNativeModuleVersionError, getNativeModuleRecoveryMessage } from '../utils/error-recovery.js';
+export class NativeModuleError extends Error {
+ originalError;
+ isNativeModuleError = true;
+ constructor(message, originalError){
+ super(message);
+ this.name = 'NativeModuleError';
+ this.originalError = originalError;
+ }
+}
export class DatabaseManager {
provider;
dbType;
@@ -21,11 +31,14 @@ export class DatabaseManager {
return new SQLiteProvider(this.dbPath);
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
- if (errorMsg.includes('ENOTEMPTY') || errorMsg.includes('better-sqlite3')) {
+ if (error instanceof NativeModuleError || isNativeModuleVersionError(error)) {
+ console.warn('\n' + (error instanceof NativeModuleError ? error.message : getNativeModuleRecoveryMessage(error)));
+ console.warn(' Falling back to JSON storage (no data loss, just slower).\n');
+ } else if (errorMsg.includes('ENOTEMPTY') || errorMsg.includes('better-sqlite3')) {
console.warn('⚠️ SQLite initialization failed due to npm cache error');
console.warn(' Will attempt automatic recovery during initialize()');
} else {
- console.warn('SQLite not available, falling back to JSON storage:', error);
+ console.warn('SQLite not available, falling back to JSON storage:', errorMsg);
}
this.provider = new JSONProvider(this.dbPath.replace('.sqlite', '.json'));
this.dbType = 'json';
@@ -128,6 +141,10 @@ let SQLiteProvider = class SQLiteProvider {
const Database = require('better-sqlite3');
this.db = new Database(dbPath);
} catch (error) {
+ if (isNativeModuleVersionError(error)) {
+ const recoveryMsg = getNativeModuleRecoveryMessage(error);
+ throw new NativeModuleError(recoveryMsg, error);
+ }
throw new Error('better-sqlite3 not available. Install with: npm install better-sqlite3');
}
}
diff --git a/dist-cjs/src/core/DatabaseManager.js.map b/dist-cjs/src/core/DatabaseManager.js.map
index 08d45b54fa..a7eacc20ff 100644
--- a/dist-cjs/src/core/DatabaseManager.js.map
+++ b/dist-cjs/src/core/DatabaseManager.js.map
@@ -1 +1 @@
-{"version":3,"sources":["../../../src/core/DatabaseManager.ts"],"sourcesContent":["/**\n * DatabaseManager - Manages SQLite and JSON fallback storage\n * Provides a unified interface for persistent data storage with automatic fallback\n */\n\nimport * as fs from 'fs-extra';\nimport * as path from 'path';\nimport { IDatabaseProvider } from '../types/interfaces.js';\n\nexport class DatabaseManager implements IDatabaseProvider {\n private provider: IDatabaseProvider;\n private dbType: 'sqlite' | 'json';\n private dbPath: string;\n private initialized: boolean = false;\n private retryCount: number = 0;\n private maxRetries: number = 3;\n\n constructor(dbType: 'sqlite' | 'json' = 'sqlite', dbPath?: string) {\n this.dbType = dbType;\n this.dbPath = dbPath || this.getDefaultPath();\n\n // Try SQLite first, fallback to JSON if needed\n if (this.dbType === 'sqlite') {\n this.provider = this.initializeSQLiteWithRecovery();\n } else {\n this.provider = new JSONProvider(this.dbPath);\n }\n }\n\n /**\n * Initialize SQLite with automatic error recovery\n */\n private initializeSQLiteWithRecovery(): IDatabaseProvider {\n try {\n return new SQLiteProvider(this.dbPath);\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error);\n\n // Check if it's an npm cache error\n if (errorMsg.includes('ENOTEMPTY') || errorMsg.includes('better-sqlite3')) {\n console.warn('⚠️ SQLite initialization failed due to npm cache error');\n console.warn(' Will attempt automatic recovery during initialize()');\n } else {\n console.warn('SQLite not available, falling back to JSON storage:', error);\n }\n\n // Fallback to JSON for now\n this.provider = new JSONProvider(this.dbPath.replace('.sqlite', '.json'));\n this.dbType = 'json';\n return this.provider;\n }\n }\n\n private getDefaultPath(): string {\n const baseDir = path.join(process.cwd(), '.claude-flow');\n return this.dbType === 'sqlite'\n ? path.join(baseDir, 'database.sqlite')\n : path.join(baseDir, 'database.json');\n }\n\n async initialize(): Promise<void> {\n await fs.ensureDir(path.dirname(this.dbPath));\n\n try {\n await this.provider.initialize();\n this.initialized = true;\n } catch (error) {\n // If JSON provider failed, just propagate the error\n if (this.dbType === 'json') {\n throw error;\n }\n\n // For SQLite errors, attempt recovery\n const errorMsg = error instanceof Error ? error.message : String(error);\n if (this.retryCount < this.maxRetries) {\n console.warn(`⚠️ Database initialization failed (attempt ${this.retryCount + 1}/${this.maxRetries})`);\n console.warn(` Error: ${errorMsg}`);\n\n // Attempt to recover by switching to JSON\n console.log('🔄 Switching to JSON storage as fallback...');\n this.provider = new JSONProvider(this.dbPath.replace('.sqlite', '.json'));\n this.dbType = 'json';\n this.retryCount++;\n\n // Retry initialization with JSON provider\n await this.initialize();\n } else {\n throw error;\n }\n }\n }\n\n async store(key: string, value: any, namespace: string = 'default'): Promise<void> {\n if (!this.initialized) {\n await this.initialize();\n }\n return this.provider.store(key, value, namespace);\n }\n\n async retrieve(key: string, namespace: string = 'default'): Promise<any> {\n if (!this.initialized) {\n await this.initialize();\n }\n return this.provider.retrieve(key, namespace);\n }\n\n async delete(key: string, namespace: string = 'default'): Promise<boolean> {\n if (!this.initialized) {\n await this.initialize();\n }\n return this.provider.delete(key, namespace);\n }\n\n async list(namespace: string = 'default'): Promise<string[]> {\n if (!this.initialized) {\n await this.initialize();\n }\n return this.provider.list(namespace);\n }\n\n async close(): Promise<void> {\n if (this.provider) {\n await this.provider.close();\n }\n this.initialized = false;\n }\n\n getDatabaseType(): 'sqlite' | 'json' {\n return this.dbType;\n }\n\n getDatabasePath(): string {\n return this.dbPath;\n }\n\n isInitialized(): boolean {\n return this.initialized;\n }\n\n // Specialized methods for common operations\n async storeJSON(key: string, data: object, namespace?: string): Promise<void> {\n await this.store(key, JSON.stringify(data), namespace);\n }\n\n async retrieveJSON(key: string, namespace?: string): Promise<object | null> {\n const data = await this.retrieve(key, namespace);\n if (!data) return null;\n try {\n return typeof data === 'string' ? JSON.parse(data) : data;\n } catch {\n return null;\n }\n }\n\n async exists(key: string, namespace?: string): Promise<boolean> {\n const data = await this.retrieve(key, namespace);\n return data !== null && data !== undefined;\n }\n\n async clear(namespace?: string): Promise<void> {\n const keys = await this.list(namespace);\n await Promise.all(keys.map(key => this.delete(key, namespace)));\n }\n}\n\n/**\n * SQLite implementation\n */\nclass SQLiteProvider implements IDatabaseProvider {\n private db: any;\n private dbPath: string;\n\n constructor(dbPath: string) {\n this.dbPath = dbPath;\n // Dynamic import to handle optional dependency\n try {\n const Database = require('better-sqlite3');\n this.db = new Database(dbPath);\n } catch (error) {\n throw new Error('better-sqlite3 not available. Install with: npm install better-sqlite3');\n }\n }\n\n async initialize(): Promise<void> {\n // Create tables\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS storage (\n namespace TEXT NOT NULL,\n key TEXT NOT NULL,\n value TEXT NOT NULL,\n created_at INTEGER DEFAULT (strftime('%s', 'now')),\n updated_at INTEGER DEFAULT (strftime('%s', 'now')),\n PRIMARY KEY (namespace, key)\n )\n `);\n\n this.db.exec(`\n CREATE INDEX IF NOT EXISTS idx_storage_namespace ON storage(namespace);\n CREATE INDEX IF NOT EXISTS idx_storage_created_at ON storage(created_at);\n `);\n }\n\n async store(key: string, value: any, namespace: string = 'default'): Promise<void> {\n const stmt = this.db.prepare(`\n INSERT OR REPLACE INTO storage (namespace, key, value, updated_at)\n VALUES (?, ?, ?, strftime('%s', 'now'))\n `);\n\n const serializedValue = typeof value === 'string' ? value : JSON.stringify(value);\n stmt.run(namespace, key, serializedValue);\n }\n\n async retrieve(key: string, namespace: string = 'default'): Promise<any> {\n const stmt = this.db.prepare('SELECT value FROM storage WHERE namespace = ? AND key = ?');\n const row = stmt.get(namespace, key);\n\n if (!row) return null;\n\n try {\n return JSON.parse(row.value);\n } catch {\n return row.value;\n }\n }\n\n async delete(key: string, namespace: string = 'default'): Promise<boolean> {\n const stmt = this.db.prepare('DELETE FROM storage WHERE namespace = ? AND key = ?');\n const result = stmt.run(namespace, key);\n return result.changes > 0;\n }\n\n async list(namespace: string = 'default'): Promise<string[]> {\n const stmt = this.db.prepare('SELECT key FROM storage WHERE namespace = ? ORDER BY key');\n const rows = stmt.all(namespace);\n return rows.map((row: any) => row.key);\n }\n\n async close(): Promise<void> {\n if (this.db) {\n this.db.close();\n }\n }\n}\n\n/**\n * JSON file-based implementation\n */\nclass JSONProvider implements IDatabaseProvider {\n private data: Record<string, Record<string, any>> = {};\n private dbPath: string;\n\n constructor(dbPath: string) {\n this.dbPath = dbPath;\n }\n\n async initialize(): Promise<void> {\n try {\n if (await fs.pathExists(this.dbPath)) {\n const content = await fs.readJSON(this.dbPath);\n this.data = content || {};\n }\n } catch (error) {\n console.warn('Failed to load JSON database, starting fresh:', error);\n this.data = {};\n }\n }\n\n async store(key: string, value: any, namespace: string = 'default'): Promise<void> {\n if (!this.data[namespace]) {\n this.data[namespace] = {};\n }\n\n this.data[namespace][key] = value;\n await this.persist();\n }\n\n async retrieve(key: string, namespace: string = 'default'): Promise<any> {\n if (!this.data[namespace]) {\n return null;\n }\n return this.data[namespace][key] || null;\n }\n\n async delete(key: string, namespace: string = 'default'): Promise<boolean> {\n if (!this.data[namespace] || !(key in this.data[namespace])) {\n return false;\n }\n\n delete this.data[namespace][key];\n await this.persist();\n return true;\n }\n\n async list(namespace: string = 'default'): Promise<string[]> {\n if (!this.data[namespace]) {\n return [];\n }\n return Object.keys(this.data[namespace]).sort();\n }\n\n async close(): Promise<void> {\n await this.persist();\n }\n\n private async persist(): Promise<void> {\n try {\n await fs.ensureDir(path.dirname(this.dbPath));\n await fs.writeJSON(this.dbPath, this.data, { spaces: 2 });\n } catch (error) {\n console.error('Failed to persist JSON database:', error);\n }\n }\n}"],"names":["fs","path","DatabaseManager","provider","dbType","dbPath","initialized","retryCount","maxRetries","getDefaultPath","initializeSQLiteWithRecovery","JSONProvider","SQLiteProvider","error","errorMsg","Error","message","String","includes","console","warn","replace","baseDir","join","process","cwd","initialize","ensureDir","dirname","log","store","key","value","namespace","retrieve","delete","list","close","getDatabaseType","getDatabasePath","isInitialized","storeJSON","data","JSON","stringify","retrieveJSON","parse","exists","undefined","clear","keys","Promise","all","map","db","Database","require","exec","stmt","prepare","serializedValue","run","row","get","result","changes","rows","pathExists","content","readJSON","persist","Object","sort","writeJSON","spaces"],"mappings":"AAKA,YAAYA,QAAQ,WAAW;AAC/B,YAAYC,UAAU,OAAO;AAG7B,OAAO,MAAMC;IACHC,SAA4B;IAC5BC,OAA0B;IAC1BC,OAAe;IACfC,cAAuB,MAAM;IAC7BC,aAAqB,EAAE;IACvBC,aAAqB,EAAE;IAE/B,YAAYJ,SAA4B,QAAQ,EAAEC,MAAe,CAAE;QACjE,IAAI,CAACD,MAAM,GAAGA;QACd,IAAI,CAACC,MAAM,GAAGA,UAAU,IAAI,CAACI,cAAc;QAG3C,IAAI,IAAI,CAACL,MAAM,KAAK,UAAU;YAC5B,IAAI,CAACD,QAAQ,GAAG,IAAI,CAACO,4BAA4B;QACnD,OAAO;YACL,IAAI,CAACP,QAAQ,GAAG,IAAIQ,aAAa,IAAI,CAACN,MAAM;QAC9C;IACF;IAKQK,+BAAkD;QACxD,IAAI;YACF,OAAO,IAAIE,eAAe,IAAI,CAACP,MAAM;QACvC,EAAE,OAAOQ,OAAO;YACd,MAAMC,WAAWD,iBAAiBE,QAAQF,MAAMG,OAAO,GAAGC,OAAOJ;YA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U,EAAEuC,IAAI;IAC/C;IAEA,MAAMnC,QAAuB;QAC3B,MAAM,IAAI,CAACiC,OAAO;IACpB;IAEA,MAAcA,UAAyB;QACrC,IAAI;YACF,MAAMtE,GAAG2B,SAAS,CAAC1B,KAAK2B,OAAO,CAAC,IAAI,CAACvB,MAAM;YAC3C,MAAML,GAAGyE,SAAS,CAAC,IAAI,CAACpE,MAAM,EAAE,IAAI,CAACqC,IAAI,EAAE;gBAAEgC,QAAQ;YAAE;QACzD,EAAE,OAAO7D,OAAO;YACdM,QAAQN,KAAK,CAAC,oCAAoCA;QACpD;IACF;AACF"}
\ No newline at end of file
+{"version":3,"sources":["../../../src/core/DatabaseManager.ts"],"sourcesContent":["/**\n * DatabaseManager - Manages SQLite and JSON fallback storage\n * Provides a unified interface for persistent data storage with automatic fallback\n */\n\nimport * as fs from 'fs-extra';\nimport * as path from 'path';\nimport { IDatabaseProvider } from '../types/interfaces.js';\nimport { isNativeModuleVersionError, getNativeModuleRecoveryMessage } from '../utils/error-recovery.js';\n\n/**\n * Custom error class for native module issues\n */\nexport class NativeModuleError extends Error {\n public readonly originalError: Error;\n public readonly isNativeModuleError = true;\n\n constructor(message: string, originalError: Error) {\n super(message);\n this.name = 'NativeModuleError';\n this.originalError = originalError;\n }\n}\n\nexport class DatabaseManager implements IDatabaseProvider {\n private provider: IDatabaseProvider;\n private dbType: 'sqlite' | 'json';\n private dbPath: string;\n private initialized: boolean = false;\n private retryCount: number = 0;\n private maxRetries: number = 3;\n\n constructor(dbType: 'sqlite' | 'json' = 'sqlite', dbPath?: string) {\n this.dbType = dbType;\n this.dbPath = dbPath || this.getDefaultPath();\n\n // Try SQLite first, fallback to JSON if needed\n if (this.dbType === 'sqlite') {\n this.provider = this.initializeSQLiteWithRecovery();\n } else {\n this.provider = new JSONProvider(this.dbPath);\n }\n }\n\n /**\n * Initialize SQLite with automatic error recovery\n */\n private initializeSQLiteWithRecovery(): IDatabaseProvider {\n try {\n return new SQLiteProvider(this.dbPath);\n } catch (error) {\n const errorMsg = error instanceof Error ? error.message : String(error);\n\n // Check for native module version mismatch (NODE_MODULE_VERSION error)\n if (error instanceof NativeModuleError || isNativeModuleVersionError(error)) {\n console.warn('\\n' + (error instanceof NativeModuleError ? error.message : getNativeModuleRecoveryMessage(error)));\n console.warn(' Falling back to JSON storage (no data loss, just slower).\\n');\n }\n // Check if it's an npm cache error\n else if (errorMsg.includes('ENOTEMPTY') || errorMsg.includes('better-sqlite3')) {\n console.warn('⚠️ SQLite initialization failed due to npm cache error');\n console.warn(' Will attempt automatic recovery during initialize()');\n } else {\n console.warn('SQLite not available, falling back to JSON storage:', errorMsg);\n }\n\n // Fallback to JSON for now\n this.provider = new JSONProvider(this.dbPath.replace('.sqlite', '.json'));\n this.dbType = 'json';\n return this.provider;\n }\n }\n\n private getDefaultPath(): string {\n const baseDir = path.join(process.cwd(), '.claude-flow');\n return this.dbType === 'sqlite'\n ? path.join(baseDir, 'database.sqlite')\n : path.join(baseDir, 'database.json');\n }\n\n async initialize(): Promise<void> {\n await fs.ensureDir(path.dirname(this.dbPath));\n\n try {\n await this.provider.initialize();\n this.initialized = true;\n } catch (error) {\n // If JSON provider failed, just propagate the error\n if (this.dbType === 'json') {\n throw error;\n }\n\n // For SQLite errors, attempt recovery\n const errorMsg = error instanceof Error ? error.message : String(error);\n if (this.retryCount < this.maxRetries) {\n console.warn(`⚠️ Database initialization failed (attempt ${this.retryCount + 1}/${this.maxRetries})`);\n console.warn(` Error: ${errorMsg}`);\n\n // Attempt to recover by switching to JSON\n console.log('🔄 Switching to JSON storage as fallback...');\n this.provider = new JSONProvider(this.dbPath.replace('.sqlite', '.json'));\n this.dbType = 'json';\n this.retryCount++;\n\n // Retry initialization with JSON provider\n await this.initialize();\n } else {\n throw error;\n }\n }\n }\n\n async store(key: string, value: any, namespace: string = 'default'): Promise<void> {\n if (!this.initialized) {\n await this.initialize();\n }\n return this.provider.store(key, value, namespace);\n }\n\n async retrieve(key: string, namespace: string = 'default'): Promise<any> {\n if (!this.initialized) {\n await this.initialize();\n }\n return this.provider.retrieve(key, namespace);\n }\n\n async delete(key: string, namespace: string = 'default'): Promise<boolean> {\n if (!this.initialized) {\n await this.initialize();\n }\n return this.provider.delete(key, namespace);\n }\n\n async list(namespace: string = 'default'): Promise<string[]> {\n if (!this.initialized) {\n await this.initialize();\n }\n return this.provider.list(namespace);\n }\n\n async close(): Promise<void> {\n if (this.provider) {\n await this.provider.close();\n }\n this.initialized = false;\n }\n\n getDatabaseType(): 'sqlite' | 'json' {\n return this.dbType;\n }\n\n getDatabasePath(): string {\n return this.dbPath;\n }\n\n isInitialized(): boolean {\n return this.initialized;\n }\n\n // Specialized methods for common operations\n async storeJSON(key: string, data: object, namespace?: string): Promise<void> {\n await this.store(key, JSON.stringify(data), namespace);\n }\n\n async retrieveJSON(key: string, namespace?: string): Promise<object | null> {\n const data = await this.retrieve(key, namespace);\n if (!data) return null;\n try {\n return typeof data === 'string' ? JSON.parse(data) : data;\n } catch {\n return null;\n }\n }\n\n async exists(key: string, namespace?: string): Promise<boolean> {\n const data = await this.retrieve(key, namespace);\n return data !== null && data !== undefined;\n }\n\n async clear(namespace?: string): Promise<void> {\n const keys = await this.list(namespace);\n await Promise.all(keys.map(key => this.delete(key, namespace)));\n }\n}\n\n/**\n * SQLite implementation\n */\nclass SQLiteProvider implements IDatabaseProvider {\n private db: any;\n private dbPath: string;\n\n constructor(dbPath: string) {\n this.dbPath = dbPath;\n // Dynamic import to handle optional dependency\n try {\n const Database = require('better-sqlite3');\n this.db = new Database(dbPath);\n } catch (error) {\n // Check for native module version mismatch (NODE_MODULE_VERSION error)\n if (isNativeModuleVersionError(error)) {\n const recoveryMsg = getNativeModuleRecoveryMessage(error);\n throw new NativeModuleError(recoveryMsg, error as Error);\n }\n throw new Error('better-sqlite3 not available. Install with: npm install better-sqlite3');\n }\n }\n\n async initialize(): Promise<void> {\n // Create tables\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS storage (\n namespace TEXT NOT NULL,\n key TEXT NOT NULL,\n value TEXT NOT NULL,\n created_at INTEGER DEFAULT (strftime('%s', 'now')),\n updated_at INTEGER DEFAULT (strftime('%s', 'now')),\n PRIMARY KEY (namespace, key)\n )\n `);\n\n this.db.exec(`\n CREATE INDEX IF NOT EXISTS idx_storage_namespace ON storage(namespace);\n CREATE INDEX IF NOT EXISTS idx_storage_created_at ON storage(created_at);\n `);\n }\n\n async store(key: string, value: any, namespace: string = 'default'): Promise<void> {\n const stmt = this.db.prepare(`\n INSERT OR REPLACE INTO storage (namespace, key, value, updated_at)\n VALUES (?, ?, ?, strftime('%s', 'now'))\n `);\n\n const serializedValue = typeof value === 'string' ? value : JSON.stringify(value);\n stmt.run(namespace, key, serializedValue);\n }\n\n async retrieve(key: string, namespace: string = 'default'): Promise<any> {\n const stmt = this.db.prepare('SELECT value FROM storage WHERE namespace = ? AND key = ?');\n const row = stmt.get(namespace, key);\n\n if (!row) return null;\n\n try {\n return JSON.parse(row.value);\n } catch {\n return row.value;\n }\n }\n\n async delete(key: string, namespace: string = 'default'): Promise<boolean> {\n const stmt = this.db.prepare('DELETE FROM storage WHERE namespace = ? AND key = ?');\n const result = stmt.run(namespace, key);\n return result.changes > 0;\n }\n\n async list(namespace: string = 'default'): Promise<string[]> {\n const stmt = this.db.prepare('SELECT key FROM storage WHERE namespace = ? ORDER BY key');\n const rows = stmt.all(namespace);\n return rows.map((row: any) => row.key);\n }\n\n async close(): Promise<void> {\n if (this.db) {\n this.db.close();\n }\n }\n}\n\n/**\n * JSON file-based implementation\n */\nclass JSONProvider implements IDatabaseProvider {\n private data: Record<string, Record<string, any>> = {};\n private dbPath: string;\n\n constructor(dbPath: string) {\n this.dbPath = dbPath;\n }\n\n async initialize(): Promise<void> {\n try {\n if (await fs.pathExists(this.dbPath)) {\n const content = await fs.readJSON(this.dbPath);\n this.data = content || {};\n }\n } catch (error) {\n console.warn('Failed to load JSON database, starting fresh:', error);\n this.data = {};\n }\n }\n\n async store(key: string, value: any, namespace: string = 'default'): Promise<void> {\n if (!this.data[namespace]) {\n this.data[namespace] = {};\n }\n\n this.data[namespace][key] = value;\n await this.persist();\n }\n\n async retrieve(key: string, namespace: string = 'default'): Promise<any> {\n if (!this.data[namespace]) {\n return null;\n }\n return this.data[namespace][key] || null;\n }\n\n async delete(key: string, namespace: string = 'default'): Promise<boolean> {\n if (!this.data[namespace] || !(key in this.data[namespace])) {\n return false;\n }\n\n delete this.data[namespace][key];\n await this.persist();\n return true;\n }\n\n async list(namespace: string = 'default'): Promise<string[]> {\n if (!this.data[namespace]) {\n return [];\n }\n return Object.keys(this.data[namespace]).sort();\n }\n\n async close(): Promise<void> {\n await this.persist();\n }\n\n private async persist(): Promise<void> {\n try {\n await fs.ensureDir(path.dirname(this.dbPath));\n await fs.writeJSON(this.dbPath, this.data, { spaces: 2 });\n } catch (error) {\n console.error('Failed to persist JSON database:', error);\n }\n }\n}"],"names":["fs","path","isNativeModuleVersionError","getNativeModuleRecoveryMessage","NativeModuleError","Error","originalError","isNativeModuleError","message","name","DatabaseManager","provider","dbType","dbPath","initialized","retryCount","maxRetries","getDefaultPath","initializeSQLiteWithRecovery","JSONProvider","SQLiteProvider","error","errorMsg","String","console","warn","includes","replace","baseDir","join","process","cwd","initialize","ensureDir","dirname","log","store","key","value","namespace","retrieve","delete","list","close","getDatabaseType","getDatabasePath","isInitialized","storeJSON","data","JSON","stringify","retrieveJSON","parse","exists","undefined","clear","keys","Promise","all","map","db","Database","require","recoveryMsg","exec","stmt","prepare","serializedValue","run","row","get","result","changes","rows","pathExists","content","readJSON","persist","Object","sort","writeJSON","spaces"],"mappings":"AAKA,YAAYA,QAAQ,WAAW;AAC/B,YAAYC,UAAU,OAAO;AAE7B,SAASC,0BAA0B,EAAEC,8BAA8B,QAAQ,6BAA6B;AAKxG,OAAO,MAAMC,0BAA0BC;IACrBC,cAAqB;IACrBC,sBAAsB,KAAK;IAE3C,YAAYC,OAAe,EAAEF,aAAoB,CAAE;QACjD,KAAK,CAACE;QACN,I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IAAI,EAAE;gBAAEiC,QAAQ;YAAE;QACzD,EAAE,OAAO5D,OAAO;YACdG,QAAQH,KAAK,CAAC,oCAAoCA;QACpD;IACF;AACF"}
\ No newline at end of file
diff --git a/dist-cjs/src/core/version.js b/dist-cjs/src/core/version.js
index 226f11fd6e..0ecd303456 100644
--- a/dist-cjs/src/core/version.js
+++ b/dist-cjs/src/core/version.js
@@ -23,4 +23,4 @@ export function displayVersion() {
console.log(getVersionString());
}
-//# sourceMappingURL=version.js.mapp
\ No newline at end of file
+//# sourceMappingURL=version.js.map
\ No newline at end of file
diff --git a/dist-cjs/src/utils/error-recovery.js b/dist-cjs/src/utils/error-recovery.js
index 97ee8c6a62..4ad818e45b 100644
--- a/dist-cjs/src/utils/error-recovery.js
+++ b/dist-cjs/src/utils/error-recovery.js
@@ -6,6 +6,33 @@ export function isNpmCacheError(error) {
const errorStr = error?.message || String(error);
return errorStr.includes('ENOTEMPTY') && (errorStr.includes('npm') || errorStr.includes('npx') || errorStr.includes('_npx')) || errorStr.includes('better-sqlite3');
}
+export function isNativeModuleVersionError(error) {
+ const errorStr = error?.message || String(error);
+ return errorStr.includes('NODE_MODULE_VERSION') || errorStr.includes('was compiled against a different Node.js version') || errorStr.includes('re-compiling or re-installing the module');
+}
+export function getNativeModuleRecoveryMessage(error) {
+ const errorStr = error?.message || String(error);
+ const compiledMatch = errorStr.match(/NODE_MODULE_VERSION (\d+)/);
+ const requiredMatch = errorStr.match(/requires\s+NODE_MODULE_VERSION (\d+)/);
+ let message = '⚠️ Native module version mismatch detected.\n';
+ if (compiledMatch && requiredMatch) {
+ const nodeVersionMap = {
+ '108': '18.x',
+ '115': '20.x',
+ '120': '21.x',
+ '127': '22.x',
+ '131': '23.x'
+ };
+ const compiled = nodeVersionMap[compiledMatch[1]] || `ABI ${compiledMatch[1]}`;
+ const required = nodeVersionMap[requiredMatch[1]] || `ABI ${requiredMatch[1]}`;
+ message += ` Module was compiled for Node.js ${compiled}, but running Node.js ${required}.\n`;
+ }
+ message += '\n To fix this, try one of:\n';
+ message += ' 1. npm rebuild better-sqlite3\n';
+ message += ' 2. rm -rf node_modules && npm install\n';
+ message += ' 3. npx cache: rm -rf ~/.npm/_npx/ && run command again\n';
+ return message;
+}
export function isWSL() {
if (process.platform !== 'linux') {
return false;
@@ -203,6 +230,8 @@ export async function recoverInitErrors(error) {
}
export const errorRecovery = {
isNpmCacheError,
+ isNativeModuleVersionError,
+ getNativeModuleRecoveryMessage,
isWSL,
cleanNpmCache,
retryWithRecovery,
diff --git a/dist-cjs/src/utils/error-recovery.js.map b/dist-cjs/src/utils/error-recovery.js.map
index 840318cf44..89342c11e1 100644
--- a/dist-cjs/src/utils/error-recovery.js.map
+++ b/dist-cjs/src/utils/error-recovery.js.map
@@ -1 +1 @@
-{"version":3,"sources":["../../../src/utils/error-recovery.ts"],"sourcesContent":["/**\n * Error Recovery Utilities\n * Automatic error detection and recovery for common installation issues\n */\n\nimport { execSync } from 'child_process';\nimport * as fs from 'fs-extra';\nimport * as path from 'path';\nimport * as os from 'os';\n\nexport interface RecoveryResult {\n success: boolean;\n action: string;\n message: string;\n recovered: boolean;\n}\n\nexport interface RetryOptions {\n maxRetries?: number;\n delay?: number;\n onRetry?: (attempt: number, error: Error) => void;\n cleanupFn?: () => Promise<void>;\n}\n\n/**\n * Detect if an error is the ENOTEMPTY npm cache error\n */\nexport function isNpmCacheError(error: any): boolean {\n const errorStr = error?.message || String(error);\n return (\n errorStr.includes('ENOTEMPTY') &&\n (errorStr.includes('npm') || errorStr.includes('npx') || errorStr.includes('_npx'))\n ) || errorStr.includes('better-sqlite3');\n}\n\n/**\n * Detect if running on WSL (Windows Subsystem for Linux)\n */\nexport function isWSL(): boolean {\n if (process.platform !== 'linux') {\n return false;\n }\n\n try {\n const release = fs.readFileSync('/proc/version', 'utf8').toLowerCase();\n return release.includes('microsoft') || release.includes('wsl');\n } catch {\n return false;\n }\n}\n\n/**\n * Clean npm and npx cache directories\n */\nexport async function cleanNpmCache(): Promise<RecoveryResult> {\n const homeDir = os.homedir();\n const npxCacheDir = path.join(homeDir, '.npm', '_npx');\n\n try {\n console.log('🧹 Cleaning npm cache...');\n\n // Clean npm cache\n try {\n execSync('npm cache clean --force', { stdio: 'pipe' });\n console.log('✅ npm cache cleaned');\n } catch (error) {\n console.warn('⚠️ npm cache clean failed, continuing...');\n }\n\n // Remove npx cache directory\n if (await fs.pathExists(npxCacheDir)) {\n console.log(`🗑️ Removing npx cache: ${npxCacheDir}`);\n await fs.remove(npxCacheDir);\n console.log('✅ npx cache removed');\n }\n\n // Fix permissions on WSL\n if (isWSL()) {\n const npmDir = path.join(homeDir, '.npm');\n if (await fs.pathExists(npmDir)) {\n try {\n execSync(`chmod -R 755 \"${npmDir}\"`, { stdio: 'pipe' });\n console.log('✅ npm directory permissions fixed');\n } catch (error) {\n console.warn('⚠️ Permission fix failed, continuing...');\n }\n }\n }\n\n return {\n success: true,\n action: 'cache-cleanup',\n message: 'npm/npx cache cleaned successfully',\n recovered: true\n };\n } catch (error) {\n return {\n success: false,\n action: 'cache-cleanup',\n message: `Failed to clean cache: ${error instanceof Error ? error.message : String(error)}`,\n recovered: false\n };\n }\n}\n\n/**\n * Automatic retry with exponential backoff and error recovery\n */\nexport async function retryWithRecovery<T>(\n fn: () => Promise<T>,\n options: RetryOptions = {}\n): Promise<T> {\n const {\n maxRetries = 3,\n delay = 1000,\n onRetry,\n cleanupFn\n } = options;\n\n let lastError: Error | undefined;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error as Error;\n\n // Check if it's a recoverable error\n if (isNpmCacheError(error)) {\n console.log(`\\n⚠️ Detected npm cache error (attempt ${attempt}/${maxRetries})`);\n\n // Attempt automatic recovery\n const recovery = await cleanNpmCache();\n if (recovery.success) {\n console.log('✅ Cache cleaned, retrying...\\n');\n\n // Run custom cleanup if provided\n if (cleanupFn) {\n await cleanupFn();\n }\n\n // Exponential backoff\n const backoffDelay = delay * Math.pow(2, attempt - 1);\n await new Promise(resolve => setTimeout(resolve, backoffDelay));\n\n continue; // Retry\n } else {\n console.error('❌ Cache cleanup failed:', recovery.message);\n }\n }\n\n // Call retry callback\n if (onRetry && attempt < maxRetries) {\n onRetry(attempt, lastError);\n await new Promise(resolve => setTimeout(resolve, delay));\n continue;\n }\n\n // Last attempt failed\n if (attempt === maxRetries) {\n break;\n }\n }\n }\n\n // All retries exhausted\n throw new Error(\n `Operation failed after ${maxRetries} attempts. ` +\n `Last error: ${lastError?.message || 'Unknown error'}`\n );\n}\n\n/**\n * WSL-specific error recovery\n */\nexport async function recoverWSLErrors(): Promise<RecoveryResult> {\n if (!isWSL()) {\n return {\n success: true,\n action: 'wsl-check',\n message: 'Not running on WSL, no recovery needed',\n recovered: false\n };\n }\n\n console.log('🔍 Detected WSL environment, applying fixes...');\n\n try {\n const homeDir = os.homedir();\n\n // Check if running from Windows mount\n const cwd = process.cwd();\n if (cwd.startsWith('/mnt/')) {\n console.warn('⚠️ WARNING: Running from Windows filesystem (/mnt/)');\n console.warn(' For best results, run from WSL filesystem (e.g., ~/projects/)');\n }\n\n // Ensure build tools are available\n try {\n execSync('which gcc', { stdio: 'pipe' });\n } catch {\n console.warn('⚠️ build-essential not found. Install with:');\n console.warn(' sudo apt-get update && sudo apt-get install -y build-essential python3');\n }\n\n // Clean cache with WSL-specific handling\n return await cleanNpmCache();\n } catch (error) {\n return {\n success: false,\n action: 'wsl-recovery',\n message: `WSL recovery failed: ${error instanceof Error ? error.message : String(error)}`,\n recovered: false\n };\n }\n}\n\n/**\n * Verify better-sqlite3 installation\n */\nexport async function verifyBetterSqlite3(): Promise<boolean> {\n try {\n require.resolve('better-sqlite3');\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Install better-sqlite3 with retry and error recovery\n */\nexport async function installBetterSqlite3WithRecovery(): Promise<RecoveryResult> {\n console.log('📦 Installing better-sqlite3...');\n\n return retryWithRecovery(\n async () => {\n execSync('npm install better-sqlite3 --no-save', {\n stdio: 'inherit',\n cwd: process.cwd()\n });\n\n // Verify installation\n if (await verifyBetterSqlite3()) {\n return {\n success: true,\n action: 'install-sqlite',\n message: 'better-sqlite3 installed successfully',\n recovered: true\n };\n } else {\n throw new Error('Installation completed but module not found');\n }\n },\n {\n maxRetries: 3,\n delay: 2000,\n onRetry: (attempt, error) => {\n console.log(`⚠️ Install attempt ${attempt} failed: ${error.message}`);\n console.log('🔄 Cleaning cache and retrying...');\n }\n }\n );\n}\n\n/**\n * Comprehensive error recovery for initialization\n */\nexport async function recoverInitErrors(error: any): Promise<RecoveryResult> {\n console.log('\\n🚨 Error detected during initialization');\n console.log(` Error: ${error?.message || String(error)}\\n`);\n\n // WSL-specific recovery\n if (isWSL()) {\n console.log('🔧 Applying WSL-specific fixes...');\n const wslRecovery = await recoverWSLErrors();\n if (!wslRecovery.success) {\n return wslRecovery;\n }\n }\n\n // npm cache error recovery\n if (isNpmCacheError(error)) {\n console.log('🔧 Detected npm cache error, attempting recovery...');\n const cacheRecovery = await cleanNpmCache();\n if (!cacheRecovery.success) {\n return cacheRecovery;\n }\n\n // Try to reinstall better-sqlite3\n if (!await verifyBetterSqlite3()) {\n console.log('🔧 better-sqlite3 missing, attempting reinstall...');\n return await installBetterSqlite3WithRecovery();\n }\n\n return {\n success: true,\n action: 'error-recovery',\n message: 'Cache cleaned and dependencies verified',\n recovered: true\n };\n }\n\n // Generic error handling\n return {\n success: false,\n action: 'error-recovery',\n message: `Unable to automatically recover from error: ${error?.message || String(error)}`,\n recovered: false\n };\n}\n\n/**\n * Export utility functions\n */\nexport const errorRecovery = {\n isNpmCacheError,\n isWSL,\n cleanNpmCache,\n retryWithRecovery,\n recoverWSLErrors,\n verifyBetterSqlite3,\n installBetterSqlite3WithRecovery,\n recoverInitErrors\n};\n"],"names":["execSync","fs","path","os","isNpmCacheError","error","errorStr","message","String","includes","isWSL","process","platform","release","readFileSync","toLowerCase","cleanNpmCache","homeDir","homedir","npxCacheDir","join","console","log","stdio","warn","pathExists","remove","npmDir","success","action","recovered","Error","retryWithRecovery","fn","options","maxRetries","delay","onRetry","cleanupFn","lastError","attempt","recovery","backoffDelay","Math","pow","Promise","resolve","setTimeout","recoverWSLErrors","cwd","startsWith","verifyBetterSqlite3","require","installBetterSqlite3WithRecovery","recoverInitErrors","wslRecovery","cacheRecovery","errorRecovery"],"mappings":"AAKA,SAASA,QAAQ,QAAQ,gBAAgB;AACzC,YAAYC,QAAQ,WAAW;AAC/B,YAAYC,UAAU,OAAO;AAC7B,YAAYC,QAAQ,KAAK;AAmBzB,OAAO,SAASC,gBAAgBC,KAAU;IACxC,MAAMC,WAAWD,OAAOE,WAAWC,OAAOH;IAC1C,OAAO,AACLC,SAASG,QAAQ,CAAC,gBACjBH,CAAAA,SAASG,QAAQ,CAAC,UAAUH,SAASG,QAAQ,CAAC,UAAUH,SAASG,QAAQ,CAAC,OAAM,KAC9EH,SAASG,QAAQ,CAAC;AACzB;AAKA,OAAO,SAASC;IACd,IAAIC,QAAQC,QAAQ,KAAK,SAAS;QAChC,OAAO;IACT;IAEA,IAAI;QACF,MAAMC,UAAUZ,GAAGa,YAAY,CAAC,iBAAiB,QAAQC,WAAW;QACpE,OAAOF,QAAQJ,QAAQ,CAAC,gBAAgBI,QAAQJ,QAAQ,CAAC;IAC3D,EAAE,OAAM;QACN,OAAO;IACT;AACF;AAKA,OAAO,eAAeO;IACpB,MAAMC,UAAUd,GAAGe,OAAO;IAC1B,MAAMC,cAAcjB,KAAKkB,IAAI,CAACH,SAAS,QAAQ;IAE/C,IAAI;QACFI,QAAQC,GAAG,CAAC;QAGZ,IAAI;YACFtB,SAAS,2BAA2B;gBAAEuB,OAAO;YAAO;YACpDF,QAAQC,GAAG,CAAC;QACd,EAAE,OAAOjB,OAAO;YACdgB,QAAQG,IAAI,CAAC;QACf;QAGA,IAAI,MAAMvB,GAAGwB,UAAU,CAACN,cAAc;YACpCE,QAAQC,GAAG,CAAC,CAAC,yBAAyB,EAAEH,aAAa;YACrD,MAAMlB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ACF,EAAE"}
\ No newline at end of file
+{"version":3,"sources":["../../../src/utils/error-recovery.ts"],"sourcesContent":["/**\n * Error Recovery Utilities\n * Automatic error detection and recovery for common installation issues\n */\n\nimport { execSync } from 'child_process';\nimport * as fs from 'fs-extra';\nimport * as path from 'path';\nimport * as os from 'os';\n\nexport interface RecoveryResult {\n success: boolean;\n action: string;\n message: string;\n recovered: boolean;\n}\n\nexport interface RetryOptions {\n maxRetries?: number;\n delay?: number;\n onRetry?: (attempt: number, error: Error) => void;\n cleanupFn?: () => Promise<void>;\n}\n\n/**\n * Detect if an error is the ENOTEMPTY npm cache error\n */\nexport function isNpmCacheError(error: any): boolean {\n const errorStr = error?.message || String(error);\n return (\n errorStr.includes('ENOTEMPTY') &&\n (errorStr.includes('npm') || errorStr.includes('npx') || errorStr.includes('_npx'))\n ) || errorStr.includes('better-sqlite3');\n}\n\n/**\n * Detect if an error is a native module version mismatch (NODE_MODULE_VERSION)\n * This happens when native modules are compiled for a different Node.js version\n */\nexport function isNativeModuleVersionError(error: any): boolean {\n const errorStr = error?.message || String(error);\n return (\n errorStr.includes('NODE_MODULE_VERSION') ||\n errorStr.includes('was compiled against a different Node.js version') ||\n errorStr.includes('re-compiling or re-installing the module')\n );\n}\n\n/**\n * Get helpful message for native module version mismatch\n */\nexport function getNativeModuleRecoveryMessage(error: any): string {\n const errorStr = error?.message || String(error);\n\n // Extract version numbers if available\n const compiledMatch = errorStr.match(/NODE_MODULE_VERSION (\\d+)/);\n const requiredMatch = errorStr.match(/requires\\s+NODE_MODULE_VERSION (\\d+)/);\n\n let message = '⚠️ Native module version mismatch detected.\\n';\n\n if (compiledMatch && requiredMatch) {\n const nodeVersionMap: Record<string, string> = {\n '108': '18.x',\n '115': '20.x',\n '120': '21.x',\n '127': '22.x',\n '131': '23.x'\n };\n const compiled = nodeVersionMap[compiledMatch[1]] || `ABI ${compiledMatch[1]}`;\n const required = nodeVersionMap[requiredMatch[1]] || `ABI ${requiredMatch[1]}`;\n message += ` Module was compiled for Node.js ${compiled}, but running Node.js ${required}.\\n`;\n }\n\n message += '\\n To fix this, try one of:\\n';\n message += ' 1. npm rebuild better-sqlite3\\n';\n message += ' 2. rm -rf node_modules && npm install\\n';\n message += ' 3. npx cache: rm -rf ~/.npm/_npx/ && run command again\\n';\n\n return message;\n}\n\n/**\n * Detect if running on WSL (Windows Subsystem for Linux)\n */\nexport function isWSL(): boolean {\n if (process.platform !== 'linux') {\n return false;\n }\n\n try {\n const release = fs.readFileSync('/proc/version', 'utf8').toLowerCase();\n return release.includes('microsoft') || release.includes('wsl');\n } catch {\n return false;\n }\n}\n\n/**\n * Clean npm and npx cache directories\n */\nexport async function cleanNpmCache(): Promise<RecoveryResult> {\n const homeDir = os.homedir();\n const npxCacheDir = path.join(homeDir, '.npm', '_npx');\n\n try {\n console.log('🧹 Cleaning npm cache...');\n\n // Clean npm cache\n try {\n execSync('npm cache clean --force', { stdio: 'pipe' });\n console.log('✅ npm cache cleaned');\n } catch (error) {\n console.warn('⚠️ npm cache clean failed, continuing...');\n }\n\n // Remove npx cache directory\n if (await fs.pathExists(npxCacheDir)) {\n console.log(`🗑️ Removing npx cache: ${npxCacheDir}`);\n await fs.remove(npxCacheDir);\n console.log('✅ npx cache removed');\n }\n\n // Fix permissions on WSL\n if (isWSL()) {\n const npmDir = path.join(homeDir, '.npm');\n if (await fs.pathExists(npmDir)) {\n try {\n execSync(`chmod -R 755 \"${npmDir}\"`, { stdio: 'pipe' });\n console.log('✅ npm directory permissions fixed');\n } catch (error) {\n console.warn('⚠️ Permission fix failed, continuing...');\n }\n }\n }\n\n return {\n success: true,\n action: 'cache-cleanup',\n message: 'npm/npx cache cleaned successfully',\n recovered: true\n };\n } catch (error) {\n return {\n success: false,\n action: 'cache-cleanup',\n message: `Failed to clean cache: ${error instanceof Error ? error.message : String(error)}`,\n recovered: false\n };\n }\n}\n\n/**\n * Automatic retry with exponential backoff and error recovery\n */\nexport async function retryWithRecovery<T>(\n fn: () => Promise<T>,\n options: RetryOptions = {}\n): Promise<T> {\n const {\n maxRetries = 3,\n delay = 1000,\n onRetry,\n cleanupFn\n } = options;\n\n let lastError: Error | undefined;\n\n for (let attempt = 1; attempt <= maxRetries; attempt++) {\n try {\n return await fn();\n } catch (error) {\n lastError = error as Error;\n\n // Check if it's a recoverable error\n if (isNpmCacheError(error)) {\n console.log(`\\n⚠️ Detected npm cache error (attempt ${attempt}/${maxRetries})`);\n\n // Attempt automatic recovery\n const recovery = await cleanNpmCache();\n if (recovery.success) {\n console.log('✅ Cache cleaned, retrying...\\n');\n\n // Run custom cleanup if provided\n if (cleanupFn) {\n await cleanupFn();\n }\n\n // Exponential backoff\n const backoffDelay = delay * Math.pow(2, attempt - 1);\n await new Promise(resolve => setTimeout(resolve, backoffDelay));\n\n continue; // Retry\n } else {\n console.error('❌ Cache cleanup failed:', recovery.message);\n }\n }\n\n // Call retry callback\n if (onRetry && attempt < maxRetries) {\n onRetry(attempt, lastError);\n await new Promise(resolve => setTimeout(resolve, delay));\n continue;\n }\n\n // Last attempt failed\n if (attempt === maxRetries) {\n break;\n }\n }\n }\n\n // All retries exhausted\n throw new Error(\n `Operation failed after ${maxRetries} attempts. ` +\n `Last error: ${lastError?.message || 'Unknown error'}`\n );\n}\n\n/**\n * WSL-specific error recovery\n */\nexport async function recoverWSLErrors(): Promise<RecoveryResult> {\n if (!isWSL()) {\n return {\n success: true,\n action: 'wsl-check',\n message: 'Not running on WSL, no recovery needed',\n recovered: false\n };\n }\n\n console.log('🔍 Detected WSL environment, applying fixes...');\n\n try {\n const homeDir = os.homedir();\n\n // Check if running from Windows mount\n const cwd = process.cwd();\n if (cwd.startsWith('/mnt/')) {\n console.warn('⚠️ WARNING: Running from Windows filesystem (/mnt/)');\n console.warn(' For best results, run from WSL filesystem (e.g., ~/projects/)');\n }\n\n // Ensure build tools are available\n try {\n execSync('which gcc', { stdio: 'pipe' });\n } catch {\n console.warn('⚠️ build-essential not found. Install with:');\n console.warn(' sudo apt-get update && sudo apt-get install -y build-essential python3');\n }\n\n // Clean cache with WSL-specific handling\n return await cleanNpmCache();\n } catch (error) {\n return {\n success: false,\n action: 'wsl-recovery',\n message: `WSL recovery failed: ${error instanceof Error ? error.message : String(error)}`,\n recovered: false\n };\n }\n}\n\n/**\n * Verify better-sqlite3 installation\n */\nexport async function verifyBetterSqlite3(): Promise<boolean> {\n try {\n require.resolve('better-sqlite3');\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Install better-sqlite3 with retry and error recovery\n */\nexport async function installBetterSqlite3WithRecovery(): Promise<RecoveryResult> {\n console.log('📦 Installing better-sqlite3...');\n\n return retryWithRecovery(\n async () => {\n execSync('npm install better-sqlite3 --no-save', {\n stdio: 'inherit',\n cwd: process.cwd()\n });\n\n // Verify installation\n if (await verifyBetterSqlite3()) {\n return {\n success: true,\n action: 'install-sqlite',\n message: 'better-sqlite3 installed successfully',\n recovered: true\n };\n } else {\n throw new Error('Installation completed but module not found');\n }\n },\n {\n maxRetries: 3,\n delay: 2000,\n onRetry: (attempt, error) => {\n console.log(`⚠️ Install attempt ${attempt} failed: ${error.message}`);\n console.log('🔄 Cleaning cache and retrying...');\n }\n }\n );\n}\n\n/**\n * Comprehensive error recovery for initialization\n */\nexport async function recoverInitErrors(error: any): Promise<RecoveryResult> {\n console.log('\\n🚨 Error detected during initialization');\n console.log(` Error: ${error?.message || String(error)}\\n`);\n\n // WSL-specific recovery\n if (isWSL()) {\n console.log('🔧 Applying WSL-specific fixes...');\n const wslRecovery = await recoverWSLErrors();\n if (!wslRecovery.success) {\n return wslRecovery;\n }\n }\n\n // npm cache error recovery\n if (isNpmCacheError(error)) {\n console.log('🔧 Detected npm cache error, attempting recovery...');\n const cacheRecovery = await cleanNpmCache();\n if (!cacheRecovery.success) {\n return cacheRecovery;\n }\n\n // Try to reinstall better-sqlite3\n if (!await verifyBetterSqlite3()) {\n console.log('🔧 better-sqlite3 missing, attempting reinstall...');\n return await installBetterSqlite3WithRecovery();\n }\n\n return {\n success: true,\n action: 'error-recovery',\n message: 'Cache cleaned and dependencies verified',\n recovered: true\n };\n }\n\n // Generic error handling\n return {\n success: false,\n action: 'error-recovery',\n message: `Unable to automatically recover from error: ${error?.message || String(error)}`,\n recovered: false\n };\n}\n\n/**\n * Export utility functions\n */\nexport const errorRecovery = {\n isNpmCacheError,\n isNativeModuleVersionError,\n getNativeModuleRecoveryMessage,\n isWSL,\n cleanNpmCache,\n retryWithRecovery,\n recoverWSLErrors,\n verifyBetterSqlite3,\n installBetterSqlite3WithRecovery,\n recoverInitErrors\n};\n"],"names":["execSync","fs","path","os","isNpmCacheError","error","errorStr","message","String","includes","isNativeModuleVersionError","getNativeModuleRecoveryMessage","compiledMatch","match","requiredMatch","nodeVersionMap","compiled","required","isWSL","process","platform","release","readFileSync","toLowerCase","cleanNpmCache","homeDir","homedir","npxCacheDir","join","console","log","stdio","warn","pathExists","remove","npmDir","success","action","recovered","Error","retryWithRecovery","fn","options","maxRetries","delay","onRetry","cleanupFn","lastError","attempt","recovery","backoffDelay","Math","pow","Promise","resolve","setTimeout","recoverWSLErrors","cwd","startsWith","verifyBetterSqlite3","require","installBetterSqlite3WithRecovery","recoverInitErrors","wslRecovery","cacheRecovery","errorRecovery"],"mappings":"AAKA,SAASA,QAAQ,QAAQ,gBAAgB;AACzC,YAAYC,QAAQ,WAAW;AAC/B,YAAYC,UAAU,OAAO;AAC7B,YAAYC,QAAQ,KAAK;AAmBzB,OAAO,SAASC,gBAAgBC,KAAU;IACxC,MAAMC,WAAWD,OAAOE,WAAWC,OAAOH;IAC1C,OAAO,AACLC,SAASG,QAAQ,CAAC,gBACjBH,CAAAA,SAASG,QAAQ,CAAC,UAAUH,SAASG,QAAQ,CAAC,UAAUH,SAASG,QAAQ,CAAC,OAAM,KAC9EH,SAASG,QAAQ,CAAC;AACzB;AAMA,OAAO,SAASC,2BAA2BL,KAAU;IACnD,MAAMC,WAAWD,OAAOE,WAAWC,OAAOH;IAC1C,OACEC,SAASG,QAAQ,CAAC,0BAClBH,S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,WAAWC,OAAOH,QAAQ;QACzFiC,WAAW;IACb;AACF;AAKA,OAAO,MAAM2B,gBAAgB;IAC3B7D;IACAM;IACAC;IACAO;IACAM;IACAgB;IACAgB;IACAG;IACAE;IACAC;AACF,EAAE"}
\ No newline at end of file
diff --git a/dist-cjs/src/utils/key-redactor.js.map b/dist-cjs/src/utils/key-redactor.js.map
index 70ffc2588a..1792a21611 100644
--- a/dist-cjs/src/utils/key-redactor.js.map
+++ b/dist-cjs/src/utils/key-redactor.js.map
@@ -1 +1 @@
-{"version":3,"sources":["../../../src/utils/key-redactor.js"],"sourcesContent":["/**\n * API Key Redaction Utility\n * Prevents sensitive data from leaking into logs, memory, or git commits\n */\n\nexport class KeyRedactor {\n static 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 static 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, showPrefix = true) {\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(obj, deep = true) {\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];\n if (value && value.length > 8) {\n redacted[key] = `${value.substring(0, 4)}...[REDACTED]`;\n } else {\n redacted[key] = '[REDACTED]';\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]);\n }\n });\n\n return redacted;\n }\n\n /**\n * Sanitize text for safe logging\n */\n static sanitize(text) {\n return this.redact(text, true);\n }\n\n /**\n * Sanitize command arguments\n */\n static sanitizeArgs(args) {\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) {\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) {\n const warnings = [];\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) {\n const redacted = {};\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":"AAKA,OAAO,MAAMA;IACX,OAAOC,mBAAmB;QAExB;QAGA;QAGA;QAGA;QAGA;QAGA;QAGA;KACD,CAAC;IAEF,OAAOC,mBAAmB;QACxB;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;QACA;KACD,CAAC;IAKF,OAAOC,OAAOC,IAAI,EAAEC,aAAa,IAAI,EAAE;QACrC,IAAI,CAACD,MAAM,OAAOA;QAElB,IAAIE,WAAWF;QAGf,IAAI,CAACH,gBAAgB,CAACM,OAAO,CAACC,CAAAA;YAC5BF,WAAWA,SAASG,OAAO,CAACD,SAAS,CAACE;gBACpC,IAAIL,cAAcK,MAAMC,MAAM,GAAG,GAAG;oBAClC,MAAMC,SAASF,MAAMG,SAAS,CAAC,GAAG;oBAClC,OAAO,GAAGD,OAAO,aAAa,CAAC;gBACjC;gBACA,OAAO;YACT;QACF;QAEA,OAAON;IACT;IAKA,OAAOQ,aAAaC,GAAG,EAAEC,OAAO,IAAI,EAAE;QACpC,IAAI,CAACD,OAAO,OAAOA,QAAQ,UAAU,OAAOA;QAE5C,MAAMT,WAAW;YAAE,GAAGS,GAAG;QAAC;QAE1BE,OAAOC,IAAI,CAACZ,UAAUC,OAAO,CA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D;IAKA,OAAO8B,SAAS9B,IAAI,EAAE;QACpB,MAAM+B,WAAW,EAAE;QAEnB,IAAI,CAAClC,gBAAgB,CAACM,OAAO,CAAC,CAACC,SAAS4B;YACtC,IAAI5B,QAAQyB,IAAI,CAAC7B,OAAO;gBACtB+B,SAASE,IAAI,CAAC,CAAC,oCAAoC,EAAED,QAAQ,EAAE,CAAC,CAAC;YACnE;QACF;QAEA,OAAO;YACLE,MAAMH,SAASxB,MAAM,KAAK;YAC1BwB;QACF;IACF;IAKA,OAAOI,UAAUC,GAAG,EAAE;QACpB,MAAMlC,WAAW,CAAC;QAElBW,OAAOC,IAAI,CAACsB,KAAKjC,OAAO,CAACY,CAAAA;YACvB,MAAMO,QAAQc,GAAG,CAACrB,IAAI;YACtB,IAAI,CAACO,OAAO;gBACVpB,QAAQ,CAACa,IAAI,GAAG;gBAChB;YACF;YAEA,MAAMC,WAAWD,IAAIE,WAAW;YAChC,MAAMC,cAAcF,SAASK,QAAQ,CAAC,UACnBL,SAASK,QAAQ,CAAC,YAClBL,SAASK,QAAQ,CAAC,aAClBL,SAASK,QAAQ,CAAC;YAErC,IAAIH,aAAa;gBACfhB,QAAQ,CAACa,IAAI,GAAGO,MAAMf,MAAM,GAAG,IAC3B,GAAGe,MAAMb,SAAS,CAAC,GAAG,GAAG,aAAa,CAAC,GACvC;YACN,OAAO;gBACLP,QAAQ,CAACa,IAAI,GAAGO;YAClB;QACF;QAEA,OAAOpB;IACT;AACF;AAGA,OAAO,MAAMmC,WAAWzC,YAAY"}
\ No newline at end of file
+{"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;YAC5BF,WAAWA,SAASG,OAAO,CAACD,SAAS,CAACE;gBACpC,IAAIL,cAAcK,MAAMC,MAAM,GAAG,GAAG;oBAClC,MAAMC,SAASF,MAAMG,SAAS,CAAC,GAAG;oBAClC,OAAO,GAAGD,OAAO,aAAa,CAAC;gBACjC;gBACA,OAAO;YACT;QACF;QAEA,OAAON;IACT;IAKA,OAAOQ,aAA4CC,GAAM,EAAEC,OAAO,IAAI,EAAK;QACzE,IAAI,CAACD,OAAO,OAAOA,QAAQ,UAAU,OAAOA;QAE5C,MAAMT,WAAW;YAAE,GAAGS,GAAG;QAAC;QAE1BE,OAAOC,IAAI,CAACZ,UAAUC,OAAO,CAACY,CAAAA;YAC5B,MAAMC,WAAWD,IAAIE,WAAW;YAGhC,MAAMC,cAAc,IAAI,CAACpB,gBAAgB,CAACqB,IAAI,CAACC,CAAAA,QAC7CJ,SAASK,QAAQ,CAACD;YAGpB,IAAIF,eAAe,OAAOhB,QAAQ,CAACa,IAAI,KAAK,UAAU;gBACpD,MAAMO,QAAQpB,QAAQ,CAACa,IAAI;gBAC3B,IAAIO,SAASA,MAAMf,MAAM,GAAG,GAAG;oBAC7BL,QAAQ,CAACa,IAAI,GAAG,GAAGO,MAAMb,SAAS,CAAC,GAAG,GAAG,aAAa,CAAC;gBACzD,OAAO;oBACLP,QAAQ,CAACa,IAAI,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C,OAAO,CAACY,CAAAA;YACvB,MAAMO,QAAQc,GAAG,CAACrB,IAAI;YACtB,IAAI,CAACO,OAAO;gBACVpB,QAAQ,CAACa,IAAI,GAAG;gBAChB;YACF;YAEA,MAAMC,WAAWD,IAAIE,WAAW;YAChC,MAAMC,cAAcF,SAASK,QAAQ,CAAC,UACnBL,SAASK,QAAQ,CAAC,YAClBL,SAASK,QAAQ,CAAC,aAClBL,SAASK,QAAQ,CAAC;YAErC,IAAIH,aAAa;gBACfhB,QAAQ,CAACa,IAAI,GAAGO,MAAMf,MAAM,GAAG,IAC3B,GAAGe,MAAMb,SAAS,CAAC,GAAG,GAAG,aAAa,CAAC,GACvC;YACN,OAAO;gBACLP,QAAQ,CAACa,IAAI,GAAGO;YAClB;QACF;QAEA,OAAOpB;IACT;AACF;AAGA,OAAO,MAAMmC,WAAWzC,YAAY"}
\ No newline at end of file
diff --git a/src/cli/simple-commands/hooks.js b/src/cli/simple-commands/hooks.js
index 193aaa3a52..9cc5aefc3d 100644
--- a/src/cli/simple-commands/hooks.js
+++ b/src/cli/simple-commands/hooks.js
@@ -6,15 +6,45 @@ import {
checkRuvSwarmAvailable,
} from '../utils.js';
import { SqliteMemoryStore } from '../../memory/sqlite-store.js';
+import { InMemoryStore } from '../../memory/in-memory-store.js';
// Initialize memory store
let memoryStore = null;
+let storeInitFailed = false;
async function getMemoryStore() {
- if (!memoryStore) {
+ if (memoryStore) return memoryStore;
+
+ // If we already failed, return a working in-memory store
+ if (storeInitFailed) {
+ if (!memoryStore) {
+ memoryStore = new InMemoryStore();
+ await memoryStore.initialize();
+ }
+ return memoryStore;
+ }
+
+ try {
memoryStore = new SqliteMemoryStore();
await memoryStore.initialize();
+ } catch (err) {
+ // Check if it's a native module error (NODE_MODULE_VERSION mismatch)
+ const isNativeModuleError =
+ err.message?.includes('NODE_MODULE_VERSION') ||
+ err.message?.includes('was compiled against a different Node.js version') ||
+ err.message?.includes('better-sqlite3') ||
+ err.message?.includes('SQLite is not available');
+
+ if (isNativeModuleError) {
+ printWarning(`SQLite unavailable, using in-memory storage for hooks (data won't persist)`);
+ storeInitFailed = true;
+ memoryStore = new InMemoryStore();
+ await memoryStore.initialize();
+ } else {
+ throw err;
+ }
}
+
return memoryStore;
}
diff --git a/src/core/DatabaseManager.ts b/src/core/DatabaseManager.ts
index 687fb7f863..e28d1a4d0b 100644
--- a/src/core/DatabaseManager.ts
+++ b/src/core/DatabaseManager.ts
@@ -6,6 +6,21 @@
import * as fs from 'fs-extra';
import * as path from 'path';
import { IDatabaseProvider } from '../types/interfaces.js';
+import { isNativeModuleVersionError, getNativeModuleRecoveryMessage } from '../utils/error-recovery.js';
+
+/**
+ * Custom error class for native module issues
+ */
+export class NativeModuleError extends Error {
+ public readonly originalError: Error;
+ public readonly isNativeModuleError = true;
+
+ constructor(message: string, originalError: Error) {
+ super(message);
+ this.name = 'NativeModuleError';
+ this.originalError = originalError;
+ }
+}
export class DatabaseManager implements IDatabaseProvider {
private provider: IDatabaseProvider;
@@ -36,12 +51,17 @@ export class DatabaseManager implements IDatabaseProvider {
} catch (error) {
const errorMsg = error instanceof Error ? error.message : String(error);
+ // Check for native module version mismatch (NODE_MODULE_VERSION error)
+ if (error instanceof NativeModuleError || isNativeModuleVersionError(error)) {
+ console.warn('\n' + (error instanceof NativeModuleError ? error.message : getNativeModuleRecoveryMessage(error)));
+ console.warn(' Falling back to JSON storage (no data loss, just slower).\n');
+ }
// Check if it's an npm cache error
- if (errorMsg.includes('ENOTEMPTY') || errorMsg.includes('better-sqlite3')) {
+ else if (errorMsg.includes('ENOTEMPTY') || errorMsg.includes('better-sqlite3')) {
console.warn('⚠️ SQLite initialization failed due to npm cache error');
console.warn(' Will attempt automatic recovery during initialize()');
} else {
- console.warn('SQLite not available, falling back to JSON storage:', error);
+ console.warn('SQLite not available, falling back to JSON storage:', errorMsg);
}
// Fallback to JSON for now
@@ -177,6 +197,11 @@ class SQLiteProvider implements IDatabaseProvider {
const Database = require('better-sqlite3');
this.db = new Database(dbPath);
} catch (error) {
+ // Check for native module version mismatch (NODE_MODULE_VERSION error)
+ if (isNativeModuleVersionError(error)) {
+ const recoveryMsg = getNativeModuleRecoveryMessage(error);
+ throw new NativeModuleError(recoveryMsg, error as Error);
+ }
throw new Error('better-sqlite3 not available. Install with: npm install better-sqlite3');
}
}
diff --git a/src/memory/sqlite-wrapper.js b/src/memory/sqlite-wrapper.js
index f1fd9fbb47..2576047594 100644
--- a/src/memory/sqlite-wrapper.js
+++ b/src/memory/sqlite-wrapper.js
@@ -33,35 +33,79 @@ async function tryLoadSQLite() {
return true;
} catch (importErr) {
loadError = importErr;
-
- // Check for specific Windows errors
- if (requireErr.message.includes('was compiled against a different Node.js version') ||
- requireErr.message.includes('Could not locate the bindings file') ||
- requireErr.message.includes('The specified module could not be found') ||
+
+ // Check for NODE_MODULE_VERSION mismatch (different Node.js ABI)
+ const isVersionMismatch =
+ requireErr.message?.includes('NODE_MODULE_VERSION') ||
+ importErr.message?.includes('NODE_MODULE_VERSION') ||
+ requireErr.message?.includes('was compiled against a different Node.js version') ||
+ importErr.message?.includes('was compiled against a different Node.js version');
+
+ if (isVersionMismatch) {
+ // Extract version info for helpful message
+ const errorMsg = requireErr.message || importErr.message || '';
+ const compiledMatch = errorMsg.match(/NODE_MODULE_VERSION (\d+)/);
+ const requiredMatch = errorMsg.match(/requires\s+NODE_MODULE_VERSION (\d+)/);
+
+ const nodeVersionMap = {
+ '108': '18.x', '115': '20.x', '120': '21.x', '127': '22.x', '131': '23.x'
+ };
+
+ let versionInfo = '';
+ if (compiledMatch && requiredMatch) {
+ const compiled = nodeVersionMap[compiledMatch[1]] || `ABI ${compiledMatch[1]}`;
+ const required = nodeVersionMap[requiredMatch[1]] || `ABI ${requiredMatch[1]}`;
+ versionInfo = `\n║ Module compiled for Node.js ${compiled}, running Node.js ${required}`.padEnd(79) + '║';
+ }
+
+ console.warn(`
+╔══════════════════════════════════════════════════════════════════════════════╗
+║ Native Module Version Mismatch (NODE_MODULE_VERSION) ║
+╠══════════════════════════════════════════════════════════════════════════════╣
+║ ║
+║ The better-sqlite3 module was compiled for a different Node.js version. ║${versionInfo}
+║ ║
+║ Claude Flow will continue with JSON fallback storage (still works fine). ║
+║ ║
+║ To fix this and use SQLite: ║
+║ ║
+║ Option 1 - Rebuild the module: ║
+║ > npm rebuild better-sqlite3 ║
+║ ║
+║ Option 2 - Clear npx cache (if using npx): ║
+║ > rm -rf ~/.npm/_npx/ && npx claude-flow@alpha ... ║
+║ ║
+║ Option 3 - Reinstall dependencies: ║
+║ > rm -rf node_modules && npm install ║
+║ ║
+╚══════════════════════════════════════════════════════════════════════════════╝
+`);
+ return false;
+ }
+
+ // Check for other Windows/installation errors
+ if (requireErr.message?.includes('Could not locate the bindings file') ||
+ requireErr.message?.includes('The specified module could not be found') ||
requireErr.code === 'MODULE_NOT_FOUND') {
-
+
console.warn(`
╔══════════════════════════════════════════════════════════════════════════════╗
-║ Windows SQLite Installation Issue ║
+║ SQLite Native Module Installation Issue ║
╠══════════════════════════════════════════════════════════════════════════════╣
║ ║
║ The native SQLite module failed to load. This is common on Windows when ║
-║ using 'npx' or when node-gyp build tools are not available. ║
-║ ║
-║ Claude Flow will continue with in-memory storage (non-persistent). ║
+║ using 'npx' or when node-gyp build tools are not available. ║
║ ║
-║ To enable persistent storage on Windows: ║
+║ Claude Flow will continue with JSON fallback storage (still works fine). ║
║ ║
-║ Option 1 - Install Windows Build Tools: ║
-║ > npm install --global windows-build-tools ║
-║ > npm install claude-flow@alpha ║
+║ To enable SQLite storage: ║
║ ║
-║ Option 2 - Use Pre-built Binaries: ║
-║ > npm config set python python3 ║
-║ > npm install claude-flow@alpha --build-from-source=false ║
+║ Option 1 - Install Build Tools (Windows): ║
+║ > npm install --global windows-build-tools ║
+║ > npm install claude-flow@alpha ║
║ ║
-║ Option 3 - Use WSL (Windows Subsystem for Linux): ║
-║ Install WSL and run Claude Flow inside a Linux environment ║
+║ Option 2 - Use WSL (Windows Subsystem for Linux): ║
+║ Install WSL and run Claude Flow inside a Linux environment ║
║ ║
╚══════════════════════════════════════════════════════════════════════════════╝
`);
diff --git a/src/utils/error-recovery.ts b/src/utils/error-recovery.ts
index a8772d94fb..f966d0f98b 100644
--- a/src/utils/error-recovery.ts
+++ b/src/utils/error-recovery.ts
@@ -33,6 +33,52 @@ export function isNpmCacheError(error: any): boolean {
) || errorStr.includes('better-sqlite3');
}
+/**
+ * Detect if an error is a native module version mismatch (NODE_MODULE_VERSION)
+ * This happens when native modules are compiled for a different Node.js version
+ */
+export function isNativeModuleVersionError(error: any): boolean {
+ const errorStr = error?.message || String(error);
+ return (
+ errorStr.includes('NODE_MODULE_VERSION') ||
+ errorStr.includes('was compiled against a different Node.js version') ||
+ errorStr.includes('re-compiling or re-installing the module')
+ );
+}
+
+/**
+ * Get helpful message for native module version mismatch
+ */
+export function getNativeModuleRecoveryMessage(error: any): string {
+ const errorStr = error?.message || String(error);
+
+ // Extract version numbers if available
+ const compiledMatch = errorStr.match(/NODE_MODULE_VERSION (\d+)/);
+ const requiredMatch = errorStr.match(/requires\s+NODE_MODULE_VERSION (\d+)/);
+
+ let message = '⚠️ Native module version mismatch detected.\n';
+
+ if (compiledMatch && requiredMatch) {
+ const nodeVersionMap: Record<string, string> = {
+ '108': '18.x',
+ '115': '20.x',
+ '120': '21.x',
+ '127': '22.x',
+ '131': '23.x'
+ };
+ const compiled = nodeVersionMap[compiledMatch[1]] || `ABI ${compiledMatch[1]}`;
+ const required = nodeVersionMap[requiredMatch[1]] || `ABI ${requiredMatch[1]}`;
+ message += ` Module was compiled for Node.js ${compiled}, but running Node.js ${required}.\n`;
+ }
+
+ message += '\n To fix this, try one of:\n';
+ message += ' 1. npm rebuild better-sqlite3\n';
+ message += ' 2. rm -rf node_modules && npm install\n';
+ message += ' 3. npx cache: rm -rf ~/.npm/_npx/ && run command again\n';
+
+ return message;
+}
+
/**
* Detect if running on WSL (Windows Subsystem for Linux)
*/
@@ -315,6 +361,8 @@ export async function recoverInitErrors(error: any): Promise<RecoveryResult> {
*/
export const errorRecovery = {
isNpmCacheError,
+ isNativeModuleVersionError,
+ getNativeModuleRecoveryMessage,
isWSL,
cleanNpmCache,
retryWithRecovery,