From 53805286d4387ecb9d047960ef246742079af87d Mon Sep 17 00:00:00 2001 From: Sagar Date: Wed, 16 Sep 2026 22:19:31 +0530 Subject: [PATCH] Fix #42: Build Error Taxonomy and Healing Pattern System --- data/community-patterns.json | 52 ++++++++++++ package-lock.json | 22 +++++ package.json | 1 + patch_advanced.js | 55 +++++++++++++ patch_index.js | 19 +++++ patch_index_2.js | 45 ++++++++++ patch_session.js | 55 +++++++++++++ src/commands/advanced-session.js | 26 ++++++ src/commands/session.js | 32 ++++++++ src/commands/taxonomy.js | 26 ++++++ src/index.js | 35 ++++++++ src/services/taxonomy.js | 136 +++++++++++++++++++++++++++++++ 12 files changed, 504 insertions(+) create mode 100644 data/community-patterns.json create mode 100644 patch_advanced.js create mode 100644 patch_index.js create mode 100644 patch_index_2.js create mode 100644 patch_session.js create mode 100644 src/commands/taxonomy.js create mode 100644 src/services/taxonomy.js diff --git a/data/community-patterns.json b/data/community-patterns.json new file mode 100644 index 0000000..4bbab81 --- /dev/null +++ b/data/community-patterns.json @@ -0,0 +1,52 @@ +[ + { "id": "cp_001", "commandRegex": "^git push", "errorRegex": "Updates were rejected because the tip of your current branch is behind", "os": [], "shell": [], "fix": "git pull --rebase && git push", "confidence": 0.9 }, + { "id": "cp_002", "commandRegex": "^npm install", "errorRegex": "npm ERR! code ERESOLVE", "os": [], "shell": [], "fix": "npm install --legacy-peer-deps", "confidence": 0.8 }, + { "id": "cp_003", "commandRegex": "^npm install", "errorRegex": "npm ERR! cb() never called", "os": [], "shell": [], "fix": "npm cache clean --force && npm install", "confidence": 0.7 }, + { "id": "cp_004", "commandRegex": "^docker build", "errorRegex": "failed to solve: rpc error: code = Unknown", "os": [], "shell": [], "fix": "docker builder prune -f && docker build .", "confidence": 0.7 }, + { "id": "cp_005", "commandRegex": "^docker run", "errorRegex": "port is already allocated", "os": [], "shell": [], "fix": "docker ps -q | xargs docker stop", "confidence": 0.6 }, + { "id": "cp_006", "commandRegex": "^git commit", "errorRegex": "Please tell me who you are", "os": [], "shell": [], "fix": "git config --global user.email \"user@example.com\" && git config --global user.name \"User\"", "confidence": 0.8 }, + { "id": "cp_007", "commandRegex": "^node ", "errorRegex": "Cannot find module", "os": [], "shell": [], "fix": "npm install", "confidence": 0.7 }, + { "id": "cp_008", "commandRegex": "^python", "errorRegex": "ModuleNotFoundError: No module named", "os": [], "shell": [], "fix": "pip install -r requirements.txt", "confidence": 0.7 }, + { "id": "cp_009", "commandRegex": "^pip install", "errorRegex": "error: externally-managed-environment", "os": ["linux"], "shell": [], "fix": "pip install --break-system-packages", "confidence": 0.5 }, + { "id": "cp_010", "commandRegex": "^curl", "errorRegex": "Could not resolve host", "os": [], "shell": [], "fix": "ping 8.8.8.8", "confidence": 0.5 }, + { "id": "cp_011", "commandRegex": "^make", "errorRegex": "missing separator", "os": [], "shell": [], "fix": "sed -i 's/^[ ]*/\\t/' Makefile", "confidence": 0.6 }, + { "id": "cp_012", "commandRegex": "^rm ", "errorRegex": "Directory not empty", "os": [], "shell": [], "fix": "rm -rf", "confidence": 0.7 }, + { "id": "cp_013", "commandRegex": "^chown", "errorRegex": "Operation not permitted", "os": [], "shell": [], "fix": "sudo chown", "confidence": 0.8 }, + { "id": "cp_014", "commandRegex": "^apt-get install", "errorRegex": "Could not open lock file", "os": ["linux"], "shell": [], "fix": "sudo rm /var/lib/dpkg/lock-frontend && sudo apt-get install", "confidence": 0.6 }, + { "id": "cp_015", "commandRegex": "^brew install", "errorRegex": "Another active Homebrew update process is already in progress", "os": ["darwin"], "shell": [], "fix": "rm -rf $(brew --prefix)/var/homebrew/locks", "confidence": 0.7 }, + { "id": "cp_016", "commandRegex": "^composer install", "errorRegex": "Allowed memory size of", "os": [], "shell": [], "fix": "COMPOSER_MEMORY_LIMIT=-1 composer install", "confidence": 0.9 }, + { "id": "cp_017", "commandRegex": "^yarn install", "errorRegex": "There appears to be trouble with your network connection", "os": [], "shell": [], "fix": "yarn config set network-timeout 600000 -g && yarn install", "confidence": 0.8 }, + { "id": "cp_018", "commandRegex": "^go get", "errorRegex": "module declares its path as", "os": [], "shell": [], "fix": "go mod tidy", "confidence": 0.7 }, + { "id": "cp_019", "commandRegex": "^cargo build", "errorRegex": "failed to download", "os": [], "shell": [], "fix": "cargo clean && cargo build", "confidence": 0.7 }, + { "id": "cp_020", "commandRegex": "^terraform init", "errorRegex": "Failed to query available provider packages", "os": [], "shell": [], "fix": "rm -rf .terraform && terraform init", "confidence": 0.8 }, + { "id": "cp_021", "commandRegex": "^kubectl get", "errorRegex": "connection refused", "os": [], "shell": [], "fix": "minikube start", "confidence": 0.6 }, + { "id": "cp_022", "commandRegex": "^git clone", "errorRegex": "Permission denied \\(publickey\\)", "os": [], "shell": [], "fix": "ssh-keygen -t rsa -b 4096", "confidence": 0.5 }, + { "id": "cp_023", "commandRegex": "^ls", "errorRegex": "No such file or directory", "os": [], "shell": [], "fix": "pwd", "confidence": 0.4 }, + { "id": "cp_024", "commandRegex": "^cd", "errorRegex": "Not a directory", "os": [], "shell": [], "fix": "cat", "confidence": 0.3 }, + { "id": "cp_025", "commandRegex": "^vim", "errorRegex": "command not found", "os": ["linux"], "shell": [], "fix": "sudo apt install vim", "confidence": 0.8 }, + { "id": "cp_026", "commandRegex": "^nano", "errorRegex": "command not found", "os": ["linux"], "shell": [], "fix": "sudo apt install nano", "confidence": 0.8 }, + { "id": "cp_027", "commandRegex": "^tar", "errorRegex": "Not found in archive", "os": [], "shell": [], "fix": "tar -tvf", "confidence": 0.5 }, + { "id": "cp_028", "commandRegex": "^unzip", "errorRegex": "command not found", "os": ["linux"], "shell": [], "fix": "sudo apt install unzip", "confidence": 0.8 }, + { "id": "cp_029", "commandRegex": "^psql", "errorRegex": "role .* does not exist", "os": [], "shell": [], "fix": "createuser -s root", "confidence": 0.5 }, + { "id": "cp_030", "commandRegex": "^mysql", "errorRegex": "Access denied for user", "os": [], "shell": [], "fix": "mysql -u root -p", "confidence": 0.6 }, + { "id": "cp_031", "commandRegex": "^ssh", "errorRegex": "REMOTE HOST IDENTIFICATION HAS CHANGED", "os": [], "shell": [], "fix": "ssh-keygen -R", "confidence": 0.8 }, + { "id": "cp_032", "commandRegex": "^scp", "errorRegex": "Permission denied", "os": [], "shell": [], "fix": "chmod 400", "confidence": 0.6 }, + { "id": "cp_033", "commandRegex": "^systemctl", "errorRegex": "Failed to connect to bus", "os": ["linux"], "shell": [], "fix": "sudo systemctl", "confidence": 0.7 }, + { "id": "cp_034", "commandRegex": "^service", "errorRegex": "unrecognized service", "os": ["linux"], "shell": [], "fix": "systemctl status", "confidence": 0.6 }, + { "id": "cp_035", "commandRegex": "^journalctl", "errorRegex": "No journal files were found", "os": ["linux"], "shell": [], "fix": "sudo journalctl", "confidence": 0.7 }, + { "id": "cp_036", "commandRegex": "^nvm use", "errorRegex": "N/A: version .* is not yet installed", "os": [], "shell": [], "fix": "nvm install", "confidence": 0.9 }, + { "id": "cp_037", "commandRegex": "^rvm use", "errorRegex": "is not installed", "os": [], "shell": [], "fix": "rvm install", "confidence": 0.9 }, + { "id": "cp_038", "commandRegex": "^pyenv install", "errorRegex": "BUILD FAILED", "os": [], "shell": [], "fix": "sudo apt install build-essential libssl-dev zlib1g-dev", "confidence": 0.7 }, + { "id": "cp_039", "commandRegex": "^grep", "errorRegex": "invalid option", "os": [], "shell": [], "fix": "grep --help", "confidence": 0.5 }, + { "id": "cp_040", "commandRegex": "^find", "errorRegex": "paths must precede expression", "os": [], "shell": [], "fix": "find . -name", "confidence": 0.6 }, + { "id": "cp_041", "commandRegex": "^xargs", "errorRegex": "argument line too long", "os": [], "shell": [], "fix": "xargs -n 1", "confidence": 0.8 }, + { "id": "cp_042", "commandRegex": "^awk", "errorRegex": "syntax error", "os": [], "shell": [], "fix": "awk '{print $1}'", "confidence": 0.4 }, + { "id": "cp_043", "commandRegex": "^sed", "errorRegex": "unterminated `s' command", "os": [], "shell": [], "fix": "sed 's/foo/bar/g'", "confidence": 0.5 }, + { "id": "cp_044", "commandRegex": "^cat", "errorRegex": "Is a directory", "os": [], "shell": [], "fix": "ls -la", "confidence": 0.8 }, + { "id": "cp_045", "commandRegex": "^tail", "errorRegex": "cannot open .* for reading", "os": [], "shell": [], "fix": "sudo tail", "confidence": 0.7 }, + { "id": "cp_046", "commandRegex": "^less", "errorRegex": "No such file or directory", "os": [], "shell": [], "fix": "ls", "confidence": 0.6 }, + { "id": "cp_047", "commandRegex": "^chmod", "errorRegex": "invalid mode", "os": [], "shell": [], "fix": "chmod +x", "confidence": 0.7 }, + { "id": "cp_048", "commandRegex": "^ping", "errorRegex": "unknown host", "os": [], "shell": [], "fix": "cat /etc/resolv.conf", "confidence": 0.6 }, + { "id": "cp_049", "commandRegex": "^netstat", "errorRegex": "command not found", "os": ["linux"], "shell": [], "fix": "sudo apt install net-tools", "confidence": 0.8 }, + { "id": "cp_050", "commandRegex": "^ifconfig", "errorRegex": "command not found", "os": ["linux"], "shell": [], "fix": "ip a", "confidence": 0.9 } +] diff --git a/package-lock.json b/package-lock.json index 64dde1d..de2b15f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -11,6 +11,7 @@ "dependencies": { "@google/generative-ai": "^0.24.1", "bash-parser": "^0.5.0", + "better-sqlite3": "^13.0.3", "chalk": "^5.6.2", "dotenv": "^17.2.3", "groq-sdk": "^0.37.0", @@ -2925,6 +2926,27 @@ "dev": true, "license": "Apache-2.0" }, + "node_modules/better-sqlite3": { + "version": "13.0.3", + "resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-13.0.3.tgz", + "integrity": "sha512-RbOBxmLBG8uvFUc15X9+9SFemKcQ0WBuISBVkpuiaUB2qblC8UWlHEjdWVoZ8AdhSwmoEgsiXKfopX0CQxaACQ==", + "license": "MIT", + "dependencies": { + "node-addon-api": "^8.0.0" + }, + "engines": { + "node": ">=22" + } + }, + "node_modules/better-sqlite3/node_modules/node-addon-api": { + "version": "8.9.2", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz", + "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==", + "license": "MIT", + "engines": { + "node": "^18 || ^20 || >= 21" + } + }, "node_modules/bidi-js": { "version": "1.0.3", "resolved": "https://registry.npmjs.org/bidi-js/-/bidi-js-1.0.3.tgz", diff --git a/package.json b/package.json index 3ebac70..8959fb1 100644 --- a/package.json +++ b/package.json @@ -74,6 +74,7 @@ "dependencies": { "@google/generative-ai": "^0.24.1", "bash-parser": "^0.5.0", + "better-sqlite3": "^13.0.3", "chalk": "^5.6.2", "dotenv": "^17.2.3", "groq-sdk": "^0.37.0", diff --git a/patch_advanced.js b/patch_advanced.js new file mode 100644 index 0000000..90bbfb9 --- /dev/null +++ b/patch_advanced.js @@ -0,0 +1,55 @@ +import fs from 'fs'; + +let content = fs.readFileSync('src/commands/advanced-session.js', 'utf8'); + +// Import TaxonomySystem +if (!content.includes('TaxonomySystem')) { + content = content.replace( + "import NamespacedVectorMemory from '../services/namespaced-memory.js';", + "import NamespacedVectorMemory from '../services/namespaced-memory.js';\nimport { TaxonomySystem } from '../services/taxonomy.js';" + ); +} + +// Instantiate +if (!content.includes('const taxonomy = new TaxonomySystem()')) { + content = content.replace( + "const memory = new NamespacedVectorMemory();", + "const memory = new NamespacedVectorMemory();\nconst taxonomy = new TaxonomySystem();\n// Load community patterns on startup if exists\nimport path from 'path';\nimport { fileURLToPath } from 'url';\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\ntaxonomy.loadCommunityPatterns(path.join(__dirname, '../../data/community-patterns.json'));" + ); +} + +// Update handleAutoHealingSafe +const healRegex = /async function handleAutoHealingSafe\(command, result\) \{\s*try \{\s*const errorMsg = result\.stderr \|\| 'Unknown error';/m; +if (content.match(healRegex)) { + const replacement = `async function handleAutoHealingSafe(command, result) { + try { + const errorMsg = result.stderr || 'Unknown error'; + + // 0. Taxonomy Pattern Check (Instant, Local, Proven) + const patternMatch = taxonomy.match(command, errorMsg); + if (patternMatch) { + console.log((await import('chalk')).default.green(\`\\n🛡️ Taxonomy Fix (Confidence \${Math.round(patternMatch.effectiveConfidence * 100)}%):\`)); + console.log((await import('chalk')).default.bold(patternMatch.fix)); + + const inquirer = (await import('inquirer')).default; + const { confirm } = await inquirer.prompt([{ + type: 'confirm', name: 'confirm', message: 'Execute?', default: true + }]); + + if (confirm) { + try { + const output = await executeSystemCommand(patternMatch.fix, { cwd: SessionContext.getCwd() }); + console.log(output); + taxonomy.updateConfidence(patternMatch.id, true); + } catch(e) { + console.log((await import('chalk')).default.red(\`Fix failed: \${e.message}\`)); + taxonomy.updateConfidence(patternMatch.id, false); + } + } + return; + } +`; + content = content.replace(healRegex, replacement); +} + +fs.writeFileSync('src/commands/advanced-session.js', content); diff --git a/patch_index.js b/patch_index.js new file mode 100644 index 0000000..fe06b90 --- /dev/null +++ b/patch_index.js @@ -0,0 +1,19 @@ +import fs from 'fs'; + +let content = fs.readFileSync('src/index.js', 'utf8'); + +const setupCommand = "if (cleanedArgs[0] === 'setup') {"; +const newCommand = `if (cleanedArgs[0] === 'taxonomy') { + const { handleTaxonomyCommand } = await import('./commands/taxonomy.js'); + await handleTaxonomyCommand(cleanedArgs.slice(1)); + return; + } + + if (cleanedArgs[0] === 'setup') {`; + +if (content.includes(setupCommand) && !content.includes("cleanedArgs[0] === 'taxonomy'")) { + content = content.replace(setupCommand, newCommand); + fs.writeFileSync('src/index.js', content); +} else { + console.log("Could not find setup command block or already patched."); +} diff --git a/patch_index_2.js b/patch_index_2.js new file mode 100644 index 0000000..1b4543f --- /dev/null +++ b/patch_index_2.js @@ -0,0 +1,45 @@ +import fs from 'fs'; + +let content = fs.readFileSync('src/index.js', 'utf8'); + +// Ensure TaxonomySystem is imported at the top if not already (it's in the same file so might be hard to patch at top, let's just inline import) +const searchStr = "console.log(chalk.yellow('\\n🤖 Nebula is analyzing the failure...'));\\n\\n try {"; +const replacement = `console.log(chalk.yellow('\\n🤖 Nebula is analyzing the failure...')); + + try { + // 0. Taxonomy Pattern Check + const { TaxonomySystem } = await import('./services/taxonomy.js'); + const taxonomy = new TaxonomySystem(); + const { fileURLToPath } = await import('url'); + const path = await import('path'); + const __dirname = path.dirname(fileURLToPath(import.meta.url)); + taxonomy.loadCommunityPatterns(path.join(__dirname, '../data/community-patterns.json')); + + const patternMatch = taxonomy.match(command, error.message); + if (patternMatch) { + console.log(chalk.green(\`\\n🛡️ Taxonomy Fix (Confidence \${Math.round(patternMatch.effectiveConfidence * 100)}%):\`)); + console.log(chalk.bold(patternMatch.fix)); + + const { confirm } = await inquirer.prompt([{ + type: 'confirm', name: 'confirm', message: 'Execute?', default: true + }]); + + if (confirm) { + try { + const output = await executeSystemCommand(patternMatch.fix, { cwd: process.cwd(), dryRun: flags.dryRun }); + console.log(output); + taxonomy.updateConfidence(patternMatch.id, true); + } catch(e) { + console.log(chalk.red(\`Fix failed: \${e.message}\`)); + taxonomy.updateConfidence(patternMatch.id, false); + } + } + return; + }`; + +if (content.match(/console\.log\(chalk\.yellow\('\\n🤖 Nebula is analyzing the failure\.\.\.'\)\);\s*try \{/)) { + content = content.replace(/console\.log\(chalk\.yellow\('\\n🤖 Nebula is analyzing the failure\.\.\.'\)\);\s*try \{/, replacement); + fs.writeFileSync('src/index.js', content); +} else { + console.log("Could not find the target string in index.js"); +} diff --git a/patch_session.js b/patch_session.js new file mode 100644 index 0000000..137c126 --- /dev/null +++ b/patch_session.js @@ -0,0 +1,55 @@ +import fs from 'fs'; + +let content = fs.readFileSync('src/commands/session.js', 'utf8'); + +// Import TaxonomySystem +if (!content.includes('TaxonomySystem')) { + content = content.replace( + "import NamespacedVectorMemory from '../services/namespaced-memory.js';", + "import NamespacedVectorMemory from '../services/namespaced-memory.js';\nimport { TaxonomySystem } from '../services/taxonomy.js';" + ); +} + +// Instantiate +if (!content.includes('const taxonomy = new TaxonomySystem()')) { + content = content.replace( + "const memory = new NamespacedVectorMemory();", + "const memory = new NamespacedVectorMemory();\nconst taxonomy = new TaxonomySystem();\n// Load community patterns on startup if exists\nimport path from 'path';\nimport { fileURLToPath } from 'url';\nconst __dirname = path.dirname(fileURLToPath(import.meta.url));\ntaxonomy.loadCommunityPatterns(path.join(__dirname, '../../data/community-patterns.json'));" + ); +} + +// Update handleAutoHealingSafe +const healRegex = /async function handleAutoHealingSafe\(command, result, rl\) \{\s*try \{\s*const errorMsg = result\.stderr \|\| 'Unknown error';/m; +if (content.match(healRegex)) { + const replacement = `async function handleAutoHealingSafe(command, result, rl) { + try { + const errorMsg = result.stderr || 'Unknown error'; + + // 0. Taxonomy Pattern Check (Instant, Local, Proven) + const patternMatch = taxonomy.match(command, errorMsg); + if (patternMatch) { + console.log((await import('chalk')).default.green(\`\\n🛡️ Taxonomy Fix (Confidence \${Math.round(patternMatch.effectiveConfidence * 100)}%):\`)); + console.log((await import('chalk')).default.bold(patternMatch.fix)); + + const inquirer = (await import('inquirer')).default; + const { confirm } = await inquirer.prompt([{ + type: 'confirm', name: 'confirm', message: 'Execute?', default: true + }]); + + if (confirm) { + try { + const output = await executeSystemCommand(patternMatch.fix, { cwd: SessionContext.getCwd() }); + console.log(output); + taxonomy.updateConfidence(patternMatch.id, true); + } catch(e) { + console.log((await import('chalk')).default.red(\`Fix failed: \${e.message}\`)); + taxonomy.updateConfidence(patternMatch.id, false); + } + } + return; + } +`; + content = content.replace(healRegex, replacement); +} + +fs.writeFileSync('src/commands/session.js', content); diff --git a/src/commands/advanced-session.js b/src/commands/advanced-session.js index 2cb28b5..b9c950c 100644 --- a/src/commands/advanced-session.js +++ b/src/commands/advanced-session.js @@ -5,6 +5,7 @@ import path from 'path'; import { executeSystemCommand, analyzeCommand, requireApproval, spawnAgent, ToolRegistry } from '../utils/advanced-executioner.js'; import { AIService } from '../services/ai.service.js'; import NamespacedVectorMemory from '../services/namespaced-memory.js'; +import { TaxonomySystem } from '../services/taxonomy.js'; import { ContextScrubber } from '../utils/context-scrubber.js'; import SessionContext from '../utils/session-context.js'; import { UniversalPredictor } from '../services/universal-predictor.js'; @@ -412,6 +413,31 @@ async function handleAutoHealingSafe(command, result) { try { const errorMsg = result.stderr || 'Unknown error'; + // 0. Taxonomy Pattern Check (Instant, Local, Proven) + const patternMatch = taxonomy.match(command, errorMsg); + if (patternMatch) { + console.log((await import('chalk')).default.green(`\n🛡️ Taxonomy Fix (Confidence ${Math.round(patternMatch.effectiveConfidence * 100)}%):`)); + console.log((await import('chalk')).default.bold(patternMatch.fix)); + + const inquirer = (await import('inquirer')).default; + const { confirm } = await inquirer.prompt([{ + type: 'confirm', name: 'confirm', message: 'Execute?', default: true + }]); + + if (confirm) { + try { + const output = await executeSystemCommand(patternMatch.fix, { cwd: SessionContext.getCwd() }); + console.log(output); + taxonomy.updateConfidence(patternMatch.id, true); + } catch(e) { + console.log((await import('chalk')).default.red(`Fix failed: ${e.message}`)); + taxonomy.updateConfidence(patternMatch.id, false); + } + } + return; + } + + // Instant mode: no vector memory — go straight to AI diagnosis if (memory) { // Vector Cache Check diff --git a/src/commands/session.js b/src/commands/session.js index 91b9d3a..12c49dd 100644 --- a/src/commands/session.js +++ b/src/commands/session.js @@ -5,6 +5,7 @@ import path from 'path'; import { executeSystemCommand } from '../utils/executioner.js'; import { AIService } from '../services/ai.service.js'; import NamespacedVectorMemory from '../services/namespaced-memory.js'; +import { TaxonomySystem } from '../services/taxonomy.js'; import { ContextScrubber } from '../utils/context-scrubber.js'; import SessionContext from '../utils/session-context.js'; import { UniversalPredictor } from '../services/universal-predictor.js'; @@ -13,6 +14,12 @@ import os from 'os'; const aiService = new AIService(); const memory = new NamespacedVectorMemory(); +const taxonomy = new TaxonomySystem(); +// Load community patterns on startup if exists +import path from 'path'; +import { fileURLToPath } from 'url'; +const __dirname = path.dirname(fileURLToPath(import.meta.url)); +taxonomy.loadCommunityPatterns(path.join(__dirname, '../../data/community-patterns.json')); // CRITICAL: Global error handler process.on('unhandledRejection', (reason, promise) => { @@ -269,6 +276,31 @@ async function handleAutoHealingSafe(command, result, rl) { try { const errorMsg = result.stderr || 'Unknown error'; + // 0. Taxonomy Pattern Check (Instant, Local, Proven) + const patternMatch = taxonomy.match(command, errorMsg); + if (patternMatch) { + console.log((await import('chalk')).default.green(`\n🛡️ Taxonomy Fix (Confidence ${Math.round(patternMatch.effectiveConfidence * 100)}%):`)); + console.log((await import('chalk')).default.bold(patternMatch.fix)); + + const inquirer = (await import('inquirer')).default; + const { confirm } = await inquirer.prompt([{ + type: 'confirm', name: 'confirm', message: 'Execute?', default: true + }]); + + if (confirm) { + try { + const output = await executeSystemCommand(patternMatch.fix, { cwd: SessionContext.getCwd() }); + console.log(output); + taxonomy.updateConfidence(patternMatch.id, true); + } catch(e) { + console.log((await import('chalk')).default.red(`Fix failed: ${e.message}`)); + taxonomy.updateConfidence(patternMatch.id, false); + } + } + return; + } + + // 1. Vector Cache Check const similar = await Promise.race([ memory.findSimilar(command, errorMsg), diff --git a/src/commands/taxonomy.js b/src/commands/taxonomy.js new file mode 100644 index 0000000..0744139 --- /dev/null +++ b/src/commands/taxonomy.js @@ -0,0 +1,26 @@ +import chalk from 'chalk'; +import { TaxonomySystem } from '../services/taxonomy.js'; + +export async function handleTaxonomyCommand(args) { + const taxonomy = new TaxonomySystem(); + const query = args.join(' '); + + if (!query) { + console.log(chalk.yellow('Please provide a search query. Usage: nebula taxonomy ')); + return; + } + + const results = taxonomy.searchPatterns(query); + if (results.length === 0) { + console.log(chalk.gray(`No patterns found matching '${query}'`)); + return; + } + + console.log(chalk.green(`\n🔍 Found ${results.length} patterns for '${query}':\n`)); + results.forEach(res => { + console.log(chalk.cyan(`ID: ${res.id}`) + chalk.gray(` (Confidence: ${Math.round(res.confidence * 100)}%)`)); + if (res.commandRegex) console.log(`Command Regex: ${res.commandRegex}`); + if (res.errorRegex) console.log(`Error Regex: ${res.errorRegex}`); + console.log(chalk.bold(`Fix: ${res.fix}\n`)); + }); +} diff --git a/src/index.js b/src/index.js index b700734..ca54eef 100755 --- a/src/index.js +++ b/src/index.js @@ -381,6 +381,12 @@ ${chalk.cyan('Commands:')} } // NEW: Setup Mode + if (cleanedArgs[0] === 'taxonomy') { + const { handleTaxonomyCommand } = await import('./commands/taxonomy.js'); + await handleTaxonomyCommand(cleanedArgs.slice(1)); + return; + } + if (cleanedArgs[0] === 'setup') { const { runSetup } = await import('./commands/setup.js'); await runSetup(); @@ -408,6 +414,35 @@ ${chalk.cyan('Commands:')} console.log(chalk.yellow('\n🤖 Nebula is analyzing the failure...')); try { + // 0. Taxonomy Pattern Check + const { TaxonomySystem } = await import('./services/taxonomy.js'); + const taxonomy = new TaxonomySystem(); + const { fileURLToPath } = await import('url'); + const path = await import('path'); + const __dirname = path.dirname(fileURLToPath(import.meta.url)); + taxonomy.loadCommunityPatterns(path.join(__dirname, '../data/community-patterns.json')); + + const patternMatch = taxonomy.match(command, error.message); + if (patternMatch) { + console.log(chalk.green(`\n🛡️ Taxonomy Fix (Confidence ${Math.round(patternMatch.effectiveConfidence * 100)}%):`)); + console.log(chalk.bold(patternMatch.fix)); + + const { confirm } = await inquirer.prompt([{ + type: 'confirm', name: 'confirm', message: 'Execute?', default: true + }]); + + if (confirm) { + try { + const output = await executeSystemCommand(patternMatch.fix, { cwd: process.cwd(), dryRun: flags.dryRun }); + console.log(output); + taxonomy.updateConfidence(patternMatch.id, true); + } catch(e) { + console.log(chalk.red(`Fix failed: ${e.message}`)); + taxonomy.updateConfidence(patternMatch.id, false); + } + } + return; + } // Check Vector Memory (skipped in instant mode — go straight to AI) let suggestedFix; let isCached = false; diff --git a/src/services/taxonomy.js b/src/services/taxonomy.js new file mode 100644 index 0000000..4b53a08 --- /dev/null +++ b/src/services/taxonomy.js @@ -0,0 +1,136 @@ +import Database from 'better-sqlite3'; +import path from 'path'; +import fs from 'fs'; +import { fileURLToPath } from 'url'; +import os from 'os'; + +const __filename = fileURLToPath(import.meta.url); +const __dirname = path.dirname(__filename); + +export class TaxonomySystem { + constructor() { + // Init sqlite db + this.dbDir = path.join(os.homedir(), '.nebula-cli'); + if (!fs.existsSync(this.dbDir)) { + fs.mkdirSync(this.dbDir, { recursive: true }); + } + this.dbPath = path.join(this.dbDir, 'taxonomy.db'); + this.db = new Database(this.dbPath); + this.initDb(); + } + + initDb() { + this.db.exec(` + CREATE TABLE IF NOT EXISTS patterns ( + id TEXT PRIMARY KEY, + commandRegex TEXT, + errorRegex TEXT, + os TEXT, + shell TEXT, + fix TEXT, + confidence REAL DEFAULT 0.5, + source TEXT DEFAULT 'local', + lastUpdated INTEGER + ) + `); + } + + // Load from JSON file (e.g. community patterns) + loadCommunityPatterns(jsonPath) { + if (!fs.existsSync(jsonPath)) return; + const data = JSON.parse(fs.readFileSync(jsonPath, 'utf8')); + const stmt = this.db.prepare(` + INSERT INTO patterns (id, commandRegex, errorRegex, os, shell, fix, confidence, source, lastUpdated) + VALUES (@id, @commandRegex, @errorRegex, @os, @shell, @fix, @confidence, 'community', @lastUpdated) + ON CONFLICT(id) DO UPDATE SET + commandRegex = excluded.commandRegex, + errorRegex = excluded.errorRegex, + os = excluded.os, + shell = excluded.shell, + fix = excluded.fix, + source = excluded.source, + lastUpdated = excluded.lastUpdated + `); + + const updateDb = this.db.transaction((patterns) => { + for (const pat of patterns) { + stmt.run({ + id: pat.id, + commandRegex: pat.commandRegex, + errorRegex: pat.errorRegex, + os: JSON.stringify(pat.os || []), + shell: JSON.stringify(pat.shell || []), + fix: pat.fix, + confidence: pat.confidence || 0.5, + lastUpdated: Date.now() + }); + } + }); + + updateDb(data); + } + + match(command, errorMsg) { + const rows = this.db.prepare('SELECT * FROM patterns ORDER BY confidence DESC').all(); + const currentOs = process.platform; + const currentShell = process.env.SHELL || 'bash'; + + for (const row of rows) { + // Apply decay based on lastUpdated? "Time decay: Older patterns get lower confidence" + // Let's calculate effective confidence + let timeDecay = 1; + if (row.lastUpdated) { + const daysOld = (Date.now() - row.lastUpdated) / (1000 * 60 * 60 * 24); + // Decay by 1% per day, max 50% + timeDecay = Math.max(0.5, 1 - (daysOld * 0.01)); + } + const effectiveConfidence = row.confidence * timeDecay; + + // Context awareness + const osList = JSON.parse(row.os || '[]'); + if (osList.length > 0 && !osList.includes(currentOs)) continue; + + const shellList = JSON.parse(row.shell || '[]'); + // fuzzy shell check + if (shellList.length > 0 && !shellList.some(s => currentShell.includes(s))) continue; + + if (row.commandRegex && !new RegExp(row.commandRegex).test(command)) continue; + + if (row.errorRegex && !new RegExp(row.errorRegex).test(errorMsg)) continue; + + return { + ...row, + effectiveConfidence + }; + } + return null; + } + + updateConfidence(id, success) { + const row = this.db.prepare('SELECT confidence FROM patterns WHERE id = ?').get(id); + if (!row) return; + + // Bayesian-like update + let conf = row.confidence; + if (success) { + conf = conf + 0.1 * (1 - conf); + } else { + conf = conf - 0.2 * conf; // Penalize failure more + } + + this.db.prepare('UPDATE patterns SET confidence = ?, lastUpdated = ? WHERE id = ?') + .run(conf, Date.now(), id); + } + + searchPatterns(query) { + // fuzzy search commandRegex, errorRegex, or fix + const stmt = this.db.prepare(` + SELECT * FROM patterns + WHERE commandRegex LIKE @q + OR errorRegex LIKE @q + OR fix LIKE @q + ORDER BY confidence DESC + `); + return stmt.all({ q: `%${query}%` }); + } +}