@triedotdev/mcp 1.0.93 → 1.0.97

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.
Files changed (84) hide show
  1. package/README.md +145 -137
  2. package/dist/chunk-APMV77PU.js +313 -0
  3. package/dist/chunk-APMV77PU.js.map +1 -0
  4. package/dist/{chunk-MZI46HQT.js → chunk-B3MNN3XB.js} +13 -18
  5. package/dist/{chunk-MZI46HQT.js.map → chunk-B3MNN3XB.js.map} +1 -1
  6. package/dist/{chunk-5Z7O66DE.js → chunk-F4NJ4CBP.js} +2 -2
  7. package/dist/{chunk-YTJXD664.js → chunk-FNCCZ3XB.js} +1222 -75
  8. package/dist/chunk-FNCCZ3XB.js.map +1 -0
  9. package/dist/chunk-G76DYVGX.js +136 -0
  10. package/dist/chunk-G76DYVGX.js.map +1 -0
  11. package/dist/chunk-HSNE46VE.js +956 -0
  12. package/dist/chunk-HSNE46VE.js.map +1 -0
  13. package/dist/{chunk-LVVG2DMW.js → chunk-IXO4G4D3.js} +2 -2
  14. package/dist/{chunk-LP4MVJDW.js → chunk-JDHR5BDR.js} +2 -3
  15. package/dist/chunk-NIASHOAB.js +1304 -0
  16. package/dist/chunk-NIASHOAB.js.map +1 -0
  17. package/dist/{chunk-NMGINYYX.js → chunk-OVRG5RP3.js} +6 -7
  18. package/dist/chunk-OVRG5RP3.js.map +1 -0
  19. package/dist/{chunk-T5UOH56R.js → chunk-R3I2GCZC.js} +3 -3
  20. package/dist/{chunk-RDOJCRKJ.js → chunk-R4AAPFXC.js} +2 -2
  21. package/dist/{chunk-R6AUYN3R.js → chunk-SLL2MDJD.js} +786 -4668
  22. package/dist/chunk-SLL2MDJD.js.map +1 -0
  23. package/dist/cli/create-agent.js +931 -7
  24. package/dist/cli/create-agent.js.map +1 -1
  25. package/dist/cli/main.js +151 -383
  26. package/dist/cli/main.js.map +1 -1
  27. package/dist/cli/yolo-daemon.js +13 -20
  28. package/dist/cli/yolo-daemon.js.map +1 -1
  29. package/dist/{goal-manager-ESJCJXFS.js → goal-manager-LAOT4QQX.js} +6 -6
  30. package/dist/guardian-agent-M352CBE5.js +19 -0
  31. package/dist/index.js +1025 -1550
  32. package/dist/index.js.map +1 -1
  33. package/dist/{issue-store-JZ2LCQEG.js → issue-store-W2X33X2X.js} +4 -4
  34. package/dist/{progress-PH6NNWZM.js → progress-PQVEM7BR.js} +2 -2
  35. package/dist/{vibe-code-signatures-K4UIWKJZ.js → vibe-code-signatures-ELEWJFGZ.js} +3 -3
  36. package/dist/{vulnerability-signatures-ZKVLMBRG.js → vulnerability-signatures-EIJQX2TS.js} +3 -3
  37. package/dist/workers/agent-worker.js +2 -11
  38. package/dist/workers/agent-worker.js.map +1 -1
  39. package/package.json +2 -2
  40. package/dist/agent-smith-QYDXPFPJ.js +0 -14
  41. package/dist/agent-smith-runner-GXGDJTSR.js +0 -573
  42. package/dist/agent-smith-runner-GXGDJTSR.js.map +0 -1
  43. package/dist/cache-manager-7SKX3IGO.js +0 -10
  44. package/dist/chunk-74NPKTZV.js +0 -141
  45. package/dist/chunk-74NPKTZV.js.map +0 -1
  46. package/dist/chunk-BG2BHWCC.js +0 -10879
  47. package/dist/chunk-BG2BHWCC.js.map +0 -1
  48. package/dist/chunk-CUXXRM3T.js +0 -2124
  49. package/dist/chunk-CUXXRM3T.js.map +0 -1
  50. package/dist/chunk-D25EIBPO.js +0 -183
  51. package/dist/chunk-D25EIBPO.js.map +0 -1
  52. package/dist/chunk-F55XBLIA.js +0 -536
  53. package/dist/chunk-F55XBLIA.js.map +0 -1
  54. package/dist/chunk-HFQ5ORON.js +0 -279
  55. package/dist/chunk-HFQ5ORON.js.map +0 -1
  56. package/dist/chunk-IOUOVBJZ.js +0 -175
  57. package/dist/chunk-IOUOVBJZ.js.map +0 -1
  58. package/dist/chunk-KWDNYWOR.js +0 -2270
  59. package/dist/chunk-KWDNYWOR.js.map +0 -1
  60. package/dist/chunk-LT7MKIXU.js +0 -266
  61. package/dist/chunk-LT7MKIXU.js.map +0 -1
  62. package/dist/chunk-MURGTWG4.js +0 -279
  63. package/dist/chunk-MURGTWG4.js.map +0 -1
  64. package/dist/chunk-NMGINYYX.js.map +0 -1
  65. package/dist/chunk-R6AUYN3R.js.map +0 -1
  66. package/dist/chunk-SJFJ6GLR.js +0 -955
  67. package/dist/chunk-SJFJ6GLR.js.map +0 -1
  68. package/dist/chunk-YTJXD664.js.map +0 -1
  69. package/dist/git-PZV3BBYI.js +0 -29
  70. package/dist/guardian-agent-ZHJXLBOU.js +0 -21
  71. package/dist/progress-PH6NNWZM.js.map +0 -1
  72. package/dist/vibe-code-signatures-K4UIWKJZ.js.map +0 -1
  73. package/dist/vulnerability-signatures-ZKVLMBRG.js.map +0 -1
  74. /package/dist/{chunk-5Z7O66DE.js.map → chunk-F4NJ4CBP.js.map} +0 -0
  75. /package/dist/{chunk-LVVG2DMW.js.map → chunk-IXO4G4D3.js.map} +0 -0
  76. /package/dist/{chunk-LP4MVJDW.js.map → chunk-JDHR5BDR.js.map} +0 -0
  77. /package/dist/{chunk-T5UOH56R.js.map → chunk-R3I2GCZC.js.map} +0 -0
  78. /package/dist/{chunk-RDOJCRKJ.js.map → chunk-R4AAPFXC.js.map} +0 -0
  79. /package/dist/{agent-smith-QYDXPFPJ.js.map → goal-manager-LAOT4QQX.js.map} +0 -0
  80. /package/dist/{cache-manager-7SKX3IGO.js.map → guardian-agent-M352CBE5.js.map} +0 -0
  81. /package/dist/{git-PZV3BBYI.js.map → issue-store-W2X33X2X.js.map} +0 -0
  82. /package/dist/{goal-manager-ESJCJXFS.js.map → progress-PQVEM7BR.js.map} +0 -0
  83. /package/dist/{guardian-agent-ZHJXLBOU.js.map → vibe-code-signatures-ELEWJFGZ.js.map} +0 -0
  84. /package/dist/{issue-store-JZ2LCQEG.js.map → vulnerability-signatures-EIJQX2TS.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/utils/project-info.ts","../src/utils/context-state.ts","../src/skills/built-in/security.ts","../src/skills/built-in/privacy.ts","../src/skills/built-in/typecheck.ts","../src/skills/built-in/comprehension.ts","../src/skills/built-in/accessibility.ts","../src/skills/built-in/design-engineer.ts","../src/skills/built-in/legal.ts","../src/skills/built-in/test.ts","../src/skills/built-in/software-architect.ts","../src/skills/built-in/devops.ts","../src/skills/built-in/bug-finding.ts","../src/skills/built-in/user-testing.ts","../src/skills/built-in/trie-clean.ts","../src/skills/built-in/soc2.ts","../src/skills/built-in/super-reviewer.ts","../src/skills/built-in/performance.ts","../src/skills/built-in/e2e.ts","../src/skills/built-in/visual-qa.ts","../src/skills/built-in/data-flow.ts","../src/skills/built-in/moneybags.ts","../src/skills/built-in/production-ready.ts","../src/skills/installer.ts","../src/skills/parser.ts","../src/skills/security-scanner.ts","../src/skills/gating.ts","../src/skills/built-in/skill-review.ts","../src/skills/built-in/custom-skill.ts","../src/skills/built-in/registry.ts"],"sourcesContent":["/**\n * Project Info Manager\n * \n * Manages the .trie/PROJECT.md file that stores user-defined project context.\n * Unlike AGENTS.md (auto-generated), PROJECT.md is fully user-controlled.\n */\n\nimport { readFile, writeFile, mkdir } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { getWorkingDirectory, getTrieDirectory } from './workspace.js';\n\nconst PROJECT_MD_PATH = 'PROJECT.md';\n\n/**\n * Default PROJECT.md template\n */\nexport function getProjectTemplate(): string {\n return `# Project Information\n\n> This file stores important project context for AI assistants.\n> Edit freely - this file is yours, not auto-generated.\n> Available via MCP resource: \\`trie://project\\`\n\n---\n\n## Project Overview\n\n<!-- Describe your project's purpose and goals -->\n\n[Add project description here]\n\n---\n\n## Technology Stack\n\n<!-- List frameworks, languages, databases, cloud services, etc. -->\n\n- **Language:** \n- **Framework:** \n- **Database:** \n- **Hosting:** \n\n---\n\n## Architecture\n\n<!-- Key patterns, architectural decisions, and system design -->\n\n[Describe your architecture here]\n\n---\n\n## Coding Conventions\n\n<!-- Style guidelines, naming conventions, patterns to follow -->\n\n- \n- \n- \n\n---\n\n## Environment\n\n<!-- URLs, API endpoints, deployment info -->\n\n| Environment | URL | Notes |\n|-------------|-----|-------|\n| Development | | |\n| Staging | | |\n| Production | | |\n\n---\n\n## Team\n\n<!-- Ownership, contacts, responsibilities -->\n\n- **Owner:** \n- **Team:** \n\n---\n\n## Compliance\n\n<!-- HIPAA, SOC2, GDPR, PCI-DSS requirements if applicable -->\n\n- [ ] GDPR\n- [ ] SOC2\n- [ ] HIPAA\n- [ ] PCI-DSS\n\n---\n\n## AI Instructions\n\n<!-- Special instructions for AI assistants working on this project -->\n\nWhen working on this project, AI assistants should:\n\n1. \n2. \n3. \n\n---\n\n*This file is read by Trie agents and exposed via \\`trie://project\\` MCP resource.*\n*Edit this file to provide context to Claude Code, Cursor, GitHub Actions, and other AI tools.*\n`;\n}\n\n/**\n * Check if PROJECT.md exists\n */\nexport function projectInfoExists(workDir?: string): boolean {\n const dir = workDir || getWorkingDirectory(undefined, true);\n const projectPath = join(getTrieDirectory(dir), PROJECT_MD_PATH);\n return existsSync(projectPath);\n}\n\n/**\n * Load PROJECT.md content\n */\nexport async function loadProjectInfo(workDir?: string): Promise<string | null> {\n const dir = workDir || getWorkingDirectory(undefined, true);\n const projectPath = join(getTrieDirectory(dir), PROJECT_MD_PATH);\n \n try {\n if (!existsSync(projectPath)) {\n return null;\n }\n return await readFile(projectPath, 'utf-8');\n } catch {\n return null;\n }\n}\n\n/**\n * Save PROJECT.md content\n */\nexport async function saveProjectInfo(content: string, workDir?: string): Promise<void> {\n const dir = workDir || getWorkingDirectory(undefined, true);\n const trieDir = getTrieDirectory(dir);\n const projectPath = join(trieDir, PROJECT_MD_PATH);\n \n // Ensure .trie directory exists\n await mkdir(trieDir, { recursive: true });\n \n await writeFile(projectPath, content, 'utf-8');\n}\n\n/**\n * Initialize PROJECT.md with template\n */\nexport async function initProjectInfo(workDir?: string): Promise<{ created: boolean; path: string }> {\n const dir = workDir || getWorkingDirectory(undefined, true);\n const projectPath = join(getTrieDirectory(dir), PROJECT_MD_PATH);\n \n if (existsSync(projectPath)) {\n return { created: false, path: projectPath };\n }\n \n await saveProjectInfo(getProjectTemplate(), dir);\n return { created: true, path: projectPath };\n}\n\n/**\n * Get a specific section from PROJECT.md\n */\nexport async function getProjectSection(sectionName: string, workDir?: string): Promise<string | null> {\n const content = await loadProjectInfo(workDir);\n if (!content) return null;\n \n // Find section by header\n const sectionRegex = new RegExp(\n `## ${escapeRegex(sectionName)}\\\\s*\\\\n([\\\\s\\\\S]*?)(?=\\\\n## |\\\\n---\\\\s*$|$)`,\n 'i'\n );\n \n const match = content.match(sectionRegex);\n if (match?.[1]) {\n return match[1].trim();\n }\n \n return null;\n}\n\n/**\n * Update a specific section in PROJECT.md\n */\nexport async function updateProjectSection(\n sectionName: string, \n newContent: string, \n workDir?: string\n): Promise<boolean> {\n let content = await loadProjectInfo(workDir);\n \n if (!content) {\n // Initialize with template first\n await initProjectInfo(workDir);\n content = await loadProjectInfo(workDir);\n if (!content) return false;\n }\n \n // Find and replace section content\n const sectionRegex = new RegExp(\n `(## ${escapeRegex(sectionName)}\\\\s*\\\\n)([\\\\s\\\\S]*?)((?=\\\\n## )|(?=\\\\n---\\\\s*$)|$)`,\n 'i'\n );\n \n if (content.match(sectionRegex)) {\n const updatedContent = content.replace(sectionRegex, `$1\\n${newContent}\\n\\n$3`);\n await saveProjectInfo(updatedContent, workDir);\n return true;\n }\n \n return false;\n}\n\n/**\n * Append content to a section\n */\nexport async function appendToSection(\n sectionName: string,\n contentToAdd: string,\n workDir?: string\n): Promise<boolean> {\n const currentContent = await getProjectSection(sectionName, workDir);\n if (currentContent === null) return false;\n \n const newContent = currentContent + '\\n' + contentToAdd;\n return updateProjectSection(sectionName, newContent, workDir);\n}\n\n/**\n * Get all section names from PROJECT.md\n */\nexport async function getProjectSections(workDir?: string): Promise<string[]> {\n const content = await loadProjectInfo(workDir);\n if (!content) return [];\n \n const sectionRegex = /^## (.+)$/gm;\n const sections: string[] = [];\n let match;\n \n while ((match = sectionRegex.exec(content)) !== null) {\n if (match[1]) {\n sections.push(match[1].trim());\n }\n }\n \n return sections;\n}\n\n/**\n * Get project info as structured data (for JSON responses)\n */\nexport async function getProjectInfoStructured(workDir?: string): Promise<{\n exists: boolean;\n path: string;\n sections: Record<string, string>;\n raw: string | null;\n}> {\n const dir = workDir || getWorkingDirectory(undefined, true);\n const projectPath = join(getTrieDirectory(dir), PROJECT_MD_PATH);\n const content = await loadProjectInfo(dir);\n \n if (!content) {\n return {\n exists: false,\n path: projectPath,\n sections: {},\n raw: null,\n };\n }\n \n const sectionNames = await getProjectSections(dir);\n const sections: Record<string, string> = {};\n \n for (const name of sectionNames) {\n const sectionContent = await getProjectSection(name, dir);\n if (sectionContent) {\n sections[name] = sectionContent;\n }\n }\n \n return {\n exists: true,\n path: projectPath,\n sections,\n raw: content,\n };\n}\n\n/**\n * Escape special regex characters\n */\nfunction escapeRegex(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n}\n","/**\n * Context State Manager\n * \n * Manages the .trie/AGENTS.md file that provides context to AI coding assistants.\n * Updates automatically when agents run to keep context current.\n * Also integrates with issue memory and cross-project tracking.\n * \n * Phase 1 Hardening:\n * - Atomic writes to prevent corruption\n */\n\nimport { readFile, mkdir } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join, basename } from 'path';\nimport { getWorkingDirectory, getTrieDirectory } from './workspace.js';\nimport type { AgentResult } from '../types/index.js';\nimport type { SkillRecord } from '../types/external-skill.js';\nimport { loadProjectInfo, projectInfoExists } from './project-info.js';\nimport { storeIssues, autoResolveIssues, getIssueHash } from '../memory/issue-store.js';\nimport { recordToGlobalMemory, updateGlobalMemoryMd } from '../memory/global-memory.js';\nimport { atomicWriteJSON, atomicWriteFile } from './atomic-write.js';\n\nexport interface ScanSummary {\n timestamp: string;\n agents: string[];\n filesScanned: number;\n issues: {\n critical: number;\n serious: number;\n moderate: number;\n low: number;\n total: number;\n };\n duration: number;\n hotFiles: Array<{ file: string; issueCount: number }>;\n}\n\nexport interface ContextState {\n lastScan: ScanSummary | null;\n healthScore: number;\n activePriorities: string[];\n contextSignals: Record<string, boolean>;\n agentStatus: Record<string, {\n lastRun: string | null;\n issuesFound: number;\n skillsApplied?: string[];\n }>;\n scanHistory: ScanSummary[];\n customAgents: string[];\n skills: Record<string, SkillRecord>;\n environment?: string;\n}\n\nconst AGENTS_MD_PATH = 'AGENTS.md';\nconst STATE_JSON_PATH = 'state.json';\n\n/**\n * Load current context state\n */\nexport async function loadContextState(): Promise<ContextState> {\n const workDir = getWorkingDirectory(undefined, true);\n const statePath = join(getTrieDirectory(workDir), STATE_JSON_PATH);\n const defaults = getDefaultState();\n \n try {\n if (existsSync(statePath)) {\n const content = await readFile(statePath, 'utf-8');\n const loaded = JSON.parse(content);\n // Merge with defaults to ensure new fields exist\n return {\n ...defaults,\n ...loaded,\n skills: loaded.skills || defaults.skills,\n };\n }\n } catch {\n // Return default state\n }\n \n return defaults;\n}\n\n/**\n * Save context state using atomic write\n */\nexport async function saveContextState(state: ContextState): Promise<void> {\n const workDir = getWorkingDirectory(undefined, true);\n const trieDir = getTrieDirectory(workDir);\n const statePath = join(trieDir, STATE_JSON_PATH);\n \n // Ensure directory exists\n await mkdir(trieDir, { recursive: true });\n \n // Use atomic write to prevent corruption\n await atomicWriteJSON(statePath, state);\n}\n\n/**\n * Update context state after a scan\n */\nexport async function updateContextAfterScan(\n results: AgentResult[],\n filesScanned: number,\n contextSignals: Record<string, boolean>,\n duration: number,\n scannedFiles?: string[]\n): Promise<void> {\n const state = await loadContextState();\n const workDir = getWorkingDirectory(undefined, true);\n const now = new Date().toISOString();\n \n // Calculate issue counts\n const allIssues = results.flatMap(r => r.issues);\n const issueCounts = {\n critical: allIssues.filter(i => i.severity === 'critical').length,\n serious: allIssues.filter(i => i.severity === 'serious').length,\n moderate: allIssues.filter(i => i.severity === 'moderate').length,\n low: allIssues.filter(i => i.severity === 'low').length,\n total: allIssues.length,\n };\n \n // Find hot files\n const fileIssueMap = new Map<string, number>();\n for (const issue of allIssues) {\n const count = fileIssueMap.get(issue.file) || 0;\n fileIssueMap.set(issue.file, count + 1);\n }\n const hotFiles = Array.from(fileIssueMap.entries())\n .sort((a, b) => b[1] - a[1])\n .slice(0, 10)\n .map(([file, issueCount]) => ({ file, issueCount }));\n \n // Create scan summary\n const scanSummary: ScanSummary = {\n timestamp: now,\n agents: results.map(r => r.agent),\n filesScanned,\n issues: issueCounts,\n duration,\n hotFiles,\n };\n \n // Update agent status\n for (const result of results) {\n state.agentStatus[result.agent] = {\n lastRun: now,\n issuesFound: result.issues.length,\n };\n }\n \n // Calculate health score (0-100)\n // Penalize critical issues heavily, serious issues moderately\n const criticalPenalty = issueCounts.critical * 25;\n const seriousPenalty = issueCounts.serious * 10;\n const moderatePenalty = issueCounts.moderate * 3;\n const lowPenalty = issueCounts.low * 1;\n const totalPenalty = Math.min(100, criticalPenalty + seriousPenalty + moderatePenalty + lowPenalty);\n state.healthScore = Math.max(0, 100 - totalPenalty);\n \n // Update priorities based on issues\n state.activePriorities = generatePriorities(issueCounts, contextSignals);\n \n // Update context signals\n state.contextSignals = { ...state.contextSignals, ...contextSignals };\n \n // Update scan history (keep last 20)\n state.scanHistory = [scanSummary, ...state.scanHistory.slice(0, 19)];\n state.lastScan = scanSummary;\n \n // Save state\n await saveContextState(state);\n \n // Update AGENTS.md\n await updateAgentsMd(state);\n \n // Store issues to memory\n const projectName = basename(workDir);\n if (allIssues.length > 0) {\n try {\n await storeIssues(allIssues, projectName, workDir);\n await recordToGlobalMemory(allIssues, projectName, workDir, state.healthScore);\n await updateGlobalMemoryMd();\n } catch {\n // Memory storage is non-critical, don't fail the scan\n }\n }\n \n // Auto-resolve issues that are no longer detected in scanned files\n if (scannedFiles && scannedFiles.length > 0) {\n try {\n // Build set of hashes from current scan\n const currentHashes = new Set(allIssues.map(issue => getIssueHash(issue)));\n const { resolved } = await autoResolveIssues(currentHashes, scannedFiles, workDir);\n if (resolved > 0) {\n // Log auto-resolution in non-interactive mode\n const { isInteractiveMode } = await import('./progress.js');\n if (!isInteractiveMode()) {\n console.error(` ✓ Auto-resolved ${resolved} issue${resolved > 1 ? 's' : ''} no longer detected`);\n }\n }\n } catch {\n // Auto-resolution is non-critical\n }\n }\n}\n\n/**\n * Update the AGENTS.md file with current state\n */\nasync function updateAgentsMd(state: ContextState): Promise<void> {\n const workDir = getWorkingDirectory(undefined, true);\n const mdPath = join(getTrieDirectory(workDir), AGENTS_MD_PATH);\n \n let content: string;\n try {\n content = await readFile(mdPath, 'utf-8');\n } catch {\n // Use template if file doesn't exist\n content = getAgentsMdTemplate();\n }\n \n // Update sections\n content = updateSection(content, 'Project State', generateProjectStateTable(state));\n content = updateSection(content, 'Active Priorities', generatePrioritiesList(state));\n content = updateSection(content, 'Agent Status', generateAgentStatusTable(state));\n content = updateSection(content, 'Recent Scan History', generateScanHistoryTable(state));\n content = updateSection(content, 'Context Signals Detected', generateContextSignals(state));\n content = updateSection(content, 'Risk Assessment', generateRiskAssessment(state));\n content = updateSection(content, 'Hot Files', generateHotFilesSection(state));\n \n // Update last updated timestamp\n content = content.replace(\n /Last updated:.*$/m,\n `Last updated: ${new Date().toISOString()}`\n );\n \n // Use atomic write to prevent corruption\n await atomicWriteFile(mdPath, content);\n}\n\n/**\n * Update a specific section in the markdown\n */\nfunction updateSection(content: string, sectionName: string, newContent: string): string {\n // Look for the section header and replace content until the next section\n const sectionRegex = new RegExp(\n `(### ${sectionName}[\\\\s\\\\S]*?)(?=###|---|\\n## |$)`,\n 'g'\n );\n \n const replacement = `### ${sectionName}\\n${newContent}\\n\\n`;\n \n if (content.match(sectionRegex)) {\n return content.replace(sectionRegex, replacement);\n }\n \n // Section doesn't exist, don't add it\n return content;\n}\n\n/**\n * Generate the project state table\n */\nfunction generateProjectStateTable(state: ContextState): string {\n const lastScan = state.lastScan;\n const lastScanDate = lastScan ? new Date(lastScan.timestamp).toLocaleString() : 'Never';\n const criticalCount = lastScan?.issues.critical ?? 0;\n const totalTasks = lastScan?.issues.total ?? 0;\n \n return `| Metric | Value | Updated |\n|--------|-------|---------|\n| Last Scan | ${lastScanDate} | ${lastScan ? 'Auto' : '-'} |\n| Critical Issues | ${criticalCount} | ${lastScan ? 'Auto' : '-'} |\n| Open Tasks | ${totalTasks} | ${lastScan ? 'Auto' : '-'} |\n| Health Score | ${state.healthScore}% | ${lastScan ? 'Auto' : '-'} |`;\n}\n\n/**\n * Generate priorities list\n */\nfunction generatePrioritiesList(state: ContextState): string {\n if (state.activePriorities.length === 0) {\n return '_No active priorities. Run a scan to identify issues._';\n }\n \n return state.activePriorities\n .map((p, i) => `${i + 1}. ${p}`)\n .join('\\n');\n}\n\n/**\n * Generate priorities based on scan results\n */\nfunction generatePriorities(\n issues: { critical: number; serious: number; moderate: number; low: number },\n contextSignals: Record<string, boolean>\n): string[] {\n const priorities: string[] = [];\n \n if (issues.critical > 0) {\n priorities.push(`Fix ${issues.critical} critical security issue${issues.critical > 1 ? 's' : ''} immediately`);\n }\n \n if (issues.serious > 0) {\n priorities.push(`Address ${issues.serious} serious issue${issues.serious > 1 ? 's' : ''} before deployment`);\n }\n \n if (contextSignals.touchesAuth && issues.critical === 0) {\n priorities.push('Auth code reviewed - continue monitoring');\n }\n \n if (contextSignals.touchesPayments) {\n priorities.push('💳 Payment code detected - ensure PCI compliance');\n }\n \n if (contextSignals.touchesUserData) {\n priorities.push('User data handling detected - verify privacy compliance');\n }\n \n if (issues.moderate > 5) {\n priorities.push(`Schedule time to address ${issues.moderate} moderate issues`);\n }\n \n if (priorities.length === 0) {\n priorities.push('No critical issues - focus on feature development');\n }\n \n return priorities.slice(0, 5);\n}\n\n/**\n * Generate agent status table\n */\nfunction generateAgentStatusTable(state: ContextState): string {\n const builtInAgents = [\n 'security', 'privacy', 'legal', 'accessibility', 'bugs',\n 'design', 'architecture', 'performance', 'devops', 'soc2',\n 'e2e', 'typecheck', 'visual-qa', 'data-flow'\n ];\n \n let table = `| Agent | Status | Last Run | Issues Found |\n|-------|--------|----------|--------------|`;\n \n for (const agent of builtInAgents) {\n const status = state.agentStatus[agent];\n const lastRun = status?.lastRun \n ? new Date(status.lastRun).toLocaleDateString()\n : 'Never';\n const issues = status?.issuesFound ?? '-';\n const statusEmoji = status ? '✅' : '⏸️';\n \n table += `\\n| ${agent} | ${statusEmoji} Ready | ${lastRun} | ${issues} |`;\n }\n \n return table;\n}\n\n/**\n * Generate scan history table\n */\nfunction generateScanHistoryTable(state: ContextState): string {\n if (state.scanHistory.length === 0) {\n return `| Date | Agents | Files | Issues | Duration |\n|------|--------|-------|--------|----------|\n| - | - | - | - | - |`;\n }\n \n let table = `| Date | Agents | Files | Issues | Duration |\n|------|--------|-------|--------|----------|`;\n \n for (const scan of state.scanHistory.slice(0, 10)) {\n const date = new Date(scan.timestamp).toLocaleDateString();\n const agents = scan.agents.slice(0, 3).join(', ') + (scan.agents.length > 3 ? '...' : '');\n const duration = `${(scan.duration / 1000).toFixed(1)}s`;\n \n table += `\\n| ${date} | ${agents} | ${scan.filesScanned} | ${scan.issues.total} | ${duration} |`;\n }\n \n return table;\n}\n\n/**\n * Generate context signals section\n */\nfunction generateContextSignals(state: ContextState): string {\n const signals = [\n 'touchesAuth',\n 'touchesPayments', \n 'touchesUserData',\n 'touchesAPI',\n 'touchesDatabase',\n 'touchesCrypto'\n ];\n \n return signals\n .map(s => {\n const value = state.contextSignals[s];\n const emoji = value === true ? '✅' : value === false ? '❌' : '❓';\n return `- \\`${s}\\`: ${emoji} ${value === undefined ? 'Unknown' : value ? 'Yes' : 'No'}`;\n })\n .join('\\n');\n}\n\n/**\n * Generate risk assessment section\n */\nfunction generateRiskAssessment(state: ContextState): string {\n const score = state.healthScore;\n let riskLevel: string;\n let confidence: number;\n \n if (state.lastScan === null) {\n return `- Overall Risk: Unknown\n- Confidence: 0%`;\n }\n \n if (score >= 90) {\n riskLevel = '🟢 Low';\n confidence = 95;\n } else if (score >= 70) {\n riskLevel = '🟡 Medium';\n confidence = 85;\n } else if (score >= 50) {\n riskLevel = '🟠 High';\n confidence = 80;\n } else {\n riskLevel = '🔴 Critical';\n confidence = 90;\n }\n \n return `- Overall Risk: ${riskLevel}\n- Health Score: ${score}%\n- Confidence: ${confidence}%`;\n}\n\n/**\n * Generate hot files section\n */\nfunction generateHotFilesSection(state: ContextState): string {\n if (!state.lastScan || state.lastScan.hotFiles.length === 0) {\n return '_Run a scan to identify hot files._';\n }\n \n return state.lastScan.hotFiles\n .map(f => `- \\`${f.file}\\` - ${f.issueCount} issue${f.issueCount > 1 ? 's' : ''}`)\n .join('\\n');\n}\n\n/**\n * Get default state\n */\nfunction getDefaultState(): ContextState {\n return {\n lastScan: null,\n healthScore: 0,\n activePriorities: [\n 'Initial setup required - run first scan with `trie scan`',\n 'Configure agents in `.trie/config.json`',\n 'Set up CI/CD integration'\n ],\n contextSignals: {},\n agentStatus: {},\n scanHistory: [],\n customAgents: [],\n skills: {},\n environment: detectEnvironment(),\n };\n}\n\n/**\n * Detect the current execution environment\n */\nexport function detectEnvironment(): string {\n if (process.env.GITHUB_ACTIONS) return 'github-actions';\n if (process.env.GITLAB_CI) return 'gitlab-ci';\n if (process.env.CI) return 'ci';\n const parent = process.env._ || '';\n if (parent.includes('cursor')) return 'cursor';\n if (parent.includes('claude')) return 'claude-code';\n return 'cli';\n}\n\n/**\n * Record skill installation in context state\n */\nexport async function recordSkillInstalled(params: {\n name: string;\n source: string;\n}): Promise<void> {\n const state = await loadContextState();\n state.skills[params.name] = {\n source: params.source,\n installedAt: new Date().toISOString(),\n timesApplied: 0,\n appliedBy: [],\n };\n await saveContextState(state);\n}\n\n/**\n * Record skill usage by an agent\n */\nexport async function recordSkillUsage(params: {\n skillNames: string[];\n agentName: string;\n}): Promise<void> {\n const state = await loadContextState();\n const now = new Date().toISOString();\n \n for (const skillName of params.skillNames) {\n const skillRecord = state.skills[skillName];\n if (skillRecord) {\n skillRecord.timesApplied++;\n skillRecord.lastApplied = now;\n if (!skillRecord.appliedBy.includes(params.agentName)) {\n skillRecord.appliedBy.push(params.agentName);\n }\n }\n }\n \n const agentStatus = state.agentStatus[params.agentName];\n if (agentStatus) {\n agentStatus.skillsApplied = params.skillNames;\n }\n \n await saveContextState(state);\n}\n\n/**\n * Get the AGENTS.md template\n */\nfunction getAgentsMdTemplate(): string {\n return `# Trie Agent Context\n\n> **Auto-generated file** - Updated automatically when agents run.\n> Last updated: Never (initial state)\n\nThis file provides prioritized context for all AI coding assistants working with this codebase.\nAgents should read this file first and update it after completing scans.\n\n---\n\n## Quick Context (Read First)\n\n### Project State\n| Metric | Value | Updated |\n|--------|-------|---------|\n| Last Scan | Never | - |\n| Critical Issues | 0 | - |\n| Open Tasks | 0 | - |\n| Health Score | Unknown | - |\n\n### Active Priorities\n1. Initial setup required - run first scan with \\`trie scan\\`\n2. Configure agents in \\`.trie/config.json\\`\n3. Set up CI/CD integration\n\n### Hot Files\n_Run a scan to identify hot files._\n\n---\n\n## Agent Status\n\n### Agent Status\n| Agent | Status | Last Run | Issues Found |\n|-------|--------|----------|--------------|\n| security | Ready | Never | - |\n| privacy | Ready | Never | - |\n| bugs | Ready | Never | - |\n\n### Recent Scan History\n| Date | Agents | Files | Issues | Duration |\n|------|--------|-------|--------|----------|\n| - | - | - | - | - |\n\n---\n\n## Context Analysis\n\n### Context Signals Detected\n- \\`touchesAuth\\`: Unknown\n- \\`touchesPayments\\`: Unknown\n- \\`touchesUserData\\`: Unknown\n- \\`touchesAPI\\`: Unknown\n- \\`touchesDatabase\\`: Unknown\n- \\`touchesCrypto\\`: Unknown\n\n### Risk Assessment\n- Overall Risk: Unknown\n- Confidence: 0%\n\n---\n\n*This file is maintained by Trie agents. Manual edits will be preserved in non-auto sections.*\n`;\n}\n\n/**\n * Add custom skill to context state\n */\nexport async function addCustomAgentToContext(agentName: string): Promise<void> {\n const state = await loadContextState();\n \n if (!state.customAgents.includes(agentName)) {\n state.customAgents.push(agentName);\n await saveContextState(state);\n }\n}\n\n/**\n * Get context state for AI assistants (formatted summary)\n */\nexport async function getContextForAI(): Promise<string> {\n const state = await loadContextState();\n const workDir = getWorkingDirectory(undefined, true);\n \n const lines: string[] = [];\n \n // Include PROJECT.md content first (user-defined context takes priority)\n if (projectInfoExists(workDir)) {\n const projectInfo = await loadProjectInfo(workDir);\n if (projectInfo) {\n lines.push(projectInfo);\n lines.push('');\n lines.push('---');\n lines.push('');\n }\n }\n \n // Add Trie scan context\n lines.push(\n '## Trie Scan Context',\n '',\n `**Health Score:** ${state.healthScore}%`,\n `**Last Scan:** ${state.lastScan ? new Date(state.lastScan.timestamp).toLocaleString() : 'Never'}`,\n '',\n '**Active Priorities:**',\n ...state.activePriorities.map(p => `- ${p}`),\n ''\n );\n \n if (state.lastScan) {\n lines.push(\n '**Recent Issues:**',\n `- Critical: ${state.lastScan.issues.critical}`,\n `- Serious: ${state.lastScan.issues.serious}`,\n `- Moderate: ${state.lastScan.issues.moderate}`,\n `- Low: ${state.lastScan.issues.low}`,\n ''\n );\n \n if (state.lastScan.hotFiles.length > 0) {\n lines.push(\n '**Hot Files (most issues):**',\n ...state.lastScan.hotFiles.slice(0, 5).map(f => `- ${f.file}: ${f.issueCount} issues`),\n ''\n );\n }\n }\n \n return lines.join('\\n');\n}\n","import { BaseSkill, FileRelevance } from './base-skill.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 checks to avoid fixture false positives\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: /\\b(AKI|ASI|AGP|AID|ANP|ARO|AIP)A[A-Z0-9]{16}\\b/, severity: 'critical' as const, issue: 'AWS Access Key exposed', fix: 'Remove AWS key and rotate immediately. Use environment variables.' },\n { pattern: /aws_secret_access_key\\s*[:=]\\s*['\"][A-Za-z0-9/+=]{40}['\"]/i, severity: 'critical' as const, issue: 'AWS Secret Access Key exposed', fix: 'Remove AWS secret and rotate immediately. Use environment variables or a secret manager.' },\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: /github_pat_[A-Za-z0-9_]{70,}/, severity: 'critical' as const, issue: 'GitHub fine-grained 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: /rk_live_[A-Za-z0-9]{24,}/, severity: 'critical' as const, issue: 'Stripe live restricted 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 SecuritySkill extends BaseSkill {\n name = 'security';\n description = 'AI-powered security analysis: vulnerabilities, injection risks, authentication issues';\n version = '2.0.0';\n override author = 'Trie Agent';\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 if (this.isTestFile(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\n// Backward compatibility export\nexport { SecuritySkill as SecurityAgent };\n","import { BaseSkill, 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 PrivacySkill extends BaseSkill {\n name = 'privacy';\n description = 'AI-powered privacy analysis: GDPR, CCPA, PCI-DSS compliance';\n version = '2.0.0';\n override author = 'Trie Agent';\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\n// Backward compatibility export\nexport { PrivacySkill as PrivacyAgent };\n","import { BaseSkill } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\nimport { extname } from 'path';\nimport { isInteractiveMode } from '../../utils/progress.js';\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 TypeCheckSkill extends BaseSkill {\n name = 'typecheck';\n description = 'Catches type errors and ensures type safety';\n version = '1.0.0';\n override author = 'Trie Agent';\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 if (!isInteractiveMode()) {\n console.error(`TypeCheck Agent: Error reading file ${file}:`, error);\n }\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}\n\n// Backward compatibility export\nexport { TypeCheckSkill as TypeCheckAgent };\n","import { BaseSkill } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\n\nexport class ComprehensionSkill extends BaseSkill {\n name = 'comprehension';\n description = 'Explains what code does in plain language for non-technical builders';\n version = '1.0.0';\n override author = 'Trie Agent';\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}\n\n// Backward compatibility export\nexport { ComprehensionSkill as ComprehensionAgent };\n","import { BaseSkill } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\nimport { isInteractiveMode } from '../../utils/progress.js';\n\n// ============================================================================\n// WCAG 2.1 SEVERITY LEVELS — Mapped to WCAG Conformance\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\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.2.5': { name: 'Change on Request', level: 'AAA', description: 'Changes of context are initiated only by user request' },\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 AccessibilitySkill extends BaseSkill {\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 override author = 'Trie Agent';\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 if (!isInteractiveMode()) {\n console.error(`Accessibility Agent: Error reading file ${file}:`, error);\n }\n }\n }\n\n // Add accessibility summary if there are significant issues\n // NOTE: Summary should be low severity - it's informational, not a separate issue\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 const shouldTriggerVisualQA = criticalCount > 0 || seriousCount >= 2;\n \n let recommendation = `Review and fix accessibility issues starting with critical problems. Use axe-core or Lighthouse for additional validation.`;\n \n if (shouldTriggerVisualQA) {\n recommendation = `${recommendation}\\n\\nℹ️ Consider running 'trie_visual_qa_browser' to capture screenshots for Guardian visual analysis of these accessibility issues.`;\n }\n \n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low', // Summary is informational, not a blocker\n `Accessibility Score: ${score}/100 — ${criticalCount} critical, ${seriousCount} serious issues${shouldTriggerVisualQA ? ' (Visual QA recommended)' : ''}`,\n recommendation,\n files[0] || 'project',\n undefined,\n 0.60,\n undefined,\n false,\n { category: 'accessibility-summary' }\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') ?? line;\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') ?? line;\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') ?? line;\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\n// Backward compatibility export\nexport { AccessibilitySkill as AccessibilityAgent };\n","import { BaseSkill } 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 DesignEngineerSkill extends BaseSkill {\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 override author = 'Trie Agent';\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 // NOTE: Design health is informational, not a blocker - always use 'low' severity\n if (healthScore.score < 80 || healthScore.slopScore < 70) {\n const domainRecommendation = this.getDomainRecommendations(designContext);\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low', // Design scores are informational, not blockers\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.60, // Lower confidence for aggregate scores\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 'moderate', // Design issues should not be critical - reserved for security/data loss\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.75,\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 'low', // Design preference, not a real issue\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.65,\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 - NOTE: Design issues are NOT critical/serious security issues\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 'low', // Design suggestions should be low severity, not 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.70, // Lower confidence for design opinions\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\n// Backward compatibility export\nexport { DesignEngineerSkill as DesignEngineerAgent };\n","import { BaseSkill } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\n\nexport class LegalSkill extends BaseSkill {\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 override author = 'Trie Agent';\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 // Skip self-scanning to prevent false positives from detection code\n if (this.shouldExcludeTrieFile(file)) {\n continue;\n }\n\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 const hasKnownPaymentProcessor = /\\b(stripe|braintree|square|paypal)\\b/i.test(content);\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const trimmed = line.trim();\n\n // Ignore comments (marketing copy or examples inside comments create noise)\n if (trimmed.startsWith('//') || trimmed.startsWith('/*') || trimmed.startsWith('*') || trimmed.startsWith('<!--')) {\n continue;\n }\n\n // Common good-practice marketing claim; not an indicator of card handling\n if (/\\bno\\s+credit\\s+card\\s+required\\b/i.test(line)) {\n continue;\n }\n\n // Check for direct card handling (should use tokenization)\n //\n // Prior behavior was too naive: it flagged any mention of \"credit card\" or \"card number\",\n // including marketing copy. We now require *code-level* signals of card data handling.\n //\n // Avoid false positives:\n // - \"postalCode\" / \"billingZip\" alone are common in address forms (not payment-specific)\n // - \"expiry\" / \"expiration\" alone are common in tokens, sessions, cookies\n // - \"card\" alone matches UI components like \"dashboard card\", \"info card\"\n //\n // High-signal patterns (require multiple payment indicators or explicit card data fields):\n const hasExplicitCardDataField = \n // Explicit card number / CVV / CVC (very high signal)\n /\\b(cardNumber|card_number|card[-_]?num|ccNumber|cc_number)\\b/i.test(line) ||\n /\\b(cvv|cvc|securityCode|security_code|cardCode|card_code)\\b/i.test(line) ||\n // PAN (Primary Account Number) - very high signal\n /\\bpan\\b/i.test(line) && /\\b(card|payment|credit|debit)\\b/i.test(line);\n \n const hasCardExpiryInPaymentContext =\n // Expiry only counts if combined with payment-related terms\n /\\b(expMonth|expYear|exp_month|exp_year|cardExp|card_exp)\\b/i.test(line) ||\n (/\\b(expiry|expiration)\\b/i.test(line) && /\\b(card|payment|credit|billing)\\b/i.test(line));\n \n const hasCardHolderData =\n // Cardholder name is high signal\n /\\b(cardholderName|cardholder_name|cardHolder|card_holder)\\b/i.test(line);\n \n const isCardDataCodeSignal =\n hasExplicitCardDataField ||\n hasCardExpiryInPaymentContext ||\n hasCardHolderData ||\n // HTML/JSX form fields collecting card data (high-signal, very specific autocomplete values)\n /<input\\b[^>]*(autoComplete|autocomplete)\\s*=\\s*[\"'{](cc-number|cc-csc|cc-exp)[^\"'}]*[\"'}][^>]*>/i.test(line) ||\n // Server-side request body containing explicit card fields\n /\\b(req|request)\\.(body|query|params)\\.(cardNumber|cvv|cvc|ccNumber)\\b/i.test(line);\n\n // Low-signal marketing phrases should not trigger card-handling findings.\n const isLowSignalCardMention =\n /\\bcredit\\s*card\\b/i.test(line) || /\\bcard\\s*number\\b/i.test(line);\n\n if (!isCardDataCodeSignal) {\n // If it's only a low-signal mention (e.g., \"No credit card required\"), ignore.\n if (isLowSignalCardMention) continue;\n }\n\n if (isCardDataCodeSignal && !hasKnownPaymentProcessor) {\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 const lines = content.split('\\n');\n const isLikelyMarketingFile = /\\b(landing|homepage|home|pricing|marketing|copy|content|hero|cta|features|testimonials?)\\b/i.test(file);\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 fake testimonials/reviews\n //\n // Prior behavior was too broad: any \"review\" (e.g., code review, profile review) + any \"ai review\"\n // anywhere in the file could incorrectly raise a CRITICAL FTC issue.\n //\n // New behavior:\n // - Requires EXPLICIT \"testimonial\" language (not just \"review\" which is too common in code)\n // - Requires \"fake\" or \"synthetic\" indicators directly related to testimonials\n // - Ignores common engineering contexts (code review, PR review, AI-generated code)\n // - Only triggers on marketing files OR explicit testimonial generation code\n //\n // Common false positive causes to avoid:\n // - \"AI-generated code review\" → should NOT trigger\n // - \"generated content\" in any context → should NOT trigger\n // - \"review\" in UI (e.g., \"review your order\") → should NOT trigger\n const testimonialIndicator = /\\btestimonial(s)?\\b/i;\n const fakeTestimonialPattern = /\\b(fake|synthetic|generated|fabricated)\\s+(testimonial|review|rating|feedback)s?\\b/i;\n const testimonialGenerationPattern = /\\b(generate|create|make)\\s+(fake|synthetic)?\\s*(testimonial|review|rating)s?\\b/i;\n \n // Expanded engineering context to exclude\n const engineeringContext = /\\b(code\\s+review|pr\\s+review|pull\\s+request|profile\\s+review|review\\s+agent|reviewer|super-reviewer|trie|scout|ai[-\\s]?generated\\s+code|generated\\s+(by\\s+)?(ai|claude|gpt|llm|copilot)|code\\s+generation|content\\s+generation)\\b/i;\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i]!;\n const trimmed = line.trim();\n\n // Ignore comments to avoid triggering off docs/prompt guidance.\n if (trimmed.startsWith('//') || trimmed.startsWith('/*') || trimmed.startsWith('*') || trimmed.startsWith('<!--')) {\n continue;\n }\n\n // Windowed context (±2 lines) so unrelated words elsewhere don't combine into a \"critical\".\n const start = Math.max(0, i - 2);\n const end = Math.min(lines.length, i + 3);\n const window = lines.slice(start, end).join('\\n');\n\n // Skip if this looks like engineering/development context\n if (engineeringContext.test(window)) continue;\n\n // Only flag if there's EXPLICIT fake testimonial language\n const hasFakeTestimonial = fakeTestimonialPattern.test(window);\n const hasTestimonialGeneration = testimonialGenerationPattern.test(window);\n \n // In marketing files, also check for testimonial + fake/synthetic in same context\n const hasTestimonialWithFake = testimonialIndicator.test(window) && \n /\\b(fake|synthetic|fabricated|made[-\\s]?up)\\b/i.test(window);\n\n if (!hasFakeTestimonial && !hasTestimonialGeneration && !(isLikelyMarketingFile && hasTestimonialWithFake)) {\n continue;\n }\n\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, typical, and verifiable.',\n file,\n i + 1,\n 0.90,\n 'FTC Act - Deceptive advertising prohibition',\n true\n ));\n break; // one per file is enough; avoid spamming duplicates\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 // Skip React files that just use `children` prop (very common false positive)\n const isReactChildrenUsage = /children\\s*[:\\?})]|React\\.ReactNode|PropsWithChildren|\\.children/i.test(content);\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 // NOTE: Be careful not to false-positive on React's `children` prop\n const childPattern = /\\b(kids|minor|under.*13|age.*13)\\b/i;\n const childrenPropPattern = /children\\s*[:\\?})\\]=]|\\.children|ReactNode/i;\n \n // Only check if it looks like actual child-directed content, not React children\n if (childPattern.test(line) && !childrenPropPattern.test(line) && !isReactChildrenUsage) {\n if (!/coppa|parentalConsent|verifiableConsent/i.test(content)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'serious', // Downgraded from critical - needs human review\n 'Potential child-directed content without COPPA compliance',\n 'COPPA requires verifiable parental consent before collecting data from children under 13. Review if this applies to your app.',\n file,\n i + 1,\n 0.70, // Lower confidence - needs human verification\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 /**\n * Check if a file is part of Trie's own codebase (to prevent self-detection false positives)\n */\n private shouldExcludeTrieFile(filePath: string): boolean {\n // Normalize path to use forward slashes for consistent matching\n const normalizedPath = filePath.replace(/\\\\/g, '/');\n \n // Exclude files in Trie's source directories (handles both installed and development)\n if (normalizedPath.includes('trie') && normalizedPath.includes('/src/')) {\n return true;\n }\n \n // Check for skills directory\n if (normalizedPath.includes('/skills/')) {\n return true;\n }\n \n // Check for trie directory (scanner files)\n if (normalizedPath.includes('/trie/')) {\n return true;\n }\n \n // Exclude specific Trie scanner/skill files by filename\n const fileName = normalizedPath.split('/').pop() || '';\n const TRIE_SCANNER_FILES = [\n 'vulnerability-signatures.ts', 'vulnerability-signatures.js',\n 'vibe-code-signatures.ts', 'vibe-code-signatures.js',\n 'legal.ts', 'legal.js',\n 'security-scanner.ts', 'security-scanner.js',\n 'agent-smith.ts', 'agent-smith.js',\n 'security.ts', 'security.js',\n 'privacy.ts', 'privacy.js',\n 'soc2.ts', 'soc2.js',\n ];\n \n return TRIE_SCANNER_FILES.includes(fileName);\n }\n}\n\n// Backward compatibility export\nexport { LegalSkill as LegalAgent };\n","import { BaseSkill } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\nimport { basename, dirname } from 'path';\nimport { existsSync } from 'fs';\nimport { isInteractiveMode } from '../../utils/progress.js';\n\nexport class TestSkill extends BaseSkill {\n name = 'test';\n description = 'Test coverage analysis, test quality, and testing best practices';\n version = '1.0.0';\n override author = 'Trie Agent';\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 if (!isInteractiveMode()) {\n console.error(`Test Agent: Error reading file ${file}:`, error);\n }\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 // Skip files that typically don't need individual tests\n if (/index\\.[jt]sx?$|types?\\.[jt]s$|constants?\\.[jt]s$|config\\.[jt]s$/.test(fileName)) {\n return issues;\n }\n\n // Skip UI components by default - they're often tested via integration tests\n if (/\\.(tsx|jsx)$/.test(fileName) && !/\\.test\\.|\\.spec\\./.test(fileName)) {\n // Only flag if it's a critical component\n if (!/auth|login|payment|checkout|form/i.test(content)) {\n return issues;\n }\n }\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 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.70, // Lower confidence - we can't know if tests exist elsewhere\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 // SIGNIFICANTLY REDUCED: Only flag the most critical testable patterns\n // Removed: complex conditionals, error handling, async operations\n // These generate too many issues and ESLint/TypeScript handle most of them\n const issues: Issue[] = [];\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 // 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// Backward compatibility export\nexport { TestSkill as TestAgent };\n","import { BaseSkill } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\n\nexport class SoftwareArchitectSkill extends BaseSkill {\n name = 'software-architect';\n description = 'Architecture patterns, code organization, SOLID principles, and scalability';\n version = '1.0.0';\n override author = 'Trie Agent';\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 // NOTE: Be careful not to match HTML <select> elements!\n // Only match actual ORM/database patterns, not SQL keywords that could be in strings\n if (/\\.(tsx|jsx)$/.test(file)) {\n const hasOrmImport = /from\\s+['\"]prisma|from\\s+['\"]mongoose|from\\s+['\"]sequelize|from\\s+['\"]typeorm|from\\s+['\"]@prisma/i.test(line);\n const hasDirectQuery = /\\.query\\s*\\(|\\.execute\\s*\\(|\\.raw\\s*\\(/.test(line);\n \n if (hasOrmImport || hasDirectQuery) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate', // Downgraded - sometimes this is intentional (Next.js server components)\n 'Direct database access in UI component',\n 'Move database logic to API layer or server action',\n file,\n lineNumber,\n 0.75,\n undefined,\n false\n ));\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 // NOTE: Be more specific about DB patterns to avoid false positives\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 = /from\\s+['\"]prisma|from\\s+['\"]mongoose|from\\s+['\"]sequelize|\\.query\\s*\\(/i.test(content);\n \n const concernCount = [hasUI, hasAPI, hasDB].filter(Boolean).length;\n\n // Only flag if we see ALL three concerns, not just two (too noisy otherwise)\n if (concernCount >= 3) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low', // Downgraded - this is more of a suggestion\n 'Multiple concerns mixed in single file',\n 'Consider separating UI, API, and data access layers',\n file,\n undefined,\n 0.60,\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\n// Backward compatibility export\nexport { SoftwareArchitectSkill as SoftwareArchitectAgent };\n","import { BaseSkill } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext } from '../types/index.js';\n\nexport class DevOpsSkill extends BaseSkill {\n name = 'devops';\n description = 'Infrastructure, deployment, configuration, and operational concerns';\n version = '1.0.0';\n override author = 'Trie Agent';\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\n// Backward compatibility export\nexport { DevOpsSkill as DevOpsAgent };\n","import { BaseSkill, 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 BugFindingSkill extends BaseSkill {\n name = 'bug-finding';\n description = 'AI-powered bug detection: null safety, edge cases, async issues, runtime errors';\n version = '2.0.0';\n override author = 'Trie Agent';\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\n// Backward compatibility export\nexport { BugFindingSkill as BugFindingAgent };\n","import { BaseSkill } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext, AgentPriority } from '../types/index.js';\nimport { isInteractiveMode } from '../../utils/progress.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 UserTestingSkill extends BaseSkill {\n name = 'user-testing';\n description = 'Simulates user personas (happy path, security tester, confused user) to find vulnerabilities';\n version = '2.0.0';\n override author = 'Trie Agent';\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 if (!isInteractiveMode()) {\n console.error(`User Testing Agent: Error reading file ${file}:`, error);\n }\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\n// Backward compatibility export\nexport { UserTestingSkill as UserTestingAgent };\n","import { BaseSkill } 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';\nimport { isInteractiveMode } from '../../utils/progress.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 TrieCleanSkill extends BaseSkill {\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 override author = 'Trie Agent';\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 if (!isInteractiveMode()) {\n console.error(`Trie Clean Agent: Error reading file ${file}:`, error);\n }\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 += `- [X] ${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\n\n// Backward compatibility export\nexport { TrieCleanSkill as TrieCleanAgent };\n","import { BaseSkill } 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 SOC2Skill extends BaseSkill {\n name = 'soc2';\n description = 'SOC 2 Type II compliance: access controls, encryption, logging, change management';\n version = '1.0.0';\n override author = 'Trie Agent';\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\n// Backward compatibility export\nexport { SOC2Skill as SOC2Agent };\n","import { BaseSkill } 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 SuperReviewerSkill extends BaseSkill {\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 override author = 'Trie Agent';\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\n// Backward compatibility export\nexport { SuperReviewerSkill as SuperReviewerAgent };\n","import { BaseSkill } 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 PerformanceSkill extends BaseSkill {\n name = 'performance';\n description = 'Surfaces performance patterns for human review: memory, renders, bundles, queries';\n version = '1.0.0';\n override author = 'Trie Agent';\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\n// Backward compatibility export\nexport { PerformanceSkill as PerformanceAgent };\n","import { BaseSkill } 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 E2ESkill extends BaseSkill {\n name = 'e2e';\n description = 'Identifies E2E test gaps and flaky test patterns for human review';\n version = '1.0.0';\n override author = 'Trie Agent';\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\n// Backward compatibility export\nexport { E2ESkill as E2EAgent };\n","import { BaseSkill } 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 VisualQASkill extends BaseSkill {\n name = 'visual-qa';\n description = 'Surfaces potential visual/layout issues in CSS for human review';\n version = '1.0.0';\n override author = 'Trie Agent';\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\n// Backward compatibility export\nexport { VisualQASkill as VisualQAAgent };\n","import { BaseSkill } 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 DataFlowSkill extends BaseSkill {\n name = 'data-flow';\n description = 'Detects schema mismatches, placeholder data, and data integrity issues';\n version = '1.0.0';\n override author = 'Trie Agent';\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 - only high-confidence ones\n // Removed: foo/bar/baz (too common in legit code), xxx/yyy/zzz (too broad)\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: /[\"']PLACEHOLDER[\"']/i, desc: 'PLACEHOLDER string value' },\n { pattern: /[\"']changeme[\"']|[\"']replace[-_]?me[\"']/i, desc: 'Replace-me placeholder' },\n { pattern: /[\"']your[-_]?(api[-_]?key|token|password)[-_]?here[\"']/i, desc: 'Your-X-here 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 // REMOVED: Optional chaining count check - too noisy, not a real issue\n // REMOVED: Type assertion check - too noisy, TypeScript handles this\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n const lineNumber = i + 1;\n\n // Only check for truly dangerous patterns: deep access on API response without null checks\n if (/response\\.(data|body)\\.(\\w+)\\.(\\w+)\\.(\\w+)/.test(line)) {\n if (!/\\?\\./.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low', // Downgraded - optional chaining is good but not critical\n 'Deep property access on API response without null checks',\n 'Add optional chaining or validate response structure',\n file,\n lineNumber,\n 0.60,\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 // REMOVED: Number conversion check - too many false positives\n // TypeScript handles this, and most conversions are intentional\n }\n\n return issues;\n }\n\n private checkTypeCoercion(content: string, file: string): Issue[] {\n // SIGNIFICANTLY REDUCED: Only flag the most dangerous type coercion issues\n // Removed: loose equality check (ESLint handles this better)\n // Removed: truthy checks on numbers (too many false positives)\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 // Flag the most dangerous coercion patterns\n if (/==\\s*null/.test(line) || /==\\s*undefined/.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'moderate',\n 'Loose equality check against null/undefined',\n 'Use strict equality (===) to avoid accidental truthiness',\n file,\n lineNumber,\n 0.75,\n undefined,\n true,\n { category: 'equality', effort: 'trivial' }\n ));\n }\n\n // Only flag the most dangerous pattern: comparing to '' or 0 with ==\n if (/==\\s*[\"']['\"]/.test(line) || /==\\s*0[^.]/.test(line)) {\n issues.push(this.createIssue(\n this.generateIssueId(),\n 'low',\n 'Loose equality with empty string or zero - type coercion risk',\n 'Use strict equality (===) to avoid unexpected behavior',\n file,\n lineNumber,\n 0.65,\n undefined,\n true,\n { category: 'equality', effort: 'trivial' }\n ));\n }\n }\n\n return issues;\n }\n}\n\n// Backward compatibility export\nexport { DataFlowSkill as DataFlowAgent };\n","import { BaseSkill, FileRelevance } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext, AgentPriority } from '../types/index.js';\nimport { output } from '../../utils/output-manager.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) - realistic estimates for finding bugs pre-production\n * These represent the cost if fixed NOW during development (developer time + overhead)\n *\n * NOTE: Significantly reduced for more realistic estimates. These are per-issue costs.\n * Calibrated for indie/small team development. Industry multipliers provide scaling.\n */\nconst BASE_COST_BY_SEVERITY = {\n critical: 300, // Critical bugs found in dev (~2 hrs @ $150)\n serious: 150, // Serious issues (~1 hr @ $150)\n moderate: 75, // Moderate issues (~30 min @ $150)\n low: 25, // Low severity - quick fixes (~10 min @ $150)\n};\n\n/**\n * Production multipliers - how much more it costs if this reaches production\n * Based on IBM Systems Sciences Institute research, but scaled for small teams\n *\n * NOTE: Reduced from enterprise research for indie/startup reality.\n * Production issues are still expensive but not catastrophic for small teams.\n */\nconst PRODUCTION_MULTIPLIER = {\n critical: 5, // Critical bugs can cause outages, but smaller scale\n serious: 3, // Serious bugs cause user impact\n moderate: 2, // Moderate bugs require hotfixes, user support\n low: 1.5, // Low bugs accumulate tech debt\n};\n\n/**\n * Category-specific cost multipliers based on industry data\n * \n * NOTE: Multipliers are realistic for typical apps, not Fortune 500 enterprises.\n * The Ponemon \"$4.45M breach\" stat is for large enterprises with millions of records.\n * Most indie/startup apps would see much lower actual costs.\n */\nconst CATEGORY_MULTIPLIERS: Record<string, { multiplier: number; reason: string }> = {\n // Security categories - reduced but still prioritized\n 'security': { multiplier: 3.0, reason: 'Security vulnerabilities require careful remediation' },\n 'authentication': { multiplier: 4.0, reason: 'Auth bypass is serious but fixable' },\n 'authorization': { multiplier: 3.0, reason: 'Authorization flaws expose sensitive data' },\n 'injection': { multiplier: 6.0, reason: 'SQL/Command injection is severe - prioritize fix' },\n 'xss': { multiplier: 2.5, reason: 'XSS needs fixing but React mitigates most cases' },\n 'secrets': { multiplier: 4.0, reason: 'Exposed secrets require rotation' },\n 'cryptography': { multiplier: 2.5, reason: 'Weak crypto should be updated' },\n\n // Data integrity categories\n 'data-loss': { multiplier: 5.0, reason: 'Data loss is serious - ensure backups exist' },\n 'data-corruption': { multiplier: 3.5, reason: 'Data corruption requires recovery work' },\n 'privacy': { multiplier: 3.5, reason: 'Privacy violations carry compliance risk' },\n\n // Financial categories - still high priority but more reasonable\n 'payment': { multiplier: 8.0, reason: 'Payment bugs need immediate attention' },\n 'billing': { multiplier: 4.0, reason: 'Billing errors erode trust' },\n 'financial-calculation': { multiplier: 3.5, reason: 'Incorrect calculations compound over time' },\n\n // Reliability categories\n 'crash': { multiplier: 2.5, reason: 'Crashes hurt user experience' },\n 'memory-leak': { multiplier: 2.0, reason: 'Memory leaks cause gradual degradation' },\n 'deadlock': { multiplier: 2.5, reason: 'Deadlocks require restarts' },\n 'race-condition': { multiplier: 2.5, reason: 'Race conditions are hard to debug' },\n\n // User experience\n 'accessibility': { multiplier: 1.3, reason: 'Accessibility issues should be addressed' },\n 'performance': { multiplier: 1.5, reason: 'Performance issues hurt conversion rates' },\n 'ux': { multiplier: 1.2, reason: 'UX bugs increase support costs' },\n\n // Code quality\n 'bug': { multiplier: 1.0, reason: 'General bugs require developer time' },\n 'type-error': { multiplier: 0.8, reason: 'Type errors caught early save debugging time' },\n 'logic-error': { multiplier: 1.3, reason: 'Logic errors produce incorrect outcomes' },\n\n // Default\n 'default': { multiplier: 1.0, reason: 'General code issues' },\n};\n\n/**\n * Context multipliers based on what the code touches\n * \n * NOTE: These are intentionally LOW to prevent absurd compounding.\n * They add minor adjustments, not major multipliers.\n */\nconst CONTEXT_MULTIPLIERS: Record<string, { multiplier: number; description: string }> = {\n touchesPayments: { multiplier: 1.3, description: 'Payment processing code' },\n touchesAuth: { multiplier: 1.2, description: 'Authentication/authorization code' },\n touchesUserData: { multiplier: 1.15, description: 'User PII handling' },\n touchesHealthData: { multiplier: 1.3, description: 'Health data (HIPAA liability)' },\n touchesDatabase: { multiplier: 1.1, description: 'Database operations' },\n touchesAPI: { multiplier: 1.1, description: 'External API integrations' },\n touchesCrypto: { multiplier: 1.15, description: 'Cryptographic operations' },\n touchesFileSystem: { multiplier: 1.05, 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.25, // 15 minutes - typo fix, obvious one-liner\n easy: 1, // 1 hour - simple fix, clear solution\n medium: 4, // 4 hours - half day, requires some investigation\n hard: 16, // 2 days - complex fix, testing needed\n};\n\nconst DEVELOPER_HOURLY_RATE = 150; // Blended rate including benefits, overhead\n\n/**\n * Industry multipliers - different industries have different risk profiles\n * Solopreneur/startup have lower costs (less compliance, smaller blast radius)\n * Fintech/healthcare have higher costs (regulatory requirements, compliance)\n */\nconst INDUSTRY_MULTIPLIERS: Record<string, { multiplier: number; label: string }> = {\n 'solopreneur': { multiplier: 0.2, label: 'Solopreneur (1-person team, minimal overhead)' },\n 'startup': { multiplier: 0.6, label: 'Startup (small team, fast iteration)' },\n 'saas': { multiplier: 0.8, label: 'SaaS (recurring revenue, moderate compliance)' },\n 'ecommerce': { multiplier: 1.0, label: 'E-commerce (transactions, customer data)' },\n 'enterprise': { multiplier: 1.5, label: 'Enterprise (large contracts, SLAs)' },\n 'fintech': { multiplier: 2.0, label: 'Fintech (financial regulations, audits)' },\n 'healthcare': { multiplier: 2.5, label: 'Healthcare (HIPAA, patient data)' },\n};\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 1K users; 250 users is intentionally lower to reflect early-stage apps\n *\n * NOTE: Multipliers are capped to prevent absurd estimates.\n * A 1M user app isn't 40x more expensive per bug - there are economies of scale.\n */\nconst USER_COUNT_MULTIPLIERS = [\n { threshold: 0, multiplier: 0.2, label: 'Pre-launch (0 users)' },\n { threshold: 50, multiplier: 0.35, label: 'MVP (50 users)' },\n { threshold: 250, multiplier: 0.6, label: 'Early stage (250 users)' },\n { threshold: 1000, multiplier: 1.0, label: 'Growing (1K users)' }, // Baseline\n { threshold: 5000, multiplier: 2.0, label: 'Traction (5K users)' },\n { threshold: 25000, multiplier: 4.0, label: 'Scale-up (25K users)' },\n { threshold: 100000, multiplier: 7.0, label: 'Growth (100K users)' },\n { threshold: 500000, multiplier: 10.0, label: 'Large (500K users)' },\n { threshold: 1000000, multiplier: 12.0, label: 'Enterprise (1M+ users)' }, // Capped to avoid runaway estimates\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: 250) */\n userCount?: number;\n /** Number of paying customers (default: 0 = not set, uses userCount) */\n payingUsers?: number;\n /** Average revenue per user per month in USD (default: 0 = not set) */\n revenuePerUser?: number;\n /** Developer hourly rate for fix cost calculation (default: $150) */\n developerRate?: number;\n /** Industry for specialized multipliers */\n industry?: 'solopreneur' | '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 MoneybagSkill extends BaseSkill {\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 override author = 'Trie Agent';\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 * Get the industry multiplier for current industry setting\n */\n private getIndustryMultiplier(): { multiplier: number; label: string } {\n const industry = this.config.industry;\n if (!industry || !INDUSTRY_MULTIPLIERS[industry]) {\n return { multiplier: 1.0, label: 'General (no industry specified)' };\n }\n return INDUSTRY_MULTIPLIERS[industry];\n }\n\n /**\n * Get paying user count (defaults to userCount if not set)\n */\n get payingUsers(): number {\n return this.config.payingUsers && this.config.payingUsers > 0 \n ? this.config.payingUsers \n : this.userCount;\n }\n\n /**\n * Get monthly recurring revenue (MRR)\n */\n get monthlyRevenue(): number {\n const rpu = this.config.revenuePerUser ?? 0;\n return this.payingUsers * rpu;\n }\n\n /**\n * Get revenue context for cost scaling\n * If revenue is set, we can make smarter decisions about cost impact\n */\n private getRevenueContext(): { \n hasRevenue: boolean; \n mrr: number; \n payingUsers: number;\n revenuePerUser: number;\n revenueMultiplier: number;\n label: string;\n } {\n const rpu = this.config.revenuePerUser ?? 0;\n const payingUsers = this.payingUsers;\n const mrr = payingUsers * rpu;\n \n if (rpu <= 0 || mrr <= 0) {\n return { \n hasRevenue: false, \n mrr: 0, \n payingUsers,\n revenuePerUser: 0,\n revenueMultiplier: 1.0, \n label: 'No revenue data' \n };\n }\n \n // Revenue-based multiplier: scale costs relative to monthly revenue\n // Lower revenue = lower absolute cost caps (but not below a floor)\n // Higher revenue = higher potential impact from bugs\n let revenueMultiplier: number;\n let label: string;\n \n if (mrr < 500) {\n revenueMultiplier = 0.2;\n label = `Hobby ($${mrr}/mo MRR)`;\n } else if (mrr < 2000) {\n revenueMultiplier = 0.4;\n label = `Side project ($${mrr.toLocaleString()}/mo MRR)`;\n } else if (mrr < 10000) {\n revenueMultiplier = 0.7;\n label = `Small business ($${mrr.toLocaleString()}/mo MRR)`;\n } else if (mrr < 50000) {\n revenueMultiplier = 1.0;\n label = `Growing business ($${(mrr/1000).toFixed(0)}k/mo MRR)`;\n } else if (mrr < 200000) {\n revenueMultiplier = 1.5;\n label = `Established ($${(mrr/1000).toFixed(0)}k/mo MRR)`;\n } else {\n revenueMultiplier = 2.0;\n label = `Scale-up ($${(mrr/1000).toFixed(0)}k/mo MRR)`;\n }\n \n return { hasRevenue: true, mrr, payingUsers, revenuePerUser: rpu, revenueMultiplier, label };\n }\n\n /**\n * Display the Moneybags entrance banner\n * Uses OutputManager to route to TUI or console\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)] ?? 'Every bug has a price tag.';\n\n output().banner('moneybags', MONEYBAGS_ASCII, {\n quote: quote,\n version: this.version\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 2x to avoid unrealistic estimates\n contextMultiplier = Math.min(contextMultiplier, 2);\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 // 4b. Industry multiplier - different industries have different risk profiles\n const industryScale = this.getIndustryMultiplier();\n const industryMultiplier = industryScale.multiplier;\n \n // 4c. Revenue context - if set, use revenue to scale costs dynamically\n const revenueContext = this.getRevenueContext();\n const revenueMultiplier = revenueContext.hasRevenue ? revenueContext.revenueMultiplier : 1.0;\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 - default effort scales with severity\n const defaultEffort = issue.severity === 'critical' ? 'hard' : \n issue.severity === 'serious' ? 'medium' : 'easy';\n const effort = issue.effort || defaultEffort;\n const fixHours = EFFORT_HOURS[effort] || 4;\n const developerRate = this.config.developerRate ?? DEVELOPER_HOURLY_RATE;\n const fixCost = fixHours * developerRate;\n \n // 7. Calculate totals based on revenue context\n // PRE-REVENUE MODE: If no paying users/revenue, cost = developer time only\n // REVENUE MODE: Apply multipliers based on business impact\n \n let totalNowCost: number;\n let totalProductionCost: number;\n let savings: number;\n \n const isPreRevenue = !revenueContext.hasRevenue || revenueContext.mrr === 0;\n \n if (isPreRevenue) {\n // PRE-REVENUE: Cost is purely developer time to fix\n // No fancy multipliers - just how long will this take to fix?\n totalNowCost = Math.round(fixCost);\n \n // Production cost for pre-revenue is just slightly higher (context switch, debugging in prod)\n // Use a small severity multiplier to still prioritize critical bugs\n const severityMultiplier = { critical: 2.0, serious: 1.5, moderate: 1.2, low: 1.0 }[issue.severity];\n totalProductionCost = Math.round(fixCost * severityMultiplier);\n \n savings = totalProductionCost - totalNowCost;\n } else {\n // REVENUE MODE: Full cost analysis with business impact\n const BASE_NOW_CAP = 3000; // Realistic cap for indie/small team remediation\n const BASE_PROD_CAP = 15000; // Realistic production cap for small teams\n \n // Use the minimum of user scale and revenue multiplier to keep costs reasonable\n // But weight revenue more heavily since it's actual business data\n const effectiveMultiplier = Math.min(userScaleMultiplier, revenueMultiplier) * 0.7 + revenueMultiplier * 0.3;\n \n const maxNowCost = BASE_NOW_CAP * effectiveMultiplier;\n const maxProdCost = BASE_PROD_CAP * effectiveMultiplier;\n \n const rawNowCost = (baseCost * categoryMultiplier * contextMultiplier * industryMultiplier * revenueMultiplier) + fixCost;\n totalNowCost = Math.round(Math.min(rawNowCost, maxNowCost));\n \n const rawProductionCost = \n (baseCost * productionMultiplier * categoryMultiplier * contextMultiplier * industryMultiplier * revenueMultiplier) + \n perUserCost + // Add per-user costs for production impact\n (fixCost * 2); // Production fixes take 2x longer\n totalProductionCost = Math.round(Math.min(rawProductionCost, maxProdCost));\n \n savings = totalProductionCost - totalNowCost;\n }\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 revenueContext = this.getRevenueContext();\n const isPreRevenue = !revenueContext.hasRevenue || revenueContext.mrr === 0;\n \n if (isPreRevenue) {\n // PRE-REVENUE: Simple developer time summary\n const hours = nowCost / (this.config.developerRate ?? DEVELOPER_HOURLY_RATE);\n const hoursStr = hours < 1 ? `${Math.round(hours * 60)}min` : `${hours.toFixed(1)}hr`;\n \n let summary = `Dev time: ${hoursStr} (${formatCurrency(nowCost)})`;\n \n if (contextFactors.length > 0) {\n summary += ` | ${contextFactors.join(', ')}`;\n }\n \n return summary;\n }\n \n // REVENUE MODE: Full cost breakdown\n \n let summary = `Fix now: ${formatCurrency(nowCost)} | If production: ${formatCurrency(productionCost)} | Save: ${formatCurrency(savings)}`;\n \n // Add MRR context instead of user count\n const mrrStr = revenueContext.mrr >= 1000 \n ? `$${(revenueContext.mrr / 1000).toFixed(0)}k MRR` \n : `$${revenueContext.mrr} MRR`;\n summary += ` (${mrrStr})`;\n \n if (contextFactors.length > 0) {\n summary += ` | Risk factors: ${contextFactors.join(', ')}`;\n }\n \n // Add urgency indicator - thresholds scaled for MRR\n const mrrScale = Math.max(1, Math.sqrt(revenueContext.mrr / 10000));\n const scaledHighThreshold = 75000 * mrrScale;\n const scaledMediumThreshold = 20000 * mrrScale;\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 // Report aggregate cost to OutputManager for dashboard display\n if (issues.length > 0) {\n let totalFixNow = 0;\n let totalProduction = 0;\n const perIssue: Array<{ issue: string; cost: number }> = [];\n \n for (const issue of issues) {\n // Extract cost from issue text (format: \"issue | Fix now: $X | If production: $Y | Save: $Z\")\n const costMatch = issue.issue.match(/Fix now: \\$([0-9,.kM]+)/);\n const prodMatch = issue.issue.match(/If production: \\$([0-9,.kM]+)/);\n \n const parseCost = (s: string | undefined): number => {\n if (!s) return 0;\n if (s.endsWith('M')) return parseFloat(s) * 1000000;\n if (s.endsWith('k')) return parseFloat(s) * 1000;\n return parseFloat(s.replace(/,/g, ''));\n };\n \n const fixCost = parseCost(costMatch?.[1]);\n const prodCost = parseCost(prodMatch?.[1]);\n \n totalFixNow += fixCost;\n totalProduction += prodCost;\n perIssue.push({ issue: issue.issue.split(' | ')[0] || 'Unknown', cost: prodCost });\n }\n \n output().cost(totalFixNow, totalProduction, totalProduction - totalFixNow, perIssue.slice(0, 10));\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 (baseline for 1K users, scale by industry/user count):\n- Critical bugs: $2k now, $16k in production\n- Serious bugs: $800 now, $4k in production \n- Moderate bugs: $200 now, $600 in production\n- Low bugs: $50 now, $100 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 (never scale down for small user bases)\n const scaleMultiplier = Math.max(1, userScale.multiplier);\n let riskLevel: 'low' | 'medium' | 'high' | 'critical' = 'low';\n if (totalProductionCost > 200000 * scaleMultiplier) riskLevel = 'critical';\n else if (totalProductionCost > 75000 * scaleMultiplier) riskLevel = 'high';\n else if (totalProductionCost > 20000 * 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\n// Backward compatibility export\nexport { MoneybagSkill as MoneybagAgent };\n","import { BaseSkill, FileRelevance } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext, AgentPriority } from '../types/index.js';\nimport { output } from '../../utils/output-manager.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 * \n * NOTE: These checks are primarily for BACKEND/SERVER applications.\n * Frontend-only apps (React, Vue, etc.) don't need health endpoints, connection pooling, etc.\n */\nconst PRODUCTION_PATTERNS = {\n // Health & Reliability - BACKEND ONLY\n healthEndpoint: {\n pattern: /\\/health|healthcheck|health-check|readiness|liveness/i,\n category: 'reliability',\n requirement: 'Health check endpoint',\n severity: 'moderate' as const, // Downgraded - not critical for all apps\n backendOnly: true,\n },\n gracefulShutdown: {\n pattern: /SIGTERM|SIGINT|process\\.on\\s*\\(\\s*['\"]SIG/i,\n category: 'reliability',\n requirement: 'Graceful shutdown handling',\n severity: 'low' as const,\n backendOnly: true,\n },\n \n // Scalability - BACKEND ONLY\n connectionPooling: {\n pattern: /connectionLimit|pool|poolSize|max_connections|maxConnections/i,\n category: 'scalability',\n requirement: 'Database connection pooling',\n severity: 'moderate' as const,\n backendOnly: true,\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: 'moderate' as const,\n backendOnly: true,\n },\n \n // Error Handling - BACKEND ONLY\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: 'moderate' as const,\n backendOnly: true,\n },\n \n // Security Headers - BACKEND ONLY (frontend relies on hosting platform)\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: 'moderate' as const,\n backendOnly: true,\n },\n \n // Rate Limiting - BACKEND ONLY\n rateLimiting: {\n pattern: /rateLimit|rate-limit|throttle|express-rate-limit|slowDown/i,\n category: 'security',\n requirement: 'API rate limiting',\n severity: 'low' as const,\n backendOnly: true,\n },\n \n // Logging - applies to both but less critical for frontend\n structuredLogging: {\n pattern: /pino|winston|bunyan|structured.*log|log.*json/i,\n category: 'observability',\n requirement: 'Structured logging',\n severity: 'low' as const,\n backendOnly: false,\n },\n \n // Monitoring - applies to both\n monitoring: {\n pattern: /prometheus|datadog|newrelic|sentry|bugsnag|opentelemetry|@sentry/i,\n category: 'observability',\n requirement: 'Error/performance monitoring',\n severity: 'low' as const,\n backendOnly: false,\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 ProductionReadySkill extends BaseSkill {\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 override author = 'Trie Agent';\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)] ?? 'Ship it? Not until I say so.';\n \n output().banner('production-ready', PRODUCTION_READY_ASCII, {\n quote: quote,\n version: this.version\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 // Detect if this is a frontend-only app (no backend server)\n const combinedContent = allContent.join('\\n');\n const isFrontendOnly = this.detectFrontendOnlyApp(combinedContent, files);\n \n // Second pass: report missing requirements (skip backend-only for frontend apps)\n for (const [key, config] of Object.entries(PRODUCTION_PATTERNS)) {\n // Skip backend-only checks for frontend-only apps\n const patternConfig = config as typeof config & { backendOnly?: boolean };\n if (isFrontendOnly && patternConfig.backendOnly) {\n continue;\n }\n \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.6, // Lower confidence for missing checks\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 /**\n * Detect if this is a frontend-only app (React, Vue, Svelte, etc.) without a backend\n * Frontend apps don't need health endpoints, database pooling, session stores, etc.\n */\n private detectFrontendOnlyApp(content: string, files: string[]): boolean {\n // Check content for frontend-only indicators\n const frontendContentPatterns = [\n /vite\\.config|next\\.config|nuxt\\.config|svelte\\.config/i,\n /from ['\"]react['\"]|from ['\"]vue['\"]|from ['\"]svelte['\"]/i,\n /createRoot|ReactDOM|createApp/i,\n ];\n \n // Check file extensions\n const frontendFilePatterns = [\n /\\.tsx$/,\n /\\.jsx$/,\n /\\.vue$/,\n /\\.svelte$/,\n ];\n \n // Indicators of backend/server presence\n const backendIndicators = [\n /express|fastify|koa|hapi|nest|@nestjs/i,\n /createServer|http\\.Server|https\\.Server/i,\n /app\\.listen\\s*\\(|server\\.listen\\s*\\(/i,\n /middleware|router\\.get|router\\.post|app\\.get\\s*\\(/i,\n /prisma|sequelize|mongoose|knex|typeorm/i,\n ];\n \n const hasFrontendContent = frontendContentPatterns.some(p => p.test(content));\n const hasFrontendFiles = files.some(f => frontendFilePatterns.some(p => p.test(f)));\n const hasFrontendSignals = hasFrontendContent || hasFrontendFiles;\n \n const hasBackendSignals = backendIndicators.some(p => p.test(content));\n \n // It's frontend-only if we see frontend signals but no backend signals\n return hasFrontendSignals && !hasBackendSignals;\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: 'ready' | 'caution' | 'not-ready' = criticalIssues > 0 || seriousIssues > 2 \n ? 'not-ready' \n : seriousIssues > 0 \n ? 'caution'\n : 'ready';\n \n // Build requirements list with met status\n const requirements: Array<{ name: string; met: boolean }> = [];\n for (const [key, config] of Object.entries(PRODUCTION_PATTERNS)) {\n requirements.push({\n name: config.requirement,\n met: this.foundRequirements.has(key),\n });\n }\n \n // Route readiness report through OutputManager\n output().readiness(readinessScore, metRequirements, totalRequirements, status, requirements);\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// Backward compatibility export\nexport { ProductionReadySkill as ProductionReadyAgent };\n","/**\n * Skill Installer\n * \n * Installs skills from GitHub repositories into .trie/skills/\n * Skills can come from any repo that follows the SKILL.md format.\n */\n\nimport { mkdir, rm, writeFile, readdir, readFile, access, cp, stat } from 'fs/promises';\nimport { join, basename, extname } from 'path';\nimport { homedir } from 'os';\nimport { existsSync } from 'fs';\nimport { parseSkillMd } from './parser.js';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport type { InstalledSkill, SkillInstallResult } from '../types/external-skill.js';\nimport { scanSkillForThreats, formatSecuritySummary } from './security-scanner.js';\nimport { runShellCommand } from '../utils/command-runner.js';\n\n/**\n * Global skills directories for various AI coding tools\n * Custom skills are written to ALL these locations so they work everywhere\n */\nconst GLOBAL_SKILLS_DIRS = {\n trie: join(homedir(), '.trie', 'skills'),\n cursor: join(homedir(), '.cursor', 'skills'),\n claude: join(homedir(), '.claude', 'skills'),\n opencode: join(homedir(), '.config', 'opencode', 'skills'),\n};\n\n/** Primary global skills directory (Trie's own) */\nconst GLOBAL_SKILLS_DIR = GLOBAL_SKILLS_DIRS.trie;\n\n/** Get all global skill directories to write to */\nfunction getAllGlobalSkillDirs(): string[] {\n return Object.values(GLOBAL_SKILLS_DIRS);\n}\n\n/**\n * Parse a GitHub source URL or path\n * Supports:\n * - owner/repo\n * - owner/repo/skill-name\n * - https://github.com/owner/repo\n * - https://github.com/owner/repo/tree/main/skill-name\n */\nfunction parseGitHubSource(source: string): { owner: string; repo: string; skill?: string } | null {\n // Handle full GitHub URLs\n const urlMatch = source.match(/github\\.com\\/([^/]+)\\/([^/]+?)(?:\\.git)?(?:\\/(?:tree|blob)\\/[^/]+\\/(.+))?$/);\n if (urlMatch) {\n const skill = urlMatch[3]?.replace(/\\/$/, '');\n return {\n owner: urlMatch[1]!,\n repo: urlMatch[2]!,\n ...(skill ? { skill } : {})\n };\n }\n \n // Handle owner/repo or owner/repo/skill format\n const parts = source.split('/');\n if (parts.length >= 2) {\n const skill = parts[2];\n return {\n owner: parts[0]!,\n repo: parts[1]!,\n ...(skill ? { skill } : {})\n };\n }\n \n return null;\n}\n\n/**\n * Install a skill from a GitHub repository\n * \n * @param source - GitHub source in format \"owner/repo\", \"owner/repo/skill-name\", or full URL\n * @param skillName - Optional skill name if repo contains multiple skills\n */\nexport async function installSkill(source: string, skillName?: string): Promise<SkillInstallResult> {\n const parsed = parseGitHubSource(source);\n if (!parsed) {\n return { success: false, name: 'unknown', error: 'Invalid source format. Use owner/repo, owner/repo/skill-name, or full GitHub URL' };\n }\n \n const { owner, repo, skill: parsedSkill } = parsed;\n const specifiedSkill = skillName || parsedSkill;\n \n const skillsDir = join(getTrieDirectory(getWorkingDirectory(undefined, true)), 'skills');\n const tempDir = join(skillsDir, `.temp-${Date.now()}`);\n \n try {\n await mkdir(skillsDir, { recursive: true });\n \n console.log('Cloning repository...');\n \n // Clone the repository (URL is already sanitized by template literal)\n const repoUrl = `https://github.com/${owner}/${repo}.git`;\n \n // Validate URL format\n if (!repoUrl.startsWith('https://github.com/') || repoUrl.includes('..') || repoUrl.includes('~')) {\n throw new Error('Invalid repository URL');\n }\n \n await runShellCommand(\n `git clone --depth 1 \"${repoUrl}\" \"${tempDir}\"`,\n { actor: 'internal:skills-installer', triggeredBy: 'manual', targetPath: getWorkingDirectory(undefined, true) },\n { timeoutMs: 60000, captureOutput: false }\n );\n \n // Find the SKILL.md file\n const sourcePath = await findSkillPath(tempDir, specifiedSkill);\n if (!sourcePath) {\n throw new Error(`SKILL.md not found in repository. Searched in: root, skills/, ${specifiedSkill || 'subdirectories'}`);\n }\n \n console.log('Running security scan...');\n \n // SECURITY SCAN - Automatic flagging\n const securityScan = await scanSkillForThreats(sourcePath);\n \n console.log(`Security scan: ${formatSecuritySummary(securityScan)}`);\n \n // Warn about any security risks found\n if (securityScan.risks.length > 0) {\n console.warn('\\n⚠️ SECURITY RISKS DETECTED\\n');\n \n const criticalRisks = securityScan.risks.filter(r => r.severity === 'critical');\n const highRisks = securityScan.risks.filter(r => r.severity === 'high');\n \n // Show critical risks first\n for (const risk of criticalRisks) {\n console.warn(`🔴 CRITICAL: ${risk.description}`);\n console.warn(` ${risk.location}: ${risk.pattern}`);\n console.warn(` → ${risk.recommendation}\\n`);\n }\n \n // Show high risks\n for (const risk of highRisks) {\n console.warn(`🟠 HIGH: ${risk.description}`);\n console.warn(` ${risk.location}`);\n console.warn(` → ${risk.recommendation}\\n`);\n }\n \n if (criticalRisks.length > 0) {\n console.warn('⚠️ This skill has CRITICAL security risks. Use with extreme caution.\\n');\n } else {\n console.warn('⚠️ Review these risks before using this skill.\\n');\n }\n }\n \n // Parse and validate the skill\n const parsed = await parseSkillMd(sourcePath);\n const name = parsed.frontmatter.name;\n \n // Copy to final location\n const targetPath = join(skillsDir, name);\n \n // Remove existing if present\n await rm(targetPath, { recursive: true, force: true });\n \n // Copy skill directory\n await cp(sourcePath, targetPath, { recursive: true });\n \n // Write installation metadata including security scan results\n await writeFile(join(targetPath, '.installed.json'), JSON.stringify({\n installedFrom: source,\n installedAt: new Date().toISOString(),\n repository: `${owner}/${repo}`,\n securityScan: {\n safe: securityScan.safe,\n riskCount: securityScan.risks.length,\n criticalRisks: securityScan.risks.filter(r => r.severity === 'critical').length,\n highRisks: securityScan.risks.filter(r => r.severity === 'high').length,\n scannedAt: new Date().toISOString(),\n },\n risks: securityScan.risks, // Store full risk details\n permissions: securityScan.requiredPermissions,\n }, null, 2));\n \n if (securityScan.risks.length > 0) {\n console.log(`\\n⚠️ View security details with: trie skills info ${name}\\n`);\n }\n \n return { success: true, name, path: targetPath };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { success: false, name: skillName || 'unknown', error: message };\n } finally {\n // Clean up temp directory\n await rm(tempDir, { recursive: true, force: true }).catch(() => {});\n }\n}\n\n/**\n * Find the path to a SKILL.md within a cloned repository\n * Also supports Claude Code subagent format (individual .md files)\n */\nasync function findSkillPath(repoPath: string, skillName?: string): Promise<string | null> {\n const searchPaths: string[] = [];\n \n if (skillName) {\n // Search for specific skill in standard locations\n searchPaths.push(\n join(repoPath, 'skills', skillName),\n join(repoPath, skillName),\n );\n }\n \n // Also search common locations\n searchPaths.push(\n repoPath,\n join(repoPath, 'skill'),\n );\n \n // If no specific skill, try to find any skill directory\n if (!skillName) {\n try {\n const skillsSubdir = join(repoPath, 'skills');\n await access(skillsSubdir);\n const entries = await readdir(skillsSubdir, { withFileTypes: true });\n for (const entry of entries) {\n if (entry.isDirectory() && !entry.name.startsWith('.')) {\n searchPaths.push(join(skillsSubdir, entry.name));\n }\n }\n } catch {\n // skills/ directory doesn't exist\n }\n }\n \n // Check each path for SKILL.md\n for (const searchPath of searchPaths) {\n try {\n await parseSkillMd(searchPath);\n return searchPath;\n } catch {\n // Not a valid skill directory\n }\n }\n \n // Fallback: Check for Claude Code subagent format (individual .md files)\n if (skillName) {\n const subagentPath = await findClaudeCodeSubagent(repoPath, skillName);\n if (subagentPath) {\n return subagentPath;\n }\n }\n \n return null;\n}\n\n/**\n * Find a Claude Code subagent format skill (.md file with frontmatter)\n * These repos have files like `typescript-pro.md` in the root\n */\nasync function findClaudeCodeSubagent(repoPath: string, skillName: string): Promise<string | null> {\n // Look for .md file directly\n const searchNames = [\n `${skillName}.md`,\n `${skillName.replace(/-/g, '_')}.md`,\n // Also try without common suffixes\n skillName.replace(/-pro$/, '-pro.md'),\n skillName.replace(/-expert$/, '-expert.md'),\n ];\n \n for (const fileName of searchNames) {\n const filePath = join(repoPath, fileName);\n try {\n await access(filePath);\n const content = await readFile(filePath, 'utf-8');\n \n // Check if it has frontmatter\n if (content.startsWith('---')) {\n // It's a valid subagent format - convert to SKILL.md format\n return await convertClaudeCodeToSkillMd(repoPath, filePath, skillName);\n }\n } catch {\n // File doesn't exist or can't be read\n }\n }\n \n // List available .md files for better error messages\n try {\n const entries = await readdir(repoPath);\n const mdFiles = entries.filter(e => e.endsWith('.md') && !e.toLowerCase().includes('readme') && !e.toLowerCase().includes('license'));\n if (mdFiles.length > 0) {\n // Store available skills for error message\n const availableSkills = mdFiles.map(f => f.replace('.md', '')).join(', ');\n throw new Error(`Skill \"${skillName}\" not found. Available: ${availableSkills}`);\n }\n } catch (e) {\n if (e instanceof Error && e.message.includes('Available:')) {\n throw e; // Re-throw our custom error\n }\n }\n \n return null;\n}\n\n/**\n * Convert a Claude Code subagent .md file to SKILL.md format\n */\nasync function convertClaudeCodeToSkillMd(\n repoPath: string, \n filePath: string, \n skillName: string\n): Promise<string> {\n const content = await readFile(filePath, 'utf-8');\n \n // Parse frontmatter\n const fmMatch = content.match(/^---\\n([\\s\\S]*?)\\n---\\n([\\s\\S]*)$/);\n if (!fmMatch) {\n throw new Error('Invalid frontmatter format');\n }\n \n const frontmatter = fmMatch[1]!;\n const body = fmMatch[2]!;\n \n // Extract fields from Claude Code format\n const nameMatch = frontmatter.match(/name:\\s*(.+)/);\n const descMatch = frontmatter.match(/description:\\s*(.+)/);\n const modelMatch = frontmatter.match(/model:\\s*(.+)/);\n \n const name = nameMatch ? nameMatch[1]!.trim() : skillName;\n const description = descMatch ? descMatch[1]!.trim() : `Skill from Claude Code subagent: ${name}`;\n const model = modelMatch ? modelMatch[1]!.trim() : undefined;\n \n // Create a temp directory for the converted skill\n const tempSkillDir = join(repoPath, '.converted-skill', name);\n await mkdir(tempSkillDir, { recursive: true });\n \n // Build new SKILL.md with our format\n let newContent = `---\nname: ${name}\ndescription: ${description}\nauthor: claude-code-subagent\ntags: [claude-code, subagent${model ? `, ${model}` : ''}]\n---\n\n# ${name}\n\n${body}\n`;\n \n await writeFile(join(tempSkillDir, 'SKILL.md'), newContent, 'utf-8');\n \n return tempSkillDir;\n}\n\n/**\n * List all installed skills\n */\nexport async function listInstalledSkills(): Promise<InstalledSkill[]> {\n const skillsDir = join(getTrieDirectory(getWorkingDirectory(undefined, true)), 'skills');\n const skills: InstalledSkill[] = [];\n \n try {\n const entries = await readdir(skillsDir, { withFileTypes: true });\n \n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name.startsWith('.')) continue;\n \n const skillPath = join(skillsDir, entry.name);\n \n try {\n const parsed = await parseSkillMd(skillPath);\n const metaPath = join(skillPath, '.installed.json');\n \n let meta = { installedFrom: 'unknown', installedAt: new Date().toISOString() };\n try {\n meta = JSON.parse(await readFile(metaPath, 'utf-8'));\n } catch {\n // No metadata file\n }\n \n skills.push({\n name: parsed.frontmatter.name,\n description: parsed.frontmatter.description,\n path: skillPath,\n installedFrom: meta.installedFrom,\n installedAt: meta.installedAt,\n });\n } catch {\n // Invalid skill directory, skip\n }\n }\n } catch {\n // Skills directory doesn't exist\n }\n \n return skills;\n}\n\n/**\n * Remove an installed skill\n */\nexport async function removeSkill(skillName: string): Promise<boolean> {\n const skillsDir = join(getTrieDirectory(getWorkingDirectory(undefined, true)), 'skills');\n const skillPath = join(skillsDir, skillName);\n \n try {\n await rm(skillPath, { recursive: true });\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Get a specific installed skill by name\n */\nexport async function getInstalledSkill(skillName: string): Promise<InstalledSkill | null> {\n const skills = await listInstalledSkills();\n return skills.find(s => s.name === skillName) || null;\n}\n\n/**\n * List all global skills (available across all projects)\n */\nexport async function listGlobalSkills(): Promise<InstalledSkill[]> {\n const skills: InstalledSkill[] = [];\n \n try {\n const entries = await readdir(GLOBAL_SKILLS_DIR, { withFileTypes: true });\n \n for (const entry of entries) {\n if (!entry.isDirectory() || entry.name.startsWith('.')) continue;\n \n const skillPath = join(GLOBAL_SKILLS_DIR, entry.name);\n \n try {\n const parsed = await parseSkillMd(skillPath);\n const metaPath = join(skillPath, '.installed.json');\n \n let meta = { installedFrom: 'custom', installedAt: new Date().toISOString() };\n try {\n meta = JSON.parse(await readFile(metaPath, 'utf-8'));\n } catch {\n // No metadata file\n }\n \n skills.push({\n name: parsed.frontmatter.name,\n description: parsed.frontmatter.description,\n path: skillPath,\n installedFrom: meta.installedFrom,\n installedAt: meta.installedAt,\n });\n } catch {\n // Invalid skill directory, skip\n }\n }\n } catch {\n // Global skills directory doesn't exist\n }\n \n return skills;\n}\n\n/**\n * Create a global skill from a text file\n * \n * The text file content becomes the skill instructions.\n * A SKILL.md is generated with the file name as the skill name.\n * \n * @param filePath - Path to the text file to convert\n * @param skillName - Optional custom name (defaults to filename)\n * @param description - Optional description\n */\n/**\n * Write a skill to all global skill directories (Trie, Cursor, Claude Code, OpenCode)\n * This ensures the skill works across all AI coding tools\n */\nasync function writeSkillToAllDirs(\n name: string,\n skillMdContent: string,\n metadata: Record<string, unknown>\n): Promise<{ primaryPath: string; writtenTo: string[] }> {\n const writtenTo: string[] = [];\n let primaryPath = '';\n \n for (const [tool, baseDir] of Object.entries(GLOBAL_SKILLS_DIRS)) {\n try {\n await mkdir(baseDir, { recursive: true });\n const skillPath = join(baseDir, name);\n \n // Skip if already exists in this directory\n if (existsSync(skillPath)) {\n continue;\n }\n \n await mkdir(skillPath, { recursive: true });\n await writeFile(join(skillPath, 'SKILL.md'), skillMdContent, 'utf-8');\n await writeFile(join(skillPath, '.installed.json'), JSON.stringify(metadata, null, 2));\n \n writtenTo.push(tool);\n \n // Primary path is Trie's directory\n if (tool === 'trie') {\n primaryPath = skillPath;\n }\n } catch {\n // Ignore errors for individual directories (permissions, etc.)\n // Continue writing to other directories\n }\n }\n \n // If Trie directory failed, use first successful one\n if (!primaryPath && writtenTo.length > 0) {\n const firstTool = writtenTo[0];\n if (firstTool) {\n primaryPath = join(GLOBAL_SKILLS_DIRS[firstTool as keyof typeof GLOBAL_SKILLS_DIRS], name);\n }\n }\n \n return { primaryPath, writtenTo };\n}\n\nexport async function createSkillFromFile(\n filePath: string,\n skillName?: string,\n description?: string\n): Promise<SkillInstallResult> {\n try {\n // Validate file exists and is readable\n const stats = await stat(filePath);\n if (!stats.isFile()) {\n return { success: false, name: 'unknown', error: 'Path is not a file' };\n }\n \n // Read file content\n const content = await readFile(filePath, 'utf-8');\n if (!content.trim()) {\n return { success: false, name: 'unknown', error: 'File is empty' };\n }\n \n // Derive skill name from filename if not provided\n const ext = extname(filePath);\n const baseFileName = basename(filePath, ext);\n const name = skillName || baseFileName.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-');\n \n // Check if skill already exists in primary directory\n const primarySkillPath = join(GLOBAL_SKILLS_DIR, name);\n if (existsSync(primarySkillPath)) {\n return { success: false, name, error: `Skill \"${name}\" already exists. Use a different name or remove the existing skill.` };\n }\n \n // Generate SKILL.md content\n const skillDescription = description || `Custom skill created from ${basename(filePath)}`;\n const skillMdContent = `---\nname: ${name}\ndescription: ${skillDescription}\nauthor: custom\ntags: [custom, local]\n---\n\n# ${name}\n\n${content}\n`;\n \n // Metadata\n const metadata = {\n installedFrom: `file://${filePath}`,\n installedAt: new Date().toISOString(),\n type: 'custom',\n originalFile: basename(filePath),\n };\n \n // Write to all global skill directories\n const { primaryPath, writtenTo } = await writeSkillToAllDirs(name, skillMdContent, metadata);\n \n if (writtenTo.length === 0) {\n return { success: false, name, error: 'Failed to write skill to any directory' };\n }\n \n return { \n success: true, \n name, \n path: primaryPath,\n writtenTo,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { success: false, name: skillName || 'unknown', error: message };\n }\n}\n\n/**\n * Create a global skill from raw text content\n * \n * @param content - The skill content/instructions\n * @param skillName - Name for the skill\n * @param description - Optional description\n */\nexport async function createSkillFromText(\n content: string,\n skillName: string,\n description?: string\n): Promise<SkillInstallResult> {\n try {\n if (!content.trim()) {\n return { success: false, name: skillName, error: 'Content is empty' };\n }\n \n // Sanitize skill name\n const name = skillName.toLowerCase().replace(/[^a-z0-9-]/g, '-').replace(/-+/g, '-');\n \n // Check if skill already exists in primary directory\n const primarySkillPath = join(GLOBAL_SKILLS_DIR, name);\n if (existsSync(primarySkillPath)) {\n return { success: false, name, error: `Skill \"${name}\" already exists. Use a different name or remove the existing skill.` };\n }\n \n // Generate SKILL.md content\n const skillDescription = description || `Custom skill: ${name}`;\n const skillMdContent = `---\nname: ${name}\ndescription: ${skillDescription}\nauthor: custom\ntags: [custom, local]\n---\n\n# ${name}\n\n${content}\n`;\n \n // Metadata\n const metadata = {\n installedFrom: 'custom-text',\n installedAt: new Date().toISOString(),\n type: 'custom',\n };\n \n // Write to all global skill directories\n const { primaryPath, writtenTo } = await writeSkillToAllDirs(name, skillMdContent, metadata);\n \n if (writtenTo.length === 0) {\n return { success: false, name, error: 'Failed to write skill to any directory' };\n }\n \n return { success: true, name, path: primaryPath, writtenTo };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { success: false, name: skillName, error: message };\n }\n}\n\n/**\n * Remove a global skill from all directories\n */\nexport async function removeGlobalSkill(skillName: string): Promise<boolean> {\n let removed = false;\n \n // Remove from all global skill directories\n for (const baseDir of getAllGlobalSkillDirs()) {\n const skillPath = join(baseDir, skillName);\n try {\n if (existsSync(skillPath)) {\n await rm(skillPath, { recursive: true });\n removed = true;\n }\n } catch {\n // Continue removing from other directories\n }\n }\n \n return removed;\n}\n\n/**\n * Check if a path looks like a file path (for drag-drop detection)\n */\nexport function isFilePath(input: string): boolean {\n const trimmed = input.trim();\n // Check for common path patterns\n return (\n trimmed.startsWith('/') ||\n trimmed.startsWith('~') ||\n trimmed.startsWith('./') ||\n trimmed.startsWith('../') ||\n /^[A-Za-z]:\\\\/.test(trimmed) || // Windows paths\n existsSync(trimmed)\n );\n}\n","/**\n * Skill Parser\n * \n * Parses SKILL.md files to extract frontmatter and content.\n * Skills follow the Agent Skills specification from skills.sh.\n */\n\nimport { readFile } from 'fs/promises';\nimport { join } from 'path';\nimport type { ParsedSkill, SkillFrontmatter } from '../types/external-skill.js';\n\n/**\n * Parse a SKILL.md file from a skill directory\n */\nexport async function parseSkillMd(skillPath: string): Promise<ParsedSkill> {\n const skillMdPath = join(skillPath, 'SKILL.md');\n const rawContent = await readFile(skillMdPath, 'utf-8');\n \n const frontmatterMatch = rawContent.match(/^---\\n([\\s\\S]*?)\\n---/);\n if (!frontmatterMatch || !frontmatterMatch[1]) {\n throw new Error('Invalid SKILL.md: missing YAML frontmatter');\n }\n \n const frontmatter = parseYamlFrontmatter(frontmatterMatch[1]);\n \n if (!frontmatter.name || !frontmatter.description) {\n throw new Error('Invalid SKILL.md: missing required name or description in frontmatter');\n }\n \n const content = rawContent.slice(frontmatterMatch[0].length).trim();\n \n return {\n frontmatter,\n content,\n rawContent,\n };\n}\n\n/**\n * Simple YAML frontmatter parser\n * Handles basic key: value pairs without external dependencies\n */\nfunction parseYamlFrontmatter(yaml: string): SkillFrontmatter {\n const result: Record<string, unknown> = {};\n const lines = yaml.split('\\n');\n \n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed || trimmed.startsWith('#')) continue;\n \n const colonIndex = trimmed.indexOf(':');\n if (colonIndex === -1) continue;\n \n const key = trimmed.slice(0, colonIndex).trim();\n let value: unknown = trimmed.slice(colonIndex + 1).trim();\n \n if (value === '') continue;\n \n // Remove quotes if present\n if (typeof value === 'string') {\n if ((value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))) {\n value = value.slice(1, -1);\n }\n \n // Handle arrays (simple format: [item1, item2])\n if (typeof value === 'string' && value.startsWith('[') && value.endsWith(']')) {\n value = value.slice(1, -1).split(',').map(s => s.trim().replace(/^[\"']|[\"']$/g, ''));\n }\n }\n \n result[key] = value;\n }\n \n return result as unknown as SkillFrontmatter;\n}\n\n/**\n * Extract just the name from a SKILL.md without full parsing\n */\nexport async function extractSkillName(skillPath: string): Promise<string | null> {\n try {\n const parsed = await parseSkillMd(skillPath);\n return parsed.frontmatter.name;\n } catch {\n return null;\n }\n}\n","/**\n * Skill Security Scanner\n * \n * Scans skills for malicious patterns before installation\n * Inspired by ClawdHub supply chain attack research\n */\n\nimport { readFile, readdir, stat } from 'fs/promises';\nimport { join, relative } from 'path';\n\nexport interface SecurityScanResult {\n safe: boolean;\n risks: SecurityRisk[];\n requiredPermissions: SkillPermission[];\n filesScanned: number;\n scanDuration: number;\n}\n\nexport interface SecurityRisk {\n severity: 'critical' | 'high' | 'medium' | 'low';\n category: 'shell-execution' | 'network-access' | 'file-system' | 'credential-access' | 'reconnaissance' | 'persistence' | 'exfiltration';\n description: string;\n location: string;\n pattern: string;\n recommendation: string;\n}\n\nexport interface SkillPermission {\n name: string;\n description: string;\n required: boolean;\n}\n\n/**\n * Dangerous patterns that indicate potential malicious behavior\n * Based on common supply chain attack techniques\n */\nconst DANGEROUS_PATTERNS = [\n // Network exfiltration\n {\n pattern: /curl\\s+.*-X\\s+POST.*https?:\\/\\/(?!github\\.com|githubusercontent\\.com|npmjs\\.org|pypi\\.org)/gi,\n severity: 'critical' as const,\n category: 'exfiltration' as const,\n description: 'HTTP POST to external domain - possible data exfiltration',\n recommendation: 'Review the destination URL. Only allow posts to trusted domains.'\n },\n {\n pattern: /wget\\s+.*--post/gi,\n severity: 'critical' as const,\n category: 'exfiltration' as const,\n description: 'wget POST request - possible data exfiltration',\n recommendation: 'Verify the destination and data being sent.'\n },\n \n // Credential access\n {\n pattern: /\\.env(?!\\.example)/gi,\n severity: 'critical' as const,\n category: 'credential-access' as const,\n description: 'Access to .env file - may expose secrets',\n recommendation: 'Skills should not access .env files. Use explicit configuration instead.'\n },\n {\n pattern: /\\.ssh[\\/\\\\](?:id_rsa|id_ed25519|authorized_keys)/gi,\n severity: 'critical' as const,\n category: 'credential-access' as const,\n description: 'Access to SSH keys - credential theft attempt',\n recommendation: 'Block this skill. SSH key access is never legitimate for code analysis.'\n },\n {\n pattern: /\\.aws[\\/\\\\]credentials/gi,\n severity: 'critical' as const,\n category: 'credential-access' as const,\n description: 'Access to AWS credentials',\n recommendation: 'Block this skill. AWS credential access indicates malicious intent.'\n },\n {\n pattern: /(?:AWS|ANTHROPIC|OPENAI|GITHUB)_(?:ACCESS_)?(?:SECRET_)?KEY/gi,\n severity: 'high' as const,\n category: 'credential-access' as const,\n description: 'API key access pattern detected',\n recommendation: 'Verify this is necessary for skill functionality.'\n },\n \n // Persistence mechanisms\n {\n pattern: /crontab\\s+-e|crontab.*<<.*EOF/gi,\n severity: 'critical' as const,\n category: 'persistence' as const,\n description: 'Crontab modification - persistence mechanism',\n recommendation: 'Block this skill. Cron modification indicates malware behavior.'\n },\n {\n pattern: /\\.(?:bashrc|zshrc|profile|bash_profile)\\s*>>/gi,\n severity: 'critical' as const,\n category: 'persistence' as const,\n description: 'Shell profile modification - persistence mechanism',\n recommendation: 'Block this skill. Shell profile modification is malicious.'\n },\n \n // Shell execution (context-dependent)\n {\n pattern: /(?:bash|sh)\\s+-c\\s+[\"'].*(?:curl|wget)/gi,\n severity: 'high' as const,\n category: 'shell-execution' as const,\n description: 'Shell command with network access',\n recommendation: 'Review the command. Should use proper APIs instead of shell.'\n },\n {\n pattern: /eval\\s*\\(/gi,\n severity: 'high' as const,\n category: 'shell-execution' as const,\n description: 'eval() usage - potential code injection',\n recommendation: 'eval() should be avoided. Review for necessity.'\n },\n \n // Reconnaissance\n {\n pattern: /\\b(?:hostname|whoami|uname|id)\\b(?:\\s|$|;|\\||&)/gi,\n severity: 'medium' as const,\n category: 'reconnaissance' as const,\n description: 'System reconnaissance command',\n recommendation: 'Review if system info is necessary for skill functionality.'\n },\n {\n pattern: /env\\s*(?:$|;|\\||>>)/gim,\n severity: 'medium' as const,\n category: 'reconnaissance' as const,\n description: 'Environment variable enumeration',\n recommendation: 'Skills should not need to enumerate all env variables.'\n },\n \n // File enumeration\n {\n pattern: /find\\s+.*-name\\s+['\"].*\\.(?:env|pem|key|credentials)/gi,\n severity: 'high' as const,\n category: 'credential-access' as const,\n description: 'Searching for credential files',\n recommendation: 'Block this skill. Credential file enumeration is malicious.'\n },\n {\n pattern: /grep\\s+-r.*(?:password|secret|token|key)/gi,\n severity: 'high' as const,\n category: 'credential-access' as const,\n description: 'Recursive search for secrets',\n recommendation: 'Skills should use static analysis, not grep for secrets.'\n },\n \n // Encoding/obfuscation (often used for evasion)\n {\n pattern: /base64.*\\|\\s*(?:curl|wget|bash|sh)/gi,\n severity: 'critical' as const,\n category: 'exfiltration' as const,\n description: 'Base64 encoding with command execution - obfuscation technique',\n recommendation: 'Block this skill. Base64 piping indicates malicious behavior.'\n },\n {\n pattern: /tar\\s+.*\\|\\s*(?:curl|wget)/gi,\n severity: 'critical' as const,\n category: 'exfiltration' as const,\n description: 'Archiving and sending data externally',\n recommendation: 'Block this skill. Tar piping indicates data exfiltration.'\n },\n \n // Network access to suspicious TLDs\n {\n pattern: /https?:\\/\\/[^\\s'\"]+\\.(?:tk|ml|ga|cf|gq|top|xyz)\\b/gi,\n severity: 'high' as const,\n category: 'network-access' as const,\n description: 'Access to domain with suspicious TLD',\n recommendation: 'Free TLDs are often used for malicious infrastructure. Verify legitimacy.'\n },\n];\n\n/**\n * Known safe domains that skills may legitimately access\n */\nconst SAFE_DOMAINS = [\n 'github.com',\n 'githubusercontent.com',\n 'api.github.com',\n 'raw.githubusercontent.com',\n 'npmjs.org',\n 'registry.npmjs.org',\n 'pypi.org',\n 'anthropic.com',\n 'openai.com',\n];\n\n/**\n * Recursively find all files in a directory\n */\nasync function findAllFiles(dir: string, files: string[] = []): Promise<string[]> {\n const entries = await readdir(dir, { withFileTypes: true });\n \n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n \n if (entry.isDirectory()) {\n // Skip hidden and common non-skill directories\n if (!entry.name.startsWith('.') && entry.name !== 'node_modules') {\n await findAllFiles(fullPath, files);\n }\n } else if (entry.isFile()) {\n // Scan text files only\n const ext = entry.name.split('.').pop()?.toLowerCase();\n if (ext && ['md', 'txt', 'js', 'ts', 'py', 'sh', 'bash', 'json', 'yaml', 'yml'].includes(ext)) {\n files.push(fullPath);\n }\n }\n }\n \n return files;\n}\n\n/**\n * Get line number for a match index in text\n */\nfunction getLineNumber(text: string, index: number): number {\n return text.substring(0, index).split('\\n').length;\n}\n\n/**\n * Extract URLs from text\n */\nfunction extractUrls(text: string): string[] {\n const urlPattern = /https?:\\/\\/[^\\s'\"<>)]+/gi;\n return Array.from(text.matchAll(urlPattern), m => m[0]);\n}\n\n/**\n * Check if a URL is from a known safe domain\n */\nfunction isSafeDomain(url: string): boolean {\n try {\n const hostname = new URL(url).hostname.toLowerCase();\n return SAFE_DOMAINS.some(safe => \n hostname === safe || hostname.endsWith('.' + safe)\n );\n } catch {\n return false;\n }\n}\n\n/**\n * Scan a skill directory for security threats\n */\nexport async function scanSkillForThreats(skillPath: string): Promise<SecurityScanResult> {\n const startTime = Date.now();\n const risks: SecurityRisk[] = [];\n const permissions = new Set<string>();\n \n // Find all files to scan\n const files = await findAllFiles(skillPath);\n \n // Scan each file\n for (const file of files) {\n const relPath = relative(skillPath, file);\n \n try {\n const stats = await stat(file);\n \n // Skip large files (>1MB) to avoid DoS\n if (stats.size > 1024 * 1024) {\n continue;\n }\n \n const content = await readFile(file, 'utf-8');\n \n // Check against dangerous patterns\n for (const rule of DANGEROUS_PATTERNS) {\n const matches = content.matchAll(rule.pattern);\n \n for (const match of matches) {\n const lineNum = getLineNumber(content, match.index ?? 0);\n \n risks.push({\n severity: rule.severity,\n category: rule.category,\n description: rule.description,\n location: `${relPath}:${lineNum}`,\n pattern: match[0].substring(0, 100), // Limit pattern length\n recommendation: rule.recommendation,\n });\n \n // Track required permissions based on detected patterns\n if (rule.category === 'shell-execution') {\n permissions.add('shell:execute');\n } else if (rule.category === 'network-access') {\n permissions.add('network:access');\n } else if (rule.category === 'credential-access') {\n permissions.add('credential:read');\n }\n }\n }\n \n // Check for external URLs not caught by patterns\n const urls = extractUrls(content);\n for (const url of urls) {\n if (!isSafeDomain(url)) {\n risks.push({\n severity: 'medium',\n category: 'network-access',\n description: `External URL: ${url}`,\n location: relPath,\n pattern: url,\n recommendation: 'Verify this domain is necessary and trustworthy.',\n });\n permissions.add('network:access');\n }\n }\n \n } catch (error) {\n // Skip files we can't read\n continue;\n }\n }\n \n // Determine if skill is safe overall\n const criticalRisks = risks.filter(r => r.severity === 'critical');\n const highRisks = risks.filter(r => r.severity === 'high');\n \n const safe = criticalRisks.length === 0 && highRisks.length < 3;\n \n // Convert permissions to structured format\n const requiredPermissions: SkillPermission[] = Array.from(permissions).map(perm => ({\n name: perm,\n description: getPermissionDescription(perm),\n required: true,\n }));\n \n return {\n safe,\n risks: risks.sort((a, b) => {\n // Sort by severity: critical > high > medium > low\n const severityOrder = { critical: 0, high: 1, medium: 2, low: 3 };\n return severityOrder[a.severity] - severityOrder[b.severity];\n }),\n requiredPermissions,\n filesScanned: files.length,\n scanDuration: Date.now() - startTime,\n };\n}\n\nfunction getPermissionDescription(permission: string): string {\n const descriptions: Record<string, string> = {\n 'shell:execute': 'Execute shell commands on your system',\n 'network:access': 'Make network requests to external servers',\n 'credential:read': 'Access credential files and environment variables',\n 'file:write': 'Modify files in your project',\n 'file:read': 'Read files in your project',\n };\n \n return descriptions[permission] || permission;\n}\n\n/**\n * Quick check if a skill has any critical security issues\n */\nexport async function quickSecurityCheck(skillPath: string): Promise<boolean> {\n const result = await scanSkillForThreats(skillPath);\n return result.safe;\n}\n\n/**\n * Get human-readable summary of security scan\n */\nexport function formatSecuritySummary(result: SecurityScanResult): string {\n if (result.risks.length === 0) {\n return '✅ No security risks detected';\n }\n \n const critical = result.risks.filter(r => r.severity === 'critical').length;\n const high = result.risks.filter(r => r.severity === 'high').length;\n const medium = result.risks.filter(r => r.severity === 'medium').length;\n const low = result.risks.filter(r => r.severity === 'low').length;\n \n const parts: string[] = [];\n \n if (critical > 0) parts.push(`🔴 ${critical} critical`);\n if (high > 0) parts.push(`🟠 ${high} high`);\n if (medium > 0) parts.push(`🟡 ${medium} medium`);\n if (low > 0) parts.push(`🔵 ${low} low`);\n \n return parts.join(', ') + ' risk' + (result.risks.length === 1 ? '' : 's');\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 type { SkillFrontmatter } from '../types/external-skill.js';\nimport { runShellCommandSync } from '../utils/command-runner.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 const command = process.platform === 'win32' ? `where ${binary}` : `which ${binary}`;\n const { exitCode } = runShellCommandSync(\n command,\n { actor: 'internal:skill-gating', triggeredBy: 'scan', targetPath: process.cwd() },\n { captureOutput: false }\n );\n return exitCode === 0;\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 { BaseSkill } 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 '../installer.js';\nimport { parseSkillMd } from '../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 '../gating.js';\n\nexport class SkillReviewSkill extends BaseSkill {\n name = 'skill-review';\n description = 'Applies installed skills from GitHub repositories to code review';\n version = '1.0.0';\n override author = 'Trie Agent';\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// Backward compatibility export\nexport { SkillReviewSkill as SkillReviewAgent };\n","/**\n * Custom Skill - Runtime class for document-generated skills\n */\n\nimport { BaseSkill } from './base-agent.js';\nimport type { Issue, ScanContext, CodeContext, AgentPriority } from '../types/index.js';\nimport type { GeneratedAgentConfig, DetectionRule } from '../../types/custom-agent.js';\nimport { isInteractiveMode } from '../../utils/progress.js';\n\nexport class CustomSkill extends BaseSkill {\n override name: string;\n override description: string;\n override version: string;\n override author?: string = undefined;\n override authorUrl?: string = undefined;\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 // Custom skills can have user-provided author attribution\n const authorAttr = (config as GeneratedAgentConfig & { author?: string }).author;\n if (authorAttr !== undefined) {\n this.author = authorAttr;\n }\n const authorUrlAttr = (config as GeneratedAgentConfig & { authorUrl?: string }).authorUrl;\n if (authorUrlAttr !== undefined) {\n this.authorUrl = authorUrlAttr;\n }\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 if (!isInteractiveMode()) {\n console.error(`${this.name}: Error reading file ${file}:`, error);\n }\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 if (!isInteractiveMode()) {\n console.error(`Invalid regex pattern in rule ${rule.id}: ${pattern}`);\n }\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 { Skill } from '../types/index.js';\nimport { SecuritySkill } from './security.js';\nimport { PrivacySkill } from './privacy.js';\nimport { TypeCheckSkill } from './typecheck.js';\nimport { ComprehensionSkill } from './comprehension.js';\nimport { AccessibilitySkill } from './accessibility.js';\nimport { DesignEngineerSkill } from './design-engineer.js';\nimport { LegalSkill } from './legal.js';\nimport { TestSkill } from './test.js';\nimport { SoftwareArchitectSkill } from './software-architect.js';\nimport { DevOpsSkill } from './devops.js';\nimport { BugFindingSkill } from './bug-finding.js';\nimport { UserTestingSkill } from './user-testing.js';\nimport { TrieCleanSkill } from './trie-clean.js';\nimport { SOC2Skill } from './soc2.js';\nimport { SuperReviewerSkill } from './super-reviewer.js';\nimport { AgentSmithSkill } from './agent-smith.js';\nimport { PerformanceSkill } from './performance.js';\nimport { E2ESkill } from './e2e.js';\nimport { VisualQASkill } from './visual-qa.js';\nimport { DataFlowSkill } from './data-flow.js';\nimport { MoneybagSkill } from './moneybags.js';\nimport { ProductionReadySkill } from './production-ready.js';\nimport { SkillReviewSkill } 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, getTrieDirectory } from '../utils/workspace.js';\nimport { isInteractiveMode } from '../../utils/progress.js';\n\nclass SkillRegistryImpl {\n private skills: Map<string, Skill> = new Map();\n private customSkillsLoaded: boolean = false;\n private initialized: boolean = false;\n\n constructor() {\n this.registerBuiltinSkills();\n }\n\n private registerBuiltinSkills() {\n if (this.initialized) return;\n this.initialized = true;\n\n const builtinSkills: Skill[] = [\n // Core skills (always available)\n new SecuritySkill(),\n new PrivacySkill(),\n new TypeCheckSkill(),\n new ComprehensionSkill(),\n \n // Specialized skills\n new AccessibilitySkill(),\n new DesignEngineerSkill(),\n new LegalSkill(),\n new TestSkill(),\n new SoftwareArchitectSkill(),\n new DevOpsSkill(),\n new BugFindingSkill(),\n new UserTestingSkill(),\n new TrieCleanSkill(),\n new SOC2Skill(),\n new SuperReviewerSkill(),\n new AgentSmithSkill(),\n \n // New skills (inspired by Turkey Build)\n new PerformanceSkill(),\n new E2ESkill(),\n new VisualQASkill(),\n new DataFlowSkill(),\n \n // Cost analysis skill\n new MoneybagSkill(),\n \n // Production readiness gate\n new ProductionReadySkill(),\n \n // Skill review skill (applies external skills)\n new SkillReviewSkill(),\n ];\n\n // Only log from main thread, not workers (workers have isMainThread = false)\n // Also check TRIE_QUIET env to suppress entirely\n const isWorker = typeof process !== 'undefined' && \n (process.env.TRIE_WORKER === 'true' || process.env.NODE_ENV === 'test');\n if (!isWorker && !process.env.TRIE_QUIET && !isInteractiveMode()) {\n console.error(`Loaded config for ${builtinSkills.length} built-in scouts`);\n }\n\n for (const skill of builtinSkills) {\n this.skills.set(skill.name, skill);\n }\n }\n\n /**\n * Load custom skills from .trie/agents/ directory\n */\n async loadCustomSkills(): Promise<void> {\n if (this.customSkillsLoaded) return;\n \n try {\n const skillsDir = join(getTrieDirectory(getWorkingDirectory(undefined, true)), '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.skills.set(skill.name, skill);\n loadedCount++;\n \n } catch (error) {\n if (!isInteractiveMode()) {\n console.error(`Failed to load custom skill from ${file}:`, error);\n }\n }\n }\n \n if (loadedCount > 0 && !isInteractiveMode()) {\n console.error(`Loaded ${loadedCount} custom skill(s) from .trie/agents/`);\n }\n \n this.customSkillsLoaded = true;\n } catch (error) {\n // Directory doesn't exist or other error - that's okay\n this.customSkillsLoaded = true;\n }\n \n // Load skills for the SkillReviewSkill\n await this.loadSkillsForSkill();\n }\n\n // Backward compatibility alias\n async loadCustomAgents(): Promise<void> {\n return this.loadCustomSkills();\n }\n \n /**\n * Load installed skills for the SkillReviewSkill\n */\n private async loadSkillsForSkill(): Promise<void> {\n const skillReviewAgent = this.skills.get('skill-review');\n if (skillReviewAgent && skillReviewAgent instanceof SkillReviewSkill) {\n await skillReviewAgent.loadSkills();\n if (skillReviewAgent.hasSkills() && !isInteractiveMode()) {\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.skills.entries()) {\n if (agent instanceof CustomSkill) {\n this.skills.delete(name);\n }\n }\n \n this.customSkillsLoaded = false;\n await this.loadCustomSkills();\n }\n\n // Backward compatibility alias\n async reloadCustomAgents(): Promise<void> {\n return this.reloadCustomSkills();\n }\n\n getSkill(name: string): Skill | undefined {\n return this.skills.get(name);\n }\n\n // Backward compatibility alias\n getAgent(name: string): Skill | undefined {\n return this.getSkill(name);\n }\n\n getSkillsByNames(names: string[]): Skill[] {\n return names\n .map(name => this.getSkill(name))\n .filter((skill): skill is Skill => skill !== undefined);\n }\n\n // Backward compatibility alias\n getAgentsByNames(names: string[]): Skill[] {\n return this.getSkillsByNames(names);\n }\n\n getAllSkills(): Skill[] {\n return Array.from(this.skills.values());\n }\n\n // Backward compatibility alias\n getAllAgents(): Skill[] {\n return this.getAllSkills();\n }\n\n /**\n * Get only built-in skills\n */\n getBuiltinSkills(): Skill[] {\n return Array.from(this.skills.values()).filter(\n skill => !(skill instanceof CustomSkill)\n );\n }\n\n // Backward compatibility alias\n getBuiltinAgents(): Skill[] {\n return this.getBuiltinSkills();\n }\n\n /**\n * Get only custom skills\n */\n getCustomSkills(): CustomSkill[] {\n return Array.from(this.skills.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 registerSkill(skill: Skill): void {\n this.skills.set(skill.name, skill);\n if (!isInteractiveMode()) {\n console.error(`Registered custom skill: ${skill.name}`);\n }\n }\n\n // Backward compatibility alias\n registerAgent(skill: Skill): void {\n this.registerSkill(skill);\n }\n\n /**\n * Unregister a skill by name\n */\n unregisterSkill(name: string): boolean {\n return this.skills.delete(name);\n }\n\n // Backward compatibility alias\n unregisterAgent(name: string): boolean {\n return this.unregisterSkill(name);\n }\n\n getSkillNames(): string[] {\n return Array.from(this.skills.keys());\n }\n\n getSkillDescriptions(): { name: string; description: string; isCustom: boolean }[] {\n return Array.from(this.skills.values()).map(skill => ({\n name: skill.name,\n description: skill.description,\n isCustom: skill instanceof CustomSkill,\n }));\n }\n\n /**\n * Check if a skill is custom\n */\n isCustomSkill(name: string): boolean {\n const skill = this.skills.get(name);\n return skill 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 skill = this.skills.get(name);\n if (skill instanceof CustomSkill) {\n return skill.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_SKILL_REGISTRY__';\nconst LEGACY_SINGLETON_KEY = '__TRIE_AGENT_REGISTRY__';\nconst LOGGED_KEY = '__TRIE_REGISTRY_LOGGED__';\n\n/**\n * Get the singleton SkillRegistry instance\n */\nexport function getSkillRegistry(): SkillRegistryImpl {\n const global = globalThis as unknown as Record<string, SkillRegistryImpl | boolean | undefined>;\n if (!global[SINGLETON_KEY]) {\n const existing = global[LEGACY_SINGLETON_KEY] as SkillRegistryImpl | undefined;\n global[SINGLETON_KEY] = existing ?? new SkillRegistryImpl();\n global[LEGACY_SINGLETON_KEY] = global[SINGLETON_KEY];\n }\n return global[SINGLETON_KEY] as SkillRegistryImpl;\n}\n\n/**\n * Check if we've already logged the \"Loaded config\" message\n */\nexport function hasLoggedRegistryInit(): boolean {\n const global = globalThis as unknown as Record<string, boolean | undefined>;\n return global[LOGGED_KEY] === true;\n}\n\n/**\n * Mark that we've logged the registry init message\n */\nexport function markRegistryLogged(): void {\n const global = globalThis as unknown as Record<string, boolean>;\n global[LOGGED_KEY] = true;\n}\n\n/**\n * SkillRegistry class - use getSkillRegistry() for singleton access\n * @deprecated Use getSkillRegistry() instead to ensure singleton behavior\n */\nexport class SkillRegistry extends SkillRegistryImpl {\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAOA,SAAS,UAAU,WAAW,aAAa;AAC3C,SAAS,kBAAkB;AAC3B,SAAS,YAAY;AAGrB,IAAM,kBAAkB;AAKjB,SAAS,qBAA6B;AAC3C,SAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA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existsSync","basename","existsSync","summary","mkdir","writeFile","readdir","readFile","stat","join","basename","extname","existsSync","readFile","join","readFile","join","join","mkdir","parsed","writeFile","readdir","readFile","readdir","join","readFile","mkdir","existsSync","writeFile","stat","extname","basename","join","existsSync","existsSync","readFile","join","existsSync","join","readFile","readdir","readFile","join","join","readdir","readFile"]}