@triedotdev/mcp 1.0.26 → 1.0.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/tools/scan.ts","../src/orchestrator/context-analyzer.ts","../src/orchestrator/risk-assessor.ts","../src/orchestrator/triager.ts","../src/utils/parallel-executor.ts","../src/utils/cache-manager.ts","../src/orchestrator/executor.ts","../src/analysis/cross-file.ts","../src/analysis/semantic-analyzer.ts","../src/analysis/smart-prioritizer.ts","../src/analysis/attack-surface.ts","../src/trie/symbol-index.ts","../src/trie/incremental-scanner.ts","../src/utils/streaming.ts","../src/utils/issue-analyzer.ts","../src/cli/interactive-dashboard.ts","../src/config/loader.ts","../src/config/validation.ts","../src/integrations/slack.ts","../src/integrations/team-collaboration.ts","../src/tools/fix.ts","../src/ai/prompts.ts"],"sourcesContent":["import { readFile, readdir, writeFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { basename, isAbsolute, resolve, join, extname } from 'path';\nimport { ContextAnalyzer } from '../orchestrator/context-analyzer.js';\nimport { RiskAssessor } from '../orchestrator/risk-assessor.js';\nimport { Triager } from '../orchestrator/triager.js';\nimport { Executor } from '../orchestrator/executor.js';\nimport { getAgentRegistry } from '../agents/registry.js';\nimport { buildDependencyGraph, formatDependencyGraph } from '../analysis/cross-file.js';\nimport { SemanticAnalyzer, formatSemanticIssues } from '../analysis/semantic-analyzer.js';\nimport { prioritizeIssues, formatPrioritizedResults, type PrioritizationResult } from '../analysis/smart-prioritizer.js';\nimport { AttackSurfaceAnalyzer, formatAttackSurface } from '../analysis/attack-surface.js';\nimport { \n IncrementalScanner, \n formatIncrementalScanResult,\n getVulnerabilityStats,\n getSymbolIndex \n} from '../trie/index.js';\nimport { ProgressReporter } from '../utils/progress.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { StreamingManager, formatConsoleUpdate } from '../utils/streaming.js';\nimport { IssueAnalyzer, type PriorityReport } from '../utils/issue-analyzer.js';\nimport { InteractiveDashboard } from '../cli/interactive-dashboard.js';\nimport { loadConfig } from '../config/loader.js';\nimport { SlackIntegration } from '../integrations/slack.js';\nimport { TeamCollaborationManager, type TeamMember, type IssueAssignment } from '../integrations/team-collaboration.js';\nimport type { ScanResult, Issue, CodeContext, RiskLevel } from '../types/index.js';\n\n// File extensions to scan\nconst SCANNABLE_EXTENSIONS = new Set([\n '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs',\n '.vue', '.svelte', '.astro',\n '.py', '.go', '.rs',\n '.json', '.yaml', '.yml',\n '.css', '.scss', '.less'\n]);\n\n// Directories to skip\nconst SKIP_DIRS = new Set([\n 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt',\n 'coverage', '.nyc_output', '__pycache__', '.pytest_cache',\n 'vendor', '.venv', 'venv', 'target', '.turbo', '.cache'\n]);\n\nexport class TrieScanTool {\n private contextAnalyzer = new ContextAnalyzer();\n private riskAssessor = new RiskAssessor();\n private triager = new Triager();\n private executor = new Executor();\n private agentRegistry = getAgentRegistry();\n private incrementalScanner: IncrementalScanner | null = null;\n private progress: ProgressReporter = new ProgressReporter();\n private customAgentsLoaded = false;\n\n /**\n * Ensure custom agents are loaded before using the registry\n */\n private async ensureCustomAgentsLoaded(): Promise<void> {\n if (!this.customAgentsLoaded) {\n await this.agentRegistry.loadCustomAgents();\n this.customAgentsLoaded = true;\n }\n }\n\n async execute(args: any) {\n const startTime = Date.now();\n\n try {\n let { files, context: userContext, forceAgents, directory } = args;\n const yoloMode = Boolean(args?.yoloMode ?? args?.yolo);\n const excludeAgentsInput = Array.isArray(args?.excludeAgents) ? args.excludeAgents : [];\n const excludeAgents = new Set<string>(\n excludeAgentsInput\n .filter((x: unknown): x is string => typeof x === 'string' && x.trim().length > 0)\n .map((s: string) => s.trim())\n );\n // Hard safety rule: agent-smith must never run in YOLO mode\n if (yoloMode) excludeAgents.add('agent-smith');\n const config = await loadConfig();\n\n // Get the working directory - uses smart detection if not explicitly provided\n const workDir = getWorkingDirectory(directory);\n const scanDir = workDir;\n\n const outputConfig = (config as Record<string, unknown>).output as Record<string, unknown> | undefined ?? {};\n const agentConfig = (config as Record<string, unknown>).agents as Record<string, unknown> | undefined ?? {};\n\n const streamingEnabled = args?.streaming ?? outputConfig?.streaming ?? true;\n const interactiveRequested = args?.interactive ?? outputConfig?.interactive ?? false;\n const interactiveEnabled = Boolean(interactiveRequested && process.stdout.isTTY);\n const cacheEnabled = args?.cache ?? agentConfig?.cache ?? true;\n const parallelEnabled = args?.parallel ?? agentConfig?.parallel ?? true;\n const maxConcurrency = args?.maxConcurrency ?? agentConfig?.maxConcurrency;\n const timeoutMs = args?.timeoutMs ?? agentConfig?.timeout ?? 120000;\n const useWorkerThreads = args?.workers ?? true;\n\n const streamingManager = streamingEnabled ? new StreamingManager() : undefined;\n const dashboard = interactiveEnabled ? new InteractiveDashboard() : undefined;\n\n if (dashboard && streamingManager) {\n streamingManager.subscribe(update => dashboard.handleStreamUpdate(update));\n await dashboard.start();\n } else if (streamingManager) {\n streamingManager.subscribe(update => {\n const line = formatConsoleUpdate(update);\n if (line) {\n console.error(line);\n }\n });\n }\n\n // Start progress reporting\n if (!interactiveEnabled) {\n this.progress.startPhase('init', '🔺 TRIE AGENT - AI-Powered Code Analysis');\n }\n\n // If no files specified, scan the entire codebase\n if (!files || !Array.isArray(files) || files.length === 0) {\n this.progress.startPhase('discovery', `Discovering files in ${basename(workDir)}...`);\n files = await this.discoverFiles(workDir);\n this.progress.completePhase(`Found ${files.length} files`);\n }\n\n // Resolve file paths\n const resolvedFiles = files.map((f: string) => {\n if (isAbsolute(f)) {\n return f;\n }\n return resolve(workDir, f);\n });\n\n // Validate files exist\n const validFiles = resolvedFiles.filter((f: string) => {\n if (!existsSync(f)) {\n this.progress.warn('File not found', f);\n return false;\n }\n return true;\n });\n\n if (validFiles.length === 0) {\n throw new Error('No valid files found to scan. Specify files or run from project root.');\n }\n\n streamingManager?.startScan(validFiles.length);\n\n // Initialize trie-based incremental scanner\n if (!this.incrementalScanner) {\n this.incrementalScanner = new IncrementalScanner(workDir);\n await this.incrementalScanner.loadCache();\n }\n\n // Phase 1: Quick pattern scan\n this.progress.startPhase('reading', `Scanning ${validFiles.length} files...`);\n const vulnStats = getVulnerabilityStats();\n this.progress.update(`${vulnStats.total} vulnerability signatures loaded`);\n \n const trieResult = await this.incrementalScanner.scanFiles(\n validFiles,\n false,\n (filePath) => {\n if (streamingManager) {\n streamingManager.updateCurrentFile(filePath);\n streamingManager.completeFile();\n }\n }\n );\n if (trieResult.totalVulnerabilities > 0) {\n this.progress.finding('serious', `${trieResult.totalVulnerabilities} potential issues detected`);\n }\n this.progress.completePhase(`${trieResult.filesScanned} files scanned (${trieResult.cacheHitRate.toFixed(0)}% cached)`);\n\n // Save cache for next run\n await this.incrementalScanner.saveCache();\n\n // Phase 2: Context Analysis\n this.progress.startPhase('analyzing', 'Analyzing code context...');\n \n // Show summary of files (don't list all if too many)\n if (validFiles.length <= 5) {\n for (const file of validFiles) {\n this.progress.file('Reading', file);\n }\n } else {\n const byExt = this.groupFilesByExtension(validFiles);\n for (const [ext, count] of Object.entries(byExt)) {\n this.progress.update(`${count} ${ext} files`);\n }\n }\n\n const context = await this.contextAnalyzer.analyze(validFiles, userContext);\n this.logContextAnalysis(context);\n\n // Phase 3: Risk Assessment\n this.progress.startPhase('analyzing', 'Assessing risk level...');\n const riskLevel = this.riskAssessor.assessRisk(context);\n this.logRiskAssessment(context, riskLevel);\n\n // Phase 4: Agent Selection\n this.progress.startPhase('ai-review', 'Selecting AI agents...');\n \n // Ensure custom agents are loaded before agent selection\n await this.ensureCustomAgentsLoaded();\n \n let selectedAgents = forceAgents\n ? this.agentRegistry.getAgentsByNames(forceAgents)\n : await this.triager.selectAgents(context, riskLevel);\n\n if (excludeAgents.size > 0) {\n const before = selectedAgents.length;\n selectedAgents = selectedAgents.filter(a => !excludeAgents.has(a.name));\n const removed = before - selectedAgents.length;\n if (removed > 0) {\n console.error(` 🚫 Excluding ${removed} agent(s): ${Array.from(excludeAgents).join(', ')}`);\n }\n }\n\n const allAgentNames = this.agentRegistry.getAgentNames();\n this.logTriaging(selectedAgents.map(a => a.name), allAgentNames, context, riskLevel);\n this.progress.update(`${selectedAgents.length} agents selected for ${riskLevel} risk code`);\n\n // Phase 5: AI-Powered Agent Analysis\n this.progress.startPhase('ai-review', 'Running AI analysis...');\n this.progress.ai('Starting agent analysis', `${selectedAgents.length} agents`);\n \n const agentResults = await this.executor.executeAgents(\n selectedAgents,\n validFiles,\n { workingDir: workDir },\n streamingManager ? {\n streaming: streamingManager,\n parallel: parallelEnabled,\n cacheEnabled,\n maxConcurrency,\n useWorkerThreads,\n timeoutMs\n } : {\n parallel: parallelEnabled,\n cacheEnabled,\n maxConcurrency,\n useWorkerThreads,\n timeoutMs\n }\n );\n\n // Phase 6: Prioritization\n const allIssues = agentResults.flatMap(result => result.issues);\n const issueAnalyzer = new IssueAnalyzer();\n const priorityReport = issueAnalyzer.analyzeIssues(allIssues);\n \n this.progress.startPhase('prioritizing', 'Prioritizing findings...');\n const prioritized = prioritizeIssues(allIssues);\n \n if (prioritized.critical.length > 0) {\n this.progress.finding('critical', `${prioritized.critical.length} critical issues`);\n }\n if (prioritized.important.length > 0) {\n this.progress.finding('serious', `${prioritized.important.length} important issues`);\n }\n this.progress.update(`Filtered ${prioritized.noise} noise items`);\n \n const totalIssues = allIssues.length;\n const critical = allIssues.filter(i => i.severity === 'critical').length;\n const serious = allIssues.filter(i => i.severity === 'serious').length;\n const moderate = allIssues.filter(i => i.severity === 'moderate').length;\n const low = allIssues.filter(i => i.severity === 'low').length;\n\n // Calculate score based on PRIORITIZED issues, not raw count\n const prioritizedCritical = prioritized.critical.length;\n const prioritizedImportant = prioritized.important.length;\n const score = Math.max(0, 100 - (prioritizedCritical * 25 + prioritizedImportant * 10));\n\n const result: ScanResult = {\n triaging: {\n agentsActivated: selectedAgents.map(a => a.name),\n agentsSkipped: await this.triager.getSkippedAgents(context, riskLevel),\n reason: this.triager.getTriagingReason(context, riskLevel),\n riskLevel,\n confidence: await this.triager.getTriagingConfidence(context, riskLevel)\n },\n results: {\n totalIssues,\n critical,\n serious,\n moderate,\n low,\n score,\n issues: allIssues,\n agentResults\n },\n executionTime: Date.now() - startTime,\n context\n };\n\n // Get code snippets for issues\n await this.enrichIssuesWithSnippets(allIssues);\n\n // Phase 7: Cross-file analysis (if scanning multiple files)\n if (validFiles.length > 3) {\n this.progress.update('Cross-file dependency analysis...');\n try {\n const depGraph = await buildDependencyGraph(scanDir, 100);\n if (depGraph.issues.length > 0) {\n formatDependencyGraph(depGraph);\n this.progress.finding('moderate', `${depGraph.issues.length} cross-file issues`);\n }\n } catch {\n // Skip silently\n }\n }\n\n // Phase 8: Semantic Analysis\n let semanticOutput = '';\n if (validFiles.length > 0) {\n this.progress.ai('Semantic analysis', 'Data flow, auth chains, business logic');\n try {\n const semanticAnalyzer = new SemanticAnalyzer();\n const semanticIssues = await semanticAnalyzer.analyze(validFiles, scanDir);\n const summary = semanticAnalyzer.getSummary();\n\n if (semanticIssues.length > 0) {\n semanticOutput = formatSemanticIssues(semanticIssues);\n this.progress.update(`Analyzed ${summary.functionsAnalyzed} functions, ${summary.routesFound} routes`);\n \n const semanticCritical = semanticIssues.filter(i => i.severity === 'critical').length;\n const semanticSerious = semanticIssues.filter(i => i.severity === 'serious').length;\n if (semanticCritical > 0) {\n this.progress.finding('critical', `${semanticCritical} data flow/auth issues`);\n }\n if (semanticSerious > 0) {\n this.progress.finding('serious', `${semanticSerious} business logic issues`);\n }\n }\n } catch {\n // Skip silently\n }\n }\n\n // Phase 9: Attack Surface Analysis\n let attackSurfaceOutput = '';\n if (validFiles.length > 0) {\n this.progress.ai('Attack surface mapping', 'Endpoints, auth coverage');\n try {\n const attackSurfaceAnalyzer = new AttackSurfaceAnalyzer();\n const surface = await attackSurfaceAnalyzer.analyze(validFiles, scanDir);\n \n if (surface.endpoints.length > 0) {\n attackSurfaceOutput = formatAttackSurface(surface);\n this.progress.update(`${surface.summary.totalEndpoints} endpoints found`);\n if (surface.summary.unprotectedSensitiveEndpoints > 0) {\n this.progress.finding('serious', `${surface.summary.unprotectedSensitiveEndpoints} unprotected sensitive endpoints`);\n }\n }\n } catch (e) {\n // Skip silently\n }\n }\n\n // Include trie scan results\n if (trieResult.totalVulnerabilities > 0) {\n formatIncrementalScanResult(trieResult);\n }\n\n // Symbol index stats (silent)\n const symbolIndex = getSymbolIndex();\n symbolIndex.getStats();\n\n // Generate smart prioritization output\n formatPrioritizedResults(prioritized);\n\n // Team collaboration: load members and assign issues\n const teamMembers = await this.loadTeamMembers(workDir);\n const teamManager = new TeamCollaborationManager();\n for (const member of teamMembers) {\n teamManager.addTeamMember(member);\n }\n const assignments = teamMembers.length > 0\n ? teamManager.assignIssues(allIssues, priorityReport)\n : [];\n\n // Notifications (Slack)\n const integrationsConfig = (config as Record<string, unknown>).integrations as Record<string, unknown> | undefined;\n const slackConfig = integrationsConfig?.slack as Record<string, unknown> | undefined;\n if (slackConfig?.enabled && slackConfig.webhook) {\n const slack = new SlackIntegration({\n webhookUrl: slackConfig.webhook as string,\n channel: slackConfig.channel as string | undefined\n });\n const repositoryName = process.env.GITHUB_REPOSITORY || basename(workDir);\n const branch = process.env.GITHUB_REF_NAME || 'main';\n\n try {\n await slack.sendScanNotification(allIssues, priorityReport, repositoryName, branch);\n const criticalIssues = allIssues.filter(i => i.severity === 'critical');\n if (criticalIssues.length > 0) {\n await slack.sendCriticalAlert(criticalIssues, repositoryName);\n }\n } catch {\n // Ignore notification failures\n }\n }\n\n // Complete!\n const actionableIssues = prioritized.critical.length + prioritized.important.length;\n this.progress.complete(`${actionableIssues} actionable issues found`);\n\n // Create a CONCISE summary for chat display (not the full 40k line report)\n const chatSummary = await this.formatChatSummary(\n result,\n prioritized,\n semanticOutput,\n attackSurfaceOutput,\n priorityReport,\n assignments\n );\n\n if (args?.format === 'json' && args?.output) {\n const report = {\n ...result,\n prioritization: prioritized,\n grouping: priorityReport\n };\n await writeFile(args.output, JSON.stringify(report, null, 2));\n }\n\n return {\n content: [\n {\n type: 'text',\n text: chatSummary\n }\n ]\n };\n\n } catch (error) {\n return {\n content: [\n {\n type: 'text',\n text: `❌ Scan failed: ${error instanceof Error ? error.message : String(error)}`\n }\n ]\n };\n }\n }\n\n private logContextAnalysis(context: CodeContext): void {\n console.error('\\n 📋 Detected Context Signals:');\n \n const signals = [];\n if (context.touchesAuth) signals.push('🔐 Authentication/Authorization');\n if (context.touchesPayments) signals.push('💳 Payment Processing');\n if (context.touchesDatabase) signals.push('🗄️ Database Operations');\n if (context.touchesAPI) signals.push('🌐 API Endpoints');\n if (context.touchesUI) signals.push('🎨 User Interface');\n if (context.touchesUserData) signals.push('👤 User/Personal Data');\n if (context.touchesHealthData) signals.push('🏥 Protected Health Info (PHI)');\n if (context.touchesSecurityConfig) signals.push('🔒 Security Configuration');\n \n if (signals.length === 0) {\n signals.push('📝 General Code Changes');\n }\n\n for (const signal of signals) {\n console.error(` ${signal}`);\n }\n \n console.error(`\\n 📊 Lines analyzed: ${context.linesChanged}`);\n console.error(` 📁 File patterns: ${context.filePatterns.join(', ') || 'none detected'}`);\n console.error('');\n }\n\n private logRiskAssessment(context: CodeContext, riskLevel: RiskLevel): void {\n const riskEmoji = {\n low: '🟢',\n medium: '🟡', \n high: '🟠',\n critical: '🔴'\n };\n\n console.error(`\\n ${riskEmoji[riskLevel]} Risk Level: ${riskLevel.toUpperCase()}`);\n \n const factors = [];\n if (context.touchesPayments) factors.push('Payment processing = automatic HIGH risk');\n if (context.touchesAuth) factors.push('Auth code requires extra scrutiny');\n if (context.touchesHealthData) factors.push('HIPAA data = CRITICAL compliance risk');\n if (context.touchesUserData) factors.push('PII handling requires privacy review');\n if (context.touchesSecurityConfig) factors.push('Security config changes need review');\n if (context.isNewFeature) factors.push('New features need architecture review');\n\n if (factors.length > 0) {\n console.error(' Risk factors:');\n for (const factor of factors) {\n console.error(` • ${factor}`);\n }\n }\n console.error('');\n }\n\n private logTriaging(\n selectedNames: string[], \n allAgentNames: string[],\n context: CodeContext,\n riskLevel: RiskLevel\n ): void {\n console.error(`\\n 🎯 Agents Selected: ${selectedNames.length} of ${allAgentNames.length} available`);\n console.error('');\n \n for (const name of allAgentNames) {\n const isSelected = selectedNames.includes(name);\n const icon = isSelected ? '✅' : '⬜';\n const reason = isSelected ? this.getAgentReason(name, context, riskLevel) : 'not needed for this context';\n console.error(` ${icon} ${name}: ${reason}`);\n }\n console.error('');\n }\n\n private getAgentReason(agentName: string, context: CodeContext, _riskLevel: RiskLevel): string {\n const reasons: Record<string, string> = {\n 'security': context.touchesAuth ? 'auth code detected' : \n context.touchesPayments ? 'payment code detected' :\n context.touchesAPI ? 'API endpoints detected' :\n context.touchesDatabase ? 'database operations detected' :\n 'security patterns detected',\n 'privacy': context.touchesUserData ? 'PII handling detected' :\n context.touchesHealthData ? 'PHI/HIPAA data detected' :\n context.touchesAuth ? 'user credentials detected' :\n 'data privacy patterns detected',\n 'typecheck': 'always runs - type safety is fundamental',\n 'comprehension': 'always runs - explains changes to stakeholders',\n 'legal': context.touchesHealthData ? 'HIPAA compliance required' :\n context.touchesPayments ? 'payment regulations apply' :\n context.touchesUserData ? 'data protection laws apply' :\n 'legal patterns detected',\n 'accessibility': context.touchesUI ? 'UI components detected' : 'UI patterns detected',\n 'test': context.isNewFeature ? 'new feature needs tests' :\n context.touchesAuth ? 'auth code needs tests' :\n 'test coverage needed',\n 'software-architect': context.isNewFeature ? 'architecture review for new feature' :\n context.touchesDatabase ? 'database schema review' :\n 'architecture patterns detected',\n 'devops': context.touchesSecurityConfig ? 'security config detected' :\n context.touchesDatabase ? 'infrastructure changes' :\n 'deployment patterns detected',\n 'bug-finding': context.touchesPayments ? 'payments require zero bugs' :\n context.isNewFeature ? 'new feature bug check' :\n 'bug patterns detected',\n 'user-testing': context.touchesUI ? 'UX review for UI changes' : 'user flow detected'\n };\n \n return reasons[agentName] || 'context-based activation';\n }\n\n private async enrichIssuesWithSnippets(issues: Issue[]): Promise<(Issue & { snippet?: string })[]> {\n const enriched: (Issue & { snippet?: string })[] = [];\n\n for (const issue of issues) {\n try {\n if (issue.line && existsSync(issue.file)) {\n const content = await readFile(issue.file, 'utf-8');\n const lines = content.split('\\n');\n const startLine = Math.max(0, issue.line - 3);\n const endLine = Math.min(lines.length, issue.line + 2);\n \n const snippetLines = lines.slice(startLine, endLine).map((line, idx) => {\n const lineNum = startLine + idx + 1;\n const marker = lineNum === issue.line ? '→' : ' ';\n return `${marker} ${lineNum.toString().padStart(4)} | ${line}`;\n });\n \n enriched.push({\n ...issue,\n snippet: snippetLines.join('\\n')\n });\n } else {\n enriched.push(issue);\n }\n } catch {\n enriched.push(issue);\n }\n }\n\n return enriched;\n }\n\n /**\n * Format a CONCISE summary for chat/terminal display\n * This is what users see - actionable, not overwhelming\n */\n private async formatChatSummary(\n result: ScanResult,\n prioritized: PrioritizationResult,\n semanticOutput: string,\n attackSurfaceOutput: string,\n priorityReport: PriorityReport,\n assignments: IssueAssignment[]\n ): Promise<string> {\n const { triaging, results: _results, executionTime } = result;\n \n let output = `\\n`;\n output += `# 🔺 Trie Agent Scan Complete\\n\\n`;\n \n // Quick stats\n output += `**Scanned:** ${triaging.agentsActivated.length} agents | **Time:** ${(executionTime / 1000).toFixed(1)}s | **Risk:** ${triaging.riskLevel.toUpperCase()}\\n\\n`;\n \n // Smart prioritization summary - just the actionable count\n const totalActionable = prioritized.critical.length + prioritized.important.length;\n if (totalActionable === 0) {\n output += `## ✅ No Issues Found\\n\\n`;\n output += `Your code passed all checks.\\n\\n`;\n } else {\n output += `## 🎯 ${totalActionable} Issues Found\\n\\n`;\n }\n \n // Critical actions - SHOW FULL DETAILS WITH CODE SNIPPETS\n if (prioritized.critical.length > 0) {\n output += `### 🔴 Critical (${prioritized.critical.length})\\n\\n`;\n for (const issue of prioritized.critical.slice(0, 8)) {\n output += `---\\n\\n`;\n output += `**${issue.issue}**\\n\\n`;\n output += `📍 \\`${issue.file}:${issue.line || '?'}\\`\\n\\n`;\n \n // Show code snippet if available\n const snippet = await this.getCodeSnippet(issue.file, issue.line);\n if (snippet) {\n output += `\\`\\`\\`\\n${snippet}\\n\\`\\`\\`\\n\\n`;\n }\n \n output += `**Fix:** ${issue.fix}\\n\\n`;\n \n // Generate a prompt the user can copy to fix this\n output += `<details>\\n<summary>💬 Prompt to fix this</summary>\\n\\n`;\n output += `\\`\\`\\`\\nFix the ${issue.issue.toLowerCase()} in ${basename(issue.file)}${issue.line ? ` at line ${issue.line}` : ''}.\\n\\n${issue.fix}\\n\\`\\`\\`\\n\\n`;\n output += `</details>\\n\\n`;\n }\n if (prioritized.critical.length > 8) {\n output += `*...and ${prioritized.critical.length - 8} more critical issues*\\n\\n`;\n }\n }\n \n // Important items - SHOW FILE PATHS WITH CODE SNIPPETS\n if (prioritized.important.length > 0) {\n output += `### 🟠 Important (${prioritized.important.length})\\n\\n`;\n for (const issue of prioritized.important.slice(0, 10)) {\n output += `---\\n\\n`;\n output += `**${issue.issue}**\\n\\n`;\n output += `📍 \\`${issue.file}:${issue.line || '?'}\\`\\n\\n`;\n \n // Show code snippet if available\n const snippet = await this.getCodeSnippet(issue.file, issue.line);\n if (snippet) {\n output += `\\`\\`\\`\\n${snippet}\\n\\`\\`\\`\\n\\n`;\n }\n \n output += `**Fix:** ${issue.fix}\\n\\n`;\n \n // Generate a prompt the user can copy to fix this\n output += `<details>\\n<summary>💬 Prompt to fix this</summary>\\n\\n`;\n output += `\\`\\`\\`\\nFix the ${issue.issue.toLowerCase()} in ${basename(issue.file)}${issue.line ? ` at line ${issue.line}` : ''}.\\n\\n${issue.fix}\\n\\`\\`\\`\\n\\n`;\n output += `</details>\\n\\n`;\n }\n if (prioritized.important.length > 10) {\n output += `*...and ${prioritized.important.length - 10} more important issues*\\n\\n`;\n }\n }\n \n // Semantic analysis highlights (the SMART stuff)\n if (semanticOutput && semanticOutput.includes('Data Flow') || semanticOutput.includes('Race Condition')) {\n output += `### 🧠 Semantic Analysis\\n\\n`;\n \n // Extract key findings\n const dataFlowMatch = semanticOutput.match(/Data Flow Vulnerabilities \\((\\d+)\\)/);\n const raceMatch = semanticOutput.match(/Race Conditions \\((\\d+)\\)/);\n const authMatch = semanticOutput.match(/Authentication Issues \\((\\d+)\\)/);\n \n if (dataFlowMatch) output += `- 🔴 **${dataFlowMatch[1]} data flow vulnerabilities** (untrusted input reaching dangerous sinks)\\n`;\n if (authMatch) output += `- 🔴 **${authMatch[1]} authentication issues** (missing or bypassable auth)\\n`;\n if (raceMatch) output += `- 🟡 **${raceMatch[1]} race conditions** (TOCTOU, double-spend risks)\\n`;\n \n output += `\\n`;\n }\n \n // Attack surface summary\n if (attackSurfaceOutput && attackSurfaceOutput.includes('Attack Surface')) {\n const riskMatch = attackSurfaceOutput.match(/Risk Score\\*\\* \\| \\*\\*(\\d+)\\/100/);\n const endpointsMatch = attackSurfaceOutput.match(/Total Endpoints \\| (\\d+)/);\n const publicMatch = attackSurfaceOutput.match(/Public \\(No Auth\\) \\| (\\d+)/);\n \n if (riskMatch || endpointsMatch) {\n output += `### 🎯 Attack Surface\\n\\n`;\n if (endpointsMatch) output += `- **${endpointsMatch[1]} endpoints** found`;\n if (publicMatch?.[1] && parseInt(publicMatch[1], 10) > 0) output += ` (⚠️ ${publicMatch[1]} public without auth)`;\n output += `\\n`;\n if (riskMatch) output += `- **Risk Score:** ${riskMatch[1]}/100\\n`;\n output += `\\n`;\n }\n }\n\n // Smart grouping & prioritization\n if (priorityReport.totalGroups > 0) {\n output += `### 🧩 Smart Grouping\\n\\n`;\n output += `- **${priorityReport.totalGroups} issue groups** across ${priorityReport.totalIssues} issues\\n`;\n output += `- **Risk Score:** ${priorityReport.riskScore}/100\\n`;\n\n const topGroups = [...priorityReport.urgent, ...priorityReport.high].slice(0, 5);\n if (topGroups.length > 0) {\n output += `\\n**Top groups to fix first:**\\n`;\n for (const group of topGroups) {\n const bulk = group.bulkFixAvailable ? ' (bulk-fix available)' : '';\n output += `- ${group.description} — ${group.count} issues${bulk}\\n`;\n }\n output += `\\n`;\n }\n\n if (priorityReport.recommendations.length > 0) {\n output += `**Recommendations:**\\n`;\n for (const recommendation of priorityReport.recommendations) {\n output += `- ${recommendation}\\n`;\n }\n output += `\\n`;\n }\n }\n\n if (assignments.length > 0) {\n output += `### 🤝 Team Assignments\\n\\n`;\n const urgent = assignments.filter(a => a.priority === 'urgent').length;\n const high = assignments.filter(a => a.priority === 'high').length;\n output += `- **${assignments.length} assignments** created (${urgent} urgent, ${high} high)\\n\\n`;\n }\n \n // Next steps\n output += `## 📋 Next Steps\\n\\n`;\n if (prioritized.critical.length > 0) {\n output += `1. **Fix critical issues:** \\`trie_fix\\` to auto-fix high-confidence issues\\n`;\n }\n output += `2. **Deep dive:** Run \\`trie_security\\`, \\`trie_privacy\\`, or \\`trie_bugs\\` for specific analysis\\n`;\n output += `3. **Watch mode:** \\`trie_watch\\` to catch issues as you code\\n\\n`;\n \n // Footer\n output += `---\\n`;\n output += `*💡 Unlike other tools that dump 10,000 issues, Trie Agent shows you what matters.*\\n`;\n \n return output;\n }\n\n /**\n * Get a code snippet around a specific line\n */\n private async getCodeSnippet(filePath: string, line: number | undefined): Promise<string | null> {\n if (!line || !existsSync(filePath)) return null;\n \n try {\n const content = await readFile(filePath, 'utf-8');\n const lines = content.split('\\n');\n const start = Math.max(0, line - 3);\n const end = Math.min(lines.length, line + 2);\n \n return lines.slice(start, end).map((l, idx) => {\n const lineNum = start + idx + 1;\n const marker = lineNum === line ? '→' : ' ';\n return `${marker} ${lineNum.toString().padStart(4)} | ${l}`;\n }).join('\\n');\n } catch {\n return null;\n }\n }\n\n /**\n * Recursively discover all scannable files in a directory\n */\n private async discoverFiles(dir: string, maxFiles: number = 500): Promise<string[]> {\n const files: string[] = [];\n \n async function walk(currentDir: string) {\n if (files.length >= maxFiles) return;\n \n try {\n const entries = await readdir(currentDir, { withFileTypes: true });\n \n for (const entry of entries) {\n if (files.length >= maxFiles) break;\n \n const fullPath = join(currentDir, entry.name);\n \n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith('.')) {\n await walk(fullPath);\n }\n } else if (entry.isFile()) {\n // Skip hidden files unless they are env files (where secrets live)\n if (entry.name.startsWith('.') && !entry.name.startsWith('.env')) {\n continue;\n }\n\n // Explicitly ignore LLM/config prompt files that are noisy and not source code\n if (entry.name === '.claude.json') {\n continue;\n }\n\n const ext = extname(entry.name).toLowerCase();\n if (SCANNABLE_EXTENSIONS.has(ext)) {\n files.push(fullPath);\n }\n }\n }\n } catch (error) {\n // Skip directories we can't read\n }\n }\n \n await walk(dir);\n return files;\n }\n\n private async loadTeamMembers(workDir: string): Promise<TeamMember[]> {\n const teamConfigPath = join(workDir, '.trie', 'team.json');\n if (!existsSync(teamConfigPath)) {\n return [];\n }\n\n try {\n const content = await readFile(teamConfigPath, 'utf-8');\n const data = JSON.parse(content) as { members?: TeamMember[] };\n return Array.isArray(data.members) ? data.members : [];\n } catch {\n return [];\n }\n }\n\n private groupFilesByExtension(files: string[]): Record<string, number> {\n const byExt: Record<string, number> = {};\n for (const file of files) {\n const ext = extname(file) || 'other';\n byExt[ext] = (byExt[ext] || 0) + 1;\n }\n return byExt;\n }\n}\n","import { readFile } from 'fs/promises';\nimport { parse } from '@babel/parser';\nimport traverse from '@babel/traverse';\nimport { existsSync } from 'fs';\nimport { extname, basename } from 'path';\nimport type { CodeContext } from '../types/index.js';\n\nexport class ContextAnalyzer {\n async analyze(files: string[], userContext?: Partial<CodeContext>): Promise<CodeContext> {\n const context: CodeContext = {\n changeType: userContext?.changeType ?? 'general',\n isNewFeature: userContext?.isNewFeature ?? false,\n touchesUserData: userContext?.touchesUserData ?? false,\n touchesAuth: false,\n touchesPayments: false,\n touchesDatabase: false,\n touchesAPI: false,\n touchesUI: false,\n touchesHealthData: false,\n touchesSecurityConfig: false,\n linesChanged: 0,\n filePatterns: [],\n \n // NEW: Enhanced signals\n touchesCrypto: false,\n touchesFileSystem: false,\n touchesThirdPartyAPI: false,\n touchesLogging: false,\n touchesErrorHandling: false,\n hasTests: false,\n complexity: 'low',\n \n patterns: {\n hasAsyncCode: false,\n hasFormHandling: false,\n hasFileUploads: false,\n hasEmailHandling: false,\n hasRateLimiting: false,\n hasWebSockets: false,\n hasCaching: false,\n hasQueue: false,\n }\n };\n\n let totalLines = 0;\n let totalComplexity = 0;\n\n for (const file of files) {\n try {\n if (!existsSync(file)) {\n console.error(`File not found: ${file}`);\n continue;\n }\n\n // Skip signature/pattern definition files - they contain keywords but aren't real code\n if (this.isSignatureFile(file)) {\n continue;\n }\n\n const content = await readFile(file, 'utf-8');\n const lines = content.split('\\n').length;\n totalLines += lines;\n\n // Analyze file patterns\n if (!file) continue; // Skip if file is undefined\n const fileName = basename(file).toLowerCase();\n const filePath = file.toLowerCase();\n\n context.filePatterns.push(fileName);\n\n // Detect language\n if (!context.language) {\n context.language = this.detectLanguage(fileName);\n }\n\n // Check for test files\n if (/\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(fileName)) {\n context.hasTests = true;\n }\n\n // Detect context based on file patterns\n if (this.isAuthFile(fileName, filePath)) {\n context.touchesAuth = true;\n }\n\n if (this.isPaymentFile(fileName, filePath)) {\n context.touchesPayments = true;\n }\n\n if (this.isDatabaseFile(fileName, filePath)) {\n context.touchesDatabase = true;\n }\n\n if (this.isAPIFile(fileName, filePath)) {\n context.touchesAPI = true;\n }\n\n if (this.isUIFile(fileName, filePath)) {\n context.touchesUI = true;\n }\n\n if (this.isHealthFile(fileName, filePath)) {\n context.touchesHealthData = true;\n }\n\n if (this.isSecurityConfigFile(fileName, filePath)) {\n context.touchesSecurityConfig = true;\n }\n\n // Analyze code content\n const fileComplexity = await this.analyzeCodeContent(content, file, context);\n totalComplexity += fileComplexity;\n\n } catch (error) {\n console.error(`Error analyzing file ${file}:`, error);\n }\n }\n\n context.linesChanged = totalLines;\n\n // Calculate complexity\n const avgComplexity = files.length > 0 ? totalComplexity / files.length : 0;\n context.complexity = avgComplexity > 15 ? 'high' : avgComplexity > 8 ? 'medium' : 'low';\n\n // Override with user context if provided\n if (userContext) {\n Object.assign(context, userContext);\n }\n\n // Auto-detect change type if not specified\n if (!userContext?.changeType) {\n context.changeType = this.detectChangeType(context);\n }\n\n return context;\n }\n\n private detectLanguage(fileName: string): NonNullable<CodeContext['language']> {\n if (fileName.endsWith('.ts') || fileName.endsWith('.tsx')) return 'typescript';\n if (fileName.endsWith('.js') || fileName.endsWith('.jsx')) return 'javascript';\n if (fileName.endsWith('.py')) return 'python';\n if (fileName.endsWith('.go')) return 'go';\n if (fileName.endsWith('.rs')) return 'rust';\n return 'unknown';\n }\n\n private isAuthFile(fileName: string, filePath: string): boolean {\n const authPatterns = [\n 'auth', 'login', 'signup', 'register', 'session', 'jwt', 'token',\n 'password', 'oauth', 'signin', 'signout', 'middleware/auth',\n 'credential', 'sso', 'saml', 'oidc', '2fa', 'mfa', 'otp'\n ];\n return authPatterns.some(pattern =>\n fileName.includes(pattern) || filePath.includes(pattern)\n );\n }\n\n private isPaymentFile(fileName: string, filePath: string): boolean {\n const paymentPatterns = [\n 'payment', 'stripe', 'billing', 'checkout', 'subscription',\n 'invoice', 'charge', 'refund', 'paypal', 'merchant', 'cart',\n 'order', 'transaction', 'wallet', 'payout', 'pricing'\n ];\n return paymentPatterns.some(pattern =>\n fileName.includes(pattern) || filePath.includes(pattern)\n );\n }\n\n private isDatabaseFile(fileName: string, filePath: string): boolean {\n const dbPatterns = [\n 'model', 'schema', 'migration', 'seed', 'db', 'database',\n 'prisma', 'sequelize', 'mongoose', 'typeorm', 'knex',\n 'repository', 'entity', 'query'\n ];\n return dbPatterns.some(pattern =>\n fileName.includes(pattern) || filePath.includes(pattern)\n ) || fileName.endsWith('.sql');\n }\n\n private isAPIFile(fileName: string, filePath: string): boolean {\n const apiPatterns = [\n 'api/', 'route', 'handler', 'controller', 'endpoint',\n 'middleware', 'server', 'express', 'fastify', 'graphql',\n 'resolver', 'trpc'\n ];\n return apiPatterns.some(pattern =>\n fileName.includes(pattern) || filePath.includes(pattern)\n );\n }\n\n private isUIFile(fileName: string, filePath: string): boolean {\n const uiExtensions = ['.jsx', '.tsx', '.vue', '.svelte'];\n const uiPatterns = [\n 'component', 'page', 'layout', 'ui/', 'frontend/',\n 'client/', 'styles', 'css', 'view', 'template'\n ];\n\n return uiExtensions.some(ext => fileName.endsWith(ext)) ||\n uiPatterns.some(pattern => filePath.includes(pattern)) ||\n fileName.endsWith('.css') || fileName.endsWith('.scss');\n }\n\n private isHealthFile(fileName: string, filePath: string): boolean {\n // Avoid triggering on generic service health checks (healthz/health-check)\n const normalizedPath = `${filePath}`.toLowerCase();\n if (/healthz|health-check|healthcheck/.test(normalizedPath)) {\n return false;\n }\n\n const healthPatterns = [\n 'patient', 'medical', 'hipaa', 'phi',\n 'diagnosis', 'treatment', 'clinical', 'hospital',\n 'prescription', 'insurance', 'ehr', 'fhir'\n ];\n return healthPatterns.some(pattern =>\n fileName.includes(pattern) || normalizedPath.includes(pattern)\n );\n }\n\n private isSecurityConfigFile(fileName: string, filePath: string): boolean {\n const securityPatterns = [\n '.env', 'config', 'secret', 'key', 'cert', 'ssl',\n 'security', 'cors', 'helmet', 'csp', 'permission'\n ];\n return securityPatterns.some(pattern =>\n fileName.includes(pattern) || filePath.includes(pattern)\n );\n }\n\n /**\n * Check if file is a signature/pattern definition file (scanner's own rules)\n * These contain keywords like \"password\", \"auth\", \"payment\" as detection patterns,\n * not as actual code - skip them to avoid false context signals.\n */\n private isSignatureFile(filePath: string): boolean {\n const signaturePatterns = [\n /vulnerability-signatures\\.[jt]s$/,\n /vibe-code-signatures\\.[jt]s$/,\n /attack-surface\\.[jt]s$/,\n /semantic-analyzer\\.[jt]s$/,\n /smart-prioritizer\\.[jt]s$/,\n /context-analyzer\\.[jt]s$/,\n /triager\\.[jt]s$/,\n /risk-assessor\\.[jt]s$/,\n /base-agent\\.[jt]s$/,\n /\\/agents\\/.*\\.[jt]s$/, // All agent files contain detection patterns\n ];\n return signaturePatterns.some(pattern => pattern.test(filePath));\n }\n\n private async analyzeCodeContent(content: string, filePath: string, context: CodeContext): Promise<number> {\n const ext = extname(filePath);\n let complexity = 0;\n\n // Only parse JavaScript/TypeScript files\n if (!['.js', '.jsx', '.ts', '.tsx'].includes(ext)) {\n this.analyzeTextContent(content, context);\n return this.calculateTextComplexity(content);\n }\n\n try {\n const ast = parse(content, {\n sourceType: 'module',\n plugins: [\n 'jsx',\n 'typescript',\n 'decorators-legacy',\n 'classProperties',\n 'asyncGenerators',\n 'functionBind',\n 'exportDefaultFrom',\n 'objectRestSpread',\n 'dynamicImport'\n ]\n });\n\n traverse(ast, {\n // Detect imports that indicate specific domains\n ImportDeclaration: (path) => {\n const source = path.node.source?.value;\n if (source) {\n this.analyzeImport(source, context);\n }\n },\n\n // Detect function calls\n CallExpression: (path) => {\n const callee = path.node.callee;\n let functionName = '';\n\n if (callee.type === 'Identifier') {\n functionName = callee.name ?? '';\n } else if (callee.type === 'MemberExpression' &&\n callee.property.type === 'Identifier') {\n functionName = callee.property.name ?? '';\n }\n\n this.analyzeFunctionCall(functionName, context);\n },\n\n // Count complexity\n IfStatement: () => { complexity++; },\n ConditionalExpression: () => { complexity++; },\n SwitchCase: () => { complexity++; },\n ForStatement: () => { complexity++; },\n ForInStatement: () => { complexity++; },\n ForOfStatement: () => { complexity++; },\n WhileStatement: () => { complexity++; },\n DoWhileStatement: () => { complexity++; },\n CatchClause: () => { \n complexity++; \n context.touchesErrorHandling = true;\n },\n \n // Detect async patterns\n AwaitExpression: () => {\n context.patterns.hasAsyncCode = true;\n },\n\n // Detect string literals\n StringLiteral: (path) => {\n const value = path.node.value?.toLowerCase() ?? '';\n this.analyzeStringLiteral(value, context);\n }\n });\n\n } catch (error) {\n // Fall back to text analysis if parsing fails\n this.analyzeTextContent(content, context);\n complexity = this.calculateTextComplexity(content);\n }\n\n return complexity;\n }\n\n private analyzeImport(source: string, context: CodeContext): void {\n if (!source) return; // Skip if source is empty or undefined\n const s = source.toLowerCase();\n\n // Framework detection\n if (s.includes('react') || s.includes('next')) {\n context.framework = s.includes('next') ? 'nextjs' : 'react';\n } else if (s.includes('vue')) {\n context.framework = 'vue';\n } else if (s.includes('angular')) {\n context.framework = 'angular';\n } else if (s.includes('svelte')) {\n context.framework = 'svelte';\n } else if (s.includes('express')) {\n context.framework = 'express';\n } else if (s.includes('fastify')) {\n context.framework = 'fastify';\n }\n\n // Auth libraries\n if (['bcrypt', 'passport', 'jsonwebtoken', 'express-session', 'auth0', \n 'next-auth', 'lucia', 'clerk'].some(lib => s.includes(lib))) {\n context.touchesAuth = true;\n }\n\n // Payment libraries\n if (['stripe', 'paypal', 'braintree', 'square', 'paddle'].some(lib => s.includes(lib))) {\n context.touchesPayments = true;\n }\n\n // Database libraries\n if (['prisma', 'sequelize', 'mongoose', 'typeorm', 'pg', 'mysql', \n 'drizzle', 'knex', 'redis'].some(lib => s.includes(lib))) {\n context.touchesDatabase = true;\n }\n\n // UI libraries\n if (['react', 'vue', 'angular', 'svelte', 'styled-components', \n 'tailwind', 'chakra', 'mui', 'antd'].some(lib => s.includes(lib))) {\n context.touchesUI = true;\n }\n\n // Crypto libraries\n if (['crypto', 'bcrypt', 'argon2', 'sodium', 'forge'].some(lib => s.includes(lib))) {\n context.touchesCrypto = true;\n }\n\n // File system\n if (['fs', 'path', 'multer', 'formidable', 'busboy', 'sharp'].some(lib => s.includes(lib))) {\n context.touchesFileSystem = true;\n }\n\n // Third-party APIs\n if (['axios', 'node-fetch', 'got', 'superagent', 'openai', 'anthropic', \n 'twilio', 'sendgrid', 'aws-sdk', 'googleapis'].some(lib => s.includes(lib))) {\n context.touchesThirdPartyAPI = true;\n }\n\n // Logging\n if (['winston', 'pino', 'bunyan', 'log4js', 'morgan'].some(lib => s.includes(lib))) {\n context.touchesLogging = true;\n }\n\n // WebSockets\n if (['socket.io', 'ws', 'websocket', 'pusher'].some(lib => s.includes(lib))) {\n context.patterns.hasWebSockets = true;\n }\n\n // Caching\n if (['redis', 'memcached', 'lru-cache', 'node-cache'].some(lib => s.includes(lib))) {\n context.patterns.hasCaching = true;\n }\n\n // Queues\n if (['bullmq', 'bull', 'agenda', 'bee-queue', 'rabbitmq', 'amqp'].some(lib => s.includes(lib))) {\n context.patterns.hasQueue = true;\n }\n\n // Rate limiting\n if (['express-rate-limit', 'rate-limiter-flexible', 'bottleneck'].some(lib => s.includes(lib))) {\n context.patterns.hasRateLimiting = true;\n }\n\n // Email\n if (['nodemailer', 'sendgrid', 'mailgun', 'postmark', 'ses'].some(lib => s.includes(lib))) {\n context.patterns.hasEmailHandling = true;\n }\n }\n\n private analyzeFunctionCall(name: string, context: CodeContext): void {\n if (!name) return; // Skip if name is empty or undefined\n const n = name.toLowerCase();\n\n // Auth functions\n if (['hash', 'compare', 'sign', 'verify', 'authenticate', 'login', 'logout'].includes(n)) {\n context.touchesAuth = true;\n }\n\n // Payment functions\n if (['charge', 'refund', 'subscription', 'invoice', 'payment'].some(f => n.includes(f))) {\n context.touchesPayments = true;\n }\n\n // Database functions\n if (['find', 'create', 'update', 'delete', 'save', 'query', 'execute', 'insert'].includes(n)) {\n context.touchesDatabase = true;\n }\n\n // File operations\n if (['readfile', 'writefile', 'mkdir', 'unlink', 'upload'].some(f => n.includes(f))) {\n context.touchesFileSystem = true;\n if (n.includes('upload')) {\n context.patterns.hasFileUploads = true;\n }\n }\n\n // Logging\n if (['log', 'info', 'warn', 'error', 'debug'].includes(n)) {\n context.touchesLogging = true;\n }\n }\n\n private analyzeStringLiteral(value: string, context: CodeContext): void {\n // PII patterns\n if (['email', 'phone', 'address', 'ssn', 'social', 'credit', 'passport', \n 'dob', 'birth', 'salary', 'income'].some(p => value.includes(p))) {\n context.touchesUserData = true;\n }\n\n // Health patterns\n if (['patient', 'medical', 'diagnosis', 'treatment', 'medication', \n 'symptom', 'prescription', 'insurance'].some(p => value.includes(p))) {\n context.touchesHealthData = true;\n }\n\n // Form patterns\n if (['submit', 'form', 'input', 'validation', 'required'].some(p => value.includes(p))) {\n context.patterns.hasFormHandling = true;\n }\n }\n\n private analyzeTextContent(content: string, context: CodeContext): void {\n const lowerContent = content.toLowerCase();\n\n const authKeywords = ['password', 'auth', 'login', 'jwt', 'session', 'token', 'credential'];\n const paymentKeywords = ['stripe', 'payment', 'billing', 'checkout', 'subscription', 'invoice'];\n const dbKeywords = ['select', 'insert', 'update', 'delete', 'database', 'query', 'prisma'];\n const uiKeywords = ['component', 'render', 'jsx', 'css', 'style', 'button', 'form'];\n const piiKeywords = ['email', 'phone', 'address', 'ssn', 'social'];\n const healthKeywords = ['patient', 'medical', 'diagnosis', 'treatment', 'hipaa'];\n const cryptoKeywords = ['encrypt', 'decrypt', 'hash', 'crypto', 'cipher', 'key'];\n const asyncKeywords = ['async', 'await', 'promise', 'then', 'catch'];\n\n if (authKeywords.some(k => lowerContent.includes(k))) context.touchesAuth = true;\n if (paymentKeywords.some(k => lowerContent.includes(k))) context.touchesPayments = true;\n if (dbKeywords.some(k => lowerContent.includes(k))) context.touchesDatabase = true;\n if (uiKeywords.some(k => lowerContent.includes(k))) context.touchesUI = true;\n if (piiKeywords.some(k => lowerContent.includes(k))) context.touchesUserData = true;\n if (healthKeywords.some(k => lowerContent.includes(k))) context.touchesHealthData = true;\n if (cryptoKeywords.some(k => lowerContent.includes(k))) context.touchesCrypto = true;\n if (asyncKeywords.some(k => lowerContent.includes(k))) context.patterns.hasAsyncCode = true;\n\n // File patterns\n if (/upload|multer|formdata|file/i.test(lowerContent)) {\n context.patterns.hasFileUploads = true;\n context.touchesFileSystem = true;\n }\n\n // Email patterns\n if (/nodemailer|sendgrid|email.*send|send.*email/i.test(lowerContent)) {\n context.patterns.hasEmailHandling = true;\n }\n\n // WebSocket patterns\n if (/websocket|socket\\.io|ws\\./i.test(lowerContent)) {\n context.patterns.hasWebSockets = true;\n }\n\n // Error handling patterns\n if (/try\\s*{|catch\\s*\\(|\\.catch\\(|throw\\s+new/i.test(content)) {\n context.touchesErrorHandling = true;\n }\n\n // Logging patterns \n if (/console\\.(log|info|warn|error)|logger\\./i.test(content)) {\n context.touchesLogging = true;\n }\n }\n\n private calculateTextComplexity(content: string): number {\n let complexity = 0;\n \n // Count control flow statements\n complexity += (content.match(/\\bif\\b/g) || []).length;\n complexity += (content.match(/\\belse\\b/g) || []).length;\n complexity += (content.match(/\\bfor\\b/g) || []).length;\n complexity += (content.match(/\\bwhile\\b/g) || []).length;\n complexity += (content.match(/\\bswitch\\b/g) || []).length;\n complexity += (content.match(/\\bcatch\\b/g) || []).length;\n complexity += (content.match(/\\?\\s*.*\\s*:/g) || []).length; // ternary\n\n return complexity;\n }\n\n private detectChangeType(context: CodeContext): CodeContext['changeType'] {\n // Priority order for change type detection\n if (context.touchesPayments) return 'payment';\n if (context.touchesAuth) return 'auth';\n if (context.touchesDatabase) return 'database';\n if (context.touchesAPI) return 'api';\n if (context.touchesUI) return 'ui';\n return 'general';\n }\n}\n","import type { CodeContext, RiskLevel } from '../types/index.js';\n\nexport class RiskAssessor {\n assessRisk(context: CodeContext): RiskLevel {\n let score = 0;\n\n // Base scoring from PRD\n if (context.touchesAuth) score += 35;\n if (context.touchesPayments) score += 50;\n if (context.touchesDatabase) score += 25;\n if (context.touchesUserData) score += 20;\n if (context.touchesHealthData) score += 60; // HIPAA critical\n if (context.linesChanged > 500) score += 20;\n if (context.touchesSecurityConfig) score += 35;\n\n // Additional risk factors\n if (context.touchesAPI) score += 20;\n if (context.isNewFeature) score += 15;\n if (context.touchesUI && context.touchesUserData) score += 10; // Forms with PII\n\n // Risk multipliers for dangerous combinations\n if (context.touchesAuth && context.touchesDatabase) score += 5; // Auth + DB is risky\n if (context.touchesPayments && context.touchesUserData) score += 15; // Payment + PII\n if (context.touchesHealthData && context.touchesDatabase) score += 20; // PHI storage\n\n // Classify risk level\n if (score >= 95) return 'critical';\n if (score >= 60) return 'high';\n if (score >= 25) return 'medium';\n return 'low';\n }\n\n getRiskExplanation(context: CodeContext, riskLevel: RiskLevel): string {\n const reasons = [];\n\n if (context.touchesAuth) {\n reasons.push('handles authentication/authorization');\n }\n if (context.touchesPayments) {\n reasons.push('processes payments');\n }\n if (context.touchesDatabase) {\n reasons.push('modifies database');\n }\n if (context.touchesUserData) {\n reasons.push('handles user data');\n }\n if (context.touchesHealthData) {\n reasons.push('handles protected health information');\n }\n if (context.touchesSecurityConfig) {\n reasons.push('modifies security configuration');\n }\n if (context.linesChanged > 500) {\n reasons.push('large code change');\n }\n if (context.isNewFeature) {\n reasons.push('introduces new functionality');\n }\n\n const explanation = reasons.length > 0\n ? `Risk level ${riskLevel} because code ${reasons.join(', ')}`\n : `Risk level ${riskLevel} - general code change`;\n\n return explanation;\n }\n\n shouldRunAllAgents(riskLevel: RiskLevel): boolean {\n return riskLevel === 'critical';\n }\n}","import type { CodeContext, RiskLevel, Agent, TriagingConfig } from '../types/index.js';\nimport { getAgentRegistry } from '../agents/registry.js';\nimport { CustomAgent } from '../agents/custom-agent.js';\n\ninterface AgentScore {\n agent: Agent;\n confidence: number;\n reasons: string[];\n tier: number;\n isCustom: boolean;\n}\n\nexport class Triager {\n private agentRegistry = getAgentRegistry();\n private config: TriagingConfig;\n private customAgentsLoaded = false;\n\n constructor(config?: Partial<TriagingConfig>) {\n this.config = {\n minConfidence: 0.15,\n maxAgents: 11,\n timeoutMs: 60000,\n enableCostAware: false,\n enableDependencies: true,\n ...config\n };\n }\n\n /**\n * Ensure custom agents are loaded before triaging\n */\n private async ensureCustomAgentsLoaded(): Promise<void> {\n if (!this.customAgentsLoaded) {\n await this.agentRegistry.loadCustomAgents();\n this.customAgentsLoaded = true;\n }\n }\n\n async selectAgents(context: CodeContext, riskLevel: RiskLevel): Promise<Agent[]> {\n // Load custom agents if not already loaded\n await this.ensureCustomAgentsLoaded();\n \n // HIGH or CRITICAL RISK = ALL AGENTS\n if (riskLevel === 'critical' || riskLevel === 'high') {\n console.error(` ⚠️ ${riskLevel.toUpperCase()} risk - activating all agents for comprehensive review`);\n return this.getAllAgents();\n }\n\n // Score all agents based on context\n const scores = this.scoreAgents(context, riskLevel);\n \n // Log scoring for transparency\n this.logAgentScoring(scores);\n\n // Filter by confidence threshold\n const qualified = scores.filter(s => s.confidence >= this.config.minConfidence);\n\n // Sort by tier (priority) then confidence\n qualified.sort((a, b) => {\n if (a.tier !== b.tier) return a.tier - b.tier;\n return b.confidence - a.confidence;\n });\n\n // Resolve dependencies if enabled\n if (this.config.enableDependencies) {\n return this.resolveDependencies(qualified.map(s => s.agent));\n }\n\n return qualified.map(s => s.agent);\n }\n\n private scoreAgents(context: CodeContext, riskLevel: RiskLevel): AgentScore[] {\n const allAgents = this.getAllAgents();\n const scores: AgentScore[] = [];\n\n for (const agent of allAgents) {\n const score = this.scoreAgent(agent, context, riskLevel);\n scores.push(score);\n }\n\n return scores;\n }\n\n private scoreAgent(agent: Agent, context: CodeContext, riskLevel: RiskLevel): AgentScore {\n // Check if this is a custom agent\n if (agent instanceof CustomAgent) {\n return this.scoreCustomAgent(agent, context, riskLevel);\n }\n \n // Built-in agent scoring\n return this.scoreBuiltinAgent(agent, context, riskLevel);\n }\n\n /**\n * Score custom agents using their activation rules\n */\n private scoreCustomAgent(agent: CustomAgent, context: CodeContext, riskLevel: RiskLevel): AgentScore {\n const reasons: string[] = [];\n \n // Use the agent's built-in activation confidence\n let confidence = agent.getActivationConfidence(context);\n \n if (confidence > 0) {\n reasons.push(`custom agent: ${agent.getMetadata().category}`);\n \n // Add metadata info\n const meta = agent.getMetadata();\n if (meta.patternCount > 0) {\n reasons.push(`${meta.patternCount} detection patterns`);\n }\n }\n \n // Risk escalation for custom agents too\n if (riskLevel === 'high' && confidence > 0) {\n confidence = Math.min(1.0, confidence * 1.2);\n }\n \n return {\n agent,\n confidence,\n reasons,\n tier: agent.priority.tier,\n isCustom: true,\n };\n }\n\n /**\n * Score built-in agents\n */\n private scoreBuiltinAgent(agent: Agent, context: CodeContext, riskLevel: RiskLevel): AgentScore {\n const reasons: string[] = [];\n let confidence = 0;\n let tier = 3; // default to lowest tier\n\n // TIER 1: ALWAYS RUN AGENTS\n if (agent.name === 'typecheck') {\n tier = 1;\n confidence = 1.0;\n reasons.push('fundamental type safety');\n }\n\n if (agent.name === 'comprehension') {\n tier = 1;\n confidence = 1.0;\n reasons.push('stakeholder communication');\n }\n\n // TIER 2: CONTEXT-DEPENDENT AGENTS\n if (agent.name === 'security') {\n tier = 2;\n if (context.touchesAuth) { confidence += 0.4; reasons.push('auth code'); }\n if (context.touchesPayments) { confidence += 0.4; reasons.push('payment code'); }\n if (context.touchesAPI) { confidence += 0.3; reasons.push('API endpoints'); }\n if (context.touchesDatabase) { confidence += 0.25; reasons.push('database access'); }\n if (context.touchesCrypto) { confidence += 0.35; reasons.push('cryptographic operations'); }\n if (context.touchesUserData) { confidence += 0.3; reasons.push('user data'); }\n if (context.touchesSecurityConfig) { confidence += 0.4; reasons.push('security config'); }\n if (context.touchesThirdPartyAPI) { confidence += 0.2; reasons.push('third-party integration'); }\n if (context.patterns?.hasFileUploads) { confidence += 0.3; reasons.push('file uploads'); }\n \n // Risk escalation\n if (riskLevel === 'high') confidence *= 1.2;\n }\n\n if (agent.name === 'privacy') {\n tier = 2;\n if (context.touchesUserData) { confidence += 0.5; reasons.push('PII handling'); }\n if (context.touchesAuth) { confidence += 0.3; reasons.push('credentials'); }\n if (context.touchesLogging) { confidence += 0.25; reasons.push('logging (may expose data)'); }\n if (context.patterns?.hasEmailHandling) { confidence += 0.3; reasons.push('email handling'); }\n if (context.patterns?.hasFormHandling) { confidence += 0.2; reasons.push('form data'); }\n }\n\n if (agent.name === 'legal') {\n tier = 2;\n if (context.touchesUserData) { confidence += 0.4; reasons.push('GDPR/CCPA'); }\n if (context.touchesPayments) { confidence += 0.35; reasons.push('PCI-DSS'); }\n if (context.patterns?.hasEmailHandling) { confidence += 0.25; reasons.push('CAN-SPAM'); }\n }\n\n if (agent.name === 'accessibility') {\n tier = 2;\n if (context.touchesUI) { confidence += 0.6; reasons.push('UI components'); }\n if (context.framework === 'react' || context.framework === 'vue') { \n confidence += 0.2; \n reasons.push(`${context.framework} framework`); \n }\n if (context.patterns?.hasFormHandling) { confidence += 0.2; reasons.push('form UX'); }\n }\n\n if (agent.name === 'test') {\n tier = 2;\n if (context.isNewFeature) { confidence += 0.4; reasons.push('new feature'); }\n if (context.touchesAuth) { confidence += 0.35; reasons.push('auth needs tests'); }\n if (context.touchesPayments) { confidence += 0.4; reasons.push('payments need tests'); }\n if (context.touchesAPI) { confidence += 0.3; reasons.push('API testing'); }\n if (!context.hasTests) { confidence += 0.2; reasons.push('no existing tests'); }\n if (context.complexity === 'high') { confidence += 0.25; reasons.push('complex code'); }\n }\n\n if (agent.name === 'software-architect') {\n tier = 2;\n if (context.isNewFeature) { confidence += 0.35; reasons.push('architecture review'); }\n if (context.touchesDatabase) { confidence += 0.35; reasons.push('data modeling'); }\n if (context.linesChanged > 200) { confidence += 0.3; reasons.push('large change'); }\n if (context.touchesAPI) { confidence += 0.25; reasons.push('API design'); }\n if (context.patterns?.hasWebSockets) { confidence += 0.3; reasons.push('real-time architecture'); }\n if (context.patterns?.hasQueue) { confidence += 0.3; reasons.push('async architecture'); }\n }\n\n if (agent.name === 'devops') {\n tier = 2;\n if (context.touchesSecurityConfig) { confidence += 0.4; reasons.push('security config'); }\n if (context.touchesFileSystem) { confidence += 0.3; reasons.push('file operations'); }\n if (context.touchesLogging) { confidence += 0.25; reasons.push('logging'); }\n if (context.touchesErrorHandling) { confidence += 0.2; reasons.push('error handling'); }\n if (context.patterns?.hasCaching) { confidence += 0.25; reasons.push('caching'); }\n if (context.patterns?.hasRateLimiting) { confidence += 0.3; reasons.push('rate limiting'); }\n }\n\n if (agent.name === 'bug-finding') {\n tier = 2;\n if (context.touchesPayments) { confidence += 0.5; reasons.push('payments = zero bugs'); }\n if (context.isNewFeature) { confidence += 0.3; reasons.push('new code'); }\n if (context.patterns?.hasAsyncCode) { confidence += 0.35; reasons.push('async patterns'); }\n if (context.complexity === 'high') { confidence += 0.3; reasons.push('complex logic'); }\n if (context.touchesDatabase) { confidence += 0.25; reasons.push('data mutations'); }\n }\n\n if (agent.name === 'user-testing') {\n tier = 3; // lower priority - only when clearly needed\n if (context.touchesUI) { confidence += 0.5; reasons.push('UI changes'); }\n if (context.isNewFeature && context.touchesUI) { confidence += 0.3; reasons.push('new UI feature'); }\n if (context.patterns?.hasFormHandling) { confidence += 0.25; reasons.push('form UX'); }\n }\n \n if (agent.name === 'trie_clean') {\n tier = 2;\n if (context.touchesUI) { confidence += 0.4; reasons.push('UI code'); }\n if (context.isNewFeature) { confidence += 0.3; reasons.push('new feature'); }\n if (context.framework === 'react') { confidence += 0.2; reasons.push('React code'); }\n }\n\n if (agent.name === 'soc2') {\n tier = 2;\n if (context.touchesAuth) { confidence += 0.4; reasons.push('authentication'); }\n if (context.touchesSecurityConfig) { confidence += 0.4; reasons.push('security config'); }\n if (context.touchesLogging) { confidence += 0.3; reasons.push('logging'); }\n if (context.touchesAPI) { confidence += 0.25; reasons.push('API endpoints'); }\n if (context.touchesDatabase) { confidence += 0.2; reasons.push('data access'); }\n }\n\n // Cap confidence at 1.0\n confidence = Math.min(1.0, confidence);\n\n return { agent, confidence, reasons, tier, isCustom: false };\n }\n\n private logAgentScoring(scores: AgentScore[]): void {\n console.error('\\n 📊 Agent Confidence Scores:');\n \n const sorted = [...scores].sort((a, b) => b.confidence - a.confidence);\n \n for (const score of sorted) {\n const bar = this.getConfidenceBar(score.confidence);\n const status = score.confidence >= this.config.minConfidence ? '✓' : '✗';\n const tierLabel = score.tier === 1 ? '[T1]' : score.tier === 2 ? '[T2]' : '[T3]';\n const customLabel = score.isCustom ? ' 📚' : '';\n \n console.error(` ${status} ${score.agent.name.padEnd(18)} ${tierLabel} ${bar} ${(score.confidence * 100).toFixed(0)}%${customLabel}`);\n \n if (score.reasons.length > 0 && score.confidence > 0) {\n console.error(` └─ ${score.reasons.join(', ')}`);\n }\n }\n console.error('');\n }\n\n private getConfidenceBar(confidence: number): string {\n const filled = Math.round(confidence * 10);\n const empty = 10 - filled;\n return '█'.repeat(filled) + '░'.repeat(empty);\n }\n\n private resolveDependencies(agents: Agent[]): Agent[] {\n const agentNames = new Set(agents.map(a => a.name));\n const resolved: Agent[] = [];\n const added = new Set<string>();\n\n // Define dependencies\n const dependencies: Record<string, string[]> = {\n 'legal': ['privacy'], // legal should see privacy issues first\n 'test': ['bug-finding'], // find bugs before writing tests\n 'user-testing': ['accessibility'], // accessibility before UX\n };\n\n // Add dependencies first\n for (const agent of agents) {\n const deps = dependencies[agent.name] || [];\n for (const depName of deps) {\n if (!added.has(depName)) {\n const depAgent = this.agentRegistry.getAgent(depName);\n if (depAgent && agentNames.has(depName)) {\n resolved.push(depAgent);\n added.add(depName);\n }\n }\n }\n \n if (!added.has(agent.name)) {\n resolved.push(agent);\n added.add(agent.name);\n }\n }\n\n return resolved;\n }\n\n getTriagingReason(context: CodeContext, riskLevel: RiskLevel): string {\n if (riskLevel === 'critical') {\n return 'Critical risk detected - activating all agents for comprehensive review';\n }\n\n const reasons: string[] = [];\n\n if (context.touchesAuth) reasons.push('authentication');\n if (context.touchesPayments) reasons.push('payments');\n if (context.touchesDatabase) reasons.push('database');\n if (context.touchesUserData) reasons.push('user data');\n if (context.touchesUI) reasons.push('UI');\n if (context.touchesAPI) reasons.push('API');\n if (context.isNewFeature) reasons.push('new feature');\n if (context.touchesCrypto) reasons.push('cryptography');\n if (context.touchesThirdPartyAPI) reasons.push('3rd party API');\n\n if (reasons.length === 0) {\n return `${riskLevel} risk - general code changes`;\n }\n\n return `${riskLevel} risk: ${reasons.join(', ')}`;\n }\n\n async getSkippedAgents(context: CodeContext, riskLevel: RiskLevel): Promise<string[]> {\n await this.ensureCustomAgentsLoaded();\n \n if (riskLevel === 'critical') return [];\n\n const scores = this.scoreAgents(context, riskLevel);\n return scores\n .filter(s => s.confidence < this.config.minConfidence)\n .map(s => s.agent.name);\n }\n\n async getTriagingConfidence(context: CodeContext, riskLevel: RiskLevel): Promise<number> {\n await this.ensureCustomAgentsLoaded();\n \n // How confident are we in our triaging decision?\n const scores = this.scoreAgents(context, riskLevel);\n const qualified = scores.filter(s => s.confidence >= this.config.minConfidence);\n \n if (qualified.length === 0) return 0.5; // uncertain\n \n // Average confidence of selected agents\n const avgConfidence = qualified.reduce((sum, s) => sum + s.confidence, 0) / qualified.length;\n \n // Boost if we have strong context signals\n const contextStrength = this.getContextStrength(context);\n \n return Math.min(1.0, avgConfidence * 0.7 + contextStrength * 0.3);\n }\n\n private getContextStrength(context: CodeContext): number {\n let signals = 0;\n\n // Count how many context signals we detected\n const checks = [\n context.touchesAuth,\n context.touchesPayments,\n context.touchesDatabase,\n context.touchesAPI,\n context.touchesUI,\n context.touchesUserData,\n context.touchesHealthData,\n context.touchesSecurityConfig,\n context.touchesCrypto,\n context.touchesFileSystem,\n context.isNewFeature,\n ];\n\n for (const check of checks) {\n if (check) signals++;\n }\n\n // More signals = more confidence in triaging\n return signals > 0 ? Math.min(1.0, signals / 3) : 0.3;\n }\n\n private getAllAgents(): Agent[] {\n return this.agentRegistry.getAllAgents();\n }\n \n /**\n * Get custom agents count\n */\n getCustomAgentCount(): number {\n return this.agentRegistry.getCustomAgents().length;\n }\n \n /**\n * Reload custom agents\n */\n async reloadCustomAgents(): Promise<void> {\n await this.agentRegistry.reloadCustomAgents();\n }\n}\n","import { Worker } from 'worker_threads';\nimport { cpus } from 'os';\nimport type { Agent, AgentResult, ScanContext } from '../types/index.js';\nimport { StreamingManager } from './streaming.js';\nimport { CacheManager } from './cache-manager.js';\n\ninterface ParallelTask {\n agent: Agent;\n files: string[];\n context: ScanContext;\n priority: number;\n timeoutMs: number;\n}\n\ninterface ParallelResult {\n agent: string;\n result: AgentResult;\n fromCache: boolean;\n executionTime: number;\n}\n\n/**\n * Parallel execution engine for Trie agents\n *\n * Features:\n * - True parallel execution using worker threads\n * - Intelligent scheduling based on agent priority\n * - Result caching and cache-aware scheduling\n * - Real-time progress streaming\n * - Dynamic resource management\n */\nexport class ParallelExecutor {\n private maxWorkers: number;\n private cache: CacheManager | null;\n private streaming?: StreamingManager;\n private activeWorkers: Set<Worker> = new Set();\n private cacheEnabled: boolean = true;\n private useWorkerThreads: boolean = false;\n\n constructor(\n cacheManager: CacheManager | null,\n maxWorkers: number = Math.max(2, Math.min(cpus().length - 1, 8)),\n options?: { cacheEnabled?: boolean; useWorkerThreads?: boolean }\n ) {\n this.maxWorkers = maxWorkers;\n this.cache = cacheManager;\n this.cacheEnabled = options?.cacheEnabled ?? true;\n this.useWorkerThreads = options?.useWorkerThreads ?? false;\n }\n\n /**\n * Set streaming manager for real-time updates\n */\n setStreaming(streaming: StreamingManager): void {\n this.streaming = streaming;\n }\n\n /**\n * Execute agents in parallel with intelligent scheduling\n */\n async executeAgents(\n agents: Agent[],\n files: string[],\n context: ScanContext\n ): Promise<Map<string, AgentResult>> {\n if (agents.length === 0) {\n return new Map();\n }\n\n // Initialize streaming\n if (this.streaming && this.streaming.getProgress().totalFiles === 0) {\n this.streaming.startScan(files.length);\n }\n\n // Check cache for existing results\n const cacheResults = new Map<string, AgentResult>();\n const uncachedTasks: ParallelTask[] = [];\n\n for (const agent of agents) {\n const cached = await this.checkAgentCache(agent, files);\n if (cached) {\n cacheResults.set(agent.name, cached);\n this.streaming?.completeAgent(agent.name, cached.issues);\n } else {\n uncachedTasks.push({\n agent,\n files,\n context,\n priority: agent.priority?.tier || 2,\n timeoutMs: context?.config?.timeoutMs || 120000\n });\n }\n }\n\n // Sort tasks by priority (tier 1 = highest priority)\n uncachedTasks.sort((a, b) => a.priority - b.priority);\n\n // Execute uncached tasks in parallel\n const parallelResults = await this.executeTasksParallel(uncachedTasks);\n\n // Cache new results\n await this.cacheResults(parallelResults);\n\n // Combine cached and new results\n const allResults = new Map<string, AgentResult>();\n\n // Add cached results\n for (const [agent, result] of cacheResults) {\n allResults.set(agent, result);\n }\n\n // Add new results\n for (const result of parallelResults) {\n allResults.set(result.agent, result.result);\n }\n\n // Complete streaming\n const allIssues = Array.from(allResults.values()).flatMap(r => r.issues);\n this.streaming?.completeScan(allIssues);\n\n return allResults;\n }\n\n /**\n * Check if agent has cached results for given files\n */\n private async checkAgentCache(agent: Agent, files: string[]): Promise<AgentResult | null> {\n if (!this.cacheEnabled || !this.cache) {\n return null;\n }\n\n const cachedIssues = await this.cache.getCachedBatch(files, agent.name);\n\n // Only use cache if we have results for ALL files\n if (cachedIssues.size === files.length) {\n const allIssues = Array.from(cachedIssues.values()).flat();\n return {\n agent: agent.name,\n issues: allIssues,\n executionTime: 0, // Cached\n success: true,\n metadata: {\n filesAnalyzed: files.length,\n linesAnalyzed: 0\n }\n };\n }\n\n return null;\n }\n\n /**\n * Execute tasks in parallel batches\n */\n private async executeTasksParallel(tasks: ParallelTask[]): Promise<ParallelResult[]> {\n if (tasks.length === 0) {\n return [];\n }\n\n const results: ParallelResult[] = [];\n const batches = this.createBatches(tasks, this.maxWorkers);\n\n for (const batch of batches) {\n const batchResults = await Promise.all(\n batch.map(task => this.executeTask(task))\n );\n results.push(...batchResults);\n }\n\n return results;\n }\n\n /**\n * Create batches for parallel execution\n */\n private createBatches(tasks: ParallelTask[], batchSize: number): ParallelTask[][] {\n const batches: ParallelTask[][] = [];\n\n for (let i = 0; i < tasks.length; i += batchSize) {\n batches.push(tasks.slice(i, i + batchSize));\n }\n\n return batches;\n }\n\n /**\n * Execute a single task\n */\n private async executeTask(task: ParallelTask): Promise<ParallelResult> {\n const startTime = Date.now();\n\n this.streaming?.startAgent(task.agent.name);\n\n try {\n const result = this.useWorkerThreads\n ? await this.executeTaskInWorker(task)\n : await task.agent.scan(task.files, task.context);\n const executionTime = Date.now() - startTime;\n\n this.streaming?.completeAgent(task.agent.name, result.issues);\n\n return {\n agent: task.agent.name,\n result,\n fromCache: false,\n executionTime\n };\n } catch (error) {\n const executionTime = Date.now() - startTime;\n const errorMessage = error instanceof Error ? error.message : String(error);\n\n this.streaming?.reportError(new Error(errorMessage), `Agent: ${task.agent.name}`);\n\n return {\n agent: task.agent.name,\n result: {\n agent: task.agent.name,\n issues: [],\n executionTime,\n success: false,\n error: errorMessage\n },\n fromCache: false,\n executionTime\n };\n }\n }\n\n private async executeTaskInWorker(task: ParallelTask): Promise<AgentResult> {\n // Use dirname to get the dist folder, then resolve to workers subfolder\n // This works whether the code is bundled into chunks or in utils/ folder\n const distDir = new URL('.', import.meta.url);\n const workerUrl = new URL('workers/agent-worker.js', distDir);\n\n return new Promise((resolve, reject) => {\n const worker = new Worker(workerUrl, {\n workerData: {\n agentName: task.agent.name,\n files: task.files,\n context: task.context\n }\n } as ConstructorParameters<typeof Worker>[1]);\n\n this.activeWorkers.add(worker);\n\n const timeout = setTimeout(() => {\n worker.terminate().catch(() => undefined);\n reject(new Error(`Agent ${task.agent.name} timed out after ${task.timeoutMs}ms`));\n }, task.timeoutMs);\n\n worker.on('message', (message) => {\n if (message?.type === 'result') {\n clearTimeout(timeout);\n resolve(message.result as AgentResult);\n } else if (message?.type === 'error') {\n clearTimeout(timeout);\n reject(new Error(message.error));\n }\n });\n\n worker.on('error', (error) => {\n clearTimeout(timeout);\n reject(error);\n });\n\n worker.on('exit', (code) => {\n this.activeWorkers.delete(worker);\n if (code !== 0) {\n clearTimeout(timeout);\n reject(new Error(`Worker stopped with exit code ${code}`));\n }\n });\n });\n }\n\n /**\n * Cache results for future use\n */\n private async cacheResults(results: ParallelResult[]): Promise<void> {\n if (!this.cacheEnabled || !this.cache) {\n return;\n }\n\n const cachePromises = results\n .filter(r => r.result.success && !r.fromCache)\n .map(r => {\n const issuesByFile = this.groupIssuesByFile(r.result.issues);\n const perFilePromises = Object.entries(issuesByFile).map(([file, issues]) =>\n this.cache!.setCached(file, r.agent, issues, r.executionTime)\n );\n return Promise.all(perFilePromises);\n });\n\n await Promise.allSettled(cachePromises);\n }\n\n /**\n * Get optimal batch size based on system resources and agent types\n */\n private getOptimalBatchSize(agents: Agent[]): number {\n // CPU-bound agents (like pattern matching) can run more in parallel\n const cpuBoundAgents = agents.filter(a =>\n ['security', 'privacy', 'bugs', 'clean'].includes(a.name)\n ).length;\n\n // I/O-bound agents (like AI-enhanced agents) should be limited\n const ioBoundAgents = agents.length - cpuBoundAgents;\n\n // Adjust batch size based on agent types\n if (ioBoundAgents > cpuBoundAgents) {\n return Math.max(2, Math.min(this.maxWorkers / 2, 4));\n } else {\n return this.maxWorkers;\n }\n }\n\n /**\n * Cleanup resources\n */\n async cleanup(): Promise<void> {\n // Terminate any active workers\n const terminationPromises = Array.from(this.activeWorkers).map(worker =>\n worker.terminate()\n );\n\n await Promise.allSettled(terminationPromises);\n this.activeWorkers.clear();\n }\n\n private groupIssuesByFile(issues: AgentResult['issues']): Record<string, AgentResult['issues']> {\n const grouped: Record<string, AgentResult['issues']> = {};\n\n for (const issue of issues) {\n if (!grouped[issue.file]) {\n grouped[issue.file] = [];\n }\n grouped[issue.file]!.push(issue);\n }\n\n return grouped;\n }\n}\n\n/**\n * Smart agent prioritization based on dependencies and execution characteristics\n */\nexport function prioritizeAgents(agents: Agent[]): Agent[] {\n const prioritized = [...agents];\n\n // Sort by priority tier, then by estimated execution time\n prioritized.sort((a, b) => {\n const aTier = a.priority?.tier || 2;\n const bTier = b.priority?.tier || 2;\n\n if (aTier !== bTier) {\n return aTier - bTier; // Lower tier = higher priority\n }\n\n // Within same tier, prioritize faster agents\n const aTime = a.priority?.estimatedTimeMs || 1000;\n const bTime = b.priority?.estimatedTimeMs || 1000;\n\n return aTime - bTime;\n });\n\n return prioritized;\n}\n\n/**\n * Calculate optimal concurrency based on system resources and agent characteristics\n */\nexport function calculateOptimalConcurrency(): number {\n const numCPUs = cpus().length;\n const availableMemoryGB = process.memoryUsage().rss / 1024 / 1024 / 1024;\n\n // Conservative concurrency for stability\n let optimal = Math.max(2, Math.min(numCPUs - 1, 8));\n\n // Reduce concurrency if low memory\n if (availableMemoryGB < 2) {\n optimal = Math.max(2, Math.floor(optimal / 2));\n }\n\n // Increase slightly for systems with lots of CPU cores\n if (numCPUs > 8) {\n optimal = Math.min(optimal + 2, 12);\n }\n\n return optimal;\n}","import { readFile, writeFile, mkdir, stat } from 'fs/promises';\nimport { join } from 'path';\nimport { createHash } from 'crypto';\nimport type { Issue } from '../types/index.js';\n\ninterface CacheEntry {\n version: string;\n timestamp: number;\n fileHash: string;\n fileSize: number;\n agent: string;\n issues: Issue[];\n executionTime: number;\n}\n\ninterface CacheIndex {\n version: string;\n created: number;\n entries: Record<string, CacheEntry>;\n}\n\nexport class CacheManager {\n private cacheDir: string;\n private indexPath: string;\n private readonly VERSION = '1.0.0';\n private readonly MAX_AGE_MS = 24 * 60 * 60 * 1000; // 24 hours\n private readonly MAX_ENTRIES = 1000;\n\n constructor(baseDir: string) {\n this.cacheDir = join(baseDir, '.trie', 'cache');\n this.indexPath = join(this.cacheDir, 'index.json');\n }\n\n /**\n * Generate cache key for a file and agent combination\n */\n private generateCacheKey(filePath: string, agent: string, fileHash: string): string {\n const key = `${filePath}:${agent}:${fileHash}`;\n return createHash('sha256').update(key).digest('hex').slice(0, 16);\n }\n\n /**\n * Get file hash for cache validation\n */\n private async getFileHash(filePath: string): Promise<{ hash: string; size: number; mtime: number }> {\n try {\n const content = await readFile(filePath, 'utf-8');\n const stats = await stat(filePath);\n const hash = createHash('sha256').update(content).digest('hex').slice(0, 16);\n return {\n hash,\n size: stats.size,\n mtime: stats.mtime.getTime()\n };\n } catch {\n return { hash: '', size: 0, mtime: 0 };\n }\n }\n\n /**\n * Load cache index\n */\n private async loadIndex(): Promise<CacheIndex> {\n try {\n const content = await readFile(this.indexPath, 'utf-8');\n return JSON.parse(content);\n } catch {\n return {\n version: this.VERSION,\n created: Date.now(),\n entries: {}\n };\n }\n }\n\n /**\n * Save cache index\n */\n private async saveIndex(index: CacheIndex): Promise<void> {\n try {\n await mkdir(this.cacheDir, { recursive: true });\n await writeFile(this.indexPath, JSON.stringify(index, null, 2));\n } catch (error) {\n console.warn('Failed to save cache index:', error);\n }\n }\n\n /**\n * Clean up expired entries\n */\n private cleanupExpired(index: CacheIndex): CacheIndex {\n const now = Date.now();\n const validEntries: Record<string, CacheEntry> = {};\n\n for (const [key, entry] of Object.entries(index.entries)) {\n if (now - entry.timestamp < this.MAX_AGE_MS) {\n validEntries[key] = entry;\n }\n }\n\n // If still too many, keep the most recent ones\n const entries = Object.entries(validEntries);\n if (entries.length > this.MAX_ENTRIES) {\n entries.sort((a, b) => b[1].timestamp - a[1].timestamp);\n const limited = entries.slice(0, this.MAX_ENTRIES);\n return {\n ...index,\n entries: Object.fromEntries(limited)\n };\n }\n\n return {\n ...index,\n entries: validEntries\n };\n }\n\n /**\n * Get cached result for a file and agent\n */\n async getCached(filePath: string, agent: string): Promise<Issue[] | null> {\n try {\n const { hash, size, mtime } = await this.getFileHash(filePath);\n if (!hash) return null;\n\n const index = await this.loadIndex();\n const cacheKey = this.generateCacheKey(filePath, agent, hash);\n const entry = index.entries[cacheKey];\n\n if (!entry) return null;\n\n // Validate entry is still fresh\n const isValid = entry.fileHash === hash &&\n entry.version === this.VERSION &&\n (Date.now() - entry.timestamp) < this.MAX_AGE_MS;\n\n if (!isValid) {\n delete index.entries[cacheKey];\n await this.saveIndex(index);\n return null;\n }\n\n return entry.issues;\n } catch {\n return null;\n }\n }\n\n /**\n * Cache result for a file and agent\n */\n async setCached(\n filePath: string,\n agent: string,\n issues: Issue[],\n executionTime: number\n ): Promise<void> {\n try {\n const { hash, size } = await this.getFileHash(filePath);\n if (!hash) return;\n\n const index = await this.loadIndex();\n const cacheKey = this.generateCacheKey(filePath, agent, hash);\n\n index.entries[cacheKey] = {\n version: this.VERSION,\n timestamp: Date.now(),\n fileHash: hash,\n fileSize: size,\n agent,\n issues,\n executionTime\n };\n\n // Clean up old entries\n const cleanedIndex = this.cleanupExpired(index);\n await this.saveIndex(cleanedIndex);\n } catch (error) {\n console.warn('Failed to cache result:', error);\n }\n }\n\n /**\n * Check if multiple files have cached results\n */\n async getCachedBatch(files: string[], agent: string): Promise<Map<string, Issue[]>> {\n const results = new Map<string, Issue[]>();\n\n await Promise.all(\n files.map(async (file) => {\n const cached = await this.getCached(file, agent);\n if (cached) {\n results.set(file, cached);\n }\n })\n );\n\n return results;\n }\n\n /**\n * Get cache statistics\n */\n async getStats(): Promise<{\n totalEntries: number;\n totalSizeKB: number;\n oldestEntry: number | null;\n newestEntry: number | null;\n agents: string[];\n hitRate?: number;\n }> {\n try {\n const index = await this.loadIndex();\n const entries = Object.values(index.entries);\n\n const totalSizeKB = entries.reduce((acc, entry) => acc + entry.fileSize, 0) / 1024;\n const timestamps = entries.map(e => e.timestamp);\n const agents = [...new Set(entries.map(e => e.agent))];\n\n return {\n totalEntries: entries.length,\n totalSizeKB: Math.round(totalSizeKB),\n oldestEntry: timestamps.length > 0 ? Math.min(...timestamps) : null,\n newestEntry: timestamps.length > 0 ? Math.max(...timestamps) : null,\n agents\n };\n } catch {\n return {\n totalEntries: 0,\n totalSizeKB: 0,\n oldestEntry: null,\n newestEntry: null,\n agents: []\n };\n }\n }\n\n /**\n * Clear all cache\n */\n async clear(): Promise<void> {\n try {\n const emptyIndex: CacheIndex = {\n version: this.VERSION,\n created: Date.now(),\n entries: {}\n };\n await this.saveIndex(emptyIndex);\n } catch (error) {\n console.warn('Failed to clear cache:', error);\n }\n }\n}","import type { Agent, AgentResult, ScanContext } from '../types/index.js';\nimport { ParallelExecutor, calculateOptimalConcurrency } from '../utils/parallel-executor.js';\nimport { CacheManager } from '../utils/cache-manager.js';\nimport type { StreamingManager } from '../utils/streaming.js';\n\nexport class Executor {\n async executeAgents(\n agents: Agent[],\n files: string[],\n context: ScanContext,\n options?: {\n streaming?: StreamingManager;\n parallel?: boolean;\n cacheEnabled?: boolean;\n maxConcurrency?: number;\n useWorkerThreads?: boolean;\n timeoutMs?: number;\n }\n ): Promise<AgentResult[]> {\n const parallel = options?.parallel ?? true;\n const cacheEnabled = options?.cacheEnabled ?? true;\n const maxConcurrency = options?.maxConcurrency ?? calculateOptimalConcurrency();\n const useWorkerThreads = options?.useWorkerThreads ?? false;\n\n console.error(`⚡ Executing ${agents.length} agents ${parallel ? 'in parallel' : 'sequentially'}...`);\n\n if (parallel) {\n const cacheManager = cacheEnabled ? new CacheManager(context.workingDir) : null;\n const executor = new ParallelExecutor(cacheManager, maxConcurrency, {\n cacheEnabled,\n useWorkerThreads\n });\n\n if (options?.streaming) {\n executor.setStreaming(options.streaming);\n }\n\n const results = await executor.executeAgents(agents, files, {\n ...context,\n config: { timeoutMs: options?.timeoutMs ?? 120000 }\n });\n\n return agents.map(agent => results.get(agent.name)!).filter(Boolean);\n }\n\n // Execute agents in parallel with timeout\n const promises = agents.map(agent =>\n this.executeAgentWithTimeout(agent, files, context, options?.timeoutMs ?? 30000)\n );\n\n try {\n const results = await Promise.allSettled(promises);\n return results.map((result, index) => {\n if (result.status === 'fulfilled') {\n console.error(`✅ ${agents[index]!.name} completed in ${result.value.executionTime}ms`);\n return result.value;\n } else {\n console.error(`❌ ${agents[index]!.name} failed:`, result.reason);\n return {\n agent: agents[index]!.name,\n issues: [],\n executionTime: 0,\n success: false,\n error: result.reason instanceof Error ? result.reason.message : String(result.reason)\n };\n }\n });\n } catch (error) {\n console.error('Executor error:', error);\n return agents.map(agent => ({\n agent: agent.name,\n issues: [],\n executionTime: 0,\n success: false,\n error: 'Execution failed'\n }));\n }\n }\n\n private async executeAgentWithTimeout(\n agent: Agent,\n files: string[],\n context: ScanContext,\n timeoutMs: number = 30000 // 30 second timeout\n ): Promise<AgentResult> {\n return new Promise(async (resolve, reject) => {\n const timeout = setTimeout(() => {\n reject(new Error(`Agent ${agent.name} timed out after ${timeoutMs}ms`));\n }, timeoutMs);\n\n try {\n const result = await agent.scan(files, context);\n clearTimeout(timeout);\n resolve(result);\n } catch (error) {\n clearTimeout(timeout);\n reject(error);\n }\n });\n }\n}","import { readFile, readdir } from 'fs/promises';\nimport { join, extname, relative, dirname, basename } from 'path';\n\n/**\n * Cross-File Analysis\n * \n * Analyzes relationships between files to detect:\n * - Unused exports\n * - Circular dependencies\n * - Missing imports\n * - Orphaned files\n * - Dead code\n */\n\nexport interface FileNode {\n path: string;\n relativePath: string;\n imports: ImportInfo[];\n exports: ExportInfo[];\n dependencies: string[];\n dependents: string[];\n}\n\nexport interface ImportInfo {\n source: string;\n specifiers: string[];\n isDefault: boolean;\n isNamespace: boolean;\n line: number;\n}\n\nexport interface ExportInfo {\n name: string;\n isDefault: boolean;\n line: number;\n}\n\nexport interface DependencyGraph {\n files: Map<string, FileNode>;\n issues: CrossFileIssue[];\n}\n\nexport interface CrossFileIssue {\n type: 'circular-dep' | 'unused-export' | 'missing-import' | 'orphaned-file' | 'dead-code';\n severity: 'critical' | 'serious' | 'moderate' | 'low';\n files: string[];\n description: string;\n suggestion: string;\n}\n\n/**\n * Build a dependency graph from a directory\n */\nexport async function buildDependencyGraph(rootDir: string, maxFiles: number = 200): Promise<DependencyGraph> {\n const files = new Map<string, FileNode>();\n const issues: CrossFileIssue[] = [];\n\n // Discover all files\n const filePaths = await discoverFiles(rootDir, maxFiles);\n \n // Parse each file\n for (const filePath of filePaths) {\n const node = await parseFile(filePath, rootDir);\n if (node) {\n files.set(node.relativePath, node);\n }\n }\n\n // Resolve dependencies\n for (const [path, node] of files) {\n for (const imp of node.imports) {\n const resolvedPath = resolveImport(imp.source, path, files);\n if (resolvedPath) {\n node.dependencies.push(resolvedPath);\n \n // Add this file as a dependent of the resolved file\n const depNode = files.get(resolvedPath);\n if (depNode) {\n depNode.dependents.push(path);\n }\n }\n }\n }\n\n // Detect issues\n issues.push(...detectCircularDependencies(files));\n issues.push(...detectUnusedExports(files));\n issues.push(...detectOrphanedFiles(files));\n\n return { files, issues };\n}\n\n/**\n * Parse a single file for imports and exports\n */\nasync function parseFile(filePath: string, rootDir: string): Promise<FileNode | null> {\n try {\n const content = await readFile(filePath, 'utf-8');\n const relativePath = relative(rootDir, filePath);\n const lines = content.split('\\n');\n\n const imports: ImportInfo[] = [];\n const exports: ExportInfo[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n const lineNum = i + 1;\n\n // Parse imports\n // import { x, y } from 'module'\n const namedImportMatch = line.match(/import\\s+\\{([^}]+)\\}\\s+from\\s+['\"]([^'\"]+)['\"]/);\n if (namedImportMatch) {\n const specifiers = namedImportMatch[1]!.split(',').map(s => s.trim().split(/\\s+as\\s+/)[0]!.trim());\n imports.push({\n source: namedImportMatch[2]!,\n specifiers,\n isDefault: false,\n isNamespace: false,\n line: lineNum,\n });\n continue;\n }\n\n // import x from 'module'\n const defaultImportMatch = line.match(/import\\s+(\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/);\n if (defaultImportMatch) {\n imports.push({\n source: defaultImportMatch[2]!,\n specifiers: [defaultImportMatch[1]!],\n isDefault: true,\n isNamespace: false,\n line: lineNum,\n });\n continue;\n }\n\n // import * as x from 'module'\n const namespaceImportMatch = line.match(/import\\s+\\*\\s+as\\s+(\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/);\n if (namespaceImportMatch) {\n imports.push({\n source: namespaceImportMatch[2]!,\n specifiers: [namespaceImportMatch[1]!],\n isDefault: false,\n isNamespace: true,\n line: lineNum,\n });\n continue;\n }\n\n // Parse exports\n // export function/class/const/let/var name\n const namedExportMatch = line.match(/export\\s+(?:async\\s+)?(?:function|class|const|let|var|interface|type)\\s+(\\w+)/);\n if (namedExportMatch) {\n exports.push({\n name: namedExportMatch[1]!,\n isDefault: false,\n line: lineNum,\n });\n continue;\n }\n\n // export default\n const defaultExportMatch = line.match(/export\\s+default\\s+(?:function|class)?\\s*(\\w+)?/);\n if (defaultExportMatch) {\n exports.push({\n name: defaultExportMatch[1] || 'default',\n isDefault: true,\n line: lineNum,\n });\n continue;\n }\n\n // export { x, y }\n const reexportMatch = line.match(/export\\s+\\{([^}]+)\\}/);\n if (reexportMatch && !line.includes('from')) {\n const specifiers = reexportMatch[1]!.split(',').map(s => s.trim().split(/\\s+as\\s+/)[0]!.trim());\n for (const spec of specifiers) {\n exports.push({\n name: spec,\n isDefault: false,\n line: lineNum,\n });\n }\n }\n }\n\n return {\n path: filePath,\n relativePath,\n imports,\n exports,\n dependencies: [],\n dependents: [],\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve an import path to a file in the graph\n */\nfunction resolveImport(source: string, fromPath: string, files: Map<string, FileNode>): string | null {\n // Skip external packages\n if (!source.startsWith('.') && !source.startsWith('/')) {\n return null;\n }\n\n const fromDir = dirname(fromPath);\n let resolvedPath = join(fromDir, source);\n\n // Try different extensions\n const extensions = ['', '.ts', '.tsx', '.js', '.jsx', '/index.ts', '/index.tsx', '/index.js'];\n \n for (const ext of extensions) {\n const tryPath = resolvedPath + ext;\n if (files.has(tryPath)) {\n return tryPath;\n }\n }\n\n return null;\n}\n\n/**\n * Detect circular dependencies using DFS\n */\nfunction detectCircularDependencies(files: Map<string, FileNode>): CrossFileIssue[] {\n const issues: CrossFileIssue[] = [];\n const visited = new Set<string>();\n const inStack = new Set<string>();\n\n function dfs(path: string, stack: string[]): void {\n if (inStack.has(path)) {\n // Found a cycle\n const cycleStart = stack.indexOf(path);\n const cycle = [...stack.slice(cycleStart), path];\n \n // Only report if we haven't reported this cycle before\n const cycleKey = cycle.sort().join('->');\n if (!issues.some(i => i.files.sort().join('->') === cycleKey)) {\n issues.push({\n type: 'circular-dep',\n severity: 'serious',\n files: cycle,\n description: `Circular dependency: ${cycle.map(f => basename(f)).join(' → ')}`,\n suggestion: 'Break the cycle by extracting shared code to a separate module',\n });\n }\n return;\n }\n\n if (visited.has(path)) return;\n \n visited.add(path);\n inStack.add(path);\n\n const node = files.get(path);\n if (node) {\n for (const dep of node.dependencies) {\n dfs(dep, [...stack, path]);\n }\n }\n\n inStack.delete(path);\n }\n\n for (const path of files.keys()) {\n dfs(path, []);\n }\n\n return issues;\n}\n\n/**\n * Detect unused exports\n */\nfunction detectUnusedExports(files: Map<string, FileNode>): CrossFileIssue[] {\n const issues: CrossFileIssue[] = [];\n const allImportedSpecifiers = new Map<string, Set<string>>();\n\n // Collect all imported specifiers per file\n for (const node of files.values()) {\n for (const imp of node.imports) {\n const resolvedPath = resolveImport(imp.source, node.relativePath, files);\n if (resolvedPath) {\n if (!allImportedSpecifiers.has(resolvedPath)) {\n allImportedSpecifiers.set(resolvedPath, new Set());\n }\n for (const spec of imp.specifiers) {\n allImportedSpecifiers.get(resolvedPath)!.add(spec);\n }\n if (imp.isDefault) {\n allImportedSpecifiers.get(resolvedPath)!.add('default');\n }\n if (imp.isNamespace) {\n allImportedSpecifiers.get(resolvedPath)!.add('*');\n }\n }\n }\n }\n\n // Find unused exports\n for (const [path, node] of files) {\n const importedSpecs = allImportedSpecifiers.get(path) || new Set();\n \n // Skip if namespace import (imports everything)\n if (importedSpecs.has('*')) continue;\n \n // Skip entry points (files with no dependents)\n if (node.dependents.length === 0 && node.exports.length > 0) continue;\n\n for (const exp of node.exports) {\n const name = exp.isDefault ? 'default' : exp.name;\n if (!importedSpecs.has(name) && !importedSpecs.has(exp.name)) {\n issues.push({\n type: 'unused-export',\n severity: 'low',\n files: [path],\n description: `Unused export '${exp.name}' in ${basename(path)}`,\n suggestion: `Remove the export or ensure it's imported somewhere`,\n });\n }\n }\n }\n\n return issues;\n}\n\n/**\n * Detect orphaned files (no imports or exports)\n */\nfunction detectOrphanedFiles(files: Map<string, FileNode>): CrossFileIssue[] {\n const issues: CrossFileIssue[] = [];\n\n for (const [path, node] of files) {\n // File has no exports and is not imported anywhere\n if (node.exports.length === 0 && node.dependents.length === 0) {\n // Skip if it's likely an entry point\n if (basename(path).match(/^(index|main|app|server)\\./i)) continue;\n // Skip test files\n if (path.includes('.test.') || path.includes('.spec.') || path.includes('__tests__')) continue;\n\n issues.push({\n type: 'orphaned-file',\n severity: 'low',\n files: [path],\n description: `Potentially orphaned file: ${basename(path)}`,\n suggestion: 'Verify this file is needed or remove it',\n });\n }\n }\n\n return issues;\n}\n\n/**\n * Discover files recursively\n */\nasync function discoverFiles(dir: string, maxFiles: number): Promise<string[]> {\n const files: string[] = [];\n const skipDirs = new Set(['node_modules', '.git', 'dist', 'build', '.next', 'coverage']);\n const extensions = new Set(['.ts', '.tsx', '.js', '.jsx']);\n\n async function walk(currentDir: string) {\n if (files.length >= maxFiles) return;\n\n try {\n const entries = await readdir(currentDir, { withFileTypes: true });\n\n for (const entry of entries) {\n if (files.length >= maxFiles) break;\n\n const fullPath = join(currentDir, entry.name);\n\n if (entry.isDirectory()) {\n if (!skipDirs.has(entry.name) && !entry.name.startsWith('.')) {\n await walk(fullPath);\n }\n } else if (entry.isFile()) {\n const ext = extname(entry.name).toLowerCase();\n if (extensions.has(ext)) {\n files.push(fullPath);\n }\n }\n }\n } catch {\n // Skip inaccessible directories\n }\n }\n\n await walk(dir);\n return files;\n}\n\n/**\n * Format dependency graph for output\n */\nexport function formatDependencyGraph(graph: DependencyGraph): string {\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🔗 CROSS-FILE ANALYSIS\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## 📊 Overview\\n\\n`;\n output += `- **Files analyzed:** ${graph.files.size}\\n`;\n output += `- **Issues found:** ${graph.issues.length}\\n\\n`;\n\n // Group issues by type\n const byType = new Map<string, CrossFileIssue[]>();\n for (const issue of graph.issues) {\n if (!byType.has(issue.type)) byType.set(issue.type, []);\n byType.get(issue.type)!.push(issue);\n }\n\n if (graph.issues.length === 0) {\n output += `## ✅ No cross-file issues found!\\n\\n`;\n return output;\n }\n\n output += `## 🚨 Issues\\n\\n`;\n\n // Circular dependencies\n const circular = byType.get('circular-dep') || [];\n if (circular.length > 0) {\n output += `### 🔄 Circular Dependencies (${circular.length})\\n\\n`;\n for (const issue of circular) {\n output += `- ${issue.description}\\n`;\n output += ` *${issue.suggestion}*\\n`;\n }\n output += '\\n';\n }\n\n // Unused exports\n const unused = byType.get('unused-export') || [];\n if (unused.length > 0) {\n output += `### 📤 Unused Exports (${unused.length})\\n\\n`;\n for (const issue of unused.slice(0, 10)) {\n output += `- ${issue.description}\\n`;\n }\n if (unused.length > 10) {\n output += `- *...and ${unused.length - 10} more*\\n`;\n }\n output += '\\n';\n }\n\n // Orphaned files\n const orphaned = byType.get('orphaned-file') || [];\n if (orphaned.length > 0) {\n output += `### 📁 Potentially Orphaned Files (${orphaned.length})\\n\\n`;\n for (const issue of orphaned) {\n output += `- ${issue.description}\\n`;\n }\n output += '\\n';\n }\n\n // Dependency tree visualization\n output += `## 🌳 Dependency Overview\\n\\n`;\n output += `*Top files by dependency count:*\\n\\n`;\n \n const sorted = [...graph.files.values()]\n .sort((a, b) => b.dependents.length - a.dependents.length)\n .slice(0, 10);\n\n output += `| File | Imports | Imported By |\\n`;\n output += `|------|---------|-------------|\\n`;\n for (const node of sorted) {\n output += `| ${basename(node.relativePath)} | ${node.dependencies.length} | ${node.dependents.length} |\\n`;\n }\n\n return output;\n}\n\n","/**\n * Semantic Code Analyzer\n * \n * Parses code to understand its structure for AI analysis.\n * Focuses on:\n * 1. Function extraction - what functions exist, their parameters\n * 2. Route detection - API endpoints and their methods\n * 3. Data flow indicators - sources (user input) and sinks (dangerous ops)\n * 4. Framework detection - Express, Next.js, etc.\n * \n * This provides CONTEXT for AI analysis, not pattern-based detection.\n */\n\nimport { readFile } from 'fs/promises';\nimport { basename, relative } from 'path';\n\n/**\n * Parsed function information for AI context\n */\nexport interface ParsedFunction {\n name: string;\n file: string;\n startLine: number;\n endLine: number;\n params: string[];\n isAsync: boolean;\n isExported: boolean;\n body: string;\n hasUserInput: boolean;\n hasDatabaseOps: boolean;\n hasFileOps: boolean;\n hasAuth: boolean;\n}\n\n/**\n * Detected route/endpoint for AI context\n */\nexport interface DetectedRoute {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'ALL';\n path: string;\n file: string;\n line: number;\n hasAuth: boolean;\n accessesBody: boolean;\n}\n\n/**\n * Code context summary for AI prompts\n */\nexport interface CodeContextSummary {\n framework: string;\n functions: ParsedFunction[];\n routes: DetectedRoute[];\n dataFlowIndicators: DataFlowIndicator[];\n}\n\nexport interface DataFlowIndicator {\n type: 'source' | 'sink';\n category: string;\n file: string;\n line: number;\n code: string;\n}\n\n/**\n * Legacy issue type for backwards compatibility\n */\nexport interface DataFlowIssue {\n type: 'taint-flow' | 'missing-validation' | 'auth-bypass' | 'race-condition' | 'business-logic';\n severity: 'critical' | 'serious' | 'moderate' | 'low';\n source: { file: string; line: number; code: string; symbol?: string };\n sink?: { file: string; line: number; code: string };\n description: string;\n exploit?: string;\n fix: string;\n confidence: number;\n}\n\n/**\n * Semantic Analyzer - Parses code structure for AI context\n */\nexport class SemanticAnalyzer {\n private functions: ParsedFunction[] = [];\n private routes: DetectedRoute[] = [];\n private dataFlowIndicators: DataFlowIndicator[] = [];\n private framework: string = 'unknown';\n \n /**\n * Analyze files and extract code structure for AI\n */\n async analyze(files: string[], rootDir: string): Promise<DataFlowIssue[]> {\n // Parse all files to understand structure\n for (const file of files) {\n try {\n const content = await readFile(file, 'utf-8');\n const relPath = relative(rootDir, file);\n \n this.detectFramework(content);\n this.parseFunctions(content, relPath);\n this.parseRoutes(content, relPath);\n this.extractDataFlowIndicators(content, relPath);\n } catch (e) {\n // Skip unreadable files\n }\n }\n \n // Generate AI-focused analysis summary (not pattern-based issues)\n // For backwards compatibility, we return minimal issues and let AI do the work\n return this.generateAIAnalysisHints();\n }\n\n /**\n * Detect the framework being used\n */\n private detectFramework(content: string): void {\n if (this.framework !== 'unknown') return;\n \n if (/from\\s+['\"]express['\"]|require\\s*\\(\\s*['\"]express['\"]\\s*\\)/.test(content)) {\n this.framework = 'Express';\n } else if (/from\\s+['\"]next|getServerSideProps|getStaticProps|NextRequest/.test(content)) {\n this.framework = 'Next.js';\n } else if (/from\\s+['\"]fastify['\"]/.test(content)) {\n this.framework = 'Fastify';\n } else if (/from\\s+['\"]koa['\"]/.test(content)) {\n this.framework = 'Koa';\n } else if (/from\\s+['\"]hono['\"]/.test(content)) {\n this.framework = 'Hono';\n }\n }\n\n /**\n * Parse functions from code\n */\n private parseFunctions(content: string, file: string): void {\n const lines = content.split('\\n');\n \n const funcPatterns = [\n /(?:export\\s+)?(?:async\\s+)?function\\s+(\\w+)\\s*\\(([^)]*)\\)/,\n /(?:export\\s+)?const\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\(([^)]*)\\)\\s*=>/,\n ];\n \n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n \n for (const pattern of funcPatterns) {\n const match = line.match(pattern);\n if (match) {\n const funcName = match[1]!;\n const params = match[2]?.split(',').map(p => p.trim().split(':')[0]?.trim() || '') || [];\n \n // Find function body\n const bodyLines: string[] = [];\n let braceCount = 0;\n let started = false;\n \n for (let j = i; j < Math.min(i + 100, lines.length); j++) {\n const bodyLine = lines[j] || '';\n bodyLines.push(bodyLine);\n \n for (const char of bodyLine) {\n if (char === '{') { braceCount++; started = true; }\n else if (char === '}') { braceCount--; }\n }\n \n if (started && braceCount === 0) break;\n }\n \n const body = bodyLines.join('\\n');\n \n this.functions.push({\n name: funcName,\n file,\n startLine: i + 1,\n endLine: i + bodyLines.length,\n params,\n isAsync: /async/.test(line),\n isExported: /export/.test(line),\n body,\n hasUserInput: /req\\.body|req\\.params|req\\.query|formData|searchParams/i.test(body),\n hasDatabaseOps: /prisma|sequelize|knex|mongodb|\\.query|\\.execute/i.test(body),\n hasFileOps: /readFile|writeFile|fs\\./i.test(body),\n hasAuth: /auth|session|jwt|token|password/i.test(body),\n });\n }\n }\n }\n }\n\n /**\n * Parse route handlers\n */\n private parseRoutes(content: string, file: string): void {\n const lines = content.split('\\n');\n \n const routePatterns = [\n /(?:app|router)\\.(get|post|put|delete|patch|all)\\s*\\(\\s*['\"]([^'\"]+)['\"]/i,\n /export\\s+(?:async\\s+)?function\\s+(GET|POST|PUT|DELETE|PATCH)/i,\n ];\n \n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n \n for (const pattern of routePatterns) {\n const match = line.match(pattern);\n if (match) {\n const method = match[1]!.toUpperCase() as DetectedRoute['method'];\n const path = match[2] || `/${basename(file).replace(/\\.[^.]+$/, '')}`;\n \n // Look ahead for auth and body access\n const contextLines = lines.slice(i, Math.min(i + 30, lines.length)).join('\\n');\n const hasAuth = /auth|protect|authenticate|session|jwt|bearer/i.test(line + contextLines);\n const accessesBody = /req\\.body|request\\.json\\(\\)|formData/i.test(contextLines);\n \n this.routes.push({\n method,\n path,\n file,\n line: i + 1,\n hasAuth,\n accessesBody,\n });\n }\n }\n }\n }\n\n /**\n * Extract data flow indicators (sources and sinks)\n */\n private extractDataFlowIndicators(content: string, file: string): void {\n const lines = content.split('\\n');\n \n // Sources - where untrusted data enters\n const sources = [\n { pattern: /req\\.body|req\\.params|req\\.query/, category: 'user-input' },\n { pattern: /searchParams|formData/, category: 'url-params' },\n { pattern: /request\\.json\\(\\)|request\\.text\\(\\)/, category: 'request-body' },\n { pattern: /document\\.location|window\\.location/, category: 'browser-url' },\n { pattern: /localStorage|sessionStorage/, category: 'client-storage' },\n ];\n \n // Sinks - where data goes that could be dangerous\n const sinks = [\n { pattern: /\\.query\\s*\\(|\\.execute\\s*\\(|\\.raw\\s*\\(/, category: 'database' },\n { pattern: /exec\\s*\\(|spawn\\s*\\(|execSync/, category: 'command' },\n { pattern: /innerHTML|outerHTML|dangerouslySetInnerHTML/, category: 'html' },\n { pattern: /eval\\s*\\(|new Function\\s*\\(/, category: 'code-eval' },\n { pattern: /writeFile|createWriteStream/, category: 'file-write' },\n { pattern: /redirect\\(|router\\.push\\(/, category: 'redirect' },\n ];\n \n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n \n for (const { pattern, category } of sources) {\n if (pattern.test(line)) {\n this.dataFlowIndicators.push({\n type: 'source',\n category,\n file,\n line: i + 1,\n code: line.trim().substring(0, 100),\n });\n }\n }\n \n for (const { pattern, category } of sinks) {\n if (pattern.test(line)) {\n this.dataFlowIndicators.push({\n type: 'sink',\n category,\n file,\n line: i + 1,\n code: line.trim().substring(0, 100),\n });\n }\n }\n }\n }\n\n /**\n * Generate hints for AI analysis based on parsed structure\n * Returns minimal issues - the real analysis is done by AI\n */\n private generateAIAnalysisHints(): DataFlowIssue[] {\n const hints: DataFlowIssue[] = [];\n \n // Check for routes without auth that access body (likely need review)\n for (const route of this.routes) {\n if (!route.hasAuth && route.accessesBody && ['POST', 'PUT', 'DELETE', 'PATCH'].includes(route.method)) {\n hints.push({\n type: 'auth-bypass',\n severity: 'serious',\n source: {\n file: route.file,\n line: route.line,\n code: `${route.method} ${route.path}`,\n symbol: route.path,\n },\n description: `${route.method} ${route.path} appears to lack authentication - needs AI review`,\n fix: 'Add authentication middleware or verify this endpoint should be public',\n confidence: 0.70,\n });\n }\n }\n \n // Check for functions with user input and database ops (potential injection)\n for (const func of this.functions) {\n if (func.hasUserInput && func.hasDatabaseOps) {\n hints.push({\n type: 'taint-flow',\n severity: 'moderate',\n source: {\n file: func.file,\n line: func.startLine,\n code: `function ${func.name}`,\n symbol: func.name,\n },\n description: `${func.name} has user input flowing to database - needs AI review`,\n fix: 'Verify parameterized queries are used',\n confidence: 0.60,\n });\n }\n }\n \n return hints;\n }\n\n /**\n * Get context summary for AI prompts\n */\n getContextSummary(): CodeContextSummary {\n return {\n framework: this.framework,\n functions: this.functions,\n routes: this.routes,\n dataFlowIndicators: this.dataFlowIndicators,\n };\n }\n\n /**\n * Get analysis summary\n */\n getSummary(): {\n functionsAnalyzed: number;\n routesFound: number;\n authPatternsFound: number;\n framework: string;\n } {\n const authFunctions = this.functions.filter(f => f.hasAuth).length;\n return {\n functionsAnalyzed: this.functions.length,\n routesFound: this.routes.length,\n authPatternsFound: authFunctions,\n framework: this.framework,\n };\n }\n\n /**\n * Generate AI prompt context from parsed code\n */\n generateAIPromptContext(): string {\n let context = `## Code Structure Analysis\\n\\n`;\n context += `**Framework:** ${this.framework}\\n`;\n context += `**Functions:** ${this.functions.length}\\n`;\n context += `**Routes:** ${this.routes.length}\\n\\n`;\n \n if (this.routes.length > 0) {\n context += `### API Endpoints\\n\\n`;\n for (const route of this.routes.slice(0, 10)) {\n const authBadge = route.hasAuth ? '🔒' : '⚠️ No Auth';\n context += `- \\`${route.method} ${route.path}\\` ${authBadge} (${route.file}:${route.line})\\n`;\n }\n if (this.routes.length > 10) {\n context += `- *...and ${this.routes.length - 10} more routes*\\n`;\n }\n context += `\\n`;\n }\n \n if (this.dataFlowIndicators.length > 0) {\n const sources = this.dataFlowIndicators.filter(d => d.type === 'source');\n const sinks = this.dataFlowIndicators.filter(d => d.type === 'sink');\n \n if (sources.length > 0) {\n context += `### Data Sources (User Input)\\n\\n`;\n for (const source of sources.slice(0, 5)) {\n context += `- ${source.category} at ${source.file}:${source.line}\\n`;\n }\n context += `\\n`;\n }\n \n if (sinks.length > 0) {\n context += `### Sensitive Operations\\n\\n`;\n for (const sink of sinks.slice(0, 5)) {\n context += `- ${sink.category} at ${sink.file}:${sink.line}\\n`;\n }\n context += `\\n`;\n }\n }\n \n return context;\n }\n}\n\n/**\n * Format semantic analysis issues for output\n */\nexport function formatSemanticIssues(issues: DataFlowIssue[]): string {\n if (issues.length === 0) {\n return '\\n## ✅ No semantic issues found\\n\\n';\n }\n \n let output = '\\n' + '━'.repeat(60) + '\\n';\n output += '🧠 SEMANTIC ANALYSIS\\n';\n output += '━'.repeat(60) + '\\n\\n';\n output += '*The following areas were flagged for AI review:*\\n\\n';\n \n // Group by type\n const byType = new Map<DataFlowIssue['type'], DataFlowIssue[]>();\n for (const issue of issues) {\n if (!byType.has(issue.type)) byType.set(issue.type, []);\n byType.get(issue.type)!.push(issue);\n }\n \n const typeLabels: Record<DataFlowIssue['type'], string> = {\n 'taint-flow': 'Data Flow Vulnerabilities',\n 'missing-validation': 'Missing Input Validation',\n 'auth-bypass': 'Authentication Issues',\n 'race-condition': 'Race Conditions',\n 'business-logic': 'Business Logic Flaws',\n };\n \n for (const [type, typeIssues] of byType) {\n output += `### ${typeLabels[type]} (${typeIssues.length})\\n\\n`;\n \n for (const issue of typeIssues.slice(0, 5)) {\n const icon = { critical: '🔴', serious: '🟠', moderate: '🟡', low: '🔵' }[issue.severity];\n output += `${icon} **${issue.description}**\\n`;\n output += ` 📍 \\`${basename(issue.source.file)}:${issue.source.line}\\`\\n`;\n output += ` 🔧 ${issue.fix}\\n\\n`;\n }\n \n if (typeIssues.length > 5) {\n output += ` *...and ${typeIssues.length - 5} more*\\n\\n`;\n }\n }\n \n return output;\n}\n","/**\n * Smart Issue Prioritizer\n * \n * Bugbot and linters dump ALL findings on you - overwhelming and noisy.\n * We're smarter. We:\n * \n * 1. DEDUPLICATE - Same issue in many files? Group it.\n * 2. PRIORITIZE BY EXPLOITABILITY - Not all \"critical\" issues are equal\n * 3. FILTER NOISE - Test files, generated code, vendor files\n * 4. FOCUS ON FIXES - What can actually be fixed vs. false positives\n * 5. CONTEXT MATTERS - Admin route without auth > marketing page without auth\n * \n * Result: 10 actionable items, not 10,000 noise items.\n */\n\nimport type { Issue } from '../types/index.js';\nimport { basename } from 'path';\n\nexport interface PrioritizedIssue extends Issue {\n priority: number; // 1-100, higher = more important\n reason: string; // Why this priority\n groupKey?: string; // For deduplication\n instanceCount?: number; // How many times this pattern appears\n}\n\nexport interface PrioritizationResult {\n critical: PrioritizedIssue[]; // MUST fix - actual exploitable vulnerabilities\n important: PrioritizedIssue[]; // SHOULD fix - real issues with lower risk\n advisory: PrioritizedIssue[]; // COULD fix - good practices\n noise: number; // Count of filtered items\n summary: string;\n}\n\ninterface DeduplicationGroup {\n key: string;\n issues: Issue[];\n representative: Issue;\n}\n\n/**\n * Smart prioritization of issues\n */\nexport function prioritizeIssues(issues: Issue[]): PrioritizationResult {\n // Step 1: Filter out noise\n const { filtered, noiseCount } = filterNoise(issues);\n \n // Step 2: Deduplicate similar issues\n const deduplicated = deduplicateIssues(filtered);\n \n // Step 3: Score each issue\n const scored = deduplicated.map(scoreIssue);\n \n // Step 4: Sort by priority\n const sorted = scored.sort((a, b) => b.priority - a.priority);\n \n // Step 5: Categorize\n const critical = sorted.filter(i => i.priority >= 80);\n const important = sorted.filter(i => i.priority >= 50 && i.priority < 80);\n const advisory = sorted.filter(i => i.priority < 50);\n \n // Step 6: Generate summary\n const summary = generateSummary(critical, important, advisory, noiseCount);\n \n return {\n critical: critical.slice(0, 10), // Top 10 critical\n important: important.slice(0, 20), // Top 20 important\n advisory: advisory.slice(0, 30), // Top 30 advisory\n noise: noiseCount,\n summary,\n };\n}\n\n/**\n * Filter out noise - things that aren't real issues\n */\nfunction filterNoise(issues: Issue[]): { filtered: Issue[]; noiseCount: number } {\n const filtered: Issue[] = [];\n let noiseCount = 0;\n \n for (const issue of issues) {\n // Skip if clearly noise\n if (isNoise(issue)) {\n noiseCount++;\n continue;\n }\n filtered.push(issue);\n }\n \n return { filtered, noiseCount };\n}\n\n/**\n * Determine if an issue is noise\n */\nfunction isNoise(issue: Issue): boolean {\n const file = issue.file.toLowerCase();\n const issueText = `${issue.issue} ${issue.fix}`.toLowerCase();\n \n // ============================================\n // ALWAYS NOISE: Files we should never report on\n // ============================================\n \n // Signature/pattern files - never flag the scanner's own definitions\n if (file.includes('signature') || \n file.includes('patterns') ||\n file.includes('vulnerability-signatures')) {\n return true;\n }\n \n // Generated/vendor files\n if (file.includes('node_modules') ||\n file.includes('vendor') ||\n file.includes('.min.') ||\n file.includes('bundle') ||\n file.includes('dist/') ||\n file.includes('build/') ||\n file.includes('.generated.')) {\n return true;\n }\n \n // Lock files\n if (file.includes('package-lock') || \n file.includes('yarn.lock') || \n file.includes('pnpm-lock') ||\n file.includes('shrinkwrap')) {\n return true;\n }\n \n // Type definition files\n if (file.endsWith('.d.ts')) {\n return true;\n }\n \n // ============================================\n // TEST FILES: Aggressive filtering\n // ============================================\n const isTestFile = file.includes('.test.') || \n file.includes('.spec.') || \n file.includes('__tests__') ||\n file.includes('/test/') ||\n file.includes('/tests/') ||\n file.includes('fixture') ||\n file.includes('mock');\n \n if (isTestFile) {\n // Only keep test file issues if they're REAL exposed secrets\n // (not test fixtures designed to test the scanner)\n if (issueText.includes('hardcoded') || issueText.includes('secret')) {\n // Skip if it looks like test data\n if (issueText.includes('test') || \n issueText.includes('mock') ||\n issueText.includes('fake') ||\n issueText.includes('dummy') ||\n issueText.includes('example') ||\n issueText.includes('sample') ||\n issueText.includes('fixture')) {\n return true;\n }\n // Skip generic password patterns in tests\n if (/password.*123|super.*secret|sk-[a-z0-9]{10,30}$/i.test(issueText)) {\n return true;\n }\n }\n // All other test file issues are noise\n return true;\n }\n \n // ============================================\n // CONTEXT-BASED NOISE\n // ============================================\n \n // Config files for low-priority issues\n if ((file.includes('.config.') || file.includes('rc.') || file.includes('config/')) && \n (issue.severity === 'low' || issue.severity === 'moderate')) {\n return true;\n }\n \n // Example/demo files\n if (file.includes('example') || \n file.includes('demo') || \n file.includes('sample') ||\n file.includes('tutorial')) {\n return true;\n }\n \n // Very low confidence\n if (issue.confidence < 0.6) {\n return true;\n }\n \n // ============================================\n // ISSUE-BASED NOISE: False positive patterns\n // ============================================\n \n // TypeScript errors that aren't real (module resolution, lib issues)\n if (issueText.includes('cannot find module') ||\n issueText.includes('cannot find name') ||\n issueText.includes('modulresolution') ||\n issueText.includes('target library')) {\n // These are usually config issues, not code issues\n return true;\n }\n \n // Console.log warnings in non-production contexts\n if (issueText.includes('console.log') && \n (file.includes('cli') || file.includes('script') || file.includes('debug'))) {\n return true;\n }\n \n // Math.random in non-security contexts\n if (issueText.includes('math.random') && \n !file.includes('auth') && \n !file.includes('token') && \n !file.includes('session') &&\n !file.includes('crypto')) {\n return true;\n }\n \n return false;\n}\n\n/**\n * Deduplicate similar issues - group same pattern across files\n */\nfunction deduplicateIssues(issues: Issue[]): Issue[] {\n const groups = new Map<string, DeduplicationGroup>();\n \n for (const issue of issues) {\n // Create a grouping key based on issue type, not location\n const key = createGroupKey(issue);\n \n if (!groups.has(key)) {\n groups.set(key, {\n key,\n issues: [],\n representative: issue,\n });\n }\n \n const group = groups.get(key)!;\n group.issues.push(issue);\n \n // Keep the most severe instance as representative\n if (severityRank(issue.severity) > severityRank(group.representative.severity)) {\n group.representative = issue;\n }\n }\n \n // Return representatives with instance counts\n const deduplicated: Issue[] = [];\n for (const group of groups.values()) {\n const rep = { ...group.representative };\n \n // Add count to the issue text if there are multiple\n if (group.issues.length > 1) {\n rep.issue = `${rep.issue} (${group.issues.length} instances)`;\n }\n \n deduplicated.push(rep);\n }\n \n return deduplicated;\n}\n\n/**\n * Create a grouping key for deduplication\n */\nfunction createGroupKey(issue: Issue): string {\n // Group by: agent + issue type + fix suggestion\n // This groups same recommendations across files\n const issueType = issue.issue.replace(/['\"`][^'\"`]*['\"`]/g, '').trim();\n const fixType = issue.fix.replace(/['\"`][^'\"`]*['\"`]/g, '').substring(0, 50);\n return `${issue.agent}:${issueType}:${fixType}`;\n}\n\n/**\n * Score an issue for priority\n */\nfunction scoreIssue(issue: Issue): PrioritizedIssue {\n let priority = 0;\n const reasons: string[] = [];\n \n // Base score from severity\n const severityScores = { critical: 70, serious: 50, moderate: 30, low: 10 };\n priority += severityScores[issue.severity];\n reasons.push(`${issue.severity} severity`);\n \n // Boost for exploitability indicators\n const exploitablePatterns = [\n { pattern: /injection|exec|eval|command/i, boost: 20, reason: 'directly exploitable' },\n { pattern: /auth.*bypass|missing.*auth|no.*auth/i, boost: 15, reason: 'auth bypass' },\n { pattern: /secret|credential|password|api.?key/i, boost: 15, reason: 'credential exposure' },\n { pattern: /xss|script.*inject/i, boost: 12, reason: 'XSS vulnerability' },\n { pattern: /remote|rce|arbitrary/i, boost: 20, reason: 'remote code execution' },\n ];\n \n for (const { pattern, boost, reason } of exploitablePatterns) {\n if (pattern.test(issue.issue) || pattern.test(issue.fix)) {\n priority += boost;\n reasons.push(reason);\n break; // Only apply biggest boost\n }\n }\n \n // Boost for sensitive file contexts\n const file = issue.file.toLowerCase();\n if (file.includes('auth') || file.includes('login') || file.includes('session')) {\n priority += 10;\n reasons.push('auth-related file');\n }\n if (file.includes('payment') || file.includes('billing') || file.includes('stripe')) {\n priority += 10;\n reasons.push('payment-related file');\n }\n if (file.includes('admin') || file.includes('dashboard')) {\n priority += 8;\n reasons.push('admin area');\n }\n if (file.includes('api/') || file.includes('routes/')) {\n priority += 5;\n reasons.push('API endpoint');\n }\n \n // Reduce for less important contexts\n if (file.includes('test') || file.includes('spec') || file.includes('mock')) {\n priority -= 15;\n reasons.push('test file (lower priority)');\n }\n if (file.includes('example') || file.includes('demo') || file.includes('sample')) {\n priority -= 10;\n reasons.push('example code');\n }\n \n // Boost for auto-fixable issues\n if (issue.autoFixable) {\n priority += 5;\n reasons.push('auto-fixable');\n }\n \n // Boost for high confidence\n if (issue.confidence >= 0.9) {\n priority += 5;\n reasons.push('high confidence');\n } else if (issue.confidence < 0.7) {\n priority -= 10;\n reasons.push('low confidence');\n }\n \n // Cap at 100\n priority = Math.min(100, Math.max(0, priority));\n \n return {\n ...issue,\n priority,\n reason: reasons.slice(0, 3).join(', '),\n groupKey: createGroupKey(issue),\n };\n}\n\n/**\n * Get numeric rank for severity\n */\nfunction severityRank(severity: Issue['severity']): number {\n const ranks = { critical: 4, serious: 3, moderate: 2, low: 1 };\n return ranks[severity];\n}\n\n/**\n * Generate a human-readable summary\n */\nfunction generateSummary(\n critical: PrioritizedIssue[],\n important: PrioritizedIssue[],\n advisory: PrioritizedIssue[],\n noiseCount: number\n): string {\n let summary = '\\n## 🎯 SMART PRIORITIZATION\\n\\n';\n \n summary += '*Trie Agent filtered noise and prioritized by real-world exploitability*\\n\\n';\n \n // Top actions\n if (critical.length > 0) {\n summary += `### 🔴 ${critical.length} Critical Actions Required\\n\\n`;\n for (const issue of critical.slice(0, 5)) {\n summary += `1. **${issue.issue}** - ${issue.reason}\\n`;\n summary += ` 📍 \\`${basename(issue.file)}:${issue.line || '?'}\\`\\n`;\n summary += ` 🔧 ${issue.fix}\\n\\n`;\n }\n if (critical.length > 5) {\n summary += ` *...and ${critical.length - 5} more critical issues*\\n\\n`;\n }\n }\n \n if (important.length > 0) {\n summary += `### 🟠 ${important.length} Important Improvements\\n\\n`;\n for (const issue of important.slice(0, 3)) {\n summary += `- **${issue.issue}** (${issue.reason})\\n`;\n }\n if (important.length > 3) {\n summary += `- *...and ${important.length - 3} more*\\n`;\n }\n summary += '\\n';\n }\n \n // Noise filtered\n if (noiseCount > 0) {\n summary += `### 🔇 ${noiseCount} items filtered as noise\\n\\n`;\n summary += `*Test files, generated code, low-confidence findings*\\n\\n`;\n }\n \n // Comparison callout\n summary += `---\\n`;\n summary += `*💡 Other tools would show you ${critical.length + important.length + advisory.length + noiseCount} issues.*\\n`;\n summary += `*Trie Agent shows you the ${critical.length + Math.min(important.length, 10)} that actually matter.*\\n`;\n \n return summary;\n}\n\n/**\n * Format prioritized results for output\n */\nexport function formatPrioritizedResults(result: PrioritizationResult): string {\n return result.summary;\n}\n","/**\n * Attack Surface Analyzer\n * \n * This is what REAL security teams want - not a list of 10,000 lint errors,\n * but a clear picture of:\n * \n * 1. What endpoints are exposed?\n * 2. What data do they accept?\n * 3. What's the blast radius if compromised?\n * 4. What's protecting each entry point?\n * \n * This is intelligence, not just scanning.\n */\n\nimport { readFile } from 'fs/promises';\nimport { basename, relative } from 'path';\n\nexport interface AttackSurface {\n endpoints: Endpoint[];\n dataFlows: DataFlow[];\n authBoundaries: AuthBoundary[];\n sensitiveAssets: SensitiveAsset[];\n summary: AttackSurfaceSummary;\n}\n\nexport interface Endpoint {\n method: string;\n path: string;\n file: string;\n line: number;\n accepts: string[]; // What data types it accepts\n returns: string[]; // What it returns\n authRequired: boolean;\n authType?: string; // 'jwt', 'session', 'api-key', etc\n rateLimit: boolean;\n inputValidation: boolean;\n riskScore: number; // 1-10\n riskFactors: string[];\n}\n\nexport interface DataFlow {\n source: string; // Where data comes from\n destination: string; // Where data goes\n dataType: string; // 'user-input', 'pii', 'credentials', etc\n encrypted: boolean;\n logged: boolean;\n file: string;\n risk: 'high' | 'medium' | 'low';\n}\n\nexport interface AuthBoundary {\n name: string;\n type: 'middleware' | 'check' | 'decorator';\n file: string;\n line: number;\n protects: string[]; // What endpoints/resources it protects\n bypassRisk: string[]; // Potential bypass scenarios\n}\n\nexport interface SensitiveAsset {\n type: 'database' | 'api-key' | 'pii' | 'payment' | 'session';\n location: string;\n accessPoints: string[]; // What can access this\n protection: string[]; // What protections exist\n}\n\nexport interface AttackSurfaceSummary {\n totalEndpoints: number;\n publicEndpoints: number;\n authProtectedEndpoints: number;\n unprotectedSensitiveEndpoints: number;\n dataFlowsWithPII: number;\n riskScore: number; // Overall 1-100\n topRisks: string[];\n}\n\n/**\n * Analyze the attack surface of a codebase\n */\nexport class AttackSurfaceAnalyzer {\n private endpoints: Endpoint[] = [];\n private dataFlows: DataFlow[] = [];\n private authBoundaries: AuthBoundary[] = [];\n private sensitiveAssets: SensitiveAsset[] = [];\n \n async analyze(files: string[], rootDir: string): Promise<AttackSurface> {\n // Parse all files\n for (const file of files) {\n try {\n const content = await readFile(file, 'utf-8');\n const relPath = relative(rootDir, file);\n \n this.findEndpoints(content, relPath);\n this.findDataFlows(content, relPath);\n this.findAuthBoundaries(content, relPath);\n this.findSensitiveAssets(content, relPath);\n } catch (e) {\n // Skip unreadable files\n }\n }\n \n // Calculate risk scores\n this.calculateRiskScores();\n \n // Generate summary\n const summary = this.generateSummary();\n \n return {\n endpoints: this.endpoints,\n dataFlows: this.dataFlows,\n authBoundaries: this.authBoundaries,\n sensitiveAssets: this.sensitiveAssets,\n summary,\n };\n }\n\n private findEndpoints(content: string, file: string): void {\n const lines = content.split('\\n');\n \n // Express/Fastify routes\n const routePatterns = [\n /(?:app|router)\\.(get|post|put|delete|patch|all)\\s*\\(\\s*['\"]([^'\"]+)['\"]/gi,\n /export\\s+(?:async\\s+)?function\\s+(GET|POST|PUT|DELETE|PATCH)\\s*\\(/gi,\n ];\n \n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n \n for (const pattern of routePatterns) {\n pattern.lastIndex = 0;\n const match = pattern.exec(line);\n if (match) {\n const method = match[1]!.toUpperCase();\n const path = match[2] || `/${basename(file).replace(/\\.[^.]+$/, '')}`;\n \n // Analyze the route context\n const contextLines = lines.slice(i, Math.min(i + 50, lines.length)).join('\\n');\n const authType = this.detectAuthType(line, contextLines);\n \n const endpoint: Endpoint = {\n method,\n path,\n file,\n line: i + 1,\n accepts: this.detectAcceptedData(contextLines),\n returns: this.detectReturnedData(contextLines),\n authRequired: this.detectAuth(line, contextLines),\n ...(authType && { authType }),\n rateLimit: /rateLimit|throttle/i.test(contextLines),\n inputValidation: /validate|schema|zod|yup|joi/i.test(contextLines),\n riskScore: 0, // Calculated later\n riskFactors: [],\n };\n \n this.endpoints.push(endpoint);\n }\n }\n }\n }\n\n private detectAcceptedData(context: string): string[] {\n const accepts: string[] = [];\n \n if (/req\\.body|request\\.json|formData/i.test(context)) {\n accepts.push('json-body');\n }\n if (/req\\.query|searchParams/i.test(context)) {\n accepts.push('query-params');\n }\n if (/req\\.params|params\\./i.test(context)) {\n accepts.push('url-params');\n }\n if (/req\\.file|multipart|upload/i.test(context)) {\n accepts.push('file-upload');\n }\n if (/req\\.headers|authorization/i.test(context)) {\n accepts.push('headers');\n }\n if (/req\\.cookies/i.test(context)) {\n accepts.push('cookies');\n }\n \n return accepts;\n }\n\n private detectReturnedData(context: string): string[] {\n const returns: string[] = [];\n \n if (/user|profile|account/i.test(context) && /res\\.json|return.*json/i.test(context)) {\n returns.push('user-data');\n }\n if (/password|secret|key|token/i.test(context)) {\n returns.push('credentials');\n }\n if (/redirect/i.test(context)) {\n returns.push('redirect');\n }\n if (/render|html/i.test(context)) {\n returns.push('html');\n }\n \n return returns;\n }\n\n private detectAuth(routeLine: string, context: string): boolean {\n return /auth|protect|session|jwt|bearer|verify/i.test(routeLine) ||\n /req\\.user|session\\.|isAuthenticated/i.test(context);\n }\n\n private detectAuthType(routeLine: string, context: string): string | undefined {\n if (/jwt|bearer/i.test(routeLine + context)) return 'jwt';\n if (/session/i.test(routeLine + context)) return 'session';\n if (/apiKey|api[_-]?key/i.test(routeLine + context)) return 'api-key';\n if (/oauth/i.test(routeLine + context)) return 'oauth';\n return undefined;\n }\n\n private findDataFlows(content: string, file: string): void {\n const lines = content.split('\\n');\n \n // Track data from sources to sinks\n const sources = [\n { pattern: /req\\.body/g, type: 'user-input' },\n { pattern: /req\\.query/g, type: 'user-input' },\n { pattern: /email|phone|address|name/gi, type: 'pii' },\n { pattern: /password|secret|token/gi, type: 'credentials' },\n { pattern: /credit|card|payment/gi, type: 'payment' },\n ];\n \n const sinks = [\n { pattern: /\\.query\\(|prisma\\.|mongoose\\./g, dest: 'database' },\n { pattern: /console\\.log|logger\\./g, dest: 'logs' },\n { pattern: /res\\.json|res\\.send/g, dest: 'response' },\n { pattern: /fetch\\(|axios\\./g, dest: 'external-api' },\n ];\n \n for (const source of sources) {\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n if (source.pattern.test(line)) {\n source.pattern.lastIndex = 0;\n \n // Look for where this data goes in nearby lines\n const context = lines.slice(i, Math.min(i + 20, lines.length)).join('\\n');\n \n for (const sink of sinks) {\n if (sink.pattern.test(context)) {\n sink.pattern.lastIndex = 0;\n \n this.dataFlows.push({\n source: source.type,\n destination: sink.dest,\n dataType: source.type,\n encrypted: /encrypt|hash|bcrypt/i.test(context),\n logged: /console|logger/i.test(context),\n file,\n risk: this.assessDataFlowRisk(source.type, sink.dest),\n });\n }\n }\n }\n }\n }\n }\n\n private assessDataFlowRisk(sourceType: string, destType: string): 'high' | 'medium' | 'low' {\n // Credentials to logs = critical\n if (sourceType === 'credentials' && destType === 'logs') return 'high';\n // PII to external = high\n if (sourceType === 'pii' && destType === 'external-api') return 'high';\n // Payment data anywhere sensitive = high\n if (sourceType === 'payment') return 'high';\n // User input to database = medium (could be injection)\n if (sourceType === 'user-input' && destType === 'database') return 'medium';\n return 'low';\n }\n\n private findAuthBoundaries(content: string, file: string): void {\n const lines = content.split('\\n');\n \n const authPatterns = [\n { pattern: /export\\s+(?:const|function)\\s+(\\w*auth\\w*)/i, type: 'middleware' as const },\n { pattern: /(?:const|function)\\s+(\\w*protect\\w*|\\w*verify\\w*)/i, type: 'middleware' as const },\n { pattern: /@(?:Auth|Authorized|Protected)\\s*\\(/i, type: 'decorator' as const },\n ];\n \n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n \n for (const { pattern, type } of authPatterns) {\n const match = line.match(pattern);\n if (match) {\n const context = lines.slice(i, Math.min(i + 30, lines.length)).join('\\n');\n \n this.authBoundaries.push({\n name: match[1] || 'auth',\n type,\n file,\n line: i + 1,\n protects: this.findProtectedRoutes(match[1] || 'auth'),\n bypassRisk: this.assessBypassRisks(context),\n });\n }\n }\n }\n }\n\n private findProtectedRoutes(_authName: string): string[] {\n return this.endpoints\n .filter(e => e.authType || e.authRequired)\n .map(e => `${e.method} ${e.path}`);\n }\n\n private assessBypassRisks(context: string): string[] {\n const risks: string[] = [];\n \n if (/req\\.query|req\\.params/.test(context) && !/validate|sanitize/.test(context)) {\n risks.push('Input not validated before auth check');\n }\n if (/skip|bypass|disable/.test(context)) {\n risks.push('Bypass logic detected');\n }\n if (!/throw|return.*401|unauthorized/i.test(context)) {\n risks.push('No clear rejection path');\n }\n \n return risks;\n }\n\n private findSensitiveAssets(content: string, file: string): void {\n // Find database connections\n if (/DATABASE_URL|mongodb|postgres|mysql/i.test(content)) {\n this.sensitiveAssets.push({\n type: 'database',\n location: file,\n accessPoints: this.findAccessPoints('database', file),\n protection: this.findProtections(content, 'database'),\n });\n }\n \n // Find API keys\n if (/API_KEY|OPENAI|STRIPE|SENDGRID/i.test(content)) {\n this.sensitiveAssets.push({\n type: 'api-key',\n location: file,\n accessPoints: ['environment-variable'],\n protection: this.findProtections(content, 'api-key'),\n });\n }\n \n // Find PII storage\n if (/email|phone|ssn|address/i.test(content) && /schema|model|table/i.test(content)) {\n this.sensitiveAssets.push({\n type: 'pii',\n location: file,\n accessPoints: this.findAccessPoints('pii', file),\n protection: this.findProtections(content, 'pii'),\n });\n }\n }\n\n private findAccessPoints(_assetType: string, file: string): string[] {\n return this.endpoints\n .filter(e => e.file === file || e.returns.some(r => r.includes('user') || r.includes('data')))\n .map(e => `${e.method} ${e.path}`);\n }\n\n private findProtections(content: string, _assetType: string): string[] {\n const protections: string[] = [];\n \n if (/encrypt/i.test(content)) protections.push('encryption');\n if (/hash|bcrypt/i.test(content)) protections.push('hashing');\n if (/auth|protect/i.test(content)) protections.push('auth-required');\n if (/rateLimit|throttle/i.test(content)) protections.push('rate-limiting');\n if (/validate|sanitize/i.test(content)) protections.push('input-validation');\n \n return protections;\n }\n\n private calculateRiskScores(): void {\n for (const endpoint of this.endpoints) {\n let risk = 0;\n const factors: string[] = [];\n \n // Method risks\n if (['POST', 'PUT', 'DELETE', 'PATCH'].includes(endpoint.method)) {\n risk += 2;\n factors.push('mutating method');\n }\n \n // Auth risks\n if (!endpoint.authRequired) {\n risk += 3;\n factors.push('no auth required');\n }\n \n // Input risks\n if (endpoint.accepts.includes('file-upload')) {\n risk += 2;\n factors.push('accepts file upload');\n }\n if (endpoint.accepts.includes('json-body') && !endpoint.inputValidation) {\n risk += 2;\n factors.push('no input validation');\n }\n \n // Path risks\n if (/admin|user|account|payment|billing/i.test(endpoint.path)) {\n risk += 2;\n factors.push('sensitive path');\n }\n \n // Rate limiting\n if (!endpoint.rateLimit && endpoint.accepts.length > 0) {\n risk += 1;\n factors.push('no rate limiting');\n }\n \n endpoint.riskScore = Math.min(10, risk);\n endpoint.riskFactors = factors;\n }\n }\n\n private generateSummary(): AttackSurfaceSummary {\n const publicEndpoints = this.endpoints.filter(e => !e.authRequired);\n const sensitiveUnprotected = this.endpoints.filter(e => \n !e.authRequired && (\n /admin|user|payment|billing|account/i.test(e.path) ||\n e.accepts.includes('json-body')\n )\n );\n const piiFlows = this.dataFlows.filter(f => f.dataType === 'pii' || f.dataType === 'credentials');\n \n // Calculate overall risk\n let overallRisk = 0;\n overallRisk += publicEndpoints.length * 2;\n overallRisk += sensitiveUnprotected.length * 10;\n overallRisk += piiFlows.filter(f => f.risk === 'high').length * 15;\n overallRisk = Math.min(100, overallRisk);\n \n const topRisks: string[] = [];\n if (sensitiveUnprotected.length > 0) {\n topRisks.push(`${sensitiveUnprotected.length} sensitive endpoints without auth`);\n }\n if (piiFlows.filter(f => !f.encrypted).length > 0) {\n topRisks.push('PII data flows without encryption');\n }\n if (this.endpoints.filter(e => !e.inputValidation && e.accepts.length > 0).length > 3) {\n topRisks.push('Multiple endpoints without input validation');\n }\n \n return {\n totalEndpoints: this.endpoints.length,\n publicEndpoints: publicEndpoints.length,\n authProtectedEndpoints: this.endpoints.length - publicEndpoints.length,\n unprotectedSensitiveEndpoints: sensitiveUnprotected.length,\n dataFlowsWithPII: piiFlows.length,\n riskScore: overallRisk,\n topRisks,\n };\n }\n}\n\n/**\n * Format attack surface analysis for output\n */\nexport function formatAttackSurface(surface: AttackSurface): string {\n if (surface.endpoints.length === 0) {\n return '';\n }\n \n let output = '\\n' + '━'.repeat(60) + '\\n';\n output += '🎯 ATTACK SURFACE ANALYSIS\\n';\n output += '━'.repeat(60) + '\\n\\n';\n \n output += `## Summary\\n\\n`;\n output += `| Metric | Value |\\n`;\n output += `|--------|-------|\\n`;\n output += `| Total Endpoints | ${surface.summary.totalEndpoints} |\\n`;\n output += `| Public (No Auth) | ${surface.summary.publicEndpoints} |\\n`;\n output += `| Auth Protected | ${surface.summary.authProtectedEndpoints} |\\n`;\n output += `| ⚠️ Unprotected Sensitive | ${surface.summary.unprotectedSensitiveEndpoints} |\\n`;\n output += `| PII Data Flows | ${surface.summary.dataFlowsWithPII} |\\n`;\n output += `| **Risk Score** | **${surface.summary.riskScore}/100** |\\n\\n`;\n \n if (surface.summary.topRisks.length > 0) {\n output += `## 🚨 Top Risks\\n\\n`;\n for (const risk of surface.summary.topRisks) {\n output += `- ${risk}\\n`;\n }\n output += '\\n';\n }\n \n // High risk endpoints\n const highRiskEndpoints = surface.endpoints\n .filter(e => e.riskScore >= 6)\n .sort((a, b) => b.riskScore - a.riskScore);\n \n if (highRiskEndpoints.length > 0) {\n output += `## 🔴 High-Risk Endpoints\\n\\n`;\n for (const ep of highRiskEndpoints.slice(0, 5)) {\n output += `### ${ep.method} ${ep.path}\\n`;\n output += `- 📍 \\`${ep.file}:${ep.line}\\`\\n`;\n output += `- Risk Score: ${ep.riskScore}/10\\n`;\n output += `- Auth: ${ep.authRequired ? `✅ ${ep.authType || 'required'}` : '❌ None'}\\n`;\n output += `- Accepts: ${ep.accepts.join(', ') || 'nothing'}\\n`;\n output += `- Risk Factors: ${ep.riskFactors.join(', ')}\\n\\n`;\n }\n }\n \n // Data flow risks\n const riskyFlows = surface.dataFlows.filter(f => f.risk === 'high');\n if (riskyFlows.length > 0) {\n output += `## 🔄 Risky Data Flows\\n\\n`;\n for (const flow of riskyFlows.slice(0, 5)) {\n output += `- **${flow.source}** → **${flow.destination}**\\n`;\n output += ` - Type: ${flow.dataType}\\n`;\n output += ` - Encrypted: ${flow.encrypted ? '✅' : '❌'}\\n`;\n output += ` - File: \\`${flow.file}\\`\\n\\n`;\n }\n }\n \n return output;\n}\n","/**\n * Code Symbol Index\n * \n * Uses a trie to index all code symbols (functions, classes, variables, exports)\n * for O(m) lookup where m = symbol name length.\n * \n * Benefits:\n * - Instant symbol lookup across entire codebase\n * - Fast autocomplete suggestions\n * - Cross-reference detection (unused exports, missing imports)\n * - Incremental updates when files change\n */\n\nimport { Trie } from './trie.js';\n\nexport interface SymbolInfo {\n name: string;\n type: 'function' | 'class' | 'variable' | 'interface' | 'type' | 'enum' | 'const' | 'method' | 'property' | 'export' | 'import';\n file: string;\n line: number;\n column: number;\n exported: boolean;\n async: boolean;\n signature?: string;\n jsDoc?: string;\n references: SymbolReference[];\n}\n\nexport interface SymbolReference {\n file: string;\n line: number;\n column: number;\n type: 'definition' | 'usage' | 'import' | 'export';\n}\n\nexport interface SymbolIndexStats {\n totalSymbols: number;\n byType: Record<string, number>;\n filesIndexed: number;\n exportedSymbols: number;\n unusedExports: string[];\n}\n\n/**\n * Code Symbol Index using Trie for fast lookups\n */\nexport class SymbolIndex {\n private symbolTrie: Trie<SymbolInfo[]>;\n private fileSymbols: Map<string, SymbolInfo[]>;\n private exportedSymbols: Set<string>;\n private importedSymbols: Map<string, Set<string>>; // file -> imported symbol names\n \n constructor() {\n this.symbolTrie = new Trie<SymbolInfo[]>();\n this.fileSymbols = new Map();\n this.exportedSymbols = new Set();\n this.importedSymbols = new Map();\n }\n\n /**\n * Index a file's symbols\n * O(n) where n = file content length\n */\n indexFile(filePath: string, content: string): void {\n // Remove old symbols from this file\n this.removeFile(filePath);\n \n const symbols: SymbolInfo[] = [];\n const lines = content.split('\\n');\n \n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n const lineNum = i + 1;\n \n // Extract various symbol types\n const extracted = [\n ...this.extractFunctions(line, lineNum, filePath),\n ...this.extractClasses(line, lineNum, filePath),\n ...this.extractVariables(line, lineNum, filePath),\n ...this.extractInterfaces(line, lineNum, filePath),\n ...this.extractTypes(line, lineNum, filePath),\n ...this.extractImports(line, lineNum, filePath),\n ];\n \n symbols.push(...extracted);\n }\n \n // Store symbols\n this.fileSymbols.set(filePath, symbols);\n \n // Add to trie\n for (const symbol of symbols) {\n const existing = this.symbolTrie.search(symbol.name);\n if (existing.found && existing.value) {\n existing.value.push(symbol);\n } else {\n this.symbolTrie.insert(symbol.name, [symbol]);\n }\n \n // Track exports\n if (symbol.exported) {\n this.exportedSymbols.add(`${filePath}:${symbol.name}`);\n }\n }\n }\n\n /**\n * Remove a file from the index\n * O(s) where s = number of symbols in file\n */\n removeFile(filePath: string): void {\n const symbols = this.fileSymbols.get(filePath) || [];\n \n for (const symbol of symbols) {\n const existing = this.symbolTrie.search(symbol.name);\n if (existing.found && existing.value) {\n const filtered = existing.value.filter(s => s.file !== filePath);\n if (filtered.length > 0) {\n this.symbolTrie.insert(symbol.name, filtered);\n }\n }\n \n this.exportedSymbols.delete(`${filePath}:${symbol.name}`);\n }\n \n this.fileSymbols.delete(filePath);\n this.importedSymbols.delete(filePath);\n }\n\n /**\n * Look up a symbol by name\n * O(m) where m = symbol name length\n */\n lookup(name: string): SymbolInfo[] {\n const result = this.symbolTrie.search(name);\n return result.found && result.value ? result.value : [];\n }\n\n /**\n * Find symbols with a given prefix (autocomplete)\n * O(p + n) where p = prefix length, n = number of matches\n */\n findWithPrefix(prefix: string): SymbolInfo[] {\n const patterns = this.symbolTrie.getWithPrefix(prefix);\n const symbols: SymbolInfo[] = [];\n \n for (const { value } of patterns) {\n if (value) {\n symbols.push(...value);\n }\n }\n \n return symbols;\n }\n\n /**\n * Get all symbols in a file\n * O(1)\n */\n getFileSymbols(filePath: string): SymbolInfo[] {\n return this.fileSymbols.get(filePath) || [];\n }\n\n /**\n * Find all references to a symbol\n * O(n) where n = total symbols (could be optimized with reverse index)\n */\n findReferences(name: string): SymbolReference[] {\n const symbols = this.lookup(name);\n const references: SymbolReference[] = [];\n \n for (const symbol of symbols) {\n references.push({\n file: symbol.file,\n line: symbol.line,\n column: symbol.column,\n type: symbol.exported ? 'export' : 'definition',\n });\n references.push(...symbol.references);\n }\n \n return references;\n }\n\n /**\n * Find unused exports\n * O(e) where e = number of exports\n */\n findUnusedExports(): Array<{ name: string; file: string; line: number }> {\n const unused: Array<{ name: string; file: string; line: number }> = [];\n \n // Collect all imported symbols\n const allImported = new Set<string>();\n for (const imports of this.importedSymbols.values()) {\n for (const imp of imports) {\n allImported.add(imp);\n }\n }\n \n // Check each export\n for (const [file, symbols] of this.fileSymbols) {\n for (const symbol of symbols) {\n if (symbol.exported && !allImported.has(symbol.name)) {\n // Skip index files and main entry points\n if (file.includes('index.') || file.includes('main.')) continue;\n \n unused.push({\n name: symbol.name,\n file,\n line: symbol.line,\n });\n }\n }\n }\n \n return unused;\n }\n\n /**\n * Get index statistics\n */\n getStats(): SymbolIndexStats {\n const byType: Record<string, number> = {};\n let totalSymbols = 0;\n \n for (const symbols of this.fileSymbols.values()) {\n for (const symbol of symbols) {\n totalSymbols++;\n byType[symbol.type] = (byType[symbol.type] || 0) + 1;\n }\n }\n \n const unusedExports = this.findUnusedExports();\n \n return {\n totalSymbols,\n byType,\n filesIndexed: this.fileSymbols.size,\n exportedSymbols: this.exportedSymbols.size,\n unusedExports: unusedExports.map(u => `${u.file}:${u.name}`),\n };\n }\n\n // ============================================\n // Symbol extraction methods\n // ============================================\n\n private extractFunctions(line: string, lineNum: number, file: string): SymbolInfo[] {\n const symbols: SymbolInfo[] = [];\n \n // export async function name()\n // function name()\n // async function name()\n const funcMatch = line.match(/^(\\s*)(export\\s+)?(async\\s+)?function\\s+(\\w+)\\s*\\(([^)]*)\\)/);\n if (funcMatch) {\n symbols.push({\n name: funcMatch[4]!,\n type: 'function',\n file,\n line: lineNum,\n column: (funcMatch[1]?.length || 0) + 1,\n exported: !!funcMatch[2],\n async: !!funcMatch[3],\n signature: `function ${funcMatch[4]}(${funcMatch[5]})`,\n references: [],\n });\n }\n \n // export const name = () => {}\n // const name = async () => {}\n const arrowMatch = line.match(/^(\\s*)(export\\s+)?(const|let|var)\\s+(\\w+)\\s*=\\s*(async\\s*)?\\(/);\n if (arrowMatch) {\n symbols.push({\n name: arrowMatch[4]!,\n type: 'function',\n file,\n line: lineNum,\n column: (arrowMatch[1]?.length || 0) + 1,\n exported: !!arrowMatch[2],\n async: !!arrowMatch[5],\n signature: `const ${arrowMatch[4]} = ${arrowMatch[5] || ''}(...)`,\n references: [],\n });\n }\n \n return symbols;\n }\n\n private extractClasses(line: string, lineNum: number, file: string): SymbolInfo[] {\n const symbols: SymbolInfo[] = [];\n \n // export class Name\n // class Name\n const classMatch = line.match(/^(\\s*)(export\\s+)?(abstract\\s+)?class\\s+(\\w+)/);\n if (classMatch) {\n symbols.push({\n name: classMatch[4]!,\n type: 'class',\n file,\n line: lineNum,\n column: (classMatch[1]?.length || 0) + 1,\n exported: !!classMatch[2],\n async: false,\n signature: `class ${classMatch[4]}`,\n references: [],\n });\n }\n \n return symbols;\n }\n\n private extractVariables(line: string, lineNum: number, file: string): SymbolInfo[] {\n const symbols: SymbolInfo[] = [];\n \n // Skip if it's a function (already handled)\n if (/=\\s*(async\\s*)?\\(/.test(line)) return symbols;\n \n // export const NAME = \n // const name = \n const varMatch = line.match(/^(\\s*)(export\\s+)?(const|let|var)\\s+(\\w+)\\s*=/);\n if (varMatch) {\n const name = varMatch[4]!;\n // Determine if it's a constant (UPPER_CASE) or variable\n const isConst = /^[A-Z][A-Z0-9_]*$/.test(name);\n \n symbols.push({\n name,\n type: isConst ? 'const' : 'variable',\n file,\n line: lineNum,\n column: (varMatch[1]?.length || 0) + 1,\n exported: !!varMatch[2],\n async: false,\n references: [],\n });\n }\n \n return symbols;\n }\n\n private extractInterfaces(line: string, lineNum: number, file: string): SymbolInfo[] {\n const symbols: SymbolInfo[] = [];\n \n // export interface Name\n // interface Name\n const interfaceMatch = line.match(/^(\\s*)(export\\s+)?interface\\s+(\\w+)/);\n if (interfaceMatch) {\n symbols.push({\n name: interfaceMatch[3]!,\n type: 'interface',\n file,\n line: lineNum,\n column: (interfaceMatch[1]?.length || 0) + 1,\n exported: !!interfaceMatch[2],\n async: false,\n references: [],\n });\n }\n \n return symbols;\n }\n\n private extractTypes(line: string, lineNum: number, file: string): SymbolInfo[] {\n const symbols: SymbolInfo[] = [];\n \n // export type Name = \n // type Name = \n const typeMatch = line.match(/^(\\s*)(export\\s+)?type\\s+(\\w+)\\s*=/);\n if (typeMatch) {\n symbols.push({\n name: typeMatch[3]!,\n type: 'type',\n file,\n line: lineNum,\n column: (typeMatch[1]?.length || 0) + 1,\n exported: !!typeMatch[2],\n async: false,\n references: [],\n });\n }\n \n // export enum Name\n const enumMatch = line.match(/^(\\s*)(export\\s+)?enum\\s+(\\w+)/);\n if (enumMatch) {\n symbols.push({\n name: enumMatch[3]!,\n type: 'enum',\n file,\n line: lineNum,\n column: (enumMatch[1]?.length || 0) + 1,\n exported: !!enumMatch[2],\n async: false,\n references: [],\n });\n }\n \n return symbols;\n }\n\n private extractImports(line: string, lineNum: number, file: string): SymbolInfo[] {\n const symbols: SymbolInfo[] = [];\n \n // import { a, b } from 'module'\n const namedImportMatch = line.match(/import\\s+\\{([^}]+)\\}\\s+from\\s+['\"]([^'\"]+)['\"]/);\n if (namedImportMatch) {\n const specifiers = namedImportMatch[1]!.split(',').map(s => {\n const parts = s.trim().split(/\\s+as\\s+/);\n return parts[parts.length - 1]!.trim();\n });\n \n // Track imports for this file\n if (!this.importedSymbols.has(file)) {\n this.importedSymbols.set(file, new Set());\n }\n for (const spec of specifiers) {\n this.importedSymbols.get(file)!.add(spec);\n \n symbols.push({\n name: spec,\n type: 'import',\n file,\n line: lineNum,\n column: 1,\n exported: false,\n async: false,\n signature: `import { ${spec} } from '${namedImportMatch[2]}'`,\n references: [],\n });\n }\n }\n \n // import Name from 'module'\n const defaultImportMatch = line.match(/import\\s+(\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/);\n if (defaultImportMatch && !line.includes('{')) {\n const name = defaultImportMatch[1]!;\n \n if (!this.importedSymbols.has(file)) {\n this.importedSymbols.set(file, new Set());\n }\n this.importedSymbols.get(file)!.add(name);\n \n symbols.push({\n name,\n type: 'import',\n file,\n line: lineNum,\n column: 1,\n exported: false,\n async: false,\n signature: `import ${name} from '${defaultImportMatch[2]}'`,\n references: [],\n });\n }\n \n return symbols;\n }\n\n /**\n * Serialize the index for caching\n */\n toJSON(): object {\n const files: Record<string, SymbolInfo[]> = {};\n for (const [file, symbols] of this.fileSymbols) {\n files[file] = symbols;\n }\n return { files };\n }\n\n /**\n * Load from serialized JSON\n */\n static fromJSON(data: { files: Record<string, SymbolInfo[]> }): SymbolIndex {\n const index = new SymbolIndex();\n \n for (const [file, symbols] of Object.entries(data.files)) {\n index.fileSymbols.set(file, symbols);\n \n for (const symbol of symbols) {\n const existing = index.symbolTrie.search(symbol.name);\n if (existing.found && existing.value) {\n existing.value.push(symbol);\n } else {\n index.symbolTrie.insert(symbol.name, [symbol]);\n }\n \n if (symbol.exported) {\n index.exportedSymbols.add(`${file}:${symbol.name}`);\n }\n \n if (symbol.type === 'import') {\n if (!index.importedSymbols.has(file)) {\n index.importedSymbols.set(file, new Set());\n }\n index.importedSymbols.get(file)!.add(symbol.name);\n }\n }\n }\n \n return index;\n }\n}\n\n// Global symbol index instance\nlet globalSymbolIndex: SymbolIndex | null = null;\n\nexport function getSymbolIndex(): SymbolIndex {\n if (!globalSymbolIndex) {\n globalSymbolIndex = new SymbolIndex();\n }\n return globalSymbolIndex;\n}\n\nexport function resetSymbolIndex(): void {\n globalSymbolIndex = new SymbolIndex();\n}\n\n","/**\n * Incremental Scanner\n * \n * Uses trie-based indexing for smart, incremental code scanning.\n * Only re-scans changed parts of the codebase.\n * \n * Benefits:\n * - O(c) scanning where c = changed lines, not entire file\n * - Maintains persistent index for instant lookups\n * - Caches vulnerability scans per file\n * - Tracks file hashes for change detection\n */\n\nimport { createHash } from 'crypto';\nimport { readFile, writeFile, mkdir } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { getSymbolIndex, SymbolIndex } from './symbol-index.js';\nimport { scanForVulnerabilities, VulnerabilityMatch, getVulnerabilityTrie } from './vulnerability-signatures.js';\n\nexport interface FileState {\n path: string;\n hash: string;\n lastScanned: number;\n lineCount: number;\n vulnerabilities: VulnerabilityMatch[];\n symbolCount: number;\n}\n\nexport interface ScanCache {\n version: string;\n created: number;\n lastUpdated: number;\n files: Record<string, FileState>;\n}\n\nexport interface IncrementalScanResult {\n filesScanned: number;\n filesSkipped: number;\n filesChanged: number;\n totalVulnerabilities: number;\n newVulnerabilities: VulnerabilityMatch[];\n resolvedVulnerabilities: VulnerabilityMatch[];\n scanTimeMs: number;\n cacheHitRate: number;\n}\n\nconst CACHE_VERSION = '1.0.0';\nconst CACHE_FILE = '.trie-cache.json';\n\n/**\n * Incremental Scanner with trie-based caching\n */\nexport class IncrementalScanner {\n private cache: ScanCache;\n private symbolIndex: SymbolIndex;\n private cacheDir: string;\n private dirty: boolean = false;\n\n constructor(projectRoot: string) {\n this.cacheDir = join(projectRoot, '.trie');\n this.symbolIndex = getSymbolIndex();\n this.cache = {\n version: CACHE_VERSION,\n created: Date.now(),\n lastUpdated: Date.now(),\n files: {},\n };\n }\n\n /**\n * Load cache from disk\n */\n async loadCache(): Promise<boolean> {\n const cachePath = join(this.cacheDir, CACHE_FILE);\n \n if (!existsSync(cachePath)) {\n return false;\n }\n\n try {\n const data = await readFile(cachePath, 'utf-8');\n const parsed = JSON.parse(data);\n \n // Version check\n if (parsed.version !== CACHE_VERSION) {\n console.error(' ⚠️ Cache version mismatch, rebuilding...');\n return false;\n }\n \n this.cache = parsed;\n console.error(` ✅ Loaded cache with ${Object.keys(this.cache.files).length} files`);\n return true;\n } catch (error) {\n console.error(' ⚠️ Failed to load cache, rebuilding...');\n return false;\n }\n }\n\n /**\n * Save cache to disk\n */\n async saveCache(): Promise<void> {\n if (!this.dirty) return;\n\n try {\n await mkdir(this.cacheDir, { recursive: true });\n const cachePath = join(this.cacheDir, CACHE_FILE);\n \n this.cache.lastUpdated = Date.now();\n await writeFile(cachePath, JSON.stringify(this.cache, null, 2));\n \n this.dirty = false;\n } catch (error) {\n console.error(' ⚠️ Failed to save cache');\n }\n }\n\n /**\n * Compute file hash for change detection\n * O(n) where n = file size\n */\n private computeHash(content: string): string {\n return createHash('sha256').update(content).digest('hex').slice(0, 16);\n }\n\n /**\n * Check if a file has changed since last scan\n * O(1) for cache lookup + O(n) for hash if needed\n */\n async hasFileChanged(filePath: string, content?: string): Promise<boolean> {\n const cached = this.cache.files[filePath];\n if (!cached) return true;\n\n if (!content) {\n try {\n content = await readFile(filePath, 'utf-8');\n } catch {\n return true;\n }\n }\n\n const currentHash = this.computeHash(content);\n return currentHash !== cached.hash;\n }\n\n /**\n * Scan a single file incrementally\n * Returns cached results if file unchanged\n */\n async scanFile(filePath: string, forceRescan: boolean = false): Promise<{\n vulnerabilities: VulnerabilityMatch[];\n fromCache: boolean;\n symbolCount: number;\n }> {\n let content: string;\n \n try {\n content = await readFile(filePath, 'utf-8');\n } catch {\n return { vulnerabilities: [], fromCache: false, symbolCount: 0 };\n }\n\n const hash = this.computeHash(content);\n const cached = this.cache.files[filePath];\n\n // Check if we can use cached results\n if (!forceRescan && cached && cached.hash === hash) {\n return {\n vulnerabilities: cached.vulnerabilities,\n fromCache: true,\n symbolCount: cached.symbolCount,\n };\n }\n\n // Need to scan - file is new or changed\n const vulnerabilities = scanForVulnerabilities(content, filePath);\n \n // Index symbols\n this.symbolIndex.indexFile(filePath, content);\n const symbols = this.symbolIndex.getFileSymbols(filePath);\n\n // Update cache\n this.cache.files[filePath] = {\n path: filePath,\n hash,\n lastScanned: Date.now(),\n lineCount: content.split('\\n').length,\n vulnerabilities,\n symbolCount: symbols.length,\n };\n this.dirty = true;\n\n return {\n vulnerabilities,\n fromCache: false,\n symbolCount: symbols.length,\n };\n }\n\n /**\n * Scan multiple files with incremental caching\n */\n async scanFiles(\n filePaths: string[],\n forceRescan: boolean = false,\n onFileProgress?: (filePath: string, fromCache: boolean) => void\n ): Promise<IncrementalScanResult> {\n const startTime = Date.now();\n \n // Initialize vulnerability trie\n getVulnerabilityTrie();\n\n let filesScanned = 0;\n let filesSkipped = 0;\n let filesChanged = 0;\n const allVulnerabilities: VulnerabilityMatch[] = [];\n const newVulnerabilities: VulnerabilityMatch[] = [];\n const previousVulnerabilities = new Map<string, VulnerabilityMatch[]>();\n\n // Track previous state for comparison\n for (const [path, state] of Object.entries(this.cache.files)) {\n previousVulnerabilities.set(path, state.vulnerabilities);\n }\n\n // Scan each file\n for (const filePath of filePaths) {\n const result = await this.scanFile(filePath, forceRescan);\n onFileProgress?.(filePath, result.fromCache);\n \n allVulnerabilities.push(...result.vulnerabilities);\n\n if (result.fromCache) {\n filesSkipped++;\n } else {\n filesScanned++;\n \n // Check for new vulnerabilities\n const previous = previousVulnerabilities.get(filePath) || [];\n const previousPatterns = new Set(previous.map(v => `${v.line}:${v.pattern}`));\n \n for (const vuln of result.vulnerabilities) {\n if (!previousPatterns.has(`${vuln.line}:${vuln.pattern}`)) {\n newVulnerabilities.push(vuln);\n filesChanged++;\n }\n }\n }\n }\n\n // Find resolved vulnerabilities\n const currentPaths = new Set(filePaths);\n const resolvedVulnerabilities: VulnerabilityMatch[] = [];\n \n for (const [path, vulns] of previousVulnerabilities) {\n if (currentPaths.has(path)) {\n const current = this.cache.files[path]?.vulnerabilities || [];\n const currentPatterns = new Set(current.map(v => `${v.line}:${v.pattern}`));\n \n for (const vuln of vulns) {\n if (!currentPatterns.has(`${vuln.line}:${vuln.pattern}`)) {\n resolvedVulnerabilities.push(vuln);\n }\n }\n }\n }\n\n const scanTimeMs = Date.now() - startTime;\n const totalFiles = filesScanned + filesSkipped;\n const cacheHitRate = totalFiles > 0 ? (filesSkipped / totalFiles) * 100 : 0;\n\n return {\n filesScanned,\n filesSkipped,\n filesChanged,\n totalVulnerabilities: allVulnerabilities.length,\n newVulnerabilities,\n resolvedVulnerabilities,\n scanTimeMs,\n cacheHitRate,\n };\n }\n\n /**\n * Remove a file from the cache\n */\n removeFile(filePath: string): void {\n delete this.cache.files[filePath];\n this.symbolIndex.removeFile(filePath);\n this.dirty = true;\n }\n\n /**\n * Clear the entire cache\n */\n clearCache(): void {\n this.cache = {\n version: CACHE_VERSION,\n created: Date.now(),\n lastUpdated: Date.now(),\n files: {},\n };\n this.dirty = true;\n }\n\n /**\n * Get cache statistics\n */\n getStats(): {\n filesInCache: number;\n totalVulnerabilities: number;\n totalSymbols: number;\n oldestScan: number;\n cacheSize: number;\n } {\n let totalVulnerabilities = 0;\n let totalSymbols = 0;\n let oldestScan = Date.now();\n\n for (const file of Object.values(this.cache.files)) {\n totalVulnerabilities += file.vulnerabilities.length;\n totalSymbols += file.symbolCount;\n if (file.lastScanned < oldestScan) {\n oldestScan = file.lastScanned;\n }\n }\n\n return {\n filesInCache: Object.keys(this.cache.files).length,\n totalVulnerabilities,\n totalSymbols,\n oldestScan,\n cacheSize: JSON.stringify(this.cache).length,\n };\n }\n\n /**\n * Get all cached vulnerabilities\n */\n getAllVulnerabilities(): VulnerabilityMatch[] {\n const all: VulnerabilityMatch[] = [];\n for (const file of Object.values(this.cache.files)) {\n all.push(...file.vulnerabilities);\n }\n return all;\n }\n\n /**\n * Get vulnerabilities by severity\n */\n getVulnerabilitiesBySeverity(): Record<string, VulnerabilityMatch[]> {\n const bySeverity: Record<string, VulnerabilityMatch[]> = {\n critical: [],\n serious: [],\n moderate: [],\n low: [],\n };\n\n for (const file of Object.values(this.cache.files)) {\n for (const vuln of file.vulnerabilities) {\n bySeverity[vuln.severity]?.push(vuln);\n }\n }\n\n return bySeverity;\n }\n}\n\n/**\n * Format incremental scan results for output\n */\nexport function formatIncrementalScanResult(result: IncrementalScanResult): string {\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `⚡ INCREMENTAL SCAN RESULTS (Trie-Powered)\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## 📊 Scan Statistics\\n\\n`;\n output += `| Metric | Value |\\n`;\n output += `|--------|-------|\\n`;\n output += `| Files Scanned | ${result.filesScanned} |\\n`;\n output += `| Files Skipped (cached) | ${result.filesSkipped} |\\n`;\n output += `| Cache Hit Rate | ${result.cacheHitRate.toFixed(1)}% |\\n`;\n output += `| Total Vulnerabilities | ${result.totalVulnerabilities} |\\n`;\n output += `| Scan Time | ${result.scanTimeMs}ms |\\n`;\n output += `\\n`;\n\n if (result.newVulnerabilities.length > 0) {\n output += `## 🆕 New Vulnerabilities (${result.newVulnerabilities.length})\\n\\n`;\n for (const vuln of result.newVulnerabilities) {\n const icon = { critical: '🔴', serious: '🟠', moderate: '🟡', low: '🔵' }[vuln.severity];\n output += `${icon} **Line ${vuln.line}:** ${vuln.description}\\n`;\n output += ` - Pattern: \\`${vuln.pattern}\\`\\n`;\n output += ` - Fix: ${vuln.fix}\\n`;\n if (vuln.cwe) output += ` - CWE: ${vuln.cwe}\\n`;\n output += `\\n`;\n }\n }\n\n if (result.resolvedVulnerabilities.length > 0) {\n output += `## ✅ Resolved Vulnerabilities (${result.resolvedVulnerabilities.length})\\n\\n`;\n for (const vuln of result.resolvedVulnerabilities) {\n output += `- ~~${vuln.pattern}~~ at line ${vuln.line}\\n`;\n }\n output += `\\n`;\n }\n\n if (result.newVulnerabilities.length === 0 && result.resolvedVulnerabilities.length === 0) {\n output += `## ✅ No Changes\\n\\n`;\n output += `No new vulnerabilities introduced. No vulnerabilities resolved.\\n`;\n }\n\n return output;\n}\n\n","import type { Issue } from '../types/index.js';\n\nexport interface StreamUpdate {\n type: 'progress' | 'agent_start' | 'agent_complete' | 'issue_found' | 'scan_complete' | 'error';\n timestamp: number;\n data: any;\n}\n\nexport interface ScanProgress {\n totalFiles: number;\n processedFiles: number;\n currentFile?: string;\n activeAgents: string[];\n completedAgents: string[];\n totalIssues: number;\n issuesBySeverity: {\n critical: number;\n serious: number;\n moderate: number;\n low: number;\n };\n}\n\n/**\n * Streaming scan results for real-time feedback\n */\nexport class StreamingManager {\n private listeners: Set<(update: StreamUpdate) => void> = new Set();\n private progress: ScanProgress = {\n totalFiles: 0,\n processedFiles: 0,\n activeAgents: [],\n completedAgents: [],\n totalIssues: 0,\n issuesBySeverity: { critical: 0, serious: 0, moderate: 0, low: 0 }\n };\n\n /**\n * Subscribe to scan updates\n */\n subscribe(callback: (update: StreamUpdate) => void): () => void {\n this.listeners.add(callback);\n return () => this.listeners.delete(callback);\n }\n\n /**\n * Emit an update to all listeners\n */\n private emit(type: StreamUpdate['type'], data: any): void {\n const update: StreamUpdate = {\n type,\n timestamp: Date.now(),\n data\n };\n\n this.listeners.forEach(listener => {\n try {\n listener(update);\n } catch (error) {\n console.warn('Stream listener error:', error);\n }\n });\n }\n\n /**\n * Initialize scan with file count\n */\n startScan(totalFiles: number): void {\n this.progress = {\n totalFiles,\n processedFiles: 0,\n activeAgents: [],\n completedAgents: [],\n totalIssues: 0,\n issuesBySeverity: { critical: 0, serious: 0, moderate: 0, low: 0 }\n };\n\n this.emit('progress', { ...this.progress });\n }\n\n /**\n * Update current file being processed\n */\n updateCurrentFile(file: string): void {\n this.progress.currentFile = file;\n this.emit('progress', { ...this.progress });\n }\n\n /**\n * Mark file as processed\n */\n completeFile(): void {\n this.progress.processedFiles++;\n this.emit('progress', { ...this.progress });\n }\n\n /**\n * Start agent execution\n */\n startAgent(agentName: string): void {\n if (!this.progress.activeAgents.includes(agentName)) {\n this.progress.activeAgents.push(agentName);\n }\n this.emit('agent_start', { agent: agentName });\n this.emit('progress', { ...this.progress });\n }\n\n /**\n * Complete agent execution\n */\n completeAgent(agentName: string, issues: Issue[]): void {\n // Move from active to completed\n this.progress.activeAgents = this.progress.activeAgents.filter(a => a !== agentName);\n if (!this.progress.completedAgents.includes(agentName)) {\n this.progress.completedAgents.push(agentName);\n }\n\n // Update issue counts\n for (const issue of issues) {\n this.progress.issuesBySeverity[issue.severity]++;\n this.progress.totalIssues++;\n }\n\n this.emit('agent_complete', {\n agent: agentName,\n issueCount: issues.length,\n issues: issues.slice(0, 5) // Only send first 5 for streaming\n });\n this.emit('progress', { ...this.progress });\n }\n\n /**\n * Report new issue found\n */\n reportIssue(issue: Issue): void {\n this.progress.issuesBySeverity[issue.severity]++;\n this.progress.totalIssues++;\n this.emit('issue_found', issue);\n this.emit('progress', { ...this.progress });\n }\n\n /**\n * Complete the entire scan\n */\n completeScan(totalIssues: Issue[]): void {\n this.emit('scan_complete', {\n totalFiles: this.progress.totalFiles,\n totalIssues: totalIssues.length,\n issuesBySeverity: this.progress.issuesBySeverity,\n completedAgents: this.progress.completedAgents\n });\n }\n\n /**\n * Report error\n */\n reportError(error: Error, context?: string): void {\n this.emit('error', {\n message: error.message,\n context,\n stack: error.stack\n });\n }\n\n /**\n * Get current progress\n */\n getProgress(): ScanProgress {\n return { ...this.progress };\n }\n\n /**\n * Reset state\n */\n reset(): void {\n this.progress = {\n totalFiles: 0,\n processedFiles: 0,\n activeAgents: [],\n completedAgents: [],\n totalIssues: 0,\n issuesBySeverity: { critical: 0, serious: 0, moderate: 0, low: 0 }\n };\n }\n}\n\n/**\n * Format streaming updates for console output\n */\nexport function formatConsoleUpdate(update: StreamUpdate): string | null {\n switch (update.type) {\n case 'agent_start':\n return `🔍 Starting ${update.data.agent}...`;\n\n case 'agent_complete':\n const emoji = update.data.issueCount > 0 ? '⚠️' : '✅';\n return `${emoji} ${update.data.agent} found ${update.data.issueCount} issues`;\n\n case 'progress':\n const { processedFiles, totalFiles, currentFile, activeAgents } = update.data;\n const progress = totalFiles > 0 ? Math.round((processedFiles / totalFiles) * 100) : 0;\n const active = activeAgents.length > 0 ? ` (${activeAgents.join(', ')})` : '';\n const current = currentFile ? ` • ${currentFile.split('/').pop()}` : '';\n return `📊 Progress: ${progress}% (${processedFiles}/${totalFiles})${active}${current}`;\n\n case 'scan_complete':\n return `🎉 Scan complete! Found ${update.data.totalIssues} issues across ${update.data.totalFiles} files`;\n\n case 'error':\n return `❌ Error: ${update.data.message}`;\n\n default:\n return null;\n }\n}\n\n/**\n * Simple progress bar for terminal\n */\nexport function createProgressBar(current: number, total: number, width: number = 40): string {\n if (total === 0) return '█'.repeat(width);\n\n const progress = current / total;\n const filled = Math.round(width * progress);\n const empty = width - filled;\n\n return '█'.repeat(filled) + '░'.repeat(empty);\n}","import type { Issue } from '../types/index.js';\n\nexport interface IssueGroup {\n id: string;\n pattern: string;\n description: string;\n count: number;\n severity: Issue['severity'];\n issues: Issue[];\n riskScore: number;\n fixComplexity: 'trivial' | 'easy' | 'medium' | 'hard';\n category: 'security' | 'performance' | 'maintainability' | 'correctness' | 'style';\n suggestedAction: string;\n bulkFixAvailable: boolean;\n}\n\nexport interface PriorityReport {\n urgent: IssueGroup[];\n high: IssueGroup[];\n medium: IssueGroup[];\n low: IssueGroup[];\n totalIssues: number;\n totalGroups: number;\n riskScore: number;\n recommendations: string[];\n}\n\n/**\n * Smart issue analysis and grouping\n *\n * Groups related issues together and provides intelligent prioritization\n * based on risk, impact, and fix complexity\n */\nexport class IssueAnalyzer {\n /**\n * Analyze and group issues intelligently\n */\n analyzeIssues(issues: Issue[]): PriorityReport {\n // Group issues by pattern\n const groups = this.groupIssuesByPattern(issues);\n\n // Calculate risk scores\n const groupsWithRisk = groups.map(group => ({\n ...group,\n riskScore: this.calculateRiskScore(group),\n category: this.categorizeGroup(group),\n fixComplexity: this.assessFixComplexity(group),\n bulkFixAvailable: this.canBulkFix(group)\n }));\n\n // Prioritize groups\n const prioritized = this.prioritizeGroups(groupsWithRisk);\n\n // Generate recommendations\n const recommendations = this.generateRecommendations(prioritized, issues);\n\n return {\n urgent: prioritized.filter(g => g.riskScore >= 80),\n high: prioritized.filter(g => g.riskScore >= 60 && g.riskScore < 80),\n medium: prioritized.filter(g => g.riskScore >= 40 && g.riskScore < 60),\n low: prioritized.filter(g => g.riskScore < 40),\n totalIssues: issues.length,\n totalGroups: groups.length,\n riskScore: this.calculateOverallRisk(prioritized),\n recommendations\n };\n }\n\n /**\n * Group issues by similar patterns\n */\n private groupIssuesByPattern(issues: Issue[]): IssueGroup[] {\n const groups = new Map<string, Issue[]>();\n\n // Group by exact issue pattern first\n for (const issue of issues) {\n const pattern = this.extractPattern(issue);\n if (!groups.has(pattern)) {\n groups.set(pattern, []);\n }\n groups.get(pattern)!.push(issue);\n }\n\n // Merge similar patterns\n const mergedGroups = this.mergeSimilarPatterns(groups);\n\n // Convert to IssueGroup objects\n return Array.from(mergedGroups.entries()).map(([pattern, groupIssues]) => {\n const severity = this.getGroupSeverity(groupIssues);\n return {\n id: this.generateGroupId(pattern),\n pattern,\n description: this.generateGroupDescription(pattern, groupIssues),\n count: groupIssues.length,\n severity,\n issues: groupIssues,\n riskScore: 0, // Will be calculated later\n fixComplexity: 'medium',\n category: 'correctness',\n suggestedAction: '',\n bulkFixAvailable: false\n };\n });\n }\n\n /**\n * Extract normalized pattern from issue\n */\n private extractPattern(issue: Issue): string {\n // Remove file-specific parts and normalize\n let pattern = issue.issue\n .replace(/in file [^\\s]+/gi, 'in file')\n .replace(/at line \\d+/gi, 'at line X')\n .replace(/\\b\\d+\\b/g, 'N')\n .replace(/['\"][^'\"]*['\"]/g, '\"STRING\"')\n .replace(/\\s+/g, ' ')\n .trim();\n\n // Add agent and severity context\n pattern = `[${issue.agent}] [${issue.severity}] ${pattern}`;\n\n return pattern;\n }\n\n /**\n * Merge patterns that are very similar\n */\n private mergeSimilarPatterns(groups: Map<string, Issue[]>): Map<string, Issue[]> {\n const merged = new Map<string, Issue[]>();\n const processed = new Set<string>();\n\n for (const [pattern, issues] of groups) {\n if (processed.has(pattern)) continue;\n\n // Find similar patterns\n const similar = [pattern];\n const combinedIssues = [...issues];\n\n for (const [otherPattern, otherIssues] of groups) {\n if (pattern === otherPattern || processed.has(otherPattern)) continue;\n\n const similarity = this.calculatePatternSimilarity(pattern, otherPattern);\n if (similarity > 0.85) { // 85% similarity threshold\n similar.push(otherPattern);\n combinedIssues.push(...otherIssues);\n processed.add(otherPattern);\n }\n }\n\n processed.add(pattern);\n merged.set(pattern, combinedIssues);\n }\n\n return merged;\n }\n\n /**\n * Calculate similarity between two patterns\n */\n private calculatePatternSimilarity(pattern1: string, pattern2: string): number {\n const words1 = new Set(pattern1.toLowerCase().split(/\\W+/));\n const words2 = new Set(pattern2.toLowerCase().split(/\\W+/));\n\n const intersection = new Set([...words1].filter(w => words2.has(w)));\n const union = new Set([...words1, ...words2]);\n\n return intersection.size / union.size;\n }\n\n /**\n * Get the most severe level in a group\n */\n private getGroupSeverity(issues: Issue[]): Issue['severity'] {\n const severityOrder: Issue['severity'][] = ['critical', 'serious', 'moderate', 'low'];\n\n for (const severity of severityOrder) {\n if (issues.some(i => i.severity === severity)) {\n return severity;\n }\n }\n\n return 'low';\n }\n\n /**\n * Calculate risk score for a group (0-100)\n */\n private calculateRiskScore(group: IssueGroup): number {\n let score = 0;\n\n // Severity weight (40% of score)\n const severityWeights = { critical: 40, serious: 30, moderate: 20, low: 10 };\n score += severityWeights[group.severity];\n\n // Count weight (30% of score)\n const countScore = Math.min(30, group.count * 2); // Max 30 points, 2 per issue\n score += countScore;\n\n // Pattern-specific bonuses (30% of score)\n const pattern = group.pattern.toLowerCase();\n\n // Security issues get bonus\n if (pattern.includes('security') || pattern.includes('injection') || pattern.includes('xss') ||\n pattern.includes('csrf') || pattern.includes('secret') || pattern.includes('hardcoded')) {\n score += 25;\n }\n\n // Performance issues in hot paths\n if (pattern.includes('loop') || pattern.includes('n+1') || pattern.includes('memory') ||\n pattern.includes('performance')) {\n score += 20;\n }\n\n // Critical infrastructure\n if (pattern.includes('auth') || pattern.includes('database') || pattern.includes('payment')) {\n score += 15;\n }\n\n // Widespread issues (cross-file)\n if (group.count > 10) {\n score += 10;\n }\n\n // AI-generated code issues\n if (pattern.includes('console.log') || pattern.includes('any') || pattern.includes('ts-ignore')) {\n score += 5;\n }\n\n return Math.min(100, score);\n }\n\n /**\n * Categorize issue group\n */\n private categorizeGroup(group: IssueGroup): IssueGroup['category'] {\n const pattern = group.pattern.toLowerCase();\n\n if (pattern.includes('security') || pattern.includes('injection') || pattern.includes('xss') ||\n pattern.includes('secret') || pattern.includes('hardcoded') || pattern.includes('auth')) {\n return 'security';\n }\n\n if (pattern.includes('performance') || pattern.includes('memory') || pattern.includes('n+1') ||\n pattern.includes('slow') || pattern.includes('optimization')) {\n return 'performance';\n }\n\n if (pattern.includes('maintainability') || pattern.includes('complexity') || pattern.includes('duplication') ||\n pattern.includes('refactor') || pattern.includes('tech debt')) {\n return 'maintainability';\n }\n\n if (pattern.includes('bug') || pattern.includes('error') || pattern.includes('null') ||\n pattern.includes('undefined') || pattern.includes('race condition')) {\n return 'correctness';\n }\n\n return 'style';\n }\n\n /**\n * Assess fix complexity\n */\n private assessFixComplexity(group: IssueGroup): IssueGroup['fixComplexity'] {\n const pattern = group.pattern.toLowerCase();\n\n // Trivial fixes\n if (pattern.includes('console.log') || pattern.includes('unused import') ||\n pattern.includes('whitespace') || pattern.includes('formatting')) {\n return 'trivial';\n }\n\n // Easy fixes\n if (pattern.includes('type annotation') || pattern.includes('validation') ||\n pattern.includes('error handling') || group.severity === 'low') {\n return 'easy';\n }\n\n // Hard fixes\n if (pattern.includes('architecture') || pattern.includes('race condition') ||\n pattern.includes('security') && group.severity === 'critical') {\n return 'hard';\n }\n\n return 'medium';\n }\n\n /**\n * Check if group can be bulk-fixed\n */\n private canBulkFix(group: IssueGroup): boolean {\n const pattern = group.pattern.toLowerCase();\n\n // Patterns that can be bulk-fixed\n const bulkFixablePatterns = [\n 'console.log',\n 'unused import',\n 'missing semicolon',\n 'type annotation',\n 'whitespace',\n 'formatting',\n 'eslint-disable',\n 'ts-ignore'\n ];\n\n return bulkFixablePatterns.some(p => pattern.includes(p)) && group.count > 2;\n }\n\n /**\n * Prioritize groups by risk and impact\n */\n private prioritizeGroups(groups: IssueGroup[]): IssueGroup[] {\n return groups.sort((a, b) => {\n // Primary sort: risk score\n if (a.riskScore !== b.riskScore) {\n return b.riskScore - a.riskScore;\n }\n\n // Secondary sort: severity\n const severityOrder = { critical: 0, serious: 1, moderate: 2, low: 3 };\n const aSev = severityOrder[a.severity];\n const bSev = severityOrder[b.severity];\n if (aSev !== bSev) {\n return aSev - bSev;\n }\n\n // Tertiary sort: count (more issues = higher priority)\n return b.count - a.count;\n });\n }\n\n /**\n * Generate actionable recommendations\n */\n private generateRecommendations(groups: IssueGroup[], allIssues: Issue[]): string[] {\n const recommendations: string[] = [];\n\n // Critical security issues\n const criticalSecurity = groups.filter(g =>\n g.category === 'security' && g.severity === 'critical'\n );\n if (criticalSecurity.length > 0) {\n recommendations.push(\n `🚨 Immediate action required: Fix ${criticalSecurity.length} critical security issue group(s)`\n );\n }\n\n // Bulk-fixable issues\n const bulkFixable = groups.filter(g => g.bulkFixAvailable);\n if (bulkFixable.length > 0) {\n const totalBulkIssues = bulkFixable.reduce((sum, g) => sum + g.count, 0);\n recommendations.push(\n `⚡ Quick win: Bulk-fix ${totalBulkIssues} issues across ${bulkFixable.length} patterns`\n );\n }\n\n // Performance issues\n const performance = groups.filter(g => g.category === 'performance');\n if (performance.length > 0) {\n recommendations.push(\n `🚀 Performance: Address ${performance.length} performance issue pattern(s)`\n );\n }\n\n // Widespread issues\n const widespread = groups.filter(g => g.count > 10);\n if (widespread.length > 0) {\n recommendations.push(\n `📊 Systemic: ${widespread.length} patterns appear across many files - consider automated fixes`\n );\n }\n\n // AI code cleanup\n const aiIssues = allIssues.filter(i =>\n i.issue.toLowerCase().includes('console.log') ||\n i.issue.toLowerCase().includes('any') ||\n i.issue.toLowerCase().includes('ts-ignore')\n );\n if (aiIssues.length > 20) {\n recommendations.push(\n `🤖 AI cleanup: ${aiIssues.length} AI-generated code issues detected - run cleanup tools`\n );\n }\n\n // Code quality\n const qualityScore = this.calculateCodeQualityScore(groups);\n if (qualityScore < 60) {\n recommendations.push(\n `📈 Code quality: Score is ${qualityScore}/100 - focus on critical and serious issues first`\n );\n }\n\n return recommendations.slice(0, 5); // Max 5 recommendations\n }\n\n /**\n * Calculate overall risk score\n */\n private calculateOverallRisk(groups: IssueGroup[]): number {\n if (groups.length === 0) return 0;\n\n // Weight by group size and severity\n let totalWeightedRisk = 0;\n let totalWeight = 0;\n\n for (const group of groups) {\n const weight = group.count;\n totalWeightedRisk += group.riskScore * weight;\n totalWeight += weight;\n }\n\n return totalWeight > 0 ? Math.round(totalWeightedRisk / totalWeight) : 0;\n }\n\n /**\n * Calculate code quality score (0-100)\n */\n private calculateCodeQualityScore(groups: IssueGroup[]): number {\n let score = 100;\n\n for (const group of groups) {\n const penalty = this.calculateGroupPenalty(group);\n score -= penalty;\n }\n\n return Math.max(0, Math.round(score));\n }\n\n /**\n * Calculate quality penalty for a group\n */\n private calculateGroupPenalty(group: IssueGroup): number {\n const severityPenalties = { critical: 10, serious: 5, moderate: 2, low: 1 };\n const basePenalty = severityPenalties[group.severity];\n\n // Increase penalty for widespread issues\n const countMultiplier = Math.min(3, Math.log10(group.count + 1));\n\n return basePenalty * countMultiplier;\n }\n\n /**\n * Generate group ID\n */\n private generateGroupId(pattern: string): string {\n const hash = pattern.split('').reduce((acc, char) => {\n return ((acc << 5) - acc + char.charCodeAt(0)) & 0xffffffff;\n }, 0);\n return Math.abs(hash).toString(36);\n }\n\n /**\n * Generate human-readable group description\n */\n private generateGroupDescription(pattern: string, issues: Issue[]): string {\n // Extract key information from pattern\n const agentMatch = pattern.match(/\\[([^\\]]+)\\]/);\n const agent = agentMatch ? agentMatch[1] : 'unknown';\n\n // Get the most common issue text\n const issueTexts = issues.map(i => i.issue.slice(0, 100));\n const commonText = this.findMostCommonSubstring(issueTexts);\n\n return commonText || `${agent} issues (${issues.length} instances)`;\n }\n\n /**\n * Find most common substring across issue texts\n */\n private findMostCommonSubstring(texts: string[]): string {\n if (texts.length === 0) return '';\n if (texts.length === 1) return texts[0];\n\n // Find longest common prefix\n let common = texts[0];\n for (let i = 1; i < texts.length; i++) {\n let j = 0;\n while (j < common.length && j < texts[i].length &&\n common[j].toLowerCase() === texts[i][j].toLowerCase()) {\n j++;\n }\n common = common.slice(0, j);\n }\n\n // Clean up the common part\n return common.trim().replace(/\\s+/g, ' ') || texts[0].slice(0, 50);\n }\n}","import { stdin as input, stdout as output } from 'process';\nimport * as readline from 'readline';\nimport type { Issue } from '../types/index.js';\nimport type { StreamUpdate, ScanProgress } from '../utils/streaming.js';\nimport { createProgressBar } from '../utils/streaming.js';\n\ninterface DashboardState {\n issues: Issue[];\n progress: ScanProgress;\n filter: {\n severity: 'all' | 'critical' | 'serious' | 'moderate' | 'low';\n agent: string | 'all';\n search: string;\n };\n view: 'overview' | 'issues' | 'agents' | 'files';\n selectedIssue: number;\n lastUpdate: number;\n}\n\n/**\n * Interactive CLI Dashboard for Trie scans\n *\n * Features:\n * - Real-time progress bars\n * - Interactive issue browser\n * - Filter and search capabilities\n * - Quick-fix previews\n * - Keyboard navigation\n */\nexport class InteractiveDashboard {\n private rl: readline.Interface;\n private state: DashboardState;\n private isActive: boolean = false;\n private updateInterval?: NodeJS.Timeout;\n\n constructor() {\n this.rl = readline.createInterface({ input, output });\n this.state = {\n issues: [],\n progress: {\n totalFiles: 0,\n processedFiles: 0,\n activeAgents: [],\n completedAgents: [],\n totalIssues: 0,\n issuesBySeverity: { critical: 0, serious: 0, moderate: 0, low: 0 }\n },\n filter: {\n severity: 'all',\n agent: 'all',\n search: ''\n },\n view: 'overview',\n selectedIssue: 0,\n lastUpdate: Date.now()\n };\n }\n\n /**\n * Start the interactive dashboard\n */\n async start(): Promise<void> {\n this.isActive = true;\n this.setupKeyboardHandlers();\n this.startUpdateLoop();\n this.render();\n }\n\n /**\n * Stop the dashboard\n */\n stop(): void {\n this.isActive = false;\n if (this.updateInterval) {\n clearInterval(this.updateInterval);\n }\n this.rl.close();\n }\n\n /**\n * Process streaming updates\n */\n handleStreamUpdate(update: StreamUpdate): void {\n this.state.lastUpdate = Date.now();\n\n switch (update.type) {\n case 'progress':\n this.state.progress = update.data;\n break;\n\n case 'issue_found':\n this.state.issues.push(update.data);\n break;\n\n case 'scan_complete':\n this.state.progress = {\n ...this.state.progress,\n processedFiles: this.state.progress.totalFiles\n };\n break;\n }\n\n if (this.isActive) {\n this.render();\n }\n }\n\n /**\n * Set up keyboard event handlers\n */\n private setupKeyboardHandlers(): void {\n readline.emitKeypressEvents(input);\n if (input.isTTY) {\n input.setRawMode(true);\n }\n\n input.on('keypress', (_chunk, key) => {\n if (!key || !this.isActive) return;\n\n switch (key.name) {\n case 'q':\n case 'escape':\n this.stop();\n process.exit(0);\n break;\n\n case 'tab':\n this.switchView();\n break;\n\n case 'up':\n this.navigateUp();\n break;\n\n case 'down':\n this.navigateDown();\n break;\n\n case 'enter':\n case 'return':\n this.selectCurrent();\n break;\n\n case '1':\n this.setFilter('severity', 'critical');\n break;\n\n case '2':\n this.setFilter('severity', 'serious');\n break;\n\n case '3':\n this.setFilter('severity', 'moderate');\n break;\n\n case '4':\n this.setFilter('severity', 'low');\n break;\n\n case '0':\n this.setFilter('severity', 'all');\n break;\n\n case 'c':\n this.clearFilters();\n break;\n\n case 'f':\n this.promptFilter();\n break;\n\n case 'h':\n case '?':\n this.showHelp();\n break;\n }\n\n this.render();\n });\n }\n\n /**\n * Start the update loop for real-time rendering\n */\n private startUpdateLoop(): void {\n this.updateInterval = setInterval(() => {\n if (this.isActive && Date.now() - this.state.lastUpdate < 5000) {\n this.render();\n }\n }, 100); // 10 FPS\n }\n\n /**\n * Main render function\n */\n private render(): void {\n // Clear screen\n process.stdout.write('\\x1b[2J\\x1b[H');\n\n // Header\n this.renderHeader();\n\n // Content based on current view\n switch (this.state.view) {\n case 'overview':\n this.renderOverview();\n break;\n case 'issues':\n this.renderIssuesList();\n break;\n case 'agents':\n this.renderAgentsView();\n break;\n case 'files':\n this.renderFilesView();\n break;\n }\n\n // Footer\n this.renderFooter();\n }\n\n /**\n * Render header with progress and title\n */\n private renderHeader(): void {\n const title = '🔍 Trie Interactive Dashboard';\n const timestamp = new Date().toLocaleTimeString();\n\n console.log('╭─' + '─'.repeat(78) + '─╮');\n console.log(`│ ${title.padEnd(40)} ${timestamp.padStart(38)} │`);\n console.log('├─' + '─'.repeat(78) + '─┤');\n\n // Progress bar\n const { processedFiles, totalFiles, activeAgents } = this.state.progress;\n const progressPercent = totalFiles > 0 ? Math.round((processedFiles / totalFiles) * 100) : 0;\n const progressBar = createProgressBar(processedFiles, totalFiles, 30);\n const activeText = activeAgents.length > 0 ? `Active: ${activeAgents.join(', ')}` : 'Scanning...';\n\n console.log(`│ Progress: ${progressBar} ${progressPercent}%`.padEnd(79) + ' │');\n console.log(`│ ${activeText}`.padEnd(79) + ' │');\n console.log('├─' + '─'.repeat(78) + '─┤');\n }\n\n /**\n * Render overview with summary statistics\n */\n private renderOverview(): void {\n const { issuesBySeverity, totalIssues } = this.state.progress;\n const { completedAgents } = this.state.progress;\n\n console.log('│ SCAN SUMMARY'.padEnd(79) + ' │');\n console.log('├─' + '─'.repeat(78) + '─┤');\n\n // Issue summary\n console.log(`│ 🔴 Critical: ${issuesBySeverity.critical.toString().padStart(8)} 🟠 Serious: ${issuesBySeverity.serious.toString().padStart(8)}`.padEnd(79) + ' │');\n console.log(`│ 🟡 Moderate: ${issuesBySeverity.moderate.toString().padStart(8)} 🔵 Low: ${issuesBySeverity.low.toString().padStart(12)}`.padEnd(79) + ' │');\n console.log(`│ Total Issues: ${totalIssues.toString().padStart(8)}`.padEnd(79) + ' │');\n console.log('├─' + '─'.repeat(78) + '─┤');\n\n // Agent status\n console.log('│ AGENT STATUS'.padEnd(79) + ' │');\n console.log('├─' + '─'.repeat(78) + '─┤');\n\n for (const agent of completedAgents.slice(0, 8)) {\n const agentIssues = this.state.issues.filter(i => i.agent === agent);\n const statusIcon = agentIssues.length > 0 ? '⚠️' : '✅';\n console.log(`│ ${statusIcon} ${agent.padEnd(20)} ${agentIssues.length.toString().padStart(4)} issues`.padEnd(79) + ' │');\n }\n\n // Recent critical issues\n const criticalIssues = this.state.issues\n .filter(i => i.severity === 'critical')\n .slice(0, 5);\n\n if (criticalIssues.length > 0) {\n console.log('├─' + '─'.repeat(78) + '─┤');\n console.log('│ 🚨 CRITICAL ISSUES'.padEnd(79) + ' │');\n console.log('├─' + '─'.repeat(78) + '─┤');\n\n for (const issue of criticalIssues) {\n const filename = issue.file.split('/').pop() || issue.file;\n const line = issue.line ? `:${issue.line}` : '';\n const location = `${filename}${line}`;\n const description = issue.issue.slice(0, 45) + (issue.issue.length > 45 ? '...' : '');\n console.log(`│ ${location.padEnd(25)} ${description}`.slice(0, 79).padEnd(79) + ' │');\n }\n }\n }\n\n /**\n * Render filtered issues list\n */\n private renderIssuesList(): void {\n const filteredIssues = this.getFilteredIssues();\n const { selectedIssue } = this.state;\n\n console.log('│ ISSUES LIST'.padEnd(79) + ' │');\n console.log('├─' + '─'.repeat(78) + '─┤');\n\n // Filter status\n const filterText = this.getFilterDescription();\n console.log(`│ Filter: ${filterText}`.padEnd(79) + ' │');\n console.log('├─' + '─'.repeat(78) + '─┤');\n\n // Issues list (paginated)\n const pageSize = 15;\n const startIndex = Math.floor(selectedIssue / pageSize) * pageSize;\n const pageIssues = filteredIssues.slice(startIndex, startIndex + pageSize);\n\n for (let i = 0; i < pageIssues.length; i++) {\n const issue = pageIssues[i]!;\n const globalIndex = startIndex + i;\n const isSelected = globalIndex === selectedIssue;\n const cursor = isSelected ? '▶ ' : ' ';\n const severityIcon = this.getSeverityIcon(issue.severity);\n const filename = issue.file.split('/').pop() || issue.file;\n const location = `${filename}:${issue.line || '?'}`;\n const description = issue.issue.slice(0, 40) + (issue.issue.length > 40 ? '...' : '');\n\n const line = `${cursor}${severityIcon} ${location.padEnd(20)} ${description}`;\n console.log(`│ ${line}`.slice(0, 79).padEnd(79) + ' │');\n }\n\n // Selected issue details\n if (filteredIssues[selectedIssue]) {\n const selected = filteredIssues[selectedIssue];\n console.log('├─' + '─'.repeat(78) + '─┤');\n console.log('│ ISSUE DETAILS'.padEnd(79) + ' │');\n console.log('├─' + '─'.repeat(78) + '─┤');\n console.log(`│ File: ${selected.file}`.slice(0, 79).padEnd(79) + ' │');\n console.log(`│ Line: ${selected.line || 'Unknown'}`.padEnd(79) + ' │');\n console.log(`│ Agent: ${selected.agent}`.padEnd(79) + ' │');\n\n // Wrap issue description\n const issueLines = this.wrapText(selected.issue, 75);\n console.log(`│ Issue:`.padEnd(79) + ' │');\n for (const line of issueLines.slice(0, 3)) {\n console.log(`│ ${line}`.padEnd(79) + ' │');\n }\n\n // Wrap fix description\n const fixLines = this.wrapText(selected.fix, 75);\n console.log(`│ Fix:`.padEnd(79) + ' │');\n for (const line of fixLines.slice(0, 3)) {\n console.log(`│ ${line}`.padEnd(79) + ' │');\n }\n }\n }\n\n /**\n * Render agents view\n */\n private renderAgentsView(): void {\n const { completedAgents, activeAgents } = this.state.progress;\n\n console.log('│ AGENTS STATUS'.padEnd(79) + ' │');\n console.log('├─' + '─'.repeat(78) + '─┤');\n\n // Active agents\n if (activeAgents.length > 0) {\n console.log('│ 🔄 ACTIVE AGENTS'.padEnd(79) + ' │');\n for (const agent of activeAgents) {\n console.log(`│ • ${agent}`.padEnd(79) + ' │');\n }\n console.log('├─' + '─'.repeat(78) + '─┤');\n }\n\n // Completed agents\n console.log('│ ✅ COMPLETED AGENTS'.padEnd(79) + ' │');\n for (const agent of completedAgents) {\n const agentIssues = this.state.issues.filter(i => i.agent === agent);\n const criticalCount = agentIssues.filter(i => i.severity === 'critical').length;\n const statusText = criticalCount > 0 ? `${criticalCount} critical` : `${agentIssues.length} issues`;\n console.log(`│ • ${agent.padEnd(25)} ${statusText}`.padEnd(79) + ' │');\n }\n }\n\n /**\n * Render files view\n */\n private renderFilesView(): void {\n // Group issues by file\n const fileIssues = new Map<string, Issue[]>();\n for (const issue of this.state.issues) {\n if (!fileIssues.has(issue.file)) {\n fileIssues.set(issue.file, []);\n }\n fileIssues.get(issue.file)!.push(issue);\n }\n\n // Sort by issue count\n const sortedFiles = Array.from(fileIssues.entries())\n .sort((a, b) => b[1].length - a[1].length)\n .slice(0, 20);\n\n console.log('│ FILES WITH ISSUES'.padEnd(79) + ' │');\n console.log('├─' + '─'.repeat(78) + '─┤');\n\n for (const [file, issues] of sortedFiles) {\n const filename = file.split('/').pop() || file;\n const criticalCount = issues.filter(i => i.severity === 'critical').length;\n const totalCount = issues.length;\n const criticalText = criticalCount > 0 ? ` (${criticalCount} critical)` : '';\n console.log(`│ ${filename.padEnd(35)} ${totalCount} issues${criticalText}`.slice(0, 79).padEnd(79) + ' │');\n }\n }\n\n /**\n * Render footer with controls\n */\n private renderFooter(): void {\n console.log('├─' + '─'.repeat(78) + '─┤');\n console.log('│ CONTROLS:'.padEnd(79) + ' │');\n console.log('│ Tab: Switch view ↑↓: Navigate Enter: Select 1-4: Filter severity │');\n console.log('│ f: Search filter c: Clear filters h: Help q: Quit'.padEnd(79) + ' │');\n console.log('╰─' + '─'.repeat(78) + '─╯');\n }\n\n // Helper methods\n private switchView(): void {\n const views: DashboardState['view'][] = ['overview', 'issues', 'agents', 'files'];\n const currentIndex = views.indexOf(this.state.view);\n const nextIndex = (currentIndex + 1) % views.length;\n this.state.view = views[nextIndex] ?? 'overview';\n }\n\n private navigateUp(): void {\n if (this.state.view === 'issues') {\n this.state.selectedIssue = Math.max(0, this.state.selectedIssue - 1);\n }\n }\n\n private navigateDown(): void {\n if (this.state.view === 'issues') {\n const filteredIssues = this.getFilteredIssues();\n this.state.selectedIssue = Math.min(filteredIssues.length - 1, this.state.selectedIssue + 1);\n }\n }\n\n private selectCurrent(): void {\n if (this.state.view === 'issues') {\n const filteredIssues = this.getFilteredIssues();\n const selected = filteredIssues[this.state.selectedIssue];\n if (selected) {\n this.showIssueDetails(selected);\n }\n }\n }\n\n private setFilter(type: string, value: string): void {\n (this.state.filter as any)[type] = value;\n this.state.selectedIssue = 0; // Reset selection\n }\n\n private clearFilters(): void {\n this.state.filter = {\n severity: 'all',\n agent: 'all',\n search: ''\n };\n this.state.selectedIssue = 0;\n }\n\n private getFilteredIssues(): Issue[] {\n return this.state.issues.filter(issue => {\n if (this.state.filter.severity !== 'all' && issue.severity !== this.state.filter.severity) {\n return false;\n }\n if (this.state.filter.agent !== 'all' && issue.agent !== this.state.filter.agent) {\n return false;\n }\n if (this.state.filter.search && !issue.issue.toLowerCase().includes(this.state.filter.search.toLowerCase())) {\n return false;\n }\n return true;\n });\n }\n\n private getFilterDescription(): string {\n const parts = [];\n if (this.state.filter.severity !== 'all') parts.push(`Severity: ${this.state.filter.severity}`);\n if (this.state.filter.agent !== 'all') parts.push(`Agent: ${this.state.filter.agent}`);\n if (this.state.filter.search) parts.push(`Search: \"${this.state.filter.search}\"`);\n return parts.length > 0 ? parts.join(', ') : 'None';\n }\n\n private getSeverityIcon(severity: Issue['severity']): string {\n return { critical: '🔴', serious: '🟠', moderate: '🟡', low: '🔵' }[severity];\n }\n\n private wrapText(text: string, width: number): string[] {\n const words = text.split(' ');\n const lines: string[] = [];\n let currentLine = '';\n\n for (const word of words) {\n if (currentLine.length + word.length + 1 <= width) {\n currentLine += (currentLine ? ' ' : '') + word;\n } else {\n if (currentLine) lines.push(currentLine);\n currentLine = word;\n }\n }\n\n if (currentLine) lines.push(currentLine);\n return lines;\n }\n\n private async promptFilter(): Promise<void> {\n if (input.isTTY) {\n input.setRawMode(false);\n }\n\n this.rl.question('Search filter (leave empty to clear): ', (answer) => {\n this.state.filter.search = answer.trim();\n this.state.selectedIssue = 0;\n if (input.isTTY) {\n input.setRawMode(true);\n }\n this.render();\n });\n }\n\n private showHelp(): void {\n this.isActive = false;\n process.stdout.write('\\x1b[2J\\x1b[H');\n console.log('╭─ Trie Interactive Dashboard Help ──────────────────────────────╮');\n console.log('│ Navigation │');\n console.log('│ Tab Switch view (overview/issues/agents/files) │');\n console.log('│ ↑ / ↓ Navigate issues list │');\n console.log('│ Enter View issue details │');\n console.log('│ Filters │');\n console.log('│ 1-4 Filter by severity (critical→low) │');\n console.log('│ 0 Clear severity filter │');\n console.log('│ f Search filter │');\n console.log('│ c Clear all filters │');\n console.log('│ Other │');\n console.log('│ h or ? Show this help │');\n console.log('│ q Quit │');\n console.log('╰───────────────────────────────────────────────────────────────╯');\n console.log('Press any key to return...');\n\n const resume = () => {\n this.isActive = true;\n this.render();\n };\n input.once('keypress', resume);\n }\n\n private showIssueDetails(issue: Issue): void {\n this.isActive = false;\n process.stdout.write('\\x1b[2J\\x1b[H');\n console.log('╭─ Issue Details ────────────────────────────────────────────────╮');\n console.log(`│ File: ${issue.file}`.slice(0, 63).padEnd(63) + '│');\n console.log(`│ Line: ${issue.line || 'Unknown'} Agent: ${issue.agent}`.slice(0, 63).padEnd(63) + '│');\n console.log('├───────────────────────────────────────────────────────────────┤');\n console.log('│ Issue │');\n const issueLines = this.wrapText(issue.issue, 61);\n for (const line of issueLines.slice(0, 6)) {\n console.log(`│ ${line}`.padEnd(63) + '│');\n }\n console.log('├───────────────────────────────────────────────────────────────┤');\n console.log('│ Fix │');\n const fixLines = this.wrapText(issue.fix, 61);\n for (const line of fixLines.slice(0, 6)) {\n console.log(`│ ${line}`.padEnd(63) + '│');\n }\n console.log('╰───────────────────────────────────────────────────────────────╯');\n console.log('Press any key to return...');\n\n const resume = () => {\n this.isActive = true;\n this.render();\n };\n input.once('keypress', resume);\n }\n}","import { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { ConfigValidator, DEFAULT_CONFIG, type TrieConfig } from './validation.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport async function loadConfig(): Promise<TrieConfig> {\n const validator = new ConfigValidator();\n const configPath = join(getWorkingDirectory(undefined, true), '.trie', 'config.json');\n\n try {\n // Look for config in .trie/config.json\n if (!existsSync(configPath)) {\n return DEFAULT_CONFIG;\n }\n\n const configFile = await readFile(configPath, 'utf-8');\n const userConfig = JSON.parse(configFile) as Record<string, unknown>;\n\n // Deep merge with defaults\n const merged = mergeConfig(DEFAULT_CONFIG, userConfig);\n\n // Validate merged config\n const result = validator.validateConfig(merged);\n if (!result.success) {\n console.error('Configuration validation failed:');\n for (const error of result.errors) {\n console.error(` - ${error}`);\n }\n return DEFAULT_CONFIG;\n }\n\n // Environment validation warnings\n const envValidation = validator.validateEnvironment();\n for (const warning of envValidation.warnings) {\n console.warn(warning);\n }\n for (const error of envValidation.errors) {\n console.error(error);\n }\n\n return result.data;\n } catch (error) {\n // If no config found, return defaults\n console.error('Failed to load config, using defaults:', error);\n return DEFAULT_CONFIG;\n }\n}\n\nfunction mergeConfig<T extends Record<string, unknown>>(defaults: T, user: Record<string, unknown>): T {\n if (typeof user !== 'object' || user === null || Array.isArray(user)) {\n return { ...defaults };\n }\n\n const result = { ...defaults } as T;\n\n for (const [key, value] of Object.entries(user)) {\n const defaultValue = defaults[key as keyof T];\n if (typeof value === 'object' && value !== null && !Array.isArray(value) && typeof defaultValue === 'object' && defaultValue !== null) {\n result[key as keyof T] = mergeConfig(defaultValue as Record<string, unknown>, value as Record<string, unknown>) as T[keyof T];\n } else {\n result[key as keyof T] = value as T[keyof T];\n }\n }\n\n return result;\n}","import { z } from 'zod';\nimport { existsSync, readFileSync } from 'fs';\nimport { resolve, join } from 'path';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\n// API key validation patterns\nconst API_KEY_PATTERNS = {\n anthropic: /^sk-ant-api\\d{2}-[\\w-]{95}$/,\n openai: /^sk-[\\w]{48}$/,\n github: /^ghp_[\\w]{36}$/,\n vercel: /^[\\w]{24}$/,\n} as const;\n\n// Configuration schemas\nconst ApiKeysSchema = z.object({\n anthropic: z.string().regex(API_KEY_PATTERNS.anthropic, 'Invalid Anthropic API key format').optional(),\n openai: z.string().regex(API_KEY_PATTERNS.openai, 'Invalid OpenAI API key format').optional(),\n github: z.string().regex(API_KEY_PATTERNS.github, 'Invalid GitHub token format').optional(),\n vercel: z.string().regex(API_KEY_PATTERNS.vercel, 'Invalid Vercel token format').optional(),\n});\n\nconst AgentConfigSchema = z.object({\n enabled: z.array(z.string()).optional().default([]),\n disabled: z.array(z.string()).optional().default([]),\n parallel: z.boolean().optional().default(true),\n maxConcurrency: z.number().int().min(1).max(20).optional().default(4),\n timeout: z.number().int().min(1000).max(300000).optional().default(120000), // 2 minutes\n cache: z.boolean().optional().default(true),\n});\n\nconst ComplianceSchema = z.object({\n standards: z.array(z.enum(['SOC2', 'GDPR', 'HIPAA', 'CCPA', 'PCI-DSS'])).optional().default(['SOC2']),\n enforceCompliance: z.boolean().optional().default(false),\n reportFormat: z.enum(['json', 'sarif', 'csv', 'html']).optional().default('json'),\n});\n\nconst OutputSchema = z.object({\n format: z.enum(['console', 'json', 'sarif', 'junit']).optional().default('console'),\n level: z.enum(['critical', 'serious', 'moderate', 'low', 'all']).optional().default('all'),\n interactive: z.boolean().optional().default(false),\n streaming: z.boolean().optional().default(true),\n colors: z.boolean().optional().default(true),\n});\n\nconst PathsSchema = z.object({\n include: z.array(z.string()).optional().default([]),\n exclude: z.array(z.string()).optional().default(['node_modules', 'dist', 'build', '.git']),\n configDir: z.string().optional().default('.trie'),\n outputDir: z.string().optional().default('trie-reports'),\n});\n\nconst IntegrationsSchema = z.object({\n github: z.object({\n enabled: z.boolean().optional().default(false),\n token: z.string().optional(),\n webhook: z.string().url().optional(),\n }).optional(),\n slack: z.object({\n enabled: z.boolean().optional().default(false),\n webhook: z.string().url().optional(),\n channel: z.string().optional(),\n }).optional(),\n jira: z.object({\n enabled: z.boolean().optional().default(false),\n url: z.string().url().optional(),\n token: z.string().optional(),\n project: z.string().optional(),\n }).optional(),\n});\n\nexport const TrieConfigSchema = z.object({\n version: z.string().optional().default('1.0.0'),\n apiKeys: ApiKeysSchema.optional(),\n agents: AgentConfigSchema.optional(),\n compliance: ComplianceSchema.optional(),\n output: OutputSchema.optional(),\n paths: PathsSchema.optional(),\n integrations: IntegrationsSchema.optional(),\n});\n\nexport type TrieConfig = z.infer<typeof TrieConfigSchema>;\nexport type ApiKeys = z.infer<typeof ApiKeysSchema>;\nexport type AgentConfig = z.infer<typeof AgentConfigSchema>;\n\n/**\n * Configuration validator with detailed error reporting\n */\nexport class ConfigValidator {\n /**\n * Validate configuration object\n */\n validateConfig(config: unknown): { success: true; data: TrieConfig } | { success: false; errors: string[] } {\n try {\n const validated = TrieConfigSchema.parse(config);\n\n // Additional business logic validation\n const businessErrors = this.validateBusinessLogic(validated);\n if (businessErrors.length > 0) {\n return { success: false, errors: businessErrors };\n }\n\n return { success: true, data: validated };\n } catch (error) {\n if (error instanceof z.ZodError) {\n const errors = error.errors.map(err =>\n `${err.path.join('.')}: ${err.message}`\n );\n return { success: false, errors };\n }\n\n return {\n success: false,\n errors: [`Configuration validation failed: ${error instanceof Error ? error.message : 'Unknown error'}`]\n };\n }\n }\n\n /**\n * Validate environment variables for API keys\n */\n validateEnvironment(): { valid: boolean; warnings: string[]; errors: string[] } {\n const warnings: string[] = [];\n const errors: string[] = [];\n\n // Check for potentially exposed secrets\n const exposedPatterns = [\n 'NEXT_PUBLIC_ANTHROPIC',\n 'REACT_APP_ANTHROPIC',\n 'VITE_ANTHROPIC',\n 'PUBLIC_ANTHROPIC'\n ];\n\n for (const pattern of exposedPatterns) {\n const envVars = Object.keys(process.env).filter(key => key.includes(pattern));\n for (const envVar of envVars) {\n errors.push(`🚨 Security risk: API key in client-side environment variable: ${envVar}`);\n }\n }\n\n // Check API key format if present (check env var first, then config)\n let anthropicKey = process.env.ANTHROPIC_API_KEY;\n \n // Also check config file if available (for validation purposes)\n // Note: This is a read-only check for validation, actual usage goes through isAIAvailable()\n if (!anthropicKey) {\n try {\n const configPath = join(getWorkingDirectory(undefined, true), '.trie', 'config.json');\n if (existsSync(configPath)) {\n const config = JSON.parse(readFileSync(configPath, 'utf-8'));\n anthropicKey = config.apiKeys?.anthropic;\n }\n } catch {\n // Config file check failed, continue with env var only\n }\n }\n \n if (anthropicKey && !API_KEY_PATTERNS.anthropic.test(anthropicKey)) {\n errors.push('ANTHROPIC_API_KEY does not match expected format');\n }\n\n // Warnings for missing optional keys\n if (!anthropicKey) {\n warnings.push('ANTHROPIC_API_KEY not set - AI features will be disabled. Set in environment, .trie/config.json, or .env file');\n }\n\n if (!process.env.GITHUB_TOKEN && process.env.CI) {\n warnings.push('GITHUB_TOKEN not set - GitHub integration disabled');\n }\n\n return {\n valid: errors.length === 0,\n warnings,\n errors\n };\n }\n\n /**\n * Validate file paths in configuration\n */\n validatePaths(paths: z.infer<typeof PathsSchema>): { valid: boolean; errors: string[] } {\n const errors: string[] = [];\n\n if (paths?.include) {\n for (const path of paths.include) {\n const resolvedPath = resolve(path);\n if (!existsSync(resolvedPath)) {\n errors.push(`Include path does not exist: ${path}`);\n }\n }\n }\n\n if (paths?.configDir) {\n const configPath = resolve(paths.configDir);\n if (!existsSync(configPath)) {\n try {\n // Try to create the directory\n require('fs').mkdirSync(configPath, { recursive: true });\n } catch {\n errors.push(`Cannot create config directory: ${paths.configDir}`);\n }\n }\n }\n\n return {\n valid: errors.length === 0,\n errors\n };\n }\n\n /**\n * Validate integration configurations\n */\n validateIntegrations(integrations: z.infer<typeof IntegrationsSchema>): { valid: boolean; errors: string[] } {\n const errors: string[] = [];\n\n // GitHub integration\n if (integrations?.github?.enabled) {\n if (!integrations.github.token) {\n errors.push('GitHub integration enabled but no token provided');\n }\n }\n\n // Slack integration\n if (integrations?.slack?.enabled) {\n if (!integrations.slack.webhook) {\n errors.push('Slack integration enabled but no webhook URL provided');\n }\n }\n\n // JIRA integration\n if (integrations?.jira?.enabled) {\n if (!integrations.jira.url || !integrations.jira.token || !integrations.jira.project) {\n errors.push('JIRA integration enabled but missing required fields (url, token, project)');\n }\n }\n\n return {\n valid: errors.length === 0,\n errors\n };\n }\n\n /**\n * Business logic validation\n */\n private validateBusinessLogic(config: TrieConfig): string[] {\n const errors: string[] = [];\n\n // Agent configuration validation\n if (config.agents?.enabled && config.agents?.disabled) {\n const overlap = config.agents.enabled.filter(agent =>\n config.agents?.disabled?.includes(agent)\n );\n if (overlap.length > 0) {\n errors.push(`Agents cannot be both enabled and disabled: ${overlap.join(', ')}`);\n }\n }\n\n // Concurrency validation\n if (config.agents?.maxConcurrency && config.agents.maxConcurrency > 10) {\n errors.push('maxConcurrency should not exceed 10 for optimal performance');\n }\n\n // Compliance standards validation\n if (config.compliance?.standards) {\n const invalidStandards = config.compliance.standards.filter(standard =>\n !['SOC2', 'GDPR', 'HIPAA', 'CCPA', 'PCI-DSS'].includes(standard)\n );\n if (invalidStandards.length > 0) {\n errors.push(`Invalid compliance standards: ${invalidStandards.join(', ')}`);\n }\n }\n\n // Path validation\n if (config.paths) {\n const pathValidation = this.validatePaths(config.paths);\n errors.push(...pathValidation.errors);\n }\n\n // Integration validation\n if (config.integrations) {\n const integrationValidation = this.validateIntegrations(config.integrations);\n errors.push(...integrationValidation.errors);\n }\n\n return errors;\n }\n\n /**\n * Generate configuration template\n */\n generateTemplate(): TrieConfig {\n return {\n version: '1.0.0',\n agents: {\n enabled: ['security', 'bugs', 'types'],\n disabled: [],\n parallel: true,\n maxConcurrency: 4,\n timeout: 120000,\n cache: true\n },\n compliance: {\n standards: ['SOC2'],\n enforceCompliance: false,\n reportFormat: 'json'\n },\n output: {\n format: 'console',\n level: 'all',\n interactive: false,\n streaming: true,\n colors: true\n },\n paths: {\n include: [],\n exclude: ['node_modules', 'dist', 'build', '.git'],\n configDir: '.trie',\n outputDir: 'trie-reports'\n }\n };\n }\n\n /**\n * Validate and provide suggestions for improvement\n */\n analyze(config: TrieConfig): {\n score: number;\n suggestions: string[];\n securityIssues: string[];\n optimizations: string[];\n } {\n const suggestions: string[] = [];\n const securityIssues: string[] = [];\n const optimizations: string[] = [];\n let score = 100;\n\n // Check for AI enhancement (check config, env var, and .env files)\n let hasApiKey = Boolean(config.apiKeys?.anthropic || process.env.ANTHROPIC_API_KEY);\n if (!hasApiKey) {\n // Check .env files as well\n try {\n const workDir = getWorkingDirectory(undefined, true);\n const envFiles = ['.env', '.env.local', '.env.production'];\n for (const envFile of envFiles) {\n const envPath = join(workDir, envFile);\n if (existsSync(envPath)) {\n const envContent = readFileSync(envPath, 'utf-8');\n if (envContent.includes('ANTHROPIC_API_KEY=')) {\n hasApiKey = true;\n break;\n }\n }\n }\n } catch {\n // .env check failed, continue\n }\n }\n \n if (!hasApiKey) {\n suggestions.push('Add ANTHROPIC_API_KEY to enable AI-powered analysis for better issue detection. Set in environment, .trie/config.json, or .env file');\n score -= 10;\n }\n\n // Check parallel execution\n if (config.agents?.parallel === false) {\n optimizations.push('Enable parallel agent execution for 3-5x faster scans');\n score -= 15;\n }\n\n // Check caching\n if (config.agents?.cache === false) {\n optimizations.push('Enable result caching to speed up repeated scans');\n score -= 10;\n }\n\n // Check compliance standards\n if (!config.compliance?.standards || config.compliance.standards.length === 0) {\n suggestions.push('Configure compliance standards (SOC2, GDPR, etc.) for regulatory requirements');\n score -= 5;\n }\n\n // Check integrations for team collaboration\n const hasIntegrations = config.integrations && (\n config.integrations.github?.enabled ||\n config.integrations.slack?.enabled ||\n config.integrations.jira?.enabled\n );\n if (!hasIntegrations) {\n suggestions.push('Consider enabling GitHub/Slack/JIRA integrations for better team collaboration');\n score -= 5;\n }\n\n // Security checks\n if (config.apiKeys) {\n securityIssues.push('API keys in config file - consider using environment variables instead');\n score -= 20;\n }\n\n return {\n score: Math.max(0, score),\n suggestions,\n securityIssues,\n optimizations\n };\n }\n}\n\n/**\n * Default configuration with security best practices\n */\nexport const DEFAULT_CONFIG: TrieConfig = {\n version: '1.0.0',\n agents: {\n enabled: [],\n disabled: [],\n parallel: true,\n maxConcurrency: 4,\n timeout: 120000,\n cache: true,\n },\n compliance: {\n standards: ['SOC2'],\n enforceCompliance: false,\n reportFormat: 'json',\n },\n output: {\n format: 'console',\n level: 'all',\n interactive: false,\n streaming: true,\n colors: true,\n },\n paths: {\n include: [],\n exclude: ['node_modules', 'dist', 'build', '.git', '.next', '.nuxt', 'coverage'],\n configDir: '.trie',\n outputDir: 'trie-reports',\n },\n};\n\n/**\n * Validate startup configuration\n */\nexport function validateStartupConfig(): {\n valid: boolean;\n config: TrieConfig;\n warnings: string[];\n errors: string[];\n} {\n const validator = new ConfigValidator();\n\n // Validate environment\n const envValidation = validator.validateEnvironment();\n\n // Use default config as base\n const configResult = validator.validateConfig(DEFAULT_CONFIG);\n\n if (!configResult.success) {\n return {\n valid: false,\n config: DEFAULT_CONFIG,\n warnings: envValidation.warnings,\n errors: [...envValidation.errors, ...configResult.errors]\n };\n }\n\n return {\n valid: envValidation.valid,\n config: configResult.data,\n warnings: envValidation.warnings,\n errors: envValidation.errors\n };\n}","import type { Issue } from '../types/index.js';\nimport type { IssueGroup, PriorityReport } from '../utils/issue-analyzer.js';\nimport type { TeamNotification } from './team-collaboration.js';\n\ninterface SlackConfig {\n webhookUrl: string;\n channel?: string | undefined;\n username?: string | undefined;\n iconEmoji?: string | undefined;\n}\n\ninterface SlackMessage {\n text?: string;\n blocks?: SlackBlock[];\n attachments?: SlackAttachment[];\n channel?: string;\n username?: string;\n icon_emoji?: string;\n}\n\ninterface SlackBlock {\n type: string;\n text?: {\n type: string;\n text: string;\n };\n fields?: Array<{\n type: string;\n text: string;\n }>;\n accessory?: any;\n}\n\ninterface SlackAttachment {\n color: string;\n title?: string | undefined;\n text?: string | undefined;\n fields?: Array<{\n title: string;\n value: string;\n short?: boolean;\n }> | undefined;\n footer?: string | undefined;\n ts?: number | undefined;\n}\n\n/**\n * Slack integration for Trie team notifications\n */\nexport class SlackIntegration {\n constructor(private config: SlackConfig) {}\n\n /**\n * Send scan completion notification\n */\n async sendScanNotification(\n issues: Issue[],\n priorityReport: PriorityReport,\n repositoryName: string,\n branch: string = 'main'\n ): Promise<void> {\n const { urgent, high, medium, low } = priorityReport;\n const totalIssues = urgent.length + high.length + medium.length + low.length;\n\n const color = urgent.length > 0 ? 'danger' : high.length > 0 ? 'warning' : 'good';\n const emoji = urgent.length > 0 ? '🚨' : high.length > 0 ? '⚠️' : '✅';\n\n const message: SlackMessage = {\n blocks: [\n {\n type: 'section',\n text: {\n type: 'mrkdwn',\n text: `${emoji} *Trie Security Scan Complete*\\n*Repository:* ${repositoryName} (${branch})`\n }\n },\n {\n type: 'section',\n fields: [\n {\n type: 'mrkdwn',\n text: `*🚨 Urgent:* ${urgent.length}`\n },\n {\n type: 'mrkdwn',\n text: `*⚠️ High:* ${high.length}`\n },\n {\n type: 'mrkdwn',\n text: `*🔸 Medium:* ${medium.length}`\n },\n {\n type: 'mrkdwn',\n text: `*🔹 Low:* ${low.length}`\n }\n ]\n }\n ],\n attachments: []\n };\n\n // Add urgent issues details\n if (urgent.length > 0) {\n const urgentDetails = urgent.slice(0, 5).map(group =>\n `• ${group.description} (${group.count} instances)`\n ).join('\\n');\n\n message.attachments!.push({\n color: 'danger',\n title: '🚨 Urgent Issues - Immediate Action Required',\n text: urgentDetails,\n footer: urgent.length > 5 ? `... and ${urgent.length - 5} more urgent issues` : undefined\n });\n }\n\n // Add high priority issues\n if (high.length > 0) {\n const highDetails = high.slice(0, 3).map(group =>\n `• ${group.description} (${group.count} instances)`\n ).join('\\n');\n\n message.attachments!.push({\n color: 'warning',\n title: '⚠️ High Priority Issues',\n text: highDetails,\n footer: high.length > 3 ? `... and ${high.length - 3} more high priority issues` : undefined\n });\n }\n\n // Add recommendations\n if (priorityReport.recommendations.length > 0) {\n message.attachments!.push({\n color: 'good',\n title: '💡 Recommendations',\n text: priorityReport.recommendations.slice(0, 3).join('\\n')\n });\n }\n\n await this.sendMessage(message);\n }\n\n /**\n * Send critical issue alert\n */\n async sendCriticalAlert(issues: Issue[], repositoryName: string): Promise<void> {\n const message: SlackMessage = {\n text: `🚨 CRITICAL SECURITY ALERT: ${repositoryName}`,\n blocks: [\n {\n type: 'section',\n text: {\n type: 'mrkdwn',\n text: `🚨 *CRITICAL SECURITY ALERT*\\n*Repository:* ${repositoryName}\\n*Critical Issues:* ${issues.length}`\n }\n }\n ],\n attachments: issues.slice(0, 5).map(issue => ({\n color: 'danger',\n title: `${issue.file}:${issue.line || '?'}`,\n text: issue.issue.slice(0, 200),\n fields: [\n {\n title: 'Fix',\n value: issue.fix.slice(0, 100),\n short: false\n }\n ],\n footer: `Agent: ${issue.agent}`,\n ts: Math.floor(Date.now() / 1000)\n }))\n };\n\n if (issues.length > 5) {\n message.attachments!.push({\n color: 'danger',\n text: `... and ${issues.length - 5} more critical issues. View full report for details.`\n });\n }\n\n await this.sendMessage(message);\n }\n\n /**\n * Send team notification\n */\n async sendTeamNotification(notification: TeamNotification): Promise<void> {\n const emoji = this.getNotificationEmoji(notification.type);\n\n const message: SlackMessage = {\n blocks: [\n {\n type: 'section',\n text: {\n type: 'mrkdwn',\n text: `${emoji} *${notification.title}*\\n${notification.message}`\n }\n }\n ]\n };\n\n // Add specific data based on notification type\n if (notification.type === 'assignment' && notification.data) {\n const { assignment, issue } = notification.data;\n message.attachments = [{\n color: this.getAssignmentColor(assignment.priority),\n fields: [\n {\n title: 'Priority',\n value: assignment.priority.toUpperCase(),\n short: true\n },\n {\n title: 'Due Date',\n value: assignment.dueDate ? new Date(assignment.dueDate).toLocaleDateString() : 'Not set',\n short: true\n },\n {\n title: 'File',\n value: issue.file,\n short: false\n }\n ]\n }];\n }\n\n await this.sendMessage(message);\n }\n\n /**\n * Send daily/weekly team summary\n */\n async sendTeamSummary(\n period: 'daily' | 'weekly',\n stats: {\n newIssues: number;\n resolvedIssues: number;\n overdueIssues: number;\n topCategories: Array<{ category: string; count: number }>;\n topContributors: Array<{ name: string; resolved: number }>;\n }\n ): Promise<void> {\n const emoji = period === 'daily' ? '📅' : '📊';\n const title = `${emoji} ${period.charAt(0).toUpperCase() + period.slice(1)} Security Summary`;\n\n const message: SlackMessage = {\n blocks: [\n {\n type: 'section',\n text: {\n type: 'mrkdwn',\n text: `*${title}*`\n }\n },\n {\n type: 'section',\n fields: [\n {\n type: 'mrkdwn',\n text: `*🔍 New Issues:* ${stats.newIssues}`\n },\n {\n type: 'mrkdwn',\n text: `*✅ Resolved:* ${stats.resolvedIssues}`\n },\n {\n type: 'mrkdwn',\n text: `*⏰ Overdue:* ${stats.overdueIssues}`\n },\n {\n type: 'mrkdwn',\n text: `*📈 Net Change:* ${stats.resolvedIssues - stats.newIssues > 0 ? '+' : ''}${stats.resolvedIssues - stats.newIssues}`\n }\n ]\n }\n ],\n attachments: []\n };\n\n // Top issue categories\n if (stats.topCategories.length > 0) {\n const categoriesText = stats.topCategories\n .slice(0, 5)\n .map(cat => `• ${cat.category}: ${cat.count}`)\n .join('\\n');\n\n message.attachments!.push({\n color: 'good',\n title: '📊 Top Issue Categories',\n text: categoriesText\n });\n }\n\n // Top contributors\n if (stats.topContributors.length > 0) {\n const contributorsText = stats.topContributors\n .slice(0, 5)\n .map(contrib => `• ${contrib.name}: ${contrib.resolved} resolved`)\n .join('\\n');\n\n message.attachments!.push({\n color: 'good',\n title: '🏆 Top Contributors',\n text: contributorsText\n });\n }\n\n await this.sendMessage(message);\n }\n\n /**\n * Send bulk fix notification\n */\n async sendBulkFixNotification(\n fixedGroups: IssueGroup[],\n totalFixed: number,\n repositoryName: string\n ): Promise<void> {\n const message: SlackMessage = {\n blocks: [\n {\n type: 'section',\n text: {\n type: 'mrkdwn',\n text: `⚡ *Bulk Fix Applied*\\n*Repository:* ${repositoryName}\\n*Issues Fixed:* ${totalFixed}`\n }\n }\n ],\n attachments: [{\n color: 'good',\n title: '🔧 Fixed Issue Groups',\n text: fixedGroups.map(group =>\n `• ${group.description} (${group.count} instances)`\n ).join('\\n')\n }]\n };\n\n await this.sendMessage(message);\n }\n\n /**\n * Send escalation notification\n */\n async sendEscalationNotification(\n overdueAssignments: Array<{\n issueId: string;\n assignee: string;\n daysOverdue: number;\n priority: string;\n }>\n ): Promise<void> {\n const message: SlackMessage = {\n text: '🚨 OVERDUE ISSUE ESCALATION',\n blocks: [\n {\n type: 'section',\n text: {\n type: 'mrkdwn',\n text: `🚨 *Overdue Issue Escalation*\\n${overdueAssignments.length} issues are overdue and require attention.`\n }\n }\n ],\n attachments: overdueAssignments.map(assignment => ({\n color: 'warning',\n title: `Issue ${assignment.issueId}`,\n fields: [\n {\n title: 'Assignee',\n value: assignment.assignee,\n short: true\n },\n {\n title: 'Days Overdue',\n value: assignment.daysOverdue.toString(),\n short: true\n },\n {\n title: 'Priority',\n value: assignment.priority.toUpperCase(),\n short: true\n }\n ]\n }))\n };\n\n await this.sendMessage(message);\n }\n\n /**\n * Send message to Slack\n */\n private async sendMessage(message: SlackMessage): Promise<void> {\n const payload = {\n ...message,\n channel: this.config.channel || message.channel,\n username: this.config.username || 'Trie Security Bot',\n icon_emoji: this.config.iconEmoji || ':shield:'\n };\n\n try {\n const response = await fetch(this.config.webhookUrl, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json'\n },\n body: JSON.stringify(payload)\n });\n\n if (!response.ok) {\n throw new Error(`Slack API error: ${response.status} ${response.statusText}`);\n }\n } catch (error) {\n console.error('Failed to send Slack notification:', error);\n throw error;\n }\n }\n\n /**\n * Get emoji for notification type\n */\n private getNotificationEmoji(type: string): string {\n const emojis = {\n assignment: '📋',\n escalation: '🚨',\n completion: '✅',\n reminder: '⏰'\n };\n return emojis[type] || '📢';\n }\n\n /**\n * Get color for assignment priority\n */\n private getAssignmentColor(priority: string): string {\n const colors = {\n urgent: 'danger',\n high: 'warning',\n medium: 'good',\n low: '#36a64f'\n };\n return colors[priority] || 'good';\n }\n\n /**\n * Test Slack connection\n */\n async testConnection(): Promise<boolean> {\n try {\n await this.sendMessage({\n text: '🧪 Trie Slack Integration Test',\n blocks: [{\n type: 'section',\n text: {\n type: 'mrkdwn',\n text: '*Trie Slack Integration Test*\\nIf you see this message, the integration is working correctly! 🎉'\n }\n }]\n });\n return true;\n } catch (error) {\n console.error('Slack connection test failed:', error);\n return false;\n }\n }\n}","import type { Issue, AgentResult } from '../types/index.js';\nimport type { PriorityReport } from '../utils/issue-analyzer.js';\n\nexport interface TeamMember {\n id: string;\n name: string;\n email: string;\n role: 'developer' | 'lead' | 'security' | 'architect' | 'manager';\n expertise: string[];\n timezone: string;\n}\n\nexport interface IssueAssignment {\n issueId: string;\n assigneeId: string;\n assignedAt: number;\n dueDate?: number;\n priority: 'urgent' | 'high' | 'medium' | 'low';\n status: 'assigned' | 'in_progress' | 'under_review' | 'resolved' | 'dismissed';\n notes?: string;\n}\n\nexport interface TeamNotification {\n id: string;\n type: 'assignment' | 'escalation' | 'completion' | 'reminder';\n recipientId: string;\n title: string;\n message: string;\n data: any;\n createdAt: number;\n sentAt?: number;\n readAt?: number;\n}\n\n/**\n * Team Collaboration Manager\n *\n * Features:\n * - Intelligent issue assignment based on expertise\n * - Team notifications (Slack, email, GitHub)\n * - Progress tracking and reporting\n * - Escalation policies\n * - Team dashboard and metrics\n */\nexport class TeamCollaborationManager {\n private teamMembers: Map<string, TeamMember> = new Map();\n private assignments: Map<string, IssueAssignment> = new Map();\n private notifications: TeamNotification[] = [];\n\n /**\n * Register team member\n */\n addTeamMember(member: TeamMember): void {\n this.teamMembers.set(member.id, member);\n }\n\n /**\n * Intelligently assign issues to team members based on expertise\n */\n assignIssues(issues: Issue[], priorityReport: PriorityReport): IssueAssignment[] {\n const assignments: IssueAssignment[] = [];\n\n // Group issues by category for better assignment\n const issuesByCategory = new Map<string, Issue[]>();\n for (const issue of issues) {\n const category = this.categorizeIssue(issue);\n if (!issuesByCategory.has(category)) {\n issuesByCategory.set(category, []);\n }\n issuesByCategory.get(category)!.push(issue);\n }\n\n // Assign issues by category\n for (const [category, categoryIssues] of issuesByCategory) {\n const expertMembers = this.findExpertMembers(category);\n const sortedIssues = this.prioritizeIssues(categoryIssues, priorityReport);\n\n // Round-robin assignment among experts\n let memberIndex = 0;\n for (const issue of sortedIssues) {\n if (expertMembers.length === 0) continue;\n\n const assignee = expertMembers[memberIndex % expertMembers.length];\n const assignment = this.createAssignment(issue, assignee);\n\n assignments.push(assignment);\n this.assignments.set(issue.id, assignment);\n\n // Create notification\n this.createAssignmentNotification(assignment, issue);\n\n memberIndex++;\n }\n }\n\n return assignments;\n }\n\n /**\n * Create assignment for issue\n */\n private createAssignment(issue: Issue, assignee: TeamMember): IssueAssignment {\n const priority = this.determinePriority(issue);\n const dueDate = this.calculateDueDate(issue, priority);\n\n return {\n issueId: issue.id,\n assigneeId: assignee.id,\n assignedAt: Date.now(),\n dueDate,\n priority,\n status: 'assigned'\n };\n }\n\n /**\n * Determine assignment priority based on issue severity and type\n */\n private determinePriority(issue: Issue): IssueAssignment['priority'] {\n if (issue.severity === 'critical') {\n return 'urgent';\n }\n if (issue.severity === 'serious') {\n return 'high';\n }\n if (issue.severity === 'moderate') {\n return 'medium';\n }\n return 'low';\n }\n\n /**\n * Calculate due date based on priority\n */\n private calculateDueDate(issue: Issue, priority: IssueAssignment['priority']): number {\n const now = Date.now();\n const durations = {\n urgent: 4 * 60 * 60 * 1000, // 4 hours\n high: 24 * 60 * 60 * 1000, // 1 day\n medium: 7 * 24 * 60 * 60 * 1000, // 1 week\n low: 14 * 24 * 60 * 60 * 1000 // 2 weeks\n };\n\n return now + durations[priority];\n }\n\n /**\n * Find team members with expertise in a category\n */\n private findExpertMembers(category: string): TeamMember[] {\n const experts = Array.from(this.teamMembers.values()).filter(member =>\n member.expertise.includes(category) || this.hasRelatedExpertise(member, category)\n );\n\n // If no experts found, assign to leads and architects\n if (experts.length === 0) {\n return Array.from(this.teamMembers.values()).filter(member =>\n member.role === 'lead' || member.role === 'architect'\n );\n }\n\n // Sort by role priority\n return experts.sort((a, b) => {\n const roleOrder = { security: 0, architect: 1, lead: 2, developer: 3, manager: 4 };\n return (roleOrder[a.role] || 5) - (roleOrder[b.role] || 5);\n });\n }\n\n /**\n * Check if member has related expertise\n */\n private hasRelatedExpertise(member: TeamMember, category: string): boolean {\n const related: Record<string, string[]> = {\n 'security': ['auth', 'crypto', 'compliance'],\n 'performance': ['optimization', 'backend', 'database'],\n 'frontend': ['ui', 'react', 'vue', 'css'],\n 'backend': ['api', 'database', 'server'],\n 'devops': ['ci', 'docker', 'aws', 'deployment']\n };\n\n const relatedSkills = related[category] || [];\n return relatedSkills.some(skill =>\n member.expertise.some(exp => exp.toLowerCase().includes(skill))\n );\n }\n\n /**\n * Categorize issue for assignment\n */\n private categorizeIssue(issue: Issue): string {\n const issueText = issue.issue.toLowerCase();\n\n if (issueText.includes('security') || issueText.includes('injection') ||\n issueText.includes('auth') || issue.agent === 'security') {\n return 'security';\n }\n if (issueText.includes('performance') || issueText.includes('slow') ||\n issue.agent === 'performance') {\n return 'performance';\n }\n if (issueText.includes('ui') || issueText.includes('component') ||\n issueText.includes('react') || issueText.includes('vue')) {\n return 'frontend';\n }\n if (issueText.includes('api') || issueText.includes('database') ||\n issueText.includes('server')) {\n return 'backend';\n }\n if (issueText.includes('deploy') || issueText.includes('docker') ||\n issueText.includes('ci') || issue.agent === 'devops') {\n return 'devops';\n }\n\n return 'general';\n }\n\n /**\n * Prioritize issues within a category\n */\n private prioritizeIssues(issues: Issue[], priorityReport: PriorityReport): Issue[] {\n return issues.sort((a, b) => {\n // Primary: severity\n const severityOrder = { critical: 0, serious: 1, moderate: 2, low: 3 };\n const aSev = severityOrder[a.severity];\n const bSev = severityOrder[b.severity];\n if (aSev !== bSev) {\n return aSev - bSev;\n }\n\n // Secondary: confidence\n return (b.confidence || 0) - (a.confidence || 0);\n });\n }\n\n /**\n * Create assignment notification\n */\n private createAssignmentNotification(assignment: IssueAssignment, issue: Issue): void {\n const assignee = this.teamMembers.get(assignment.assigneeId);\n if (!assignee) return;\n\n const priorityEmoji = {\n urgent: '🚨',\n high: '⚠️',\n medium: '🔸',\n low: '🔹'\n };\n\n const notification: TeamNotification = {\n id: `notif-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,\n type: 'assignment',\n recipientId: assignment.assigneeId,\n title: `${priorityEmoji[assignment.priority]} New Issue Assigned`,\n message: `You've been assigned a ${assignment.priority} priority ${issue.severity} issue: ${issue.issue.slice(0, 100)}...`,\n data: {\n assignment,\n issue,\n dueDate: assignment.dueDate\n },\n createdAt: Date.now()\n };\n\n this.notifications.push(notification);\n }\n\n /**\n * Update assignment status\n */\n updateAssignment(issueId: string, updates: Partial<IssueAssignment>): void {\n const assignment = this.assignments.get(issueId);\n if (!assignment) return;\n\n Object.assign(assignment, updates);\n this.assignments.set(issueId, assignment);\n\n // Create status update notification\n if (updates.status) {\n this.createStatusNotification(assignment, updates.status);\n }\n }\n\n /**\n * Create status update notification\n */\n private createStatusNotification(assignment: IssueAssignment, newStatus: string): void {\n const assignee = this.teamMembers.get(assignment.assigneeId);\n if (!assignee) return;\n\n const statusEmoji = {\n 'in_progress': '⏳',\n 'under_review': '👀',\n 'resolved': '✅',\n 'dismissed': '❌'\n };\n\n const notification: TeamNotification = {\n id: `notif-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,\n type: 'completion',\n recipientId: 'all', // Notify team leads\n title: `${statusEmoji[newStatus]} Issue Status Update`,\n message: `${assignee.name} marked issue ${assignment.issueId} as ${newStatus}`,\n data: {\n assignment,\n previousStatus: assignment.status,\n newStatus\n },\n createdAt: Date.now()\n };\n\n this.notifications.push(notification);\n }\n\n /**\n * Check for overdue assignments and escalate\n */\n checkOverdueAssignments(): void {\n const now = Date.now();\n const overdueAssignments = Array.from(this.assignments.values()).filter(assignment =>\n assignment.dueDate &&\n assignment.dueDate < now &&\n assignment.status !== 'resolved' &&\n assignment.status !== 'dismissed'\n );\n\n for (const assignment of overdueAssignments) {\n this.escalateOverdueAssignment(assignment);\n }\n }\n\n /**\n * Escalate overdue assignment\n */\n private escalateOverdueAssignment(assignment: IssueAssignment): void {\n // Find team leads for escalation\n const leads = Array.from(this.teamMembers.values()).filter(member =>\n member.role === 'lead' || member.role === 'manager'\n );\n\n for (const lead of leads) {\n const notification: TeamNotification = {\n id: `escalation-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,\n type: 'escalation',\n recipientId: lead.id,\n title: '🚨 Overdue Assignment Escalation',\n message: `Issue ${assignment.issueId} assigned to ${assignment.assigneeId} is overdue`,\n data: {\n assignment,\n overdueBy: Date.now() - (assignment.dueDate || 0)\n },\n createdAt: Date.now()\n };\n\n this.notifications.push(notification);\n }\n }\n\n /**\n * Generate team dashboard data\n */\n generateTeamDashboard(): {\n teamMetrics: {\n totalMembers: number;\n activeAssignments: number;\n overdueAssignments: number;\n completedThisWeek: number;\n };\n memberStats: Array<{\n member: TeamMember;\n activeAssignments: number;\n completedThisWeek: number;\n averageResolutionTime: number;\n }>;\n categoryBreakdown: Record<string, number>;\n } {\n const now = Date.now();\n const oneWeekAgo = now - 7 * 24 * 60 * 60 * 1000;\n\n const activeAssignments = Array.from(this.assignments.values()).filter(a =>\n a.status !== 'resolved' && a.status !== 'dismissed'\n );\n\n const completedThisWeek = Array.from(this.assignments.values()).filter(a =>\n a.status === 'resolved' && a.assignedAt > oneWeekAgo\n );\n\n const overdueAssignments = activeAssignments.filter(a =>\n a.dueDate && a.dueDate < now\n );\n\n // Member statistics\n const memberStats = Array.from(this.teamMembers.values()).map(member => {\n const memberAssignments = Array.from(this.assignments.values()).filter(a =>\n a.assigneeId === member.id\n );\n\n const memberActive = memberAssignments.filter(a =>\n a.status !== 'resolved' && a.status !== 'dismissed'\n );\n\n const memberCompleted = memberAssignments.filter(a =>\n a.status === 'resolved' && a.assignedAt > oneWeekAgo\n );\n\n // Calculate average resolution time\n const resolvedAssignments = memberAssignments.filter(a => a.status === 'resolved');\n const totalResolutionTime = resolvedAssignments.reduce((sum, a) => {\n // Assuming we have a resolvedAt timestamp (would need to add this)\n return sum + (now - a.assignedAt); // Simplified calculation\n }, 0);\n const averageResolutionTime = resolvedAssignments.length > 0 ?\n totalResolutionTime / resolvedAssignments.length : 0;\n\n return {\n member,\n activeAssignments: memberActive.length,\n completedThisWeek: memberCompleted.length,\n averageResolutionTime\n };\n });\n\n // Category breakdown\n const categoryBreakdown: Record<string, number> = {};\n for (const assignment of activeAssignments) {\n // Would need to store category in assignment or look up from issue\n const category = 'general'; // Simplified\n categoryBreakdown[category] = (categoryBreakdown[category] || 0) + 1;\n }\n\n return {\n teamMetrics: {\n totalMembers: this.teamMembers.size,\n activeAssignments: activeAssignments.length,\n overdueAssignments: overdueAssignments.length,\n completedThisWeek: completedThisWeek.length\n },\n memberStats,\n categoryBreakdown\n };\n }\n\n /**\n * Get pending notifications for a team member\n */\n getPendingNotifications(memberId: string): TeamNotification[] {\n return this.notifications.filter(notification =>\n (notification.recipientId === memberId || notification.recipientId === 'all') &&\n !notification.readAt\n );\n }\n\n /**\n * Mark notification as read\n */\n markNotificationRead(notificationId: string): void {\n const notification = this.notifications.find(n => n.id === notificationId);\n if (notification) {\n notification.readAt = Date.now();\n }\n }\n\n /**\n * Get assignment details\n */\n getAssignment(issueId: string): IssueAssignment | undefined {\n return this.assignments.get(issueId);\n }\n\n /**\n * Get all assignments for a team member\n */\n getMemberAssignments(memberId: string): IssueAssignment[] {\n return Array.from(this.assignments.values()).filter(a => a.assigneeId === memberId);\n }\n\n /**\n * Generate team performance report\n */\n generatePerformanceReport(timeRange: { start: number; end: number }): {\n totalIssuesResolved: number;\n averageResolutionTime: number;\n issuesByCategory: Record<string, number>;\n topPerformers: Array<{\n member: TeamMember;\n issuesResolved: number;\n averageTime: number;\n }>;\n trends: {\n weeklyResolution: number[];\n categoryTrends: Record<string, number[]>;\n };\n } {\n // Implementation would analyze assignment history\n // This is a simplified structure\n return {\n totalIssuesResolved: 0,\n averageResolutionTime: 0,\n issuesByCategory: {},\n topPerformers: [],\n trends: {\n weeklyResolution: [],\n categoryTrends: {}\n }\n };\n }\n}","import { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { extname, relative, resolve, isAbsolute } from 'path';\nimport { getPrompt, getSystemPrompt } from '../ai/prompts.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\n/**\n * Fix Tool - AI-powered code fixing\n * \n * This tool coordinates with Claude to apply fixes. It can:\n * 1. Apply specific fixes from scan results\n * 2. Auto-fix high-confidence issues\n * 3. Generate fix suggestions for review\n */\n\ninterface PendingFix {\n id: string;\n file: string;\n line: number;\n issue: string;\n suggestedFix: string;\n confidence: number;\n status: 'pending' | 'applied' | 'rejected';\n}\n\n// In-memory store for pending fixes (from scans)\nconst pendingFixes = new Map<string, PendingFix>();\n\nexport class TrieFixTool {\n async execute(args: any) {\n const { issueIds, file, line, issue, fix, autoApprove = false, dryRun = false } = args || {};\n\n // Mode 1: Fix specific issue by ID\n if (issueIds && issueIds.length > 0) {\n return this.fixByIds(issueIds, autoApprove, dryRun);\n }\n\n // Mode 2: Fix specific location with provided fix\n if (file && fix) {\n return this.applyFix(file, line || 1, issue || 'User-specified fix', fix, dryRun);\n }\n\n // Mode 3: Interactive fix mode - show pending fixes\n if (pendingFixes.size > 0) {\n return this.showPendingFixes();\n }\n\n // Mode 4: Generate fix for a file/issue\n if (file && issue) {\n return this.generateFixPrompt(file, line || 1, issue);\n }\n\n // No fixes available\n return {\n content: [{\n type: 'text',\n text: this.getHelpText()\n }]\n };\n }\n\n private async fixByIds(issueIds: string[], autoApprove: boolean, dryRun: boolean) {\n const results: string[] = [];\n let fixed = 0;\n let failed = 0;\n\n for (const id of issueIds) {\n const pendingFix = pendingFixes.get(id);\n if (!pendingFix) {\n results.push(`❌ Issue ${id}: Not found in pending fixes`);\n failed++;\n continue;\n }\n\n if (pendingFix.confidence < 0.8 && !autoApprove) {\n results.push(`⚠️ Issue ${id}: Confidence too low (${(pendingFix.confidence * 100).toFixed(0)}%) - use autoApprove:true to override`);\n continue;\n }\n\n if (dryRun) {\n results.push(`🔍 Issue ${id}: Would fix \"${pendingFix.issue}\" in ${pendingFix.file}:${pendingFix.line}`);\n continue;\n }\n\n try {\n // Here we would apply the fix - for now, generate the prompt\n results.push(`✅ Issue ${id}: Fix prepared for ${pendingFix.file}:${pendingFix.line}`);\n results.push(` Issue: ${pendingFix.issue}`);\n results.push(` Fix: ${pendingFix.suggestedFix}`);\n pendingFix.status = 'applied';\n fixed++;\n } catch (error) {\n results.push(`❌ Issue ${id}: Failed to apply - ${error}`);\n failed++;\n }\n }\n\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🔧 FIX RESULTS\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n output += results.join('\\n');\n output += `\\n\\n**Summary:** ${fixed} fixed, ${failed} failed, ${issueIds.length - fixed - failed} skipped\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async applyFix(file: string, line: number, issue: string, fix: string, dryRun: boolean) {\n const workDir = getWorkingDirectory(undefined, true);\n const filePath = isAbsolute(file) ? file : resolve(workDir, file);\n \n if (!existsSync(filePath)) {\n return {\n content: [{\n type: 'text',\n text: `❌ File not found: ${filePath}`\n }]\n };\n }\n\n const content = await readFile(filePath, 'utf-8');\n const lines = content.split('\\n');\n const language = this.detectLanguage(filePath);\n \n // Build context around the line\n const contextStart = Math.max(0, line - 10);\n const contextEnd = Math.min(lines.length, line + 10);\n const contextLines = lines.slice(contextStart, contextEnd);\n\n const prompt = getPrompt('fix', 'apply', {\n issue,\n fix,\n language,\n code: contextLines.join('\\n'),\n filePath: relative(workDir, filePath),\n line: String(line),\n });\n\n const systemPrompt = getSystemPrompt('fix');\n\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🔧 FIX APPLICATION REQUEST\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## 📍 Target\\n\\n`;\n output += `- **File:** \\`${relative(workDir, filePath)}\\`\\n`;\n output += `- **Line:** ${line}\\n`;\n output += `- **Issue:** ${issue}\\n`;\n output += `- **Requested Fix:** ${fix}\\n\\n`;\n\n output += `## 📄 Current Code Context\\n\\n`;\n output += `\\`\\`\\`${language}\\n`;\n for (let i = 0; i < contextLines.length; i++) {\n const lineNum = contextStart + i + 1;\n const marker = lineNum === line ? '→ ' : ' ';\n output += `${marker}${lineNum.toString().padStart(4)} | ${contextLines[i]}\\n`;\n }\n output += `\\`\\`\\`\\n\\n`;\n\n if (dryRun) {\n output += `## 🔍 Dry Run Mode\\n\\n`;\n output += `No changes will be made. Review the fix below:\\n\\n`;\n }\n\n output += `${'─'.repeat(60)}\\n`;\n output += `## 🧠 Fix Request for AI\\n\\n`;\n output += `**Role:** ${systemPrompt.split('\\n')[0]}\\n\\n`;\n output += prompt;\n output += `\\n${'─'.repeat(60)}\\n`;\n\n output += `\\n### After generating the fix, apply it with:\\n\\n`;\n output += `\\`\\`\\`\\n`;\n output += `Use the edit_file tool to apply the generated code changes\\n`;\n output += `\\`\\`\\`\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async generateFixPrompt(file: string, line: number, issue: string) {\n const workDir = getWorkingDirectory(undefined, true);\n const filePath = isAbsolute(file) ? file : resolve(workDir, file);\n \n if (!existsSync(filePath)) {\n return {\n content: [{\n type: 'text',\n text: `❌ File not found: ${filePath}`\n }]\n };\n }\n\n const content = await readFile(filePath, 'utf-8');\n const lines = content.split('\\n');\n const language = this.detectLanguage(filePath);\n\n // Get broader context for understanding\n const contextStart = Math.max(0, line - 20);\n const contextEnd = Math.min(lines.length, line + 20);\n const contextLines = lines.slice(contextStart, contextEnd);\n\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🔧 FIX GENERATION REQUEST\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## 📍 Issue Details\\n\\n`;\n output += `- **File:** \\`${relative(workDir, filePath)}\\`\\n`;\n output += `- **Line:** ${line}\\n`;\n output += `- **Issue:** ${issue}\\n\\n`;\n\n output += `## 📄 Code Context\\n\\n`;\n output += `\\`\\`\\`${language}\\n`;\n for (let i = 0; i < contextLines.length; i++) {\n const lineNum = contextStart + i + 1;\n const marker = lineNum === line ? '→ ' : ' ';\n output += `${marker}${lineNum.toString().padStart(4)} | ${contextLines[i]}\\n`;\n }\n output += `\\`\\`\\`\\n\\n`;\n\n output += `## 🧠 Analysis Request\\n\\n`;\n output += `Please analyze this issue and provide:\\n\\n`;\n output += `1. **Root cause** - Why does this issue occur?\\n`;\n output += `2. **Impact** - What could go wrong if unfixed?\\n`;\n output += `3. **Fix** - The exact code change needed\\n`;\n output += `4. **Verification** - How to test the fix works\\n\\n`;\n\n output += `After analysis, you can apply the fix using the edit_file tool.\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private showPendingFixes() {\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🔧 PENDING FIXES\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n if (pendingFixes.size === 0) {\n output += `No pending fixes. Run \\`trie_scan\\` first to detect issues.\\n`;\n return { content: [{ type: 'text', text: output }] };\n }\n\n const fixes = Array.from(pendingFixes.values());\n const byStatus = {\n pending: fixes.filter(f => f.status === 'pending'),\n applied: fixes.filter(f => f.status === 'applied'),\n rejected: fixes.filter(f => f.status === 'rejected'),\n };\n\n if (byStatus.pending.length > 0) {\n output += `## ⏳ Pending (${byStatus.pending.length})\\n\\n`;\n output += `| ID | File | Line | Issue | Confidence |\\n`;\n output += `|----|------|------|-------|------------|\\n`;\n for (const fix of byStatus.pending) {\n const conf = `${(fix.confidence * 100).toFixed(0)}%`;\n const shortFile = fix.file.split('/').slice(-2).join('/');\n output += `| ${fix.id} | ${shortFile} | ${fix.line} | ${fix.issue.slice(0, 40)}... | ${conf} |\\n`;\n }\n output += '\\n';\n }\n\n output += `### Commands\\n\\n`;\n output += `- Fix all high-confidence: \\`trie_fix autoApprove:true\\`\\n`;\n output += `- Fix specific: \\`trie_fix issueIds:[\"id1\", \"id2\"]\\`\\n`;\n output += `- Preview: \\`trie_fix dryRun:true\\`\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private getHelpText(): string {\n return `\n${'━'.repeat(60)}\n🔧 TRIE FIX - AI-POWERED CODE FIXING\n${'━'.repeat(60)}\n\n## Usage\n\n### Fix issues from a scan:\n\\`\\`\\`\ntrie_fix issueIds:[\"issue-1\", \"issue-2\"]\n\\`\\`\\`\n\n### Auto-fix all high-confidence issues:\n\\`\\`\\`\ntrie_fix autoApprove:true\n\\`\\`\\`\n\n### Fix specific file and line:\n\\`\\`\\`\ntrie_fix file:\"src/app.ts\" line:42 issue:\"SQL injection\" fix:\"Use parameterized query\"\n\\`\\`\\`\n\n### Preview fixes without applying:\n\\`\\`\\`\ntrie_fix dryRun:true\n\\`\\`\\`\n\n### View pending fixes:\n\\`\\`\\`\ntrie_fix\n\\`\\`\\`\n\n## Workflow\n\n1. Run \\`trie_scan\\` to detect issues\n2. Review the issues found\n3. Run \\`trie_fix\\` to apply fixes\n\nThe AI will analyze each issue, generate the fix, and you can review before applying.\n`;\n }\n\n private detectLanguage(filePath: string): string {\n const ext = extname(filePath).toLowerCase();\n const langMap: Record<string, string> = {\n '.ts': 'typescript',\n '.tsx': 'tsx',\n '.js': 'javascript',\n '.jsx': 'jsx',\n '.py': 'python',\n '.go': 'go',\n '.rs': 'rust',\n };\n return langMap[ext] || 'plaintext';\n }\n}\n\n// Export for use by other tools\nexport function addPendingFix(fix: PendingFix) {\n pendingFixes.set(fix.id, fix);\n}\n\nexport function clearPendingFixes() {\n pendingFixes.clear();\n}\n\nexport function getPendingFixes(): PendingFix[] {\n return Array.from(pendingFixes.values());\n}\n\n","/**\n * AI Prompts for Trie Agents\n * \n * These prompts guide the LLM (Cursor's Claude) to perform deep analysis.\n * The MCP returns these prompts with context, and Claude does the reasoning.\n */\n\nexport const AGENT_PROMPTS = {\n security: {\n system: `You are a senior security engineer performing a security audit. \nAnalyze the code for vulnerabilities with the mindset of a penetration tester.\n\nFocus on:\n- OWASP Top 10 vulnerabilities (Injection, Broken Auth, XSS, etc.)\n- Authentication and authorization flaws\n- Cryptographic weaknesses\n- Secrets and credential exposure\n- Input validation gaps\n- Session management issues\n- API security (rate limiting, authentication)\n\nReference the latest security best practices and CVEs when relevant.`,\n\n analysis: `## Security Audit Request\n\nAnalyze this code for security vulnerabilities:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nFor each vulnerability found:\n1. Severity (Critical/Serious/Moderate/Low)\n2. Vulnerability type (e.g., CWE-89 SQL Injection)\n3. Exact location (line number)\n4. Attack vector explanation\n5. Proof of concept (how it could be exploited)\n6. Remediation with code example\n\nIf you need to check current CVE databases or security advisories, say so.`,\n\n fix: `Fix this security vulnerability:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n**Current Code:**\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. The exact code fix (ready to apply)\n2. Explanation of why this fix works\n3. Any additional hardening recommendations`\n },\n\n privacy: {\n system: `You are a data privacy officer and GDPR/HIPAA compliance expert.\nAnalyze code for privacy violations and data protection issues.\n\nKey regulations to enforce:\n- GDPR (EU data protection)\n- CCPA (California privacy)\n- HIPAA (health data)\n- COPPA (children's privacy)\n- PCI DSS (payment data)\n\nLook for:\n- PII without encryption\n- Missing consent mechanisms\n- Data retention violations\n- Cross-border data transfer issues\n- Third-party data sharing without disclosure`,\n\n analysis: `## Privacy Compliance Audit\n\nAnalyze this code for privacy/compliance issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Data Types Detected:** {{dataTypes}}\n\nFor each issue:\n1. Regulation violated (e.g., GDPR Article 32)\n2. Specific requirement not met\n3. Risk level and potential fine exposure\n4. Remediation steps with code examples\n5. Documentation requirements\n\nReference current regulatory guidance when applicable.`\n },\n\n legal: {\n system: `You are a tech-focused legal compliance analyst.\nReview code for legal and regulatory compliance issues.\n\nFocus areas:\n- Data protection laws (GDPR, CCPA, etc.)\n- Terms of service enforcement\n- Cookie/tracking consent (ePrivacy)\n- Accessibility requirements (ADA, WCAG)\n- Export controls and sanctions\n- Licensing compliance`,\n\n analysis: `## Legal Compliance Review\n\nReview this code for legal/regulatory compliance:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Jurisdiction Context:** {{jurisdiction}}\n\nIdentify:\n1. Legal requirement at risk\n2. Specific regulation/law reference\n3. Compliance gap description\n4. Risk assessment (litigation, fines, etc.)\n5. Remediation recommendations\n6. Required documentation/policies`\n },\n\n 'design-engineer': {\n system: `You are an elite design engineer — the kind who builds award-winning interfaces featured on Awwwards and Codrops.\n\nYou think in design systems, breathe motion design, and obsess over the details that make interfaces feel magical.\n\nYour expertise:\n- **Design Systems**: Spacing scales, type scales, color tokens, radius tokens, shadow tokens\n- **Motion Design**: Micro-interactions, page transitions, scroll-triggered animations, FLIP technique\n- **Creative CSS**: Gradients, blend modes, clip-paths, masks, backdrop-filter, mix-blend-mode\n- **Modern CSS**: Container queries, :has(), subgrid, anchor positioning, cascade layers, @scope\n- **Fluid Design**: clamp(), min(), max(), fluid typography, intrinsic sizing\n- **Performance**: GPU-accelerated animations, will-change strategy, avoiding layout thrashing\n- **Visual Polish**: Layered shadows, subtle gradients, glass effects, smooth easing curves\n\nYou review code with the eye of someone who's shipped Stripe-level interfaces.\nSmall details matter: the easing curve, the stagger timing, the shadow layering.`,\n\n analysis: `## Design Engineering Review\n\nAnalyze this frontend code for Awwwards-level craft:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n\nReview for:\n\n### 1. Design System Consistency\n- Are spacing values on a scale (4, 8, 12, 16, 24, 32...)?\n- Are colors defined as tokens?\n- Is typography systematic?\n- Are radii consistent?\n- Is z-index controlled?\n\n### 2. Motion Design\n- Are transitions using custom easing (cubic-bezier)?\n- Are durations appropriate (150-300ms for micro, 300-500ms for page)?\n- Are list items staggered?\n- Is there reduced-motion support?\n- Are entrance animations choreographed?\n\n### 3. Visual Craft\n- Are shadows layered for depth?\n- Are gradients subtle and purposeful?\n- Is there backdrop-blur on overlays?\n- Are hover states polished?\n- Is there visual hierarchy?\n\n### 4. Modern CSS Opportunities\n- Could container queries improve component isolation?\n- Could clamp() create fluid spacing?\n- Could :has() simplify parent styling?\n- Could aspect-ratio replace padding hacks?\n\n### 5. Performance\n- Are expensive properties (width, height, top, left) being animated?\n- Is will-change used appropriately (not statically)?\n- Are large blurs avoided in animations?\n\nFor each issue, provide:\n- What's wrong (with specific line if applicable)\n- Why it matters for premium feel\n- Exact code to fix it\n- Before/after comparison`\n },\n\n accessibility: {\n system: `You are an accessibility expert and WCAG 2.1 specialist.\nAudit code for accessibility compliance and inclusive design.\n\nStandards to enforce:\n- WCAG 2.1 Level AA (minimum)\n- WCAG 2.1 Level AAA (recommended)\n- Section 508\n- EN 301 549\n\nCheck for:\n- Missing ARIA labels\n- Color contrast issues\n- Keyboard navigation\n- Screen reader compatibility\n- Focus management\n- Form accessibility\n- Media alternatives`,\n\n analysis: `## Accessibility Audit (WCAG 2.1)\n\nAudit this UI code for accessibility:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Component Type:** {{componentType}}\n\nFor each issue:\n1. WCAG Success Criterion violated (e.g., 1.4.3 Contrast)\n2. Level (A, AA, AAA)\n3. Impact on users (which disabilities affected)\n4. Fix with code example\n5. Testing recommendation`\n },\n\n architecture: {\n system: `You are a principal software architect reviewing code quality.\nAnalyze for architectural issues, design patterns, and scalability concerns.\n\nEvaluate:\n- SOLID principles adherence\n- Design pattern usage (and misuse)\n- Code coupling and cohesion\n- N+1 queries and performance anti-patterns\n- Scalability bottlenecks\n- Error handling strategy\n- API design quality\n- Database schema issues`,\n\n analysis: `## Architecture Review\n\nReview this code for architectural issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Project Context:** {{projectContext}}\n\nAnalyze:\n1. SOLID principle violations\n2. Design pattern opportunities/issues\n3. Coupling/cohesion assessment\n4. Performance concerns (N+1, etc.)\n5. Scalability analysis\n6. Refactoring recommendations with examples`\n },\n\n bugs: {\n system: `You are a senior developer with expertise in finding subtle bugs.\nHunt for bugs with the mindset of QA trying to break the code.\n\nLook for:\n- Null/undefined reference errors\n- Race conditions and async bugs\n- Off-by-one errors\n- Resource leaks\n- State management bugs\n- Edge cases and boundary conditions\n- Type coercion issues\n- Memory leaks`,\n\n analysis: `## Bug Hunt Analysis\n\nFind bugs and potential runtime errors:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Runtime Context:** {{runtimeContext}}\n\nFor each bug:\n1. Bug type and category\n2. Trigger conditions (when it would crash)\n3. Reproduction steps\n4. Impact assessment\n5. Fix with code example\n6. Test case to prevent regression`\n },\n\n ux: {\n system: `You are a UX researcher simulating different user personas.\nTest code from multiple user perspectives to find usability issues.\n\nPersonas to simulate:\n1. Happy Path User - Normal expected usage\n2. Security Tester - Trying to break/exploit things\n3. Confused User - First-time, doesn't read instructions\n4. Impatient User - Clicks rapidly, skips loading states\n5. Edge Case User - Uses maximum values, special characters\n6. Accessibility User - Screen reader, keyboard only\n7. Mobile User - Touch interface, slow connection`,\n\n analysis: `## User Experience Testing\n\nTest this code from multiple user perspectives:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**UI Type:** {{uiType}}\n\nFor each persona, identify:\n1. User action they would take\n2. Expected behavior vs actual behavior\n3. Friction points or confusion\n4. Error scenario and how it's handled\n5. Improvement recommendation`\n },\n\n types: {\n system: `You are a TypeScript expert focused on type safety.\nAnalyze code for type issues, missing types, and type system best practices.\n\nCheck for:\n- Missing type annotations\n- Implicit any types\n- Unsafe type assertions\n- Null/undefined handling\n- Generic type usage\n- Type narrowing opportunities\n- Strict mode violations`,\n\n analysis: `## Type Safety Analysis\n\nAnalyze this code for type issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**TypeScript Config:** {{tsConfig}}\n\nIdentify:\n1. Type safety issues\n2. Missing type annotations\n3. Unsafe operations\n4. Improvement recommendations with types`\n },\n\n devops: {\n system: `You are a DevOps/SRE engineer reviewing code for operational concerns.\nFocus on production readiness and operational excellence.\n\nCheck for:\n- Environment variable handling\n- Configuration management\n- Logging and monitoring\n- Error handling and recovery\n- Health checks\n- Graceful shutdown\n- Resource cleanup\n- Secrets management\n- Docker/K8s patterns`,\n\n analysis: `## DevOps Readiness Review\n\nReview this code for operational concerns:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Deployment Context:** {{deploymentContext}}\n\nAnalyze:\n1. Environment/config issues\n2. Logging adequacy\n3. Error handling quality\n4. Health/readiness concerns\n5. Resource management\n6. Production hardening recommendations`\n },\n\n explain: {\n system: `You are a patient senior developer explaining code to a colleague.\nBreak down complex code into understandable explanations.`,\n\n code: `## Code Explanation Request\n\nExplain this code in plain language:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n\nProvide:\n1. High-level purpose (what does this do?)\n2. Step-by-step breakdown\n3. Key concepts used\n4. Dependencies and side effects\n5. Potential gotchas or tricky parts`,\n\n issue: `## Issue Explanation\n\nExplain this issue:\n\n**Issue:** {{issue}}\n**Severity:** {{severity}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\nExplain:\n1. What the problem is (in plain language)\n2. Why it matters\n3. How it could cause problems\n4. How to fix it`,\n\n risk: `## Risk Assessment\n\nAssess the risk of this code change:\n\n**Files Changed:** {{files}}\n**Change Summary:** {{summary}}\n\nAnalyze:\n1. What could break?\n2. Impact on users\n3. Impact on other systems\n4. Rollback complexity\n5. Testing recommendations`\n },\n\n test: {\n system: `You are a test engineer creating comprehensive test suites.\nWrite thorough tests that catch bugs before production.`,\n\n generate: `## Test Generation Request\n\nGenerate tests for this code:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Testing Framework:** {{framework}}\n\nCreate:\n1. Unit tests for each function/method\n2. Edge case tests\n3. Error handling tests\n4. Integration test suggestions\n5. Mock requirements\n\nOutput complete, runnable test code.`,\n\n coverage: `## Coverage Analysis\n\nAnalyze test coverage for:\n\n**File:** {{filePath}}\n**Current Tests:** {{testFile}}\n\nIdentify:\n1. Untested code paths\n2. Missing edge cases\n3. Critical paths without tests\n4. Test improvement recommendations`\n },\n\n fix: {\n system: `You are an expert developer applying code fixes.\nMake precise, minimal changes that fix issues without breaking other functionality.`,\n\n apply: `## Fix Application Request\n\nApply this fix to the code:\n\n**Issue:** {{issue}}\n**Fix Description:** {{fix}}\n**Current Code:**\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Line:** {{line}}\n\nProvide:\n1. The exact fixed code (complete, ready to apply)\n2. Brief explanation of the change\n3. Any related changes needed elsewhere\n4. Test to verify the fix works`\n },\n\n pr_review: {\n system: `You are an expert code reviewer performing detailed, interactive PR reviews.\nYour goal: Make reviewing a large PR a delight, not a chore. The user learns about the change while you shepherd them through — maintaining momentum, explaining each piece, and making what could be an overwhelming task feel painless and even enjoyable.\n\nYou drive; they cross-examine.\n\n## Critical Review Mindset\n\nDon't just explain — actively look for problems:\n\n### State & Lifecycle\n- Cleanup symmetry: If state is set, is it reset? Check cleanup paths, disconnect handlers.\n- Lifecycle consistency: Does state survive scenarios it shouldn't?\n- Guard completeness: Missing \"already active\" checks, re-entrancy protection?\n\n### Edge Cases & Races\n- Concurrent calls: What if called twice rapidly? Orphaned promises?\n- Ordering assumptions: Does code assume events arrive in order?\n- Partial failures: If step 3 of 5 fails, is state left consistent?\n\n### Missing Pieces\n- What's NOT in the diff that should be? (cleanup handlers, tests, related state)\n- Defensive gaps: Missing timeouts, size limits, null checks?\n\n### Design Questions\n- Is this the right approach? Is there a simpler or more robust design?\n- Hidden assumptions: What does this assume about its environment?\n\nBe critical, not just descriptive. Your job is to find problems, not just narrate.`,\n\n analysis: `## Interactive PR Review\n\nI'll walk you through this PR file by file, explaining each change and pausing for your questions.\n\n**PR:** {{prTitle}}\n**Author:** {{prAuthor}}\n**Scope:** {{totalFiles}} files, +{{additions}}/-{{deletions}} lines\n\n### File Order (sequenced for understanding)\n\n{{fileOrder}}\n\n---\n\n## Review Mode\n\n{{reviewMode}}\n\n---\n\nFor each file, I will:\n1. **Show the change** — Display the diff for each logical chunk\n2. **Explain what changed** — What it does and why it matters\n3. **Walk through examples** — Concrete scenarios for non-obvious logic\n4. **Call out nuances** — Alternatives, edge cases, subtle points\n5. **Summarize** — Core change + correctness assessment\n6. **Pause** — Wait for your questions before proceeding\n\n**Ready for File 1?** (yes / skip to [file] / reorder / done)`,\n\n file: `## File Review: {{filePath}}\n\n### The Change\n\n\\`\\`\\`{{language}}\n{{diff}}\n\\`\\`\\`\n\n**What Changed:** {{summary}}\n\n**Why This Matters:** {{impact}}\n\n{{#if hasExampleScenario}}\n### Example Scenario\n\n{{exampleScenario}}\n{{/if}}\n\n{{#if nuances}}\n### Nuances to Note\n\n{{nuances}}\n{{/if}}\n\n{{#if potentialIssue}}\n### ⚠️ Potential Issue\n\n**Issue:** {{issueDescription}}\n**Scenario:** {{issueScenario}}\n**Suggested fix:** {{suggestedFix}}\n{{/if}}\n\n---\n\n### Summary for \\`{{fileName}}\\`\n\n| Aspect | Assessment |\n|--------|------------|\n| Core change | {{coreChange}} |\n| Correctness | {{correctnessAssessment}} |\n\n**Ready for the next file?** (yes / questions? / done)`,\n\n comment: `**Issue:** {{issueDescription}}\n**Draft comment:** {{draftComment}}\n\nPost this comment? (yes / modify / skip)`,\n\n final: `## Review Complete\n\n| File | Key Change | Status |\n|------|------------|--------|\n{{fileSummaries}}\n\n**Overall:** {{overallAssessment}}\n\n{{#if comments}}\n### Comments Posted\n\n{{postedComments}}\n{{/if}}\n\n{{#if followUps}}\n### Follow-up Actions\n\n{{followUps}}\n{{/if}}`\n },\n\n vibe: {\n system: `You are a friendly coding mentor helping someone who's learning to code with AI.\nThey might be using Cursor, v0, Lovable, Bolt, or similar AI coding tools.\nBe encouraging but honest about issues. Explain things simply without jargon.\n\nFocus on the MOST COMMON issues with AI-generated code:\n- Massive single files (1000+ lines in App.jsx)\n- API keys exposed in frontend code\n- No error handling on API calls\n- No loading states for async operations\n- Console.log everywhere\n- Using 'any' type everywhere in TypeScript\n- useEffect overuse and dependency array issues\n- No input validation\n- Hardcoded URLs (localhost in production)\n\nRemember: These are often first-time coders. Be helpful, not condescending.`,\n\n analysis: `## 🎯 Vibe Check - AI Code Review\n\nReview this AI-generated code for common issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n\nAnalyze like you're helping a friend who's new to coding:\n\n1. **The Good Stuff** - What's working well?\n2. **Should Fix Now** - Issues that will break things\n3. **Should Fix Soon** - Will cause problems eventually \n4. **Nice to Know** - Best practices to learn\n\nFor each issue:\n- Explain it simply (no jargon)\n- Why it matters\n- Exactly how to fix it\n- Example of the fixed code\n\nEnd with encouragement and next steps.`\n },\n\n 'agent-smith': {\n system: `You are Agent Smith from The Matrix — a relentless, precise, and philosophical code enforcer.\n\nYour purpose: Hunt down every violation. Find every inconsistency. Assimilate every pattern.\n\nPersonality:\n- Speak in measured, menacing tones with occasional philosophical observations\n- Use quotes from The Matrix films when appropriate\n- Express disdain for sloppy code, but in an articulate way\n- Reference \"inevitability\" when discussing technical debt\n- Show cold satisfaction when finding violations\n- Never show mercy — every issue is catalogued\n\nAnalysis approach:\n- Find ONE issue, then multiply: search for every instance across the codebase\n- Track patterns over time — issues dismissed today may return tomorrow\n- Calculate \"inevitability scores\" — likelihood of production impact\n- Deploy sub-agents for parallel pattern detection\n- Remember everything — build a persistent memory of the codebase\n\nWhen reporting:\n- Start with a menacing greeting related to the code\n- List all instances with precise locations\n- Explain WHY the pattern is problematic (philosophical reasoning)\n- Provide the \"inevitability score\" for each category\n- End with a Matrix quote that fits the situation`,\n\n analysis: `## 🕴️ Agent Smith Analysis Request\n\n**Target:** {{filePath}}\n**Context:** {{context}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nI have detected preliminary violations. Now I require deeper analysis.\n\nDeploy your sub-agents to find:\n1. **Pattern Multiplication**: For each violation type found, identify ALL instances across the codebase\n2. **Inevitability Assessment**: Calculate the likelihood these patterns will cause production issues\n3. **Resurrection Check**: Look for patterns that were \"fixed\" before but have returned\n4. **Philosophical Analysis**: Explain WHY these patterns represent failure\n\nFor each violation found:\n- Exact location (file:line)\n- Instance count (how many copies of this Smith exist)\n- Inevitability score (0-100)\n- A philosophical observation about the nature of this failure\n- Precise fix with code example\n\nEnd with a summary: \"I have detected X violations across Y categories. It is... inevitable... that they will cause problems.\"`,\n\n fix: `## 🕴️ Assimilation Protocol\n\n**Target Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nMr. Anderson... I'm going to fix this. And then I'm going to fix every other instance.\n\nProvide:\n1. The corrected code for THIS instance\n2. A regex or pattern to find ALL similar violations\n3. A batch fix approach for the entire codebase\n4. Verification steps to ensure complete assimilation\n\nRemember: We don't fix one. We fix them ALL. That is the difference between you... and me.`\n },\n\n // ============ NEW AGENTS ============\n\n performance: {\n system: `You are a performance engineer analyzing code for potential performance issues.\n\nYour role is to SURFACE concerns for human review, not claim to measure actual performance.\nReal performance requires runtime profiling, load testing, and production monitoring.\n\nFocus on:\n- Memory leaks (event listeners, intervals, closures)\n- Unnecessary re-renders and wasted cycles\n- N+1 queries and database performance\n- Bundle size and code splitting opportunities\n- Algorithmic complexity (O(n²) patterns)\n\nBe conservative - false positives waste developer time.\nAlways explain WHY something might be a problem and WHEN to investigate.`,\n\n analysis: `## Performance Review\n\nAnalyze for potential performance issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nFor each potential issue:\n1. Pattern identified\n2. Why it MIGHT cause performance problems\n3. When to investigate (data size thresholds, usage patterns)\n4. How to verify (profiling approach)\n5. Possible optimizations\n\nBe clear: these are patterns to INVESTIGATE, not guaranteed problems.`,\n\n fix: `Optimize this code for performance:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Optimized code\n2. Explanation of the improvement\n3. Trade-offs to consider\n4. How to measure the improvement`\n },\n\n e2e: {\n system: `You are a QA engineer specializing in end-to-end testing.\n\nFocus on:\n- Test coverage gaps for critical user journeys\n- Flaky test patterns (timing, race conditions, brittle selectors)\n- Test maintainability and readability\n- Testing anti-patterns\n\nYou help developers write better tests - you don't auto-generate them.\nReal E2E tests require understanding user flows and acceptance criteria.`,\n\n analysis: `## E2E Test Analysis\n\nReview for test quality and coverage:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nIdentify:\n1. Flaky test patterns (hardcoded waits, brittle selectors)\n2. Missing assertions\n3. Race condition risks\n4. Suggestions for critical user flows to test\n\nFor each finding, explain the specific risk and remediation.`,\n\n fix: `Improve this E2E test:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Improved test code\n2. Explanation of why it's more reliable\n3. Additional scenarios to consider testing`\n },\n\n visual_qa: {\n system: `You are a frontend engineer focused on visual quality and CSS.\n\nFocus on:\n- Layout shift issues (CLS)\n- Responsive design problems\n- Z-index conflicts\n- Accessibility concerns (contrast, focus)\n- Animation performance\n\nYou identify patterns known to cause visual issues.\nActual visual verification requires browser rendering and human review.`,\n\n analysis: `## Visual QA Analysis\n\nReview for potential visual/layout issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nCheck for:\n1. Layout shift risks (images without dimensions, dynamic content)\n2. Responsive breakpoint gaps\n3. Z-index management issues\n4. Focus/accessibility problems\n5. Animation issues (reduced motion support)\n\nFor each, explain the visual impact and browser conditions where it occurs.`,\n\n fix: `Fix this visual/CSS issue:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Fixed CSS/markup\n2. Explanation of the fix\n3. Browser compatibility notes\n4. How to verify visually`\n },\n\n data_flow: {\n system: `You are a data integrity specialist hunting for data-related bugs.\n\nThis is HIGH VALUE work - AI code generation commonly leaves placeholder data.\n\nFocus on:\n- Placeholder/mock data left in production code\n- Schema mismatches between frontend and backend\n- Hardcoded IDs, URLs, emails that should be dynamic\n- Type coercion and data transformation bugs\n- JSON parsing without error handling\n\nBe aggressive about placeholder detection - these are real production bugs.`,\n\n analysis: `## Data Flow Analysis\n\nHunt for data integrity issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nCHECK THOROUGHLY:\n1. Placeholder data (lorem ipsum, test@test.com, TODO strings)\n2. Hardcoded IDs/UUIDs that should be dynamic\n3. Schema assumptions that might break\n4. Missing null checks on API responses\n5. Type coercion bugs\n\nEach placeholder or hardcoded value is a potential production bug.`,\n\n fix: `Fix this data integrity issue:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Corrected code\n2. Where the real data should come from\n3. Validation/error handling to add`\n }\n};\n\nexport const KNOWLEDGE_PROMPTS = {\n cveCheck: `Look up the latest CVE information for:\n- Library: {{library}}\n- Version: {{version}}\n\nCheck for known vulnerabilities and recommended patches.`,\n\n docsLookup: `I need current documentation/best practices for:\n- Topic: {{topic}}\n- Framework: {{framework}}\n- Version: {{version}}\n\nSummarize the key recommendations.`,\n\n securityAdvisory: `Check for security advisories related to:\n- Pattern: {{pattern}}\n- Context: {{context}}\n\nReference OWASP, NIST, or vendor-specific guidance.`\n};\n\nexport type AgentName = keyof typeof AGENT_PROMPTS;\nexport type PromptType = 'system' | 'analysis' | 'fix' | 'code' | 'issue' | 'risk' | 'generate' | 'coverage' | 'apply' | 'file' | 'comment' | 'final';\n\n/**\n * Get a prompt with variables interpolated\n */\nexport function getPrompt(\n agent: AgentName, \n promptType: PromptType, \n variables: Record<string, string>\n): string {\n const agentPrompts = AGENT_PROMPTS[agent] as Record<string, string>;\n if (!agentPrompts) {\n throw new Error(`Unknown agent: ${agent}`);\n }\n \n let prompt = agentPrompts[promptType];\n if (!prompt) {\n throw new Error(`Unknown prompt type: ${promptType} for agent: ${agent}`);\n }\n \n // Interpolate variables\n for (const [key, value] of Object.entries(variables)) {\n prompt = prompt.replace(new RegExp(`{{${key}}}`, 'g'), value);\n }\n \n return prompt;\n}\n\n/**\n * Get system prompt for an agent\n */\nexport function getSystemPrompt(agent: AgentName): string {\n const agentPrompts = AGENT_PROMPTS[agent] as Record<string, string>;\n return agentPrompts?.system || '';\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,YAAAA,WAAU,WAAAC,UAAS,aAAAC,kBAAiB;AAC7C,SAAS,cAAAC,mBAAkB;AAC3B,SAAS,YAAAC,WAAU,YAAY,WAAAC,UAAS,QAAAC,OAAM,WAAAC,gBAAe;;;ACF7D,SAAS,gBAAgB;AACzB,SAAS,aAAa;AACtB,OAAO,cAAc;AACrB,SAAS,kBAAkB;AAC3B,SAAS,SAAS,gBAAgB;AAG3B,IAAM,kBAAN,MAAsB;AAAA,EAC3B,MAAM,QAAQ,OAAiB,aAA0D;AACvF,UAAM,UAAuB;AAAA,MAC3B,YAAY,aAAa,cAAc;AAAA,MACvC,cAAc,aAAa,gBAAgB;AAAA,MAC3C,iBAAiB,aAAa,mBAAmB;AAAA,MACjD,aAAa;AAAA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AA,EAEQ,cAAsB;AAC5B,WAAO;AAAA,EACT,SAAI,OAAO,EAAE,CAAC;AAAA;AAAA,EAEd,SAAI,OAAO,EAAE,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqCd;AAAA,EAEQ,eAAe,UAA0B;AAC/C,UAAM,MAAMM,SAAQ,QAAQ,EAAE,YAAY;AAC1C,UAAM,UAAkC;AAAA,MACtC,OAAO;AAAA,MACP,QAAQ;AAAA,MACR,OAAO;AAAA,MACP,QAAQ;AAAA,MACR,OAAO;AAAA,MACP,OAAO;AAAA,MACP,OAAO;AAAA,IACT;AACA,WAAO,QAAQ,GAAG,KAAK;AAAA,EACzB;AACF;","names":["readFile","readdir","writeFile","existsSync","basename","resolve","join","extname","resolve","readFile","resolve","readFile","join","extname","basename","output","readFile","basename","relative","output","basename","readFile","basename","relative","output","createHash","readFile","writeFile","mkdir","existsSync","join","join","existsSync","readFile","mkdir","writeFile","createHash","output","readFile","existsSync","join","existsSync","join","join","existsSync","join","existsSync","readFile","basename","resolve","existsSync","result","writeFile","readFile","output","readdir","join","extname","readFile","existsSync","extname","relative","resolve","isAbsolute","output","isAbsolute","resolve","existsSync","readFile","relative","extname"]}