@triedotdev/mcp 1.0.94 → 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.
- package/README.md +145 -137
- package/dist/{chunk-JAAIHNOE.js → chunk-APMV77PU.js} +21 -6
- package/dist/chunk-APMV77PU.js.map +1 -0
- package/dist/{chunk-HLSBTOVE.js → chunk-B3MNN3XB.js} +13 -18
- package/dist/{chunk-HLSBTOVE.js.map → chunk-B3MNN3XB.js.map} +1 -1
- package/dist/{chunk-JO6RVXS6.js → chunk-F4NJ4CBP.js} +2 -2
- package/dist/{chunk-AZRCKBGF.js → chunk-FNCCZ3XB.js} +1222 -75
- package/dist/chunk-FNCCZ3XB.js.map +1 -0
- package/dist/chunk-G76DYVGX.js +136 -0
- package/dist/chunk-G76DYVGX.js.map +1 -0
- package/dist/chunk-HSNE46VE.js +956 -0
- package/dist/chunk-HSNE46VE.js.map +1 -0
- package/dist/{chunk-STEFLYPR.js → chunk-IXO4G4D3.js} +2 -2
- package/dist/{chunk-OEYIOOYB.js → chunk-JDHR5BDR.js} +2 -3
- package/dist/chunk-NIASHOAB.js +1304 -0
- package/dist/chunk-NIASHOAB.js.map +1 -0
- package/dist/{chunk-CKM6A3G6.js → chunk-OVRG5RP3.js} +6 -7
- package/dist/chunk-OVRG5RP3.js.map +1 -0
- package/dist/{chunk-RYRVEO2B.js → chunk-R3I2GCZC.js} +3 -3
- package/dist/{chunk-WT3XQCG2.js → chunk-R4AAPFXC.js} +2 -2
- package/dist/{chunk-IIF5XDCJ.js → chunk-SLL2MDJD.js} +786 -4694
- package/dist/chunk-SLL2MDJD.js.map +1 -0
- package/dist/cli/create-agent.js +931 -7
- package/dist/cli/create-agent.js.map +1 -1
- package/dist/cli/main.js +151 -383
- package/dist/cli/main.js.map +1 -1
- package/dist/cli/yolo-daemon.js +13 -20
- package/dist/cli/yolo-daemon.js.map +1 -1
- package/dist/{goal-manager-HOZ7R2QV.js → goal-manager-LAOT4QQX.js} +6 -6
- package/dist/guardian-agent-M352CBE5.js +19 -0
- package/dist/index.js +1025 -1550
- package/dist/index.js.map +1 -1
- package/dist/{issue-store-DXIOP6AK.js → issue-store-W2X33X2X.js} +4 -4
- package/dist/{progress-LHI66U7B.js → progress-PQVEM7BR.js} +2 -2
- package/dist/{vibe-code-signatures-C5A4BHXD.js → vibe-code-signatures-ELEWJFGZ.js} +3 -3
- package/dist/{vulnerability-signatures-SVIHJQO5.js → vulnerability-signatures-EIJQX2TS.js} +3 -3
- package/dist/workers/agent-worker.js +2 -11
- package/dist/workers/agent-worker.js.map +1 -1
- package/package.json +2 -2
- package/dist/agent-smith-MYQ35URL.js +0 -14
- package/dist/agent-smith-runner-4TBONXCP.js +0 -573
- package/dist/agent-smith-runner-4TBONXCP.js.map +0 -1
- package/dist/cache-manager-RMPRPD5T.js +0 -10
- package/dist/chunk-AZRCKBGF.js.map +0 -1
- package/dist/chunk-CKM6A3G6.js.map +0 -1
- package/dist/chunk-E2ZATINO.js +0 -10879
- package/dist/chunk-E2ZATINO.js.map +0 -1
- package/dist/chunk-FFWNZUG2.js +0 -266
- package/dist/chunk-FFWNZUG2.js.map +0 -1
- package/dist/chunk-FK6DQKDY.js +0 -175
- package/dist/chunk-FK6DQKDY.js.map +0 -1
- package/dist/chunk-IFGF33R5.js +0 -279
- package/dist/chunk-IFGF33R5.js.map +0 -1
- package/dist/chunk-IIF5XDCJ.js.map +0 -1
- package/dist/chunk-JAAIHNOE.js.map +0 -1
- package/dist/chunk-ODWDESYP.js +0 -141
- package/dist/chunk-ODWDESYP.js.map +0 -1
- package/dist/chunk-OWBWNXSC.js +0 -955
- package/dist/chunk-OWBWNXSC.js.map +0 -1
- package/dist/chunk-Q764X2WD.js +0 -2124
- package/dist/chunk-Q764X2WD.js.map +0 -1
- package/dist/chunk-RE6ZWXJC.js +0 -279
- package/dist/chunk-RE6ZWXJC.js.map +0 -1
- package/dist/chunk-RNJ6JKMA.js +0 -2270
- package/dist/chunk-RNJ6JKMA.js.map +0 -1
- package/dist/chunk-Y62VM3ER.js +0 -536
- package/dist/chunk-Y62VM3ER.js.map +0 -1
- package/dist/git-45LZUUYA.js +0 -29
- package/dist/guardian-agent-RB2UQP5V.js +0 -21
- package/dist/progress-LHI66U7B.js.map +0 -1
- package/dist/vibe-code-signatures-C5A4BHXD.js.map +0 -1
- package/dist/vulnerability-signatures-SVIHJQO5.js.map +0 -1
- /package/dist/{chunk-JO6RVXS6.js.map → chunk-F4NJ4CBP.js.map} +0 -0
- /package/dist/{chunk-STEFLYPR.js.map → chunk-IXO4G4D3.js.map} +0 -0
- /package/dist/{chunk-OEYIOOYB.js.map → chunk-JDHR5BDR.js.map} +0 -0
- /package/dist/{chunk-RYRVEO2B.js.map → chunk-R3I2GCZC.js.map} +0 -0
- /package/dist/{chunk-WT3XQCG2.js.map → chunk-R4AAPFXC.js.map} +0 -0
- /package/dist/{agent-smith-MYQ35URL.js.map → goal-manager-LAOT4QQX.js.map} +0 -0
- /package/dist/{cache-manager-RMPRPD5T.js.map → guardian-agent-M352CBE5.js.map} +0 -0
- /package/dist/{git-45LZUUYA.js.map → issue-store-W2X33X2X.js.map} +0 -0
- /package/dist/{goal-manager-HOZ7R2QV.js.map → progress-PQVEM7BR.js.map} +0 -0
- /package/dist/{guardian-agent-RB2UQP5V.js.map → vibe-code-signatures-ELEWJFGZ.js.map} +0 -0
- /package/dist/{issue-store-DXIOP6AK.js.map → vulnerability-signatures-EIJQX2TS.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/streaming.ts","../src/cli/interactive-dashboard.ts","../src/utils/file-picker.ts","../src/tools/scan.ts","../src/orchestrator/context-analyzer.ts","../src/orchestrator/risk-assessor.ts","../src/analysis/cross-file.ts","../src/analysis/semantic-analyzer.ts","../src/analysis/smart-prioritizer.ts","../src/analysis/attack-surface.ts","../src/trie/symbol-index.ts","../src/trie/incremental-scanner.ts","../src/utils/issue-analyzer.ts","../src/integrations/team-collaboration.ts"],"sourcesContent":["import type { Issue } from '../types/index.js';\nimport { isInteractiveMode } from './progress.js';\nimport type { \n BannerContent, \n SnippetContent, \n CostContent, \n ReadinessContent, \n SemanticContent, \n AttackSurfaceContent \n} from './output-manager.js';\n\n// Internal flag to suppress console output (used in emit error handler)\nconst shouldSuppressConsole = () => isInteractiveMode();\n\n// Rich content event types\nexport type RichContentType = \n | 'snippet' // Code snippet for issue\n | 'cost_report' // Moneybags cost estimate\n | 'readiness_report' // Production readiness\n | 'semantic_report' // Data flow analysis\n | 'attack_surface' // Endpoint analysis\n | 'skill_banner' // ASCII art + quote\n | 'raw_log'; // Raw console log capture\n\nexport interface StreamUpdate {\n type: 'progress' | 'agent_start' | 'agent_complete' | 'issue_found' | 'scan_complete' | 'error' | 'watch_status' | 'watch_change' | 'memory' | RichContentType;\n timestamp: number;\n data: any;\n}\n\n// Re-export rich content types for convenience\nexport type { BannerContent, SnippetContent, CostContent, ReadinessContent, SemanticContent, AttackSurfaceContent };\n\nexport interface ScanProgress {\n totalFiles: number;\n processedFiles: number;\n currentFile?: string;\n activeAgents: string[];\n completedAgents: string[];\n totalIssues: number;\n issuesBySeverity: {\n critical: number;\n serious: number;\n moderate: number;\n low: number;\n };\n}\n\n/**\n * Streaming scan results for real-time feedback\n */\nexport class StreamingManager {\n private listeners: Set<(update: StreamUpdate) => void> = new Set();\n private progress: ScanProgress = {\n totalFiles: 0,\n processedFiles: 0,\n activeAgents: [],\n completedAgents: [],\n totalIssues: 0,\n issuesBySeverity: { critical: 0, serious: 0, moderate: 0, low: 0 }\n };\n\n /**\n * Subscribe to scan updates\n */\n subscribe(callback: (update: StreamUpdate) => void): () => void {\n this.listeners.add(callback);\n return () => this.listeners.delete(callback);\n }\n\n /**\n * Emit an update to all listeners\n */\n private emit(type: StreamUpdate['type'], data: any): void {\n const update: StreamUpdate = {\n type,\n timestamp: Date.now(),\n data\n };\n\n this.listeners.forEach(listener => {\n try {\n listener(update);\n } catch (error) {\n if (!shouldSuppressConsole()) {\n console.warn('Stream listener error:', error);\n }\n }\n });\n }\n\n /**\n * Initialize scan with file count\n */\n startScan(totalFiles: number): void {\n this.progress = {\n totalFiles,\n processedFiles: 0,\n activeAgents: [],\n completedAgents: [],\n totalIssues: 0,\n issuesBySeverity: { critical: 0, serious: 0, moderate: 0, low: 0 }\n };\n\n this.emit('progress', { ...this.progress });\n }\n\n /**\n * Update current file being processed\n */\n updateCurrentFile(file: string): void {\n this.progress.currentFile = file;\n this.emit('progress', { ...this.progress });\n }\n\n /**\n * Mark file as processed\n */\n completeFile(): void {\n this.progress.processedFiles++;\n this.emit('progress', { ...this.progress });\n }\n\n /**\n * Start agent execution\n */\n startAgent(agentName: string): void {\n if (!this.progress.activeAgents.includes(agentName)) {\n this.progress.activeAgents.push(agentName);\n }\n this.emit('agent_start', { agent: agentName });\n this.emit('progress', { ...this.progress });\n }\n\n /**\n * Complete agent execution\n */\n completeAgent(agentName: string, issues: Issue[]): void {\n // Move from active to completed\n this.progress.activeAgents = this.progress.activeAgents.filter(a => a !== agentName);\n if (!this.progress.completedAgents.includes(agentName)) {\n this.progress.completedAgents.push(agentName);\n }\n\n // Update issue counts\n for (const issue of issues) {\n this.progress.issuesBySeverity[issue.severity]++;\n this.progress.totalIssues++;\n }\n\n this.emit('agent_complete', {\n agent: agentName,\n issueCount: issues.length,\n issues: issues.slice(0, 5) // Only send first 5 for streaming\n });\n this.emit('progress', { ...this.progress });\n }\n\n /**\n * Report new issue found\n */\n reportIssue(issue: Issue): void {\n this.progress.issuesBySeverity[issue.severity]++;\n this.progress.totalIssues++;\n this.emit('issue_found', issue);\n this.emit('progress', { ...this.progress });\n }\n\n /**\n * Complete the entire scan\n */\n completeScan(totalIssues: Issue[]): void {\n this.emit('scan_complete', {\n totalFiles: this.progress.totalFiles,\n totalIssues: totalIssues.length,\n issues: totalIssues, // Include all issues for the dashboard\n issuesBySeverity: this.progress.issuesBySeverity,\n completedAgents: this.progress.completedAgents\n });\n }\n\n /**\n * Report error\n */\n reportError(error: Error, context?: string): void {\n this.emit('error', {\n message: error.message,\n context,\n stack: error.stack\n });\n }\n\n /**\n * Get current progress\n */\n getProgress(): ScanProgress {\n return { ...this.progress };\n }\n\n /**\n * Reset state\n */\n reset(): void {\n this.progress = {\n totalFiles: 0,\n processedFiles: 0,\n activeAgents: [],\n completedAgents: [],\n totalIssues: 0,\n issuesBySeverity: { critical: 0, serious: 0, moderate: 0, low: 0 }\n };\n }\n\n /**\n * Report watch status (directories, debounce, last change)\n */\n reportWatchStatus(status: { watching: boolean; directories?: number; debounceMs?: number; lastChange?: string; recentChanges?: Array<{ file: string; time: string }> }): void {\n this.emit('watch_status', status);\n }\n\n /**\n * Report a specific file change when watching\n */\n reportWatchChange(file: string): void {\n this.emit('watch_change', { file });\n }\n\n /**\n * Report memory operations (saving context, learning patterns)\n */\n reportMemory(action: 'saving' | 'saved' | 'learning', details?: string): void {\n this.emit('memory', { action, details });\n }\n\n // ============================================\n // Rich Content Events (for TUI panes)\n // ============================================\n\n /**\n * Report a code snippet for display\n */\n reportSnippet(snippet: SnippetContent): void {\n this.emit('snippet', snippet);\n }\n\n /**\n * Report cost estimate from Moneybags\n */\n reportCost(cost: CostContent): void {\n this.emit('cost_report', cost);\n }\n\n /**\n * Report production readiness score\n */\n reportReadiness(readiness: ReadinessContent): void {\n this.emit('readiness_report', readiness);\n }\n\n /**\n * Report semantic analysis results\n */\n reportSemantic(semantic: SemanticContent): void {\n this.emit('semantic_report', semantic);\n }\n\n /**\n * Report attack surface analysis\n */\n reportAttackSurface(attack: AttackSurfaceContent): void {\n this.emit('attack_surface', attack);\n }\n\n /**\n * Report skill banner (ASCII art + quote)\n */\n reportBanner(banner: BannerContent): void {\n this.emit('skill_banner', banner);\n }\n\n /**\n * Report raw log entry\n */\n reportRawLog(level: 'info' | 'warn' | 'error' | 'debug', message: string): void {\n this.emit('raw_log', { level, message, time: new Date().toLocaleTimeString('en-US', { hour12: false }) });\n }\n}\n\n/**\n * Format streaming updates for console output\n * Returns null if interactive mode is enabled (dashboard handles display)\n */\nexport function formatConsoleUpdate(update: StreamUpdate): string | null {\n // In interactive mode, the dashboard handles all display\n if (isInteractiveMode()) {\n return null;\n }\n\n switch (update.type) {\n case 'agent_start':\n // Suppress agent start messages - they're redundant with progress updates\n return null;\n\n case 'agent_complete':\n const label = update.data.issueCount > 0 ? '[WARN]' : '[OK]';\n const severityBreakdown: string[] = [];\n if (update.data.issues && Array.isArray(update.data.issues)) {\n const bySeverity = { critical: 0, serious: 0, moderate: 0, low: 0 };\n for (const issue of update.data.issues) {\n if (issue.severity && bySeverity.hasOwnProperty(issue.severity)) {\n bySeverity[issue.severity as keyof typeof bySeverity]++;\n }\n }\n if (bySeverity.critical > 0) severityBreakdown.push(`${bySeverity.critical} critical`);\n if (bySeverity.serious > 0) severityBreakdown.push(`${bySeverity.serious} serious`);\n if (bySeverity.moderate > 0) severityBreakdown.push(`${bySeverity.moderate} moderate`);\n if (bySeverity.low > 0) severityBreakdown.push(`${bySeverity.low} low`);\n }\n const breakdown = severityBreakdown.length > 0 ? ` (${severityBreakdown.join(', ')})` : '';\n return `${label} ${update.data.agent}: ${update.data.issueCount} issues${breakdown}`;\n\n case 'progress':\n // Only show progress updates every 10% or when significant changes occur\n const { processedFiles, totalFiles, currentFile, activeAgents } = update.data;\n const progress = totalFiles > 0 ? Math.round((processedFiles / totalFiles) * 100) : 0;\n \n // Suppress frequent progress updates - only show at milestones\n if (totalFiles > 10 && progress % 10 !== 0 && processedFiles !== totalFiles) {\n return null;\n }\n \n const active = activeAgents.length > 0 ? ` (${activeAgents.join(', ')})` : '';\n const current = currentFile && totalFiles <= 10 ? ` - ${currentFile.split('/').pop()}` : '';\n return `Progress: ${progress}% (${processedFiles}/${totalFiles})${active}${current}`;\n\n case 'scan_complete':\n const { totalIssues, totalFiles: filesScanned, issuesBySeverity } = update.data;\n const severitySummary: string[] = [];\n if (issuesBySeverity) {\n if (issuesBySeverity.critical > 0) severitySummary.push(`${issuesBySeverity.critical} critical`);\n if (issuesBySeverity.serious > 0) severitySummary.push(`${issuesBySeverity.serious} serious`);\n if (issuesBySeverity.moderate > 0) severitySummary.push(`${issuesBySeverity.moderate} moderate`);\n if (issuesBySeverity.low > 0) severitySummary.push(`${issuesBySeverity.low} low`);\n }\n const summary = severitySummary.length > 0 ? ` [${severitySummary.join(', ')}]` : '';\n return `[COMPLETE] Scan finished: ${totalIssues} issues across ${filesScanned} files${summary}`;\n\n case 'error':\n return `[ERROR] ${update.data.message}`;\n\n default:\n return null;\n }\n}\n\n/**\n * Simple progress bar for terminal\n */\nexport function createProgressBar(current: number, total: number, width: number = 40): string {\n if (total === 0) return '█'.repeat(width);\n\n const progress = current / total;\n const filled = Math.round(width * progress);\n const empty = width - filled;\n\n return '█'.repeat(filled) + '░'.repeat(empty);\n}","import { stdin as input, stdout as output } from 'process';\nimport * as readline from 'readline';\nimport { existsSync } from 'fs';\nimport { readFile, writeFile, mkdir } from 'fs/promises';\nimport { join, basename } from 'path';\nimport pc from 'picocolors';\nimport type { Issue } from '../types/index.js';\nimport type { \n StreamUpdate, \n ScanProgress, \n BannerContent, \n SnippetContent, \n CostContent, \n ReadinessContent, \n SemanticContent, \n AttackSurfaceContent \n} from '../utils/streaming.js';\nimport { getOutputManager, type NudgeContent } from '../utils/output-manager.js';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport { installSkill, listInstalledSkills, listGlobalSkills, createSkillFromFile, removeGlobalSkill } from '../skills/installer.js';\nimport { openFilePicker, isFilePickerAvailable } from '../utils/file-picker.js';\nimport { getGuardianState, type Goal, type Hypothesis } from '../guardian/guardian-state.js';\nimport { detectStack, getSkillCategories, getSkillsByCategory } from '../bootstrap/stack-detector.js';\nimport { loadContextState } from '../utils/context-state.js';\nimport { getGuardian, type GuardianInsight } from '../guardian/guardian-agent.js';\nimport { isAIAvailable } from '../ai/client.js';\nimport { searchIssues, getRecentIssues, getMemoryStats, type StoredIssue, type IssueMemoryStats } from '../memory/issue-store.js';\nimport { findCrossProjectPatterns, type GlobalPattern } from '../memory/global-memory.js';\n\n/**\n * Color theme for Trie TUI (cyan-based, not orange like Claude Code)\n */\nconst colors = {\n // UI elements\n border: (s: string) => pc.cyan(s),\n header: (s: string) => pc.bold(pc.cyan(s)),\n brand: (s: string) => pc.bold(pc.cyan(s)),\n dim: (s: string) => pc.dim(s),\n \n // Severity levels\n critical: (s: string) => pc.bold(pc.red(s)),\n serious: (s: string) => pc.yellow(s),\n moderate: (s: string) => pc.blue(s),\n low: (s: string) => pc.dim(s),\n \n // Status\n success: (s: string) => pc.green(s),\n running: (s: string) => pc.yellow(s),\n waiting: (s: string) => pc.dim(s),\n alert: (s: string) => pc.bold(pc.red(s)),\n \n // Interactive\n selected: (s: string) => pc.bold(pc.magenta(s)),\n highlight: (s: string) => pc.bold(pc.white(s)),\n \n // Additional\n yellow: (s: string) => pc.yellow(s),\n};\n\n/**\n * Strip ANSI escape codes to get visible string length\n */\n// eslint-disable-next-line no-control-regex\nconst stripAnsi = (s: string): string => s.replace(/\\x1B\\[[0-9;]*[a-zA-Z]/g, '');\n\n/**\n * Calculate visible width of a string, accounting for:\n * - ANSI escape codes (0 width)\n * - Emojis and wide characters (2 width)\n * - Regular characters (1 width)\n */\nconst visibleLength = (s: string): number => {\n const plain = stripAnsi(s);\n let width = 0;\n for (const char of plain) {\n const code = char.codePointAt(0) || 0;\n // Emoji ranges and other wide characters\n if (\n (code >= 0x1F300 && code <= 0x1F9FF) || // Emoji\n (code >= 0x2600 && code <= 0x26FF) || // Misc symbols\n (code >= 0x2700 && code <= 0x27BF) || // Dingbats\n (code >= 0xFE00 && code <= 0xFE0F) || // Variation selectors\n (code >= 0x1F000 && code <= 0x1FFFF) || // Extended emoji\n (code >= 0x3000 && code <= 0x9FFF) || // CJK\n (code >= 0xAC00 && code <= 0xD7AF) // Korean\n ) {\n width += 2;\n } else {\n width += 1;\n }\n }\n return width;\n};\n\n/**\n * Pad a colored string to a target visible width\n */\nconst padEnd = (s: string, targetWidth: number): string => {\n const visible = visibleLength(s);\n const padding = Math.max(0, targetWidth - visible);\n return s + ' '.repeat(padding);\n};\n\n/**\n * Unicode box-drawing characters for cleaner TUI\n */\nconst box = {\n topLeft: '┌',\n topRight: '┐',\n bottomLeft: '└',\n bottomRight: '┘',\n horizontal: '─',\n vertical: '│',\n leftT: '├',\n rightT: '┤',\n topT: '┬',\n bottomT: '┴',\n cross: '┼',\n};\n\n// All available view types (including new rich content views)\ntype DashboardView = \n | 'overview' // Main dashboard with progress\n | 'issues' // Issue list browser\n | 'agents' // Agent/scout status\n | 'files' // Files with issues\n | 'details' // Selected issue with code snippet\n | 'costs' // Moneybags cost breakdown\n | 'readiness' // Production readiness checklist\n | 'analysis' // Semantic + attack surface\n | 'rawlog' // Raw log viewer\n | 'skills' // Skills browser and installer\n | 'guardian' // Guardian notifications history\n | 'goals' // Goals management panel\n | 'hypotheses' // Hypotheses management panel\n | 'memory'; // Memory tree visualization\n\ninterface DashboardState {\n issues: Issue[];\n progress: ScanProgress;\n filter: {\n severity: 'all' | 'critical' | 'serious' | 'moderate' | 'low';\n agent: string | 'all';\n search: string;\n };\n view: DashboardView;\n previousView: DashboardView | null;\n selectedIssue: number;\n selectedAgent: number;\n lastUpdate: number;\n scanComplete: boolean;\n scanEndTime?: number;\n startTime: number;\n scanStartTime: number;\n activityLog: Array<{ time: string; message: string }>;\n activityPage: number;\n agentPage: number;\n quietMode: boolean;\n alerts: {\n hasCritical: boolean;\n lastCriticalAt?: number;\n };\n watch: {\n watching: boolean;\n directories: number;\n debounceMs?: number;\n lastChange?: string;\n recentChanges: Array<{ file: string; time: string }>;\n };\n agents: Record<string, {\n status: 'queued' | 'running' | 'done';\n start?: number;\n end?: number;\n durationMs?: number;\n issues: number;\n }>;\n \n // === NEW: Rich content state ===\n \n // Code snippets for issues (keyed by issue index)\n codeSnippets: Map<number, SnippetContent>;\n \n // Cost report from Moneybags\n costReport: CostContent | null;\n \n // Production readiness from production-ready skill\n readiness: ReadinessContent | null;\n \n // Semantic analysis results\n semanticAnalysis: SemanticContent | null;\n \n // Attack surface analysis\n attackSurface: AttackSurfaceContent | null;\n \n // Skill banners (most recent first)\n skillBanners: BannerContent[];\n \n // Raw log capture (for rawlog view)\n rawLog: Array<{ time: string; level: string; message: string }>;\n rawLogPage: number;\n \n // Scroll positions for scrollable views\n scrollPositions: Record<DashboardView, number>;\n \n // === Proactive Notifications (Guardian Nudges) ===\n notification: {\n active: boolean;\n message: string;\n severity: 'critical' | 'warning' | 'info';\n file?: string;\n timestamp: number;\n autoHideAt?: number; // Auto-dismiss after this timestamp\n } | null;\n notificationHistory: Array<{\n message: string;\n severity: 'critical' | 'warning' | 'info';\n file?: string;\n timestamp: number;\n dismissed: boolean;\n }>;\n \n // Guardian Agent insights - the agentic, conversational alerts\n guardianInsights: GuardianInsight[];\n guardianInitialized: boolean;\n \n // Guardian Agency status (goals, hypotheses, risk, effectiveness)\n agencyStatus: {\n goals: { active: number; completed: number; topGoal?: string };\n hypotheses: { testing: number; validated: number; topHypothesis?: string };\n riskLevel: 'low' | 'medium' | 'high' | 'critical';\n scanFrequency: number;\n effectiveness: number;\n isQuietHours: boolean;\n } | null;\n \n // Guardian insight navigation\n selectedGuardianInsight: number;\n expandedGuardianInsight: number | null; // null = none expanded, number = index of expanded insight\n \n // Global Guardian Agent configuration\n guardianConfig: {\n // Moneybags settings\n moneybags: {\n userCount: number;\n payingUsers: number;\n revenuePerUser: number;\n developerRate: number;\n industry?: 'solopreneur' | 'startup' | 'fintech' | 'healthcare' | 'enterprise' | 'saas' | 'ecommerce';\n };\n // Agent Smith settings\n agentSmith: {\n aiEnhancement: boolean;\n minSeverity: 'critical' | 'serious' | 'moderate' | 'low';\n enabledCategories: {\n security: boolean;\n codeSmells: boolean;\n asyncBugs: boolean;\n reactPatterns: boolean;\n uxPatterns: boolean;\n backendPatterns: boolean;\n };\n memoryRetentionDays: number;\n };\n // Scan performance settings\n performance: {\n parallel: boolean;\n cache: boolean;\n maxConcurrency: number;\n timeoutMs: number;\n workers: boolean;\n streaming: boolean;\n };\n // Risk assessment thresholds\n riskThresholds: {\n critical: number;\n high: number;\n medium: number;\n };\n // Escalation settings\n escalation: {\n enabled: boolean;\n targets: Array<{\n type: 'slack' | 'email' | 'webhook';\n enabled: boolean;\n config: {\n webhookUrl?: string;\n email?: string;\n channel?: string;\n username?: string;\n };\n forSeverities: string[];\n forCategories: string[];\n }>;\n cooldownMinutes: number;\n maxEscalationsPerHour: number;\n respectQuietHours: boolean;\n criticalBypassQuietHours: boolean;\n };\n };\n \n // Skills browser state\n skillsBrowser: {\n installedSkills: Array<{\n name: string;\n description: string;\n path: string;\n installedFrom: string;\n installedAt: string;\n timesApplied?: number;\n }>;\n globalSkills: Array<{\n name: string;\n description: string;\n path: string;\n installedFrom: string;\n installedAt: string;\n }>;\n suggestedSkills: string[];\n detectedStack: {\n framework?: string;\n language?: string;\n database?: string;\n };\n categories: Array<{ name: string; count: number }>;\n selectedCategory: string | null;\n categorySkills: string[];\n selectedIndex: number;\n activePanel: 'installed' | 'global' | 'suggested' | 'categories';\n installing: boolean;\n inputMode: 'browse' | 'drop-file';\n droppedFilePath: string;\n installStatus: string;\n lastRefresh: number;\n };\n \n // Goals management state\n goalsPanel: {\n goals: Array<{\n id: string;\n description: string;\n type: string;\n target: number;\n currentValue: number;\n status: string;\n autoGenerated: boolean;\n category?: string;\n updatedAt: string;\n }>;\n selectedIndex: number;\n selectedAchievedIndex: number;\n inputMode: 'browse' | 'add';\n inputBuffer: string;\n lastRefresh: number;\n };\n \n // Hypotheses management state\n hypothesesPanel: {\n hypotheses: Array<{\n id: string;\n statement: string;\n confidence: number;\n status: string;\n evidenceCount: number;\n category?: string;\n updatedAt: string;\n }>;\n selectedIndex: number;\n selectedCompletedIndex: number;\n inputMode: 'browse' | 'add';\n inputBuffer: string;\n lastRefresh: number;\n };\n \n // Memory tree visualization state\n memoryTree: {\n loaded: boolean;\n issues: StoredIssue[];\n stats: IssueMemoryStats | null;\n globalPatterns: GlobalPattern[];\n expandedNodes: Set<string>;\n selectedNode: string;\n scrollPosition: number;\n lastRefresh: number;\n };\n}\n\n/**\n * Interactive CLI Dashboard for Trie scans\n *\n * Features:\n * - Real-time progress bars\n * - Interactive issue browser\n * - Filter and search capabilities\n * - Keyboard navigation\n */\n// ASCII animation frames for watch mode\nconst WATCH_FRAMES = ['◐', '◓', '◑', '◒']; // Rotating circle\nconst SCAN_FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']; // Braille spinner\n\nexport class InteractiveDashboard {\n private rl: readline.Interface;\n private state: DashboardState;\n private isActive: boolean = false;\n private updateInterval: NodeJS.Timeout | undefined;\n private resizeHandler: (() => void) | undefined;\n private resizeDebounce: NodeJS.Timeout | undefined;\n private guardianConfigPath: string;\n \n // Double-buffering to prevent flicker\n private buffer: string[] = [];\n private lastFrame: string = '';\n \n // Animation frame counter\n private animFrame: number = 0;\n \n // Callback for when Moneybags settings change (triggers recalculation)\n private onMoneybagsChangeCallback: (() => void) | null = null;\n\n constructor() {\n this.rl = readline.createInterface({ input, output });\n const workDir = getWorkingDirectory(undefined, true);\n this.guardianConfigPath = join(getTrieDirectory(workDir), 'guardian.json');\n this.state = {\n issues: [],\n progress: {\n totalFiles: 0,\n processedFiles: 0,\n activeAgents: [],\n completedAgents: [],\n totalIssues: 0,\n issuesBySeverity: { critical: 0, serious: 0, moderate: 0, low: 0 }\n },\n filter: {\n severity: 'all',\n agent: 'all',\n search: ''\n },\n view: 'overview',\n previousView: null,\n selectedIssue: 0,\n selectedAgent: 0,\n lastUpdate: Date.now(),\n scanComplete: false,\n startTime: Date.now(),\n scanStartTime: Date.now(),\n activityLog: [],\n activityPage: 0,\n agentPage: 0,\n quietMode: false,\n alerts: { hasCritical: false },\n watch: {\n watching: false,\n directories: 0,\n recentChanges: []\n },\n agents: {},\n \n // Rich content state\n codeSnippets: new Map(),\n costReport: null,\n readiness: null,\n semanticAnalysis: null,\n attackSurface: null,\n skillBanners: [],\n rawLog: [],\n rawLogPage: 0,\n scrollPositions: {\n overview: 0,\n issues: 0,\n agents: 0,\n files: 0,\n details: 0,\n costs: 0,\n readiness: 0,\n analysis: 0,\n rawlog: 0,\n skills: 0,\n guardian: 0,\n goals: 0,\n hypotheses: 0,\n memory: 0\n },\n notification: null,\n notificationHistory: [],\n guardianInsights: [],\n guardianInitialized: false,\n agencyStatus: null,\n selectedGuardianInsight: 0,\n expandedGuardianInsight: null,\n guardianConfig: {\n moneybags: {\n userCount: 250,\n payingUsers: 0, // 0 = not set, will use userCount\n revenuePerUser: 0, // 0 = not set, no revenue context\n developerRate: 150\n },\n agentSmith: {\n aiEnhancement: true,\n minSeverity: 'low',\n enabledCategories: {\n security: true,\n codeSmells: true,\n asyncBugs: true,\n reactPatterns: true,\n uxPatterns: true,\n backendPatterns: true\n },\n memoryRetentionDays: 30\n },\n performance: {\n parallel: true,\n cache: true,\n maxConcurrency: 4,\n timeoutMs: 120000,\n workers: true,\n streaming: true\n },\n riskThresholds: {\n critical: 70,\n high: 40,\n medium: 20,\n },\n escalation: {\n enabled: false,\n targets: [],\n cooldownMinutes: 15,\n maxEscalationsPerHour: 5,\n respectQuietHours: true,\n criticalBypassQuietHours: true,\n },\n },\n \n // Skills browser state\n skillsBrowser: {\n installedSkills: [],\n globalSkills: [],\n suggestedSkills: [],\n detectedStack: {},\n categories: [],\n selectedCategory: null,\n categorySkills: [],\n selectedIndex: 0,\n activePanel: 'installed',\n installing: false,\n installStatus: '',\n lastRefresh: 0,\n inputMode: 'browse',\n droppedFilePath: ''\n },\n \n // Goals panel state\n goalsPanel: {\n goals: [],\n selectedIndex: 0,\n selectedAchievedIndex: 0,\n inputMode: 'browse',\n inputBuffer: '',\n lastRefresh: 0\n },\n \n // Hypotheses panel state\n hypothesesPanel: {\n hypotheses: [],\n selectedIndex: 0,\n selectedCompletedIndex: 0,\n inputMode: 'browse',\n inputBuffer: '',\n lastRefresh: 0\n },\n \n // Memory tree state\n memoryTree: {\n loaded: false,\n issues: [],\n stats: null,\n globalPatterns: [],\n expandedNodes: new Set(['severity', 'files']), // Default expanded\n selectedNode: 'severity',\n scrollPosition: 0,\n lastRefresh: 0\n }\n };\n }\n\n /**\n * Start the interactive dashboard\n */\n async start(): Promise<void> {\n this.isActive = true;\n this.state.startTime = Date.now();\n this.addActivity('Guardian started');\n \n // Load persisted goals and hypotheses on startup\n await this.refreshGoalsData();\n await this.refreshHypothesesData();\n\n // Clear any pending input to prevent character leaking\n if (process.stdin.isTTY) {\n process.stdin.pause();\n process.stdin.resume();\n }\n\n await this.loadGuardianConfig();\n \n // Switch to alternate screen buffer - this is the proper TUI approach\n // The alternate screen is separate from the main terminal scrollback\n // When we exit, the terminal returns to its previous state\n process.stdout.write(\n '\\x1b[?1049h' + // Enter alternate screen buffer\n '\\x1b[?25l' + // Hide cursor\n '\\x1b[2J' + // Clear the alternate screen\n '\\x1b[H' + // Move cursor to home\n '\\x1b[3J' // Clear scrollback (prevents top gap in some terminals)\n );\n \n this.setupKeyboardHandlers();\n this.setupResizeHandler();\n this.startUpdateLoop();\n \n // Register with OutputManager for rich content routing\n this.registerOutputManagerCallbacks();\n \n this.render();\n }\n\n private async loadGuardianConfig(): Promise<void> {\n if (!existsSync(this.guardianConfigPath)) {\n return;\n }\n try {\n const raw = await readFile(this.guardianConfigPath, 'utf-8');\n const parsed = JSON.parse(raw) as Partial<DashboardState['guardianConfig']>;\n this.applyGuardianConfig(parsed);\n } catch {\n // Ignore malformed config and keep defaults\n }\n }\n\n private applyGuardianConfig(config?: Partial<DashboardState['guardianConfig']>): void {\n if (!config) return;\n if (config.moneybags) {\n const moneybags = config.moneybags;\n if (typeof moneybags.userCount === 'number') this.state.guardianConfig.moneybags.userCount = moneybags.userCount;\n if (typeof moneybags.payingUsers === 'number') this.state.guardianConfig.moneybags.payingUsers = moneybags.payingUsers;\n if (typeof moneybags.revenuePerUser === 'number') this.state.guardianConfig.moneybags.revenuePerUser = moneybags.revenuePerUser;\n if (typeof moneybags.developerRate === 'number') this.state.guardianConfig.moneybags.developerRate = moneybags.developerRate;\n // Handle industry: if property exists, update it (null from JSON means cleared/undefined)\n if ('industry' in moneybags) {\n if (moneybags.industry === null) {\n delete this.state.guardianConfig.moneybags.industry;\n } else if (moneybags.industry) {\n this.state.guardianConfig.moneybags.industry = moneybags.industry;\n }\n }\n }\n if (config.agentSmith) {\n const agentSmith = config.agentSmith;\n if (typeof agentSmith.aiEnhancement === 'boolean') this.state.guardianConfig.agentSmith.aiEnhancement = agentSmith.aiEnhancement;\n if (typeof agentSmith.minSeverity === 'string') this.state.guardianConfig.agentSmith.minSeverity = agentSmith.minSeverity as DashboardState['guardianConfig']['agentSmith']['minSeverity'];\n if (typeof agentSmith.enabledCategories === 'object' && agentSmith.enabledCategories) {\n this.state.guardianConfig.agentSmith.enabledCategories = {\n ...this.state.guardianConfig.agentSmith.enabledCategories,\n ...agentSmith.enabledCategories\n };\n }\n if (typeof agentSmith.memoryRetentionDays === 'number') this.state.guardianConfig.agentSmith.memoryRetentionDays = agentSmith.memoryRetentionDays;\n }\n if (config.performance) {\n const perf = config.performance;\n if (typeof perf.parallel === 'boolean') this.state.guardianConfig.performance.parallel = perf.parallel;\n if (typeof perf.cache === 'boolean') this.state.guardianConfig.performance.cache = perf.cache;\n if (typeof perf.maxConcurrency === 'number') this.state.guardianConfig.performance.maxConcurrency = perf.maxConcurrency;\n if (typeof perf.timeoutMs === 'number') this.state.guardianConfig.performance.timeoutMs = perf.timeoutMs;\n if (typeof perf.workers === 'boolean') this.state.guardianConfig.performance.workers = perf.workers;\n if (typeof perf.streaming === 'boolean') this.state.guardianConfig.performance.streaming = perf.streaming;\n }\n if (config.riskThresholds) {\n const thresholds = config.riskThresholds;\n if (typeof thresholds.critical === 'number') this.state.guardianConfig.riskThresholds.critical = thresholds.critical;\n if (typeof thresholds.high === 'number') this.state.guardianConfig.riskThresholds.high = thresholds.high;\n if (typeof thresholds.medium === 'number') this.state.guardianConfig.riskThresholds.medium = thresholds.medium;\n }\n if (config.escalation) {\n const esc = config.escalation;\n if (typeof esc.enabled === 'boolean') this.state.guardianConfig.escalation.enabled = esc.enabled;\n if (Array.isArray(esc.targets)) this.state.guardianConfig.escalation.targets = esc.targets;\n if (typeof esc.cooldownMinutes === 'number') this.state.guardianConfig.escalation.cooldownMinutes = esc.cooldownMinutes;\n if (typeof esc.maxEscalationsPerHour === 'number') this.state.guardianConfig.escalation.maxEscalationsPerHour = esc.maxEscalationsPerHour;\n if (typeof esc.respectQuietHours === 'boolean') this.state.guardianConfig.escalation.respectQuietHours = esc.respectQuietHours;\n if (typeof esc.criticalBypassQuietHours === 'boolean') this.state.guardianConfig.escalation.criticalBypassQuietHours = esc.criticalBypassQuietHours;\n }\n }\n\n private async persistGuardianConfig(): Promise<void> {\n try {\n await mkdir(getTrieDirectory(getWorkingDirectory(undefined, true)), { recursive: true });\n // Create a copy of the config for serialization\n // If industry was deleted (doesn't exist), we need to explicitly set it to null\n const configToSave = JSON.parse(JSON.stringify(this.state.guardianConfig));\n // Ensure industry is explicitly null if it was deleted, so it persists correctly\n if (!('industry' in this.state.guardianConfig.moneybags)) {\n configToSave.moneybags.industry = null;\n }\n await writeFile(this.guardianConfigPath, JSON.stringify(configToSave, null, 2), 'utf-8');\n } catch {\n // Ignore persistence failures in TUI\n }\n }\n \n /**\n * Register callbacks with OutputManager for rich content\n */\n private registerOutputManagerCallbacks(): void {\n const outputManager = getOutputManager();\n outputManager.setMode('tui');\n outputManager.registerTUICallbacks({\n onBanner: (banner: BannerContent) => {\n this.state.skillBanners.unshift(banner);\n if (this.state.skillBanners.length > 5) {\n this.state.skillBanners.pop();\n }\n this.addActivity(`[BANNER] ${banner.skill}${banner.quote ? ': ' + banner.quote.slice(0, 40) + '...' : ''}`);\n this.render();\n },\n onSnippet: (snippet: SnippetContent) => {\n // Store snippet for the current selected issue\n this.state.codeSnippets.set(this.state.selectedIssue, snippet);\n this.render();\n },\n onCost: (cost: CostContent) => {\n this.state.costReport = cost;\n this.addActivity(`[COST] Fix: $${cost.fixNowCost} | Prod: $${cost.productionCost}`);\n this.render();\n },\n onReadiness: (readiness: ReadinessContent) => {\n this.state.readiness = readiness;\n this.addActivity(`[READY] Score: ${readiness.score}/100 - ${readiness.status.toUpperCase()}`);\n this.render();\n },\n onSemantic: (semantic: SemanticContent) => {\n this.state.semanticAnalysis = semantic;\n this.addActivity(`[SEMANTIC] DataFlow: ${semantic.dataFlowIssues} | Race: ${semantic.raceConditions} | Auth: ${semantic.authIssues}`);\n this.render();\n },\n onAttack: (attack: AttackSurfaceContent) => {\n this.state.attackSurface = attack;\n this.addActivity(`[ATTACK] ${attack.totalEndpoints} endpoints (${attack.unprotected} unprotected)`);\n this.render();\n },\n onActivity: (message: string) => {\n this.addActivity(message);\n this.render();\n },\n onLog: (level: string, message: string) => {\n const time = new Date().toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' });\n this.state.rawLog.unshift({ time, level, message });\n if (this.state.rawLog.length > 500) {\n this.state.rawLog.pop();\n }\n // Only render if we're in rawlog view to avoid spam\n if (this.state.view === 'rawlog') {\n this.render();\n }\n },\n onNudge: (nudge: NudgeContent) => {\n // Show proactive notification overlay\n this.showNotification(\n nudge.message,\n nudge.severity,\n nudge.file,\n nudge.autoHideMs\n );\n }\n });\n }\n\n /**\n * Stop the dashboard\n */\n stop(): void {\n this.isActive = false;\n if (this.updateInterval) {\n clearInterval(this.updateInterval);\n this.updateInterval = undefined;\n }\n if (this.resizeDebounce) {\n clearTimeout(this.resizeDebounce);\n this.resizeDebounce = undefined;\n }\n if (this.resizeHandler && process.stdout.isTTY) {\n process.stdout.off('resize', this.resizeHandler);\n this.resizeHandler = undefined;\n }\n this.rl.close();\n \n // Unregister from OutputManager\n const outputManager = getOutputManager();\n outputManager.clearTUICallbacks();\n outputManager.setMode('console');\n \n // Clear render buffer to prevent partial renders\n this.buffer = [];\n this.lastFrame = '';\n \n // Clear the screen before exiting alternate buffer\n process.stdout.write('\\x1b[2J\\x1b[H');\n \n // Exit alternate screen buffer and show cursor\n // This restores the terminal to its state before we started\n process.stdout.write(\n '\\x1b[?25h' + // Show cursor\n '\\x1b[?1049l' // Exit alternate screen buffer (restores previous screen)\n );\n }\n\n /**\n * Add activity log entry\n */\n private addActivity(message: string): void {\n const time = new Date().toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' });\n this.state.activityLog.unshift({ time, message });\n // Keep only last 50 entries for scrollable history\n if (this.state.activityLog.length > 50) {\n this.state.activityLog.pop();\n }\n }\n\n /**\n * Show a proactive notification/nudge from the Guardian Agent\n * This adds to the notification strip (non-blocking, inline)\n */\n showNotification(message: string, severity: 'critical' | 'warning' | 'info', file?: string, autoHideMs?: number): void {\n const now = Date.now();\n \n // Build history entry (only include file if defined for exactOptionalPropertyTypes)\n const historyEntry: {\n message: string;\n severity: 'critical' | 'warning' | 'info';\n file?: string;\n timestamp: number;\n dismissed: boolean;\n } = {\n message,\n severity,\n timestamp: now,\n dismissed: false\n };\n if (file !== undefined) {\n historyEntry.file = file;\n }\n \n // Store in history (newest first)\n this.state.notificationHistory.unshift(historyEntry);\n \n // Keep history reasonable\n if (this.state.notificationHistory.length > 50) {\n this.state.notificationHistory.pop();\n }\n \n // Build active notification for the strip\n const notification: {\n active: boolean;\n message: string;\n severity: 'critical' | 'warning' | 'info';\n file?: string;\n timestamp: number;\n autoHideAt?: number;\n } = {\n active: true,\n message,\n severity,\n timestamp: now\n };\n if (file !== undefined) {\n notification.file = file;\n }\n if (autoHideMs !== undefined) {\n notification.autoHideAt = now + autoHideMs;\n }\n \n this.state.notification = notification;\n \n // Also add to activity log\n const prefix = severity === 'critical' ? '[!]' : severity === 'warning' ? '[!]' : '[>]';\n this.addActivity(`${prefix} ${message}`);\n \n // Force re-render to show notification immediately\n this.render();\n }\n\n /**\n * Dismiss the current notification\n */\n dismissNotification(): void {\n if (this.state.notification) {\n // Mark as dismissed in history\n const historyItem = this.state.notificationHistory.find(\n h => h.timestamp === this.state.notification?.timestamp\n );\n if (historyItem) {\n historyItem.dismissed = true;\n }\n \n this.state.notification = null;\n this.render();\n }\n }\n\n /**\n * Format timestamp as relative time (e.g., \"2m ago\", \"just now\")\n */\n private formatTimeAgo(timestamp: number): string {\n const seconds = Math.floor((Date.now() - timestamp) / 1000);\n if (seconds < 10) return 'just now';\n if (seconds < 60) return `${seconds}s ago`;\n const minutes = Math.floor(seconds / 60);\n if (minutes < 60) return `${minutes}m ago`;\n const hours = Math.floor(minutes / 60);\n return `${hours}h ago`;\n }\n \n /**\n * Process issues through the Guardian Agent to generate insights\n */\n private async processGuardianInsights(issues: Issue[]): Promise<void> {\n try {\n const workDir = getWorkingDirectory(undefined, true);\n const guardian = getGuardian(workDir);\n \n // Initialize Guardian if needed\n if (!this.state.guardianInitialized) {\n await guardian.initialize();\n this.state.guardianInitialized = true;\n \n // Load persisted insights from previous sessions\n const persistedInsights = guardian.getActiveInsights();\n if (persistedInsights.length > 0) {\n // Add persisted insights that aren't already in our list\n for (const insight of persistedInsights) {\n const isDuplicate = this.state.guardianInsights.some(\n existing => existing.id === insight.id\n );\n if (!isDuplicate) {\n this.state.guardianInsights.push(insight);\n }\n }\n // Sort by priority (highest first) then by timestamp (newest first)\n this.state.guardianInsights.sort((a, b) => {\n if (a.priority !== b.priority) return b.priority - a.priority;\n return b.timestamp - a.timestamp;\n });\n this.addActivity(`Guardian: Loaded ${persistedInsights.length} persisted insight${persistedInsights.length > 1 ? 's' : ''}`);\n }\n }\n \n // Get recent file changes for context\n const filesChanged = this.state.watch.recentChanges.map(c => c.file);\n \n // Let the Guardian analyze and generate insights\n const newInsights = await guardian.processIssues(issues, {\n filesChanged,\n isWatchMode: this.state.watch.watching\n });\n \n // Merge new insights with existing (avoid duplicates by message similarity)\n for (const insight of newInsights) {\n const isDuplicate = this.state.guardianInsights.some(\n existing => existing.message === insight.message && !existing.dismissed\n );\n if (!isDuplicate) {\n this.state.guardianInsights.unshift(insight);\n }\n }\n \n // Keep insights list manageable\n this.state.guardianInsights = this.state.guardianInsights.slice(0, 50);\n \n // Fetch agency status (goals, hypotheses, risk, effectiveness)\n try {\n this.state.agencyStatus = await guardian.getAgencyStatus();\n } catch {\n // Agency status is optional\n }\n \n // Log Guardian activity\n if (newInsights.length > 0) {\n this.addActivity(`Guardian: ${newInsights.length} new insight${newInsights.length > 1 ? 's' : ''}`);\n }\n } catch (error) {\n // Guardian errors shouldn't break the dashboard\n this.addActivity(`Guardian error: ${error instanceof Error ? error.message : 'unknown'}`);\n }\n }\n \n /**\n * Dismiss the currently selected insight in Guardian view\n */\n private dismissSelectedInsight(): void {\n // Get insights as displayed (dismissed filtered out)\n const visibleInsights = this.getVisibleGuardianInsights();\n const selectedIdx = this.state.selectedGuardianInsight;\n const insight = visibleInsights[selectedIdx];\n \n if (!insight) {\n this.addActivity('[ERROR] No insight selected to dismiss');\n return;\n }\n \n if (insight.dismissed) {\n this.addActivity('[WARNING] Insight already dismissed');\n return;\n }\n \n insight.dismissed = true;\n this.persistInsightDismissal(insight.id);\n this.addActivity(`Dismissed: ${insight.message.slice(0, 40)}...`);\n \n // Collapse if expanded\n if (this.state.expandedGuardianInsight === selectedIdx) {\n this.state.expandedGuardianInsight = null;\n }\n \n // Adjust selection index since dismissed insight will be removed from display\n const remainingInsights = this.getVisibleGuardianInsights();\n if (remainingInsights.length === 0) {\n this.state.selectedGuardianInsight = 0;\n this.state.scrollPositions.guardian = 0;\n } else {\n if (this.state.selectedGuardianInsight >= remainingInsights.length) {\n this.state.selectedGuardianInsight = Math.max(0, remainingInsights.length - 1);\n }\n // Reset scroll position if needed\n if (this.state.scrollPositions.guardian >= remainingInsights.length) {\n this.state.scrollPositions.guardian = Math.max(0, remainingInsights.length - 1);\n }\n }\n \n this.render();\n }\n\n /**\n * Ignore (persistently dismiss) the currently selected insight in Guardian view\n * Behaves like dismiss, but with explicit \"Ignored\" activity log entry.\n */\n private ignoreSelectedInsight(): void {\n const visibleInsights = this.getVisibleGuardianInsights();\n const selectedIdx = this.state.selectedGuardianInsight;\n const insight = visibleInsights[selectedIdx];\n \n if (!insight) {\n this.addActivity('[ERROR] No insight selected to ignore');\n return;\n }\n \n if (insight.dismissed) {\n this.addActivity('[WARNING] Insight already dismissed/ignored');\n return;\n }\n \n insight.dismissed = true;\n this.persistInsightDismissal(insight.id);\n this.addActivity(`Ignored: ${insight.message.slice(0, 40)}...`);\n \n // Collapse if expanded\n if (this.state.expandedGuardianInsight === selectedIdx) {\n this.state.expandedGuardianInsight = null;\n }\n \n // Adjust selection/scroll after removal\n const remainingInsights = this.getVisibleGuardianInsights();\n if (remainingInsights.length === 0) {\n this.state.selectedGuardianInsight = 0;\n this.state.scrollPositions.guardian = 0;\n } else {\n if (this.state.selectedGuardianInsight >= remainingInsights.length) {\n this.state.selectedGuardianInsight = Math.max(0, remainingInsights.length - 1);\n }\n if (this.state.scrollPositions.guardian >= remainingInsights.length) {\n this.state.scrollPositions.guardian = Math.max(0, remainingInsights.length - 1);\n }\n }\n \n this.render();\n }\n \n /**\n * Clear all dismissed insights from the list\n */\n private clearDismissedInsights(): void {\n const dismissedCount = this.state.guardianInsights.filter(i => i.dismissed).length;\n \n if (dismissedCount === 0) {\n this.addActivity('No dismissed insights to clear');\n return;\n }\n \n // Remove dismissed insights from the state\n this.state.guardianInsights = this.state.guardianInsights.filter(i => !i.dismissed);\n \n // Also clear old notification history\n this.state.notificationHistory = [];\n \n // Reset selection if needed\n if (this.state.selectedGuardianInsight >= this.state.guardianInsights.length) {\n this.state.selectedGuardianInsight = Math.max(0, this.state.guardianInsights.length - 1);\n }\n this.state.expandedGuardianInsight = null;\n this.state.scrollPositions.guardian = 0;\n \n this.addActivity(`Cleared ${dismissedCount} dismissed insight${dismissedCount !== 1 ? 's' : ''}`);\n this.render();\n }\n \n /**\n * Persist an insight dismissal to the InsightStore\n */\n private async persistInsightDismissal(insightId: string): Promise<void> {\n try {\n const workDir = getWorkingDirectory(undefined, true);\n const guardian = getGuardian(workDir);\n await guardian.dismissInsight(insightId);\n } catch {\n // Don't break the UI on persistence errors\n }\n }\n\n /**\n * Process streaming updates\n */\n handleStreamUpdate(update: StreamUpdate): void {\n this.state.lastUpdate = Date.now();\n\n switch (update.type) {\n case 'progress':\n // Log file scanning milestones\n const oldProgress = this.state.progress;\n \n // Detect new scan starting (totalFiles goes from 0 to positive, or processedFiles resets to 0)\n if ((oldProgress.totalFiles === 0 && update.data.totalFiles > 0) ||\n (oldProgress.processedFiles > 0 && update.data.processedFiles === 0)) {\n this.state.scanStartTime = Date.now();\n this.state.scanComplete = false;\n delete this.state.scanEndTime;\n }\n \n this.state.progress = update.data;\n if (update.data.issuesBySeverity?.critical > 0) {\n this.state.alerts = { hasCritical: true, lastCriticalAt: update.timestamp };\n }\n \n // Log when we start scanning a new file (every 10th file to avoid spam)\n if (update.data.currentFile && update.data.processedFiles % 10 === 0 && update.data.processedFiles !== oldProgress.processedFiles) {\n this.addActivity(`Scanned ${update.data.processedFiles}/${update.data.totalFiles} files`);\n }\n break;\n\n case 'agent_start':\n this.addActivity(`[*] Scout started: ${update.data.agent}`);\n this.state.agents[update.data.agent] = {\n ...(this.state.agents[update.data.agent] || { issues: 0, status: 'queued' }),\n status: 'running',\n start: update.timestamp\n };\n break;\n\n case 'agent_complete':\n this.addActivity(`[+] Scout complete: ${update.data.agent} (${update.data.issueCount} issues)`);\n {\n const prev = this.state.agents[update.data.agent];\n const start = prev?.start;\n const issues = update.data.issueCount ?? prev?.issues ?? 0;\n const durationMs = start !== undefined ? update.timestamp - start : undefined;\n this.state.agents[update.data.agent] = {\n ...(prev ?? { issues: 0, status: 'queued' }),\n status: 'done',\n end: update.timestamp,\n ...(start !== undefined ? { start } : {}),\n ...(durationMs !== undefined ? { durationMs } : {}),\n issues\n };\n }\n break;\n\n case 'issue_found':\n this.state.issues.push(update.data);\n // Log critical and serious issues immediately\n if (update.data.severity === 'critical' || update.data.severity === 'serious') {\n const icon = update.data.severity === 'critical' ? '[!]' : '[x]';\n const fileName = update.data.file?.split('/').pop() || 'unknown';\n this.addActivity(`${icon} ${update.data.severity.toUpperCase()}: ${update.data.message?.slice(0, 40) || fileName}`);\n if (update.data.severity === 'critical') {\n this.state.alerts = { hasCritical: true, lastCriticalAt: update.timestamp };\n }\n }\n if (update.data.agent) {\n const agentMeta = this.state.agents[update.data.agent];\n if (agentMeta) {\n agentMeta.issues += 1;\n }\n }\n break;\n\n case 'scan_complete':\n this.state.scanComplete = true;\n this.state.scanEndTime = update.timestamp;\n this.state.progress = {\n ...this.state.progress,\n processedFiles: this.state.progress.totalFiles\n };\n // Store all issues from the scan\n if (update.data.issues && Array.isArray(update.data.issues)) {\n this.state.issues = update.data.issues;\n }\n const elapsed = ((Date.now() - this.state.scanStartTime) / 1000).toFixed(1);\n this.addActivity(`=== Scan complete - ${this.state.progress.totalIssues} issues in ${elapsed}s ===`);\n \n // Let the Guardian Agent analyze the issues and generate insights\n this.processGuardianInsights(this.state.issues);\n break;\n \n case 'watch_status':\n this.state.watch = {\n watching: update.data.watching ?? this.state.watch.watching,\n directories: update.data.directories ?? this.state.watch.directories,\n debounceMs: update.data.debounceMs ?? this.state.watch.debounceMs,\n lastChange: update.data.lastChange ?? this.state.watch.lastChange,\n recentChanges: update.data.recentChanges ?? this.state.watch.recentChanges\n };\n // Log watch status changes\n if (update.data.watching !== undefined) {\n this.addActivity(update.data.watching \n ? `[*] Watch mode: ACTIVE (${update.data.directories ?? 0} dirs)` \n : '[*] Watch mode: OFF');\n }\n break;\n\n case 'watch_change':\n const entry = { file: update.data.file, time: new Date(update.timestamp).toLocaleTimeString('en-US', { hour12: false }) };\n this.state.watch.recentChanges.unshift(entry);\n this.state.watch.recentChanges = this.state.watch.recentChanges.slice(0, 5);\n this.state.watch.lastChange = entry.time;\n this.addActivity(`Change detected: ${update.data.file}`);\n break;\n\n case 'memory':\n if (update.data.action === 'saving') {\n this.addActivity(`[~] Saving to memory...`);\n } else if (update.data.action === 'saved') {\n this.addActivity(`[+] Memory updated: ${update.data.details || 'context saved'}`);\n } else if (update.data.action === 'learning') {\n this.addActivity(`[~] Learning: ${update.data.details || 'analyzing patterns'}`);\n }\n break;\n \n // === Rich Content Events ===\n \n case 'snippet':\n // Store snippet keyed by file (not ideal but works for now)\n this.state.codeSnippets.set(this.state.selectedIssue, update.data as SnippetContent);\n break;\n \n case 'cost_report':\n this.state.costReport = update.data as CostContent;\n this.addActivity(`[COST] Fix now: $${update.data.fixNowCost} | Production: $${update.data.productionCost}`);\n break;\n \n case 'readiness_report':\n this.state.readiness = update.data as ReadinessContent;\n this.addActivity(`[READINESS] ${update.data.score}/100 - ${update.data.status}`);\n break;\n \n case 'semantic_report':\n this.state.semanticAnalysis = update.data as SemanticContent;\n {\n const sem = update.data as SemanticContent;\n const total = sem.dataFlowIssues + sem.raceConditions + sem.authIssues;\n if (total > 0) {\n this.addActivity(`[SEMANTIC] ${total} issues (${sem.dataFlowIssues} dataflow, ${sem.raceConditions} race, ${sem.authIssues} auth)`);\n }\n }\n break;\n \n case 'attack_surface':\n this.state.attackSurface = update.data as AttackSurfaceContent;\n {\n const atk = update.data as AttackSurfaceContent;\n this.addActivity(`[ATTACK] ${atk.totalEndpoints} endpoints, ${atk.unprotected} unprotected, risk ${atk.riskScore}/100`);\n }\n break;\n \n case 'skill_banner':\n const banner = update.data as BannerContent;\n this.state.skillBanners.unshift(banner);\n if (this.state.skillBanners.length > 5) {\n this.state.skillBanners.pop();\n }\n this.addActivity(`[SKILL] ${banner.skill}${banner.quote ? ': \"' + banner.quote.slice(0, 30) + '...\"' : ''}`);\n break;\n \n case 'raw_log':\n this.state.rawLog.unshift({\n time: update.data.time || new Date(update.timestamp).toLocaleTimeString('en-US', { hour12: false }),\n level: update.data.level,\n message: update.data.message\n });\n if (this.state.rawLog.length > 500) {\n this.state.rawLog.pop();\n }\n break;\n }\n\n if (this.isActive) {\n this.render();\n }\n }\n\n /**\n * Set up keyboard event handlers\n */\n private setupKeyboardHandlers(): void {\n readline.emitKeypressEvents(input);\n if (input.isTTY) {\n input.setRawMode(true);\n }\n\n input.on('keypress', async (_chunk, key) => {\n if (!key || !this.isActive) return;\n\n // Handle goals view input\n if (this.state.view === 'goals') {\n if (this.state.goalsPanel.inputMode === 'add') {\n if (key.name === 'escape') {\n this.state.goalsPanel.inputMode = 'browse';\n this.state.goalsPanel.inputBuffer = '';\n } else if (key.name === 'return' || key.name === 'enter') {\n await this.addGoalFromUI(this.state.goalsPanel.inputBuffer);\n this.state.goalsPanel.inputMode = 'browse';\n this.state.goalsPanel.inputBuffer = '';\n } else if (key.name === 'backspace') {\n this.state.goalsPanel.inputBuffer = this.state.goalsPanel.inputBuffer.slice(0, -1);\n } else if (key.sequence && key.sequence.length === 1 && !key.ctrl && !key.meta) {\n this.state.goalsPanel.inputBuffer += key.sequence;\n }\n this.render();\n return;\n }\n \n // Browse mode keys\n if (key.name === 'a') {\n this.state.goalsPanel.inputMode = 'add';\n this.state.goalsPanel.inputBuffer = '';\n this.render();\n return;\n }\n if (key.name === 'return' || key.name === 'enter') {\n const activeGoals = this.state.goalsPanel.goals.filter(g => g.status === 'active');\n const selected = activeGoals[this.state.goalsPanel.selectedIndex];\n if (selected) {\n await this.completeGoalFromUI(selected.id);\n }\n return;\n }\n if (key.name === 'd') {\n const activeGoals = this.state.goalsPanel.goals.filter(g => g.status === 'active');\n const selected = activeGoals[this.state.goalsPanel.selectedIndex];\n if (selected) {\n await this.deleteGoalFromUI(selected.id);\n }\n return;\n }\n if (key.name === 'x') {\n // Delete achieved/failed goals\n const completedGoals = this.state.goalsPanel.goals.filter(g => g.status === 'achieved' || g.status === 'failed');\n const selected = completedGoals[this.state.goalsPanel.selectedAchievedIndex || 0];\n if (selected) {\n await this.deleteGoalFromUI(selected.id);\n }\n return;\n }\n if (key.name === 'u') {\n // Undo - reactivate last completed goal\n const recentlyCompleted = this.state.goalsPanel.goals\n .filter(g => g.status === 'achieved')\n .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());\n if (recentlyCompleted.length > 0) {\n const goal = recentlyCompleted[0]!;\n await this.reactivateGoalFromUI(goal.id);\n }\n return;\n }\n if (key.name === 'up' || key.name === 'k') {\n this.state.goalsPanel.selectedIndex = Math.max(0, this.state.goalsPanel.selectedIndex - 1);\n this.render();\n return;\n }\n if (key.name === 'down' || key.name === 'j') {\n const activeGoals = this.state.goalsPanel.goals.filter(g => g.status === 'active');\n this.state.goalsPanel.selectedIndex = Math.min(activeGoals.length - 1, this.state.goalsPanel.selectedIndex + 1);\n this.render();\n return;\n }\n }\n\n // Handle hypotheses view input\n if (this.state.view === 'hypotheses') {\n if (this.state.hypothesesPanel.inputMode === 'add') {\n if (key.name === 'escape') {\n this.state.hypothesesPanel.inputMode = 'browse';\n this.state.hypothesesPanel.inputBuffer = '';\n } else if (key.name === 'return' || key.name === 'enter') {\n await this.addHypothesisFromUI(this.state.hypothesesPanel.inputBuffer);\n this.state.hypothesesPanel.inputMode = 'browse';\n this.state.hypothesesPanel.inputBuffer = '';\n } else if (key.name === 'backspace') {\n this.state.hypothesesPanel.inputBuffer = this.state.hypothesesPanel.inputBuffer.slice(0, -1);\n } else if (key.sequence && key.sequence.length === 1 && !key.ctrl && !key.meta) {\n this.state.hypothesesPanel.inputBuffer += key.sequence;\n }\n this.render();\n return;\n }\n \n // Browse mode keys\n if (key.name === 'a') {\n this.state.hypothesesPanel.inputMode = 'add';\n this.state.hypothesesPanel.inputBuffer = '';\n this.render();\n return;\n }\n if (key.name === 'v') {\n const testing = this.state.hypothesesPanel.hypotheses.filter(h => h.status === 'testing');\n const selected = testing[this.state.hypothesesPanel.selectedIndex];\n if (selected) {\n await this.updateHypothesisFromUI(selected.id, 'validate');\n }\n return;\n }\n if (key.name === 'x') {\n const testing = this.state.hypothesesPanel.hypotheses.filter(h => h.status === 'testing');\n const selected = testing[this.state.hypothesesPanel.selectedIndex];\n if (selected) {\n await this.updateHypothesisFromUI(selected.id, 'invalidate');\n }\n return;\n }\n if (key.name === 'd') {\n const testing = this.state.hypothesesPanel.hypotheses.filter(h => h.status === 'testing');\n const selected = testing[this.state.hypothesesPanel.selectedIndex];\n if (selected) {\n await this.updateHypothesisFromUI(selected.id, 'delete');\n }\n return;\n }\n if (key.name === 'r') {\n // Remove validated/invalidated hypotheses\n const completed = this.state.hypothesesPanel.hypotheses.filter(h => h.status === 'validated' || h.status === 'invalidated');\n const selected = completed[this.state.hypothesesPanel.selectedCompletedIndex || 0];\n if (selected) {\n await this.updateHypothesisFromUI(selected.id, 'delete');\n }\n return;\n }\n if (key.name === 'u') {\n // Undo - reactivate last validated/invalidated hypothesis\n const recentlyCompleted = this.state.hypothesesPanel.hypotheses\n .filter(h => h.status === 'validated' || h.status === 'invalidated')\n .sort((a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime());\n if (recentlyCompleted.length > 0) {\n const hypothesis = recentlyCompleted[0]!;\n await this.reactivateHypothesisFromUI(hypothesis.id);\n }\n return;\n }\n if (key.name === 'up' || key.name === 'k') {\n this.state.hypothesesPanel.selectedIndex = Math.max(0, this.state.hypothesesPanel.selectedIndex - 1);\n this.render();\n return;\n }\n if (key.name === 'down' || key.name === 'j') {\n const testing = this.state.hypothesesPanel.hypotheses.filter(h => h.status === 'testing');\n this.state.hypothesesPanel.selectedIndex = Math.min(testing.length - 1, this.state.hypothesesPanel.selectedIndex + 1);\n this.render();\n return;\n }\n }\n\n switch (key.name) {\n case 'q':\n case 'escape':\n this.stop();\n process.exit(0);\n break;\n\n case 'tab':\n this.switchView();\n break;\n\n case 'up':\n case 'k':\n this.navigateUp();\n break;\n\n case 'down':\n case 'j':\n this.navigateDown();\n break;\n\n case 'enter':\n case 'return':\n this.selectCurrent().catch(() => {\n // Silently handle errors\n });\n break;\n\n case '1':\n this.setFilter('severity', 'critical');\n break;\n\n case '2':\n this.setFilter('severity', 'serious');\n break;\n\n case '3':\n this.setFilter('severity', 'moderate');\n break;\n\n case '4':\n this.setFilter('severity', 'low');\n break;\n\n case '0':\n this.setFilter('severity', 'all');\n break;\n\n case 'x':\n if (this.state.view === 'guardian') {\n // Clear all dismissed insights from the list\n this.clearDismissedInsights();\n } else {\n this.clearFilters();\n }\n break;\n\n case 'f':\n this.promptFilter();\n break;\n\n case 'n':\n this.nextPage();\n break;\n\n case 'p':\n this.prevPage();\n break;\n\n case 's':\n this.promptAgentFilter();\n break;\n\n case 'b':\n this.goBack();\n break;\n\n case 'h':\n this.showHelp();\n break;\n \n case 'i':\n if (this.state.view === 'guardian') {\n // Ignore (persistently dismiss) the selected insight\n this.ignoreSelectedInsight();\n } else if (this.state.view === 'skills') {\n // In skills view: create custom skill from file\n this.showCreateCustomSkillDialog();\n } else {\n // Configure Guardian Agent settings\n this.showGuardianConfig();\n }\n break;\n \n case 'c':\n // In skills view: create custom skill from file\n // Otherwise: Configure Guardian Agent settings\n if (this.state.view === 'skills') {\n this.showCreateCustomSkillDialog();\n } else {\n this.showGuardianConfig();\n }\n break;\n \n // === NEW VIEW SHORTCUTS ===\n case 'd':\n // In Guardian view, dismiss the selected insight; otherwise go to details view\n if (this.state.view === 'guardian') {\n this.dismissSelectedInsight();\n } else if (this.state.scanComplete && this.state.issues.length > 0) {\n this.goToView('details');\n }\n break;\n \n case 'm':\n // Money/Costs view\n if (this.state.costReport) {\n this.goToView('costs');\n }\n break;\n \n case 'r':\n // Readiness view\n if (this.state.readiness) {\n this.goToView('readiness');\n }\n break;\n \n case 'a':\n // Analysis view (semantic + attack surface)\n if (this.state.semanticAnalysis || this.state.attackSurface) {\n this.goToView('analysis');\n }\n break;\n \n case 'l':\n // Raw log view\n this.goToView('rawlog');\n break;\n \n case 'v':\n // Toolkit view - browse scouts and install skills\n this.goToView('skills');\n this.refreshSkillsData();\n break;\n \n case 'g':\n // Guardian notifications view - all alerts and nudges\n this.goToView('guardian');\n break;\n \n case 'o':\n // Goals management view\n this.goToView('goals');\n this.refreshGoalsData();\n break;\n \n case 'y':\n // Hypotheses management view\n this.goToView('hypotheses');\n this.refreshHypothesesData();\n break;\n \n case 't':\n // Memory tree view\n this.goToView('memory');\n this.loadMemoryTreeData();\n break;\n }\n\n if (this.isActive) {\n this.render();\n }\n });\n }\n\n /**\n * Handle terminal resize events\n */\n private setupResizeHandler(): void {\n if (!process.stdout.isTTY) return;\n this.resizeHandler = () => {\n if (!this.isActive) return;\n if (this.resizeDebounce) {\n clearTimeout(this.resizeDebounce);\n }\n this.resizeDebounce = setTimeout(() => {\n if (!this.isActive) return;\n // Reset frame cache and clear screen so the new layout fits cleanly\n this.lastFrame = '';\n process.stdout.write('\\x1b[2J\\x1b[H\\x1b[3J');\n this.render();\n }, 80);\n };\n process.stdout.on('resize', this.resizeHandler);\n }\n\n /**\n * Start the update loop for real-time rendering\n */\n private startUpdateLoop(): void {\n this.updateInterval = setInterval(() => {\n const shouldAnimate = !this.state.scanComplete || this.state.watch.watching;\n if (this.isActive && (Date.now() - this.state.lastUpdate < 5000 || shouldAnimate)) {\n this.render();\n }\n }, 100); // 10 FPS\n }\n\n /**\n * Create a horizontal line (Unicode box-drawing)\n */\n private line(width: number = 78): string {\n return box.horizontal.repeat(width);\n }\n\n /**\n * Create progress bar with color\n */\n private progressBar(current: number, total: number, width: number = 50): string {\n if (total === 0) return colors.dim('[' + '█'.repeat(width) + ']');\n const progress = Math.min(1, current / total);\n const filled = Math.round(width * progress);\n const empty = width - filled;\n const filledBar = colors.border('█'.repeat(filled));\n const emptyBar = colors.dim('░'.repeat(empty));\n return '[' + filledBar + emptyBar + ']';\n }\n\n /**\n * Get severity icon with color\n */\n private severityIcon(severity: Issue['severity']): string {\n switch (severity) {\n case 'critical':\n return colors.critical('[!]');\n case 'serious':\n return colors.serious('[x]');\n case 'moderate':\n return colors.moderate('[~]');\n case 'low':\n return colors.low('[-]');\n default:\n return colors.dim('[-]');\n }\n }\n\n /**\n * Get agent status icon with color\n */\n private agentIcon(status: 'running' | 'done' | 'waiting'): string {\n switch (status) {\n case 'running':\n return colors.running('●');\n case 'done':\n return colors.success('✓');\n case 'waiting':\n return colors.waiting('○');\n default:\n return colors.dim('○');\n }\n }\n\n /**\n * Render a line with proper padding (accounts for ANSI color codes)\n */\n /**\n * Add a line to the render buffer (buffered output to prevent flicker)\n * Automatically appends \\x1b[K to clear to end of line (prevents remnants from wider terminals)\n */\n private bufferLine(line: string): void {\n this.buffer.push(line + '\\x1b[K');\n }\n\n private renderLine(content: string, width: number): void {\n const v = colors.border(box.vertical);\n const innerWidth = width - 2; // Account for borders\n const contentLen = visibleLength(content);\n \n // Truncate content if too long\n let displayContent = content;\n if (contentLen > innerWidth) {\n // Need to truncate - find where to cut\n displayContent = this.truncateToWidth(content, innerWidth - 3) + '...';\n }\n \n const displayLen = visibleLength(displayContent);\n const padding = Math.max(0, innerWidth - displayLen);\n this.bufferLine(v + displayContent + ' '.repeat(padding) + v);\n }\n\n /**\n * Render a section border that properly connects to vertical borders\n */\n private renderSectionBorder(width: number): void {\n const v = colors.border(box.vertical);\n const border = colors.border(box.leftT + this.line(width - 4) + box.rightT);\n this.bufferLine(v + border + v);\n }\n\n /**\n * Return Guardian insights that should be shown (dismissed filtered out),\n * sorted the same way as in the UI.\n */\n private getVisibleGuardianInsights(): GuardianInsight[] {\n return [...this.state.guardianInsights]\n .filter(i => !i.dismissed)\n .sort((a, b) => {\n if (a.priority !== b.priority) return b.priority - a.priority;\n return b.timestamp - a.timestamp;\n });\n }\n\n /**\n * Truncate a string (with ANSI codes) to a visible width\n * Handles wide characters (emojis, CJK) that take 2 columns\n */\n private truncateToWidth(str: string, maxWidth: number): string {\n let visibleLen = 0;\n let result = '';\n let inEscape = false;\n \n for (const char of str) {\n if (char === '\\x1b') {\n inEscape = true;\n result += char;\n } else if (inEscape) {\n result += char;\n if (char === 'm') {\n inEscape = false;\n }\n } else {\n const code = char.codePointAt(0) || 0;\n // Calculate width of this character\n const charWidth = (\n (code >= 0x1F300 && code <= 0x1F9FF) || // Emoji\n (code >= 0x2600 && code <= 0x26FF) || // Misc symbols\n (code >= 0x2700 && code <= 0x27BF) || // Dingbats\n (code >= 0xFE00 && code <= 0xFE0F) || // Variation selectors\n (code >= 0x1F000 && code <= 0x1FFFF) || // Extended emoji\n (code >= 0x3000 && code <= 0x9FFF) || // CJK\n (code >= 0xAC00 && code <= 0xD7AF) // Korean\n ) ? 2 : 1;\n \n if (visibleLen + charWidth > maxWidth) {\n break;\n }\n result += char;\n visibleLen += charWidth;\n }\n }\n \n // Reset any open ANSI codes\n return result + '\\x1b[0m';\n }\n\n /**\n * Get responsive width based on terminal size\n */\n private getWidth(): number {\n const cols = process.stdout.columns || 80;\n // Responsive: use more space on wider terminals, cap at 120 for readability\n return Math.max(60, Math.min(120, cols - 2));\n }\n\n /**\n * Main render function - uses double buffering to prevent flicker\n */\n private render(): void {\n // Clear the buffer\n this.buffer = [];\n \n // Advance animation frame\n this.animFrame = (this.animFrame + 1) % 100;\n\n // Get terminal size - responsive to terminal width\n const width = this.getWidth();\n const height = Math.max(24, process.stdout.rows || 40); // ensure a minimum but respect small terminals\n\n // Build frame into buffer\n // Header\n this.renderHeader(width);\n\n // Content based on current view and scan state\n if (!this.state.scanComplete) {\n this.renderScanningView(width, height);\n } else {\n switch (this.state.view) {\n case 'overview':\n this.renderOverview(width, height);\n break;\n case 'issues':\n this.renderIssuesList(width);\n break;\n case 'agents':\n this.renderAgentsView(width);\n break;\n case 'files':\n this.renderFilesView(width);\n break;\n // === NEW VIEWS ===\n case 'details':\n this.renderDetailsView(width, height);\n break;\n case 'costs':\n this.renderCostsView(width, height);\n break;\n case 'readiness':\n this.renderReadinessView(width, height);\n break;\n case 'analysis':\n this.renderAnalysisView(width, height);\n break;\n case 'rawlog':\n this.renderRawLogView(width, height);\n break;\n case 'skills':\n this.renderSkillsView(width, height);\n break;\n case 'guardian':\n this.renderGuardianView(width, height);\n break;\n case 'goals':\n this.renderGoalsView(width, height);\n break;\n case 'hypotheses':\n this.renderHypothesesView(width, height);\n break;\n case 'memory':\n this.renderMemoryTreeView(width, height);\n break;\n }\n }\n\n // Footer\n this.renderFooter(width);\n\n // Flush buffer to screen in one write (prevents flicker)\n let frame = this.buffer.join('\\n');\n \n // Check if notifications should auto-dismiss based on time\n const now = Date.now();\n for (const notif of this.state.notificationHistory) {\n // Auto-dismiss info/warning after some time if not already dismissed\n if (!notif.dismissed && notif.severity !== 'critical') {\n const age = now - notif.timestamp;\n // Auto-dismiss info after 30s, warnings after 60s\n const autoHideMs = notif.severity === 'info' ? 30000 : 60000;\n if (age > autoHideMs) {\n notif.dismissed = true;\n }\n }\n }\n \n // Only redraw if frame changed (further reduces flicker)\n if (frame !== this.lastFrame) {\n // Better in-place update approach:\n // 1. Hide cursor\n // 2. Move cursor to home (top-left)\n // 3. Write the frame content\n // 4. Clear from cursor to end of screen (in case new frame is shorter)\n // This avoids the flash from clearing the entire screen first\n process.stdout.write(\n '\\x1b[?25l' + // Hide cursor\n '\\x1b[H' + // Move cursor to home position (1,1)\n frame + // Write the frame content\n '\\x1b[J' // Clear from cursor to end of screen\n );\n \n this.lastFrame = frame;\n }\n }\n\n /**\n * Render header with title and status\n */\n private renderHeader(width: number): void {\n const time = colors.dim(new Date().toLocaleTimeString('en-US', { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' }));\n \n // Animated watch indicator\n const watchSpinner = WATCH_FRAMES[this.animFrame % WATCH_FRAMES.length];\n const watchLabel = this.state.watch.watching \n ? colors.success(`[${watchSpinner} WATCHING]`) \n : colors.dim('[WATCH OFF]');\n \n // Animated scan indicator\n const scanSpinner = SCAN_FRAMES[this.animFrame % SCAN_FRAMES.length];\n let statusText = '';\n if (this.state.scanComplete) {\n statusText = colors.success('ALL SYSTEMS GO') + ' ' + colors.success('[OK]');\n } else {\n statusText = colors.running(`${scanSpinner} SCANNING`) + ' ' + colors.dim('(...)');\n }\n \n let alertText = '';\n if (this.state.alerts.hasCritical) {\n alertText = ' ' + colors.alert('│ ALERT: CRITICAL');\n }\n \n const v = colors.border(box.vertical);\n const topBorder = colors.border(box.topLeft + this.line(width - 2) + box.topRight);\n const midBorder = colors.border(box.leftT + this.line(width - 2) + box.rightT);\n \n // Build content and pad to width (accounting for ANSI codes)\n const brand = colors.brand('TRIE AGENT');\n const rightContent = statusText + ' ' + watchLabel + alertText + ' ' + time;\n // Line structure: │ + 2 spaces + brand + gap + rightContent + 1 space + │ = 5 fixed chars\n const innerWidth = width - 5;\n const brandLen = visibleLength(brand);\n const rightLen = visibleLength(rightContent);\n const gap = Math.max(2, innerWidth - brandLen - rightLen);\n \n this.bufferLine(topBorder);\n this.bufferLine(v + ' ' + brand + ' '.repeat(gap) + rightContent + ' ' + v);\n this.bufferLine(midBorder);\n }\n\n /**\n * Render scanning in progress view\n */\n private renderScanningView(width: number, height: number): void {\n const { processedFiles, totalFiles, currentFile, activeAgents, completedAgents } = this.state.progress;\n const { issuesBySeverity } = this.state.progress;\n \n // Calculate available rows for variable sections to avoid scrolling\n const baseTotal = 21;\n const variableBudget = Math.max(0, height - baseTotal);\n const agentRows = Math.max(1, Math.min(4, Math.floor(variableBudget / 2)));\n const remaining = Math.max(0, variableBudget - agentRows);\n const activityRows = Math.max(1, Math.min(10, remaining || 1));\n \n // Progress section\n const percent = totalFiles > 0 ? Math.round((processedFiles / totalFiles) * 100) : 0;\n const current = currentFile ? currentFile.split('/').pop() || '' : '';\n const progressBar = this.progressBar(processedFiles, totalFiles, 50);\n \n this.renderLine('', width);\n this.renderLine(' ' + colors.dim('Scanning:') + ' ' + colors.highlight(current.slice(0, 40)), width);\n this.renderLine(' ' + progressBar + ' ' + colors.highlight(`${percent}%`) + ' ' + colors.dim(`(${processedFiles}/${totalFiles} files)`), width);\n this.renderLine('', width);\n \n // Agents section\n this.renderSectionBorder(width);\n this.renderLine(' ' + colors.header('SCOUTS'), width);\n this.renderLine(' ' + colors.dim(this.line(width - 6)), width);\n \n // Combine all agents for display\n const allAgents = [...new Set([...activeAgents, ...completedAgents])];\n const waitingAgents = ['security', 'privacy', 'typecheck', 'accessibility', 'legal', 'test', 'moneybags', 'production-ready']\n .filter(a => !activeAgents.includes(a) && !completedAgents.includes(a));\n \n // Display in 2 columns\n const leftAgents: string[] = [];\n const rightAgents: string[] = [];\n \n allAgents.forEach((agent, i) => {\n const isActive = activeAgents.includes(agent);\n const isDone = completedAgents.includes(agent);\n const icon = isActive ? this.agentIcon('running') : isDone ? this.agentIcon('done') : this.agentIcon('waiting');\n const statusText = isActive \n ? colors.running('analyzing') \n : isDone \n ? colors.success(`done (${this.getAgentIssueCount(agent)})`) \n : colors.waiting('waiting');\n const entry = `${icon} ${agent.slice(0, 12).padEnd(12)} ${colors.dim('...')} ${statusText}`;\n \n if (i % 2 === 0) {\n leftAgents.push(entry);\n } else {\n rightAgents.push(entry);\n }\n });\n \n // Add waiting agents\n waitingAgents.slice(0, 4).forEach((agent, i) => {\n const entry = `${this.agentIcon('waiting')} ${agent.slice(0, 12).padEnd(12)} ${colors.dim('...')} ${colors.waiting('waiting')}`;\n if ((allAgents.length + i) % 2 === 0) {\n leftAgents.push(entry);\n } else {\n rightAgents.push(entry);\n }\n });\n \n const maxRows = Math.max(leftAgents.length, rightAgents.length, agentRows);\n for (let i = 0; i < maxRows && i < agentRows; i++) {\n const left = leftAgents[i] || '';\n const right = rightAgents[i] || '';\n this.renderLine(' ' + padEnd(left, 35) + ' ' + right, width);\n }\n \n this.renderLine('', width);\n \n // Issues found section\n this.renderSectionBorder(width);\n this.renderLine(' ' + colors.header('ISSUES FOUND'), width);\n this.renderLine(' ' + colors.dim(this.line(width - 6)), width);\n \n const criticalLine = `${colors.critical('[!]')} ${colors.critical('Critical')} ${colors.critical(issuesBySeverity.critical.toString().padStart(4))}`;\n const moderateLine = `${colors.moderate('[~]')} ${colors.moderate('Moderate')} ${colors.moderate(issuesBySeverity.moderate.toString().padStart(5))}`;\n const seriousLine = `${colors.serious('[x]')} ${colors.serious('Serious')} ${colors.serious(issuesBySeverity.serious.toString().padStart(4))}`;\n const lowLine = `${colors.low('[-]')} ${colors.low('Low')} ${colors.low(issuesBySeverity.low.toString().padStart(5))}`;\n \n this.renderLine(' ' + padEnd(criticalLine, 28) + moderateLine, width);\n this.renderLine(' ' + padEnd(seriousLine, 28) + lowLine, width);\n this.renderLine('', width);\n \n // Watch status section\n this.renderSectionBorder(width);\n this.renderLine(' ' + colors.header('WATCH STATUS'), width);\n this.renderLine(' ' + colors.dim(this.line(width - 6)), width);\n const watchAnim = WATCH_FRAMES[this.animFrame % WATCH_FRAMES.length];\n const watchLine = this.state.watch.watching\n ? colors.success(`${watchAnim} Watching ${this.state.watch.directories} dirs`) + colors.dim(this.state.watch.debounceMs ? ` • debounce ${this.state.watch.debounceMs}ms` : '')\n : colors.dim('Watch idle');\n this.renderLine(' ' + watchLine, width);\n const lastChange = this.state.watch.lastChange \n ? colors.dim('Last change: ') + colors.highlight(this.state.watch.lastChange) \n : colors.dim('Last change: --');\n this.renderLine(' ' + lastChange, width);\n const recentChange = this.state.watch.recentChanges[0]?.file\n ? colors.dim('Recent: ') + this.state.watch.recentChanges[0].file\n : '';\n this.renderLine(' ' + recentChange, width);\n \n // Activity log section\n this.renderSectionBorder(width);\n this.renderLine(' ' + colors.header('ACTIVITY LOG'), width);\n this.renderLine(' ' + colors.dim(this.line(width - 6)), width);\n \n const startIdx = this.state.activityPage * activityRows;\n const recentActivity = this.state.activityLog.slice(startIdx, startIdx + activityRows);\n for (const entry of recentActivity) {\n const logLine = colors.dim(entry.time) + ' ' + this.colorizeActivityMessage(this.stripEmojis(entry.message));\n this.renderLine(' ' + logLine, width);\n }\n for (let i = recentActivity.length; i < activityRows; i++) {\n this.renderLine('', width);\n }\n }\n\n /**\n * Strip emojis from a message string\n */\n private stripEmojis(text: string): string {\n // Remove common emoji ranges\n return text.replace(/[\\u{1F300}-\\u{1F9FF}]/gu, '') // Emoji range\n .replace(/[\\u{2600}-\\u{26FF}]/gu, '') // Misc symbols\n .replace(/[\\u{2700}-\\u{27BF}]/gu, '') // Dingbats\n .replace(/[\\u{FE00}-\\u{FE0F}]/gu, '') // Variation selectors\n .replace(/[\\u{1F000}-\\u{1FFFF}]/gu, '') // Extended emoji\n .trim();\n }\n\n /**\n * Colorize activity log messages based on content\n */\n private colorizeActivityMessage(message: string): string {\n if (message.includes('[!]') || message.includes('CRITICAL')) {\n return colors.critical(message);\n }\n if (message.includes('[x]') || message.includes('SERIOUS')) {\n return colors.serious(message);\n }\n if (message.includes('[+]') || message.includes('complete')) {\n return colors.success(message);\n }\n if (message.includes('[*]') || message.includes('started')) {\n return colors.running(message);\n }\n if (message.includes('===')) {\n return colors.header(message);\n }\n // Color skill/banner activations for better visibility\n if (message.includes('[BANNER]') || message.includes('[SKILL]')) {\n return colors.brand(message);\n }\n return message;\n }\n\n /**\n * Get issue count for an agent\n */\n private getAgentIssueCount(agent: string): number {\n return this.state.issues.filter(i => i.agent === agent).length;\n }\n\n /**\n * Render overview with summary statistics\n */\n private renderOverview(width: number, height: number): void {\n const { issuesBySeverity, totalIssues, processedFiles } = this.state.progress;\n const { completedAgents } = this.state.progress;\n const endTime = this.state.scanComplete && this.state.scanEndTime\n ? this.state.scanEndTime\n : Date.now();\n const elapsed = ((endTime - this.state.scanStartTime) / 1000).toFixed(1);\n const activityRows = Math.max(2, Math.min(8, Math.max(0, height - 26)));\n\n this.renderLine('', width);\n this.renderLine(' ' + colors.highlight(`${processedFiles}`) + colors.dim(` files scanned in ${elapsed}s`), width);\n this.renderLine(' ' + colors.highlight(`${completedAgents.length}`) + colors.dim(' scouts activated'), width);\n this.renderLine('', width);\n \n // Summary section\n this.renderSectionBorder(width);\n this.renderLine(' ' + colors.header('SUMMARY'), width);\n this.renderLine(' ' + colors.dim(this.line(width - 6)), width);\n \n const criticalLabel = issuesBySeverity.critical > 0 ? ' ' + colors.alert('<- FIX NOW') : '';\n this.renderLine(' ' + colors.critical('[!]') + ' ' + colors.critical(issuesBySeverity.critical.toString().padStart(4)) + ' ' + colors.critical('Critical issues') + criticalLabel, width);\n this.renderLine(' ' + colors.serious('[x]') + ' ' + colors.serious(issuesBySeverity.serious.toString().padStart(4)) + ' ' + colors.serious('Serious issues'), width);\n this.renderLine(' ' + colors.moderate('[~]') + ' ' + colors.moderate(issuesBySeverity.moderate.toString().padStart(4)) + ' ' + colors.moderate('Moderate issues'), width);\n this.renderLine(' ' + colors.low('[-]') + ' ' + colors.low(issuesBySeverity.low.toString().padStart(4)) + ' ' + colors.low('Low issues'), width);\n this.renderLine('', width);\n\n // Top critical issues\n const criticalIssues = this.state.issues\n .filter(i => i.severity === 'critical')\n .slice(0, 3);\n\n if (criticalIssues.length > 0) {\n this.renderSectionBorder(width);\n this.renderLine(' ' + colors.critical('TOP CRITICAL ISSUES'), width);\n this.renderLine(' ' + colors.dim(this.line(width - 6)), width);\n\n for (const issue of criticalIssues) {\n const filename = issue.file.split('/').pop() || issue.file;\n const lineNum = issue.line ? `:${issue.line}` : '';\n const location = `${filename}${lineNum}`;\n const description = issue.issue.slice(0, 40) + (issue.issue.length > 40 ? '...' : '');\n this.renderLine(' ' + colors.critical('▸') + ' ' + colors.critical(description), width);\n this.renderLine(' ' + colors.dim(location), width);\n this.renderLine('', width);\n }\n } else if (totalIssues === 0) {\n this.renderSectionBorder(width);\n this.renderLine(' ' + colors.success('✓ No issues found - code looks good!'), width);\n this.renderLine('', width);\n }\n \n // Activity log section (paged)\n this.renderSectionBorder(width);\n this.renderLine(' ' + colors.header('ACTIVITY LOG'), width);\n this.renderLine(' ' + colors.dim(this.line(width - 6)), width);\n \n const startIdx = this.state.activityPage * activityRows;\n const recentActivity = this.state.activityLog.slice(startIdx, startIdx + activityRows);\n for (const entry of recentActivity) {\n const logLine = colors.dim(entry.time) + ' ' + this.colorizeActivityMessage(this.stripEmojis(entry.message));\n this.renderLine(' ' + logLine, width);\n }\n for (let i = recentActivity.length; i < activityRows; i++) {\n this.renderLine('', width);\n }\n }\n\n /**\n * Render filtered issues list\n */\n private renderIssuesList(width: number): void {\n const filteredIssues = this.getFilteredIssues();\n const { selectedIssue } = this.state;\n\n const pageSize = 10;\n const currentPage = Math.floor(selectedIssue / pageSize) + 1;\n const totalPages = Math.max(1, Math.ceil(filteredIssues.length / pageSize));\n const pageInfo = colors.dim(`Page ${currentPage}/${totalPages}`) + ' ' + colors.highlight(`${filteredIssues.length}`) + colors.dim(' issues');\n \n this.renderLine(' ' + colors.dim('Filter:') + ' ' + this.getFilterDescription() + ' ' + pageInfo, width);\n this.renderSectionBorder(width);\n\n // Issues list (paginated)\n const startIndex = Math.floor(selectedIssue / pageSize) * pageSize;\n const pageIssues = filteredIssues.slice(startIndex, startIndex + pageSize);\n\n // Show message if no issues match filter\n if (filteredIssues.length === 0) {\n this.renderLine('', width);\n this.renderLine(' ' + colors.dim('No issues match the current filter.'), width);\n this.renderLine(' ' + colors.dim('Press [x] to clear filters or [b] to go back.'), width);\n this.renderLine('', width);\n for (let i = 0; i < pageSize - 4; i++) {\n this.renderLine('', width);\n }\n return;\n }\n\n for (let i = 0; i < pageIssues.length; i++) {\n const issue = pageIssues[i]!;\n const globalIndex = startIndex + i;\n const isSelected = globalIndex === selectedIssue;\n const cursor = isSelected ? colors.selected('▸') : ' ';\n const severityIcon = this.severityIcon(issue.severity);\n const filename = issue.file.split('/').pop() || issue.file;\n const location = colors.dim(`${filename}:${issue.line || '?'}`);\n const description = issue.issue.slice(0, 35) + (issue.issue.length > 35 ? '...' : '');\n const descText = isSelected ? colors.selected(description) : description;\n\n this.renderLine(' ' + severityIcon + ' ' + cursor + ' ' + padEnd(descText, 40) + location, width);\n }\n\n // Padding if fewer issues\n for (let i = pageIssues.length; i < pageSize; i++) {\n this.renderLine('', width);\n }\n\n // Selected issue details\n if (filteredIssues[selectedIssue]) {\n const selected = filteredIssues[selectedIssue];\n this.renderSectionBorder(width);\n this.renderLine(' ' + colors.header('SELECTED:') + ' ' + colors.highlight(selected.issue.slice(0, width - 20)), width);\n this.renderLine(' ' + colors.dim(this.line(width - 6)), width);\n this.renderLine(' ' + colors.dim('File:') + ' ' + selected.file.slice(0, width - 15), width);\n this.renderLine(' ' + colors.dim('Line:') + ' ' + (selected.line || 'Unknown') + ' ' + colors.dim('Scout:') + ' ' + selected.agent, width);\n this.renderLine('', width);\n \n // Fix suggestion\n const fixLines = this.wrapText(selected.fix, width - 8);\n this.renderLine(' ' + colors.success('Fix:'), width);\n for (const line of fixLines.slice(0, 2)) {\n this.renderLine(' ' + colors.success(line), width);\n }\n }\n }\n\n /**\n * Render agents view\n */\n private renderAgentsView(width: number): void {\n const sorted = this.getSortedAgents();\n\n const pageSize = 6;\n const startIdx = this.state.agentPage * pageSize;\n const slice = sorted.slice(startIdx, startIdx + pageSize);\n\n const totalPages = Math.max(1, Math.ceil(sorted.length / pageSize));\n const pageHint = totalPages > 1 ? ' ' + colors.highlight(`[n/p]`) + colors.dim(' more pages') : '';\n this.renderLine(' ' + colors.header('SCOUT STATUS') + ' ' + colors.dim('(j/k navigate, Enter view issues)'), width);\n this.renderSectionBorder(width);\n this.renderLine(' ' + colors.highlight(`${sorted.length}`) + colors.dim(' scouts') + ' ' + colors.dim(`Page ${this.state.agentPage + 1}/${totalPages}`) + pageHint, width);\n\n if (slice.length === 0) {\n this.renderLine(' ' + colors.dim('No scouts yet'), width);\n return;\n }\n\n this.renderLine(' ' + colors.dim('Name Status Issues Duration'), width);\n this.renderLine(' ' + colors.dim(this.line(width - 6)), width);\n \n for (let i = 0; i < slice.length; i++) {\n const agent = slice[i];\n if (!agent) continue;\n const globalIdx = startIdx + i;\n const isSelected = globalIdx === this.state.selectedAgent;\n const cursor = isSelected ? colors.selected('▸') : ' ';\n const statusIcon = agent.status === 'running' \n ? this.agentIcon('running')\n : agent.status === 'done' \n ? this.agentIcon('done') \n : this.agentIcon('waiting');\n const statusText = agent.status === 'running'\n ? colors.running(agent.status.padEnd(9))\n : agent.status === 'done'\n ? colors.success(agent.status.padEnd(9))\n : colors.waiting(agent.status.padEnd(9));\n const issueCount = agent.issues > 0 ? colors.serious(agent.issues.toString().padStart(6)) : colors.dim(agent.issues.toString().padStart(6));\n const duration = colors.dim(agent.duration.padEnd(8));\n const nameText = isSelected ? colors.selected(agent.name.padEnd(18)) : agent.name.padEnd(18);\n \n this.renderLine(' ' + cursor + ' ' + statusIcon + ' ' + nameText + ' ' + statusText + ' ' + issueCount + ' ' + duration, width);\n }\n \n // Padding\n for (let i = slice.length; i < pageSize; i++) {\n this.renderLine('', width);\n }\n\n // Show recent skill activations (discrete banner display)\n if (this.state.skillBanners.length > 0) {\n this.renderSectionBorder(width);\n this.renderLine(' ' + colors.header('RECENT ACTIVATIONS'), width);\n this.renderLine(' ' + colors.dim(this.line(width - 6)), width);\n\n const recentBanners = this.state.skillBanners.slice(0, 3); // Show last 3\n for (const banner of recentBanners) {\n const skillName = colors.highlight(banner.skill);\n const quote = banner.quote ? ' ' + colors.dim(`\"${banner.quote.slice(0, 35)}${banner.quote.length > 35 ? '...' : ''}\"`) : '';\n this.renderLine(' ' + colors.brand('◉') + ' ' + skillName + quote, width);\n }\n this.renderLine('', width);\n }\n\n // Show selected agent summary\n const selected = sorted[this.state.selectedAgent];\n if (selected) {\n const agentIssues = this.state.issues.filter(i => i.agent === selected.name);\n const criticals = agentIssues.filter(i => i.severity === 'critical').length;\n const serious = agentIssues.filter(i => i.severity === 'serious').length;\n \n this.renderSectionBorder(width);\n this.renderLine(' ' + colors.header('SELECTED:') + ' ' + colors.highlight(selected.name), width);\n this.renderLine(' ' + colors.dim(this.line(width - 6)), width);\n this.renderLine(' ' + colors.dim('Issues:') + ' ' + colors.highlight(agentIssues.length.toString()) + ' total (' + colors.critical(`[!] ${criticals} critical`) + ', ' + colors.serious(`[x] ${serious} serious`) + ')', width);\n this.renderLine(' ' + colors.dim('Press Enter to view all issues from this scout'), width);\n }\n }\n\n /**\n * Render files view\n */\n private renderFilesView(width: number): void {\n \n // Group issues by file\n const fileIssues = new Map<string, Issue[]>();\n for (const issue of this.state.issues) {\n if (!fileIssues.has(issue.file)) {\n fileIssues.set(issue.file, []);\n }\n fileIssues.get(issue.file)!.push(issue);\n }\n\n // Sort by issue count\n const sortedFiles = Array.from(fileIssues.entries())\n .sort((a, b) => b[1].length - a[1].length)\n .slice(0, 15);\n\n this.renderLine(' ' + colors.header('FILES WITH ISSUES'), width);\n this.renderSectionBorder(width);\n\n for (const [file, issues] of sortedFiles) {\n const filename = file.split('/').pop() || file;\n const criticalCount = issues.filter(i => i.severity === 'critical').length;\n const totalCount = issues.length;\n const criticalText = criticalCount > 0 ? colors.critical(` (${criticalCount} critical)`) : '';\n const countText = criticalCount > 0 ? colors.serious(`${totalCount} issues`) : colors.dim(`${totalCount} issues`);\n this.renderLine(' ' + filename.padEnd(35) + ' ' + countText + criticalText, width);\n }\n\n // Padding if fewer files\n for (let i = sortedFiles.length; i < 10; i++) {\n this.renderLine('', width);\n }\n }\n\n // ============================================\n // NEW VIEWS\n // ============================================\n\n /**\n * Render details view - selected issue with code snippet\n */\n private renderDetailsView(width: number, _height: number): void {\n const filteredIssues = this.getFilteredIssues();\n const issue = filteredIssues[this.state.selectedIssue];\n \n if (!issue) {\n this.renderLine(' ' + colors.dim('No issue selected. Press [b] to go back.'), width);\n return;\n }\n \n // Header\n const severityColor = issue.severity === 'critical' ? colors.critical :\n issue.severity === 'serious' ? colors.serious :\n issue.severity === 'moderate' ? colors.moderate : colors.low;\n \n this.renderLine(' ' + colors.header('ISSUE DETAILS') + ' ' + severityColor(`[${issue.severity.toUpperCase()}]`), width);\n this.renderSectionBorder(width);\n \n // Issue info\n this.renderLine(' ' + colors.dim('File:') + ' ' + issue.file, width);\n this.renderLine(' ' + colors.dim('Line:') + ' ' + (issue.line || '?') + ' ' + colors.dim('Scout:') + ' ' + (issue.agent || 'unknown'), width);\n this.renderLine('', width);\n \n // Issue description\n this.renderLine(' ' + colors.header('Issue'), width);\n const issueLines = this.wrapText(issue.issue, width - 8);\n for (const line of issueLines.slice(0, 4)) {\n this.renderLine(' ' + severityColor(line), width);\n }\n this.renderLine('', width);\n \n // Code snippet section\n this.renderSectionBorder(width);\n this.renderLine(' ' + colors.header('CODE SNIPPET'), width);\n \n const snippet = this.state.codeSnippets.get(this.state.selectedIssue);\n if (snippet) {\n this.renderLine(' ' + colors.dim(this.line(width - 6)), width);\n const maxLines = Math.min(snippet.lines.length, 10);\n for (let i = 0; i < maxLines; i++) {\n const lineNum = snippet.startLine + i;\n const isHighlight = lineNum === snippet.highlightLine;\n const prefix = isHighlight ? colors.critical('→') : ' ';\n const lineNumStr = colors.dim(lineNum.toString().padStart(4));\n const lineContent = isHighlight ? colors.yellow(snippet.lines[i] || '') : (snippet.lines[i] || '');\n this.renderLine(' ' + prefix + ' ' + lineNumStr + ' ' + colors.dim('│') + ' ' + lineContent, width);\n }\n if (snippet.lines.length > 10) {\n this.renderLine(' ' + colors.dim(` ... ${snippet.lines.length - 10} more lines`), width);\n }\n } else {\n this.renderLine(' ' + colors.dim('No code snippet available. Snippet is loaded when issue is selected.'), width);\n }\n this.renderLine('', width);\n \n // Fix suggestion\n this.renderSectionBorder(width);\n this.renderLine(' ' + colors.success('SUGGESTED FIX'), width);\n const fixLines = this.wrapText(issue.fix, width - 8);\n for (const line of fixLines.slice(0, 4)) {\n this.renderLine(' ' + colors.success(line), width);\n }\n \n // Metadata\n if (issue.cwe || issue.owasp || issue.effort) {\n this.renderLine('', width);\n this.renderSectionBorder(width);\n this.renderLine(' ' + colors.header('METADATA'), width);\n if (issue.cwe) this.renderLine(' ' + colors.dim('CWE:') + ' ' + issue.cwe, width);\n if (issue.owasp) this.renderLine(' ' + colors.dim('OWASP:') + ' ' + issue.owasp, width);\n if (issue.effort) this.renderLine(' ' + colors.dim('Effort:') + ' ' + issue.effort, width);\n }\n }\n\n /**\n * Render costs view - Moneybags cost breakdown\n */\n private renderCostsView(width: number, _height: number): void {\n \n this.renderLine(' ' + colors.header('💰 COST ANALYSIS') + ' ' + colors.dim('(Moneybags)'), width);\n this.renderSectionBorder(width);\n \n const cost = this.state.costReport;\n if (!cost) {\n this.renderLine(' ' + colors.dim('No cost data available. Run a full scan to get cost estimates.'), width);\n this.renderLine('', width);\n return;\n }\n \n // Format currency helper\n const fmt = (n: number) => n >= 1000000 ? `$${(n / 1000000).toFixed(2)}M` :\n n >= 1000 ? `$${(n / 1000).toFixed(1)}k` : `$${n}`;\n \n // Check if pre-revenue mode\n const payingUsersCount = this.state.guardianConfig.moneybags.payingUsers;\n const rpuValue = this.state.guardianConfig.moneybags.revenuePerUser;\n const isPreRevenue = payingUsersCount === 0 || rpuValue === 0;\n \n // Summary cards\n this.renderLine('', width);\n this.renderLine(' ' + colors.header('SUMMARY'), width);\n this.renderLine(' ' + colors.dim(this.line(width - 6)), width);\n \n if (isPreRevenue) {\n // PRE-REVENUE MODE: Show developer time focus\n const devRate = this.state.guardianConfig.moneybags.developerRate;\n const hoursToFix = cost.fixNowCost / devRate;\n const hoursStr = hoursToFix < 1 ? `${Math.round(hoursToFix * 60)} minutes` : `${hoursToFix.toFixed(1)} hours`;\n \n this.renderLine(' ' + colors.header('PRE-REVENUE MODE') + ' ' + colors.dim('(cost = developer time only)'), width);\n this.renderLine('', width);\n this.renderLine(' ' + colors.success('Total Dev Time:') + ' ' + colors.success(hoursStr), width);\n this.renderLine(' ' + colors.dim('Dev Cost:') + ' ' + colors.highlight(fmt(cost.fixNowCost)), width);\n this.renderLine('', width);\n this.renderLine(' ' + colors.dim('Set paying users + revenue/user in config (c) to enable full cost analysis'), width);\n this.renderLine('', width);\n } else {\n // REVENUE MODE: Full cost breakdown\n const fixNowLabel = colors.success('Fix Now Cost:');\n const prodLabel = colors.critical('Production Cost:');\n const savingsLabel = colors.running('Potential Savings:');\n \n this.renderLine(' ' + fixNowLabel + ' ' + colors.success(fmt(cost.fixNowCost)), width);\n this.renderLine(' ' + prodLabel + ' ' + colors.critical(fmt(cost.productionCost)), width);\n this.renderLine(' ' + savingsLabel + ' ' + colors.running(fmt(cost.savings)), width);\n this.renderLine('', width);\n \n // ROI\n const roi = cost.fixNowCost > 0 ? Math.round((cost.savings / cost.fixNowCost) * 100) : 0;\n this.renderLine(' ' + colors.dim('ROI:') + ' ' + colors.highlight(`${roi}%`) + ' ' + colors.dim('return on fixing these issues now'), width);\n this.renderLine('', width);\n }\n \n // Current configuration\n this.renderSectionBorder(width);\n this.renderLine(' ' + colors.header('CONFIGURATION'), width);\n this.renderLine(' ' + colors.dim(this.line(width - 6)), width);\n this.renderLine(' ' + colors.dim('Users:') + ' ' + colors.highlight(this.state.guardianConfig.moneybags.userCount.toLocaleString()), width);\n const payingUsers = this.state.guardianConfig.moneybags.payingUsers;\n const rpu = this.state.guardianConfig.moneybags.revenuePerUser;\n if (payingUsers > 0 || rpu > 0) {\n if (payingUsers > 0) {\n this.renderLine(' ' + colors.dim('Paying:') + ' ' + colors.highlight(payingUsers.toLocaleString()), width);\n }\n if (rpu > 0) {\n const effectiveUsers = payingUsers > 0 ? payingUsers : this.state.guardianConfig.moneybags.userCount;\n const mrr = effectiveUsers * rpu;\n this.renderLine(' ' + colors.dim('MRR:') + ' ' + colors.success(`$${mrr.toLocaleString()}/mo`), width);\n }\n }\n this.renderLine(' ' + colors.dim('Dev Rate:') + ' ' + colors.highlight(`$${this.state.guardianConfig.moneybags.developerRate}/hr`), width);\n if (this.state.guardianConfig.moneybags.industry) {\n this.renderLine(' ' + colors.dim('Industry:') + ' ' + colors.highlight(this.state.guardianConfig.moneybags.industry), width);\n }\n this.renderLine(' ' + colors.dim('Press') + ' ' + colors.highlight('c') + ' ' + colors.dim('for full config'), width);\n this.renderLine('', width);\n \n // Per-issue breakdown (if available)\n if (cost.perIssue && cost.perIssue.length > 0) {\n this.renderSectionBorder(width);\n this.renderLine(' ' + colors.header('PER-ISSUE BREAKDOWN'), width);\n this.renderLine(' ' + colors.dim(this.line(width - 6)), width);\n \n const maxRows = Math.min(cost.perIssue.length, 8);\n for (let i = 0; i < maxRows; i++) {\n const item = cost.perIssue[i];\n if (!item) continue;\n const issueName = item.issue.slice(0, 40) + (item.issue.length > 40 ? '...' : '');\n this.renderLine(' ' + colors.dim('•') + ' ' + issueName.padEnd(45) + ' ' + colors.serious(fmt(item.cost)), width);\n }\n if (cost.perIssue.length > 8) {\n this.renderLine(' ' + colors.dim(`... and ${cost.perIssue.length - 8} more`), width);\n }\n }\n \n // Padding\n this.renderLine('', width);\n }\n\n /**\n * Render readiness view - Production readiness checklist\n */\n private renderReadinessView(width: number, _height: number): void {\n \n this.renderLine(' ' + colors.header('PRODUCTION READINESS'), width);\n this.renderSectionBorder(width);\n \n const readiness = this.state.readiness;\n if (!readiness) {\n this.renderLine(' ' + colors.dim('No readiness data. Run production-ready agent for assessment.'), width);\n return;\n }\n \n // Status indicator\n const statusColor = readiness.status === 'ready' ? colors.success :\n readiness.status === 'caution' ? colors.running : colors.critical;\n const statusIcon = readiness.status === 'ready' ? '✓' :\n readiness.status === 'caution' ? '~' : '✗';\n \n this.renderLine('', width);\n this.renderLine(' ' + colors.header('STATUS'), width);\n this.renderLine(' ' + colors.dim(this.line(width - 6)), width);\n this.renderLine(' ' + statusColor(`[${statusIcon}] ${readiness.status.toUpperCase()}`), width);\n this.renderLine('', width);\n \n // Score bar\n const scoreWidth = 40;\n const scoreFilled = Math.round((readiness.score / 100) * scoreWidth);\n const scoreEmpty = scoreWidth - scoreFilled;\n const scoreBar = statusColor('█'.repeat(scoreFilled)) + colors.dim('░'.repeat(scoreEmpty));\n \n this.renderLine(' ' + colors.dim('Score:') + ' ' + scoreBar + ' ' + statusColor(`${readiness.score}/100`), width);\n this.renderLine('', width);\n \n // Requirements summary\n this.renderSectionBorder(width);\n this.renderLine(' ' + colors.header('REQUIREMENTS'), width);\n this.renderLine(' ' + colors.dim(this.line(width - 6)), width);\n this.renderLine(' ' + colors.dim('Met:') + ' ' + colors.highlight(`${readiness.requirementsMet}/${readiness.total}`), width);\n this.renderLine('', width);\n \n // Requirements list (if available)\n if (readiness.requirements && readiness.requirements.length > 0) {\n for (const req of readiness.requirements.slice(0, 10)) {\n const icon = req.met ? colors.success('✓') : colors.critical('✗');\n const text = req.met ? colors.dim(req.name) : req.name;\n this.renderLine(' ' + icon + ' ' + text, width);\n }\n }\n \n this.renderLine('', width);\n }\n\n /**\n * Render analysis view - Semantic + Attack Surface\n */\n private renderAnalysisView(width: number, _height: number): void {\n \n this.renderLine(' ' + colors.header('ANALYSIS REPORT'), width);\n this.renderSectionBorder(width);\n \n // Semantic Analysis section\n const semantic = this.state.semanticAnalysis;\n if (semantic) {\n this.renderLine(' ' + colors.header('SEMANTIC ANALYSIS'), width);\n this.renderLine(' ' + colors.dim(this.line(width - 6)), width);\n \n if (semantic.dataFlowIssues > 0) {\n this.renderLine(' ' + colors.critical('[!]') + ' ' + colors.critical(`${semantic.dataFlowIssues} Data Flow Vulnerabilities`), width);\n this.renderLine(' ' + colors.dim('Untrusted input reaching dangerous sinks'), width);\n }\n if (semantic.raceConditions > 0) {\n this.renderLine(' ' + colors.running('[~]') + ' ' + colors.running(`${semantic.raceConditions} Race Conditions`), width);\n this.renderLine(' ' + colors.dim('TOCTOU, double-spend risks'), width);\n }\n if (semantic.authIssues > 0) {\n this.renderLine(' ' + colors.critical('[!]') + ' ' + colors.critical(`${semantic.authIssues} Authentication Issues`), width);\n this.renderLine(' ' + colors.dim('Missing or bypassable auth'), width);\n }\n \n const total = semantic.dataFlowIssues + semantic.raceConditions + semantic.authIssues;\n if (total === 0) {\n this.renderLine(' ' + colors.success('✓ No semantic issues detected'), width);\n }\n \n this.renderLine('', width);\n }\n \n // Attack Surface section\n const attack = this.state.attackSurface;\n if (attack) {\n this.renderSectionBorder(width);\n this.renderLine(' ' + colors.header('ATTACK SURFACE'), width);\n this.renderLine(' ' + colors.dim(this.line(width - 6)), width);\n \n this.renderLine(' ' + colors.dim('Endpoints:') + ' ' + colors.highlight(attack.totalEndpoints.toString()), width);\n \n if (attack.unprotected > 0) {\n this.renderLine(' ' + colors.critical('Unprotected:') + ' ' + colors.critical(attack.unprotected.toString()), width);\n } else {\n this.renderLine(' ' + colors.success('Unprotected:') + ' ' + colors.success('0'), width);\n }\n \n // Risk score bar\n const riskWidth = 30;\n const riskFilled = Math.round((attack.riskScore / 100) * riskWidth);\n const riskEmpty = riskWidth - riskFilled;\n const riskColor = attack.riskScore > 70 ? colors.critical :\n attack.riskScore > 40 ? colors.running : colors.success;\n const riskBar = riskColor('█'.repeat(riskFilled)) + colors.dim('░'.repeat(riskEmpty));\n \n this.renderLine(' ' + colors.dim('Risk Score:') + ' ' + riskBar + ' ' + riskColor(`${attack.riskScore}/100`), width);\n \n this.renderLine('', width);\n \n // Endpoints list (if available)\n if (attack.endpoints && attack.endpoints.length > 0) {\n this.renderLine(' ' + colors.dim('Top Endpoints:'), width);\n for (const ep of attack.endpoints.slice(0, 5)) {\n const authIcon = ep.auth ? colors.success('[AUTH]') : colors.critical('[PUBLIC]');\n const method = colors.dim(ep.method.padEnd(6));\n const path = ep.sensitive ? colors.serious(ep.path) : ep.path;\n this.renderLine(' ' + authIcon + ' ' + method + ' ' + path, width);\n }\n }\n }\n \n if (!semantic && !attack) {\n this.renderLine(' ' + colors.dim('No analysis data available. Run a full scan for semantic analysis.'), width);\n }\n \n this.renderLine('', width);\n }\n\n /**\n * Render raw log view - All console output\n */\n private renderRawLogView(width: number, height: number): void {\n \n const pageSize = Math.max(10, height - 15);\n const totalPages = Math.max(1, Math.ceil(this.state.rawLog.length / pageSize));\n \n this.renderLine(' ' + colors.header('RAW LOG') + ' ' + colors.dim(`Page ${this.state.rawLogPage + 1}/${totalPages}`) + ' ' + colors.highlight(`${this.state.rawLog.length}`) + colors.dim(' entries'), width);\n this.renderSectionBorder(width);\n \n if (this.state.rawLog.length === 0) {\n this.renderLine(' ' + colors.dim('No log entries yet.'), width);\n this.renderLine('', width);\n return;\n }\n \n const startIdx = this.state.rawLogPage * pageSize;\n const logs = this.state.rawLog.slice(startIdx, startIdx + pageSize);\n \n for (const entry of logs) {\n const levelColor = entry.level === 'error' ? colors.critical :\n entry.level === 'warn' ? colors.running :\n entry.level === 'info' ? colors.success : colors.dim;\n const levelStr = levelColor(`[${entry.level.toUpperCase().padEnd(5)}]`);\n const timeStr = colors.dim(entry.time);\n const message = entry.message.slice(0, width - 25);\n \n this.renderLine(' ' + timeStr + ' ' + levelStr + ' ' + message, width);\n }\n \n // Padding\n for (let i = logs.length; i < pageSize; i++) {\n this.renderLine('', width);\n }\n }\n\n /**\n * Render skills browser view\n */\n private renderSkillsView(width: number, _height: number): void {\n const { skillsBrowser } = this.state;\n \n // Built-in scouts list (static)\n const builtInScouts = [\n { name: 'security', desc: 'Security vulnerabilities' },\n { name: 'privacy', desc: 'Data privacy issues' },\n { name: 'accessibility', desc: 'A11y compliance' },\n { name: 'performance', desc: 'Performance bottlenecks' },\n { name: 'production-ready', desc: 'Deploy readiness' },\n { name: 'moneybags', desc: 'Cost analysis' },\n { name: 'agent-smith', desc: 'Pattern hunter' },\n { name: 'soc2', desc: 'SOC2 compliance' },\n { name: 'devops', desc: 'CI/CD & infra' },\n { name: 'test', desc: 'Test coverage' },\n { name: 'bug-finding', desc: 'Bug detection' },\n { name: 'typecheck', desc: 'Type safety' },\n ];\n \n // Title with custom skill hint\n this.renderLine(' ' + colors.header('TOOLKIT') + ' ' + colors.dim('Scouts (built-in) + Skills (installable)'), width);\n this.renderSectionBorder(width);\n \n // Calculate column widths (4 panels, but we show 2 rows of 2)\n const innerWidth = width - 4;\n const halfWidth = Math.floor(innerWidth / 2);\n \n // Panel headers with selection indicator - Row 1: Scouts | Installed Skills\n const scoutsHeader = skillsBrowser.activePanel === 'installed' \n ? colors.selected('▸ Scouts') + colors.dim(` (${builtInScouts.length}+)`)\n : colors.dim(' Scouts') + colors.dim(` (${builtInScouts.length}+)`);\n \n const installedHeader = skillsBrowser.activePanel === 'global'\n ? colors.selected('▸ Skills') + colors.dim(` (${skillsBrowser.installedSkills.length + skillsBrowser.globalSkills.length})`)\n : colors.dim(' Skills') + colors.dim(` (${skillsBrowser.installedSkills.length + skillsBrowser.globalSkills.length})`);\n \n // Row 2 headers: Suggested | Categories\n const suggestedHeader = skillsBrowser.activePanel === 'suggested'\n ? colors.selected('▸ Suggested') + colors.dim(` (${skillsBrowser.suggestedSkills.length})`)\n : colors.dim(' Suggested') + colors.dim(` (${skillsBrowser.suggestedSkills.length})`);\n \n const categoriesHeader = skillsBrowser.activePanel === 'categories'\n ? colors.selected('▸ Categories') + colors.dim(` (${skillsBrowser.categories.length})`)\n : colors.dim(' Categories') + colors.dim(` (${skillsBrowser.categories.length})`);\n \n // Render header row 1: Scouts | Skills\n const headerRow1 = ' ' + padEnd(scoutsHeader, halfWidth) + colors.border('│') + installedHeader;\n this.renderLine(headerRow1, width);\n this.renderSectionBorder(width);\n \n // Determine max items per column\n const maxItems = 5;\n \n // Combine installed and global skills for the Skills column\n const allInstalledSkills = [...skillsBrowser.installedSkills, ...skillsBrowser.globalSkills];\n \n // Render content rows for Scouts | Skills\n for (let i = 0; i < maxItems; i++) {\n let scoutsCol = '';\n let skillsCol = '';\n \n // Scouts column (built-in)\n const scout = builtInScouts[i];\n if (scout) {\n const isSelected = skillsBrowser.activePanel === 'installed' && skillsBrowser.selectedIndex === i;\n const name = scout.name.slice(0, halfWidth - 15);\n const desc = colors.dim(scout.desc.slice(0, 12));\n scoutsCol = isSelected \n ? colors.selected('▸ ') + colors.highlight(name) + ' ' + desc\n : ' ' + colors.success('●') + ' ' + name + ' ' + desc;\n }\n \n // Installed skills column\n const skill = allInstalledSkills[i];\n if (skill) {\n const isSelected = skillsBrowser.activePanel === 'global' && skillsBrowser.selectedIndex === i;\n const name = skill.name.slice(0, halfWidth - 4);\n const isCustom = skill.installedFrom?.startsWith('file://');\n const badge = isCustom ? colors.dim(' (custom)') : '';\n skillsCol = isSelected\n ? colors.selected('▸ ') + colors.highlight(name) + badge\n : ' ' + name + badge;\n }\n \n const row = ' ' + padEnd(scoutsCol || '', halfWidth) + colors.border('│') + (skillsCol || '');\n this.renderLine(row, width);\n }\n \n // Separator and header row 2\n this.renderSectionBorder(width);\n const headerRow2 = ' ' + padEnd(suggestedHeader, halfWidth) + colors.border('│') + categoriesHeader;\n this.renderLine(headerRow2, width);\n this.renderSectionBorder(width);\n \n // Render content rows for Suggested | Categories\n for (let i = 0; i < maxItems; i++) {\n let suggestedCol = '';\n let categoriesCol = '';\n \n // Suggested skills column\n const suggestedSkill = skillsBrowser.suggestedSkills[i];\n if (suggestedSkill) {\n const isSelected = skillsBrowser.activePanel === 'suggested' && skillsBrowser.selectedIndex === i;\n const display = suggestedSkill.length > halfWidth - 4 ? suggestedSkill.slice(0, halfWidth - 7) + '...' : suggestedSkill;\n suggestedCol = isSelected\n ? colors.selected('▸ ') + colors.highlight(display)\n : ' ' + display;\n }\n \n // Categories column (or category detail)\n if (skillsBrowser.selectedCategory) {\n const catSkill = skillsBrowser.categorySkills[i];\n if (catSkill) {\n const isSelected = skillsBrowser.activePanel === 'categories' && skillsBrowser.selectedIndex === i;\n const display = catSkill.length > halfWidth - 4 ? catSkill.slice(0, halfWidth - 7) + '...' : catSkill;\n categoriesCol = isSelected\n ? colors.selected('▸ ') + colors.highlight(display)\n : ' ' + display;\n }\n } else {\n const cat = skillsBrowser.categories[i];\n if (cat) {\n const isSelected = skillsBrowser.activePanel === 'categories' && skillsBrowser.selectedIndex === i;\n const display = `${cat.name} (${cat.count})`;\n categoriesCol = isSelected\n ? colors.selected('▸ ') + colors.highlight(display)\n : ' ' + display;\n }\n }\n \n const row = ' ' + padEnd(suggestedCol || '', halfWidth) + colors.border('│') + (categoriesCol || '');\n this.renderLine(row, width);\n }\n \n // Detected stack info\n this.renderSectionBorder(width);\n const stackParts: string[] = [];\n if (skillsBrowser.detectedStack.framework) stackParts.push(skillsBrowser.detectedStack.framework);\n if (skillsBrowser.detectedStack.language) stackParts.push(skillsBrowser.detectedStack.language);\n if (skillsBrowser.detectedStack.database) stackParts.push(skillsBrowser.detectedStack.database);\n \n if (stackParts.length > 0) {\n this.renderLine(' ' + colors.dim('Stack: ') + colors.success(stackParts.join(', ')), width);\n }\n \n // Installation status or custom skill hint\n if (skillsBrowser.installing) {\n this.renderLine(' ' + colors.running('Installing: ') + skillsBrowser.installStatus, width);\n } else if (skillsBrowser.installStatus) {\n this.renderLine(' ' + colors.success(skillsBrowser.installStatus), width);\n } else {\n // Custom skill creation hint\n this.renderLine(' ' + colors.dim('Tip: Drag a text file here and press') + ' ' + colors.highlight('c') + ' ' + colors.dim('to create a global custom skill'), width);\n }\n \n // Category breadcrumb\n if (skillsBrowser.selectedCategory) {\n this.renderLine(' ' + colors.dim('Category: ') + colors.highlight(skillsBrowser.selectedCategory) + colors.dim(' (press b to go back)'), width);\n }\n \n // Controls hint\n this.renderSectionBorder(width);\n const key = (k: string) => colors.border('[') + colors.highlight(k) + colors.border(']');\n this.renderLine(' ' + key('Tab') + colors.dim(' panel ') + \n key('↑↓') + colors.dim(' select ') + \n key('Enter') + colors.dim(' install/browse ') + \n key('c') + colors.dim(' custom ') +\n key('b') + colors.dim(' back'), width);\n }\n\n /**\n * Render guardian view - conversational insights from your Guardian Agent\n */\n private renderGuardianView(width: number, height: number): void {\n \n // Combine Guardian insights with legacy notifications for total count\n const totalInsights = this.state.guardianInsights.length;\n const activeInsights = this.state.guardianInsights.filter(i => !i.dismissed).length;\n const countStr = activeInsights > 0 \n ? colors.critical(` (${activeInsights} active)`)\n : colors.dim(` (${totalInsights} total)`);\n \n this.renderLine(' ' + colors.header('GUARDIAN INSIGHTS') + countStr + ' ' + colors.dim('Your agentic code companion'), width);\n this.renderSectionBorder(width);\n \n // Agency Status Bar (compact, always shown if available)\n const agency = this.state.agencyStatus;\n if (agency) {\n const riskColor = agency.riskLevel === 'critical' ? colors.critical :\n agency.riskLevel === 'high' ? colors.serious :\n agency.riskLevel === 'medium' ? colors.running : colors.success;\n \n const goalsStr = `${colors.dim('Goals:')} ${colors.highlight(String(agency.goals.active))}/${agency.goals.completed + agency.goals.active}`;\n const hypothesesStr = `${colors.dim('Hypo:')} ${colors.highlight(String(agency.hypotheses.testing))} testing`;\n const riskStr = `${colors.dim('Risk:')} ${riskColor(agency.riskLevel.toUpperCase())}`;\n const effectStr = `${colors.dim('Effect:')} ${(agency.effectiveness >= 80 ? colors.success : agency.effectiveness >= 50 ? colors.running : colors.serious)(String(agency.effectiveness) + '%')}`;\n const quietStr = agency.isQuietHours ? colors.dim(' [quiet]') : '';\n \n this.renderLine(` ${goalsStr} ${hypothesesStr} ${riskStr} ${effectStr}${quietStr}`, width);\n this.renderSectionBorder(width);\n }\n \n // Calculate available lines\n const pageSize = Math.max(10, height - 14);\n const scrollPos = this.state.scrollPositions.guardian;\n \n if (totalInsights === 0 && this.state.notificationHistory.length === 0) {\n // Empty state - explain what Guardian does\n this.renderLine('', width);\n this.renderLine(' ' + colors.highlight('The Guardian is watching over your code.'), width);\n this.renderLine('', width);\n this.renderLine(' ' + colors.dim(\"Unlike a log viewer, the Guardian is an agent that:\"), width);\n this.renderLine(' ' + colors.dim(\" • Synthesizes insights from all skills\"), width);\n this.renderLine(' ' + colors.dim(\" • Speaks conversationally about what matters\"), width);\n this.renderLine(' ' + colors.dim(\" • Suggests specific actions to take\"), width);\n this.renderLine(' ' + colors.dim(\" • Celebrates when you fix issues\"), width);\n this.renderLine(' ' + colors.dim(\" • Tracks patterns over time\"), width);\n this.renderLine('', width);\n this.renderLine(' ' + colors.dim(\"When the Guardian has something to say, it'll appear here.\"), width);\n this.renderLine('', width);\n \n // AI enhancement status\n if (isAIAvailable()) {\n this.renderLine(' ' + colors.success('✓') + colors.dim(' AI-enhanced insights enabled'), width);\n } else {\n this.renderLine(' ' + colors.dim('Want smarter insights? Set ') + colors.highlight('ANTHROPIC_API_KEY') + colors.dim(' for AI enhancement'), width);\n }\n \n // Fill remaining space\n for (let i = 0; i < pageSize - 13; i++) {\n this.renderLine('', width);\n }\n } else {\n // Render Guardian insights (newest first, prioritized)\n // Filter out dismissed insights from the display\n const insights = this.getVisibleGuardianInsights();\n // Clamp selection/scroll to available items\n if (insights.length === 0) {\n this.state.selectedGuardianInsight = 0;\n this.state.scrollPositions.guardian = 0;\n } else {\n if (this.state.selectedGuardianInsight >= insights.length) {\n this.state.selectedGuardianInsight = insights.length - 1;\n }\n if (this.state.scrollPositions.guardian >= insights.length) {\n this.state.scrollPositions.guardian = Math.max(0, insights.length - 1);\n }\n }\n \n const startIdx = scrollPos;\n let linesUsed = 0;\n let itemIdx = startIdx;\n \n while (linesUsed < pageSize && itemIdx < insights.length) {\n const insight = insights[itemIdx];\n if (!insight) break;\n \n // Check if this insight is selected or expanded\n const isSelected = itemIdx === this.state.selectedGuardianInsight;\n const isExpanded = itemIdx === this.state.expandedGuardianInsight;\n \n // Format timestamp\n const ago = this.formatTimeAgo(insight.timestamp);\n \n // Type-based styling\n let icon: string;\n let typeColor: (s: string) => string;\n switch (insight.type) {\n case 'warning':\n icon = '[!]';\n typeColor = colors.critical;\n break;\n case 'observation':\n icon = '[>]';\n typeColor = colors.serious;\n break;\n case 'suggestion':\n icon = '[?]';\n typeColor = colors.highlight;\n break;\n case 'celebration':\n icon = '[+]';\n typeColor = colors.success;\n break;\n case 'question':\n icon = '[?]';\n typeColor = colors.moderate;\n break;\n default:\n icon = '[>]';\n typeColor = colors.dim;\n }\n \n // Selection and status indicators\n const selector = isSelected ? colors.highlight('▶ ') : ' ';\n const status = insight.dismissed ? colors.dim('✓') : isExpanded ? colors.highlight('▼') : colors.dim('▷');\n \n // Header line: [type] message (show full message when expanded, truncated otherwise)\n // Strip any emojis from the message\n const cleanMessage = this.stripEmojis(insight.message);\n if (isExpanded && !insight.dismissed && cleanMessage.length > width - 32) {\n // Multi-line message when expanded\n const msgLines = this.wrapText(cleanMessage, width - 12);\n for (let i = 0; i < msgLines.length && i < 3 && linesUsed < pageSize - 1; i++) {\n const msgLine = msgLines[i];\n if (!msgLine) continue;\n const prefix = i === 0 ? `${selector}${status} ${icon} ` : ' ';\n const line = i === 0 && isSelected\n ? pc.inverse(` ${msgLine} `)\n : typeColor(msgLine);\n this.renderLine(prefix + line, width);\n linesUsed++;\n }\n if (msgLines.length > 3) {\n this.renderLine(' ' + colors.dim('...'), width);\n linesUsed++;\n }\n } else {\n // Single line (truncated if needed)\n const msgMaxLen = width - 32;\n const msg = cleanMessage.length > msgMaxLen\n ? cleanMessage.slice(0, msgMaxLen - 3) + '...'\n : cleanMessage;\n\n const headerText = isSelected && !insight.dismissed\n ? pc.inverse(` ${icon} ${msg} `)\n : `${icon} ${typeColor(msg)}`;\n\n this.renderLine(`${selector}${status} ${headerText}`, width);\n linesUsed++;\n }\n \n // Time and category\n const metaLine = colors.dim(` ${ago} • ${insight.category}${isSelected && !isExpanded ? ' • Press Enter to expand' : ''}`);\n this.renderLine(' ' + metaLine, width);\n linesUsed++;\n \n // Show details if EXPANDED (not just selected)\n const showDetails = isExpanded && !insight.dismissed;\n \n // Verbose details section (if expanded)\n if (showDetails && insight.details && linesUsed < pageSize - 4) {\n // Severity breakdown\n if (insight.details.issueBreakdown && Object.keys(insight.details.issueBreakdown).length > 0) {\n const breakdown = insight.details.issueBreakdown;\n const parts: string[] = [];\n if (breakdown['critical']) parts.push(colors.critical(`${breakdown['critical']} critical`));\n if (breakdown['serious']) parts.push(colors.serious(`${breakdown['serious']} serious`));\n if (breakdown['moderate']) parts.push(colors.moderate(`${breakdown['moderate']} moderate`));\n if (parts.length > 0) {\n this.renderLine(' ' + parts.join(colors.dim(' • ')), width);\n linesUsed++;\n }\n }\n \n // Affected files (show more when expanded)\n if (insight.details.affectedFiles && insight.details.affectedFiles.length > 0 && linesUsed < pageSize - 3) {\n this.renderLine(' ' + colors.header('Files:'), width);\n linesUsed++;\n for (const file of insight.details.affectedFiles.slice(0, 8)) {\n if (linesUsed >= pageSize - 4) break;\n this.renderLine(' ' + pc.cyan('• ' + file), width);\n linesUsed++;\n }\n if (insight.details.affectedFiles.length > 8) {\n this.renderLine(' ' + colors.dim(`... +${insight.details.affectedFiles.length - 8} more`), width);\n linesUsed++;\n }\n }\n \n // Examples (specific issues - show more when expanded)\n if (insight.details.examples && insight.details.examples.length > 0 && linesUsed < pageSize - 2) {\n this.renderLine(' ' + colors.header('Examples:'), width);\n linesUsed++;\n for (const example of insight.details.examples.slice(0, 5)) {\n if (linesUsed >= pageSize - 2) break;\n\n // Better wrapping for long examples\n const maxLen = width - 18; // Room for prefix and padding\n if (example.length <= maxLen) {\n this.renderLine(' ' + colors.dim('• ') + example, width);\n linesUsed++;\n } else {\n // Wrap long examples intelligently\n const parts = this.wrapText(example, maxLen);\n for (let j = 0; j < parts.length && j < 2 && linesUsed < pageSize - 1; j++) {\n const prefix = j === 0 ? colors.dim('• ') : colors.dim(' ');\n this.renderLine(' ' + prefix + parts[j], width);\n linesUsed++;\n }\n if (parts.length > 2) {\n this.renderLine(' ' + colors.dim(' ...'), width);\n linesUsed++;\n }\n }\n }\n }\n \n // Comparison/trend\n if (insight.details.comparison && linesUsed < pageSize - 1) {\n const trendIcon = insight.details.trend === 'improving' ? '↓' : \n insight.details.trend === 'worsening' ? '↑' : '→';\n this.renderLine(' ' + colors.dim(`${trendIcon} ${insight.details.comparison}`), width);\n linesUsed++;\n }\n \n // Goal achievement receipt (resolved issues)\n if (insight.type === 'celebration' && insight.message.includes('Goal achieved') && linesUsed < pageSize - 3) {\n // Context is required - show error if missing\n if (!insight.context) {\n this.renderLine(' ' + colors.critical('[ERROR] Missing context in goal achievement insight'), width);\n linesUsed++;\n } else {\n this.renderLine(' ' + colors.dim(insight.context), width);\n linesUsed++;\n }\n \n // Details object is required - show error if missing\n if (!insight.details) {\n this.renderLine(' ' + colors.critical('[ERROR] Missing details object in goal achievement insight'), width);\n linesUsed++;\n } else if (insight.details.resolvedCount === undefined) {\n this.renderLine(' ' + colors.critical('[ERROR] Missing resolvedCount in goal achievement details'), width);\n linesUsed++;\n } else if (insight.details.resolvedCount === 0) {\n this.renderLine(' ' + colors.yellow('[WARNING] resolvedCount is 0 - no issues were found matching this goal'), width);\n linesUsed++;\n } else if (!insight.details.resolvedIssues) {\n this.renderLine(' ' + colors.critical(`[ERROR] Missing resolvedIssues array (expected ${insight.details.resolvedCount} issues)`), width);\n linesUsed++;\n } else if (insight.details.resolvedIssues.length === 0) {\n this.renderLine(' ' + colors.critical(`[ERROR] resolvedIssues array is empty (expected ${insight.details.resolvedCount} issues)`), width);\n linesUsed++;\n } else {\n // Validate count matches array length\n if (insight.details.resolvedCount !== insight.details.resolvedIssues.length) {\n this.renderLine(' ' + colors.critical(`[ERROR] resolvedCount (${insight.details.resolvedCount}) doesn't match array length (${insight.details.resolvedIssues.length})`), width);\n linesUsed++;\n }\n \n // Show resolved issues\n const resolvedCount = insight.details.resolvedCount;\n this.renderLine(' ' + colors.header(`Resolved ${resolvedCount} issue${resolvedCount > 1 ? 's' : ''}:`), width);\n linesUsed++;\n \n const maxIssues = Math.min(insight.details.resolvedIssues.length, 10);\n for (let i = 0; i < maxIssues && linesUsed < pageSize - 2; i++) {\n const issue = insight.details.resolvedIssues[i];\n if (!issue) {\n this.renderLine(' ' + colors.critical(`[ERROR] Missing issue at index ${i}`), width);\n linesUsed++;\n continue;\n }\n \n if (!issue.file) {\n this.renderLine(' ' + colors.critical(`[ERROR] Missing file in issue at index ${i}`), width);\n linesUsed++;\n continue;\n }\n \n if (!issue.issue) {\n this.renderLine(' ' + colors.critical(`[ERROR] Missing issue description at index ${i}`), width);\n linesUsed++;\n continue;\n }\n \n const fileName = basename(issue.file);\n const lineInfo = issue.line ? `:${issue.line}` : '';\n const issueText = issue.issue.length > 50 ? issue.issue.slice(0, 47) + '...' : issue.issue;\n const agentInfo = issue.agent ? colors.dim(` (${issue.agent})`) : '';\n \n this.renderLine(' ' + colors.success('• ') + `${fileName}${lineInfo}: ${issueText}${agentInfo}`, width);\n linesUsed++;\n }\n \n if (insight.details.resolvedIssues.length > maxIssues) {\n this.renderLine(' ' + colors.dim(`... +${insight.details.resolvedIssues.length - maxIssues} more`), width);\n linesUsed++;\n }\n }\n \n // Summary for goal achievements (always show if available)\n if (insight.details.summary && linesUsed < pageSize - 1) {\n this.renderLine(' ' + colors.dim(insight.details.summary), width);\n linesUsed++;\n }\n }\n }\n \n // Suggested action (show if expanded or selected)\n if (insight.suggestedAction && (showDetails || isSelected) && !insight.dismissed && linesUsed < pageSize) {\n const actionLine = colors.dim(' → ') + colors.highlight(insight.suggestedAction);\n this.renderLine(' ' + actionLine, width);\n linesUsed++;\n }\n \n // Command (show if expanded) - indicate that Enter will run it\n if (insight.actionCommand && showDetails && linesUsed < pageSize) {\n const cmdLine = colors.dim(' $ ') + colors.success(insight.actionCommand) + \n (isSelected ? colors.dim(' ') + colors.highlight('[Enter to run]') : '');\n this.renderLine(' ' + cmdLine, width);\n linesUsed++;\n }\n \n // Related issues count (show if expanded)\n if (showDetails && insight.relatedIssues && insight.relatedIssues.length > 0 && linesUsed < pageSize) {\n this.renderLine(' ' + colors.dim(`Related issues: ${insight.relatedIssues.length}`), width);\n linesUsed++;\n }\n \n // Spacing between insights\n if (linesUsed < pageSize - 1) {\n this.renderLine('', width);\n linesUsed++;\n }\n \n itemIdx++;\n }\n \n // Fill remaining space\n while (linesUsed < pageSize) {\n this.renderLine('', width);\n linesUsed++;\n }\n \n // Pagination info\n this.renderSectionBorder(width);\n const itemsPerPage = Math.floor(pageSize / 4); // Approximate items per page\n const currentPage = Math.floor(scrollPos / itemsPerPage) + 1;\n const totalPages = Math.max(1, Math.ceil(insights.length / itemsPerPage));\n const pageInfo = totalPages > 1 \n ? colors.dim(`Page ${currentPage}/${totalPages}`)\n : '';\n this.renderLine(' ' + pageInfo, width);\n }\n \n // Summary stats with AI status\n this.renderSectionBorder(width);\n const warningInsights = this.state.guardianInsights.filter(i => i.type === 'warning').length;\n const suggestionInsights = this.state.guardianInsights.filter(i => i.type === 'suggestion').length;\n const celebrationInsights = this.state.guardianInsights.filter(i => i.type === 'celebration').length;\n \n const statsLine = [\n warningInsights > 0 ? colors.critical(`${warningInsights} warnings`) : null,\n suggestionInsights > 0 ? colors.highlight(`${suggestionInsights} suggestions`) : null,\n celebrationInsights > 0 ? colors.success(`${celebrationInsights} wins`) : null\n ].filter(Boolean).join(' ');\n \n // AI status indicator\n const aiStatus = isAIAvailable() \n ? colors.success('AI ✓')\n : colors.dim('AI off');\n \n const summaryContent = statsLine || colors.dim('Watching...');\n this.renderLine(' ' + summaryContent + ' ' + colors.dim('│') + ' ' + aiStatus, width);\n \n // Controls with AI hint\n this.renderSectionBorder(width);\n const key = (k: string) => colors.border('[') + colors.highlight(k) + colors.border(']');\n const aiHint = isAIAvailable() ? '' : colors.dim(' │ Set ANTHROPIC_API_KEY for smarter insights');\n this.renderLine(' ' + key('n/p') + colors.dim(' pages ') + \n key('b') + colors.dim(' back ') +\n key('x') + colors.dim(' clear') + aiHint, width);\n }\n\n /**\n * Render goals management view\n */\n private renderGoalsView(width: number, _height: number): void {\n const { goalsPanel } = this.state;\n \n // Title\n this.renderLine(' ' + colors.header('GOALS') + ' ' + colors.dim('Track progress, achieve targets') + ' ' + colors.border('[') + colors.highlight('G') + colors.border(']'), width);\n this.renderSectionBorder(width);\n \n // Input mode\n if (goalsPanel.inputMode === 'add') {\n this.renderLine(' ' + colors.highlight('New goal:') + ' ' + goalsPanel.inputBuffer + colors.highlight('▌'), width);\n this.renderSectionBorder(width);\n this.renderLine(' ' + colors.dim('Examples: \"Reduce auth bugs by 50%\", \"Eliminate critical issues\"'), width);\n this.renderLine(' ' + colors.dim('Press Enter to add, Escape to cancel'), width);\n return;\n }\n \n // Add button\n const key = (k: string) => colors.border('[') + colors.highlight(k) + colors.border(']');\n this.renderLine(' ' + key('a') + colors.dim(' Add new goal'), width);\n this.renderSectionBorder(width);\n \n // Goals list\n const activeGoals = goalsPanel.goals.filter(g => g.status === 'active');\n const achievedGoals = goalsPanel.goals.filter(g => g.status === 'achieved');\n const otherGoals = goalsPanel.goals.filter(g => g.status !== 'active' && g.status !== 'achieved');\n \n if (goalsPanel.goals.length === 0) {\n this.renderLine('', width);\n this.renderLine(' ' + colors.dim('No goals yet.'), width);\n this.renderLine(' ' + colors.dim('Press [a] to add your first goal, or wait for auto-generated goals.'), width);\n this.renderLine('', width);\n } else {\n // Active goals\n if (activeGoals.length > 0) {\n this.renderLine(' ' + colors.highlight('Active:'), width);\n activeGoals.forEach((goal, idx) => {\n const isSelected = goalsPanel.selectedIndex === idx;\n const progress = this.calculateGoalProgress(goal);\n const bar = this.renderProgressBar(progress, 10);\n const source = goal.autoGenerated ? colors.dim('[auto]') : colors.dim('[manual]');\n const prefix = isSelected ? colors.highlight('▶ ') : ' ';\n this.renderLine(prefix + bar + ' ' + goal.description.slice(0, width - 30) + ' ' + source, width);\n });\n this.renderLine('', width);\n }\n \n // Achieved goals\n if (achievedGoals.length > 0) {\n this.renderLine(' ' + colors.success('Achieved:') + colors.dim(' [x to remove]'), width);\n achievedGoals.slice(0, 5).forEach(goal => {\n this.renderLine(' [+] ' + goal.description.slice(0, width - 10), width);\n });\n if (achievedGoals.length > 5) {\n this.renderLine(' ' + colors.dim(`+${achievedGoals.length - 5} more`), width);\n }\n this.renderLine('', width);\n }\n \n // Other goals\n if (otherGoals.length > 0) {\n this.renderLine(' ' + colors.dim('Other:'), width);\n otherGoals.slice(0, 2).forEach(goal => {\n const icon = goal.status === 'failed' ? '[X]' : goal.status === 'paused' ? '[P]' : '•';\n this.renderLine(' ' + icon + ' ' + goal.description.slice(0, width - 20) + colors.dim(` (${goal.status})`), width);\n });\n }\n }\n \n // Controls\n this.renderSectionBorder(width);\n const selectedGoal = activeGoals[goalsPanel.selectedIndex];\n if (selectedGoal) {\n this.renderLine(' ' + key('j/k') + colors.dim(' navigate ') +\n key('Enter') + colors.dim(' complete ') + \n key('d') + colors.dim(' delete ') +\n key('b') + colors.dim(' back'), width);\n } else {\n this.renderLine(' ' + key('j/k') + colors.dim(' navigate ') +\n key('a') + colors.dim(' add ') +\n key('b') + colors.dim(' back'), width);\n }\n }\n\n /**\n * Render hypotheses management view\n */\n private renderHypothesesView(width: number, _height: number): void {\n const { hypothesesPanel } = this.state;\n \n // Title\n this.renderLine(' ' + colors.header('HYPOTHESES') + ' ' + colors.dim('Test theories about your codebase') + ' ' + colors.border('[') + colors.highlight('y') + colors.border(']'), width);\n this.renderSectionBorder(width);\n \n // Input mode\n if (hypothesesPanel.inputMode === 'add') {\n this.renderLine(' ' + colors.highlight('New hypothesis:') + ' ' + hypothesesPanel.inputBuffer + colors.highlight('▌'), width);\n this.renderSectionBorder(width);\n this.renderLine(' ' + colors.dim('Examples: \"Mondays have more bugs\", \"Code reviews reduce issues\"'), width);\n this.renderLine(' ' + colors.dim('Press Enter to add, Escape to cancel'), width);\n return;\n }\n \n // Add button\n const key = (k: string) => colors.border('[') + colors.highlight(k) + colors.border(']');\n this.renderLine(' ' + key('a') + colors.dim(' Add new hypothesis'), width);\n this.renderSectionBorder(width);\n \n // Hypotheses list\n const testing = hypothesesPanel.hypotheses.filter(h => h.status === 'testing');\n const validated = hypothesesPanel.hypotheses.filter(h => h.status === 'validated');\n const invalidated = hypothesesPanel.hypotheses.filter(h => h.status === 'invalidated');\n \n if (hypothesesPanel.hypotheses.length === 0) {\n this.renderLine('', width);\n this.renderLine(' ' + colors.dim('No hypotheses yet.'), width);\n this.renderLine(' ' + colors.dim('Press [a] to add your first hypothesis.'), width);\n this.renderLine(' ' + colors.dim('The guardian will collect evidence and update confidence over time.'), width);\n this.renderLine('', width);\n } else {\n // Testing hypotheses\n if (testing.length > 0) {\n this.renderLine(' ' + colors.highlight('Testing:'), width);\n testing.forEach((hypo, idx) => {\n const isSelected = hypothesesPanel.selectedIndex === idx;\n const conf = Math.round(hypo.confidence * 100);\n const confColor = conf >= 70 ? colors.success : conf >= 40 ? colors.running : colors.serious;\n const prefix = isSelected ? colors.highlight('▶ ') : ' ';\n this.renderLine(prefix + '[?] \"' + hypo.statement.slice(0, width - 35) + '\" ' + confColor(`(${conf}%)`), width);\n this.renderLine(' ' + colors.dim(`Evidence: ${hypo.evidenceCount} points`), width);\n });\n this.renderLine('', width);\n }\n \n // Validated hypotheses\n if (validated.length > 0) {\n this.renderLine(' ' + colors.success('Validated:') + colors.dim(' [r to remove]'), width);\n validated.slice(0, 3).forEach(hypo => {\n this.renderLine(' [+] \"' + hypo.statement.slice(0, width - 15) + '\"', width);\n });\n if (validated.length > 3) {\n this.renderLine(' ' + colors.dim(`+${validated.length - 3} more`), width);\n }\n this.renderLine('', width);\n }\n \n // Invalidated hypotheses\n if (invalidated.length > 0) {\n this.renderLine(' ' + colors.serious('Invalidated:') + colors.dim(' [r to remove]'), width);\n invalidated.slice(0, 2).forEach(hypo => {\n this.renderLine(' [X] \"' + hypo.statement.slice(0, width - 15) + '\"', width);\n });\n if (invalidated.length > 2) {\n this.renderLine(' ' + colors.dim(`+${invalidated.length - 2} more`), width);\n }\n }\n }\n \n // Controls\n this.renderSectionBorder(width);\n const selectedHypo = testing[hypothesesPanel.selectedIndex];\n if (selectedHypo) {\n this.renderLine(' ' + key('j/k') + colors.dim(' navigate ') +\n key('v') + colors.dim(' validate ') + \n key('x') + colors.dim(' invalidate ') +\n key('d') + colors.dim(' delete ') +\n key('b') + colors.dim(' back'), width);\n } else {\n this.renderLine(' ' + key('j/k') + colors.dim(' navigate ') +\n key('a') + colors.dim(' add ') +\n key('b') + colors.dim(' back'), width);\n }\n }\n\n /**\n * Calculate goal progress correctly for both increase and reduction goals.\n * For reduction goals (startValue > target): progress = (startValue - currentValue) / (startValue - target)\n * For increase goals (startValue <= target): progress = currentValue / target\n */\n private calculateGoalProgress(goal: { startValue?: number | undefined; currentValue: number; target: number }): number {\n if (goal.target <= 0) return 0;\n \n const startValue = goal.startValue ?? goal.currentValue;\n \n // Reduction goal: startValue > target (e.g., reduce from 20 to 10)\n if (startValue > goal.target) {\n const totalReduction = startValue - goal.target;\n const actualReduction = startValue - goal.currentValue;\n return Math.round((actualReduction / totalReduction) * 100);\n }\n \n // Increase goal: progress toward target\n return Math.round((goal.currentValue / goal.target) * 100);\n }\n\n /**\n * Render a simple progress bar\n */\n private renderProgressBar(percent: number, width: number): string {\n const clamped = Math.max(0, Math.min(100, percent)); // Clamp to 0-100\n const filled = Math.round((clamped / 100) * width);\n const empty = width - filled;\n return colors.border('[') + \n colors.success('█'.repeat(filled)) + \n colors.dim('░'.repeat(empty)) + \n colors.border(']');\n }\n\n /**\n * Render memory tree view - visual hierarchy of issues\n */\n private renderMemoryTreeView(width: number, _height: number): void {\n const { memoryTree } = this.state;\n const stats = memoryTree.stats;\n const issues = memoryTree.issues;\n const patterns = memoryTree.globalPatterns;\n \n // Title\n const totalIssues = stats?.totalIssues || issues.length;\n this.renderLine(' ' + colors.header('MEMORY TREE') + ' ' + colors.dim(`[${totalIssues} issues]`) + ' ' + colors.border('[') + colors.highlight('t') + colors.border(']'), width);\n this.renderSectionBorder(width);\n \n if (!memoryTree.loaded) {\n this.renderLine(' ' + colors.dim('Loading memory data...'), width);\n return;\n }\n \n if (issues.length === 0 && patterns.length === 0) {\n this.renderLine(' ' + colors.dim('No issues in memory yet.'), width);\n this.renderLine(' ' + colors.dim('Run a scan to populate the memory tree.'), width);\n return;\n }\n \n // Tree rendering\n const tree = box;\n const selected = memoryTree.selectedNode;\n const expanded = memoryTree.expandedNodes;\n \n // Group issues by severity\n const bySeverity = { critical: [] as StoredIssue[], serious: [] as StoredIssue[], moderate: [] as StoredIssue[], low: [] as StoredIssue[] };\n for (const issue of issues) {\n const sev = issue.severity;\n if (sev === 'critical') bySeverity.critical.push(issue);\n else if (sev === 'serious') bySeverity.serious.push(issue);\n else if (sev === 'moderate') bySeverity.moderate.push(issue);\n else if (sev === 'low') bySeverity.low.push(issue);\n }\n \n // Group issues by file\n const byFile = new Map<string, StoredIssue[]>();\n for (const issue of issues) {\n if (!byFile.has(issue.file)) {\n byFile.set(issue.file, []);\n }\n byFile.get(issue.file)!.push(issue);\n }\n const sortedFiles = Array.from(byFile.entries())\n .sort((a, b) => b[1].length - a[1].length)\n .slice(0, 10);\n \n // Group issues by agent\n const byAgent = new Map<string, StoredIssue[]>();\n for (const issue of issues) {\n if (!byAgent.has(issue.agent)) {\n byAgent.set(issue.agent, []);\n }\n byAgent.get(issue.agent)!.push(issue);\n }\n const sortedAgents = Array.from(byAgent.entries())\n .sort((a, b) => b[1].length - a[1].length);\n \n // Severity bar helper\n const severityBar = (count: number, max: number, barWidth: number = 16): string => {\n const filled = max > 0 ? Math.round((count / max) * barWidth) : 0;\n return '█'.repeat(filled) + '░'.repeat(barWidth - filled);\n };\n \n const maxCount = Math.max(\n bySeverity.critical.length,\n bySeverity.serious.length,\n bySeverity.moderate.length,\n bySeverity.low.length,\n 1\n );\n \n // === SEVERITY SECTION ===\n const sevExpanded = expanded.has('severity');\n const sevIcon = sevExpanded ? '▼' : '▶';\n const sevSelected = selected === 'severity';\n const sevPrefix = sevSelected ? colors.selected('→') : ' ';\n this.renderLine(` ${sevPrefix} ${sevIcon} ` + (sevSelected ? colors.selected('By Severity') : colors.header('By Severity')), width);\n \n if (sevExpanded) {\n // Critical\n const critSelected = selected === 'severity-critical';\n const critPrefix = critSelected ? colors.selected('→') : ' ';\n const critCount = bySeverity.critical.length;\n const critBar = colors.critical(severityBar(critCount, maxCount));\n this.renderLine(` ${critPrefix} ${tree.vertical} ${critSelected ? colors.selected('critical') : colors.critical('critical')} (${critCount}) ${critBar}`, width);\n \n // Show individual critical issues if expanded\n if (expanded.has('severity-critical') && bySeverity.critical.length > 0) {\n const critIssues = bySeverity.critical.slice(0, 5);\n critIssues.forEach((issue, idx) => {\n const isLast = idx === critIssues.length - 1;\n const connector = isLast ? tree.bottomLeft : tree.leftT;\n const issueId = `severity-critical-${issue.id}`;\n const issueSelected = selected === issueId;\n const prefix = issueSelected ? colors.selected('→') : ' ';\n const filename = issue.file.split('/').pop() || issue.file;\n const line = issue.line ? `:${issue.line}` : '';\n const desc = issue.issue.slice(0, 35) + (issue.issue.length > 35 ? '...' : '');\n this.renderLine(` ${prefix} ${tree.vertical} ${connector}${tree.horizontal} ${issueSelected ? colors.selected(`${filename}${line}`) : colors.dim(`${filename}${line}`)} - ${colors.critical(desc)}`, width);\n });\n if (bySeverity.critical.length > 5) {\n this.renderLine(` ${tree.vertical} ${colors.dim(`... ${bySeverity.critical.length - 5} more`)}`, width);\n }\n }\n \n // Serious\n const serSelected = selected === 'severity-serious';\n const serPrefix = serSelected ? colors.selected('→') : ' ';\n const serCount = bySeverity.serious.length;\n const serBar = colors.serious(severityBar(serCount, maxCount));\n this.renderLine(` ${serPrefix} ${tree.vertical} ${serSelected ? colors.selected('serious') : colors.serious('serious')} (${serCount}) ${serBar}`, width);\n \n // Moderate\n const modSelected = selected === 'severity-moderate';\n const modPrefix = modSelected ? colors.selected('→') : ' ';\n const modCount = bySeverity.moderate.length;\n const modBar = colors.moderate(severityBar(modCount, maxCount));\n this.renderLine(` ${modPrefix} ${tree.vertical} ${modSelected ? colors.selected('moderate') : colors.moderate('moderate')} (${modCount}) ${modBar}`, width);\n \n // Low\n const lowSelected = selected === 'severity-low';\n const lowPrefix = lowSelected ? colors.selected('→') : ' ';\n const lowCount = bySeverity.low.length;\n const lowBar = colors.low(severityBar(lowCount, maxCount));\n this.renderLine(` ${lowPrefix} ${tree.bottomLeft} ${lowSelected ? colors.selected('low') : colors.low('low')} (${lowCount}) ${lowBar}`, width);\n }\n \n // === FILES SECTION ===\n const filesExpanded = expanded.has('files');\n const filesIcon = filesExpanded ? '▼' : '▶';\n const filesSelected = selected === 'files';\n const filesPrefix = filesSelected ? colors.selected('→') : ' ';\n this.renderLine(` ${filesPrefix} ${filesIcon} ` + (filesSelected ? colors.selected('By File (Hot Spots)') : colors.header('By File (Hot Spots)')), width);\n \n if (filesExpanded && sortedFiles.length > 0) {\n const maxFileCount = sortedFiles[0]?.[1].length || 1;\n sortedFiles.forEach(([file, fileIssues], idx) => {\n const isLast = idx === sortedFiles.length - 1;\n const connector = isLast ? tree.bottomLeft : tree.leftT;\n const fileId = `file-${file}`;\n const fileNodeSelected = selected === fileId;\n const prefix = fileNodeSelected ? colors.selected('→') : ' ';\n const filename = file.split('/').pop() || file;\n const count = fileIssues.length;\n const fileBar = severityBar(count, maxFileCount);\n const hasCritical = fileIssues.some(i => i.severity === 'critical');\n const barColor = hasCritical ? colors.critical(fileBar) : colors.moderate(fileBar);\n this.renderLine(` ${prefix} ${connector}${tree.horizontal} ${fileNodeSelected ? colors.selected(filename) : filename} (${count}) ${barColor}`, width);\n });\n }\n \n // === AGENTS SECTION ===\n const agentsExpanded = expanded.has('agents');\n const agentsIcon = agentsExpanded ? '▼' : '▶';\n const agentsSelected = selected === 'agents';\n const agentsPrefix = agentsSelected ? colors.selected('→') : ' ';\n this.renderLine(` ${agentsPrefix} ${agentsIcon} ` + (agentsSelected ? colors.selected('By Agent') : colors.header('By Agent')), width);\n \n if (agentsExpanded && sortedAgents.length > 0) {\n sortedAgents.forEach(([agent, agentIssues], idx) => {\n const isLast = idx === sortedAgents.length - 1;\n const connector = isLast ? tree.bottomLeft : tree.leftT;\n const agentId = `agent-${agent}`;\n const agentSelected = selected === agentId;\n const prefix = agentSelected ? colors.selected('→') : ' ';\n this.renderLine(` ${prefix} ${connector}${tree.horizontal} ${agentSelected ? colors.selected(agent) : agent} (${agentIssues.length})`, width);\n });\n }\n \n // === CROSS-PROJECT PATTERNS SECTION ===\n const patternsExpanded = expanded.has('patterns');\n const patternsIcon = patternsExpanded ? '▼' : '▶';\n const patternsSelected = selected === 'patterns';\n const patternsPrefix = patternsSelected ? colors.selected('→') : ' ';\n const patternCount = patterns.length;\n this.renderLine(` ${patternsPrefix} ${patternsIcon} ` + (patternsSelected ? colors.selected(`Cross-Project Patterns (${patternCount} recurring)`) : colors.header(`Cross-Project Patterns (${patternCount} recurring)`)), width);\n \n if (patternsExpanded && patterns.length > 0) {\n patterns.slice(0, 5).forEach((pattern, idx) => {\n const isLast = idx === Math.min(4, patterns.length - 1);\n const connector = isLast ? tree.bottomLeft : tree.leftT;\n const patternId = `pattern-${pattern.id}`;\n const patternNodeSelected = selected === patternId;\n const prefix = patternNodeSelected ? colors.selected('→') : ' ';\n const desc = pattern.pattern.slice(0, 40) + (pattern.pattern.length > 40 ? '...' : '');\n const projectsText = `seen in ${pattern.projects.length} projects`;\n this.renderLine(` ${prefix} ${connector}${tree.horizontal} ${patternNodeSelected ? colors.selected(`\"${desc}\"`) : colors.dim(`\"${desc}\"`)} - ${colors.dim(projectsText)}`, width);\n });\n if (patterns.length > 5) {\n this.renderLine(` ${colors.dim(`... ${patterns.length - 5} more patterns`)}`, width);\n }\n }\n \n // Summary stats\n this.renderLine('', width);\n this.renderSectionBorder(width);\n const trend = stats?.improvementTrend || 'unknown';\n const trendIcon = trend === 'improving' ? colors.success('↑') : trend === 'declining' ? colors.critical('↓') : colors.dim('→');\n const trendText = trend === 'improving' ? colors.success('Improving') : trend === 'declining' ? colors.critical('Declining') : colors.dim('Stable');\n const resolvedCount = stats?.resolvedCount || 0;\n this.renderLine(` ${colors.dim('Trend:')} ${trendIcon} ${trendText} ${colors.dim('| Resolved:')} ${colors.success(resolvedCount.toString())} ${colors.dim('| Historical:')} ${colors.dim((stats?.historicalIssues || 0).toString())}`, width);\n }\n\n /**\n * Get all visible memory tree nodes for navigation\n */\n private getMemoryTreeNodes(): Array<{ id: string; level: number }> {\n const nodes: Array<{ id: string; level: number }> = [];\n const expanded = this.state.memoryTree.expandedNodes;\n const issues = this.state.memoryTree.issues;\n const patterns = this.state.memoryTree.globalPatterns;\n \n // Severity section\n nodes.push({ id: 'severity', level: 0 });\n if (expanded.has('severity')) {\n nodes.push({ id: 'severity-critical', level: 1 });\n if (expanded.has('severity-critical')) {\n const criticalIssues = issues.filter(i => i.severity === 'critical').slice(0, 5);\n criticalIssues.forEach(issue => {\n nodes.push({ id: `severity-critical-${issue.id}`, level: 2 });\n });\n }\n nodes.push({ id: 'severity-serious', level: 1 });\n nodes.push({ id: 'severity-moderate', level: 1 });\n nodes.push({ id: 'severity-low', level: 1 });\n }\n \n // Files section\n nodes.push({ id: 'files', level: 0 });\n if (expanded.has('files')) {\n const byFile = new Map<string, StoredIssue[]>();\n for (const issue of issues) {\n if (!byFile.has(issue.file)) byFile.set(issue.file, []);\n byFile.get(issue.file)!.push(issue);\n }\n const sortedFiles = Array.from(byFile.keys())\n .sort((a, b) => (byFile.get(b)?.length || 0) - (byFile.get(a)?.length || 0))\n .slice(0, 10);\n sortedFiles.forEach(file => {\n nodes.push({ id: `file-${file}`, level: 1 });\n });\n }\n \n // Agents section\n nodes.push({ id: 'agents', level: 0 });\n if (expanded.has('agents')) {\n const byAgent = new Map<string, StoredIssue[]>();\n for (const issue of issues) {\n if (!byAgent.has(issue.agent)) byAgent.set(issue.agent, []);\n byAgent.get(issue.agent)!.push(issue);\n }\n const sortedAgents = Array.from(byAgent.keys())\n .sort((a, b) => (byAgent.get(b)?.length || 0) - (byAgent.get(a)?.length || 0));\n sortedAgents.forEach(agent => {\n nodes.push({ id: `agent-${agent}`, level: 1 });\n });\n }\n \n // Patterns section\n nodes.push({ id: 'patterns', level: 0 });\n if (expanded.has('patterns')) {\n patterns.slice(0, 5).forEach(pattern => {\n nodes.push({ id: `pattern-${pattern.id}`, level: 1 });\n });\n }\n \n return nodes;\n }\n\n /**\n * Toggle expand/collapse on selected memory tree node\n */\n private toggleMemoryTreeNode(): void {\n const selected = this.state.memoryTree.selectedNode;\n const expanded = this.state.memoryTree.expandedNodes;\n \n // Only toggle on expandable nodes (top-level sections and severity categories)\n const expandableNodes = ['severity', 'files', 'agents', 'patterns', 'severity-critical', 'severity-serious', 'severity-moderate', 'severity-low'];\n \n if (expandableNodes.includes(selected)) {\n if (expanded.has(selected)) {\n expanded.delete(selected);\n } else {\n expanded.add(selected);\n }\n }\n }\n\n /**\n * Refresh skills data from the system\n */\n private async refreshSkillsData(): Promise<void> {\n const now = Date.now();\n // Debounce refreshes\n if (now - this.state.skillsBrowser.lastRefresh < 1000) {\n return;\n }\n this.state.skillsBrowser.lastRefresh = now;\n \n try {\n // Load installed skills with usage stats\n const installed = await listInstalledSkills();\n const contextState = await loadContextState();\n \n this.state.skillsBrowser.installedSkills = installed.map(skill => ({\n ...skill,\n timesApplied: contextState.skills?.[skill.name]?.timesApplied || 0\n }));\n \n // Load global skills\n const globalSkills = await listGlobalSkills();\n this.state.skillsBrowser.globalSkills = globalSkills;\n \n // Detect stack and get suggestions\n const workDir = getWorkingDirectory(undefined, true);\n const stack = await detectStack(workDir);\n \n this.state.skillsBrowser.suggestedSkills = stack.suggestedSkills;\n // Only set defined values to avoid exactOptionalPropertyTypes issues\n const detectedStack: { framework?: string; language?: string; database?: string } = {};\n if (stack.framework) detectedStack.framework = stack.framework;\n if (stack.language) detectedStack.language = stack.language;\n if (stack.database) detectedStack.database = stack.database;\n this.state.skillsBrowser.detectedStack = detectedStack;\n \n // Load categories\n this.state.skillsBrowser.categories = getSkillCategories();\n \n this.render();\n } catch (error) {\n this.addActivity(`Skills refresh error: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Refresh goals data from guardian state\n */\n private async refreshGoalsData(): Promise<void> {\n const now = Date.now();\n const isInitialLoad = this.state.goalsPanel.lastRefresh === 0;\n if (now - this.state.goalsPanel.lastRefresh < 500) {\n return;\n }\n this.state.goalsPanel.lastRefresh = now;\n \n try {\n const workDir = getWorkingDirectory(undefined, true);\n const guardianState = getGuardianState(workDir);\n await guardianState.load();\n \n const goals = guardianState.getAllGoals();\n const activeCount = goals.filter(g => g.status === 'active').length;\n const achievedCount = goals.filter(g => g.status === 'achieved').length;\n \n this.state.goalsPanel.goals = goals.map(g => {\n const base = {\n id: g.id,\n description: g.description,\n type: g.type,\n target: g.target,\n currentValue: g.currentValue,\n status: g.status,\n autoGenerated: g.autoGenerated,\n updatedAt: g.updatedAt\n };\n return g.category ? { ...base, category: g.category } : base;\n });\n \n // Log if goals were loaded on initial startup\n if (goals.length > 0 && isInitialLoad) {\n this.addActivity(`Loaded ${activeCount} active goal${activeCount !== 1 ? 's' : ''}, ${achievedCount} achieved`);\n }\n \n this.render();\n } catch (error) {\n this.addActivity(`Goals refresh error: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Refresh hypotheses data from guardian state\n */\n private async refreshHypothesesData(): Promise<void> {\n const now = Date.now();\n const isInitialLoad = this.state.hypothesesPanel.lastRefresh === 0;\n if (now - this.state.hypothesesPanel.lastRefresh < 500) {\n return;\n }\n this.state.hypothesesPanel.lastRefresh = now;\n \n try {\n const workDir = getWorkingDirectory(undefined, true);\n const guardianState = getGuardianState(workDir);\n await guardianState.load();\n \n const hypotheses = guardianState.getAllHypotheses();\n const testingCount = hypotheses.filter(h => h.status === 'testing' || h.status === 'proposed').length;\n const validatedCount = hypotheses.filter(h => h.status === 'validated').length;\n \n this.state.hypothesesPanel.hypotheses = hypotheses.map(h => {\n const base = {\n id: h.id,\n statement: h.statement,\n confidence: h.confidence,\n status: h.status,\n evidenceCount: h.evidence.length,\n updatedAt: h.updatedAt\n };\n return h.category ? { ...base, category: h.category } : base;\n });\n \n // Log if hypotheses were loaded on initial startup\n if (hypotheses.length > 0 && isInitialLoad) {\n this.addActivity(`Loaded ${testingCount} testing hypothesis${testingCount !== 1 ? 'es' : ''}, ${validatedCount} validated`);\n }\n \n this.render();\n } catch (error) {\n this.addActivity(`Hypotheses refresh error: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Load memory tree data from issue store and global patterns\n */\n private async loadMemoryTreeData(): Promise<void> {\n const now = Date.now();\n // Rate limit refreshes\n if (now - this.state.memoryTree.lastRefresh < 500) {\n return;\n }\n this.state.memoryTree.lastRefresh = now;\n \n try {\n const workDir = getWorkingDirectory(undefined, true);\n \n // Load recent issues, stats, and global patterns in parallel\n const [issues, stats, patterns] = await Promise.all([\n getRecentIssues({ workDir, limit: 200, daysBack: 30 }),\n getMemoryStats(workDir),\n findCrossProjectPatterns(2)\n ]);\n \n this.state.memoryTree.issues = issues;\n this.state.memoryTree.stats = stats;\n this.state.memoryTree.globalPatterns = patterns;\n this.state.memoryTree.loaded = true;\n \n if (!this.state.memoryTree.loaded) {\n this.addActivity(`Memory loaded: ${issues.length} issues, ${patterns.length} patterns`);\n }\n \n this.render();\n } catch (error) {\n this.addActivity(`Memory load error: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Add a new goal from the UI\n * \n * Goals are tracked automatically by the Guardian Agent based on scan results.\n * The goal description is semantically matched to issue types during scans.\n */\n private async addGoalFromUI(description: string): Promise<void> {\n if (!description.trim()) return;\n \n try {\n const workDir = getWorkingDirectory(undefined, true);\n const guardianState = getGuardianState(workDir);\n await guardianState.load();\n \n // Parse goal type from description\n const reductionMatch = description.match(/reduce.*?(\\d+)%/i);\n const streakMatch = description.match(/(\\d+)\\s*days?\\s*(streak|in a row)/i);\n \n // Default is reduction goal (reduce issues to zero)\n let goalType: 'streak' | 'reduction' | 'score' | 'custom' = 'reduction';\n let target = 0; // Target is zero issues by default\n let metric = 'semantic'; // Use semantic matching for natural language goals\n \n if (reductionMatch && reductionMatch[1]) {\n goalType = 'reduction';\n const percent = parseInt(reductionMatch[1], 10);\n // Will be calculated as percentage of startValue\n metric = 'reduction_percent';\n target = percent;\n } else if (streakMatch && streakMatch[1]) {\n goalType = 'streak';\n target = parseInt(streakMatch[1], 10);\n metric = 'days_streak';\n }\n \n // Get baseline count from current scan for semantic goals\n let startValue = 0;\n if (metric === 'semantic') {\n startValue = await this.measureSemanticGoalBaseline(description.trim(), workDir);\n }\n \n const deadline = new Date();\n deadline.setDate(deadline.getDate() + 14);\n \n const goal: Goal = {\n id: `goal-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n description: description.trim(),\n type: goalType,\n metric,\n target,\n currentValue: startValue,\n startValue: startValue,\n status: 'active',\n autoGenerated: false,\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n deadline: deadline.toISOString()\n };\n \n await guardianState.addGoal(goal);\n const progressText = startValue > 0 ? ` (tracking ${startValue} issues)` : '';\n this.addActivity(`Goal added: ${description.slice(0, 40)}...${progressText}`);\n await this.refreshGoalsData();\n } catch (error) {\n this.addActivity(`Failed to add goal: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n \n /**\n * Measure baseline issue count for a semantic goal\n */\n private async measureSemanticGoalBaseline(description: string, workDir: string): Promise<number> {\n try {\n const { searchIssues } = await import('../memory/issue-store.js');\n const issues = await searchIssues('', {\n workDir,\n limit: 1000,\n includeResolved: false,\n });\n \n const desc = description.toLowerCase();\n \n // Dead code / unused code\n if (desc.includes('dead code') || desc.includes('unused') || desc.includes('remove unused')) {\n return issues.filter(r => {\n const msg = r.issue.issue.toLowerCase();\n return msg.includes('unused') || msg.includes('dead code') || \n msg.includes('never used') || msg.includes('unreachable') ||\n msg.includes('no-unused') || msg.includes('defined but never');\n }).length;\n }\n \n // Security\n if (desc.includes('security') || desc.includes('vulnerab')) {\n return issues.filter(r => \n r.issue.agent === 'security' || r.issue.agent === 'privacy' ||\n r.issue.severity === 'critical'\n ).length;\n }\n \n // Type safety\n if (desc.includes('type') || desc.includes('typescript') || desc.includes('any type')) {\n return issues.filter(r => \n r.issue.agent === 'typecheck' ||\n r.issue.issue.toLowerCase().includes('type')\n ).length;\n }\n \n // Tests\n if (desc.includes('test') || desc.includes('coverage')) {\n return issues.filter(r => \n r.issue.agent === 'test' ||\n r.issue.issue.toLowerCase().includes('test')\n ).length;\n }\n \n // Performance\n if (desc.includes('performance') || desc.includes('slow') || desc.includes('optimize')) {\n return issues.filter(r => \n r.issue.agent === 'performance'\n ).length;\n }\n \n // Accessibility\n if (desc.includes('accessibility') || desc.includes('a11y')) {\n return issues.filter(r => \n r.issue.agent === 'accessibility'\n ).length;\n }\n \n // Bugs\n if (desc.includes('bug') || desc.includes('fix') || desc.includes('error')) {\n return issues.filter(r => \n r.issue.agent === 'bug-finding' ||\n r.issue.severity === 'critical' ||\n r.issue.severity === 'serious'\n ).length;\n }\n \n // Default: all issues\n return issues.length;\n } catch {\n return 0;\n }\n }\n\n /**\n * Complete a goal from the UI\n */\n private async completeGoalFromUI(goalId: string): Promise<void> {\n try {\n const workDir = getWorkingDirectory(undefined, true);\n const guardianState = getGuardianState(workDir);\n await guardianState.load();\n \n const goals = guardianState.getAllGoals();\n const goal = goals.find(g => g.id === goalId);\n \n if (goal) {\n await guardianState.updateGoal(goalId, {\n status: 'achieved',\n currentValue: goal.target,\n achievedAt: new Date().toISOString()\n });\n this.addActivity(`Goal achieved: ${goal.description.slice(0, 30)}...`);\n await this.refreshGoalsData();\n }\n } catch (error) {\n this.addActivity(`Failed to complete goal: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Delete a goal from the UI\n */\n private async deleteGoalFromUI(goalId: string): Promise<void> {\n try {\n const workDir = getWorkingDirectory(undefined, true);\n const guardianState = getGuardianState(workDir);\n await guardianState.load();\n \n await guardianState.updateGoal(goalId, { status: 'rejected' });\n this.addActivity('Goal removed');\n await this.refreshGoalsData();\n } catch (error) {\n this.addActivity(`Failed to delete goal: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Add a new hypothesis from the UI\n */\n private async addHypothesisFromUI(statement: string): Promise<void> {\n if (!statement.trim()) return;\n \n try {\n const workDir = getWorkingDirectory(undefined, true);\n const guardianState = getGuardianState(workDir);\n await guardianState.load();\n \n const hypothesis: Hypothesis = {\n id: `hypo-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`,\n statement: statement.trim(),\n confidence: 0.5,\n status: 'testing',\n evidence: [],\n createdAt: new Date().toISOString(),\n updatedAt: new Date().toISOString(),\n testCriteria: 'Collect evidence from scans'\n };\n \n await guardianState.addHypothesis(hypothesis);\n this.addActivity(`Hypothesis added: ${statement.slice(0, 40)}...`);\n await this.refreshHypothesesData();\n } catch (error) {\n this.addActivity(`Failed to add hypothesis: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Validate/invalidate a hypothesis from the UI\n */\n private async updateHypothesisFromUI(hypoId: string, action: 'validate' | 'invalidate' | 'delete'): Promise<void> {\n try {\n const workDir = getWorkingDirectory(undefined, true);\n const guardianState = getGuardianState(workDir);\n await guardianState.load();\n \n if (action === 'validate') {\n await guardianState.updateHypothesis(hypoId, { status: 'validated', confidence: 0.9 });\n this.addActivity('Hypothesis validated');\n } else if (action === 'invalidate') {\n await guardianState.updateHypothesis(hypoId, { status: 'invalidated', confidence: 0.1 });\n this.addActivity('Hypothesis invalidated');\n } else {\n await guardianState.updateHypothesis(hypoId, { status: 'retired' });\n this.addActivity('Hypothesis removed');\n }\n \n await this.refreshHypothesesData();\n } catch (error) {\n this.addActivity(`Failed to update hypothesis: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Reactivate a goal (undo completion)\n */\n private async reactivateGoalFromUI(goalId: string): Promise<void> {\n try {\n const workDir = getWorkingDirectory(undefined, true);\n const guardianState = getGuardianState(workDir);\n await guardianState.load();\n \n const goals = guardianState.getAllGoals();\n const goal = goals.find(g => g.id === goalId);\n \n if (goal) {\n await guardianState.updateGoal(goalId, {\n status: 'active',\n achievedAt: undefined\n });\n this.addActivity(`Goal reactivated: ${goal.description.slice(0, 30)}...`);\n await this.refreshGoalsData();\n }\n } catch (error) {\n this.addActivity(`Failed to reactivate goal: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Reactivate a hypothesis (undo validation/invalidation)\n */\n private async reactivateHypothesisFromUI(hypoId: string): Promise<void> {\n try {\n const workDir = getWorkingDirectory(undefined, true);\n const guardianState = getGuardianState(workDir);\n await guardianState.load();\n \n const hypotheses = guardianState.getAllHypotheses();\n const hypothesis = hypotheses.find(h => h.id === hypoId);\n \n if (hypothesis) {\n await guardianState.updateHypothesis(hypoId, {\n status: 'testing',\n confidence: 0.5,\n validatedAt: undefined\n });\n this.addActivity(`Hypothesis reactivated: ${hypothesis.statement.slice(0, 40)}...`);\n await this.refreshHypothesesData();\n }\n } catch (error) {\n this.addActivity(`Failed to reactivate hypothesis: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n /**\n * Handle skills panel navigation\n */\n private skillsPanelNext(): void {\n const panels: Array<'installed' | 'global' | 'suggested' | 'categories'> = ['installed', 'global', 'suggested', 'categories'];\n const currentIdx = panels.indexOf(this.state.skillsBrowser.activePanel);\n const nextPanel = panels[(currentIdx + 1) % panels.length];\n this.state.skillsBrowser.activePanel = nextPanel ?? 'installed';\n this.state.skillsBrowser.selectedIndex = 0;\n }\n\n /**\n * Get max items in current skills panel\n */\n private getSkillsPanelMaxItems(): number {\n const { skillsBrowser } = this.state;\n switch (skillsBrowser.activePanel) {\n case 'installed':\n return skillsBrowser.installedSkills.length;\n case 'global':\n return skillsBrowser.globalSkills.length;\n case 'suggested':\n return skillsBrowser.suggestedSkills.length;\n case 'categories':\n return skillsBrowser.selectedCategory \n ? skillsBrowser.categorySkills.length \n : skillsBrowser.categories.length;\n default:\n return 0;\n }\n }\n\n /**\n * Handle Enter key in skills view\n */\n private async handleSkillsEnter(): Promise<void> {\n const { skillsBrowser } = this.state;\n \n switch (skillsBrowser.activePanel) {\n case 'installed': {\n // Show info about installed skill (could expand to show details)\n const skill = skillsBrowser.installedSkills[skillsBrowser.selectedIndex];\n if (skill) {\n this.addActivity(`Skill info: ${skill.name} from ${skill.installedFrom}`);\n }\n break;\n }\n \n case 'global': {\n // Show info about global skill - offer to remove\n const skill = skillsBrowser.globalSkills[skillsBrowser.selectedIndex];\n if (skill) {\n await this.showGlobalSkillDialog(skill);\n }\n break;\n }\n \n case 'suggested': {\n // Install suggested skill\n const skillSource = skillsBrowser.suggestedSkills[skillsBrowser.selectedIndex];\n if (skillSource) {\n await this.showSkillInstallDialog(skillSource);\n }\n break;\n }\n \n case 'categories': {\n if (skillsBrowser.selectedCategory) {\n // Install skill from category\n const skillSource = skillsBrowser.categorySkills[skillsBrowser.selectedIndex];\n if (skillSource) {\n await this.showSkillInstallDialog(skillSource);\n }\n } else {\n // Drill into category\n const category = skillsBrowser.categories[skillsBrowser.selectedIndex];\n if (category) {\n skillsBrowser.selectedCategory = category.name;\n skillsBrowser.categorySkills = getSkillsByCategory(category.name);\n skillsBrowser.selectedIndex = 0;\n }\n }\n break;\n }\n }\n }\n\n /**\n * Handle back navigation in skills view\n */\n private handleSkillsBack(): void {\n if (this.state.skillsBrowser.selectedCategory) {\n this.state.skillsBrowser.selectedCategory = null;\n this.state.skillsBrowser.categorySkills = [];\n this.state.skillsBrowser.selectedIndex = 0;\n } else {\n this.goBack();\n }\n }\n\n /**\n * Show skill installation dialog\n */\n private async showSkillInstallDialog(skillSource: string): Promise<void> {\n this.isActive = false;\n process.stdout.write('\\x1b[2J\\x1b[H');\n \n const v = colors.border(box.vertical);\n const w = Math.max(60, Math.min(80, (process.stdout.columns || 80) - 4));\n \n const pLine = (content: string) => {\n const len = visibleLength(content);\n console.log(v + ' ' + content + ' '.repeat(Math.max(0, w - 3 - len)) + v);\n };\n \n // Parse skill source\n const parts = skillSource.split(' ');\n const repo = parts[0] ?? skillSource; // Fallback to full source if no space\n const skillName = parts[1] ?? '';\n \n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(colors.header('INSTALL SKILL'));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine('');\n pLine(colors.dim('Repository: ') + colors.highlight(repo));\n if (skillName) {\n pLine(colors.dim('Skill: ') + colors.highlight(skillName));\n }\n pLine('');\n pLine(colors.dim('This will clone the repository and install the skill'));\n pLine(colors.dim('to .trie/skills/ in your project.'));\n pLine('');\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine('');\n pLine(colors.highlight('Install this skill? ') + colors.dim('(y/n)'));\n pLine('');\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n \n // Wait for user input\n const answer = await new Promise<string>((resolve) => {\n const handler = (_chunk: string, key: { name: string }) => {\n if (key.name === 'y' || key.name === 'n' || key.name === 'escape' || key.name === 'q') {\n input.removeListener('keypress', handler);\n resolve(key.name);\n }\n };\n input.on('keypress', handler);\n });\n \n if (answer !== 'y') {\n this.isActive = true;\n this.render();\n return;\n }\n \n // Show installing state\n process.stdout.write('\\x1b[2J\\x1b[H');\n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(colors.header('INSTALLING SKILL'));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine('');\n pLine(colors.running('Cloning repository...'));\n pLine('');\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n \n this.state.skillsBrowser.installing = true;\n this.state.skillsBrowser.installStatus = 'Cloning repository...';\n \n try {\n const result = await installSkill(repo, skillName || undefined);\n \n if (result.success) {\n this.state.skillsBrowser.installStatus = `Installed: ${result.name}`;\n this.addActivity(`Installed skill: ${result.name}`);\n \n // Show success\n process.stdout.write('\\x1b[2J\\x1b[H');\n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(colors.success('SKILL INSTALLED'));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine('');\n pLine(colors.success('✓ ') + 'Skill: ' + colors.highlight(result.name));\n pLine(colors.dim(' Path: ') + result.path);\n pLine('');\n pLine(colors.dim('The skill will be applied during the next ') + colors.highlight('trie scan'));\n pLine('');\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine(colors.dim('Press any key to continue...'));\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n \n // Refresh skills list\n await this.refreshSkillsData();\n } else {\n this.state.skillsBrowser.installStatus = `Failed: ${result.error}`;\n this.addActivity(`Skill install failed: ${result.error}`);\n \n // Show error\n process.stdout.write('\\x1b[2J\\x1b[H');\n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(colors.critical('INSTALLATION FAILED'));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine('');\n pLine(colors.critical('✗ ') + colors.dim('Error: ') + result.error);\n pLine('');\n pLine(colors.dim('Common issues:'));\n pLine(colors.dim(' • Repository not found'));\n pLine(colors.dim(' • No SKILL.md in repository'));\n pLine(colors.dim(' • Network connectivity'));\n pLine('');\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine(colors.dim('Press any key to continue...'));\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n }\n } catch (error) {\n const errMsg = error instanceof Error ? error.message : String(error);\n this.state.skillsBrowser.installStatus = `Error: ${errMsg}`;\n this.addActivity(`Skill install error: ${errMsg}`);\n }\n \n this.state.skillsBrowser.installing = false;\n \n // Wait for any key to return\n await new Promise<void>((resolve) => {\n const handler = () => {\n input.removeListener('keypress', handler);\n resolve();\n };\n input.once('keypress', handler);\n });\n \n this.isActive = true;\n this.render();\n }\n\n /**\n * Show global skill details dialog with option to remove\n */\n private async showGlobalSkillDialog(skill: { name: string; description: string; path: string; installedFrom: string }): Promise<void> {\n this.isActive = false;\n process.stdout.write('\\x1b[2J\\x1b[H');\n \n const v = colors.border(box.vertical);\n const w = Math.max(60, Math.min(80, (process.stdout.columns || 80) - 4));\n \n const pLine = (content: string) => {\n const len = visibleLength(content);\n console.log(v + ' ' + content + ' '.repeat(Math.max(0, w - 3 - len)) + v);\n };\n \n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(colors.header('GLOBAL SKILL'));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine('');\n pLine(colors.dim('Name: ') + colors.highlight(skill.name));\n pLine(colors.dim('Description: ') + skill.description.slice(0, w - 16));\n pLine(colors.dim('Source: ') + skill.installedFrom.slice(0, w - 16));\n pLine(colors.dim('Path: ') + skill.path.slice(0, w - 16));\n pLine('');\n pLine(colors.dim('Global skills are available across all your projects.'));\n pLine('');\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine('');\n pLine(colors.highlight('Remove this skill? ') + colors.dim('(y/n)'));\n pLine('');\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n \n // Wait for user input\n const answer = await new Promise<string>((resolve) => {\n const handler = (_chunk: string, key: { name: string }) => {\n if (key.name === 'y' || key.name === 'n' || key.name === 'escape' || key.name === 'q') {\n input.removeListener('keypress', handler);\n resolve(key.name);\n }\n };\n input.on('keypress', handler);\n });\n \n if (answer === 'y') {\n const removed = await removeGlobalSkill(skill.name);\n if (removed) {\n this.state.skillsBrowser.installStatus = `Removed: ${skill.name}`;\n this.addActivity(`Removed global skill: ${skill.name}`);\n await this.refreshSkillsData();\n } else {\n this.state.skillsBrowser.installStatus = `Failed to remove: ${skill.name}`;\n }\n }\n \n this.isActive = true;\n this.render();\n }\n\n /**\n * Show dialog to create a custom skill from a file\n */\n private async showCreateCustomSkillDialog(): Promise<void> {\n this.isActive = false;\n process.stdout.write('\\x1b[2J\\x1b[H');\n \n const v = colors.border(box.vertical);\n const w = Math.max(60, Math.min(80, (process.stdout.columns || 80) - 4));\n \n const pLine = (content: string) => {\n const len = visibleLength(content);\n console.log(v + ' ' + content + ' '.repeat(Math.max(0, w - 3 - len)) + v);\n };\n \n // Check if native file picker is available\n const hasNativePicker = await isFilePickerAvailable();\n \n let filePath = '';\n \n if (hasNativePicker) {\n // Use native file picker\n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(colors.header('CREATE CUSTOM SKILL'));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine('');\n pLine(colors.running('Opening file picker...'));\n pLine('');\n pLine(colors.dim('Select a text file (.md, .txt, etc.)'));\n pLine(colors.dim('The file contents become the skill instructions.'));\n pLine('');\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n \n const result = await openFilePicker({\n title: 'Select a file to create a skill from',\n fileTypes: ['md', 'txt', 'json', '*']\n });\n \n if (result.cancelled) {\n this.isActive = true;\n this.render();\n return;\n }\n \n if (!result.success || !result.path) {\n // Fall back to paste method\n process.stdout.write('\\x1b[2J\\x1b[H');\n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(colors.running('FILE PICKER UNAVAILABLE'));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine('');\n pLine(colors.dim(result.error || 'Could not open file picker.'));\n pLine(colors.dim('Falling back to manual entry...'));\n pLine('');\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n await new Promise(resolve => setTimeout(resolve, 1500));\n // Continue to paste method below\n } else {\n filePath = result.path;\n }\n }\n \n // Fallback: paste/drop method\n if (!filePath) {\n process.stdout.write('\\x1b[2J\\x1b[H');\n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(colors.header('CREATE CUSTOM SKILL'));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine('');\n pLine(colors.dim('Convert any text file into a global skill.'));\n pLine(colors.dim('The file contents become the skill instructions.'));\n pLine('');\n pLine(colors.highlight('How to use:'));\n pLine(colors.dim(' 1. Drag a text file onto this terminal'));\n pLine(colors.dim(' 2. The file path will be pasted'));\n pLine(colors.dim(' 3. Press Enter to create the skill'));\n pLine('');\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine('');\n pLine(colors.dim('Paste/drop file path: ') + colors.highlight('_'));\n pLine('');\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n \n // Temporarily disable raw mode for line input\n if (input.isTTY) {\n input.setRawMode(false);\n }\n \n const rl = readline.createInterface({ input, output });\n \n filePath = await new Promise<string>((resolve) => {\n rl.question('', (answer) => {\n rl.close();\n resolve(answer.trim());\n });\n });\n \n // Re-enable raw mode\n if (input.isTTY) {\n input.setRawMode(true);\n }\n \n // Clean up file path (remove quotes that might be added by drag-drop)\n filePath = filePath.replace(/^[\"']|[\"']$/g, '').trim();\n }\n \n if (!filePath) {\n this.isActive = true;\n this.render();\n return;\n }\n \n // Expand ~ to home directory\n if (filePath.startsWith('~')) {\n const { homedir } = await import('os');\n filePath = filePath.replace('~', homedir());\n }\n \n // Check if file exists\n if (!existsSync(filePath)) {\n process.stdout.write('\\x1b[2J\\x1b[H');\n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(colors.critical('FILE NOT FOUND'));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine('');\n pLine(colors.dim('Path: ') + filePath);\n pLine('');\n pLine(colors.dim('Make sure the file exists and try again.'));\n pLine('');\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine(colors.dim('Press any key to continue...'));\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n \n await new Promise<void>((resolve) => {\n input.once('keypress', () => resolve());\n });\n \n this.isActive = true;\n this.render();\n return;\n }\n \n // Show creating status\n process.stdout.write('\\x1b[2J\\x1b[H');\n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(colors.running('CREATING SKILL...'));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine('');\n pLine(colors.dim('Reading file and generating skill...'));\n pLine('');\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n \n // Create the skill\n const result = await createSkillFromFile(filePath);\n \n if (result.success) {\n // Format which tools it was written to\n const toolsWritten = result.writtenTo?.map(t => {\n const names: Record<string, string> = { trie: 'Trie', cursor: 'Cursor', claude: 'Claude Code', opencode: 'OpenCode' };\n return names[t] ?? t;\n }).join(', ') ?? 'Trie';\n \n this.state.skillsBrowser.installStatus = `Created: ${result.name}`;\n this.addActivity(`Created custom skill: ${result.name} (${toolsWritten})`);\n \n process.stdout.write('\\x1b[2J\\x1b[H');\n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(colors.success('SKILL CREATED'));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine('');\n pLine(colors.success('✓ ') + 'Skill: ' + colors.highlight(result.name));\n pLine('');\n pLine(colors.dim('Available in: ') + colors.highlight(toolsWritten));\n pLine('');\n pLine(colors.dim('This skill now works in all supported AI coding tools.'));\n pLine(colors.dim('In Trie: applied during ') + colors.highlight('trie scan'));\n pLine(colors.dim('In Cursor/Claude/OpenCode: available in skill picker'));\n pLine('');\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine(colors.dim('Press any key to continue...'));\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n \n await this.refreshSkillsData();\n } else {\n this.state.skillsBrowser.installStatus = `Failed: ${result.error}`;\n \n process.stdout.write('\\x1b[2J\\x1b[H');\n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(colors.critical('CREATION FAILED'));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine('');\n pLine(colors.critical('✗ ') + colors.dim('Error: ') + (result.error ?? 'Unknown error'));\n pLine('');\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine(colors.dim('Press any key to continue...'));\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n }\n \n await new Promise<void>((resolve) => {\n input.once('keypress', () => resolve());\n });\n \n this.isActive = true;\n this.render();\n }\n\n /**\n * Render footer with controls\n */\n private renderFooter(width: number): void {\n const bottomBorder = colors.border(box.bottomLeft + this.line(width - 2) + box.bottomRight);\n this.bufferLine(bottomBorder);\n \n // Helper to format keyboard hints\n const key = (k: string) => colors.border('[') + colors.highlight(k) + colors.border(']');\n const hint = (k: string, desc: string) => key(k) + colors.dim(` ${desc}`);\n \n // Build available panes hint based on what data is available\n const paneHints: string[] = [];\n \n // Guardian alerts - highlight if there are unread notifications\n const unreadCount = this.state.notificationHistory.filter(n => !n.dismissed).length;\n if (unreadCount > 0) {\n // Show dismiss hint when notifications are pending\n paneHints.push(key('d') + colors.critical(` Dismiss`));\n paneHints.push(key('g') + colors.critical(` Guard(${unreadCount})`));\n } else {\n // Normal hints when no pending notifications\n if (this.state.issues.length > 0) paneHints.push(hint('d', 'Details'));\n paneHints.push(hint('g', 'Guard'));\n }\n \n if (this.state.costReport) {\n paneHints.push(hint('m', 'Cost'));\n paneHints.push(hint('c', 'Config'));\n }\n if (this.state.readiness) paneHints.push(hint('r', 'Ready'));\n if (this.state.semanticAnalysis || this.state.attackSurface) paneHints.push(hint('a', 'Analysis'));\n paneHints.push(hint('t', 'Memory'));\n paneHints.push(hint('v', 'Toolkit'));\n paneHints.push(hint('l', 'Log'));\n const paneStr = paneHints.length > 0 ? ' ' + paneHints.join(' ') : '';\n \n if (!this.state.scanComplete) {\n this.renderLine(' ' + hint('v', 'Toolkit') + ' ' + hint('l', 'Log') + ' ' + hint('q', 'Quit') + ' ' + hint('h', 'Help'), width);\n } else if (this.state.view === 'skills') {\n // Toolkit view - show toolkit-specific hints\n this.renderLine(' ' + hint('Tab', 'Panel') + ' ' + hint('j/k', 'Select') + ' ' + hint('Enter', 'Install') + ' ' + hint('b', 'Back') + ' ' + hint('h', 'Help') + ' ' + hint('q', 'Quit'), width);\n } else if (this.state.view === 'guardian') {\n // Guardian view - show guardian-specific hints\n // Change Enter hint based on whether selected insight is expanded and has a command\n const insights = this.state.guardianInsights;\n const selectedInsight = insights[this.state.selectedGuardianInsight];\n const isExpanded = this.state.expandedGuardianInsight === this.state.selectedGuardianInsight;\n const hasCommand = selectedInsight?.actionCommand;\n \n const enterHint = isExpanded && hasCommand \n ? hint('Enter', 'Run') \n : isExpanded \n ? hint('Enter', 'Collapse')\n : hint('Enter', 'Expand');\n \n const hintLine = ' ' + hint('j/k', 'Nav') + ' ' + enterHint + ' ' + hint('d', 'Dismiss') + ' ' + hint('i', 'Ignore') + ' ' + hint('x', 'Clear dismissed') + ' ' + hint('o', 'Goals') + ' ' + hint('y', 'Hypo') + ' ' + hint('b', 'Back') + ' ' + hint('q', 'Quit');\n this.renderLine(hintLine, width);\n } else if (this.state.view === 'goals') {\n // Goals view - show goals-specific hints\n const inputMode = this.state.goalsPanel.inputMode === 'add';\n const hasAchieved = this.state.goalsPanel.goals.some(g => g.status === 'achieved' || g.status === 'failed');\n if (inputMode) {\n this.renderLine(' ' + hint('Type', 'Goal') + ' ' + hint('Enter', 'Save') + ' ' + hint('Esc', 'Cancel'), width);\n } else if (hasAchieved) {\n this.renderLine(' ' + hint('j/k', 'Nav') + ' ' + hint('a', 'Add') + ' ' + hint('Enter', 'Complete') + ' ' + hint('d', 'Delete') + ' ' + hint('x', 'Remove achieved') + ' ' + hint('u', 'Undo') + ' ' + hint('b', 'Back'), width);\n } else {\n this.renderLine(' ' + hint('j/k', 'Nav') + ' ' + hint('a', 'Add') + ' ' + hint('Enter', 'Complete') + ' ' + hint('d', 'Delete') + ' ' + hint('b', 'Back') + ' ' + hint('h', 'Help') + ' ' + hint('q', 'Quit'), width);\n }\n } else if (this.state.view === 'hypotheses') {\n // Hypotheses view - show hypotheses-specific hints\n const inputMode = this.state.hypothesesPanel.inputMode === 'add';\n const hasCompleted = this.state.hypothesesPanel.hypotheses.some(h => h.status === 'validated' || h.status === 'invalidated');\n if (inputMode) {\n this.renderLine(' ' + hint('Type', 'Hypothesis') + ' ' + hint('Enter', 'Save') + ' ' + hint('Esc', 'Cancel'), width);\n } else if (hasCompleted) {\n this.renderLine(' ' + hint('j/k', 'Nav') + ' ' + hint('a', 'Add') + ' ' + hint('v', 'Validate') + ' ' + hint('x', 'Invalidate') + ' ' + hint('r', 'Remove') + ' ' + hint('u', 'Undo') + ' ' + hint('d', 'Delete'), width);\n } else {\n this.renderLine(' ' + hint('j/k', 'Nav') + ' ' + hint('a', 'Add') + ' ' + hint('v', 'Validate') + ' ' + hint('x', 'Invalidate') + ' ' + hint('d', 'Delete') + ' ' + hint('b', 'Back') + ' ' + hint('q', 'Quit'), width);\n }\n } else if (this.state.view === 'memory') {\n // Memory tree view - show memory-specific hints\n this.renderLine(' ' + hint('j/k', 'Nav') + ' ' + hint('Enter', 'Expand') + ' ' + hint('b', 'Back') + ' ' + hint('h', 'Help') + ' ' + hint('q', 'Quit'), width);\n } else if (this.state.view === 'details' || this.state.view === 'costs' || this.state.view === 'readiness' || this.state.view === 'analysis' || this.state.view === 'rawlog') {\n // Secondary views - show back hint\n this.renderLine(' ' + hint('b', 'Back') + ' ' + hint('n/p', 'Pages') + ' ' + hint('Tab', 'Main') + ' ' + hint('h', 'Help') + ' ' + hint('q', 'Quit'), width);\n } else if (this.state.view === 'agents') {\n this.renderLine(' ' + hint('j/k', 'Select') + ' ' + hint('Enter', 'View') + ' ' + hint('n/p', 'Pages') + ' ' + hint('Tab', 'Views') + paneStr + ' ' + hint('h', 'Help') + ' ' + hint('q', 'Quit'), width);\n } else if (this.state.view === 'issues') {\n this.renderLine(' ' + hint('j/k', 'Nav') + ' ' + hint('Enter', 'Details') + ' ' + hint('1-4', 'Sev') + ' ' + hint('f', 'Find') + ' ' + hint('Tab', 'Views') + paneStr + ' ' + hint('h', 'Help') + ' ' + hint('q', 'Quit'), width);\n } else {\n this.renderLine(' ' + hint('Tab', 'Views') + ' ' + hint('n/p', 'Pages') + paneStr + ' ' + hint('h', 'Help') + ' ' + hint('q', 'Quit'), width);\n }\n }\n\n // Helper methods\n private switchView(): void {\n // In skills view, Tab switches panels instead of views\n if (this.state.view === 'skills') {\n this.skillsPanelNext();\n return;\n }\n \n if (!this.state.scanComplete) return;\n // Main views that cycle with Tab\n const mainViews: DashboardView[] = ['overview', 'issues', 'agents', 'files', 'memory'];\n const currentIndex = mainViews.indexOf(this.state.view);\n if (currentIndex >= 0) {\n const nextIndex = (currentIndex + 1) % mainViews.length;\n const nextView = mainViews[nextIndex] ?? 'overview';\n this.state.view = nextView;\n // Load memory data when switching to memory view\n if (nextView === 'memory') {\n this.loadMemoryTreeData();\n }\n } else {\n // If in a secondary view, go back to overview\n this.state.view = 'overview';\n }\n }\n \n /**\n * Navigate to a specific view\n */\n private goToView(view: DashboardView): void {\n if (!this.state.scanComplete && view !== 'rawlog') return;\n this.state.previousView = this.state.view;\n this.state.view = view;\n }\n\n private navigateUp(): void {\n if (this.state.view === 'issues') {\n this.state.selectedIssue = Math.max(0, this.state.selectedIssue - 1);\n } else if (this.state.view === 'agents') {\n this.state.selectedAgent = Math.max(0, this.state.selectedAgent - 1);\n // Adjust page if needed\n const pageSize = 6;\n const page = Math.floor(this.state.selectedAgent / pageSize);\n if (page !== this.state.agentPage) {\n this.state.agentPage = page;\n }\n } else if (this.state.view === 'skills') {\n const maxItems = this.getSkillsPanelMaxItems();\n if (maxItems > 0) {\n this.state.skillsBrowser.selectedIndex = Math.max(0, this.state.skillsBrowser.selectedIndex - 1);\n }\n } else if (this.state.view === 'guardian') {\n // Navigate up in Guardian insights\n const visibleInsights = this.getVisibleGuardianInsights();\n if (visibleInsights.length === 0) {\n this.state.selectedGuardianInsight = 0;\n this.state.scrollPositions.guardian = 0;\n return;\n }\n this.state.selectedGuardianInsight = Math.max(0, this.state.selectedGuardianInsight - 1);\n // Adjust scroll to keep selection visible\n if (this.state.selectedGuardianInsight < this.state.scrollPositions.guardian) {\n this.state.scrollPositions.guardian = this.state.selectedGuardianInsight;\n }\n } else if (this.state.view === 'memory') {\n // Navigate up in memory tree\n const nodes = this.getMemoryTreeNodes();\n const currentIdx = nodes.findIndex(n => n.id === this.state.memoryTree.selectedNode);\n if (currentIdx > 0) {\n this.state.memoryTree.selectedNode = nodes[currentIdx - 1]?.id || nodes[0]?.id || 'severity';\n }\n }\n }\n\n private navigateDown(): void {\n if (this.state.view === 'issues') {\n const filteredIssues = this.getFilteredIssues();\n if (filteredIssues.length > 0) {\n this.state.selectedIssue = Math.min(filteredIssues.length - 1, this.state.selectedIssue + 1);\n }\n } else if (this.state.view === 'agents') {\n const agents = this.getSortedAgents();\n this.state.selectedAgent = Math.min(agents.length - 1, this.state.selectedAgent + 1);\n // Adjust page if needed\n const pageSize = 6;\n const page = Math.floor(this.state.selectedAgent / pageSize);\n if (page !== this.state.agentPage) {\n this.state.agentPage = page;\n }\n } else if (this.state.view === 'skills') {\n const maxItems = this.getSkillsPanelMaxItems();\n if (maxItems > 0) {\n this.state.skillsBrowser.selectedIndex = Math.min(maxItems - 1, this.state.skillsBrowser.selectedIndex + 1);\n }\n } else if (this.state.view === 'guardian') {\n // Navigate down in Guardian insights\n const visibleInsights = this.getVisibleGuardianInsights();\n if (visibleInsights.length === 0) {\n this.state.selectedGuardianInsight = 0;\n this.state.scrollPositions.guardian = 0;\n return;\n }\n const maxIdx = Math.max(0, visibleInsights.length - 1);\n this.state.selectedGuardianInsight = Math.min(maxIdx, this.state.selectedGuardianInsight + 1);\n // Adjust scroll to keep selection visible (approximate 4 lines per insight)\n const visibleItems = Math.floor(20 / 4);\n if (this.state.selectedGuardianInsight >= this.state.scrollPositions.guardian + visibleItems) {\n this.state.scrollPositions.guardian = this.state.selectedGuardianInsight - visibleItems + 1;\n }\n } else if (this.state.view === 'memory') {\n // Navigate down in memory tree\n const nodes = this.getMemoryTreeNodes();\n const currentIdx = nodes.findIndex(n => n.id === this.state.memoryTree.selectedNode);\n if (currentIdx < nodes.length - 1) {\n this.state.memoryTree.selectedNode = nodes[currentIdx + 1]?.id || 'severity';\n }\n }\n }\n\n private getSortedAgents(): Array<{ name: string; status: string; issues: number; duration: string }> {\n const agentEntries: Array<{ name: string; status: 'queued' | 'running' | 'done'; issues: number; duration: string }> = [];\n \n for (const [name, data] of Object.entries(this.state.agents)) {\n const duration = data.durationMs ? `${(data.durationMs / 1000).toFixed(1)}s` : '—';\n agentEntries.push({ name, status: data.status, issues: data.issues, duration });\n }\n \n // Add agents from progress that might not be in state.agents yet\n for (const name of this.state.progress.activeAgents) {\n if (!this.state.agents[name]) {\n agentEntries.push({ name, status: 'running', issues: 0, duration: '—' });\n }\n }\n for (const name of this.state.progress.completedAgents) {\n if (!this.state.agents[name]) {\n agentEntries.push({ name, status: 'done', issues: this.getAgentIssueCount(name), duration: '—' });\n }\n }\n \n const order: Record<string, number> = { running: 0, queued: 1, done: 2 };\n return agentEntries.sort((a, b) => (order[a.status] ?? 2) - (order[b.status] ?? 2) || a.name.localeCompare(b.name));\n }\n\n private nextPage(): void {\n if (this.state.view === 'agents') {\n const total = Math.max(1, Math.ceil(Object.keys(this.state.agents).length / 6));\n this.state.agentPage = Math.min(total - 1, this.state.agentPage + 1);\n } else {\n const total = Math.max(1, Math.ceil(this.state.activityLog.length / 6));\n this.state.activityPage = Math.min(total - 1, this.state.activityPage + 1);\n }\n }\n\n private prevPage(): void {\n if (this.state.view === 'agents') {\n this.state.agentPage = Math.max(0, this.state.agentPage - 1);\n } else {\n this.state.activityPage = Math.max(0, this.state.activityPage - 1);\n }\n }\n\n private async selectCurrent(): Promise<void> {\n if (this.state.view === 'issues') {\n const filteredIssues = this.getFilteredIssues();\n const selected = filteredIssues[this.state.selectedIssue];\n if (selected) {\n this.showIssueDetails(selected);\n }\n } else if (this.state.view === 'agents') {\n // Drill into selected agent's issues\n const agents = this.getSortedAgents();\n const selected = agents[this.state.selectedAgent];\n if (selected) {\n this.state.previousView = 'agents';\n this.state.filter.agent = selected.name;\n this.state.selectedIssue = 0;\n \n // Check if we have issues for this agent in current session\n const currentSessionIssues = this.state.issues.filter(i => i.agent === selected.name);\n \n // If no issues in current session but agent shows issues, load from memory\n if (currentSessionIssues.length === 0 && selected.issues > 0) {\n try {\n const workDir = getWorkingDirectory(undefined, true);\n // Search for all issues from this agent (empty query = all issues)\n const memoryResults = await searchIssues('', {\n workDir,\n agent: selected.name,\n limit: 1000, // Load up to 1000 issues\n includeResolved: false\n });\n \n // Convert StoredIssue to Issue format and merge with current issues\n const convertedIssues: Issue[] = memoryResults.map(result => {\n const issue: Issue = {\n id: result.issue.id,\n severity: result.issue.severity as 'critical' | 'serious' | 'moderate' | 'low',\n issue: result.issue.issue,\n fix: result.issue.fix,\n file: result.issue.file,\n agent: result.issue.agent,\n confidence: 0.8, // Default confidence for memory-loaded issues\n autoFixable: false // Default to not auto-fixable for memory-loaded issues\n };\n if (result.issue.line !== undefined) {\n issue.line = result.issue.line;\n }\n if (result.issue.category !== undefined) {\n issue.category = result.issue.category;\n }\n return issue;\n });\n \n // Merge with existing issues (avoid duplicates by ID)\n const existingIds = new Set(this.state.issues.map((i: Issue) => i.id));\n const newIssues = convertedIssues.filter((i: Issue) => !existingIds.has(i.id));\n this.state.issues = [...this.state.issues, ...newIssues];\n } catch (error) {\n // Silently fail - memory might not be available\n }\n }\n \n this.state.view = 'issues';\n }\n } else if (this.state.view === 'skills') {\n // Handle enter in skills view\n this.handleSkillsEnter();\n } else if (this.state.view === 'guardian') {\n // If insight is already expanded, run the command if available\n const insights = this.getVisibleGuardianInsights();\n if (insights.length === 0) {\n return;\n }\n // Clamp selection in case list shrank\n if (this.state.selectedGuardianInsight >= insights.length) {\n this.state.selectedGuardianInsight = insights.length - 1;\n }\n if (this.state.expandedGuardianInsight === this.state.selectedGuardianInsight) {\n const insight = insights[this.state.selectedGuardianInsight];\n \n if (insight?.actionCommand) {\n // Run the suggested command\n await this.runInsightCommand(insight.actionCommand);\n } else {\n // No command available - collapse\n this.state.expandedGuardianInsight = null;\n }\n } else {\n // Expand the selected insight\n this.state.expandedGuardianInsight = this.state.selectedGuardianInsight;\n }\n } else if (this.state.view === 'memory') {\n // Toggle expand/collapse on selected node\n this.toggleMemoryTreeNode();\n }\n }\n \n /**\n * Run a command from a Guardian insight\n * Pauses the TUI, runs the command, then resumes\n */\n private async runInsightCommand(command: string): Promise<void> {\n const { spawn } = await import('child_process');\n \n // Pause the dashboard\n this.isActive = false;\n \n // Restore terminal to normal mode\n process.stdout.write('\\x1b[?25h'); // Show cursor\n process.stdout.write('\\x1b[2J\\x1b[H'); // Clear screen\n \n console.log(colors.header(`\\n Running: ${command}\\n`));\n console.log(colors.dim(' ─'.repeat(40)));\n console.log('');\n \n // Run the command\n const child = spawn(command, [], {\n shell: true,\n stdio: 'inherit',\n cwd: process.cwd(),\n });\n \n await new Promise<void>((resolve) => {\n child.on('close', (code) => {\n console.log('');\n console.log(colors.dim(' ─'.repeat(40)));\n if (code === 0) {\n console.log(colors.success(` ✓ Command completed successfully`));\n } else {\n console.log(colors.serious(` ✗ Command exited with code ${code}`));\n }\n console.log('');\n console.log(colors.dim(' Press any key to return to dashboard...'));\n resolve();\n });\n \n child.on('error', (err) => {\n console.log('');\n console.log(colors.critical(` ✗ Failed to run command: ${err.message}`));\n console.log('');\n console.log(colors.dim(' Press any key to return to dashboard...'));\n resolve();\n });\n });\n \n // Wait for a keypress before resuming\n await new Promise<void>((resolve) => {\n const onKeypress = () => {\n process.stdin.removeListener('keypress', onKeypress);\n resolve();\n };\n process.stdin.once('keypress', onKeypress);\n });\n \n // Resume the dashboard\n this.isActive = true;\n process.stdout.write('\\x1b[?25l'); // Hide cursor again\n this.render();\n }\n\n private goBack(): void {\n // Skills view has special back handling\n if (this.state.view === 'skills') {\n this.handleSkillsBack();\n return;\n }\n \n if (this.state.previousView) {\n // Clear the agent filter if we came from agents view\n if (this.state.previousView === 'agents' && this.state.filter.agent !== 'all') {\n this.state.filter.agent = 'all';\n }\n this.state.view = this.state.previousView;\n this.state.previousView = null;\n }\n }\n\n private setFilter(type: string, value: string): void {\n (this.state.filter as any)[type] = value;\n this.state.selectedIssue = 0; // Reset selection\n }\n\n private clearFilters(): void {\n this.state.filter = {\n severity: 'all',\n agent: 'all',\n search: ''\n };\n this.state.selectedIssue = 0;\n }\n\n private getFilteredIssues(): Issue[] {\n return this.state.issues.filter(issue => {\n if (this.state.filter.severity !== 'all' && issue.severity !== this.state.filter.severity) {\n return false;\n }\n if (this.state.filter.agent !== 'all' && issue.agent !== this.state.filter.agent) {\n return false;\n }\n if (this.state.filter.search && !issue.issue.toLowerCase().includes(this.state.filter.search.toLowerCase())) {\n return false;\n }\n return true;\n });\n }\n\n private getFilterDescription(): string {\n const parts = [];\n if (this.state.filter.severity !== 'all') parts.push(`Severity: ${this.state.filter.severity}`);\n if (this.state.filter.agent !== 'all') parts.push(`Scout: ${this.state.filter.agent}`);\n if (this.state.filter.search) parts.push(`Search: \"${this.state.filter.search}\"`);\n return parts.length > 0 ? parts.join(', ') : 'All issues';\n }\n\n /**\n * Strip markdown formatting for clean terminal display.\n * Removes **bold**, *italic*, `code`, and markdown headers.\n */\n private stripMarkdown(text: string): string {\n return text\n // Remove markdown bold **text** or __text__\n .replace(/\\*\\*(.+?)\\*\\*/g, '$1')\n .replace(/__(.+?)__/g, '$1')\n // Remove markdown italic *text* or _text_ (but not underscores in words)\n .replace(/(?<!\\w)\\*(.+?)\\*(?!\\w)/g, '$1')\n .replace(/(?<!\\w)_(.+?)_(?!\\w)/g, '$1')\n // Remove inline code `text`\n .replace(/`(.+?)`/g, '$1')\n // Remove markdown headers (# ## ### etc.)\n .replace(/^#{1,6}\\s*/gm, '')\n // Normalize multiple spaces\n .replace(/\\s{2,}/g, ' ')\n .trim();\n }\n\n private wrapText(text: string, width: number): string[] {\n // Clean markdown formatting and handle newlines\n const cleaned = this.stripMarkdown(text);\n const paragraphs = cleaned.split(/\\n+/);\n const lines: string[] = [];\n\n for (const paragraph of paragraphs) {\n const words = paragraph.split(' ').filter(w => w.length > 0);\n let currentLine = '';\n let currentWidth = 0;\n\n for (const word of words) {\n const wordWidth = visibleLength(word);\n const spaceWidth = currentLine ? 1 : 0;\n\n if (currentWidth + spaceWidth + wordWidth <= width) {\n currentLine += (currentLine ? ' ' : '') + word;\n currentWidth += spaceWidth + wordWidth;\n } else {\n if (currentLine) lines.push(currentLine);\n // Handle words longer than width\n if (wordWidth > width) {\n // Truncate long words\n lines.push(word.slice(0, width - 3) + '...');\n currentLine = '';\n currentWidth = 0;\n } else {\n currentLine = word;\n currentWidth = wordWidth;\n }\n }\n }\n\n if (currentLine) lines.push(currentLine);\n }\n\n return lines.length > 0 ? lines : [''];\n }\n\n private async promptFilter(): Promise<void> {\n // Pause the update loop while prompting\n if (this.updateInterval) {\n clearInterval(this.updateInterval);\n this.updateInterval = undefined;\n }\n \n if (input.isTTY) {\n input.setRawMode(false);\n }\n \n const v = colors.border(box.vertical);\n // Responsive width\n const w = Math.max(50, Math.min(70, (process.stdout.columns || 80) - 4));\n \n // Helper for padded lines\n const pLine = (content: string) => {\n const len = visibleLength(content);\n console.log(v + content + ' '.repeat(Math.max(0, w - 2 - len)) + v);\n };\n \n // Clear screen and show prompt\n process.stdout.write('\\x1b[2J\\x1b[H\\x1b[?25h'); // Clear, home, show cursor\n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(' ' + colors.header('FILTER ISSUES'));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine(' ' + colors.dim('Current filters:'));\n pLine(' ' + colors.dim('Severity:') + ' ' + colors.highlight(this.state.filter.severity));\n pLine(' ' + colors.dim('Scout:') + ' ' + colors.highlight(this.state.filter.agent));\n pLine(' ' + colors.dim('Search:') + ' ' + colors.highlight(this.state.filter.search || '(none)'));\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n console.log('');\n \n this.rl.question(colors.border('▸ ') + 'Enter search term (empty to clear): ', (answer) => {\n this.state.filter.search = answer.trim();\n this.state.selectedIssue = 0;\n \n if (input.isTTY) {\n input.setRawMode(true);\n }\n \n // Restart the update loop\n this.startUpdateLoop();\n this.render();\n });\n }\n\n private async promptAgentFilter(): Promise<void> {\n // Pause the update loop while prompting\n if (this.updateInterval) {\n clearInterval(this.updateInterval);\n this.updateInterval = undefined;\n }\n \n if (input.isTTY) {\n input.setRawMode(false);\n }\n \n // Get list of agents\n const agents = [...new Set([\n ...this.state.progress.completedAgents,\n ...this.state.progress.activeAgents,\n ...Object.keys(this.state.agents)\n ])].sort();\n \n const v = colors.border(box.vertical);\n // Responsive width\n const w = Math.max(50, Math.min(70, (process.stdout.columns || 80) - 4));\n \n // Helper for padded lines\n const pLine = (content: string) => {\n const len = visibleLength(content);\n console.log(v + content + ' '.repeat(Math.max(0, w - 2 - len)) + v);\n };\n \n // Clear screen and show prompt\n process.stdout.write('\\x1b[2J\\x1b[H\\x1b[?25h'); // Clear, home, show cursor\n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(' ' + colors.header('FILTER BY SCOUT'));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine(' ' + colors.dim('Current scout filter:') + ' ' + colors.highlight(this.state.filter.agent));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine(' ' + colors.dim('Available scouts:'));\n // Show more scouts on wider terminals\n const maxScouts = w > 60 ? 12 : 8;\n for (const agent of agents.slice(0, maxScouts)) {\n pLine(' ' + colors.success('•') + ' ' + agent);\n }\n if (agents.length > maxScouts) {\n pLine(' ' + colors.dim(`... and ${agents.length - maxScouts} more`));\n }\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n console.log('');\n \n this.rl.question(colors.border('▸ ') + 'Enter scout name (empty for all): ', (answer) => {\n const trimmed = answer.trim();\n if (trimmed === '' || trimmed.toLowerCase() === 'all') {\n this.state.filter.agent = 'all';\n } else {\n // Fuzzy match agent name\n const match = agents.find(a => a.toLowerCase().includes(trimmed.toLowerCase()));\n this.state.filter.agent = match || trimmed;\n }\n this.state.selectedIssue = 0;\n \n if (input.isTTY) {\n input.setRawMode(true);\n }\n \n // Restart the update loop\n this.startUpdateLoop();\n this.render();\n });\n }\n\n private showHelp(): void {\n this.isActive = false;\n process.stdout.write('\\x1b[2J\\x1b[H');\n const v = colors.border(box.vertical);\n // Responsive width - wider for comprehensive help\n const w = Math.max(70, Math.min(90, (process.stdout.columns || 80) - 4));\n \n // Helper for padded lines\n const pLine = (content: string) => {\n const len = visibleLength(content);\n console.log(v + content + ' '.repeat(Math.max(0, w - 2 - len)) + v);\n };\n \n // Helper for key-description line\n const keyLine = (key: string, desc: string) => {\n pLine(' ' + colors.highlight(key.padEnd(12)) + ' ' + colors.dim(desc));\n };\n \n // Helper for section header\n const section = (title: string) => {\n pLine('');\n pLine(' ' + colors.header(title));\n };\n \n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(' ' + colors.brand('TRIE AGENT') + ' ' + colors.dim('-') + ' ' + colors.header('KEYBOARD SHORTCUTS'));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n \n // === NAVIGATION ===\n section('Navigation');\n keyLine('Tab', 'Cycle main views (overview → issues → scouts → files)');\n keyLine('↑ / k', 'Navigate up in lists');\n keyLine('↓ / j', 'Navigate down in lists');\n keyLine('n', 'Next page');\n keyLine('p', 'Previous page');\n keyLine('Enter', 'Select item / drill into scout / view issue details');\n keyLine('b', 'Go back to previous view');\n \n // === VIEWS ===\n section('Quick Views');\n keyLine('d', 'Issue Details - view selected issue with code snippet');\n keyLine('m', 'Money/Costs - Moneybags cost analysis view');\n keyLine('r', 'Readiness - Production readiness score');\n keyLine('a', 'Analysis - Semantic analysis + Attack surface');\n keyLine('g', 'Guardian - Alert history from all agents');\n keyLine('v', 'Toolkit - Scouts (built-in) + Skills (installable)');\n keyLine('l', 'Log - Raw log/activity viewer');\n pLine(' ' + colors.dim('In Toolkit view: press [c] to create from file'));\n pLine('');\n pLine(' ' + colors.header('Guardian Agency'));\n keyLine('o', 'Goals panel - Add, complete, delete goals');\n keyLine('y', 'Hypotheses panel - Add, validate, invalidate hypotheses');\n pLine(' ' + colors.dim('In Goals panel:'));\n pLine(' ' + colors.dim(' [a] add [Enter] complete [d] delete [x] remove achieved [u] undo'));\n pLine(' ' + colors.dim('In Hypotheses panel:'));\n pLine(' ' + colors.dim(' [a] add [v] validate [x] invalidate [r] remove [u] undo'));\n \n // === FILTERING ===\n section('Filtering');\n keyLine('1', 'Filter: Critical severity only');\n keyLine('2', 'Filter: Serious severity only');\n keyLine('3', 'Filter: Moderate severity only');\n keyLine('4', 'Filter: Low severity only');\n keyLine('0', 'Filter: Show all severities');\n keyLine('f', 'Filter: Search issues by text');\n keyLine('s', 'Filter: Search by scout name');\n keyLine('x', 'Clear all filters');\n \n // === CONFIGURATION ===\n section('Configuration');\n keyLine('c', 'Open Guardian Agent config menu (escalation, costs, etc.)');\n pLine(' ' + colors.dim('├─ Moneybags: users, dev rate, industry, revenue'));\n pLine(' ' + colors.dim('├─ Agent Smith: AI enhancement, severity, patterns'));\n pLine(' ' + colors.dim('├─ Performance: concurrency, timeout'));\n pLine(' ' + colors.dim('├─ Risk thresholds: critical, high, medium'));\n pLine(' ' + colors.dim('└─ Auto-escalation: Slack/webhook/email setup'));\n \n // === OTHER ===\n section('Other');\n keyLine('h', 'Show this help screen');\n keyLine('q / Esc', 'Quit the dashboard');\n \n // === CLI COMMANDS ===\n section('CLI Commands');\n pLine(' ' + colors.highlight('trie help') + ' ' + colors.dim('Show all available commands'));\n pLine(' ' + colors.highlight('trie scan') + ' ' + colors.dim('Scan once and exit'));\n pLine(' ' + colors.highlight('trie watch') + ' ' + colors.dim('Watch mode (this dashboard)'));\n pLine(' ' + colors.highlight('trie init') + ' ' + colors.dim('Initialize Trie in a project'));\n pLine(' ' + colors.highlight('trie check') + ' ' + colors.dim('Pre-push risk check'));\n \n // === CI/CD SETUP ===\n section('CI/CD Integration');\n pLine(' ' + colors.dim('Add memory caching to your GitHub Actions for cross-run learning:'));\n pLine('');\n pLine(' ' + colors.highlight('- uses: actions/cache@v4'));\n pLine(' ' + colors.dim('with:'));\n pLine(' ' + colors.dim('path: .trie/memory'));\n pLine(' ' + colors.dim('key: trie-memory-${{ github.repository }}'));\n pLine('');\n pLine(' ' + colors.dim('See: ') + colors.highlight('.github/workflows/examples.md'));\n \n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine(' ' + colors.dim('Tip: Run ') + colors.highlight('trie help') + colors.dim(' for all commands'));\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n console.log(' ' + colors.dim('Press any key to return...'));\n\n const resume = () => {\n this.isActive = true;\n this.render();\n };\n input.once('keypress', resume);\n }\n\n /**\n * Show Guardian Agent configuration dialog\n */\n private async showGuardianConfig(): Promise<void> {\n this.isActive = false;\n process.stdout.write('\\x1b[2J\\x1b[H');\n const v = colors.border(box.vertical);\n const w = Math.max(60, Math.min(80, (process.stdout.columns || 80) - 4));\n \n const pLine = (content: string) => {\n const len = visibleLength(content);\n console.log(v + content + ' '.repeat(Math.max(0, w - 2 - len)) + v);\n };\n \n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(' ' + colors.header('GUARDIAN AGENT CONFIGURATION'));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine('');\n pLine(' ' + colors.header('💰 Moneybags'));\n pLine(' ' + colors.dim(` Users: ${this.state.guardianConfig.moneybags.userCount.toLocaleString()}`));\n pLine(' ' + colors.dim(` Dev Rate: $${this.state.guardianConfig.moneybags.developerRate}/hr`));\n if (this.state.guardianConfig.moneybags.industry) {\n pLine(' ' + colors.dim(` Industry: ${this.state.guardianConfig.moneybags.industry}`));\n }\n pLine('');\n pLine(' ' + colors.header('Agent Smith'));\n const smithCfg = this.state.guardianConfig.agentSmith;\n pLine(' ' + colors.dim(` AI Enhancement: ${smithCfg.aiEnhancement ? 'On' : 'Off'}`));\n pLine(' ' + colors.dim(` Min Severity: ${smithCfg.minSeverity}`));\n const enabledCount = Object.values(smithCfg.enabledCategories).filter(v => v).length;\n pLine(' ' + colors.dim(` Categories: ${enabledCount}/6 enabled`));\n pLine('');\n pLine(' ' + colors.header('Performance'));\n pLine(' ' + colors.dim(` Parallel: ${this.state.guardianConfig.performance.parallel ? 'Yes' : 'No'}`));\n pLine(' ' + colors.dim(` Cache: ${this.state.guardianConfig.performance.cache ? 'Yes' : 'No'}`));\n pLine(' ' + colors.dim(` Max Concurrency: ${this.state.guardianConfig.performance.maxConcurrency}`));\n pLine(' ' + colors.dim(` Timeout: ${this.state.guardianConfig.performance.timeoutMs / 1000}s`));\n pLine('');\n pLine(' ' + colors.header('Risk Thresholds'));\n pLine(' ' + colors.dim(` Critical: ${this.state.guardianConfig.riskThresholds.critical}`));\n pLine(' ' + colors.dim(` High: ${this.state.guardianConfig.riskThresholds.high}`));\n pLine(' ' + colors.dim(` Medium: ${this.state.guardianConfig.riskThresholds.medium}`));\n pLine('');\n pLine(' ' + colors.header('Auto-Escalation'));\n const escCfg = this.state.guardianConfig.escalation;\n pLine(' ' + colors.dim(` Enabled: ${escCfg.enabled ? 'Yes' : 'No'}`));\n pLine(' ' + colors.dim(` Targets: ${escCfg.targets.length} configured`));\n if (escCfg.targets.length > 0) {\n const enabledTargets = escCfg.targets.filter(t => t.enabled);\n pLine(' ' + colors.dim(` Active: ${enabledTargets.length} (${enabledTargets.map(t => t.type).join(', ')})`));\n }\n pLine('');\n pLine(' ' + colors.dim('Press a key to configure:'));\n pLine(' ' + colors.highlight(' 1') + ' - Moneybags settings');\n pLine(' ' + colors.highlight(' 2') + ' - Agent Smith settings');\n pLine(' ' + colors.highlight(' 3') + ' - Performance settings');\n pLine(' ' + colors.highlight(' 4') + ' - Risk thresholds');\n pLine(' ' + colors.highlight(' 5') + ' - Auto-escalation settings');\n pLine(' ' + colors.highlight(' Esc') + ' - Cancel');\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n \n return new Promise((resolve) => {\n const handler = (_ch: string, key: readline.Key) => {\n if (key.name === 'escape') {\n input.removeListener('keypress', handler);\n this.isActive = true;\n this.render();\n resolve();\n return;\n }\n \n if (key.name === '1' || _ch === '1') {\n input.removeListener('keypress', handler);\n this.showMoneybagsConfig().then(() => {\n this.isActive = true;\n this.render();\n resolve();\n });\n return;\n }\n \n if (key.name === '2' || _ch === '2') {\n input.removeListener('keypress', handler);\n this.showAgentSmithConfig().then(() => {\n this.isActive = true;\n this.render();\n resolve();\n });\n return;\n }\n \n if (key.name === '3' || _ch === '3') {\n input.removeListener('keypress', handler);\n this.showPerformanceConfig().then(() => {\n this.isActive = true;\n this.render();\n resolve();\n });\n return;\n }\n \n if (key.name === '4' || _ch === '4') {\n input.removeListener('keypress', handler);\n this.showRiskThresholdsConfig().then(() => {\n this.isActive = true;\n this.render();\n resolve();\n });\n return;\n }\n \n if (key.name === '5' || _ch === '5') {\n input.removeListener('keypress', handler);\n this.showEscalationConfig().then(() => {\n this.isActive = true;\n this.render();\n resolve();\n });\n return;\n }\n };\n \n input.on('keypress', handler);\n });\n }\n\n /**\n * Show Moneybags configuration submenu\n */\n private async showMoneybagsConfig(): Promise<void> {\n return new Promise((resolve) => {\n process.stdout.write('\\x1b[2J\\x1b[H');\n const v = colors.border(box.vertical);\n const w = Math.max(60, Math.min(80, (process.stdout.columns || 80) - 4));\n const pLine = (content: string) => {\n const len = visibleLength(content);\n console.log(v + content + ' '.repeat(Math.max(0, w - 2 - len)) + v);\n };\n \n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(' ' + colors.header('💰 MONEYBAGS CONFIGURATION'));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine('');\n pLine(' ' + colors.dim('Current Settings:'));\n pLine(' ' + colors.highlight(` Users: ${this.state.guardianConfig.moneybags.userCount.toLocaleString()}`));\n const payingUsers = this.state.guardianConfig.moneybags.payingUsers;\n const revenuePerUser = this.state.guardianConfig.moneybags.revenuePerUser;\n if (payingUsers > 0) {\n pLine(' ' + colors.highlight(` Paying Users: ${payingUsers.toLocaleString()}`));\n } else {\n pLine(' ' + colors.dim(' Paying Users: (not set)'));\n }\n if (revenuePerUser > 0) {\n pLine(' ' + colors.highlight(` Revenue/User: $${revenuePerUser}/mo`));\n const mrr = (payingUsers > 0 ? payingUsers : this.state.guardianConfig.moneybags.userCount) * revenuePerUser;\n pLine(' ' + colors.success(` Est. MRR: $${mrr.toLocaleString()}/mo`));\n } else {\n pLine(' ' + colors.dim(' Revenue/User: (not set)'));\n }\n pLine(' ' + colors.highlight(` Developer Rate: $${this.state.guardianConfig.moneybags.developerRate}/hr`));\n if (this.state.guardianConfig.moneybags.industry) {\n pLine(' ' + colors.highlight(` Industry: ${this.state.guardianConfig.moneybags.industry}`));\n } else {\n pLine(' ' + colors.dim(' Industry: (not set)'));\n }\n pLine('');\n pLine(' ' + colors.dim('Press a key to configure:'));\n pLine(' ' + colors.highlight(' 1') + ' - Set user count');\n pLine(' ' + colors.highlight(' 2') + ' - Set paying users');\n pLine(' ' + colors.highlight(' 3') + ' - Set revenue per user');\n pLine(' ' + colors.highlight(' 4') + ' - Set developer rate');\n pLine(' ' + colors.highlight(' 5') + ' - Set industry');\n pLine(' ' + colors.highlight(' Esc') + ' - Back');\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n \n const handler = (_ch: string, key: readline.Key) => {\n if (key.name === 'escape') {\n input.removeListener('keypress', handler);\n resolve();\n return;\n }\n \n if (key.name === '1' || _ch === '1') {\n input.removeListener('keypress', handler);\n this.promptUserCount().then(resolve);\n return;\n }\n \n if (key.name === '2' || _ch === '2') {\n input.removeListener('keypress', handler);\n this.promptPayingUsers().then(resolve);\n return;\n }\n \n if (key.name === '3' || _ch === '3') {\n input.removeListener('keypress', handler);\n this.promptRevenuePerUser().then(resolve);\n return;\n }\n \n if (key.name === '4' || _ch === '4') {\n input.removeListener('keypress', handler);\n this.promptDeveloperRate().then(resolve);\n return;\n }\n \n if (key.name === '5' || _ch === '5') {\n input.removeListener('keypress', handler);\n this.promptIndustry().then(resolve);\n return;\n }\n };\n \n input.on('keypress', handler);\n });\n }\n\n /**\n * Show Agent Smith configuration submenu\n */\n private async showAgentSmithConfig(): Promise<void> {\n return new Promise((resolve) => {\n process.stdout.write('\\x1b[2J\\x1b[H');\n const v = colors.border(box.vertical);\n const w = Math.max(60, Math.min(80, (process.stdout.columns || 80) - 4));\n const pLine = (content: string) => {\n const len = visibleLength(content);\n console.log(v + content + ' '.repeat(Math.max(0, w - 2 - len)) + v);\n };\n \n const cfg = this.state.guardianConfig.agentSmith;\n \n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(' ' + colors.header('AGENT SMITH CONFIGURATION'));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine('');\n pLine(' ' + colors.dim('Current Settings:'));\n pLine(' ' + colors.highlight(` AI Enhancement: ${cfg.aiEnhancement ? 'On' : 'Off'}`));\n pLine(' ' + colors.highlight(` Min Severity: ${cfg.minSeverity}`));\n pLine(' ' + colors.highlight(` Memory Retention: ${cfg.memoryRetentionDays} days`));\n pLine('');\n pLine(' ' + colors.dim('Pattern Categories:'));\n pLine(' ' + (cfg.enabledCategories.security ? colors.success('✓') : colors.dim('○')) + ' Security (secrets, injection, XSS)');\n pLine(' ' + (cfg.enabledCategories.codeSmells ? colors.success('✓') : colors.dim('○')) + ' Code Smells (console.log, any, ts-ignore)');\n pLine(' ' + (cfg.enabledCategories.asyncBugs ? colors.success('✓') : colors.dim('○')) + ' Async Bugs (await mistakes, promises)');\n pLine(' ' + (cfg.enabledCategories.reactPatterns ? colors.success('✓') : colors.dim('○')) + ' React Patterns (useEffect, useState)');\n pLine(' ' + (cfg.enabledCategories.uxPatterns ? colors.success('✓') : colors.dim('○')) + ' UX Patterns (loading, error states)');\n pLine(' ' + (cfg.enabledCategories.backendPatterns ? colors.success('✓') : colors.dim('○')) + ' Backend (validation, N+1)');\n pLine('');\n pLine(' ' + colors.dim('Press a key to configure:'));\n pLine(' ' + colors.highlight(' 1') + ' - Toggle AI Enhancement');\n pLine(' ' + colors.highlight(' 2') + ' - Set Min Severity');\n pLine(' ' + colors.highlight(' 3') + ' - Toggle Pattern Categories');\n pLine(' ' + colors.highlight(' 4') + ' - Set Memory Retention');\n pLine(' ' + colors.highlight(' Esc') + ' - Back');\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n \n const handler = (_ch: string, key: readline.Key) => {\n if (key.name === 'escape') {\n input.removeListener('keypress', handler);\n resolve();\n return;\n }\n \n if (key.name === '1' || _ch === '1') {\n input.removeListener('keypress', handler);\n this.state.guardianConfig.agentSmith.aiEnhancement = !this.state.guardianConfig.agentSmith.aiEnhancement;\n const status = this.state.guardianConfig.agentSmith.aiEnhancement ? 'enabled' : 'disabled';\n this.addActivity(`Agent Smith: AI Enhancement ${status}`);\n this.showAgentSmithConfig().then(resolve);\n return;\n }\n \n if (key.name === '2' || _ch === '2') {\n input.removeListener('keypress', handler);\n this.promptSmithMinSeverity().then(resolve);\n return;\n }\n \n if (key.name === '3' || _ch === '3') {\n input.removeListener('keypress', handler);\n this.promptSmithCategories().then(resolve);\n return;\n }\n \n if (key.name === '4' || _ch === '4') {\n input.removeListener('keypress', handler);\n this.promptSmithMemoryRetention().then(resolve);\n return;\n }\n };\n \n input.on('keypress', handler);\n });\n }\n\n /**\n * Prompt for Agent Smith min severity\n */\n private async promptSmithMinSeverity(): Promise<void> {\n return new Promise((resolve) => {\n process.stdout.write('\\x1b[2J\\x1b[H');\n console.log(colors.header('Set Minimum Severity'));\n console.log(colors.dim(`Current: ${this.state.guardianConfig.agentSmith.minSeverity}`));\n console.log('');\n console.log(colors.dim('Only report issues at or above this level:'));\n console.log(' 1 - low (show all)');\n console.log(' 2 - moderate');\n console.log(' 3 - serious');\n console.log(' 4 - critical');\n \n // Disable raw mode to allow readline to work\n if (input.isTTY) {\n input.setRawMode(false);\n }\n \n this.rl.question('> ', (answer) => {\n // Restore raw mode\n if (input.isTTY) {\n input.setRawMode(true);\n }\n \n const severities: Array<'low' | 'moderate' | 'serious' | 'critical'> = ['low', 'moderate', 'serious', 'critical'];\n const idx = parseInt(answer.trim(), 10) - 1;\n if (idx >= 0 && idx < severities.length) {\n this.state.guardianConfig.agentSmith.minSeverity = severities[idx]!;\n this.addActivity(`Agent Smith: Min severity set to ${severities[idx]}`);\n }\n this.showAgentSmithConfig().then(resolve);\n });\n });\n }\n\n /**\n * Prompt for Agent Smith pattern categories\n */\n private async promptSmithCategories(): Promise<void> {\n return new Promise((resolve) => {\n process.stdout.write('\\x1b[2J\\x1b[H');\n const cfg = this.state.guardianConfig.agentSmith.enabledCategories;\n \n console.log(colors.header('Toggle Pattern Categories'));\n console.log(colors.dim('Press number to toggle, Enter when done:'));\n console.log('');\n console.log(' 1 - ' + (cfg.security ? colors.success('[ON]') : colors.dim('[OFF]')) + ' Security');\n console.log(' 2 - ' + (cfg.codeSmells ? colors.success('[ON]') : colors.dim('[OFF]')) + ' Code Smells');\n console.log(' 3 - ' + (cfg.asyncBugs ? colors.success('[ON]') : colors.dim('[OFF]')) + ' Async Bugs');\n console.log(' 4 - ' + (cfg.reactPatterns ? colors.success('[ON]') : colors.dim('[OFF]')) + ' React Patterns');\n console.log(' 5 - ' + (cfg.uxPatterns ? colors.success('[ON]') : colors.dim('[OFF]')) + ' UX Patterns');\n console.log(' 6 - ' + (cfg.backendPatterns ? colors.success('[ON]') : colors.dim('[OFF]')) + ' Backend Patterns');\n console.log('');\n console.log(' a - Enable All');\n console.log(' n - Disable All');\n console.log(' Enter - Done');\n \n const handler = (_ch: string, key: readline.Key) => {\n if (key.name === 'return' || key.name === 'escape') {\n input.removeListener('keypress', handler);\n const enabledCount = Object.values(this.state.guardianConfig.agentSmith.enabledCategories).filter(v => v).length;\n this.addActivity(`Agent Smith: ${enabledCount}/6 categories enabled`);\n void this.persistGuardianConfig();\n this.showAgentSmithConfig().then(resolve);\n return;\n }\n \n const cats = this.state.guardianConfig.agentSmith.enabledCategories;\n if (key.name === '1' || _ch === '1') cats.security = !cats.security;\n if (key.name === '2' || _ch === '2') cats.codeSmells = !cats.codeSmells;\n if (key.name === '3' || _ch === '3') cats.asyncBugs = !cats.asyncBugs;\n if (key.name === '4' || _ch === '4') cats.reactPatterns = !cats.reactPatterns;\n if (key.name === '5' || _ch === '5') cats.uxPatterns = !cats.uxPatterns;\n if (key.name === '6' || _ch === '6') cats.backendPatterns = !cats.backendPatterns;\n if (key.name === 'a' || _ch === 'a') {\n cats.security = cats.codeSmells = cats.asyncBugs = cats.reactPatterns = cats.uxPatterns = cats.backendPatterns = true;\n }\n if (key.name === 'n' || _ch === 'n') {\n cats.security = cats.codeSmells = cats.asyncBugs = cats.reactPatterns = cats.uxPatterns = cats.backendPatterns = false;\n }\n \n // Refresh the display\n input.removeListener('keypress', handler);\n this.promptSmithCategories().then(resolve);\n };\n \n input.on('keypress', handler);\n });\n }\n\n /**\n * Prompt for Agent Smith memory retention days\n */\n private async promptSmithMemoryRetention(): Promise<void> {\n return new Promise((resolve) => {\n process.stdout.write('\\x1b[2J\\x1b[H');\n console.log(colors.header('Set Memory Retention'));\n console.log(colors.dim(`Current: ${this.state.guardianConfig.agentSmith.memoryRetentionDays} days`));\n console.log('');\n console.log(colors.dim('How long should Agent Smith remember dismissed issues?'));\n console.log(colors.dim('Enter number of days (1-365, or press Enter to cancel):'));\n \n // Disable raw mode to allow readline to work\n if (input.isTTY) {\n input.setRawMode(false);\n }\n \n this.rl.question('> ', (answer) => {\n // Restore raw mode\n if (input.isTTY) {\n input.setRawMode(true);\n }\n \n const trimmed = answer.trim();\n if (trimmed) {\n const days = parseInt(trimmed, 10);\n if (!isNaN(days) && days >= 1 && days <= 365) {\n this.state.guardianConfig.agentSmith.memoryRetentionDays = days;\n this.addActivity(`Agent Smith: Memory retention set to ${days} days`);\n }\n }\n this.showAgentSmithConfig().then(resolve);\n });\n });\n }\n\n /**\n * Show Performance configuration submenu\n */\n private async showPerformanceConfig(): Promise<void> {\n return new Promise((resolve) => {\n process.stdout.write('\\x1b[2J\\x1b[H');\n const v = colors.border(box.vertical);\n const w = Math.max(60, Math.min(80, (process.stdout.columns || 80) - 4));\n const pLine = (content: string) => {\n const len = visibleLength(content);\n console.log(v + content + ' '.repeat(Math.max(0, w - 2 - len)) + v);\n };\n \n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(' ' + colors.header('PERFORMANCE CONFIGURATION'));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine('');\n pLine(' ' + colors.dim('Current Settings:'));\n pLine(' ' + colors.highlight(` Parallel: ${this.state.guardianConfig.performance.parallel ? 'Yes' : 'No'}`));\n pLine(' ' + colors.highlight(` Cache: ${this.state.guardianConfig.performance.cache ? 'Yes' : 'No'}`));\n pLine(' ' + colors.highlight(` Max Concurrency: ${this.state.guardianConfig.performance.maxConcurrency}`));\n pLine(' ' + colors.highlight(` Timeout: ${this.state.guardianConfig.performance.timeoutMs / 1000}s`));\n pLine(' ' + colors.highlight(` Workers: ${this.state.guardianConfig.performance.workers ? 'Yes' : 'No'}`));\n pLine(' ' + colors.highlight(` Streaming: ${this.state.guardianConfig.performance.streaming ? 'Yes' : 'No'}`));\n pLine('');\n pLine(' ' + colors.dim('Press a key to toggle/configure:'));\n pLine(' ' + colors.highlight(' 1') + ' - Toggle parallel execution');\n pLine(' ' + colors.highlight(' 2') + ' - Toggle caching');\n pLine(' ' + colors.highlight(' 3') + ' - Set max concurrency');\n pLine(' ' + colors.highlight(' 4') + ' - Set timeout (seconds)');\n pLine(' ' + colors.highlight(' 5') + ' - Toggle worker threads');\n pLine(' ' + colors.highlight(' 6') + ' - Toggle streaming');\n pLine(' ' + colors.highlight(' Esc') + ' - Back');\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n \n const handler = (_ch: string, key: readline.Key) => {\n if (key.name === 'escape') {\n input.removeListener('keypress', handler);\n resolve();\n return;\n }\n \n if (key.name === '1' || _ch === '1') {\n this.state.guardianConfig.performance.parallel = !this.state.guardianConfig.performance.parallel;\n this.addActivity(`Performance: Parallel execution ${this.state.guardianConfig.performance.parallel ? 'enabled' : 'disabled'}`);\n void this.persistGuardianConfig();\n input.removeListener('keypress', handler);\n resolve();\n return;\n }\n \n if (key.name === '2' || _ch === '2') {\n this.state.guardianConfig.performance.cache = !this.state.guardianConfig.performance.cache;\n this.addActivity(`Performance: Caching ${this.state.guardianConfig.performance.cache ? 'enabled' : 'disabled'}`);\n void this.persistGuardianConfig();\n input.removeListener('keypress', handler);\n resolve();\n return;\n }\n \n if (key.name === '3' || _ch === '3') {\n input.removeListener('keypress', handler);\n this.promptMaxConcurrency().then(resolve);\n return;\n }\n \n if (key.name === '4' || _ch === '4') {\n input.removeListener('keypress', handler);\n this.promptTimeout().then(resolve);\n return;\n }\n \n if (key.name === '5' || _ch === '5') {\n this.state.guardianConfig.performance.workers = !this.state.guardianConfig.performance.workers;\n this.addActivity(`Performance: Worker threads ${this.state.guardianConfig.performance.workers ? 'enabled' : 'disabled'}`);\n void this.persistGuardianConfig();\n input.removeListener('keypress', handler);\n resolve();\n return;\n }\n \n if (key.name === '6' || _ch === '6') {\n this.state.guardianConfig.performance.streaming = !this.state.guardianConfig.performance.streaming;\n this.addActivity(`Performance: Streaming ${this.state.guardianConfig.performance.streaming ? 'enabled' : 'disabled'}`);\n void this.persistGuardianConfig();\n input.removeListener('keypress', handler);\n resolve();\n return;\n }\n };\n \n input.on('keypress', handler);\n });\n }\n\n /**\n * Show Risk Thresholds configuration submenu\n */\n private async showRiskThresholdsConfig(): Promise<void> {\n return new Promise((resolve) => {\n process.stdout.write('\\x1b[2J\\x1b[H');\n const v = colors.border(box.vertical);\n const w = Math.max(60, Math.min(80, (process.stdout.columns || 80) - 4));\n const pLine = (content: string) => {\n const len = visibleLength(content);\n console.log(v + content + ' '.repeat(Math.max(0, w - 2 - len)) + v);\n };\n \n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(' ' + colors.header('RISK THRESHOLDS CONFIGURATION'));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine('');\n pLine(' ' + colors.dim('Current Thresholds:'));\n pLine(' ' + colors.highlight(` Critical: ${this.state.guardianConfig.riskThresholds.critical}`));\n pLine(' ' + colors.highlight(` High: ${this.state.guardianConfig.riskThresholds.high}`));\n pLine(' ' + colors.highlight(` Medium: ${this.state.guardianConfig.riskThresholds.medium}`));\n pLine('');\n pLine(' ' + colors.dim('Press a key to configure:'));\n pLine(' ' + colors.highlight(' 1') + ' - Set critical threshold');\n pLine(' ' + colors.highlight(' 2') + ' - Set high threshold');\n pLine(' ' + colors.highlight(' 3') + ' - Set medium threshold');\n pLine(' ' + colors.highlight(' Esc') + ' - Back');\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n \n const handler = (_ch: string, key: readline.Key) => {\n if (key.name === 'escape') {\n input.removeListener('keypress', handler);\n resolve();\n return;\n }\n \n if (key.name === '1' || _ch === '1') {\n input.removeListener('keypress', handler);\n this.promptRiskThreshold('critical').then(resolve);\n return;\n }\n \n if (key.name === '2' || _ch === '2') {\n input.removeListener('keypress', handler);\n this.promptRiskThreshold('high').then(resolve);\n return;\n }\n \n if (key.name === '3' || _ch === '3') {\n input.removeListener('keypress', handler);\n this.promptRiskThreshold('medium').then(resolve);\n return;\n }\n };\n \n input.on('keypress', handler);\n });\n }\n\n /**\n * Prompt for user count\n */\n private async promptUserCount(): Promise<void> {\n return new Promise((resolve) => {\n process.stdout.write('\\x1b[2J\\x1b[H\\x1b[?25h'); // Clear, home, show cursor\n console.log(colors.header('💰 Set User Count'));\n console.log(colors.dim(`Current: ${this.state.guardianConfig.moneybags.userCount.toLocaleString()} users`));\n console.log('');\n console.log(colors.dim('Enter number of users/customers (or press Enter to cancel):'));\n \n // Disable raw mode to allow readline to work\n if (input.isTTY) {\n input.setRawMode(false);\n }\n \n this.rl.question('> ', (answer) => {\n // Restore raw mode\n if (input.isTTY) {\n input.setRawMode(true);\n }\n \n const trimmed = answer.trim();\n let changed = false;\n if (trimmed) {\n const count = parseInt(trimmed.replace(/,/g, ''), 10);\n if (!isNaN(count) && count >= 0) {\n this.state.guardianConfig.moneybags.userCount = count;\n this.addActivity(`Moneybags: User count set to ${count.toLocaleString()}`);\n changed = true;\n }\n }\n if (changed) {\n this.triggerMoneybagsRecalc();\n }\n resolve();\n });\n });\n }\n\n /**\n * Prompt for paying users\n */\n private async promptPayingUsers(): Promise<void> {\n return new Promise((resolve) => {\n process.stdout.write('\\x1b[2J\\x1b[H\\x1b[?25h'); // Clear, home, show cursor\n console.log(colors.header('💰 Set Paying Users'));\n const current = this.state.guardianConfig.moneybags.payingUsers;\n console.log(colors.dim(`Current: ${current > 0 ? current.toLocaleString() : '(not set)'}`));\n console.log('');\n console.log(colors.dim('Enter number of paying customers (0 to clear, Enter to cancel):'));\n \n // Disable raw mode to allow readline to work\n if (input.isTTY) {\n input.setRawMode(false);\n }\n \n this.rl.question('> ', (answer) => {\n // Restore raw mode\n if (input.isTTY) {\n input.setRawMode(true);\n }\n \n const trimmed = answer.trim();\n let changed = false;\n if (trimmed) {\n const count = parseInt(trimmed.replace(/,/g, ''), 10);\n if (!isNaN(count) && count >= 0) {\n this.state.guardianConfig.moneybags.payingUsers = count;\n if (count > 0) {\n this.addActivity(`Moneybags: Paying users set to ${count.toLocaleString()}`);\n } else {\n this.addActivity('Moneybags: Paying users cleared');\n }\n changed = true;\n }\n }\n if (changed) {\n this.triggerMoneybagsRecalc();\n }\n resolve();\n });\n });\n }\n\n /**\n * Prompt for revenue per user\n */\n private async promptRevenuePerUser(): Promise<void> {\n return new Promise((resolve) => {\n process.stdout.write('\\x1b[2J\\x1b[H\\x1b[?25h'); // Clear, home, show cursor\n console.log(colors.header('💰 Set Revenue Per User'));\n const current = this.state.guardianConfig.moneybags.revenuePerUser;\n console.log(colors.dim(`Current: ${current > 0 ? `$${current}/mo` : '(not set)'}`));\n console.log('');\n console.log(colors.dim('Enter average monthly revenue per user in USD (0 to clear, Enter to cancel):'));\n \n // Disable raw mode to allow readline to work\n if (input.isTTY) {\n input.setRawMode(false);\n }\n \n this.rl.question('> ', (answer) => {\n // Restore raw mode\n if (input.isTTY) {\n input.setRawMode(true);\n }\n \n const trimmed = answer.trim();\n let changed = false;\n if (trimmed) {\n const amount = parseFloat(trimmed.replace(/[$,\\s]/g, ''));\n if (!isNaN(amount) && amount >= 0) {\n this.state.guardianConfig.moneybags.revenuePerUser = Math.round(amount * 100) / 100;\n if (amount > 0) {\n this.addActivity(`Moneybags: Revenue per user set to $${amount}/mo`);\n } else {\n this.addActivity('Moneybags: Revenue per user cleared');\n }\n changed = true;\n }\n }\n if (changed) {\n this.triggerMoneybagsRecalc();\n }\n resolve();\n });\n });\n }\n\n /**\n * Prompt for developer rate\n */\n private async promptDeveloperRate(): Promise<void> {\n return new Promise((resolve) => {\n process.stdout.write('\\x1b[2J\\x1b[H\\x1b[?25h'); // Clear, home, show cursor\n console.log(colors.header('💰 Set Developer Rate'));\n console.log(colors.dim(`Current: $${this.state.guardianConfig.moneybags.developerRate}/hr`));\n console.log('');\n console.log(colors.dim('Enter hourly rate in USD (or press Enter to cancel):'));\n \n // Disable raw mode to allow readline to work\n if (input.isTTY) {\n input.setRawMode(false);\n }\n \n this.rl.question('> ', (answer) => {\n // Restore raw mode\n if (input.isTTY) {\n input.setRawMode(true);\n }\n \n const trimmed = answer.trim();\n let changed = false;\n if (trimmed) {\n const rate = parseFloat(trimmed.replace(/[$,\\s]/g, ''));\n if (!isNaN(rate) && rate > 0) {\n this.state.guardianConfig.moneybags.developerRate = Math.round(rate);\n this.addActivity(`Moneybags: Developer rate set to $${this.state.guardianConfig.moneybags.developerRate}/hr`);\n changed = true;\n }\n }\n if (changed) {\n this.triggerMoneybagsRecalc();\n }\n resolve();\n });\n });\n }\n\n /**\n * Show Escalation configuration submenu\n */\n private async showEscalationConfig(): Promise<void> {\n return new Promise((resolve) => {\n process.stdout.write('\\x1b[2J\\x1b[H');\n const v = colors.border(box.vertical);\n const w = Math.max(60, Math.min(80, (process.stdout.columns || 80) - 4));\n const pLine = (content: string) => {\n const len = visibleLength(content);\n console.log(v + content + ' '.repeat(Math.max(0, w - 2 - len)) + v);\n };\n \n const escCfg = this.state.guardianConfig.escalation;\n \n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(' ' + colors.header('AUTO-ESCALATION CONFIGURATION'));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine('');\n pLine(' ' + colors.header('Current Settings:'));\n pLine(' ' + colors.dim(` Status: ${escCfg.enabled ? colors.success('✓ Enabled') : colors.critical('✗ Disabled')}`));\n pLine(' ' + colors.dim(` Targets: ${escCfg.targets.length} configured`));\n if (escCfg.targets.length > 0) {\n const enabledTargets = escCfg.targets.filter(t => t.enabled);\n pLine(' ' + colors.dim(` Active: ${enabledTargets.length}`));\n for (const target of escCfg.targets) {\n const status = target.enabled ? colors.success('●') : colors.critical('○');\n const type = target.type.toUpperCase();\n pLine(' ' + colors.dim(` ${status} ${type}: ${target.config.channel || target.config.email || 'configured'}`));\n }\n } else {\n pLine(' ' + colors.dim(` [!] No targets configured`));\n }\n pLine(' ' + colors.dim(` Cooldown: ${escCfg.cooldownMinutes} minutes`));\n pLine(' ' + colors.dim(` Max/hour: ${escCfg.maxEscalationsPerHour}`));\n pLine(' ' + colors.dim(` Quiet hours: ${escCfg.respectQuietHours ? 'Respect (9pm-8am)' : 'Ignore'}`));\n pLine(' ' + colors.dim(` Critical bypass: ${escCfg.criticalBypassQuietHours ? 'Yes' : 'No'}`));\n pLine('');\n pLine(' ' + colors.header('Setup Instructions:'));\n pLine(' ' + colors.dim(' 1. Create/edit ' + colors.highlight('.trie/config.json') + ' in project root'));\n pLine(' ' + colors.dim(' 2. Add escalation configuration (see README)'));\n pLine(' ' + colors.dim(' 3. Get Slack webhook: ' + colors.highlight('https://api.slack.com/apps')));\n pLine(' ' + colors.dim(' 4. Restart watch mode to apply changes'));\n pLine('');\n pLine(' ' + colors.dim('Example config.json:'));\n pLine(' ' + colors.dim(' {'));\n pLine(' ' + colors.dim(' \"escalation\": {'));\n pLine(' ' + colors.dim(' \"enabled\": true,'));\n pLine(' ' + colors.dim(' \"targets\": [{'));\n pLine(' ' + colors.dim(' \"type\": \"slack\",'));\n pLine(' ' + colors.dim(' \"enabled\": true,'));\n pLine(' ' + colors.dim(' \"config\": {'));\n pLine(' ' + colors.dim(' \"webhookUrl\": \"https://hooks.slack.com/...\",'));\n pLine(' ' + colors.dim(' \"channel\": \"#security-alerts\"'));\n pLine(' ' + colors.dim(' },'));\n pLine(' ' + colors.dim(' \"forSeverities\": [\"critical\"],'));\n pLine(' ' + colors.dim(' \"forCategories\": [\"security\", \"all\"]'));\n pLine(' ' + colors.dim(' }]'));\n pLine(' ' + colors.dim(' }'));\n pLine(' ' + colors.dim(' }'));\n pLine('');\n pLine(' ' + colors.dim('Full docs: README.md → Configuration → Auto-Escalation'));\n pLine('');\n pLine(' ' + colors.highlight(' Esc') + ' - Back');\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n \n const handler = (_ch: string, key: readline.Key) => {\n if (key.name === 'escape') {\n input.removeListener('keypress', handler);\n resolve();\n }\n };\n \n input.on('keypress', handler);\n });\n }\n\n /**\n * Prompt for industry\n */\n private async promptIndustry(): Promise<void> {\n return new Promise((resolve) => {\n process.stdout.write('\\x1b[2J\\x1b[H\\x1b[?25h'); // Clear, home, show cursor\n console.log(colors.header('💰 Set Industry'));\n const current = this.state.guardianConfig.moneybags.industry || '(not set)';\n console.log(colors.dim(`Current: ${current}`));\n console.log('');\n console.log(colors.dim('Select industry (or press Enter to cancel):'));\n console.log(' 1 - solopreneur (1-person team)');\n console.log(' 2 - startup');\n console.log(' 3 - fintech');\n console.log(' 4 - healthcare');\n console.log(' 5 - enterprise');\n console.log(' 6 - saas');\n console.log(' 7 - ecommerce');\n console.log(' 8 - Clear industry');\n \n // Create a fresh readline interface for this prompt to avoid state issues\n const tempRl = readline.createInterface({\n input: input,\n output: process.stdout,\n terminal: false // Disable terminal features to avoid escape sequences\n });\n\n // Disable raw mode completely during input\n if (input.isTTY) {\n input.setRawMode(false);\n }\n\n tempRl.question('> ', (answer) => {\n try {\n tempRl.close();\n\n // Restore raw mode safely\n if (input.isTTY) {\n try {\n input.setRawMode(true);\n } catch (error) {\n console.error('Warning: Failed to restore raw mode:', error);\n }\n }\n\n this.handleIndustryInput(answer, resolve);\n } catch (error) {\n console.error('Error handling industry input:', error);\n // Ensure raw mode is restored even on error\n if (input.isTTY) {\n try {\n input.setRawMode(true);\n } catch {\n // Ignore errors in error handling\n }\n }\n resolve(); // Resolve to prevent hanging\n }\n });\n });\n }\n\n /**\n * Handle industry input after prompt\n */\n private handleIndustryInput(answer: string, resolve: () => void): void {\n try {\n // Sanitize input - remove any control characters or escape sequences\n const sanitized = answer.replace(/[^\\d\\w\\s]/g, '').trim();\n\n const industries: ['solopreneur', 'startup', 'fintech', 'healthcare', 'enterprise', 'saas', 'ecommerce'] =\n ['solopreneur', 'startup', 'fintech', 'healthcare', 'enterprise', 'saas', 'ecommerce'];\n\n let changed = false;\n if (sanitized === '') {\n // User pressed Enter to cancel - no change\n resolve();\n return;\n } else if (sanitized === '8') {\n // Clear industry - delete the property for proper persistence\n delete this.state.guardianConfig.moneybags.industry;\n this.addActivity('Moneybags: Industry cleared');\n changed = true;\n } else if (/^[1-7]$/.test(sanitized)) {\n const idx = parseInt(sanitized, 10) - 1;\n if (idx >= 0 && idx < industries.length) {\n const industry = industries[idx]!;\n this.state.guardianConfig.moneybags.industry = industry;\n this.addActivity(`Moneybags: Industry set to ${industry}`);\n changed = true;\n }\n } else {\n // Invalid input - provide feedback\n console.log('');\n console.log(colors.critical(`Invalid selection: \"${sanitized}\"`));\n console.log(colors.dim('Please enter a number between 1-8, or press Enter to cancel.'));\n // Small delay to show error, then resolve\n setTimeout(() => {\n resolve();\n }, 1500);\n return;\n }\n\n if (changed) {\n // Persist and trigger recalculation\n this.triggerMoneybagsRecalc();\n }\n resolve();\n } catch (error) {\n console.error('Error in handleIndustryInput:', error);\n // Always resolve to prevent hanging\n resolve();\n }\n }\n\n /**\n * Prompt for max concurrency\n */\n private async promptMaxConcurrency(): Promise<void> {\n return new Promise((resolve) => {\n process.stdout.write('\\x1b[2J\\x1b[H\\x1b[?25h'); // Clear, home, show cursor\n console.log(colors.header('Set Max Concurrency'));\n console.log(colors.dim(`Current: ${this.state.guardianConfig.performance.maxConcurrency}`));\n console.log('');\n console.log(colors.dim('Enter max parallel agents (1-20, or press Enter to cancel):'));\n \n // Disable raw mode to allow readline to work\n if (input.isTTY) {\n input.setRawMode(false);\n }\n \n this.rl.question('> ', (answer) => {\n // Restore raw mode\n if (input.isTTY) {\n input.setRawMode(true);\n }\n \n const trimmed = answer.trim();\n if (trimmed) {\n const val = parseInt(trimmed, 10);\n if (!isNaN(val) && val >= 1 && val <= 20) {\n this.state.guardianConfig.performance.maxConcurrency = val;\n this.addActivity(`Performance: Max concurrency set to ${val}`);\n }\n }\n resolve();\n });\n });\n }\n\n /**\n * Prompt for timeout\n */\n private async promptTimeout(): Promise<void> {\n return new Promise((resolve) => {\n process.stdout.write('\\x1b[2J\\x1b[H\\x1b[?25h'); // Clear, home, show cursor\n console.log(colors.header('Set Timeout'));\n console.log(colors.dim(`Current: ${this.state.guardianConfig.performance.timeoutMs / 1000}s`));\n console.log('');\n console.log(colors.dim('Enter timeout in seconds (or press Enter to cancel):'));\n \n // Disable raw mode to allow readline to work\n if (input.isTTY) {\n input.setRawMode(false);\n }\n \n this.rl.question('> ', (answer) => {\n // Restore raw mode\n if (input.isTTY) {\n input.setRawMode(true);\n }\n \n const trimmed = answer.trim();\n if (trimmed) {\n const seconds = parseFloat(trimmed);\n if (!isNaN(seconds) && seconds > 0) {\n this.state.guardianConfig.performance.timeoutMs = Math.round(seconds * 1000);\n this.addActivity(`Performance: Timeout set to ${this.state.guardianConfig.performance.timeoutMs / 1000}s`);\n }\n }\n resolve();\n });\n });\n }\n\n /**\n * Prompt for risk threshold\n */\n private async promptRiskThreshold(level: 'critical' | 'high' | 'medium'): Promise<void> {\n return new Promise((resolve) => {\n process.stdout.write('\\x1b[2J\\x1b[H\\x1b[?25h'); // Clear, home, show cursor\n console.log(colors.header(`Set ${level.toUpperCase()} Risk Threshold`));\n console.log(colors.dim(`Current: ${this.state.guardianConfig.riskThresholds[level]}`));\n console.log('');\n console.log(colors.dim('Enter threshold value (0-100, or press Enter to cancel):'));\n \n // Disable raw mode to allow readline to work\n if (input.isTTY) {\n input.setRawMode(false);\n }\n \n this.rl.question('> ', (answer) => {\n // Restore raw mode\n if (input.isTTY) {\n input.setRawMode(true);\n }\n \n const trimmed = answer.trim();\n if (trimmed) {\n const val = parseInt(trimmed, 10);\n if (!isNaN(val) && val >= 0 && val <= 100) {\n this.state.guardianConfig.riskThresholds[level] = val;\n this.addActivity(`Risk: ${level} threshold set to ${val}`);\n }\n }\n resolve();\n });\n });\n }\n\n /**\n * Get Guardian Agent configuration (for watch mode to use)\n */\n getGuardianConfig(): typeof this.state.guardianConfig {\n return {\n moneybags: { ...this.state.guardianConfig.moneybags },\n agentSmith: { \n ...this.state.guardianConfig.agentSmith,\n enabledCategories: { ...this.state.guardianConfig.agentSmith.enabledCategories }\n },\n performance: { ...this.state.guardianConfig.performance },\n riskThresholds: { ...this.state.guardianConfig.riskThresholds },\n escalation: { \n ...this.state.guardianConfig.escalation,\n targets: [...this.state.guardianConfig.escalation.targets]\n }\n };\n }\n\n /**\n * Get Moneybags configuration (backward compatibility)\n */\n getMoneybagsConfig(): { \n userCount: number; \n payingUsers?: number;\n revenuePerUser?: number;\n developerRate: number; \n industry?: 'solopreneur' | 'startup' | 'fintech' | 'healthcare' | 'enterprise' | 'saas' | 'ecommerce' \n } {\n const config: { \n userCount: number; \n payingUsers?: number;\n revenuePerUser?: number;\n developerRate: number; \n industry?: 'solopreneur' | 'startup' | 'fintech' | 'healthcare' | 'enterprise' | 'saas' | 'ecommerce' \n } = {\n userCount: this.state.guardianConfig.moneybags.userCount,\n developerRate: this.state.guardianConfig.moneybags.developerRate\n };\n if (this.state.guardianConfig.moneybags.payingUsers > 0) {\n config.payingUsers = this.state.guardianConfig.moneybags.payingUsers;\n }\n if (this.state.guardianConfig.moneybags.revenuePerUser > 0) {\n config.revenuePerUser = this.state.guardianConfig.moneybags.revenuePerUser;\n }\n if (this.state.guardianConfig.moneybags.industry) {\n config.industry = this.state.guardianConfig.moneybags.industry;\n }\n return config;\n }\n\n private showIssueDetails(issue: Issue): void {\n this.isActive = false;\n process.stdout.write('\\x1b[2J\\x1b[H');\n const v = colors.border(box.vertical);\n // Responsive width: use most of terminal, min 60, max 100\n const w = Math.max(60, Math.min(100, (process.stdout.columns || 80) - 4));\n const severityColor = issue.severity === 'critical' ? colors.critical \n : issue.severity === 'serious' ? colors.serious \n : issue.severity === 'moderate' ? colors.moderate \n : colors.low;\n \n // Helper for padded lines in this popup\n const pLine = (content: string) => {\n const len = visibleLength(content);\n console.log(v + content + ' '.repeat(Math.max(0, w - 2 - len)) + v);\n };\n \n console.log(colors.border(box.topLeft + this.line(w - 2) + box.topRight));\n pLine(' ' + colors.header('ISSUE DETAILS') + ' ' + severityColor(`[${issue.severity.toUpperCase()}]`));\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n \n // File path - truncate from left if too long, show end\n const maxFileLen = w - 12;\n const filePath = issue.file.length > maxFileLen \n ? '...' + issue.file.slice(-(maxFileLen - 3)) \n : issue.file;\n pLine(' ' + colors.dim('File:') + ' ' + filePath);\n pLine(' ' + colors.dim('Line:') + ' ' + (issue.line || 'Unknown') + ' ' + colors.dim('Scout:') + ' ' + issue.agent);\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine(' ' + colors.header('Issue'));\n // More lines on wider terminals\n const maxIssueLines = w > 80 ? 8 : 5;\n const issueLines = this.wrapText(issue.issue, w - 10);\n for (const line of issueLines.slice(0, maxIssueLines)) {\n pLine(' ' + severityColor(line));\n }\n if (issueLines.length > maxIssueLines) {\n pLine(' ' + colors.dim(`... ${issueLines.length - maxIssueLines} more lines`));\n }\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine(' ' + colors.success('Suggested Fix'));\n const maxFixLines = w > 80 ? 8 : 5;\n const fixLines = this.wrapText(issue.fix, w - 10);\n for (const line of fixLines.slice(0, maxFixLines)) {\n pLine(' ' + colors.success(line));\n }\n if (fixLines.length > maxFixLines) {\n pLine(' ' + colors.dim(`... ${fixLines.length - maxFixLines} more lines`));\n }\n // Additional metadata if available\n if (issue.cwe || issue.owasp || issue.effort) {\n console.log(colors.border(box.leftT + this.line(w - 2) + box.rightT));\n pLine(' ' + colors.header('Metadata'));\n if (issue.cwe) pLine(' ' + colors.dim('CWE:') + ' ' + issue.cwe);\n if (issue.owasp) pLine(' ' + colors.dim('OWASP:') + ' ' + issue.owasp);\n if (issue.effort) pLine(' ' + colors.dim('Effort:') + ' ' + issue.effort);\n }\n console.log(colors.border(box.bottomLeft + this.line(w - 2) + box.bottomRight));\n console.log(' ' + colors.dim('Press any key to return...'));\n\n const resume = () => {\n this.isActive = true;\n this.render();\n };\n input.once('keypress', resume);\n }\n\n /**\n * Register a callback to be called when Moneybags settings change.\n * The daemon uses this to trigger a Moneybags recalculation.\n */\n onMoneybagsChange(callback: () => void): void {\n this.onMoneybagsChangeCallback = callback;\n }\n\n /**\n * Trigger the Moneybags change callback (called after settings are updated)\n */\n private triggerMoneybagsRecalc(): void {\n try {\n // Always persist the config when settings change\n void this.persistGuardianConfig();\n\n // Trigger recalculation callback if registered (e.g., from yolo daemon)\n if (this.onMoneybagsChangeCallback) {\n this.addActivity('Moneybags: Recalculating costs with new settings...');\n try {\n this.onMoneybagsChangeCallback();\n } catch (error) {\n console.error('Error in moneybags change callback:', error);\n this.addActivity('Moneybags: Settings saved (recalculation failed)');\n }\n } else {\n this.addActivity('Moneybags: Settings updated');\n }\n } catch (error) {\n console.error('Error in triggerMoneybagsRecalc:', error);\n this.addActivity('Moneybags: Error updating settings');\n }\n }\n}\n","/**\n * Native File Picker\n * \n * Opens the OS-native file picker dialog for selecting files.\n * Works on macOS, Linux, and Windows.\n */\n\nimport { platform } from 'os';\nimport { getWorkingDirectory } from './workspace.js';\nimport { runShellCommand } from './command-runner.js';\n\nexport interface FilePickerOptions {\n title?: string;\n fileTypes?: string[]; // e.g., ['txt', 'md', 'json']\n multiple?: boolean;\n}\n\nexport interface FilePickerResult {\n success: boolean;\n path?: string;\n paths?: string[];\n error?: string;\n cancelled?: boolean;\n}\n\n/**\n * Open native file picker dialog\n */\nexport async function openFilePicker(options: FilePickerOptions = {}): Promise<FilePickerResult> {\n const os = platform();\n \n try {\n switch (os) {\n case 'darwin':\n return await openMacOSFilePicker(options);\n case 'linux':\n return await openLinuxFilePicker(options);\n case 'win32':\n return await openWindowsFilePicker(options);\n default:\n return {\n success: false,\n error: `Unsupported platform: ${os}. Please paste the file path manually.`\n };\n }\n } catch (error) {\n return {\n success: false,\n error: error instanceof Error ? error.message : String(error)\n };\n }\n}\n\n/**\n * macOS file picker using osascript\n */\nasync function openMacOSFilePicker(options: FilePickerOptions): Promise<FilePickerResult> {\n const title = options.title || 'Select a file';\n const multiple = options.multiple ? 'multiple selections allowed true' : '';\n \n // Build file type filter\n let typeFilter = '';\n if (options.fileTypes && options.fileTypes.length > 0) {\n // Map extensions to UTIs\n const utiMap: Record<string, string> = {\n 'txt': 'public.plain-text',\n 'md': 'net.daringfireball.markdown',\n 'json': 'public.json',\n 'js': 'com.netscape.javascript-source',\n 'ts': 'public.source-code',\n 'py': 'public.python-script',\n '*': 'public.item'\n };\n \n const utis = options.fileTypes.map(ext => utiMap[ext] || 'public.item');\n typeFilter = `of type {${utis.map(u => `\"${u}\"`).join(', ')}}`;\n }\n \n const script = `\n tell application \"System Events\"\n activate\n end tell\n set selectedFile to choose file with prompt \"${title}\" ${typeFilter} ${multiple}\n return POSIX path of selectedFile\n `.trim();\n \n try {\n const { stdout, stderr } = await runShellCommand(\n `osascript -e '${script.replace(/'/g, \"'\\\"'\\\"'\")}'`,\n { actor: 'internal:file-picker', triggeredBy: 'manual', targetPath: getWorkingDirectory(undefined, true) },\n { timeoutMs: 120000, captureOutput: false }\n );\n \n if (stderr && stderr.includes('User canceled')) {\n return { success: false, cancelled: true };\n }\n \n const path = stdout.trim();\n if (path) {\n return { success: true, path };\n }\n \n return { success: false, cancelled: true };\n } catch (error: unknown) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n if (errorMessage.includes('User canceled') || errorMessage.includes('-128')) {\n return { success: false, cancelled: true };\n }\n throw error;\n }\n}\n\n/**\n * Linux file picker using zenity, kdialog, or yad\n */\nasync function openLinuxFilePicker(options: FilePickerOptions): Promise<FilePickerResult> {\n const title = options.title || 'Select a file';\n \n // Build file filter\n let filter = '';\n if (options.fileTypes && options.fileTypes.length > 0) {\n const patterns = options.fileTypes.map(ext => `*.${ext}`).join(' ');\n filter = `--file-filter=\"Text files | ${patterns}\"`;\n }\n \n // Try zenity first (GTK), then kdialog (KDE), then yad\n const commands = [\n `zenity --file-selection --title=\"${title}\" ${filter}`,\n `kdialog --getopenfilename . \"${options.fileTypes?.map(e => `*.${e}`).join(' ') || '*'}\" --title \"${title}\"`,\n `yad --file --title=\"${title}\"`\n ];\n \n for (const cmd of commands) {\n try {\n const { stdout } = await runShellCommand(\n cmd,\n { actor: 'internal:file-picker', triggeredBy: 'manual', targetPath: getWorkingDirectory(undefined, true) },\n { timeoutMs: 120000, captureOutput: false }\n );\n const path = stdout.trim();\n if (path) {\n return { success: true, path };\n }\n } catch {\n // Try next command\n continue;\n }\n }\n \n return {\n success: false,\n error: 'No file picker available. Install zenity, kdialog, or yad.'\n };\n}\n\n/**\n * Windows file picker using PowerShell\n */\nasync function openWindowsFilePicker(options: FilePickerOptions): Promise<FilePickerResult> {\n const title = options.title || 'Select a file';\n \n // Build file filter\n let filter = 'All files (*.*)|*.*';\n if (options.fileTypes && options.fileTypes.length > 0) {\n const patterns = options.fileTypes.map(ext => `*.${ext}`).join(';');\n filter = `Text files (${patterns})|${patterns}|All files (*.*)|*.*`;\n }\n \n const script = `\n Add-Type -AssemblyName System.Windows.Forms\n $dialog = New-Object System.Windows.Forms.OpenFileDialog\n $dialog.Title = \"${title}\"\n $dialog.Filter = \"${filter}\"\n $dialog.InitialDirectory = [Environment]::GetFolderPath('Desktop')\n if ($dialog.ShowDialog() -eq 'OK') {\n Write-Output $dialog.FileName\n }\n `.trim().replace(/\\n/g, '; ');\n \n try {\n const { stdout } = await runShellCommand(\n `powershell -Command \"${script}\"`,\n { actor: 'internal:file-picker', triggeredBy: 'manual', targetPath: getWorkingDirectory(undefined, true) },\n { timeoutMs: 120000, captureOutput: false }\n );\n \n const path = stdout.trim();\n if (path) {\n return { success: true, path };\n }\n \n return { success: false, cancelled: true };\n } catch {\n return { success: false, cancelled: true };\n }\n}\n\n/**\n * Check if native file picker is available\n */\nexport async function isFilePickerAvailable(): Promise<boolean> {\n const os = platform();\n \n switch (os) {\n case 'darwin':\n // osascript is always available on macOS\n return true;\n case 'linux':\n // Check for zenity, kdialog, or yad\n try {\n await runShellCommand(\n 'which zenity || which kdialog || which yad',\n { actor: 'internal:file-picker', triggeredBy: 'manual', targetPath: getWorkingDirectory(undefined, true) },\n { captureOutput: false }\n );\n return true;\n } catch {\n return false;\n }\n case 'win32':\n // PowerShell is always available on modern Windows\n return true;\n default:\n return false;\n }\n}\n","import { readFile, readdir, writeFile, mkdir } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { basename, isAbsolute, resolve, join, extname, dirname } from 'path';\nimport { ContextAnalyzer } from '../orchestrator/context-analyzer.js';\nimport { RiskAssessor } from '../orchestrator/risk-assessor.js';\nimport { Triager } from '../orchestrator/triager.js';\nimport { Executor } from '../orchestrator/executor.js';\nimport { getSkillRegistry } from '../skills/built-in/registry.js';\nimport { buildDependencyGraph, formatDependencyGraph } from '../analysis/cross-file.js';\nimport { SemanticAnalyzer, formatSemanticIssues } from '../analysis/semantic-analyzer.js';\nimport { prioritizeIssues, formatPrioritizedResults, type PrioritizationResult } from '../analysis/smart-prioritizer.js';\nimport { AttackSurfaceAnalyzer, formatAttackSurface } from '../analysis/attack-surface.js';\nimport { \n IncrementalScanner, \n formatIncrementalScanResult,\n getVulnerabilityStats,\n getSymbolIndex \n} from '../trie/index.js';\nimport { ProgressReporter, setInteractiveMode, isInteractiveMode } from '../utils/progress.js';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport { isTrieInitialized } from '../utils/trie-init.js';\nimport { StreamingManager, formatConsoleUpdate } from '../utils/streaming.js';\nimport { getOutputManager } from '../utils/output-manager.js';\nimport { IssueAnalyzer, type PriorityReport } from '../utils/issue-analyzer.js';\nimport { InteractiveDashboard } from '../cli/interactive-dashboard.js';\nimport { loadConfig } from '../config/loader.js';\nimport { SlackIntegration } from '../integrations/slack.js';\nimport { TeamCollaborationManager, type TeamMember, type IssueAssignment } from '../integrations/team-collaboration.js';\nimport { updateContextAfterScan } from '../utils/context-state.js';\nimport { buildSavedPatternIssues, getDetectionRuleAgents, loadSavedPatterns } from '../patterns/saved-patterns.js';\nimport type { ScanResult, Issue, CodeContext, RiskLevel, Agent } from '../types/index.js';\n\n/**\n * Agent usage ledger entry with full timestamps\n */\ninterface LedgerEntry {\n agent: string;\n author?: string;\n authorUrl?: string;\n version?: string;\n // Timestamps\n firstRun: string;\n lastRun: string;\n // Stats\n totalRuns: number;\n totalIssuesFound: number;\n lastIssuesFound: number;\n}\n\n/**\n * Ledger metadata including user info\n */\ninterface LedgerMeta {\n createdAt: string;\n updatedAt: string;\n user?: {\n name?: string;\n role?: string;\n email?: string;\n };\n}\n\n/**\n * Full ledger structure\n */\ninterface AgentLedger {\n meta: LedgerMeta;\n agents: Record<string, LedgerEntry>;\n}\n\n/**\n * Update the agent usage ledger in .trie/ledger.json\n */\nasync function updateAgentLedger(\n workDir: string, \n agentResults: Array<{ agent: string; issues: Issue[] }>,\n registry: { getAgent(name: string): Agent | undefined },\n userConfig?: { name?: string; role?: string; email?: string }\n): Promise<void> {\n const ledgerPath = join(getTrieDirectory(workDir), 'ledger.json');\n \n try {\n // Ensure .trie directory exists\n const trieDir = dirname(ledgerPath);\n if (!existsSync(trieDir)) {\n await mkdir(trieDir, { recursive: true });\n }\n \n // Load existing ledger or create new\n const now = new Date().toISOString();\n const meta: LedgerMeta = {\n createdAt: now,\n updatedAt: now,\n };\n if (userConfig !== undefined) {\n meta.user = userConfig;\n }\n let ledger: AgentLedger = {\n meta,\n agents: {}\n };\n \n if (existsSync(ledgerPath)) {\n try {\n const content = await readFile(ledgerPath, 'utf-8');\n const existing = JSON.parse(content);\n // Handle old format (flat object) vs new format (with meta)\n if (existing.meta) {\n ledger = existing;\n } else {\n // Migrate old format\n ledger.agents = existing;\n }\n } catch {\n // Invalid JSON, start fresh\n }\n }\n \n // Update metadata\n ledger.meta.updatedAt = now;\n if (userConfig) {\n ledger.meta.user = userConfig;\n }\n \n // Update entries for agents that ran\n for (const result of agentResults) {\n const agent = registry.getAgent(result.agent);\n const existing = ledger.agents[result.agent];\n \n const entry: LedgerEntry = {\n agent: result.agent,\n firstRun: existing?.firstRun || now,\n lastRun: now,\n totalRuns: (existing?.totalRuns || 0) + 1,\n totalIssuesFound: (existing?.totalIssuesFound || 0) + result.issues.length,\n lastIssuesFound: result.issues.length\n };\n const author = agent?.author || existing?.author;\n if (author !== undefined) entry.author = author;\n const authorUrl = agent?.authorUrl || existing?.authorUrl;\n if (authorUrl !== undefined) entry.authorUrl = authorUrl;\n const version = agent?.version || existing?.version;\n if (version !== undefined) entry.version = version;\n ledger.agents[result.agent] = entry;\n }\n \n // Save updated ledger\n await writeFile(ledgerPath, JSON.stringify(ledger, null, 2));\n } catch {\n // Silently fail - ledger is non-critical\n }\n}\n\n// File extensions to scan\nconst SCANNABLE_EXTENSIONS = new Set([\n '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs',\n '.vue', '.svelte', '.astro',\n '.py', '.go', '.rs',\n '.json', '.yaml', '.yml',\n '.css', '.scss', '.less'\n]);\n\n// Directories to skip\nconst SKIP_DIRS = new Set([\n 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt',\n 'coverage', '.nyc_output', '__pycache__', '.pytest_cache',\n 'vendor', '.venv', 'venv', 'target', '.turbo', '.cache'\n]);\n\nexport class TrieScanTool {\n private contextAnalyzer = new ContextAnalyzer();\n private riskAssessor = new RiskAssessor();\n private triager = new Triager();\n private executor = new Executor();\n private agentRegistry = getSkillRegistry();\n private incrementalScanner: IncrementalScanner | null = null;\n private progress: ProgressReporter = new ProgressReporter();\n private customSkillsLoaded = false;\n\n /**\n * Ensure custom skills are loaded before using the registry\n */\n private async ensureCustomSkillsLoaded(): Promise<void> {\n if (!this.customSkillsLoaded) {\n await this.agentRegistry.loadCustomSkills();\n this.customSkillsLoaded = true;\n }\n }\n\n async execute(args: any) {\n const startTime = Date.now();\n\n try {\n let { files, context: userContext, forceAgents, directory } = args;\n const excludeAgentsInput = Array.isArray(args?.excludeAgents) ? args.excludeAgents : [];\n const excludeAgents = new Set<string>(\n excludeAgentsInput\n .filter((x: unknown): x is string => typeof x === 'string' && x.trim().length > 0)\n .map((s: string) => s.trim())\n );\n \n const config = await loadConfig();\n\n // Get the working directory - uses smart detection if not explicitly provided\n const workDir = getWorkingDirectory(directory);\n const scanDir = workDir;\n\n if (!isTrieInitialized(workDir)) {\n throw new Error('Trie is not initialized for this project. Run `trie init` first.');\n }\n\n const outputConfig = (config as Record<string, unknown>).output as Record<string, unknown> | undefined ?? {};\n const agentConfig = (config as Record<string, unknown>).agents as Record<string, unknown> | undefined ?? {};\n\n const streamingEnabled = args?.streaming ?? outputConfig?.streaming ?? true;\n const interactiveRequested = args?.interactive ?? outputConfig?.interactive ?? false;\n const interactiveEnabled = Boolean(interactiveRequested && process.stdout.isTTY);\n const cacheEnabled = args?.cache ?? agentConfig?.cache ?? true;\n const parallelEnabled = args?.parallel ?? agentConfig?.parallel ?? true;\n const maxConcurrency = args?.maxConcurrency ?? agentConfig?.maxConcurrency;\n const timeoutMs = args?.timeoutMs ?? agentConfig?.timeout ?? 120000;\n const useWorkerThreads = args?.workers ?? true;\n\n const streamingManager: StreamingManager | undefined = streamingEnabled\n ? (args?.streamingManager instanceof StreamingManager ? args.streamingManager : new StreamingManager())\n : undefined;\n const dashboard: InteractiveDashboard | undefined = interactiveEnabled\n ? (args?.dashboard instanceof InteractiveDashboard ? args.dashboard : new InteractiveDashboard())\n : undefined;\n\n // Enable interactive mode to suppress console output when dashboard is active\n if (interactiveEnabled) {\n setInteractiveMode(true);\n getOutputManager().setMode('tui');\n } else {\n // When not in interactive mode, set to console or mcp based on context\n // MCP mode is detected by checking if stdout is not a TTY (running as MCP tool)\n const isMCPContext = !process.stdout.isTTY;\n getOutputManager().setMode(isMCPContext ? 'mcp' : 'console');\n }\n \n // Connect streaming manager to output manager\n if (streamingManager) {\n getOutputManager().setStreamingManager(streamingManager);\n }\n\n if (dashboard && streamingManager) {\n if (!(args?.dashboard instanceof InteractiveDashboard)) {\n // Only create subscription and start dashboard if we created it ourselves\n streamingManager.subscribe(update => dashboard.handleStreamUpdate(update));\n await dashboard.start();\n } else {\n // Dashboard was passed from external caller (like watch mode)\n // Don't start it again, just ensure streaming updates are connected\n // The external caller manages dashboard lifecycle\n }\n } else if (streamingManager) {\n streamingManager.subscribe(update => {\n const line = formatConsoleUpdate(update);\n if (line) {\n console.error(line);\n }\n });\n }\n\n // Start progress reporting\n if (!interactiveEnabled) {\n this.progress.startPhase('init', 'TRIE AGENT - AI-Powered Code Analysis');\n }\n\n // If no files specified, scan the entire codebase\n if (!files || !Array.isArray(files) || files.length === 0) {\n this.progress.startPhase('discovery', `Discovering files in ${basename(workDir)}...`);\n files = await this.discoverFiles(workDir);\n this.progress.completePhase(`Found ${files.length} files`);\n }\n\n // Resolve file paths\n const resolvedFiles = files.map((f: string) => {\n if (isAbsolute(f)) {\n return f;\n }\n return resolve(workDir, f);\n });\n\n // Validate files exist\n const validFiles = resolvedFiles.filter((f: string) => {\n if (!existsSync(f)) {\n this.progress.warn('File not found', f);\n return false;\n }\n return true;\n });\n\n if (validFiles.length === 0) {\n throw new Error('No valid files found to scan. Specify files or run from project root.');\n }\n\n streamingManager?.startScan(validFiles.length);\n\n // Force rescan if cache is disabled\n const forceRescan = !cacheEnabled;\n\n // Initialize trie-based incremental scanner\n if (!this.incrementalScanner) {\n this.incrementalScanner = new IncrementalScanner(workDir);\n await this.incrementalScanner.loadCache();\n }\n\n // Detect changed files via git to invalidate skill cache\n // This ensures cache auto-updates when Claude fixes code\n // Add timeout to prevent hanging on slow git operations\n if (cacheEnabled && !forceRescan) {\n try {\n const { getGitChangedFiles } = await import('../agent/git.js');\n // Set a timeout for git operations (3 seconds max)\n const gitPromise = getGitChangedFiles(workDir);\n const timeoutPromise = new Promise<null>((resolve) => {\n setTimeout(() => resolve(null), 3000);\n });\n const gitChangedFiles = await Promise.race([gitPromise, timeoutPromise]);\n if (gitChangedFiles && gitChangedFiles.length > 0) {\n // Invalidate cache for changed files\n // The CacheManager will naturally invalidate via hash checking,\n // but we can also proactively clean up stale entries\n const { CacheManager } = await import('../utils/cache-manager.js');\n const cacheManager = new CacheManager(workDir);\n const invalidated = await cacheManager.cleanupStaleEntries(gitChangedFiles);\n if (invalidated > 0 && !isInteractiveMode()) {\n this.progress.update(`Invalidated ${invalidated} stale cache entries for changed files`);\n }\n }\n } catch (error) {\n // Git detection failed - cache will still invalidate naturally via hash checking\n }\n } else if (forceRescan && !isInteractiveMode()) {\n this.progress.update('Force rescan enabled - bypassing cache');\n }\n\n // Phase 1: Quick pattern scan\n this.progress.startPhase('reading', `Scanning ${validFiles.length} files...`);\n const vulnStats = getVulnerabilityStats();\n this.progress.update(`${vulnStats.total} vulnerability signatures loaded`);\n \n const trieResult = await this.incrementalScanner.scanFiles(\n validFiles,\n forceRescan, // Already defined above\n (filePath) => {\n if (streamingManager) {\n streamingManager.updateCurrentFile(filePath);\n streamingManager.completeFile();\n }\n }\n );\n if (trieResult.totalVulnerabilities > 0) {\n this.progress.finding('serious', `${trieResult.totalVulnerabilities} potential issues detected`);\n }\n this.progress.completePhase(`${trieResult.filesScanned} files scanned (${trieResult.cacheHitRate.toFixed(0)}% cached)`);\n\n // Save cache for next run\n await this.incrementalScanner.saveCache();\n\n // Phase 2: Context Analysis\n this.progress.startPhase('analyzing', 'Analyzing code context...');\n \n // Show summary of files (don't list all if too many)\n if (validFiles.length <= 5) {\n for (const file of validFiles) {\n this.progress.file('Reading', file);\n }\n } else {\n const byExt = this.groupFilesByExtension(validFiles);\n for (const [ext, count] of Object.entries(byExt)) {\n this.progress.update(`${count} ${ext} files`);\n }\n }\n\n const context = await this.contextAnalyzer.analyze(validFiles, userContext);\n this.logContextAnalysis(context);\n\n // Phase 3: Risk Assessment\n this.progress.startPhase('analyzing', 'Assessing risk level...');\n const riskLevel = this.riskAssessor.assessRisk(context);\n this.logRiskAssessment(context, riskLevel);\n\n // Phase 4: Agent Selection\n this.progress.startPhase('ai-review', 'Selecting AI agents...');\n \n // Ensure custom skills are loaded before agent selection\n await this.ensureCustomSkillsLoaded();\n\n const savedPatterns = await loadSavedPatterns(workDir);\n \n let selectedAgents = forceAgents\n ? this.agentRegistry.getAgentsByNames(forceAgents)\n : await this.triager.selectAgents(context, riskLevel);\n\n if (excludeAgents.size > 0) {\n const before = selectedAgents.length;\n selectedAgents = selectedAgents.filter(a => !excludeAgents.has(a.name));\n const removed = before - selectedAgents.length;\n if (removed > 0 && !isInteractiveMode()) {\n console.error(` Excluding ${removed} agent(s): ${Array.from(excludeAgents).join(', ')}`);\n }\n }\n\n // Ensure saved detection-rule patterns are included\n const savedDetectionAgents = getDetectionRuleAgents(savedPatterns)\n .filter(agent => !excludeAgents.has(agent));\n if (savedDetectionAgents.length > 0) {\n const selectedNames = new Set(selectedAgents.map(a => a.name));\n const extraAgents = this.agentRegistry\n .getAgentsByNames(savedDetectionAgents)\n .filter(a => !selectedNames.has(a.name));\n if (extraAgents.length > 0) {\n selectedAgents.push(...extraAgents);\n if (!isInteractiveMode()) {\n console.error(` Added ${extraAgents.length} saved scout(s): ${extraAgents.map(a => a.name).join(', ')}`);\n }\n }\n }\n\n const allAgentNames = this.agentRegistry.getSkillNames();\n this.logTriaging(selectedAgents.map(a => a.name), allAgentNames, context, riskLevel);\n this.progress.update(`${selectedAgents.length} agents selected for ${riskLevel} risk code`);\n\n // Configure moneybags agent with user count and other settings if specified\n const userCount = args?.userCount;\n const moneybagsConfig = args?.moneybagsConfig as { \n userCount?: number; \n payingUsers?: number;\n revenuePerUser?: number;\n developerRate?: number; \n industry?: 'solopreneur' | 'startup' | 'fintech' | 'healthcare' | 'enterprise' | 'saas' | 'ecommerce';\n } | undefined;\n \n const moneybags = selectedAgents.find(a => a.name === 'moneybags');\n if (moneybags && 'configure' in moneybags && typeof moneybags.configure === 'function') {\n // Use full config if available, otherwise fall back to just userCount\n if (moneybagsConfig) {\n moneybags.configure(moneybagsConfig);\n if (!isInteractiveMode()) {\n console.error(` Cost estimates: ${moneybagsConfig.userCount?.toLocaleString() || 250} users, $${moneybagsConfig.developerRate || 150}/hr${moneybagsConfig.industry ? `, ${moneybagsConfig.industry}` : ''}`);\n }\n } else if (userCount) {\n moneybags.configure({ userCount });\n if (!isInteractiveMode()) {\n console.error(` Cost estimates scaled for ${userCount.toLocaleString()} users`);\n }\n }\n }\n\n // Configure Agent Smith with settings from dashboard\n const agentSmithConfig = args?.agentSmithConfig as { \n aiEnhancement?: boolean; \n minSeverity?: string;\n enabledCategories?: Record<string, boolean>;\n memoryRetentionDays?: number;\n } | undefined;\n \n const agentSmith = selectedAgents.find(a => a.name === 'agent-smith');\n if (agentSmith && 'configure' in agentSmith && typeof agentSmith.configure === 'function' && agentSmithConfig) {\n agentSmith.configure(agentSmithConfig);\n if (!isInteractiveMode()) {\n const enabledCount = agentSmithConfig.enabledCategories \n ? Object.values(agentSmithConfig.enabledCategories).filter(v => v).length \n : 6;\n console.error(` Agent Smith: AI ${agentSmithConfig.aiEnhancement ? 'on' : 'off'}, ${agentSmithConfig.minSeverity || 'low'}+ severity, ${enabledCount}/6 categories`);\n }\n }\n\n // Phase 5: AI-Powered Agent Analysis\n this.progress.startPhase('ai-review', 'Running AI analysis...');\n this.progress.ai('Starting agent analysis', `${selectedAgents.length} agents`);\n \n const agentResults = await this.executor.executeAgents(\n selectedAgents,\n validFiles,\n { workingDir: workDir },\n streamingManager ? {\n streaming: streamingManager,\n parallel: parallelEnabled,\n cacheEnabled,\n maxConcurrency,\n useWorkerThreads,\n timeoutMs\n } : {\n parallel: parallelEnabled,\n cacheEnabled,\n maxConcurrency,\n useWorkerThreads,\n timeoutMs\n }\n );\n\n // Phase 6: Prioritization\n const savedPatternIssues = await buildSavedPatternIssues(\n savedPatterns,\n validFiles,\n async (filePath) => readFile(filePath, 'utf-8')\n );\n if (savedPatternIssues.length > 0) {\n agentResults.push({\n agent: 'saved-patterns',\n issues: savedPatternIssues,\n executionTime: 0,\n success: true,\n metadata: {\n filesAnalyzed: validFiles.length,\n linesAnalyzed: 0,\n },\n });\n }\n\n const allIssues = agentResults.flatMap(result => result.issues);\n const issueAnalyzer = new IssueAnalyzer();\n const priorityReport = issueAnalyzer.analyzeIssues(allIssues);\n \n this.progress.startPhase('prioritizing', 'Prioritizing findings...');\n const prioritized = prioritizeIssues(allIssues);\n \n // Phase 6b: Moneybags cost analysis on ACTIONABLE issues only (not noise)\n // Exclude meta-agents (agent-smith, super-reviewer) from cost calculation\n const META_AGENTS = new Set(['agent-smith', 'super-reviewer']);\n // Only include prioritized (actionable) issues, not all 1000+ raw issues\n const issuesForCostAnalysis = [...prioritized.critical, ...prioritized.important];\n const costableIssues = issuesForCostAnalysis.filter(issue => !META_AGENTS.has(issue.agent || ''));\n \n let costReport: { totalNowCost: number; totalProductionCost: number; totalSavings: number; summary: string } | null = null;\n const moneybagsAgent = selectedAgents.find(a => a.name === 'moneybags');\n if (moneybagsAgent && 'generateCostReport' in moneybagsAgent && typeof moneybagsAgent.generateCostReport === 'function' && costableIssues.length > 0) {\n costReport = moneybagsAgent.generateCostReport(costableIssues, context);\n }\n \n if (prioritized.critical.length > 0) {\n this.progress.finding('critical', `${prioritized.critical.length} critical issues`);\n }\n if (prioritized.important.length > 0) {\n this.progress.finding('serious', `${prioritized.important.length} important issues`);\n }\n this.progress.update(`Filtered ${prioritized.noise} noise items`);\n \n const totalIssues = allIssues.length;\n const critical = allIssues.filter(i => i.severity === 'critical').length;\n const serious = allIssues.filter(i => i.severity === 'serious').length;\n const moderate = allIssues.filter(i => i.severity === 'moderate').length;\n const low = allIssues.filter(i => i.severity === 'low').length;\n\n // Calculate score based on PRIORITIZED issues, not raw count\n const prioritizedCritical = prioritized.critical.length;\n const prioritizedImportant = prioritized.important.length;\n const score = Math.max(0, 100 - (prioritizedCritical * 25 + prioritizedImportant * 10));\n\n const result: ScanResult = {\n triaging: {\n agentsActivated: selectedAgents.map(a => a.name),\n agentsSkipped: await this.triager.getSkippedAgents(context, riskLevel),\n reason: this.triager.getTriagingReason(context, riskLevel),\n riskLevel,\n confidence: await this.triager.getTriagingConfidence(context, riskLevel)\n },\n results: {\n totalIssues,\n critical,\n serious,\n moderate,\n low,\n score,\n issues: allIssues,\n agentResults\n },\n executionTime: Date.now() - startTime,\n context\n };\n\n // Get code snippets for issues\n await this.enrichIssuesWithSnippets(allIssues);\n\n // Phase 7: Cross-file analysis (if scanning multiple files)\n if (validFiles.length > 3) {\n this.progress.update('Cross-file dependency analysis...');\n try {\n const depGraph = await buildDependencyGraph(scanDir, 100);\n if (depGraph.issues.length > 0) {\n formatDependencyGraph(depGraph);\n this.progress.finding('moderate', `${depGraph.issues.length} cross-file issues`);\n }\n } catch {\n // Skip silently\n }\n }\n\n // Phase 8: Semantic Analysis\n let semanticOutput = '';\n if (validFiles.length > 0) {\n this.progress.ai('Semantic analysis', 'Data flow, auth chains, business logic');\n try {\n const semanticAnalyzer = new SemanticAnalyzer();\n const semanticIssues = await semanticAnalyzer.analyze(validFiles, scanDir);\n const summary = semanticAnalyzer.getSummary();\n\n if (semanticIssues.length > 0) {\n semanticOutput = formatSemanticIssues(semanticIssues);\n this.progress.update(`Analyzed ${summary.functionsAnalyzed} functions, ${summary.routesFound} routes`);\n \n const semanticCritical = semanticIssues.filter(i => i.severity === 'critical').length;\n const semanticSerious = semanticIssues.filter(i => i.severity === 'serious').length;\n if (semanticCritical > 0) {\n this.progress.finding('critical', `${semanticCritical} data flow/auth issues`);\n }\n if (semanticSerious > 0) {\n this.progress.finding('serious', `${semanticSerious} business logic issues`);\n }\n }\n } catch {\n // Skip silently\n }\n }\n\n // Phase 9: Attack Surface Analysis\n let attackSurfaceOutput = '';\n if (validFiles.length > 0) {\n this.progress.ai('Attack surface mapping', 'Endpoints, auth coverage');\n try {\n const attackSurfaceAnalyzer = new AttackSurfaceAnalyzer();\n const surface = await attackSurfaceAnalyzer.analyze(validFiles, scanDir);\n \n if (surface.endpoints.length > 0) {\n attackSurfaceOutput = formatAttackSurface(surface);\n this.progress.update(`${surface.summary.totalEndpoints} endpoints found`);\n if (surface.summary.unprotectedSensitiveEndpoints > 0) {\n this.progress.finding('serious', `${surface.summary.unprotectedSensitiveEndpoints} unprotected sensitive endpoints`);\n }\n }\n } catch (e) {\n // Skip silently\n }\n }\n\n // Include trie scan results\n if (trieResult.totalVulnerabilities > 0) {\n formatIncrementalScanResult(trieResult);\n }\n\n // Symbol index stats (silent)\n const symbolIndex = getSymbolIndex();\n symbolIndex.getStats();\n\n // Generate smart prioritization output\n formatPrioritizedResults(prioritized);\n\n // Team collaboration: load members and assign issues\n const teamMembers = await this.loadTeamMembers(workDir);\n const teamManager = new TeamCollaborationManager();\n for (const member of teamMembers) {\n teamManager.addTeamMember(member);\n }\n const assignments = teamMembers.length > 0\n ? teamManager.assignIssues(allIssues, priorityReport)\n : [];\n\n // Notifications (Slack)\n const integrationsConfig = (config as Record<string, unknown>).integrations as Record<string, unknown> | undefined;\n const slackConfig = integrationsConfig?.slack as Record<string, unknown> | undefined;\n if (slackConfig?.enabled && slackConfig.webhook) {\n const slack = new SlackIntegration({\n webhookUrl: slackConfig.webhook as string,\n channel: slackConfig.channel as string | undefined\n });\n const repositoryName = process.env.GITHUB_REPOSITORY || basename(workDir);\n const branch = process.env.GITHUB_REF_NAME || 'main';\n\n try {\n await slack.sendScanNotification(allIssues, priorityReport, repositoryName, branch);\n const criticalIssues = allIssues.filter(i => i.severity === 'critical');\n if (criticalIssues.length > 0) {\n await slack.sendCriticalAlert(criticalIssues, repositoryName);\n }\n } catch {\n // Ignore notification failures\n }\n }\n\n // Complete!\n const actionableIssues = prioritized.critical.length + prioritized.important.length;\n this.progress.complete(`${actionableIssues} actionable issues found`);\n\n // Create a CONCISE summary for chat display (not the full 40k line report)\n const chatSummary = await this.formatChatSummary(\n result,\n prioritized,\n semanticOutput,\n attackSurfaceOutput,\n priorityReport,\n assignments,\n costReport\n );\n\n if (args?.format === 'json' && args?.output) {\n const report = {\n ...result,\n prioritization: prioritized,\n grouping: priorityReport\n };\n await writeFile(args.output, JSON.stringify(report, null, 2));\n }\n\n // Update context state for AI assistants\n try {\n streamingManager?.reportMemory('saving', 'scan results');\n \n const contextSignals: Record<string, boolean> = {\n touchesAuth: context.touchesAuth ?? false,\n touchesPayments: context.touchesPayments ?? false,\n touchesUserData: context.touchesUserData ?? false,\n touchesAPI: context.touchesAPI ?? false,\n touchesDatabase: context.touchesDatabase ?? false,\n touchesCrypto: context.touchesCrypto ?? false,\n };\n await updateContextAfterScan(\n agentResults,\n validFiles.length,\n contextSignals,\n Date.now() - startTime,\n validFiles\n );\n \n // Update agent usage ledger with user attribution (only if name is set)\n let userConfig: { name?: string; role?: string; email?: string } | undefined;\n if (config.user?.name) {\n userConfig = { name: config.user.name };\n if (config.user.role !== undefined) {\n userConfig.role = config.user.role;\n }\n if (config.user.email !== undefined) {\n userConfig.email = config.user.email;\n }\n }\n await updateAgentLedger(workDir, agentResults, this.agentRegistry, userConfig);\n \n streamingManager?.reportMemory('saved', `${agentResults.length} scouts, ${allIssues.length} findings`);\n } catch {\n // Non-critical - don't fail scan if context update fails\n }\n\n // Notify dashboard that scan is complete\n streamingManager?.completeScan(allIssues);\n\n return {\n content: [\n {\n type: 'text',\n text: chatSummary\n }\n ]\n };\n\n } catch (error) {\n return {\n content: [\n {\n type: 'text',\n text: `[ERROR] Scan failed: ${error instanceof Error ? error.message : String(error)}`\n }\n ]\n };\n }\n }\n\n private logContextAnalysis(context: CodeContext): void {\n // Skip console output in interactive mode (dashboard handles display)\n if (isInteractiveMode()) return;\n\n console.error('\\n Detected Context Signals:');\n \n const signals = [];\n if (context.touchesAuth) signals.push('* Authentication/Authorization');\n if (context.touchesPayments) signals.push('* Payment Processing');\n if (context.touchesDatabase) signals.push('* Database Operations');\n if (context.touchesAPI) signals.push('* API Endpoints');\n if (context.touchesUI) signals.push('* User Interface');\n if (context.touchesUserData) signals.push('* User/Personal Data');\n if (context.touchesHealthData) signals.push('* Protected Health Info (PHI)');\n if (context.touchesSecurityConfig) signals.push('* Security Configuration');\n \n if (signals.length === 0) {\n signals.push('* General Code Changes');\n }\n\n for (const signal of signals) {\n console.error(` ${signal}`);\n }\n \n console.error(`\\n Lines analyzed: ${context.linesChanged}`);\n console.error(` File patterns: ${context.filePatterns.join(', ') || 'none detected'}`);\n console.error('');\n }\n\n private logRiskAssessment(context: CodeContext, riskLevel: RiskLevel): void {\n // Skip console output in interactive mode (dashboard handles display)\n if (isInteractiveMode()) return;\n\n const riskLabel = {\n low: '[LOW]',\n medium: '[MEDIUM]', \n high: '[HIGH]',\n critical: '[CRITICAL]'\n };\n\n console.error(`\\n ${riskLabel[riskLevel]} Risk Level: ${riskLevel.toUpperCase()}`);\n \n const factors = [];\n if (context.touchesPayments) factors.push('Payment processing = automatic HIGH risk');\n if (context.touchesAuth) factors.push('Auth code requires extra scrutiny');\n if (context.touchesHealthData) factors.push('HIPAA data = CRITICAL compliance risk');\n if (context.touchesUserData) factors.push('PII handling requires privacy review');\n if (context.touchesSecurityConfig) factors.push('Security config changes need review');\n if (context.isNewFeature) factors.push('New features need architecture review');\n\n if (factors.length > 0) {\n console.error(' Risk factors:');\n for (const factor of factors) {\n console.error(` - ${factor}`);\n }\n }\n console.error('');\n }\n\n private logTriaging(\n selectedNames: string[], \n allAgentNames: string[],\n context: CodeContext,\n riskLevel: RiskLevel\n ): void {\n // Skip console output in interactive mode (dashboard handles display)\n if (isInteractiveMode()) return;\n\n console.error(`\\n Agents Selected: ${selectedNames.length} of ${allAgentNames.length} available`);\n console.error('');\n \n for (const name of allAgentNames) {\n const isSelected = selectedNames.includes(name);\n const icon = isSelected ? '[x]' : '[ ]';\n const reason = isSelected ? this.getAgentReason(name, context, riskLevel) : 'not needed for this context';\n console.error(` ${icon} ${name}: ${reason}`);\n }\n console.error('');\n }\n\n private getAgentReason(agentName: string, context: CodeContext, _riskLevel: RiskLevel): string {\n const reasons: Record<string, string> = {\n 'security': context.touchesAuth ? 'auth code detected' : \n context.touchesPayments ? 'payment code detected' :\n context.touchesAPI ? 'API endpoints detected' :\n context.touchesDatabase ? 'database operations detected' :\n 'security patterns detected',\n 'privacy': context.touchesUserData ? 'PII handling detected' :\n context.touchesHealthData ? 'PHI/HIPAA data detected' :\n context.touchesAuth ? 'user credentials detected' :\n 'data privacy patterns detected',\n 'typecheck': 'always runs - type safety is fundamental',\n 'comprehension': 'always runs - explains changes to stakeholders',\n 'legal': context.touchesHealthData ? 'HIPAA compliance required' :\n context.touchesPayments ? 'payment regulations apply' :\n context.touchesUserData ? 'data protection laws apply' :\n 'legal patterns detected',\n 'accessibility': context.touchesUI ? 'UI components detected' : 'UI patterns detected',\n 'test': context.isNewFeature ? 'new feature needs tests' :\n context.touchesAuth ? 'auth code needs tests' :\n 'test coverage needed',\n 'software-architect': context.isNewFeature ? 'architecture review for new feature' :\n context.touchesDatabase ? 'database schema review' :\n 'architecture patterns detected',\n 'devops': context.touchesSecurityConfig ? 'security config detected' :\n context.touchesDatabase ? 'infrastructure changes' :\n 'deployment patterns detected',\n 'bug-finding': context.touchesPayments ? 'payments require zero bugs' :\n context.isNewFeature ? 'new feature bug check' :\n 'bug patterns detected',\n 'user-testing': context.touchesUI ? 'UX review for UI changes' : 'user flow detected'\n };\n \n return reasons[agentName] || 'context-based activation';\n }\n\n private async enrichIssuesWithSnippets(issues: Issue[]): Promise<(Issue & { snippet?: string })[]> {\n const enriched: (Issue & { snippet?: string })[] = [];\n\n for (const issue of issues) {\n try {\n if (issue.line && existsSync(issue.file)) {\n const content = await readFile(issue.file, 'utf-8');\n const lines = content.split('\\n');\n const startLine = Math.max(0, issue.line - 3);\n const endLine = Math.min(lines.length, issue.line + 2);\n \n const snippetLines = lines.slice(startLine, endLine).map((line, idx) => {\n const lineNum = startLine + idx + 1;\n const marker = lineNum === issue.line ? '→' : ' ';\n return `${marker} ${lineNum.toString().padStart(4)} | ${line}`;\n });\n \n enriched.push({\n ...issue,\n snippet: snippetLines.join('\\n')\n });\n } else {\n enriched.push(issue);\n }\n } catch {\n enriched.push(issue);\n }\n }\n\n return enriched;\n }\n\n /**\n * Format a CONCISE summary for chat/terminal display\n * This is what users see - actionable, not overwhelming\n */\n private async formatChatSummary(\n result: ScanResult,\n prioritized: PrioritizationResult,\n semanticOutput: string,\n attackSurfaceOutput: string,\n priorityReport: PriorityReport,\n assignments: IssueAssignment[],\n costReport?: { totalNowCost: number; totalProductionCost: number; totalSavings: number; summary: string } | null\n ): Promise<string> {\n const { triaging, results: _results, executionTime } = result;\n \n let output = `\\n`;\n output += `TRIE SCAN COMPLETE\\n`;\n output += `==================\\n\\n`;\n \n // Quick stats line\n output += `${triaging.agentsActivated.length} agents | ${(executionTime / 1000).toFixed(1)}s | Risk: ${triaging.riskLevel.toUpperCase()}\\n\\n`;\n \n // Smart prioritization summary - just the actionable count\n const totalActionable = prioritized.critical.length + prioritized.important.length;\n if (totalActionable === 0) {\n output += `## No Issues Found\\n\\n`;\n output += `Your code passed all checks.\\n\\n`;\n } else {\n output += `## ${totalActionable} Issues Found\\n\\n`;\n }\n \n // Agent summary (compact one-liner)\n const agentSummary = result.results.agentResults\n .filter(r => r.issues.length > 0)\n .map(r => `${r.agent}: ${r.issues.length}`)\n .slice(0, 6)\n .join(' | ');\n \n if (agentSummary) {\n output += `**Agent Summary:** ${agentSummary}\\n\\n`;\n }\n \n // Cost report section (if available)\n if (costReport && costReport.totalProductionCost > 0) {\n const formatCurrency = (n: number) => \n n >= 1000000 ? `$${(n / 1000000).toFixed(2)}M` :\n n >= 1000 ? `$${(n / 1000).toFixed(1)}k` : `$${n}`;\n \n output += `**Estimated Cost:** Fix now ${formatCurrency(costReport.totalNowCost)} | If production ${formatCurrency(costReport.totalProductionCost)} | Savings ${formatCurrency(costReport.totalSavings)}\\n\\n`;\n }\n \n // Critical actions - SHOW FULL DETAILS WITH CODE SNIPPETS\n if (prioritized.critical.length > 0) {\n output += `### [CRITICAL] (${prioritized.critical.length})\\n\\n`;\n for (const issue of prioritized.critical.slice(0, 8)) {\n output += `---\\n\\n`;\n output += `**${issue.issue}**\\n\\n`;\n output += `File: \\`${issue.file}:${issue.line || '?'}\\`\\n\\n`;\n \n // Show code snippet if available\n const snippet = await this.getCodeSnippet(issue.file, issue.line);\n if (snippet) {\n output += `\\`\\`\\`\\n${snippet}\\n\\`\\`\\`\\n\\n`;\n }\n \n output += `**Fix:** ${issue.fix}\\n\\n`;\n \n // Generate a prompt the user can copy to fix this\n output += `<details>\\n<summary>Prompt to fix this</summary>\\n\\n`;\n output += `\\`\\`\\`\\nFix the ${issue.issue.toLowerCase()} in ${basename(issue.file)}${issue.line ? ` at line ${issue.line}` : ''}.\\n\\n${issue.fix}\\n\\`\\`\\`\\n\\n`;\n output += `</details>\\n\\n`;\n }\n if (prioritized.critical.length > 8) {\n output += `*...and ${prioritized.critical.length - 8} more critical issues*\\n\\n`;\n }\n }\n \n // Important items - SHOW FILE PATHS WITH CODE SNIPPETS\n if (prioritized.important.length > 0) {\n output += `### [SERIOUS] (${prioritized.important.length})\\n\\n`;\n for (const issue of prioritized.important.slice(0, 10)) {\n output += `---\\n\\n`;\n output += `**${issue.issue}**\\n\\n`;\n output += `File: \\`${issue.file}:${issue.line || '?'}\\`\\n\\n`;\n \n // Show code snippet if available\n const snippet = await this.getCodeSnippet(issue.file, issue.line);\n if (snippet) {\n output += `\\`\\`\\`\\n${snippet}\\n\\`\\`\\`\\n\\n`;\n }\n \n output += `**Fix:** ${issue.fix}\\n\\n`;\n \n // Generate a prompt the user can copy to fix this\n output += `<details>\\n<summary>Prompt to fix this</summary>\\n\\n`;\n output += `\\`\\`\\`\\nFix the ${issue.issue.toLowerCase()} in ${basename(issue.file)}${issue.line ? ` at line ${issue.line}` : ''}.\\n\\n${issue.fix}\\n\\`\\`\\`\\n\\n`;\n output += `</details>\\n\\n`;\n }\n if (prioritized.important.length > 10) {\n output += `*...and ${prioritized.important.length - 10} more important issues*\\n\\n`;\n }\n }\n \n // Semantic analysis highlights (the SMART stuff)\n if (semanticOutput && semanticOutput.includes('Data Flow') || semanticOutput.includes('Race Condition')) {\n output += `### Semantic Analysis\\n\\n`;\n \n // Extract key findings\n const dataFlowMatch = semanticOutput.match(/Data Flow Vulnerabilities \\((\\d+)\\)/);\n const raceMatch = semanticOutput.match(/Race Conditions \\((\\d+)\\)/);\n const authMatch = semanticOutput.match(/Authentication Issues \\((\\d+)\\)/);\n \n if (dataFlowMatch) output += `- [CRITICAL] **${dataFlowMatch[1]} data flow vulnerabilities** (untrusted input reaching dangerous sinks)\\n`;\n if (authMatch) output += `- [CRITICAL] **${authMatch[1]} authentication issues** (missing or bypassable auth)\\n`;\n if (raceMatch) output += `- [WARN] **${raceMatch[1]} race conditions** (TOCTOU, double-spend risks)\\n`;\n \n output += `\\n`;\n }\n \n // Attack surface summary\n if (attackSurfaceOutput && attackSurfaceOutput.includes('Attack Surface')) {\n const riskMatch = attackSurfaceOutput.match(/Risk Score\\*\\* \\| \\*\\*(\\d+)\\/100/);\n const endpointsMatch = attackSurfaceOutput.match(/Total Endpoints \\| (\\d+)/);\n const publicMatch = attackSurfaceOutput.match(/Public \\(No Auth\\) \\| (\\d+)/);\n \n if (riskMatch || endpointsMatch) {\n output += `### Attack Surface\\n\\n`;\n if (endpointsMatch) output += `- **${endpointsMatch[1]} endpoints** found`;\n if (publicMatch?.[1] && parseInt(publicMatch[1], 10) > 0) output += ` [WARN: ${publicMatch[1]} public without auth]`;\n output += `\\n`;\n if (riskMatch) output += `- **Risk Score:** ${riskMatch[1]}/100\\n`;\n output += `\\n`;\n }\n }\n\n // Smart grouping & prioritization\n if (priorityReport.totalGroups > 0) {\n output += `### Smart Grouping\\n\\n`;\n output += `- **${priorityReport.totalGroups} issue groups** across ${priorityReport.totalIssues} issues\\n`;\n output += `- **Risk Score:** ${priorityReport.riskScore}/100\\n`;\n\n const topGroups = [...priorityReport.urgent, ...priorityReport.high].slice(0, 5);\n if (topGroups.length > 0) {\n output += `\\n**Top groups to fix first:**\\n`;\n for (const group of topGroups) {\n const bulk = group.bulkFixAvailable ? ' (bulk-fix available)' : '';\n output += `- ${group.description} -- ${group.count} issues${bulk}\\n`;\n }\n output += `\\n`;\n }\n\n if (priorityReport.recommendations.length > 0) {\n output += `**Recommendations:**\\n`;\n for (const recommendation of priorityReport.recommendations) {\n output += `- ${recommendation}\\n`;\n }\n output += `\\n`;\n }\n }\n\n if (assignments.length > 0) {\n output += `### Team Assignments\\n\\n`;\n const urgent = assignments.filter(a => a.priority === 'urgent').length;\n const high = assignments.filter(a => a.priority === 'high').length;\n output += `- **${assignments.length} assignments** created (${urgent} urgent, ${high} high)\\n\\n`;\n }\n \n // Next steps\n output += `## Next Steps\\n\\n`;\n if (prioritized.critical.length > 0) {\n output += `1. **Fix critical issues:** \\`trie_fix\\` to apply high-confidence issues\\n`;\n }\n output += `2. **Deep dive:** Run \\`trie_security\\`, \\`trie_privacy\\`, or \\`trie_bugs\\` for specific analysis\\n`;\n output += `3. **Watch mode:** \\`trie_watch\\` to catch issues as you code\\n\\n`;\n \n // Agent attributions\n const agentsWithIssues = result.results.agentResults\n .filter(r => r.issues.length > 0)\n .map(r => r.agent);\n \n if (agentsWithIssues.length > 0) {\n const agentCredits = agentsWithIssues.map(name => {\n const agent = this.agentRegistry.getAgent(name);\n if (agent?.author) {\n return `${name} by ${agent.author}`;\n }\n return name;\n });\n output += `**Agents:** ${agentCredits.join(', ')}\\n\\n`;\n }\n \n // Include any accumulated rich content from OutputManager (MCP mode)\n const outputManager = getOutputManager();\n if (outputManager.getMode() === 'mcp') {\n const accumulatedMarkdown = outputManager.getMarkdown();\n if (accumulatedMarkdown.trim()) {\n output += `---\\n\\n`;\n output += `## Additional Analysis\\n\\n`;\n output += accumulatedMarkdown;\n output += `\\n`;\n }\n // Clear buffers for next run\n outputManager.clearBuffers();\n }\n \n // Footer\n output += `---\\n`;\n output += `*Powered by Trie Agent — showing you what matters.*\\n`;\n \n return output;\n }\n\n /**\n * Get a code snippet around a specific line\n */\n private async getCodeSnippet(filePath: string, line: number | undefined): Promise<string | null> {\n if (!line || !existsSync(filePath)) return null;\n \n try {\n const content = await readFile(filePath, 'utf-8');\n const lines = content.split('\\n');\n const start = Math.max(0, line - 3);\n const end = Math.min(lines.length, line + 2);\n \n return lines.slice(start, end).map((l, idx) => {\n const lineNum = start + idx + 1;\n const marker = lineNum === line ? '→' : ' ';\n return `${marker} ${lineNum.toString().padStart(4)} | ${l}`;\n }).join('\\n');\n } catch {\n return null;\n }\n }\n\n /**\n * Recursively discover all scannable files in a directory\n */\n private async discoverFiles(dir: string, maxFiles: number = 500): Promise<string[]> {\n const files: string[] = [];\n \n async function walk(currentDir: string) {\n if (files.length >= maxFiles) return;\n \n try {\n const entries = await readdir(currentDir, { withFileTypes: true });\n \n for (const entry of entries) {\n if (files.length >= maxFiles) break;\n \n const fullPath = join(currentDir, entry.name);\n \n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith('.')) {\n await walk(fullPath);\n }\n } else if (entry.isFile()) {\n // Skip hidden files unless they are env files (where secrets live)\n if (entry.name.startsWith('.') && !entry.name.startsWith('.env')) {\n continue;\n }\n\n // Explicitly ignore LLM/config prompt files that are noisy and not source code\n if (entry.name === '.claude.json') {\n continue;\n }\n\n const ext = extname(entry.name).toLowerCase();\n if (SCANNABLE_EXTENSIONS.has(ext)) {\n files.push(fullPath);\n }\n }\n }\n } catch (error) {\n // Skip directories we can't read\n }\n }\n \n await walk(dir);\n return files;\n }\n\n private async loadTeamMembers(workDir: string): Promise<TeamMember[]> {\n const teamConfigPath = join(getTrieDirectory(workDir), 'team.json');\n if (!existsSync(teamConfigPath)) {\n return [];\n }\n\n try {\n const content = await readFile(teamConfigPath, 'utf-8');\n const data = JSON.parse(content) as { members?: TeamMember[] };\n return Array.isArray(data.members) ? data.members : [];\n } catch {\n return [];\n }\n }\n\n private groupFilesByExtension(files: string[]): Record<string, number> {\n const byExt: Record<string, number> = {};\n for (const file of files) {\n const ext = extname(file) || 'other';\n byExt[ext] = (byExt[ext] || 0) + 1;\n }\n return byExt;\n }\n}\n","import { readFile } from 'fs/promises';\nimport { parse } from '@babel/parser';\nimport _traverse from '@babel/traverse';\nimport type { NodePath, TraverseOptions } from '@babel/traverse';\nimport type { Node } from '@babel/types';\nimport type * as t from '@babel/types';\nimport { existsSync } from 'fs';\nimport { extname, basename } from 'path';\n\n// Handle both ESM and CJS module formats for @babel/traverse\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nconst traverse = ((_traverse as any).default ?? _traverse) as (ast: Node, opts: TraverseOptions) => void;\nimport type { CodeContext } from '../types/index.js';\nimport { isInteractiveMode } from '../utils/progress.js';\n\nexport class ContextAnalyzer {\n async analyze(files: string[], userContext?: Partial<CodeContext>): Promise<CodeContext> {\n const context: CodeContext = {\n changeType: userContext?.changeType ?? 'general',\n isNewFeature: userContext?.isNewFeature ?? false,\n touchesUserData: userContext?.touchesUserData ?? false,\n touchesAuth: false,\n touchesPayments: false,\n touchesDatabase: false,\n touchesAPI: false,\n touchesUI: false,\n touchesHealthData: false,\n touchesSecurityConfig: false,\n linesChanged: 0,\n filePatterns: [],\n \n // NEW: Enhanced signals\n touchesCrypto: false,\n touchesFileSystem: false,\n touchesThirdPartyAPI: false,\n touchesLogging: false,\n touchesErrorHandling: false,\n hasTests: false,\n complexity: 'low',\n \n patterns: {\n hasAsyncCode: false,\n hasFormHandling: false,\n hasFileUploads: false,\n hasEmailHandling: false,\n hasRateLimiting: false,\n hasWebSockets: false,\n hasCaching: false,\n hasQueue: false,\n }\n };\n\n let totalLines = 0;\n let totalComplexity = 0;\n\n for (const file of files) {\n try {\n if (!existsSync(file)) {\n if (!isInteractiveMode()) {\n console.error(`File not found: ${file}`);\n }\n continue;\n }\n\n // Skip signature/pattern definition files - they contain keywords but aren't real code\n if (this.isSignatureFile(file)) {\n continue;\n }\n\n const content = await readFile(file, 'utf-8');\n const lines = content.split('\\n').length;\n totalLines += lines;\n\n // Analyze file patterns\n if (!file) continue; // Skip if file is undefined\n const fileName = basename(file).toLowerCase();\n const filePath = file.toLowerCase();\n\n context.filePatterns.push(fileName);\n\n // Detect language\n if (!context.language) {\n context.language = this.detectLanguage(fileName);\n }\n\n // Check for test files\n if (/\\.(test|spec)\\.(ts|js|tsx|jsx)$/.test(fileName)) {\n context.hasTests = true;\n }\n\n // Detect context based on file patterns\n if (this.isAuthFile(fileName, filePath)) {\n context.touchesAuth = true;\n }\n\n if (this.isPaymentFile(fileName, filePath)) {\n context.touchesPayments = true;\n }\n\n if (this.isDatabaseFile(fileName, filePath)) {\n context.touchesDatabase = true;\n }\n\n if (this.isAPIFile(fileName, filePath)) {\n context.touchesAPI = true;\n }\n\n if (this.isUIFile(fileName, filePath)) {\n context.touchesUI = true;\n }\n\n if (this.isHealthFile(fileName, filePath)) {\n context.touchesHealthData = true;\n }\n\n if (this.isSecurityConfigFile(fileName, filePath)) {\n context.touchesSecurityConfig = true;\n }\n\n // Analyze code content\n const fileComplexity = await this.analyzeCodeContent(content, file, context);\n totalComplexity += fileComplexity;\n\n } catch (error) {\n if (!isInteractiveMode()) {\n console.error(`Error analyzing file ${file}:`, error);\n }\n }\n }\n\n context.linesChanged = totalLines;\n\n // Calculate complexity\n const avgComplexity = files.length > 0 ? totalComplexity / files.length : 0;\n context.complexity = avgComplexity > 15 ? 'high' : avgComplexity > 8 ? 'medium' : 'low';\n\n // Override with user context if provided\n if (userContext) {\n Object.assign(context, userContext);\n }\n\n // Auto-detect change type if not specified\n if (!userContext?.changeType) {\n context.changeType = this.detectChangeType(context);\n }\n\n return context;\n }\n\n private detectLanguage(fileName: string): NonNullable<CodeContext['language']> {\n if (fileName.endsWith('.ts') || fileName.endsWith('.tsx')) return 'typescript';\n if (fileName.endsWith('.js') || fileName.endsWith('.jsx')) return 'javascript';\n if (fileName.endsWith('.py')) return 'python';\n if (fileName.endsWith('.go')) return 'go';\n if (fileName.endsWith('.rs')) return 'rust';\n return 'unknown';\n }\n\n private isAuthFile(fileName: string, filePath: string): boolean {\n const authPatterns = [\n 'auth', 'login', 'signup', 'register', 'session', 'jwt', 'token',\n 'password', 'oauth', 'signin', 'signout', 'middleware/auth',\n 'credential', 'sso', 'saml', 'oidc', '2fa', 'mfa', 'otp'\n ];\n return authPatterns.some(pattern =>\n fileName.includes(pattern) || filePath.includes(pattern)\n );\n }\n\n private isPaymentFile(fileName: string, filePath: string): boolean {\n const paymentPatterns = [\n 'payment', 'stripe', 'billing', 'checkout', 'subscription',\n 'invoice', 'charge', 'refund', 'paypal', 'merchant', 'cart',\n 'order', 'transaction', 'wallet', 'payout', 'pricing'\n ];\n return paymentPatterns.some(pattern =>\n fileName.includes(pattern) || filePath.includes(pattern)\n );\n }\n\n private isDatabaseFile(fileName: string, filePath: string): boolean {\n const dbPatterns = [\n 'model', 'schema', 'migration', 'seed', 'db', 'database',\n 'prisma', 'sequelize', 'mongoose', 'typeorm', 'knex',\n 'repository', 'entity', 'query'\n ];\n return dbPatterns.some(pattern =>\n fileName.includes(pattern) || filePath.includes(pattern)\n ) || fileName.endsWith('.sql');\n }\n\n private isAPIFile(fileName: string, filePath: string): boolean {\n const apiPatterns = [\n 'api/', 'route', 'handler', 'controller', 'endpoint',\n 'middleware', 'server', 'express', 'fastify', 'graphql',\n 'resolver', 'trpc'\n ];\n return apiPatterns.some(pattern =>\n fileName.includes(pattern) || filePath.includes(pattern)\n );\n }\n\n private isUIFile(fileName: string, filePath: string): boolean {\n const uiExtensions = ['.jsx', '.tsx', '.vue', '.svelte'];\n const uiPatterns = [\n 'component', 'page', 'layout', 'ui/', 'frontend/',\n 'client/', 'styles', 'css', 'view', 'template'\n ];\n\n return uiExtensions.some(ext => fileName.endsWith(ext)) ||\n uiPatterns.some(pattern => filePath.includes(pattern)) ||\n fileName.endsWith('.css') || fileName.endsWith('.scss');\n }\n\n private isHealthFile(fileName: string, filePath: string): boolean {\n // Avoid triggering on generic service health checks (healthz/health-check)\n const normalizedPath = `${filePath}`.toLowerCase();\n if (/healthz|health-check|healthcheck/.test(normalizedPath)) {\n return false;\n }\n\n const healthPatterns = [\n 'patient', 'medical', 'hipaa', 'phi',\n 'diagnosis', 'treatment', 'clinical', 'hospital',\n 'prescription', 'insurance', 'ehr', 'fhir'\n ];\n return healthPatterns.some(pattern =>\n fileName.includes(pattern) || normalizedPath.includes(pattern)\n );\n }\n\n private isSecurityConfigFile(fileName: string, filePath: string): boolean {\n const securityPatterns = [\n '.env', 'config', 'secret', 'key', 'cert', 'ssl',\n 'security', 'cors', 'helmet', 'csp', 'permission'\n ];\n return securityPatterns.some(pattern =>\n fileName.includes(pattern) || filePath.includes(pattern)\n );\n }\n\n /**\n * Check if file is a signature/pattern definition file (scanner's own rules)\n * These contain keywords like \"password\", \"auth\", \"payment\" as detection patterns,\n * not as actual code - skip them to avoid false context signals.\n */\n private isSignatureFile(filePath: string): boolean {\n const signaturePatterns = [\n /vulnerability-signatures\\.[jt]s$/,\n /vibe-code-signatures\\.[jt]s$/,\n /attack-surface\\.[jt]s$/,\n /semantic-analyzer\\.[jt]s$/,\n /smart-prioritizer\\.[jt]s$/,\n /context-analyzer\\.[jt]s$/,\n /triager\\.[jt]s$/,\n /risk-assessor\\.[jt]s$/,\n /base-agent\\.[jt]s$/,\n /\\/agents\\/.*\\.[jt]s$/, // All agent files contain detection patterns\n ];\n return signaturePatterns.some(pattern => pattern.test(filePath));\n }\n\n private async analyzeCodeContent(content: string, filePath: string, context: CodeContext): Promise<number> {\n const ext = extname(filePath);\n let complexity = 0;\n\n // Only parse JavaScript/TypeScript files\n if (!['.js', '.jsx', '.ts', '.tsx'].includes(ext)) {\n this.analyzeTextContent(content, context);\n return this.calculateTextComplexity(content);\n }\n\n try {\n const ast = parse(content, {\n sourceType: 'module',\n plugins: [\n 'jsx',\n 'typescript',\n 'decorators-legacy',\n 'classProperties',\n 'asyncGenerators',\n 'functionBind',\n 'exportDefaultFrom',\n 'objectRestSpread',\n 'dynamicImport'\n ]\n });\n\n traverse(ast, {\n // Detect imports that indicate specific domains\n ImportDeclaration: (path: NodePath<t.ImportDeclaration>) => {\n const source = path.node.source?.value;\n if (source) {\n this.analyzeImport(source, context);\n }\n },\n\n // Detect function calls\n CallExpression: (path: NodePath<t.CallExpression>) => {\n const callee = path.node.callee;\n let functionName = '';\n\n if (callee.type === 'Identifier') {\n functionName = callee.name ?? '';\n } else if (callee.type === 'MemberExpression' &&\n callee.property.type === 'Identifier') {\n functionName = callee.property.name ?? '';\n }\n\n this.analyzeFunctionCall(functionName, context);\n },\n\n // Count complexity\n IfStatement: () => { complexity++; },\n ConditionalExpression: () => { complexity++; },\n SwitchCase: () => { complexity++; },\n ForStatement: () => { complexity++; },\n ForInStatement: () => { complexity++; },\n ForOfStatement: () => { complexity++; },\n WhileStatement: () => { complexity++; },\n DoWhileStatement: () => { complexity++; },\n CatchClause: () => { \n complexity++; \n context.touchesErrorHandling = true;\n },\n \n // Detect async patterns\n AwaitExpression: () => {\n context.patterns.hasAsyncCode = true;\n },\n\n // Detect string literals\n StringLiteral: (path: NodePath<t.StringLiteral>) => {\n const value = path.node.value?.toLowerCase() ?? '';\n this.analyzeStringLiteral(value, context);\n }\n });\n\n } catch (error) {\n // Fall back to text analysis if parsing fails\n this.analyzeTextContent(content, context);\n complexity = this.calculateTextComplexity(content);\n }\n\n return complexity;\n }\n\n private analyzeImport(source: string, context: CodeContext): void {\n if (!source) return; // Skip if source is empty or undefined\n const s = source.toLowerCase();\n\n // Framework detection\n if (s.includes('react') || s.includes('next')) {\n context.framework = s.includes('next') ? 'nextjs' : 'react';\n } else if (s.includes('vue')) {\n context.framework = 'vue';\n } else if (s.includes('angular')) {\n context.framework = 'angular';\n } else if (s.includes('svelte')) {\n context.framework = 'svelte';\n } else if (s.includes('express')) {\n context.framework = 'express';\n } else if (s.includes('fastify')) {\n context.framework = 'fastify';\n }\n\n // Auth libraries\n if (['bcrypt', 'passport', 'jsonwebtoken', 'express-session', 'auth0', \n 'next-auth', 'lucia', 'clerk'].some(lib => s.includes(lib))) {\n context.touchesAuth = true;\n }\n\n // Payment libraries\n if (['stripe', 'paypal', 'braintree', 'square', 'paddle'].some(lib => s.includes(lib))) {\n context.touchesPayments = true;\n }\n\n // Database libraries\n if (['prisma', 'sequelize', 'mongoose', 'typeorm', 'pg', 'mysql', \n 'drizzle', 'knex', 'redis'].some(lib => s.includes(lib))) {\n context.touchesDatabase = true;\n }\n\n // UI libraries\n if (['react', 'vue', 'angular', 'svelte', 'styled-components', \n 'tailwind', 'chakra', 'mui', 'antd'].some(lib => s.includes(lib))) {\n context.touchesUI = true;\n }\n\n // Crypto libraries\n if (['crypto', 'bcrypt', 'argon2', 'sodium', 'forge'].some(lib => s.includes(lib))) {\n context.touchesCrypto = true;\n }\n\n // File system\n if (['fs', 'path', 'multer', 'formidable', 'busboy', 'sharp'].some(lib => s.includes(lib))) {\n context.touchesFileSystem = true;\n }\n\n // Third-party APIs\n if (['axios', 'node-fetch', 'got', 'superagent', 'openai', 'anthropic', \n 'twilio', 'sendgrid', 'aws-sdk', 'googleapis'].some(lib => s.includes(lib))) {\n context.touchesThirdPartyAPI = true;\n }\n\n // Logging\n if (['winston', 'pino', 'bunyan', 'log4js', 'morgan'].some(lib => s.includes(lib))) {\n context.touchesLogging = true;\n }\n\n // WebSockets\n if (['socket.io', 'ws', 'websocket', 'pusher'].some(lib => s.includes(lib))) {\n context.patterns.hasWebSockets = true;\n }\n\n // Caching\n if (['redis', 'memcached', 'lru-cache', 'node-cache'].some(lib => s.includes(lib))) {\n context.patterns.hasCaching = true;\n }\n\n // Queues\n if (['bullmq', 'bull', 'agenda', 'bee-queue', 'rabbitmq', 'amqp'].some(lib => s.includes(lib))) {\n context.patterns.hasQueue = true;\n }\n\n // Rate limiting\n if (['express-rate-limit', 'rate-limiter-flexible', 'bottleneck'].some(lib => s.includes(lib))) {\n context.patterns.hasRateLimiting = true;\n }\n\n // Email\n if (['nodemailer', 'sendgrid', 'mailgun', 'postmark', 'ses'].some(lib => s.includes(lib))) {\n context.patterns.hasEmailHandling = true;\n }\n }\n\n private analyzeFunctionCall(name: string, context: CodeContext): void {\n if (!name) return; // Skip if name is empty or undefined\n const n = name.toLowerCase();\n\n // Auth functions\n if (['hash', 'compare', 'sign', 'verify', 'authenticate', 'login', 'logout'].includes(n)) {\n context.touchesAuth = true;\n }\n\n // Payment functions\n if (['charge', 'refund', 'subscription', 'invoice', 'payment'].some(f => n.includes(f))) {\n context.touchesPayments = true;\n }\n\n // Database functions\n if (['find', 'create', 'update', 'delete', 'save', 'query', 'execute', 'insert'].includes(n)) {\n context.touchesDatabase = true;\n }\n\n // File operations\n if (['readfile', 'writefile', 'mkdir', 'unlink', 'upload'].some(f => n.includes(f))) {\n context.touchesFileSystem = true;\n if (n.includes('upload')) {\n context.patterns.hasFileUploads = true;\n }\n }\n\n // Logging\n if (['log', 'info', 'warn', 'error', 'debug'].includes(n)) {\n context.touchesLogging = true;\n }\n }\n\n private analyzeStringLiteral(value: string, context: CodeContext): void {\n // PII patterns\n if (['email', 'phone', 'address', 'ssn', 'social', 'credit', 'passport', \n 'dob', 'birth', 'salary', 'income'].some(p => value.includes(p))) {\n context.touchesUserData = true;\n }\n\n // Health patterns\n if (['patient', 'medical', 'diagnosis', 'treatment', 'medication', \n 'symptom', 'prescription', 'insurance'].some(p => value.includes(p))) {\n context.touchesHealthData = true;\n }\n\n // Form patterns\n if (['submit', 'form', 'input', 'validation', 'required'].some(p => value.includes(p))) {\n context.patterns.hasFormHandling = true;\n }\n }\n\n private analyzeTextContent(content: string, context: CodeContext): void {\n const lowerContent = content.toLowerCase();\n\n const authKeywords = ['password', 'auth', 'login', 'jwt', 'session', 'token', 'credential'];\n const paymentKeywords = ['stripe', 'payment', 'billing', 'checkout', 'subscription', 'invoice'];\n const dbKeywords = ['select', 'insert', 'update', 'delete', 'database', 'query', 'prisma'];\n const uiKeywords = ['component', 'render', 'jsx', 'css', 'style', 'button', 'form'];\n const piiKeywords = ['email', 'phone', 'address', 'ssn', 'social'];\n const healthKeywords = ['patient', 'medical', 'diagnosis', 'treatment', 'hipaa'];\n const cryptoKeywords = ['encrypt', 'decrypt', 'hash', 'crypto', 'cipher', 'key'];\n const asyncKeywords = ['async', 'await', 'promise', 'then', 'catch'];\n\n if (authKeywords.some(k => lowerContent.includes(k))) context.touchesAuth = true;\n if (paymentKeywords.some(k => lowerContent.includes(k))) context.touchesPayments = true;\n if (dbKeywords.some(k => lowerContent.includes(k))) context.touchesDatabase = true;\n if (uiKeywords.some(k => lowerContent.includes(k))) context.touchesUI = true;\n if (piiKeywords.some(k => lowerContent.includes(k))) context.touchesUserData = true;\n if (healthKeywords.some(k => lowerContent.includes(k))) context.touchesHealthData = true;\n if (cryptoKeywords.some(k => lowerContent.includes(k))) context.touchesCrypto = true;\n if (asyncKeywords.some(k => lowerContent.includes(k))) context.patterns.hasAsyncCode = true;\n\n // File patterns\n if (/upload|multer|formdata|file/i.test(lowerContent)) {\n context.patterns.hasFileUploads = true;\n context.touchesFileSystem = true;\n }\n\n // Email patterns\n if (/nodemailer|sendgrid|email.*send|send.*email/i.test(lowerContent)) {\n context.patterns.hasEmailHandling = true;\n }\n\n // WebSocket patterns\n if (/websocket|socket\\.io|ws\\./i.test(lowerContent)) {\n context.patterns.hasWebSockets = true;\n }\n\n // Error handling patterns\n if (/try\\s*{|catch\\s*\\(|\\.catch\\(|throw\\s+new/i.test(content)) {\n context.touchesErrorHandling = true;\n }\n\n // Logging patterns \n if (/console\\.(log|info|warn|error)|logger\\./i.test(content)) {\n context.touchesLogging = true;\n }\n }\n\n private calculateTextComplexity(content: string): number {\n let complexity = 0;\n \n // Count control flow statements\n complexity += (content.match(/\\bif\\b/g) || []).length;\n complexity += (content.match(/\\belse\\b/g) || []).length;\n complexity += (content.match(/\\bfor\\b/g) || []).length;\n complexity += (content.match(/\\bwhile\\b/g) || []).length;\n complexity += (content.match(/\\bswitch\\b/g) || []).length;\n complexity += (content.match(/\\bcatch\\b/g) || []).length;\n complexity += (content.match(/\\?\\s*.*\\s*:/g) || []).length; // ternary\n\n return complexity;\n }\n\n private detectChangeType(context: CodeContext): CodeContext['changeType'] {\n // Priority order for change type detection\n if (context.touchesPayments) return 'payment';\n if (context.touchesAuth) return 'auth';\n if (context.touchesDatabase) return 'database';\n if (context.touchesAPI) return 'api';\n if (context.touchesUI) return 'ui';\n return 'general';\n }\n}\n","import type { CodeContext, RiskLevel } from '../types/index.js';\n\nexport class RiskAssessor {\n assessRisk(context: CodeContext): RiskLevel {\n let score = 0;\n\n // Base scoring from PRD\n if (context.touchesAuth) score += 35;\n if (context.touchesPayments) score += 50;\n if (context.touchesDatabase) score += 25;\n if (context.touchesUserData) score += 20;\n if (context.touchesHealthData) score += 60; // HIPAA critical\n if (context.linesChanged > 500) score += 20;\n if (context.touchesSecurityConfig) score += 35;\n\n // Additional risk factors\n if (context.touchesAPI) score += 20;\n if (context.isNewFeature) score += 15;\n if (context.touchesUI && context.touchesUserData) score += 10; // Forms with PII\n\n // Risk multipliers for dangerous combinations\n if (context.touchesAuth && context.touchesDatabase) score += 5; // Auth + DB is risky\n if (context.touchesPayments && context.touchesUserData) score += 15; // Payment + PII\n if (context.touchesHealthData && context.touchesDatabase) score += 20; // PHI storage\n\n // Classify risk level\n if (score >= 95) return 'critical';\n if (score >= 60) return 'high';\n if (score >= 25) return 'medium';\n return 'low';\n }\n\n getRiskExplanation(context: CodeContext, riskLevel: RiskLevel): string {\n const reasons = [];\n\n if (context.touchesAuth) {\n reasons.push('handles authentication/authorization');\n }\n if (context.touchesPayments) {\n reasons.push('processes payments');\n }\n if (context.touchesDatabase) {\n reasons.push('modifies database');\n }\n if (context.touchesUserData) {\n reasons.push('handles user data');\n }\n if (context.touchesHealthData) {\n reasons.push('handles protected health information');\n }\n if (context.touchesSecurityConfig) {\n reasons.push('modifies security configuration');\n }\n if (context.linesChanged > 500) {\n reasons.push('large code change');\n }\n if (context.isNewFeature) {\n reasons.push('introduces new functionality');\n }\n\n const explanation = reasons.length > 0\n ? `Risk level ${riskLevel} because code ${reasons.join(', ')}`\n : `Risk level ${riskLevel} - general code change`;\n\n return explanation;\n }\n\n shouldRunAllAgents(riskLevel: RiskLevel): boolean {\n return riskLevel === 'critical';\n }\n}","import { readFile, readdir } from 'fs/promises';\nimport { join, extname, relative, dirname, basename } from 'path';\n\n/**\n * Cross-File Analysis\n * \n * Analyzes relationships between files to detect:\n * - Unused exports\n * - Circular dependencies\n * - Missing imports\n * - Orphaned files\n * - Dead code\n */\n\nexport interface FileNode {\n path: string;\n relativePath: string;\n imports: ImportInfo[];\n exports: ExportInfo[];\n dependencies: string[];\n dependents: string[];\n}\n\nexport interface ImportInfo {\n source: string;\n specifiers: string[];\n isDefault: boolean;\n isNamespace: boolean;\n line: number;\n}\n\nexport interface ExportInfo {\n name: string;\n isDefault: boolean;\n line: number;\n}\n\nexport interface DependencyGraph {\n files: Map<string, FileNode>;\n issues: CrossFileIssue[];\n}\n\nexport interface CrossFileIssue {\n type: 'circular-dep' | 'unused-export' | 'missing-import' | 'orphaned-file' | 'dead-code';\n severity: 'critical' | 'serious' | 'moderate' | 'low';\n files: string[];\n description: string;\n suggestion: string;\n}\n\n/**\n * Build a dependency graph from a directory\n */\nexport async function buildDependencyGraph(rootDir: string, maxFiles: number = 200): Promise<DependencyGraph> {\n const files = new Map<string, FileNode>();\n const issues: CrossFileIssue[] = [];\n\n // Discover all files\n const filePaths = await discoverFiles(rootDir, maxFiles);\n \n // Parse each file\n for (const filePath of filePaths) {\n const node = await parseFile(filePath, rootDir);\n if (node) {\n files.set(node.relativePath, node);\n }\n }\n\n // Resolve dependencies\n for (const [path, node] of files) {\n for (const imp of node.imports) {\n const resolvedPath = resolveImport(imp.source, path, files);\n if (resolvedPath) {\n node.dependencies.push(resolvedPath);\n \n // Add this file as a dependent of the resolved file\n const depNode = files.get(resolvedPath);\n if (depNode) {\n depNode.dependents.push(path);\n }\n }\n }\n }\n\n // Detect issues\n issues.push(...detectCircularDependencies(files));\n issues.push(...detectUnusedExports(files));\n issues.push(...detectOrphanedFiles(files));\n\n return { files, issues };\n}\n\n/**\n * Parse a single file for imports and exports\n */\nasync function parseFile(filePath: string, rootDir: string): Promise<FileNode | null> {\n try {\n const content = await readFile(filePath, 'utf-8');\n const relativePath = relative(rootDir, filePath);\n const lines = content.split('\\n');\n\n const imports: ImportInfo[] = [];\n const exports: ExportInfo[] = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n const lineNum = i + 1;\n\n // Parse imports\n // import { x, y } from 'module'\n const namedImportMatch = line.match(/import\\s+\\{([^}]+)\\}\\s+from\\s+['\"]([^'\"]+)['\"]/);\n if (namedImportMatch) {\n const specifiers = namedImportMatch[1]!.split(',').map(s => s.trim().split(/\\s+as\\s+/)[0]!.trim());\n imports.push({\n source: namedImportMatch[2]!,\n specifiers,\n isDefault: false,\n isNamespace: false,\n line: lineNum,\n });\n continue;\n }\n\n // import x from 'module'\n const defaultImportMatch = line.match(/import\\s+(\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/);\n if (defaultImportMatch) {\n imports.push({\n source: defaultImportMatch[2]!,\n specifiers: [defaultImportMatch[1]!],\n isDefault: true,\n isNamespace: false,\n line: lineNum,\n });\n continue;\n }\n\n // import * as x from 'module'\n const namespaceImportMatch = line.match(/import\\s+\\*\\s+as\\s+(\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/);\n if (namespaceImportMatch) {\n imports.push({\n source: namespaceImportMatch[2]!,\n specifiers: [namespaceImportMatch[1]!],\n isDefault: false,\n isNamespace: true,\n line: lineNum,\n });\n continue;\n }\n\n // Parse exports\n // export function/class/const/let/var name\n const namedExportMatch = line.match(/export\\s+(?:async\\s+)?(?:function|class|const|let|var|interface|type)\\s+(\\w+)/);\n if (namedExportMatch) {\n exports.push({\n name: namedExportMatch[1]!,\n isDefault: false,\n line: lineNum,\n });\n continue;\n }\n\n // export default\n const defaultExportMatch = line.match(/export\\s+default\\s+(?:function|class)?\\s*(\\w+)?/);\n if (defaultExportMatch) {\n exports.push({\n name: defaultExportMatch[1] || 'default',\n isDefault: true,\n line: lineNum,\n });\n continue;\n }\n\n // export { x, y }\n const reexportMatch = line.match(/export\\s+\\{([^}]+)\\}/);\n if (reexportMatch && !line.includes('from')) {\n const specifiers = reexportMatch[1]!.split(',').map(s => s.trim().split(/\\s+as\\s+/)[0]!.trim());\n for (const spec of specifiers) {\n exports.push({\n name: spec,\n isDefault: false,\n line: lineNum,\n });\n }\n }\n }\n\n return {\n path: filePath,\n relativePath,\n imports,\n exports,\n dependencies: [],\n dependents: [],\n };\n } catch {\n return null;\n }\n}\n\n/**\n * Resolve an import path to a file in the graph\n */\nfunction resolveImport(source: string, fromPath: string, files: Map<string, FileNode>): string | null {\n // Skip external packages\n if (!source.startsWith('.') && !source.startsWith('/')) {\n return null;\n }\n\n const fromDir = dirname(fromPath);\n let resolvedPath = join(fromDir, source);\n\n // Try different extensions\n const extensions = ['', '.ts', '.tsx', '.js', '.jsx', '/index.ts', '/index.tsx', '/index.js'];\n \n for (const ext of extensions) {\n const tryPath = resolvedPath + ext;\n if (files.has(tryPath)) {\n return tryPath;\n }\n }\n\n return null;\n}\n\n/**\n * Detect circular dependencies using DFS\n */\nfunction detectCircularDependencies(files: Map<string, FileNode>): CrossFileIssue[] {\n const issues: CrossFileIssue[] = [];\n const visited = new Set<string>();\n const inStack = new Set<string>();\n\n function dfs(path: string, stack: string[]): void {\n if (inStack.has(path)) {\n // Found a cycle\n const cycleStart = stack.indexOf(path);\n const cycle = [...stack.slice(cycleStart), path];\n \n // Only report if we haven't reported this cycle before\n const cycleKey = cycle.sort().join('->');\n if (!issues.some(i => i.files.sort().join('->') === cycleKey)) {\n issues.push({\n type: 'circular-dep',\n severity: 'serious',\n files: cycle,\n description: `Circular dependency: ${cycle.map(f => basename(f)).join(' → ')}`,\n suggestion: 'Break the cycle by extracting shared code to a separate module',\n });\n }\n return;\n }\n\n if (visited.has(path)) return;\n \n visited.add(path);\n inStack.add(path);\n\n const node = files.get(path);\n if (node) {\n for (const dep of node.dependencies) {\n dfs(dep, [...stack, path]);\n }\n }\n\n inStack.delete(path);\n }\n\n for (const path of files.keys()) {\n dfs(path, []);\n }\n\n return issues;\n}\n\n/**\n * Detect unused exports\n */\nfunction detectUnusedExports(files: Map<string, FileNode>): CrossFileIssue[] {\n const issues: CrossFileIssue[] = [];\n const allImportedSpecifiers = new Map<string, Set<string>>();\n\n // Collect all imported specifiers per file\n for (const node of files.values()) {\n for (const imp of node.imports) {\n const resolvedPath = resolveImport(imp.source, node.relativePath, files);\n if (resolvedPath) {\n if (!allImportedSpecifiers.has(resolvedPath)) {\n allImportedSpecifiers.set(resolvedPath, new Set());\n }\n for (const spec of imp.specifiers) {\n allImportedSpecifiers.get(resolvedPath)!.add(spec);\n }\n if (imp.isDefault) {\n allImportedSpecifiers.get(resolvedPath)!.add('default');\n }\n if (imp.isNamespace) {\n allImportedSpecifiers.get(resolvedPath)!.add('*');\n }\n }\n }\n }\n\n // Find unused exports\n for (const [path, node] of files) {\n const importedSpecs = allImportedSpecifiers.get(path) || new Set();\n \n // Skip if namespace import (imports everything)\n if (importedSpecs.has('*')) continue;\n \n // Skip entry points (files with no dependents)\n if (node.dependents.length === 0 && node.exports.length > 0) continue;\n\n for (const exp of node.exports) {\n const name = exp.isDefault ? 'default' : exp.name;\n if (!importedSpecs.has(name) && !importedSpecs.has(exp.name)) {\n issues.push({\n type: 'unused-export',\n severity: 'low',\n files: [path],\n description: `Unused export '${exp.name}' in ${basename(path)}`,\n suggestion: `Remove the export or ensure it's imported somewhere`,\n });\n }\n }\n }\n\n return issues;\n}\n\n/**\n * Detect orphaned files (no imports or exports)\n */\nfunction detectOrphanedFiles(files: Map<string, FileNode>): CrossFileIssue[] {\n const issues: CrossFileIssue[] = [];\n\n for (const [path, node] of files) {\n // File has no exports and is not imported anywhere\n if (node.exports.length === 0 && node.dependents.length === 0) {\n // Skip if it's likely an entry point\n if (basename(path).match(/^(index|main|app|server)\\./i)) continue;\n // Skip test files\n if (path.includes('.test.') || path.includes('.spec.') || path.includes('__tests__')) continue;\n\n issues.push({\n type: 'orphaned-file',\n severity: 'low',\n files: [path],\n description: `Potentially orphaned file: ${basename(path)}`,\n suggestion: 'Verify this file is needed or remove it',\n });\n }\n }\n\n return issues;\n}\n\n/**\n * Discover files recursively\n */\nasync function discoverFiles(dir: string, maxFiles: number): Promise<string[]> {\n const files: string[] = [];\n const skipDirs = new Set(['node_modules', '.git', 'dist', 'build', '.next', 'coverage']);\n const extensions = new Set(['.ts', '.tsx', '.js', '.jsx']);\n\n async function walk(currentDir: string) {\n if (files.length >= maxFiles) return;\n\n try {\n const entries = await readdir(currentDir, { withFileTypes: true });\n\n for (const entry of entries) {\n if (files.length >= maxFiles) break;\n\n const fullPath = join(currentDir, entry.name);\n\n if (entry.isDirectory()) {\n if (!skipDirs.has(entry.name) && !entry.name.startsWith('.')) {\n await walk(fullPath);\n }\n } else if (entry.isFile()) {\n const ext = extname(entry.name).toLowerCase();\n if (extensions.has(ext)) {\n files.push(fullPath);\n }\n }\n }\n } catch {\n // Skip inaccessible directories\n }\n }\n\n await walk(dir);\n return files;\n}\n\n/**\n * Format dependency graph for output\n */\nexport function formatDependencyGraph(graph: DependencyGraph): string {\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🔗 CROSS-FILE ANALYSIS\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## 📊 Overview\\n\\n`;\n output += `- **Files analyzed:** ${graph.files.size}\\n`;\n output += `- **Issues found:** ${graph.issues.length}\\n\\n`;\n\n // Group issues by type\n const byType = new Map<string, CrossFileIssue[]>();\n for (const issue of graph.issues) {\n if (!byType.has(issue.type)) byType.set(issue.type, []);\n byType.get(issue.type)!.push(issue);\n }\n\n if (graph.issues.length === 0) {\n output += `## ✅ No cross-file issues found!\\n\\n`;\n return output;\n }\n\n output += `## Issues\\n\\n`;\n\n // Circular dependencies\n const circular = byType.get('circular-dep') || [];\n if (circular.length > 0) {\n output += `### 🔄 Circular Dependencies (${circular.length})\\n\\n`;\n for (const issue of circular) {\n output += `- ${issue.description}\\n`;\n output += ` *${issue.suggestion}*\\n`;\n }\n output += '\\n';\n }\n\n // Unused exports\n const unused = byType.get('unused-export') || [];\n if (unused.length > 0) {\n output += `### 📤 Unused Exports (${unused.length})\\n\\n`;\n for (const issue of unused.slice(0, 10)) {\n output += `- ${issue.description}\\n`;\n }\n if (unused.length > 10) {\n output += `- *...and ${unused.length - 10} more*\\n`;\n }\n output += '\\n';\n }\n\n // Orphaned files\n const orphaned = byType.get('orphaned-file') || [];\n if (orphaned.length > 0) {\n output += `### 📁 Potentially Orphaned Files (${orphaned.length})\\n\\n`;\n for (const issue of orphaned) {\n output += `- ${issue.description}\\n`;\n }\n output += '\\n';\n }\n\n // Dependency tree visualization\n output += `## 🌳 Dependency Overview\\n\\n`;\n output += `*Top files by dependency count:*\\n\\n`;\n \n const sorted = [...graph.files.values()]\n .sort((a, b) => b.dependents.length - a.dependents.length)\n .slice(0, 10);\n\n output += `| File | Imports | Imported By |\\n`;\n output += `|------|---------|-------------|\\n`;\n for (const node of sorted) {\n output += `| ${basename(node.relativePath)} | ${node.dependencies.length} | ${node.dependents.length} |\\n`;\n }\n\n return output;\n}\n\n","/**\n * Semantic Code Analyzer\n * \n * Parses code to understand its structure for AI analysis.\n * Focuses on:\n * 1. Function extraction - what functions exist, their parameters\n * 2. Route detection - API endpoints and their methods\n * 3. Data flow indicators - sources (user input) and sinks (dangerous ops)\n * 4. Framework detection - Express, Next.js, etc.\n * \n * This provides CONTEXT for AI analysis, not pattern-based detection.\n */\n\nimport { readFile } from 'fs/promises';\nimport { basename, relative } from 'path';\n\n/**\n * Parsed function information for AI context\n */\nexport interface ParsedFunction {\n name: string;\n file: string;\n startLine: number;\n endLine: number;\n params: string[];\n isAsync: boolean;\n isExported: boolean;\n body: string;\n hasUserInput: boolean;\n hasDatabaseOps: boolean;\n hasFileOps: boolean;\n hasAuth: boolean;\n}\n\n/**\n * Detected route/endpoint for AI context\n */\nexport interface DetectedRoute {\n method: 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'ALL';\n path: string;\n file: string;\n line: number;\n hasAuth: boolean;\n accessesBody: boolean;\n}\n\n/**\n * Code context summary for AI prompts\n */\nexport interface CodeContextSummary {\n framework: string;\n functions: ParsedFunction[];\n routes: DetectedRoute[];\n dataFlowIndicators: DataFlowIndicator[];\n}\n\nexport interface DataFlowIndicator {\n type: 'source' | 'sink';\n category: string;\n file: string;\n line: number;\n code: string;\n}\n\n/**\n * Legacy issue type for backwards compatibility\n */\nexport interface DataFlowIssue {\n type: 'taint-flow' | 'missing-validation' | 'auth-bypass' | 'race-condition' | 'business-logic';\n severity: 'critical' | 'serious' | 'moderate' | 'low';\n source: { file: string; line: number; code: string; symbol?: string };\n sink?: { file: string; line: number; code: string };\n description: string;\n exploit?: string;\n fix: string;\n confidence: number;\n}\n\n/**\n * Semantic Analyzer - Parses code structure for AI context\n */\nexport class SemanticAnalyzer {\n private functions: ParsedFunction[] = [];\n private routes: DetectedRoute[] = [];\n private dataFlowIndicators: DataFlowIndicator[] = [];\n private framework: string = 'unknown';\n \n /**\n * Analyze files and extract code structure for AI\n */\n async analyze(files: string[], rootDir: string): Promise<DataFlowIssue[]> {\n // Parse all files to understand structure\n for (const file of files) {\n try {\n const content = await readFile(file, 'utf-8');\n const relPath = relative(rootDir, file);\n \n this.detectFramework(content);\n this.parseFunctions(content, relPath);\n this.parseRoutes(content, relPath);\n this.extractDataFlowIndicators(content, relPath);\n } catch (e) {\n // Skip unreadable files\n }\n }\n \n // Generate AI-focused analysis summary (not pattern-based issues)\n // For backwards compatibility, we return minimal issues and let AI do the work\n return this.generateAIAnalysisHints();\n }\n\n /**\n * Detect the framework being used\n */\n private detectFramework(content: string): void {\n if (this.framework !== 'unknown') return;\n \n if (/from\\s+['\"]express['\"]|require\\s*\\(\\s*['\"]express['\"]\\s*\\)/.test(content)) {\n this.framework = 'Express';\n } else if (/from\\s+['\"]next|getServerSideProps|getStaticProps|NextRequest/.test(content)) {\n this.framework = 'Next.js';\n } else if (/from\\s+['\"]fastify['\"]/.test(content)) {\n this.framework = 'Fastify';\n } else if (/from\\s+['\"]koa['\"]/.test(content)) {\n this.framework = 'Koa';\n } else if (/from\\s+['\"]hono['\"]/.test(content)) {\n this.framework = 'Hono';\n }\n }\n\n /**\n * Parse functions from code\n */\n private parseFunctions(content: string, file: string): void {\n const lines = content.split('\\n');\n \n const funcPatterns = [\n /(?:export\\s+)?(?:async\\s+)?function\\s+(\\w+)\\s*\\(([^)]*)\\)/,\n /(?:export\\s+)?const\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\(([^)]*)\\)\\s*=>/,\n ];\n \n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n \n for (const pattern of funcPatterns) {\n const match = line.match(pattern);\n if (match) {\n const funcName = match[1]!;\n const params = match[2]?.split(',').map(p => p.trim().split(':')[0]?.trim() || '') || [];\n \n // Find function body\n const bodyLines: string[] = [];\n let braceCount = 0;\n let started = false;\n \n for (let j = i; j < Math.min(i + 100, lines.length); j++) {\n const bodyLine = lines[j] || '';\n bodyLines.push(bodyLine);\n \n for (const char of bodyLine) {\n if (char === '{') { braceCount++; started = true; }\n else if (char === '}') { braceCount--; }\n }\n \n if (started && braceCount === 0) break;\n }\n \n const body = bodyLines.join('\\n');\n \n this.functions.push({\n name: funcName,\n file,\n startLine: i + 1,\n endLine: i + bodyLines.length,\n params,\n isAsync: /async/.test(line),\n isExported: /export/.test(line),\n body,\n hasUserInput: /req\\.body|req\\.params|req\\.query|formData|searchParams/i.test(body),\n hasDatabaseOps: /prisma|sequelize|knex|mongodb|\\.query|\\.execute/i.test(body),\n hasFileOps: /readFile|writeFile|fs\\./i.test(body),\n hasAuth: /auth|session|jwt|token|password/i.test(body),\n });\n }\n }\n }\n }\n\n /**\n * Parse route handlers\n */\n private parseRoutes(content: string, file: string): void {\n const lines = content.split('\\n');\n \n const routePatterns = [\n /(?:app|router)\\.(get|post|put|delete|patch|all)\\s*\\(\\s*['\"]([^'\"]+)['\"]/i,\n /export\\s+(?:async\\s+)?function\\s+(GET|POST|PUT|DELETE|PATCH)/i,\n ];\n \n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n \n for (const pattern of routePatterns) {\n const match = line.match(pattern);\n if (match) {\n const method = match[1]!.toUpperCase() as DetectedRoute['method'];\n const path = match[2] || `/${basename(file).replace(/\\.[^.]+$/, '')}`;\n \n // Look ahead for auth and body access\n const contextLines = lines.slice(i, Math.min(i + 30, lines.length)).join('\\n');\n const hasAuth = /auth|protect|authenticate|session|jwt|bearer/i.test(line + contextLines);\n const accessesBody = /req\\.body|request\\.json\\(\\)|formData/i.test(contextLines);\n \n this.routes.push({\n method,\n path,\n file,\n line: i + 1,\n hasAuth,\n accessesBody,\n });\n }\n }\n }\n }\n\n /**\n * Extract data flow indicators (sources and sinks)\n */\n private extractDataFlowIndicators(content: string, file: string): void {\n const lines = content.split('\\n');\n \n // Sources - where untrusted data enters\n const sources = [\n { pattern: /req\\.body|req\\.params|req\\.query/, category: 'user-input' },\n { pattern: /searchParams|formData/, category: 'url-params' },\n { pattern: /request\\.json\\(\\)|request\\.text\\(\\)/, category: 'request-body' },\n { pattern: /document\\.location|window\\.location/, category: 'browser-url' },\n { pattern: /localStorage|sessionStorage/, category: 'client-storage' },\n ];\n \n // Sinks - where data goes that could be dangerous\n const sinks = [\n { pattern: /\\.query\\s*\\(|\\.execute\\s*\\(|\\.raw\\s*\\(/, category: 'database' },\n { pattern: /exec\\s*\\(|spawn\\s*\\(|execSync/, category: 'command' },\n { pattern: /innerHTML|outerHTML|dangerouslySetInnerHTML/, category: 'html' },\n { pattern: /eval\\s*\\(|new Function\\s*\\(/, category: 'code-eval' },\n { pattern: /writeFile|createWriteStream/, category: 'file-write' },\n { pattern: /redirect\\(|router\\.push\\(/, category: 'redirect' },\n ];\n \n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n \n for (const { pattern, category } of sources) {\n if (pattern.test(line)) {\n this.dataFlowIndicators.push({\n type: 'source',\n category,\n file,\n line: i + 1,\n code: line.trim().substring(0, 100),\n });\n }\n }\n \n for (const { pattern, category } of sinks) {\n if (pattern.test(line)) {\n this.dataFlowIndicators.push({\n type: 'sink',\n category,\n file,\n line: i + 1,\n code: line.trim().substring(0, 100),\n });\n }\n }\n }\n }\n\n /**\n * Generate hints for AI analysis based on parsed structure\n * Returns minimal issues - the real analysis is done by AI\n */\n private generateAIAnalysisHints(): DataFlowIssue[] {\n const hints: DataFlowIssue[] = [];\n \n // Check for routes without auth that access body (likely need review)\n for (const route of this.routes) {\n if (!route.hasAuth && route.accessesBody && ['POST', 'PUT', 'DELETE', 'PATCH'].includes(route.method)) {\n hints.push({\n type: 'auth-bypass',\n severity: 'serious',\n source: {\n file: route.file,\n line: route.line,\n code: `${route.method} ${route.path}`,\n symbol: route.path,\n },\n description: `${route.method} ${route.path} appears to lack authentication - needs AI review`,\n fix: 'Add authentication middleware or verify this endpoint should be public',\n confidence: 0.70,\n });\n }\n }\n \n // Check for functions with user input and database ops (potential injection)\n for (const func of this.functions) {\n if (func.hasUserInput && func.hasDatabaseOps) {\n hints.push({\n type: 'taint-flow',\n severity: 'moderate',\n source: {\n file: func.file,\n line: func.startLine,\n code: `function ${func.name}`,\n symbol: func.name,\n },\n description: `${func.name} has user input flowing to database - needs AI review`,\n fix: 'Verify parameterized queries are used',\n confidence: 0.60,\n });\n }\n }\n \n return hints;\n }\n\n /**\n * Get context summary for AI prompts\n */\n getContextSummary(): CodeContextSummary {\n return {\n framework: this.framework,\n functions: this.functions,\n routes: this.routes,\n dataFlowIndicators: this.dataFlowIndicators,\n };\n }\n\n /**\n * Get analysis summary\n */\n getSummary(): {\n functionsAnalyzed: number;\n routesFound: number;\n authPatternsFound: number;\n framework: string;\n } {\n const authFunctions = this.functions.filter(f => f.hasAuth).length;\n return {\n functionsAnalyzed: this.functions.length,\n routesFound: this.routes.length,\n authPatternsFound: authFunctions,\n framework: this.framework,\n };\n }\n\n /**\n * Generate AI prompt context from parsed code\n */\n generateAIPromptContext(): string {\n let context = `## Code Structure Analysis\\n\\n`;\n context += `**Framework:** ${this.framework}\\n`;\n context += `**Functions:** ${this.functions.length}\\n`;\n context += `**Routes:** ${this.routes.length}\\n\\n`;\n \n if (this.routes.length > 0) {\n context += `### API Endpoints\\n\\n`;\n for (const route of this.routes.slice(0, 10)) {\n const authBadge = route.hasAuth ? '[AUTH]' : '[!] No Auth';\n context += `- \\`${route.method} ${route.path}\\` ${authBadge} (${route.file}:${route.line})\\n`;\n }\n if (this.routes.length > 10) {\n context += `- *...and ${this.routes.length - 10} more routes*\\n`;\n }\n context += `\\n`;\n }\n \n if (this.dataFlowIndicators.length > 0) {\n const sources = this.dataFlowIndicators.filter(d => d.type === 'source');\n const sinks = this.dataFlowIndicators.filter(d => d.type === 'sink');\n \n if (sources.length > 0) {\n context += `### Data Sources (User Input)\\n\\n`;\n for (const source of sources.slice(0, 5)) {\n context += `- ${source.category} at ${source.file}:${source.line}\\n`;\n }\n context += `\\n`;\n }\n \n if (sinks.length > 0) {\n context += `### Sensitive Operations\\n\\n`;\n for (const sink of sinks.slice(0, 5)) {\n context += `- ${sink.category} at ${sink.file}:${sink.line}\\n`;\n }\n context += `\\n`;\n }\n }\n \n return context;\n }\n}\n\n/**\n * Format semantic analysis issues for output\n */\nexport function formatSemanticIssues(issues: DataFlowIssue[]): string {\n if (issues.length === 0) {\n return '\\n## ✅ No semantic issues found\\n\\n';\n }\n \n let output = '\\n' + '━'.repeat(60) + '\\n';\n output += '🧠 SEMANTIC ANALYSIS\\n';\n output += '━'.repeat(60) + '\\n\\n';\n output += '*The following areas were flagged for AI review:*\\n\\n';\n \n // Group by type\n const byType = new Map<DataFlowIssue['type'], DataFlowIssue[]>();\n for (const issue of issues) {\n if (!byType.has(issue.type)) byType.set(issue.type, []);\n byType.get(issue.type)!.push(issue);\n }\n \n const typeLabels: Record<DataFlowIssue['type'], string> = {\n 'taint-flow': 'Data Flow Vulnerabilities',\n 'missing-validation': 'Missing Input Validation',\n 'auth-bypass': 'Authentication Issues',\n 'race-condition': 'Race Conditions',\n 'business-logic': 'Business Logic Flaws',\n };\n \n for (const [type, typeIssues] of byType) {\n output += `### ${typeLabels[type]} (${typeIssues.length})\\n\\n`;\n \n for (const issue of typeIssues.slice(0, 5)) {\n const icon = { critical: '🔴', serious: '🟠', moderate: '🟡', low: '🔵' }[issue.severity];\n output += `${icon} **${issue.description}**\\n`;\n output += ` 📍 \\`${basename(issue.source.file)}:${issue.source.line}\\`\\n`;\n output += ` 🔧 ${issue.fix}\\n\\n`;\n }\n \n if (typeIssues.length > 5) {\n output += ` *...and ${typeIssues.length - 5} more*\\n\\n`;\n }\n }\n \n return output;\n}\n","/**\n * Smart Issue Prioritizer\n * \n * Bugbot and linters dump ALL findings on you - overwhelming and noisy.\n * We're smarter. We:\n * \n * 1. DEDUPLICATE - Same issue in many files? Group it.\n * 2. PRIORITIZE BY EXPLOITABILITY - Not all \"critical\" issues are equal\n * 3. FILTER NOISE - Test files, generated code, vendor files\n * 4. FOCUS ON FIXES - What can actually be fixed vs. false positives\n * 5. CONTEXT MATTERS - Admin route without auth > marketing page without auth\n * \n * Result: 10 actionable items, not 10,000 noise items.\n */\n\nimport type { Issue } from '../types/index.js';\nimport { basename } from 'path';\n\nexport interface PrioritizedIssue extends Issue {\n priority: number; // 1-100, higher = more important\n reason: string; // Why this priority\n groupKey?: string; // For deduplication\n instanceCount?: number; // How many times this pattern appears\n}\n\nexport interface PrioritizationResult {\n critical: PrioritizedIssue[]; // MUST fix - actual exploitable vulnerabilities\n important: PrioritizedIssue[]; // SHOULD fix - real issues with lower risk\n advisory: PrioritizedIssue[]; // COULD fix - good practices\n noise: number; // Count of filtered items\n summary: string;\n}\n\ninterface DeduplicationGroup {\n key: string;\n issues: Issue[];\n representative: Issue;\n}\n\n/**\n * Smart prioritization of issues\n */\nexport function prioritizeIssues(issues: Issue[]): PrioritizationResult {\n // Step 1: Filter out noise\n const { filtered, noiseCount } = filterNoise(issues);\n \n // Step 2: Deduplicate similar issues\n const deduplicated = deduplicateIssues(filtered);\n \n // Step 3: Score each issue\n const scored = deduplicated.map(scoreIssue);\n \n // Step 4: Sort by priority\n const sorted = scored.sort((a, b) => b.priority - a.priority);\n \n // Step 5: Categorize\n const critical = sorted.filter(i => i.priority >= 80);\n const important = sorted.filter(i => i.priority >= 50 && i.priority < 80);\n const advisory = sorted.filter(i => i.priority < 50);\n \n // Step 6: Generate summary\n const summary = generateSummary(critical, important, advisory, noiseCount);\n \n return {\n critical: critical.slice(0, 10), // Top 10 critical\n important: important.slice(0, 20), // Top 20 important\n advisory: advisory.slice(0, 30), // Top 30 advisory\n noise: noiseCount,\n summary,\n };\n}\n\n/**\n * Filter out noise - things that aren't real issues\n */\nfunction filterNoise(issues: Issue[]): { filtered: Issue[]; noiseCount: number } {\n const filtered: Issue[] = [];\n let noiseCount = 0;\n \n for (const issue of issues) {\n // Skip if clearly noise\n if (isNoise(issue)) {\n noiseCount++;\n continue;\n }\n filtered.push(issue);\n }\n \n return { filtered, noiseCount };\n}\n\n/**\n * Determine if an issue is noise\n */\nfunction isNoise(issue: Issue): boolean {\n const file = issue.file.toLowerCase();\n const issueText = `${issue.issue} ${issue.fix}`.toLowerCase();\n \n // ============================================\n // ALWAYS NOISE: Files we should never report on\n // ============================================\n \n // Signature/pattern files - never flag the scanner's own definitions\n if (file.includes('signature') || \n file.includes('patterns') ||\n file.includes('vulnerability-signatures')) {\n return true;\n }\n \n // Generated/vendor files\n if (file.includes('node_modules') ||\n file.includes('vendor') ||\n file.includes('.min.') ||\n file.includes('bundle') ||\n file.includes('dist/') ||\n file.includes('build/') ||\n file.includes('.generated.')) {\n return true;\n }\n \n // Lock files\n if (file.includes('package-lock') || \n file.includes('yarn.lock') || \n file.includes('pnpm-lock') ||\n file.includes('shrinkwrap')) {\n return true;\n }\n \n // Type definition files\n if (file.endsWith('.d.ts')) {\n return true;\n }\n \n // ============================================\n // TEST FILES: Aggressive filtering\n // ============================================\n const isTestFile = file.includes('.test.') || \n file.includes('.spec.') || \n file.includes('__tests__') ||\n file.includes('/test/') ||\n file.includes('/tests/') ||\n file.includes('fixture') ||\n file.includes('mock');\n \n if (isTestFile) {\n // Only keep test file issues if they're REAL exposed secrets\n // (not test fixtures designed to test the scanner)\n if (issueText.includes('hardcoded') || issueText.includes('secret')) {\n // Skip if it looks like test data\n if (issueText.includes('test') || \n issueText.includes('mock') ||\n issueText.includes('fake') ||\n issueText.includes('dummy') ||\n issueText.includes('example') ||\n issueText.includes('sample') ||\n issueText.includes('fixture')) {\n return true;\n }\n // Skip generic password patterns in tests\n if (/password.*123|super.*secret|sk-[a-z0-9]{10,30}$/i.test(issueText)) {\n return true;\n }\n }\n // All other test file issues are noise\n return true;\n }\n \n // ============================================\n // CONTEXT-BASED NOISE\n // ============================================\n \n // Config files for low-priority issues\n if ((file.includes('.config.') || file.includes('rc.') || file.includes('config/')) && \n (issue.severity === 'low' || issue.severity === 'moderate')) {\n return true;\n }\n \n // Example/demo files\n if (file.includes('example') || \n file.includes('demo') || \n file.includes('sample') ||\n file.includes('tutorial')) {\n return true;\n }\n \n // Very low confidence\n if (issue.confidence < 0.6) {\n return true;\n }\n \n // ============================================\n // ISSUE-BASED NOISE: False positive patterns\n // ============================================\n \n // TypeScript errors that aren't real (module resolution, lib issues)\n if (issueText.includes('cannot find module') ||\n issueText.includes('cannot find name') ||\n issueText.includes('modulresolution') ||\n issueText.includes('target library')) {\n // These are usually config issues, not code issues\n return true;\n }\n \n // Console.log warnings in non-production contexts\n if (issueText.includes('console.log') && \n (file.includes('cli') || file.includes('script') || file.includes('debug'))) {\n return true;\n }\n \n // Math.random in non-security contexts\n if (issueText.includes('math.random') && \n !file.includes('auth') && \n !file.includes('token') && \n !file.includes('session') &&\n !file.includes('crypto')) {\n return true;\n }\n \n return false;\n}\n\n/**\n * Deduplicate similar issues - group same pattern across files\n */\nfunction deduplicateIssues(issues: Issue[]): Issue[] {\n const groups = new Map<string, DeduplicationGroup>();\n \n for (const issue of issues) {\n // Create a grouping key based on issue type, not location\n const key = createGroupKey(issue);\n \n if (!groups.has(key)) {\n groups.set(key, {\n key,\n issues: [],\n representative: issue,\n });\n }\n \n const group = groups.get(key)!;\n group.issues.push(issue);\n \n // Keep the most severe instance as representative\n if (severityRank(issue.severity) > severityRank(group.representative.severity)) {\n group.representative = issue;\n }\n }\n \n // Return representatives with instance counts\n const deduplicated: Issue[] = [];\n for (const group of groups.values()) {\n const rep = { ...group.representative };\n \n // Add count to the issue text if there are multiple\n if (group.issues.length > 1) {\n rep.issue = `${rep.issue} (${group.issues.length} instances)`;\n }\n \n deduplicated.push(rep);\n }\n \n return deduplicated;\n}\n\n/**\n * Create a grouping key for deduplication\n */\nfunction createGroupKey(issue: Issue): string {\n // Group by: agent + issue type + fix suggestion\n // This groups same recommendations across files\n const issueType = issue.issue.replace(/['\"`][^'\"`]*['\"`]/g, '').trim();\n const fixType = issue.fix.replace(/['\"`][^'\"`]*['\"`]/g, '').substring(0, 50);\n return `${issue.agent}:${issueType}:${fixType}`;\n}\n\n/**\n * Score an issue for priority\n */\nfunction scoreIssue(issue: Issue): PrioritizedIssue {\n let priority = 0;\n const reasons: string[] = [];\n \n // Base score from severity\n const severityScores = { critical: 70, serious: 50, moderate: 30, low: 10 };\n priority += severityScores[issue.severity];\n reasons.push(`${issue.severity} severity`);\n \n // Boost for exploitability indicators\n const exploitablePatterns = [\n { pattern: /injection|exec|eval|command/i, boost: 20, reason: 'directly exploitable' },\n { pattern: /auth.*bypass|missing.*auth|no.*auth/i, boost: 15, reason: 'auth bypass' },\n { pattern: /secret|credential|password|api.?key/i, boost: 15, reason: 'credential exposure' },\n { pattern: /xss|script.*inject/i, boost: 12, reason: 'XSS vulnerability' },\n { pattern: /remote|rce|arbitrary/i, boost: 20, reason: 'remote code execution' },\n ];\n \n for (const { pattern, boost, reason } of exploitablePatterns) {\n if (pattern.test(issue.issue) || pattern.test(issue.fix)) {\n priority += boost;\n reasons.push(reason);\n break; // Only apply biggest boost\n }\n }\n \n // Boost for sensitive file contexts\n const file = issue.file.toLowerCase();\n if (file.includes('auth') || file.includes('login') || file.includes('session')) {\n priority += 10;\n reasons.push('auth-related file');\n }\n if (file.includes('payment') || file.includes('billing') || file.includes('stripe')) {\n priority += 10;\n reasons.push('payment-related file');\n }\n if (file.includes('admin') || file.includes('dashboard')) {\n priority += 8;\n reasons.push('admin area');\n }\n if (file.includes('api/') || file.includes('routes/')) {\n priority += 5;\n reasons.push('API endpoint');\n }\n \n // Reduce for less important contexts\n if (file.includes('test') || file.includes('spec') || file.includes('mock')) {\n priority -= 15;\n reasons.push('test file (lower priority)');\n }\n if (file.includes('example') || file.includes('demo') || file.includes('sample')) {\n priority -= 10;\n reasons.push('example code');\n }\n \n // Boost for auto-fixable issues\n if (issue.autoFixable) {\n priority += 5;\n reasons.push('auto-fixable');\n }\n \n // Boost for high confidence\n if (issue.confidence >= 0.9) {\n priority += 5;\n reasons.push('high confidence');\n } else if (issue.confidence < 0.7) {\n priority -= 10;\n reasons.push('low confidence');\n }\n \n // Cap at 100\n priority = Math.min(100, Math.max(0, priority));\n \n return {\n ...issue,\n priority,\n reason: reasons.slice(0, 3).join(', '),\n groupKey: createGroupKey(issue),\n };\n}\n\n/**\n * Get numeric rank for severity\n */\nfunction severityRank(severity: Issue['severity']): number {\n const ranks = { critical: 4, serious: 3, moderate: 2, low: 1 };\n return ranks[severity];\n}\n\n/**\n * Generate a human-readable summary\n */\nfunction generateSummary(\n critical: PrioritizedIssue[],\n important: PrioritizedIssue[],\n advisory: PrioritizedIssue[],\n noiseCount: number\n): string {\n let summary = '\\n## SMART PRIORITIZATION\\n\\n';\n \n summary += '*Trie Agent filtered noise and prioritized by real-world exploitability*\\n\\n';\n \n // Top actions\n if (critical.length > 0) {\n summary += `### 🔴 ${critical.length} Critical Actions Required\\n\\n`;\n for (const issue of critical.slice(0, 5)) {\n summary += `1. **${issue.issue}** - ${issue.reason}\\n`;\n summary += ` 📍 \\`${basename(issue.file)}:${issue.line || '?'}\\`\\n`;\n summary += ` 🔧 ${issue.fix}\\n\\n`;\n }\n if (critical.length > 5) {\n summary += ` *...and ${critical.length - 5} more critical issues*\\n\\n`;\n }\n }\n \n if (important.length > 0) {\n summary += `### 🟠 ${important.length} Important Improvements\\n\\n`;\n for (const issue of important.slice(0, 3)) {\n summary += `- **${issue.issue}** (${issue.reason})\\n`;\n }\n if (important.length > 3) {\n summary += `- *...and ${important.length - 3} more*\\n`;\n }\n summary += '\\n';\n }\n \n // Noise filtered\n if (noiseCount > 0) {\n summary += `### 🔇 ${noiseCount} items filtered as noise\\n\\n`;\n summary += `*Test files, generated code, low-confidence findings*\\n\\n`;\n }\n \n // Comparison callout\n summary += `---\\n`;\n summary += `*💡 Other tools would show you ${critical.length + important.length + advisory.length + noiseCount} issues.*\\n`;\n summary += `*Trie Agent shows you the ${critical.length + Math.min(important.length, 10)} that actually matter.*\\n`;\n \n return summary;\n}\n\n/**\n * Format prioritized results for output\n */\nexport function formatPrioritizedResults(result: PrioritizationResult): string {\n return result.summary;\n}\n","/**\n * Attack Surface Analyzer\n * \n * This is what REAL security teams want - not a list of 10,000 lint errors,\n * but a clear picture of:\n * \n * 1. What endpoints are exposed?\n * 2. What data do they accept?\n * 3. What's the blast radius if compromised?\n * 4. What's protecting each entry point?\n * \n * This is intelligence, not just scanning.\n */\n\nimport { readFile } from 'fs/promises';\nimport { basename, relative } from 'path';\n\nexport interface AttackSurface {\n endpoints: Endpoint[];\n dataFlows: DataFlow[];\n authBoundaries: AuthBoundary[];\n sensitiveAssets: SensitiveAsset[];\n summary: AttackSurfaceSummary;\n}\n\nexport interface Endpoint {\n method: string;\n path: string;\n file: string;\n line: number;\n accepts: string[]; // What data types it accepts\n returns: string[]; // What it returns\n authRequired: boolean;\n authType?: string; // 'jwt', 'session', 'api-key', etc\n rateLimit: boolean;\n inputValidation: boolean;\n riskScore: number; // 1-10\n riskFactors: string[];\n}\n\nexport interface DataFlow {\n source: string; // Where data comes from\n destination: string; // Where data goes\n dataType: string; // 'user-input', 'pii', 'credentials', etc\n encrypted: boolean;\n logged: boolean;\n file: string;\n risk: 'high' | 'medium' | 'low';\n}\n\nexport interface AuthBoundary {\n name: string;\n type: 'middleware' | 'check' | 'decorator';\n file: string;\n line: number;\n protects: string[]; // What endpoints/resources it protects\n bypassRisk: string[]; // Potential bypass scenarios\n}\n\nexport interface SensitiveAsset {\n type: 'database' | 'api-key' | 'pii' | 'payment' | 'session';\n location: string;\n accessPoints: string[]; // What can access this\n protection: string[]; // What protections exist\n}\n\nexport interface AttackSurfaceSummary {\n totalEndpoints: number;\n publicEndpoints: number;\n authProtectedEndpoints: number;\n unprotectedSensitiveEndpoints: number;\n dataFlowsWithPII: number;\n riskScore: number; // Overall 1-100\n topRisks: string[];\n}\n\n/**\n * Analyze the attack surface of a codebase\n */\nexport class AttackSurfaceAnalyzer {\n private endpoints: Endpoint[] = [];\n private dataFlows: DataFlow[] = [];\n private authBoundaries: AuthBoundary[] = [];\n private sensitiveAssets: SensitiveAsset[] = [];\n \n async analyze(files: string[], rootDir: string): Promise<AttackSurface> {\n // Parse all files\n for (const file of files) {\n try {\n const content = await readFile(file, 'utf-8');\n const relPath = relative(rootDir, file);\n \n this.findEndpoints(content, relPath);\n this.findDataFlows(content, relPath);\n this.findAuthBoundaries(content, relPath);\n this.findSensitiveAssets(content, relPath);\n } catch (e) {\n // Skip unreadable files\n }\n }\n \n // Calculate risk scores\n this.calculateRiskScores();\n \n // Generate summary\n const summary = this.generateSummary();\n \n return {\n endpoints: this.endpoints,\n dataFlows: this.dataFlows,\n authBoundaries: this.authBoundaries,\n sensitiveAssets: this.sensitiveAssets,\n summary,\n };\n }\n\n private findEndpoints(content: string, file: string): void {\n const lines = content.split('\\n');\n \n // Express/Fastify routes\n const routePatterns = [\n /(?:app|router)\\.(get|post|put|delete|patch|all)\\s*\\(\\s*['\"]([^'\"]+)['\"]/gi,\n /export\\s+(?:async\\s+)?function\\s+(GET|POST|PUT|DELETE|PATCH)\\s*\\(/gi,\n ];\n \n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n \n for (const pattern of routePatterns) {\n pattern.lastIndex = 0;\n const match = pattern.exec(line);\n if (match) {\n const method = match[1]!.toUpperCase();\n const path = match[2] || `/${basename(file).replace(/\\.[^.]+$/, '')}`;\n \n // Analyze the route context\n const contextLines = lines.slice(i, Math.min(i + 50, lines.length)).join('\\n');\n const authType = this.detectAuthType(line, contextLines);\n \n const endpoint: Endpoint = {\n method,\n path,\n file,\n line: i + 1,\n accepts: this.detectAcceptedData(contextLines),\n returns: this.detectReturnedData(contextLines),\n authRequired: this.detectAuth(line, contextLines),\n ...(authType && { authType }),\n rateLimit: /rateLimit|throttle/i.test(contextLines),\n inputValidation: /validate|schema|zod|yup|joi/i.test(contextLines),\n riskScore: 0, // Calculated later\n riskFactors: [],\n };\n \n this.endpoints.push(endpoint);\n }\n }\n }\n }\n\n private detectAcceptedData(context: string): string[] {\n const accepts: string[] = [];\n \n if (/req\\.body|request\\.json|formData/i.test(context)) {\n accepts.push('json-body');\n }\n if (/req\\.query|searchParams/i.test(context)) {\n accepts.push('query-params');\n }\n if (/req\\.params|params\\./i.test(context)) {\n accepts.push('url-params');\n }\n if (/req\\.file|multipart|upload/i.test(context)) {\n accepts.push('file-upload');\n }\n if (/req\\.headers|authorization/i.test(context)) {\n accepts.push('headers');\n }\n if (/req\\.cookies/i.test(context)) {\n accepts.push('cookies');\n }\n \n return accepts;\n }\n\n private detectReturnedData(context: string): string[] {\n const returns: string[] = [];\n \n if (/user|profile|account/i.test(context) && /res\\.json|return.*json/i.test(context)) {\n returns.push('user-data');\n }\n if (/password|secret|key|token/i.test(context)) {\n returns.push('credentials');\n }\n if (/redirect/i.test(context)) {\n returns.push('redirect');\n }\n if (/render|html/i.test(context)) {\n returns.push('html');\n }\n \n return returns;\n }\n\n private detectAuth(routeLine: string, context: string): boolean {\n return /auth|protect|session|jwt|bearer|verify/i.test(routeLine) ||\n /req\\.user|session\\.|isAuthenticated/i.test(context);\n }\n\n private detectAuthType(routeLine: string, context: string): string | undefined {\n if (/jwt|bearer/i.test(routeLine + context)) return 'jwt';\n if (/session/i.test(routeLine + context)) return 'session';\n if (/apiKey|api[_-]?key/i.test(routeLine + context)) return 'api-key';\n if (/oauth/i.test(routeLine + context)) return 'oauth';\n return undefined;\n }\n\n private findDataFlows(content: string, file: string): void {\n const lines = content.split('\\n');\n \n // Track data from sources to sinks\n const sources = [\n { pattern: /req\\.body/g, type: 'user-input' },\n { pattern: /req\\.query/g, type: 'user-input' },\n { pattern: /email|phone|address|name/gi, type: 'pii' },\n { pattern: /password|secret|token/gi, type: 'credentials' },\n { pattern: /credit|card|payment/gi, type: 'payment' },\n ];\n \n const sinks = [\n { pattern: /\\.query\\(|prisma\\.|mongoose\\./g, dest: 'database' },\n { pattern: /console\\.log|logger\\./g, dest: 'logs' },\n { pattern: /res\\.json|res\\.send/g, dest: 'response' },\n { pattern: /fetch\\(|axios\\./g, dest: 'external-api' },\n ];\n \n for (const source of sources) {\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n if (source.pattern.test(line)) {\n source.pattern.lastIndex = 0;\n \n // Look for where this data goes in nearby lines\n const context = lines.slice(i, Math.min(i + 20, lines.length)).join('\\n');\n \n for (const sink of sinks) {\n if (sink.pattern.test(context)) {\n sink.pattern.lastIndex = 0;\n \n this.dataFlows.push({\n source: source.type,\n destination: sink.dest,\n dataType: source.type,\n encrypted: /encrypt|hash|bcrypt/i.test(context),\n logged: /console|logger/i.test(context),\n file,\n risk: this.assessDataFlowRisk(source.type, sink.dest),\n });\n }\n }\n }\n }\n }\n }\n\n private assessDataFlowRisk(sourceType: string, destType: string): 'high' | 'medium' | 'low' {\n // Credentials to logs = critical\n if (sourceType === 'credentials' && destType === 'logs') return 'high';\n // PII to external = high\n if (sourceType === 'pii' && destType === 'external-api') return 'high';\n // Payment data anywhere sensitive = high\n if (sourceType === 'payment') return 'high';\n // User input to database = medium (could be injection)\n if (sourceType === 'user-input' && destType === 'database') return 'medium';\n return 'low';\n }\n\n private findAuthBoundaries(content: string, file: string): void {\n const lines = content.split('\\n');\n \n const authPatterns = [\n { pattern: /export\\s+(?:const|function)\\s+(\\w*auth\\w*)/i, type: 'middleware' as const },\n { pattern: /(?:const|function)\\s+(\\w*protect\\w*|\\w*verify\\w*)/i, type: 'middleware' as const },\n { pattern: /@(?:Auth|Authorized|Protected)\\s*\\(/i, type: 'decorator' as const },\n ];\n \n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n \n for (const { pattern, type } of authPatterns) {\n const match = line.match(pattern);\n if (match) {\n const context = lines.slice(i, Math.min(i + 30, lines.length)).join('\\n');\n \n this.authBoundaries.push({\n name: match[1] || 'auth',\n type,\n file,\n line: i + 1,\n protects: this.findProtectedRoutes(match[1] || 'auth'),\n bypassRisk: this.assessBypassRisks(context),\n });\n }\n }\n }\n }\n\n private findProtectedRoutes(_authName: string): string[] {\n return this.endpoints\n .filter(e => e.authType || e.authRequired)\n .map(e => `${e.method} ${e.path}`);\n }\n\n private assessBypassRisks(context: string): string[] {\n const risks: string[] = [];\n \n if (/req\\.query|req\\.params/.test(context) && !/validate|sanitize/.test(context)) {\n risks.push('Input not validated before auth check');\n }\n if (/skip|bypass|disable/.test(context)) {\n risks.push('Bypass logic detected');\n }\n if (!/throw|return.*401|unauthorized/i.test(context)) {\n risks.push('No clear rejection path');\n }\n \n return risks;\n }\n\n private findSensitiveAssets(content: string, file: string): void {\n // Find database connections\n if (/DATABASE_URL|mongodb|postgres|mysql/i.test(content)) {\n this.sensitiveAssets.push({\n type: 'database',\n location: file,\n accessPoints: this.findAccessPoints('database', file),\n protection: this.findProtections(content, 'database'),\n });\n }\n \n // Find API keys\n if (/API_KEY|OPENAI|STRIPE|SENDGRID/i.test(content)) {\n this.sensitiveAssets.push({\n type: 'api-key',\n location: file,\n accessPoints: ['environment-variable'],\n protection: this.findProtections(content, 'api-key'),\n });\n }\n \n // Find PII storage\n if (/email|phone|ssn|address/i.test(content) && /schema|model|table/i.test(content)) {\n this.sensitiveAssets.push({\n type: 'pii',\n location: file,\n accessPoints: this.findAccessPoints('pii', file),\n protection: this.findProtections(content, 'pii'),\n });\n }\n }\n\n private findAccessPoints(_assetType: string, file: string): string[] {\n return this.endpoints\n .filter(e => e.file === file || e.returns.some(r => r.includes('user') || r.includes('data')))\n .map(e => `${e.method} ${e.path}`);\n }\n\n private findProtections(content: string, _assetType: string): string[] {\n const protections: string[] = [];\n \n if (/encrypt/i.test(content)) protections.push('encryption');\n if (/hash|bcrypt/i.test(content)) protections.push('hashing');\n if (/auth|protect/i.test(content)) protections.push('auth-required');\n if (/rateLimit|throttle/i.test(content)) protections.push('rate-limiting');\n if (/validate|sanitize/i.test(content)) protections.push('input-validation');\n \n return protections;\n }\n\n private calculateRiskScores(): void {\n for (const endpoint of this.endpoints) {\n let risk = 0;\n const factors: string[] = [];\n \n // Method risks\n if (['POST', 'PUT', 'DELETE', 'PATCH'].includes(endpoint.method)) {\n risk += 2;\n factors.push('mutating method');\n }\n \n // Auth risks\n if (!endpoint.authRequired) {\n risk += 3;\n factors.push('no auth required');\n }\n \n // Input risks\n if (endpoint.accepts.includes('file-upload')) {\n risk += 2;\n factors.push('accepts file upload');\n }\n if (endpoint.accepts.includes('json-body') && !endpoint.inputValidation) {\n risk += 2;\n factors.push('no input validation');\n }\n \n // Path risks\n if (/admin|user|account|payment|billing/i.test(endpoint.path)) {\n risk += 2;\n factors.push('sensitive path');\n }\n \n // Rate limiting\n if (!endpoint.rateLimit && endpoint.accepts.length > 0) {\n risk += 1;\n factors.push('no rate limiting');\n }\n \n endpoint.riskScore = Math.min(10, risk);\n endpoint.riskFactors = factors;\n }\n }\n\n private generateSummary(): AttackSurfaceSummary {\n const publicEndpoints = this.endpoints.filter(e => !e.authRequired);\n const sensitiveUnprotected = this.endpoints.filter(e => \n !e.authRequired && (\n /admin|user|payment|billing|account/i.test(e.path) ||\n e.accepts.includes('json-body')\n )\n );\n const piiFlows = this.dataFlows.filter(f => f.dataType === 'pii' || f.dataType === 'credentials');\n \n // Calculate overall risk\n let overallRisk = 0;\n overallRisk += publicEndpoints.length * 2;\n overallRisk += sensitiveUnprotected.length * 10;\n overallRisk += piiFlows.filter(f => f.risk === 'high').length * 15;\n overallRisk = Math.min(100, overallRisk);\n \n const topRisks: string[] = [];\n if (sensitiveUnprotected.length > 0) {\n topRisks.push(`${sensitiveUnprotected.length} sensitive endpoints without auth`);\n }\n if (piiFlows.filter(f => !f.encrypted).length > 0) {\n topRisks.push('PII data flows without encryption');\n }\n if (this.endpoints.filter(e => !e.inputValidation && e.accepts.length > 0).length > 3) {\n topRisks.push('Multiple endpoints without input validation');\n }\n \n return {\n totalEndpoints: this.endpoints.length,\n publicEndpoints: publicEndpoints.length,\n authProtectedEndpoints: this.endpoints.length - publicEndpoints.length,\n unprotectedSensitiveEndpoints: sensitiveUnprotected.length,\n dataFlowsWithPII: piiFlows.length,\n riskScore: overallRisk,\n topRisks,\n };\n }\n}\n\n/**\n * Format attack surface analysis for output\n */\nexport function formatAttackSurface(surface: AttackSurface): string {\n if (surface.endpoints.length === 0) {\n return '';\n }\n \n let output = '\\n' + '━'.repeat(60) + '\\n';\n output += 'ATTACK SURFACE ANALYSIS\\n';\n output += '━'.repeat(60) + '\\n\\n';\n \n output += `## Summary\\n\\n`;\n output += `| Metric | Value |\\n`;\n output += `|--------|-------|\\n`;\n output += `| Total Endpoints | ${surface.summary.totalEndpoints} |\\n`;\n output += `| Public (No Auth) | ${surface.summary.publicEndpoints} |\\n`;\n output += `| Auth Protected | ${surface.summary.authProtectedEndpoints} |\\n`;\n output += `| [!] Unprotected Sensitive | ${surface.summary.unprotectedSensitiveEndpoints} |\\n`;\n output += `| PII Data Flows | ${surface.summary.dataFlowsWithPII} |\\n`;\n output += `| **Risk Score** | **${surface.summary.riskScore}/100** |\\n\\n`;\n \n if (surface.summary.topRisks.length > 0) {\n output += `## Top Risks\\n\\n`;\n for (const risk of surface.summary.topRisks) {\n output += `- ${risk}\\n`;\n }\n output += '\\n';\n }\n \n // High risk endpoints\n const highRiskEndpoints = surface.endpoints\n .filter(e => e.riskScore >= 6)\n .sort((a, b) => b.riskScore - a.riskScore);\n \n if (highRiskEndpoints.length > 0) {\n output += `## 🔴 High-Risk Endpoints\\n\\n`;\n for (const ep of highRiskEndpoints.slice(0, 5)) {\n output += `### ${ep.method} ${ep.path}\\n`;\n output += `- 📍 \\`${ep.file}:${ep.line}\\`\\n`;\n output += `- Risk Score: ${ep.riskScore}/10\\n`;\n output += `- Auth: ${ep.authRequired ? `✅ ${ep.authType || 'required'}` : '❌ None'}\\n`;\n output += `- Accepts: ${ep.accepts.join(', ') || 'nothing'}\\n`;\n output += `- Risk Factors: ${ep.riskFactors.join(', ')}\\n\\n`;\n }\n }\n \n // Data flow risks\n const riskyFlows = surface.dataFlows.filter(f => f.risk === 'high');\n if (riskyFlows.length > 0) {\n output += `## 🔄 Risky Data Flows\\n\\n`;\n for (const flow of riskyFlows.slice(0, 5)) {\n output += `- **${flow.source}** → **${flow.destination}**\\n`;\n output += ` - Type: ${flow.dataType}\\n`;\n output += ` - Encrypted: ${flow.encrypted ? '✅' : '❌'}\\n`;\n output += ` - File: \\`${flow.file}\\`\\n\\n`;\n }\n }\n \n return output;\n}\n","/**\n * Code Symbol Index\n * \n * Uses a trie to index all code symbols (functions, classes, variables, exports)\n * for O(m) lookup where m = symbol name length.\n * \n * Benefits:\n * - Instant symbol lookup across entire codebase\n * - Fast autocomplete suggestions\n * - Cross-reference detection (unused exports, missing imports)\n * - Incremental updates when files change\n */\n\nimport { Trie } from './trie.js';\n\nexport interface SymbolInfo {\n name: string;\n type: 'function' | 'class' | 'variable' | 'interface' | 'type' | 'enum' | 'const' | 'method' | 'property' | 'export' | 'import';\n file: string;\n line: number;\n column: number;\n exported: boolean;\n async: boolean;\n signature?: string;\n jsDoc?: string;\n references: SymbolReference[];\n}\n\nexport interface SymbolReference {\n file: string;\n line: number;\n column: number;\n type: 'definition' | 'usage' | 'import' | 'export';\n}\n\nexport interface SymbolIndexStats {\n totalSymbols: number;\n byType: Record<string, number>;\n filesIndexed: number;\n exportedSymbols: number;\n unusedExports: string[];\n}\n\n/**\n * Code Symbol Index using Trie for fast lookups\n */\nexport class SymbolIndex {\n private symbolTrie: Trie<SymbolInfo[]>;\n private fileSymbols: Map<string, SymbolInfo[]>;\n private exportedSymbols: Set<string>;\n private importedSymbols: Map<string, Set<string>>; // file -> imported symbol names\n \n constructor() {\n this.symbolTrie = new Trie<SymbolInfo[]>();\n this.fileSymbols = new Map();\n this.exportedSymbols = new Set();\n this.importedSymbols = new Map();\n }\n\n /**\n * Index a file's symbols\n * O(n) where n = file content length\n */\n indexFile(filePath: string, content: string): void {\n // Remove old symbols from this file\n this.removeFile(filePath);\n \n const symbols: SymbolInfo[] = [];\n const lines = content.split('\\n');\n \n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n const lineNum = i + 1;\n \n // Extract various symbol types\n const extracted = [\n ...this.extractFunctions(line, lineNum, filePath),\n ...this.extractClasses(line, lineNum, filePath),\n ...this.extractVariables(line, lineNum, filePath),\n ...this.extractInterfaces(line, lineNum, filePath),\n ...this.extractTypes(line, lineNum, filePath),\n ...this.extractImports(line, lineNum, filePath),\n ];\n \n symbols.push(...extracted);\n }\n \n // Store symbols\n this.fileSymbols.set(filePath, symbols);\n \n // Add to trie\n for (const symbol of symbols) {\n const existing = this.symbolTrie.search(symbol.name);\n if (existing.found && existing.value) {\n existing.value.push(symbol);\n } else {\n this.symbolTrie.insert(symbol.name, [symbol]);\n }\n \n // Track exports\n if (symbol.exported) {\n this.exportedSymbols.add(`${filePath}:${symbol.name}`);\n }\n }\n }\n\n /**\n * Remove a file from the index\n * O(s) where s = number of symbols in file\n */\n removeFile(filePath: string): void {\n const symbols = this.fileSymbols.get(filePath) || [];\n \n for (const symbol of symbols) {\n const existing = this.symbolTrie.search(symbol.name);\n if (existing.found && existing.value) {\n const filtered = existing.value.filter(s => s.file !== filePath);\n if (filtered.length > 0) {\n this.symbolTrie.insert(symbol.name, filtered);\n }\n }\n \n this.exportedSymbols.delete(`${filePath}:${symbol.name}`);\n }\n \n this.fileSymbols.delete(filePath);\n this.importedSymbols.delete(filePath);\n }\n\n /**\n * Look up a symbol by name\n * O(m) where m = symbol name length\n */\n lookup(name: string): SymbolInfo[] {\n const result = this.symbolTrie.search(name);\n return result.found && result.value ? result.value : [];\n }\n\n /**\n * Find symbols with a given prefix (autocomplete)\n * O(p + n) where p = prefix length, n = number of matches\n */\n findWithPrefix(prefix: string): SymbolInfo[] {\n const patterns = this.symbolTrie.getWithPrefix(prefix);\n const symbols: SymbolInfo[] = [];\n \n for (const { value } of patterns) {\n if (value) {\n symbols.push(...value);\n }\n }\n \n return symbols;\n }\n\n /**\n * Get all symbols in a file\n * O(1)\n */\n getFileSymbols(filePath: string): SymbolInfo[] {\n return this.fileSymbols.get(filePath) || [];\n }\n\n /**\n * Find all references to a symbol\n * O(n) where n = total symbols (could be optimized with reverse index)\n */\n findReferences(name: string): SymbolReference[] {\n const symbols = this.lookup(name);\n const references: SymbolReference[] = [];\n \n for (const symbol of symbols) {\n references.push({\n file: symbol.file,\n line: symbol.line,\n column: symbol.column,\n type: symbol.exported ? 'export' : 'definition',\n });\n references.push(...symbol.references);\n }\n \n return references;\n }\n\n /**\n * Find unused exports\n * O(e) where e = number of exports\n */\n findUnusedExports(): Array<{ name: string; file: string; line: number }> {\n const unused: Array<{ name: string; file: string; line: number }> = [];\n \n // Collect all imported symbols\n const allImported = new Set<string>();\n for (const imports of this.importedSymbols.values()) {\n for (const imp of imports) {\n allImported.add(imp);\n }\n }\n \n // Check each export\n for (const [file, symbols] of this.fileSymbols) {\n for (const symbol of symbols) {\n if (symbol.exported && !allImported.has(symbol.name)) {\n // Skip index files and main entry points\n if (file.includes('index.') || file.includes('main.')) continue;\n \n unused.push({\n name: symbol.name,\n file,\n line: symbol.line,\n });\n }\n }\n }\n \n return unused;\n }\n\n /**\n * Get index statistics\n */\n getStats(): SymbolIndexStats {\n const byType: Record<string, number> = {};\n let totalSymbols = 0;\n \n for (const symbols of this.fileSymbols.values()) {\n for (const symbol of symbols) {\n totalSymbols++;\n byType[symbol.type] = (byType[symbol.type] || 0) + 1;\n }\n }\n \n const unusedExports = this.findUnusedExports();\n \n return {\n totalSymbols,\n byType,\n filesIndexed: this.fileSymbols.size,\n exportedSymbols: this.exportedSymbols.size,\n unusedExports: unusedExports.map(u => `${u.file}:${u.name}`),\n };\n }\n\n // ============================================\n // Symbol extraction methods\n // ============================================\n\n private extractFunctions(line: string, lineNum: number, file: string): SymbolInfo[] {\n const symbols: SymbolInfo[] = [];\n \n // export async function name()\n // function name()\n // async function name()\n const funcMatch = line.match(/^(\\s*)(export\\s+)?(async\\s+)?function\\s+(\\w+)\\s*\\(([^)]*)\\)/);\n if (funcMatch) {\n symbols.push({\n name: funcMatch[4]!,\n type: 'function',\n file,\n line: lineNum,\n column: (funcMatch[1]?.length || 0) + 1,\n exported: !!funcMatch[2],\n async: !!funcMatch[3],\n signature: `function ${funcMatch[4]}(${funcMatch[5]})`,\n references: [],\n });\n }\n \n // export const name = () => {}\n // const name = async () => {}\n const arrowMatch = line.match(/^(\\s*)(export\\s+)?(const|let|var)\\s+(\\w+)\\s*=\\s*(async\\s*)?\\(/);\n if (arrowMatch) {\n symbols.push({\n name: arrowMatch[4]!,\n type: 'function',\n file,\n line: lineNum,\n column: (arrowMatch[1]?.length || 0) + 1,\n exported: !!arrowMatch[2],\n async: !!arrowMatch[5],\n signature: `const ${arrowMatch[4]} = ${arrowMatch[5] || ''}(...)`,\n references: [],\n });\n }\n \n return symbols;\n }\n\n private extractClasses(line: string, lineNum: number, file: string): SymbolInfo[] {\n const symbols: SymbolInfo[] = [];\n \n // export class Name\n // class Name\n const classMatch = line.match(/^(\\s*)(export\\s+)?(abstract\\s+)?class\\s+(\\w+)/);\n if (classMatch) {\n symbols.push({\n name: classMatch[4]!,\n type: 'class',\n file,\n line: lineNum,\n column: (classMatch[1]?.length || 0) + 1,\n exported: !!classMatch[2],\n async: false,\n signature: `class ${classMatch[4]}`,\n references: [],\n });\n }\n \n return symbols;\n }\n\n private extractVariables(line: string, lineNum: number, file: string): SymbolInfo[] {\n const symbols: SymbolInfo[] = [];\n \n // Skip if it's a function (already handled)\n if (/=\\s*(async\\s*)?\\(/.test(line)) return symbols;\n \n // export const NAME = \n // const name = \n const varMatch = line.match(/^(\\s*)(export\\s+)?(const|let|var)\\s+(\\w+)\\s*=/);\n if (varMatch) {\n const name = varMatch[4]!;\n // Determine if it's a constant (UPPER_CASE) or variable\n const isConst = /^[A-Z][A-Z0-9_]*$/.test(name);\n \n symbols.push({\n name,\n type: isConst ? 'const' : 'variable',\n file,\n line: lineNum,\n column: (varMatch[1]?.length || 0) + 1,\n exported: !!varMatch[2],\n async: false,\n references: [],\n });\n }\n \n return symbols;\n }\n\n private extractInterfaces(line: string, lineNum: number, file: string): SymbolInfo[] {\n const symbols: SymbolInfo[] = [];\n \n // export interface Name\n // interface Name\n const interfaceMatch = line.match(/^(\\s*)(export\\s+)?interface\\s+(\\w+)/);\n if (interfaceMatch) {\n symbols.push({\n name: interfaceMatch[3]!,\n type: 'interface',\n file,\n line: lineNum,\n column: (interfaceMatch[1]?.length || 0) + 1,\n exported: !!interfaceMatch[2],\n async: false,\n references: [],\n });\n }\n \n return symbols;\n }\n\n private extractTypes(line: string, lineNum: number, file: string): SymbolInfo[] {\n const symbols: SymbolInfo[] = [];\n \n // export type Name = \n // type Name = \n const typeMatch = line.match(/^(\\s*)(export\\s+)?type\\s+(\\w+)\\s*=/);\n if (typeMatch) {\n symbols.push({\n name: typeMatch[3]!,\n type: 'type',\n file,\n line: lineNum,\n column: (typeMatch[1]?.length || 0) + 1,\n exported: !!typeMatch[2],\n async: false,\n references: [],\n });\n }\n \n // export enum Name\n const enumMatch = line.match(/^(\\s*)(export\\s+)?enum\\s+(\\w+)/);\n if (enumMatch) {\n symbols.push({\n name: enumMatch[3]!,\n type: 'enum',\n file,\n line: lineNum,\n column: (enumMatch[1]?.length || 0) + 1,\n exported: !!enumMatch[2],\n async: false,\n references: [],\n });\n }\n \n return symbols;\n }\n\n private extractImports(line: string, lineNum: number, file: string): SymbolInfo[] {\n const symbols: SymbolInfo[] = [];\n \n // import { a, b } from 'module'\n const namedImportMatch = line.match(/import\\s+\\{([^}]+)\\}\\s+from\\s+['\"]([^'\"]+)['\"]/);\n if (namedImportMatch) {\n const specifiers = namedImportMatch[1]!.split(',').map(s => {\n const parts = s.trim().split(/\\s+as\\s+/);\n return parts[parts.length - 1]!.trim();\n });\n \n // Track imports for this file\n if (!this.importedSymbols.has(file)) {\n this.importedSymbols.set(file, new Set());\n }\n for (const spec of specifiers) {\n this.importedSymbols.get(file)!.add(spec);\n \n symbols.push({\n name: spec,\n type: 'import',\n file,\n line: lineNum,\n column: 1,\n exported: false,\n async: false,\n signature: `import { ${spec} } from '${namedImportMatch[2]}'`,\n references: [],\n });\n }\n }\n \n // import Name from 'module'\n const defaultImportMatch = line.match(/import\\s+(\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/);\n if (defaultImportMatch && !line.includes('{')) {\n const name = defaultImportMatch[1]!;\n \n if (!this.importedSymbols.has(file)) {\n this.importedSymbols.set(file, new Set());\n }\n this.importedSymbols.get(file)!.add(name);\n \n symbols.push({\n name,\n type: 'import',\n file,\n line: lineNum,\n column: 1,\n exported: false,\n async: false,\n signature: `import ${name} from '${defaultImportMatch[2]}'`,\n references: [],\n });\n }\n \n return symbols;\n }\n\n /**\n * Serialize the index for caching\n */\n toJSON(): object {\n const files: Record<string, SymbolInfo[]> = {};\n for (const [file, symbols] of this.fileSymbols) {\n files[file] = symbols;\n }\n return { files };\n }\n\n /**\n * Load from serialized JSON\n */\n static fromJSON(data: { files: Record<string, SymbolInfo[]> }): SymbolIndex {\n const index = new SymbolIndex();\n \n for (const [file, symbols] of Object.entries(data.files)) {\n index.fileSymbols.set(file, symbols);\n \n for (const symbol of symbols) {\n const existing = index.symbolTrie.search(symbol.name);\n if (existing.found && existing.value) {\n existing.value.push(symbol);\n } else {\n index.symbolTrie.insert(symbol.name, [symbol]);\n }\n \n if (symbol.exported) {\n index.exportedSymbols.add(`${file}:${symbol.name}`);\n }\n \n if (symbol.type === 'import') {\n if (!index.importedSymbols.has(file)) {\n index.importedSymbols.set(file, new Set());\n }\n index.importedSymbols.get(file)!.add(symbol.name);\n }\n }\n }\n \n return index;\n }\n}\n\n// Global symbol index instance\nlet globalSymbolIndex: SymbolIndex | null = null;\n\nexport function getSymbolIndex(): SymbolIndex {\n if (!globalSymbolIndex) {\n globalSymbolIndex = new SymbolIndex();\n }\n return globalSymbolIndex;\n}\n\nexport function resetSymbolIndex(): void {\n globalSymbolIndex = new SymbolIndex();\n}\n\n","/**\n * Incremental Scanner\n * \n * Uses trie-based indexing for smart, incremental code scanning.\n * Only re-scans changed parts of the codebase.\n * \n * Benefits:\n * - O(c) scanning where c = changed lines, not entire file\n * - Maintains persistent index for instant lookups\n * - Caches vulnerability scans per file\n * - Tracks file hashes for change detection\n */\n\nimport { createHash } from 'crypto';\nimport { readFile, mkdir, stat } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { getTrieDirectory } from '../utils/workspace.js';\nimport { getSymbolIndex, SymbolIndex } from './symbol-index.js';\nimport { scanForVulnerabilities, VulnerabilityMatch, getVulnerabilityTrie } from './vulnerability-signatures.js';\nimport { isInteractiveMode } from '../utils/progress.js';\nimport { getChangedFilesSinceTimestamp, isGitRepo } from '../agent/git.js';\nimport { atomicWriteJSON } from '../utils/atomic-write.js';\n\n// Concurrency limit for parallel file scanning\nconst SCAN_CONCURRENCY = 10;\n\nexport interface FileState {\n path: string;\n hash: string;\n lastScanned: number;\n lineCount: number;\n vulnerabilities: VulnerabilityMatch[];\n symbolCount: number;\n // Fast pre-check fields (avoid hash computation if unchanged)\n mtime?: number;\n size?: number;\n}\n\nexport interface ScanCache {\n version: string;\n created: number;\n lastUpdated: number;\n files: Record<string, FileState>;\n // Git optimization: track last scan time for git-based change detection\n lastFullScanTime?: number;\n}\n\nexport interface IncrementalScanResult {\n filesScanned: number;\n filesSkipped: number;\n filesChanged: number;\n totalVulnerabilities: number;\n newVulnerabilities: VulnerabilityMatch[];\n resolvedVulnerabilities: VulnerabilityMatch[];\n scanTimeMs: number;\n cacheHitRate: number;\n}\n\nconst CACHE_VERSION = '1.1.0'; // Bumped for mtime/size pre-check + git optimization\nconst CACHE_FILE = '.trie-cache.json';\n\n/**\n * Incremental Scanner with trie-based caching\n */\nexport class IncrementalScanner {\n private cache: ScanCache;\n private symbolIndex: SymbolIndex;\n private cacheDir: string;\n private projectRoot: string;\n private dirty: boolean = false;\n private isGitRepoCache: boolean | null = null;\n\n constructor(projectRoot: string) {\n this.projectRoot = projectRoot;\n this.cacheDir = getTrieDirectory(projectRoot);\n this.symbolIndex = getSymbolIndex();\n this.cache = {\n version: CACHE_VERSION,\n created: Date.now(),\n lastUpdated: Date.now(),\n files: {},\n };\n }\n\n /**\n * Load cache from disk\n */\n async loadCache(): Promise<boolean> {\n const cachePath = join(this.cacheDir, CACHE_FILE);\n \n if (!existsSync(cachePath)) {\n return false;\n }\n\n try {\n const data = await readFile(cachePath, 'utf-8');\n const parsed = JSON.parse(data);\n \n // Version check\n if (parsed.version !== CACHE_VERSION) {\n if (!isInteractiveMode()) {\n console.error(' Cache version mismatch, rebuilding...');\n }\n return false;\n }\n \n this.cache = parsed;\n if (!isInteractiveMode()) {\n console.error(` ✅ Loaded cache with ${Object.keys(this.cache.files).length} files`);\n }\n return true;\n } catch (error) {\n if (!isInteractiveMode()) {\n console.error(' Failed to load cache, rebuilding...');\n }\n return false;\n }\n }\n\n /**\n * Save cache to disk using atomic write\n * \n * Uses temp file + rename pattern to prevent cache corruption\n * from interrupted writes.\n */\n async saveCache(): Promise<void> {\n if (!this.dirty) return;\n\n try {\n await mkdir(this.cacheDir, { recursive: true });\n const cachePath = join(this.cacheDir, CACHE_FILE);\n \n this.cache.lastUpdated = Date.now();\n \n // Use atomic write to prevent corruption\n await atomicWriteJSON(cachePath, this.cache);\n \n this.dirty = false;\n } catch (error) {\n if (!isInteractiveMode()) {\n console.error(' Failed to save cache');\n }\n }\n }\n\n /**\n * Compute file hash for change detection\n * O(n) where n = file size\n */\n private computeHash(content: string): string {\n return createHash('sha256').update(content).digest('hex').slice(0, 16);\n }\n\n /**\n * Fast pre-check using file stats (mtime + size)\n * Returns true if file might have changed (needs hash check)\n * Returns false if file definitely hasn't changed (skip hash)\n * O(1) - just a stat call, no file read\n */\n private async fastPreCheck(filePath: string): Promise<{ changed: boolean; stats?: { mtime: number; size: number } }> {\n const cached = this.cache.files[filePath];\n if (!cached || cached.mtime === undefined || cached.size === undefined) {\n // No cached stats, need to scan\n try {\n const stats = await stat(filePath);\n return { changed: true, stats: { mtime: stats.mtimeMs, size: stats.size } };\n } catch {\n return { changed: true };\n }\n }\n\n try {\n const stats = await stat(filePath);\n const currentMtime = stats.mtimeMs;\n const currentSize = stats.size;\n\n // If mtime and size match, file hasn't changed - skip hash computation\n if (currentMtime === cached.mtime && currentSize === cached.size) {\n return { changed: false, stats: { mtime: currentMtime, size: currentSize } };\n }\n\n return { changed: true, stats: { mtime: currentMtime, size: currentSize } };\n } catch {\n return { changed: true };\n }\n }\n\n /**\n * Check if this project is a git repo (cached)\n */\n private async checkIsGitRepo(): Promise<boolean> {\n if (this.isGitRepoCache !== null) return this.isGitRepoCache;\n this.isGitRepoCache = await isGitRepo(this.projectRoot);\n return this.isGitRepoCache;\n }\n\n /**\n * Get files changed since last scan using git (fast path)\n * Returns null if not a git repo or git detection fails\n */\n async getGitChangedFiles(): Promise<Set<string> | null> {\n if (!(await this.checkIsGitRepo())) return null;\n \n const lastScanTime = this.cache.lastFullScanTime;\n if (!lastScanTime) return null;\n\n try {\n const changedFiles = await getChangedFilesSinceTimestamp(this.projectRoot, lastScanTime);\n return changedFiles ? new Set(changedFiles) : null;\n } catch {\n return null;\n }\n }\n\n /**\n * Check if a file has changed since last scan\n * O(1) for cache lookup + O(n) for hash if needed\n */\n async hasFileChanged(filePath: string, content?: string): Promise<boolean> {\n const cached = this.cache.files[filePath];\n if (!cached) return true;\n\n if (!content) {\n try {\n content = await readFile(filePath, 'utf-8');\n } catch {\n return true;\n }\n }\n\n const currentHash = this.computeHash(content);\n return currentHash !== cached.hash;\n }\n\n /**\n * Scan a single file incrementally\n * Returns cached results if file unchanged\n * \n * Optimization layers:\n * 1. Fast pre-check (mtime + size) - O(1), avoids file read\n * 2. Hash comparison - O(n), only if pre-check fails\n */\n async scanFile(filePath: string, forceRescan: boolean = false): Promise<{\n vulnerabilities: VulnerabilityMatch[];\n fromCache: boolean;\n symbolCount: number;\n }> {\n const cached = this.cache.files[filePath];\n\n // Layer 1: Fast pre-check using mtime + size (avoids reading file content)\n if (!forceRescan && cached) {\n const preCheck = await this.fastPreCheck(filePath);\n if (!preCheck.changed) {\n // File stats unchanged - definitely same file, skip everything\n return {\n vulnerabilities: cached.vulnerabilities,\n fromCache: true,\n symbolCount: cached.symbolCount,\n };\n }\n }\n\n // Need to read file content\n let content: string;\n let fileStats: { mtime: number; size: number } | undefined;\n \n try {\n const stats = await stat(filePath);\n fileStats = { mtime: stats.mtimeMs, size: stats.size };\n content = await readFile(filePath, 'utf-8');\n } catch {\n return { vulnerabilities: [], fromCache: false, symbolCount: 0 };\n }\n\n // Layer 2: Hash comparison (in case mtime changed but content didn't)\n const hash = this.computeHash(content);\n if (!forceRescan && cached && cached.hash === hash) {\n // Content same, but update mtime/size for future fast pre-checks\n if (fileStats) {\n cached.mtime = fileStats.mtime;\n cached.size = fileStats.size;\n this.dirty = true;\n }\n return {\n vulnerabilities: cached.vulnerabilities,\n fromCache: true,\n symbolCount: cached.symbolCount,\n };\n }\n\n // Need to scan - file is new or changed\n const vulnerabilities = scanForVulnerabilities(content, filePath);\n \n // Index symbols\n this.symbolIndex.indexFile(filePath, content);\n const symbols = this.symbolIndex.getFileSymbols(filePath);\n\n // Update cache with mtime/size for future fast pre-checks\n this.cache.files[filePath] = {\n path: filePath,\n hash,\n lastScanned: Date.now(),\n lineCount: content.split('\\n').length,\n vulnerabilities,\n symbolCount: symbols.length,\n mtime: fileStats?.mtime,\n size: fileStats?.size,\n };\n this.dirty = true;\n\n return {\n vulnerabilities,\n fromCache: false,\n symbolCount: symbols.length,\n };\n }\n\n /**\n * Scan multiple files with incremental caching\n * \n * Optimizations:\n * 1. Git-based change detection (when available) - only scan changed files\n * 2. Parallel file scanning with concurrency limit\n * 3. Fast pre-check (mtime + size) per file\n */\n async scanFiles(\n filePaths: string[],\n forceRescan: boolean = false,\n onFileProgress?: (filePath: string, fromCache: boolean) => void\n ): Promise<IncrementalScanResult> {\n const startTime = Date.now();\n \n // Initialize vulnerability trie\n getVulnerabilityTrie();\n\n let filesScanned = 0;\n let filesSkipped = 0;\n let filesChanged = 0;\n const allVulnerabilities: VulnerabilityMatch[] = [];\n const newVulnerabilities: VulnerabilityMatch[] = [];\n const previousVulnerabilities = new Map<string, VulnerabilityMatch[]>();\n\n // Track previous state for comparison\n for (const [path, state] of Object.entries(this.cache.files)) {\n previousVulnerabilities.set(path, state.vulnerabilities);\n }\n\n // Optimization: Use git to detect changed files (fast path)\n // Add timeout to prevent hanging on slow git operations\n let gitChangedFiles: Set<string> | null = null;\n if (!forceRescan) {\n try {\n // Set a timeout for git operations (5 seconds max)\n const gitPromise = this.getGitChangedFiles();\n const timeoutPromise = new Promise<null>((resolve) => {\n setTimeout(() => resolve(null), 5000);\n });\n gitChangedFiles = await Promise.race([gitPromise, timeoutPromise]);\n if (gitChangedFiles && !isInteractiveMode()) {\n console.error(` Git detected ${gitChangedFiles.size} changed files`);\n }\n } catch (error) {\n // Git detection failed - continue without git optimization\n gitChangedFiles = null;\n }\n }\n\n // Parallel scan with concurrency limit\n const scanResults = await this.parallelScan(\n filePaths,\n forceRescan,\n gitChangedFiles,\n onFileProgress\n );\n\n // Process results\n for (const { filePath, result } of scanResults) {\n allVulnerabilities.push(...result.vulnerabilities);\n\n if (result.fromCache) {\n filesSkipped++;\n } else {\n filesScanned++;\n \n // Check for new vulnerabilities\n const previous = previousVulnerabilities.get(filePath) || [];\n const previousPatterns = new Set(previous.map(v => `${v.line}:${v.pattern}`));\n \n for (const vuln of result.vulnerabilities) {\n if (!previousPatterns.has(`${vuln.line}:${vuln.pattern}`)) {\n newVulnerabilities.push(vuln);\n filesChanged++;\n }\n }\n }\n }\n\n // Find resolved vulnerabilities\n const currentPaths = new Set(filePaths);\n const resolvedVulnerabilities: VulnerabilityMatch[] = [];\n \n for (const [path, vulns] of previousVulnerabilities) {\n if (currentPaths.has(path)) {\n const current = this.cache.files[path]?.vulnerabilities || [];\n const currentPatterns = new Set(current.map(v => `${v.line}:${v.pattern}`));\n \n for (const vuln of vulns) {\n if (!currentPatterns.has(`${vuln.line}:${vuln.pattern}`)) {\n resolvedVulnerabilities.push(vuln);\n }\n }\n }\n }\n\n // Update last full scan time for git optimization\n this.cache.lastFullScanTime = Date.now();\n this.dirty = true;\n\n const scanTimeMs = Date.now() - startTime;\n const totalFiles = filesScanned + filesSkipped;\n const cacheHitRate = totalFiles > 0 ? (filesSkipped / totalFiles) * 100 : 0;\n\n return {\n filesScanned,\n filesSkipped,\n filesChanged,\n totalVulnerabilities: allVulnerabilities.length,\n newVulnerabilities,\n resolvedVulnerabilities,\n scanTimeMs,\n cacheHitRate,\n };\n }\n\n /**\n * Parallel file scanning with concurrency limit\n * Processes SCAN_CONCURRENCY files at a time\n * Includes timeout protection to prevent hanging\n */\n private async parallelScan(\n filePaths: string[],\n forceRescan: boolean,\n gitChangedFiles: Set<string> | null,\n onFileProgress?: (filePath: string, fromCache: boolean) => void\n ): Promise<Array<{ filePath: string; result: { vulnerabilities: VulnerabilityMatch[]; fromCache: boolean; symbolCount: number } }>> {\n const results: Array<{ filePath: string; result: { vulnerabilities: VulnerabilityMatch[]; fromCache: boolean; symbolCount: number } }> = [];\n const FILE_SCAN_TIMEOUT_MS = 30000; // 30 seconds per file max\n \n // Process in batches for controlled concurrency\n for (let i = 0; i < filePaths.length; i += SCAN_CONCURRENCY) {\n const batch = filePaths.slice(i, i + SCAN_CONCURRENCY);\n \n const batchPromises = batch.map(async (filePath) => {\n try {\n // Git optimization: if we have git info and file not in changed set, use cache\n if (gitChangedFiles && !gitChangedFiles.has(filePath)) {\n const cached = this.cache.files[filePath];\n if (cached) {\n onFileProgress?.(filePath, true);\n return {\n filePath,\n result: {\n vulnerabilities: cached.vulnerabilities,\n fromCache: true,\n symbolCount: cached.symbolCount,\n },\n };\n }\n }\n\n // Add timeout to prevent hanging on individual file scans\n const scanPromise = this.scanFile(filePath, forceRescan);\n const timeoutPromise = new Promise<{ vulnerabilities: VulnerabilityMatch[]; fromCache: boolean; symbolCount: number }>((resolve) => {\n setTimeout(() => {\n resolve({\n vulnerabilities: [],\n fromCache: false,\n symbolCount: 0,\n });\n }, FILE_SCAN_TIMEOUT_MS);\n });\n \n const result = await Promise.race([scanPromise, timeoutPromise]);\n onFileProgress?.(filePath, result.fromCache);\n return { filePath, result };\n } catch (error) {\n // If file scan fails, return empty result to continue processing\n onFileProgress?.(filePath, false);\n return {\n filePath,\n result: {\n vulnerabilities: [],\n fromCache: false,\n symbolCount: 0,\n },\n };\n }\n });\n\n // Use Promise.allSettled to continue even if some files fail\n const batchSettled = await Promise.allSettled(batchPromises);\n const batchResults = batchSettled.map((settled, idx) => {\n if (settled.status === 'fulfilled') {\n return settled.value;\n } else {\n // Return empty result for failed files\n const filePath = batch[idx]!;\n onFileProgress?.(filePath, false);\n return {\n filePath,\n result: {\n vulnerabilities: [],\n fromCache: false,\n symbolCount: 0,\n },\n };\n }\n });\n results.push(...batchResults);\n }\n\n return results;\n }\n\n /**\n * Remove a file from the cache\n */\n removeFile(filePath: string): void {\n delete this.cache.files[filePath];\n this.symbolIndex.removeFile(filePath);\n this.dirty = true;\n }\n\n /**\n * Clear the entire cache\n */\n clearCache(): void {\n this.cache = {\n version: CACHE_VERSION,\n created: Date.now(),\n lastUpdated: Date.now(),\n files: {},\n };\n this.dirty = true;\n }\n\n /**\n * Get cache statistics\n */\n getStats(): {\n filesInCache: number;\n totalVulnerabilities: number;\n totalSymbols: number;\n oldestScan: number;\n cacheSize: number;\n } {\n let totalVulnerabilities = 0;\n let totalSymbols = 0;\n let oldestScan = Date.now();\n\n for (const file of Object.values(this.cache.files)) {\n totalVulnerabilities += file.vulnerabilities.length;\n totalSymbols += file.symbolCount;\n if (file.lastScanned < oldestScan) {\n oldestScan = file.lastScanned;\n }\n }\n\n return {\n filesInCache: Object.keys(this.cache.files).length,\n totalVulnerabilities,\n totalSymbols,\n oldestScan,\n cacheSize: JSON.stringify(this.cache).length,\n };\n }\n\n /**\n * Get all cached vulnerabilities\n */\n getAllVulnerabilities(): VulnerabilityMatch[] {\n const all: VulnerabilityMatch[] = [];\n for (const file of Object.values(this.cache.files)) {\n all.push(...file.vulnerabilities);\n }\n return all;\n }\n\n /**\n * Get vulnerabilities by severity\n */\n getVulnerabilitiesBySeverity(): Record<string, VulnerabilityMatch[]> {\n const bySeverity: Record<string, VulnerabilityMatch[]> = {\n critical: [],\n serious: [],\n moderate: [],\n low: [],\n };\n\n for (const file of Object.values(this.cache.files)) {\n for (const vuln of file.vulnerabilities) {\n bySeverity[vuln.severity]?.push(vuln);\n }\n }\n\n return bySeverity;\n }\n}\n\n/**\n * Format incremental scan results for output\n */\nexport function formatIncrementalScanResult(result: IncrementalScanResult): string {\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `INCREMENTAL SCAN RESULTS (Trie-Powered)\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## Scan Statistics\\n\\n`;\n output += `| Metric | Value |\\n`;\n output += `|--------|-------|\\n`;\n output += `| Files Scanned | ${result.filesScanned} |\\n`;\n output += `| Files Skipped (cached) | ${result.filesSkipped} |\\n`;\n output += `| Cache Hit Rate | ${result.cacheHitRate.toFixed(1)}% |\\n`;\n output += `| Total Vulnerabilities | ${result.totalVulnerabilities} |\\n`;\n output += `| Scan Time | ${result.scanTimeMs}ms |\\n`;\n output += `\\n`;\n\n if (result.newVulnerabilities.length > 0) {\n output += `## New Vulnerabilities (${result.newVulnerabilities.length})\\n\\n`;\n for (const vuln of result.newVulnerabilities) {\n const icon = { critical: '[!]', serious: '[!]', moderate: '[~]', low: '[-]' }[vuln.severity];\n output += `${icon} **Line ${vuln.line}:** ${vuln.description}\\n`;\n output += ` - Pattern: \\`${vuln.pattern}\\`\\n`;\n output += ` - Fix: ${vuln.fix}\\n`;\n if (vuln.cwe) output += ` - CWE: ${vuln.cwe}\\n`;\n output += `\\n`;\n }\n }\n\n if (result.resolvedVulnerabilities.length > 0) {\n output += `## Resolved Vulnerabilities (${result.resolvedVulnerabilities.length})\\n\\n`;\n for (const vuln of result.resolvedVulnerabilities) {\n output += `- ~~${vuln.pattern}~~ at line ${vuln.line}\\n`;\n }\n output += `\\n`;\n }\n\n if (result.newVulnerabilities.length === 0 && result.resolvedVulnerabilities.length === 0) {\n output += `## No Changes\\n\\n`;\n output += `No new vulnerabilities introduced. No vulnerabilities resolved.\\n`;\n }\n\n return output;\n}\n\n","import type { Issue } from '../types/index.js';\n\nexport interface IssueGroup {\n id: string;\n pattern: string;\n description: string;\n count: number;\n severity: Issue['severity'];\n issues: Issue[];\n riskScore: number;\n fixComplexity: 'trivial' | 'easy' | 'medium' | 'hard';\n category: 'security' | 'performance' | 'maintainability' | 'correctness' | 'style';\n suggestedAction: string;\n bulkFixAvailable: boolean;\n}\n\nexport interface PriorityReport {\n urgent: IssueGroup[];\n high: IssueGroup[];\n medium: IssueGroup[];\n low: IssueGroup[];\n totalIssues: number;\n totalGroups: number;\n riskScore: number;\n recommendations: string[];\n}\n\n/**\n * Smart issue analysis and grouping\n *\n * Groups related issues together and provides intelligent prioritization\n * based on risk, impact, and fix complexity\n */\nexport class IssueAnalyzer {\n /**\n * Analyze and group issues intelligently\n */\n analyzeIssues(issues: Issue[]): PriorityReport {\n // Group issues by pattern\n const groups = this.groupIssuesByPattern(issues);\n\n // Calculate risk scores\n const groupsWithRisk = groups.map(group => ({\n ...group,\n riskScore: this.calculateRiskScore(group),\n category: this.categorizeGroup(group),\n fixComplexity: this.assessFixComplexity(group),\n bulkFixAvailable: this.canBulkFix(group)\n }));\n\n // Prioritize groups\n const prioritized = this.prioritizeGroups(groupsWithRisk);\n\n // Generate recommendations\n const recommendations = this.generateRecommendations(prioritized, issues);\n\n return {\n urgent: prioritized.filter(g => g.riskScore >= 80),\n high: prioritized.filter(g => g.riskScore >= 60 && g.riskScore < 80),\n medium: prioritized.filter(g => g.riskScore >= 40 && g.riskScore < 60),\n low: prioritized.filter(g => g.riskScore < 40),\n totalIssues: issues.length,\n totalGroups: groups.length,\n riskScore: this.calculateOverallRisk(prioritized),\n recommendations\n };\n }\n\n /**\n * Group issues by similar patterns\n */\n private groupIssuesByPattern(issues: Issue[]): IssueGroup[] {\n const groups = new Map<string, Issue[]>();\n\n // Group by exact issue pattern first\n for (const issue of issues) {\n const pattern = this.extractPattern(issue);\n if (!groups.has(pattern)) {\n groups.set(pattern, []);\n }\n groups.get(pattern)!.push(issue);\n }\n\n // Merge similar patterns\n const mergedGroups = this.mergeSimilarPatterns(groups);\n\n // Convert to IssueGroup objects\n return Array.from(mergedGroups.entries()).map(([pattern, groupIssues]) => {\n const severity = this.getGroupSeverity(groupIssues);\n return {\n id: this.generateGroupId(pattern),\n pattern,\n description: this.generateGroupDescription(pattern, groupIssues),\n count: groupIssues.length,\n severity,\n issues: groupIssues,\n riskScore: 0, // Will be calculated later\n fixComplexity: 'medium',\n category: 'correctness',\n suggestedAction: '',\n bulkFixAvailable: false\n };\n });\n }\n\n /**\n * Extract normalized pattern from issue\n */\n private extractPattern(issue: Issue): string {\n // Remove file-specific parts and normalize\n let pattern = issue.issue\n .replace(/in file [^\\s]+/gi, 'in file')\n .replace(/at line \\d+/gi, 'at line X')\n .replace(/\\b\\d+\\b/g, 'N')\n .replace(/['\"][^'\"]*['\"]/g, '\"STRING\"')\n .replace(/\\s+/g, ' ')\n .trim();\n\n // Add agent and severity context\n pattern = `[${issue.agent}] [${issue.severity}] ${pattern}`;\n\n return pattern;\n }\n\n /**\n * Merge patterns that are very similar\n */\n private mergeSimilarPatterns(groups: Map<string, Issue[]>): Map<string, Issue[]> {\n const merged = new Map<string, Issue[]>();\n const processed = new Set<string>();\n\n for (const [pattern, issues] of groups) {\n if (processed.has(pattern)) continue;\n\n // Find similar patterns\n const similar = [pattern];\n const combinedIssues = [...issues];\n\n for (const [otherPattern, otherIssues] of groups) {\n if (pattern === otherPattern || processed.has(otherPattern)) continue;\n\n const similarity = this.calculatePatternSimilarity(pattern, otherPattern);\n if (similarity > 0.85) { // 85% similarity threshold\n similar.push(otherPattern);\n combinedIssues.push(...otherIssues);\n processed.add(otherPattern);\n }\n }\n\n processed.add(pattern);\n merged.set(pattern, combinedIssues);\n }\n\n return merged;\n }\n\n /**\n * Calculate similarity between two patterns\n */\n private calculatePatternSimilarity(pattern1: string, pattern2: string): number {\n const words1 = new Set(pattern1.toLowerCase().split(/\\W+/));\n const words2 = new Set(pattern2.toLowerCase().split(/\\W+/));\n\n const intersection = new Set([...words1].filter(w => words2.has(w)));\n const union = new Set([...words1, ...words2]);\n\n return intersection.size / union.size;\n }\n\n /**\n * Get the most severe level in a group\n */\n private getGroupSeverity(issues: Issue[]): Issue['severity'] {\n const severityOrder: Issue['severity'][] = ['critical', 'serious', 'moderate', 'low'];\n\n for (const severity of severityOrder) {\n if (issues.some(i => i.severity === severity)) {\n return severity;\n }\n }\n\n return 'low';\n }\n\n /**\n * Calculate risk score for a group (0-100)\n */\n private calculateRiskScore(group: IssueGroup): number {\n let score = 0;\n\n // Severity weight (40% of score)\n const severityWeights = { critical: 40, serious: 30, moderate: 20, low: 10 };\n score += severityWeights[group.severity];\n\n // Count weight (30% of score)\n const countScore = Math.min(30, group.count * 2); // Max 30 points, 2 per issue\n score += countScore;\n\n // Pattern-specific bonuses (30% of score)\n const pattern = group.pattern.toLowerCase();\n\n // Security issues get bonus\n if (pattern.includes('security') || pattern.includes('injection') || pattern.includes('xss') ||\n pattern.includes('csrf') || pattern.includes('secret') || pattern.includes('hardcoded')) {\n score += 25;\n }\n\n // Performance issues in hot paths\n if (pattern.includes('loop') || pattern.includes('n+1') || pattern.includes('memory') ||\n pattern.includes('performance')) {\n score += 20;\n }\n\n // Critical infrastructure\n if (pattern.includes('auth') || pattern.includes('database') || pattern.includes('payment')) {\n score += 15;\n }\n\n // Widespread issues (cross-file)\n if (group.count > 10) {\n score += 10;\n }\n\n // AI-generated code issues\n if (pattern.includes('console.log') || pattern.includes('any') || pattern.includes('ts-ignore')) {\n score += 5;\n }\n\n return Math.min(100, score);\n }\n\n /**\n * Categorize issue group\n */\n private categorizeGroup(group: IssueGroup): IssueGroup['category'] {\n const pattern = group.pattern.toLowerCase();\n\n if (pattern.includes('security') || pattern.includes('injection') || pattern.includes('xss') ||\n pattern.includes('secret') || pattern.includes('hardcoded') || pattern.includes('auth')) {\n return 'security';\n }\n\n if (pattern.includes('performance') || pattern.includes('memory') || pattern.includes('n+1') ||\n pattern.includes('slow') || pattern.includes('optimization')) {\n return 'performance';\n }\n\n if (pattern.includes('maintainability') || pattern.includes('complexity') || pattern.includes('duplication') ||\n pattern.includes('refactor') || pattern.includes('tech debt')) {\n return 'maintainability';\n }\n\n if (pattern.includes('bug') || pattern.includes('error') || pattern.includes('null') ||\n pattern.includes('undefined') || pattern.includes('race condition')) {\n return 'correctness';\n }\n\n return 'style';\n }\n\n /**\n * Assess fix complexity\n */\n private assessFixComplexity(group: IssueGroup): IssueGroup['fixComplexity'] {\n const pattern = group.pattern.toLowerCase();\n\n // Trivial fixes\n if (pattern.includes('console.log') || pattern.includes('unused import') ||\n pattern.includes('whitespace') || pattern.includes('formatting')) {\n return 'trivial';\n }\n\n // Easy fixes\n if (pattern.includes('type annotation') || pattern.includes('validation') ||\n pattern.includes('error handling') || group.severity === 'low') {\n return 'easy';\n }\n\n // Hard fixes\n if (pattern.includes('architecture') || pattern.includes('race condition') ||\n pattern.includes('security') && group.severity === 'critical') {\n return 'hard';\n }\n\n return 'medium';\n }\n\n /**\n * Check if group can be bulk-fixed\n */\n private canBulkFix(group: IssueGroup): boolean {\n const pattern = group.pattern.toLowerCase();\n\n // Patterns that can be bulk-fixed\n const bulkFixablePatterns = [\n 'console.log',\n 'unused import',\n 'missing semicolon',\n 'type annotation',\n 'whitespace',\n 'formatting',\n 'eslint-disable',\n 'ts-ignore'\n ];\n\n return bulkFixablePatterns.some(p => pattern.includes(p)) && group.count > 2;\n }\n\n /**\n * Prioritize groups by risk and impact\n */\n private prioritizeGroups(groups: IssueGroup[]): IssueGroup[] {\n return groups.sort((a, b) => {\n // Primary sort: risk score\n if (a.riskScore !== b.riskScore) {\n return b.riskScore - a.riskScore;\n }\n\n // Secondary sort: severity\n const severityOrder = { critical: 0, serious: 1, moderate: 2, low: 3 };\n const aSev = severityOrder[a.severity];\n const bSev = severityOrder[b.severity];\n if (aSev !== bSev) {\n return aSev - bSev;\n }\n\n // Tertiary sort: count (more issues = higher priority)\n return b.count - a.count;\n });\n }\n\n /**\n * Generate actionable recommendations\n */\n private generateRecommendations(groups: IssueGroup[], allIssues: Issue[]): string[] {\n const recommendations: string[] = [];\n\n // Critical security issues\n const criticalSecurity = groups.filter(g =>\n g.category === 'security' && g.severity === 'critical'\n );\n if (criticalSecurity.length > 0) {\n recommendations.push(\n `[!] Immediate action required: Fix ${criticalSecurity.length} critical security issue group(s)`\n );\n }\n\n // Bulk-fixable issues\n const bulkFixable = groups.filter(g => g.bulkFixAvailable);\n if (bulkFixable.length > 0) {\n const totalBulkIssues = bulkFixable.reduce((sum, g) => sum + g.count, 0);\n recommendations.push(\n `⚡ Quick win: Bulk-fix ${totalBulkIssues} issues across ${bulkFixable.length} patterns`\n );\n }\n\n // Performance issues\n const performance = groups.filter(g => g.category === 'performance');\n if (performance.length > 0) {\n recommendations.push(\n `🚀 Performance: Address ${performance.length} performance issue pattern(s)`\n );\n }\n\n // Widespread issues\n const widespread = groups.filter(g => g.count > 10);\n if (widespread.length > 0) {\n recommendations.push(\n `📊 Systemic: ${widespread.length} patterns appear across many files - consider automated fixes`\n );\n }\n\n // AI code cleanup\n const aiIssues = allIssues.filter(i =>\n i.issue.toLowerCase().includes('console.log') ||\n i.issue.toLowerCase().includes('any') ||\n i.issue.toLowerCase().includes('ts-ignore')\n );\n if (aiIssues.length > 20) {\n recommendations.push(\n `🤖 AI cleanup: ${aiIssues.length} AI-generated code issues detected - run cleanup tools`\n );\n }\n\n // Code quality\n const qualityScore = this.calculateCodeQualityScore(groups);\n if (qualityScore < 60) {\n recommendations.push(\n `📈 Code quality: Score is ${qualityScore}/100 - focus on critical and serious issues first`\n );\n }\n\n return recommendations.slice(0, 5); // Max 5 recommendations\n }\n\n /**\n * Calculate overall risk score\n */\n private calculateOverallRisk(groups: IssueGroup[]): number {\n if (groups.length === 0) return 0;\n\n // Weight by group size and severity\n let totalWeightedRisk = 0;\n let totalWeight = 0;\n\n for (const group of groups) {\n const weight = group.count;\n totalWeightedRisk += group.riskScore * weight;\n totalWeight += weight;\n }\n\n return totalWeight > 0 ? Math.round(totalWeightedRisk / totalWeight) : 0;\n }\n\n /**\n * Calculate code quality score (0-100)\n */\n private calculateCodeQualityScore(groups: IssueGroup[]): number {\n let score = 100;\n\n for (const group of groups) {\n const penalty = this.calculateGroupPenalty(group);\n score -= penalty;\n }\n\n return Math.max(0, Math.round(score));\n }\n\n /**\n * Calculate quality penalty for a group\n */\n private calculateGroupPenalty(group: IssueGroup): number {\n const severityPenalties = { critical: 10, serious: 5, moderate: 2, low: 1 };\n const basePenalty = severityPenalties[group.severity];\n\n // Increase penalty for widespread issues\n const countMultiplier = Math.min(3, Math.log10(group.count + 1));\n\n return basePenalty * countMultiplier;\n }\n\n /**\n * Generate group ID\n */\n private generateGroupId(pattern: string): string {\n const hash = pattern.split('').reduce((acc, char) => {\n return ((acc << 5) - acc + char.charCodeAt(0)) & 0xffffffff;\n }, 0);\n return Math.abs(hash).toString(36);\n }\n\n /**\n * Generate human-readable group description\n */\n private generateGroupDescription(pattern: string, issues: Issue[]): string {\n // Extract key information from pattern\n const agentMatch = pattern.match(/\\[([^\\]]+)\\]/);\n const agent = agentMatch ? agentMatch[1] : 'unknown';\n\n // Get the most common issue text\n const issueTexts = issues.map(i => i.issue.slice(0, 100));\n const commonText = this.findMostCommonSubstring(issueTexts);\n\n return commonText || `${agent} issues (${issues.length} instances)`;\n }\n\n /**\n * Find most common substring across issue texts\n */\n private findMostCommonSubstring(texts: string[]): string {\n if (texts.length === 0) return '';\n const firstText = texts[0];\n if (!firstText) return '';\n if (texts.length === 1) return firstText;\n\n // Find longest common prefix\n let common: string = firstText;\n for (let i = 1; i < texts.length; i++) {\n const currentText = texts[i];\n if (!currentText) continue;\n let j = 0;\n while (j < common.length && j < currentText.length &&\n common[j]!.toLowerCase() === currentText[j]!.toLowerCase()) {\n j++;\n }\n common = common.slice(0, j);\n }\n\n // Clean up the common part\n return common.trim().replace(/\\s+/g, ' ') || firstText.slice(0, 50);\n }\n}","import type { Issue } from '../types/index.js';\nimport type { PriorityReport } from '../utils/issue-analyzer.js';\n\nexport interface TeamMember {\n id: string;\n name: string;\n email: string;\n role: 'developer' | 'lead' | 'security' | 'architect' | 'manager';\n expertise: string[];\n timezone: string;\n}\n\nexport interface IssueAssignment {\n issueId: string;\n assigneeId: string;\n assignedAt: number;\n dueDate?: number;\n priority: 'urgent' | 'high' | 'medium' | 'low';\n status: 'assigned' | 'in_progress' | 'under_review' | 'resolved' | 'dismissed';\n notes?: string;\n}\n\nexport interface TeamNotification {\n id: string;\n type: 'assignment' | 'escalation' | 'completion' | 'reminder';\n recipientId: string;\n title: string;\n message: string;\n data: any;\n createdAt: number;\n sentAt?: number;\n readAt?: number;\n}\n\n/**\n * Team Collaboration Manager\n *\n * Features:\n * - Intelligent issue assignment based on expertise\n * - Team notifications (Slack, email, GitHub)\n * - Progress tracking and reporting\n * - Escalation policies\n * - Team dashboard and metrics\n */\nexport class TeamCollaborationManager {\n private teamMembers: Map<string, TeamMember> = new Map();\n private assignments: Map<string, IssueAssignment> = new Map();\n private notifications: TeamNotification[] = [];\n\n /**\n * Register team member\n */\n addTeamMember(member: TeamMember): void {\n this.teamMembers.set(member.id, member);\n }\n\n /**\n * Intelligently assign issues to team members based on expertise\n */\n assignIssues(issues: Issue[], priorityReport: PriorityReport): IssueAssignment[] {\n const assignments: IssueAssignment[] = [];\n\n // Group issues by category for better assignment\n const issuesByCategory = new Map<string, Issue[]>();\n for (const issue of issues) {\n const category = this.categorizeIssue(issue);\n if (!issuesByCategory.has(category)) {\n issuesByCategory.set(category, []);\n }\n issuesByCategory.get(category)!.push(issue);\n }\n\n // Assign issues by category\n for (const [category, categoryIssues] of issuesByCategory) {\n const expertMembers = this.findExpertMembers(category);\n const sortedIssues = this.prioritizeIssues(categoryIssues, priorityReport);\n\n // Round-robin assignment among experts\n let memberIndex = 0;\n for (const issue of sortedIssues) {\n if (expertMembers.length === 0) continue;\n\n const assignee = expertMembers[memberIndex % expertMembers.length];\n if (!assignee) continue;\n const assignment = this.createAssignment(issue, assignee);\n\n assignments.push(assignment);\n this.assignments.set(issue.id, assignment);\n\n // Create notification\n this.createAssignmentNotification(assignment, issue);\n\n memberIndex++;\n }\n }\n\n return assignments;\n }\n\n /**\n * Create assignment for issue\n */\n private createAssignment(issue: Issue, assignee: TeamMember): IssueAssignment {\n const priority = this.determinePriority(issue);\n const dueDate = this.calculateDueDate(issue, priority);\n\n return {\n issueId: issue.id,\n assigneeId: assignee.id,\n assignedAt: Date.now(),\n dueDate,\n priority,\n status: 'assigned'\n };\n }\n\n /**\n * Determine assignment priority based on issue severity and type\n */\n private determinePriority(issue: Issue): IssueAssignment['priority'] {\n if (issue.severity === 'critical') {\n return 'urgent';\n }\n if (issue.severity === 'serious') {\n return 'high';\n }\n if (issue.severity === 'moderate') {\n return 'medium';\n }\n return 'low';\n }\n\n /**\n * Calculate due date based on priority\n */\n private calculateDueDate(_issue: Issue, priority: IssueAssignment['priority']): number {\n const now = Date.now();\n const durations = {\n urgent: 4 * 60 * 60 * 1000, // 4 hours\n high: 24 * 60 * 60 * 1000, // 1 day\n medium: 7 * 24 * 60 * 60 * 1000, // 1 week\n low: 14 * 24 * 60 * 60 * 1000 // 2 weeks\n };\n\n return now + durations[priority];\n }\n\n /**\n * Find team members with expertise in a category\n */\n private findExpertMembers(category: string): TeamMember[] {\n const experts = Array.from(this.teamMembers.values()).filter(member =>\n member.expertise.includes(category) || this.hasRelatedExpertise(member, category)\n );\n\n // If no experts found, assign to leads and architects\n if (experts.length === 0) {\n return Array.from(this.teamMembers.values()).filter(member =>\n member.role === 'lead' || member.role === 'architect'\n );\n }\n\n // Sort by role priority\n return experts.sort((a, b) => {\n const roleOrder = { security: 0, architect: 1, lead: 2, developer: 3, manager: 4 };\n return (roleOrder[a.role] || 5) - (roleOrder[b.role] || 5);\n });\n }\n\n /**\n * Check if member has related expertise\n */\n private hasRelatedExpertise(member: TeamMember, category: string): boolean {\n const related: Record<string, string[]> = {\n 'security': ['auth', 'crypto', 'compliance'],\n 'performance': ['optimization', 'backend', 'database'],\n 'frontend': ['ui', 'react', 'vue', 'css'],\n 'backend': ['api', 'database', 'server'],\n 'devops': ['ci', 'docker', 'aws', 'deployment']\n };\n\n const relatedSkills = related[category] || [];\n return relatedSkills.some(skill =>\n member.expertise.some(exp => exp.toLowerCase().includes(skill))\n );\n }\n\n /**\n * Categorize issue for assignment\n */\n private categorizeIssue(issue: Issue): string {\n const issueText = issue.issue.toLowerCase();\n\n if (issueText.includes('security') || issueText.includes('injection') ||\n issueText.includes('auth') || issue.agent === 'security') {\n return 'security';\n }\n if (issueText.includes('performance') || issueText.includes('slow') ||\n issue.agent === 'performance') {\n return 'performance';\n }\n if (issueText.includes('ui') || issueText.includes('component') ||\n issueText.includes('react') || issueText.includes('vue')) {\n return 'frontend';\n }\n if (issueText.includes('api') || issueText.includes('database') ||\n issueText.includes('server')) {\n return 'backend';\n }\n if (issueText.includes('deploy') || issueText.includes('docker') ||\n issueText.includes('ci') || issue.agent === 'devops') {\n return 'devops';\n }\n\n return 'general';\n }\n\n /**\n * Prioritize issues within a category\n */\n private prioritizeIssues(issues: Issue[], _priorityReport: PriorityReport): Issue[] {\n return issues.sort((a, b) => {\n // Primary: severity\n const severityOrder = { critical: 0, serious: 1, moderate: 2, low: 3 };\n const aSev = severityOrder[a.severity];\n const bSev = severityOrder[b.severity];\n if (aSev !== bSev) {\n return aSev - bSev;\n }\n\n // Secondary: confidence\n return (b.confidence || 0) - (a.confidence || 0);\n });\n }\n\n /**\n * Create assignment notification\n */\n private createAssignmentNotification(assignment: IssueAssignment, issue: Issue): void {\n const assignee = this.teamMembers.get(assignment.assigneeId);\n if (!assignee) return;\n\n const priorityEmoji = {\n urgent: '[URGENT]',\n high: '[HIGH]',\n medium: '[MED]',\n low: '[LOW]'\n };\n\n const notification: TeamNotification = {\n id: `notif-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,\n type: 'assignment',\n recipientId: assignment.assigneeId,\n title: `${priorityEmoji[assignment.priority]} New Issue Assigned`,\n message: `You've been assigned a ${assignment.priority} priority ${issue.severity} issue: ${issue.issue.slice(0, 100)}...`,\n data: {\n assignment,\n issue,\n dueDate: assignment.dueDate\n },\n createdAt: Date.now()\n };\n\n this.notifications.push(notification);\n }\n\n /**\n * Update assignment status\n */\n updateAssignment(issueId: string, updates: Partial<IssueAssignment>): void {\n const assignment = this.assignments.get(issueId);\n if (!assignment) return;\n\n Object.assign(assignment, updates);\n this.assignments.set(issueId, assignment);\n\n // Create status update notification\n if (updates.status) {\n this.createStatusNotification(assignment, updates.status);\n }\n }\n\n /**\n * Create status update notification\n */\n private createStatusNotification(assignment: IssueAssignment, newStatus: string): void {\n const assignee = this.teamMembers.get(assignment.assigneeId);\n if (!assignee) return;\n\n const statusEmoji: Record<string, string> = {\n 'in_progress': '[IN PROGRESS]',\n 'under_review': '[REVIEW]',\n 'resolved': '[RESOLVED]',\n 'dismissed': '[DISMISSED]'\n };\n\n const notification: TeamNotification = {\n id: `notif-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,\n type: 'completion',\n recipientId: 'all', // Notify team leads\n title: `${statusEmoji[newStatus] ?? '[UPDATE]'} Issue Status Update`,\n message: `${assignee.name} marked issue ${assignment.issueId} as ${newStatus}`,\n data: {\n assignment,\n previousStatus: assignment.status,\n newStatus\n },\n createdAt: Date.now()\n };\n\n this.notifications.push(notification);\n }\n\n /**\n * Check for overdue assignments and escalate\n */\n checkOverdueAssignments(): void {\n const now = Date.now();\n const overdueAssignments = Array.from(this.assignments.values()).filter(assignment =>\n assignment.dueDate &&\n assignment.dueDate < now &&\n assignment.status !== 'resolved' &&\n assignment.status !== 'dismissed'\n );\n\n for (const assignment of overdueAssignments) {\n this.escalateOverdueAssignment(assignment);\n }\n }\n\n /**\n * Escalate overdue assignment\n */\n private escalateOverdueAssignment(assignment: IssueAssignment): void {\n // Find team leads for escalation\n const leads = Array.from(this.teamMembers.values()).filter(member =>\n member.role === 'lead' || member.role === 'manager'\n );\n\n for (const lead of leads) {\n const notification: TeamNotification = {\n id: `escalation-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`,\n type: 'escalation',\n recipientId: lead.id,\n title: 'Overdue Assignment Escalation',\n message: `Issue ${assignment.issueId} assigned to ${assignment.assigneeId} is overdue`,\n data: {\n assignment,\n overdueBy: Date.now() - (assignment.dueDate || 0)\n },\n createdAt: Date.now()\n };\n\n this.notifications.push(notification);\n }\n }\n\n /**\n * Generate team dashboard data\n */\n generateTeamDashboard(): {\n teamMetrics: {\n totalMembers: number;\n activeAssignments: number;\n overdueAssignments: number;\n completedThisWeek: number;\n };\n memberStats: Array<{\n member: TeamMember;\n activeAssignments: number;\n completedThisWeek: number;\n averageResolutionTime: number;\n }>;\n categoryBreakdown: Record<string, number>;\n } {\n const now = Date.now();\n const oneWeekAgo = now - 7 * 24 * 60 * 60 * 1000;\n\n const activeAssignments = Array.from(this.assignments.values()).filter(a =>\n a.status !== 'resolved' && a.status !== 'dismissed'\n );\n\n const completedThisWeek = Array.from(this.assignments.values()).filter(a =>\n a.status === 'resolved' && a.assignedAt > oneWeekAgo\n );\n\n const overdueAssignments = activeAssignments.filter(a =>\n a.dueDate && a.dueDate < now\n );\n\n // Member statistics\n const memberStats = Array.from(this.teamMembers.values()).map(member => {\n const memberAssignments = Array.from(this.assignments.values()).filter(a =>\n a.assigneeId === member.id\n );\n\n const memberActive = memberAssignments.filter(a =>\n a.status !== 'resolved' && a.status !== 'dismissed'\n );\n\n const memberCompleted = memberAssignments.filter(a =>\n a.status === 'resolved' && a.assignedAt > oneWeekAgo\n );\n\n // Calculate average resolution time\n const resolvedAssignments = memberAssignments.filter(a => a.status === 'resolved');\n const totalResolutionTime = resolvedAssignments.reduce((sum, a) => {\n // Assuming we have a resolvedAt timestamp (would need to add this)\n return sum + (now - a.assignedAt); // Simplified calculation\n }, 0);\n const averageResolutionTime = resolvedAssignments.length > 0 ?\n totalResolutionTime / resolvedAssignments.length : 0;\n\n return {\n member,\n activeAssignments: memberActive.length,\n completedThisWeek: memberCompleted.length,\n averageResolutionTime\n };\n });\n\n // Category breakdown\n const categoryBreakdown: Record<string, number> = {};\n for (const _assignment of activeAssignments) {\n // Would need to store category in assignment or look up from issue\n const category = 'general'; // Simplified\n categoryBreakdown[category] = (categoryBreakdown[category] || 0) + 1;\n }\n\n return {\n teamMetrics: {\n totalMembers: this.teamMembers.size,\n activeAssignments: activeAssignments.length,\n overdueAssignments: overdueAssignments.length,\n completedThisWeek: completedThisWeek.length\n },\n memberStats,\n categoryBreakdown\n };\n }\n\n /**\n * Get pending notifications for a team member\n */\n getPendingNotifications(memberId: string): TeamNotification[] {\n return this.notifications.filter(notification =>\n (notification.recipientId === memberId || notification.recipientId === 'all') &&\n !notification.readAt\n );\n }\n\n /**\n * Mark notification as read\n */\n markNotificationRead(notificationId: string): void {\n const notification = this.notifications.find(n => n.id === notificationId);\n if (notification) {\n notification.readAt = Date.now();\n }\n }\n\n /**\n * Get assignment details\n */\n getAssignment(issueId: string): IssueAssignment | undefined {\n return this.assignments.get(issueId);\n }\n\n /**\n * Get all assignments for a team member\n */\n getMemberAssignments(memberId: string): IssueAssignment[] {\n return Array.from(this.assignments.values()).filter(a => a.assigneeId === memberId);\n }\n\n /**\n * Generate team performance report\n */\n generatePerformanceReport(_timeRange: { start: number; end: number }): {\n totalIssuesResolved: number;\n averageResolutionTime: number;\n issuesByCategory: Record<string, number>;\n topPerformers: Array<{\n member: TeamMember;\n issuesResolved: number;\n averageTime: number;\n }>;\n trends: {\n weeklyResolution: number[];\n categoryTrends: Record<string, number[]>;\n };\n } {\n // Implementation would analyze assignment history\n // This is a simplified structure\n return {\n totalIssuesResolved: 0,\n averageResolutionTime: 0,\n issuesByCategory: {},\n topPerformers: [],\n trends: {\n weeklyResolution: [],\n categoryTrends: {}\n }\n };\n }\n}"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAYA,IAAM,wBAAwB,MAAM,kBAAkB;AAuC/C,IAAM,mBAAN,MAAuB;AAAA,EACpB,YAAiD,oBAAI,IAAI;AAAA,EACzD,WAAyB;AAAA,IAC/B,YAAY;AAAA,IACZ,gBAAgB;AAAA,IAChB,cAAc,CAAC;AAAA,IACf,iBAAiB,CAAC;AAAA,IAClB,aAAa;AAAA,IACb,kBAAkB,EAAE,UAAU,GAAG,SAAS,GAAG,UAAU,GAAG,KAAK,EAAE;AAAA,EACnE;AAAA;AAAA;AAAA;AAAA,EAKA,UAAU,UAAsD;AAC9D,SAAK,UAAU,IAAI,QAAQ;AAC3B,WAAO,MAAM,KAAK,UAAU,OAAO,QAAQ;AAAA,EAC7C;AAAA;AAAA;AAAA;AAAA,EAKQ,KAAK,MAA4B,MAAiB;AACxD,UAAM,SAAuB;AAAA,MAC3B;AAAA,MACA,WAAW,KAAK,IAAI;AAAA,MACpB;AAAA,IACF;AAEA,SAAK,UAAU,QAAQ,cAAY;AACjC,UAAI;AACF,iBAAS,MAAM;AAAA,MACjB,SAAS,OAAO;AACd,YAAI,CAAC,sBAAsB,GAAG;AAC5B,kBAAQ,KAAK,0BAA0B,KAAK;AAAA,QAC9C;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKA,UAAU,YAA0B;AAClC,SAAK,WAAW;AAAA,MACd;AAAA,MACA,gBAAgB;AAAA,MAChB,cAAc,CAAC;AAAA,MACf,iBAAiB,CAAC;AAAA,MAClB,aAAa;AAAA,MACb,kBAAkB,EAAE,UAAU,GAAG,SAAS,GAAG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AAC/B,aAAO,CAAC;AAAA,IACV;AAEA,QAAI;AACF,YAAM,UAAU,MAAME,UAAS,gBAAgB,OAAO;AACtD,YAAM,OAAO,KAAK,MAAM,OAAO;AAC/B,aAAO,MAAM,QAAQ,KAAK,OAAO,IAAI,KAAK,UAAU,CAAC;AAAA,IACvD,QAAQ;AACN,aAAO,CAAC;AAAA,IACV;AAAA,EACF;AAAA,EAEQ,sBAAsB,OAAyC;AACrE,UAAM,QAAgC,CAAC;AACvC,eAAW,QAAQ,OAAO;AACxB,YAAM,MAAMO,SAAQ,IAAI,KAAK;AAC7B,YAAM,GAAG,KAAK,MAAM,GAAG,KAAK,KAAK;AAAA,IACnC;AACA,WAAO;AAAA,EACT;AACF;","names":["searchIssues","resolve","result","v","readFile","readdir","writeFile","mkdir","existsSync","basename","join","extname","dirname","readFile","existsSync","basename","existsSync","readFile","basename","readFile","join","extname","basename","output","readFile","basename","relative","output","basename","readFile","basename","relative","output","readFile","mkdir","existsSync","join","join","existsSync","readFile","mkdir","resolve","output","join","dirname","existsSync","mkdir","readFile","writeFile","basename","resolve","result","output","readdir","extname"]}
|