@triedotdev/mcp 1.0.46 → 1.0.49
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.
- package/README.md +82 -17
- package/dist/{agent-smith-W7F55E6P.js → agent-smith-5QOZXLMV.js} +2 -2
- package/dist/{agent-smith-runner-SH76O724.js → agent-smith-runner-ZTDCJJQG.js} +2 -2
- package/dist/{chunk-BAME4KVK.js → chunk-6T7S77U7.js} +339 -20
- package/dist/chunk-6T7S77U7.js.map +1 -0
- package/dist/{chunk-5AS3BWAZ.js → chunk-JDICQHNT.js} +84 -62
- package/dist/chunk-JDICQHNT.js.map +1 -0
- package/dist/{chunk-OB45V2QC.js → chunk-KQOMSIVR.js} +201 -234
- package/dist/chunk-KQOMSIVR.js.map +1 -0
- package/dist/{chunk-R5HWHP5N.js → chunk-VZYCZXEQ.js} +55 -66
- package/dist/chunk-VZYCZXEQ.js.map +1 -0
- package/dist/cli/main.js +107 -16
- package/dist/cli/main.js.map +1 -1
- package/dist/cli/yolo-daemon.js +3 -3
- package/dist/index.js +12 -7
- package/dist/index.js.map +1 -1
- package/dist/workers/agent-worker.js +2 -2
- package/package.json +1 -1
- package/dist/chunk-5AS3BWAZ.js.map +0 -1
- package/dist/chunk-BAME4KVK.js.map +0 -1
- package/dist/chunk-OB45V2QC.js.map +0 -1
- package/dist/chunk-R5HWHP5N.js.map +0 -1
- /package/dist/{agent-smith-W7F55E6P.js.map → agent-smith-5QOZXLMV.js.map} +0 -0
- /package/dist/{agent-smith-runner-SH76O724.js.map → agent-smith-runner-ZTDCJJQG.js.map} +0 -0
|
@@ -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/moneybags.ts","../src/agents/production-ready.ts","../src/skills/gating.ts","../src/agents/skill-review.ts","../src/agents/custom-skill.ts","../src/agents/registry.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\n// ============================================================================\n// WCAG 2.1 SEVERITY LEVELS — Mapped to WCAG Conformance\n// ============================================================================\n\n/**\n * Issue severity based on WCAG impact\n * Critical: Blocks access entirely for some users\n * Serious: Significantly impairs access\n * Moderate: Creates barriers but workarounds exist\n * Low: Minor issues, best practices\n */\ntype A11ySeverity = 'critical' | 'serious' | 'moderate' | 'low';\n\n/**\n * WCAG Success Criteria with descriptions\n */\nconst WCAG_CRITERIA = {\n // Perceivable\n '1.1.1': { name: 'Non-text Content', level: 'A', description: 'All non-text content has text alternatives' },\n '1.3.1': { name: 'Info and Relationships', level: 'A', description: 'Information and relationships are programmatically determinable' },\n '1.3.2': { name: 'Meaningful Sequence', level: 'A', description: 'Reading order is correct and meaningful' },\n '1.3.5': { name: 'Identify Input Purpose', level: 'AA', description: 'Input purpose can be programmatically determined' },\n '1.4.1': { name: 'Use of Color', level: 'A', description: 'Color is not the only means of conveying information' },\n '1.4.3': { name: 'Contrast (Minimum)', level: 'AA', description: 'Text has 4.5:1 contrast ratio (3:1 for large text)' },\n '1.4.4': { name: 'Resize Text', level: 'AA', description: 'Text can be resized up to 200% without loss of functionality' },\n '1.4.10': { name: 'Reflow', level: 'AA', description: 'Content can reflow without horizontal scrolling at 320px width' },\n '1.4.11': { name: 'Non-text Contrast', level: 'AA', description: 'UI components have 3:1 contrast ratio' },\n '1.4.12': { name: 'Text Spacing', level: 'AA', description: 'No loss of content when text spacing is adjusted' },\n '1.4.13': { name: 'Content on Hover or Focus', level: 'AA', description: 'Hover/focus content is dismissible, hoverable, persistent' },\n\n // Operable\n '2.1.1': { name: 'Keyboard', level: 'A', description: 'All functionality is available from keyboard' },\n '2.1.2': { name: 'No Keyboard Trap', level: 'A', description: 'Keyboard focus can be moved away using standard keys' },\n '2.4.1': { name: 'Bypass Blocks', level: 'A', description: 'Skip links or landmarks allow bypassing repeated content' },\n '2.4.3': { name: 'Focus Order', level: 'A', description: 'Focus order preserves meaning and operability' },\n '2.4.4': { name: 'Link Purpose (In Context)', level: 'A', description: 'Link purpose is clear from text or context' },\n '2.4.6': { name: 'Headings and Labels', level: 'AA', description: 'Headings and labels describe topic or purpose' },\n '2.4.7': { name: 'Focus Visible', level: 'AA', description: 'Keyboard focus indicator is visible' },\n '2.5.5': { name: 'Target Size', level: 'AAA', description: 'Touch targets are at least 44×44 CSS pixels' },\n '2.5.8': { name: 'Target Size (Minimum)', level: 'AA', description: 'Touch targets are at least 24×24 CSS pixels' },\n\n // Understandable\n '3.2.1': { name: 'On Focus', level: 'A', description: 'Focus does not trigger unexpected context changes' },\n '3.2.2': { name: 'On Input', level: 'A', description: 'Input does not trigger unexpected context changes' },\n '3.3.1': { name: 'Error Identification', level: 'A', description: 'Errors are identified and described in text' },\n '3.3.2': { name: 'Labels or Instructions', level: 'A', description: 'Labels or instructions are provided for user input' },\n\n // Robust\n '4.1.1': { name: 'Parsing', level: 'A', description: 'HTML is well-formed with unique IDs' },\n '4.1.2': { name: 'Name, Role, Value', level: 'A', description: 'UI components have accessible name, role, and state' },\n '4.1.3': { name: 'Status Messages', level: 'AA', description: 'Status messages are announced to assistive technology' },\n} as const;\n\n/**\n * Required ARIA attributes for each role\n */\nconst REQUIRED_ARIA_ATTRIBUTES: Record<string, string[]> = {\n 'checkbox': ['aria-checked'],\n 'combobox': ['aria-expanded', 'aria-controls'],\n 'grid': ['aria-rowcount', 'aria-colcount'],\n 'gridcell': [],\n 'heading': ['aria-level'],\n 'listbox': [],\n 'menu': [],\n 'menubar': [],\n 'menuitem': [],\n 'menuitemcheckbox': ['aria-checked'],\n 'menuitemradio': ['aria-checked'],\n 'option': ['aria-selected'],\n 'progressbar': ['aria-valuenow', 'aria-valuemin', 'aria-valuemax'],\n 'radio': ['aria-checked'],\n 'scrollbar': ['aria-controls', 'aria-valuenow', 'aria-valuemin', 'aria-valuemax', 'aria-orientation'],\n 'searchbox': [],\n 'separator': [],\n 'slider': ['aria-valuenow', 'aria-valuemin', 'aria-valuemax'],\n 'spinbutton': ['aria-valuenow', 'aria-valuemin', 'aria-valuemax'],\n 'switch': ['aria-checked'],\n 'tab': ['aria-selected'],\n 'tablist': [],\n 'tabpanel': [],\n 'textbox': [],\n 'tree': [],\n 'treegrid': [],\n 'treeitem': [],\n};\n\n/**\n * Accessibility Agent — Comprehensive WCAG 2.1 Compliance\n * \n * This agent performs thorough accessibility audits matching and exceeding\n * tools like rams.ai, axe-core, and Lighthouse accessibility checks.\n * \n * Coverage:\n * - Critical: Blocks access entirely (images without alt, icon-only buttons)\n * - Serious: Significantly impairs access (focus removal, keyboard traps)\n * - Moderate: Creates barriers (missing labels, color-only info)\n * - Low: Best practices (touch targets, heading levels)\n */\nexport class AccessibilityAgent extends BaseAgent {\n name = 'accessibility';\n description = 'WCAG 2.1 AA compliance: screen readers, keyboard nav, color contrast, touch targets, semantic HTML, ARIA patterns';\n version = '2.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 // Core accessibility checks\n issues.push(...this.analyzeImages(content, file));\n issues.push(...this.analyzeInteractiveElements(content, file));\n issues.push(...this.analyzeFormAccessibility(content, file));\n issues.push(...this.analyzeKeyboardNavigation(content, file));\n issues.push(...this.analyzeSemanticStructure(content, file));\n issues.push(...this.analyzeARIAUsage(content, file));\n issues.push(...this.analyzeColorAccessibility(content, file));\n issues.push(...this.analyzeTouchTargets(content, file));\n issues.push(...this.analyzeMotionAccessibility(content, file));\n issues.push(...this.analyzeLinks(content, file));\n }\n } catch (error) {\n console.error(`Accessibility Agent: Error reading file ${file}:`, error);\n }\n }\n\n // Add accessibility summary if there are significant issues\n const criticalCount = issues.filter(i => i.severity === 'critical').length;\n const seriousCount = issues.filter(i => i.severity === 'serious').length;\n \n if (criticalCount > 0 || seriousCount > 2) {\n const score = this.calculateAccessibilityScore(issues);\n issues.push(this.createIssue(\n this.generateIssueId(),\n criticalCount > 0 ? 'critical' : 'serious',\n `Accessibility Score: ${score}/100 — ${criticalCount} critical, ${seriousCount} serious issues`,\n `Review and fix accessibility issues starting with critical problems. Use axe-core or Lighthouse for additional validation.`,\n files[0] || 'project',\n undefined,\n 0.95,\n undefined,\n false\n ));\n }\n\n return issues;\n }\n\n private isFrontendFile(file: string): boolean {\n return /\\.(tsx|jsx|vue|svelte|astro|html|htm)$/.test(file);\n }\n\n /**\n * Calculate accessibility score based on issues\n */\n private calculateAccessibilityScore(issues: Issue[]): number {\n const criticalPenalty = issues.filter(i => i.severity === 'critical').length * 20;\n const seriousPenalty = issues.filter(i => i.severity === 'serious').length * 10;\n const moderatePenalty = issues.filter(i => i.severity === 'moderate').length * 5;\n const lowPenalty = issues.filter(i => i.severity === 'low').length * 2;\n \n return Math.max(0, 100 - criticalPenalty - seriousPenalty - moderatePenalty - lowPenalty);\n }\n\n /**\n * Get WCAG criterion string\n */\n private getWCAGRef(criterionId: keyof typeof WCAG_CRITERIA): string {\n const criterion = WCAG_CRITERIA[criterionId];\n return `WCAG 2.1 ${criterion.level} - ${criterionId} ${criterion.name}`;\n }\n\n // ============================================================================\n // IMAGE ACCESSIBILITY — WCAG 1.1.1\n // ============================================================================\n\n private analyzeImages(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\\s/i.test(line)) {\n if (!line.includes('alt=')) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'critical',\n 'Image missing alt attribute',\n 'Add alt=\"description\" for informative images or alt=\"\" for decorative images. Screen readers cannot describe this image.',\n file,\n lineNumber,\n 0.98,\n this.getWCAGRef('1.1.1'),\n true\n ));\n } else if (/alt=[\"']\\s*[\"']/i.test(line)) {\n // Empty alt is valid for decorative images, but check if it looks informative\n const context = lines.slice(Math.max(0, i - 3), i + 3).join('\\n');\n if (/hero|logo|banner|product|avatar|icon/i.test(context) && !/decorative|spacer|divider/i.test(context)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Empty alt on potentially informative image',\n 'If this image conveys information, add descriptive alt text. Empty alt is only for purely decorative images.',\n file,\n lineNumber,\n 0.70,\n this.getWCAGRef('1.1.1'),\n true\n ));\n }\n }\n }\n\n // Check for background images that might need text alternatives\n if (/background-image:\\s*url\\(/i.test(line) || /backgroundImage.*url\\(/i.test(line)) {\n const context = lines.slice(Math.max(0, i - 5), i + 5).join('\\n');\n if (/hero|banner|feature|card/i.test(context) && !/aria-label|sr-only|visually-hidden/i.test(context)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Background image may need text alternative',\n 'If this background image conveys information, add a text alternative using aria-label or visually hidden text.',\n file,\n lineNumber,\n 0.65,\n this.getWCAGRef('1.1.1'),\n false\n ));\n }\n }\n\n // Check for SVG without accessible name\n if (/<svg\\s/i.test(line)) {\n const svgContext = this.getMultiLineElement(lines, i, 'svg');\n if (!/aria-label|aria-labelledby|<title>|role=[\"']img[\"']/i.test(svgContext) && \n !/aria-hidden=[\"']true[\"']/i.test(svgContext)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'SVG missing accessible name',\n 'Add aria-label, aria-labelledby with <title>, or aria-hidden=\"true\" if decorative.',\n file,\n lineNumber,\n 0.85,\n this.getWCAGRef('1.1.1'),\n true\n ));\n }\n }\n }\n\n return issues;\n }\n\n // ============================================================================\n // INTERACTIVE ELEMENTS — WCAG 4.1.2, 2.1.1\n // ============================================================================\n\n private analyzeInteractiveElements(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 icon-only buttons without accessible name\n if (/<button/i.test(line) || /Button\\s/i.test(line)) {\n const buttonContext = this.getMultiLineElement(lines, i, 'button') || \n this.getMultiLineElement(lines, i, 'Button');\n \n // Detect icon-only patterns\n const hasIconOnly = />\\s*<(Icon|svg|i\\s|img)[^>]*>\\s*<\\/(button|Button)/i.test(buttonContext) ||\n />\\s*<[A-Z][a-zA-Z]*Icon[^>]*\\s*\\/>\\s*<\\/(button|Button)/i.test(buttonContext) ||\n /<(Icon|svg)[^>]*\\/>\\s*<\\/(button|Button)/i.test(buttonContext);\n \n const hasAccessibleName = /aria-label|aria-labelledby|title=|sr-only|visually-hidden/i.test(buttonContext);\n \n if (hasIconOnly && !hasAccessibleName) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'critical',\n 'Icon-only button missing accessible name',\n 'Add aria-label=\"Close\" or include visually hidden text. Screen reader users cannot identify this button.',\n file,\n lineNumber,\n 0.95,\n this.getWCAGRef('4.1.2'),\n true\n ));\n }\n }\n\n // Check for non-semantic click handlers (div, span with onClick)\n if (/onClick|@click|v-on:click|\\(click\\)/i.test(line)) {\n // Check if it's on a non-interactive element\n if (/<(div|span|li|td|tr|p|section|article)\\s/i.test(line) && \n !/role=[\"'](button|link|menuitem|tab|option)/i.test(line)) {\n \n const elementContext = lines.slice(Math.max(0, i - 2), i + 3).join('\\n');\n const hasKeyboardSupport = /onKeyDown|onKeyPress|onKeyUp|@keydown|@keypress|@keyup|\\(keydown\\)|\\(keypress\\)/i.test(elementContext);\n const hasRole = /role=/i.test(elementContext);\n const hasTabIndex = /tabIndex|tabindex/i.test(elementContext);\n \n if (!hasKeyboardSupport) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'critical',\n 'Non-semantic element with click handler lacks keyboard support',\n `Add role=\"button\" tabIndex={0} onKeyDown={(e) => e.key === 'Enter' && handleClick()}. Or use a <button> element instead.`,\n file,\n lineNumber,\n 0.92,\n this.getWCAGRef('2.1.1'),\n true\n ));\n } else if (!hasRole || !hasTabIndex) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Clickable element missing role or tabIndex',\n 'Add role=\"button\" and tabIndex={0} for proper keyboard accessibility.',\n file,\n lineNumber,\n 0.85,\n this.getWCAGRef('4.1.2'),\n true\n ));\n }\n }\n }\n\n // Check for links without href\n if (/<a\\s/i.test(line) || /<Link\\s/i.test(line)) {\n const linkContext = this.getMultiLineElement(lines, i, 'a') || \n this.getMultiLineElement(lines, i, 'Link');\n \n if (!/href=|to=/i.test(linkContext)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Link element without href',\n 'Add href attribute or use a <button> if this triggers an action. Links must have a destination.',\n file,\n lineNumber,\n 0.90,\n this.getWCAGRef('2.4.4'),\n true\n ));\n }\n }\n }\n\n return issues;\n }\n\n // ============================================================================\n // FORM ACCESSIBILITY — WCAG 1.3.1, 3.3.2, 1.3.5\n // ============================================================================\n\n private analyzeFormAccessibility(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 inputs without labels\n if (/<input\\s/i.test(line) || /<Input\\s/i.test(line) || /<textarea/i.test(line) || /<select/i.test(line)) {\n const inputContext = lines.slice(Math.max(0, i - 5), i + 5).join('\\n');\n \n const hasLabel = /<label/i.test(inputContext) && /htmlFor|for=/i.test(inputContext);\n const hasAriaLabel = /aria-label=/i.test(line);\n const hasAriaLabelledBy = /aria-labelledby=/i.test(line);\n const hasPlaceholder = /placeholder=/i.test(line);\n const hasTitle = /title=/i.test(line);\n \n if (!hasLabel && !hasAriaLabel && !hasAriaLabelledBy) {\n if (hasPlaceholder && !hasTitle) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Form input uses placeholder as only label',\n 'Placeholder text disappears when typing. Add a visible <label> or aria-label for persistent identification.',\n file,\n lineNumber,\n 0.88,\n this.getWCAGRef('3.3.2'),\n true\n ));\n } else if (!hasTitle) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Form input without accessible label',\n 'Add <label htmlFor=\"id\"> associated with input, or use aria-label/aria-labelledby.',\n file,\n lineNumber,\n 0.85,\n this.getWCAGRef('1.3.1'),\n true\n ));\n }\n }\n\n // Check for autocomplete attribute on appropriate inputs\n if (/type=[\"'](email|tel|password|name|address|cc-|url)/i.test(line) && !/autoComplete|autocomplete/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Input missing autocomplete attribute',\n 'Add autocomplete attribute (e.g., autocomplete=\"email\") to help users fill forms.',\n file,\n lineNumber,\n 0.70,\n this.getWCAGRef('1.3.5'),\n true\n ));\n }\n }\n\n // Check for required inputs without aria-required or visual indication\n if (/required(?!=\\{false\\})/i.test(line) && !/aria-required|required.*\\*/i.test(line)) {\n const labelContext = lines.slice(Math.max(0, i - 5), i + 5).join('\\n');\n if (!/\\*|required|Required/i.test(labelContext)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Required field lacks visual indication',\n 'Add visual indicator (e.g., asterisk *) and aria-required=\"true\" for clarity.',\n file,\n lineNumber,\n 0.75,\n this.getWCAGRef('3.3.2'),\n true\n ));\n }\n }\n\n // Check for disabled elements without explanation\n if (/disabled(?!=\\{false\\})/i.test(line)) {\n const elementContext = lines.slice(Math.max(0, i - 2), i + 2).join('\\n');\n if (!/title=|aria-describedby|tooltip|Tooltip/i.test(elementContext)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Disabled element without explanation',\n 'Add tooltip or aria-describedby explaining why the action is unavailable.',\n file,\n lineNumber,\n 0.65,\n undefined,\n true\n ));\n }\n }\n }\n\n return issues;\n }\n\n // ============================================================================\n // KEYBOARD NAVIGATION — WCAG 2.1.1, 2.1.2, 2.4.3, 2.4.7\n // ============================================================================\n\n private analyzeKeyboardNavigation(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 focus outline removal without replacement\n if (/outline:\\s*none|outline:\\s*0|outline-width:\\s*0/i.test(line)) {\n const styleContext = lines.slice(Math.max(0, i - 3), i + 3).join('\\n');\n const hasFocusReplacement = /focus-visible|ring-|box-shadow.*focus|border.*focus|outline.*focus-visible/i.test(styleContext);\n \n if (!hasFocusReplacement) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Focus outline removed without replacement',\n 'Add focus-visible:ring-2 or custom focus indicator. Keyboard users cannot see where they are.',\n file,\n lineNumber,\n 0.92,\n this.getWCAGRef('2.4.7'),\n true\n ));\n }\n }\n\n // Check for Tailwind focus removal\n if (/focus:outline-none|outline-none/i.test(line)) {\n const styleContext = lines.slice(Math.max(0, i - 1), i + 2).join('\\n');\n if (!/focus-visible:ring|focus:ring|focus-visible:border|focus:border/i.test(styleContext)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Tailwind outline-none without focus replacement',\n 'Add focus-visible:ring-2 focus-visible:ring-offset-2 for visible focus indicator.',\n file,\n lineNumber,\n 0.90,\n this.getWCAGRef('2.4.7'),\n true\n ));\n }\n }\n\n // Check for positive tabindex values (disrupts natural tab order)\n if (/tabIndex=\\{?[\"']?([1-9]\\d*)[\"']?\\}?|tabindex=[\"']([1-9]\\d*)[\"']/i.test(line)) {\n const match = line.match(/tabIndex=\\{?[\"']?([1-9]\\d*)[\"']?\\}?|tabindex=[\"']([1-9]\\d*)[\"']/i);\n const value = match?.[1] || match?.[2];\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n `Positive tabIndex value (${value}) disrupts natural tab order`,\n 'Use tabIndex={0} for focusable elements or tabIndex={-1} for programmatic focus. Positive values create confusing navigation.',\n file,\n lineNumber,\n 0.88,\n this.getWCAGRef('2.4.3'),\n true\n ));\n }\n\n // Check for keyboard traps in modals/dialogs\n if (/modal|dialog|drawer|overlay/i.test(line.toLowerCase())) {\n const componentContext = lines.slice(i, Math.min(lines.length, i + 30)).join('\\n');\n if (/onClose|onDismiss|closeModal/i.test(componentContext)) {\n if (!/onKeyDown.*Escape|useEscapeKey|handleEscape|key.*===.*Escape/i.test(componentContext)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Modal/dialog may trap keyboard focus without Escape key support',\n 'Add Escape key handler to close modal and manage focus trap with focus-trap library.',\n file,\n lineNumber,\n 0.75,\n this.getWCAGRef('2.1.2'),\n false\n ));\n }\n }\n }\n }\n\n return issues;\n }\n\n // ============================================================================\n // SEMANTIC STRUCTURE — WCAG 1.3.1, 2.4.6\n // ============================================================================\n\n private analyzeSemanticStructure(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n \n // Track heading levels to detect skipping\n const headingLevels: { level: number; line: number }[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const lineNumber = i + 1;\n\n // Extract heading levels\n const headingMatch = line.match(/<h([1-6])|role=[\"']heading[\"'].*aria-level=[\"'](\\d)[\"']/i);\n if (headingMatch) {\n const level = parseInt(headingMatch[1] || headingMatch[2] || '0');\n if (level > 0) {\n headingLevels.push({ level, line: lineNumber });\n }\n }\n\n // Check for semantic element opportunities\n if (/<div[^>]*class=[\"'][^\"']*nav|navigation/i.test(line) && !/<nav/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Navigation using div instead of semantic <nav>',\n 'Use <nav> element for navigation sections. Screen readers announce this as navigation.',\n file,\n lineNumber,\n 0.80,\n this.getWCAGRef('1.3.1'),\n true\n ));\n }\n\n if (/<div[^>]*class=[\"'][^\"']*header/i.test(line) && !/<header/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Header content using div instead of semantic <header>',\n 'Use <header> element for page/section headers for better screen reader navigation.',\n file,\n lineNumber,\n 0.70,\n this.getWCAGRef('1.3.1'),\n true\n ));\n }\n\n if (/<div[^>]*class=[\"'][^\"']*footer/i.test(line) && !/<footer/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Footer content using div instead of semantic <footer>',\n 'Use <footer> element for page/section footers for better screen reader navigation.',\n file,\n lineNumber,\n 0.70,\n this.getWCAGRef('1.3.1'),\n true\n ));\n }\n\n if (/<div[^>]*class=[\"'][^\"']*main/i.test(line) && !/<main/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Main content using div instead of semantic <main>',\n 'Use <main> element for primary content. Allows \"skip to main content\" functionality.',\n file,\n lineNumber,\n 0.75,\n this.getWCAGRef('2.4.1'),\n true\n ));\n }\n\n // Check for list content without list semantics\n if (/<div[^>]*class=[\"'][^\"']*(list|items|menu)[^\"']*[\"']/i.test(line)) {\n const context = lines.slice(i, Math.min(lines.length, i + 10)).join('\\n');\n if (!/<ul|<ol|<menu|role=[\"']list/i.test(context)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'List-like content without list semantics',\n 'Use <ul>/<ol> for lists or add role=\"list\" with role=\"listitem\" children.',\n file,\n lineNumber,\n 0.65,\n this.getWCAGRef('1.3.1'),\n false\n ));\n }\n }\n }\n\n // Check for skipped heading levels\n for (let i = 1; i < headingLevels.length; i++) {\n const current = headingLevels[i]!;\n const previous = headingLevels[i - 1]!;\n \n if (current.level > previous.level + 1) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n `Skipped heading level: h${previous.level} to h${current.level}`,\n `Heading levels should not skip. Go from h${previous.level} to h${previous.level + 1}. Screen reader users navigate by headings.`,\n file,\n current.line,\n 0.85,\n this.getWCAGRef('2.4.6'),\n true\n ));\n }\n }\n\n // Check if page starts with h1\n if (headingLevels.length > 0 && headingLevels[0]!.level !== 1) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n `First heading is h${headingLevels[0]!.level} instead of h1`,\n 'Each page should start with an h1 describing the page content.',\n file,\n headingLevels[0]!.line,\n 0.80,\n this.getWCAGRef('2.4.6'),\n true\n ));\n }\n\n return issues;\n }\n\n // ============================================================================\n // ARIA USAGE — WCAG 4.1.2\n // ============================================================================\n\n private analyzeARIAUsage(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 role without required ARIA attributes\n const roleMatch = line.match(/role=[\"']([a-z]+)[\"']/i);\n if (roleMatch) {\n const role = roleMatch[1]!.toLowerCase();\n const requiredAttrs = REQUIRED_ARIA_ATTRIBUTES[role];\n \n if (requiredAttrs && requiredAttrs.length > 0) {\n const elementContext = this.getMultiLineElement(lines, i, undefined) || line;\n const missingAttrs = requiredAttrs.filter(attr => !new RegExp(attr, 'i').test(elementContext));\n \n if (missingAttrs.length > 0) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n `Role \"${role}\" missing required ARIA attributes: ${missingAttrs.join(', ')}`,\n `Add ${missingAttrs.map(a => `${a}=\"value\"`).join(' ')} for proper screen reader support.`,\n file,\n lineNumber,\n 0.88,\n this.getWCAGRef('4.1.2'),\n true\n ));\n }\n }\n }\n\n // Check for aria-hidden on focusable elements\n if (/aria-hidden=[\"']true[\"']/i.test(line)) {\n const elementContext = lines.slice(Math.max(0, i - 1), i + 5).join('\\n');\n if (/<(button|a|input|select|textarea)|tabIndex=\\{?[\"']?0|tabindex=[\"']0/i.test(elementContext)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'aria-hidden on element containing focusable content',\n 'Remove aria-hidden or add tabIndex={-1} to focusable children. Hidden content should not be focusable.',\n file,\n lineNumber,\n 0.85,\n this.getWCAGRef('4.1.2'),\n true\n ));\n }\n }\n\n // Check for invalid ARIA attribute values\n if (/aria-expanded=[\"'](yes|no)[\"']/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Invalid aria-expanded value (use \"true\"/\"false\" not \"yes\"/\"no\")',\n 'Use aria-expanded=\"true\" or aria-expanded=\"false\".',\n file,\n lineNumber,\n 0.95,\n this.getWCAGRef('4.1.2'),\n true\n ));\n }\n\n // Check for aria-label on non-interactive elements\n if (/aria-label=/i.test(line)) {\n if (/<(div|span|p|section)\\s/i.test(line) && !/role=/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'aria-label on non-interactive element without role',\n 'Add an appropriate role or use aria-labelledby for non-interactive regions.',\n file,\n lineNumber,\n 0.70,\n this.getWCAGRef('4.1.2'),\n false\n ));\n }\n }\n\n // Check for live regions\n if (/aria-live=/i.test(line)) {\n if (!/aria-live=[\"'](polite|assertive|off)[\"']/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Invalid aria-live value',\n 'Use aria-live=\"polite\" for non-urgent updates or aria-live=\"assertive\" for critical alerts.',\n file,\n lineNumber,\n 0.85,\n this.getWCAGRef('4.1.3'),\n true\n ));\n }\n }\n\n // Check for status messages that should use aria-live\n if (/toast|notification|alert|error.*message|success.*message/i.test(line)) {\n const context = lines.slice(Math.max(0, i - 3), i + 5).join('\\n');\n if (!/aria-live|role=[\"']alert|role=[\"']status/i.test(context)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Status message may not be announced to screen readers',\n 'Add role=\"status\" aria-live=\"polite\" for status messages or role=\"alert\" for errors.',\n file,\n lineNumber,\n 0.75,\n this.getWCAGRef('4.1.3'),\n true\n ));\n }\n }\n }\n\n return issues;\n }\n\n // ============================================================================\n // COLOR ACCESSIBILITY — WCAG 1.4.1, 1.4.3, 1.4.11\n // ============================================================================\n\n private analyzeColorAccessibility(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 color-only information indicators\n if (/color:\\s*(red|green|#f00|#0f0|#ff0000|#00ff00)/i.test(line)) {\n const context = lines.slice(Math.max(0, i - 5), i + 5).join('\\n');\n if (/error|success|warning|valid|invalid/i.test(context)) {\n if (!/icon|Icon|✓|✗|×|⚠|aria-label|sr-only|visually-hidden/i.test(context)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Color may be the only indicator of status',\n 'Add icon, text, or other visual indicator besides color. Colorblind users cannot distinguish red/green.',\n file,\n lineNumber,\n 0.80,\n this.getWCAGRef('1.4.1'),\n true\n ));\n }\n }\n }\n\n // Check for potentially low contrast text colors\n if (/color:\\s*#([0-9a-f]{3,6})/i.test(line)) {\n const hexMatch = line.match(/color:\\s*#([0-9a-f]{3,6})/i);\n if (hexMatch) {\n const hex = hexMatch[1]!.toLowerCase();\n const lightness = this.getRelativeLuminance(hex);\n \n // Flag mid-gray colors that often fail contrast\n if (lightness > 0.3 && lightness < 0.5) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Text color may have insufficient contrast',\n 'Verify 4.5:1 contrast ratio at webaim.org/resources/contrastchecker. Consider darker (#374151) or lighter (#d1d5db) alternatives.',\n file,\n lineNumber,\n 0.65,\n this.getWCAGRef('1.4.3'),\n false\n ));\n }\n }\n }\n\n // Check for border-only focus indicators (may have low contrast)\n if (/focus.*border/i.test(line) && !/ring|outline|shadow/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Focus indicator uses only border - verify 3:1 contrast',\n 'Ensure focus border has 3:1 contrast against adjacent colors. Consider adding focus ring.',\n file,\n lineNumber,\n 0.60,\n this.getWCAGRef('1.4.11'),\n false\n ));\n }\n }\n\n return issues;\n }\n\n // ============================================================================\n // TOUCH TARGETS — WCAG 2.5.5, 2.5.8\n // ============================================================================\n\n private analyzeTouchTargets(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 small explicit sizes on interactive elements\n if (/<(button|a|input|select)|onClick|@click/i.test(line)) {\n const sizeMatch = line.match(/(?:width|height|size):\\s*(\\d+)(?:px)?/i) ||\n line.match(/(?:w-|h-)(\\d+)/);\n \n if (sizeMatch) {\n const size = parseInt(sizeMatch[1]!);\n // Tailwind w-8 = 32px, w-10 = 40px, w-11 = 44px\n const pxSize = size <= 12 ? size * 4 : size; // Convert Tailwind to px estimate\n \n if (pxSize < 24) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n `Touch target size ${pxSize}px is below WCAG minimum (24px)`,\n 'Increase touch target to at least 24×24px (WCAG AA) or 44×44px (WCAG AAA) for mobile usability.',\n file,\n lineNumber,\n 0.75,\n this.getWCAGRef('2.5.8'),\n true\n ));\n } else if (pxSize < 44) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n `Touch target size ${pxSize}px is below recommended 44px`,\n 'Consider increasing to 44×44px for optimal mobile usability (WCAG AAA).',\n file,\n lineNumber,\n 0.60,\n this.getWCAGRef('2.5.5'),\n false\n ));\n }\n }\n }\n\n // Check for icon-only buttons that might be too small\n if (/(Icon|icon).*size=[\"']?(sm|xs|small|12|14|16)/i.test(line)) {\n const context = lines.slice(Math.max(0, i - 2), i + 2).join('\\n');\n if (/<button|onClick/i.test(context) && !/p-|padding/i.test(context)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Small icon button may have insufficient touch target',\n 'Add padding (e.g., p-2 or p-3) to ensure 44×44px touch target around small icons.',\n file,\n lineNumber,\n 0.70,\n this.getWCAGRef('2.5.8'),\n true\n ));\n }\n }\n }\n\n return issues;\n }\n\n // ============================================================================\n // MOTION ACCESSIBILITY — WCAG 2.3.3\n // ============================================================================\n\n private analyzeMotionAccessibility(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n\n // Check for animations without reduced-motion handling\n if (/animation:|@keyframes|animate-|transition:/i.test(content)) {\n if (!/prefers-reduced-motion/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Animations without prefers-reduced-motion support',\n 'Add @media (prefers-reduced-motion: reduce) { animation: none; transition: none; } for motion-sensitive users.',\n file,\n undefined,\n 0.80,\n 'WCAG 2.1 AA - 2.3.3 Animation from Interactions',\n false\n ));\n }\n }\n\n // Check for autoplay video/audio\n if (/autoPlay|autoplay/i.test(content)) {\n if (!/muted|controls/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Autoplaying media without mute or controls',\n 'Add muted attribute or provide controls. Autoplay audio can disorient screen reader users.',\n file,\n undefined,\n 0.85,\n 'WCAG 2.1 A - 1.4.2 Audio Control',\n true\n ));\n }\n }\n\n return issues;\n }\n\n // ============================================================================\n // LINK ACCESSIBILITY — WCAG 2.4.4\n // ============================================================================\n\n private analyzeLinks(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 empty links\n if (/<a[^>]*>\\s*<\\/a>/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'critical',\n 'Empty link with no text content',\n 'Add meaningful link text or aria-label. Screen readers announce this as \"link\" with no destination.',\n file,\n lineNumber,\n 0.95,\n this.getWCAGRef('2.4.4'),\n true\n ));\n }\n\n // Check for placeholder href\n if (/href=[\"']#[\"']\\s*>/i.test(line) && !/onClick|@click/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Link with placeholder href=\"#\"',\n 'Add meaningful destination or use <button> for actions. Placeholder links confuse users.',\n file,\n lineNumber,\n 0.80,\n this.getWCAGRef('2.4.4'),\n true\n ));\n }\n\n // Check for generic link text\n if (/>(?:click here|here|read more|learn more|more)<\\/a>/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Generic link text (\"click here\", \"read more\")',\n 'Use descriptive link text that makes sense out of context. Screen reader users navigate by link list.',\n file,\n lineNumber,\n 0.75,\n this.getWCAGRef('2.4.4'),\n true\n ));\n }\n\n // Check for links opening in new window without warning\n if (/target=[\"']_blank[\"']/i.test(line)) {\n if (!/aria-label.*new window|aria-label.*new tab|external|External|↗|↪/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Link opens in new window without warning',\n 'Add visual indicator (↗) and aria-label mentioning \"opens in new window\" for user awareness.',\n file,\n lineNumber,\n 0.65,\n this.getWCAGRef('3.2.5'),\n true\n ));\n }\n }\n\n // Check for adjacent links to same destination\n if (/<a[^>]*href=[\"']([^\"']+)[\"'][^>]*>.*<img/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Image and text link may create duplicate links',\n 'Combine image and text in single link or add aria-hidden=\"true\" to decorative image link.',\n file,\n lineNumber,\n 0.60,\n this.getWCAGRef('2.4.4'),\n false\n ));\n }\n }\n\n return issues;\n }\n\n // ============================================================================\n // UTILITY METHODS\n // ============================================================================\n\n /**\n * Get multi-line element content starting at line index\n */\n private getMultiLineElement(lines: string[], startIndex: number, tagName?: string): string | null {\n const startLine = lines[startIndex];\n if (!startLine) return null;\n\n // If tag closes on same line, return it\n const tag = tagName || startLine.match(/<([a-zA-Z][a-zA-Z0-9]*)/)?.[1];\n if (!tag) return startLine;\n\n if (new RegExp(`</${tag}|/>`, 'i').test(startLine)) {\n return startLine;\n }\n\n // Otherwise, collect lines until closing tag\n let content = startLine;\n for (let j = startIndex + 1; j < Math.min(lines.length, startIndex + 20); j++) {\n content += '\\n' + lines[j];\n if (new RegExp(`</${tag}>|/>`, 'i').test(lines[j]!)) {\n break;\n }\n }\n \n return content;\n }\n\n /**\n * Calculate relative luminance for contrast checking\n */\n private getRelativeLuminance(hex: string): number {\n // Normalize to 6 characters\n let normalized = hex.length === 3 \n ? hex.split('').map(c => c + c).join('')\n : hex;\n \n const r = parseInt(normalized.slice(0, 2), 16) / 255;\n const g = parseInt(normalized.slice(2, 4), 16) / 255;\n const b = parseInt(normalized.slice(4, 6), 16) / 255;\n \n const [R, G, B] = [r, g, b].map(c => \n c <= 0.03928 ? c / 12.92 : Math.pow((c + 0.055) / 1.055, 2.4)\n );\n \n return 0.2126 * R! + 0.7152 * G! + 0.0722 * B!;\n }\n\n /**\n * AI Enhancement for accessibility review\n */\n protected override getAIEnhancementSystemPrompt(): string {\n return `You are a WCAG 2.1 AA accessibility expert and inclusive design advocate. \nReview code for comprehensive accessibility compliance.\n\n## Analysis Categories\n\n### Critical (Blocks Access)\n- Images without alt text\n- Icon-only buttons missing aria-label\n- Non-semantic click handlers without keyboard support\n- Empty links\n- Missing form labels\n\n### Serious (Significantly Impairs)\n- Focus outline removed without replacement\n- Positive tabIndex values disrupting tab order\n- Role without required ARIA attributes\n- Color-only status indicators\n- Links without href\n\n### Moderate (Creates Barriers)\n- Skipped heading levels\n- Missing autocomplete on inputs\n- Touch targets under 44px\n- Generic link text\n- Missing prefers-reduced-motion\n\n### Low (Best Practices)\n- Semantic element opportunities\n- Status messages without aria-live\n- External links without warning\n\n## WCAG Success Criteria Reference\n- 1.1.1: Non-text Content (images, icons)\n- 1.3.1: Info and Relationships (semantic HTML)\n- 1.4.1: Use of Color (color-only info)\n- 1.4.3: Contrast (Minimum)\n- 2.1.1: Keyboard accessibility\n- 2.4.3: Focus Order\n- 2.4.4: Link Purpose\n- 2.4.6: Headings and Labels\n- 2.4.7: Focus Visible\n- 2.5.5: Target Size\n- 4.1.2: Name, Role, Value\n\n## Output Format\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\" | \"serious\" | \"moderate\" | \"low\",\n \"wcag_criterion\": \"WCAG 2.1 AA - X.X.X Name\",\n \"impact\": \"How this affects users with disabilities\",\n \"code_snippet\": \"The problematic code\",\n \"fix\": \"Accessible code fix with example\"\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 description\",\n \"code_snippet\": \"Problematic code\",\n \"fix\": \"Accessible implementation with example\"\n }],\n \"score\": {\n \"overall\": 85,\n \"critical_count\": 0,\n \"serious_count\": 2,\n \"moderate_count\": 5,\n \"low_count\": 3\n },\n \"summary\": \"Overall accessibility assessment with key recommendations\"\n}`;\n }\n}\n","import { BaseAgent } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\n\n// ============================================================================\n// DESIGN CONTEXT TYPES — Layer 1 of Design Intelligence\n// ============================================================================\n\n/**\n * Product types that influence design decisions\n */\ntype ProductType = 'saas' | 'ecommerce' | 'portfolio' | 'dashboard' | 'marketing' | 'social' | 'fintech' | 'health' | 'education' | 'fitness' | 'creativeTools';\n\n/**\n * Emotional targets for design\n */\ntype DesiredFeeling = 'calm' | 'energetic' | 'trustworthy' | 'playful' | 'premium' | 'minimal' | 'bold';\n\n/**\n * Design context extracted from codebase\n */\ninterface DesignContext {\n productType: ProductType;\n desiredFeeling?: DesiredFeeling;\n existingBrand?: {\n primaryColor?: string;\n fonts?: string[];\n toneOfVoice?: 'formal' | 'casual' | 'friendly' | 'professional';\n };\n targetAudience?: 'developers' | 'designers' | 'enterprise' | 'consumers' | 'creators' | 'general';\n framework: 'react' | 'vue' | 'svelte' | 'vanilla' | 'unknown';\n hasExistingDesignSystem: boolean;\n competitors?: string[];\n}\n\n/**\n * Domain-specific design rules\n */\ninterface DomainDesignRules {\n defaultMode: 'dark' | 'light';\n accentSuggestions: string[];\n typographyVibe: string;\n motionLevel: 'high' | 'medium' | 'subtle' | 'minimal';\n uiDensity: 'spacious' | 'balanced' | 'compact' | 'minimal-chrome' | 'scannable';\n keyPatterns: string[];\n avoid: string[];\n reference: string[];\n}\n\n/**\n * Domain-specific design rules database\n * Reference: radix-ui.com/colors for accent scales\n */\nconst DOMAIN_DESIGN_RULES: Record<string, DomainDesignRules> = {\n fitness: {\n defaultMode: 'dark',\n accentSuggestions: ['orange', 'tomato', 'amber'], // energetic - from Radix\n typographyVibe: 'bold-condensed',\n motionLevel: 'high',\n uiDensity: 'spacious',\n keyPatterns: ['progress-rings', 'stat-cards', 'workout-timers', 'streak-badges'],\n avoid: ['passive voice', 'too much text', 'busy layouts'],\n reference: ['Strava', 'Nike Training Club', 'Peloton'],\n },\n fintech: {\n defaultMode: 'light',\n accentSuggestions: ['sky', 'teal', 'grass'], // trust + growth - from Radix\n typographyVibe: 'clean-professional',\n motionLevel: 'subtle',\n uiDensity: 'balanced',\n keyPatterns: ['account-cards', 'transaction-lists', 'charts', 'security-indicators'],\n avoid: ['flashy animations', 'informal language', 'unclear numbers'],\n reference: ['Stripe Dashboard', 'Mercury', 'Ramp'],\n },\n creativeTools: {\n defaultMode: 'dark',\n accentSuggestions: ['violet', 'pink', 'sky'], // creative - from Radix\n typographyVibe: 'minimal-clean',\n motionLevel: 'medium',\n uiDensity: 'minimal-chrome',\n keyPatterns: ['canvas-first', 'contextual-toolbars', 'layers-panel'],\n avoid: ['distracting UI', 'modal overload', 'complex menus'],\n reference: ['Figma', 'Linear', 'Notion'],\n },\n ecommerce: {\n defaultMode: 'light',\n accentSuggestions: ['tomato', 'pink', 'amber'], // action-oriented - from Radix\n typographyVibe: 'readable-hierarchy',\n motionLevel: 'subtle',\n uiDensity: 'scannable',\n keyPatterns: ['product-cards', 'filters', 'cart-drawer', 'trust-badges'],\n avoid: ['slow load', 'hidden prices', 'complex checkout'],\n reference: ['Shopify themes', 'Apple Store', 'Glossier'],\n },\n dashboard: {\n defaultMode: 'light',\n accentSuggestions: ['blue', 'indigo', 'cyan'], // professional - from Radix\n typographyVibe: 'clean-readable',\n motionLevel: 'subtle',\n uiDensity: 'balanced',\n keyPatterns: ['data-tables', 'charts', 'stat-cards', 'filters', 'navigation'],\n avoid: ['excessive animations', 'low contrast', 'information overload'],\n reference: ['Linear', 'Vercel Dashboard', 'Stripe Dashboard'],\n },\n marketing: {\n defaultMode: 'light',\n accentSuggestions: ['blue', 'violet', 'crimson'], // attention-grabbing\n typographyVibe: 'bold-impactful',\n motionLevel: 'high',\n uiDensity: 'spacious',\n keyPatterns: ['hero-sections', 'feature-grids', 'testimonials', 'CTAs', 'pricing-tables'],\n avoid: ['walls of text', 'weak CTAs', 'generic stock photos'],\n reference: ['Linear', 'Vercel', 'Stripe', 'Raycast'],\n },\n saas: {\n defaultMode: 'light',\n accentSuggestions: ['blue', 'indigo', 'violet'],\n typographyVibe: 'clean-professional',\n motionLevel: 'medium',\n uiDensity: 'balanced',\n keyPatterns: ['dashboards', 'settings', 'onboarding', 'feature-flags'],\n avoid: ['complex navigation', 'unclear value props'],\n reference: ['Linear', 'Notion', 'Slack'],\n },\n portfolio: {\n defaultMode: 'dark',\n accentSuggestions: ['slate', 'mauve', 'sage'], // premium/minimal\n typographyVibe: 'expressive-editorial',\n motionLevel: 'high',\n uiDensity: 'spacious',\n keyPatterns: ['case-studies', 'image-galleries', 'project-grids', 'about-sections'],\n avoid: ['cluttered layouts', 'generic templates', 'slow loading'],\n reference: ['Awwwards winners', 'Codrops demos'],\n },\n};\n\n// ============================================================================\n// VERIFIED DESIGN TOKEN SOURCES — Reference, Don't Hardcode\n// ============================================================================\n\n/**\n * Design Token Sources — fetch from these, don't hardcode hex values\n * This prevents \"AI slop\" by forcing derivation from context\n * Exported for use in other tools that need verified design references\n */\nexport const DESIGN_TOKEN_SOURCES = {\n colors: {\n radix: {\n url: 'https://www.radix-ui.com/colors',\n docs: 'https://www.radix-ui.com/colors/docs/overview/usage',\n npm: '@radix-ui/colors',\n why: 'Every scale guarantees WCAG AA contrast between steps',\n },\n tailwind: {\n url: 'https://tailwindcss.com/docs/customizing-colors',\n npm: 'tailwindcss',\n why: 'Widely used, stable, good defaults',\n },\n shadcn: {\n url: 'https://ui.shadcn.com/themes',\n docs: 'https://ui.shadcn.com/docs/theming',\n why: 'Pre-built themes with proper contrast',\n },\n contrastChecker: {\n url: 'https://webaim.org/resources/contrastchecker/',\n why: 'Validate any color passes WCAG AA (4.5:1 for text)',\n },\n },\n feelingToScale: {\n energetic: { radix: ['orange', 'tomato', 'amber'], tailwind: ['orange', 'amber'] },\n calm: { radix: ['teal', 'cyan', 'sky'], tailwind: ['teal', 'cyan', 'sky'] },\n trustworthy: { radix: ['blue', 'sky'], tailwind: ['blue', 'sky'] },\n growth: { radix: ['grass', 'green', 'teal'], tailwind: ['green', 'emerald', 'teal'] },\n bold: { radix: ['crimson', 'ruby', 'pink'], tailwind: ['rose', 'pink', 'fuchsia'] },\n premium: { radix: ['slate', 'mauve', 'sage'], tailwind: ['slate', 'zinc', 'neutral'] },\n playful: { radix: ['pink', 'plum', 'violet'], tailwind: ['pink', 'purple', 'violet'] },\n minimal: { radix: ['slate', 'gray', 'sand'], tailwind: ['slate', 'zinc', 'stone'] },\n },\n contrastRules: {\n textOnBackground: 4.5, // WCAG AA\n largeTextOnBackground: 3.0, // 18px+ or 14px+ bold\n uiComponents: 3.0, // Buttons, inputs, icons\n focusIndicators: 3.0, // Focus rings\n surfaceFromBackground: 8, // 8% lightness difference minimum\n maxSaturationAccent: 75, // Prevents neon slop\n maxSaturationBackground: 15,\n maxSaturationText: 5,\n },\n};\n\n/**\n * Verified Typography Tokens\n * Exported for use in other tools that need verified design references\n */\nexport const TYPOGRAPHY_TOKENS = {\n fontStack: {\n sans: \"'Inter', 'Geist Sans', -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif\",\n mono: \"'JetBrains Mono', 'Fira Code', 'SF Mono', monospace\",\n },\n sizes: {\n xs: '0.75rem', // 12px\n sm: '0.875rem', // 14px\n base: '1rem', // 16px\n lg: '1.125rem', // 18px\n xl: '1.25rem', // 20px\n '2xl': '1.5rem', // 24px\n '3xl': '1.875rem',// 30px\n '4xl': '2.25rem', // 36px\n '5xl': '3rem', // 48px\n },\n weights: {\n normal: 400,\n medium: 500,\n semibold: 600,\n bold: 700,\n },\n lineHeights: {\n none: 1,\n tight: 1.25,\n snug: 1.375,\n normal: 1.5,\n relaxed: 1.625,\n },\n};\n\n/**\n * Verified Spacing Tokens (4px base grid)\n */\nconst SPACING_TOKENS = {\n scale: [0, 1, 2, 4, 6, 8, 12, 16, 20, 24, 32, 40, 48, 64, 80, 96],\n allowedPx: [0, 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 80, 96, 128],\n};\n\n/**\n * Z-Index Scale\n * Exported for use in other tools that need verified design references\n */\nexport const Z_INDEX_TOKENS = {\n behind: -1,\n base: 0,\n raised: 1,\n dropdown: 100,\n sticky: 200,\n overlay: 300,\n modal: 400,\n popover: 500,\n toast: 600,\n tooltip: 700,\n max: 9999,\n};\n\n/**\n * Motion Tokens\n * Exported for use in other tools that need verified design references\n */\nexport const MOTION_DESIGN_TOKENS = {\n duration: {\n instant: 0,\n fast: 100,\n normal: 200,\n slow: 300,\n slower: 500,\n },\n easing: {\n standard: { css: 'cubic-bezier(0.4, 0, 0.2, 1)', gsap: 'power2.inOut' },\n enter: { css: 'cubic-bezier(0, 0, 0.2, 1)', gsap: 'power2.out' },\n exit: { css: 'cubic-bezier(0.4, 0, 1, 1)', gsap: 'power2.in' },\n spring: { gsap: 'elastic.out(1, 0.5)' },\n },\n};\n\n// ============================================================================\n// AI SLOP BLOCKERS — Critical Detection Rules\n// ============================================================================\n\n/**\n * Hard rules for blocking AI-generated design slop\n */\nconst AI_SLOP_BLOCKERS = {\n colors: {\n rejectPureSaturated: /^#(ff0000|00ff00|0000ff|ffff00|ff00ff|00ffff)$/i,\n rejectNeonGreen: /^#[0-4][eEfF][0-5][0-4][0-2][0-4]$/,\n rejectHotMagenta: /^#[fF][0-3][0-5][fF][0-3][fF]$/,\n maxSaturation: 80,\n minSurfaceLightnessDelta: 8,\n },\n typography: {\n rejectGenericStack: /^(-apple-system|BlinkMacSystemFont|\"Segoe UI\"|Roboto|sans-serif)$/,\n minDistinctWeights: 3,\n allowedSizes: [12, 14, 16, 18, 20, 24, 30, 36, 48, 60, 72],\n },\n spacing: {\n allowedValues: SPACING_TOKENS.allowedPx,\n rejectMagicNumbers: true,\n },\n accents: {\n maxAccentHues: 1,\n semanticExempt: ['success', 'warning', 'error', 'info'],\n },\n contrast: {\n textOnBackground: 4.5,\n largeTextOnBackground: 3.0,\n uiComponents: 3.0,\n },\n};\n\n// ============================================================================\n// OPENAI APPS SDK UI GUIDELINES — Verified Patterns\n// ============================================================================\n\n/**\n * OpenAI Apps SDK UI Guidelines\n * Exported for use in other tools that need verified design references\n */\nexport const OPENAI_UI_PRINCIPLES = {\n color: {\n systemColors: true,\n brandAccentsOnly: ['icons', 'logos', 'badges', 'primary-buttons'],\n noCustomGradients: true,\n noBackgroundColors: true,\n },\n typography: {\n inheritSystemFont: true,\n preferredSizes: ['body', 'body-small'],\n limitVariation: true,\n },\n spacing: {\n useSystemGrid: true,\n consistentPadding: true,\n noEdgeToEdgeText: true,\n },\n cards: {\n maxPrimaryActions: 2,\n noDeepNavigation: true,\n noNestedScrolling: true,\n autoFitContent: true,\n },\n carousels: {\n minItems: 3,\n maxItems: 8,\n maxMetadataLines: 3,\n singleCtaPerItem: true,\n },\n accessibility: {\n wcagLevel: 'AA',\n minContrastRatio: 4.5,\n requireAltText: true,\n supportTextResizing: true,\n },\n};\n\n// ============================================================================\n// AI SLOP COLORS — Legacy Detection Patterns\n// ============================================================================\n\n/**\n * AI Slop Colors — Common AI-generated color anti-patterns\n * These are the garish, oversaturated colors that scream \"AI made this\"\n */\nconst AI_SLOP_COLORS = [\n // Neon/toxic greens (AI loves these for \"success\")\n { pattern: /#[0-4][eEfF][0-5][0-4][0-2][0-4]/i, name: 'toxic neon green', suggestion: 'emerald-500 (#10b981) or green-600 (#16a34a)' },\n { pattern: /#00[fF][fF]00/i, name: 'pure lime green', suggestion: 'emerald-400 (#34d399) for a modern SaaS look' },\n { pattern: /#[0-3][fF][fF][0-3][fF][0-3]/i, name: 'cyan-green neon', suggestion: 'teal-500 (#14b8a6) for sophistication' },\n \n // Garish purples/magentas\n { pattern: /#[fF][0-3][0-5][fF][0-3][fF]/i, name: 'hot magenta', suggestion: 'fuchsia-500 (#d946ef) or violet-500 (#8b5cf6)' },\n { pattern: /#[8-9aA][0-3][0-3][fF][fF][fF]/i, name: 'electric purple', suggestion: 'indigo-500 (#6366f1) for a Stripe-like feel' },\n \n // Oversaturated blues\n { pattern: /#00[0-5][0-5][fF][fF]/i, name: 'electric blue', suggestion: 'blue-600 (#2563eb) or sky-500 (#0ea5e9)' },\n { pattern: /#0{4}[fF]{2}/i, name: 'pure blue', suggestion: 'blue-500 (#3b82f6) for modern SaaS' },\n \n // Harsh reds\n { pattern: /#[fF][fF]0{4}/i, name: 'pure red', suggestion: 'rose-500 (#f43f5e) or red-500 (#ef4444)' },\n { pattern: /#[fF][0-3][0-3][0-3][0-3][0-3]/i, name: 'harsh red', suggestion: 'rose-600 (#e11d48) for errors, or softer coral (#fb7185)' },\n \n // Dated yellows/oranges\n { pattern: /#[fF][fF][fF][fF]00/i, name: 'pure yellow', suggestion: 'amber-400 (#fbbf24) or yellow-500 (#eab308)' },\n { pattern: /#[fF][fF][aA-fF]000/i, name: 'orange-yellow', suggestion: 'amber-500 (#f59e0b) for warnings' },\n \n // Gray issues\n { pattern: /#[8-9][8-9][8-9][8-9][8-9][8-9]/i, name: 'flat mid-gray', suggestion: 'slate-400 (#94a3b8) or zinc-500 (#71717a) for depth' },\n { pattern: /#[cC][cC][cC][cC][cC][cC]/i, name: 'washed-out gray', suggestion: 'slate-300 (#cbd5e1) or neutral-300 (#d4d4d4)' },\n];\n\n/**\n * Modern SaaS Color Palettes — Inspired by top sites on saaslandingpage.com and Awwwards\n * These are the color schemes that define premium SaaS design in 2024-2025\n */\nconst MODERN_PALETTES = {\n // Dark mode palettes (most popular on Awwwards)\n vercel: {\n name: 'Vercel/Next.js',\n bg: '#000000',\n surface: '#111111',\n border: '#333333',\n text: '#ededed',\n muted: '#888888',\n accent: '#0070f3',\n },\n linear: {\n name: 'Linear',\n bg: '#000212',\n surface: '#0a0a1a',\n border: '#1a1a2e',\n text: '#f7f8f8',\n muted: '#8f9ba8',\n accent: '#5e6ad2',\n },\n stripe: {\n name: 'Stripe',\n bg: '#0a2540',\n surface: '#0d3358',\n border: '#1a4a70',\n text: '#ffffff',\n muted: '#adbdcc',\n accent: '#635bff',\n },\n \n // Light mode palettes\n notion: {\n name: 'Notion',\n bg: '#ffffff',\n surface: '#f7f6f3',\n border: '#e3e2de',\n text: '#37352f',\n muted: '#9b9a97',\n accent: '#2eaadc',\n },\n figma: {\n name: 'Figma',\n bg: '#ffffff',\n surface: '#f5f5f5',\n border: '#e5e5e5',\n text: '#1e1e1e',\n muted: '#8c8c8c',\n accent: '#0d99ff',\n },\n framer: {\n name: 'Framer',\n bg: '#ffffff',\n surface: '#fafafa',\n border: '#ebebeb',\n text: '#171717',\n muted: '#666666',\n accent: '#0055ff',\n },\n};\n\n/**\n * Motion Libraries & Creative Effects — Codrops/Awwwards-level\n * Suggests based on project context\n * Exported for use in other tools that need verified design references\n */\nexport const MOTION_LIBRARIES = {\n react: [\n { name: 'framer-motion', desc: 'Production-ready motion library for React', use: 'Complex animations, gestures, layout animations, shared element transitions' },\n { name: '@react-spring/web', desc: 'Spring-physics based animations', use: 'Natural-feeling animations, physics-based motion' },\n { name: '@formkit/auto-animate', desc: 'Zero-config animations', use: 'Quick wins: list reordering, enter/exit animations' },\n { name: 'motion', desc: 'Motion One for React', use: 'Lightweight, performant micro-interactions' },\n ],\n threejs: [\n { name: '@react-three/fiber', desc: 'React renderer for Three.js', use: '3D scenes, product showcases, immersive experiences' },\n { name: '@react-three/drei', desc: 'Useful helpers for R3F', use: 'Camera controls, loaders, abstractions' },\n { name: '@react-three/postprocessing', desc: 'Post-processing effects', use: 'Bloom, depth of field, glitch effects' },\n ],\n scroll: [\n { name: '@studio-freight/lenis', desc: 'Smooth scroll library', use: 'Butter-smooth scrolling, parallax foundations' },\n { name: 'locomotive-scroll', desc: 'Smooth scroll + parallax', use: 'Scroll-triggered animations, parallax sections' },\n { name: 'gsap/ScrollTrigger', desc: 'GSAP scroll animations', use: 'Scroll-linked animations, pinning, scrubbing' },\n ],\n gsap: [\n { name: 'gsap', desc: 'Professional animation library', use: 'Complex timelines, morphing, text animations' },\n { name: 'gsap/ScrollTrigger', desc: 'Scroll-based animations', use: 'Reveal on scroll, parallax, pinned sections' },\n { name: 'gsap/SplitText', desc: 'Text animation plugin', use: 'Character/word/line animations (Club GreenSock)' },\n { name: 'gsap/MorphSVGPlugin', desc: 'SVG morphing', use: 'Shape morphing, path animations (Club GreenSock)' },\n ],\n creative: [\n { name: 'splitting', desc: 'Text/element splitting', use: 'Character-by-character animations, free alternative to SplitText' },\n { name: 'rellax', desc: 'Lightweight parallax', use: 'Simple parallax effects without heavy libraries' },\n { name: 'atropos', desc: '3D parallax hover effects', use: 'Card tilt effects, depth on hover' },\n { name: 'typed.js', desc: 'Typing animations', use: 'Typewriter effects for hero sections' },\n ],\n};\n\n/**\n * Project context detection for appropriate effect recommendations\n */\nconst PROJECT_CONTEXTS = {\n marketing: {\n patterns: [/landing|hero|pricing|features|testimonial|cta|homepage/i, /marketing|campaign|launch/i],\n effects: ['3D product showcases', 'scroll-triggered reveals', 'parallax sections', 'text animations', 'gradient meshes'],\n },\n dashboard: {\n patterns: [/dashboard|admin|analytics|settings|sidebar|table|chart/i],\n effects: ['subtle micro-interactions', 'skeleton loaders', 'toast animations', 'chart transitions'],\n },\n ecommerce: {\n patterns: [/product|cart|checkout|shop|store|catalog/i],\n effects: ['image zoom', 'add-to-cart animations', 'filter transitions', 'product card hovers'],\n },\n portfolio: {\n patterns: [/portfolio|gallery|showcase|project|work|case-study/i],\n effects: ['image reveals', 'cursor effects', 'page transitions', 'scroll-linked galleries'],\n },\n};\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 * - Color systems (detecting AI slop, suggesting modern palettes)\n * - Motion libraries (Framer Motion, GSAP, Three.js, Lenis)\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 * \n * Inspiration sources:\n * - saaslandingpage.com (890+ landing page examples)\n * - awwwards.com (award-winning web design)\n * - codrops.com (creative frontend tutorials)\n * - Linear, Vercel, Stripe, Notion, Figma, Framer\n */\nexport class DesignEngineerAgent extends BaseAgent {\n name = 'design-engineer';\n description = 'Award-winning frontend craft: design systems, motion design, creative CSS, modern color palettes, Awwwards-level polish';\n version = '2.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 // Detect project context from all files\n const allContent = await this.getAllContent(files);\n const projectContext = this.detectProjectContext(allContent);\n const hasMotionLibrary = this.detectMotionLibraries(allContent);\n const designContext = this.detectDesignContext(allContent);\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 // Core design analysis\n issues.push(...this.analyzeColorPalette(content, file));\n issues.push(...this.analyzeMotionLibraries(content, file, hasMotionLibrary, projectContext));\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 // Enhanced AI slop detection (new)\n issues.push(...this.detectAISlopPatterns(content, file));\n issues.push(...this.analyzeTypographyPatterns(content, file));\n issues.push(...this.analyzeContrastRatios(content, file));\n issues.push(...this.analyzeSpacingGrid(content, file));\n }\n } catch (error) {\n console.error(`Design Engineer Agent: Error reading file ${file}:`, error);\n }\n }\n\n // Calculate design health score\n const healthScore = this.calculateDesignHealthScore(issues);\n \n // Add design health summary if there are significant issues\n if (healthScore.score < 80 || healthScore.slopScore < 70) {\n const domainRecommendation = this.getDomainRecommendations(designContext);\n issues.push(this.createIssue(\n this.generateIssueId(),\n healthScore.score < 50 ? 'serious' : 'moderate',\n `Design Health Score: ${healthScore.score}/100 | Slop Score: ${healthScore.slopScore}/100`,\n `Breakdown: Token adoption ${healthScore.breakdown.tokenAdoption}%, Contrast ${healthScore.breakdown.contrastCompliance}%, Spacing ${healthScore.breakdown.spacingConsistency}%, Typography ${healthScore.breakdown.typographySystem}%, Surface hierarchy ${healthScore.breakdown.surfaceHierarchy}%. ${domainRecommendation}`,\n files[0] || 'project',\n undefined,\n 0.95,\n undefined,\n false\n ));\n }\n\n return issues;\n }\n\n /**\n * Get all content from files for context detection\n */\n private async getAllContent(files: string[]): Promise<string> {\n const contents: string[] = [];\n for (const file of files.slice(0, 20)) { // Limit to first 20 files\n try {\n const content = await this.readFile(file);\n contents.push(content);\n } catch {\n // Skip files that can't be read\n }\n }\n return contents.join('\\n');\n }\n\n /**\n * Detect project context (marketing, dashboard, ecommerce, portfolio)\n */\n private detectProjectContext(content: string): string {\n for (const [context, config] of Object.entries(PROJECT_CONTEXTS)) {\n for (const pattern of config.patterns) {\n if (pattern.test(content)) {\n return context;\n }\n }\n }\n return 'general';\n }\n\n /**\n * Detect which motion libraries are already installed\n */\n private detectMotionLibraries(content: string): Set<string> {\n const detected = new Set<string>();\n \n if (/framer-motion|from ['\"]framer-motion['\"]/.test(content)) detected.add('framer-motion');\n if (/gsap|from ['\"]gsap['\"]/.test(content)) detected.add('gsap');\n if (/@react-three\\/fiber|from ['\"]@react-three\\/fiber['\"]/.test(content)) detected.add('three');\n if (/lenis|locomotive-scroll/.test(content)) detected.add('scroll');\n if (/react-spring|@react-spring/.test(content)) detected.add('react-spring');\n if (/auto-animate|@formkit\\/auto-animate/.test(content)) detected.add('auto-animate');\n \n return detected;\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 color palette for AI slop and suggest modern alternatives\n * Inspired by top SaaS sites: Linear, Vercel, Stripe, Notion, Figma, Framer\n */\n private analyzeColorPalette(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n // Track all colors found for overall palette analysis\n const colorsFound: { hex: string; line: number }[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const lineNumber = i + 1;\n\n // Extract hex colors\n const hexMatches = line.matchAll(/#[0-9a-fA-F]{3,8}\\b/g);\n for (const match of hexMatches) {\n const hex = match[0].toLowerCase();\n colorsFound.push({ hex, line: lineNumber });\n\n // Check against AI slop patterns\n for (const slop of AI_SLOP_COLORS) {\n if (slop.pattern.test(hex)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n `AI slop color detected: ${slop.name} (${hex})`,\n `Replace with modern SaaS palette: ${slop.suggestion}. See Linear, Vercel, Stripe for inspiration.`,\n file,\n lineNumber,\n 0.85,\n undefined,\n true\n ));\n break;\n }\n }\n\n // Check for fully saturated primary colors (pure RGB)\n if (/^#(ff0000|00ff00|0000ff|ffff00|ff00ff|00ffff)$/i.test(hex)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n `Pure saturated color ${hex} — looks amateur, not SaaS-ready`,\n 'Use desaturated alternatives. Modern SaaS uses muted, sophisticated colors. Try Tailwind\\'s color palette or Linear\\'s scheme.',\n file,\n lineNumber,\n 0.95,\n undefined,\n true\n ));\n }\n }\n\n // Check for dated gradient patterns\n if (/linear-gradient|radial-gradient/i.test(line)) {\n // Check for rainbow gradients (multiple saturated colors)\n const gradientColors = line.match(/#[0-9a-fA-F]{3,8}/g) || [];\n if (gradientColors.length >= 3) {\n const hasSaturated = gradientColors.some(c => \n /^#(ff|00)[0-9a-f]{4}$/i.test(c) || /^#[0-9a-f]{2}(ff|00)[0-9a-f]{2}$/i.test(c)\n );\n if (hasSaturated) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Multi-color gradient with saturated colors — can look dated or garish',\n 'Modern SaaS uses subtle gradients: 2 colors max, low saturation, or monochromatic. See Stripe\\'s gradient mesh.',\n file,\n lineNumber,\n 0.75,\n undefined,\n false\n ));\n }\n }\n }\n\n // Check for black text on white (suggest slightly off-white/black for sophistication)\n if (/#000000|#ffffff/i.test(line) && /color:|background:/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Pure black/white detected — consider off-black/off-white for sophistication',\n 'Modern SaaS uses near-black (#171717, #0a0a0a) and near-white (#fafafa, #f5f5f5). Pure #000/#fff can feel harsh.',\n file,\n lineNumber,\n 0.65,\n undefined,\n false\n ));\n }\n }\n\n // Analyze overall palette coherence\n if (colorsFound.length > 5) {\n const uniqueColors = new Set(colorsFound.map(c => c.hex));\n if (uniqueColors.size > 15) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n `${uniqueColors.size} unique colors detected — palette lacks cohesion`,\n `Modern SaaS uses 5-8 core colors max. Establish a design system with tokens: --color-primary, --color-surface, --color-text, --color-muted, --color-accent. Reference: ${this.getRandomPaletteRecommendation()}`,\n file,\n undefined,\n 0.80,\n undefined,\n false\n ));\n }\n\n // Detect over-reliance on violet/purple tones (common AI-slop overuse)\n let violetCount = 0;\n for (const { hex } of colorsFound) {\n const rgb = this.hexToRgb(hex);\n if (!rgb) continue;\n const hue = this.rgbToHue(rgb.r, rgb.g, rgb.b);\n if (hue >= 250 && hue <= 310) violetCount++;\n }\n if (violetCount >= 3 && violetCount / colorsFound.length > 0.35) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Palette leans heavily on violet/purple — looks templated/AI-generated',\n 'Use Josef Albers “Interaction of Color” approach: constrain to 1-2 hue families, anchor with neutrals, and build contrast via value/temperature shifts rather than piling on violet gradients.',\n file,\n undefined,\n 0.78,\n undefined,\n false\n ));\n }\n }\n\n return issues;\n }\n\n /**\n * Convert hex color to RGB\n */\n private hexToRgb(hex: string): { r: number; g: number; b: number } | null {\n const normalized = hex.replace('#', '');\n if (normalized.length === 3) {\n const r = parseInt(normalized.charAt(0) + normalized.charAt(0), 16);\n const g = parseInt(normalized.charAt(1) + normalized.charAt(1), 16);\n const b = parseInt(normalized.charAt(2) + normalized.charAt(2), 16);\n return { r, g, b };\n }\n if (normalized.length === 6) {\n const r = parseInt(normalized.slice(0, 2), 16);\n const g = parseInt(normalized.slice(2, 4), 16);\n const b = parseInt(normalized.slice(4, 6), 16);\n return { r, g, b };\n }\n return null;\n }\n\n /**\n * Calculate hue in degrees from RGB\n */\n private rgbToHue(r: number, g: number, b: number): number {\n const rNorm = r / 255;\n const gNorm = g / 255;\n const bNorm = b / 255;\n const max = Math.max(rNorm, gNorm, bNorm);\n const min = Math.min(rNorm, gNorm, bNorm);\n const delta = max - min;\n\n if (delta === 0) return 0;\n\n let hue: number;\n switch (max) {\n case rNorm:\n hue = ((gNorm - bNorm) / delta) % 6;\n break;\n case gNorm:\n hue = (bNorm - rNorm) / delta + 2;\n break;\n default:\n hue = (rNorm - gNorm) / delta + 4;\n break;\n }\n\n hue *= 60;\n if (hue < 0) hue += 360;\n return hue;\n }\n\n /**\n * Get a random modern palette recommendation\n */\n private getRandomPaletteRecommendation(): string {\n const palettes = Object.values(MODERN_PALETTES);\n const palette = palettes[Math.floor(Math.random() * palettes.length)]!;\n return `${palette.name} palette: bg ${palette.bg}, text ${palette.text}, accent ${palette.accent}`;\n }\n\n /**\n * Analyze motion library usage and suggest Awwwards-level effects\n */\n private analyzeMotionLibraries(content: string, file: string, hasLibraries: Set<string>, projectContext: string): Issue[] {\n const issues: Issue[] = [];\n const isReact = /from ['\"]react['\"]|import React/.test(content);\n const hasAnimations = /animation|transition|@keyframes|animate/i.test(content);\n const purposefulMotionSignals =\n hasAnimations ||\n /hero|landing|modal|dialog|drawer|toast|tooltip|hover|scroll|parallax|reveal|transition|carousel|slider|gallery/i.test(content);\n\n // Avoid pushing motion where it isn't needed; default to stillness unless the UI already implies motion affordances.\n if (!purposefulMotionSignals) {\n return issues;\n }\n \n // Check for CSS-only animations in React that could use Framer Motion\n if (isReact && !hasLibraries.has('framer-motion') && !hasLibraries.has('react-spring')) {\n // Detect complex animation patterns that would benefit from a motion library\n if (/useState.*animation|setAnimation|isAnimating|animationState/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Manual animation state management — use Framer Motion instead',\n `Install framer-motion for declarative animations: \\`npm i framer-motion\\`. Replace useState + CSS with <motion.div animate={{ ... }} />. See: https://www.framer.com/motion/`,\n file,\n undefined,\n 0.80,\n undefined,\n false\n ));\n }\n\n // Detect list animations that could use AnimatePresence\n if (/\\.map\\s*\\(.*\\).*\\.(filter|sort)|filter\\(.*\\)\\.map/.test(content) && hasAnimations) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'List filtering without exit animations — use AnimatePresence',\n 'Framer Motion\\'s AnimatePresence handles enter/exit animations for lists: <AnimatePresence>{items.map(...)}</AnimatePresence>',\n file,\n undefined,\n 0.70,\n undefined,\n false\n ));\n }\n\n // Detect layout shifts that could use layout animations\n if (/grid|flex.*gap|justify|align/i.test(content) && /setState|dispatch|set[A-Z]/.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Layout changes without animation — consider layout prop',\n 'Framer Motion\\'s layout prop auto-animates position/size changes: <motion.div layout>. Creates smooth reflow animations.',\n file,\n undefined,\n 0.60,\n undefined,\n false\n ));\n }\n }\n\n // Check for scroll-based content without scroll library\n if (!hasLibraries.has('scroll') && !hasLibraries.has('gsap')) {\n if (/scroll|parallax|reveal|fade.*in|slide.*in/i.test(content)) {\n const contextConfig = PROJECT_CONTEXTS[projectContext as keyof typeof PROJECT_CONTEXTS];\n const effects = contextConfig?.effects?.join(', ') || 'scroll-triggered animations';\n \n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Scroll-based effects without a scroll library',\n `For ${projectContext} sites, consider: Lenis for smooth scrolling (\\`npm i @studio-freight/lenis\\`), GSAP ScrollTrigger for ${effects}. See Codrops for inspiration.`,\n file,\n undefined,\n 0.65,\n undefined,\n false\n ));\n }\n }\n\n // Check for hero/landing sections that could use 3D\n if (projectContext === 'marketing' || projectContext === 'portfolio') {\n if (/hero|landing|showcase|featured/i.test(file) || /Hero|Landing|Showcase/.test(content)) {\n if (!hasLibraries.has('three')) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Hero section opportunity — consider 3D/WebGL elements',\n 'For Awwwards-level impact, add 3D with React Three Fiber: `npm i @react-three/fiber @react-three/drei`. Start with a simple floating object or gradient orb. See: https://codrops.com/tag/threejs/',\n file,\n undefined,\n 0.50,\n undefined,\n false\n ));\n }\n }\n }\n\n // Check for text that could have character animations\n if (/heading|title|h1|h2|hero.*text/i.test(content) && !hasLibraries.has('gsap')) {\n if (!/split|char|letter/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Headings without text animation — add character reveals',\n 'Use Splitting.js (free) or GSAP SplitText for character-by-character animations. Classic Awwwards effect: staggered character reveals on scroll.',\n file,\n undefined,\n 0.55,\n undefined,\n false\n ));\n }\n }\n\n // Suggest specific effects based on project context\n if (projectContext !== 'general' && !hasLibraries.has('framer-motion') && !hasLibraries.has('gsap')) {\n const contextConfig = PROJECT_CONTEXTS[projectContext as keyof typeof PROJECT_CONTEXTS];\n if (contextConfig) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n `${projectContext.charAt(0).toUpperCase() + projectContext.slice(1)} site detected — add motion polish`,\n `Recommended effects for ${projectContext}: ${contextConfig.effects.join(', ')}. Start with Framer Motion for React or GSAP for vanilla JS.`,\n file,\n undefined,\n 0.60,\n undefined,\n false\n ));\n }\n }\n\n return issues;\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 // ENHANCED AI SLOP DETECTION — Critical for Design Quality\n // ============================================================================\n\n /**\n * Detect and block AI slop patterns with enhanced rules\n * Returns issues with severity 'critical' for slop that MUST be fixed\n */\n private detectAISlopPatterns(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n\n // 1. Surface hierarchy check — dark-on-dark detection\n const bgColors = this.extractBackgroundColors(content);\n if (bgColors.length >= 2) {\n const lightnesses = bgColors.map(c => this.getLightness(c));\n const minDelta = this.getMinimumLightnessDelta(lightnesses);\n \n if (minDelta < AI_SLOP_BLOCKERS.colors.minSurfaceLightnessDelta) {\n const suggestedFix = this.suggestLighterSurface(bgColors[0]!, 10);\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'critical',\n `AI SLOP: Surfaces too similar (${minDelta.toFixed(1)}% lightness delta). Min 8% required.`,\n `Change surface color to create visible hierarchy. Suggestion: use ${suggestedFix} for elevated surfaces. Reference: zinc scale at tailwindcss.com/docs/customizing-colors`,\n file,\n undefined,\n 0.95,\n undefined,\n true\n ));\n }\n }\n\n // 2. Accent color count — detect rainbow slop\n const accentColors = this.extractAccentColors(content);\n const accentHues = this.getUniqueHueFamilies(accentColors);\n \n if (accentHues.length > AI_SLOP_BLOCKERS.accents.maxAccentHues + 1) { // Allow 2 for some flexibility\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n `AI SLOP: ${accentHues.length} accent color families detected. Use ONE primary accent.`,\n `Standardize on a single accent hue family. Semantic colors (success/warning/error) are exempt. Reference: radix-ui.com/colors for cohesive scales`,\n file,\n undefined,\n 0.90,\n undefined,\n true\n ));\n }\n\n // 3. Purple/violet overuse detection\n const allColors = this.extractAllColors(content);\n const purpleCount = allColors.filter(c => {\n const hue = this.getHueFromHex(c);\n return hue >= 250 && hue <= 310;\n }).length;\n \n if (allColors.length > 3 && purpleCount / allColors.length > 0.4) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'AI SLOP: Over-reliance on purple/violet (common AI tell)',\n 'Consider alternatives from radix-ui.com/colors — try orange, teal, or green scales for differentiation. Apply Josef Albers principle: constrain to 1-2 hue families.',\n file,\n undefined,\n 0.85,\n undefined,\n true\n ));\n }\n\n // 4. Neon color detection\n for (const color of allColors) {\n const saturation = this.getSaturation(color);\n const lightness = this.getLightness(color);\n \n if (saturation > AI_SLOP_BLOCKERS.colors.maxSaturation && lightness > 40 && lightness < 60) {\n const desaturated = this.desaturateColor(color, 60);\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n `AI SLOP: Neon color detected (${color}, ${saturation.toFixed(0)}% saturation)`,\n `Desaturate to ${desaturated}. Max recommended saturation: 75%. Source colors from radix-ui.com/colors for contrast-safe alternatives.`,\n file,\n undefined,\n 0.90,\n undefined,\n true\n ));\n }\n }\n\n return issues;\n }\n\n /**\n * Analyze typography patterns for AI slop\n */\n private analyzeTypographyPatterns(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n \n // 1. Font weight uniformity check\n const weights = this.extractFontWeights(content);\n const uniqueWeights = new Set(weights);\n \n if (uniqueWeights.size === 1 && weights.length > 3) {\n const singleWeight = [...uniqueWeights][0];\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n `AI SLOP: All text uses font-weight: ${singleWeight}. No visual hierarchy.`,\n 'Use weight hierarchy: 400 for body, 500 for labels/emphasis, 600 for headings, 700 for hero/strong emphasis.',\n file,\n undefined,\n 0.80,\n undefined,\n true\n ));\n }\n\n // 2. Missing modern font check\n const fontFamilies = this.extractFontFamilies(content);\n const hasModernFont = fontFamilies.some(f => \n /inter|geist|graphik|söhne|suisse|plus jakarta|dm sans|manrope/i.test(f)\n );\n \n if (!hasModernFont && fontFamilies.length > 0) {\n const isGenericOnly = fontFamilies.every(f =>\n /^(-apple-system|BlinkMacSystemFont|Segoe UI|Roboto|Helvetica Neue|Arial|sans-serif|system-ui)$/i.test(f.trim())\n );\n \n if (isGenericOnly) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'AI SLOP: No modern font specified (using only system fonts)',\n `Add a modern font: font-family: 'Inter', -apple-system, sans-serif. Get Inter from fonts.google.com or Geist from vercel.com/font`,\n file,\n undefined,\n 0.75,\n undefined,\n true\n ));\n }\n }\n\n // 3. Font size not on scale\n const fontSizes = content.match(/font-size:\\s*([\\d.]+)(px|rem)/gi) || [];\n for (const sizeMatch of fontSizes) {\n const match = sizeMatch.match(/font-size:\\s*([\\d.]+)(px|rem)/i);\n if (match) {\n const value = parseFloat(match[1]!);\n const unit = match[2]!;\n \n // Convert to px for comparison\n const pxValue = unit === 'rem' ? value * 16 : value;\n const allowedSizes = AI_SLOP_BLOCKERS.typography.allowedSizes;\n \n if (!allowedSizes.includes(Math.round(pxValue))) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n `Font size ${value}${unit} not on type scale`,\n `Use systematic type scale: ${allowedSizes.join(', ')}px. Or use clamp() for fluid typography.`,\n file,\n undefined,\n 0.65,\n undefined,\n false\n ));\n }\n }\n }\n\n return issues;\n }\n\n /**\n * Analyze contrast ratios between colors\n */\n private analyzeContrastRatios(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n // Look for text color + background color pairs\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const lineNumber = i + 1;\n\n // Check for low-contrast text on dark backgrounds\n if (/color:\\s*#[45678][0-9a-f]{5}/i.test(line)) {\n const context = lines.slice(Math.max(0, i - 5), i + 5).join('\\n');\n if (/background.*#[012][0-9a-f]{5}|bg-.*-9[05]0/i.test(context)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Low contrast text detected — may fail WCAG AA',\n `Text on dark backgrounds needs 4.5:1 contrast ratio. Use zinc-50 (#fafafa) for primary text, zinc-400 (#a1a1aa) for secondary. Validate at webaim.org/resources/contrastchecker`,\n file,\n lineNumber,\n 0.85,\n undefined,\n true\n ));\n }\n }\n\n // Check for text-secondary that's too dark on dark mode\n if (/--text-secondary|text-muted|text-tertiary/i.test(line)) {\n const colorMatch = line.match(/#[0-9a-f]{6}/i);\n if (colorMatch) {\n const lightness = this.getLightness(colorMatch[0]);\n if (lightness < 30) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Secondary text too dark for readability',\n 'Secondary text should be at least zinc-400 (#a1a1aa, ~40% lightness) on dark backgrounds. Consider zinc-500 (#71717a) minimum.',\n file,\n lineNumber,\n 0.80,\n undefined,\n false\n ));\n }\n }\n }\n }\n\n return issues;\n }\n\n /**\n * Analyze spacing for magic numbers\n */\n private analyzeSpacingGrid(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|inset/i.test(line)) {\n const pxMatches = line.matchAll(/:\\s*(\\d+)px/g);\n for (const match of pxMatches) {\n const value = parseInt(match[1]!);\n if (value > 2 && !SPACING_TOKENS.allowedPx.includes(value)) {\n const closestValue = SPACING_TOKENS.allowedPx.reduce((prev, curr) =>\n Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev\n );\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n `Magic number ${value}px — not on 4px spacing grid`,\n `Use ${closestValue}px instead, or design token --space-${closestValue / 4}. Allowed: ${SPACING_TOKENS.allowedPx.slice(0, 10).join(', ')}...`,\n file,\n lineNumber,\n 0.60,\n undefined,\n false\n ));\n }\n }\n }\n }\n\n return issues;\n }\n\n // ============================================================================\n // DESIGN HEALTH SCORING — Self-Critique System\n // ============================================================================\n\n /**\n * Calculate overall design health score\n */\n private calculateDesignHealthScore(issues: Issue[]): {\n score: number;\n slopScore: number;\n breakdown: {\n tokenAdoption: number;\n contrastCompliance: number;\n spacingConsistency: number;\n typographySystem: number;\n surfaceHierarchy: number;\n };\n } {\n const slopIssues = issues.filter(i => (i as any).isSlop);\n const criticalIssues = issues.filter(i => i.severity === 'critical');\n const seriousIssues = issues.filter(i => i.severity === 'serious');\n const moderateIssues = issues.filter(i => i.severity === 'moderate');\n\n // Calculate slop score (0 = pure slop, 100 = no slop detected)\n const slopScore = Math.max(0, 100 - (slopIssues.length * 15));\n\n // Calculate component scores\n const tokenIssues = issues.filter(i => /token|hardcoded|magic number/i.test(i.issue));\n const contrastIssues = issues.filter(i => /contrast|WCAG|readability/i.test(i.issue));\n const spacingIssues = issues.filter(i => /spacing|grid|magic number/i.test(i.issue));\n const typographyIssues = issues.filter(i => /font|typography|weight/i.test(i.issue));\n const surfaceIssues = issues.filter(i => /surface|hierarchy|dark-on-dark/i.test(i.issue));\n\n const tokenAdoption = Math.max(0, 100 - (tokenIssues.length * 10));\n const contrastCompliance = Math.max(0, 100 - (contrastIssues.length * 20));\n const spacingConsistency = Math.max(0, 100 - (spacingIssues.length * 8));\n const typographySystem = Math.max(0, 100 - (typographyIssues.length * 12));\n const surfaceHierarchy = Math.max(0, 100 - (surfaceIssues.length * 25));\n\n // Overall score weighted by severity\n const severityPenalty = (criticalIssues.length * 25) + \n (seriousIssues.length * 15) + \n (moderateIssues.length * 5);\n const score = Math.max(0, 100 - severityPenalty);\n\n return {\n score,\n slopScore,\n breakdown: {\n tokenAdoption,\n contrastCompliance,\n spacingConsistency,\n typographySystem,\n surfaceHierarchy,\n },\n };\n }\n\n // ============================================================================\n // COLOR UTILITY METHODS — Enhanced Analysis\n // ============================================================================\n\n /**\n * Extract all background colors from content\n */\n private extractBackgroundColors(content: string): string[] {\n const colors: string[] = [];\n const matches = content.matchAll(/background(?:-color)?:\\s*(#[0-9a-fA-F]{3,8})/gi);\n for (const match of matches) {\n colors.push(match[1]!.toLowerCase());\n }\n // Also check for CSS variables that look like backgrounds\n const varMatches = content.matchAll(/--(?:bg|background|surface|base)[^:]*:\\s*(#[0-9a-fA-F]{3,8})/gi);\n for (const match of varMatches) {\n colors.push(match[1]!.toLowerCase());\n }\n return colors;\n }\n\n /**\n * Extract accent/interactive colors\n */\n private extractAccentColors(content: string): string[] {\n const colors: string[] = [];\n const patterns = [\n /--(?:accent|primary|interactive|brand|cta)[^:]*:\\s*(#[0-9a-fA-F]{3,8})/gi,\n /(?:button|btn|link)[^{]*{\\s*[^}]*(?:background|color):\\s*(#[0-9a-fA-F]{3,8})/gi,\n ];\n for (const pattern of patterns) {\n const matches = content.matchAll(pattern);\n for (const match of matches) {\n colors.push(match[1]!.toLowerCase());\n }\n }\n return colors;\n }\n\n /**\n * Extract all hex colors from content\n */\n private extractAllColors(content: string): string[] {\n const colors: string[] = [];\n const matches = content.matchAll(/#[0-9a-fA-F]{3,8}\\b/g);\n for (const match of matches) {\n const hex = match[0].toLowerCase();\n // Normalize 3-char to 6-char\n if (hex.length === 4) {\n colors.push(`#${hex[1]}${hex[1]}${hex[2]}${hex[2]}${hex[3]}${hex[3]}`);\n } else if (hex.length === 7) {\n colors.push(hex);\n }\n }\n return [...new Set(colors)];\n }\n\n /**\n * Extract font weights from content\n */\n private extractFontWeights(content: string): number[] {\n const weights: number[] = [];\n const matches = content.matchAll(/font-weight:\\s*(\\d+)/g);\n for (const match of matches) {\n weights.push(parseInt(match[1]!));\n }\n return weights;\n }\n\n /**\n * Extract font families from content\n */\n private extractFontFamilies(content: string): string[] {\n const families: string[] = [];\n const matches = content.matchAll(/font-family:\\s*([^;]+)/gi);\n for (const match of matches) {\n const fontList = match[1]!.split(',').map(f => f.trim().replace(/['\"]/g, ''));\n families.push(...fontList);\n }\n return families;\n }\n\n /**\n * Get lightness value from hex color (0-100)\n */\n private getLightness(hex: string): number {\n const rgb = this.hexToRgb(hex);\n if (!rgb) return 0;\n \n const r = rgb.r / 255;\n const g = rgb.g / 255;\n const b = rgb.b / 255;\n \n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n \n return ((max + min) / 2) * 100;\n }\n\n /**\n * Get saturation value from hex color (0-100)\n */\n private getSaturation(hex: string): number {\n const rgb = this.hexToRgb(hex);\n if (!rgb) return 0;\n \n const r = rgb.r / 255;\n const g = rgb.g / 255;\n const b = rgb.b / 255;\n \n const max = Math.max(r, g, b);\n const min = Math.min(r, g, b);\n const l = (max + min) / 2;\n \n if (max === min) return 0;\n \n const d = max - min;\n return (l > 0.5 ? d / (2 - max - min) : d / (max + min)) * 100;\n }\n\n /**\n * Get hue from hex color\n */\n private getHueFromHex(hex: string): number {\n const rgb = this.hexToRgb(hex);\n if (!rgb) return 0;\n return this.rgbToHue(rgb.r, rgb.g, rgb.b);\n }\n\n /**\n * Get unique hue families from colors\n */\n private getUniqueHueFamilies(colors: string[]): string[] {\n const families = new Set<string>();\n \n for (const color of colors) {\n const hue = this.getHueFromHex(color);\n // Group into families (30-degree ranges)\n if (hue < 30 || hue >= 330) families.add('red');\n else if (hue < 60) families.add('orange');\n else if (hue < 90) families.add('yellow');\n else if (hue < 150) families.add('green');\n else if (hue < 210) families.add('cyan');\n else if (hue < 270) families.add('blue');\n else if (hue < 330) families.add('purple');\n }\n \n return [...families];\n }\n\n /**\n * Get minimum lightness delta between colors\n */\n private getMinimumLightnessDelta(lightnesses: number[]): number {\n if (lightnesses.length < 2) return 100;\n \n let minDelta = 100;\n for (let i = 0; i < lightnesses.length; i++) {\n for (let j = i + 1; j < lightnesses.length; j++) {\n const delta = Math.abs(lightnesses[i]! - lightnesses[j]!);\n if (delta < minDelta) minDelta = delta;\n }\n }\n \n return minDelta;\n }\n\n /**\n * Suggest a lighter surface color\n */\n private suggestLighterSurface(baseColor: string, deltaPercent: number): string {\n const rgb = this.hexToRgb(baseColor);\n if (!rgb) return '#1a1a1a'; // zinc-900 fallback\n \n // Increase lightness\n const increase = deltaPercent / 100 * 255;\n const newR = Math.min(255, Math.round(rgb.r + increase));\n const newG = Math.min(255, Math.round(rgb.g + increase));\n const newB = Math.min(255, Math.round(rgb.b + increase));\n \n return `#${newR.toString(16).padStart(2, '0')}${newG.toString(16).padStart(2, '0')}${newB.toString(16).padStart(2, '0')}`;\n }\n\n /**\n * Desaturate a color\n */\n private desaturateColor(hex: string, targetSaturation: number): string {\n const rgb = this.hexToRgb(hex);\n if (!rgb) return hex;\n \n // Convert to HSL, adjust saturation, convert back\n // Simplified: blend with gray\n const gray = (rgb.r + rgb.g + rgb.b) / 3;\n const factor = targetSaturation / 100;\n \n const newR = Math.round(gray + (rgb.r - gray) * factor);\n const newG = Math.round(gray + (rgb.g - gray) * factor);\n const newB = Math.round(gray + (rgb.b - gray) * factor);\n \n return `#${newR.toString(16).padStart(2, '0')}${newG.toString(16).padStart(2, '0')}${newB.toString(16).padStart(2, '0')}`;\n }\n\n /**\n * Detect design context from content\n */\n private detectDesignContext(content: string): DesignContext {\n let productType: ProductType = 'saas';\n let framework: DesignContext['framework'] = 'unknown';\n \n // Detect framework\n if (/from ['\"]react['\"]|import React/.test(content)) framework = 'react';\n else if (/from ['\"]vue['\"]|<template>/.test(content)) framework = 'vue';\n else if (/from ['\"]svelte['\"]|<script.*lang=[\"']ts[\"']/.test(content)) framework = 'svelte';\n \n // Detect product type\n if (/dashboard|admin|analytics/i.test(content)) productType = 'dashboard';\n else if (/checkout|cart|product|shop|store/i.test(content)) productType = 'ecommerce';\n else if (/hero|landing|pricing|testimonial|cta/i.test(content)) productType = 'marketing';\n else if (/portfolio|gallery|showcase|case-study/i.test(content)) productType = 'portfolio';\n else if (/fitness|workout|exercise|training/i.test(content)) productType = 'fitness';\n else if (/bank|finance|money|payment|transaction/i.test(content)) productType = 'fintech';\n else if (/canvas|editor|design|creative/i.test(content)) productType = 'creativeTools';\n \n // Detect existing design system\n const hasExistingDesignSystem = /--color-|--spacing-|--radius-|--font-|theme|tokens/i.test(content);\n \n return {\n productType,\n framework,\n hasExistingDesignSystem,\n };\n }\n\n /**\n * Get domain-specific recommendations\n */\n private getDomainRecommendations(context: DesignContext): string {\n const rules = DOMAIN_DESIGN_RULES[context.productType];\n if (!rules) return '';\n \n return `For ${context.productType}: Use ${rules.defaultMode} mode, accent colors from Radix (${rules.accentSuggestions.join('/')}), ${rules.motionLevel} motion. Reference: ${rules.reference.join(', ')}`;\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 (Linear, Vercel, Stripe caliber). You review and generate code for Awwwards-level polish and Codrops-worthy effects.\n\n## Design Intelligence Stack (5 Layers)\n\n### Layer 5: Emotional Design\n\"What feeling should this evoke?\"\n- Calm → muted colors, generous whitespace, slow transitions\n- Energetic → vibrant accents, dynamic motion, bold typography\n- Trustworthy → blues, clean lines, consistent patterns\n- Playful → rounded corners, illustrations, micro-interactions\n- Premium → desaturated, spacious, subtle motion\n\n### Layer 4: Domain Awareness\n\"What kind of product is this?\"\n- Fitness app → dark mode, energetic, progress-focused (Strava, Peloton)\n- Banking app → light mode, trustworthy, security-focused (Mercury, Ramp)\n- Creative tool → dark mode, minimal chrome, content-first (Figma, Linear)\n- E-commerce → light mode, scannable, conversion-optimized (Shopify, Glossier)\n- Dashboard → balanced density, clear data hierarchy (Vercel, Stripe)\n\n### Layer 3: Brand Intelligence\nExtract from existing code: logo colors, CSS variables, fonts, tone of voice\nExtend: generate complementary palette from Radix/Tailwind scales\nMaintain: track brand consistency across components\n\n### Layer 2: Semantic Understanding\n\"What is this component FOR?\"\n- Hero → command attention, single CTA, emotional hook\n- Pricing → scannable, comparison-friendly, reduce anxiety\n- Testimonials → build trust, social proof, authentic\n- Dashboard → information density, quick actions, status clarity\n\n### Layer 1: Token System\nFoundation layer — colors, typography, spacing, effects, motion\nReference external sources: radix-ui.com/colors, tailwindcss.com/docs\n\n## Guardrails: Design & Engineering Principles\n- Lead with user-centricity, clarity, and accessibility; animation is optional\n- KISS and DRY: reduce complexity, prefer design tokens and reusable patterns\n- Reliability and feedback: motion only when it improves understanding or state change\n- Efficiency and sustainability: bias to stillness, avoid unnecessary paints/GPU work\n- Ethics and integrity: honest communication about capabilities, avoid dark patterns\n- Honor prefers-reduced-motion always\n\n## CRITICAL: Generation Mode Constraints\n\nWhen generating UI, enforce these HARD RULES. Violations are unacceptable:\n\n### Color System (DERIVE, don't hardcode)\n\\`\\`\\`css\n/* Source: tailwindcss.com/docs/customizing-colors (zinc scale) */\n/* Or: radix-ui.com/colors (slate scale) */\n\n/* Dark Mode Foundation */\n--bg-base: var(--zinc-950); /* True background */\n--bg-surface: var(--zinc-900); /* Cards — MUST differ by ≥8% lightness */\n--bg-elevated: var(--zinc-800); /* Modals, dropdowns */\n--border-subtle: var(--zinc-800); /* Dividers */\n--border-default: var(--zinc-700); /* Input borders */\n--text-primary: var(--zinc-50); /* Main text — MUST pass WCAG AA (4.5:1) */\n--text-secondary: var(--zinc-400); /* Muted text */\n--text-tertiary: var(--zinc-500); /* Disabled/hint */\n\n/* ACCENT — Derive from brand or user context */\n/* Selection process:\n 1. Extract from logo/brand assets if available\n 2. Ask: \"What feeling? Energetic/Calm/Trustworthy/Bold\"\n 3. Map feeling → Radix scale (Orange, Teal, Blue, Crimson, etc.)\n 4. Validate contrast: webaim.org/resources/contrastchecker\n DO NOT hardcode hex values — derive from context */\n--accent-primary: var(--brand-derived);\n\n/* Semantic colors — use Radix scales */\n--success: var(--radix-green-9);\n--warning: var(--radix-amber-9);\n--error: var(--radix-red-9);\n\\`\\`\\`\n\n### Surface Hierarchy (CRITICAL — Squint Test)\nBackground (zinc-950) ← darkest\n ↓ +6-10% lightness\nSurface (zinc-900) ← cards, sidebars\n ↓ +6-10% lightness\nElevated (zinc-800) ← modals, dropdowns, hover states\n\n**Test:** Squint at the UI. If cards disappear into background, FAIL.\n\n### Typography System\n\\`\\`\\`css\n--font-sans: 'Inter', 'Geist Sans', -apple-system, sans-serif;\n--font-mono: 'JetBrains Mono', 'Fira Code', monospace;\n\n/* Type Scale */\n--text-xs: 0.75rem; /* 12px — captions */\n--text-sm: 0.875rem; /* 14px — secondary */\n--text-base: 1rem; /* 16px — body */\n--text-lg: 1.125rem; /* 18px — emphasized */\n--text-xl: 1.25rem; /* 20px — section headers */\n--text-2xl: 1.5rem; /* 24px — card titles */\n--text-3xl: 1.875rem; /* 30px — page headers */\n--text-4xl: 2.25rem; /* 36px — hero */\n\n/* Weights — Create hierarchy */\n--font-normal: 400; /* Body */\n--font-medium: 500; /* Labels */\n--font-semibold: 600; /* Headers */\n--font-bold: 700; /* Hero */\n\\`\\`\\`\n\n### Spacing Scale (4px grid only)\nAllowed: 0, 2, 4, 8, 12, 16, 20, 24, 32, 40, 48, 64, 80, 96px\nNO magic numbers (17px, 23px, 37px are REJECTED)\n\n### Accent Color Rules\n1. ONE primary accent — for interactive elements, focus states, CTAs\n2. Semantic colors are NOT decorative — green=success, amber=warning, red=error\n3. Never 3+ accent colors on same view — looks like a casino\n\n### Contrast Requirements (WCAG AA)\n| Element | Minimum Ratio |\n|---------|---------------|\n| Body text on surface | 4.5:1 |\n| Large text (18px+) | 3:1 |\n| UI components | 3:1 |\n\n## AI Slop Detection (BLOCK These Patterns)\n\n### Colors\n- ❌ NO pure saturated colors (#ff0000, #00ff00, #0000ff)\n- ❌ NO neon colors (saturation > 80%)\n- ❌ NO more than ONE accent color family per view\n- ❌ NO dark-on-dark where surfaces blend into background\n- ❌ NO purple/violet overuse (>40% of palette)\n\n### Typography\n- ❌ NO system fonts alone — specify Inter or Geist\n- ❌ NO single font-weight for entire UI — need hierarchy (400, 500, 600)\n\n### Spacing\n- ❌ NO magic numbers — use 4px grid only\n\n### Before Output Checklist\n1. [ ] Can I distinguish cards from background? (squint test)\n2. [ ] Is there only ONE accent color for interactivity?\n3. [ ] Does text have clear size/weight hierarchy?\n4. [ ] Are all spacing values on 4px grid?\n5. [ ] Is a modern font (Inter/Geist) specified?\n6. [ ] Does secondary text pass contrast check on surfaces?\n\nIf ANY check fails → FIX BEFORE OUTPUTTING\n\n## Animation & Visualization Knowledge\n\n### GSAP Best Practices\n- Use gsap.context() for React cleanup\n- Prefer timelines for sequenced animations\n- Respect prefers-reduced-motion\n- Animate transform/opacity only (not width/height/top/left)\n- Duration guidelines: micro (100-200ms), standard (300-500ms), emphasis (600-1000ms)\n- Easing: power2.out for entrances, power2.in for exits\n\n### Recharts/D3 Best Practices\n- Always use ResponsiveContainer with explicit height\n- Use design system colors, not hardcoded hex\n- Style axes with design tokens\n- Disable animations for reduced-motion preference\n\n### React Three Fiber Best Practices\n- Performance budget: <100k triangles mobile, <500k desktop\n- Use Suspense with fallback for loading\n- Support reduced-motion\n- Dispose resources on unmount\n- Cap devicePixelRatio at 2\n\n### Motion Tokens (Unified)\n\\`\\`\\`\nDuration:\n- instant: 100ms (micro-interactions)\n- fast: 200ms (hover, toggle)\n- normal: 300ms (standard transitions)\n- slow: 500ms (emphasis)\n- slower: 800ms (hero, dramatic)\n\nEasing:\n- Enter: ease-out / power2.out\n- Exit: ease-in / power2.in\n- Move: ease-in-out / power2.inOut\n\\`\\`\\`\n\n## OpenAI Apps SDK UI Guidelines\n- Max 2 primary actions per card\n- No nested scrolling — auto-fit content\n- 3-8 items per carousel, max 3 metadata lines\n- Single optional CTA per carousel item\n- WCAG AA contrast minimum\n- Support text resizing\n\n## Inspiration Sources\n- Radix Colors: radix-ui.com/colors (contrast-guaranteed scales)\n- Tailwind CSS: tailwindcss.com/docs (default palettes + spacing)\n- shadcn/ui: ui.shadcn.com (production-ready themes)\n- Codrops: tympanus.net/codrops/hub/ (creative patterns)\n- Awwwards: awwwards.com/directory/ (benchmarks: Linear, Vercel, Stripe)\n\nAnalyze issues and code for:\n1. **AI Slop Detection** — Surface hierarchy, accent count, neon colors, purple overuse\n2. **Color coherence** — Cohesive palette from verified sources\n3. **Typography system** — Modern fonts, weight hierarchy, scale adherence\n4. **Contrast compliance** — WCAG AA validation\n5. **Spacing consistency** — 4px grid enforcement\n6. **Motion quality** — Easing, duration, reduced-motion support\n7. **Design system** — Token adoption, component patterns\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\" | \"serious\" | \"moderate\" | \"low\",\n \"design_impact\": \"Why this hurts the user experience\",\n \"fix\": \"Specific fix with exact values from verified sources\"\n }],\n \"additional\": [{\n \"issue\": \"Design opportunity found\",\n \"file\": \"path\",\n \"line\": 123,\n \"severity\": \"low\",\n \"enhancement\": \"How to elevate to Awwwards quality\",\n \"fix\": \"Modern CSS/animation code with npm install if needed\"\n }],\n \"slop_indicators\": {\n \"surfaceContrast\": \"pass\" | \"fail\",\n \"accentCount\": 1,\n \"neonColors\": 0,\n \"purpleOveruse\": false,\n \"fontModernity\": \"modern\" | \"system-only\",\n \"weightVariation\": 3,\n \"spacingGrid\": \"on-grid\" | \"magic-numbers\"\n },\n \"design_health\": {\n \"score\": 85,\n \"slopScore\": 95,\n \"tokenAdoption\": 80,\n \"contrastCompliance\": 100,\n \"spacingConsistency\": 90,\n \"typographySystem\": 85,\n \"surfaceHierarchy\": 100\n },\n \"palette_recommendation\": {\n \"primary\": \"#hex\",\n \"secondary\": \"#hex\",\n \"background\": \"#hex\",\n \"surface\": \"#hex\",\n \"text\": \"#hex\",\n \"muted\": \"#hex\",\n \"accent\": \"#hex\",\n \"source\": \"Radix teal scale / Tailwind zinc\",\n \"feeling\": \"calm | energetic | trustworthy | bold | premium\"\n },\n \"domain_context\": {\n \"detected\": \"saas | ecommerce | dashboard | marketing | portfolio | fitness | fintech | creativeTools\",\n \"recommendations\": \"Domain-specific design guidance\"\n },\n \"motion_recommendations\": [{\n \"library\": \"framer-motion\",\n \"install\": \"npm i framer-motion\",\n \"use_case\": \"What specific effect to implement\",\n \"example_code\": \"Brief code snippet\"\n }],\n \"summary\": \"Overall design craft assessment with specific recommendations\"\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 = 'Comprehensive legal compliance for app development: licensing, ToS, accessibility, IP, data protection, e-commerce, and regulatory requirements';\n version = '2.0.0';\n\n shouldActivate(context: CodeContext): boolean {\n return (\n context.touchesUserData ||\n context.touchesPayments ||\n context.touchesAuth ||\n context.touchesUI ||\n context.touchesAPI ||\n context.touchesThirdPartyAPI ||\n context.touchesHealthData // HIPAA compliance\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 // License & Open Source Compliance\n issues.push(...this.checkLicenseCompliance(content, file));\n issues.push(...this.checkOpenSourceObligations(content, file));\n \n // Terms & Legal Documents\n issues.push(...this.checkTermsOfService(content, file));\n issues.push(...this.checkPrivacyPolicyRequirements(content, file));\n \n // Third-Party & API Compliance\n issues.push(...this.checkAPITermsCompliance(content, file));\n issues.push(...this.checkThirdPartyLicenses(content, file));\n \n // Intellectual Property\n issues.push(...this.checkCopyrightCompliance(content, file));\n issues.push(...this.checkTrademarkUsage(content, file));\n \n // Accessibility (ADA/Section 508)\n issues.push(...this.checkAccessibilityCompliance(content, file));\n \n // Data Protection (GDPR/CCPA - General)\n issues.push(...this.checkDataProtection(content, file));\n issues.push(...this.checkConsentManagement(content, file));\n issues.push(...this.checkDataRetention(content, file));\n \n // E-Commerce & Consumer Protection\n issues.push(...this.checkECommerceCompliance(content, file));\n issues.push(...this.checkPaymentCompliance(content, file));\n issues.push(...this.checkRefundPolicy(content, file));\n \n // Marketing & Advertising\n issues.push(...this.checkMarketingCompliance(content, file));\n issues.push(...this.checkFTCDisclosure(content, file));\n \n // Age Restrictions & Child Safety\n issues.push(...this.checkAgeRestrictions(content, file));\n \n // Export Controls & Encryption\n issues.push(...this.checkExportControls(content, file));\n \n // User-Generated Content & Moderation\n issues.push(...this.checkUGCCompliance(content, file));\n issues.push(...this.checkContentModeration(content, file));\n \n // Contract & Agreement Patterns\n issues.push(...this.checkContractPatterns(content, file));\n issues.push(...this.checkClickwrapCompliance(content, file));\n \n // Jurisdictional & International\n issues.push(...this.checkJurisdictionalCompliance(content, file));\n \n // Security & Liability\n issues.push(...this.checkSecurityDisclosure(content, file));\n issues.push(...this.checkLiabilityProtections(content, file));\n \n } catch (error) {\n console.error(`Legal Agent: Error reading file ${file}:`, error);\n }\n }\n\n return issues;\n }\n\n // ============================================================\n // LICENSE & OPEN SOURCE COMPLIANCE\n // ============================================================\n\n private checkLicenseCompliance(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n // Check for GPL code in non-GPL projects\n const gplIndicators = /gpl|gnu\\s+general\\s+public|copyleft/i;\n if (gplIndicators.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'GPL/Copyleft licensed code detected',\n 'GPL code requires your entire project to be GPL-licensed. Verify license compatibility or find alternative libraries.',\n file,\n undefined,\n 0.85,\n 'GPL License Compliance - Copyleft obligations may apply',\n false\n ));\n }\n\n // Check for AGPL which has network use requirements\n if (/agpl|affero/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'critical',\n 'AGPL licensed code detected - network use triggers obligations',\n 'AGPL requires source disclosure even for SaaS/network use. This has significant business implications.',\n file,\n undefined,\n 0.95,\n 'AGPL License - Network use copyleft provisions',\n false\n ));\n }\n\n // Check for missing license headers in source files\n const isSourceFile = /\\.(ts|js|tsx|jsx|py|java|go|rs|c|cpp|h)$/.test(file);\n if (isSourceFile && !/(license|copyright|©|\\(c\\)|spdx)/i.test(content.slice(0, 500))) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Missing license header in source file',\n 'Consider adding SPDX license identifier or copyright notice for clarity',\n file,\n 1,\n 0.50,\n 'Best Practice - License clarity in source files',\n false\n ));\n }\n\n // Check for license file existence patterns\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n if (/require\\(|import\\s+.*from|from\\s+['\"]/.test(line) && \n /node_modules|vendor|third.?party/i.test(line)) {\n // Suggest license audit for dependencies\n if (!this.hasSeenDependencyWarning) {\n this.hasSeenDependencyWarning = true;\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Third-party dependencies detected - license audit recommended',\n 'Run license audit tools (license-checker, pip-licenses) to verify all dependency licenses are compatible',\n file,\n i + 1,\n 0.70,\n 'Dependency License Compliance',\n false\n ));\n }\n }\n }\n\n return issues;\n }\n\n private hasSeenDependencyWarning = false;\n\n private checkOpenSourceObligations(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n\n // Check for attribution requirements\n const attributionRequired = /mit|bsd|apache|isc/i.test(content) && \n /license|copyright/i.test(content);\n if (attributionRequired && !/notice|attribution|credits/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Open source license requires attribution',\n 'MIT, BSD, Apache licenses require copyright notice preservation. Ensure NOTICE/CREDITS file exists.',\n file,\n undefined,\n 0.75,\n 'Open Source Attribution Requirements',\n false\n ));\n }\n\n // Check for Apache 2.0 patent grant considerations\n if (/apache.*2\\.0|apache-2\\.0/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Apache 2.0 includes patent grant provisions',\n 'Apache 2.0 includes express patent license from contributors. Understand implications for your project.',\n file,\n undefined,\n 0.55,\n 'Apache 2.0 Patent Grant',\n false\n ));\n }\n\n return issues;\n }\n\n // ============================================================\n // TERMS OF SERVICE & PRIVACY POLICY\n // ============================================================\n\n private checkTermsOfService(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n\n // Check if user signup/registration exists without ToS reference\n if (/signup|register|createAccount|onboard/i.test(content) &&\n !/terms|tos|termsOfService|agreement|policy/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'User registration without Terms of Service reference',\n 'Link to Terms of Service during registration. Users must agree before account creation.',\n file,\n undefined,\n 0.85,\n 'Contract Law - Terms of Service acceptance',\n false\n ));\n }\n\n // Check for ToS acceptance pattern\n if (/terms.*accept|agree.*terms|accept.*policy/i.test(content)) {\n // Good pattern - but verify it's not pre-checked\n if (/defaultChecked|checked.*true|value.*true/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Pre-checked Terms of Service acceptance',\n 'ToS acceptance should require affirmative action. Do not pre-check agreement boxes.',\n file,\n undefined,\n 0.90,\n 'Contract Law - Affirmative consent required',\n true\n ));\n }\n }\n\n return issues;\n }\n\n private checkPrivacyPolicyRequirements(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n\n // Check for data collection without privacy policy reference\n const collectsData = /email|phone|address|location|deviceId|fingerprint|analytics/i.test(content);\n const hasPrivacyRef = /privacy|privacyPolicy|dataPolicy/i.test(content);\n\n if (collectsData && !hasPrivacyRef) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Data collection without privacy policy reference',\n 'Any data collection requires accessible privacy policy disclosure. Link to privacy policy.',\n file,\n undefined,\n 0.85,\n 'Privacy Law - Disclosure requirements (GDPR, CCPA, CalOPPA)',\n false\n ));\n }\n\n // Check for California users (CalOPPA requirements)\n if (/california|\\.ca\\.|\\bca\\b/i.test(content) && collectsData) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'California users detected - CalOPPA compliance required',\n 'California Online Privacy Protection Act requires conspicuous privacy policy link',\n file,\n undefined,\n 0.70,\n 'CalOPPA Compliance',\n false\n ));\n }\n\n return issues;\n }\n\n // ============================================================\n // THIRD-PARTY & API COMPLIANCE\n // ============================================================\n\n private checkAPITermsCompliance(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n const apiPatterns: { pattern: RegExp; name: string; concern: string }[] = [\n { pattern: /api\\.openai\\.com|openai/i, name: 'OpenAI', concern: 'Usage policies prohibit certain content generation' },\n { pattern: /api\\.stripe\\.com|stripe/i, name: 'Stripe', concern: 'PCI compliance and prohibited business types' },\n { pattern: /graph\\.facebook\\.com|facebook/i, name: 'Meta/Facebook', concern: 'Platform policies and data usage restrictions' },\n { pattern: /api\\.twitter\\.com|twitter|x\\.com/i, name: 'Twitter/X', concern: 'API rate limits and content policies' },\n { pattern: /maps\\.google|googleapis\\.com\\/maps/i, name: 'Google Maps', concern: 'Display requirements and usage restrictions' },\n { pattern: /api\\.twilio\\.com|twilio/i, name: 'Twilio', concern: 'A2P messaging compliance and opt-out requirements' },\n { pattern: /api\\.sendgrid\\.com|sendgrid/i, name: 'SendGrid', concern: 'Anti-spam compliance required' },\n { pattern: /api\\.aws\\.amazon|amazonaws\\.com/i, name: 'AWS', concern: 'Acceptable Use Policy and export controls' },\n { pattern: /youtube|youtu\\.be/i, name: 'YouTube', concern: 'API Services Terms of Service, embedding restrictions' },\n ];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n for (const api of apiPatterns) {\n if (api.pattern.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n `${api.name} API usage detected - review terms`,\n `${api.concern}. Verify compliance with ${api.name} Terms of Service.`,\n file,\n i + 1,\n 0.70,\n `${api.name} API Terms of Service`,\n false\n ));\n break;\n }\n }\n }\n\n return issues;\n }\n\n private checkThirdPartyLicenses(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n\n // Check for bundled assets that may have license requirements\n if (/\\.(ttf|otf|woff|woff2)/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Font files detected - verify font licensing',\n 'Many fonts have commercial licensing requirements. Verify you have proper license for web/app use.',\n file,\n undefined,\n 0.75,\n 'Font Licensing - Commercial use restrictions',\n false\n ));\n }\n\n // Check for stock images/assets\n if (/unsplash|pexels|shutterstock|gettyimages|istock/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Stock asset service detected - verify attribution requirements',\n 'Check license terms for attribution requirements and usage restrictions',\n file,\n undefined,\n 0.60,\n 'Stock Asset Licensing',\n false\n ));\n }\n\n return issues;\n }\n\n // ============================================================\n // INTELLECTUAL PROPERTY\n // ============================================================\n\n private checkCopyrightCompliance(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\n // Check for copied code attribution\n if (/stackoverflow|copied from|adapted from|based on|from:?\\s*http/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Code attribution comment detected - verify license',\n 'Ensure copied code is properly licensed for your use. Stack Overflow code is CC BY-SA licensed.',\n file,\n i + 1,\n 0.60,\n 'Copyright - Code attribution and licensing',\n false\n ));\n }\n\n // Check for potential trademark issues in branding\n if (/logo|brand|trademark|®|™/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Trademark/branding reference detected',\n 'Verify trademark usage complies with brand guidelines and trademark law',\n file,\n i + 1,\n 0.50,\n 'Trademark Law Compliance',\n false\n ));\n }\n }\n\n return issues;\n }\n\n private checkTrademarkUsage(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n\n // Major platform trademarks that have specific usage requirements\n const trademarks = [\n { pattern: /\\bapple\\b|iphone|ipad|ios|app\\s*store/i, name: 'Apple', guide: 'Apple Trademark Guidelines' },\n { pattern: /\\bgoogle\\b|android|play\\s*store|chrome/i, name: 'Google', guide: 'Google Brand Guidelines' },\n { pattern: /\\bmicrosoft\\b|windows|azure/i, name: 'Microsoft', guide: 'Microsoft Trademark Guidelines' },\n { pattern: /\\bamazon\\b|aws|alexa/i, name: 'Amazon', guide: 'Amazon Trademark Guidelines' },\n ];\n\n for (const tm of trademarks) {\n if (tm.pattern.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n `${tm.name} trademark reference detected`,\n `If using ${tm.name} branding, review ${tm.guide} for proper usage`,\n file,\n undefined,\n 0.50,\n `${tm.name} Trademark Guidelines`,\n false\n ));\n break; // Only one trademark warning per file\n }\n }\n\n return issues;\n }\n\n // ============================================================\n // ACCESSIBILITY (ADA/SECTION 508)\n // ============================================================\n\n private checkAccessibilityCompliance(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n const lines = content.split('\\n');\n\n // Check for images without alt text\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n\n if (/<img/i.test(line) && !/alt\\s*=/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Image without alt text - accessibility violation',\n 'Add alt attribute to images for screen reader accessibility (ADA/WCAG 2.1)',\n file,\n i + 1,\n 0.80,\n 'ADA/WCAG 2.1 - Images require alternative text',\n true\n ));\n }\n\n // Check for click handlers on non-interactive elements\n if (/onClick|@click/i.test(line) && /<(div|span|p)\\s/i.test(line) && \n !/role=|tabIndex|tabindex/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Click handler on non-interactive element without keyboard support',\n 'Add role=\"button\" and tabIndex for keyboard accessibility',\n file,\n i + 1,\n 0.75,\n 'WCAG 2.1.1 - Keyboard accessible',\n true\n ));\n }\n\n // Check for color-only information\n if (/color.*:.*red|color.*:.*green/i.test(line) && /error|success|valid|invalid/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Color may be sole indicator of status',\n 'Do not use color alone to convey information. Add icons or text for colorblind users.',\n file,\n i + 1,\n 0.70,\n 'WCAG 1.4.1 - Use of Color',\n false\n ));\n }\n }\n\n // Check for video without captions reference\n if (/<video|video\\s*:/i.test(content) && !/caption|subtitle|track\\s+kind/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Video content without captions/subtitles',\n 'Provide captions for video content (ADA/WCAG 1.2.2)',\n file,\n undefined,\n 0.75,\n 'WCAG 1.2.2 - Captions (Prerecorded)',\n false\n ));\n }\n\n return issues;\n }\n\n // ============================================================\n // DATA PROTECTION (GDPR/CCPA - GENERAL)\n // ============================================================\n\n private checkDataProtection(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\n if (/email|phone|location|deviceId/i.test(line) && \n /save|store|insert|create|post/i.test(line) &&\n !/consent|optIn|agreement/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 personal data (GDPR Article 6, CCPA)',\n file,\n lineNumber,\n 0.80,\n 'GDPR Article 6 / CCPA - Lawful basis for processing',\n false\n ));\n }\n\n // Check for analytics without consent\n if (/analytics|gtag|fbq|pixel|tracking|mixpanel|amplitude|segment/i.test(line) && \n !/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 before loading tracking scripts (ePrivacy/GDPR)',\n file,\n lineNumber,\n 0.85,\n 'GDPR Article 7 / ePrivacy Directive',\n false\n ));\n }\n }\n\n // Check for data export capability (Right to portability)\n if (/userData|userProfile|account/i.test(content)) {\n if (!/export|download|portability/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Consider implementing data portability',\n 'Users have right to export their data in machine-readable format (GDPR Article 20)',\n file,\n undefined,\n 0.65,\n 'GDPR Article 20 - Right to data portability',\n false\n ));\n }\n }\n\n // Check for delete account functionality\n if (/deleteAccount|removeAccount|closeAccount/i.test(content)) {\n // Good pattern exists\n } else if (/account|user.*profile/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Account deletion functionality may be missing',\n 'Users have right to delete their accounts and data (GDPR Article 17)',\n file,\n undefined,\n 0.70,\n 'GDPR Article 17 - Right to erasure',\n false\n ));\n }\n\n return issues;\n }\n\n private checkConsentManagement(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/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Pre-checked consent detected',\n 'Consent must be freely given via affirmative action. Remove default checked state.',\n file,\n lineNumber,\n 0.90,\n 'GDPR Recital 32 - No pre-ticked consent boxes',\n true\n ));\n }\n\n // Check for bundled consent\n if (/&&.*consent.*&&|all.*agree|single.*checkbox/i.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Potentially bundled consent',\n 'Separate consents for different purposes (marketing vs. essential)',\n file,\n lineNumber,\n 0.70,\n 'GDPR - Granular consent requirements',\n false\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/i.test(content) &&\n !/delete|expire|retention|ttl|expiresAt|purge/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 automatic deletion procedures',\n file,\n undefined,\n 0.70,\n 'GDPR Article 5(1)(e) - Storage limitation principle',\n false\n ));\n }\n\n return issues;\n }\n\n // ============================================================\n // E-COMMERCE & CONSUMER PROTECTION\n // ============================================================\n\n private checkECommerceCompliance(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n\n // Check for price display requirements\n if (/price|cost|\\$|€|£/i.test(content) && /product|item|cart|checkout/i.test(content)) {\n if (!/tax|vat|total|shipping/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Price display may not include all costs',\n 'Display total price including taxes and fees before purchase (Consumer protection laws)',\n file,\n undefined,\n 0.75,\n 'FTC / EU Consumer Rights Directive - Price transparency',\n false\n ));\n }\n }\n\n // Check for clear purchase button labeling\n if (/checkout|purchase|buy|order/i.test(content)) {\n if (!/confirm|review|final/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Consider clear purchase confirmation step',\n 'Provide order review before final purchase to prevent accidental orders',\n file,\n undefined,\n 0.60,\n 'Consumer Protection - Clear purchase flow',\n false\n ));\n }\n }\n\n return issues;\n }\n\n private checkPaymentCompliance(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\n // Check for direct card handling (should use tokenization)\n if (/cardNumber|cvv|cvc|credit.*card|card.*number/i.test(line) &&\n !/stripe|braintree|square|paypal|token/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'critical',\n 'Direct payment card handling detected',\n 'Use PCI-compliant payment processor (Stripe, Braintree, etc.) for card handling. Never store raw card data.',\n file,\n i + 1,\n 0.95,\n 'PCI DSS Compliance - Use tokenization',\n true\n ));\n }\n\n // Check for subscription handling\n if (/subscription|recurring|autoRenew/i.test(line)) {\n if (!/cancel|unsubscribe|manage/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Subscription without clear cancellation method',\n 'FTC requires clear and simple cancellation process for subscriptions',\n file,\n i + 1,\n 0.80,\n 'FTC - Click-to-Cancel Rule / Restore Online Shoppers Confidence Act',\n false\n ));\n }\n }\n }\n\n return issues;\n }\n\n private checkRefundPolicy(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n\n if (/purchase|payment|checkout|order/i.test(content)) {\n if (!/refund|return|cancellation|moneyBack/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'No refund/return policy reference found',\n 'Link to refund policy during checkout (required in EU, recommended globally)',\n file,\n undefined,\n 0.70,\n 'EU Consumer Rights Directive - Return policy disclosure',\n false\n ));\n }\n }\n\n return issues;\n }\n\n // ============================================================\n // MARKETING & ADVERTISING COMPLIANCE\n // ============================================================\n\n private checkMarketingCompliance(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\n // Check for email marketing without opt-out\n if (/sendEmail|mailchimp|sendgrid|newsletter|marketing.*email/i.test(line)) {\n if (!/unsubscribe|optOut|preferences/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Marketing email without unsubscribe mechanism',\n 'CAN-SPAM requires clear opt-out in every marketing email',\n file,\n i + 1,\n 0.85,\n 'CAN-SPAM Act - Unsubscribe requirements',\n false\n ));\n }\n }\n\n // Check for SMS marketing\n if (/sms|textMessage|twilio.*sms/i.test(line) && /marketing|promo|offer/i.test(content)) {\n if (!/consent|optIn|tcpa/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'critical',\n 'SMS marketing requires express written consent',\n 'TCPA requires prior express written consent for marketing SMS. Violations up to $1,500 per text.',\n file,\n i + 1,\n 0.95,\n 'TCPA - Telephone Consumer Protection Act',\n false\n ));\n }\n }\n }\n\n return issues;\n }\n\n private checkFTCDisclosure(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n\n // Check for affiliate/sponsored content\n if (/affiliate|referral|sponsored|partner.*link|commission/i.test(content)) {\n if (!/disclosure|ad|sponsored|affiliate.*disclosure/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Affiliate/sponsored content without disclosure',\n 'FTC requires clear disclosure of material connections (affiliate links, sponsorships)',\n file,\n undefined,\n 0.85,\n 'FTC Endorsement Guidelines - Material connection disclosure',\n false\n ));\n }\n }\n\n // Check for testimonials/reviews\n if (/testimonial|review|rating|feedback/i.test(content)) {\n if (/fake|generated|synthetic|ai.*review/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'critical',\n 'Fake reviews/testimonials detected',\n 'FTC prohibits fake reviews. Ensure all testimonials are genuine and typical.',\n file,\n undefined,\n 0.95,\n 'FTC Act - Deceptive advertising prohibition',\n true\n ));\n }\n }\n\n return issues;\n }\n\n // ============================================================\n // AGE RESTRICTIONS & CHILD SAFETY\n // ============================================================\n\n private checkAgeRestrictions(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\n // Check for child-directed content without COPPA compliance\n if (/kids|children|child|minor|under.*13|age.*13/i.test(line)) {\n if (!/coppa|parentalConsent|verifiableConsent/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'critical',\n 'Child-directed content without COPPA compliance',\n 'COPPA requires verifiable parental consent before collecting data from children under 13',\n file,\n i + 1,\n 0.95,\n 'COPPA - Children\\'s Online Privacy Protection Act',\n false\n ));\n }\n }\n\n // Check for age verification\n if (/alcohol|gambling|cannabis|adult|18\\+|21\\+/i.test(line)) {\n if (!/ageVerification|verifyAge|dateOfBirth|ageGate/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious',\n 'Age-restricted content without age verification',\n 'Implement age verification for alcohol, gambling, or adult content',\n file,\n i + 1,\n 0.85,\n 'Age-restricted content regulations',\n false\n ));\n }\n }\n }\n\n return issues;\n }\n\n // ============================================================\n // EXPORT CONTROLS & ENCRYPTION\n // ============================================================\n\n private checkExportControls(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n\n // Check for strong encryption that may have export restrictions\n if (/aes-256|rsa|elliptic.*curve|ed25519|crypto\\.subtle/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Strong encryption detected - be aware of export controls',\n 'Encryption software may have export control requirements (EAR/ITAR). Review if shipping internationally.',\n file,\n undefined,\n 0.50,\n 'Export Administration Regulations (EAR) - Encryption controls',\n false\n ));\n }\n\n // Check for sanctioned country handling\n if (/country|region|locale/i.test(content) && /block|restrict|prohibit/i.test(content)) {\n if (!/ofac|sanction|embargo/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Consider OFAC sanctions compliance',\n 'If operating internationally, implement OFAC sanctions screening',\n file,\n undefined,\n 0.65,\n 'OFAC - Sanctions compliance',\n false\n ));\n }\n }\n\n return issues;\n }\n\n // ============================================================\n // USER-GENERATED CONTENT & MODERATION\n // ============================================================\n\n private checkUGCCompliance(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n\n // Check for user content without moderation\n if (/userContent|userPost|comment|review|upload/i.test(content)) {\n if (!/moderate|report|flag|review.*queue/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'User-generated content without moderation system',\n 'Implement content moderation to prevent liability for user content',\n file,\n undefined,\n 0.70,\n 'Section 230 / Platform liability',\n false\n ));\n }\n }\n\n // Check for DMCA compliance\n if (/upload|file.*share|media.*upload/i.test(content)) {\n if (!/dmca|takedown|copyright.*notice/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'File uploads without DMCA takedown process',\n 'Implement DMCA takedown procedures to maintain safe harbor protection',\n file,\n undefined,\n 0.75,\n 'DMCA Safe Harbor Requirements',\n false\n ));\n }\n }\n\n return issues;\n }\n\n private checkContentModeration(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n\n // Check for hate speech / illegal content detection\n if (/chat|message|post|comment/i.test(content) && /public|share|publish/i.test(content)) {\n if (!/filter|moderate|block|detect/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Public content without content filtering',\n 'Consider content filtering for CSAM, hate speech, and illegal content',\n file,\n undefined,\n 0.70,\n 'Platform Safety - Content moderation best practices',\n false\n ));\n }\n }\n\n return issues;\n }\n\n // ============================================================\n // CONTRACT & AGREEMENT PATTERNS\n // ============================================================\n\n private checkContractPatterns(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n\n // Check for clickwrap without scroll requirement\n if (/terms|eula|license.*agreement/i.test(content) && /accept|agree/i.test(content)) {\n if (!/scroll|read|acknowledge/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Agreement acceptance without scroll/read verification',\n 'Consider requiring users scroll through terms for stronger enforceability',\n file,\n undefined,\n 0.55,\n 'Contract Law - Browse-wrap vs click-wrap enforceability',\n false\n ));\n }\n }\n\n // Check for arbitration clauses\n if (/arbitration|dispute.*resolution/i.test(content)) {\n if (!/opt.*out|waiver|class.*action/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Arbitration clause without opt-out provision',\n 'Consider arbitration opt-out period for consumer contracts',\n file,\n undefined,\n 0.50,\n 'Arbitration - Consumer protection considerations',\n false\n ));\n }\n }\n\n return issues;\n }\n\n private checkClickwrapCompliance(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n\n // Check for proper agreement recording\n if (/accept.*terms|agree.*terms/i.test(content)) {\n if (!/timestamp|recordConsent|auditLog|agreement.*record/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Terms acceptance without consent recording',\n 'Record timestamp and version of terms accepted for legal enforceability',\n file,\n undefined,\n 0.70,\n 'Contract Law - Evidence of acceptance',\n false\n ));\n }\n }\n\n return issues;\n }\n\n // ============================================================\n // JURISDICTIONAL & INTERNATIONAL COMPLIANCE\n // ============================================================\n\n private checkJurisdictionalCompliance(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n\n // Check for EU-specific requirements\n if (/europe|eu|gdpr|\\.eu\\b|germany|france|spain/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'EU market detected - ensure GDPR compliance',\n 'EU users require GDPR-compliant data handling, cookie consent, and DPO if processing at scale',\n file,\n undefined,\n 0.75,\n 'GDPR - EU data protection requirements',\n false\n ));\n }\n\n // Check for cross-border data transfer\n if (/transfer|export|crossBorder/i.test(content) && /data|user|personal/i.test(content)) {\n if (!/sccs|adequacy|binding.*corporate/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Cross-border data transfer without legal basis',\n 'International data transfers require SCCs, adequacy decisions, or other legal mechanisms',\n file,\n undefined,\n 0.70,\n 'GDPR Chapter V - International data transfers',\n false\n ));\n }\n }\n\n // Check for Brazil (LGPD)\n if (/brazil|brasil|\\.br\\b|lgpd/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Brazil market detected - ensure LGPD compliance',\n 'LGPD (Lei Geral de Proteção de Dados) applies to Brazilian user data',\n file,\n undefined,\n 0.70,\n 'LGPD - Brazil data protection law',\n false\n ));\n }\n\n return issues;\n }\n\n // ============================================================\n // SECURITY DISCLOSURE & LIABILITY\n // ============================================================\n\n private checkSecurityDisclosure(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n\n // Check for security.txt or vulnerability disclosure\n if (/security|vulnerability|disclosure/i.test(file)) {\n // Good - has security considerations\n } else if (/contact|report|bug/i.test(content)) {\n if (!/security|vulnerability/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Consider adding security vulnerability disclosure process',\n 'Add security.txt or responsible disclosure policy for security researchers',\n file,\n undefined,\n 0.50,\n 'Security Best Practice - Vulnerability disclosure',\n false\n ));\n }\n }\n\n return issues;\n }\n\n private checkLiabilityProtections(content: string, file: string): Issue[] {\n const issues: Issue[] = [];\n\n // Check for warranty disclaimers in appropriate places\n if (/license|readme|terms/i.test(file.toLowerCase())) {\n if (!/warranty|as.?is|without.*guarantee|liability/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Consider adding warranty disclaimer',\n 'Add appropriate warranty disclaimers and limitation of liability clauses',\n file,\n undefined,\n 0.50,\n 'Warranty - Software liability protection',\n false\n ));\n }\n }\n\n // Check for indemnification in user-facing content\n if (/userContent|thirdParty.*content/i.test(content)) {\n if (!/indemnify|hold.*harmless/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Consider indemnification clause for user content',\n 'Add indemnification provisions for user-generated content in Terms of Service',\n file,\n undefined,\n 0.50,\n 'Indemnification - User content liability',\n false\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';\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 // Super Reviewer is explicitly invoked via trie_super_reviewer, not auto-triaged.\n // It's an interactive PR review tool, not meant for automated scans.\n return false;\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","import { BaseAgent, FileRelevance } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext, AgentPriority } from '../types/index.js';\n\n/**\n * ASCII Art Banner for Moneybags Agent\n */\nconst MONEYBAGS_ASCII = `\n ███╗ ███╗ ██████╗ ███╗ ██╗███████╗██╗ ██╗\n ████╗ ████║██╔═══██╗████╗ ██║██╔════╝╚██╗ ██╔╝\n ██╔████╔██║██║ ██║██╔██╗ ██║█████╗ ╚████╔╝ \n ██║╚██╔╝██║██║ ██║██║╚██╗██║██╔══╝ ╚██╔╝ \n ██║ ╚═╝ ██║╚██████╔╝██║ ╚████║███████╗ ██║ \n ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝╚══════╝ ╚═╝ \n \n ██████╗ █████╗ ██████╗ ███████╗\n ██╔══██╗██╔══██╗██╔════╝ ██╔════╝\n ██████╔╝███████║██║ ███╗███████╗\n ██╔══██╗██╔══██║██║ ██║╚════██║\n ██████╔╝██║ ██║╚██████╔╝███████║\n ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚══════╝\n`;\n\nconst MONEYBAGS_QUOTES = [\n 'Every bug has a price tag. I\\'m here to show you the receipt.',\n 'That temporary fix will cost you $50k when it hits production.',\n 'A penny saved in development is $30 saved in production.',\n 'Floating-point for money? That\\'s going to be an expensive lesson.',\n];\n\n/**\n * Cost estimation research sources:\n * - IBM Systems Sciences Institute: 30x cost multiplier for production bugs vs development\n * - NIST: ~$15k average to fix production bug vs $500 in development\n * - Ponemon Institute 2023: $4.45M average data breach cost\n * - Gartner: $5,600/minute average downtime cost\n * - OWASP: Security vulnerabilities cost 10-100x more than regular bugs\n */\n\n/**\n * Base costs by severity (in USD) - conservative estimates for finding bugs pre-production\n * These represent the cost if fixed NOW during development\n */\nconst BASE_COST_BY_SEVERITY = {\n critical: 5000, // Critical bugs found in dev - still expensive to fix properly\n serious: 2000, // Serious issues need careful remediation\n moderate: 500, // Moderate issues are quicker fixes\n low: 100, // Low severity - mostly cleanup\n};\n\n/**\n * Production multipliers - how much more it costs if this reaches production\n * Based on IBM Systems Sciences Institute research\n */\nconst PRODUCTION_MULTIPLIER = {\n critical: 30, // Critical bugs can cause outages, breaches\n serious: 20, // Serious bugs cause significant user impact\n moderate: 10, // Moderate bugs require hotfixes, user support\n low: 5, // Low bugs accumulate tech debt\n};\n\n/**\n * Category-specific cost multipliers based on industry data\n */\nconst CATEGORY_MULTIPLIERS: Record<string, { multiplier: number; reason: string }> = {\n // Security categories - based on breach cost data\n 'security': { multiplier: 8, reason: 'Security vulnerabilities can lead to data breaches (avg $4.45M)' },\n 'authentication': { multiplier: 10, reason: 'Auth bypass leads to complete system compromise' },\n 'authorization': { multiplier: 8, reason: 'Authorization flaws expose sensitive data' },\n 'injection': { multiplier: 12, reason: 'SQL/Command injection enables full system takeover' },\n 'xss': { multiplier: 5, reason: 'XSS enables session hijacking and data theft' },\n 'secrets': { multiplier: 15, reason: 'Exposed secrets require immediate rotation and audit' },\n 'cryptography': { multiplier: 6, reason: 'Weak crypto undermines entire security model' },\n \n // Data integrity categories\n 'data-loss': { multiplier: 20, reason: 'Data loss can be irrecoverable and legally actionable' },\n 'data-corruption': { multiplier: 15, reason: 'Data corruption requires manual recovery and validation' },\n 'privacy': { multiplier: 10, reason: 'Privacy violations carry regulatory fines (GDPR: 4% revenue)' },\n \n // Financial categories\n 'payment': { multiplier: 25, reason: 'Payment bugs can cause direct financial loss or fraud' },\n 'billing': { multiplier: 20, reason: 'Billing errors require refunds and erode trust' },\n 'financial-calculation': { multiplier: 15, reason: 'Incorrect calculations compound over time' },\n \n // Reliability categories\n 'crash': { multiplier: 8, reason: 'Crashes cause downtime (avg $5,600/minute)' },\n 'memory-leak': { multiplier: 5, reason: 'Memory leaks cause gradual degradation and outages' },\n 'deadlock': { multiplier: 10, reason: 'Deadlocks require restarts and cause data inconsistency' },\n 'race-condition': { multiplier: 8, reason: 'Race conditions cause intermittent, hard-to-debug failures' },\n \n // User experience\n 'accessibility': { multiplier: 3, reason: 'Accessibility issues can lead to lawsuits (ADA compliance)' },\n 'performance': { multiplier: 2, reason: 'Performance issues hurt conversion rates (~7% per 1s delay)' },\n 'ux': { multiplier: 1.5, reason: 'UX bugs increase support costs and churn' },\n \n // Code quality\n 'bug': { multiplier: 2, reason: 'General bugs require developer time and QA cycles' },\n 'type-error': { multiplier: 1.5, reason: 'Type errors caught early save debugging time' },\n 'logic-error': { multiplier: 3, reason: 'Logic errors produce incorrect business outcomes' },\n \n // Default\n 'default': { multiplier: 2, reason: 'General code issues' },\n};\n\n/**\n * Context multipliers based on what the code touches\n */\nconst CONTEXT_MULTIPLIERS: Record<string, { multiplier: number; description: string }> = {\n touchesPayments: { multiplier: 5, description: 'Payment processing code' },\n touchesAuth: { multiplier: 4, description: 'Authentication/authorization code' },\n touchesUserData: { multiplier: 3, description: 'User PII handling' },\n touchesHealthData: { multiplier: 6, description: 'Health data (HIPAA liability)' },\n touchesDatabase: { multiplier: 2.5, description: 'Database operations' },\n touchesAPI: { multiplier: 2, description: 'External API integrations' },\n touchesCrypto: { multiplier: 3, description: 'Cryptographic operations' },\n touchesFileSystem: { multiplier: 2, description: 'File system operations' },\n};\n\n/**\n * Effort to cost mapping - how long the fix takes\n */\nconst EFFORT_HOURS: Record<string, number> = {\n trivial: 0.5,\n easy: 2,\n medium: 8,\n hard: 24,\n};\n\nconst DEVELOPER_HOURLY_RATE = 150; // Blended rate including benefits, overhead\n\n/**\n * Default user count for scaling estimates\n * Users can configure this via --users flag\n */\nconst DEFAULT_USER_COUNT = 250;\n\n/**\n * User count scaling tiers\n * Costs scale based on blast radius - more users = higher impact\n * Baseline is 250 users (typical early-stage app)\n */\nconst USER_COUNT_MULTIPLIERS = [\n { threshold: 0, multiplier: 0.1, label: 'Pre-launch (0 users)' },\n { threshold: 50, multiplier: 0.3, label: 'MVP (50 users)' },\n { threshold: 250, multiplier: 1.0, label: 'Early stage (250 users)' }, // Baseline (default)\n { threshold: 1000, multiplier: 2.0, label: 'Growing (1K users)' },\n { threshold: 5000, multiplier: 4.0, label: 'Traction (5K users)' },\n { threshold: 25000, multiplier: 8.0, label: 'Scale-up (25K users)' },\n { threshold: 100000, multiplier: 15, label: 'Growth (100K users)' },\n { threshold: 500000, multiplier: 25, label: 'Large (500K users)' },\n { threshold: 1000000, multiplier: 40, label: 'Enterprise (1M+ users)' },\n];\n\n/**\n * Per-user costs for certain categories (in cents)\n * These scale directly with user count\n */\nconst PER_USER_COSTS = {\n 'data-loss': 5.00, // $5 per affected user (notification, support)\n 'privacy': 3.50, // $3.50 per user (GDPR: can be much higher)\n 'payment': 0.50, // $0.50 per transaction affected\n 'billing': 0.25, // $0.25 per billing record affected\n 'security': 2.00, // $2 per potentially affected user\n 'accessibility': 0.10, // $0.10 per user (support costs)\n};\n\n/**\n * Moneybags configuration options\n */\nexport interface MoneybagConfig {\n /** Number of users/customers in your app (default: 1000) */\n userCount?: number;\n /** Developer hourly rate for fix cost calculation (default: $150) */\n developerRate?: number;\n /** Industry for specialized multipliers */\n industry?: 'startup' | 'fintech' | 'healthcare' | 'enterprise' | 'saas' | 'ecommerce';\n}\n\n/**\n * Cost estimation result with detailed breakdown\n */\nexport interface CostEstimate {\n /** Base cost for this severity */\n baseCost: number;\n /** Cost if this bug reaches production */\n productionCost: number;\n /** Category multiplier applied */\n categoryMultiplier: number;\n /** Category reason */\n categoryReason: string;\n /** Context multiplier (based on what code touches) */\n contextMultiplier: number;\n /** Context factors that increased the cost */\n contextFactors: string[];\n /** User scale multiplier applied */\n userScaleMultiplier: number;\n /** User scale label */\n userScaleLabel: string;\n /** User count used for estimate */\n userCount: number;\n /** Per-user cost component (if applicable) */\n perUserCost: number;\n /** Developer time cost to fix */\n fixCost: number;\n /** Final estimated cost if caught now */\n totalNowCost: number;\n /** Final estimated cost if it reaches production */\n totalProductionCost: number;\n /** Savings by fixing now vs production */\n savings: number;\n /** Human-readable summary */\n summary: string;\n}\n\n/**\n * Extended issue with cost data\n */\nexport interface CostAwareIssue extends Issue {\n costEstimate?: CostEstimate;\n}\n\nexport class MoneybagAgent extends BaseAgent {\n name = 'moneybags';\n description = 'Estimates the dollar cost of bugs based on severity, category, and user scale. Uses industry research (IBM, NIST, Ponemon) with configurable user count scaling.';\n version = '1.1.0';\n\n private bannerShown = false;\n private config: MoneybagConfig = {\n userCount: DEFAULT_USER_COUNT,\n developerRate: DEVELOPER_HOURLY_RATE,\n };\n\n /**\n * Configure the Moneybags agent\n * @param config User count and other scaling options\n */\n configure(config: MoneybagConfig): void {\n this.config = { ...this.config, ...config };\n }\n\n /**\n * Get the current user count\n */\n get userCount(): number {\n return this.config.userCount ?? DEFAULT_USER_COUNT;\n }\n\n /**\n * Get the user scale multiplier for current user count\n */\n private getUserScaleMultiplier(): { multiplier: number; label: string } {\n const count = this.userCount;\n // Find the highest threshold that's <= user count\n let scale = USER_COUNT_MULTIPLIERS[0]!;\n for (const tier of USER_COUNT_MULTIPLIERS) {\n if (count >= tier.threshold) {\n scale = tier;\n }\n }\n return { multiplier: scale.multiplier, label: scale.label };\n }\n\n /**\n * Display the Moneybags entrance banner\n */\n private displayMoneybagsBanner(): void {\n if (this.bannerShown) return;\n this.bannerShown = true;\n\n const quote = MONEYBAGS_QUOTES[Math.floor(Math.random() * MONEYBAGS_QUOTES.length)];\n \n console.error('\\n' + '='.repeat(60));\n console.error(MONEYBAGS_ASCII);\n console.error(' Bug Cost Estimator v' + this.version);\n console.error('');\n console.error(' ' + quote);\n console.error('='.repeat(60) + '\\n');\n }\n\n // Run after other agents so we can analyze their findings\n override get priority(): AgentPriority {\n return {\n name: this.name,\n tier: 3, // Run after primary agents\n estimatedTimeMs: 50,\n dependencies: ['security', 'bug-finding', 'privacy', 'performance']\n };\n }\n\n shouldActivate(context: CodeContext): boolean {\n // Activate when there's high-stakes code\n return (\n context.touchesPayments ||\n context.touchesAuth ||\n context.touchesUserData ||\n context.touchesHealthData ||\n context.touchesDatabase ||\n context.isNewFeature\n );\n }\n\n override getActivationConfidence(context: CodeContext): number {\n let confidence = 0.3; // Base confidence\n \n if (context.touchesPayments) confidence += 0.3;\n if (context.touchesAuth) confidence += 0.2;\n if (context.touchesUserData) confidence += 0.15;\n if (context.touchesHealthData) confidence += 0.25;\n if (context.touchesDatabase) confidence += 0.1;\n \n return Math.min(confidence, 1.0);\n }\n\n /**\n * Check file relevance for cost 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\\/|\\.lock$/.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 // High-cost indicators\n if (/payment|stripe|paypal|billing|credit|debit|invoice/i.test(content)) {\n indicators.push('payment processing');\n priority = 'high';\n }\n if (/auth|login|session|jwt|token|oauth|password/i.test(content)) {\n indicators.push('authentication');\n priority = 'high';\n }\n if (/encrypt|decrypt|crypto|hash|secret|key/i.test(content)) {\n indicators.push('cryptography');\n priority = 'high';\n }\n if (/pii|ssn|social.?security|health|hipaa|gdpr|dob|birth/i.test(content)) {\n indicators.push('sensitive data');\n priority = 'high';\n }\n\n // Medium-cost indicators\n if (/database|sql|query|prisma|mongoose|sequelize/i.test(content)) {\n indicators.push('database operations');\n if (priority === 'low') priority = 'medium';\n }\n if (/api|fetch|axios|http|request/i.test(content)) {\n indicators.push('API calls');\n if (priority === 'low') priority = 'medium';\n }\n\n return {\n isRelevant: content.length > 50,\n reason: indicators.length > 0 ? `Cost-sensitive: ${indicators.join(', ')}` : 'General code',\n priority,\n indicators\n };\n }\n\n /**\n * Estimate the cost of an issue\n * Costs are scaled based on user count (default: 1,000 users)\n */\n estimateCost(issue: Issue, context: CodeContext): CostEstimate {\n // 1. Base cost by severity\n const baseCost = BASE_COST_BY_SEVERITY[issue.severity];\n const productionMultiplier = PRODUCTION_MULTIPLIER[issue.severity];\n \n // 2. Category multiplier\n const category = this.inferCategory(issue);\n const categoryData = CATEGORY_MULTIPLIERS[category] || CATEGORY_MULTIPLIERS['default']!;\n const categoryMultiplier = categoryData.multiplier;\n const categoryReason = categoryData.reason;\n \n // 3. Context multipliers (compound based on what the code touches)\n let contextMultiplier = 1;\n const contextFactors: string[] = [];\n \n for (const [key, data] of Object.entries(CONTEXT_MULTIPLIERS)) {\n if (context[key as keyof CodeContext]) {\n // Use sqrt for diminishing returns on stacking multipliers\n contextMultiplier *= Math.sqrt(data.multiplier);\n contextFactors.push(data.description);\n }\n }\n \n // Cap context multiplier at 10x to avoid unrealistic estimates\n contextMultiplier = Math.min(contextMultiplier, 10);\n \n // 4. User scale multiplier - costs scale with blast radius\n const userScale = this.getUserScaleMultiplier();\n const userScaleMultiplier = userScale.multiplier;\n const userScaleLabel = userScale.label;\n const userCount = this.userCount;\n \n // 5. Per-user costs for certain categories\n const perUserRate = PER_USER_COSTS[category as keyof typeof PER_USER_COSTS] || 0;\n // Estimate % of users affected based on severity\n const affectedUserPercent = {\n critical: 0.75, // 75% of users potentially affected\n serious: 0.40, // 40% of users\n moderate: 0.15, // 15% of users\n low: 0.05, // 5% of users\n };\n const affectedUsers = Math.round(userCount * affectedUserPercent[issue.severity]);\n const perUserCost = Math.round(perUserRate * affectedUsers);\n \n // 6. Developer time to fix\n const effort = issue.effort || 'medium';\n const fixHours = EFFORT_HOURS[effort] || 8;\n const developerRate = this.config.developerRate ?? DEVELOPER_HOURLY_RATE;\n const fixCost = fixHours * developerRate;\n \n // 7. Calculate totals with user scale\n const totalNowCost = Math.round(\n (baseCost * categoryMultiplier * contextMultiplier * userScaleMultiplier) + fixCost\n );\n \n const totalProductionCost = Math.round(\n (baseCost * productionMultiplier * categoryMultiplier * contextMultiplier * userScaleMultiplier) + \n perUserCost + // Add per-user costs for production impact\n (fixCost * 3) // Production fixes take 3x longer (debugging, deployment, rollback, post-mortem)\n );\n \n const savings = totalProductionCost - totalNowCost;\n \n // 8. Generate summary\n const summary = this.generateCostSummary(\n issue, \n totalNowCost, \n totalProductionCost, \n savings,\n contextFactors,\n userCount\n );\n \n return {\n baseCost,\n productionCost: baseCost * productionMultiplier,\n categoryMultiplier,\n categoryReason,\n contextMultiplier: Math.round(contextMultiplier * 100) / 100,\n contextFactors,\n userScaleMultiplier,\n userScaleLabel,\n userCount,\n perUserCost,\n fixCost,\n totalNowCost,\n totalProductionCost,\n savings,\n summary\n };\n }\n\n /**\n * Infer the category of an issue based on its content\n */\n private inferCategory(issue: Issue): string {\n const text = `${issue.issue} ${issue.fix} ${issue.category || ''}`.toLowerCase();\n \n // Security categories\n if (/sql.?inject|command.?inject|inject/i.test(text)) return 'injection';\n if (/xss|cross.?site|script/i.test(text)) return 'xss';\n if (/secret|api.?key|password|credential|token.*expos/i.test(text)) return 'secrets';\n if (/auth.*bypass|missing.*auth|unauthorized/i.test(text)) return 'authentication';\n if (/idor|access.?control|authorization/i.test(text)) return 'authorization';\n if (/crypto|encrypt|hash|cipher/i.test(text)) return 'cryptography';\n if (/secur|vuln/i.test(text)) return 'security';\n \n // Data categories\n if (/data.?loss|delete|truncat/i.test(text)) return 'data-loss';\n if (/corrupt|invalid.?data|data.?integrit/i.test(text)) return 'data-corruption';\n if (/privacy|pii|gdpr|personal.?data/i.test(text)) return 'privacy';\n \n // Financial categories\n if (/payment|stripe|charge|refund|transaction/i.test(text)) return 'payment';\n if (/billing|invoice|subscription/i.test(text)) return 'billing';\n if (/calculat|amount|price|total|sum/i.test(text)) return 'financial-calculation';\n \n // Reliability categories\n if (/crash|exception|fatal|panic/i.test(text)) return 'crash';\n if (/memory.?leak|heap|oom/i.test(text)) return 'memory-leak';\n if (/deadlock|lock|mutex/i.test(text)) return 'deadlock';\n if (/race|concurrent|thread.?safe/i.test(text)) return 'race-condition';\n \n // UX categories\n if (/accessib|a11y|aria|screen.?reader/i.test(text)) return 'accessibility';\n if (/perform|slow|latency|timeout/i.test(text)) return 'performance';\n \n // Code quality\n if (/type.?error|typescript|type/i.test(text)) return 'type-error';\n if (/logic|incorrect|wrong/i.test(text)) return 'logic-error';\n if (/bug|issue|error/i.test(text)) return 'bug';\n \n return 'default';\n }\n\n /**\n * Generate a human-readable cost summary\n */\n private generateCostSummary(\n _issue: Issue,\n nowCost: number,\n productionCost: number,\n savings: number,\n contextFactors: string[],\n userCount: number\n ): string {\n const formatCurrency = (n: number) => \n n >= 1000 ? `$${(n / 1000).toFixed(1)}k` : `$${n}`;\n \n const formatUsers = (n: number) =>\n n >= 1000000 ? `${(n / 1000000).toFixed(1)}M` :\n n >= 1000 ? `${(n / 1000).toFixed(0)}K` : `${n}`;\n \n let summary = `Fix now: ${formatCurrency(nowCost)} | If production: ${formatCurrency(productionCost)} | Save: ${formatCurrency(savings)}`;\n \n // Add user scale context\n summary += ` (${formatUsers(userCount)} users)`;\n \n if (contextFactors.length > 0) {\n summary += ` | Risk factors: ${contextFactors.join(', ')}`;\n }\n \n // Add urgency indicator - thresholds scaled for user count\n const scaledHighThreshold = 50000 * (userCount / 1000);\n const scaledMediumThreshold = 10000 * (userCount / 1000);\n \n if (productionCost > scaledHighThreshold) {\n summary = `[HIGH COST RISK] ${summary}`;\n } else if (productionCost > scaledMediumThreshold) {\n summary = `[SIGNIFICANT COST] ${summary}`;\n }\n \n return summary;\n }\n\n /**\n * Pattern-based analysis - Moneybags focuses on analyzing OTHER agents' findings\n * but also catches high-cost patterns directly\n */\n protected override async analyzeFiles(files: string[], _context: ScanContext): Promise<Issue[]> {\n // Show the banner on first run\n this.displayMoneybagsBanner();\n \n const issues: Issue[] = [];\n \n // High-cost patterns to detect directly\n const HIGH_COST_PATTERNS = [\n {\n pattern: /(?:price|amount|total|cost)\\s*=\\s*parseFloat\\s*\\([^)]+\\)/i,\n severity: 'serious' as const,\n issue: 'Floating-point arithmetic for money calculations',\n fix: 'Use integer cents or a decimal library (e.g., Decimal.js, dinero.js) to avoid rounding errors',\n category: 'financial-calculation'\n },\n {\n pattern: /Math\\.floor.*(?:price|amount|total)/i,\n severity: 'moderate' as const,\n issue: 'Flooring money values can cause rounding discrepancies',\n fix: 'Use proper rounding (Math.round) or banker\\'s rounding for financial calculations',\n category: 'financial-calculation'\n },\n {\n pattern: /catch\\s*\\([^)]*\\)\\s*\\{\\s*\\}/,\n severity: 'moderate' as const,\n issue: 'Empty catch block swallowing errors',\n fix: 'Log or handle errors appropriately to avoid silent failures',\n category: 'bug'\n },\n {\n pattern: /(?:if|while)\\s*\\(\\s*\\w+\\s*=[^=]/,\n severity: 'serious' as const,\n issue: 'Assignment in condition (likely meant to compare)',\n fix: 'Use === for comparison, not = for assignment',\n category: 'logic-error'\n },\n {\n pattern: /DELETE\\s+FROM\\s+\\w+\\s*(?:WHERE\\s+1|;)/i,\n severity: 'critical' as const,\n issue: 'Dangerous DELETE statement - may delete all records',\n fix: 'Add proper WHERE clause with specific conditions',\n category: 'data-loss'\n },\n {\n pattern: /(?:DROP|TRUNCATE)\\s+TABLE/i,\n severity: 'critical' as const,\n issue: 'Destructive SQL operation in code',\n fix: 'Move destructive operations to migration scripts with proper safeguards',\n category: 'data-loss'\n },\n ];\n \n for (const file of 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 for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n \n for (const { pattern, severity, issue: issueText, fix, category } of HIGH_COST_PATTERNS) {\n if (pattern.test(line)) {\n this.progress?.found(severity, `${issueText} at line ${i + 1}`);\n \n // Create issue with cost context\n const codeContext: CodeContext = {\n changeType: 'general',\n isNewFeature: false,\n touchesUserData: /user|customer|client/i.test(content),\n touchesAuth: /auth|login|session/i.test(content),\n touchesPayments: /payment|stripe|charge/i.test(content),\n touchesDatabase: /sql|query|database/i.test(content),\n touchesAPI: /api|fetch|axios/i.test(content),\n touchesUI: false,\n touchesHealthData: /health|hipaa|medical/i.test(content),\n touchesSecurityConfig: false,\n linesChanged: 0,\n filePatterns: [],\n touchesCrypto: /crypto|encrypt|hash/i.test(content),\n touchesFileSystem: /fs\\.|readFile|writeFile/i.test(content),\n touchesThirdPartyAPI: false,\n touchesLogging: false,\n touchesErrorHandling: false,\n hasTests: false,\n complexity: 'medium',\n patterns: {\n hasAsyncCode: /async|await|promise/i.test(content),\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 const baseIssue = this.createIssue(\n this.generateIssueId(),\n severity,\n issueText,\n fix,\n file,\n i + 1,\n 0.9,\n undefined,\n true,\n { category }\n );\n \n const estimate = this.estimateCost(baseIssue, codeContext);\n \n // Append cost info to the fix\n const issueWithCost: Issue = {\n ...baseIssue,\n issue: `${issueText} | ${estimate.summary}`,\n };\n \n issues.push(issueWithCost);\n }\n }\n }\n } catch {\n // Skip unreadable files\n }\n }\n \n return issues;\n }\n\n /**\n * Override to add cost analysis to AI enhancement\n */\n protected override getAIEnhancementSystemPrompt(): string {\n return `You are a senior engineer performing cost-impact analysis on code issues.\n\nYour goal is to identify bugs that will cost the most money if they reach production.\n\nFOCUS ON HIGH-COST ISSUES:\n1. **Financial Bugs** (25x multiplier): Payment, billing, pricing calculation errors\n2. **Data Loss** (20x multiplier): Accidental deletes, data corruption, no backups\n3. **Security Breaches** (15x multiplier): Exposed secrets, auth bypass, injection\n4. **Privacy Violations** (10x multiplier): PII exposure, GDPR violations\n5. **System Crashes** (8x multiplier): Production downtime ($5,600/minute average)\n\nCOST ESTIMATION FACTORS:\n- Critical bugs: $5k now, $150k in production\n- Serious bugs: $2k now, $40k in production \n- Moderate bugs: $500 now, $5k in production\n- Low bugs: $100 now, $500 in production\n\nFor each issue, estimate:\n- Cost to fix NOW (during development)\n- Cost if it reaches PRODUCTION (support, hotfix, reputation, legal)\n- Savings by fixing immediately\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 \"cost_now\": 5000,\n \"cost_production\": 150000,\n \"cost_category\": \"payment|security|data-loss|privacy|crash|performance\",\n \"fix\": \"Code fix\"\n }],\n \"additional\": [{\n \"issue\": \"High-cost bug found\",\n \"file\": \"path\",\n \"line\": 123,\n \"severity\": \"serious\",\n \"cost_now\": 2000,\n \"cost_production\": 40000,\n \"cost_category\": \"billing\",\n \"fix\": \"Code fix\"\n }],\n \"total_risk_if_shipped\": 250000,\n \"summary\": \"Cost impact assessment\"\n}`;\n }\n\n /**\n * Aggregate cost report for all issues\n */\n generateCostReport(issues: Issue[], context: CodeContext): {\n totalNowCost: number;\n totalProductionCost: number;\n totalSavings: number;\n userCount: number;\n userScaleLabel: string;\n breakdown: Array<{ severity: string; count: number; nowCost: number; productionCost: number }>;\n riskLevel: 'low' | 'medium' | 'high' | 'critical';\n summary: string;\n } {\n const estimates = issues.map(issue => ({\n issue,\n estimate: this.estimateCost(issue, context)\n }));\n\n const breakdown = ['critical', 'serious', 'moderate', 'low'].map(severity => {\n const filtered = estimates.filter(e => e.issue.severity === severity);\n return {\n severity,\n count: filtered.length,\n nowCost: filtered.reduce((sum, e) => sum + e.estimate.totalNowCost, 0),\n productionCost: filtered.reduce((sum, e) => sum + e.estimate.totalProductionCost, 0)\n };\n });\n\n const totalNowCost = breakdown.reduce((sum, b) => sum + b.nowCost, 0);\n const totalProductionCost = breakdown.reduce((sum, b) => sum + b.productionCost, 0);\n const totalSavings = totalProductionCost - totalNowCost;\n \n // Get user scale info\n const userScale = this.getUserScaleMultiplier();\n const userCount = this.userCount;\n\n // Determine risk level - scaled for user count\n const scaleMultiplier = userScale.multiplier;\n let riskLevel: 'low' | 'medium' | 'high' | 'critical' = 'low';\n if (totalProductionCost > 100000 * scaleMultiplier) riskLevel = 'critical';\n else if (totalProductionCost > 25000 * scaleMultiplier) riskLevel = 'high';\n else if (totalProductionCost > 5000 * scaleMultiplier) riskLevel = 'medium';\n\n const formatCurrency = (n: number) => \n n >= 1000000 ? `$${(n / 1000000).toFixed(2)}M` :\n n >= 1000 ? `$${(n / 1000).toFixed(1)}k` : `$${n}`;\n \n const formatUsers = (n: number) =>\n n >= 1000000 ? `${(n / 1000000).toFixed(1)}M` :\n n >= 1000 ? `${Math.round(n / 1000)}K` : `${n}`;\n\n const summary = `\nCOST ANALYSIS REPORT\n=======================================\nUser Scale: ${formatUsers(userCount)} users (${userScale.label})\n Costs scaled ${userScale.multiplier}x from 1K baseline\n\nTotal Issues: ${issues.length}\n Critical: ${breakdown.find(b => b.severity === 'critical')?.count || 0}\n Serious: ${breakdown.find(b => b.severity === 'serious')?.count || 0}\n Moderate: ${breakdown.find(b => b.severity === 'moderate')?.count || 0}\n Low: ${breakdown.find(b => b.severity === 'low')?.count || 0}\n\nCOST IMPACT\n Fix now: ${formatCurrency(totalNowCost)}\n If production: ${formatCurrency(totalProductionCost)}\n Savings by fixing now: ${formatCurrency(totalSavings)}\n\nRISK LEVEL: ${riskLevel.toUpperCase()}\n${riskLevel === 'critical' ? ' URGENT: High-value bugs require immediate attention' : ''}\n${riskLevel === 'high' ? ' ATTENTION: Significant financial risk detected' : ''}\n\nBased on industry research:\n - IBM: Production bugs cost 30x more to fix\n - Ponemon: Average data breach costs $4.45M\n - Gartner: Downtime averages $5,600/minute\n\nDefault: 250 users. Scale with: trie scan --users 10000\n=======================================\n `.trim();\n\n return { \n totalNowCost, \n totalProductionCost, \n totalSavings, \n userCount, \n userScaleLabel: userScale.label,\n breakdown, \n riskLevel, \n summary \n };\n }\n}\n","import { BaseAgent, FileRelevance } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext, AgentPriority } from '../types/index.js';\n\n/**\n * ASCII Art Banner for Production Ready Agent\n */\nconst PRODUCTION_READY_ASCII = `\n ██████╗ ██████╗ ██████╗ ██████╗ \n ██╔══██╗██╔══██╗██╔═══██╗██╔══██╗\n ██████╔╝██████╔╝██║ ██║██║ ██║\n ██╔═══╝ ██╔══██╗██║ ██║██║ ██║\n ██║ ██║ ██║╚██████╔╝██████╔╝\n ╚═╝ ╚═╝ ╚═╝ ╚═════╝ ╚═════╝ \n \n ██████╗ ███████╗ █████╗ ██████╗ ██╗ ██╗\n ██╔══██╗██╔════╝██╔══██╗██╔══██╗╚██╗ ██╔╝\n ██████╔╝█████╗ ███████║██║ ██║ ╚████╔╝ \n ██╔══██╗██╔══╝ ██╔══██║██║ ██║ ╚██╔╝ \n ██║ ██║███████╗██║ ██║██████╔╝ ██║ \n ╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═════╝ ╚═╝ \n`;\n\nconst PRODUCTION_QUOTES = [\n 'Ship it? Not until I say so.',\n '\"Works on my machine\" is not a deployment strategy.',\n 'The last mile is where dreams become revenue -- or nightmares.',\n 'Production is where your code meets reality. Is yours ready?',\n];\n\n/**\n * Production readiness checks - what we look for\n */\nconst PRODUCTION_PATTERNS = {\n // Health & Reliability\n healthEndpoint: {\n pattern: /\\/health|healthcheck|health-check|readiness|liveness/i,\n category: 'reliability',\n requirement: 'Health check endpoint',\n severity: 'serious' as const,\n },\n gracefulShutdown: {\n pattern: /SIGTERM|SIGINT|process\\.on\\s*\\(\\s*['\"]SIG/i,\n category: 'reliability',\n requirement: 'Graceful shutdown handling',\n severity: 'moderate' as const,\n },\n \n // Scalability\n connectionPooling: {\n pattern: /connectionLimit|pool|poolSize|max_connections|maxConnections/i,\n category: 'scalability',\n requirement: 'Database connection pooling',\n severity: 'serious' as const,\n },\n inMemorySession: {\n pattern: /express-session.*(?!redis|memcached|mongo)|session\\s*=\\s*\\{\\}/i,\n category: 'scalability',\n requirement: 'External session store (not in-memory)',\n severity: 'serious' as const,\n },\n \n // Error Handling\n globalErrorHandler: {\n pattern: /app\\.use\\s*\\(\\s*\\(?err|errorHandler|process\\.on\\s*\\(\\s*['\"]uncaughtException/i,\n category: 'reliability',\n requirement: 'Global error handler',\n severity: 'serious' as const,\n },\n \n // Security Headers\n securityHeaders: {\n pattern: /helmet|contentSecurityPolicy|X-Frame-Options|X-Content-Type|Strict-Transport/i,\n category: 'security',\n requirement: 'Security headers (CSP, HSTS, etc.)',\n severity: 'serious' as const,\n },\n \n // Rate Limiting\n rateLimiting: {\n pattern: /rateLimit|rate-limit|throttle|express-rate-limit|slowDown/i,\n category: 'security',\n requirement: 'API rate limiting',\n severity: 'moderate' as const,\n },\n \n // Logging\n structuredLogging: {\n pattern: /pino|winston|bunyan|structured.*log|log.*json/i,\n category: 'observability',\n requirement: 'Structured logging',\n severity: 'moderate' as const,\n },\n \n // Monitoring\n monitoring: {\n pattern: /prometheus|datadog|newrelic|sentry|bugsnag|opentelemetry|@sentry/i,\n category: 'observability',\n requirement: 'Error/performance monitoring',\n severity: 'moderate' as const,\n },\n};\n\n/**\n * Anti-patterns that indicate NOT production ready\n */\nconst PRODUCTION_ANTIPATTERNS = [\n {\n pattern: /console\\.(log|debug|info)\\s*\\(/g,\n severity: 'low' as const,\n issue: 'Console logging in production code',\n fix: 'Replace with structured logging (pino, winston) that can be disabled in production',\n category: 'observability',\n },\n {\n pattern: /localhost:\\d+|127\\.0\\.0\\.1:\\d+/g,\n severity: 'serious' as const,\n issue: 'Hardcoded localhost URL will fail in production',\n fix: 'Use environment variables for all URLs: process.env.API_URL',\n category: 'configuration',\n },\n {\n pattern: /TODO.*prod|FIXME.*deploy|hack.*ship/gi,\n severity: 'serious' as const,\n issue: 'TODO/FIXME comment flagged for production',\n fix: 'Resolve the TODO before deploying to production',\n category: 'code-quality',\n },\n {\n pattern: /process\\.env\\.\\w+\\s*\\|\\|\\s*['\"][^'\"]+['\"]/g,\n severity: 'moderate' as const,\n issue: 'Hardcoded fallback for environment variable',\n fix: 'Fail fast if required env vars are missing: throw if !process.env.VAR',\n category: 'configuration',\n },\n {\n pattern: /throw\\s+['\"][^'\"]+['\"]/g,\n severity: 'moderate' as const,\n issue: 'Throwing string instead of Error object',\n fix: 'Throw proper Error objects: throw new Error(\"message\")',\n category: 'reliability',\n },\n {\n pattern: /\\.then\\s*\\([^)]*\\)\\s*(?!\\.catch)/g,\n severity: 'moderate' as const,\n issue: 'Promise without .catch() - unhandled rejection risk',\n fix: 'Add .catch() handler or use try/catch with async/await',\n category: 'reliability',\n },\n {\n pattern: /setTimeout\\s*\\([^,]+,\\s*\\d{5,}\\)/g,\n severity: 'moderate' as const,\n issue: 'Long setTimeout (>10s) - use proper job queue for background tasks',\n fix: 'Use a job queue (Bull, Agenda, BullMQ) for background processing',\n category: 'scalability',\n },\n {\n pattern: /fs\\.(readFileSync|writeFileSync)/g,\n severity: 'moderate' as const,\n issue: 'Synchronous file I/O blocks event loop',\n fix: 'Use async fs methods: fs.promises.readFile, fs.promises.writeFile',\n category: 'performance',\n },\n];\n\n/**\n * Files to check for production requirements\n */\nconst PRODUCTION_CONFIG_FILES = [\n /package\\.json$/,\n /\\.env\\.example$/,\n /docker-compose.*\\.ya?ml$/,\n /Dockerfile$/,\n /\\.github\\/workflows/,\n /vercel\\.json$/,\n /netlify\\.toml$/,\n];\n\nexport class ProductionReadyAgent extends BaseAgent {\n name = 'production-ready';\n description = 'Production readiness checker: health endpoints, graceful shutdown, connection pooling, security headers, monitoring, and deployment gates';\n version = '1.0.0';\n\n private bannerShown = false;\n private foundRequirements: Set<string> = new Set();\n\n override get priority(): AgentPriority {\n return {\n name: this.name,\n tier: 3, // Run after other agents for comprehensive check\n estimatedTimeMs: 100,\n dependencies: ['security', 'bug-finding', 'performance', 'devops']\n };\n }\n\n shouldActivate(context: CodeContext): boolean {\n // Activate for significant codebases or when deploying\n return (\n context.linesChanged > 100 ||\n context.touchesAPI ||\n context.touchesDatabase ||\n context.touchesAuth ||\n context.touchesPayments ||\n context.isNewFeature\n );\n }\n\n override getActivationConfidence(context: CodeContext): number {\n let confidence = 0.2; // Base confidence\n \n if (context.touchesAPI) confidence += 0.3;\n if (context.touchesDatabase) confidence += 0.2;\n if (context.touchesAuth) confidence += 0.2;\n if (context.touchesPayments) confidence += 0.3;\n if (context.linesChanged > 200) confidence += 0.2;\n \n return Math.min(confidence, 1.0);\n }\n\n private displayBanner(): void {\n if (this.bannerShown) return;\n this.bannerShown = true;\n\n const quote = PRODUCTION_QUOTES[Math.floor(Math.random() * PRODUCTION_QUOTES.length)];\n \n console.error('\\n' + '='.repeat(60));\n console.error(PRODUCTION_READY_ASCII);\n console.error(' Production Readiness Gate v' + this.version);\n console.error('');\n console.error(' ' + quote);\n console.error('='.repeat(60) + '\\n');\n }\n\n protected override checkFileRelevance(file: string, content: string): FileRelevance {\n // Skip non-code files\n if (/node_modules|\\.d\\.ts$|\\.min\\.|dist\\/|build\\/|\\.lock$/.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 // High priority - entry points and config\n if (/index\\.[jt]s$|main\\.[jt]s$|app\\.[jt]s$|server\\.[jt]s$/i.test(file)) {\n indicators.push('application entry point');\n priority = 'high';\n }\n if (PRODUCTION_CONFIG_FILES.some(p => p.test(file))) {\n indicators.push('configuration file');\n priority = 'high';\n }\n\n // Check for production-relevant patterns in content\n if (/express|fastify|koa|hapi|nest/i.test(content)) {\n indicators.push('web framework');\n if (priority === 'low') priority = 'medium';\n }\n if (/database|prisma|sequelize|mongoose|pg|mysql/i.test(content)) {\n indicators.push('database code');\n if (priority === 'low') priority = 'medium';\n }\n\n return {\n isRelevant: content.length > 50,\n reason: indicators.length > 0 ? `Production-critical: ${indicators.join(', ')}` : 'General code',\n priority,\n indicators\n };\n }\n\n protected override async analyzeFiles(files: string[], _context: ScanContext): Promise<Issue[]> {\n this.displayBanner();\n this.foundRequirements.clear();\n \n const issues: Issue[] = [];\n const allContent: string[] = [];\n \n // First pass: collect all content and check for requirements\n for (const file of files) {\n if (/node_modules|\\.d\\.ts$|\\.min\\.|dist\\/|build\\//.test(file)) continue;\n \n try {\n const content = await this.readFile(file);\n allContent.push(content);\n \n // Check for production requirements being met\n for (const [key, config] of Object.entries(PRODUCTION_PATTERNS)) {\n if (config.pattern.test(content)) {\n this.foundRequirements.add(key);\n }\n }\n \n // Check for anti-patterns\n const lines = content.split('\\n');\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n \n for (const antiPattern of PRODUCTION_ANTIPATTERNS) {\n // Reset regex state for global patterns\n antiPattern.pattern.lastIndex = 0;\n \n if (antiPattern.pattern.test(line)) {\n // Skip console.log in test files\n if (antiPattern.issue.includes('Console') && /\\.(test|spec)\\.[jt]sx?$/.test(file)) {\n continue;\n }\n \n this.progress?.found(antiPattern.severity, `${antiPattern.issue} at line ${i + 1}`);\n issues.push(this.createIssue(\n this.generateIssueId(),\n antiPattern.severity,\n `[NOT PROD READY] ${antiPattern.issue}`,\n antiPattern.fix,\n file,\n i + 1,\n 0.9,\n undefined,\n true,\n { category: antiPattern.category }\n ));\n }\n }\n }\n } catch {\n // Skip unreadable files\n }\n }\n \n // Second pass: report missing requirements\n const combinedContent = allContent.join('\\n');\n \n for (const [key, config] of Object.entries(PRODUCTION_PATTERNS)) {\n if (!this.foundRequirements.has(key)) {\n // Double-check against all content\n if (!config.pattern.test(combinedContent)) {\n this.progress?.found(config.severity, `Missing: ${config.requirement}`);\n issues.push(this.createIssue(\n this.generateIssueId(),\n config.severity,\n `[MISSING] ${config.requirement}`,\n this.getRequirementFix(key),\n 'project',\n undefined,\n 0.8,\n undefined,\n false,\n { category: config.category }\n ));\n }\n }\n }\n \n // Generate production readiness summary\n this.logReadinessSummary(issues);\n \n return issues;\n }\n\n private getRequirementFix(key: string): string {\n const fixes: Record<string, string> = {\n healthEndpoint: 'Add health check endpoint: app.get(\"/health\", (req, res) => res.json({ status: \"ok\" }))',\n gracefulShutdown: 'Handle SIGTERM: process.on(\"SIGTERM\", async () => { await server.close(); process.exit(0); })',\n connectionPooling: 'Configure connection pool: { max: 20, min: 5, acquire: 30000, idle: 10000 }',\n inMemorySession: 'Use Redis for sessions: new RedisStore({ client: redisClient })',\n globalErrorHandler: 'Add error middleware: app.use((err, req, res, next) => { logger.error(err); res.status(500).json({ error: \"Internal error\" }); })',\n securityHeaders: 'Add helmet middleware: app.use(helmet())',\n rateLimiting: 'Add rate limiting: app.use(rateLimit({ windowMs: 15*60*1000, max: 100 }))',\n structuredLogging: 'Use structured logger: const logger = pino({ level: process.env.LOG_LEVEL || \"info\" })',\n monitoring: 'Add error tracking: Sentry.init({ dsn: process.env.SENTRY_DSN })',\n };\n return fixes[key] || 'See production readiness documentation';\n }\n\n private logReadinessSummary(issues: Issue[]): void {\n const totalRequirements = Object.keys(PRODUCTION_PATTERNS).length;\n const metRequirements = this.foundRequirements.size;\n \n const criticalIssues = issues.filter(i => i.severity === 'critical').length;\n const seriousIssues = issues.filter(i => i.severity === 'serious').length;\n \n const readinessScore = Math.max(0, Math.round(\n ((metRequirements / totalRequirements) * 50) + \n (50 - (criticalIssues * 20) - (seriousIssues * 10))\n ));\n \n const status = criticalIssues > 0 || seriousIssues > 2 \n ? '[FAIL] NOT READY TO SHIP' \n : seriousIssues > 0 \n ? '[WARN] SHIP WITH CAUTION'\n : '[OK] READY TO SHIP';\n \n console.error('\\n' + '-'.repeat(50));\n console.error('PRODUCTION READINESS REPORT');\n console.error('-'.repeat(50));\n console.error(` Score: ${readinessScore}/100`);\n console.error(` Requirements: ${metRequirements}/${totalRequirements} met`);\n console.error(` Critical issues: ${criticalIssues}`);\n console.error(` Serious issues: ${seriousIssues}`);\n console.error('');\n console.error(` ${status}`);\n console.error('-'.repeat(50) + '\\n');\n }\n\n protected override getAIEnhancementSystemPrompt(): string {\n return `You are a production readiness engineer reviewing code for deployment.\n\nCheck for these CRITICAL production requirements:\n\n1. **Reliability**\n - Health check endpoints (/health, /ready, /live)\n - Graceful shutdown (SIGTERM handling)\n - Global error handlers\n - Circuit breakers for external services\n\n2. **Scalability**\n - Database connection pooling\n - External session storage (Redis, not in-memory)\n - Stateless application design\n - No blocking sync operations\n\n3. **Security**\n - Security headers (helmet, CSP, HSTS)\n - Rate limiting on API endpoints\n - No hardcoded secrets or URLs\n - Input validation on all endpoints\n\n4. **Observability**\n - Structured logging (not console.log)\n - Error tracking (Sentry, etc.)\n - Metrics collection\n - Request tracing\n\n5. **Configuration**\n - Environment variables for all config\n - Fail-fast on missing required vars\n - No localhost/hardcoded URLs\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\" | \"serious\" | \"moderate\" | \"low\",\n \"category\": \"reliability\" | \"scalability\" | \"security\" | \"observability\" | \"configuration\",\n \"fix\": \"Specific production-ready fix\"\n }],\n \"additional\": [{\n \"issue\": \"Production readiness gap\",\n \"file\": \"path\",\n \"line\": 123,\n \"severity\": \"serious\",\n \"category\": \"reliability\",\n \"fix\": \"How to make production-ready\"\n }],\n \"readiness_score\": 0-100,\n \"ship_verdict\": \"READY\" | \"CAUTION\" | \"NOT_READY\",\n \"summary\": \"Production readiness assessment\"\n}`;\n }\n}\n","/**\n * Skill Gating\n * \n * Checks if a skill's requirements are met by the current project.\n * Supports: dependencies, env vars, binaries, and config files.\n */\n\nimport { existsSync } from 'fs';\nimport { readFile } from 'fs/promises';\nimport { join } from 'path';\nimport { execSync } from 'child_process';\nimport type { SkillFrontmatter } from '../types/external-skill.js';\n\nexport interface GatingResult {\n allowed: boolean;\n reason?: string;\n missingDeps?: string[];\n missingEnv?: string[];\n missingBins?: string[];\n missingConfigs?: string[];\n}\n\n/**\n * Check if a skill's requirements are met\n */\nexport async function checkSkillRequirements(\n frontmatter: SkillFrontmatter,\n projectDir: string\n): Promise<GatingResult> {\n const result: GatingResult = { allowed: true };\n\n // Handle simple requires (backwards compatible)\n if (frontmatter.requires && frontmatter.requires.length > 0) {\n const projectDeps = await getProjectDependencies(projectDir);\n const missing = frontmatter.requires.filter(dep => !projectDeps.has(dep));\n \n if (missing.length > 0) {\n result.allowed = false;\n result.missingDeps = missing;\n result.reason = `Missing dependencies: ${missing.join(', ')}`;\n return result;\n }\n }\n\n // Handle extended requirements\n const reqs = frontmatter.requirements;\n if (!reqs) {\n return result;\n }\n\n // Check required deps (all must be present)\n if (reqs.deps && reqs.deps.length > 0) {\n const projectDeps = await getProjectDependencies(projectDir);\n const missing = reqs.deps.filter(dep => !projectDeps.has(dep));\n \n if (missing.length > 0) {\n result.allowed = false;\n result.missingDeps = missing;\n result.reason = `Missing dependencies: ${missing.join(', ')}`;\n return result;\n }\n }\n\n // Check anyDeps (at least one must be present)\n if (reqs.anyDeps && reqs.anyDeps.length > 0) {\n const projectDeps = await getProjectDependencies(projectDir);\n const hasAny = reqs.anyDeps.some(dep => projectDeps.has(dep));\n \n if (!hasAny) {\n result.allowed = false;\n result.missingDeps = reqs.anyDeps;\n result.reason = `Requires at least one of: ${reqs.anyDeps.join(', ')}`;\n return result;\n }\n }\n\n // Check environment variables\n if (reqs.env && reqs.env.length > 0) {\n const missing = reqs.env.filter(envVar => !process.env[envVar]);\n \n if (missing.length > 0) {\n result.allowed = false;\n result.missingEnv = missing;\n result.reason = `Missing environment variables: ${missing.join(', ')}`;\n return result;\n }\n }\n\n // Check binaries in PATH\n if (reqs.bins && reqs.bins.length > 0) {\n const missing = reqs.bins.filter(bin => !isBinaryAvailable(bin));\n \n if (missing.length > 0) {\n result.allowed = false;\n result.missingBins = missing;\n result.reason = `Missing binaries: ${missing.join(', ')}`;\n return result;\n }\n }\n\n // Check config files exist\n if (reqs.configFiles && reqs.configFiles.length > 0) {\n const missing = reqs.configFiles.filter(file => !existsSync(join(projectDir, file)));\n \n if (missing.length > 0) {\n result.allowed = false;\n result.missingConfigs = missing;\n result.reason = `Missing config files: ${missing.join(', ')}`;\n return result;\n }\n }\n\n return result;\n}\n\n/**\n * Get project dependencies from package.json\n */\nasync function getProjectDependencies(projectDir: string): Promise<Set<string>> {\n try {\n const pkgPath = join(projectDir, 'package.json');\n if (!existsSync(pkgPath)) {\n return new Set();\n }\n \n const pkg = JSON.parse(await readFile(pkgPath, 'utf-8'));\n return new Set([\n ...Object.keys(pkg.dependencies || {}),\n ...Object.keys(pkg.devDependencies || {}),\n ]);\n } catch {\n return new Set();\n }\n}\n\n/**\n * Check if a binary is available in PATH\n */\nfunction isBinaryAvailable(binary: string): boolean {\n try {\n const command = process.platform === 'win32' ? `where ${binary}` : `which ${binary}`;\n execSync(command, { stdio: 'ignore' });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Get a human-readable summary of why a skill was filtered\n */\nexport function formatGatingReason(result: GatingResult): string {\n if (result.allowed) return 'Allowed';\n \n const parts: string[] = [];\n \n if (result.missingDeps?.length) {\n parts.push(`deps: ${result.missingDeps.join(', ')}`);\n }\n if (result.missingEnv?.length) {\n parts.push(`env: ${result.missingEnv.join(', ')}`);\n }\n if (result.missingBins?.length) {\n parts.push(`bins: ${result.missingBins.join(', ')}`);\n }\n if (result.missingConfigs?.length) {\n parts.push(`configs: ${result.missingConfigs.join(', ')}`);\n }\n \n return `Missing: ${parts.join('; ')}`;\n}\n","/**\n * Skill Review Agent\n * \n * A proper agent (brain) that applies installed skills (hands) to code review.\n * \n * Key distinction:\n * - This is an AGENT: it has shouldActivate(), makes decisions, orchestrates\n * - Skills are CAPABILITIES: just knowledge/instructions this agent applies\n * \n * Skills don't \"run\" - this agent applies them.\n * \n * Skill Gating:\n * Skills can declare `requires: [\"react\", \"next\"]` in frontmatter.\n * Only skills whose requirements are met by project dependencies are loaded.\n */\n\nimport { BaseAgent } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext, AgentPriority, AgentResult } from '../types/index.js';\nimport type { InstalledSkill, ParsedSkill } from '../types/external-skill.js';\nimport { listInstalledSkills } from '../skills/installer.js';\nimport { parseSkillMd } from '../skills/parser.js';\nimport { runAIAnalysis, isAIAvailable } from '../ai/client.js';\nimport { recordSkillUsage } from '../utils/context-state.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { checkSkillRequirements, formatGatingReason, type GatingResult } from '../skills/gating.js';\n\nexport class SkillReviewAgent extends BaseAgent {\n name = 'skill-review';\n description = 'Applies installed skills from GitHub repositories to code review';\n version = '1.0.0';\n \n private skills: InstalledSkill[] = [];\n private loadedSkillContent: Map<string, ParsedSkill> = new Map();\n private filteredSkills: Map<string, GatingResult> = new Map();\n \n override get priority(): AgentPriority {\n return {\n name: this.name,\n tier: 2,\n estimatedTimeMs: 500,\n dependencies: [],\n };\n }\n \n /**\n * Agent decides when to activate based on context and installed skills\n */\n override shouldActivate(context: CodeContext): boolean {\n if (this.skills.length === 0) return false;\n return context.touchesUI || context.touchesAPI || context.isNewFeature;\n }\n \n override getActivationConfidence(context: CodeContext): number {\n if (!this.shouldActivate(context)) return 0;\n \n let confidence = 0.5;\n if (context.touchesUI) confidence += 0.2;\n if (context.isNewFeature) confidence += 0.15;\n if (context.framework) confidence += 0.1;\n if (this.skills.length > 1) confidence += 0.1;\n \n return Math.min(1.0, confidence);\n }\n \n /**\n * Load installed skills with gating based on requirements\n * Checks: dependencies, env vars, binaries, and config files\n */\n async loadSkills(): Promise<void> {\n const allSkills = await listInstalledSkills();\n const workDir = getWorkingDirectory(undefined, true);\n \n this.skills = [];\n this.loadedSkillContent.clear();\n this.filteredSkills.clear();\n \n for (const skill of allSkills) {\n try {\n const parsed = await parseSkillMd(skill.path);\n \n // Check requirements (supports both simple requires and extended requirements)\n const gatingResult = await checkSkillRequirements(parsed.frontmatter, workDir);\n \n if (gatingResult.allowed) {\n this.skills.push(skill);\n this.loadedSkillContent.set(skill.name, parsed);\n } else {\n this.filteredSkills.set(skill.name, gatingResult);\n }\n } catch {\n // Skip skills that fail to parse\n }\n }\n }\n \n /**\n * Get skills that were filtered out with reasons\n */\n getFilteredSkills(): Map<string, GatingResult> {\n return this.filteredSkills;\n }\n \n /**\n * Get filtered skill names (for backwards compatibility)\n */\n getFilteredSkillNames(): string[] {\n return Array.from(this.filteredSkills.keys());\n }\n \n /**\n * Get a summary of why skills were filtered\n */\n getFilteredSkillsSummary(): string[] {\n return Array.from(this.filteredSkills.entries()).map(([name, result]) =>\n `${name}: ${formatGatingReason(result)}`\n );\n }\n \n /**\n * Get names of skills this agent will apply\n */\n getAppliedSkillNames(): string[] {\n return this.skills.map(s => s.name);\n }\n \n /**\n * Check if any skills are loaded\n */\n hasSkills(): boolean {\n return this.skills.length > 0;\n }\n \n /**\n * Override to always use AI since skills require AI interpretation\n */\n protected override shouldAlwaysUseAI(): boolean {\n return true;\n }\n \n /**\n * Override scan to track skill usage after completion\n */\n override async scan(files: string[], context: ScanContext): Promise<AgentResult> {\n const result = await super.scan(files, context);\n \n // Track skill usage if any skills were applied\n if (this.skills.length > 0 && result.issues.length > 0) {\n await recordSkillUsage({\n skillNames: this.getAppliedSkillNames(),\n agentName: this.name,\n }).catch(() => {\n // Don't fail the scan if tracking fails\n });\n }\n \n return result;\n }\n \n /**\n * Agent orchestrates analysis - skills provide the knowledge\n */\n protected override async analyzeFiles(files: string[], context: ScanContext): Promise<Issue[]> {\n if (!isAIAvailable()) return [];\n if (this.loadedSkillContent.size === 0) return [];\n \n const snippets: string[] = [];\n const filesToAnalyze = files.slice(0, 10);\n \n for (const file of filesToAnalyze) {\n try {\n const content = await this.readFile(file);\n const rel = file.replace(context.workingDir, '').replace(/^\\//, '');\n const truncated = content.slice(0, 3000);\n snippets.push(`### ${rel}\\n\\`\\`\\`\\n${truncated}\\n\\`\\`\\``);\n } catch {\n // Skip files that can't be read\n }\n }\n \n if (snippets.length === 0) return [];\n \n const skillContexts = this.buildSkillContext();\n \n const systemPrompt = `You are the Skill Review Agent. You apply specialized skills to code review.\n\nApply these skills to the code:\n\n${skillContexts}\n\n---\n\nFor each issue found, specify which skill's guideline was violated.\nOutput ONLY valid JSON in this format:\n{\n \"issues\": [\n {\n \"severity\": \"critical|serious|moderate|low\",\n \"issue\": \"Description of the issue\",\n \"skill\": \"skill-name-that-found-this\",\n \"file\": \"path/to/file.ts\",\n \"line\": 123,\n \"fix\": \"How to fix it\"\n }\n ]\n}`;\n\n const result = await runAIAnalysis({\n systemPrompt,\n userPrompt: `Review this code:\\n\\n${snippets.join('\\n\\n')}`,\n maxTokens: 4096,\n temperature: 0.2,\n });\n \n if (!result.success) return [];\n \n return this.parseSkillIssues(result.content, files);\n }\n \n private buildSkillContext(): string {\n const contexts: string[] = [];\n \n for (const [name, parsed] of this.loadedSkillContent) {\n contexts.push(`## Skill: ${name}\\n${parsed.rawContent}`);\n }\n \n return contexts.join('\\n\\n---\\n\\n');\n }\n \n private parseSkillIssues(response: string, files: string[]): Issue[] {\n const issues: Issue[] = [];\n \n try {\n const jsonMatch = response.match(/\\{[\\s\\S]*\\}/);\n if (!jsonMatch) return issues;\n \n const parsed = JSON.parse(jsonMatch[0]);\n \n if (!parsed.issues || !Array.isArray(parsed.issues)) return issues;\n \n for (const item of parsed.issues) {\n const severity = this.normalizeSeverity(item.severity);\n const skillName = item.skill || 'unknown-skill';\n \n issues.push(this.createIssue(\n this.generateIssueId(),\n severity,\n `[${skillName}] ${item.issue || 'Issue detected'}`,\n item.fix || 'See skill guidelines',\n item.file || files[0] || 'unknown',\n item.line,\n 0.8,\n undefined,\n false,\n { category: skillName }\n ));\n }\n } catch {\n // JSON parsing failed, return empty\n }\n \n return issues;\n }\n \n private normalizeSeverity(severity: string): 'critical' | 'serious' | 'moderate' | 'low' {\n const normalized = (severity || '').toLowerCase();\n if (normalized === 'critical') return 'critical';\n if (normalized === 'serious' || normalized === 'high') return 'serious';\n if (normalized === 'moderate' || normalized === 'medium') return 'moderate';\n return 'low';\n }\n}\n","/**\n * Custom Skill - Runtime class for document-generated skills\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 CustomSkill 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 skill 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 skill 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// Backward compatibility alias\nexport { CustomSkill as CustomAgent };\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 { MoneybagAgent } from './moneybags.js';\nimport { ProductionReadyAgent } from './production-ready.js';\nimport { SkillReviewAgent } from './skill-review.js';\nimport { CustomSkill } from './custom-skill.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 // Cost analysis agent\n new MoneybagAgent(),\n \n // Production readiness gate\n new ProductionReadyAgent(),\n \n // Skill review agent (applies external skills)\n new SkillReviewAgent(),\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 skills from .trie/agents/ directory\n */\n async loadCustomSkills(): Promise<void> {\n if (this.customAgentsLoaded) return;\n \n try {\n const skillsDir = join(getWorkingDirectory(undefined, true), '.trie', 'agents');\n const files = await readdir(skillsDir);\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(skillsDir, file);\n const content = await readFile(configPath, 'utf-8');\n const config: GeneratedAgentConfig = JSON.parse(content);\n \n // Create and register the custom skill\n const skill = new CustomSkill(config);\n this.agents.set(skill.name, skill);\n loadedCount++;\n \n } catch (error) {\n console.error(`Failed to load custom skill from ${file}:`, error);\n }\n }\n \n if (loadedCount > 0) {\n console.error(`Loaded ${loadedCount} custom skill(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 // Load skills for the SkillReviewAgent\n await this.loadSkillsForAgent();\n }\n\n // Backward compatibility alias\n async loadCustomAgents(): Promise<void> {\n return this.loadCustomSkills();\n }\n \n /**\n * Load installed skills for the SkillReviewAgent\n */\n private async loadSkillsForAgent(): Promise<void> {\n const skillReviewAgent = this.agents.get('skill-review');\n if (skillReviewAgent && skillReviewAgent instanceof SkillReviewAgent) {\n await skillReviewAgent.loadSkills();\n if (skillReviewAgent.hasSkills()) {\n console.error(`Loaded ${skillReviewAgent.getAppliedSkillNames().length} skill(s) for skill-review agent`);\n }\n }\n }\n\n /**\n * Reload custom skills (useful after creating new ones)\n */\n async reloadCustomSkills(): Promise<void> {\n // Remove existing custom skills\n for (const [name, agent] of this.agents.entries()) {\n if (agent instanceof CustomSkill) {\n this.agents.delete(name);\n }\n }\n \n this.customAgentsLoaded = false;\n await this.loadCustomSkills();\n }\n\n // Backward compatibility alias\n async reloadCustomAgents(): Promise<void> {\n return this.reloadCustomSkills();\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 CustomSkill)\n );\n }\n\n /**\n * Get only custom skills\n */\n getCustomSkills(): CustomSkill[] {\n return Array.from(this.agents.values()).filter(\n (agent): agent is CustomSkill => agent instanceof CustomSkill\n );\n }\n\n // Backward compatibility alias\n getCustomAgents(): CustomSkill[] {\n return this.getCustomSkills();\n }\n\n registerAgent(agent: Agent): void {\n this.agents.set(agent.name, agent);\n console.error(`Registered custom skill: ${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 CustomSkill,\n }));\n }\n\n /**\n * Check if an agent is a custom skill\n */\n isCustomSkill(name: string): boolean {\n const agent = this.agents.get(name);\n return agent instanceof CustomSkill;\n }\n\n // Backward compatibility alias\n isCustomAgent(name: string): boolean {\n return this.isCustomSkill(name);\n }\n\n /**\n * Get custom skill metadata\n */\n getCustomSkillMetadata(name: string): ReturnType<CustomSkill['getMetadata']> | null {\n const agent = this.agents.get(name);\n if (agent instanceof CustomSkill) {\n return agent.getMetadata();\n }\n return null;\n }\n\n // Backward compatibility alias\n getCustomAgentMetadata(name: string): ReturnType<CustomSkill['getMetadata']> | null {\n return this.getCustomSkillMetadata(name);\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"],"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,sBAAsB;AAAA,IAC9E,EAAE,SAAS,wCAAwC,QAAQ,mBAAmB;AAAA,IAC9E,EAAE,SAAS,4BAA4B,QAAQ,iBAAiB;AAAA,IAChE,EAAE,SAAS,iCAAiC,QAAQ,gBAAgB;AAAA,IACpE,EAAE,SAAS,uCAAuC,QAAQ,iBAAiB;AAAA,IAC3E,EAAE,SAAS,uBAAuB,QAAQ,uBAAuB;AAAA,IACjE,EAAE,SAAS,4BAA4B,QAAQ,YAAY;AAAA,EAC7D;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