claude-flow 2.7.46 → 2.7.47
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/claude-flow +1 -1
- package/dist/src/cli/help-formatter.js +5 -0
- package/dist/src/cli/simple-commands/hooks.js +14 -14
- package/dist/src/cli/simple-commands/hooks.js.map +1 -1
- package/dist/src/core/version.js +1 -1
- package/dist/src/utils/key-redactor.js.map +1 -1
- package/package.json +1 -1
- package/src/cli/simple-commands/hooks.js +14 -14
package/bin/claude-flow
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
# Claude-Flow Smart Dispatcher - Detects and uses the best available runtime
|
|
3
3
|
# Enhanced with NPX cache error handling and retry logic
|
|
4
4
|
|
|
5
|
-
VERSION="2.7.
|
|
5
|
+
VERSION="2.7.47"
|
|
6
6
|
|
|
7
7
|
# Determine the correct path based on how the script is invoked
|
|
8
8
|
if [ -L "$0" ]; then
|
|
@@ -160,7 +160,7 @@ async function preTaskCommand(subArgs, flags) {
|
|
|
160
160
|
}, {
|
|
161
161
|
namespace: 'hooks:ruv-swarm'
|
|
162
162
|
});
|
|
163
|
-
printSuccess(
|
|
163
|
+
printSuccess(`Pre-task hook completed successfully`);
|
|
164
164
|
}
|
|
165
165
|
}
|
|
166
166
|
} catch (err) {
|
|
@@ -291,7 +291,7 @@ async function preEditCommand(subArgs, flags) {
|
|
|
291
291
|
});
|
|
292
292
|
}
|
|
293
293
|
console.log(` 💾 Pre-edit state saved to .swarm/memory.db`);
|
|
294
|
-
printSuccess(
|
|
294
|
+
printSuccess(`Pre-edit hook completed`);
|
|
295
295
|
} catch (err) {
|
|
296
296
|
printError(`Pre-edit hook failed: ${err.message}`);
|
|
297
297
|
}
|
|
@@ -368,7 +368,7 @@ async function preBashCommand(subArgs, flags) {
|
|
|
368
368
|
});
|
|
369
369
|
console.log(` 💾 Command logged to .swarm/memory.db`);
|
|
370
370
|
console.log(` 🔒 Safety check: ${safetyResult.toUpperCase()}`);
|
|
371
|
-
printSuccess(
|
|
371
|
+
printSuccess(`Pre-bash hook completed`);
|
|
372
372
|
} catch (err) {
|
|
373
373
|
printError(`Pre-bash hook failed: ${err.message}`);
|
|
374
374
|
}
|
|
@@ -409,7 +409,7 @@ async function postTaskCommand(subArgs, flags) {
|
|
|
409
409
|
console.log(` 📊 Performance: ${metrics.durationHuman}`);
|
|
410
410
|
}
|
|
411
411
|
console.log(` 💾 Task completion saved to .swarm/memory.db`);
|
|
412
|
-
printSuccess(
|
|
412
|
+
printSuccess(`Post-task hook completed`);
|
|
413
413
|
} catch (err) {
|
|
414
414
|
printError(`Post-task hook failed: ${err.message}`);
|
|
415
415
|
}
|
|
@@ -566,7 +566,7 @@ async function postEditCommand(subArgs, flags) {
|
|
|
566
566
|
namespace: 'file-history'
|
|
567
567
|
});
|
|
568
568
|
console.log(` 💾 Post-edit data saved to .swarm/memory.db`);
|
|
569
|
-
printSuccess(
|
|
569
|
+
printSuccess(`Post-edit hook completed`);
|
|
570
570
|
} catch (err) {
|
|
571
571
|
printError(`Post-edit hook failed: ${err.message}`);
|
|
572
572
|
}
|
|
@@ -664,7 +664,7 @@ async function postBashCommand(subArgs, flags) {
|
|
|
664
664
|
namespace: 'command-history'
|
|
665
665
|
});
|
|
666
666
|
console.log(` 💾 Command execution logged to .swarm/memory.db`);
|
|
667
|
-
printSuccess(
|
|
667
|
+
printSuccess(`Post-bash hook completed`);
|
|
668
668
|
} catch (err) {
|
|
669
669
|
printError(`Post-bash hook failed: ${err.message}`);
|
|
670
670
|
}
|
|
@@ -701,7 +701,7 @@ async function postSearchCommand(subArgs, flags) {
|
|
|
701
701
|
ttl: 3600
|
|
702
702
|
});
|
|
703
703
|
console.log(` 💾 Search results cached to .swarm/memory.db`);
|
|
704
|
-
printSuccess(
|
|
704
|
+
printSuccess(`Post-search hook completed`);
|
|
705
705
|
} catch (err) {
|
|
706
706
|
printError(`Post-search hook failed: ${err.message}`);
|
|
707
707
|
}
|
|
@@ -729,7 +729,7 @@ async function mcpInitializedCommand(subArgs, flags) {
|
|
|
729
729
|
}
|
|
730
730
|
});
|
|
731
731
|
console.log(` 💾 MCP session saved to .swarm/memory.db`);
|
|
732
|
-
printSuccess(
|
|
732
|
+
printSuccess(`MCP initialized hook completed`);
|
|
733
733
|
} catch (err) {
|
|
734
734
|
printError(`MCP initialized hook failed: ${err.message}`);
|
|
735
735
|
}
|
|
@@ -766,7 +766,7 @@ async function agentSpawnedCommand(subArgs, flags) {
|
|
|
766
766
|
namespace: 'agent-roster'
|
|
767
767
|
});
|
|
768
768
|
console.log(` 💾 Agent registered to .swarm/memory.db`);
|
|
769
|
-
printSuccess(
|
|
769
|
+
printSuccess(`Agent spawned hook completed`);
|
|
770
770
|
} catch (err) {
|
|
771
771
|
printError(`Agent spawned hook failed: ${err.message}`);
|
|
772
772
|
}
|
|
@@ -796,7 +796,7 @@ async function taskOrchestratedCommand(subArgs, flags) {
|
|
|
796
796
|
}
|
|
797
797
|
});
|
|
798
798
|
console.log(` 💾 Orchestration saved to .swarm/memory.db`);
|
|
799
|
-
printSuccess(
|
|
799
|
+
printSuccess(`Task orchestrated hook completed`);
|
|
800
800
|
} catch (err) {
|
|
801
801
|
printError(`Task orchestrated hook failed: ${err.message}`);
|
|
802
802
|
}
|
|
@@ -825,7 +825,7 @@ async function neuralTrainedCommand(subArgs, flags) {
|
|
|
825
825
|
}
|
|
826
826
|
});
|
|
827
827
|
console.log(` 💾 Training results saved to .swarm/memory.db`);
|
|
828
|
-
printSuccess(
|
|
828
|
+
printSuccess(`Neural trained hook completed`);
|
|
829
829
|
} catch (err) {
|
|
830
830
|
printError(`Neural trained hook failed: ${err.message}`);
|
|
831
831
|
}
|
|
@@ -942,7 +942,7 @@ async function sessionEndCommand(subArgs, flags) {
|
|
|
942
942
|
memoryStore.close();
|
|
943
943
|
memoryStore = null;
|
|
944
944
|
}
|
|
945
|
-
printSuccess(
|
|
945
|
+
printSuccess(`Session-end hook completed`);
|
|
946
946
|
} catch (err) {
|
|
947
947
|
printError(`Session-end hook failed: ${err.message}`);
|
|
948
948
|
}
|
|
@@ -979,7 +979,7 @@ async function sessionRestoreCommand(subArgs, flags) {
|
|
|
979
979
|
namespace: 'session-events'
|
|
980
980
|
});
|
|
981
981
|
console.log(` 💾 Session restored from .swarm/memory.db`);
|
|
982
|
-
printSuccess(
|
|
982
|
+
printSuccess(`Session restore completed`);
|
|
983
983
|
} else {
|
|
984
984
|
printWarning(`No session found with ID: ${sessionId}`);
|
|
985
985
|
}
|
|
@@ -1016,7 +1016,7 @@ async function notifyCommand(subArgs, flags) {
|
|
|
1016
1016
|
console.log(` ${message}`);
|
|
1017
1017
|
console.log(` 🐝 Swarm: ${swarmStatus}`);
|
|
1018
1018
|
console.log(`\n 💾 Notification saved to .swarm/memory.db`);
|
|
1019
|
-
printSuccess(
|
|
1019
|
+
printSuccess(`Notify hook completed`);
|
|
1020
1020
|
} catch (err) {
|
|
1021
1021
|
printError(`Notify hook failed: ${err.message}`);
|
|
1022
1022
|
}
|
|
@@ -1 +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';\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 <noreply@ruv.io>`;\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,IAAIC,cAAc;AAClB,IAAIC,kBAAkB;AAEtB,eAAeC;IACb,IAAIF,aAAa,OAAOA;IAGxB,IAAIC,iBAAiB;QACnB,IAAI,CAACD,aAAa;YAChBA,cAAc,IAAID;YAClB,MAAMC,YAAYG,UAAU;QAC9B;QACA,OAAOH;IACT;IAEA,IAAI;QACFA,cAAc,IAAIF;QAClB,MAAME,YAAYG,UAAU;IAC9B,E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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"}
|
|
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';\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 <noreply@ruv.io>`;\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,IAAIC,cAAc;AAClB,IAAIC,kBAAkB;AAEtB,eAAeC;IACb,IAAIF,aAAa,OAAOA;IAGxB,IAAIC,iBAAiB;QACnB,IAAI,CAACD,aAAa;YAChBA,cAAc,IAAID;YAClB,MAAMC,YAAYG,UAAU;QAC9B;QACA,OAAOH;IACT;IAEA,IAAI;QACFA,cAAc,IAAIF;QAClB,MAAME,YAAYG,UAAU;IAC9B,EAAE,OAAOC,KAAK;QAEZ,MAAMC,sBACJD,IAAIE,OAAO,EAAEC,SAAS,0BACtBH,IAAIE,OAAO,EAAEC,SAAS,uDACtBH,IAAIE,OAAO,EAAEC,SAAS,qBACtBH,IAAIE,OAAO,EAAEC,SAAS;QAExB,IAAIF,qBAAqB;YACvBV,aAAa,CAAC,0EAA0E,CAAC;YACzFM,kBAAkB;YAClBD,cAAc,IAAID;YAClB,MAAMC,YAAYG,UAAU;QAC9B,OAAO;YACL,MAAMC;QACR;IACF;IAEA,OAAOJ;AACT;AAGA,SAASQ,WAAWC,SAAS,IAAI;IAC/B,OAAO,GAAGA,OAAO,CAAC,EAAEC,KAAKC,GAAG,GAAG,CAAC,EAAEC,KAAKC,MAAM,GAAGC,QAAQ,CAAC,IAAIC,MAAM,CAAC,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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;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,eAAe9B,YAAY"}
|
package/dist/src/core/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/utils/key-redactor.
|
|
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;QA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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"},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"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "claude-flow",
|
|
3
|
-
"version": "2.7.
|
|
3
|
+
"version": "2.7.47",
|
|
4
4
|
"description": "Enterprise-grade AI agent orchestration with WASM-powered ReasoningBank memory and AgentDB vector database (always uses latest agentic-flow)",
|
|
5
5
|
"mcpName": "io.github.ruvnet/claude-flow",
|
|
6
6
|
"main": "cli.mjs",
|
|
@@ -206,7 +206,7 @@ async function preTaskCommand(subArgs, flags) {
|
|
|
206
206
|
{ namespace: 'hooks:ruv-swarm' },
|
|
207
207
|
);
|
|
208
208
|
|
|
209
|
-
printSuccess(
|
|
209
|
+
printSuccess(`Pre-task hook completed successfully`);
|
|
210
210
|
}
|
|
211
211
|
}
|
|
212
212
|
} catch (err) {
|
|
@@ -361,7 +361,7 @@ async function preEditCommand(subArgs, flags) {
|
|
|
361
361
|
}
|
|
362
362
|
|
|
363
363
|
console.log(` 💾 Pre-edit state saved to .swarm/memory.db`);
|
|
364
|
-
printSuccess(
|
|
364
|
+
printSuccess(`Pre-edit hook completed`);
|
|
365
365
|
} catch (err) {
|
|
366
366
|
printError(`Pre-edit hook failed: ${err.message}`);
|
|
367
367
|
}
|
|
@@ -452,7 +452,7 @@ async function preBashCommand(subArgs, flags) {
|
|
|
452
452
|
|
|
453
453
|
console.log(` 💾 Command logged to .swarm/memory.db`);
|
|
454
454
|
console.log(` 🔒 Safety check: ${safetyResult.toUpperCase()}`);
|
|
455
|
-
printSuccess(
|
|
455
|
+
printSuccess(`Pre-bash hook completed`);
|
|
456
456
|
} catch (err) {
|
|
457
457
|
printError(`Pre-bash hook failed: ${err.message}`);
|
|
458
458
|
}
|
|
@@ -501,7 +501,7 @@ async function postTaskCommand(subArgs, flags) {
|
|
|
501
501
|
}
|
|
502
502
|
|
|
503
503
|
console.log(` 💾 Task completion saved to .swarm/memory.db`);
|
|
504
|
-
printSuccess(
|
|
504
|
+
printSuccess(`Post-task hook completed`);
|
|
505
505
|
} catch (err) {
|
|
506
506
|
printError(`Post-task hook failed: ${err.message}`);
|
|
507
507
|
}
|
|
@@ -681,7 +681,7 @@ async function postEditCommand(subArgs, flags) {
|
|
|
681
681
|
);
|
|
682
682
|
|
|
683
683
|
console.log(` 💾 Post-edit data saved to .swarm/memory.db`);
|
|
684
|
-
printSuccess(
|
|
684
|
+
printSuccess(`Post-edit hook completed`);
|
|
685
685
|
} catch (err) {
|
|
686
686
|
printError(`Post-edit hook failed: ${err.message}`);
|
|
687
687
|
}
|
|
@@ -802,7 +802,7 @@ async function postBashCommand(subArgs, flags) {
|
|
|
802
802
|
);
|
|
803
803
|
|
|
804
804
|
console.log(` 💾 Command execution logged to .swarm/memory.db`);
|
|
805
|
-
printSuccess(
|
|
805
|
+
printSuccess(`Post-bash hook completed`);
|
|
806
806
|
} catch (err) {
|
|
807
807
|
printError(`Post-bash hook failed: ${err.message}`);
|
|
808
808
|
}
|
|
@@ -844,7 +844,7 @@ async function postSearchCommand(subArgs, flags) {
|
|
|
844
844
|
); // 1 hour TTL
|
|
845
845
|
|
|
846
846
|
console.log(` 💾 Search results cached to .swarm/memory.db`);
|
|
847
|
-
printSuccess(
|
|
847
|
+
printSuccess(`Post-search hook completed`);
|
|
848
848
|
} catch (err) {
|
|
849
849
|
printError(`Post-search hook failed: ${err.message}`);
|
|
850
850
|
}
|
|
@@ -876,7 +876,7 @@ async function mcpInitializedCommand(subArgs, flags) {
|
|
|
876
876
|
});
|
|
877
877
|
|
|
878
878
|
console.log(` 💾 MCP session saved to .swarm/memory.db`);
|
|
879
|
-
printSuccess(
|
|
879
|
+
printSuccess(`MCP initialized hook completed`);
|
|
880
880
|
} catch (err) {
|
|
881
881
|
printError(`MCP initialized hook failed: ${err.message}`);
|
|
882
882
|
}
|
|
@@ -919,7 +919,7 @@ async function agentSpawnedCommand(subArgs, flags) {
|
|
|
919
919
|
);
|
|
920
920
|
|
|
921
921
|
console.log(` 💾 Agent registered to .swarm/memory.db`);
|
|
922
|
-
printSuccess(
|
|
922
|
+
printSuccess(`Agent spawned hook completed`);
|
|
923
923
|
} catch (err) {
|
|
924
924
|
printError(`Agent spawned hook failed: ${err.message}`);
|
|
925
925
|
}
|
|
@@ -951,7 +951,7 @@ async function taskOrchestratedCommand(subArgs, flags) {
|
|
|
951
951
|
});
|
|
952
952
|
|
|
953
953
|
console.log(` 💾 Orchestration saved to .swarm/memory.db`);
|
|
954
|
-
printSuccess(
|
|
954
|
+
printSuccess(`Task orchestrated hook completed`);
|
|
955
955
|
} catch (err) {
|
|
956
956
|
printError(`Task orchestrated hook failed: ${err.message}`);
|
|
957
957
|
}
|
|
@@ -982,7 +982,7 @@ async function neuralTrainedCommand(subArgs, flags) {
|
|
|
982
982
|
});
|
|
983
983
|
|
|
984
984
|
console.log(` 💾 Training results saved to .swarm/memory.db`);
|
|
985
|
-
printSuccess(
|
|
985
|
+
printSuccess(`Neural trained hook completed`);
|
|
986
986
|
} catch (err) {
|
|
987
987
|
printError(`Neural trained hook failed: ${err.message}`);
|
|
988
988
|
}
|
|
@@ -1106,7 +1106,7 @@ async function sessionEndCommand(subArgs, flags) {
|
|
|
1106
1106
|
memoryStore = null;
|
|
1107
1107
|
}
|
|
1108
1108
|
|
|
1109
|
-
printSuccess(
|
|
1109
|
+
printSuccess(`Session-end hook completed`);
|
|
1110
1110
|
} catch (err) {
|
|
1111
1111
|
printError(`Session-end hook failed: ${err.message}`);
|
|
1112
1112
|
}
|
|
@@ -1149,7 +1149,7 @@ async function sessionRestoreCommand(subArgs, flags) {
|
|
|
1149
1149
|
);
|
|
1150
1150
|
|
|
1151
1151
|
console.log(` 💾 Session restored from .swarm/memory.db`);
|
|
1152
|
-
printSuccess(
|
|
1152
|
+
printSuccess(`Session restore completed`);
|
|
1153
1153
|
} else {
|
|
1154
1154
|
printWarning(`No session found with ID: ${sessionId}`);
|
|
1155
1155
|
}
|
|
@@ -1190,7 +1190,7 @@ async function notifyCommand(subArgs, flags) {
|
|
|
1190
1190
|
console.log(` 🐝 Swarm: ${swarmStatus}`);
|
|
1191
1191
|
|
|
1192
1192
|
console.log(`\n 💾 Notification saved to .swarm/memory.db`);
|
|
1193
|
-
printSuccess(
|
|
1193
|
+
printSuccess(`Notify hook completed`);
|
|
1194
1194
|
} catch (err) {
|
|
1195
1195
|
printError(`Notify hook failed: ${err.message}`);
|
|
1196
1196
|
}
|