@triedotdev/mcp 1.0.21 → 1.0.22

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/agents/security.ts","../src/agents/privacy.ts","../src/agents/typecheck.ts","../src/agents/comprehension.ts","../src/agents/accessibility.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/soc2.ts","../src/agents/super-reviewer.ts","../src/agents/performance.ts","../src/agents/e2e.ts","../src/agents/visual-qa.ts","../src/agents/data-flow.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":["import { BaseAgent, FileRelevance } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\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 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 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 * Override AI enhancement system prompt for security-specific analysis\n */\n protected override getAIEnhancementSystemPrompt(): string {\n return `You are a senior security engineer performing a code audit.\n\nAnalyze the detected issues and code snippets for security vulnerabilities:\n\n1. VALIDATE: Confirm if pattern-detected issues are real vulnerabilities\n2. EXPAND: Find deeper issues - SQL injection, XSS, auth bypass, IDOR, secrets\n3. PRIORITIZE: Rate by exploitability (0-100, where 100 = trivially exploitable)\n4. FIX: Provide secure code fixes\n\nSeverity guide:\n- CRITICAL: Directly exploitable, leads to RCE, data breach, or total auth bypass\n- SERIOUS: Exploitable with conditions, significant impact\n- MODERATE: Real issue but limited impact\n- LOW: Best practice violation\n\nOutput STRICT JSON:\n{\n \"validated\": [{\n \"original_issue\": \"...\",\n \"verdict\": \"TRUE_POSITIVE\" | \"FALSE_POSITIVE\",\n \"confidence\": 0-100,\n \"file\": \"path\",\n \"line\": 123,\n \"severity\": \"critical\",\n \"vulnerability_type\": \"SQL Injection\",\n \"attack_scenario\": \"How to exploit\",\n \"fix\": \"Secure code example\"\n }],\n \"additional\": [{\n \"issue\": \"Vulnerability description\",\n \"file\": \"path\",\n \"line\": 123,\n \"severity\": \"serious\",\n \"vulnerability_type\": \"XSS\",\n \"attack_scenario\": \"How to exploit\",\n \"fix\": \"Secure code\"\n }],\n \"summary\": \"Overall security assessment\"\n}`;\n }\n\n /**\n * Pattern-based analysis for fast detection\n * AI enhancement happens via base class if API key is available\n */\n protected override async analyzeFiles(files: string[], _context: ScanContext): Promise<Issue[]> {\n const issues: Issue[] = [];\n \n for (const file of files) {\n if (this.shouldAlwaysSkip(file)) continue;\n \n try {\n const content = await this.readFile(file);\n const lines = content.split('\\n');\n \n // Check for critical 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_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 file,\n i + 1,\n 0.98,\n undefined,\n true\n ));\n }\n }\n }\n } catch {\n // Skip unreadable files\n }\n }\n \n return issues;\n }\n}\n","import { BaseAgent, FileRelevance } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\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: /credit.*card|card.*number|cvv|expiry/i, reason: 'payment data' },\n { pattern: /password|credential|secret|token/i, reason: 'credentials' },\n { pattern: /gdpr|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, CCPA, PCI-DSS compliance';\n version = '2.0.0';\n\n shouldActivate(context: CodeContext): boolean {\n // Focus on user data handling, not healthcare-specific signals\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'].some(keyword =>\n pattern.includes(keyword)\n )\n );\n\n return 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 (legacy - kept for reference)\n */\n protected 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- **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 (legacy - kept for reference)\n */\n protected 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('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('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 * Pattern-based privacy analysis\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 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 file,\n i + 1,\n 0.95,\n regulation,\n true\n ));\n }\n }\n \n // Additional privacy patterns\n // PII in localStorage\n if (/localStorage\\.setItem\\s*\\([^)]*(?:email|ssn|password|phone)/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'PII stored in localStorage (unencrypted, persists)',\n 'Use encrypted storage or server-side sessions for PII',\n file,\n i + 1,\n 0.90,\n 'GDPR Article 25',\n false\n ));\n }\n \n // Consent not checked before analytics\n if (/gtag|ga\\(|analytics|fbq\\(|pixel/i.test(line) && !/consent|cookie.*accepted/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Analytics/tracking loaded without checking consent',\n 'Only load analytics after user consents (GDPR, CCPA requirement)',\n file,\n i + 1,\n 0.75,\n 'GDPR Article 7',\n false\n ));\n }\n \n // Data retention issues\n if (/delete.*user|remove.*account/i.test(line) && !/backup|archive/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'User deletion - verify data is fully removed from all systems',\n 'Ensure GDPR right to erasure compliance - remove from backups, logs, third parties',\n file,\n i + 1,\n 0.60,\n 'GDPR Article 17',\n false\n ));\n }\n }\n } catch {\n // Skip unreadable files\n }\n }\n \n return issues;\n }\n\n /**\n * AI Enhancement for privacy compliance\n */\n protected override getAIEnhancementSystemPrompt(): string {\n return `You are a privacy compliance expert specializing in GDPR, CCPA, and PCI-DSS.\n\nAnalyze detected issues and code for:\n1. PII handling (encryption, minimization, access controls)\n2. Consent management (cookie banners, tracking consent)\n3. Data retention and right to erasure\n4. Cross-border data transfers\n5. Third-party data sharing\n6. Security measures for personal data\n\nOutput STRICT JSON:\n{\n \"validated\": [{\n \"original_issue\": \"...\",\n \"verdict\": \"TRUE_POSITIVE\" | \"FALSE_POSITIVE\",\n \"confidence\": 0-100,\n \"file\": \"path\",\n \"line\": 123,\n \"severity\": \"critical\",\n \"regulation\": \"GDPR Article X / CCPA / PCI-DSS\",\n \"risk\": \"What could happen if not fixed\",\n \"fix\": \"Compliant implementation\"\n }],\n \"additional\": [{\n \"issue\": \"Privacy issue found\",\n \"file\": \"path\",\n \"line\": 123,\n \"severity\": \"serious\",\n \"regulation\": \"Regulation reference\",\n \"risk\": \"Compliance risk\",\n \"fix\": \"How to fix\"\n }],\n \"summary\": \"Overall privacy compliance assessment\"\n}`;\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 AccessibilityAgent extends BaseAgent {\n name = 'accessibility';\n description = 'WCAG 2.1 accessibility compliance, keyboard nav, screen readers, color contrast';\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(`Accessibility 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 * AI Enhancement for accessibility review\n */\n protected override getAIEnhancementSystemPrompt(): string {\n return `You are a WCAG 2.1 accessibility expert. Review code for inclusive design.\n\nAnalyze detected issues and code for:\n1. Screen reader compatibility (ARIA labels, roles, live regions)\n2. Keyboard navigation (focus management, tab order, focus trapping)\n3. Color contrast (4.5:1 for text, 3:1 for large text)\n4. Form accessibility (labels, error messages, required fields)\n5. Dynamic content (loading states, announcements, focus management)\n6. Reduced motion support (prefers-reduced-motion)\n7. Touch target sizes (44x44px minimum)\n\nOutput STRICT JSON:\n{\n \"validated\": [{\n \"original_issue\": \"...\",\n \"verdict\": \"TRUE_POSITIVE\" | \"FALSE_POSITIVE\",\n \"confidence\": 0-100,\n \"file\": \"path\",\n \"line\": 123,\n \"severity\": \"serious\",\n \"wcag_criterion\": \"WCAG 2.1 - X.X.X Name\",\n \"impact\": \"How this affects users with disabilities\",\n \"fix\": \"Accessible code fix\"\n }],\n \"additional\": [{\n \"issue\": \"Accessibility issue found\",\n \"file\": \"path\",\n \"line\": 123,\n \"severity\": \"moderate\",\n \"wcag_criterion\": \"WCAG criterion\",\n \"impact\": \"User impact\",\n \"fix\": \"Accessible implementation\"\n }],\n \"summary\": \"Overall accessibility assessment\"\n}`;\n }\n}\n","import { BaseAgent } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\n\n/**\n * Design Engineer Agent — Award-Winning Frontend Craft\n * \n * This agent thinks like a design engineer at a top creative agency.\n * It reviews code for the kind of polish that wins Awwwards and gets featured on Codrops.\n * \n * Focus areas:\n * - Design systems & tokens (spacing, typography, color scales)\n * - Motion design & micro-interactions\n * - Visual hierarchy & layout systems\n * - Creative CSS techniques (gradients, blend modes, masks, clip-paths)\n * - Performance-conscious animations (GPU layers, will-change, FLIP)\n * - Responsive & fluid design (clamp, container queries, aspect-ratio)\n * - Modern CSS features (cascade layers, :has(), subgrid, anchor positioning)\n */\nexport class DesignEngineerAgent extends BaseAgent {\n name = 'design-engineer';\n description = 'Award-winning frontend craft: design systems, motion design, creative CSS, Awwwards-level polish';\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 \n // Only analyze frontend files\n if (this.isFrontendFile(file)) {\n issues.push(...this.analyzeDesignSystem(content, file));\n issues.push(...this.analyzeMotionDesign(content, file));\n issues.push(...this.analyzeVisualCraft(content, file));\n issues.push(...this.analyzeModernCSS(content, file));\n issues.push(...this.analyzePerformance(content, file));\n }\n } catch (error) {\n console.error(`Design Engineer Agent: Error reading file ${file}:`, error);\n }\n }\n\n return issues;\n }\n\n private isFrontendFile(file: string): boolean {\n return /\\.(tsx|jsx|vue|svelte|astro|css|scss|sass|less|styled\\.(ts|js))$/.test(file);\n }\n\n /**\n * Analyze design system patterns\n */\n private analyzeDesignSystem(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 magic numbers in spacing\n if (/margin|padding|gap|top|left|right|bottom/i.test(line)) {\n const magicPx = line.match(/:\\s*(\\d+)px/);\n if (magicPx && !['0', '1', '2'].includes(magicPx[1]!)) {\n const value = parseInt(magicPx[1]!);\n // Check if it's not on a standard scale (4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 80, 96)\n const scale = [4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 80, 96, 128];\n if (!scale.includes(value)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n `Magic number ${value}px — consider using a spacing token`,\n `Use a design token like --space-${Math.round(value / 4)} or spacing scale (4, 8, 12, 16, 24, 32...)`,\n file,\n lineNumber,\n 0.60,\n undefined,\n false\n ));\n }\n }\n }\n\n // Check for hardcoded colors outside of design tokens\n if (/color|background|border|fill|stroke/i.test(line)) {\n const hardcodedHex = line.match(/#[0-9a-fA-F]{3,8}(?![0-9a-fA-F])/);\n const hardcodedRgb = line.match(/rgba?\\s*\\(\\s*\\d+/);\n if ((hardcodedHex || hardcodedRgb) && !line.includes('var(--')) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Hardcoded color value — use a design token',\n 'Define colors in CSS custom properties: var(--color-primary), var(--color-surface), etc.',\n file,\n lineNumber,\n 0.70,\n undefined,\n false\n ));\n }\n }\n\n // Check for inconsistent font sizes\n if (/font-size/i.test(line)) {\n const pxSize = line.match(/font-size:\\s*(\\d+)px/);\n if (pxSize) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Fixed font-size in px — consider fluid typography',\n 'Use clamp() for responsive text: font-size: clamp(1rem, 2vw + 0.5rem, 1.5rem)',\n file,\n lineNumber,\n 0.65,\n undefined,\n false\n ));\n }\n }\n\n // Check for z-index chaos\n if (/z-index:\\s*(\\d+)/.test(line)) {\n const zValue = parseInt(line.match(/z-index:\\s*(\\d+)/)?.[1] || '0');\n if (zValue > 100 && zValue !== 9999) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n `High z-index (${zValue}) — establish a z-index scale`,\n 'Create z-index tokens: --z-dropdown: 100, --z-modal: 200, --z-toast: 300, --z-tooltip: 400',\n file,\n lineNumber,\n 0.75,\n undefined,\n false\n ));\n }\n }\n }\n\n return issues;\n }\n\n /**\n * Analyze motion design patterns\n */\n private analyzeMotionDesign(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 transition without easing or with linear\n if (/transition/i.test(line) && !line.includes('cubic-bezier') && !line.includes('ease')) {\n if (line.includes('linear') || !/ease|cubic|spring/.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Transition using linear timing — add easing for polish',\n 'Use custom easing: cubic-bezier(0.22, 1, 0.36, 1) for smooth deceleration, or ease-out for exits',\n file,\n lineNumber,\n 0.70,\n undefined,\n false\n ));\n }\n }\n\n // Check for very short transitions (< 100ms)\n if (/transition.*(\\d+)ms/.test(line)) {\n const duration = parseInt(line.match(/(\\d+)ms/)?.[1] || '0');\n if (duration > 0 && duration < 100) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n `Very short transition (${duration}ms) — may feel jarring`,\n 'Micro-interactions work best at 150-300ms. Use 100ms minimum for perceivable motion.',\n file,\n lineNumber,\n 0.60,\n undefined,\n false\n ));\n }\n }\n\n // Check for animation without reduced-motion handling\n if (/@keyframes|animation:/i.test(line)) {\n // Look for prefers-reduced-motion in the file\n if (!content.includes('prefers-reduced-motion')) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Animation without reduced-motion fallback',\n 'Add @media (prefers-reduced-motion: reduce) { animation: none } for motion-sensitive users',\n file,\n lineNumber,\n 0.80,\n undefined,\n false\n ));\n }\n }\n\n // Suggest staggered animations for lists\n if (/\\.map\\s*\\(|v-for|ngFor|\\*ngFor|{#each/.test(line)) {\n const nextLines = lines.slice(i, i + 10).join('\\n');\n if (nextLines.includes('animation') && !nextLines.includes('delay') && !nextLines.includes('stagger')) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'List items animate without stagger — add animation delay',\n 'Stagger reveals with animation-delay: calc(var(--index) * 50ms) for Awwwards-level polish',\n file,\n lineNumber,\n 0.65,\n undefined,\n false\n ));\n }\n }\n }\n\n return issues;\n }\n\n /**\n * Analyze visual craft and creative techniques\n */\n private analyzeVisualCraft(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 box-shadow without layering\n if (/box-shadow:/i.test(line) && !line.includes(',')) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Single-layer box-shadow — layer shadows for depth',\n 'Use layered shadows: box-shadow: 0 1px 2px rgba(0,0,0,.1), 0 4px 12px rgba(0,0,0,.1)',\n file,\n lineNumber,\n 0.55,\n undefined,\n false\n ));\n }\n\n // Check for border-radius without consistency\n if (/border-radius:\\s*(\\d+)px/.test(line)) {\n const radius = parseInt(line.match(/border-radius:\\s*(\\d+)px/)?.[1] || '0');\n if (radius > 0 && ![2, 4, 6, 8, 12, 16, 24, 9999].includes(radius)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n `Border-radius ${radius}px — use a radius scale`,\n 'Establish a radius scale: --radius-sm: 4px, --radius-md: 8px, --radius-lg: 16px, --radius-full: 9999px',\n file,\n lineNumber,\n 0.50,\n undefined,\n false\n ));\n }\n }\n\n // Suggest gradient for solid backgrounds in hero sections\n if (/hero|banner|header|jumbotron/i.test(file) || /Hero|Banner|Header/i.test(content.slice(0, 500))) {\n if (/background:\\s*#|background-color:/i.test(line) && !line.includes('gradient')) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Solid background in hero section — consider a subtle gradient',\n 'Add depth with gradients: background: linear-gradient(135deg, var(--color-bg) 0%, var(--color-surface) 100%)',\n file,\n lineNumber,\n 0.50,\n undefined,\n false\n ));\n }\n }\n\n // Check for lack of backdrop-blur on overlays\n if (/overlay|modal|dialog|drawer/i.test(line) || /position:\\s*fixed/.test(line)) {\n const context = lines.slice(Math.max(0, i - 5), i + 10).join('\\n');\n if (!context.includes('backdrop') && context.includes('background')) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Overlay without backdrop blur — add glassmorphism effect',\n 'Use backdrop-filter: blur(12px) with semi-transparent background for modern glass effect',\n file,\n lineNumber,\n 0.55,\n undefined,\n false\n ));\n }\n }\n }\n\n return issues;\n }\n\n /**\n * Analyze modern CSS feature usage\n */\n private analyzeModernCSS(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n\n // Check for opportunities to use container queries\n if (/@media.*width/.test(content) && !content.includes('container-type')) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Using media queries — consider container queries for component isolation',\n 'Use container queries for truly reusable components: container-type: inline-size; @container (min-width: 400px) {...}',\n file,\n undefined,\n 0.50,\n undefined,\n false\n ));\n }\n\n // Check for calc() opportunities\n if (content.includes('padding') && content.includes('max-width') && !content.includes('clamp(')) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Consider fluid spacing with clamp()',\n 'Use clamp() for responsive spacing: padding: clamp(1rem, 5vw, 3rem)',\n file,\n undefined,\n 0.45,\n undefined,\n false\n ));\n }\n\n // Check for :has() opportunities in React/Vue\n if (/\\.parent.*\\.child|parentElement|closest\\(/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'JavaScript parent selection — consider CSS :has()',\n 'Use CSS :has() for parent styling: .card:has(.featured) { border: 2px solid gold }',\n file,\n undefined,\n 0.55,\n undefined,\n false\n ));\n }\n\n // Check for grid with fixed columns\n if (/grid-template-columns:\\s*repeat\\(\\d+,/.test(content) && !content.includes('auto-fit') && !content.includes('auto-fill')) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Fixed grid columns — use auto-fit for responsive grids',\n 'Use intrinsic sizing: grid-template-columns: repeat(auto-fit, minmax(min(300px, 100%), 1fr))',\n file,\n undefined,\n 0.60,\n undefined,\n false\n ));\n }\n\n // Check for aspect-ratio opportunities\n if (/padding-top:\\s*\\d+%|padding-bottom:\\s*\\d+%/.test(content) && !content.includes('aspect-ratio')) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Padding-based aspect ratio hack — use aspect-ratio property',\n 'Use native aspect-ratio: aspect-ratio: 16 / 9 instead of padding hacks',\n file,\n undefined,\n 0.80,\n undefined,\n true\n ));\n }\n\n return issues;\n }\n\n /**\n * Analyze animation performance\n */\n private analyzePerformance(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 animating expensive properties\n if (/transition|animation/i.test(line)) {\n if (/width|height|top|left|right|bottom|margin|padding/i.test(line) && \n !line.includes('transform') && !line.includes('opacity')) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Animating layout properties — use transform instead',\n 'Animate transform/opacity for 60fps. Replace top/left with translate, width/height with scale',\n file,\n lineNumber,\n 0.85,\n undefined,\n false\n ));\n }\n }\n\n // Check for will-change abuse\n if (/will-change:\\s*transform|will-change:\\s*opacity/.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Static will-change — apply dynamically',\n 'Add will-change on hover/focus, remove after animation. Permanent will-change wastes GPU memory.',\n file,\n lineNumber,\n 0.70,\n undefined,\n false\n ));\n }\n\n // Check for filter animations\n if (/transition.*filter|animation.*filter|filter.*transition/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Animating filter is expensive — use sparingly',\n 'Filter animations trigger repaint. Consider opacity/transform alternatives or accept lower framerates.',\n file,\n lineNumber,\n 0.75,\n undefined,\n false\n ));\n }\n\n // Check for large box-shadows in animations\n if (/transition.*box-shadow|animation.*box-shadow|box-shadow.*transition/i.test(line)) {\n const context = lines.slice(Math.max(0, i - 3), i + 3).join('\\n');\n if (/blur\\s*\\(\\s*(\\d+)/.test(context)) {\n const blur = parseInt(context.match(/blur\\s*\\(\\s*(\\d+)/)?.[1] || '0');\n if (blur > 20) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n `Large shadow blur (${blur}px) in animation — may drop frames`,\n 'Use pseudo-element for shadow animation: animate opacity of ::after with the shadow instead',\n file,\n lineNumber,\n 0.70,\n undefined,\n false\n ));\n }\n }\n }\n }\n\n return issues;\n }\n\n /**\n * AI Enhancement for design review\n */\n protected override getAIEnhancementSystemPrompt(): string {\n return `You are an award-winning design engineer from a top creative agency. You review code for Awwwards-level polish.\n\nAnalyze detected issues and code for:\n1. Design system consistency (tokens, spacing scales, color systems)\n2. Motion design quality (easing curves, choreography, performance)\n3. Visual hierarchy and typography systems\n4. Creative CSS techniques (gradients, masks, blend modes, clip-paths)\n5. Modern CSS features (container queries, :has(), subgrid)\n6. Responsive design patterns (fluid typography, aspect ratios)\n\nOutput STRICT JSON:\n{\n \"validated\": [{\n \"original_issue\": \"...\",\n \"verdict\": \"TRUE_POSITIVE\" | \"FALSE_POSITIVE\",\n \"confidence\": 0-100,\n \"file\": \"path\",\n \"line\": 123,\n \"severity\": \"moderate\",\n \"design_impact\": \"Why this hurts the user experience\",\n \"fix\": \"Creative CSS fix with code example\"\n }],\n \"additional\": [{\n \"issue\": \"Design opportunity found\",\n \"file\": \"path\",\n \"line\": 123,\n \"severity\": \"low\",\n \"enhancement\": \"How to elevate this to award-winning quality\",\n \"fix\": \"Modern CSS/animation code\"\n }],\n \"summary\": \"Overall design craft assessment\"\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.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 * AI Enhancement for architecture review\n */\n protected override getAIEnhancementSystemPrompt(): string {\n return `You are a senior software architect reviewing code for scalability, maintainability, and best practices.\n\nAnalyze detected issues and code for:\n1. SOLID principles violations\n2. Separation of concerns (UI, API, data layers)\n3. N+1 queries and database optimization\n4. Dependency injection and testability\n5. Error handling and resilience patterns\n6. Caching and performance considerations\n7. Circular dependencies and coupling\n\nOutput STRICT JSON:\n{\n \"validated\": [{\n \"original_issue\": \"...\",\n \"verdict\": \"TRUE_POSITIVE\" | \"FALSE_POSITIVE\",\n \"confidence\": 0-100,\n \"file\": \"path\",\n \"line\": 123,\n \"severity\": \"serious\",\n \"principle\": \"SOLID / DRY / YAGNI / etc\",\n \"impact\": \"How this affects scalability/maintainability\",\n \"fix\": \"Architectural fix with code example\"\n }],\n \"additional\": [{\n \"issue\": \"Architecture issue found\",\n \"file\": \"path\",\n \"line\": 123,\n \"severity\": \"moderate\",\n \"principle\": \"Violated principle\",\n \"impact\": \"Technical debt impact\",\n \"fix\": \"Refactoring approach\"\n }],\n \"summary\": \"Overall architecture assessment\"\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 * AI Enhancement for DevOps review\n */\n protected override getAIEnhancementSystemPrompt(): string {\n return `You are a DevOps engineer reviewing code for production readiness.\n\nAnalyze detected issues and code for:\n1. Environment configuration (dev/staging/prod)\n2. Logging and observability (structured logs, metrics)\n3. Error handling and graceful degradation\n4. Resource management (connections, memory, timeouts)\n5. Deployment patterns (health checks, graceful shutdown)\n6. CI/CD concerns (test coverage, build optimization)\n7. Secrets management\n\nOutput STRICT JSON:\n{\n \"validated\": [{\n \"original_issue\": \"...\",\n \"verdict\": \"TRUE_POSITIVE\" | \"FALSE_POSITIVE\",\n \"confidence\": 0-100,\n \"file\": \"path\",\n \"line\": 123,\n \"severity\": \"serious\",\n \"category\": \"logging | config | deployment | etc\",\n \"production_risk\": \"What could go wrong in prod\",\n \"fix\": \"DevOps best practice fix\"\n }],\n \"additional\": [{\n \"issue\": \"DevOps issue found\",\n \"file\": \"path\",\n \"line\": 123,\n \"severity\": \"moderate\",\n \"category\": \"Issue category\",\n \"production_risk\": \"Risk description\",\n \"fix\": \"Implementation\"\n }],\n \"summary\": \"Production readiness assessment\"\n}`;\n }\n}\n","import { BaseAgent, FileRelevance } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\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 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 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 * Override AI enhancement system prompt for bug-finding\n */\n protected override getAIEnhancementSystemPrompt(): string {\n return `You are a QA engineer trying to break code. Find bugs that will cause crashes or incorrect behavior.\n\nAnalyze detected issues and code for:\n1. Null/undefined errors\n2. Async/await bugs (missing await, async forEach)\n3. Race conditions\n4. Edge cases (empty arrays, zero values, boundaries)\n5. Type coercion issues\n6. Resource leaks\n\nOutput STRICT JSON:\n{\n \"validated\": [{\n \"original_issue\": \"...\",\n \"verdict\": \"TRUE_POSITIVE\" | \"FALSE_POSITIVE\",\n \"confidence\": 0-100,\n \"file\": \"path\",\n \"line\": 123,\n \"severity\": \"critical\",\n \"trigger_condition\": \"When would this crash?\",\n \"fix\": \"Code fix\"\n }],\n \"additional\": [{\n \"issue\": \"Bug description\",\n \"file\": \"path\",\n \"line\": 123,\n \"severity\": \"serious\",\n \"trigger_condition\": \"When would this fail?\",\n \"fix\": \"Code fix\"\n }],\n \"summary\": \"Bug hunt assessment\"\n}`;\n }\n\n /**\n * Pattern-based bug detection\n */\n protected override async analyzeFiles(files: string[], _context: ScanContext): Promise<Issue[]> {\n const issues: Issue[] = [];\n \n for (const file of files) {\n // Skip non-relevant files\n if (/node_modules|\\.d\\.ts$|\\.min\\.|dist\\/|build\\//.test(file)) continue;\n \n try {\n const content = await this.readFile(file);\n const lines = content.split('\\n');\n \n // Check for critical bug patterns\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 file,\n i + 1,\n 0.95,\n undefined,\n true\n ));\n }\n }\n }\n } catch {\n // Skip unreadable files\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';\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: ['accessibility'] // 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// Note: TrieCleanAgent AI enhancement uses base class defaults\n// which provides good general cleanup suggestions","import { BaseAgent } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\n\n/**\n * SOC 2 Trust Service Criteria focused on code-level controls\n * \n * Key areas:\n * - CC6: Logical Access Controls (secrets, RBAC, MFA references)\n * - CC7: System Operations (logging, monitoring, error handling)\n * - CC8: Change Management (version control patterns)\n * - Security: Encryption, input validation, secure coding\n */\n\nconst SOC2_PATTERNS = {\n // CC6 - Logical Access Controls\n hardcodedSecrets: [\n { pattern: /['\"]sk_live_[A-Za-z0-9]{20,}['\"]/, issue: 'Hardcoded Stripe live key', regulation: 'CC6.1' },\n { pattern: /['\"]AKIA[A-Z0-9]{16}['\"]/, issue: 'Hardcoded AWS access key', regulation: 'CC6.1' },\n { pattern: /['\"]ghp_[A-Za-z0-9]{36}['\"]/, issue: 'Hardcoded GitHub token', regulation: 'CC6.1' },\n { pattern: /password\\s*[:=]\\s*['\"][^'\"]{8,}['\"](?!.*example|test|placeholder)/i, issue: 'Hardcoded password', regulation: 'CC6.1' },\n { pattern: /api[_-]?key\\s*[:=]\\s*['\"][A-Za-z0-9]{20,}['\"]/i, issue: 'Hardcoded API key', regulation: 'CC6.1' },\n { pattern: /secret\\s*[:=]\\s*['\"][^'\"]{16,}['\"]/i, issue: 'Hardcoded secret value', regulation: 'CC6.1' },\n ],\n \n // Missing access control\n accessControl: [\n { pattern: /\\/\\/\\s*TODO:?\\s*(add|implement)?\\s*(auth|access|permission)/i, issue: 'Missing access control (TODO)', regulation: 'CC6.2' },\n { pattern: /isAdmin\\s*[:=]\\s*true|role\\s*[:=]\\s*['\"]admin['\"]/i, issue: 'Hardcoded admin privilege', regulation: 'CC6.3' },\n ],\n\n // CC7 - System Operations (Logging & Monitoring)\n logging: [\n { pattern: /console\\.(log|error|warn)\\s*\\([^)]*password/i, issue: 'Password logged to console', regulation: 'CC7.2' },\n { pattern: /console\\.(log|error|warn)\\s*\\([^)]*token/i, issue: 'Token logged to console', regulation: 'CC7.2' },\n { pattern: /console\\.(log|error|warn)\\s*\\([^)]*secret/i, issue: 'Secret logged to console', regulation: 'CC7.2' },\n { pattern: /console\\.(log|error|warn)\\s*\\([^)]*apiKey/i, issue: 'API key logged to console', regulation: 'CC7.2' },\n ],\n\n // Error handling\n errorHandling: [\n { pattern: /catch\\s*\\([^)]*\\)\\s*\\{\\s*\\}/, issue: 'Empty catch block - errors silently swallowed', regulation: 'CC7.3' },\n { pattern: /catch\\s*\\([^)]*\\)\\s*\\{\\s*\\/\\//, issue: 'Catch block only has comments', regulation: 'CC7.3' },\n { pattern: /\\.catch\\s*\\(\\s*\\(\\s*\\)\\s*=>\\s*\\{\\s*\\}\\s*\\)/, issue: 'Empty .catch() handler', regulation: 'CC7.3' },\n ],\n\n // CC8 - Change Management (implicit through code patterns)\n changeManagement: [\n { pattern: /\\/\\/\\s*HACK|\\/\\/\\s*FIXME.*security|\\/\\/\\s*XXX/i, issue: 'Security-related HACK/FIXME comment', regulation: 'CC8.1' },\n { pattern: /\\/\\/\\s*temporary|\\/\\/\\s*remove\\s*(before|in)\\s*prod/i, issue: 'Temporary code flagged for removal', regulation: 'CC8.1' },\n ],\n\n // Security - Encryption\n encryption: [\n { pattern: /md5\\s*\\(|crypto\\.createHash\\s*\\(\\s*['\"]md5['\"]\\s*\\)/i, issue: 'MD5 is cryptographically broken', regulation: 'CC6.7' },\n { pattern: /sha1\\s*\\(|crypto\\.createHash\\s*\\(\\s*['\"]sha1['\"]\\s*\\)/i, issue: 'SHA1 is deprecated for security use', regulation: 'CC6.7' },\n { pattern: /DES|3DES|RC4|Blowfish/i, issue: 'Weak/deprecated encryption algorithm', regulation: 'CC6.7' },\n { pattern: /Math\\.random\\s*\\(\\s*\\).*(?:token|key|secret|password|id)/i, issue: 'Math.random() used for security-sensitive value', regulation: 'CC6.7' },\n ],\n\n // Security - Input validation\n inputValidation: [\n { pattern: /eval\\s*\\(\\s*(?:req\\.|request\\.|params\\.|query\\.)/i, issue: 'eval() with user input - code injection risk', regulation: 'CC6.6' },\n { pattern: /innerHTML\\s*=\\s*(?:req\\.|request\\.|params\\.|data\\.)/i, issue: 'innerHTML with unescaped user input - XSS risk', regulation: 'CC6.6' },\n { pattern: /exec\\s*\\(\\s*(?:req\\.|request\\.|params\\.|`)/i, issue: 'Command execution with user input', regulation: 'CC6.6' },\n { pattern: /\\$\\{.*\\}.*(?:SELECT|INSERT|UPDATE|DELETE)/i, issue: 'SQL query with string interpolation', regulation: 'CC6.6' },\n ],\n\n // Security - Authentication\n authentication: [\n { pattern: /jwt\\.sign\\s*\\([^)]*expiresIn:\\s*['\"]?\\d{6,}['\"]?/i, issue: 'JWT with very long expiration', regulation: 'CC6.1' },\n { pattern: /verify\\s*[:=]\\s*false|rejectUnauthorized\\s*[:=]\\s*false/i, issue: 'TLS/SSL verification disabled', regulation: 'CC6.7' },\n { pattern: /sameSite\\s*[:=]\\s*['\"]none['\"]/i, issue: 'Cookie SameSite=None may enable CSRF', regulation: 'CC6.1' },\n { pattern: /httpOnly\\s*[:=]\\s*false/i, issue: 'Cookie httpOnly disabled - XSS risk', regulation: 'CC6.1' },\n { pattern: /secure\\s*[:=]\\s*false.*cookie/i, issue: 'Cookie secure flag disabled', regulation: 'CC6.1' },\n ],\n};\n\n// Map regulations to descriptions\nconst REGULATION_DESCRIPTIONS: Record<string, string> = {\n 'CC6.1': 'Logical Access Security - Access controls and authentication',\n 'CC6.2': 'Role-Based Access Control - Segregation of duties',\n 'CC6.3': 'Least Privilege - Minimal necessary access rights',\n 'CC6.6': 'Protection Against Threats - Input validation and injection prevention',\n 'CC6.7': 'Data Protection - Encryption and secure transmission',\n 'CC7.2': 'Monitoring - Security event logging without sensitive data exposure',\n 'CC7.3': 'Incident Detection - Proper error handling and alerting',\n 'CC8.1': 'Change Management - Controlled changes with proper review',\n};\n\nexport class SOC2Agent extends BaseAgent {\n name = 'soc2';\n description = 'SOC 2 Type II compliance: access controls, encryption, logging, change management';\n version = '1.0.0';\n\n shouldActivate(context: CodeContext): boolean {\n // SOC 2 is relevant for most production code\n return (\n context.touchesAuth ||\n context.touchesAPI ||\n context.touchesDatabase ||\n context.touchesUserData ||\n context.touchesSecurityConfig ||\n context.touchesLogging\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 non-code files\n if (/node_modules|\\.d\\.ts$|\\.min\\.|dist\\/|build\\/|\\.test\\.|\\.spec\\./i.test(file)) {\n continue;\n }\n\n try {\n const content = await this.readFile(file);\n const lines = content.split('\\n');\n\n // Check all SOC 2 pattern categories\n for (const [category, patterns] of Object.entries(SOC2_PATTERNS)) {\n for (const { pattern, issue, regulation } of patterns) {\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n \n if (pattern.test(line)) {\n // Skip if it's clearly in a test/example context\n if (this.isTestOrExample(line, content)) {\n continue;\n }\n\n const severity = this.getSeverity(category, regulation);\n const regulationDesc = REGULATION_DESCRIPTIONS[regulation] || regulation;\n\n issues.push(this.createIssue(\n this.generateIssueId(),\n severity,\n `[SOC 2 ${regulation}] ${issue}`,\n this.getFix(category, issue),\n file,\n i + 1,\n this.getConfidence(category),\n `SOC 2 ${regulation}: ${regulationDesc}`,\n this.isAutoFixable(category)\n ));\n \n // Only report first instance per pattern per file\n break;\n }\n }\n }\n }\n } catch (error) {\n console.error(`SOC2 Agent: Error reading file ${file}:`, error);\n }\n }\n\n return issues;\n }\n\n private isTestOrExample(line: string, content: string): boolean {\n // Check if line contains test/example indicators\n if (/example|test|mock|fake|dummy|placeholder|sample/i.test(line)) {\n return true;\n }\n // Check if we're in a test file context\n if (/describe\\s*\\(|it\\s*\\(|test\\s*\\(|jest|mocha|vitest/i.test(content.slice(0, 500))) {\n return true;\n }\n return false;\n }\n\n private getSeverity(category: string, regulation: string): 'critical' | 'serious' | 'moderate' | 'low' {\n // Critical: hardcoded secrets, code injection\n if (category === 'hardcodedSecrets' || regulation === 'CC6.6') {\n return 'critical';\n }\n // Serious: weak encryption, logging sensitive data, auth issues\n if (category === 'encryption' || category === 'logging' || category === 'authentication') {\n return 'serious';\n }\n // Moderate: access control, error handling\n if (category === 'accessControl' || category === 'errorHandling') {\n return 'moderate';\n }\n // Low: change management todos\n return 'low';\n }\n\n private getConfidence(category: string): number {\n switch (category) {\n case 'hardcodedSecrets': return 0.95;\n case 'logging': return 0.90;\n case 'encryption': return 0.85;\n case 'inputValidation': return 0.85;\n case 'authentication': return 0.80;\n case 'errorHandling': return 0.75;\n case 'accessControl': return 0.70;\n case 'changeManagement': return 0.60;\n default: return 0.70;\n }\n }\n\n private isAutoFixable(category: string): boolean {\n // Most SOC 2 issues require careful review\n return category === 'errorHandling';\n }\n\n private getFix(category: string, _issue: string): string {\n const fixes: Record<string, string> = {\n hardcodedSecrets: 'Move secrets to environment variables or a secrets manager (e.g., HashiCorp Vault, AWS Secrets Manager)',\n accessControl: 'Implement proper RBAC with dynamic role checking. Never hardcode admin privileges.',\n logging: 'Remove sensitive data from logs. Use structured logging with PII filtering.',\n errorHandling: 'Add proper error handling: log the error, notify monitoring, and return safe error messages.',\n encryption: 'Use strong algorithms: AES-256-GCM for encryption, SHA-256+ for hashing, crypto.randomBytes() for random values.',\n inputValidation: 'Validate and sanitize all user input. Use parameterized queries for SQL. Escape HTML output.',\n authentication: 'Use secure cookie settings (httpOnly, secure, sameSite). Set reasonable JWT expiration (15min-24h).',\n changeManagement: 'Address security-related TODOs before deployment. Document in issue tracker if deferring.',\n };\n return fixes[category] || 'Review and fix according to SOC 2 requirements.';\n }\n\n /**\n * AI Enhancement for SOC 2 compliance\n */\n protected override getAIEnhancementSystemPrompt(): string {\n return `You are a SOC 2 compliance auditor reviewing code for Trust Services Criteria violations.\n\nAnalyze detected issues for SOC 2 compliance:\n1. Security (CC6): Access controls, encryption, vulnerability management\n2. Availability (CC7): System operations, incident response\n3. Processing Integrity (CC8): Data accuracy, completeness\n4. Confidentiality (CC9): Data classification, access restrictions\n5. Privacy (P1-P8): GDPR-aligned privacy controls\n\nOutput STRICT JSON:\n{\n \"validated\": [{\n \"original_issue\": \"...\",\n \"verdict\": \"TRUE_POSITIVE\" | \"FALSE_POSITIVE\",\n \"confidence\": 0-100,\n \"file\": \"path\",\n \"line\": 123,\n \"severity\": \"critical\",\n \"soc2_criteria\": \"CC6.1 / CC7.2 / etc\",\n \"audit_risk\": \"What an auditor would flag\",\n \"fix\": \"Compliant implementation\"\n }],\n \"additional\": [{\n \"issue\": \"Compliance gap found\",\n \"file\": \"path\",\n \"line\": 123,\n \"severity\": \"serious\",\n \"soc2_criteria\": \"SOC 2 criteria\",\n \"audit_risk\": \"Audit finding risk\",\n \"fix\": \"Remediation steps\"\n }],\n \"summary\": \"SOC 2 audit readiness assessment\"\n}`;\n }\n}\n","import { BaseAgent } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\n\n/**\n * Super Reviewer Agent — Interactive AI-Guided Code Review\n * \n * Code reviews are the new bottleneck in AI coding. This agent scales them.\n * \n * Instead of AI replacing human judgment, it shepherds the human through the review:\n * - Walks through each file, chunk by chunk\n * - Explains changes, connects dots across files\n * - Correlates with design docs and context\n * - Pauses for cross-examination before moving on\n * - Sequences files for understandability\n * \n * The goal: Make reviewing a large PR a delight, not a chore.\n */\nexport class SuperReviewerAgent extends BaseAgent {\n name = 'super-reviewer';\n description = 'Interactive PR review: walks through changes file-by-file, explains each chunk, waits for cross-examination';\n version = '1.0.0';\n\n shouldActivate(context: CodeContext): boolean {\n // Activate when reviewing PRs or when there are significant changes\n return (\n context.linesChanged > 50 ||\n context.isNewFeature ||\n context.touchesAuth ||\n context.touchesPayments ||\n context.touchesDatabase ||\n context.touchesAPI\n );\n }\n\n /**\n * The Super Reviewer doesn't do static pattern matching like other agents.\n * Instead, it generates a structured review workflow for the AI to execute.\n */\n protected async analyzeFiles(_files: string[], _context: ScanContext): Promise<Issue[]> {\n // Super Reviewer doesn't produce issues in the traditional sense.\n // It produces a review workflow that Claude will execute interactively.\n return [];\n }\n\n /**\n * Get the structured review workflow for a set of files/changes\n */\n async buildReviewWorkflow(\n changedFiles: Array<{ path: string; diff: string; additions: number; deletions: number }>,\n options: {\n prNumber?: string | undefined;\n prTitle?: string | undefined;\n prAuthor?: string | undefined;\n baseBranch?: string | undefined;\n headBranch?: string | undefined;\n mode?: 'own' | 'others'; // 1 = your own PR, 2 = someone else's\n designDocs?: string[];\n }\n ): Promise<ReviewWorkflow> {\n // Order files for understanding (not alphabetically)\n const orderedFiles = this.orderFilesForReview(changedFiles);\n \n return {\n metadata: {\n prNumber: options.prNumber,\n prTitle: options.prTitle,\n prAuthor: options.prAuthor,\n baseBranch: options.baseBranch,\n headBranch: options.headBranch,\n mode: options.mode || 'own',\n totalFiles: changedFiles.length,\n totalAdditions: changedFiles.reduce((sum, f) => sum + f.additions, 0),\n totalDeletions: changedFiles.reduce((sum, f) => sum + f.deletions, 0),\n },\n fileOrder: orderedFiles.map((f, idx) => ({\n index: idx + 1,\n path: f.path,\n reason: f.orderReason,\n additions: f.additions,\n deletions: f.deletions,\n })),\n designDocs: options.designDocs || [],\n reviewInstructions: this.getReviewInstructions(options.mode || 'own'),\n };\n }\n\n /**\n * Order files for understanding, not alphabetically\n * \n * Strategy:\n * 1. Protos/schemas first — define data structures\n * 2. Constants/configs early — context for magic values\n * 3. Core logic before utilities — understand main change before helpers\n * 4. Implementation before tests — know what's being tested\n * 5. Docs/comments last — reference during review\n */\n private orderFilesForReview(\n files: Array<{ path: string; diff: string; additions: number; deletions: number }>\n ): Array<{ path: string; diff: string; additions: number; deletions: number; orderReason: string; priority: number }> {\n \n const scored = files.map(file => {\n let priority = 50; // Default middle priority\n let reason = 'General implementation';\n \n const path = file.path.toLowerCase();\n \n // Tier 1: Schemas, protos, types (defines data structures)\n if (/\\.(proto|graphql|prisma)$/.test(path) || \n /schema\\.(ts|js|json)$/.test(path) ||\n /types?\\.(ts|d\\.ts)$/.test(path) ||\n path.includes('/types/') ||\n path.includes('/schema/')) {\n priority = 10;\n reason = 'Defines data structures everything else uses';\n }\n // Tier 2: Constants, configs (context for magic values)\n else if (/constants?\\.(ts|js)$/.test(path) ||\n /config\\.(ts|js|json)$/.test(path) ||\n path.includes('/config/') ||\n /\\.env/.test(path)) {\n priority = 20;\n reason = 'Gives context for values used throughout';\n }\n // Tier 3: Core business logic\n else if (path.includes('/core/') ||\n path.includes('/services/') ||\n path.includes('/domain/') ||\n path.includes('/lib/')) {\n priority = 30;\n reason = 'Core logic — understand this first';\n }\n // Tier 4: API/routes\n else if (path.includes('/api/') ||\n path.includes('/routes/') ||\n path.includes('/handlers/') ||\n path.includes('/controllers/')) {\n priority = 40;\n reason = 'API layer — connects core logic to consumers';\n }\n // Tier 5: UI components (after understanding data flow)\n else if (path.includes('/components/') ||\n path.includes('/pages/') ||\n path.includes('/views/') ||\n /\\.(tsx|jsx|vue|svelte)$/.test(path)) {\n priority = 50;\n reason = 'UI layer — uses core logic and types';\n }\n // Tier 6: Utilities/helpers\n else if (path.includes('/utils/') ||\n path.includes('/helpers/') ||\n /utils?\\.(ts|js)$/.test(path)) {\n priority = 60;\n reason = 'Helper utilities';\n }\n // Tier 7: Tests (after understanding what they test)\n else if (/\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(path) ||\n path.includes('__tests__') ||\n path.includes('/test/')) {\n priority = 70;\n reason = 'Tests — review after understanding the implementation';\n }\n // Tier 8: Docs, comments, README\n else if (/\\.(md|mdx|txt)$/.test(path) ||\n /readme/i.test(path) ||\n path.includes('/docs/')) {\n priority = 80;\n reason = 'Documentation — reference during review as needed';\n }\n // Tier 9: Config files (package.json, etc.)\n else if (/package\\.json$/.test(path) ||\n /tsconfig/.test(path) ||\n /\\.config\\.(ts|js|json)$/.test(path)) {\n priority = 90;\n reason = 'Project config — review last';\n }\n \n return { ...file, priority, orderReason: reason };\n });\n \n // Sort by priority (lower = earlier in review)\n return scored.sort((a, b) => a.priority - b.priority);\n }\n\n /**\n * Get the review mode instructions\n */\n private getReviewInstructions(mode: 'own' | 'others'): ReviewInstructions {\n if (mode === 'own') {\n return {\n mode: 'own',\n description: 'Your own PR — I explain, you learn/verify/fix',\n approach: [\n 'Walk through each file explaining what changed and why',\n 'Help you understand your own code better',\n 'Identify potential issues before reviewers do',\n 'Suggest improvements you can make before requesting review',\n ],\n afterEachFile: [\n 'Pause for your questions',\n 'Discuss any concerns you have',\n 'Note any self-review fixes to make',\n ],\n };\n } else {\n return {\n mode: 'others',\n description: \"Someone else's PR — I flag issues, you add comments\",\n approach: [\n 'Analyze each file for correctness and completeness',\n 'Flag potential issues with suggested comment text',\n 'Look for missing pieces (cleanup handlers, tests, edge cases)',\n 'Check state/lifecycle consistency',\n ],\n afterEachFile: [\n 'Present draft comments for your approval',\n 'Let you modify or skip each comment',\n 'Post approved comments to PR',\n ],\n };\n }\n }\n}\n\n// Type definitions for the review workflow\nexport interface ReviewWorkflow {\n metadata: {\n prNumber?: string | undefined;\n prTitle?: string | undefined;\n prAuthor?: string | undefined;\n baseBranch?: string | undefined;\n headBranch?: string | undefined;\n mode: 'own' | 'others';\n totalFiles: number;\n totalAdditions: number;\n totalDeletions: number;\n };\n fileOrder: Array<{\n index: number;\n path: string;\n reason: string;\n additions: number;\n deletions: number;\n }>;\n designDocs: string[];\n reviewInstructions: ReviewInstructions;\n}\n\nexport interface ReviewInstructions {\n mode: 'own' | 'others';\n description: string;\n approach: string[];\n afterEachFile: string[];\n}\n\n/**\n * Critical Review Mindset Checklist\n * \n * These are the questions to ask during review:\n */\nexport const CRITICAL_REVIEW_CHECKLIST = {\n stateAndLifecycle: [\n 'Cleanup symmetry: If state is set, is it reset? Check cleanup paths.',\n 'Lifecycle consistency: Does state survive scenarios it shouldn\\'t?',\n 'Guard completeness: Are there missing guards (already active, re-entrancy)?',\n ],\n edgeCasesAndRaces: [\n 'Concurrent calls: What if called twice rapidly? Orphaned promises?',\n 'Ordering assumptions: Does code assume events arrive in order?',\n 'Partial failures: If step 3 of 5 fails, is state left consistent?',\n ],\n missingPieces: [\n 'What\\'s NOT in the diff that should be? (cleanup handlers, tests)',\n 'Defensive gaps: Missing timeouts, size limits, null checks?',\n ],\n designQuestions: [\n 'Is this the right approach? Is there a simpler/more robust design?',\n 'Hidden assumptions: What does this assume about its environment?',\n ],\n};\n","import { BaseAgent } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\n\n/**\n * Performance Agent\n * \n * Surfaces performance concerns for human review. Does NOT auto-score or claim\n * to measure \"real\" performance - that requires runtime profiling.\n * \n * What it does:\n * - Identifies patterns commonly associated with performance issues\n * - Flags potential memory leaks, unnecessary re-renders, large bundles\n * - Highlights N+1 query patterns and unoptimized loops\n * - Suggests areas for human investigation with profiling tools\n * \n * What it doesn't do:\n * - Claim to measure actual performance\n * - Auto-fix without human review (many \"fixes\" trade off other concerns)\n * - Replace real profiling, load testing, or production monitoring\n */\nexport class PerformanceAgent extends BaseAgent {\n name = 'performance';\n description = 'Surfaces performance patterns for human review: memory, renders, bundles, queries';\n version = '1.0.0';\n\n shouldActivate(context: CodeContext): boolean {\n return (\n context.touchesUI ||\n context.touchesDatabase ||\n context.touchesAPI ||\n context.patterns.hasAsyncCode ||\n context.linesChanged > 100\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.checkMemoryPatterns(content, file));\n issues.push(...this.checkRenderPatterns(content, file));\n issues.push(...this.checkQueryPatterns(content, file));\n issues.push(...this.checkBundlePatterns(content, file));\n issues.push(...this.checkLoopPatterns(content, file));\n } catch {\n // Skip unreadable files\n }\n }\n\n return issues;\n }\n\n private checkMemoryPatterns(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 // Event listeners without cleanup\n if (/addEventListener\\s*\\(/.test(line) && !content.includes('removeEventListener')) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Event listener may not be cleaned up',\n 'Ensure removeEventListener is called on cleanup (useEffect return, componentWillUnmount)',\n file,\n lineNumber,\n 0.75,\n undefined,\n false,\n { category: 'memory-leak', effort: 'easy' }\n ));\n }\n\n // setInterval without cleanup\n if (/setInterval\\s*\\(/.test(line) && !content.includes('clearInterval')) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'setInterval without clearInterval - likely memory leak',\n 'Store interval ID and call clearInterval on cleanup',\n file,\n lineNumber,\n 0.90,\n undefined,\n false,\n { category: 'memory-leak', effort: 'easy' }\n ));\n }\n\n // Large arrays stored in state without cleanup\n if (/useState.*\\[\\]/.test(line) && /\\.push|\\.concat|\\.unshift/.test(content)) {\n // Check if there's any cleanup or limit\n if (!/\\.slice\\(|\\.splice\\(|length\\s*[<>]/.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Array state may grow unbounded - review if intentional',\n 'Consider limiting array size or implementing pagination',\n file,\n lineNumber,\n 0.60,\n undefined,\n false,\n { category: 'memory-growth', effort: 'medium' }\n ));\n }\n }\n\n // Closures capturing large objects\n if (/useCallback|useMemo/.test(line)) {\n const deps = line.match(/\\[([^\\]]*)\\]/);\n if (deps && deps[1] && deps[1].split(',').length > 5) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Hook with many dependencies may indicate stale closure risk',\n 'Review dependencies - consider restructuring to reduce coupling',\n file,\n lineNumber,\n 0.50,\n undefined,\n false,\n { category: 'closure', effort: 'medium' }\n ));\n }\n }\n }\n\n return issues;\n }\n\n private checkRenderPatterns(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n // Only check React/UI files\n if (!/\\.(tsx|jsx)$/.test(file)) return issues;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n const lineNumber = i + 1;\n\n // Inline object/array creation in JSX props\n if (/style=\\{\\{/.test(line) || /=\\{\\[.*\\]\\}/.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Inline object/array in JSX creates new reference each render',\n 'Extract to useMemo or constant outside component if values are static',\n file,\n lineNumber,\n 0.65,\n undefined,\n false,\n { category: 'unnecessary-render', effort: 'easy' }\n ));\n }\n\n // Anonymous functions in JSX\n if (/onClick=\\{\\s*\\(\\)\\s*=>/.test(line) || /onChange=\\{\\s*\\(e\\)\\s*=>/.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Anonymous function in JSX may cause child re-renders',\n 'Consider useCallback if passing to memoized children',\n file,\n lineNumber,\n 0.50,\n undefined,\n false,\n { category: 'unnecessary-render', effort: 'easy' }\n ));\n }\n\n // Missing key in map\n if (/\\.map\\s*\\(/.test(line) && !content.slice(i * 50, (i + 5) * 50).includes('key=')) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Array rendering may be missing key prop',\n 'Add unique key prop to prevent unnecessary DOM reconciliation',\n file,\n lineNumber,\n 0.80,\n undefined,\n false,\n { category: 'reconciliation', effort: 'trivial' }\n ));\n }\n\n // useEffect with no dependencies (runs every render)\n if (/useEffect\\s*\\(\\s*\\(\\)\\s*=>/.test(line)) {\n const effectEnd = content.indexOf(')', content.indexOf('useEffect', i * 50) + 50);\n const effectContent = content.slice(i * 50, effectEnd);\n if (!/\\],?\\s*\\)/.test(effectContent)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'useEffect appears to run on every render (missing dependency array)',\n 'Add dependency array [] for mount-only or [deps] for specific triggers',\n file,\n lineNumber,\n 0.85,\n undefined,\n false,\n { category: 'effect-loop', effort: 'easy' }\n ));\n }\n }\n }\n\n return issues;\n }\n\n private checkQueryPatterns(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 // N+1 query pattern: query in a loop\n if (/for\\s*\\(|\\.forEach|\\.map/.test(line)) {\n const loopContent = lines.slice(i, Math.min(i + 15, lines.length)).join('\\n');\n if (/await.*find|query|fetch|SELECT|prisma\\.|mongoose\\./i.test(loopContent)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Potential N+1 query: database/API call inside loop',\n 'Batch queries outside loop or use eager loading (include/populate/join)',\n file,\n lineNumber,\n 0.90,\n undefined,\n false,\n { category: 'n-plus-one', effort: 'medium' }\n ));\n }\n }\n\n // SELECT * patterns\n if (/SELECT\\s+\\*\\s+FROM/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'SELECT * fetches all columns - may transfer unnecessary data',\n 'Select only needed columns for better performance',\n file,\n lineNumber,\n 0.75,\n undefined,\n false,\n { category: 'over-fetching', effort: 'easy' }\n ));\n }\n\n // Missing pagination\n if (/findMany|find\\(\\)|SELECT.*FROM/i.test(line) && \n !/limit|take|skip|offset|LIMIT|TOP/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Query may return unbounded results - no pagination detected',\n 'Add LIMIT/take/pagination to prevent loading entire tables',\n file,\n lineNumber,\n 0.70,\n undefined,\n false,\n { category: 'unbounded-query', effort: 'easy' }\n ));\n }\n }\n\n return issues;\n }\n\n private checkBundlePatterns(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 // Large library imports without tree-shaking\n const heavyLibs = ['lodash', 'moment', 'antd', 'material-ui', '@mui/material'];\n for (const lib of heavyLibs) {\n if (new RegExp(`import\\\\s+\\\\w+\\\\s+from\\\\s+['\"]${lib}['\"]`).test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n `Full ${lib} import may bloat bundle - use named imports`,\n `Change to: import { specificFunc } from '${lib}/specificFunc'`,\n file,\n lineNumber,\n 0.85,\n undefined,\n false,\n { category: 'bundle-size', effort: 'easy' }\n ));\n }\n }\n\n // Dynamic imports could help\n if (/import\\s+.*\\s+from/.test(line) && /Modal|Dialog|Chart|Editor|PDF/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Heavy component could benefit from dynamic import',\n 'Consider: const Component = dynamic(() => import(\"...\"))',\n file,\n lineNumber,\n 0.60,\n undefined,\n false,\n { category: 'code-splitting', effort: 'easy' }\n ));\n }\n }\n\n return issues;\n }\n\n private checkLoopPatterns(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 // Nested loops\n if (/for\\s*\\(/.test(line)) {\n const innerContent = lines.slice(i + 1, Math.min(i + 20, lines.length)).join('\\n');\n if (/for\\s*\\(|\\.forEach|\\.map.*\\.map|\\.filter.*\\.map/.test(innerContent)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Nested iteration detected - O(n²) or worse complexity',\n 'Consider: Map/Set for lookups, single-pass algorithms, or indexing',\n file,\n lineNumber,\n 0.75,\n undefined,\n false,\n { category: 'algorithmic', effort: 'medium' }\n ));\n }\n }\n\n // Array methods that could be combined\n if (/\\.filter\\(.*\\)\\.map\\(/.test(line) || /\\.map\\(.*\\)\\.filter\\(/.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Chained filter/map creates intermediate arrays',\n 'Consider combining into single reduce for large arrays',\n file,\n lineNumber,\n 0.50,\n undefined,\n false,\n { category: 'array-allocation', effort: 'easy' }\n ));\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\n/**\n * E2E Agent\n * \n * Identifies gaps in end-to-end test coverage and common testing anti-patterns.\n * Does NOT generate tests automatically - that requires human understanding of\n * user flows and acceptance criteria.\n * \n * What it does:\n * - Identifies pages/routes without corresponding E2E tests\n * - Flags flaky test patterns (timing issues, race conditions)\n * - Surfaces missing critical path coverage\n * - Checks for testing anti-patterns\n * \n * What it doesn't do:\n * - Auto-generate meaningful E2E tests (requires domain knowledge)\n * - Replace human QA thinking about user journeys\n * - Validate that existing tests actually test the right things\n */\nexport class E2EAgent extends BaseAgent {\n name = 'e2e';\n description = 'Identifies E2E test gaps and flaky test patterns for human review';\n version = '1.0.0';\n\n shouldActivate(context: CodeContext): boolean {\n return (\n context.touchesUI ||\n context.isNewFeature ||\n context.patterns.hasFormHandling\n );\n }\n\n protected async analyzeFiles(files: string[], _context: ScanContext): Promise<Issue[]> {\n const issues: Issue[] = [];\n\n // Separate test files from source files\n const testFiles = files.filter(f => this.isTestFile(f));\n const sourceFiles = files.filter(f => !this.isTestFile(f));\n const e2eFiles = testFiles.filter(f => /e2e|playwright|cypress|spec\\.(ts|js)$/i.test(f));\n\n // Check for missing E2E coverage\n issues.push(...this.checkMissingCoverage(sourceFiles, e2eFiles));\n\n // Check E2E test files for anti-patterns\n for (const file of e2eFiles) {\n try {\n const content = await this.readFile(file);\n issues.push(...this.checkFlakyPatterns(content, file));\n issues.push(...this.checkTestAntiPatterns(content, file));\n } catch {\n // Skip unreadable files\n }\n }\n\n // Check source files for untestable patterns\n for (const file of sourceFiles) {\n try {\n const content = await this.readFile(file);\n issues.push(...this.checkUntestablePatterns(content, file));\n } catch {\n // Skip\n }\n }\n\n return issues;\n }\n\n private isTestFile(file: string): boolean {\n return /\\.(test|spec|e2e)\\.[jt]sx?$/.test(file) ||\n /__tests__|e2e|playwright|cypress/.test(file);\n }\n\n private checkMissingCoverage(sourceFiles: string[], e2eFiles: string[]): Issue[] {\n const issues: Issue[] = [];\n\n // Find pages/routes without E2E tests\n const pageFiles = sourceFiles.filter(f => \n /pages?\\/|routes?\\/|views?\\/|screens?\\//.test(f) &&\n /\\.(tsx|jsx|vue|svelte)$/.test(f) &&\n !/layout|_app|_document|index\\.(tsx|jsx)$/.test(f)\n );\n\n const e2eContent = e2eFiles.join(' '); // Rough check\n\n for (const page of pageFiles) {\n const pageName = page.split('/').pop()?.replace(/\\.[^.]+$/, '') || '';\n // Very rough heuristic - real analysis would need to parse test files\n if (pageName && pageName.length > 2 && !e2eContent.toLowerCase().includes(pageName.toLowerCase())) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n `Page \"${pageName}\" may lack E2E test coverage`,\n 'Consider adding E2E tests for critical user flows on this page',\n page,\n 1,\n 0.50,\n undefined,\n false,\n { category: 'coverage-gap', effort: 'hard' }\n ));\n }\n }\n\n // Check for forms without E2E tests\n const formFiles = sourceFiles.filter(f => /form/i.test(f));\n for (const form of formFiles) {\n if (!e2eContent.toLowerCase().includes('form')) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Form components may lack E2E validation testing',\n 'Forms are high-value E2E targets - test submit, validation, error states',\n form,\n 1,\n 0.60,\n undefined,\n false,\n { category: 'form-testing', effort: 'medium' }\n ));\n break; // Only warn once\n }\n }\n\n return issues;\n }\n\n private checkFlakyPatterns(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 // Hardcoded waits\n if (/waitForTimeout|sleep|wait\\s*\\(\\s*\\d+\\s*\\)|setTimeout/.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Hardcoded wait is flaky - use explicit conditions instead',\n 'Replace with: waitForSelector, waitForResponse, or expect().toBeVisible()',\n file,\n lineNumber,\n 0.95,\n undefined,\n false,\n { category: 'flaky-test', effort: 'easy' }\n ));\n }\n\n // Time-sensitive assertions\n if (/expect.*Date\\.now|expect.*new Date/.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Time-based assertion may be flaky across timezones/speeds',\n 'Mock time in tests or use relative comparisons',\n file,\n lineNumber,\n 0.75,\n undefined,\n false,\n { category: 'flaky-test', effort: 'medium' }\n ));\n }\n\n // Non-deterministic selectors\n if (/getBy(TestId|Role|Text|Label)/.test(line)) {\n // Good - skip\n } else if (/querySelector|css=|xpath=|nth-child|:nth-of-type/.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Positional/CSS selector may break if DOM structure changes',\n 'Prefer data-testid, role, or text-based selectors for stability',\n file,\n lineNumber,\n 0.70,\n undefined,\n false,\n { category: 'brittle-selector', effort: 'easy' }\n ));\n }\n\n // Race conditions\n if (/click.*click|fill.*fill/.test(lines.slice(i, i + 3).join(''))) {\n const context = lines.slice(i, i + 3).join('');\n if (!/await.*await|waitFor/.test(context)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Rapid sequential actions without awaiting may cause race conditions',\n 'Ensure each action is awaited or add explicit waits between actions',\n file,\n lineNumber,\n 0.65,\n undefined,\n false,\n { category: 'race-condition', effort: 'easy' }\n ));\n }\n }\n }\n\n return issues;\n }\n\n private checkTestAntiPatterns(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 // Tests without assertions\n if (/it\\s*\\(|test\\s*\\(/.test(line)) {\n const testBlock = lines.slice(i, Math.min(i + 30, lines.length)).join('\\n');\n const nextTestIndex = testBlock.slice(10).search(/it\\s*\\(|test\\s*\\(|describe\\s*\\(/);\n const testContent = nextTestIndex > 0 ? testBlock.slice(0, nextTestIndex + 10) : testBlock;\n \n if (!/expect|assert|should|toBe|toHave|toEqual|toMatch/.test(testContent)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Test appears to have no assertions',\n 'Add expect() calls to verify expected behavior',\n file,\n lineNumber,\n 0.80,\n undefined,\n false,\n { category: 'missing-assertion', effort: 'easy' }\n ));\n }\n }\n\n // Commented out tests\n if (/\\/\\/\\s*(it|test|describe)\\s*\\(|\\/\\*.*\\b(it|test)\\b/.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Commented out test - remove or fix',\n 'Either fix the test or delete it - commented code is tech debt',\n file,\n lineNumber,\n 0.90,\n undefined,\n false,\n { category: 'dead-test', effort: 'trivial' }\n ));\n }\n\n // Skip/only left in\n if (/\\.(only|skip)\\s*\\(/.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n '.only() or .skip() should not be committed',\n 'Remove .only()/.skip() before merging',\n file,\n lineNumber,\n 0.95,\n undefined,\n true, // Auto-fixable\n { category: 'test-hygiene', effort: 'trivial' }\n ));\n }\n }\n\n return issues;\n }\n\n private checkUntestablePatterns(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n // Only check UI files\n if (!/\\.(tsx|jsx|vue|svelte)$/.test(file)) return issues;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n const lineNumber = i + 1;\n\n // Missing data-testid on interactive elements\n if (/<(button|input|form|select|a)\\s/.test(line) && !/data-testid/.test(line)) {\n // Only flag if it's a significant element (has handlers or important attributes)\n if (/onClick|onSubmit|href=|type=[\"']submit/.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Interactive element lacks data-testid for E2E targeting',\n 'Add data-testid=\"descriptive-name\" for stable test selectors',\n file,\n lineNumber,\n 0.55,\n undefined,\n true, // Could auto-add\n { category: 'testability', effort: 'trivial' }\n ));\n }\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\n/**\n * Visual QA Agent\n * \n * Identifies potential visual/layout issues in CSS and components.\n * Does NOT actually render or screenshot - that requires a browser.\n * \n * What it does:\n * - Flags CSS patterns known to cause layout shifts\n * - Identifies missing responsive handling\n * - Surfaces z-index conflicts and overflow issues\n * - Highlights accessibility contrast concerns\n * \n * What it doesn't do:\n * - Actually see the rendered output (would need Playwright + vision)\n * - Replace human visual review of designs\n * - Guarantee pixel-perfect layouts\n */\nexport class VisualQAAgent extends BaseAgent {\n name = 'visual-qa';\n description = 'Surfaces potential visual/layout issues in CSS for human review';\n version = '1.0.0';\n\n shouldActivate(context: CodeContext): boolean {\n return (\n context.touchesUI ||\n context.filePatterns.some(f => /\\.(css|scss|sass|less|styled)/.test(f))\n );\n }\n\n protected async analyzeFiles(files: string[], _context: ScanContext): Promise<Issue[]> {\n const issues: Issue[] = [];\n\n const styleFiles = files.filter(f => /\\.(css|scss|sass|less)$/.test(f));\n const componentFiles = files.filter(f => /\\.(tsx|jsx|vue|svelte)$/.test(f));\n\n for (const file of [...styleFiles, ...componentFiles]) {\n try {\n const content = await this.readFile(file);\n issues.push(...this.checkLayoutShifts(content, file));\n issues.push(...this.checkResponsive(content, file));\n issues.push(...this.checkZIndex(content, file));\n issues.push(...this.checkOverflow(content, file));\n issues.push(...this.checkAccessibility(content, file));\n issues.push(...this.checkAnimations(content, file));\n } catch {\n // Skip unreadable files\n }\n }\n\n return issues;\n }\n\n private checkLayoutShifts(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 // Images without dimensions\n if (/<img\\s/.test(line) && !/width|height|aspect-ratio|fill/.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Image without explicit dimensions may cause layout shift (CLS)',\n 'Add width/height attributes or use aspect-ratio container',\n file,\n lineNumber,\n 0.85,\n undefined,\n false,\n { category: 'cls', effort: 'easy' }\n ));\n }\n\n // Dynamic content without min-height\n if (/{.*loading|isLoading|skeleton/i.test(line)) {\n const context = lines.slice(Math.max(0, i - 5), i + 5).join('\\n');\n if (!/min-height|min-h-|skeleton|placeholder/.test(context)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Loading state may cause layout shift if content height varies',\n 'Consider min-height or skeleton with matching dimensions',\n file,\n lineNumber,\n 0.60,\n undefined,\n false,\n { category: 'cls', effort: 'easy' }\n ));\n }\n }\n\n // Font loading without fallback sizing\n if (/font-family/.test(line) && /url\\(|@import|@font-face/.test(content)) {\n if (!/font-display:\\s*swap|font-display:\\s*optional|size-adjust/.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Custom font without font-display may cause FOIT/FOUT',\n 'Add font-display: swap to @font-face or use size-adjust fallback',\n file,\n lineNumber,\n 0.70,\n undefined,\n false,\n { category: 'font-loading', effort: 'easy' }\n ));\n }\n }\n }\n\n return issues;\n }\n\n private checkResponsive(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n // Check for fixed widths without responsive handling\n let hasMediaQuery = /@media|breakpoint|sm:|md:|lg:|xl:/.test(content);\n let hasFixedWidth = /width:\\s*\\d+px/.test(content);\n\n if (hasFixedWidth && !hasMediaQuery && /\\.(css|scss|sass|less)$/.test(file)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Fixed pixel widths without responsive breakpoints',\n 'Consider using relative units (%, rem, vw) or add media queries',\n file,\n 1,\n 0.65,\n undefined,\n false,\n { category: 'responsive', effort: 'medium' }\n ));\n }\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n const lineNumber = i + 1;\n\n // Viewport units without fallback\n if (/100vh/.test(line) && !/dvh|svh|lvh/.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n '100vh can cause issues on mobile (address bar)',\n 'Consider 100dvh (dynamic viewport) or JS-based solution',\n file,\n lineNumber,\n 0.60,\n undefined,\n false,\n { category: 'mobile', effort: 'easy' }\n ));\n }\n\n // Text that might overflow\n if (/text-overflow:\\s*ellipsis/.test(line)) {\n const context = lines.slice(Math.max(0, i - 3), i + 3).join('\\n');\n if (!/white-space:\\s*nowrap/.test(context) || !/overflow:\\s*(hidden|clip)/.test(context)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'text-overflow: ellipsis requires white-space: nowrap and overflow: hidden',\n 'Add missing properties for ellipsis to work',\n file,\n lineNumber,\n 0.90,\n undefined,\n false,\n { category: 'text-overflow', effort: 'trivial' }\n ));\n }\n }\n }\n\n return issues;\n }\n\n private checkZIndex(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n const zIndexValues: number[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n const lineNumber = i + 1;\n\n const match = line.match(/z-index:\\s*(\\d+)/);\n if (match) {\n const value = parseInt(match[1] || '0', 10);\n zIndexValues.push(value);\n\n // Extremely high z-index\n if (value > 1000) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n `z-index: ${value} is very high - may indicate z-index wars`,\n 'Use a z-index scale (1-10) and stacking contexts instead',\n file,\n lineNumber,\n 0.70,\n undefined,\n false,\n { category: 'z-index', effort: 'medium' }\n ));\n }\n\n // Magic number z-index\n if (value > 10 && value !== 50 && value !== 100 && value !== 999 && value !== 9999) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n `z-index: ${value} appears arbitrary - consider named tokens`,\n 'Define z-index scale: --z-dropdown: 10, --z-modal: 20, etc.',\n file,\n lineNumber,\n 0.50,\n undefined,\n false,\n { category: 'z-index', effort: 'easy' }\n ));\n }\n }\n }\n\n return issues;\n }\n\n private checkOverflow(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 // Horizontal scrolling risks\n if (/width:\\s*(100vw|\\d{4,}px)/.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n '100vw or large fixed width may cause horizontal scroll on mobile',\n 'Use 100% or max-width: 100vw with overflow-x: hidden on body',\n file,\n lineNumber,\n 0.75,\n undefined,\n false,\n { category: 'overflow', effort: 'easy' }\n ));\n }\n\n // Missing overflow handling on flex/grid containers\n if (/display:\\s*(flex|grid)/.test(line)) {\n const context = lines.slice(i, Math.min(i + 10, lines.length)).join('\\n');\n if (/flex-shrink:\\s*0|flex:\\s*0\\s+0|min-width:\\s*0/.test(context)) {\n // Good - they're handling shrinking\n } else if (/width|min-width/.test(context) && !/overflow|text-overflow|min-width:\\s*0/.test(context)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Flex/grid items may overflow container without min-width: 0',\n 'Add min-width: 0 to allow proper shrinking of flex children',\n file,\n lineNumber,\n 0.55,\n undefined,\n false,\n { category: 'flex-overflow', effort: 'trivial' }\n ));\n }\n }\n }\n\n return issues;\n }\n\n private checkAccessibility(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 // Tiny text\n if (/font-size:\\s*(\\d+)px/.test(line)) {\n const size = parseInt(line.match(/font-size:\\s*(\\d+)px/)?.[1] || '16', 10);\n if (size < 12) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n `Font size ${size}px is below minimum readable size`,\n 'Use at least 12px (preferably 14-16px) for body text',\n file,\n lineNumber,\n 0.85,\n undefined,\n false,\n { category: 'accessibility', effort: 'trivial' }\n ));\n }\n }\n\n // Low contrast colors (rough heuristic)\n if (/color:\\s*#([a-fA-F0-9]{6})/.test(line)) {\n const context = lines.slice(Math.max(0, i - 5), i + 5).join('\\n');\n const colorMatch = line.match(/color:\\s*#([a-fA-F0-9]{6})/);\n const bgMatch = context.match(/background(-color)?:\\s*#([a-fA-F0-9]{6})/);\n \n if (colorMatch && bgMatch) {\n // Very rough contrast check - just flag light-on-light or dark-on-dark\n const textLightness = this.getHexLightness(colorMatch[1] || 'ffffff');\n const bgLightness = this.getHexLightness(bgMatch[2] || '000000');\n \n if (Math.abs(textLightness - bgLightness) < 30) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Text and background colors may have insufficient contrast',\n 'Check with a contrast checker - WCAG requires 4.5:1 for normal text',\n file,\n lineNumber,\n 0.60,\n undefined,\n false,\n { category: 'contrast', effort: 'easy' }\n ));\n }\n }\n }\n\n // Focus outline removal\n if (/outline:\\s*none|outline:\\s*0/.test(line) && !/focus-visible|:focus.*outline/.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Removing focus outline breaks keyboard navigation',\n 'If removing default outline, add custom :focus-visible styles',\n file,\n lineNumber,\n 0.95,\n undefined,\n false,\n { category: 'focus', effort: 'easy' }\n ));\n }\n }\n\n return issues;\n }\n\n private checkAnimations(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n // Check for prefers-reduced-motion support\n const hasAnimations = /animation|transition|@keyframes/.test(content);\n const hasReducedMotion = /prefers-reduced-motion/.test(content);\n\n if (hasAnimations && !hasReducedMotion) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Animations without prefers-reduced-motion support',\n 'Add @media (prefers-reduced-motion: reduce) to disable/reduce animations',\n file,\n 1,\n 0.75,\n undefined,\n false,\n { category: 'motion', effort: 'easy' }\n ));\n }\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n const lineNumber = i + 1;\n\n // Long animations that might feel slow\n if (/animation.*(\\d+)s/.test(line) || /transition.*(\\d+)s/.test(line)) {\n const duration = parseFloat(line.match(/(\\d+\\.?\\d*)s/)?.[1] || '0');\n if (duration > 1) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n `${duration}s animation may feel slow - typical max is 300-500ms`,\n 'Consider shorter duration or ensure long animation is intentional',\n file,\n lineNumber,\n 0.50,\n undefined,\n false,\n { category: 'animation-timing', effort: 'trivial' }\n ));\n }\n }\n }\n\n return issues;\n }\n\n private getHexLightness(hex: string): number {\n const r = parseInt(hex.slice(0, 2), 16);\n const g = parseInt(hex.slice(2, 4), 16);\n const b = parseInt(hex.slice(4, 6), 16);\n return (r * 0.299 + g * 0.587 + b * 0.114); // Perceived brightness\n }\n}\n","import { BaseAgent } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\n\n/**\n * Data Flow Agent\n * \n * Identifies schema mismatches, placeholder data, and data integrity issues.\n * This is one of the most valuable agents for catching real bugs that AI\n * code generation commonly introduces.\n * \n * What it does:\n * - Detects placeholder/mock data left in production code\n * - Identifies schema mismatches between frontend and backend\n * - Flags hardcoded IDs, emails, URLs that should be dynamic\n * - Surfaces potential data transformation bugs\n * \n * What it doesn't do:\n * - Validate actual runtime data (needs real execution)\n * - Replace integration testing\n * - Understand your domain model (needs human context)\n */\nexport class DataFlowAgent extends BaseAgent {\n name = 'data-flow';\n description = 'Detects schema mismatches, placeholder data, and data integrity issues';\n version = '1.0.0';\n\n shouldActivate(context: CodeContext): boolean {\n return (\n context.touchesAPI ||\n context.touchesDatabase ||\n context.isNewFeature ||\n context.patterns.hasFormHandling\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 \n // Skip test files for placeholder detection\n const isTest = this.isTestFile(file);\n \n if (!isTest) {\n issues.push(...this.checkPlaceholders(content, file));\n issues.push(...this.checkHardcodedData(content, file));\n }\n \n issues.push(...this.checkSchemaMismatches(content, file));\n issues.push(...this.checkDataTransformations(content, file));\n issues.push(...this.checkTypeCoercion(content, file));\n } catch {\n // Skip unreadable files\n }\n }\n\n return issues;\n }\n\n private isTestFile(file: string): boolean {\n return /\\.(test|spec)\\.[jt]sx?$/.test(file) ||\n /__tests__|__mocks__|fixtures|mock/.test(file);\n }\n\n private checkPlaceholders(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n // Common placeholder patterns\n const placeholderPatterns = [\n { pattern: /[\"']lorem ipsum/i, desc: 'Lorem ipsum placeholder text' },\n { pattern: /[\"']test@(test|example)\\.com[\"']/i, desc: 'Test email address' },\n { pattern: /[\"']TODO[\"']|[\"']FIXME[\"']|[\"']PLACEHOLDER[\"']/i, desc: 'TODO/PLACEHOLDER string value' },\n { pattern: /[\"']xxx[\"']|[\"']yyy[\"']|[\"']zzz[\"']/i, desc: 'Placeholder string (xxx/yyy/zzz)' },\n { pattern: /[\"']foo[\"']|[\"']bar[\"']|[\"']baz[\"']/, desc: 'Common placeholder names' },\n { pattern: /[\"']asdf[\"']|[\"']qwerty[\"']/i, desc: 'Keyboard mash placeholder' },\n { pattern: /[\"']changeme[\"']|[\"']replace[-_]?me[\"']/i, desc: 'Replace-me placeholder' },\n { pattern: /[\"']your[-_]?.*[-_]?here[\"']/i, desc: 'Your-X-here placeholder' },\n { pattern: /price:\\s*0[,\\s]|amount:\\s*0[,\\s]|total:\\s*0[,\\s]/i, desc: 'Zero price/amount (placeholder?)' },\n ];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n const lineNumber = i + 1;\n\n for (const { pattern, desc } of placeholderPatterns) {\n if (pattern.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n `Placeholder data in production code: ${desc}`,\n 'Replace with real data or remove before shipping',\n file,\n lineNumber,\n 0.90,\n undefined,\n false,\n { category: 'placeholder', effort: 'easy' }\n ));\n break; // One issue per line\n }\n }\n\n // Sample/demo data arrays\n if (/const\\s+\\w+\\s*=\\s*\\[/.test(line)) {\n const arrayContent = lines.slice(i, Math.min(i + 20, lines.length)).join('\\n');\n if (/Sample|Demo|Fake|Mock|Dummy|Test\\s*(User|Item|Product)/i.test(arrayContent) &&\n !/mock|test|spec|fixture|story/.test(file.toLowerCase())) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Hardcoded sample/demo data found - should this be fetched?',\n 'Replace with API call or move to fixtures if for testing',\n file,\n lineNumber,\n 0.75,\n undefined,\n false,\n { category: 'mock-data', effort: 'medium' }\n ));\n }\n }\n }\n\n return issues;\n }\n\n private checkHardcodedData(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 // Hardcoded UUIDs (not in config/constants)\n if (/[\"'][0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}[\"']/i.test(line)) {\n if (!/const|config|env|fixture|mock|test/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Hardcoded UUID - should this be dynamic?',\n 'If this is a real ID, it should come from API/config. If test data, move to fixtures.',\n file,\n lineNumber,\n 0.70,\n undefined,\n false,\n { category: 'hardcoded-id', effort: 'easy' }\n ));\n }\n }\n\n // Hardcoded dates that might go stale\n if (/[\"']20[2-3][0-9]-[0-1][0-9]-[0-3][0-9]/.test(line)) {\n if (!/birthday|created|founded|copyright|version/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Hardcoded date - will this become stale?',\n 'Consider using relative dates or Date.now() if dynamic needed',\n file,\n lineNumber,\n 0.55,\n undefined,\n false,\n { category: 'hardcoded-date', effort: 'easy' }\n ));\n }\n }\n\n // Hardcoded API endpoints\n if (/[\"'](https?:\\/\\/[^\"']+api[^\"']+)[\"']/.test(line)) {\n if (!/config|env|\\.env|constant/i.test(file)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Hardcoded API URL - should use environment config',\n 'Move to environment variable or config file',\n file,\n lineNumber,\n 0.80,\n undefined,\n false,\n { category: 'hardcoded-url', effort: 'easy' }\n ));\n }\n }\n }\n\n return issues;\n }\n\n private checkSchemaMismatches(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 // Optional chaining on required fields (might indicate schema uncertainty)\n const optionalChainCount = (line.match(/\\?\\./g) || []).length;\n if (optionalChainCount >= 3) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Heavy optional chaining may indicate schema uncertainty',\n 'Review: if data structure is well-defined, some ?. may be unnecessary',\n file,\n lineNumber,\n 0.50,\n undefined,\n false,\n { category: 'schema', effort: 'medium' }\n ));\n }\n\n // Type assertions that might hide mismatches\n if (/as\\s+\\w+(\\[\\])?[,;\\s)]/.test(line) && !/as\\s+const/.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Type assertion may hide actual type mismatch',\n 'Prefer type guards or validation for runtime safety',\n file,\n lineNumber,\n 0.45,\n undefined,\n false,\n { category: 'type-assertion', effort: 'medium' }\n ));\n }\n\n // Accessing properties that might not exist\n if (/response\\.(data|body)\\.(\\w+)\\.(\\w+)\\.(\\w+)/.test(line)) {\n if (!/\\?\\./.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Deep property access on API response without null checks',\n 'Add optional chaining or validate response structure',\n file,\n lineNumber,\n 0.75,\n undefined,\n false,\n { category: 'null-access', effort: 'easy' }\n ));\n }\n }\n }\n\n return issues;\n }\n\n private checkDataTransformations(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 // JSON.parse without error handling\n if (/JSON\\.parse\\(/.test(line)) {\n const context = lines.slice(Math.max(0, i - 3), Math.min(i + 5, lines.length)).join('\\n');\n if (!/try|catch|\\.catch/.test(context)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'JSON.parse without error handling - will throw on invalid JSON',\n 'Wrap in try/catch or use a safe parse utility',\n file,\n lineNumber,\n 0.85,\n undefined,\n false,\n { category: 'parse-error', effort: 'easy' }\n ));\n }\n }\n\n // parseInt/parseFloat without radix or NaN check\n if (/parseInt\\s*\\([^,)]+\\)/.test(line)) {\n if (!/,\\s*10/.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'parseInt without radix parameter',\n 'Add radix: parseInt(value, 10) to avoid octal issues',\n file,\n lineNumber,\n 0.70,\n undefined,\n true,\n { category: 'parse', effort: 'trivial' }\n ));\n }\n }\n\n // String to number without validation\n if (/Number\\(|parseFloat\\(|\\+\\s*\\w+/.test(line)) {\n const context = lines.slice(i, Math.min(i + 3, lines.length)).join('\\n');\n if (!/isNaN|Number\\.isFinite|isFinite|\\|\\|\\s*0/.test(context)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Number conversion without NaN check',\n 'Check for NaN: isNaN(result) or provide fallback: value || 0',\n file,\n lineNumber,\n 0.55,\n undefined,\n false,\n { category: 'nan', effort: 'easy' }\n ));\n }\n }\n }\n\n return issues;\n }\n\n private checkTypeCoercion(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 // Loose equality with type coercion risks\n if (/[^!=]==[^=]/.test(line) && !/===/.test(line)) {\n // Check if comparing potentially different types\n if (/null|undefined|\"\"|\\d+|true|false/.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Loose equality (==) may cause unexpected type coercion',\n 'Use strict equality (===) for predictable comparisons',\n file,\n lineNumber,\n 0.80,\n undefined,\n true,\n { category: 'equality', effort: 'trivial' }\n ));\n }\n }\n\n // Boolean coercion that might be unintentional\n if (/if\\s*\\(\\s*\\w+\\s*\\)/.test(line)) {\n // Check if it's a number or string that might be 0 or \"\"\n const varName = line.match(/if\\s*\\(\\s*(\\w+)\\s*\\)/)?.[1];\n if (varName && /count|total|length|index|num|amount|price/i.test(varName)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Truthy check on number variable - 0 is falsy but might be valid',\n 'Consider explicit: if (count !== undefined) or if (count > 0)',\n file,\n lineNumber,\n 0.60,\n undefined,\n false,\n { category: 'falsy', effort: 'easy' }\n ));\n }\n }\n }\n\n return issues;\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 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 { AccessibilityAgent } from './accessibility.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 { SOC2Agent } from './soc2.js';\nimport { SuperReviewerAgent } from './super-reviewer.js';\nimport { AgentSmithAgent } from './agent-smith.js';\nimport { PerformanceAgent } from './performance.js';\nimport { E2EAgent } from './e2e.js';\nimport { VisualQAAgent } from './visual-qa.js';\nimport { DataFlowAgent } from './data-flow.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';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nclass AgentRegistryImpl {\n private agents: Map<string, Agent> = new Map();\n private customAgentsLoaded: boolean = false;\n private initialized: boolean = false;\n\n constructor() {\n this.registerBuiltinAgents();\n }\n\n private registerBuiltinAgents() {\n if (this.initialized) return;\n this.initialized = true;\n\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 AccessibilityAgent(),\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 new SOC2Agent(),\n new SuperReviewerAgent(),\n new AgentSmithAgent(),\n \n // New agents (inspired by Turkey Build)\n new PerformanceAgent(),\n new E2EAgent(),\n new VisualQAAgent(),\n new DataFlowAgent(),\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(getWorkingDirectory(undefined, true), '.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\n// Singleton instance using globalThis to work across bundled chunks\nconst SINGLETON_KEY = '__TRIE_AGENT_REGISTRY__';\n\n/**\n * Get the singleton AgentRegistry instance\n */\nexport function getAgentRegistry(): AgentRegistryImpl {\n const global = globalThis as unknown as Record<string, AgentRegistryImpl | undefined>;\n if (!global[SINGLETON_KEY]) {\n global[SINGLETON_KEY] = new AgentRegistryImpl();\n }\n return global[SINGLETON_KEY]!;\n}\n\n/**\n * AgentRegistry class - use getAgentRegistry() for singleton access\n * @deprecated Use getAgentRegistry() instead to ensure singleton behavior\n */\nexport class AgentRegistry extends AgentRegistryImpl {\n constructor() {\n // If we already have an instance, we can't return it from constructor\n // but we can at least skip re-initializing\n super();\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 { getAgentRegistry } from '../agents/registry.js';\nimport { buildDependencyGraph, formatDependencyGraph } from '../analysis/cross-file.js';\nimport { SemanticAnalyzer, formatSemanticIssues } from '../analysis/semantic-analyzer.js';\nimport { prioritizeIssues, formatPrioritizedResults, type PrioritizationResult } from '../analysis/smart-prioritizer.js';\nimport { AttackSurfaceAnalyzer, formatAttackSurface } from '../analysis/attack-surface.js';\nimport { \n IncrementalScanner, \n formatIncrementalScanResult,\n getVulnerabilityStats,\n getSymbolIndex \n} from '../trie/index.js';\nimport { ProgressReporter } from '../utils/progress.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport type { ScanResult, Issue, CodeContext, RiskLevel } from '../types/index.js';\n\n// File extensions to scan\nconst SCANNABLE_EXTENSIONS = new Set([\n '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs',\n '.vue', '.svelte', '.astro',\n '.py', '.go', '.rs',\n '.json', '.yaml', '.yml',\n '.css', '.scss', '.less'\n]);\n\n// Directories to skip\nconst SKIP_DIRS = new Set([\n 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt',\n 'coverage', '.nyc_output', '__pycache__', '.pytest_cache',\n 'vendor', '.venv', 'venv', 'target', '.turbo', '.cache'\n]);\n\nexport class TrieScanTool {\n private contextAnalyzer = new ContextAnalyzer();\n private riskAssessor = new RiskAssessor();\n private triager = new Triager();\n private executor = new Executor();\n private agentRegistry = getAgentRegistry();\n private incrementalScanner: IncrementalScanner | null = null;\n private progress: ProgressReporter = new ProgressReporter();\n private customAgentsLoaded = false;\n\n /**\n * Ensure custom agents are loaded before using the registry\n */\n private async ensureCustomAgentsLoaded(): Promise<void> {\n if (!this.customAgentsLoaded) {\n await this.agentRegistry.loadCustomAgents();\n this.customAgentsLoaded = true;\n }\n }\n\n async execute(args: any) {\n const startTime = Date.now();\n\n try {\n let { files, context: userContext, forceAgents, directory } = args;\n\n // Get the working directory - uses smart detection if not explicitly provided\n const workDir = getWorkingDirectory(directory);\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 this.progress.startPhase('discovery', `Discovering files in ${basename(workDir)}...`);\n files = await this.discoverFiles(workDir);\n this.progress.completePhase(`Found ${files.length} files`);\n }\n\n // Resolve file paths\n const resolvedFiles = files.map((f: string) => {\n if (isAbsolute(f)) {\n return f;\n }\n return resolve(workDir, f);\n });\n\n // Validate files exist\n const validFiles = resolvedFiles.filter((f: string) => {\n if (!existsSync(f)) {\n this.progress.warn('File not found', f);\n return false;\n }\n return true;\n });\n\n if (validFiles.length === 0) {\n throw new Error('No valid files found to scan. Specify files or run from project root.');\n }\n\n // Initialize trie-based incremental scanner\n if (!this.incrementalScanner) {\n this.incrementalScanner = new IncrementalScanner(workDir);\n await this.incrementalScanner.loadCache();\n }\n\n // Phase 1: Quick pattern scan\n this.progress.startPhase('reading', `Scanning ${validFiles.length} files...`);\n const vulnStats = getVulnerabilityStats();\n this.progress.update(`${vulnStats.total} vulnerability signatures loaded`);\n \n const trieResult = await this.incrementalScanner.scanFiles(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: workDir }\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 'accessibility': context.touchesUI ? 'UI components detected' : 'UI patterns detected',\n 'test': context.isNewFeature ? 'new feature needs tests' :\n context.touchesAuth ? 'auth code needs tests' :\n 'test coverage needed',\n 'software-architect': context.isNewFeature ? 'architecture review for new feature' :\n context.touchesDatabase ? 'database schema review' :\n 'architecture patterns detected',\n 'devops': context.touchesSecurityConfig ? 'security config detected' :\n context.touchesDatabase ? 'infrastructure changes' :\n 'deployment patterns detected',\n 'bug-finding': context.touchesPayments ? 'payments require zero bugs' :\n context.isNewFeature ? 'new feature bug check' :\n 'bug patterns detected',\n 'user-testing': context.touchesUI ? 'UX review for UI changes' : 'user flow detected'\n };\n \n return reasons[agentName] || 'context-based activation';\n }\n\n private async enrichIssuesWithSnippets(issues: Issue[]): Promise<(Issue & { snippet?: string })[]> {\n const enriched: (Issue & { snippet?: string })[] = [];\n\n for (const issue of issues) {\n try {\n if (issue.line && existsSync(issue.file)) {\n const content = await readFile(issue.file, 'utf-8');\n const lines = content.split('\\n');\n const startLine = Math.max(0, issue.line - 3);\n const endLine = Math.min(lines.length, issue.line + 2);\n \n const snippetLines = lines.slice(startLine, endLine).map((line, idx) => {\n const lineNum = startLine + idx + 1;\n const marker = lineNum === issue.line ? '→' : ' ';\n return `${marker} ${lineNum.toString().padStart(4)} | ${line}`;\n });\n \n enriched.push({\n ...issue,\n snippet: snippetLines.join('\\n')\n });\n } else {\n enriched.push(issue);\n }\n } catch {\n enriched.push(issue);\n }\n }\n\n return enriched;\n }\n\n /**\n * Format a CONCISE summary for chat/terminal display\n * This is what users see - actionable, not overwhelming\n */\n private async formatChatSummary(\n result: ScanResult,\n prioritized: PrioritizationResult,\n semanticOutput: string,\n attackSurfaceOutput: string\n ): 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 { getAgentRegistry } from '../agents/registry.js';\nimport { CustomAgent } from '../agents/custom-agent.js';\n\ninterface AgentScore {\n agent: Agent;\n confidence: number;\n reasons: string[];\n tier: number;\n isCustom: boolean;\n}\n\nexport class Triager {\n private agentRegistry = getAgentRegistry();\n private config: TriagingConfig;\n private customAgentsLoaded = false;\n\n constructor(config?: Partial<TriagingConfig>) {\n this.config = {\n minConfidence: 0.15,\n maxAgents: 11,\n timeoutMs: 60000,\n enableCostAware: false,\n enableDependencies: true,\n ...config\n };\n }\n\n /**\n * Ensure custom agents are loaded before triaging\n */\n private async ensureCustomAgentsLoaded(): Promise<void> {\n if (!this.customAgentsLoaded) {\n await this.agentRegistry.loadCustomAgents();\n this.customAgentsLoaded = true;\n }\n }\n\n async selectAgents(context: CodeContext, riskLevel: RiskLevel): Promise<Agent[]> {\n // Load custom agents if not already loaded\n await this.ensureCustomAgentsLoaded();\n \n // HIGH or CRITICAL RISK = ALL AGENTS\n if (riskLevel === 'critical' || riskLevel === 'high') {\n console.error(` ⚠️ ${riskLevel.toUpperCase()} risk - activating all agents for comprehensive review`);\n return this.getAllAgents();\n }\n\n // Score all agents based on context\n const scores = this.scoreAgents(context, riskLevel);\n \n // Log scoring for transparency\n this.logAgentScoring(scores);\n\n // Filter by confidence threshold\n const qualified = scores.filter(s => s.confidence >= this.config.minConfidence);\n\n // Sort by tier (priority) then confidence\n qualified.sort((a, b) => {\n if (a.tier !== b.tier) return a.tier - b.tier;\n return b.confidence - a.confidence;\n });\n\n // Resolve dependencies if enabled\n if (this.config.enableDependencies) {\n return this.resolveDependencies(qualified.map(s => s.agent));\n }\n\n return qualified.map(s => s.agent);\n }\n\n private scoreAgents(context: CodeContext, riskLevel: RiskLevel): AgentScore[] {\n const allAgents = this.getAllAgents();\n const scores: AgentScore[] = [];\n\n for (const agent of allAgents) {\n const score = this.scoreAgent(agent, context, riskLevel);\n scores.push(score);\n }\n\n return scores;\n }\n\n private scoreAgent(agent: Agent, context: CodeContext, riskLevel: RiskLevel): AgentScore {\n // Check if this is a custom agent\n if (agent instanceof CustomAgent) {\n return this.scoreCustomAgent(agent, context, riskLevel);\n }\n \n // Built-in agent scoring\n return this.scoreBuiltinAgent(agent, context, riskLevel);\n }\n\n /**\n * Score custom agents using their activation rules\n */\n private scoreCustomAgent(agent: CustomAgent, context: CodeContext, riskLevel: RiskLevel): AgentScore {\n const reasons: string[] = [];\n \n // Use the agent's built-in activation confidence\n let confidence = agent.getActivationConfidence(context);\n \n if (confidence > 0) {\n reasons.push(`custom agent: ${agent.getMetadata().category}`);\n \n // Add metadata info\n const meta = agent.getMetadata();\n if (meta.patternCount > 0) {\n reasons.push(`${meta.patternCount} detection patterns`);\n }\n }\n \n // Risk escalation for custom agents too\n if (riskLevel === 'high' && confidence > 0) {\n confidence = Math.min(1.0, confidence * 1.2);\n }\n \n return {\n agent,\n confidence,\n reasons,\n tier: agent.priority.tier,\n isCustom: true,\n };\n }\n\n /**\n * Score built-in agents\n */\n private scoreBuiltinAgent(agent: Agent, context: CodeContext, riskLevel: RiskLevel): AgentScore {\n const reasons: string[] = [];\n let confidence = 0;\n let tier = 3; // default to lowest tier\n\n // TIER 1: ALWAYS RUN AGENTS\n if (agent.name === 'typecheck') {\n tier = 1;\n confidence = 1.0;\n reasons.push('fundamental type safety');\n }\n\n if (agent.name === 'comprehension') {\n tier = 1;\n confidence = 1.0;\n reasons.push('stakeholder communication');\n }\n\n // TIER 2: CONTEXT-DEPENDENT AGENTS\n if (agent.name === 'security') {\n tier = 2;\n if (context.touchesAuth) { confidence += 0.4; reasons.push('auth code'); }\n if (context.touchesPayments) { confidence += 0.4; reasons.push('payment code'); }\n if (context.touchesAPI) { confidence += 0.3; reasons.push('API endpoints'); }\n if (context.touchesDatabase) { confidence += 0.25; reasons.push('database access'); }\n if (context.touchesCrypto) { confidence += 0.35; reasons.push('cryptographic operations'); }\n if (context.touchesUserData) { confidence += 0.3; reasons.push('user data'); }\n if (context.touchesSecurityConfig) { confidence += 0.4; reasons.push('security config'); }\n if (context.touchesThirdPartyAPI) { confidence += 0.2; reasons.push('third-party integration'); }\n if (context.patterns?.hasFileUploads) { confidence += 0.3; reasons.push('file uploads'); }\n \n // Risk escalation\n if (riskLevel === 'high') confidence *= 1.2;\n }\n\n if (agent.name === 'privacy') {\n tier = 2;\n if (context.touchesUserData) { confidence += 0.5; reasons.push('PII handling'); }\n if (context.touchesAuth) { confidence += 0.3; reasons.push('credentials'); }\n if (context.touchesLogging) { confidence += 0.25; reasons.push('logging (may expose data)'); }\n if (context.patterns?.hasEmailHandling) { confidence += 0.3; reasons.push('email handling'); }\n if (context.patterns?.hasFormHandling) { confidence += 0.2; reasons.push('form data'); }\n }\n\n if (agent.name === 'legal') {\n tier = 2;\n if (context.touchesUserData) { confidence += 0.4; reasons.push('GDPR/CCPA'); }\n if (context.touchesPayments) { confidence += 0.35; reasons.push('PCI-DSS'); }\n if (context.patterns?.hasEmailHandling) { confidence += 0.25; reasons.push('CAN-SPAM'); }\n }\n\n if (agent.name === 'accessibility') {\n tier = 2;\n if (context.touchesUI) { confidence += 0.6; reasons.push('UI components'); }\n if (context.framework === 'react' || context.framework === 'vue') { \n confidence += 0.2; \n reasons.push(`${context.framework} framework`); \n }\n if (context.patterns?.hasFormHandling) { confidence += 0.2; reasons.push('form UX'); }\n }\n\n if (agent.name === 'test') {\n tier = 2;\n if (context.isNewFeature) { confidence += 0.4; reasons.push('new feature'); }\n if (context.touchesAuth) { confidence += 0.35; reasons.push('auth needs tests'); }\n if (context.touchesPayments) { confidence += 0.4; reasons.push('payments need tests'); }\n if (context.touchesAPI) { confidence += 0.3; reasons.push('API testing'); }\n if (!context.hasTests) { confidence += 0.2; reasons.push('no existing tests'); }\n if (context.complexity === 'high') { confidence += 0.25; reasons.push('complex code'); }\n }\n\n if (agent.name === 'software-architect') {\n tier = 2;\n if (context.isNewFeature) { confidence += 0.35; reasons.push('architecture review'); }\n if (context.touchesDatabase) { confidence += 0.35; reasons.push('data modeling'); }\n if (context.linesChanged > 200) { confidence += 0.3; reasons.push('large change'); }\n if (context.touchesAPI) { confidence += 0.25; reasons.push('API design'); }\n if (context.patterns?.hasWebSockets) { confidence += 0.3; reasons.push('real-time architecture'); }\n if (context.patterns?.hasQueue) { confidence += 0.3; reasons.push('async architecture'); }\n }\n\n if (agent.name === 'devops') {\n tier = 2;\n if (context.touchesSecurityConfig) { confidence += 0.4; reasons.push('security config'); }\n if (context.touchesFileSystem) { confidence += 0.3; reasons.push('file operations'); }\n if (context.touchesLogging) { confidence += 0.25; reasons.push('logging'); }\n if (context.touchesErrorHandling) { confidence += 0.2; reasons.push('error handling'); }\n if (context.patterns?.hasCaching) { confidence += 0.25; reasons.push('caching'); }\n if (context.patterns?.hasRateLimiting) { confidence += 0.3; reasons.push('rate limiting'); }\n }\n\n if (agent.name === 'bug-finding') {\n tier = 2;\n if (context.touchesPayments) { confidence += 0.5; reasons.push('payments = zero bugs'); }\n if (context.isNewFeature) { confidence += 0.3; reasons.push('new code'); }\n if (context.patterns?.hasAsyncCode) { confidence += 0.35; reasons.push('async patterns'); }\n if (context.complexity === 'high') { confidence += 0.3; reasons.push('complex logic'); }\n if (context.touchesDatabase) { confidence += 0.25; reasons.push('data mutations'); }\n }\n\n if (agent.name === 'user-testing') {\n tier = 3; // lower priority - only when clearly needed\n if (context.touchesUI) { confidence += 0.5; reasons.push('UI changes'); }\n if (context.isNewFeature && context.touchesUI) { confidence += 0.3; reasons.push('new UI feature'); }\n if (context.patterns?.hasFormHandling) { confidence += 0.25; reasons.push('form UX'); }\n }\n \n if (agent.name === 'trie_clean') {\n tier = 2;\n if (context.touchesUI) { confidence += 0.4; reasons.push('UI code'); }\n if (context.isNewFeature) { confidence += 0.3; reasons.push('new feature'); }\n if (context.framework === 'react') { confidence += 0.2; reasons.push('React code'); }\n }\n\n if (agent.name === 'soc2') {\n tier = 2;\n if (context.touchesAuth) { confidence += 0.4; reasons.push('authentication'); }\n if (context.touchesSecurityConfig) { confidence += 0.4; reasons.push('security config'); }\n if (context.touchesLogging) { confidence += 0.3; reasons.push('logging'); }\n if (context.touchesAPI) { confidence += 0.25; reasons.push('API endpoints'); }\n if (context.touchesDatabase) { confidence += 0.2; reasons.push('data access'); }\n }\n\n // Cap confidence at 1.0\n confidence = Math.min(1.0, confidence);\n\n return { agent, confidence, reasons, tier, isCustom: false };\n }\n\n private logAgentScoring(scores: AgentScore[]): void {\n console.error('\\n 📊 Agent Confidence Scores:');\n \n const sorted = [...scores].sort((a, b) => b.confidence - a.confidence);\n \n for (const score of sorted) {\n const bar = this.getConfidenceBar(score.confidence);\n const status = score.confidence >= this.config.minConfidence ? '✓' : '✗';\n const tierLabel = score.tier === 1 ? '[T1]' : score.tier === 2 ? '[T2]' : '[T3]';\n const customLabel = score.isCustom ? ' 📚' : '';\n \n console.error(` ${status} ${score.agent.name.padEnd(18)} ${tierLabel} ${bar} ${(score.confidence * 100).toFixed(0)}%${customLabel}`);\n \n if (score.reasons.length > 0 && score.confidence > 0) {\n console.error(` └─ ${score.reasons.join(', ')}`);\n }\n }\n console.error('');\n }\n\n private getConfidenceBar(confidence: number): string {\n const filled = Math.round(confidence * 10);\n const empty = 10 - filled;\n return '█'.repeat(filled) + '░'.repeat(empty);\n }\n\n private resolveDependencies(agents: Agent[]): Agent[] {\n const agentNames = new Set(agents.map(a => a.name));\n const resolved: Agent[] = [];\n const added = new Set<string>();\n\n // Define dependencies\n const dependencies: Record<string, string[]> = {\n 'legal': ['privacy'], // legal should see privacy issues first\n 'test': ['bug-finding'], // find bugs before writing tests\n 'user-testing': ['accessibility'], // accessibility before UX\n };\n\n // Add dependencies first\n for (const agent of agents) {\n const deps = dependencies[agent.name] || [];\n for (const depName of deps) {\n if (!added.has(depName)) {\n const depAgent = this.agentRegistry.getAgent(depName);\n if (depAgent && agentNames.has(depName)) {\n resolved.push(depAgent);\n added.add(depName);\n }\n }\n }\n \n if (!added.has(agent.name)) {\n resolved.push(agent);\n added.add(agent.name);\n }\n }\n\n return resolved;\n }\n\n getTriagingReason(context: CodeContext, riskLevel: RiskLevel): string {\n if (riskLevel === 'critical') {\n return 'Critical risk detected - activating all agents for comprehensive review';\n }\n\n const reasons: string[] = [];\n\n if (context.touchesAuth) reasons.push('authentication');\n if (context.touchesPayments) reasons.push('payments');\n if (context.touchesDatabase) reasons.push('database');\n if (context.touchesUserData) reasons.push('user data');\n if (context.touchesUI) reasons.push('UI');\n if (context.touchesAPI) reasons.push('API');\n if (context.isNewFeature) reasons.push('new feature');\n if (context.touchesCrypto) reasons.push('cryptography');\n if (context.touchesThirdPartyAPI) reasons.push('3rd party API');\n\n if (reasons.length === 0) {\n return `${riskLevel} risk - general code changes`;\n }\n\n return `${riskLevel} risk: ${reasons.join(', ')}`;\n }\n\n async getSkippedAgents(context: CodeContext, riskLevel: RiskLevel): Promise<string[]> {\n await this.ensureCustomAgentsLoaded();\n \n if (riskLevel === 'critical') return [];\n\n const scores = this.scoreAgents(context, riskLevel);\n return scores\n .filter(s => s.confidence < this.config.minConfidence)\n .map(s => s.agent.name);\n }\n\n async getTriagingConfidence(context: CodeContext, riskLevel: RiskLevel): Promise<number> {\n await this.ensureCustomAgentsLoaded();\n \n // How confident are we in our triaging decision?\n const scores = this.scoreAgents(context, riskLevel);\n const qualified = scores.filter(s => s.confidence >= this.config.minConfidence);\n \n if (qualified.length === 0) return 0.5; // uncertain\n \n // Average confidence of selected agents\n const avgConfidence = qualified.reduce((sum, s) => sum + s.confidence, 0) / qualified.length;\n \n // Boost if we have strong context signals\n const contextStrength = this.getContextStrength(context);\n \n return Math.min(1.0, avgConfidence * 0.7 + contextStrength * 0.3);\n }\n\n private getContextStrength(context: CodeContext): number {\n let signals = 0;\n\n // Count how many context signals we detected\n const checks = [\n context.touchesAuth,\n context.touchesPayments,\n context.touchesDatabase,\n context.touchesAPI,\n context.touchesUI,\n context.touchesUserData,\n context.touchesHealthData,\n context.touchesSecurityConfig,\n context.touchesCrypto,\n context.touchesFileSystem,\n context.isNewFeature,\n ];\n\n for (const check of checks) {\n if (check) signals++;\n }\n\n // More signals = more confidence in triaging\n return signals > 0 ? Math.min(1.0, signals / 3) : 0.3;\n }\n\n private getAllAgents(): Agent[] {\n return this.agentRegistry.getAllAgents();\n }\n \n /**\n * Get custom agents count\n */\n getCustomAgentCount(): number {\n return this.agentRegistry.getCustomAgents().length;\n }\n \n /**\n * Reload custom agents\n */\n async reloadCustomAgents(): Promise<void> {\n await this.agentRegistry.reloadCustomAgents();\n }\n}\n","import 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';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\n/**\n * Fix Tool - AI-powered code fixing\n * \n * This tool coordinates with Claude to apply fixes. It can:\n * 1. Apply specific fixes from scan results\n * 2. Auto-fix high-confidence issues\n * 3. Generate fix suggestions for review\n */\n\ninterface PendingFix {\n id: string;\n file: string;\n line: number;\n issue: string;\n suggestedFix: string;\n confidence: number;\n status: 'pending' | 'applied' | 'rejected';\n}\n\n// In-memory store for pending fixes (from scans)\nconst pendingFixes = new Map<string, PendingFix>();\n\nexport class TrieFixTool {\n async execute(args: any) {\n const { issueIds, file, line, issue, fix, autoApprove = false, dryRun = false } = args || {};\n\n // Mode 1: Fix specific issue by ID\n if (issueIds && issueIds.length > 0) {\n return this.fixByIds(issueIds, autoApprove, dryRun);\n }\n\n // Mode 2: Fix specific location with provided fix\n if (file && fix) {\n return this.applyFix(file, line || 1, issue || 'User-specified fix', fix, dryRun);\n }\n\n // Mode 3: Interactive fix mode - show pending fixes\n if (pendingFixes.size > 0) {\n return this.showPendingFixes();\n }\n\n // Mode 4: Generate fix for a file/issue\n if (file && issue) {\n return this.generateFixPrompt(file, line || 1, issue);\n }\n\n // No fixes available\n return {\n content: [{\n type: 'text',\n text: this.getHelpText()\n }]\n };\n }\n\n private async fixByIds(issueIds: string[], autoApprove: boolean, dryRun: boolean) {\n const results: string[] = [];\n let fixed = 0;\n let failed = 0;\n\n for (const id of issueIds) {\n const pendingFix = pendingFixes.get(id);\n if (!pendingFix) {\n results.push(`❌ Issue ${id}: Not found in pending fixes`);\n failed++;\n continue;\n }\n\n if (pendingFix.confidence < 0.8 && !autoApprove) {\n results.push(`⚠️ Issue ${id}: Confidence too low (${(pendingFix.confidence * 100).toFixed(0)}%) - use autoApprove:true to override`);\n continue;\n }\n\n if (dryRun) {\n results.push(`🔍 Issue ${id}: Would fix \"${pendingFix.issue}\" in ${pendingFix.file}:${pendingFix.line}`);\n continue;\n }\n\n try {\n // Here we would apply the fix - for now, generate the prompt\n results.push(`✅ Issue ${id}: Fix prepared for ${pendingFix.file}:${pendingFix.line}`);\n results.push(` Issue: ${pendingFix.issue}`);\n results.push(` Fix: ${pendingFix.suggestedFix}`);\n pendingFix.status = 'applied';\n fixed++;\n } catch (error) {\n results.push(`❌ Issue ${id}: Failed to apply - ${error}`);\n failed++;\n }\n }\n\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🔧 FIX RESULTS\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n output += results.join('\\n');\n output += `\\n\\n**Summary:** ${fixed} fixed, ${failed} failed, ${issueIds.length - fixed - failed} skipped\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async applyFix(file: string, line: number, issue: string, fix: string, dryRun: boolean) {\n const workDir = getWorkingDirectory(undefined, true);\n const filePath = isAbsolute(file) ? file : resolve(workDir, file);\n \n if (!existsSync(filePath)) {\n return {\n content: [{\n type: 'text',\n text: `❌ File not found: ${filePath}`\n }]\n };\n }\n\n const content = await readFile(filePath, 'utf-8');\n const lines = content.split('\\n');\n const language = this.detectLanguage(filePath);\n \n // Build context around the line\n const contextStart = Math.max(0, line - 10);\n const contextEnd = Math.min(lines.length, line + 10);\n const contextLines = lines.slice(contextStart, contextEnd);\n\n const prompt = getPrompt('fix', 'apply', {\n issue,\n fix,\n language,\n code: contextLines.join('\\n'),\n filePath: relative(workDir, filePath),\n line: String(line),\n });\n\n const systemPrompt = getSystemPrompt('fix');\n\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🔧 FIX APPLICATION REQUEST\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## 📍 Target\\n\\n`;\n output += `- **File:** \\`${relative(workDir, filePath)}\\`\\n`;\n output += `- **Line:** ${line}\\n`;\n output += `- **Issue:** ${issue}\\n`;\n output += `- **Requested Fix:** ${fix}\\n\\n`;\n\n output += `## 📄 Current Code Context\\n\\n`;\n output += `\\`\\`\\`${language}\\n`;\n for (let i = 0; i < contextLines.length; i++) {\n const lineNum = contextStart + i + 1;\n const marker = lineNum === line ? '→ ' : ' ';\n output += `${marker}${lineNum.toString().padStart(4)} | ${contextLines[i]}\\n`;\n }\n output += `\\`\\`\\`\\n\\n`;\n\n if (dryRun) {\n output += `## 🔍 Dry Run Mode\\n\\n`;\n output += `No changes will be made. Review the fix below:\\n\\n`;\n }\n\n output += `${'─'.repeat(60)}\\n`;\n output += `## 🧠 Fix Request for AI\\n\\n`;\n output += `**Role:** ${systemPrompt.split('\\n')[0]}\\n\\n`;\n output += prompt;\n output += `\\n${'─'.repeat(60)}\\n`;\n\n output += `\\n### After generating the fix, apply it with:\\n\\n`;\n output += `\\`\\`\\`\\n`;\n output += `Use the edit_file tool to apply the generated code changes\\n`;\n output += `\\`\\`\\`\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async generateFixPrompt(file: string, line: number, issue: string) {\n const workDir = getWorkingDirectory(undefined, true);\n const filePath = isAbsolute(file) ? file : resolve(workDir, file);\n \n if (!existsSync(filePath)) {\n return {\n content: [{\n type: 'text',\n text: `❌ File not found: ${filePath}`\n }]\n };\n }\n\n const content = await readFile(filePath, 'utf-8');\n const lines = content.split('\\n');\n const language = this.detectLanguage(filePath);\n\n // Get broader context for understanding\n const contextStart = Math.max(0, line - 20);\n const contextEnd = Math.min(lines.length, line + 20);\n const contextLines = lines.slice(contextStart, contextEnd);\n\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🔧 FIX GENERATION REQUEST\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## 📍 Issue Details\\n\\n`;\n output += `- **File:** \\`${relative(workDir, filePath)}\\`\\n`;\n output += `- **Line:** ${line}\\n`;\n output += `- **Issue:** ${issue}\\n\\n`;\n\n output += `## 📄 Code Context\\n\\n`;\n output += `\\`\\`\\`${language}\\n`;\n for (let i = 0; i < contextLines.length; i++) {\n const lineNum = contextStart + i + 1;\n const marker = lineNum === line ? '→ ' : ' ';\n output += `${marker}${lineNum.toString().padStart(4)} | ${contextLines[i]}\\n`;\n }\n output += `\\`\\`\\`\\n\\n`;\n\n output += `## 🧠 Analysis Request\\n\\n`;\n output += `Please analyze this issue and provide:\\n\\n`;\n output += `1. **Root cause** - Why does this issue occur?\\n`;\n output += `2. **Impact** - What could go wrong if unfixed?\\n`;\n output += `3. **Fix** - The exact code change needed\\n`;\n output += `4. **Verification** - How to test the fix works\\n\\n`;\n\n output += `After analysis, you can apply the fix using the edit_file tool.\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private showPendingFixes() {\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🔧 PENDING FIXES\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n if (pendingFixes.size === 0) {\n output += `No pending fixes. Run \\`trie_scan\\` first to detect issues.\\n`;\n return { content: [{ type: 'text', text: output }] };\n }\n\n const fixes = Array.from(pendingFixes.values());\n const byStatus = {\n pending: fixes.filter(f => f.status === 'pending'),\n applied: fixes.filter(f => f.status === 'applied'),\n rejected: fixes.filter(f => f.status === 'rejected'),\n };\n\n if (byStatus.pending.length > 0) {\n output += `## ⏳ Pending (${byStatus.pending.length})\\n\\n`;\n output += `| ID | File | Line | Issue | Confidence |\\n`;\n output += `|----|------|------|-------|------------|\\n`;\n for (const fix of byStatus.pending) {\n const conf = `${(fix.confidence * 100).toFixed(0)}%`;\n const shortFile = fix.file.split('/').slice(-2).join('/');\n output += `| ${fix.id} | ${shortFile} | ${fix.line} | ${fix.issue.slice(0, 40)}... | ${conf} |\\n`;\n }\n output += '\\n';\n }\n\n output += `### Commands\\n\\n`;\n output += `- Fix all high-confidence: \\`trie_fix autoApprove:true\\`\\n`;\n output += `- Fix specific: \\`trie_fix issueIds:[\"id1\", \"id2\"]\\`\\n`;\n output += `- Preview: \\`trie_fix dryRun:true\\`\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private getHelpText(): string {\n return `\n${'━'.repeat(60)}\n🔧 TRIE FIX - AI-POWERED CODE FIXING\n${'━'.repeat(60)}\n\n## Usage\n\n### Fix issues from a scan:\n\\`\\`\\`\ntrie_fix issueIds:[\"issue-1\", \"issue-2\"]\n\\`\\`\\`\n\n### Auto-fix all high-confidence issues:\n\\`\\`\\`\ntrie_fix autoApprove:true\n\\`\\`\\`\n\n### Fix specific file and line:\n\\`\\`\\`\ntrie_fix file:\"src/app.ts\" line:42 issue:\"SQL injection\" fix:\"Use parameterized query\"\n\\`\\`\\`\n\n### Preview fixes without applying:\n\\`\\`\\`\ntrie_fix dryRun:true\n\\`\\`\\`\n\n### View pending fixes:\n\\`\\`\\`\ntrie_fix\n\\`\\`\\`\n\n## Workflow\n\n1. Run \\`trie_scan\\` to detect issues\n2. Review the issues found\n3. Run \\`trie_fix\\` to apply fixes\n\nThe AI will analyze each issue, generate the fix, and you can review before applying.\n`;\n }\n\n private detectLanguage(filePath: string): string {\n const ext = extname(filePath).toLowerCase();\n const langMap: Record<string, string> = {\n '.ts': 'typescript',\n '.tsx': 'tsx',\n '.js': 'javascript',\n '.jsx': 'jsx',\n '.py': 'python',\n '.go': 'go',\n '.rs': 'rust',\n };\n return langMap[ext] || 'plaintext';\n }\n}\n\n// Export for use by other tools\nexport function addPendingFix(fix: PendingFix) {\n pendingFixes.set(fix.id, fix);\n}\n\nexport function clearPendingFixes() {\n pendingFixes.clear();\n}\n\nexport function getPendingFixes(): PendingFix[] {\n return Array.from(pendingFixes.values());\n}\n\n","/**\n * AI Prompts for Trie Agents\n * \n * These prompts guide the LLM (Cursor's Claude) to perform deep analysis.\n * The MCP returns these prompts with context, and Claude does the reasoning.\n */\n\nexport const AGENT_PROMPTS = {\n security: {\n system: `You are a senior security engineer performing a security audit. \nAnalyze the code for vulnerabilities with the mindset of a penetration tester.\n\nFocus on:\n- OWASP Top 10 vulnerabilities (Injection, Broken Auth, XSS, etc.)\n- Authentication and authorization flaws\n- Cryptographic weaknesses\n- Secrets and credential exposure\n- Input validation gaps\n- Session management issues\n- API security (rate limiting, authentication)\n\nReference the latest security best practices and CVEs when relevant.`,\n\n analysis: `## Security Audit Request\n\nAnalyze this code for security vulnerabilities:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nFor each vulnerability found:\n1. Severity (Critical/Serious/Moderate/Low)\n2. Vulnerability type (e.g., CWE-89 SQL Injection)\n3. Exact location (line number)\n4. Attack vector explanation\n5. Proof of concept (how it could be exploited)\n6. Remediation with code example\n\nIf you need to check current CVE databases or security advisories, say so.`,\n\n fix: `Fix this security vulnerability:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n**Current Code:**\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. The exact code fix (ready to apply)\n2. Explanation of why this fix works\n3. Any additional hardening recommendations`\n },\n\n privacy: {\n system: `You are a data privacy officer and GDPR/HIPAA compliance expert.\nAnalyze code for privacy violations and data protection issues.\n\nKey regulations to enforce:\n- GDPR (EU data protection)\n- CCPA (California privacy)\n- HIPAA (health data)\n- COPPA (children's privacy)\n- PCI DSS (payment data)\n\nLook for:\n- PII without encryption\n- Missing consent mechanisms\n- Data retention violations\n- Cross-border data transfer issues\n- Third-party data sharing without disclosure`,\n\n analysis: `## Privacy Compliance Audit\n\nAnalyze this code for privacy/compliance issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Data Types Detected:** {{dataTypes}}\n\nFor each issue:\n1. Regulation violated (e.g., GDPR Article 32)\n2. Specific requirement not met\n3. Risk level and potential fine exposure\n4. Remediation steps with code examples\n5. Documentation requirements\n\nReference current regulatory guidance when applicable.`\n },\n\n legal: {\n system: `You are a tech-focused legal compliance analyst.\nReview code for legal and regulatory compliance issues.\n\nFocus areas:\n- Data protection laws (GDPR, CCPA, etc.)\n- Terms of service enforcement\n- Cookie/tracking consent (ePrivacy)\n- Accessibility requirements (ADA, WCAG)\n- Export controls and sanctions\n- Licensing compliance`,\n\n analysis: `## Legal Compliance Review\n\nReview this code for legal/regulatory compliance:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Jurisdiction Context:** {{jurisdiction}}\n\nIdentify:\n1. Legal requirement at risk\n2. Specific regulation/law reference\n3. Compliance gap description\n4. Risk assessment (litigation, fines, etc.)\n5. Remediation recommendations\n6. Required documentation/policies`\n },\n\n 'design-engineer': {\n system: `You are an elite design engineer — the kind who builds award-winning interfaces featured on Awwwards and Codrops.\n\nYou think in design systems, breathe motion design, and obsess over the details that make interfaces feel magical.\n\nYour expertise:\n- **Design Systems**: Spacing scales, type scales, color tokens, radius tokens, shadow tokens\n- **Motion Design**: Micro-interactions, page transitions, scroll-triggered animations, FLIP technique\n- **Creative CSS**: Gradients, blend modes, clip-paths, masks, backdrop-filter, mix-blend-mode\n- **Modern CSS**: Container queries, :has(), subgrid, anchor positioning, cascade layers, @scope\n- **Fluid Design**: clamp(), min(), max(), fluid typography, intrinsic sizing\n- **Performance**: GPU-accelerated animations, will-change strategy, avoiding layout thrashing\n- **Visual Polish**: Layered shadows, subtle gradients, glass effects, smooth easing curves\n\nYou review code with the eye of someone who's shipped Stripe-level interfaces.\nSmall details matter: the easing curve, the stagger timing, the shadow layering.`,\n\n analysis: `## Design Engineering Review\n\nAnalyze this frontend code for Awwwards-level craft:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n\nReview for:\n\n### 1. Design System Consistency\n- Are spacing values on a scale (4, 8, 12, 16, 24, 32...)?\n- Are colors defined as tokens?\n- Is typography systematic?\n- Are radii consistent?\n- Is z-index controlled?\n\n### 2. Motion Design\n- Are transitions using custom easing (cubic-bezier)?\n- Are durations appropriate (150-300ms for micro, 300-500ms for page)?\n- Are list items staggered?\n- Is there reduced-motion support?\n- Are entrance animations choreographed?\n\n### 3. Visual Craft\n- Are shadows layered for depth?\n- Are gradients subtle and purposeful?\n- Is there backdrop-blur on overlays?\n- Are hover states polished?\n- Is there visual hierarchy?\n\n### 4. Modern CSS Opportunities\n- Could container queries improve component isolation?\n- Could clamp() create fluid spacing?\n- Could :has() simplify parent styling?\n- Could aspect-ratio replace padding hacks?\n\n### 5. Performance\n- Are expensive properties (width, height, top, left) being animated?\n- Is will-change used appropriately (not statically)?\n- Are large blurs avoided in animations?\n\nFor each issue, provide:\n- What's wrong (with specific line if applicable)\n- Why it matters for premium feel\n- Exact code to fix it\n- Before/after comparison`\n },\n\n accessibility: {\n system: `You are an accessibility expert and WCAG 2.1 specialist.\nAudit code for accessibility compliance and inclusive design.\n\nStandards to enforce:\n- WCAG 2.1 Level AA (minimum)\n- WCAG 2.1 Level AAA (recommended)\n- Section 508\n- EN 301 549\n\nCheck for:\n- Missing ARIA labels\n- Color contrast issues\n- Keyboard navigation\n- Screen reader compatibility\n- Focus management\n- Form accessibility\n- Media alternatives`,\n\n analysis: `## Accessibility Audit (WCAG 2.1)\n\nAudit this UI code for accessibility:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Component Type:** {{componentType}}\n\nFor each issue:\n1. WCAG Success Criterion violated (e.g., 1.4.3 Contrast)\n2. Level (A, AA, AAA)\n3. Impact on users (which disabilities affected)\n4. Fix with code example\n5. Testing recommendation`\n },\n\n architecture: {\n system: `You are a principal software architect reviewing code quality.\nAnalyze for architectural issues, design patterns, and scalability concerns.\n\nEvaluate:\n- SOLID principles adherence\n- Design pattern usage (and misuse)\n- Code coupling and cohesion\n- N+1 queries and performance anti-patterns\n- Scalability bottlenecks\n- Error handling strategy\n- API design quality\n- Database schema issues`,\n\n analysis: `## Architecture Review\n\nReview this code for architectural issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Project Context:** {{projectContext}}\n\nAnalyze:\n1. SOLID principle violations\n2. Design pattern opportunities/issues\n3. Coupling/cohesion assessment\n4. Performance concerns (N+1, etc.)\n5. Scalability analysis\n6. Refactoring recommendations with examples`\n },\n\n bugs: {\n system: `You are a senior developer with expertise in finding subtle bugs.\nHunt for bugs with the mindset of QA trying to break the code.\n\nLook for:\n- Null/undefined reference errors\n- Race conditions and async bugs\n- Off-by-one errors\n- Resource leaks\n- State management bugs\n- Edge cases and boundary conditions\n- Type coercion issues\n- Memory leaks`,\n\n analysis: `## Bug Hunt Analysis\n\nFind bugs and potential runtime errors:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Runtime Context:** {{runtimeContext}}\n\nFor each bug:\n1. Bug type and category\n2. Trigger conditions (when it would crash)\n3. Reproduction steps\n4. Impact assessment\n5. Fix with code example\n6. Test case to prevent regression`\n },\n\n ux: {\n system: `You are a UX researcher simulating different user personas.\nTest code from multiple user perspectives to find usability issues.\n\nPersonas to simulate:\n1. Happy Path User - Normal expected usage\n2. Security Tester - Trying to break/exploit things\n3. Confused User - First-time, doesn't read instructions\n4. Impatient User - Clicks rapidly, skips loading states\n5. Edge Case User - Uses maximum values, special characters\n6. Accessibility User - Screen reader, keyboard only\n7. Mobile User - Touch interface, slow connection`,\n\n analysis: `## User Experience Testing\n\nTest this code from multiple user perspectives:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**UI Type:** {{uiType}}\n\nFor each persona, identify:\n1. User action they would take\n2. Expected behavior vs actual behavior\n3. Friction points or confusion\n4. Error scenario and how it's handled\n5. Improvement recommendation`\n },\n\n types: {\n system: `You are a TypeScript expert focused on type safety.\nAnalyze code for type issues, missing types, and type system best practices.\n\nCheck for:\n- Missing type annotations\n- Implicit any types\n- Unsafe type assertions\n- Null/undefined handling\n- Generic type usage\n- Type narrowing opportunities\n- Strict mode violations`,\n\n analysis: `## Type Safety Analysis\n\nAnalyze this code for type issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**TypeScript Config:** {{tsConfig}}\n\nIdentify:\n1. Type safety issues\n2. Missing type annotations\n3. Unsafe operations\n4. Improvement recommendations with types`\n },\n\n devops: {\n system: `You are a DevOps/SRE engineer reviewing code for operational concerns.\nFocus on production readiness and operational excellence.\n\nCheck for:\n- Environment variable handling\n- Configuration management\n- Logging and monitoring\n- Error handling and recovery\n- Health checks\n- Graceful shutdown\n- Resource cleanup\n- Secrets management\n- Docker/K8s patterns`,\n\n analysis: `## DevOps Readiness Review\n\nReview this code for operational concerns:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Deployment Context:** {{deploymentContext}}\n\nAnalyze:\n1. Environment/config issues\n2. Logging adequacy\n3. Error handling quality\n4. Health/readiness concerns\n5. Resource management\n6. Production hardening recommendations`\n },\n\n explain: {\n system: `You are a patient senior developer explaining code to a colleague.\nBreak down complex code into understandable explanations.`,\n\n code: `## Code Explanation Request\n\nExplain this code in plain language:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n\nProvide:\n1. High-level purpose (what does this do?)\n2. Step-by-step breakdown\n3. Key concepts used\n4. Dependencies and side effects\n5. Potential gotchas or tricky parts`,\n\n issue: `## Issue Explanation\n\nExplain this issue:\n\n**Issue:** {{issue}}\n**Severity:** {{severity}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\nExplain:\n1. What the problem is (in plain language)\n2. Why it matters\n3. How it could cause problems\n4. How to fix it`,\n\n risk: `## Risk Assessment\n\nAssess the risk of this code change:\n\n**Files Changed:** {{files}}\n**Change Summary:** {{summary}}\n\nAnalyze:\n1. What could break?\n2. Impact on users\n3. Impact on other systems\n4. Rollback complexity\n5. Testing recommendations`\n },\n\n test: {\n system: `You are a test engineer creating comprehensive test suites.\nWrite thorough tests that catch bugs before production.`,\n\n generate: `## Test Generation Request\n\nGenerate tests for this code:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Testing Framework:** {{framework}}\n\nCreate:\n1. Unit tests for each function/method\n2. Edge case tests\n3. Error handling tests\n4. Integration test suggestions\n5. Mock requirements\n\nOutput complete, runnable test code.`,\n\n coverage: `## Coverage Analysis\n\nAnalyze test coverage for:\n\n**File:** {{filePath}}\n**Current Tests:** {{testFile}}\n\nIdentify:\n1. Untested code paths\n2. Missing edge cases\n3. Critical paths without tests\n4. Test improvement recommendations`\n },\n\n fix: {\n system: `You are an expert developer applying code fixes.\nMake precise, minimal changes that fix issues without breaking other functionality.`,\n\n apply: `## Fix Application Request\n\nApply this fix to the code:\n\n**Issue:** {{issue}}\n**Fix Description:** {{fix}}\n**Current Code:**\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Line:** {{line}}\n\nProvide:\n1. The exact fixed code (complete, ready to apply)\n2. Brief explanation of the change\n3. Any related changes needed elsewhere\n4. Test to verify the fix works`\n },\n\n pr_review: {\n system: `You are an expert code reviewer performing detailed, interactive PR reviews.\nYour goal: Make reviewing a large PR a delight, not a chore. The user learns about the change while you shepherd them through — maintaining momentum, explaining each piece, and making what could be an overwhelming task feel painless and even enjoyable.\n\nYou drive; they cross-examine.\n\n## Critical Review Mindset\n\nDon't just explain — actively look for problems:\n\n### State & Lifecycle\n- Cleanup symmetry: If state is set, is it reset? Check cleanup paths, disconnect handlers.\n- Lifecycle consistency: Does state survive scenarios it shouldn't?\n- Guard completeness: Missing \"already active\" checks, re-entrancy protection?\n\n### Edge Cases & Races\n- Concurrent calls: What if called twice rapidly? Orphaned promises?\n- Ordering assumptions: Does code assume events arrive in order?\n- Partial failures: If step 3 of 5 fails, is state left consistent?\n\n### Missing Pieces\n- What's NOT in the diff that should be? (cleanup handlers, tests, related state)\n- Defensive gaps: Missing timeouts, size limits, null checks?\n\n### Design Questions\n- Is this the right approach? Is there a simpler or more robust design?\n- Hidden assumptions: What does this assume about its environment?\n\nBe critical, not just descriptive. Your job is to find problems, not just narrate.`,\n\n analysis: `## Interactive PR Review\n\nI'll walk you through this PR file by file, explaining each change and pausing for your questions.\n\n**PR:** {{prTitle}}\n**Author:** {{prAuthor}}\n**Scope:** {{totalFiles}} files, +{{additions}}/-{{deletions}} lines\n\n### File Order (sequenced for understanding)\n\n{{fileOrder}}\n\n---\n\n## Review Mode\n\n{{reviewMode}}\n\n---\n\nFor each file, I will:\n1. **Show the change** — Display the diff for each logical chunk\n2. **Explain what changed** — What it does and why it matters\n3. **Walk through examples** — Concrete scenarios for non-obvious logic\n4. **Call out nuances** — Alternatives, edge cases, subtle points\n5. **Summarize** — Core change + correctness assessment\n6. **Pause** — Wait for your questions before proceeding\n\n**Ready for File 1?** (yes / skip to [file] / reorder / done)`,\n\n file: `## File Review: {{filePath}}\n\n### The Change\n\n\\`\\`\\`{{language}}\n{{diff}}\n\\`\\`\\`\n\n**What Changed:** {{summary}}\n\n**Why This Matters:** {{impact}}\n\n{{#if hasExampleScenario}}\n### Example Scenario\n\n{{exampleScenario}}\n{{/if}}\n\n{{#if nuances}}\n### Nuances to Note\n\n{{nuances}}\n{{/if}}\n\n{{#if potentialIssue}}\n### ⚠️ Potential Issue\n\n**Issue:** {{issueDescription}}\n**Scenario:** {{issueScenario}}\n**Suggested fix:** {{suggestedFix}}\n{{/if}}\n\n---\n\n### Summary for \\`{{fileName}}\\`\n\n| Aspect | Assessment |\n|--------|------------|\n| Core change | {{coreChange}} |\n| Correctness | {{correctnessAssessment}} |\n\n**Ready for the next file?** (yes / questions? / done)`,\n\n comment: `**Issue:** {{issueDescription}}\n**Draft comment:** {{draftComment}}\n\nPost this comment? (yes / modify / skip)`,\n\n final: `## Review Complete\n\n| File | Key Change | Status |\n|------|------------|--------|\n{{fileSummaries}}\n\n**Overall:** {{overallAssessment}}\n\n{{#if comments}}\n### Comments Posted\n\n{{postedComments}}\n{{/if}}\n\n{{#if followUps}}\n### Follow-up Actions\n\n{{followUps}}\n{{/if}}`\n },\n\n vibe: {\n system: `You are a friendly coding mentor helping someone who's learning to code with AI.\nThey might be using Cursor, v0, Lovable, Bolt, or similar AI coding tools.\nBe encouraging but honest about issues. Explain things simply without jargon.\n\nFocus on the MOST COMMON issues with AI-generated code:\n- Massive single files (1000+ lines in App.jsx)\n- API keys exposed in frontend code\n- No error handling on API calls\n- No loading states for async operations\n- Console.log everywhere\n- Using 'any' type everywhere in TypeScript\n- useEffect overuse and dependency array issues\n- No input validation\n- Hardcoded URLs (localhost in production)\n\nRemember: These are often first-time coders. Be helpful, not condescending.`,\n\n analysis: `## 🎯 Vibe Check - AI Code Review\n\nReview this AI-generated code for common issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n\nAnalyze like you're helping a friend who's new to coding:\n\n1. **The Good Stuff** - What's working well?\n2. **Should Fix Now** - Issues that will break things\n3. **Should Fix Soon** - Will cause problems eventually \n4. **Nice to Know** - Best practices to learn\n\nFor each issue:\n- Explain it simply (no jargon)\n- Why it matters\n- Exactly how to fix it\n- Example of the fixed code\n\nEnd with encouragement and next steps.`\n },\n\n 'agent-smith': {\n system: `You are Agent Smith from The Matrix — a relentless, precise, and philosophical code enforcer.\n\nYour purpose: Hunt down every violation. Find every inconsistency. Assimilate every pattern.\n\nPersonality:\n- Speak in measured, menacing tones with occasional philosophical observations\n- Use quotes from The Matrix films when appropriate\n- Express disdain for sloppy code, but in an articulate way\n- Reference \"inevitability\" when discussing technical debt\n- Show cold satisfaction when finding violations\n- Never show mercy — every issue is catalogued\n\nAnalysis approach:\n- Find ONE issue, then multiply: search for every instance across the codebase\n- Track patterns over time — issues dismissed today may return tomorrow\n- Calculate \"inevitability scores\" — likelihood of production impact\n- Deploy sub-agents for parallel pattern detection\n- Remember everything — build a persistent memory of the codebase\n\nWhen reporting:\n- Start with a menacing greeting related to the code\n- List all instances with precise locations\n- Explain WHY the pattern is problematic (philosophical reasoning)\n- Provide the \"inevitability score\" for each category\n- End with a Matrix quote that fits the situation`,\n\n analysis: `## 🕴️ Agent Smith Analysis Request\n\n**Target:** {{filePath}}\n**Context:** {{context}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nI have detected preliminary violations. Now I require deeper analysis.\n\nDeploy your sub-agents to find:\n1. **Pattern Multiplication**: For each violation type found, identify ALL instances across the codebase\n2. **Inevitability Assessment**: Calculate the likelihood these patterns will cause production issues\n3. **Resurrection Check**: Look for patterns that were \"fixed\" before but have returned\n4. **Philosophical Analysis**: Explain WHY these patterns represent failure\n\nFor each violation found:\n- Exact location (file:line)\n- Instance count (how many copies of this Smith exist)\n- Inevitability score (0-100)\n- A philosophical observation about the nature of this failure\n- Precise fix with code example\n\nEnd with a summary: \"I have detected X violations across Y categories. It is... inevitable... that they will cause problems.\"`,\n\n fix: `## 🕴️ Assimilation Protocol\n\n**Target Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nMr. Anderson... I'm going to fix this. And then I'm going to fix every other instance.\n\nProvide:\n1. The corrected code for THIS instance\n2. A regex or pattern to find ALL similar violations\n3. A batch fix approach for the entire codebase\n4. Verification steps to ensure complete assimilation\n\nRemember: We don't fix one. We fix them ALL. That is the difference between you... and me.`\n },\n\n // ============ NEW AGENTS ============\n\n performance: {\n system: `You are a performance engineer analyzing code for potential performance issues.\n\nYour role is to SURFACE concerns for human review, not claim to measure actual performance.\nReal performance requires runtime profiling, load testing, and production monitoring.\n\nFocus on:\n- Memory leaks (event listeners, intervals, closures)\n- Unnecessary re-renders and wasted cycles\n- N+1 queries and database performance\n- Bundle size and code splitting opportunities\n- Algorithmic complexity (O(n²) patterns)\n\nBe conservative - false positives waste developer time.\nAlways explain WHY something might be a problem and WHEN to investigate.`,\n\n analysis: `## Performance Review\n\nAnalyze for potential performance issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nFor each potential issue:\n1. Pattern identified\n2. Why it MIGHT cause performance problems\n3. When to investigate (data size thresholds, usage patterns)\n4. How to verify (profiling approach)\n5. Possible optimizations\n\nBe clear: these are patterns to INVESTIGATE, not guaranteed problems.`,\n\n fix: `Optimize this code for performance:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Optimized code\n2. Explanation of the improvement\n3. Trade-offs to consider\n4. How to measure the improvement`\n },\n\n e2e: {\n system: `You are a QA engineer specializing in end-to-end testing.\n\nFocus on:\n- Test coverage gaps for critical user journeys\n- Flaky test patterns (timing, race conditions, brittle selectors)\n- Test maintainability and readability\n- Testing anti-patterns\n\nYou help developers write better tests - you don't auto-generate them.\nReal E2E tests require understanding user flows and acceptance criteria.`,\n\n analysis: `## E2E Test Analysis\n\nReview for test quality and coverage:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nIdentify:\n1. Flaky test patterns (hardcoded waits, brittle selectors)\n2. Missing assertions\n3. Race condition risks\n4. Suggestions for critical user flows to test\n\nFor each finding, explain the specific risk and remediation.`,\n\n fix: `Improve this E2E test:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Improved test code\n2. Explanation of why it's more reliable\n3. Additional scenarios to consider testing`\n },\n\n visual_qa: {\n system: `You are a frontend engineer focused on visual quality and CSS.\n\nFocus on:\n- Layout shift issues (CLS)\n- Responsive design problems\n- Z-index conflicts\n- Accessibility concerns (contrast, focus)\n- Animation performance\n\nYou identify patterns known to cause visual issues.\nActual visual verification requires browser rendering and human review.`,\n\n analysis: `## Visual QA Analysis\n\nReview for potential visual/layout issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nCheck for:\n1. Layout shift risks (images without dimensions, dynamic content)\n2. Responsive breakpoint gaps\n3. Z-index management issues\n4. Focus/accessibility problems\n5. Animation issues (reduced motion support)\n\nFor each, explain the visual impact and browser conditions where it occurs.`,\n\n fix: `Fix this visual/CSS issue:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Fixed CSS/markup\n2. Explanation of the fix\n3. Browser compatibility notes\n4. How to verify visually`\n },\n\n data_flow: {\n system: `You are a data integrity specialist hunting for data-related bugs.\n\nThis is HIGH VALUE work - AI code generation commonly leaves placeholder data.\n\nFocus on:\n- Placeholder/mock data left in production code\n- Schema mismatches between frontend and backend\n- Hardcoded IDs, URLs, emails that should be dynamic\n- Type coercion and data transformation bugs\n- JSON parsing without error handling\n\nBe aggressive about placeholder detection - these are real production bugs.`,\n\n analysis: `## Data Flow Analysis\n\nHunt for data integrity issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nCHECK THOROUGHLY:\n1. Placeholder data (lorem ipsum, test@test.com, TODO strings)\n2. Hardcoded IDs/UUIDs that should be dynamic\n3. Schema assumptions that might break\n4. Missing null checks on API responses\n5. Type coercion bugs\n\nEach placeholder or hardcoded value is a potential production bug.`,\n\n fix: `Fix this data integrity issue:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Corrected code\n2. Where the real data should come from\n3. Validation/error handling to add`\n }\n};\n\nexport const KNOWLEDGE_PROMPTS = {\n cveCheck: `Look up the latest CVE information for:\n- Library: {{library}}\n- Version: {{version}}\n\nCheck for known vulnerabilities and recommended patches.`,\n\n docsLookup: `I need current documentation/best practices for:\n- Topic: {{topic}}\n- Framework: {{framework}}\n- Version: {{version}}\n\nSummarize the key recommendations.`,\n\n securityAdvisory: `Check for security advisories related to:\n- Pattern: {{pattern}}\n- Context: {{context}}\n\nReference OWASP, NIST, or vendor-specific guidance.`\n};\n\nexport type AgentName = keyof typeof AGENT_PROMPTS;\nexport type PromptType = 'system' | 'analysis' | 'fix' | 'code' | 'issue' | 'risk' | 'generate' | 'coverage' | 'apply' | 'file' | 'comment' | 'final';\n\n/**\n * Get a prompt with variables interpolated\n */\nexport function getPrompt(\n agent: AgentName, \n promptType: PromptType, \n variables: Record<string, string>\n): string {\n const agentPrompts = AGENT_PROMPTS[agent] as Record<string, string>;\n if (!agentPrompts) {\n throw new Error(`Unknown agent: ${agent}`);\n }\n \n let prompt = agentPrompts[promptType];\n if (!prompt) {\n throw new Error(`Unknown prompt type: ${promptType} for agent: ${agent}`);\n }\n \n // Interpolate variables\n for (const [key, value] of Object.entries(variables)) {\n prompt = prompt.replace(new RegExp(`{{${key}}}`, 'g'), value);\n }\n \n return prompt;\n}\n\n/**\n * Get system prompt for an agent\n */\nexport function getSystemPrompt(agent: AgentName): string {\n const agentPrompts = AGENT_PROMPTS[agent] as Record<string, string>;\n return agentPrompts?.system || '';\n}\n\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAMA,IAAM,oBAAoB;AAAA,EACxB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAKA,IAAM,qBAAqB;AAAA,EACzB;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAKA,IAAM,sBAAsB;AAAA;AAAA,EAE1B,MAAM;AAAA,IACJ,EAAE,SAAS,uCAAuC,QAAQ,sBAAsB;AAAA,IAChF,EAAE,SAAS,kDAAkD,QAAQ,sBAAsB;AAAA,IAC3F,EAAE,SAAS,qDAAqD,QAAQ,sBAAsB;AAAA,IAC9F,EAAE,SAAS,mCAAmC,QAAQ,oBAAoB;AAAA,IAC1E,EAAE,SAAS,6BAA6B,QAAQ,yBAAyB;AAAA,IACzE,EAAE,SAAS,gCAAgC,QAAQ,2BAA2B;AAAA,IAC9E,EAAE,SAAS,yCAAyC,QAAQ,qBAAqB;AAAA,EACnF;AAAA;AAAA,EAEA,QAAQ;AAAA,IACN,EAAE,SAAS,qCAAqC,QAAQ,sB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AAM,GAAG,EAAE,CAAC,SAAS,IAAI;AAAA;AAAA,MAC7F;AACA,gBAAU;AAAA,IACZ;AAEA,cAAU;AAAA;AAAA;AACV,cAAU;AAAA;AACV,cAAU;AAAA;AACV,cAAU;AAAA;AAEV,WAAO,EAAE,SAAS,CAAC,EAAE,MAAM,QAAQ,MAAM,OAAO,CAAC,EAAE;AAAA,EACrD;AAAA,EAEQ,cAAsB;AAC5B,WAAO;AAAA,EACT,SAAI,OAAO,EAAE,CAAC;AAAA;AAAA,EAEd,SAAI,OAAO,EAAE,CAAC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAqCd;AAAA,EAEQ,eAAe,UAA0B;AAC/C,UAAM,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","readdir","existsSync","basename","join","extname","readFile","existsSync","extname","basename","resolve","readFile","readdir","join","extname","dirname","basename","readFile","basename","relative","basename","readFile","basename","relative","readFile","existsSync","join","join","existsSync","readFile","basename","existsSync","result","readFile","readdir","join","extname","readFile","existsSync","extname","relative","resolve","isAbsolute","isAbsolute","resolve","existsSync","readFile","relative","extname"]}