@triedotdev/mcp 1.0.3 โ†’ 1.0.4

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/utils/progress.ts","../src/agents/base-agent.ts","../src/agents/security.ts","../src/agents/privacy.ts","../src/agents/typecheck.ts","../src/agents/comprehension.ts","../src/agents/design-engineer.ts","../src/agents/legal.ts","../src/agents/test.ts","../src/agents/software-architect.ts","../src/agents/devops.ts","../src/agents/bug-finding.ts","../src/agents/user-testing.ts","../src/agents/trie-clean.ts","../src/agents/custom-agent.ts","../src/agents/registry.ts","../src/tools/scan.ts","../src/orchestrator/context-analyzer.ts","../src/orchestrator/risk-assessor.ts","../src/orchestrator/triager.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/tools/fix.ts","../src/ai/prompts.ts"],"sourcesContent":["/**\n * Progress Reporter for Trie Agent\n * \n * Provides real-time feedback to users as the agent works.\n * Uses console.error because MCP clients display stderr to users.\n */\n\nexport type ProgressPhase = \n | 'init'\n | 'discovery'\n | 'reading'\n | 'analyzing'\n | 'ai-review'\n | 'prioritizing'\n | 'complete';\n\nexport interface ProgressCallback {\n (phase: ProgressPhase, message: string, detail?: string): void;\n}\n\n/**\n * Progress Reporter - streams status updates to the user\n */\nexport class ProgressReporter {\n private currentPhase: ProgressPhase = 'init';\n private startTime: number = Date.now();\n private phaseStartTime: number = Date.now();\n private verbose: boolean;\n\n constructor(options: { verbose?: boolean } = {}) {\n this.verbose = options.verbose ?? true;\n }\n\n /**\n * Report a status update\n */\n report(message: string, detail?: string): void {\n if (!this.verbose) return;\n \n const prefix = this.getPhaseIcon(this.currentPhase);\n const fullMessage = detail ? `${message}: ${detail}` : message;\n console.error(`${prefix} ${fullMessage}`);\n }\n\n /**\n * Start a new phase\n */\n startPhase(phase: ProgressPhase, message: string): void {\n this.currentPhase = phase;\n this.phaseStartTime = Date.now();\n this.report(message);\n }\n\n /**\n * Update within current phase\n */\n update(message: string, detail?: string): void {\n this.report(message, detail);\n }\n\n /**\n * Report progress on a file\n */\n file(action: string, filePath: string): void {\n // Show just the filename for cleaner output\n const fileName = filePath.split('/').pop() || filePath;\n this.report(action, fileName);\n }\n\n /**\n * Report an AI analysis step\n */\n ai(action: string, context?: string): void {\n const prefix = '๐Ÿง ';\n const message = context ? `${action}: ${context}` : action;\n console.error(`${prefix} ${message}`);\n }\n\n /**\n * Report a finding\n */\n finding(severity: 'critical' | 'serious' | 'moderate' | 'low', message: string): void {\n const icons = {\n critical: '๐Ÿ”ด',\n serious: '๐ŸŸ ',\n moderate: '๐ŸŸก',\n low: '๐Ÿ”ต'\n };\n console.error(` ${icons[severity]} ${message}`);\n }\n\n /**\n * Complete current phase\n */\n completePhase(summary: string): void {\n const elapsed = Date.now() - this.phaseStartTime;\n this.report(`โœ“ ${summary}`, `(${elapsed}ms)`);\n }\n\n /**\n * Complete the entire operation\n */\n complete(summary: string): void {\n const totalElapsed = Date.now() - this.startTime;\n console.error('');\n console.error(`โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”`);\n console.error(`โœ… ${summary}`);\n console.error(` Total time: ${(totalElapsed / 1000).toFixed(2)}s`);\n console.error(`โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”`);\n console.error('');\n }\n\n /**\n * Report an error\n */\n error(message: string, detail?: string): void {\n const fullMessage = detail ? `${message}: ${detail}` : message;\n console.error(`โŒ ${fullMessage}`);\n }\n\n /**\n * Report a warning\n */\n warn(message: string, detail?: string): void {\n const fullMessage = detail ? `${message}: ${detail}` : message;\n console.error(`โš ๏ธ ${fullMessage}`);\n }\n\n /**\n * Get icon for current phase\n */\n private getPhaseIcon(phase: ProgressPhase): string {\n const icons: Record<ProgressPhase, string> = {\n 'init': '๐Ÿ”บ',\n 'discovery': '๐Ÿ”',\n 'reading': '๐Ÿ“‚',\n 'analyzing': '๐Ÿ”ฌ',\n 'ai-review': '๐Ÿง ',\n 'prioritizing': '๐ŸŽฏ',\n 'complete': 'โœ…'\n };\n return icons[phase] || 'โ€ข';\n }\n\n /**\n * Create a sub-reporter for a specific agent\n */\n forAgent(agentName: string): AgentProgressReporter {\n return new AgentProgressReporter(agentName, this.verbose);\n }\n}\n\n/**\n * Progress reporter scoped to a specific agent\n */\nexport class AgentProgressReporter {\n private agentName: string;\n private verbose: boolean;\n private issueCount: number = 0;\n\n constructor(agentName: string, verbose: boolean = true) {\n this.agentName = agentName;\n this.verbose = verbose;\n }\n\n start(): void {\n if (!this.verbose) return;\n console.error(`\\n๐Ÿค– ${this.agentName.toUpperCase()} Agent starting...`);\n }\n\n analyzing(file: string): void {\n if (!this.verbose) return;\n const fileName = file.split('/').pop() || file;\n console.error(` ๐Ÿ“„ Analyzing ${fileName}...`);\n }\n\n aiReview(context: string): void {\n if (!this.verbose) return;\n console.error(` ๐Ÿง  AI reviewing: ${context}`);\n }\n\n found(severity: string, issue: string): void {\n this.issueCount++;\n if (!this.verbose) return;\n const icon = severity === 'critical' ? '๐Ÿ”ด' : \n severity === 'serious' ? '๐ŸŸ ' : \n severity === 'moderate' ? '๐ŸŸก' : '๐Ÿ”ต';\n console.error(` ${icon} Found: ${issue}`);\n }\n\n complete(summary?: string): void {\n if (!this.verbose) return;\n const msg = summary || `Found ${this.issueCount} issues`;\n console.error(` โœ“ ${this.agentName}: ${msg}`);\n }\n\n getIssueCount(): number {\n return this.issueCount;\n }\n}\n\n/**\n * Global singleton for easy access\n */\nlet globalReporter: ProgressReporter | null = null;\n\nexport function getProgressReporter(options?: { verbose?: boolean }): ProgressReporter {\n if (!globalReporter) {\n globalReporter = new ProgressReporter(options);\n }\n return globalReporter;\n}\n\nexport function resetProgressReporter(): void {\n globalReporter = null;\n}\n","import type { Agent, AgentResult, ScanContext, Issue, CodeContext, AgentPriority } from '../types/index.js';\nimport { AgentProgressReporter } from '../utils/progress.js';\nimport { basename, relative } from 'path';\n\n/**\n * AI Analysis Request - what the agent wants AI to analyze\n */\nexport interface AIAnalysisRequest {\n /** The file being analyzed */\n file: string;\n /** Relevant code content to analyze */\n code: string;\n /** What kind of analysis to perform */\n analysisType: string;\n /** System prompt for the AI */\n systemPrompt: string;\n /** User prompt with specific instructions */\n userPrompt: string;\n /** Additional context for the AI */\n context?: Record<string, unknown>;\n /** Files/code that might be relevant for cross-reference */\n relatedCode?: Array<{ file: string; code: string }>;\n}\n\n/**\n * AI Analysis Result - structured output from AI analysis\n */\nexport interface AIAnalysisResult {\n issues: Array<{\n severity: 'critical' | 'serious' | 'moderate' | 'low';\n title: string;\n description: string;\n line?: number;\n fix: string;\n confidence: number;\n }>;\n summary: string;\n}\n\n/**\n * File relevance check result\n */\nexport interface FileRelevance {\n isRelevant: boolean;\n reason: string;\n priority: 'high' | 'medium' | 'low';\n indicators: string[];\n}\n\nexport abstract class BaseAgent implements Agent {\n abstract name: string;\n abstract description: string;\n abstract version: string;\n \n // Progress reporter for real-time feedback\n protected progress: AgentProgressReporter | null = null;\n \n // Default priority - subclasses can override\n get priority(): AgentPriority {\n return {\n name: this.name,\n tier: 2,\n estimatedTimeMs: 100,\n dependencies: []\n };\n }\n\n abstract shouldActivate(context: CodeContext): boolean;\n\n // Default implementation - can be overridden for smarter confidence\n getActivationConfidence(context: CodeContext): number {\n return this.shouldActivate(context) ? 0.7 : 0;\n }\n\n /**\n * Main scan entry point - now with progress reporting\n */\n async scan(files: string[], context: ScanContext): Promise<AgentResult> {\n const startTime = Date.now();\n this.progress = new AgentProgressReporter(this.name);\n this.progress.start();\n\n try {\n // Use AI-first analysis if available, otherwise fall back to pattern matching\n const issues = await this.analyzeWithAI(files, context);\n\n this.progress.complete(`${issues.length} issues found`);\n\n return {\n agent: this.name,\n issues,\n executionTime: Date.now() - startTime,\n success: true,\n metadata: {\n filesAnalyzed: files.length,\n linesAnalyzed: 0,\n }\n };\n } catch (error) {\n this.progress.complete('Failed');\n return {\n agent: this.name,\n issues: [],\n executionTime: Date.now() - startTime,\n success: false,\n error: error instanceof Error ? error.message : String(error)\n };\n }\n }\n\n /**\n * AI-First Analysis - The new way\n * \n * 1. Quick filter to identify relevant files\n * 2. Generate rich AI prompts for relevant files\n * 3. Return prompts for the AI to process\n * \n * Subclasses should override this for AI-powered analysis\n */\n protected async analyzeWithAI(files: string[], context: ScanContext): Promise<Issue[]> {\n const issues: Issue[] = [];\n const aiRequests: AIAnalysisRequest[] = [];\n\n // Phase 1: Quick relevance check on all files\n this.progress?.aiReview('Identifying relevant files...');\n \n for (const file of files) {\n try {\n const content = await this.readFile(file);\n const relevance = this.checkFileRelevance(file, content);\n \n if (relevance.isRelevant) {\n this.progress?.analyzing(file);\n \n // Phase 2: Generate AI analysis request\n const request = await this.buildAIAnalysisRequest(file, content, relevance, context);\n if (request) {\n aiRequests.push(request);\n }\n }\n } catch (error) {\n // Skip unreadable files\n }\n }\n\n // Phase 3: Process AI requests and generate output\n if (aiRequests.length > 0) {\n this.progress?.aiReview(`Preparing analysis for ${aiRequests.length} files...`);\n \n for (const request of aiRequests) {\n // Generate the AI prompt that will be shown to Claude\n const aiIssues = await this.processAIRequest(request);\n issues.push(...aiIssues);\n }\n }\n\n // Fall back to legacy pattern matching for any remaining analysis\n const legacyIssues = await this.analyzeFiles(files, context);\n \n // Merge and deduplicate\n const allIssues = this.mergeIssues(issues, legacyIssues);\n \n return allIssues;\n }\n\n /**\n * Check if a file is relevant for this agent's analysis\n * Subclasses should override for domain-specific checks\n */\n protected checkFileRelevance(_file: string, _content: string): FileRelevance {\n // Default: all files are relevant with low priority\n return {\n isRelevant: true,\n reason: 'Default analysis',\n priority: 'low',\n indicators: []\n };\n }\n\n /**\n * Build an AI analysis request for a file\n * Subclasses should override to provide domain-specific prompts\n */\n protected async buildAIAnalysisRequest(\n file: string,\n content: string,\n relevance: FileRelevance,\n _context: ScanContext\n ): Promise<AIAnalysisRequest | null> {\n const fileName = basename(file);\n const relPath = this.getRelativePath(file);\n \n return {\n file,\n code: content,\n analysisType: this.name,\n systemPrompt: this.getSystemPrompt(),\n userPrompt: this.buildUserPrompt(relPath, content, relevance),\n context: {\n fileName,\n relevance: relevance.reason,\n indicators: relevance.indicators\n }\n };\n }\n\n /**\n * Get the system prompt for AI analysis\n * Subclasses should override with domain-specific prompts\n */\n protected getSystemPrompt(): string {\n return `You are an expert code analyzer specializing in ${this.name} analysis. \nAnalyze the provided code and identify issues with specific line numbers and actionable fixes.\nBe precise and avoid false positives. Only report issues you are confident about.`;\n }\n\n /**\n * Build the user prompt for AI analysis\n */\n protected buildUserPrompt(filePath: string, content: string, relevance: FileRelevance): string {\n return `Analyze this code for ${this.name} issues:\n\n**File:** ${filePath}\n**Relevance indicators:** ${relevance.indicators.join(', ') || 'general analysis'}\n\n\\`\\`\\`\n${content}\n\\`\\`\\`\n\nFor each issue found, provide:\n1. Severity (critical/serious/moderate/low)\n2. Line number\n3. Clear description of the issue\n4. Specific fix recommendation`;\n }\n\n /**\n * Process an AI analysis request and return issues\n * This generates the prompt output for Claude to process\n */\n protected async processAIRequest(request: AIAnalysisRequest): Promise<Issue[]> {\n // For now, we output the analysis request as part of the response\n // The AI (Claude) will see this and provide the actual analysis\n \n const fileName = basename(request.file);\n this.progress?.aiReview(`${fileName} queued for AI analysis`);\n \n // Create a placeholder issue that contains the AI prompt\n // This will be replaced by actual AI analysis in the output\n return [{\n id: this.generateIssueId(),\n severity: 'moderate',\n issue: `AI Analysis Required: ${request.analysisType}`,\n fix: 'Review the AI analysis output below',\n file: request.file,\n confidence: 1.0,\n autoFixable: false,\n agent: this.name,\n effort: 'medium',\n // Store the AI prompt for inclusion in output\n aiPrompt: {\n system: request.systemPrompt,\n user: request.userPrompt\n }\n } as Issue & { aiPrompt: { system: string; user: string } }];\n }\n\n /**\n * Merge and deduplicate issues from AI and legacy analysis\n */\n protected mergeIssues(aiIssues: Issue[], legacyIssues: Issue[]): Issue[] {\n // Simple merge - prefer AI issues, add legacy issues that don't overlap\n const merged = [...aiIssues];\n \n for (const legacy of legacyIssues) {\n // Check if there's an overlapping AI issue for the same file/line\n const hasOverlap = aiIssues.some(ai => \n ai.file === legacy.file && \n ai.line === legacy.line\n );\n \n if (!hasOverlap) {\n merged.push(legacy);\n }\n }\n \n return merged;\n }\n\n /**\n * Get relative path from cwd\n */\n protected getRelativePath(file: string): string {\n try {\n return relative(process.cwd(), file);\n } catch {\n return file;\n }\n }\n\n /**\n * Legacy pattern-based analysis - kept for backwards compatibility\n * Subclasses can override or deprecate\n */\n protected abstract analyzeFiles(files: string[], context: ScanContext): Promise<Issue[]>;\n\n protected createIssue(\n id: string,\n severity: Issue['severity'],\n issue: string,\n fix: string,\n file: string,\n line?: number,\n confidence: number = 0.9,\n regulation?: string,\n autoFixable: boolean = true,\n options?: {\n category?: string;\n cwe?: string;\n owasp?: string;\n effort?: Issue['effort'];\n endLine?: number;\n column?: number;\n }\n ): Issue {\n const result: Issue = {\n id,\n severity,\n issue,\n fix,\n file,\n confidence,\n autoFixable,\n agent: this.name,\n effort: options?.effort ?? this.estimateEffort(severity, autoFixable)\n };\n \n // Only add optional properties if they have values\n if (line !== undefined) result.line = line;\n if (options?.endLine !== undefined) result.endLine = options.endLine;\n if (options?.column !== undefined) result.column = options.column;\n if (regulation !== undefined) result.regulation = regulation;\n if (options?.category !== undefined) result.category = options.category;\n if (options?.cwe !== undefined) result.cwe = options.cwe;\n if (options?.owasp !== undefined) result.owasp = options.owasp;\n \n return result;\n }\n\n private estimateEffort(severity: Issue['severity'], autoFixable: boolean): 'trivial' | 'easy' | 'medium' | 'hard' {\n if (autoFixable) return 'trivial';\n if (severity === 'low') return 'easy';\n if (severity === 'moderate') return 'easy';\n if (severity === 'serious') return 'medium';\n return 'hard';\n }\n\n protected async readFile(filePath: string): Promise<string> {\n const { readFile } = await import('fs/promises');\n return readFile(filePath, 'utf-8');\n }\n\n protected generateIssueId(): string {\n return `${this.name}-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n }\n\n protected getLineContent(content: string, lineNumber: number): string {\n const lines = content.split('\\n');\n return lines[lineNumber - 1] || '';\n }\n\n protected getCodeSnippet(content: string, lineNumber: number, contextLines: number = 2): string {\n const lines = content.split('\\n');\n const start = Math.max(0, lineNumber - contextLines - 1);\n const end = Math.min(lines.length, lineNumber + contextLines);\n \n return lines\n .slice(start, end)\n .map((line, idx) => {\n const num = start + idx + 1;\n const marker = num === lineNumber ? 'โ†’' : ' ';\n return `${marker} ${num.toString().padStart(4)} | ${line}`;\n })\n .join('\\n');\n }\n}\n","import { BaseAgent, AIAnalysisRequest, FileRelevance } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\nimport { basename } from 'path';\n\n/**\n * Files to ALWAYS skip - never generate issues for these\n */\nconst ALWAYS_SKIP_FILES = [\n /vulnerability-signatures\\.[jt]s$/,\n /vibe-code-signatures\\.[jt]s$/,\n /node_modules\\//,\n /\\.d\\.ts$/,\n /\\.min\\.[jt]s$/,\n /dist\\//,\n /build\\//,\n /package-lock\\.json$/,\n /yarn\\.lock$/,\n];\n\n/**\n * Test files - skip most checks except real exposed secrets\n */\nconst TEST_FILE_PATTERNS = [\n /\\.test\\.[jt]sx?$/,\n /\\.spec\\.[jt]sx?$/,\n /__tests__\\//,\n /\\/test\\//,\n /\\/tests\\//,\n /fixture/i,\n /mock/i,\n];\n\n/**\n * Security-relevant indicators - files that need deeper analysis\n */\nconst SECURITY_INDICATORS = {\n // High priority - definitely needs security review\n high: [\n { pattern: /auth|login|session|jwt|token|oauth/i, reason: 'authentication code' },\n { pattern: /password|credential|secret|apikey|api[_-]?key/i, reason: 'credential handling' },\n { pattern: /sql|query|database|prisma|sequelize|knex|mongodb/i, reason: 'database operations' },\n { pattern: /exec|spawn|child_process|shell/i, reason: 'command execution' },\n { pattern: /eval\\s*\\(|new\\s+Function/i, reason: 'dynamic code execution' },\n { pattern: /crypto|encrypt|decrypt|hash/i, reason: 'cryptographic operations' },\n { pattern: /payment|stripe|paypal|billing|credit/i, reason: 'payment processing' },\n ],\n // Medium priority - worth reviewing\n medium: [\n { pattern: /req\\.body|req\\.params|req\\.query/i, reason: 'user input handling' },\n { pattern: /innerHTML|outerHTML|document\\.write/i, reason: 'DOM manipulation' },\n { pattern: /dangerouslySetInnerHTML/i, reason: 'React raw HTML' },\n { pattern: /fetch\\(|axios|http\\.|https\\./i, reason: 'HTTP requests' },\n { pattern: /cookie|localStorage|sessionStorage/i, reason: 'client storage' },\n { pattern: /cors|origin|header/i, reason: 'CORS/header handling' },\n { pattern: /redirect|location\\.href/i, reason: 'redirects' },\n ],\n // Low priority - might have security implications\n low: [\n { pattern: /upload|file|multer|formdata/i, reason: 'file handling' },\n { pattern: /url|path|route/i, reason: 'URL/path handling' },\n { pattern: /validate|sanitize|escape/i, reason: 'validation code' },\n ]\n};\n\n/**\n * Critical patterns that should be caught immediately (pre-AI filter)\n * These are high-confidence patterns that don't need AI to confirm\n */\nconst CRITICAL_PATTERNS = [\n // Real secrets (not placeholders)\n { pattern: /AKIA[A-Z0-9]{16}/, severity: 'critical' as const, issue: 'AWS Access Key exposed', fix: 'Remove AWS key and rotate immediately. Use environment variables.' },\n { pattern: /-----BEGIN (RSA |EC |DSA )?PRIVATE KEY-----/, severity: 'critical' as const, issue: 'Private key exposed in code', fix: 'Remove private key immediately. Store in secure vault.' },\n { pattern: /ghp_[A-Za-z0-9]{36}/, severity: 'critical' as const, issue: 'GitHub personal access token exposed', fix: 'Revoke token and use environment variables.' },\n { pattern: /sk_live_[A-Za-z0-9]{24,}/, severity: 'critical' as const, issue: 'Stripe live API key exposed', fix: 'Rotate Stripe key immediately. Use environment variables.' },\n { pattern: /xox[baprs]-[A-Za-z0-9-]{10,}/, severity: 'critical' as const, issue: 'Slack token exposed', fix: 'Revoke Slack token and use environment variables.' },\n];\n\nexport class SecurityAgent extends BaseAgent {\n name = 'security';\n description = 'AI-powered security analysis: vulnerabilities, injection risks, authentication issues';\n version = '2.0.0';\n\n shouldActivate(context: CodeContext): boolean {\n return (\n context.touchesAuth ||\n context.touchesDatabase ||\n context.touchesAPI ||\n context.touchesUserData ||\n context.touchesPayments ||\n context.touchesSecurityConfig\n );\n }\n\n /**\n * Check if file should always be skipped\n */\n private shouldAlwaysSkip(filePath: string): boolean {\n return ALWAYS_SKIP_FILES.some(pattern => pattern.test(filePath));\n }\n\n /**\n * Check if file is a test file\n */\n private isTestFile(filePath: string): boolean {\n return TEST_FILE_PATTERNS.some(pattern => pattern.test(filePath));\n }\n\n /**\n * AI-First: Check file relevance for security analysis\n */\n protected override checkFileRelevance(file: string, content: string): FileRelevance {\n if (this.shouldAlwaysSkip(file)) {\n return { isRelevant: false, reason: 'Skip file', priority: 'low', indicators: [] };\n }\n\n const indicators: string[] = [];\n let priority: 'high' | 'medium' | 'low' = 'low';\n \n // Check for security-relevant patterns\n for (const { pattern, reason } of SECURITY_INDICATORS.high) {\n if (pattern.test(content) || pattern.test(file)) {\n indicators.push(reason);\n priority = 'high';\n }\n }\n \n if (priority !== 'high') {\n for (const { pattern, reason } of SECURITY_INDICATORS.medium) {\n if (pattern.test(content)) {\n indicators.push(reason);\n if (priority === 'low') priority = 'medium';\n }\n }\n }\n \n // Even low-priority files might have issues\n if (indicators.length === 0) {\n for (const { pattern, reason } of SECURITY_INDICATORS.low) {\n if (pattern.test(content)) {\n indicators.push(reason);\n }\n }\n }\n\n return {\n isRelevant: indicators.length > 0 || content.length > 100,\n reason: indicators.length > 0 ? `Contains: ${indicators.slice(0, 3).join(', ')}` : 'General review',\n priority,\n indicators\n };\n }\n\n /**\n * Get the security-focused system prompt\n */\n protected override getSystemPrompt(): string {\n return `You are a senior security engineer performing a thorough security audit.\nYour goal is to find REAL vulnerabilities, not theoretical issues.\n\nFOCUS ON:\n1. **Injection Attacks**: SQL injection, command injection, XSS, template injection\n2. **Authentication Flaws**: Weak passwords, missing auth, session issues, JWT problems\n3. **Authorization Bypass**: Missing access controls, IDOR, privilege escalation\n4. **Secrets Exposure**: Hardcoded credentials, API keys, tokens in code\n5. **Data Exposure**: PII leaks, sensitive data in logs, insecure storage\n6. **Cryptographic Issues**: Weak algorithms, hardcoded keys, insecure random\n\nBE PRECISE:\n- Only report issues you're confident about (avoid false positives)\n- Provide exact line numbers\n- Explain WHY it's a vulnerability (attack scenario)\n- Give specific, actionable fixes with code examples\n\nSEVERITY GUIDELINES:\n- CRITICAL: Directly exploitable, leads to data breach or RCE\n- SERIOUS: Exploitable with some conditions, significant impact\n- MODERATE: Real issue but limited impact or harder to exploit\n- LOW: Best practice violation, theoretical risk`;\n }\n\n /**\n * Build security-specific analysis prompt\n */\n protected override buildUserPrompt(filePath: string, content: string, relevance: FileRelevance): string {\n const isTest = this.isTestFile(filePath);\n \n let prompt = `## Security Audit Request\n\n**File:** \\`${filePath}\\`\n**Security indicators detected:** ${relevance.indicators.join(', ') || 'general review'}\n${isTest ? '**Note:** This is a test file - only flag REAL exposed secrets, not test fixtures.' : ''}\n\n\\`\\`\\`\n${content}\n\\`\\`\\`\n\n## Analysis Instructions\n\nAnalyze this code for security vulnerabilities. For each issue found:\n\n1. **Severity**: critical / serious / moderate / low\n2. **Line number**: Exact line where the issue occurs\n3. **Vulnerability type**: (e.g., SQL Injection, XSS, Hardcoded Secret)\n4. **Description**: What's wrong and why it's dangerous\n5. **Attack scenario**: How an attacker could exploit this\n6. **Fix**: Specific code fix or remediation steps\n\n### Specific checks for this file:`;\n\n // Add context-specific checks based on indicators\n if (relevance.indicators.includes('authentication code')) {\n prompt += `\n- Check for password comparison without hashing\n- Verify JWT validation is complete (signature, expiration, issuer)\n- Look for session fixation vulnerabilities\n- Check for timing attacks in auth comparisons`;\n }\n \n if (relevance.indicators.includes('database operations')) {\n prompt += `\n- Check for SQL injection via string concatenation or template literals\n- Verify parameterized queries are used\n- Look for ORM misuse that could lead to injection`;\n }\n \n if (relevance.indicators.includes('user input handling')) {\n prompt += `\n- Trace user input to dangerous sinks\n- Check for input validation before use\n- Look for reflected XSS opportunities`;\n }\n \n if (relevance.indicators.includes('command execution')) {\n prompt += `\n- Check for command injection via user input\n- Verify shell commands are properly escaped\n- Look for path traversal in file operations`;\n }\n\n prompt += `\n\nIf no significant vulnerabilities are found, respond with:\n\"No significant security issues found in this file.\"`;\n\n return prompt;\n }\n\n /**\n * Process AI request and also check for critical patterns\n */\n protected override async processAIRequest(request: AIAnalysisRequest): Promise<Issue[]> {\n const issues: Issue[] = [];\n const fileName = basename(request.file);\n \n // First: Check for critical patterns that don't need AI\n const content = request.code;\n const lines = content.split('\\n');\n \n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n \n for (const { pattern, severity, issue, fix } of CRITICAL_PATTERNS) {\n if (pattern.test(line)) {\n this.progress?.found(severity, `${issue} at line ${i + 1}`);\n issues.push(this.createIssue(\n this.generateIssueId(),\n severity,\n issue,\n fix,\n request.file,\n i + 1,\n 0.98,\n undefined,\n true\n ));\n }\n }\n }\n\n // Then: Generate AI analysis prompt for deeper review\n this.progress?.aiReview(`${fileName} - deep security analysis`);\n \n // The AI analysis will be included in the output for Claude to process\n // We create a special issue type that contains the prompt\n const aiIssue: Issue & { aiPrompt?: { system: string; user: string } } = {\n id: this.generateIssueId(),\n severity: 'moderate',\n issue: `๐Ÿง  AI Security Analysis: ${fileName}`,\n fix: 'See AI analysis below',\n file: request.file,\n confidence: 1.0,\n autoFixable: false,\n agent: this.name,\n effort: 'medium',\n aiPrompt: {\n system: request.systemPrompt,\n user: request.userPrompt\n }\n };\n \n issues.push(aiIssue);\n \n return issues;\n }\n\n /**\n * Legacy pattern-based analysis - kept minimal for backwards compatibility\n * Now only catches the most obvious issues as a fallback\n */\n protected override async analyzeFiles(_files: string[], _context: ScanContext): Promise<Issue[]> {\n // Legacy analysis is now minimal - most work is done in AI-first flow\n // This only catches issues that slip through if AI analysis is skipped\n return [];\n }\n}\n","import { BaseAgent, AIAnalysisRequest, FileRelevance } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\nimport { basename } from 'path';\n\n/**\n * Privacy relevance indicators\n */\nconst PRIVACY_INDICATORS = {\n high: [\n { pattern: /email|phone|ssn|social.*security|passport|driver.*license/i, reason: 'PII fields' },\n { pattern: /patient|medical|diagnosis|medication|treatment|symptom/i, reason: 'PHI/health data' },\n { pattern: /credit.*card|card.*number|cvv|expiry/i, reason: 'payment data' },\n { pattern: /password|credential|secret|token/i, reason: 'credentials' },\n { pattern: /gdpr|hipaa|ccpa|coppa|consent/i, reason: 'compliance mentions' },\n ],\n medium: [\n { pattern: /user.*data|personal.*info|profile/i, reason: 'user data' },\n { pattern: /birth.*date|age|dob/i, reason: 'age data (COPPA)' },\n { pattern: /address|location|geo/i, reason: 'location data' },\n { pattern: /cookie|localStorage|sessionStorage/i, reason: 'client storage' },\n { pattern: /analytics|tracking|pixel/i, reason: 'tracking' },\n ],\n low: [\n { pattern: /name|firstName|lastName/i, reason: 'names' },\n { pattern: /log|console\\.(log|error|warn)/i, reason: 'logging' },\n { pattern: /share|transfer|send.*data/i, reason: 'data transfer' },\n ]\n};\n\n/**\n * Critical privacy patterns that need immediate attention\n */\nconst CRITICAL_PRIVACY_PATTERNS = [\n { \n pattern: /console\\.log\\s*\\([^)]*password/i, \n severity: 'critical' as const, \n issue: 'Password potentially logged',\n fix: 'Remove password from log statements',\n regulation: 'GDPR Article 25'\n },\n { \n pattern: /console\\.log\\s*\\([^)]*ssn/i, \n severity: 'critical' as const, \n issue: 'SSN potentially logged',\n fix: 'Remove SSN from log statements',\n regulation: 'GDPR Article 25'\n },\n { \n pattern: /console\\.log\\s*\\([^)]*credit.*card/i, \n severity: 'critical' as const, \n issue: 'Credit card data potentially logged',\n fix: 'Remove payment data from log statements',\n regulation: 'PCI DSS'\n },\n];\n\nexport class PrivacyAgent extends BaseAgent {\n name = 'privacy';\n description = 'AI-powered privacy analysis: GDPR, HIPAA, CCPA, COPPA compliance';\n version = '2.0.0';\n\n shouldActivate(context: CodeContext): boolean {\n const hasHealthSignals = context.touchesHealthData;\n const hasUserDataSignals = context.touchesUserData && (\n context.touchesDatabase ||\n context.touchesAuth ||\n context.patterns?.hasFormHandling ||\n context.patterns?.hasEmailHandling ||\n context.touchesThirdPartyAPI\n );\n\n const fileNameSignals = context.filePatterns.some(pattern =>\n ['profile', 'account', 'customer', 'member', 'identity', 'patient'].some(keyword =>\n pattern.includes(keyword)\n )\n );\n\n return hasHealthSignals || hasUserDataSignals || (fileNameSignals && context.touchesDatabase);\n }\n\n /**\n * Check file relevance for privacy analysis\n */\n protected override checkFileRelevance(file: string, content: string): FileRelevance {\n // Skip non-code files\n if (/node_modules|\\.d\\.ts$|\\.min\\.|dist\\/|build\\/|\\.test\\.|\\.spec\\./i.test(file)) {\n return { isRelevant: false, reason: 'Skip file', priority: 'low', indicators: [] };\n }\n\n const indicators: string[] = [];\n let priority: 'high' | 'medium' | 'low' = 'low';\n\n // Check for high-priority indicators\n for (const { pattern, reason } of PRIVACY_INDICATORS.high) {\n if (pattern.test(content) || pattern.test(file)) {\n indicators.push(reason);\n priority = 'high';\n }\n }\n\n // Check medium if not already high\n if (priority !== 'high') {\n for (const { pattern, reason } of PRIVACY_INDICATORS.medium) {\n if (pattern.test(content)) {\n indicators.push(reason);\n if (priority === 'low') priority = 'medium';\n }\n }\n }\n\n // Check if it's a persistence/API file (more relevant for privacy)\n const isPersistenceFile = /(model|schema|entity|migration|prisma|mongoose|db|database)/i.test(file);\n const isApiFile = /(api|route|controller|handler|server)/i.test(file);\n \n if (isPersistenceFile || isApiFile) {\n indicators.push(isPersistenceFile ? 'data storage' : 'API endpoint');\n if (priority === 'low') priority = 'medium';\n }\n\n return {\n isRelevant: indicators.length > 0,\n reason: indicators.length > 0 ? `Contains: ${indicators.slice(0, 3).join(', ')}` : 'General review',\n priority,\n indicators\n };\n }\n\n /**\n * Get privacy-focused system prompt\n */\n protected override getSystemPrompt(): string {\n return `You are a data privacy officer and compliance expert.\nAnalyze code for privacy violations and data protection issues.\n\nKEY REGULATIONS:\n- **GDPR**: EU data protection (consent, data minimization, right to erasure)\n- **CCPA**: California privacy (disclosure, opt-out, data access)\n- **HIPAA**: Health data protection (PHI encryption, access controls)\n- **COPPA**: Children's privacy (parental consent for under 13)\n- **PCI DSS**: Payment card data security\n\nFOCUS ON:\n1. **PII Handling**: Is personal data encrypted? Properly stored?\n2. **Consent**: Is consent obtained before data collection?\n3. **Data Minimization**: Is only necessary data collected?\n4. **Logging**: Is PII being logged inappropriately?\n5. **Third-Party Sharing**: Is data shared without disclosure?\n6. **Retention**: Are there data deletion mechanisms?\n7. **Access Controls**: Who can access sensitive data?\n\nBE PRECISE:\n- Cite specific regulations when relevant\n- Explain the compliance risk\n- Provide actionable fixes\n\nSEVERITY GUIDELINES:\n- CRITICAL: Clear violation, immediate fix required, fine risk\n- SERIOUS: Likely violation, should fix before audit\n- MODERATE: Best practice violation, recommended fix\n- LOW: Minor concern, nice to have`;\n }\n\n /**\n * Build privacy-specific analysis prompt\n */\n protected override buildUserPrompt(filePath: string, content: string, relevance: FileRelevance): string {\n const isPersistenceFile = /(model|schema|entity|migration|prisma|mongoose|db|database)/i.test(filePath);\n const isApiFile = /(api|route|controller|handler|server)/i.test(filePath);\n \n let prompt = `## Privacy Compliance Audit\n\n**File:** \\`${filePath}\\`\n**Privacy indicators:** ${relevance.indicators.join(', ') || 'general review'}\n**File type:** ${isPersistenceFile ? 'Data model/storage' : isApiFile ? 'API endpoint' : 'General code'}\n\n\\`\\`\\`\n${content}\n\\`\\`\\`\n\n## Compliance Checks`;\n\n if (relevance.indicators.includes('PII fields')) {\n prompt += `\n\n### PII Data Handling\n- Is PII encrypted at rest?\n- Is PII encrypted in transit?\n- Is there data minimization (only collecting what's needed)?\n- Are there proper access controls?`;\n }\n\n if (relevance.indicators.includes('PHI/health data')) {\n prompt += `\n\n### HIPAA Compliance (Health Data)\n- Is PHI encrypted with AES-256 or equivalent?\n- Are there audit logs for PHI access?\n- Is there access control based on roles?\n- Is there a breach notification mechanism?`;\n }\n\n if (relevance.indicators.includes('payment data')) {\n prompt += `\n\n### PCI DSS Compliance (Payment Data)\n- Is card data encrypted?\n- Is CVV NOT being stored?\n- Are there access controls?\n- Is data properly tokenized?`;\n }\n\n if (relevance.indicators.includes('age data (COPPA)')) {\n prompt += `\n\n### COPPA Compliance (Children's Data)\n- Is age verified before data collection?\n- Is parental consent obtained for under 13?\n- Is data from children handled specially?`;\n }\n\n if (relevance.indicators.includes('tracking') || relevance.indicators.includes('client storage')) {\n prompt += `\n\n### Cookie/Tracking Consent\n- Is consent obtained before tracking?\n- Is there a cookie consent banner?\n- Are analytics loaded conditionally on consent?`;\n }\n\n prompt += `\n\nFor each issue found, provide:\n1. **Severity** (critical/serious/moderate/low)\n2. **Line number** (if applicable)\n3. **Regulation** violated (GDPR Article X, HIPAA ยงX, etc.)\n4. **Description** of the privacy risk\n5. **Fix** with specific code or process changes\n\nIf no privacy issues found, respond with:\n\"No significant privacy compliance issues found in this file.\"`;\n\n return prompt;\n }\n\n /**\n * Process AI request and check for critical patterns\n */\n protected override async processAIRequest(request: AIAnalysisRequest): Promise<Issue[]> {\n const issues: Issue[] = [];\n const fileName = basename(request.file);\n const content = request.code;\n const lines = content.split('\\n');\n\n // Check for critical privacy patterns\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n \n for (const { pattern, severity, issue, fix, regulation } of CRITICAL_PRIVACY_PATTERNS) {\n if (pattern.test(line)) {\n this.progress?.found(severity, `${issue} at line ${i + 1}`);\n issues.push(this.createIssue(\n this.generateIssueId(),\n severity,\n issue,\n fix,\n request.file,\n i + 1,\n 0.95,\n regulation,\n true\n ));\n }\n }\n }\n\n // Generate AI analysis prompt\n this.progress?.aiReview(`${fileName} - privacy compliance analysis`);\n \n const aiIssue: Issue & { aiPrompt?: { system: string; user: string } } = {\n id: this.generateIssueId(),\n severity: 'moderate',\n issue: `๐Ÿง  AI Privacy Analysis: ${fileName}`,\n fix: 'See AI analysis below',\n file: request.file,\n confidence: 1.0,\n autoFixable: false,\n agent: this.name,\n effort: 'medium',\n aiPrompt: {\n system: request.systemPrompt,\n user: request.userPrompt\n }\n };\n \n issues.push(aiIssue);\n return issues;\n }\n\n /**\n * Legacy pattern-based analysis - now minimal\n */\n protected async analyzeFiles(_files: string[], _context: ScanContext): Promise<Issue[]> {\n return [];\n }\n}\n","import { BaseAgent } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\nimport { extname } from 'path';\n\n/**\n * Files to always skip type checking\n */\nconst SKIP_FILES = [\n /node_modules\\//,\n /\\.d\\.ts$/,\n /\\.min\\.[jt]s$/,\n /dist\\//,\n /build\\//,\n /\\.test\\.[jt]sx?$/,\n /\\.spec\\.[jt]sx?$/,\n];\n\nexport class TypeCheckAgent extends BaseAgent {\n name = 'typecheck';\n description = 'Catches type errors and ensures type safety';\n version = '1.0.0';\n\n shouldActivate(_context: CodeContext): boolean {\n // TypeCheck runs for all TypeScript/JavaScript files\n return true;\n }\n\n protected async analyzeFiles(files: string[], _context: ScanContext): Promise<Issue[]> {\n const issues: Issue[] = [];\n\n for (const file of files) {\n // Skip files that shouldn't be type-checked\n if (SKIP_FILES.some(pattern => pattern.test(file))) {\n continue;\n }\n \n try {\n const ext = extname(file);\n if (['.ts', '.tsx', '.js', '.jsx'].includes(ext)) {\n const content = await this.readFile(file);\n // DISABLED: TypeScript programmatic checking produces too many false positives\n // because we don't have access to the project's tsconfig.json, node_modules, etc.\n // Instead, rely on pattern-based checks only\n // issues.push(...await this.analyzeTypeScript(content, file));\n issues.push(...await this.analyzeCommonPatterns(content, file));\n }\n } catch (error) {\n console.error(`TypeCheck Agent: Error reading file ${file}:`, error);\n }\n }\n\n return issues;\n }\n\n private async analyzeCommonPatterns(content: string, filePath: string): Promise<Issue[]> {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const lineNumber = i + 1;\n const trimmedLine = line.trim();\n \n // Skip comments\n if (trimmedLine.startsWith('//') || trimmedLine.startsWith('*') || trimmedLine.startsWith('/*')) {\n continue;\n }\n\n // Only check for the most important, low-noise patterns\n issues.push(...this.checkDangerousAnyTypes(line, filePath, lineNumber));\n }\n\n return issues;\n }\n\n /**\n * Only flag 'any' in dangerous contexts - not every usage\n */\n private checkDangerousAnyTypes(line: string, file: string, lineNumber: number): Issue[] {\n const issues: Issue[] = [];\n \n // Skip if there's an eslint-disable comment\n if (/eslint-disable|@ts-ignore|@ts-expect-error/.test(line)) {\n return issues;\n }\n\n // Only flag 'any' in security-sensitive contexts\n const dangerousAnyPatterns = [\n { pattern: /password.*:\\s*any/i, reason: 'password with any type' },\n { pattern: /token.*:\\s*any/i, reason: 'token with any type' },\n { pattern: /credential.*:\\s*any/i, reason: 'credential with any type' },\n { pattern: /auth.*:\\s*any/i, reason: 'auth data with any type' },\n { pattern: /user.*:\\s*any.*=.*req\\./i, reason: 'user input with any type' },\n ];\n \n for (const { pattern, reason } of dangerousAnyPatterns) {\n if (pattern.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n `Security-sensitive data typed as \"any\": ${reason}`,\n 'Add proper type annotation to ensure type safety for sensitive data',\n file,\n lineNumber,\n 0.85,\n undefined,\n false\n ));\n break;\n }\n }\n\n return issues;\n }\n\n}","import { BaseAgent } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\n\nexport class ComprehensionAgent extends BaseAgent {\n name = 'comprehension';\n description = 'Explains what code does in plain language for non-technical builders';\n version = '1.0.0';\n\n shouldActivate(_context: CodeContext): boolean {\n // Comprehension always runs to help non-technical users understand code\n return true;\n }\n\n protected async analyzeFiles(files: string[], _context: ScanContext): Promise<Issue[]> {\n // Comprehension agent doesn't generate \"issues\" per se,\n // but rather explanations. For now, we'll create explanatory \"issues\"\n const issues: Issue[] = [];\n\n try {\n const summary = await this.generateCodeSummary(files);\n\n // Create a special \"issue\" that's actually an explanation\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low', // Low severity since it's not really an issue\n 'Code Explanation Available',\n summary,\n files.join(', '),\n undefined,\n 1.0,\n undefined,\n false\n ));\n\n } catch (error) {\n console.error('Comprehension Agent: Error generating explanation:', error);\n }\n\n return issues;\n }\n\n private async generateCodeSummary(files: string[]): Promise<string> {\n let summary = '๐Ÿ“– **WHAT THIS CODE DOES**\\n\\n';\n\n // Analyze what the code appears to be doing based on files and patterns\n const features = this.identifyFeatures(files);\n\n if (features.length > 0) {\n summary += `**Features Detected:**\\n`;\n features.forEach(feature => {\n summary += `- ${feature}\\n`;\n });\n summary += '\\n';\n }\n\n // Identify potential user flows\n const flows = this.identifyUserFlows(files);\n if (flows.length > 0) {\n summary += `**User Flows:**\\n`;\n flows.forEach((flow, index) => {\n summary += `${index + 1}. ${flow}\\n`;\n });\n summary += '\\n';\n }\n\n // Identify potential risks or things to be aware of\n const risks = this.identifyRisks(files);\n if (risks.length > 0) {\n summary += `**What Could Go Wrong:**\\n`;\n risks.forEach(risk => {\n summary += `- ${risk}\\n`;\n });\n summary += '\\n';\n }\n\n // Add technical context for developers\n summary += this.generateTechnicalContext(files);\n\n return summary;\n }\n\n private identifyFeatures(files: string[]): string[] {\n const features: string[] = [];\n const filePatterns = files.map(f => f.toLowerCase()).join(' ');\n\n // Authentication features\n if (/(auth|login|signup|register|session)/.test(filePatterns)) {\n features.push('User Authentication (login/signup system)');\n }\n\n // Payment features\n if (/(payment|stripe|billing|checkout|subscription)/.test(filePatterns)) {\n features.push('Payment Processing (handles money transactions)');\n }\n\n // Database features\n if (/(model|schema|database|migration)/.test(filePatterns)) {\n features.push('Data Storage (saves information to database)');\n }\n\n // API features\n if (/(api|route|endpoint|controller)/.test(filePatterns)) {\n features.push('API Endpoints (handles requests from frontend)');\n }\n\n // UI features\n if (/(component|page|ui|frontend)/.test(filePatterns)) {\n features.push('User Interface (what users see and interact with)');\n }\n\n // Email features\n if (/(email|mail|notification|smtp)/.test(filePatterns)) {\n features.push('Email System (sends emails to users)');\n }\n\n // File upload features\n if (/(upload|file|storage|s3|blob)/.test(filePatterns)) {\n features.push('File Upload (lets users upload documents/images)');\n }\n\n return features;\n }\n\n private identifyUserFlows(files: string[]): string[] {\n const flows: string[] = [];\n const filePatterns = files.map(f => f.toLowerCase()).join(' ');\n\n // Common user flows based on file patterns\n if (/(signup|register)/.test(filePatterns)) {\n flows.push('User signs up โ†’ Creates account โ†’ Gets welcome email');\n }\n\n if (/(login|auth)/.test(filePatterns)) {\n flows.push('User logs in โ†’ System verifies credentials โ†’ Creates session');\n }\n\n if (/(checkout|payment)/.test(filePatterns)) {\n flows.push('User adds payment info โ†’ System processes payment โ†’ Sends receipt');\n }\n\n if (/(profile|settings)/.test(filePatterns)) {\n flows.push('User updates profile โ†’ System saves changes โ†’ Shows confirmation');\n }\n\n if (/(forgot|reset.*password)/.test(filePatterns)) {\n flows.push('User forgets password โ†’ Gets reset email โ†’ Sets new password');\n }\n\n if (/(contact|support)/.test(filePatterns)) {\n flows.push('User submits contact form โ†’ System sends email โ†’ Support team responds');\n }\n\n return flows;\n }\n\n private identifyRisks(files: string[]): string[] {\n const risks: string[] = [];\n const filePatterns = files.map(f => f.toLowerCase()).join(' ');\n\n if (/(auth|login|password)/.test(filePatterns)) {\n risks.push('If password security is weak โ†’ Account takeovers possible');\n risks.push('If session management is poor โ†’ Users stay logged in forever');\n }\n\n if (/(payment|stripe|billing)/.test(filePatterns)) {\n risks.push('If payment fails โ†’ User charged but no product delivered');\n risks.push('If validation is missing โ†’ Fraudulent transactions possible');\n }\n\n if (/(database|query|sql)/.test(filePatterns)) {\n risks.push('If SQL injection exists โ†’ Hackers can access all data');\n risks.push('If backups fail โ†’ Data loss if server crashes');\n }\n\n if (/(api|endpoint|route)/.test(filePatterns)) {\n risks.push('If rate limiting missing โ†’ Server overload from spam');\n risks.push('If authentication skipped โ†’ Unauthorized data access');\n }\n\n if (/(email|mail|smtp)/.test(filePatterns)) {\n risks.push('If email service down โ†’ Users don\\'t get important notifications');\n risks.push('If templates broken โ†’ Emails look unprofessional');\n }\n\n return risks;\n }\n\n private generateTechnicalContext(files: string[]): string {\n let context = '**Technical Details:**\\n';\n\n const frameworks = this.detectFrameworks(files);\n if (frameworks.length > 0) {\n context += `- Built with: ${frameworks.join(', ')}\\n`;\n }\n\n const languages = this.detectLanguages(files);\n if (languages.length > 0) {\n context += `- Programming languages: ${languages.join(', ')}\\n`;\n }\n\n const databases = this.detectDatabases(files);\n if (databases.length > 0) {\n context += `- Database: ${databases.join(', ')}\\n`;\n }\n\n context += `- Files analyzed: ${files.length}\\n`;\n\n return context;\n }\n\n private detectFrameworks(files: string[]): string[] {\n const frameworks: string[] = [];\n const patterns = files.join(' ').toLowerCase();\n\n if (/(react|jsx|tsx)/.test(patterns)) frameworks.push('React');\n if (/(vue|\\.vue)/.test(patterns)) frameworks.push('Vue.js');\n if (/(angular|ng)/.test(patterns)) frameworks.push('Angular');\n if (/(express|app\\.js)/.test(patterns)) frameworks.push('Express.js');\n if (/(next|nextjs)/.test(patterns)) frameworks.push('Next.js');\n if (/(nuxt)/.test(patterns)) frameworks.push('Nuxt.js');\n if (/(svelte)/.test(patterns)) frameworks.push('Svelte');\n\n return frameworks;\n }\n\n private detectLanguages(files: string[]): string[] {\n const languages = new Set<string>();\n\n files.forEach(file => {\n const ext = file.split('.').pop()?.toLowerCase();\n switch (ext) {\n case 'ts':\n case 'tsx':\n languages.add('TypeScript');\n break;\n case 'js':\n case 'jsx':\n languages.add('JavaScript');\n break;\n case 'py':\n languages.add('Python');\n break;\n case 'java':\n languages.add('Java');\n break;\n case 'go':\n languages.add('Go');\n break;\n case 'rs':\n languages.add('Rust');\n break;\n case 'php':\n languages.add('PHP');\n break;\n }\n });\n\n return Array.from(languages);\n }\n\n private detectDatabases(files: string[]): string[] {\n const databases: string[] = [];\n const patterns = files.join(' ').toLowerCase();\n\n if (/(postgres|pg|postgresql)/.test(patterns)) databases.push('PostgreSQL');\n if (/(mysql)/.test(patterns)) databases.push('MySQL');\n if (/(mongo|mongodb)/.test(patterns)) databases.push('MongoDB');\n if (/(redis)/.test(patterns)) databases.push('Redis');\n if (/(sqlite)/.test(patterns)) databases.push('SQLite');\n if (/(prisma)/.test(patterns)) databases.push('Prisma ORM');\n if (/(sequelize)/.test(patterns)) databases.push('Sequelize ORM');\n\n return databases;\n }\n}","import { BaseAgent } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\n\nexport class DesignEngineerAgent extends BaseAgent {\n name = 'design-engineer';\n description = 'WCAG 2.1 accessibility compliance, visual polish, and UX best practices';\n version = '1.0.0';\n\n shouldActivate(context: CodeContext): boolean {\n return context.touchesUI;\n }\n\n protected async analyzeFiles(files: string[], _context: ScanContext): Promise<Issue[]> {\n const issues: Issue[] = [];\n\n for (const file of files) {\n try {\n const content = await this.readFile(file);\n issues.push(...this.analyzeAccessibility(content, file));\n issues.push(...this.analyzeUXPatterns(content, file));\n } catch (error) {\n console.error(`Design Engineer Agent: Error reading file ${file}:`, error);\n }\n }\n\n return issues;\n }\n\n private analyzeAccessibility(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const lineNumber = i + 1;\n\n // Check for images without alt text\n if (/<img[^>]*(?!alt=)[^>]*>/i.test(line) && !line.includes('alt=')) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Image missing alt attribute',\n 'Add descriptive alt text for screen readers: alt=\"description\"',\n file,\n lineNumber,\n 0.95,\n 'WCAG 2.1 - 1.1.1 Non-text Content',\n true\n ));\n }\n\n // Check for click handlers without keyboard support\n if (/onClick.*(?!onKeyDown|onKeyPress|onKeyUp)/i.test(line) && !/button|Button|<a /i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Click handler without keyboard equivalent',\n 'Add onKeyDown handler for keyboard accessibility',\n file,\n lineNumber,\n 0.80,\n 'WCAG 2.1 - 2.1.1 Keyboard',\n true\n ));\n }\n\n // Check for missing form labels\n if (/<input[^>]*(?!aria-label|id.*label)/i.test(line) && !/<label/i.test(lines.slice(Math.max(0, i-2), i+2).join(''))) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Form input may be missing accessible label',\n 'Associate input with <label> element or use aria-label',\n file,\n lineNumber,\n 0.70,\n 'WCAG 2.1 - 1.3.1 Info and Relationships',\n true\n ));\n }\n\n // Check for hardcoded colors (accessibility concern)\n if (/color:\\s*['\"]?#[0-9a-fA-F]{3,6}/i.test(line) || /color:\\s*['\"]?rgb\\(/i.test(line)) {\n // Only flag if it looks like low contrast (simplified check)\n if (/#fff|#FFF|white|#000|#333|gray/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Potential color contrast issue',\n 'Ensure color contrast ratio meets WCAG AA (4.5:1 for normal text)',\n file,\n lineNumber,\n 0.60,\n 'WCAG 2.1 - 1.4.3 Contrast',\n false\n ));\n }\n }\n\n // Check for focus outline removal\n if (/outline:\\s*none|outline:\\s*0/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Focus outline removed - breaks keyboard navigation',\n 'Provide alternative focus indicator instead of removing outline',\n file,\n lineNumber,\n 0.90,\n 'WCAG 2.1 - 2.4.7 Focus Visible',\n true\n ));\n }\n }\n\n return issues;\n }\n\n private analyzeUXPatterns(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const lineNumber = i + 1;\n\n // Check for disabled buttons without explanation\n if (/disabled(?!=\\{false\\})/i.test(line) && !/title=|aria-describedby/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Disabled element without explanation',\n 'Add tooltip or text explaining why the action is unavailable',\n file,\n lineNumber,\n 0.70,\n undefined,\n true\n ));\n }\n\n // Check for placeholder-only inputs\n if (/placeholder=/i.test(line) && !/<label|aria-label/i.test(lines.slice(Math.max(0, i-2), i+2).join(''))) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Input uses placeholder as only label',\n 'Add visible label - placeholder disappears when user types',\n file,\n lineNumber,\n 0.75,\n undefined,\n true\n ));\n }\n\n // Check for empty links\n if (/<a[^>]*>\\s*<\\/a>/i.test(line) || /href=['\"]#['\"]/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Empty or placeholder link',\n 'Add meaningful href and link text',\n file,\n lineNumber,\n 0.85,\n 'WCAG 2.1 - 2.4.4 Link Purpose',\n true\n ));\n }\n }\n\n return issues;\n }\n}\n\n","import { BaseAgent } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\n\nexport class LegalAgent extends BaseAgent {\n name = 'legal';\n description = 'Compliance with GDPR, CCPA, data protection laws, and legal requirements';\n version = '1.0.0';\n\n shouldActivate(context: CodeContext): boolean {\n return (\n context.touchesUserData ||\n context.touchesHealthData ||\n context.touchesPayments ||\n context.touchesAuth\n );\n }\n\n protected async analyzeFiles(files: string[], _context: ScanContext): Promise<Issue[]> {\n const issues: Issue[] = [];\n\n for (const file of files) {\n try {\n const content = await this.readFile(file);\n issues.push(...this.checkGDPRCompliance(content, file));\n issues.push(...this.checkDataRetention(content, file));\n issues.push(...this.checkConsentPatterns(content, file));\n } catch (error) {\n console.error(`Legal Agent: Error reading file ${file}:`, error);\n }\n }\n\n return issues;\n }\n\n private checkGDPRCompliance(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const lineNumber = i + 1;\n\n // Check for data collection without consent flag\n if (/email|phone|address|name|birthdate|ssn/i.test(line) && \n /save|store|insert|create|post/i.test(line) &&\n !/consent|gdpr|terms/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Personal data collection without consent verification',\n 'Implement consent collection before storing PII (GDPR Article 6)',\n file,\n lineNumber,\n 0.75,\n 'GDPR Article 6 - Lawfulness of processing',\n false\n ));\n }\n\n // Check for analytics/tracking without consent\n if (/analytics|gtag|fbq|pixel|tracking/i.test(line) && !/consent|optIn|cookie/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Analytics/tracking without consent management',\n 'Implement cookie consent banner before loading tracking scripts',\n file,\n lineNumber,\n 0.80,\n 'GDPR Article 7 / ePrivacy Directive',\n false\n ));\n }\n\n // Check for data export capability\n if (/userData|userProfile|account/i.test(line) && /get|fetch|query/i.test(line)) {\n // This is informational - checking if export exists\n const hasExport = /export|download|portability/i.test(content);\n if (!hasExport) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Consider implementing data portability',\n 'Users have right to export their data (GDPR Article 20)',\n file,\n undefined,\n 0.60,\n 'GDPR Article 20 - Right to data portability',\n false\n ));\n }\n }\n }\n\n return issues;\n }\n\n private checkDataRetention(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n\n // Check for indefinite data storage\n if (/store|save|persist|database|collection/i.test(content) &&\n !/delete|expire|retention|ttl|expiresAt|deletedAt/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'No data retention/deletion policy detected',\n 'Implement data retention limits and deletion procedures',\n file,\n undefined,\n 0.70,\n 'GDPR Article 5(1)(e) - Storage limitation',\n false\n ));\n }\n\n // Check for soft delete without actual deletion\n if (/deletedAt|isDeleted|softDelete/i.test(content) && !/hardDelete|permanentDelete|purge/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Soft delete without hard delete option',\n 'Consider implementing permanent deletion for GDPR right to erasure',\n file,\n undefined,\n 0.65,\n 'GDPR Article 17 - Right to erasure',\n false\n ));\n }\n\n return issues;\n }\n\n private checkConsentPatterns(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const lineNumber = i + 1;\n\n // Check for pre-checked consent\n if (/checked|defaultChecked|defaultValue.*true/i.test(line) && \n /consent|newsletter|marketing|terms/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Pre-checked consent box detected',\n 'Consent must be freely given - remove default checked state',\n file,\n lineNumber,\n 0.85,\n 'GDPR Recital 32 - Consent should not be pre-ticked',\n true\n ));\n }\n\n // Check for bundled consent\n if (/&&.*&&/i.test(line) && /consent|agree|accept/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Potentially bundled consent conditions',\n 'Separate consents for different purposes (GDPR granular consent)',\n file,\n lineNumber,\n 0.60,\n 'GDPR Article 7 - Conditions for consent',\n false\n ));\n }\n }\n\n return issues;\n }\n}\n\n","import { BaseAgent } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\nimport { basename, dirname } from 'path';\nimport { existsSync } from 'fs';\n\nexport class TestAgent extends BaseAgent {\n name = 'test';\n description = 'Test coverage analysis, test quality, and testing best practices';\n version = '1.0.0';\n\n shouldActivate(context: CodeContext): boolean {\n return (\n context.isNewFeature ||\n context.touchesAuth ||\n context.touchesPayments ||\n context.touchesAPI\n );\n }\n\n protected async analyzeFiles(files: string[], context: ScanContext): Promise<Issue[]> {\n const issues: Issue[] = [];\n\n for (const file of files) {\n // Skip test files themselves\n if (/\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(file)) {\n continue;\n }\n\n try {\n const content = await this.readFile(file);\n issues.push(...this.checkTestCoverage(file, content, context));\n issues.push(...this.checkTestablePatterns(content, file));\n } catch (error) {\n console.error(`Test Agent: Error reading file ${file}:`, error);\n }\n }\n\n return issues;\n }\n\n private checkTestCoverage(file: string, content: string, _context: ScanContext): Issue[] {\n const issues: Issue[] = [];\n const fileName = basename(file);\n const fileDir = dirname(file);\n\n // Check if corresponding test file exists\n const testPatterns = [\n file.replace(/\\.(ts|js|tsx|jsx)$/, '.test.$1'),\n file.replace(/\\.(ts|js|tsx|jsx)$/, '.spec.$1'),\n `${fileDir}/__tests__/${fileName}`,\n `${fileDir}/../__tests__/${fileName}`,\n ];\n\n const hasTestFile = testPatterns.some(pattern => existsSync(pattern));\n\n if (!hasTestFile) {\n // Determine severity based on what the file does\n const severity = this.determineTestSeverity(content);\n \n issues.push(this.createIssue(\n this.generateIssueId(),\n severity,\n `No test file found for ${fileName}`,\n `Create test file: ${fileName.replace(/\\.(ts|js|tsx|jsx)$/, '.test.$1')}`,\n file,\n undefined,\n 0.85,\n undefined,\n false\n ));\n }\n\n return issues;\n }\n\n private determineTestSeverity(content: string): Issue['severity'] {\n // Critical code needs tests\n if (/password|auth|payment|stripe|billing|credit/i.test(content)) {\n return 'serious';\n }\n if (/api|endpoint|route|handler/i.test(content)) {\n return 'moderate';\n }\n return 'low';\n }\n\n private checkTestablePatterns(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n // Count exported functions/classes\n const exports = content.match(/export\\s+(function|class|const|async function)/g);\n const exportCount = exports?.length || 0;\n\n // Check for complex functions that should be tested\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const lineNumber = i + 1;\n\n // Check for complex conditionals\n if ((line.match(/if|else|switch|\\?.*:/g) || []).length >= 3) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Complex conditional logic should have unit tests',\n 'Write tests covering different branches of this logic',\n file,\n lineNumber,\n 0.70,\n undefined,\n false\n ));\n }\n\n // Check for error handling that should be tested\n if (/catch\\s*\\(|\\.catch\\(/.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Error handling path should be tested',\n 'Write tests that trigger and verify error handling behavior',\n file,\n lineNumber,\n 0.65,\n undefined,\n false\n ));\n }\n\n // Check for async operations\n if (/async\\s+function|await\\s+/.test(line) && /fetch|axios|database|query/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Async operation should have integration tests',\n 'Mock external dependencies and test async behavior',\n file,\n lineNumber,\n 0.75,\n undefined,\n false\n ));\n }\n }\n\n // Warn about high export count without tests\n if (exportCount > 5) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n `${exportCount} exports detected - high test coverage recommended`,\n 'Create comprehensive test suite for all exported functions',\n file,\n undefined,\n 0.80,\n undefined,\n false\n ));\n }\n\n return issues;\n }\n}\n\n","import { BaseAgent } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\n\nexport class SoftwareArchitectAgent extends BaseAgent {\n name = 'software-architect';\n description = 'Architecture patterns, code organization, SOLID principles, and scalability';\n version = '1.0.0';\n\n shouldActivate(context: CodeContext): boolean {\n return (\n context.isNewFeature ||\n context.touchesDatabase ||\n context.touchesAPI ||\n context.linesChanged > 200\n );\n }\n\n protected async analyzeFiles(files: string[], _context: ScanContext): Promise<Issue[]> {\n const issues: Issue[] = [];\n\n for (const file of files) {\n try {\n const content = await this.readFile(file);\n issues.push(...this.checkArchitecturePatterns(content, file));\n issues.push(...this.checkCodeOrganization(content, file));\n issues.push(...this.checkScalabilityIssues(content, file));\n } catch (error) {\n console.error(`Software Architect Agent: Error reading file ${file}:`, error);\n }\n }\n\n return issues;\n }\n\n private checkArchitecturePatterns(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const lineNumber = i + 1;\n\n // Check for direct database access in UI components\n if (/\\.(tsx|jsx)$/.test(file) && /prisma|mongoose|sequelize|typeorm|query|SELECT/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Direct database access in UI component',\n 'Move database logic to API layer or server action',\n file,\n lineNumber,\n 0.90,\n undefined,\n false\n ));\n }\n\n // Check for business logic in controllers/handlers\n if (/controller|handler|route/i.test(file) && lines.slice(i, i + 20).join('\\n').split('if').length > 5) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Complex business logic in controller',\n 'Extract business logic to a service layer',\n file,\n lineNumber,\n 0.70,\n undefined,\n false\n ));\n }\n\n // Check for god classes/files\n if (lines.length > 500 && i === 0) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n `Large file detected (${lines.length} lines)`,\n 'Consider splitting into smaller, focused modules',\n file,\n undefined,\n 0.80,\n undefined,\n false\n ));\n }\n\n // Check for circular dependency patterns\n if (/import.*from\\s*['\"]\\.\\..*['\"]/g.test(line)) {\n const importPath = line.match(/from\\s*['\"]([^'\"]+)['\"]/)?.[1];\n if (importPath && importPath.includes('../../')) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Deep relative import detected',\n 'Consider using path aliases or restructuring modules',\n file,\n lineNumber,\n 0.60,\n undefined,\n true\n ));\n }\n }\n }\n\n return issues;\n }\n\n private checkCodeOrganization(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n\n // Check for mixed concerns\n const hasUI = /jsx|tsx|render|component|React|useState/i.test(content);\n const hasAPI = /fetch|axios|api|endpoint|route/i.test(content);\n const hasDB = /prisma|mongoose|query|INSERT|SELECT/i.test(content);\n \n const concernCount = [hasUI, hasAPI, hasDB].filter(Boolean).length;\n\n if (concernCount >= 2) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Multiple concerns mixed in single file',\n 'Separate UI, API, and data access layers',\n file,\n undefined,\n 0.75,\n undefined,\n false\n ));\n }\n\n // Check for missing error boundaries in React\n if (/React|useState|useEffect/i.test(content) && !/ErrorBoundary|error.*boundary/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Consider adding error boundary for React components',\n 'Wrap components in ErrorBoundary to handle render errors gracefully',\n file,\n undefined,\n 0.60,\n undefined,\n false\n ));\n }\n\n return issues;\n }\n\n private checkScalabilityIssues(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const lineNumber = i + 1;\n\n // Check for N+1 query patterns\n if (/for\\s*\\(|\\.forEach|\\.map/.test(line) && /await.*find|await.*query|await.*get/i.test(lines.slice(i, i + 5).join('\\n'))) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Potential N+1 query pattern',\n 'Use batch fetching or include/join to avoid multiple queries in loop',\n file,\n lineNumber,\n 0.80,\n undefined,\n false\n ));\n }\n\n // Check for unbounded queries\n if (/find\\(\\)|findMany\\(\\)|SELECT.*FROM.*(?!LIMIT|WHERE)/i.test(line) && !/limit|take|LIMIT/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Unbounded database query',\n 'Add pagination/limit to prevent memory issues with large datasets',\n file,\n lineNumber,\n 0.75,\n undefined,\n true\n ));\n }\n\n // Check for synchronous file operations\n if (/readFileSync|writeFileSync|readdirSync/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Synchronous file operation blocks event loop',\n 'Use async alternatives: readFile, writeFile, readdir',\n file,\n lineNumber,\n 0.85,\n undefined,\n true\n ));\n }\n\n // Check for missing caching opportunities\n if (/fetch|axios\\.get|database.*find/i.test(line) && !/cache|redis|memo/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Consider caching for repeated data fetches',\n 'Implement caching strategy for frequently accessed data',\n file,\n lineNumber,\n 0.55,\n undefined,\n false\n ));\n }\n }\n\n return issues;\n }\n}\n\n","import { BaseAgent } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\n\nexport class DevOpsAgent extends BaseAgent {\n name = 'devops';\n description = 'Infrastructure, deployment, configuration, and operational concerns';\n version = '1.0.0';\n\n shouldActivate(context: CodeContext): boolean {\n return (\n context.touchesSecurityConfig ||\n context.touchesDatabase ||\n context.touchesPayments ||\n context.touchesHealthData\n );\n }\n\n protected async analyzeFiles(files: string[], _context: ScanContext): Promise<Issue[]> {\n const issues: Issue[] = [];\n\n for (const file of files) {\n try {\n const content = await this.readFile(file);\n issues.push(...this.checkEnvironmentConfig(content, file));\n issues.push(...this.checkLogging(content, file));\n issues.push(...this.checkDeploymentPatterns(content, file));\n } catch (error) {\n console.error(`DevOps Agent: Error reading file ${file}:`, error);\n }\n }\n\n return issues;\n }\n\n private checkEnvironmentConfig(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const lineNumber = i + 1;\n\n // Check for hardcoded environment-specific values\n if (/localhost|127\\.0\\.0\\.1|0\\.0\\.0\\.0/i.test(line) && !/process\\.env|import\\.meta\\.env|\\.env/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Hardcoded localhost/IP address',\n 'Use environment variables for host configuration',\n file,\n lineNumber,\n 0.80,\n undefined,\n true\n ));\n }\n\n // Check for missing environment variable validation\n if (/process\\.env\\./i.test(line) && !/\\|\\||:\\s|[?]{2}/i.test(line) && !/throw|required|assert/i.test(lines.slice(Math.max(0, i-2), i+2).join(''))) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Environment variable used without fallback/validation',\n 'Add validation or fallback: process.env.VAR || \"default\"',\n file,\n lineNumber,\n 0.70,\n undefined,\n true\n ));\n }\n\n // Check for production checks\n if (/NODE_ENV.*production|isProduction/i.test(line)) {\n // This is good - just informational\n } else if (/console\\.log|console\\.debug|debugger/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Debug statement should be removed or wrapped in development check',\n 'Use proper logging library or wrap in if (process.env.NODE_ENV !== \"production\")',\n file,\n lineNumber,\n 0.75,\n undefined,\n true\n ));\n }\n }\n\n return issues;\n }\n\n private checkLogging(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const lineNumber = i + 1;\n\n // Check for logging sensitive data\n if (/console\\.(log|info|warn|error)|logger\\./i.test(line) && \n /password|secret|token|key|credential|ssn|credit/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'critical',\n 'Potentially logging sensitive data',\n 'Remove sensitive data from logs or mask it',\n file,\n lineNumber,\n 0.85,\n undefined,\n false\n ));\n }\n\n // Check for missing error logging in catch blocks\n if (/catch\\s*\\(.*\\)\\s*\\{/.test(line)) {\n const catchBlock = lines.slice(i, Math.min(lines.length, i + 10)).join('\\n');\n if (!/console\\.|logger\\.|log\\(|error\\(/i.test(catchBlock) && !/throw/i.test(catchBlock)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Catch block without error logging',\n 'Log errors for debugging and monitoring',\n file,\n lineNumber,\n 0.75,\n undefined,\n true\n ));\n }\n }\n }\n\n // Check for structured logging\n if (/console\\.(log|info|warn|error)/i.test(content) && content.split('console.').length > 5) {\n if (!/winston|pino|bunyan|log4js/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Consider using structured logging library',\n 'Use winston, pino, or similar for production logging with levels and formatting',\n file,\n undefined,\n 0.60,\n undefined,\n false\n ));\n }\n }\n\n return issues;\n }\n\n private checkDeploymentPatterns(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const lineNumber = i + 1;\n\n // Check for health check endpoints\n if (/app\\.(get|use)|router\\.(get|use)/i.test(line) && /health|ready|live/i.test(line)) {\n // Good pattern - has health checks\n }\n\n // Check for graceful shutdown handling\n if (/SIGTERM|SIGINT|process\\.on/i.test(line)) {\n // Good pattern - handles signals\n }\n\n // Check for connection pool configuration\n if (/createPool|connectionLimit|pool/i.test(line) && !/max|limit|size/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Database connection pool without explicit limits',\n 'Configure max connections to prevent resource exhaustion',\n file,\n lineNumber,\n 0.70,\n undefined,\n true\n ));\n }\n\n // Check for timeout configuration\n if (/fetch|axios|http\\.request/i.test(line) && !/timeout/i.test(lines.slice(i, i + 3).join(''))) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'HTTP request without timeout configuration',\n 'Add timeout to prevent hanging requests',\n file,\n lineNumber,\n 0.75,\n undefined,\n true\n ));\n }\n }\n\n return issues;\n }\n}\n\n","import { BaseAgent, AIAnalysisRequest, FileRelevance } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\nimport { basename } from 'path';\n\n/**\n * Bug relevance indicators - files that need bug analysis\n */\nconst BUG_INDICATORS = {\n high: [\n { pattern: /async|await|promise/i, reason: 'async code' },\n { pattern: /try|catch|throw|error/i, reason: 'error handling' },\n { pattern: /\\.forEach|\\.map|\\.filter|\\.reduce/i, reason: 'array operations' },\n { pattern: /JSON\\.parse|JSON\\.stringify/i, reason: 'JSON operations' },\n { pattern: /null|undefined/i, reason: 'nullability' },\n ],\n medium: [\n { pattern: /parseInt|parseFloat|Number\\(/i, reason: 'number parsing' },\n { pattern: /split|slice|substring|substr/i, reason: 'string operations' },\n { pattern: /Date|new Date|moment|dayjs/i, reason: 'date handling' },\n { pattern: /setTimeout|setInterval|clearTimeout/i, reason: 'timing' },\n { pattern: /Math\\./i, reason: 'math operations' },\n ],\n low: [\n { pattern: /\\.length|\\.size/i, reason: 'collection access' },\n { pattern: /switch|case|default/i, reason: 'switch statements' },\n { pattern: /for\\s*\\(|while\\s*\\(/i, reason: 'loops' },\n ]\n};\n\n/**\n * Critical bug patterns that can be caught without AI\n */\nconst CRITICAL_BUG_PATTERNS = [\n { \n pattern: /\\.forEach\\s*\\(\\s*async/i, \n severity: 'serious' as const, \n issue: 'async callback in forEach - await will not work as expected',\n fix: 'Use for...of loop or Promise.all with map instead'\n },\n { \n pattern: /if\\s*\\(\\s*\\w+\\s*=[^=]/, \n severity: 'serious' as const, \n issue: 'Assignment in condition - likely meant to compare',\n fix: 'Use === for comparison instead of ='\n },\n];\n\nexport class BugFindingAgent extends BaseAgent {\n name = 'bug-finding';\n description = 'AI-powered bug detection: null safety, edge cases, async issues, runtime errors';\n version = '2.0.0';\n\n shouldActivate(context: CodeContext): boolean {\n return (\n context.touchesPayments ||\n context.isNewFeature ||\n context.touchesDatabase ||\n context.touchesAPI\n );\n }\n\n /**\n * Check file relevance for bug analysis\n */\n protected override checkFileRelevance(file: string, content: string): FileRelevance {\n // Skip test files, node_modules, etc.\n if (/node_modules|\\.d\\.ts$|\\.min\\.|dist\\/|build\\//.test(file)) {\n return { isRelevant: false, reason: 'Skip file', priority: 'low', indicators: [] };\n }\n\n const indicators: string[] = [];\n let priority: 'high' | 'medium' | 'low' = 'low';\n\n // Check for high-priority indicators\n for (const { pattern, reason } of BUG_INDICATORS.high) {\n if (pattern.test(content)) {\n indicators.push(reason);\n priority = 'high';\n }\n }\n\n // Check medium if not already high\n if (priority !== 'high') {\n for (const { pattern, reason } of BUG_INDICATORS.medium) {\n if (pattern.test(content)) {\n indicators.push(reason);\n if (priority === 'low') priority = 'medium';\n }\n }\n }\n\n return {\n isRelevant: content.length > 50, // Skip empty/tiny files\n reason: indicators.length > 0 ? `Contains: ${indicators.slice(0, 3).join(', ')}` : 'General review',\n priority,\n indicators\n };\n }\n\n /**\n * Get bug-hunting system prompt\n */\n protected override getSystemPrompt(): string {\n return `You are a senior developer hunting for bugs with the mindset of QA trying to break the code.\n\nFOCUS ON:\n1. **Null/Undefined Errors**: Accessing properties on potentially null values\n2. **Async/Await Bugs**: Missing awaits, async forEach, unhandled promise rejections\n3. **Edge Cases**: Empty arrays, zero values, boundary conditions\n4. **Type Coercion**: Loose equality, implicit type conversions\n5. **Resource Leaks**: Unclosed connections, timers not cleared\n6. **Race Conditions**: State changes between checks and uses\n7. **Error Handling**: Missing try-catch, swallowed errors\n\nBE PRECISE:\n- Only report bugs you're confident about\n- Provide exact line numbers\n- Explain the trigger condition (when this bug would occur)\n- Give specific fixes\n\nSEVERITY GUIDELINES:\n- CRITICAL: Will crash in production or corrupt data\n- SERIOUS: Will cause incorrect behavior under common conditions\n- MODERATE: Will cause issues in edge cases\n- LOW: Code smell that could become a bug`;\n }\n\n /**\n * Build bug-focused analysis prompt\n */\n protected override buildUserPrompt(filePath: string, content: string, relevance: FileRelevance): string {\n const isTestFile = /\\.(test|spec)\\.[jt]sx?$/.test(filePath);\n \n return `## Bug Hunt Analysis\n\n**File:** \\`${filePath}\\`\n**Code patterns:** ${relevance.indicators.join(', ') || 'general analysis'}\n${isTestFile ? '**Note:** This is a test file - focus on test correctness.' : ''}\n\n\\`\\`\\`\n${content}\n\\`\\`\\`\n\n## Find These Bug Types\n\n${relevance.indicators.includes('async code') ? `\n### Async/Await Issues\n- Missing await keywords\n- async forEach (won't await properly)\n- Unhandled promise rejections\n- Race conditions in async code\n` : ''}\n\n${relevance.indicators.includes('error handling') ? `\n### Error Handling Bugs\n- Swallowed errors (empty catch blocks)\n- Missing try-catch around throwing code\n- Error handling that doesn't re-throw or handle properly\n` : ''}\n\n${relevance.indicators.includes('JSON operations') ? `\n### JSON Bugs\n- JSON.parse without try-catch\n- Circular reference issues\n- Invalid JSON handling\n` : ''}\n\n${relevance.indicators.includes('nullability') ? `\n### Null Safety Issues\n- Optional chaining needed\n- Null checks before property access\n- Default value handling\n` : ''}\n\nFor each bug, provide:\n1. **Line number**\n2. **Severity** (critical/serious/moderate/low)\n3. **Bug description**\n4. **Trigger condition** (when would this crash?)\n5. **Fix**\n\nIf no significant bugs found, respond with:\n\"No significant bugs found in this file.\"`;\n }\n\n /**\n * Process AI request and check for critical patterns\n */\n protected override async processAIRequest(request: AIAnalysisRequest): Promise<Issue[]> {\n const issues: Issue[] = [];\n const fileName = basename(request.file);\n const content = request.code;\n const lines = content.split('\\n');\n\n // Check for critical bug patterns that don't need AI\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n \n for (const { pattern, severity, issue, fix } of CRITICAL_BUG_PATTERNS) {\n if (pattern.test(line)) {\n this.progress?.found(severity, `${issue} at line ${i + 1}`);\n issues.push(this.createIssue(\n this.generateIssueId(),\n severity,\n issue,\n fix,\n request.file,\n i + 1,\n 0.95,\n undefined,\n true\n ));\n }\n }\n }\n\n // Generate AI analysis prompt for deeper review\n this.progress?.aiReview(`${fileName} - deep bug analysis`);\n \n const aiIssue: Issue & { aiPrompt?: { system: string; user: string } } = {\n id: this.generateIssueId(),\n severity: 'moderate',\n issue: `๐Ÿง  AI Bug Analysis: ${fileName}`,\n fix: 'See AI analysis below',\n file: request.file,\n confidence: 1.0,\n autoFixable: false,\n agent: this.name,\n effort: 'medium',\n aiPrompt: {\n system: request.systemPrompt,\n user: request.userPrompt\n }\n };\n \n issues.push(aiIssue);\n return issues;\n }\n\n /**\n * Legacy pattern-based analysis - now minimal\n */\n protected async analyzeFiles(_files: string[], _context: ScanContext): Promise<Issue[]> {\n return [];\n }\n}\n","import { BaseAgent } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext, AgentPriority } from '../types/index.js';\n\n/**\n * User Testing Agent\n * \n * Simulates different user personas to find vulnerabilities and UX issues:\n * 1. Happy Path User - Normal usage, expects things to work\n * 2. Security Tester - Tries to break things, malicious inputs\n * 3. Confused User - Makes mistakes, misunderstands UI, accessibility needs\n * 4. Impatient User - Rapid clicks, doesn't wait, closes mid-action\n * 5. Edge Case User - Empty inputs, max lengths, special characters\n */\nexport class UserTestingAgent extends BaseAgent {\n name = 'user-testing';\n description = 'Simulates user personas (happy path, security tester, confused user) to find vulnerabilities';\n version = '2.0.0';\n\n override get priority(): AgentPriority {\n return {\n name: this.name,\n tier: 2,\n estimatedTimeMs: 150,\n dependencies: ['design-engineer'] // accessibility before UX\n };\n }\n\n shouldActivate(context: CodeContext): boolean {\n return context.touchesUI || context.isNewFeature;\n }\n\n override getActivationConfidence(context: CodeContext): number {\n let confidence = 0;\n if (context.touchesUI) confidence += 0.5;\n if (context.isNewFeature) confidence += 0.3;\n if (context.patterns?.hasFormHandling) confidence += 0.25;\n if (context.touchesAuth) confidence += 0.2;\n if (context.touchesPayments) confidence += 0.3;\n return Math.min(1.0, confidence);\n }\n\n protected async analyzeFiles(files: string[], _context: ScanContext): Promise<Issue[]> {\n const issues: Issue[] = [];\n\n for (const file of files) {\n try {\n const content = await this.readFile(file);\n \n // Simulate each user persona\n issues.push(...this.simulateHappyPathUser(content, file));\n issues.push(...this.simulateSecurityTester(content, file));\n issues.push(...this.simulateConfusedUser(content, file));\n issues.push(...this.simulateImpatientUser(content, file));\n issues.push(...this.simulateEdgeCaseUser(content, file));\n \n } catch (error) {\n console.error(`User Testing Agent: Error reading file ${file}:`, error);\n }\n }\n\n return issues;\n }\n\n /**\n * HAPPY PATH USER\n * \"I'm a normal user, I expect things to just work\"\n * Finds: Missing success feedback, broken flows, dead ends\n */\n private simulateHappyPathUser(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const lineNumber = i + 1;\n const nearbyCode = lines.slice(Math.max(0, i - 5), i + 10).join('\\n');\n\n // \"I submitted a form but nothing happened?\"\n if (/onSubmit|handleSubmit/i.test(line)) {\n if (!/toast|alert|notification|message|success|redirect|navigate|push/i.test(nearbyCode)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n '[Happy Path] Form submission has no success feedback',\n 'Show success message or redirect after form submission',\n file,\n lineNumber,\n 0.80,\n undefined,\n false,\n { category: 'user-testing:happy-path' }\n ));\n }\n }\n\n // \"I clicked a button but it didn't do anything\"\n if (/onClick|onPress/i.test(line) && !/disabled/i.test(line)) {\n if (!/loading|isLoading|pending|submitting/i.test(nearbyCode)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n '[Happy Path] Button click has no loading indicator',\n 'Add loading state to show action is in progress',\n file,\n lineNumber,\n 0.65,\n undefined,\n false,\n { category: 'user-testing:happy-path' }\n ));\n }\n }\n\n // \"I signed up but where do I go now?\"\n if (/signup|register|createAccount/i.test(line)) {\n if (!/onboard|welcome|dashboard|next.*step|redirect/i.test(nearbyCode)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n '[Happy Path] Sign-up flow may have no onboarding',\n 'Guide new users to next step after registration',\n file,\n lineNumber,\n 0.70,\n undefined,\n false,\n { category: 'user-testing:happy-path' }\n ));\n }\n }\n }\n\n return issues;\n }\n\n /**\n * SECURITY TESTER\n * \"Let me try to break this thing\"\n * Finds: XSS vulnerabilities, injection points, auth bypasses\n */\n private simulateSecurityTester(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const lineNumber = i + 1;\n\n // \"What if I put <script> in this input?\"\n if (/<input|<textarea|contentEditable/i.test(line)) {\n if (!/sanitize|escape|DOMPurify|xss/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n '[Security Tester] Input field may be vulnerable to XSS',\n 'Sanitize user input before rendering - use DOMPurify or similar',\n file,\n lineNumber,\n 0.75,\n undefined,\n false,\n { category: 'user-testing:security', owasp: 'A7:2017-XSS' }\n ));\n }\n }\n\n // \"What if I modify the hidden field?\"\n if (/type=[\"']hidden[\"']|hidden.*input/i.test(line)) {\n if (/userId|price|amount|role|admin|permission/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'critical',\n '[Security Tester] Sensitive data in hidden field can be tampered',\n 'Never trust hidden fields - validate on server side',\n file,\n lineNumber,\n 0.90,\n undefined,\n false,\n { category: 'user-testing:security', cwe: 'CWE-472' }\n ));\n }\n }\n\n // \"What if I replay this request?\"\n if (/fetch|axios|api.*call/i.test(line) && /delete|remove|transfer|payment/i.test(line)) {\n if (!/idempotency|token|nonce|csrf/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n '[Security Tester] Destructive action may be replayable',\n 'Add idempotency key or CSRF token to prevent replay attacks',\n file,\n lineNumber,\n 0.80,\n undefined,\n false,\n { category: 'user-testing:security', cwe: 'CWE-352' }\n ));\n }\n }\n\n // \"What if I access this without logging in?\"\n if (/useEffect|componentDidMount/i.test(line) && /fetch|load|get/i.test(lines.slice(i, i + 10).join(''))) {\n if (!/auth|session|token|isAuthenticated|user/i.test(lines.slice(Math.max(0, i - 5), i + 5).join(''))) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n '[Security Tester] Data fetch may not check authentication',\n 'Verify user is authenticated before loading sensitive data',\n file,\n lineNumber,\n 0.65,\n undefined,\n false,\n { category: 'user-testing:security' }\n ));\n }\n }\n\n // \"What if I change the URL to access another user's data?\"\n if (/params\\.|useParams|router\\.query/i.test(line) && /userId|id|accountId/i.test(line)) {\n if (!/authorize|permission|own|current.*user/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'critical',\n '[Security Tester] URL parameter may allow IDOR attack',\n 'Verify user has permission to access requested resource',\n file,\n lineNumber,\n 0.85,\n undefined,\n false,\n { category: 'user-testing:security', cwe: 'CWE-639', owasp: 'A5:2017-Broken Access Control' }\n ));\n }\n }\n }\n\n return issues;\n }\n\n /**\n * CONFUSED USER\n * \"I don't understand what to do here\"\n * Finds: Missing labels, unclear errors, accessibility issues\n */\n private simulateConfusedUser(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const lineNumber = i + 1;\n const nearbyCode = lines.slice(Math.max(0, i - 3), i + 5).join('\\n');\n\n // \"This error message doesn't help me\"\n if (/error|Error|err\\b/i.test(line) && /message|text|display/i.test(line)) {\n if (/generic|something.*wrong|error.*occurred|try.*again/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n '[Confused User] Error message is too generic',\n 'Provide specific, actionable error messages',\n file,\n lineNumber,\n 0.75,\n undefined,\n false,\n { category: 'user-testing:confused' }\n ));\n }\n }\n\n // \"What format should I use for this field?\"\n if (/<input/i.test(line) && /date|phone|email|zip|ssn|credit/i.test(line)) {\n if (!/placeholder.*example|format|pattern|hint/i.test(nearbyCode)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n '[Confused User] Input field has no format hint',\n 'Add placeholder or hint showing expected format (e.g., \"MM/DD/YYYY\")',\n file,\n lineNumber,\n 0.70,\n undefined,\n false,\n { category: 'user-testing:confused' }\n ));\n }\n }\n\n // \"I can't tell if this checkbox is required\"\n if (/checkbox|radio/i.test(line) && /terms|consent|agree|subscribe/i.test(nearbyCode)) {\n if (!/required|must|necessary|\\*/i.test(nearbyCode)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n '[Confused User] Consent checkbox requirement unclear',\n 'Clearly indicate if checkbox is required to proceed',\n file,\n lineNumber,\n 0.65,\n undefined,\n false,\n { category: 'user-testing:confused' }\n ));\n }\n }\n\n // \"I don't know what this button does\"\n if (/<button|Button/i.test(line)) {\n if (/\\.\\.\\.|icon.*only|aria-label/i.test(line) && !/tooltip|title=/i.test(nearbyCode)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n '[Confused User] Icon-only button has no tooltip',\n 'Add tooltip or visible text to explain button action',\n file,\n lineNumber,\n 0.70,\n undefined,\n false,\n { category: 'user-testing:confused' }\n ));\n }\n }\n\n // \"I made a mistake but can't undo it\"\n if (/delete|remove|cancel|clear/i.test(line) && /onClick|onPress/i.test(line)) {\n if (!/undo|restore|confirm|modal|dialog/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n '[Confused User] Destructive action has no undo option',\n 'Add confirmation dialog or undo functionality',\n file,\n lineNumber,\n 0.80,\n undefined,\n false,\n { category: 'user-testing:confused' }\n ));\n }\n }\n }\n\n return issues;\n }\n\n /**\n * IMPATIENT USER\n * \"I'm clicking everything rapidly, not waiting for anything\"\n * Finds: Double-submit bugs, race conditions, missing debounce\n */\n private simulateImpatientUser(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const lineNumber = i + 1;\n const nearbyCode = lines.slice(Math.max(0, i - 5), i + 10).join('\\n');\n\n // \"I clicked submit 5 times because nothing happened\"\n if (/onSubmit|handleSubmit/i.test(line)) {\n if (!/disabled|loading|isSubmitting|submitting|pending/i.test(nearbyCode)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n '[Impatient User] Form can be double-submitted',\n 'Disable submit button while processing to prevent duplicates',\n file,\n lineNumber,\n 0.85,\n undefined,\n true,\n { category: 'user-testing:impatient' }\n ));\n }\n }\n\n // \"I'm typing really fast in this search box\"\n if (/onChange|onInput/i.test(line) && /search|query|filter/i.test(nearbyCode)) {\n if (!/debounce|throttle|timeout|delay/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n '[Impatient User] Search input may fire too many requests',\n 'Add debounce to prevent excessive API calls while typing',\n file,\n lineNumber,\n 0.75,\n undefined,\n true,\n { category: 'user-testing:impatient' }\n ));\n }\n }\n\n // \"I closed the modal before it finished loading\"\n if (/modal|dialog|popup/i.test(line) && /open|show|visible/i.test(line)) {\n if (/fetch|api|load/i.test(nearbyCode) && !/abort|cancel|cleanup|unmount/i.test(nearbyCode)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n '[Impatient User] Modal may have memory leak if closed during fetch',\n 'Add AbortController or cleanup function to cancel pending requests',\n file,\n lineNumber,\n 0.70,\n undefined,\n false,\n { category: 'user-testing:impatient' }\n ));\n }\n }\n\n // \"I navigated away before the action completed\"\n if (/navigate|push|replace|router/i.test(line) && /async|await|then/i.test(nearbyCode)) {\n if (!/beforeunload|prompt|warn|unsaved/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n '[Impatient User] Navigation during async action may lose data',\n 'Warn user or prevent navigation while action is in progress',\n file,\n lineNumber,\n 0.60,\n undefined,\n false,\n { category: 'user-testing:impatient' }\n ));\n }\n }\n }\n\n return issues;\n }\n\n /**\n * EDGE CASE USER\n * \"What if I enter nothing? What if I enter 10,000 characters?\"\n * Finds: Missing validation, boundary issues, special character handling\n */\n private simulateEdgeCaseUser(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const lineNumber = i + 1;\n const nearbyCode = lines.slice(Math.max(0, i - 3), i + 5).join('\\n');\n\n // \"What if I submit an empty form?\"\n if (/<input|<textarea/i.test(line) && !/required/i.test(line)) {\n if (/name|email|password|title/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n '[Edge Case] Required-looking field has no validation',\n 'Add required attribute or validation for essential fields',\n file,\n lineNumber,\n 0.70,\n undefined,\n true,\n { category: 'user-testing:edge-case' }\n ));\n }\n }\n\n // \"What if I paste a novel into this text field?\"\n if (/<input|<textarea/i.test(line) && !/maxLength|max/i.test(line)) {\n if (/bio|description|comment|message|note/i.test(nearbyCode)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n '[Edge Case] Text field has no max length limit',\n 'Add maxLength to prevent excessive input',\n file,\n lineNumber,\n 0.65,\n undefined,\n true,\n { category: 'user-testing:edge-case' }\n ));\n }\n }\n\n // \"What if I enter emoji or special characters? ๐Ÿš€<script>\"\n if (/<input/i.test(line) && /name|title|username/i.test(nearbyCode)) {\n if (!/pattern|regex|validate|sanitize/i.test(nearbyCode)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n '[Edge Case] Input may not handle special characters safely',\n 'Validate/sanitize input for special characters and emoji',\n file,\n lineNumber,\n 0.65,\n undefined,\n false,\n { category: 'user-testing:edge-case' }\n ));\n }\n }\n\n // \"What if the list is empty?\"\n if (/\\.map\\(|\\.forEach\\(/i.test(line) && /render|display|show/i.test(nearbyCode)) {\n if (!/empty|no.*items|nothing|length.*===?\\s*0/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n '[Edge Case] List may not handle empty state gracefully',\n 'Add empty state message when list has no items',\n file,\n lineNumber,\n 0.60,\n undefined,\n false,\n { category: 'user-testing:edge-case' }\n ));\n }\n }\n\n // \"What if I enter a negative number?\"\n if (/type=[\"']number[\"']/i.test(line)) {\n if (!/min=[\"']?0|positive|unsigned/i.test(nearbyCode) && /quantity|amount|count|age/i.test(nearbyCode)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n '[Edge Case] Number field may accept negative values',\n 'Add min=\"0\" to prevent negative input where inappropriate',\n file,\n lineNumber,\n 0.75,\n undefined,\n true,\n { category: 'user-testing:edge-case' }\n ));\n }\n }\n }\n\n return issues;\n }\n}\n","import { BaseAgent } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext, AgentPriority } from '../types/index.js';\nimport { \n scanForVibeCodeIssues, \n checkFileLevelIssues, \n getVibeCodeTrie,\n type VibeCodeMatch,\n type FileLevelIssue \n} from '../trie/vibe-code-signatures.js';\n\n/**\n * Trie Clean Agent\n * \n * Specialized agent for reviewing AI-generated and \"vibe coded\" projects.\n * Helps non-technical users avoid common pitfalls when using AI tools.\n * \n * Based on patterns seen in:\n * - r/cursor, r/webdev, r/reactjs, r/nextjs\n * - Twitter/X discussions about AI coding\n * - Discord communities (Cursor, v0, Lovable, Bolt)\n * \n * Philosophy: Be helpful and educational, not condescending.\n * Many users are learning to code with AI assistance.\n */\nexport class TrieCleanAgent extends BaseAgent {\n name = 'trie_clean';\n description = 'Reviews AI-generated code for common mistakes and best practices (for non-technical users)';\n version = '1.0.0';\n\n override get priority(): AgentPriority {\n return {\n name: this.name,\n tier: 1, // Always run - this is the main value prop for new coders\n estimatedTimeMs: 100,\n dependencies: []\n };\n }\n\n shouldActivate(_context: CodeContext): boolean {\n // Always activate - every project can benefit from this review\n return true;\n }\n\n protected async analyzeFiles(files: string[], _context: ScanContext): Promise<Issue[]> {\n const issues: Issue[] = [];\n \n // Initialize the trie\n getVibeCodeTrie();\n\n for (const file of files) {\n try {\n const content = await this.readFile(file);\n \n // Pattern-based checks (fast, trie-powered)\n const patternIssues = scanForVibeCodeIssues(content, file);\n issues.push(...this.convertPatternIssues(patternIssues, file));\n \n // File-level checks (size, structure)\n const fileIssues = checkFileLevelIssues(file, content);\n issues.push(...this.convertFileLevelIssues(fileIssues));\n \n } catch (error) {\n console.error(`Trie Clean Agent: Error reading file ${file}:`, error);\n }\n }\n\n // Deduplicate similar issues\n return this.deduplicateIssues(issues);\n }\n\n private convertPatternIssues(matches: VibeCodeMatch[], file: string): Issue[] {\n return matches.map(match => ({\n id: this.generateIssueId(),\n agent: this.name,\n severity: match.severity,\n issue: `${match.description}: ${match.commonMistake}`,\n fix: match.fix,\n file,\n line: match.line,\n confidence: this.getConfidence(match.severity),\n category: match.category,\n autoFixable: false, // These usually require understanding context\n }));\n }\n\n private convertFileLevelIssues(fileIssues: FileLevelIssue[]): Issue[] {\n return fileIssues.map(issue => ({\n id: this.generateIssueId(),\n agent: this.name,\n severity: issue.severity,\n issue: `${issue.issue}: ${issue.commonMistake}`,\n fix: issue.fix,\n file: issue.file,\n confidence: 0.9,\n category: issue.category,\n autoFixable: false,\n }));\n }\n\n private getConfidence(severity: string): number {\n switch (severity) {\n case 'critical': return 0.95;\n case 'serious': return 0.85;\n case 'moderate': return 0.75;\n default: return 0.65;\n }\n }\n\n private deduplicateIssues(issues: Issue[]): Issue[] {\n const seen = new Set<string>();\n return issues.filter(issue => {\n // Don't report same category multiple times for same file\n const key = `${issue.file}:${issue.category}:${issue.severity}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n }\n}\n\n/**\n * Format trie clean results in a friendly, educational way\n */\nexport function formatTrieCleanResults(issues: Issue[]): string {\n if (issues.length === 0) {\n return `\n## โœ… Your Code Looks Good!\n\nNo common AI-generated code issues found. Nice work!\n\n**Tips to keep it clean:**\n- Keep files under 300 lines\n- Group related state together\n- Always handle errors from API calls\n- Never put secrets in frontend code\n`;\n }\n\n let output = `\n## ๐ŸŽฏ Vibe Check Results\n\nFound ${issues.length} things to improve. Don't worry - these are super common with AI-generated code!\n\n`;\n\n // Group by severity\n const critical = issues.filter(i => i.severity === 'critical');\n const serious = issues.filter(i => i.severity === 'serious');\n const moderate = issues.filter(i => i.severity === 'moderate');\n const low = issues.filter(i => i.severity === 'low');\n\n if (critical.length > 0) {\n output += `### ๐Ÿšจ Fix These First! (${critical.length})\\n\\n`;\n output += `These could break your app or expose sensitive data:\\n\\n`;\n for (const issue of critical) {\n output += `**${issue.file}:${issue.line || '?'}**\\n`;\n output += `- โŒ ${issue.issue}\\n`;\n output += `- โœ… ${issue.fix}\\n\\n`;\n }\n }\n\n if (serious.length > 0) {\n output += `### โš ๏ธ Should Fix (${serious.length})\\n\\n`;\n output += `These will cause problems eventually:\\n\\n`;\n for (const issue of serious) {\n output += `- **${issue.file}:${issue.line || '?'}** - ${issue.issue}\\n`;\n output += ` โ†’ ${issue.fix}\\n`;\n }\n output += '\\n';\n }\n\n if (moderate.length > 0) {\n output += `### ๐Ÿ’ก Good to Know (${moderate.length})\\n\\n`;\n for (const issue of moderate.slice(0, 5)) {\n output += `- ${issue.issue}\\n`;\n output += ` โ†’ ${issue.fix}\\n`;\n }\n if (moderate.length > 5) {\n output += `- *...and ${moderate.length - 5} more suggestions*\\n`;\n }\n output += '\\n';\n }\n\n if (low.length > 0) {\n output += `### ๐Ÿ“ Minor Suggestions (${low.length})\\n\\n`;\n output += `These are minor but good to know:\\n`;\n for (const issue of low.slice(0, 3)) {\n output += `- ${issue.issue}\\n`;\n }\n if (low.length > 3) {\n output += `- *...and ${low.length - 3} more*\\n`;\n }\n }\n\n output += `\n---\n\n### ๐Ÿ’ฌ Need Help?\n\nAsk your AI assistant:\n- \"Can you fix the [issue name] problem?\"\n- \"Refactor this file to be smaller\"\n- \"Add error handling to my API calls\"\n- \"Create proper TypeScript types for my data\"\n\n`;\n\n return output;\n}\n\n","/**\n * Custom Agent - Runtime class for document-generated agents\n */\n\nimport { BaseAgent } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext, AgentPriority } from '../types/index.js';\nimport type { GeneratedAgentConfig, DetectionRule } from '../types/custom-agent.js';\n\nexport class CustomAgent extends BaseAgent {\n override name: string;\n override description: string;\n override version: string;\n \n private config: GeneratedAgentConfig;\n \n constructor(config: GeneratedAgentConfig) {\n super();\n this.config = config;\n this.name = config.name;\n this.description = config.description;\n this.version = config.version;\n }\n \n override get priority(): AgentPriority {\n return {\n name: this.name,\n tier: this.config.activationRules.priority,\n estimatedTimeMs: 200,\n dependencies: [],\n };\n }\n \n /**\n * Check if agent should activate based on code context\n */\n override shouldActivate(context: CodeContext): boolean {\n const rules = this.config.activationRules;\n \n // Check context signals\n for (const signal of rules.contextSignals) {\n if (this.checkContextSignal(context, signal)) {\n return true;\n }\n }\n \n // Check file patterns (would need file info from context)\n // For now, return true if no specific signals required\n return rules.contextSignals.length === 0;\n }\n \n /**\n * Get activation confidence based on content patterns\n */\n override getActivationConfidence(context: CodeContext): number {\n if (!this.shouldActivate(context)) return 0;\n \n const rules = this.config.activationRules;\n let confidence = rules.minConfidence;\n \n // Boost confidence for matching context signals\n for (const signal of rules.contextSignals) {\n if (this.checkContextSignal(context, signal)) {\n confidence += 0.15;\n }\n }\n \n return Math.min(1.0, confidence);\n }\n \n /**\n * Check a context signal\n */\n private checkContextSignal(context: CodeContext, signal: string): boolean {\n // Handle direct boolean properties\n const booleanSignals: Record<string, keyof CodeContext> = {\n 'touchesAuth': 'touchesAuth',\n 'touchesPayments': 'touchesPayments',\n 'touchesDatabase': 'touchesDatabase',\n 'touchesAPI': 'touchesAPI',\n 'touchesUI': 'touchesUI',\n 'touchesUserData': 'touchesUserData',\n 'touchesHealthData': 'touchesHealthData',\n 'touchesSecurityConfig': 'touchesSecurityConfig',\n 'touchesCrypto': 'touchesCrypto',\n 'touchesFileSystem': 'touchesFileSystem',\n 'touchesThirdPartyAPI': 'touchesThirdPartyAPI',\n 'touchesLogging': 'touchesLogging',\n 'touchesErrorHandling': 'touchesErrorHandling',\n 'isNewFeature': 'isNewFeature',\n 'hasTests': 'hasTests',\n };\n \n const signalKey = booleanSignals[signal];\n if (signalKey) {\n return Boolean(context[signalKey]);\n }\n \n // Handle framework:xxx pattern\n if (signal.startsWith('framework:')) {\n const framework = signal.split(':')[1];\n return context.framework === framework;\n }\n \n // Handle changeType:xxx pattern\n if (signal.startsWith('changeType:')) {\n const changeType = signal.split(':')[1];\n return context.changeType === changeType;\n }\n \n return false;\n }\n \n /**\n * Analyze files using detection rules from the config\n */\n protected override async analyzeFiles(files: string[], _context: ScanContext): Promise<Issue[]> {\n const issues: Issue[] = [];\n \n for (const file of files) {\n try {\n const content = await this.readFile(file);\n const fileIssues = await this.analyzeFileContent(content, file);\n issues.push(...fileIssues);\n } catch (error) {\n console.error(`${this.name}: Error reading file ${file}:`, error);\n }\n }\n \n return issues;\n }\n \n /**\n * Analyze file content against detection rules\n */\n private async analyzeFileContent(content: string, filePath: string): Promise<Issue[]> {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n \n for (const rule of this.config.patterns) {\n const ruleIssues = this.checkRule(rule, content, lines, filePath);\n issues.push(...ruleIssues);\n }\n \n return issues;\n }\n \n /**\n * Check a single detection rule against content\n */\n private checkRule(\n rule: DetectionRule,\n content: string,\n lines: string[],\n filePath: string\n ): Issue[] {\n const issues: Issue[] = [];\n \n // Map 'info' severity to 'low' for Issue compatibility\n const mapSeverity = (s: DetectionRule['severity']): Issue['severity'] => \n s === 'info' ? 'low' : s;\n \n // Check regex patterns\n if (rule.patterns.regex && rule.patterns.regex.length > 0) {\n for (const pattern of rule.patterns.regex) {\n try {\n const regex = new RegExp(pattern, 'gi');\n let match: RegExpExecArray | null;\n \n while ((match = regex.exec(content)) !== null) {\n // Find line number\n const lineNumber = this.getLineNumber(content, match.index);\n \n // Avoid duplicate issues on same line\n if (!issues.some(i => i.line === lineNumber && i.id.includes(rule.id))) {\n issues.push(this.createIssue(\n `${this.generateIssueId()}-${rule.id}`,\n mapSeverity(rule.severity),\n rule.description,\n rule.fix.description,\n filePath,\n lineNumber,\n 0.85,\n rule.regulation,\n rule.fix.autoFixable,\n rule.category ? { category: rule.category } : undefined\n ));\n }\n }\n } catch (e) {\n // Invalid regex, skip\n console.error(`Invalid regex pattern in rule ${rule.id}: ${pattern}`);\n }\n }\n }\n \n // Check keyword patterns\n if (rule.patterns.keywords && rule.patterns.keywords.length > 0) {\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]?.toLowerCase() ?? '';\n const matchedKeywords = rule.patterns.keywords.filter(kw => \n line.includes(kw?.toLowerCase() ?? '')\n );\n \n if (matchedKeywords.length >= 2) {\n // Multiple keyword matches suggest relevance\n const lineNumber = i + 1;\n \n if (!issues.some(issue => issue.line === lineNumber && issue.id.includes(rule.id))) {\n issues.push(this.createIssue(\n `${this.generateIssueId()}-${rule.id}`,\n mapSeverity(rule.severity),\n rule.description,\n rule.fix.description,\n filePath,\n lineNumber,\n 0.70,\n rule.regulation,\n rule.fix.autoFixable,\n rule.category ? { category: rule.category } : undefined\n ));\n }\n }\n }\n }\n \n return issues;\n }\n \n /**\n * Get line number from character index\n */\n private getLineNumber(content: string, index: number): number {\n return content.slice(0, index).split('\\n').length;\n }\n \n /**\n * Get the system prompt for AI-powered analysis\n */\n override getSystemPrompt(): string {\n return this.config.systemPrompt;\n }\n \n /**\n * Get the analysis prompt template\n */\n getAnalysisPrompt(): string {\n return this.config.analysisPrompt;\n }\n \n /**\n * Get the fix prompt template\n */\n getFixPrompt(): string {\n return this.config.fixPrompt;\n }\n \n /**\n * Get agent metadata\n */\n getMetadata(): {\n category: string;\n source: GeneratedAgentConfig['source'];\n patternCount: number;\n conceptCount: number;\n } {\n return {\n category: this.config.category,\n source: this.config.source,\n patternCount: this.config.patterns.length,\n conceptCount: this.config.knowledge.coreConcepts.length,\n };\n }\n}\n\n","import type { Agent } from '../types/index.js';\nimport { SecurityAgent } from './security.js';\nimport { PrivacyAgent } from './privacy.js';\nimport { TypeCheckAgent } from './typecheck.js';\nimport { ComprehensionAgent } from './comprehension.js';\nimport { DesignEngineerAgent } from './design-engineer.js';\nimport { LegalAgent } from './legal.js';\nimport { TestAgent } from './test.js';\nimport { SoftwareArchitectAgent } from './software-architect.js';\nimport { DevOpsAgent } from './devops.js';\nimport { BugFindingAgent } from './bug-finding.js';\nimport { UserTestingAgent } from './user-testing.js';\nimport { TrieCleanAgent } from './trie-clean.js';\nimport { CustomAgent } from './custom-agent.js';\nimport { readdir, readFile } from 'fs/promises';\nimport { join } from 'path';\nimport type { GeneratedAgentConfig } from '../types/custom-agent.js';\n\nexport class AgentRegistry {\n private agents: Map<string, Agent> = new Map();\n private customAgentsLoaded: boolean = false;\n\n constructor() {\n this.registerBuiltinAgents();\n }\n\n private registerBuiltinAgents() {\n const builtinAgents: Agent[] = [\n // Core agents (always available)\n new SecurityAgent(),\n new PrivacyAgent(),\n new TypeCheckAgent(),\n new ComprehensionAgent(),\n \n // Specialized agents\n new DesignEngineerAgent(),\n new LegalAgent(),\n new TestAgent(),\n new SoftwareArchitectAgent(),\n new DevOpsAgent(),\n new BugFindingAgent(),\n new UserTestingAgent(),\n new TrieCleanAgent(),\n ];\n\n console.error(`Loaded config for ${builtinAgents.length} built-in agents`);\n\n for (const agent of builtinAgents) {\n this.agents.set(agent.name, agent);\n }\n }\n\n /**\n * Load custom agents from .trie/agents/ directory\n */\n async loadCustomAgents(): Promise<void> {\n if (this.customAgentsLoaded) return;\n \n try {\n const agentsDir = join(process.cwd(), '.trie', 'agents');\n const files = await readdir(agentsDir);\n const jsonFiles = files.filter(f => f.endsWith('.json'));\n \n let loadedCount = 0;\n \n for (const file of jsonFiles) {\n try {\n const configPath = join(agentsDir, file);\n const content = await readFile(configPath, 'utf-8');\n const config: GeneratedAgentConfig = JSON.parse(content);\n \n // Create and register the custom agent\n const agent = new CustomAgent(config);\n this.agents.set(agent.name, agent);\n loadedCount++;\n \n } catch (error) {\n console.error(`Failed to load custom agent from ${file}:`, error);\n }\n }\n \n if (loadedCount > 0) {\n console.error(`Loaded ${loadedCount} custom agent(s) from .trie/agents/`);\n }\n \n this.customAgentsLoaded = true;\n } catch (error) {\n // Directory doesn't exist or other error - that's okay\n this.customAgentsLoaded = true;\n }\n }\n\n /**\n * Reload custom agents (useful after creating new ones)\n */\n async reloadCustomAgents(): Promise<void> {\n // Remove existing custom agents\n for (const [name, agent] of this.agents.entries()) {\n if (agent instanceof CustomAgent) {\n this.agents.delete(name);\n }\n }\n \n this.customAgentsLoaded = false;\n await this.loadCustomAgents();\n }\n\n getAgent(name: string): Agent | undefined {\n return this.agents.get(name);\n }\n\n getAgentsByNames(names: string[]): Agent[] {\n return names\n .map(name => this.getAgent(name))\n .filter((agent): agent is Agent => agent !== undefined);\n }\n\n getAllAgents(): Agent[] {\n return Array.from(this.agents.values());\n }\n\n /**\n * Get only built-in agents\n */\n getBuiltinAgents(): Agent[] {\n return Array.from(this.agents.values()).filter(\n agent => !(agent instanceof CustomAgent)\n );\n }\n\n /**\n * Get only custom agents\n */\n getCustomAgents(): CustomAgent[] {\n return Array.from(this.agents.values()).filter(\n (agent): agent is CustomAgent => agent instanceof CustomAgent\n );\n }\n\n registerAgent(agent: Agent): void {\n this.agents.set(agent.name, agent);\n console.error(`Registered custom agent: ${agent.name}`);\n }\n\n /**\n * Unregister an agent by name\n */\n unregisterAgent(name: string): boolean {\n return this.agents.delete(name);\n }\n\n getAgentNames(): string[] {\n return Array.from(this.agents.keys());\n }\n\n getAgentDescriptions(): { name: string; description: string; isCustom: boolean }[] {\n return Array.from(this.agents.values()).map(agent => ({\n name: agent.name,\n description: agent.description,\n isCustom: agent instanceof CustomAgent,\n }));\n }\n\n /**\n * Check if an agent is a custom agent\n */\n isCustomAgent(name: string): boolean {\n const agent = this.agents.get(name);\n return agent instanceof CustomAgent;\n }\n\n /**\n * Get custom agent metadata\n */\n getCustomAgentMetadata(name: string): ReturnType<CustomAgent['getMetadata']> | null {\n const agent = this.agents.get(name);\n if (agent instanceof CustomAgent) {\n return agent.getMetadata();\n }\n return null;\n }\n}\n","import { readFile, readdir } 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 { AgentRegistry } 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 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 = new AgentRegistry();\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\n // Start progress reporting\n this.progress.startPhase('init', '๐Ÿ”บ TRIE AGENT - AI-Powered Code Analysis');\n\n // If no files specified, scan the entire codebase\n if (!files || !Array.isArray(files) || files.length === 0) {\n const scanDir = directory || process.cwd();\n this.progress.startPhase('discovery', `Discovering files in ${basename(scanDir)}...`);\n files = await this.discoverFiles(scanDir);\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(process.cwd(), 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 // Initialize trie-based incremental scanner\n const scanDir = directory || process.cwd();\n if (!this.incrementalScanner) {\n this.incrementalScanner = new IncrementalScanner(scanDir);\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(validFiles);\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 const selectedAgents = forceAgents\n ? this.agentRegistry.getAgentsByNames(forceAgents)\n : await this.triager.selectAgents(context, riskLevel);\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: process.cwd() }\n );\n\n // Phase 6: Prioritization\n const allIssues = agentResults.flatMap(result => result.issues);\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 // 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(result, prioritized, semanticOutput, attackSurfaceOutput);\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 'design-engineer': 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 ): 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 // 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 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 { AgentRegistry } 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 = new AgentRegistry();\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.touchesHealthData) { confidence += 0.6; reasons.push('PHI/HIPAA'); }\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.touchesHealthData) { confidence += 0.6; reasons.push('HIPAA compliance'); }\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 === 'design-engineer') {\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 // 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': ['design-engineer'], // 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.touchesHealthData) reasons.push('PHI');\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 type { Agent, AgentResult, ScanContext } from '../types/index.js';\n\nexport class Executor {\n async executeAgents(\n agents: Agent[],\n files: string[],\n context: ScanContext\n ): Promise<AgentResult[]> {\n console.error(`โšก Executing ${agents.length} agents in parallel...`);\n\n // Execute agents in parallel with timeout\n const promises = agents.map(agent =>\n this.executeAgentWithTimeout(agent, files, context)\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(filePaths: string[], forceRescan: boolean = false): 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 \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 { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { extname, relative, resolve, isAbsolute } from 'path';\nimport { getPrompt, getSystemPrompt } from '../ai/prompts.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 filePath = isAbsolute(file) ? file : resolve(process.cwd(), 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(process.cwd(), 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(process.cwd(), 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 filePath = isAbsolute(file) ? file : resolve(process.cwd(), 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(process.cwd(), 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 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 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\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';\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":";;;;;;;;;;;;;;;AAuBO,IAAM,mBAAN,MAAuB;AAAA,EACpB,eAA8B;AAAA,EAC9B,YAAoB,KAAK,IAAI;AAAA,EAC7B,iBAAyB,KAAK,IAAI;AAAA,EAClC;AAAA,EAER,YAAY,UAAiC,CAAC,GAAG;AAC/C,SAAK,UAAU,QAAQ,WAAW;AAAA,EACpC;AAAA;AAAA;AAAA;AAAA,EAKA,OAAO,SAAiB,QAAuB;AAC7C,QAAI,CAAC,KAAK,QAAS;AAEnB,UAAM,SAAS,KAAK,aAAa,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A0B;AAC/C,UAAM,MAAMC,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","basename","basename","basename","basename","readFile","readdir","existsSync","basename","join","extname","readFile","existsSync","extname","basename","resolve","readFile","readdir","join","extname","relative","dirname","basename","readFile","basename","relative","basename","readFile","basename","relative","readFile","existsSync","join","join","existsSync","readFile","scanDir","basename","existsSync","result","readFile","readdir","join","extname","readFile","existsSync","extname","relative","resolve","isAbsolute","isAbsolute","resolve","existsSync","readFile","relative","extname"]}