diff --git a/CHANGELOG.md b/CHANGELOG.md index 44fac06..4a6f2d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,15 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Removed + +- `analyze --ai` and `--ai-provider`: this only ever returned a fixed template sentence, never called a model. Use `devcompass ai recommend` instead. `analyze --json`'s `metadata` no longer carries the always-`null` `aiInsight` field. +- `fix --batch`, `--batch-mode`, `--only`, `--skip`: these only ever printed "Batch mode features are not yet available". `--dry`/`--preview` still work as aliases for `--dry-run`. +- The unused, unreachable `outdated.collector.js`, `npm-audit.collector.js`, `recommendation.service.js`, and the batch-fix service files (`batch-executor`, `batch-selector`, `supply-chain-fixer`, `license-conflict-fixer`, `quality-fixer`), plus the `data/batch-categories.json` and `data/priorities.json` files only they read. The supply-chain fixer would have "fixed" a flagged typosquat by uninstalling it and installing the look-alike it matched against. +- The local-install warning in `devcompass.js` ("DevCompass is installed locally โ€” npm install -g devcompass"), which fired for global installs and `npx` too and discouraged pinning DevCompass as a devDependency, the actually-recommended setup for teams/CI. + ## [4.1.9] - 2026-10-06 ### Fixed diff --git a/MIGRATION.md b/MIGRATION.md index 209be50..da452d2 100644 --- a/MIGRATION.md +++ b/MIGRATION.md @@ -1,5 +1,18 @@ # Migration Guide +## Unreleased + +- **`analyze --ai` and `--ai-provider` are gone.** These only ever returned a + fixed template sentence โ€” no model was ever called. Use + `devcompass ai recommend` (or `ai ask`/`ai alternatives`) instead, which do + call your configured provider. If you parse `analyze --json`, its `metadata` + no longer includes the always-`null` `aiInsight` field. +- **`fix --batch`, `--batch-mode `, `--only `, and + `--skip ` are gone.** They only ever printed "Batch mode + features are not yet available" โ€” there is nothing to switch to; use plain + `devcompass fix`, `fix --all`, or `fix --yes`. `--dry-run` (and its + `--dry`/`--preview` aliases) are unaffected. + ## From v4.1.4 โ†’ v4.1.5 ### What's New diff --git a/README.md b/README.md index 37e0be6..2a100fe 100644 --- a/README.md +++ b/README.md @@ -157,8 +157,8 @@ devcompass analyze # Get full detailed report devcompass analyze --deep -# Get AI-powered recommendations -devcompass analyze --ai +# Get AI-powered recommendations (after configuring a provider with `devcompass llm add`) +devcompass ai recommend # Generate interactive dependency graph devcompass graph --open @@ -200,9 +200,6 @@ devcompass analyze # Full detailed report (all issues) devcompass analyze --deep -# With AI recommendations -devcompass analyze --ai - # JSON output for CI/CD devcompass analyze --json @@ -695,7 +692,7 @@ Every `devcompass analyze` automatically: ### ๐Ÿ” What AI Features Actually Send -Every AI feature (`devcompass analyze --ai`, `devcompass ai ask`, `devcompass ai recommend`, etc.) sends one HTTP request to whichever provider you configured, containing a system prompt plus a single user message built from your project's own analysis results. Nothing else โ€” not your source code, not file contents, not your filesystem path. Here's the actual request body, field for field (from `src/features/ai/prompt.templates.js` and `ai.command.js`): +Every AI feature (`devcompass ai ask`, `devcompass ai recommend`, `devcompass ai alternatives`, `devcompass ai chat`) sends one HTTP request to whichever provider you configured, containing a system prompt plus a single user message built from your project's own analysis results. Nothing else โ€” not your source code, not file contents, not your filesystem path. Here's the actual request body, field for field (from `src/features/ai/prompt.templates.js` and `ai.command.js`): ```json { @@ -734,7 +731,7 @@ devcompass llm add --provider local --model llama3.2 --base-url http://localhost devcompass llm test local # 6. Use it! -devcompass analyze --ai +devcompass ai recommend devcompass ai ask "What should I update first?" ``` @@ -750,7 +747,7 @@ devcompass llm add --provider openai --token sk-YOUR-KEY --model gpt-4o-mini devcompass llm test openai # Use -devcompass analyze --ai +devcompass ai recommend ``` ### AI Capabilities diff --git a/bin/devcompass.js b/bin/devcompass.js index 201b435..50d8bae 100755 --- a/bin/devcompass.js +++ b/bin/devcompass.js @@ -4,12 +4,6 @@ const { Command } = require('commander'); const chalk = require('chalk'); const packageJson = require('../package.json'); -const isLocalInstall = __dirname.includes('node_modules'); -if (isLocalInstall && process.argv.includes('analyze')) { - console.log(chalk.yellow('\nโš ๏ธ DevCompass is installed locally.')); - console.log(chalk.cyan(' npm install -g devcompass\n')); -} - const program = new Command(); program diff --git a/data/batch-categories.json b/data/batch-categories.json deleted file mode 100644 index 7c03462..0000000 --- a/data/batch-categories.json +++ /dev/null @@ -1,51 +0,0 @@ -[ - { - "id": "supply-chain", - "name": "Supply Chain Security", - "icon": "๐Ÿ›ก๏ธ", - "priority": 1, - "description": "Malicious packages, typosquatting, suspicious scripts" - }, - { - "id": "license", - "name": "License Conflicts", - "icon": "โš–๏ธ", - "priority": 2, - "description": "GPL/AGPL/LGPL package replacements" - }, - { - "id": "quality", - "name": "Package Quality", - "icon": "๐Ÿ“ฆ", - "priority": 3, - "description": "Abandoned, deprecated, stale packages" - }, - { - "id": "security", - "name": "Critical Security", - "icon": "๐Ÿ”", - "priority": 4, - "description": "npm audit vulnerabilities" - }, - { - "id": "ecosystem", - "name": "Ecosystem Alerts", - "icon": "๐Ÿšจ", - "priority": 5, - "description": "Known package issues" - }, - { - "id": "unused", - "name": "Unused Dependencies", - "icon": "๐Ÿงน", - "priority": 6, - "description": "Remove unused packages" - }, - { - "id": "updates", - "name": "Safe Updates", - "icon": "โฌ†๏ธ", - "priority": 7, - "description": "Patch and minor version updates" - } -] \ No newline at end of file diff --git a/data/priorities.json b/data/priorities.json deleted file mode 100644 index 024a511..0000000 --- a/data/priorities.json +++ /dev/null @@ -1,26 +0,0 @@ -{ - "CRITICAL": { - "level": 1, - "label": "CRITICAL", - "color": "red", - "emoji": "๐Ÿ”ด" - }, - "HIGH": { - "level": 2, - "label": "HIGH", - "color": "orange", - "emoji": "๐ŸŸ " - }, - "MEDIUM": { - "level": 3, - "label": "MEDIUM", - "color": "yellow", - "emoji": "๐ŸŸก" - }, - "LOW": { - "level": 4, - "label": "LOW", - "color": "gray", - "emoji": "โšช" - } -} \ No newline at end of file diff --git a/llms.txt b/llms.txt index b0f0ec6..de89014 100644 --- a/llms.txt +++ b/llms.txt @@ -27,7 +27,7 @@ DevCompass is a complement to `npm audit` and Dependabot for teams that also wan ## Complete command reference -- `devcompass analyze` โ€” Full dependency analysis: security, health score, license, unused/outdated packages. Flags: `--deep` (all issues, default shows top 3), `--ai` (AI recommendations), `--json`, `--silent`, `--ci`, `--ci --threshold 8.0`. Health score bands: 9.0-10.0 excellent, 8.0-8.9 good, 6.0-7.9 needs attention, 4.0-5.9 poor, 0.0-3.9 critical. +- `devcompass analyze` โ€” Full dependency analysis: security, health score, license, unused/outdated packages. Flags: `--deep` (all issues, default shows top 3), `--json`, `--silent`, `--ci`, `--ci --threshold 8.0`. Health score bands: 9.0-10.0 excellent, 8.0-8.9 good, 6.0-7.9 needs attention, 4.0-5.9 poor, 0.0-3.9 critical. - `devcompass cve` โ€” CVE database management. `cve key --set --api-key ` / `cve key` (status) / `cve key --remove`; `cve test` (test NVD connection); `cve cache --stats` / `cve cache --clear`. - `devcompass fix` โ€” Automated issue resolution with risk classification (safe/moderate/risky), preview (including a live `package.json` diff), automatic backup before changes, interactive confirmation, and rollback support. Supports `--dry-run`. `--migrate-syntax` additionally rewrites source call-sites broken by a major-version update (built-in codemod, falling back to your configured AI provider), snapshotting every touched file; `devcompass fix undo` reverts the most recent `--migrate-syntax` run. - `devcompass graph` โ€” Interactive dependency graph, 5 layouts: Tree, Force-directed, Radial, Conflict, Analytics. Real-time filtering (vulnerable/outdated/unused), dark/light themes, export to PNG/JSON/HTML. Flag: `--open`. @@ -43,7 +43,7 @@ DevCompass is a complement to `npm audit` and Dependabot for teams that also wan ## AI integration -Four providers: OpenAI, Anthropic, Google, and local Ollama (free, zero-cost, fully offline). Setup pattern: `devcompass llm add --provider [--token | --model --base-url ]`, then `devcompass llm test `, then `devcompass analyze --ai` or `devcompass ai ask "..."`. AI is used for: automatic health assessment context, risk prioritization, breaking-change warnings, migration guidance, interactive Q&A, and package-alternative suggestions (e.g. `ai alternatives moment` โ†’ date-fns/dayjs/Luxon with size comparisons). +Four providers: OpenAI, Anthropic, Google, and local Ollama (free, zero-cost, fully offline). Setup pattern: `devcompass llm add --provider [--token | --model --base-url ]`, then `devcompass llm test `, then `devcompass ai recommend` or `devcompass ai ask "..."`. AI is used for: automatic health assessment context, risk prioritization, breaking-change warnings, migration guidance, interactive Q&A, and package-alternative suggestions (e.g. `ai alternatives moment` โ†’ date-fns/dayjs/Luxon with size comparisons). ## Configuration & file locations diff --git a/src/cli/commands/analyze.cmd.js b/src/cli/commands/analyze.cmd.js index 0b20511..b0d9f06 100644 --- a/src/cli/commands/analyze.cmd.js +++ b/src/cli/commands/analyze.cmd.js @@ -13,8 +13,6 @@ module.exports = function registerAnalyzeCommand(program) { .option('--threshold ', 'Health score threshold for CI mode (default: 7.0)', '7.0') .option('--silent', 'Silent mode - no output') .option('--no-history', 'Skip saving snapshot to history database') - .option('--ai', 'Get AI-powered insights and recommendations') - .option('--ai-provider ', 'AI provider to use (openai, anthropic, google, local)') .action(async (options) => { try { if (options.ci && options.threshold) { @@ -30,7 +28,6 @@ module.exports = function registerAnalyzeCommand(program) { mode: options.deep ? 'deep' : 'default', projectPath: options.path, json: options.json, - aiEnabled: options.ai, saveHistory: options.history !== false, ci: options.ci, ciThreshold: options.ciThreshold !== undefined ? options.ciThreshold : 7.0, diff --git a/src/cli/commands/fix.cmd.js b/src/cli/commands/fix.cmd.js index 43e7c64..ff427c3 100644 --- a/src/cli/commands/fix.cmd.js +++ b/src/cli/commands/fix.cmd.js @@ -12,10 +12,6 @@ module.exports = function registerFixCommand(program) { .option('--dry-run', 'Show what would be fixed without making changes') .option('--dry', 'Alias for --dry-run') .option('--preview', 'Preview fixes without applying') - .option('--batch', 'Interactive batch mode') - .option('--batch-mode ', 'Preset batch mode: critical, high, all') - .option('--only ', 'Fix only specific categories') - .option('--skip ', 'Skip specific categories') .option('--verbose', 'Show detailed output') .option('--migrate-syntax', 'On major-version fixes, also rewrite source call-sites (built-in codemods, falling back to your configured AI provider) โ€” nothing is committed; verify with your tests, or run `devcompass fix undo`') .action(async (action, options) => { @@ -37,10 +33,6 @@ module.exports = function registerFixCommand(program) { skipConfirm: options.yes, dryRun: options.dryRun || options.dry || options.preview, preview: options.preview, - batch: options.batch, - batchMode: options.batchMode, - only: options.only, - skip: options.skip, verbose: options.verbose, migrateSyntax: options.migrateSyntax }); diff --git a/src/features/analyze/collectors/npm-audit.collector.js b/src/features/analyze/collectors/npm-audit.collector.js deleted file mode 100644 index 3a98364..0000000 --- a/src/features/analyze/collectors/npm-audit.collector.js +++ /dev/null @@ -1,74 +0,0 @@ -// src/features/analyze/collectors/npm-audit.collector.js - -const { execSync } = require('child_process'); - -async function checkSecurity(projectPath) { - const empty = { vulnerabilities: [], metadata: { total: 0, critical: 0, high: 0, moderate: 0, low: 0 } }; - - try { - const auditOutput = execSync('npm audit --json', { - cwd: projectPath, - encoding: 'utf8', - stdio: ['pipe', 'pipe', 'pipe'], - timeout: 30000 - }); - - return parseAuditOutput(auditOutput); - } catch (error) { - if (error.stdout) { - try { - return parseAuditOutput(error.stdout); - } catch (parseError) { - if (process.env.DEBUG) console.error('checkSecurity parse failed:', parseError.message); - return empty; - } - } - if (process.env.DEBUG) console.error('checkSecurity failed:', error.message); - return empty; - } -} - -function parseAuditOutput(rawOutput) { - const auditData = JSON.parse(rawOutput); - const vulnerabilities = []; - - if (auditData.vulnerabilities && typeof auditData.vulnerabilities === 'object') { - Object.entries(auditData.vulnerabilities).forEach(([packageName, vuln]) => { - const viaEntry = Array.isArray(vuln.via) ? vuln.via.find(v => typeof v === 'object') : null; - vulnerabilities.push({ - package: packageName, - severity: vuln.severity, - title: viaEntry?.title || 'Security vulnerability', - range: vuln.range, - fixAvailable: vuln.fixAvailable, - cve: viaEntry?.cve || null, - url: viaEntry?.url || null - }); - }); - } - - return { - vulnerabilities, - metadata: { - total: auditData.metadata?.vulnerabilities?.total || 0, - critical: auditData.metadata?.vulnerabilities?.critical || 0, - high: auditData.metadata?.vulnerabilities?.high || 0, - moderate: auditData.metadata?.vulnerabilities?.moderate || 0, - low: auditData.metadata?.vulnerabilities?.low || 0 - } - }; -} - -function calculateSecurityPenalty(metadata) { - if (!metadata) return 0; - - let penalty = 0; - penalty += (metadata.critical || 0) * 2.5; - penalty += (metadata.high || 0) * 1.5; - penalty += (metadata.moderate || 0) * 0.5; - penalty += (metadata.low || 0) * 0.2; - - return Math.min(penalty, 5.0); -} - -module.exports = { checkSecurity, calculateSecurityPenalty }; \ No newline at end of file diff --git a/src/features/analyze/collectors/outdated.collector.js b/src/features/analyze/collectors/outdated.collector.js deleted file mode 100644 index 6570865..0000000 --- a/src/features/analyze/collectors/outdated.collector.js +++ /dev/null @@ -1,51 +0,0 @@ -// src/features/analyze/collectors/outdated.collector.js - -const ncu = require('npm-check-updates'); -const path = require('path'); -const fs = require('fs'); - -async function findOutdatedDeps(projectPath, dependencies = {}) { - try { - const packageFilePath = path.join(projectPath, 'package.json'); - if (!fs.existsSync(packageFilePath)) return []; - - const upgraded = await ncu.run({ - packageFile: packageFilePath, - upgrade: false, - silent: true, - jsonUpgraded: true, - timeout: 30000, - dep: 'prod,dev' - }); - - if (!upgraded || typeof upgraded !== 'object') return []; - - return Object.entries(upgraded).map(([name, latest]) => { - const declared = dependencies[name] || ''; - const current = typeof declared === 'string' ? declared.replace(/^[\^~]/, '') : declared; - - return { name, current, latest, versionsBehind: getVersionDiff(current, latest) }; - }); - } catch (error) { - if (process.env.DEBUG) console.error('Error in findOutdatedDeps:', error.message); - return []; - } -} - -function getVersionDiff(current, latest) { - if (!current || !latest) return 'unknown'; - - const currParts = String(current).split('.').map(Number); - const latestParts = String(latest).split('.').map(Number); - - while (currParts.length < 3) currParts.push(0); - while (latestParts.length < 3) latestParts.push(0); - - if (currParts.some(isNaN) || latestParts.some(isNaN)) return 'unknown'; - - if (currParts[0] !== latestParts[0]) return 'major update'; - if (currParts[1] !== latestParts[1]) return 'minor update'; - return 'patch update'; -} - -module.exports = { findOutdatedDeps }; \ No newline at end of file diff --git a/src/features/analyze/index.js b/src/features/analyze/index.js index 9c89ccb..4f5e3a9 100644 --- a/src/features/analyze/index.js +++ b/src/features/analyze/index.js @@ -26,7 +26,6 @@ async function runAnalyze(options = {}) { mode = 'default', projectPath = process.cwd(), json = false, - aiEnabled = false, saveHistory = true, ci = false, silent = false, @@ -122,8 +121,7 @@ async function runAnalyze(options = {}) { securityScanIncomplete: !!securityData?.incomplete, ecosystemScanIncomplete: !!(shouldRunEcosystem && ecosystemData?.incomplete), healthScore, - totalDependencies, - aiInsight: aiEnabled ? await generateAIInsight(allIssues) : null + totalDependencies }; saveAnalysisCache({ @@ -176,11 +174,4 @@ async function runAnalyze(options = {}) { } } -async function generateAIInsight(issues) { - if (!issues || issues.length === 0) return 'Your project has no detected issues.'; - const critical = issues.filter(i => i.severity === 'CRITICAL' || i.severity === 'HIGH'); - if (critical.length === 0) return 'Your project has minor issues that can be addressed over time.'; - return `Your main risk comes from ${critical.length} high-severity issue(s). Fixing ${critical[0].name} will significantly improve security.`; -} - module.exports = { runAnalyze }; \ No newline at end of file diff --git a/src/features/analyze/renderers/deep.renderer.js b/src/features/analyze/renderers/deep.renderer.js index d9c7ebe..62607e7 100644 --- a/src/features/analyze/renderers/deep.renderer.js +++ b/src/features/analyze/renderers/deep.renderer.js @@ -43,12 +43,6 @@ function renderDeepOutput(issues, metadata) { console.log(`Risky Fixes: ${stats.riskyFixes}`); console.log(''); - if (metadata.aiInsight) { - ConsoleFormatter.section('๐Ÿค– AI Analysis'); - console.log(metadata.aiInsight); - console.log(''); - } - ConsoleFormatter.actions([ { icon: 'โœ”', label: 'Fix safe issues', command: 'devcompass fix' }, { icon: 'โš ๏ธ', label: 'Fix all issues', command: 'devcompass fix --all' }, diff --git a/src/features/analyze/renderers/default.renderer.js b/src/features/analyze/renderers/default.renderer.js index 88632e0..9c05f3b 100644 --- a/src/features/analyze/renderers/default.renderer.js +++ b/src/features/analyze/renderers/default.renderer.js @@ -30,13 +30,6 @@ function renderDefaultOutput(issues, metadata) { }; ConsoleFormatter.summary(stats); - if (metadata.aiInsight) { - console.log(''); - ConsoleFormatter.section('๐Ÿค– AI Insight'); - console.log(metadata.aiInsight); - console.log(''); - } - if (issues.length > 0) { ConsoleFormatter.actions([ { icon: 'โœ”', label: 'Fix safe issues', command: 'devcompass fix' }, diff --git a/src/features/fix/index.js b/src/features/fix/index.js index 10805f3..e023356 100644 --- a/src/features/fix/index.js +++ b/src/features/fix/index.js @@ -23,19 +23,9 @@ async function runFix(options = {}) { skipConfirm = false, dryRun = false, preview = false, - batch = false, - batchMode = null, - only = null, - skip = null, migrateSyntax: migrateSyntaxEnabled = false } = options; - if (batch || batchMode || only || skip) { - console.log('\nโš ๏ธ Batch mode features are not yet available'); - console.log('Use standard fix mode:\n devcompass fix\n devcompass fix --all\n devcompass fix --yes\n'); - return; - } - try { const analysisResult = await runAnalyze({ projectPath, mode: 'silent', silent: true, json: false, saveHistory: false }); const beforeScore = analysisResult.healthScore; diff --git a/src/features/fix/services/batch-executor.service.js b/src/features/fix/services/batch-executor.service.js deleted file mode 100644 index 861dfbb..0000000 --- a/src/features/fix/services/batch-executor.service.js +++ /dev/null @@ -1,243 +0,0 @@ -// src/features/fix/services/batch-executor.service.js - -const chalk = require('chalk'); -const ora = require('ora'); -const { execFile } = require('child_process'); -const { promisify } = require('util'); -const { sanitizePackageName, sanitizeVersion } = require('../../../shared/utils/package-sanitizer'); -const { BackupExecutor } = require('../executors/backup.executor'); - -const execFileAsync = promisify(execFile); - -class BatchExecutor { - constructor(projectPath) { - this.projectPath = projectPath; - this.activeProcesses = new Set(); - } - - async executeBatch(batch, fixes, options = {}) { - const results = { batch: batch.id, batchName: batch.name, totalFixes: Array.isArray(fixes) ? fixes.length : 1, successful: 0, failed: 0, skipped: 0, fixes: [], errors: [] }; - const { preview = false } = options; - - if (preview) { - results.preview = true; - results.operations = Array.isArray(fixes) - ? fixes.map(fix => ({ package: fix.package || fix.name || 'unknown', type: fix.type || batch.id, from: fix.current || fix.from || null, to: fix.latest || fix.to || null })) - : []; - return results; - } - - console.log('\n' + chalk.bold(`${batch.icon} ${batch.name.toUpperCase()}`)); - console.log(chalk.gray('โ”€'.repeat(70))); - - // The standard (non-batch) fix path always backs up package.json/lock - // before mutating anything; this batch path ran npm install/uninstall - // directly with no backup at all, so a bad batch (major version bump, - // lockfile corruption) had no recovery path. - const backupExecutor = new BackupExecutor(this.projectPath); - const backupResult = await backupExecutor.createBackup({ mode: 'batch', batch: batch.id, issueCount: results.totalFixes }); - if (!backupResult.success) { - console.error(chalk.yellow(`โš ๏ธ Backup failed: ${backupResult.error} โ€” proceeding without a backup`)); - } else { - console.log(chalk.gray(`๐Ÿ’พ Backup saved: ${backupResult.path}`)); - } - - try { - switch (batch.id) { - case 'supply-chain': await this.executeSupplyChainBatch(fixes, results); break; - case 'license': await this.executeLicenseBatch(fixes, results); break; - case 'quality': await this.executeQualityBatch(fixes, results); break; - case 'security': await this.executeSecurityBatch(fixes, results); break; - case 'ecosystem': await this.executeEcosystemBatch(fixes, results); break; - case 'unused': await this.executeUnusedBatch(fixes, results); break; - case 'updates': await this.executeUpdatesBatch(fixes, results); break; - default: results.skipped += Array.isArray(fixes) ? fixes.length : 0; - } - } catch (error) { - results.errors.push({ batch: batch.id, error: error.message, severity: 'critical' }); - if (error.message?.includes('ENOSPC') || error.message?.includes('ENOMEM')) { - console.error(chalk.red('\nโŒ Critical error: System resources exhausted')); - throw error; - } - } finally { - await this.cleanup(); - } - - return results; - } - - async executeSupplyChainBatch(fixes, results) { - const SupplyChainFixer = require('./supply-chain-fixer.service'); - const fixer = new SupplyChainFixer(this.projectPath); - - for (const fix of fixes) { - try { - const spinner = ora(`Fixing ${fix.type}: ${fix.package}`).start(); - const result = await fixer.fixWarning(fix, false); - - if (result.success) { - spinner.succeed(`Fixed ${fix.type}: ${fix.package}`); - results.successful++; - results.fixes.push({ type: 'supply-chain', package: fix.package, action: result.action }); - } else { - spinner.fail(`Failed to fix ${fix.package}: ${result.reason}`); - results.failed++; - results.errors.push({ package: fix.package, error: result.reason, severity: 'high' }); - } - } catch (error) { - results.failed++; - results.errors.push({ package: fix.package, error: error.message, severity: 'high' }); - } - } - } - - async executeLicenseBatch(fixes, results) { - const LicenseConflictFixer = require('./license-conflict-fixer.service'); - const fixer = new LicenseConflictFixer(this.projectPath); - - for (const fix of fixes) { - try { - const spinner = ora(`Replacing ${fix.package} (${fix.license})`).start(); - const result = await fixer.fixWarning(fix, false); - - if (result.success) { - spinner.succeed(`Replaced ${fix.package} with ${result.metadata?.to || 'alternative'}`); - results.successful++; - results.fixes.push({ type: 'license', package: fix.package, action: result.action }); - } else { - spinner.fail(`Failed to replace ${fix.package}: ${result.reason}`); - results.failed++; - results.errors.push({ package: fix.package, error: result.reason, severity: 'medium' }); - } - } catch (error) { - results.failed++; - results.errors.push({ package: fix.package, error: error.message, severity: 'medium' }); - } - } - } - - async executeQualityBatch(fixes, results) { - const QualityFixer = require('./quality-fixer.service'); - const fixer = new QualityFixer(this.projectPath); - - for (const fix of fixes) { - try { - const alternative = await fixer.findAlternative(fix.name); - const spinner = ora(`Replacing ${fix.name} (${fix.status})`).start(); - const result = await fixer.fixWarning(fix, false); - - if (result.success && result.action === 'replaced') { - spinner.succeed(`Replaced ${fix.name} with ${alternative?.recommended || 'alternative'}`); - results.successful++; - results.fixes.push({ type: 'quality', package: fix.name, action: `Replaced with ${alternative?.recommended}`, metadata: { from: fix.name, to: alternative?.recommended, reason: fix.status } }); - } else { - spinner.fail(`Failed to replace ${fix.name}: ${result.reason || 'No alternative'}`); - results.failed++; - results.errors.push({ package: fix.name, error: result.reason || 'No alternative available', severity: 'low' }); - } - } catch (error) { - results.failed++; - results.errors.push({ package: fix.name, error: error.message, severity: 'low' }); - } - } - } - - async executeSecurityBatch(fixes, results) { - const spinner = ora('Running npm audit fix...').start(); - try { - await execFileAsync('npm', ['audit', 'fix'], { cwd: this.projectPath, timeout: 60000, maxBuffer: 10 * 1024 * 1024 }); - spinner.succeed('Security vulnerabilities fixed'); - results.successful++; - results.fixes.push({ type: 'security', action: 'npm audit fix' }); - } catch (error) { - spinner.fail('Failed to run npm audit fix'); - results.failed++; - results.errors.push({ action: 'npm audit fix', error: error.message, severity: 'critical' }); - } - } - - // executeEcosystemBatch and executeUpdatesBatch both boil down to "sanitize - // + spinner + npm install @ + record success/failure" for one - // package, differing only in where the name/version/result-shape come from. - // Pulled out the shared install step; the differing bits (skip logic, error - // severity, result shape) stay in each caller. - async _installPackageUpdate({ name, version, results, errorSeverity, errorPackage, buildFixEntry }) { - try { - const safeName = sanitizePackageName(name); - const safeVersion = sanitizeVersion(version); - const spinner = ora(`Updating ${name} to ${version}`).start(); - await execFileAsync('npm', ['install', `${safeName}@${safeVersion}`], { cwd: this.projectPath, timeout: 60000, maxBuffer: 10 * 1024 * 1024 }); - spinner.succeed(`Updated ${name} to ${version}`); - results.successful++; - results.fixes.push(buildFixEntry()); - } catch (error) { - results.failed++; - results.errors.push({ package: errorPackage, error: error.message, severity: errorSeverity }); - } - } - - async executeEcosystemBatch(fixes, results) { - for (const fix of fixes) { - const pkg = (fix.package || '').split('@')[0]; - const version = fix.fix; - - if (!pkg || !version || version.includes('Migrate') || version.includes('Use')) { - results.skipped++; - results.errors.push({ package: pkg || fix.package, error: 'Migration required - manual intervention needed', severity: 'low' }); - continue; - } - - await this._installPackageUpdate({ - name: pkg, - version, - results, - errorSeverity: 'medium', - errorPackage: fix.package, - buildFixEntry: () => ({ type: 'ecosystem', package: pkg, version }) - }); - } - } - - async executeUnusedBatch(fixes, results) { - if (!Array.isArray(fixes) || fixes.length === 0) return; - const packageNames = fixes.map(sanitizePackageName); - const spinner = ora(`Removing ${fixes.length} unused package(s)...`).start(); - - try { - await execFileAsync('npm', ['uninstall', ...packageNames], { cwd: this.projectPath, timeout: 60000, maxBuffer: 10 * 1024 * 1024 }); - spinner.succeed(`Removed ${fixes.length} unused package(s)`); - results.successful += fixes.length; - results.fixes.push({ type: 'unused', packages: fixes }); - } catch (error) { - spinner.fail('Failed to remove unused packages'); - results.failed++; - results.errors.push({ packages: fixes, error: error.message, severity: 'low' }); - } - } - - async executeUpdatesBatch(fixes, results) { - for (const fix of fixes) { - await this._installPackageUpdate({ - name: fix.name, - version: fix.latest, - results, - errorSeverity: 'low', - errorPackage: fix.name, - buildFixEntry: () => ({ type: 'update', package: fix.name, from: fix.current, to: fix.latest }) - }); - } - } - - async cleanup() { - for (const proc of this.activeProcesses) { - try { - if (proc && !proc.killed) proc.kill('SIGTERM'); - } catch (error) { - if (process.env.DEBUG) console.error('Process cleanup error:', error.message); - } - } - this.activeProcesses.clear(); - } -} - -module.exports = BatchExecutor; \ No newline at end of file diff --git a/src/features/fix/services/batch-selector.service.js b/src/features/fix/services/batch-selector.service.js deleted file mode 100644 index 05f4304..0000000 --- a/src/features/fix/services/batch-selector.service.js +++ /dev/null @@ -1,87 +0,0 @@ -// src/features/fix/services/batch-selector.service.js - -const path = require('path'); -const fs = require('fs'); -const readline = require('readline'); -const chalk = require('chalk'); - -const batchCategories = JSON.parse( - fs.readFileSync(path.join(__dirname, '../../../../data/batch-categories.json'), 'utf8') -); - -class BatchSelector { - constructor() { - this.batches = Array.isArray(batchCategories) ? batchCategories : []; - } - - getBatchStats(analysisResults = {}) { - const stats = {}; - this.batches.forEach(batch => { stats[batch.id] = 0; }); - - const { supplyChain, licenseRisk, quality, security, ecosystem, unused, outdated } = analysisResults; - - if (supplyChain?.warnings) stats['supply-chain'] = supplyChain.warnings.length; - if (licenseRisk?.warnings) stats['license'] = licenseRisk.warnings.filter(w => w.autoFixable).length; - if (quality?.packages) stats['quality'] = quality.packages.filter(p => p.status === 'deprecated' || p.status === 'abandoned').length; - if (security?.vulnerabilities) stats['security'] = security.vulnerabilities.length > 0 ? 1 : 0; - if (ecosystem?.alerts) stats['ecosystem'] = ecosystem.alerts.length; - if (Array.isArray(unused)) stats['unused'] = unused.length > 0 ? 1 : 0; - if (Array.isArray(outdated)) { - const safeUpdates = outdated.filter(p => p.updateType === 'patch' || p.updateType === 'minor'); - stats['updates'] = safeUpdates.length > 0 ? 1 : 0; - } - - return stats; - } - - displayBatchMenu(stats) { - console.log('\n' + chalk.cyan.bold('๐Ÿ“ฆ BATCH FIX MODE')); - console.log(chalk.gray('โ•'.repeat(70))); - console.log(chalk.white('Select which categories to fix:\n')); - - this.batches.forEach((batch, index) => { - const count = stats[batch.id] || 0; - console.log(chalk.white(`${batch.icon} ${batch.name}`)); - console.log(chalk.gray(batch.description)); - console.log(count > 0 ? chalk.green(`Fixes available: ${count} fix(es)`) : chalk.gray('Fixes available: none')); - if (index < this.batches.length - 1) console.log(''); - }); - - console.log('\n' + chalk.gray('โ”€'.repeat(70))); - console.log(chalk.white('Preset Modes:')); - console.log(chalk.cyan('c') + ' - Critical only ' + chalk.cyan('h') + ' - High priority ' + chalk.cyan('a') + ' - All safe fixes ' + chalk.cyan('n') + ' - None (cancel)'); - } - - async promptBatchSelection(stats) { - this.displayBatchMenu(stats); - - const rl = readline.createInterface({ input: process.stdin, output: process.stdout }); - return new Promise((resolve) => { - rl.question('> ', (answer) => { - rl.close(); - resolve(this.parseBatchSelection((answer || '').trim().toLowerCase(), stats)); - }); - }); - } - - parseBatchSelection(input, stats) { - if (input === 'c') return this.batches.filter(b => ['supply-chain', 'license', 'security'].includes(b.id)).filter(b => stats[b.id] > 0); - if (input === 'h') return this.batches.filter(b => ['supply-chain', 'license', 'security', 'quality', 'ecosystem'].includes(b.id)).filter(b => stats[b.id] > 0); - if (input === 'a') return this.batches.filter(b => stats[b.id] > 0); - if (input === 'n' || input === '') return []; - - const numbers = input.split(',').map(n => parseInt(n.trim(), 10)).filter(n => !isNaN(n)); - const selectedBatches = []; - - numbers.forEach(num => { - if (num >= 1 && num <= this.batches.length) { - const batch = this.batches[num - 1]; - if (stats[batch.id] > 0) selectedBatches.push(batch); - } - }); - - return selectedBatches; - } -} - -module.exports = BatchSelector; \ No newline at end of file diff --git a/src/features/fix/services/license-conflict-fixer.service.js b/src/features/fix/services/license-conflict-fixer.service.js deleted file mode 100644 index 7515d13..0000000 --- a/src/features/fix/services/license-conflict-fixer.service.js +++ /dev/null @@ -1,66 +0,0 @@ -// src/features/fix/services/license-conflict-fixer.service.js - -const { execFileSync } = require('child_process'); -const chalk = require('chalk'); -const dynamicLicense = require('../../quality/dynamic-license.service'); -const { sanitizePackageName } = require('../../../shared/utils/package-sanitizer'); - -class LicenseConflictFixer { - constructor(projectPath = process.cwd()) { - this.projectPath = projectPath; - this.fixes = []; - this.skipped = []; - this.errors = []; - } - - async fixWarning(warning, dryRun = false) { - const packageName = warning.package; - - try { - const result = await dynamicLicense.analyzePackage(packageName); - const alternative = result?.alternative?.replacement || result?.alternative; - - if (alternative) { - if (!dryRun) { - const safePackageName = sanitizePackageName(packageName); - const safeAlternative = sanitizePackageName(alternative); - - try { - execFileSync('npm', ['uninstall', safePackageName], { stdio: 'pipe', cwd: this.projectPath }); - } catch (error) { /* ignore uninstall errors */ } - - execFileSync('npm', ['install', safeAlternative], { stdio: 'pipe', cwd: this.projectPath }); - } - - this.fixes.push({ - package: packageName, - action: 'replaced', - replacement: alternative, - oldLicense: warning.license, - newLicense: 'MIT', - severity: warning.severity - }); - - return { success: true, action: 'replaced', metadata: { from: packageName, to: alternative, oldLicense: warning.license, newLicense: 'MIT' } }; - } - - this.skipped.push({ package: packageName, license: warning.license, severity: warning.severity, reason: 'No permissive alternative available - manual review required' }); - return { success: false, action: 'review', reason: 'No alternative found' }; - } catch (error) { - this.errors.push({ package: packageName, error: error.message }); - return { success: false, action: 'error', reason: error.message }; - } - } - - getSummary() { - return { totalFixes: this.fixes.length, totalSkipped: this.skipped.length, totalErrors: this.errors.length, fixes: this.fixes, skipped: this.skipped, errors: this.errors }; - } - - reset() { - this.fixes = []; - this.skipped = []; - this.errors = []; - } -} - -module.exports = LicenseConflictFixer; \ No newline at end of file diff --git a/src/features/fix/services/quality-fixer.service.js b/src/features/fix/services/quality-fixer.service.js deleted file mode 100644 index 5ec53f0..0000000 --- a/src/features/fix/services/quality-fixer.service.js +++ /dev/null @@ -1,69 +0,0 @@ -// src/features/fix/services/quality-fixer.service.js - -const { execFileSync } = require('child_process'); -const dynamicQuality = require('../../quality/dynamic-quality.service'); -const { sanitizePackageName } = require('../../../shared/utils/package-sanitizer'); - -class QualityFixer { - constructor(projectPath = process.cwd()) { - this.projectPath = projectPath; - this.fixes = []; - this.skipped = []; - this.errors = []; - } - - async findAlternative(packageName) { - try { - const result = await dynamicQuality.analyzePackage(packageName); - if (result?.alternative) { - const replacement = result.alternative.replacement || result.alternative; - return { recommended: replacement, reason: result.alternative.reason || 'Package has quality issues' }; - } - return null; - } catch (error) { - return null; - } - } - - async fixWarning(pkg, dryRun = false) { - const packageName = pkg.name || pkg.package; - - try { - const alternative = await this.findAlternative(packageName); - - if (alternative) { - if (!dryRun) { - const safePackageName = sanitizePackageName(packageName); - const safeAlternative = sanitizePackageName(alternative.recommended); - - try { - execFileSync('npm', ['uninstall', safePackageName], { stdio: 'pipe', cwd: this.projectPath }); - } catch (error) { /* ignore uninstall errors */ } - - execFileSync('npm', ['install', safeAlternative], { stdio: 'pipe', cwd: this.projectPath }); - } - - this.fixes.push({ package: packageName, action: 'replaced', replacement: alternative.recommended, reason: alternative.reason, status: pkg.status }); - return { success: true, action: 'replaced', metadata: { from: packageName, to: alternative.recommended, reason: alternative.reason } }; - } - - this.skipped.push({ package: packageName, reason: 'No alternative available - requires manual review', status: pkg.status }); - return { success: false, action: 'review', reason: 'No alternative available' }; - } catch (error) { - this.errors.push({ package: packageName, error: error.message }); - return { success: false, action: 'error', reason: error.message }; - } - } - - getSummary() { - return { totalFixes: this.fixes.length, totalSkipped: this.skipped.length, totalErrors: this.errors.length, fixes: this.fixes, skipped: this.skipped, errors: this.errors }; - } - - reset() { - this.fixes = []; - this.skipped = []; - this.errors = []; - } -} - -module.exports = QualityFixer; \ No newline at end of file diff --git a/src/features/fix/services/recommendation.service.js b/src/features/fix/services/recommendation.service.js deleted file mode 100644 index 9667f24..0000000 --- a/src/features/fix/services/recommendation.service.js +++ /dev/null @@ -1,187 +0,0 @@ -// src/features/fix/services/recommendation.service.js - -const path = require('path'); -const fs = require('fs'); - -const PRIORITY = JSON.parse( - fs.readFileSync(path.join(__dirname, '../../../../data/priorities.json'), 'utf8') -); - -function generateSecurityRecommendations(analysisResults = {}) { - const recommendations = []; - const { supplyChain, licenseRisk, quality, security, ecosystem, unused, outdated } = analysisResults; - - if (supplyChain?.warnings) { - supplyChain.warnings.forEach(warning => { - if (warning.type === 'malicious') { - recommendations.push({ - priority: PRIORITY.CRITICAL, - category: 'supply_chain', - title: 'Remove malicious package', - package: warning.package, - action: `npm uninstall ${warning.package}`, - reason: warning.description, - impact: 'Critical security risk eliminated' - }); - } else if (warning.type === 'typosquatting' || warning.type === 'typosquat') { - recommendations.push({ - priority: PRIORITY.HIGH, - category: 'supply_chain', - title: 'Replace typosquatting attempt', - package: warning.package, - action: warning.correctPackage || warning.official - ? `npm uninstall ${warning.package} && npm install ${warning.correctPackage || warning.official}` - : `npm uninstall ${warning.package}`, - reason: `Similar to legitimate package: ${warning.correctPackage || warning.official}`, - impact: 'Prevent potential security breach' - }); - } else if (warning.type === 'install_script') { - recommendations.push({ - priority: PRIORITY.HIGH, - category: 'supply_chain', - title: 'Review suspicious install script', - package: warning.package, - action: `Review the "${warning.package}" script manually before allowing install`, - reason: warning.description, - impact: 'Prevent potentially malicious code execution' - }); - } - }); - } - - if (licenseRisk?.warnings) { - licenseRisk.warnings.forEach(warning => { - if (warning.alternative) { - recommendations.push({ - priority: PRIORITY.HIGH, - category: 'license', - title: 'Resolve license conflict', - package: warning.package, - action: `npm uninstall ${warning.package} && npm install ${warning.alternative.replacement || warning.alternative}`, - reason: `${warning.license} license may conflict with commercial use`, - impact: 'Legal compliance ensured' - }); - } else if (warning.severity === 'critical' || warning.severity === 'high') { - recommendations.push({ - priority: warning.severity === 'critical' ? PRIORITY.CRITICAL : PRIORITY.HIGH, - category: 'license', - title: 'Review license compatibility', - package: warning.package, - action: `Review license compatibility for ${warning.package}`, - reason: `${warning.license} license may conflict with commercial use`, - impact: 'Legal compliance ensured' - }); - } - }); - } - - if (quality?.packages) { - quality.packages.forEach(pkg => { - if (pkg.status === 'deprecated' || pkg.status === 'abandoned') { - const alternative = pkg.alternative?.replacement || pkg.alternative || null; - recommendations.push({ - priority: PRIORITY.HIGH, - category: 'quality', - title: `Replace ${pkg.status} package`, - package: pkg.package || pkg.name, - action: alternative - ? `npm uninstall ${pkg.package || pkg.name} && npm install ${alternative}` - : `Find actively maintained alternative for ${pkg.package || pkg.name}`, - reason: `Package is ${pkg.status}`, - impact: 'Improved stability and security' - }); - } - }); - } - - if (security?.vulnerabilities?.length > 0) { - const criticalVulns = security.vulnerabilities.filter(v => v.severity === 'critical').length; - const highVulns = security.vulnerabilities.filter(v => v.severity === 'high').length; - - if (criticalVulns > 0 || highVulns > 0) { - recommendations.push({ - priority: PRIORITY.CRITICAL, - category: 'security', - title: 'Fix security vulnerabilities', - package: 'multiple', - action: 'npm audit fix', - reason: `${criticalVulns} critical, ${highVulns} high severity vulnerabilities`, - impact: 'Security vulnerabilities resolved' - }); - } - } - - if (ecosystem?.alerts?.length > 0) { - ecosystem.alerts.forEach(alert => { - if (alert.severity === 'high' || alert.severity === 'critical') { - recommendations.push({ - priority: alert.severity === 'critical' ? PRIORITY.CRITICAL : PRIORITY.HIGH, - category: 'ecosystem', - title: 'Address known package issue', - package: alert.package, - action: alert.fix ? `npm install ${alert.package}@${alert.fix}` : `Review ${alert.package}`, - reason: alert.issue || alert.title, - impact: 'Known issues resolved' - }); - } - }); - } - - if (Array.isArray(unused) && unused.length > 0) { - const names = unused.map(u => (typeof u === 'string' ? u : u.name)).filter(Boolean); - if (names.length > 0) { - recommendations.push({ - priority: PRIORITY.MEDIUM, - category: 'cleanup', - title: 'Clean up unused dependencies', - package: 'multiple', - action: `npm uninstall ${names.join(' ')}`, - reason: `${names.length} unused dependencies detected`, - impact: 'Reduced bundle size and maintenance burden' - }); - } - } - - if (Array.isArray(outdated) && outdated.length > 0) { - const safeUpdates = outdated.filter(pkg => pkg.updateType === 'patch' || pkg.updateType === 'minor'); - if (safeUpdates.length > 0) { - recommendations.push({ - priority: PRIORITY.LOW, - category: 'updates', - title: 'Apply safe updates', - package: 'multiple', - action: 'npm update', - reason: `${safeUpdates.length} packages have safe updates available`, - impact: 'Bug fixes and minor improvements' - }); - } - } - - recommendations.sort((a, b) => (a.priority?.level || 99) - (b.priority?.level || 99)); - return recommendations; -} - -function calculateExpectedImprovement(currentScore, recommendations = []) { - let improvement = 0; - - recommendations.forEach(rec => { - switch (rec.priority?.level) { - case 1: improvement += 2.0; break; - case 2: improvement += 1.5; break; - case 3: improvement += 0.5; break; - case 4: improvement += 0.2; break; - } - }); - - const safeCurrentScore = typeof currentScore === 'number' ? currentScore : 0; - const expectedScore = Math.min(safeCurrentScore + improvement, 10); - - return { - current: safeCurrentScore, - expected: expectedScore, - improvement, - improvementPercent: Math.round((improvement / 10) * 100) - }; -} - -module.exports = { generateSecurityRecommendations, calculateExpectedImprovement, PRIORITY }; \ No newline at end of file diff --git a/src/features/fix/services/supply-chain-fixer.service.js b/src/features/fix/services/supply-chain-fixer.service.js deleted file mode 100644 index 68a835b..0000000 --- a/src/features/fix/services/supply-chain-fixer.service.js +++ /dev/null @@ -1,66 +0,0 @@ -// src/features/fix/services/supply-chain-fixer.service.js - -const { execFileSync } = require('child_process'); -const dynamicSecurity = require('../../quality/dynamic-security.service'); -const { sanitizePackageName } = require('../../../shared/utils/package-sanitizer'); - -class SupplyChainFixer { - constructor(projectPath = process.cwd()) { - this.projectPath = projectPath; - this.fixes = []; - this.skipped = []; - this.errors = []; - } - - async fixWarning(warning, dryRun = false) { - const packageName = warning.package; - - try { - if (warning.type === 'typosquatting') { - const check = dynamicSecurity.checkTyposquatting(packageName); - - if (check) { - if (!dryRun) { - execFileSync('npm', ['uninstall', sanitizePackageName(packageName)], { stdio: 'pipe', cwd: this.projectPath }); - if (warning.correctPackage) { - try { - execFileSync('npm', ['install', sanitizePackageName(warning.correctPackage)], { stdio: 'pipe', cwd: this.projectPath }); - } catch (error) { /* ignore โ€” removal already succeeded */ } - } - } - - this.fixes.push({ package: packageName, action: 'removed', correctPackage: warning.correctPackage || null, reason: 'Typosquatting detected', distance: warning.distance }); - return { success: true, action: 'removed', metadata: { package: packageName, correctPackage: warning.correctPackage, reason: 'Typosquatting' } }; - } - - this.skipped.push({ package: packageName, reason: 'No longer flagged as suspicious' }); - return { success: false, action: 'skip', reason: 'Not suspicious' }; - } - - if (warning.type === 'vulnerability') { - if (!dryRun) execFileSync('npm', ['audit', 'fix'], { stdio: 'pipe', cwd: this.projectPath }); - - this.fixes.push({ package: packageName, action: 'updated', reason: 'Security vulnerability fixed', severity: warning.severity }); - return { success: true, action: 'updated', metadata: { package: packageName, severity: warning.severity } }; - } - - this.skipped.push({ package: packageName, reason: `Unknown warning type: ${warning.type}` }); - return { success: false, action: 'skip', reason: 'Unknown type' }; - } catch (error) { - this.errors.push({ package: packageName, error: error.message }); - return { success: false, action: 'error', reason: error.message }; - } - } - - getSummary() { - return { totalFixes: this.fixes.length, totalSkipped: this.skipped.length, totalErrors: this.errors.length, fixes: this.fixes, skipped: this.skipped, errors: this.errors }; - } - - reset() { - this.fixes = []; - this.skipped = []; - this.errors = []; - } -} - -module.exports = SupplyChainFixer; \ No newline at end of file