#!/usr/bin/env node // Smart Roadmap - Main Scanner // AI-Powered Development Roadmap Generator // Version: 1.0.0 // Author: Chahua Development Co., Ltd. const fs = require('fs'); const path = require('path'); // Security const { validateInput, isPathSafe, sanitizePath, checkFilePermissions, isAllowedExtension, checkFileSize } = require('./security/path-validator'); const { SecurityError } = require('./security/security-config'); const SymlinkChecker = require('./security/symlink-checker'); const ReDoSProtector = require('./security/redos-protector'); // Scanners const CodeQualityScanner = require('./scanners/code-quality-scanner'); const DependencyScanner = require('./scanners/dependency-scanner'); const SecurityScanner = require('./scanners/security-scanner'); const ArchitectureScanner = require('./scanners/architecture-scanner'); const TestCoverageScanner = require('./scanners/test-coverage-scanner'); // Analyzers const ComplexityAnalyzer = require('./analyzers/complexity-analyzer'); const PriorityAnalyzer = require('./analyzers/priority-analyzer'); const PatternAnalyzer = require('./analyzers/pattern-analyzer'); const PhaseAnalyzer = require('./analyzers/phase-analyzer'); const BugTracker = require('./analyzers/bug-tracker'); const ProgressCalculator = require('./analyzers/progress-calculator'); const RiskAnalyzer = require('./analyzers/risk-analyzer'); const CodeContextAnalyzer = require('./analyzers/code-context-analyzer'); const DependencyAnalyzer = require('./analyzers/dependency-analyzer'); // NEW const DuplicationDetector = require('./analyzers/duplication-detector'); // NEW const PerformanceAnalyzer = require('./analyzers/performance-analyzer'); // NEW const GitContextAnalyzer = require('./analyzers/git-context-analyzer'); // NEW - Zero-Dependency Git Integration // Reporters const JSONReporter = require('./reporters/json-reporter'); const MarkdownReporter = require('./reporters/markdown-reporter'); const HTMLReporter = require('./reporters/html-reporter'); // Configuration const defaultConfig = require('./config/default-config'); // Configuration const DEFAULT_CONFIG = { scanDirs: ['.'], // Scan entire project from root ignorePatterns: [ 'node_modules', '.git', 'dist', 'build', 'coverage', 'logs', '.next', '.nuxt', 'out', 'tmp', 'docs', // Ignore docs output folder '*.log', // Ignore log files 'project-analysis.json', // Ignore output files 'DEVELOPMENT_ROADMAP*.md', // Ignore generated roadmaps 'dashboard.html' // Ignore generated dashboards ], fileExtensions: [ '.js', '.ts', '.jsx', '.tsx', '.mjs', // JavaScript/TypeScript '.py', // Python '.java', // Java '.cs', // C# '.go', // Go '.php', // PHP '.rb', // Ruby '.cpp', '.cc', '.cxx', '.c', '.h', // C/C++ '.swift', // Swift '.kt', '.kts', // Kotlin '.rs', // Rust '.scala', // Scala '.sql', // SQL '.css', '.scss', '.sass', '.less', // CSS '.html', '.htm', // HTML '.xml', // XML '.yaml', '.yml', // YAML '.json', // JSON '.md', '.markdown' // Markdown ], outputDir: './', enableSecurity: true, complexityThreshold: 10, verbose: false }; class SmartRoadmapScanner { constructor(options = {}) { this.config = { ...DEFAULT_CONFIG, ...defaultConfig, ...options }; this.projectRoot = path.resolve(this.config.projectPath || process.cwd()); // Initialize Git context analyzer (Zero-Dependency) this.gitContext = new GitContextAnalyzer(this.projectRoot); // Initialize all scanners this.scanners = { quality: new CodeQualityScanner(), dependency: new DependencyScanner(), security: new SecurityScanner(), architecture: new ArchitectureScanner(), testCoverage: new TestCoverageScanner() }; // Initialize analyzers (pass projectRoot to PriorityAnalyzer for Git context) this.analyzers = { complexity: new ComplexityAnalyzer(), priority: new PriorityAnalyzer(this.projectRoot), pattern: new PatternAnalyzer(), phase: new PhaseAnalyzer(), bugTracker: new BugTracker(), progress: new ProgressCalculator(), risk: new RiskAnalyzer(), context: new CodeContextAnalyzer(), dependency: new DependencyAnalyzer(), // NEW - Deep dependency analysis duplication: new DuplicationDetector(), // NEW - Code duplication detection performance: new PerformanceAnalyzer() // NEW - Performance bottleneck detection }; // Initialize reporters this.reporters = { json: new JSONReporter(), markdown: new MarkdownReporter(), html: new HTMLReporter() }; // Initialize security this.symlinkChecker = new SymlinkChecker(); this.redosProtector = new ReDoSProtector(); this.stats = { filesScanned: 0, linesOfCode: 0, completedFeatures: [], todoItems: [], fixmeItems: [], bugItems: [], unimplementedItems: [], imports: new Map(), exports: new Map(), testFiles: [], allFindings: [] }; // Patterns for detection this.patterns = { todo: /(?:\/\/|\/\*|\*|#)\s*TODO:?\s*(.+?)(?:\*\/|$)/gi, fixme: /(?:\/\/|\/\*|\*|#)\s*FIXME:?\s*(.+?)(?:\*\/|$)/gi, bug: /(?:\/\/|\/\*|\*|#)\s*BUG:?\s*(.+?)(?:\*\/|$)/gi, completed: /(?:function|class|const|let|export)\s+(\w+)/g, emptyFunction: /(?:function|const|let)\s+(\w+)\s*(?:=\s*)?(?:\([^)]*\))?\s*(?:=>)?\s*\{\s*\}/g, notImplemented: /throw\s+new\s+(?:Error|NotImplementedError)\s*\(\s*['"](?:Not implemented|TODO|FIXME)/gi, imports: /import\s+.*?from\s+['"]([^'"]+)['"]/g, exports: /export\s+(?:default\s+)?(?:class|function|const|let|var)\s+(\w+)/g }; } // Scan entire project async scan() { console.log('[SCAN] Starting comprehensive project analysis...\n'); const startTime = Date.now(); // Scan configured directories for (const dir of this.config.scanDirs) { const dirPath = path.join(this.projectRoot, dir); if (fs.existsSync(dirPath)) { await this.scanDirectory(dirPath, dir); } } const duration = ((Date.now() - startTime) / 1000).toFixed(2); // Collect all tasks from findings const allTasks = this.collectTasks(); // Run priority analyzer const prioritizedTasks = this.analyzers.priority.analyze(allTasks); // Run deep code context analysis const contextAnalysis = this.analyzers.context.analyze(this.stats.allFindings); // Run NEW advanced analyzers (before clearing content) console.log('[ANALYZING] Running advanced dependency analysis...'); const dependencyAnalysis = this.analyzers.dependency.analyze(this.stats.allFindings); console.log('[ANALYZING] Running code duplication detection...'); const duplicationAnalysis = this.analyzers.duplication.analyze(this.stats.allFindings); console.log('[ANALYZING] Running performance pattern detection...'); const performanceAnalysis = this.analyzers.performance.analyze(this.stats.allFindings); // Clear content from findings to save memory (keep only analysis results) this.stats.allFindings.forEach(finding => { delete finding.content; // Remove content after analysis }); // Run new analyzers const phaseAnalysis = this.analyzers.phase.analyze(prioritizedTasks, this.stats.allFindings); const bugAnalysis = this.analyzers.bugTracker.track(prioritizedTasks, this.stats.allFindings); // Analyze Git project history (Zero-Dependency) console.log('[ANALYZING] Analyzing Git project history...'); let gitHistory = null; try { gitHistory = this.gitContext.analyzeProjectHistory(); } catch (error) { console.warn('[WARNING] Git analysis failed (not a Git repository or Git not available)'); } // Generate comprehensive reports const analysis = { metadata: { projectPath: this.projectRoot, projectName: path.basename(this.projectRoot), scannedAt: new Date().toISOString(), duration: `${duration}s`, scanner: 'smart-roadmap v1.0.0', parserUsed: this.analyzers.complexity.getParserUsed() || 'built-in' }, summary: this.generateSummary(prioritizedTasks), files: this.stats.allFindings, tasks: prioritizedTasks, phases: phaseAnalysis, bugs: bugAnalysis, context: contextAnalysis, // Deep code context git: gitHistory, // NEW - Git project history (commits, authors, change frequency) dependencies: dependencyAnalysis, // NEW - Dependency graph analysis duplication: duplicationAnalysis, // NEW - Code duplication detection performance: performanceAnalysis, // NEW - Performance bottleneck detection metrics: this.generateMetrics(), issues: this.generateIssues(prioritizedTasks) }; // Calculate progress and risk after we have all data analysis.progress = this.analyzers.progress.calculate(analysis); analysis.risk = this.analyzers.risk.analyze(analysis); if (this.config.verbose) { console.log('[DEBUG] Phases:', analysis.phases ? 'YES' : 'NO'); console.log('[DEBUG] Bugs:', analysis.bugs ? 'YES' : 'NO'); console.log('[DEBUG] Progress:', analysis.progress ? 'YES' : 'NO'); console.log('[DEBUG] Risk:', analysis.risk ? 'YES' : 'NO'); } this.printSummary(analysis.summary); // Save reports await this.saveReports(analysis); return analysis; } // Collect all tasks from findings collectTasks() { const tasks = []; this.stats.allFindings.forEach(finding => { // Add security issues as tasks if (finding.security) { ['critical', 'high', 'medium', 'low'].forEach(severity => { if (finding.security[severity]) { finding.security[severity].forEach(issue => { tasks.push({ title: issue.message, message: issue.message, type: 'security', severity: severity.toUpperCase(), filePath: finding.filePath, line: issue.line, completed: false }); }); } }); } // Add quality issues as tasks if (finding.quality && finding.quality.codeSmells) { finding.quality.codeSmells.forEach(smell => { tasks.push({ title: smell.type, message: `${smell.type}: ${smell.count} occurrences`, type: 'code-smell', severity: smell.severity || 'MEDIUM', filePath: finding.filePath, completed: false }); }); } // Add architecture issues as tasks if (finding.architecture && finding.architecture.antiPatterns) { finding.architecture.antiPatterns.forEach(ap => { tasks.push({ title: ap.type, message: ap.message || ap.type, type: 'architecture', severity: ap.severity, filePath: finding.filePath, completed: false }); }); } }); // Add legacy TODO/FIXME items this.stats.todoItems.forEach(todo => { tasks.push({ title: todo.message, message: todo.message, type: 'todo', severity: 'MEDIUM', filePath: todo.file, line: todo.line, completed: false }); }); this.stats.fixmeItems.forEach(fixme => { tasks.push({ title: fixme.message, message: fixme.message, type: 'bug', severity: 'CRITICAL', filePath: fixme.file, line: fixme.line, completed: false }); }); return tasks; } // Generate summary statistics generateSummary(prioritizedTasks) { return { totalFiles: this.stats.filesScanned, totalLines: this.stats.linesOfCode, totalTasks: prioritizedTasks.length, completedTasks: prioritizedTasks.filter(t => t.completed).length, pendingTasks: prioritizedTasks.filter(t => !t.completed).length, criticalIssues: prioritizedTasks.filter(t => t.priorityLevel === 'CRITICAL').length, highIssues: prioritizedTasks.filter(t => t.priorityLevel === 'HIGH').length, mediumIssues: prioritizedTasks.filter(t => t.priorityLevel === 'MEDIUM').length, lowIssues: prioritizedTasks.filter(t => t.priorityLevel === 'LOW').length, qualityScore: this.calculateQualityScore(prioritizedTasks) }; } // Generate metrics summary generateMetrics() { const complexityMetrics = this.stats.allFindings .filter(f => f.complexity) .map(f => f.complexity); const patternMetrics = this.stats.allFindings .filter(f => f.patterns) .map(f => f.patterns); return { complexity: this.analyzers.complexity.generateReport(complexityMetrics), patterns: this.analyzers.pattern.generateReport(patternMetrics), architecture: this.scanners.architecture.generateReport( this.stats.allFindings.filter(f => f.architecture).map(f => f.architecture) ), testCoverage: this.scanners.testCoverage.generateReport( this.stats.allFindings.filter(f => f.testCoverage).map(f => f.testCoverage) ) }; } // Generate issues list generateIssues(prioritizedTasks) { return prioritizedTasks.slice(0, 50); // Top 50 issues } // Calculate overall quality score calculateQualityScore(tasks) { let score = 100; tasks.forEach(task => { if (task.priorityLevel === 'CRITICAL') score -= 10; else if (task.priorityLevel === 'HIGH') score -= 5; else if (task.priorityLevel === 'MEDIUM') score -= 2; }); return Math.max(0, Math.min(100, score)); } // Save all report formats async saveReports(analysis) { const outputDir = this.config.outputDir; try { // Save JSON report await this.reporters.json.save(analysis, path.join(outputDir, 'project-analysis.json')); console.log('\n[SAVED] project-analysis.json'); // Save Markdown roadmap await this.reporters.markdown.save(analysis, path.join(outputDir, 'DEVELOPMENT_ROADMAP.md'), 'roadmap'); console.log('[SAVED] DEVELOPMENT_ROADMAP.md'); // Save HTML dashboard await this.reporters.html.save(analysis, path.join(outputDir, 'dashboard.html')); console.log('[SAVED] dashboard.html'); } catch (error) { console.error('[ERROR] Failed to save reports:', error.message); } } // Scan directory recursively async scanDirectory(dirPath, relativePath = '') { try { if (this.config.enableSecurity) { isPathSafe(dirPath); } const entries = fs.readdirSync(dirPath, { withFileTypes: true }); for (const entry of entries) { const fullPath = path.join(dirPath, entry.name); const relPath = path.join(relativePath, entry.name); // Check ignore patterns if (this.shouldIgnore(relPath, entry.name)) { continue; } if (entry.isDirectory()) { await this.scanDirectory(fullPath, relPath); } else if (entry.isFile() && this.shouldScanFile(entry.name)) { await this.scanFile(fullPath, relPath); } } } catch (error) { if (error instanceof SecurityError) { console.warn(`[WARNING] Security: ${error.message}`); } else { console.warn(`[WARNING] Cannot scan ${dirPath}: ${error.message}`); } } } // Check if path should be ignored shouldIgnore(relPath, name) { const normalizedPath = relPath.replace(/\\/g, '/'); return this.config.ignorePatterns.some(pattern => { return name.includes(pattern) || normalizedPath.includes(pattern); }); } // Check if file should be scanned shouldScanFile(filename) { return this.config.fileExtensions.some(ext => filename.endsWith(ext)); } // Scan individual file async scanFile(filePath, relativePath) { try { if (this.config.enableSecurity) { sanitizePath(filePath); checkFilePermissions(filePath, false); checkFileSize(filePath); } const content = fs.readFileSync(filePath, 'utf8'); const lines = content.split('\n'); this.stats.filesScanned++; this.stats.linesOfCode += lines.length; // Run all scanners const findings = { filePath: relativePath, content: content, // Store content for deep analysis language: '', // Will be set from patterns analyzer linesOfCode: lines.length, quality: this.scanners.quality.scan(content, filePath), dependencies: this.scanners.dependency.scan(content, filePath), security: this.scanners.security.scan(content, filePath), architecture: this.scanners.architecture.scan(filePath, content), testCoverage: this.scanners.testCoverage.scan(filePath, content), complexity: this.analyzers.complexity.analyze(filePath, content), patterns: this.analyzers.pattern.analyze(filePath, content) }; // Set language from patterns analyzer findings.language = findings.patterns?.language || 'unknown'; // Store findings this.stats.allFindings.push(findings); // Legacy pattern scanning (for backwards compatibility) this.scanCompletedFeatures(content, relativePath, lines); this.scanIssues(content, relativePath, lines); this.scanUnimplemented(content, relativePath); this.scanDependencies(content, relativePath); // Detect test files if (relativePath.includes('test') || relativePath.includes('spec')) { this.stats.testFiles.push(relativePath); } } catch (error) { if (this.config.verbose) { console.warn(`[WARNING] Error scanning ${relativePath}: ${error.message}`); } } } // Scan for completed features scanCompletedFeatures(content, relativePath, lines) { let match; while ((match = this.patterns.completed.exec(content)) !== null) { const lineNumber = content.substring(0, match.index).split('\n').length; this.stats.completedFeatures.push({ name: match[1], file: relativePath, line: lineNumber, type: 'completed' }); } } // Scan for issues (TODO, FIXME, BUG) scanIssues(content, relativePath, lines) { // TODO comments let match; while ((match = this.patterns.todo.exec(content)) !== null) { const lineNumber = content.substring(0, match.index).split('\n').length; this.stats.todoItems.push({ file: relativePath, line: lineNumber, message: (match[1] || '').trim(), priority: 'MEDIUM' }); } // FIXME comments while ((match = this.patterns.fixme.exec(content)) !== null) { const lineNumber = content.substring(0, match.index).split('\n').length; this.stats.fixmeItems.push({ file: relativePath, line: lineNumber, message: (match[1] || '').trim(), priority: 'CRITICAL' }); } // BUG comments while ((match = this.patterns.bug.exec(content)) !== null) { const lineNumber = content.substring(0, match.index).split('\n').length; this.stats.bugItems.push({ file: relativePath, line: lineNumber, message: (match[1] || '').trim(), priority: 'CRITICAL' }); } } // Scan for unimplemented code scanUnimplemented(content, relativePath) { // Empty functions let match; while ((match = this.patterns.emptyFunction.exec(content)) !== null) { const lineNumber = content.substring(0, match.index).split('\n').length; this.stats.unimplementedItems.push({ type: 'empty-function', name: match[1], file: relativePath, line: lineNumber, priority: 'MEDIUM' }); } // Not implemented throws while ((match = this.patterns.notImplemented.exec(content)) !== null) { const lineNumber = content.substring(0, match.index).split('\n').length; this.stats.unimplementedItems.push({ type: 'not-implemented', name: 'unknown', file: relativePath, line: lineNumber, priority: 'HIGH' }); } } // Scan dependencies scanDependencies(content, relativePath) { // Imports let match; while ((match = this.patterns.imports.exec(content)) !== null) { const imported = match[1]; if (!this.stats.imports.has(imported)) { this.stats.imports.set(imported, []); } this.stats.imports.get(imported).push(relativePath); } // Exports while ((match = this.patterns.exports.exec(content)) !== null) { const exported = match[1]; if (!this.stats.exports.has(exported)) { this.stats.exports.set(exported, []); } this.stats.exports.get(exported).push(relativePath); } } // Print summary printSummary(summary) { console.log('\n' + '='.repeat(70)); console.log('[SUMMARY] Smart Roadmap Analysis'); console.log('='.repeat(70)); console.log(`Files Scanned: ${summary.totalFiles}`); console.log(`Lines of Code: ${summary.totalLines.toLocaleString()}`); console.log(`Quality Score: ${summary.qualityScore}/100`); console.log(`\nTasks:`); console.log(` Total: ${summary.totalTasks}`); console.log(` Completed: ${summary.completedTasks}`); console.log(` Pending: ${summary.pendingTasks}`); console.log(`\nPriority Breakdown:`); console.log(` Critical: ${summary.criticalIssues}`); console.log(` High: ${summary.highIssues}`); console.log(` Medium: ${summary.mediumIssues}`); console.log(` Low: ${summary.lowIssues}`); console.log('='.repeat(70) + '\n'); } // Save reports to files async saveReports(analysis) { const outputDir = this.config.outputDir || './docs'; try { // Save JSON analysis await this.reporters.json.save(analysis, path.join(outputDir, 'project-analysis.json')); console.log('[SAVED] project-analysis.json'); // Save Markdown roadmap - ENGLISH await this.reporters.markdown.save(analysis, path.join(outputDir, 'DEVELOPMENT_ROADMAP.md'), 'roadmap', 'en'); console.log('[SAVED] DEVELOPMENT_ROADMAP.md (English)'); // Save Markdown roadmap - THAI await this.reporters.markdown.save(analysis, path.join(outputDir, 'DEVELOPMENT_ROADMAP.th.md'), 'roadmap', 'th'); console.log('[SAVED] DEVELOPMENT_ROADMAP.th.md (Thai)'); // Save HTML dashboard await this.reporters.html.save(analysis, path.join(outputDir, 'dashboard.html')); console.log('[SAVED] dashboard.html'); } catch (error) { console.error('[ERROR] Failed to save reports:', error.message); throw error; } } } module.exports = SmartRoadmapScanner;