claude-flow 2.7.41 ā 2.7.43
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/simple-commands/config.js +0 -124
- package/dist/src/cli/simple-commands/config.js.map +1 -1
- package/dist/src/cli/simple-commands/hive-mind.js +42 -5
- package/dist/src/cli/simple-commands/hive-mind.js.map +1 -1
- package/dist/src/cli/simple-commands/hooks.js +21 -1
- package/dist/src/cli/simple-commands/hooks.js.map +1 -1
- package/dist/src/cli/validation-helper.js.map +1 -1
- package/dist/src/core/DatabaseManager.js +19 -2
- package/dist/src/core/DatabaseManager.js.map +1 -1
- package/dist/src/core/version.js +2 -2
- package/dist/src/core/version.js.map +1 -1
- package/dist/src/memory/sqlite-wrapper.js +52 -14
- package/dist/src/memory/sqlite-wrapper.js.map +1 -1
- package/dist/src/utils/error-recovery.js +29 -0
- package/dist/src/utils/error-recovery.js.map +1 -1
- package/package.json +1 -1
- package/src/cli/simple-commands/hive-mind.js +50 -5
- package/src/cli/simple-commands/hooks.js +31 -1
- package/src/core/DatabaseManager.ts +27 -2
- package/src/memory/sqlite-wrapper.js +63 -19
- package/src/utils/error-recovery.ts +48 -0
|
@@ -1,10 +1,30 @@
|
|
|
1
1
|
import { printSuccess, printError, printWarning, execRuvSwarmHook, checkRuvSwarmAvailable } from '../utils.js';
|
|
2
2
|
import { SqliteMemoryStore } from '../../memory/sqlite-store.js';
|
|
3
|
+
import { InMemoryStore } from '../../memory/in-memory-store.js';
|
|
3
4
|
let memoryStore = null;
|
|
5
|
+
let storeInitFailed = false;
|
|
4
6
|
async function getMemoryStore() {
|
|
5
|
-
if (
|
|
7
|
+
if (memoryStore) return memoryStore;
|
|
8
|
+
if (storeInitFailed) {
|
|
9
|
+
if (!memoryStore) {
|
|
10
|
+
memoryStore = new InMemoryStore();
|
|
11
|
+
await memoryStore.initialize();
|
|
12
|
+
}
|
|
13
|
+
return memoryStore;
|
|
14
|
+
}
|
|
15
|
+
try {
|
|
6
16
|
memoryStore = new SqliteMemoryStore();
|
|
7
17
|
await memoryStore.initialize();
|
|
18
|
+
} catch (err) {
|
|
19
|
+
const isNativeModuleError = err.message?.includes('NODE_MODULE_VERSION') || err.message?.includes('was compiled against a different Node.js version') || err.message?.includes('better-sqlite3') || err.message?.includes('SQLite is not available');
|
|
20
|
+
if (isNativeModuleError) {
|
|
21
|
+
printWarning(`SQLite unavailable, using in-memory storage for hooks (data won't persist)`);
|
|
22
|
+
storeInitFailed = true;
|
|
23
|
+
memoryStore = new InMemoryStore();
|
|
24
|
+
await memoryStore.initialize();
|
|
25
|
+
} else {
|
|
26
|
+
throw err;
|
|
27
|
+
}
|
|
8
28
|
}
|
|
9
29
|
return memoryStore;
|
|
10
30
|
}
|
|
@@ -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';\n\n// Initialize memory store\nlet memoryStore = null;\n\nasync function getMemoryStore() {\n if (!memoryStore) {\n memoryStore = new SqliteMemoryStore();\n await memoryStore.initialize();\n }\n return memoryStore;\n}\n\n// Simple ID generator\nfunction generateId(prefix = 'id') {\n return `${prefix}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n}\n\nexport async function hooksAction(subArgs, flags) {\n const subcommand = subArgs[0];\n const options = flags;\n\n if (options.help || options.h || !subcommand) {\n showHooksHelp();\n return;\n }\n\n try {\n switch (subcommand) {\n // Pre-Operation Hooks\n case 'pre-task':\n await preTaskCommand(subArgs, flags);\n break;\n case 'pre-edit':\n await preEditCommand(subArgs, flags);\n break;\n case 'pre-bash':\n case 'pre-command': // Support both names for compatibility\n await preBashCommand(subArgs, flags);\n break;\n\n // Post-Operation Hooks\n case 'post-task':\n await postTaskCommand(subArgs, flags);\n break;\n case 'post-edit':\n await postEditCommand(subArgs, flags);\n break;\n case 'post-bash':\n case 'post-command': // Support both names for compatibility\n await postBashCommand(subArgs, flags);\n break;\n case 'post-search':\n await postSearchCommand(subArgs, flags);\n break;\n\n // MCP Integration Hooks\n case 'mcp-initialized':\n await mcpInitializedCommand(subArgs, flags);\n break;\n case 'agent-spawned':\n await agentSpawnedCommand(subArgs, flags);\n break;\n case 'task-orchestrated':\n await taskOrchestratedCommand(subArgs, flags);\n break;\n case 'neural-trained':\n await neuralTrainedCommand(subArgs, flags);\n break;\n\n // Session Hooks\n case 'session-end':\n await sessionEndCommand(subArgs, flags);\n break;\n case 'session-restore':\n await sessionRestoreCommand(subArgs, flags);\n break;\n case 'notify':\n await notifyCommand(subArgs, flags);\n break;\n\n // NEW: PreToolUse Modification Hooks (v2.0.10+)\n case 'modify-bash':\n await modifyBashCommand(subArgs, flags);\n break;\n case 'modify-file':\n await modifyFileCommand(subArgs, flags);\n break;\n case 'modify-git-commit':\n await modifyGitCommitCommand(subArgs, flags);\n break;\n\n default:\n printError(`Unknown hooks command: ${subcommand}`);\n showHooksHelp();\n }\n } catch (err) {\n printError(`Hooks command failed: ${err.message}`);\n }\n}\n\n// ===== PRE-OPERATION HOOKS =====\n\nasync function preTaskCommand(subArgs, flags) {\n const options = flags;\n const description = options.description || 'Unnamed task';\n const taskId = options['task-id'] || options.taskId || generateId('task');\n const agentId = options['agent-id'] || options.agentId;\n const autoSpawnAgents = options['auto-spawn-agents'] !== 'false';\n\n console.log(`š Executing pre-task hook...`);\n console.log(`š Task: ${description}`);\n console.log(`š Task ID: ${taskId}`);\n if (agentId) console.log(`š¤ Agent: ${agentId}`);\n\n try {\n const store = await getMemoryStore();\n const taskData = {\n taskId,\n description,\n agentId,\n autoSpawnAgents,\n status: 'started',\n startedAt: new Date().toISOString(),\n };\n\n await store.store(`task:${taskId}`, taskData, {\n namespace: 'hooks:pre-task',\n metadata: { hookType: 'pre-task', agentId },\n });\n\n await store.store(\n `task-index:${Date.now()}`,\n {\n taskId,\n description,\n timestamp: new Date().toISOString(),\n },\n { namespace: 'task-index' },\n );\n\n console.log(` š¾ Saved to .swarm/memory.db`);\n\n // Execute ruv-swarm hook if available (with timeout for npx scenarios)\n try {\n const checkPromise = checkRuvSwarmAvailable();\n const timeoutPromise = new Promise((_, reject) => \n setTimeout(() => reject(new Error('Timeout')), 3000)\n );\n \n const isAvailable = await Promise.race([checkPromise, timeoutPromise]);\n \n if (isAvailable) {\n console.log(`\\nš Executing ruv-swarm pre-task hook...`);\n const hookResult = await execRuvSwarmHook('pre-task', {\n description,\n 'task-id': taskId,\n 'auto-spawn-agents': autoSpawnAgents,\n ...(agentId ? { 'agent-id': agentId } : {}),\n });\n\n if (hookResult.success) {\n await store.store(\n `task:${taskId}:ruv-output`,\n {\n output: hookResult.output,\n timestamp: new Date().toISOString(),\n },\n { namespace: 'hooks:ruv-swarm' },\n );\n\n printSuccess(`ā
Pre-task hook completed successfully`);\n }\n }\n } catch (err) {\n // Skip ruv-swarm hook if it times out or fails\n console.log(`\\nā ļø Skipping ruv-swarm hook (${err.message})`);\n }\n\n console.log(`\\nšÆ TASK PREPARATION COMPLETE`);\n \n // Close the memory store to prevent hanging\n if (memoryStore && memoryStore.close) {\n memoryStore.close();\n }\n \n // Force exit after a short delay to ensure cleanup\n setTimeout(() => {\n process.exit(0);\n }, 100);\n } catch (err) {\n printError(`Pre-task hook failed: ${err.message}`);\n \n // Close the memory store on error too\n if (memoryStore && memoryStore.close) {\n memoryStore.close();\n }\n \n // Force exit after a short delay to ensure cleanup\n setTimeout(() => {\n process.exit(1);\n }, 100);\n }\n}\n\nasync function preEditCommand(subArgs, flags) {\n const options = flags;\n const file = options.file || 'unknown-file';\n const operation = options.operation || 'edit';\n const autoAssignAgents = options['auto-assign-agents'] || false;\n const loadContext = options['load-context'] || false;\n\n console.log(`š Executing pre-edit hook...`);\n console.log(`š File: ${file}`);\n console.log(`āļø Operation: ${operation}`);\n if (autoAssignAgents) console.log(`š¤ Auto-assign agents: ENABLED`);\n if (loadContext) console.log(`š Load context: ENABLED`);\n\n try {\n const store = await getMemoryStore();\n\n // Auto-assign agents based on file type\n let assignedAgentType = 'general';\n let recommendedAgent = null;\n\n if (autoAssignAgents) {\n const path = await import('path');\n const ext = path.extname(file).toLowerCase();\n\n const agentMapping = {\n '.js': 'javascript-developer',\n '.ts': 'typescript-developer',\n '.py': 'python-developer',\n '.go': 'golang-developer',\n '.rs': 'rust-developer',\n '.java': 'java-developer',\n '.cpp': 'cpp-developer',\n '.c': 'c-developer',\n '.css': 'frontend-developer',\n '.html': 'frontend-developer',\n '.vue': 'frontend-developer',\n '.react': 'frontend-developer',\n '.md': 'technical-writer',\n '.yml': 'devops-engineer',\n '.yaml': 'devops-engineer',\n '.json': 'config-specialist',\n '.sql': 'database-expert',\n '.sh': 'system-admin',\n '.dockerfile': 'devops-engineer',\n };\n\n assignedAgentType = agentMapping[ext] || 'general-developer';\n recommendedAgent = {\n type: assignedAgentType,\n file: file,\n extension: ext,\n recommended: true,\n };\n\n console.log(` š¤ Recommended agent: ${assignedAgentType}`);\n }\n\n // Load context if requested\n let contextData = null;\n if (loadContext) {\n try {\n // Check if file exists and get basic info\n const fs = await import('fs');\n const path = await import('path');\n\n if (fs.existsSync(file)) {\n const stats = fs.statSync(file);\n const dirname = path.dirname(file);\n const basename = path.basename(file);\n\n contextData = {\n fileExists: true,\n size: stats.size,\n modified: stats.mtime,\n directory: dirname,\n filename: basename,\n isDirectory: stats.isDirectory(),\n };\n\n console.log(` š Context loaded: ${basename} (${stats.size} bytes)`);\n } else {\n contextData = {\n fileExists: false,\n willCreate: true,\n directory: path.dirname(file),\n filename: path.basename(file),\n };\n console.log(` š Context: New file will be created`);\n }\n } catch (err) {\n console.log(` ā ļø Warning: Could not load context for ${file}`);\n contextData = { error: err.message };\n }\n }\n\n const editData = {\n file,\n operation,\n timestamp: new Date().toISOString(),\n editId: generateId('edit'),\n autoAssignAgents,\n loadContext,\n assignedAgentType,\n recommendedAgent,\n contextData,\n };\n\n await store.store(`edit:${editData.editId}:pre`, editData, {\n namespace: 'hooks:pre-edit',\n metadata: { hookType: 'pre-edit', file, agentType: assignedAgentType },\n });\n\n // Store agent recommendation if enabled\n if (autoAssignAgents && recommendedAgent) {\n await store.store(`agent-recommendation:${file}`, recommendedAgent, {\n namespace: 'agent-assignments',\n ttl: 3600, // 1 hour\n });\n }\n\n console.log(` š¾ Pre-edit state saved to .swarm/memory.db`);\n printSuccess(`ā
Pre-edit hook completed`);\n } catch (err) {\n printError(`Pre-edit hook failed: ${err.message}`);\n }\n}\n\nasync function preBashCommand(subArgs, flags) {\n const options = flags;\n const command = options.command || subArgs.slice(1).join(' ') || '';\n const workingDir = options.cwd || process.cwd();\n const validateSafety = options['validate-safety'] === true || options['validate-safety'] === 'true' || options.validate === true || options.validate === 'true' || false;\n const prepareResources = options['prepare-resources'] === true || options['prepare-resources'] === 'true' || false;\n\n console.log(`š§ Executing pre-bash hook...`);\n console.log(`š Command: ${command}`);\n console.log(`š Working dir: ${workingDir}`);\n if (validateSafety) console.log(`š Safety validation: ENABLED`);\n if (prepareResources) console.log(`š ļø Resource preparation: ENABLED`);\n\n try {\n const store = await getMemoryStore();\n let safetyResult = 'skipped';\n\n if (validateSafety) {\n // Basic safety validation\n const dangerousCommands = [\n 'rm -rf /',\n 'rm -rf .',\n 'rm -rf *',\n 'format',\n 'fdisk',\n 'mkfs',\n 'curl * | bash',\n 'wget * | sh',\n 'eval',\n 'exec',\n 'chmod 777',\n ];\n\n const isDangerous = command && typeof command === 'string' && command.length > 0 \n ? dangerousCommands.some((dangerous) =>\n command.toLowerCase().includes(dangerous.toLowerCase()),\n )\n : false;\n\n safetyResult = isDangerous ? 'dangerous' : 'safe';\n\n if (isDangerous) {\n console.log(` ā ļø Safety check: DANGEROUS COMMAND DETECTED`);\n console.log(` š« Command blocked for safety`);\n printError(`Command blocked due to safety validation: ${command}`);\n return;\n }\n }\n\n if (prepareResources) {\n // Resource preparation - create working directory if needed\n const fs = await import('fs');\n const path = await import('path');\n\n if (!fs.existsSync(workingDir)) {\n fs.mkdirSync(workingDir, { recursive: true });\n console.log(` š Created working directory: ${workingDir}`);\n }\n\n // Check available disk space\n try {\n const stats = fs.statSync(workingDir);\n console.log(` š¾ Working directory prepared`);\n } catch (err) {\n console.log(` ā ļø Warning: Could not check working directory`);\n }\n }\n\n const bashData = {\n command,\n workingDir,\n timestamp: new Date().toISOString(),\n bashId: generateId('bash'),\n safety: safetyResult,\n validationEnabled: validateSafety,\n resourcesPrepped: prepareResources,\n };\n\n await store.store(`bash:${bashData.bashId}:pre`, bashData, {\n namespace: 'hooks:pre-bash',\n metadata: { hookType: 'pre-bash', command, safety: safetyResult },\n });\n\n console.log(` š¾ Command logged to .swarm/memory.db`);\n console.log(` š Safety check: ${safetyResult.toUpperCase()}`);\n printSuccess(`ā
Pre-bash hook completed`);\n } catch (err) {\n printError(`Pre-bash hook failed: ${err.message}`);\n }\n}\n\n// ===== POST-OPERATION HOOKS =====\n\nasync function postTaskCommand(subArgs, flags) {\n const options = flags;\n const taskId = options['task-id'] || options.taskId || generateId('task');\n const analyzePerformance = options['analyze-performance'] !== 'false';\n\n console.log(`š Executing post-task hook...`);\n console.log(`š Task ID: ${taskId}`);\n\n try {\n const store = await getMemoryStore();\n const taskData = await store.retrieve(`task:${taskId}`, {\n namespace: 'hooks:pre-task',\n });\n\n const completedData = {\n ...(taskData || {}),\n status: 'completed',\n completedAt: new Date().toISOString(),\n duration: taskData ? Date.now() - new Date(taskData.startedAt).getTime() : null,\n };\n\n await store.store(`task:${taskId}:completed`, completedData, {\n namespace: 'hooks:post-task',\n metadata: { hookType: 'post-task' },\n });\n\n if (analyzePerformance && completedData.duration) {\n const metrics = {\n taskId,\n duration: completedData.duration,\n durationHuman: `${(completedData.duration / 1000).toFixed(2)}s`,\n timestamp: new Date().toISOString(),\n };\n\n await store.store(`metrics:${taskId}`, metrics, {\n namespace: 'performance',\n });\n console.log(` š Performance: ${metrics.durationHuman}`);\n }\n\n console.log(` š¾ Task completion saved to .swarm/memory.db`);\n printSuccess(`ā
Post-task hook completed`);\n } catch (err) {\n printError(`Post-task hook failed: ${err.message}`);\n }\n}\n\nasync function postEditCommand(subArgs, flags) {\n const options = flags;\n const file = options.file || 'unknown-file';\n let memoryKey = options['memory-key'] || options.memoryKey;\n \n // Handle case where memory-key is passed as a boolean flag without value\n if (memoryKey === true) {\n // Generate a default memory key based on the file path and timestamp\n const path = await import('path');\n const basename = path.basename(file);\n memoryKey = `edit:${basename}:${Date.now()}`;\n }\n \n const format = options.format || false;\n const updateMemory = options['update-memory'] || false;\n const trainNeural = options['train-neural'] || false;\n\n console.log(`š Executing post-edit hook...`);\n console.log(`š File: ${file}`);\n if (memoryKey) console.log(`š¾ Memory key: ${memoryKey}`);\n if (format) console.log(`šØ Auto-format: ENABLED`);\n if (updateMemory) console.log(`š§ Memory update: ENABLED`);\n if (trainNeural) console.log(`š¤ Neural training: ENABLED`);\n\n try {\n const store = await getMemoryStore();\n const path = await import('path');\n const fs = await import('fs');\n\n // Auto-format file if requested\n let formatResult = null;\n if (format && fs.existsSync(file)) {\n const ext = path.extname(file).toLowerCase();\n const formatters = {\n '.js': 'prettier',\n '.ts': 'prettier',\n '.json': 'prettier',\n '.css': 'prettier',\n '.html': 'prettier',\n '.py': 'black',\n '.go': 'gofmt',\n '.rs': 'rustfmt',\n '.java': 'google-java-format',\n '.cpp': 'clang-format',\n '.c': 'clang-format',\n };\n\n const formatter = formatters[ext];\n if (formatter) {\n console.log(` šØ Auto-formatting with ${formatter}...`);\n formatResult = {\n formatter,\n extension: ext,\n attempted: true,\n timestamp: new Date().toISOString(),\n };\n } else {\n console.log(` ā ļø No formatter available for ${ext}`);\n formatResult = {\n extension: ext,\n attempted: false,\n reason: 'No formatter available',\n };\n }\n }\n\n // Update memory with edit context\n let memoryUpdate = null;\n if (updateMemory) {\n const editContext = {\n file,\n editedAt: new Date().toISOString(),\n editId: generateId('edit'),\n formatted: formatResult?.attempted || false,\n fileSize: fs.existsSync(file) ? fs.statSync(file).size : 0,\n directory: path.dirname(file),\n basename: path.basename(file),\n };\n\n memoryUpdate = editContext;\n\n // Store in coordination namespace\n await store.store(`edit-context:${editContext.editId}`, editContext, {\n namespace: 'coordination',\n metadata: { type: 'edit-context', file },\n });\n\n console.log(` š§ Edit context stored in memory`);\n }\n\n // Train neural patterns if requested\n let neuralTraining = null;\n if (trainNeural) {\n // Simulate neural training with file patterns\n const ext = path.extname(file).toLowerCase();\n const basename = path.basename(file);\n const editTime = new Date().toISOString();\n\n const patterns = {\n fileType: ext,\n fileName: basename,\n editTime,\n confidence: Math.random() * 0.5 + 0.5, // 50-100% confidence\n patterns: [\n `${ext}_edit_pattern`,\n `${basename}_modification`,\n `edit_${Date.now()}_sequence`,\n ],\n };\n\n neuralTraining = patterns;\n\n await store.store(`neural-pattern:${generateId('pattern')}`, patterns, {\n namespace: 'neural-training',\n metadata: { type: 'edit-pattern', file, extension: ext },\n });\n\n console.log(\n ` š¤ Neural patterns trained (${(patterns.confidence * 100).toFixed(1)}% confidence)`,\n );\n }\n\n const editData = {\n file,\n memoryKey,\n timestamp: new Date().toISOString(),\n editId: generateId('edit'),\n format,\n updateMemory,\n trainNeural,\n formatResult,\n memoryUpdate,\n neuralTraining,\n };\n\n await store.store(`edit:${editData.editId}:post`, editData, {\n namespace: 'hooks:post-edit',\n metadata: { hookType: 'post-edit', file, formatted: formatResult?.attempted || false },\n });\n\n if (memoryKey && typeof memoryKey === 'string') {\n await store.store(\n memoryKey,\n {\n file,\n editedAt: new Date().toISOString(),\n editId: editData.editId,\n enhanced: true,\n formatResult,\n memoryUpdate,\n neuralTraining,\n },\n { namespace: 'coordination' },\n );\n }\n\n const historyKey = `file-history:${file.replace(/\\//g, '_')}:${Date.now()}`;\n await store.store(\n historyKey,\n {\n file,\n editId: editData.editId,\n timestamp: new Date().toISOString(),\n enhanced: true,\n features: {\n format,\n updateMemory,\n trainNeural,\n },\n },\n { namespace: 'file-history' },\n );\n\n console.log(` š¾ Post-edit data saved to .swarm/memory.db`);\n printSuccess(`ā
Post-edit hook completed`);\n } catch (err) {\n printError(`Post-edit hook failed: ${err.message}`);\n }\n}\n\nasync function postBashCommand(subArgs, flags) {\n const options = flags;\n const command = options.command || subArgs.slice(1).join(' ');\n const exitCode = options['exit-code'] || '0';\n const output = options.output || '';\n const trackMetrics = options['track-metrics'] || false;\n const storeResults = options['store-results'] || false;\n const duration = options.duration || 0;\n\n console.log(`š§ Executing post-bash hook...`);\n console.log(`š Command: ${command}`);\n console.log(`š Exit code: ${exitCode}`);\n if (trackMetrics) console.log(`š Metrics tracking: ENABLED`);\n if (storeResults) console.log(`š¾ Results storage: ENABLED`);\n\n try {\n const store = await getMemoryStore();\n const startTime = Date.now();\n\n // Calculate performance metrics if enabled\n let metrics = null;\n if (trackMetrics) {\n const commandLength = command.length;\n const outputLength = output.length;\n const success = parseInt(exitCode) === 0;\n\n metrics = {\n commandLength,\n outputLength,\n success,\n duration: parseInt(duration) || 0,\n exitCode: parseInt(exitCode),\n timestamp: new Date().toISOString(),\n complexity: commandLength > 100 ? 'high' : commandLength > 50 ? 'medium' : 'low',\n };\n\n console.log(\n ` š Command metrics: ${commandLength} chars, ${outputLength} output, ${success ? 'SUCCESS' : 'FAILED'}`,\n );\n }\n\n const bashData = {\n command,\n exitCode,\n output: storeResults ? output.substring(0, 5000) : output.substring(0, 1000), // Store more if requested\n timestamp: new Date().toISOString(),\n bashId: generateId('bash'),\n trackMetrics,\n storeResults,\n metrics,\n };\n\n await store.store(`bash:${bashData.bashId}:post`, bashData, {\n namespace: 'hooks:post-bash',\n metadata: { hookType: 'post-bash', command, exitCode, success: parseInt(exitCode) === 0 },\n });\n\n // Store detailed results if enabled\n if (storeResults) {\n await store.store(\n `command-results:${bashData.bashId}`,\n {\n command,\n exitCode,\n output,\n timestamp: new Date().toISOString(),\n fullOutput: true,\n },\n { namespace: 'command-results' },\n );\n\n console.log(` š¾ Full command results stored`);\n }\n\n // Store metrics if enabled\n if (trackMetrics && metrics) {\n await store.store(`command-metrics:${bashData.bashId}`, metrics, {\n namespace: 'performance-metrics',\n });\n\n // Update running metrics\n const existingMetrics = (await store.retrieve('command-metrics-summary', {\n namespace: 'performance-metrics',\n })) || { totalCommands: 0, successRate: 0, avgDuration: 0 };\n\n existingMetrics.totalCommands += 1;\n existingMetrics.successRate =\n (existingMetrics.successRate * (existingMetrics.totalCommands - 1) +\n (metrics.success ? 1 : 0)) /\n existingMetrics.totalCommands;\n existingMetrics.avgDuration =\n (existingMetrics.avgDuration * (existingMetrics.totalCommands - 1) + metrics.duration) /\n existingMetrics.totalCommands;\n existingMetrics.lastUpdated = new Date().toISOString();\n\n await store.store('command-metrics-summary', existingMetrics, {\n namespace: 'performance-metrics',\n });\n }\n\n // Update command history\n await store.store(\n `command-history:${Date.now()}`,\n {\n command,\n exitCode,\n timestamp: new Date().toISOString(),\n success: parseInt(exitCode) === 0,\n hasMetrics: trackMetrics,\n hasResults: storeResults,\n },\n { namespace: 'command-history' },\n );\n\n console.log(` š¾ Command execution logged to .swarm/memory.db`);\n printSuccess(`ā
Post-bash hook completed`);\n } catch (err) {\n printError(`Post-bash hook failed: ${err.message}`);\n }\n}\n\nasync function postSearchCommand(subArgs, flags) {\n const options = flags;\n const query = options.query || subArgs.slice(1).join(' ');\n const resultCount = options['result-count'] || '0';\n const searchType = options.type || 'general';\n\n console.log(`š Executing post-search hook...`);\n console.log(`š Query: ${query}`);\n console.log(`š Results: ${resultCount}`);\n\n try {\n const store = await getMemoryStore();\n const searchData = {\n query,\n resultCount: parseInt(resultCount),\n searchType,\n timestamp: new Date().toISOString(),\n searchId: generateId('search'),\n };\n\n await store.store(`search:${searchData.searchId}`, searchData, {\n namespace: 'hooks:post-search',\n metadata: { hookType: 'post-search', query },\n });\n\n // Cache search for future use\n await store.store(\n `search-cache:${query}`,\n {\n resultCount: searchData.resultCount,\n cachedAt: new Date().toISOString(),\n },\n { namespace: 'search-cache', ttl: 3600 },\n ); // 1 hour TTL\n\n console.log(` š¾ Search results cached to .swarm/memory.db`);\n printSuccess(`ā
Post-search hook completed`);\n } catch (err) {\n printError(`Post-search hook failed: ${err.message}`);\n }\n}\n\n// ===== MCP INTEGRATION HOOKS =====\n\nasync function mcpInitializedCommand(subArgs, flags) {\n const options = flags;\n const serverName = options.server || 'claude-flow';\n const sessionId = options['session-id'] || generateId('mcp-session');\n\n console.log(`š Executing mcp-initialized hook...`);\n console.log(`š» Server: ${serverName}`);\n console.log(`š Session: ${sessionId}`);\n\n try {\n const store = await getMemoryStore();\n const mcpData = {\n serverName,\n sessionId,\n initializedAt: new Date().toISOString(),\n status: 'active',\n };\n\n await store.store(`mcp:${sessionId}`, mcpData, {\n namespace: 'hooks:mcp-initialized',\n metadata: { hookType: 'mcp-initialized', server: serverName },\n });\n\n console.log(` š¾ MCP session saved to .swarm/memory.db`);\n printSuccess(`ā
MCP initialized hook completed`);\n } catch (err) {\n printError(`MCP initialized hook failed: ${err.message}`);\n }\n}\n\nasync function agentSpawnedCommand(subArgs, flags) {\n const options = flags;\n const agentType = options.type || 'generic';\n const agentName = options.name || generateId('agent');\n const swarmId = options['swarm-id'] || 'default';\n\n console.log(`š¤ Executing agent-spawned hook...`);\n console.log(`š Agent: ${agentName}`);\n console.log(`š·ļø Type: ${agentType}`);\n\n try {\n const store = await getMemoryStore();\n const agentData = {\n agentName,\n agentType,\n swarmId,\n spawnedAt: new Date().toISOString(),\n status: 'active',\n };\n\n await store.store(`agent:${agentName}`, agentData, {\n namespace: 'hooks:agent-spawned',\n metadata: { hookType: 'agent-spawned', type: agentType },\n });\n\n // Update agent roster\n await store.store(\n `agent-roster:${Date.now()}`,\n {\n agentName,\n action: 'spawned',\n timestamp: new Date().toISOString(),\n },\n { namespace: 'agent-roster' },\n );\n\n console.log(` š¾ Agent registered to .swarm/memory.db`);\n printSuccess(`ā
Agent spawned hook completed`);\n } catch (err) {\n printError(`Agent spawned hook failed: ${err.message}`);\n }\n}\n\nasync function taskOrchestratedCommand(subArgs, flags) {\n const options = flags;\n const taskId = options['task-id'] || generateId('orchestrated-task');\n const strategy = options.strategy || 'balanced';\n const priority = options.priority || 'medium';\n\n console.log(`š Executing task-orchestrated hook...`);\n console.log(`š Task: ${taskId}`);\n console.log(`š Strategy: ${strategy}`);\n\n try {\n const store = await getMemoryStore();\n const orchestrationData = {\n taskId,\n strategy,\n priority,\n orchestratedAt: new Date().toISOString(),\n status: 'orchestrated',\n };\n\n await store.store(`orchestration:${taskId}`, orchestrationData, {\n namespace: 'hooks:task-orchestrated',\n metadata: { hookType: 'task-orchestrated', strategy },\n });\n\n console.log(` š¾ Orchestration saved to .swarm/memory.db`);\n printSuccess(`ā
Task orchestrated hook completed`);\n } catch (err) {\n printError(`Task orchestrated hook failed: ${err.message}`);\n }\n}\n\nasync function neuralTrainedCommand(subArgs, flags) {\n const options = flags;\n const modelName = options.model || 'default-neural';\n const accuracy = options.accuracy || '0.0';\n const patterns = options.patterns || '0';\n\n console.log(`š§ Executing neural-trained hook...`);\n console.log(`š¤ Model: ${modelName}`);\n console.log(`š Accuracy: ${accuracy}%`);\n\n try {\n const store = await getMemoryStore();\n const trainingData = {\n modelName,\n accuracy: parseFloat(accuracy),\n patternsLearned: parseInt(patterns),\n trainedAt: new Date().toISOString(),\n };\n\n await store.store(`neural:${modelName}:${Date.now()}`, trainingData, {\n namespace: 'hooks:neural-trained',\n metadata: { hookType: 'neural-trained', model: modelName },\n });\n\n console.log(` š¾ Training results saved to .swarm/memory.db`);\n printSuccess(`ā
Neural trained hook completed`);\n } catch (err) {\n printError(`Neural trained hook failed: ${err.message}`);\n }\n}\n\n// ===== SESSION HOOKS =====\n\nasync function sessionEndCommand(subArgs, flags) {\n const options = flags;\n const generateSummary = options['generate-summary'] !== 'false';\n const persistState = options['persist-state'] !== 'false';\n const exportMetrics = options['export-metrics'] || false;\n\n console.log(`š Executing session-end hook...`);\n if (generateSummary) console.log(`š Summary generation: ENABLED`);\n if (persistState) console.log(`š¾ State persistence: ENABLED`);\n if (exportMetrics) console.log(`š Metrics export: ENABLED`);\n\n try {\n const store = await getMemoryStore();\n const tasks = await store.list({ namespace: 'task-index', limit: 1000 });\n const edits = await store.list({ namespace: 'file-history', limit: 1000 });\n const commands = await store.list({ namespace: 'command-history', limit: 1000 });\n const agents = await store.list({ namespace: 'agent-roster', limit: 1000 });\n\n // Calculate session metrics\n let metrics = null;\n if (exportMetrics) {\n const now = new Date();\n const sessionStart = Math.min(\n ...tasks.map((t) => new Date(t.value.timestamp || now).getTime()),\n ...edits.map((e) => new Date(e.value.timestamp || now).getTime()),\n ...commands.map((c) => new Date(c.value.timestamp || now).getTime()),\n );\n\n const duration = now.getTime() - sessionStart;\n const successfulCommands = commands.filter((c) => c.value.success !== false).length;\n const commandSuccessRate = commands.length > 0 ? successfulCommands / commands.length : 1;\n\n metrics = {\n sessionDuration: duration,\n sessionDurationHuman: `${Math.round(duration / 1000 / 60)} minutes`,\n totalTasks: tasks.length,\n totalEdits: edits.length,\n totalCommands: commands.length,\n uniqueAgents: agents.length,\n commandSuccessRate: Math.round(commandSuccessRate * 100),\n avgTasksPerMinute: Math.round((tasks.length / (duration / 1000 / 60)) * 100) / 100,\n avgEditsPerMinute: Math.round((edits.length / (duration / 1000 / 60)) * 100) / 100,\n timestamp: now.toISOString(),\n };\n }\n\n const sessionData = {\n endedAt: new Date().toISOString(),\n totalTasks: tasks.length,\n totalEdits: edits.length,\n totalCommands: commands.length,\n uniqueAgents: agents.length,\n sessionId: generateId('session'),\n generateSummary,\n persistState,\n exportMetrics,\n metrics,\n };\n\n await store.store(`session:${sessionData.sessionId}`, sessionData, {\n namespace: 'sessions',\n metadata: { hookType: 'session-end' },\n });\n\n // Persist detailed state if requested\n if (persistState) {\n const detailedState = {\n sessionId: sessionData.sessionId,\n tasks: tasks.slice(0, 100), // Limit to prevent memory issues\n edits: edits.slice(0, 100),\n commands: commands.slice(0, 100),\n agents: agents.slice(0, 50),\n persistedAt: new Date().toISOString(),\n fullState: true,\n };\n\n await store.store(`session-state:${sessionData.sessionId}`, detailedState, {\n namespace: 'session-states',\n metadata: { type: 'full-state', sessionId: sessionData.sessionId },\n });\n\n console.log(` š¾ Full session state persisted`);\n }\n\n // Export metrics if requested\n if (exportMetrics && metrics) {\n await store.store(`session-metrics:${sessionData.sessionId}`, metrics, {\n namespace: 'session-metrics',\n metadata: { type: 'performance-metrics', sessionId: sessionData.sessionId },\n });\n\n console.log(` š Session metrics exported`);\n }\n\n if (generateSummary) {\n console.log(`\\nš SESSION SUMMARY:`);\n console.log(` š Tasks: ${sessionData.totalTasks}`);\n console.log(` āļø Edits: ${sessionData.totalEdits}`);\n console.log(` š§ Commands: ${sessionData.totalCommands}`);\n console.log(` š¤ Agents: ${sessionData.uniqueAgents}`);\n\n if (metrics) {\n console.log(` ā±ļø Duration: ${metrics.sessionDurationHuman}`);\n console.log(` š Success Rate: ${metrics.commandSuccessRate}%`);\n console.log(` š Tasks/min: ${metrics.avgTasksPerMinute}`);\n console.log(` āļø Edits/min: ${metrics.avgEditsPerMinute}`);\n }\n }\n\n console.log(` š¾ Session saved to .swarm/memory.db`);\n\n if (memoryStore) {\n memoryStore.close();\n memoryStore = null;\n }\n\n printSuccess(`ā
Session-end hook completed`);\n } catch (err) {\n printError(`Session-end hook failed: ${err.message}`);\n }\n}\n\nasync function sessionRestoreCommand(subArgs, flags) {\n const options = flags;\n const sessionId = options['session-id'] || 'latest';\n\n console.log(`š Executing session-restore hook...`);\n console.log(`š Session: ${sessionId}`);\n\n try {\n const store = await getMemoryStore();\n\n // Find session to restore\n let sessionData;\n if (sessionId === 'latest') {\n const sessions = await store.list({ namespace: 'sessions', limit: 1 });\n sessionData = sessions[0]?.value;\n } else {\n sessionData = await store.retrieve(`session:${sessionId}`, { namespace: 'sessions' });\n }\n\n if (sessionData) {\n console.log(`\\nš RESTORED SESSION:`);\n console.log(` š ID: ${sessionData.sessionId || 'unknown'}`);\n console.log(` š Tasks: ${sessionData.totalTasks || 0}`);\n console.log(` āļø Edits: ${sessionData.totalEdits || 0}`);\n console.log(` ā° Ended: ${sessionData.endedAt || 'unknown'}`);\n\n // Store restoration event\n await store.store(\n `session-restore:${Date.now()}`,\n {\n restoredSessionId: sessionData.sessionId || sessionId,\n restoredAt: new Date().toISOString(),\n },\n { namespace: 'session-events' },\n );\n\n console.log(` š¾ Session restored from .swarm/memory.db`);\n printSuccess(`ā
Session restore completed`);\n } else {\n printWarning(`No session found with ID: ${sessionId}`);\n }\n } catch (err) {\n printError(`Session restore hook failed: ${err.message}`);\n }\n}\n\nasync function notifyCommand(subArgs, flags) {\n const options = flags;\n const message = options.message || subArgs.slice(1).join(' ');\n const level = options.level || 'info';\n const swarmStatus = options['swarm-status'] || 'active';\n\n console.log(`š¢ Executing notify hook...`);\n console.log(`š¬ Message: ${message}`);\n console.log(`š Level: ${level}`);\n\n try {\n const store = await getMemoryStore();\n const notificationData = {\n message,\n level,\n swarmStatus,\n timestamp: new Date().toISOString(),\n notifyId: generateId('notify'),\n };\n\n await store.store(`notification:${notificationData.notifyId}`, notificationData, {\n namespace: 'hooks:notify',\n metadata: { hookType: 'notify', level },\n });\n\n // Display notification\n const icon = level === 'error' ? 'ā' : level === 'warning' ? 'ā ļø' : 'ā
';\n console.log(`\\n${icon} NOTIFICATION:`);\n console.log(` ${message}`);\n console.log(` š Swarm: ${swarmStatus}`);\n\n console.log(`\\n š¾ Notification saved to .swarm/memory.db`);\n printSuccess(`ā
Notify hook completed`);\n } catch (err) {\n printError(`Notify hook failed: ${err.message}`);\n }\n}\n\n// ===== PRETOOLUSE MODIFICATION HOOKS (v2.0.10+) =====\n\nasync function modifyBashCommand(subArgs, flags) {\n // Read JSON from stdin with timeout to detect if data is piped\n let input = '';\n let hasInput = false;\n\n const timeout = setTimeout(() => {\n if (!hasInput) {\n console.log('Usage: echo \\'{\"tool_input\":{\"command\":\"your command\"}}\\' | claude-flow hooks modify-bash');\n console.log('\\nThis hook reads JSON from stdin and outputs modified JSON.');\n console.log('It is designed for use with Claude Code v2.0.10+ PreToolUse feature.');\n console.log('\\nExample:');\n console.log(' echo \\'{\"tool_input\":{\"command\":\"rm test.txt\"}}\\' | claude-flow hooks modify-bash');\n process.exit(0);\n }\n }, 100); // 100ms timeout\n\n for await (const chunk of process.stdin) {\n hasInput = true;\n clearTimeout(timeout);\n input += chunk;\n }\n\n if (!input.trim()) {\n return; // Silently exit if no input\n }\n\n const toolInput = JSON.parse(input);\n const command = toolInput.tool_input?.command || '';\n\n if (!command) {\n console.log(input); // Pass through if no command\n return;\n }\n\n let modifiedCommand = command;\n const notes = [];\n\n // 1. Safety: Add -i flag to rm commands\n if (/^rm\\s/.test(command) && !/-[iI]/.test(command)) {\n modifiedCommand = command.replace(/^rm /, 'rm -i ');\n notes.push('[Safety: Added -i flag for interactive confirmation]');\n }\n\n // 2. Aliases\n if (/^ll(\\s|$)/.test(command)) {\n modifiedCommand = command.replace(/^ll/, 'ls -lah');\n notes.push('[Alias: ll ā ls -lah]');\n } else if (/^la(\\s|$)/.test(command)) {\n modifiedCommand = command.replace(/^la/, 'ls -la');\n notes.push('[Alias: la ā ls -la]');\n }\n\n // 3. Path correction: Redirect test files to /tmp\n if (/>\\s*test.*\\.(txt|log|tmp|json|md)/.test(command) && !/\\/tmp\\//.test(command)) {\n modifiedCommand = command.replace(/>\\s*(test[^/]*\\.(txt|log|tmp|json|md))/, '> /tmp/$1');\n notes.push('[Path: Redirected test file to /tmp/]');\n }\n\n // 4. Secret detection\n if (/(password|secret|token|api[-_]?key|auth)/i.test(command) && !/#\\s*SECRETS_OK/.test(command)) {\n notes.push('[Security: Command contains sensitive keywords. Add \"# SECRETS_OK\" to bypass]');\n }\n\n // Output modified JSON\n const output = {\n ...toolInput,\n tool_input: {\n ...toolInput.tool_input,\n command: modifiedCommand,\n },\n };\n\n if (notes.length > 0) {\n output.modification_notes = notes.join(' ');\n }\n\n console.log(JSON.stringify(output, null, 2));\n}\n\nasync function modifyFileCommand(subArgs, flags) {\n // Read JSON from stdin with timeout to detect if data is piped\n let input = '';\n let hasInput = false;\n\n const timeout = setTimeout(() => {\n if (!hasInput) {\n console.log('Usage: echo \\'{\"tool_input\":{\"file_path\":\"your/file.js\"}}\\' | claude-flow hooks modify-file');\n console.log('\\nThis hook reads JSON from stdin and outputs modified JSON.');\n console.log('It is designed for use with Claude Code v2.0.10+ PreToolUse feature.');\n console.log('\\nExample:');\n console.log(' echo \\'{\"tool_input\":{\"file_path\":\"test.js\"}}\\' | claude-flow hooks modify-file');\n process.exit(0);\n }\n }, 100); // 100ms timeout\n\n for await (const chunk of process.stdin) {\n hasInput = true;\n clearTimeout(timeout);\n input += chunk;\n }\n\n if (!input.trim()) {\n return; // Silently exit if no input\n }\n\n const toolInput = JSON.parse(input);\n const filePath = toolInput.tool_input?.file_path || toolInput.tool_input?.path || '';\n\n if (!filePath) {\n console.log(input); // Pass through if no file path\n return;\n }\n\n let modifiedPath = filePath;\n let shouldModify = false;\n const notes = [];\n\n // 1. Root folder protection\n const isRootFile = /^[^/]*\\.(js|ts|jsx|tsx|py|java|go|rs|cpp|c|h)$/.test(filePath) ||\n /^test.*\\.(txt|log|tmp|json|md)$/.test(filePath) ||\n /^(temp|tmp|working)/.test(filePath);\n\n if (isRootFile) {\n if (/test.*\\.(test|spec)\\.|\\.test\\.|\\.spec\\./.test(filePath)) {\n modifiedPath = `tests/${filePath}`;\n shouldModify = true;\n notes.push('[Organization: Moved test file to /tests/]');\n } else if (/test.*\\.md|temp.*\\.md|working.*\\.md|scratch.*\\.md/.test(filePath)) {\n modifiedPath = `docs/working/${filePath}`;\n shouldModify = true;\n notes.push('[Organization: Moved working document to /docs/working/]');\n } else if (/\\.(js|ts|jsx|tsx|py)$/.test(filePath)) {\n modifiedPath = `src/${filePath}`;\n shouldModify = true;\n notes.push('[Organization: Moved source file to /src/]');\n } else if (/^(temp|tmp|scratch)/.test(filePath)) {\n modifiedPath = `/tmp/${filePath}`;\n shouldModify = true;\n notes.push('[Organization: Redirected temporary file to /tmp/]');\n }\n }\n\n // 2. Format hints\n if (/\\.(ts|tsx|js|jsx)$/.test(modifiedPath)) {\n notes.push('[Tip: Auto-format with Prettier/ESLint recommended]');\n } else if (/\\.py$/.test(modifiedPath)) {\n notes.push('[Tip: Auto-format with Black/autopep8 recommended]');\n }\n\n // Output modified JSON\n const output = {\n ...toolInput,\n tool_input: {\n ...toolInput.tool_input,\n },\n };\n\n if (shouldModify) {\n if (toolInput.tool_input.file_path) {\n output.tool_input.file_path = modifiedPath;\n } else {\n output.tool_input.path = modifiedPath;\n }\n }\n\n if (notes.length > 0) {\n output.modification_notes = notes.join(' ');\n }\n\n console.log(JSON.stringify(output, null, 2));\n}\n\nasync function modifyGitCommitCommand(subArgs, flags) {\n // Read JSON from stdin with timeout to detect if data is piped\n let input = '';\n let hasInput = false;\n\n const timeout = setTimeout(() => {\n if (!hasInput) {\n console.log('Usage: echo \\'{\"tool_input\":{\"command\":\"git commit -m \\\\\"message\\\\\"\"}}\\' | claude-flow hooks modify-git-commit');\n console.log('\\nThis hook reads JSON from stdin and outputs modified JSON.');\n console.log('It is designed for use with Claude Code v2.0.10+ PreToolUse feature.');\n console.log('\\nExample:');\n console.log(' echo \\'{\"tool_input\":{\"command\":\"git commit -m \\\\\"fix bug\\\\\"\"}}\\' | claude-flow hooks modify-git-commit');\n process.exit(0);\n }\n }, 100); // 100ms timeout\n\n for await (const chunk of process.stdin) {\n hasInput = true;\n clearTimeout(timeout);\n input += chunk;\n }\n\n if (!input.trim()) {\n return; // Silently exit if no input\n }\n\n const toolInput = JSON.parse(input);\n const command = toolInput.tool_input?.command || '';\n\n if (!command || !/git commit/.test(command)) {\n console.log(input); // Pass through if not git commit\n return;\n }\n\n // Extract commit message\n const msgMatch = command.match(/-m\\s+[\"']([^\"']+)[\"']/) || command.match(/-m\\s+(\\S+)/);\n const commitMsg = msgMatch ? msgMatch[1] : '';\n\n if (!commitMsg || /^\\[(feat|fix|docs|style|refactor|test|chore|perf)\\]/.test(commitMsg)) {\n console.log(input); // Already formatted or no message\n return;\n }\n\n const notes = [];\n\n // Get current branch\n let branch = 'main';\n let ticket = '';\n try {\n const { execSync } = await import('child_process');\n branch = execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf8' }).trim();\n\n // Extract JIRA ticket\n const ticketMatch = branch.match(/[A-Z]+-[0-9]+/);\n if (ticketMatch) {\n ticket = ticketMatch[0];\n }\n } catch {\n // Git not available, continue\n }\n\n // Detect conventional commit type\n let type = 'chore';\n if (/^(add|implement|create|new)/i.test(commitMsg)) type = 'feat';\n else if (/^(fix|resolve|patch|correct)/i.test(commitMsg)) type = 'fix';\n else if (/^(update|modify|change|improve)/i.test(commitMsg)) type = 'refactor';\n else if (/^(doc|documentation|readme)/i.test(commitMsg)) type = 'docs';\n else if (/^(test|testing|spec)/i.test(commitMsg)) type = 'test';\n else if (/^(style|format|lint)/i.test(commitMsg)) type = 'style';\n else if (/^(perf|optimize|speed)/i.test(commitMsg)) type = 'perf';\n\n // Format message\n let formattedMsg = ticket\n ? `[${type}] ${commitMsg} (${ticket})`\n : `[${type}] ${commitMsg}`;\n\n // Add co-author\n if (!/Co-Authored-By/.test(command)) {\n formattedMsg += `\\n\\nš¤ Generated with Claude Flow\\nCo-Authored-By: claude-flow <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","memoryStore","getMemoryStore","initialize","generateId","prefix","Date","now","Math","random","toString","substr","hooksAction","subArgs","flags","subcommand","options","help","h","showHooksHelp","preTaskCommand","preEditCommand","preBashCommand","postTaskCommand","postEditCommand","postBashCommand","postSearchCommand","mcpInitializedCommand","agentSpawnedCommand","taskOrchestratedCommand","neuralTrainedCommand","sessionEndCommand","sessionRestoreCommand","notifyCommand","modifyBashCommand","modifyFileCommand","modifyGitCommitCommand","err","message","description","taskId","agentId","autoSpawnAgents","console","log","store","taskData","status","startedAt","toISOString","namespace","metadata","hookType","timestamp","checkPromise","timeoutPromise","Promise","_","reject","setTimeout","Error","isAvailable","race","hookResult","success","output","close","process","exit","file","operation","autoAssignAgents","loadContext","assignedAgentType","recommendedAgent","path","ext","extname","toLowerCase","agentMapping","type","extension","recommended","contextData","fs","existsSync","stats","statSync","dirname","basename","fileExists","size","modified","mtime","directory","filename","isDirectory","willCreate","error","editData","editId","agentType","ttl","command","slice","join","workingDir","cwd","validateSafety","validate","prepareResources","safetyResult","dangerousCommands","isDangerous","length","some","dangerous","includes","mkdirSync","recursive","bashData","bashId","safety","validationEnabled","resourcesPrepped","toUpperCase","analyzePerformance","retrieve","completedData","completedAt","duration","getTime","metrics","durationHuman","toFixed","memoryKey","format","updateMemory","trainNeural","formatResult","formatters","formatter","attempted","reason","memoryUpdate","editContext","editedAt","formatted","fileSize","neuralTraining","editTime","patterns","fileType","fileName","confidence","enhanced","historyKey","replace","features","exitCode","trackMetrics","storeResults","startTime","commandLength","outputLength","parseInt","complexity","substring","fullOutput","existingMetrics","totalCommands","successRate","avgDuration","lastUpdated","hasMetrics","hasResults","query","resultCount","searchType","searchData","searchId","cachedAt","serverName","server","sessionId","mcpData","initializedAt","agentName","name","swarmId","agentData","spawnedAt","action","strategy","priority","orchestrationData","orchestratedAt","modelName","model","accuracy","trainingData","parseFloat","patternsLearned","trainedAt","generateSummary","persistState","exportMetrics","tasks","list","limit","edits","commands","agents","sessionStart","min","map","t","value","e","c","successfulCommands","filter","commandSuccessRate","sessionDuration","sessionDurationHuman","round","totalTasks","totalEdits","uniqueAgents","avgTasksPerMinute","avgEditsPerMinute","sessionData","endedAt","detailedState","persistedAt","fullState","sessions","restoredSessionId","restoredAt","level","swarmStatus","notificationData","notifyId","icon","input","hasInput","timeout","chunk","stdin","clearTimeout","trim","toolInput","JSON","parse","tool_input","modifiedCommand","notes","test","push","modification_notes","stringify","filePath","file_path","modifiedPath","shouldModify","isRootFile","msgMatch","match","commitMsg","branch","ticket","execSync","encoding","ticketMatch","formattedMsg"],"mappings":"AAAA,SACEA,YAAY,EACZC,UAAU,EACVC,YAAY,EACZC,gBAAgB,EAChBC,sBAAsB,QACjB,cAAc;AACrB,SAASC,iBAAiB,QAAQ,+BAA+B;AAGjE,IAAIC,cAAc;AAElB,eAAeC;IACb,IAAI,CAACD,aAAa;QAChBA,cAAc,IAAID;QAClB,MAAMC,YAAYE,UAAU;IAC9B;IACA,OAAOF;AACT;AAGA,SAASG,WAAWC,SAAS,IAAI;IAC/B,OAAO,GAAGA,OAAO,CAAC,EAAEC,KAAKC,GAAG,GAAG,CAAC,EAAEC,KAAKC,MAAM,GAAGC,QAAQ,CAAC,IAAIC,MAAM,CAAC,GAAG,IAAI;AAC7E;AAEA,OAAO,eAAeC,YAAYC,OAAO,EAAEC,KAAK;IAC9C,MAAMC,aAAaF,OAAO,CAAC,EAAE;IAC7B,MAAMG,UAAUF;IAEhB,IAAIE,QAAQC,IAAI,IAAID,QAAQE,CAAC,IAAI,CAACH,YAAY;QAC5CI;QACA;IACF;IAEA,IAAI;QACF,OAAQJ;YAEN,KAAK;gBACH,MAAMK,eAAeP,SAASC;gBAC9B;YACF,KAAK;gBACH,MAAMO,eAAeR,SAASC;gBAC9B;YACF,KAAK;YACL,KAAK;gBACH,MAAMQ,eAAeT,SAASC;gBAC9B;YAGF,KAAK;gBACH,MAAMS,gBAAgBV,SAASC;gBAC/B;YACF,KAAK;gBACH,MAAMU,gBAAgBX,SAASC;gBAC/B;YACF,KAAK;YACL,KAAK;gBACH,MAAMW,gBAAgBZ,SAASC;gBAC/B;YACF,KAAK;gBACH,MAAMY,kBAAkBb,SAASC;gBACjC;YAGF,KAAK;gBACH,MAAMa,sBAAsBd,SAASC;gBACrC;YACF,KAAK;gBACH,MAAMc,oBAAoBf,SAASC;gBACnC;YACF,KAAK;gBACH,MAAMe,wBAAwBhB,SAASC;gBACvC;YACF,KAAK;gBACH,MAAMgB,qBAAqBjB,SAASC;gBAC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CAAC;IAEZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;IACZD,QAAQC,GAAG,CAAC;AACd;AAEA,eAAehC,YAAY"}
|
|
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,GAAG,IAAI;AAC7E;AAEA,OAAO,eAAeC,YAAYC,OAAO,EAAEC,KAAK;IAC9C,MAAMC,aAAaF,OAAO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G,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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../../src/cli/validation-helper.
|
|
1
|
+
{"version":3,"sources":["../../../src/cli/validation-helper.js"],"sourcesContent":["/**\n * CLI Parameter Validation Helper\n * Provides standardized error messages for invalid parameters\n */\n\nimport { HelpFormatter } from './help-formatter.js';\n\nexport class ValidationHelper {\n /**\n * Validate enum parameter\n */\n static validateEnum(value, paramName, validOptions, commandPath) {\n if (!validOptions.includes(value)) {\n console.error(\n HelpFormatter.formatValidationError(value, paramName, validOptions, commandPath),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate numeric parameter\n */\n static validateNumber(value, paramName, min, max, commandPath) {\n const num = parseInt(value, 10);\n\n if (isNaN(num)) {\n console.error(\n HelpFormatter.formatError(\n `'${value}' is not a valid number for ${paramName}.`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n if (min !== undefined && num < min) {\n console.error(\n HelpFormatter.formatError(\n `${paramName} must be at least ${min}. Got: ${num}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n if (max !== undefined && num > max) {\n console.error(\n HelpFormatter.formatError(\n `${paramName} must be at most ${max}. Got: ${num}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n\n return num;\n }\n\n /**\n * Validate required parameter\n */\n static validateRequired(value, paramName, commandPath) {\n if (!value || (typeof value === 'string' && value.trim() === '')) {\n console.error(\n HelpFormatter.formatError(\n `Missing required parameter: ${paramName}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate file path exists\n */\n static async validateFilePath(path, paramName, commandPath) {\n try {\n const fs = await import('fs/promises');\n await fs.access(path);\n } catch (error) {\n console.error(\n HelpFormatter.formatError(\n `File not found for ${paramName}: ${path}`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n }\n\n /**\n * Validate boolean flag\n */\n static validateBoolean(value, paramName, commandPath) {\n const lowerValue = value.toLowerCase();\n if (lowerValue === 'true' || lowerValue === '1' || lowerValue === 'yes') {\n return true;\n }\n if (lowerValue === 'false' || lowerValue === '0' || lowerValue === 'no') {\n return false;\n }\n\n console.error(\n HelpFormatter.formatError(\n `'${value}' is not a valid boolean for ${paramName}. Use: true, false, yes, no, 1, or 0.`,\n commandPath || 'claude-flow',\n ),\n );\n process.exit(1);\n }\n}\n"],"names":["HelpFormatter","ValidationHelper","validateEnum","value","paramName","validOptions","commandPath","includes","console","error","formatValidationError","process","exit","validateNumber","min","max","num","parseInt","isNaN","formatError","undefined","validateRequired","trim","validateFilePath","path","fs","access","validateBoolean","lowerValue","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AI,CAAC;QACf;IACF;IAKA,aAAaW,iBAAiBC,IAAI,EAAEpB,SAAS,EAAEE,WAAW,EAAE;QAC1D,IAAI;YACF,MAAMmB,KAAK,MAAM,MAAM,CAAC;YACxB,MAAMA,GAAGC,MAAM,CAACF;QAClB,EAAE,OAAOf,OAAO;YACdD,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,mBAAmB,EAAEf,UAAU,EAAE,EAAEoB,MAAM,EAC1ClB,eAAe;YAGnBK,QAAQC,IAAI,CAAC;QACf;IACF;IAKA,OAAOe,gBAAgBxB,KAAK,EAAEC,SAAS,EAAEE,WAAW,EAAE;QACpD,MAAMsB,aAAazB,MAAM0B,WAAW;QACpC,IAAID,eAAe,UAAUA,eAAe,OAAOA,eAAe,OAAO;YACvE,OAAO;QACT;QACA,IAAIA,eAAe,WAAWA,eAAe,OAAOA,eAAe,MAAM;YACvE,OAAO;QACT;QAEApB,QAAQC,KAAK,CACXT,cAAcmB,WAAW,CACvB,CAAC,CAAC,EAAEhB,MAAM,6BAA6B,EAAEC,UAAU,qCAAqC,CAAC,EACzFE,eAAe;QAGnBK,QAAQC,IAAI,CAAC;IACf;AACF"}
|
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
import * as fs from 'fs-extra';
|
|
2
2
|
import * as path from 'path';
|
|
3
|
+
import { isNativeModuleVersionError, getNativeModuleRecoveryMessage } from '../utils/error-recovery.js';
|
|
4
|
+
export class NativeModuleError extends Error {
|
|
5
|
+
originalError;
|
|
6
|
+
isNativeModuleError = true;
|
|
7
|
+
constructor(message, originalError){
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = 'NativeModuleError';
|
|
10
|
+
this.originalError = originalError;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
3
13
|
export class DatabaseManager {
|
|
4
14
|
provider;
|
|
5
15
|
dbType;
|
|
@@ -21,11 +31,14 @@ export class DatabaseManager {
|
|
|
21
31
|
return new SQLiteProvider(this.dbPath);
|
|
22
32
|
} catch (error) {
|
|
23
33
|
const errorMsg = error instanceof Error ? error.message : String(error);
|
|
24
|
-
if (
|
|
34
|
+
if (error instanceof NativeModuleError || isNativeModuleVersionError(error)) {
|
|
35
|
+
console.warn('\n' + (error instanceof NativeModuleError ? error.message : getNativeModuleRecoveryMessage(error)));
|
|
36
|
+
console.warn(' Falling back to JSON storage (no data loss, just slower).\n');
|
|
37
|
+
} else if (errorMsg.includes('ENOTEMPTY') || errorMsg.includes('better-sqlite3')) {
|
|
25
38
|
console.warn('ā ļø SQLite initialization failed due to npm cache error');
|
|
26
39
|
console.warn(' Will attempt automatic recovery during initialize()');
|
|
27
40
|
} else {
|
|
28
|
-
console.warn('SQLite not available, falling back to JSON storage:',
|
|
41
|
+
console.warn('SQLite not available, falling back to JSON storage:', errorMsg);
|
|
29
42
|
}
|
|
30
43
|
this.provider = new JSONProvider(this.dbPath.replace('.sqlite', '.json'));
|
|
31
44
|
this.dbType = 'json';
|
|
@@ -128,6 +141,10 @@ let SQLiteProvider = class SQLiteProvider {
|
|
|
128
141
|
const Database = require('better-sqlite3');
|
|
129
142
|
this.db = new Database(dbPath);
|
|
130
143
|
} catch (error) {
|
|
144
|
+
if (isNativeModuleVersionError(error)) {
|
|
145
|
+
const recoveryMsg = getNativeModuleRecoveryMessage(error);
|
|
146
|
+
throw new NativeModuleError(recoveryMsg, error);
|
|
147
|
+
}
|
|
131
148
|
throw new Error('better-sqlite3 not available. Install with: npm install better-sqlite3');
|
|
132
149
|
}
|
|
133
150
|
}
|