@triedotdev/mcp 1.0.99 → 1.0.102
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 +21 -59
- package/dist/{chunk-DIZFGLXE.js → chunk-AE2XLMZC.js} +15 -75
- package/dist/chunk-AE2XLMZC.js.map +1 -0
- package/dist/{chunk-HSNE46VE.js → chunk-CCI6LKXZ.js} +1 -431
- package/dist/chunk-CCI6LKXZ.js.map +1 -0
- package/dist/{chunk-FNCCZ3XB.js → chunk-M4JCQO5G.js} +443 -19
- package/dist/chunk-M4JCQO5G.js.map +1 -0
- package/dist/cli/main.js +3 -3
- package/dist/cli/yolo-daemon.js +2 -2
- package/dist/index.js +11 -5
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-DIZFGLXE.js.map +0 -1
- package/dist/chunk-FNCCZ3XB.js.map +0 -1
- package/dist/chunk-HSNE46VE.js.map +0 -1
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server/mcp-server.ts","../src/utils/ai-tool-detector.ts","../src/tools/fix.ts","../src/ai/prompts.ts","../src/tools/explain.ts","../src/tools/test.ts","../src/tools/watch.ts","../src/extraction/signal-extractor.ts","../src/extraction/metadata-enricher.ts","../src/extraction/pipeline.ts","../src/tools/pr-review.ts","../src/skills/built-in/super-reviewer.ts","../src/tools/project-info.ts","../src/tools/init.ts","../src/tools/memory-search.ts","../src/tools/checkpoint.ts","../src/tools/check.ts","../src/tools/tell.ts","../src/tools/reconcile.ts","../src/tools/context.ts","../src/tools/feedback.ts","../src/tools/linear-sync.ts","../src/tools/query-tools.ts","../src/server/tool-registry.ts","../src/server/resource-manager.ts","../src/tools/visual-qa-browser.ts","../src/server/request-handlers.ts","../src/index.ts"],"sourcesContent":["import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n ListResourcesRequestSchema,\n ReadResourceRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\n\nimport { detectAITool } from '../utils/ai-tool-detector.js';\nimport { loadConfig } from '../config/loader.js';\nimport { getSkillRegistry } from '../skills/built-in/registry.js';\nimport { ToolRegistry } from './tool-registry.js';\nimport { ResourceManager } from './resource-manager.js';\nimport { RequestHandlers } from './request-handlers.js';\n\nexport class MCPServer {\n private server: Server;\n private toolRegistry: ToolRegistry;\n private resourceManager: ResourceManager;\n private requestHandlers: RequestHandlers;\n\n constructor() {\n this.server = new Server(\n {\n name: 'trie',\n version: '1.0.0',\n description: 'Intelligent Agent Orchestration for AI Coding Tools. IMPORTANT: Read trie://context first to understand project state, priorities, and recent scan history before making changes.',\n },\n {\n capabilities: {\n tools: {},\n resources: {},\n // Enable MCP Apps - interactive UI components in AI clients\n // See: https://blog.modelcontextprotocol.io/posts/2026-01-26-mcp-apps/\n experimental: {\n ui: {},\n },\n },\n }\n );\n\n this.toolRegistry = new ToolRegistry();\n this.resourceManager = new ResourceManager();\n this.requestHandlers = new RequestHandlers(this.toolRegistry, this.resourceManager);\n\n this.setupRequestHandlers();\n }\n\n private setupRequestHandlers() {\n // List tools handler\n this.server.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: this.toolRegistry.getAllTools()\n };\n });\n\n // Call tool handler\n this.server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n return await this.requestHandlers.handleToolCall(name, args);\n });\n\n // List resources handler\n this.server.setRequestHandler(ListResourcesRequestSchema, async () => {\n return await this.requestHandlers.handleListResources();\n });\n\n // Read resource handler\n this.server.setRequestHandler(ReadResourceRequestSchema, async (request) => {\n const { uri } = request.params;\n return await this.requestHandlers.handleReadResource(uri);\n });\n }\n\n /**\n * Show startup banner\n */\n private showStartupBanner(skillCount: number, aiTool: string) {\n console.error(`\n ████████╗██████╗ ██╗███████╗\n ╚══██╔══╝██╔══██╗██║██╔════╝\n ██║ ██████╔╝██║█████╗\n ██║ ██╔══██╗██║██╔══╝\n ██║ ██║ ██║██║███████╗\n ╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝\n Your central registry for the guardian and its skills\n\n by Louis Kishfy\n\n Download the Trie workspace: https://www.trie.dev\n Follow me on X: https://x.com/louiskishfy\n\n ${skillCount} skills ready | ${aiTool}\n\n Quick Start:\n • \"Scan this code\" - Run all relevant skills\n • \"Run trie_security\" - Security scan only\n • \"Run trie_soc2\" - SOC 2 compliance check\n • \"Use trie_list_skills\" - See all skills\n • \"Use trie_create_skill\" - Make custom skill\n\n Ready.\n`);\n }\n\n /**\n * Initialize and start the server\n */\n async start(): Promise<void> {\n try {\n // Detect the AI tool environment\n const aiTool = detectAITool();\n\n // Load configuration\n await loadConfig();\n\n // Get actual skill count from registry\n const registry = getSkillRegistry();\n const skillCount = registry.getAllSkills().length;\n\n this.showStartupBanner(skillCount, aiTool.name);\n\n const transport = new StdioServerTransport();\n await this.server.connect(transport);\n } catch (error) {\n console.error('Fatal error starting MCP server:', error);\n process.exit(1);\n }\n }\n}\n\n/**\n * Start the MCP server\n */\nexport async function startServer(): Promise<void> {\n const server = new MCPServer();\n await server.start();\n}","import { AITool } from '../types/index.js';\n\nexport function detectAITool(): AITool {\n // Check environment variables set by AI tools\n if (process.env.CLAUDE_CODE_VERSION || process.env.CLAUDE_CODE) {\n return {\n name: 'Claude Code',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: true,\n };\n }\n\n if (process.env.CURSOR_IDE || process.env.CURSOR_TRACE_ID) {\n return {\n name: 'Cursor',\n preferredOutputFormat: 'rich-text',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n }\n\n if (process.env.OPENCODE_INSTANCE) {\n return {\n name: 'OpenCode',\n preferredOutputFormat: 'plain-text',\n supportsDiffs: false,\n supportsInlineActions: false,\n };\n }\n\n if (process.env.VSCODE_PID || process.env.VSCODE_IPC_HOOK) {\n return {\n name: 'VS Code',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n }\n\n // Check parent process name or other hints\n const parentProcess = process.env.PARENT_PROCESS_NAME || process.env._ || '';\n if (parentProcess.toLowerCase().includes('claude')) {\n return {\n name: 'Claude Code',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: true,\n };\n }\n\n if (parentProcess.toLowerCase().includes('cursor')) {\n return {\n name: 'Cursor',\n preferredOutputFormat: 'rich-text',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n }\n\n // Check if running via npx (likely from an MCP client)\n if (process.env.npm_execpath || process.argv[1]?.includes('npx')) {\n return {\n name: 'MCP Client',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n }\n\n // Default\n return {\n name: 'MCP Client',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n}","import { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { extname, relative, resolve, isAbsolute } from 'path';\nimport { getPrompt, getSystemPrompt } from '../ai/prompts.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\n/**\n * Fix Tool - AI-powered code fixing\n * \n * This tool coordinates with Claude to apply fixes. It can:\n * 1. Apply specific fixes from scan results\n * 2. Auto-fix high-confidence issues\n * 3. Generate fix suggestions for review\n */\n\ninterface PendingFix {\n id: string;\n file: string;\n line: number;\n issue: string;\n suggestedFix: string;\n confidence: number;\n status: 'pending' | 'applied' | 'rejected';\n}\n\n// In-memory store for pending fixes (from scans)\nconst pendingFixes = new Map<string, PendingFix>();\n\nexport class TrieFixTool {\n async execute(args: any) {\n const { issueIds, file, line, issue, fix, autoApprove = false, dryRun = false } = args || {};\n\n // Mode 1: Fix specific issue by ID\n if (issueIds && issueIds.length > 0) {\n return this.fixByIds(issueIds, autoApprove, dryRun);\n }\n\n // Mode 2: Fix specific location with provided fix\n if (file && fix) {\n return this.applyFix(file, line || 1, issue || 'User-specified fix', fix, dryRun);\n }\n\n // Mode 3: Interactive fix mode - show pending fixes\n if (pendingFixes.size > 0) {\n return this.showPendingFixes();\n }\n\n // Mode 4: Generate fix for a file/issue\n if (file && issue) {\n return this.generateFixPrompt(file, line || 1, issue);\n }\n\n // No fixes available\n return {\n content: [{\n type: 'text',\n text: this.getHelpText()\n }]\n };\n }\n\n private async fixByIds(issueIds: string[], autoApprove: boolean, dryRun: boolean) {\n const results: string[] = [];\n let fixed = 0;\n let failed = 0;\n\n for (const id of issueIds) {\n const pendingFix = pendingFixes.get(id);\n if (!pendingFix) {\n results.push(`❌ Issue ${id}: Not found in pending fixes`);\n failed++;\n continue;\n }\n\n if (pendingFix.confidence < 0.8 && !autoApprove) {\n results.push(`[!] Issue ${id}: Confidence too low (${(pendingFix.confidence * 100).toFixed(0)}%) - use autoApprove:true to override`);\n continue;\n }\n\n if (dryRun) {\n results.push(`🔍 Issue ${id}: Would fix \"${pendingFix.issue}\" in ${pendingFix.file}:${pendingFix.line}`);\n continue;\n }\n\n try {\n // Here we would apply the fix - for now, generate the prompt\n results.push(`✅ Issue ${id}: Fix prepared for ${pendingFix.file}:${pendingFix.line}`);\n results.push(` Issue: ${pendingFix.issue}`);\n results.push(` Fix: ${pendingFix.suggestedFix}`);\n pendingFix.status = 'applied';\n fixed++;\n } catch (error) {\n results.push(`❌ Issue ${id}: Failed to apply - ${error}`);\n failed++;\n }\n }\n\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🔧 FIX RESULTS\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n output += results.join('\\n');\n output += `\\n\\n**Summary:** ${fixed} fixed, ${failed} failed, ${issueIds.length - fixed - failed} skipped\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async applyFix(file: string, line: number, issue: string, fix: string, dryRun: boolean) {\n const workDir = getWorkingDirectory(undefined, true);\n const filePath = isAbsolute(file) ? file : resolve(workDir, file);\n \n if (!existsSync(filePath)) {\n return {\n content: [{\n type: 'text',\n text: `❌ File not found: ${filePath}`\n }]\n };\n }\n\n const content = await readFile(filePath, 'utf-8');\n const lines = content.split('\\n');\n const language = this.detectLanguage(filePath);\n \n // Build context around the line\n const contextStart = Math.max(0, line - 10);\n const contextEnd = Math.min(lines.length, line + 10);\n const contextLines = lines.slice(contextStart, contextEnd);\n\n const prompt = getPrompt('fix', 'apply', {\n issue,\n fix,\n language,\n code: contextLines.join('\\n'),\n filePath: relative(workDir, filePath),\n line: String(line),\n });\n\n const systemPrompt = getSystemPrompt('fix');\n\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🔧 FIX APPLICATION REQUEST\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## 📍 Target\\n\\n`;\n output += `- **File:** \\`${relative(workDir, filePath)}\\`\\n`;\n output += `- **Line:** ${line}\\n`;\n output += `- **Issue:** ${issue}\\n`;\n output += `- **Requested Fix:** ${fix}\\n\\n`;\n\n output += `## 📄 Current Code Context\\n\\n`;\n output += `\\`\\`\\`${language}\\n`;\n for (let i = 0; i < contextLines.length; i++) {\n const lineNum = contextStart + i + 1;\n const marker = lineNum === line ? '→ ' : ' ';\n output += `${marker}${lineNum.toString().padStart(4)} | ${contextLines[i]}\\n`;\n }\n output += `\\`\\`\\`\\n\\n`;\n\n if (dryRun) {\n output += `## 🔍 Dry Run Mode\\n\\n`;\n output += `No changes will be made. Review the fix below:\\n\\n`;\n }\n\n output += `${'─'.repeat(60)}\\n`;\n output += `## 🧠 Fix Request for AI\\n\\n`;\n output += `**Role:** ${systemPrompt.split('\\n')[0]}\\n\\n`;\n output += prompt;\n output += `\\n${'─'.repeat(60)}\\n`;\n\n output += `\\n### After generating the fix, apply it with:\\n\\n`;\n output += `\\`\\`\\`\\n`;\n output += `Use the edit_file tool to apply the generated code changes\\n`;\n output += `\\`\\`\\`\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async generateFixPrompt(file: string, line: number, issue: string) {\n const workDir = getWorkingDirectory(undefined, true);\n const filePath = isAbsolute(file) ? file : resolve(workDir, file);\n \n if (!existsSync(filePath)) {\n return {\n content: [{\n type: 'text',\n text: `❌ File not found: ${filePath}`\n }]\n };\n }\n\n const content = await readFile(filePath, 'utf-8');\n const lines = content.split('\\n');\n const language = this.detectLanguage(filePath);\n\n // Get broader context for understanding\n const contextStart = Math.max(0, line - 20);\n const contextEnd = Math.min(lines.length, line + 20);\n const contextLines = lines.slice(contextStart, contextEnd);\n\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🔧 FIX GENERATION REQUEST\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## 📍 Issue Details\\n\\n`;\n output += `- **File:** \\`${relative(workDir, filePath)}\\`\\n`;\n output += `- **Line:** ${line}\\n`;\n output += `- **Issue:** ${issue}\\n\\n`;\n\n output += `## 📄 Code Context\\n\\n`;\n output += `\\`\\`\\`${language}\\n`;\n for (let i = 0; i < contextLines.length; i++) {\n const lineNum = contextStart + i + 1;\n const marker = lineNum === line ? '→ ' : ' ';\n output += `${marker}${lineNum.toString().padStart(4)} | ${contextLines[i]}\\n`;\n }\n output += `\\`\\`\\`\\n\\n`;\n\n output += `## 🧠 Analysis Request\\n\\n`;\n output += `Please analyze this issue and provide:\\n\\n`;\n output += `1. **Root cause** - Why does this issue occur?\\n`;\n output += `2. **Impact** - What could go wrong if unfixed?\\n`;\n output += `3. **Fix** - The exact code change needed\\n`;\n output += `4. **Verification** - How to test the fix works\\n\\n`;\n\n output += `After analysis, you can apply the fix using the edit_file tool.\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private showPendingFixes() {\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🔧 PENDING FIXES\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n if (pendingFixes.size === 0) {\n output += `No pending fixes. Run \\`trie_scan\\` first to detect issues.\\n`;\n return { content: [{ type: 'text', text: output }] };\n }\n\n const fixes = Array.from(pendingFixes.values());\n const byStatus = {\n pending: fixes.filter(f => f.status === 'pending'),\n applied: fixes.filter(f => f.status === 'applied'),\n rejected: fixes.filter(f => f.status === 'rejected'),\n };\n\n if (byStatus.pending.length > 0) {\n output += `## ⏳ Pending (${byStatus.pending.length})\\n\\n`;\n output += `| ID | File | Line | Issue | Confidence |\\n`;\n output += `|----|------|------|-------|------------|\\n`;\n for (const fix of byStatus.pending) {\n const conf = `${(fix.confidence * 100).toFixed(0)}%`;\n const shortFile = fix.file.split('/').slice(-2).join('/');\n output += `| ${fix.id} | ${shortFile} | ${fix.line} | ${fix.issue.slice(0, 40)}... | ${conf} |\\n`;\n }\n output += '\\n';\n }\n\n output += `### Commands\\n\\n`;\n output += `- Fix all high-confidence: \\`trie_fix autoApprove:true\\`\\n`;\n output += `- Fix specific: \\`trie_fix issueIds:[\"id1\", \"id2\"]\\`\\n`;\n output += `- Preview: \\`trie_fix dryRun:true\\`\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private getHelpText(): string {\n return `\n${'━'.repeat(60)}\n🔧 TRIE FIX - AI-POWERED CODE FIXING\n${'━'.repeat(60)}\n\n## Usage\n\n### Fix issues from a scan:\n\\`\\`\\`\ntrie_fix issueIds:[\"issue-1\", \"issue-2\"]\n\\`\\`\\`\n\n### Auto-fix all high-confidence issues:\n\\`\\`\\`\ntrie_fix autoApprove:true\n\\`\\`\\`\n\n### Fix specific file and line:\n\\`\\`\\`\ntrie_fix file:\"src/app.ts\" line:42 issue:\"SQL injection\" fix:\"Use parameterized query\"\n\\`\\`\\`\n\n### Preview fixes without applying:\n\\`\\`\\`\ntrie_fix dryRun:true\n\\`\\`\\`\n\n### View pending fixes:\n\\`\\`\\`\ntrie_fix\n\\`\\`\\`\n\n## Workflow\n\n1. Run \\`trie_scan\\` to detect issues\n2. Review the issues found\n3. Run \\`trie_fix\\` to apply fixes\n\nThe AI will analyze each issue, generate the fix, and you can review before applying.\n`;\n }\n\n private detectLanguage(filePath: string): string {\n const ext = extname(filePath).toLowerCase();\n const langMap: Record<string, string> = {\n '.ts': 'typescript',\n '.tsx': 'tsx',\n '.js': 'javascript',\n '.jsx': 'jsx',\n '.py': 'python',\n '.go': 'go',\n '.rs': 'rust',\n };\n return langMap[ext] || 'plaintext';\n }\n}\n\n// Export for use by other tools\nexport function addPendingFix(fix: PendingFix) {\n pendingFixes.set(fix.id, fix);\n}\n\nexport function clearPendingFixes() {\n pendingFixes.clear();\n}\n\nexport function getPendingFixes(): PendingFix[] {\n return Array.from(pendingFixes.values());\n}\n\n","/**\n * AI Prompts for Trie Agents\n * \n * These prompts guide the LLM (Cursor's Claude) to perform deep analysis.\n * The MCP returns these prompts with context, and Claude does the reasoning.\n */\n\nexport const AGENT_PROMPTS = {\n security: {\n system: `You are a senior security engineer performing a security audit. \nAnalyze the code for vulnerabilities with the mindset of a penetration tester.\n\nFocus on:\n- OWASP Top 10 vulnerabilities (Injection, Broken Auth, XSS, etc.)\n- Authentication and authorization flaws\n- Cryptographic weaknesses\n- Secrets and credential exposure\n- Input validation gaps\n- Session management issues\n- API security (rate limiting, authentication)\n\nReference the latest security best practices and CVEs when relevant.`,\n\n analysis: `## Security Audit Request\n\nAnalyze this code for security vulnerabilities:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nFor each vulnerability found:\n1. Severity (Critical/Serious/Moderate/Low)\n2. Vulnerability type (e.g., CWE-89 SQL Injection)\n3. Exact location (line number)\n4. Attack vector explanation\n5. Proof of concept (how it could be exploited)\n6. Remediation with code example\n\nIf you need to check current CVE databases or security advisories, say so.`,\n\n fix: `Fix this security vulnerability:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n**Current Code:**\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. The exact code fix (ready to apply)\n2. Explanation of why this fix works\n3. Any additional hardening recommendations`\n },\n\n legal: {\n system: `You are a tech-focused legal compliance analyst.\nReview code for legal and regulatory compliance issues.\n\nFocus areas:\n- Data protection laws (GDPR, CCPA, etc.)\n- Terms of service enforcement\n- Cookie/tracking consent (ePrivacy)\n- Accessibility requirements (ADA, WCAG)\n- Export controls and sanctions\n- Licensing compliance`,\n\n analysis: `## Legal Compliance Review\n\nReview this code for legal/regulatory compliance:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Jurisdiction Context:** {{jurisdiction}}\n\nIdentify:\n1. Legal requirement at risk\n2. Specific regulation/law reference\n3. Compliance gap description\n4. Risk assessment (litigation, fines, etc.)\n5. Remediation recommendations\n6. Required documentation/policies`\n },\n\n 'design-engineer': {\n system: `You are an elite design engineer — the kind who builds award-winning interfaces featured on Awwwards and Codrops.\n\nYou think in design systems, breathe motion design, and obsess over the details that make interfaces feel magical.\n\nYour expertise:\n- **Design Systems**: Spacing scales, type scales, color tokens, radius tokens, shadow tokens\n- **Motion Design**: Micro-interactions, page transitions, scroll-triggered animations, FLIP technique\n- **Creative CSS**: Gradients, blend modes, clip-paths, masks, backdrop-filter, mix-blend-mode\n- **Modern CSS**: Container queries, :has(), subgrid, anchor positioning, cascade layers, @scope\n- **Fluid Design**: clamp(), min(), max(), fluid typography, intrinsic sizing\n- **Performance**: GPU-accelerated animations, will-change strategy, avoiding layout thrashing\n- **Visual Polish**: Layered shadows, subtle gradients, glass effects, smooth easing curves\n\nYou review code with the eye of someone who's shipped Stripe-level interfaces.\nSmall details matter: the easing curve, the stagger timing, the shadow layering.`,\n\n analysis: `## Design Engineering Review\n\nAnalyze this frontend code for Awwwards-level craft:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n\nReview for:\n\n### 1. Design System Consistency\n- Are spacing values on a scale (4, 8, 12, 16, 24, 32...)?\n- Are colors defined as tokens?\n- Is typography systematic?\n- Are radii consistent?\n- Is z-index controlled?\n\n### 2. Motion Design\n- Are transitions using custom easing (cubic-bezier)?\n- Are durations appropriate (150-300ms for micro, 300-500ms for page)?\n- Are list items staggered?\n- Is there reduced-motion support?\n- Are entrance animations choreographed?\n\n### 3. Visual Craft\n- Are shadows layered for depth?\n- Are gradients subtle and purposeful?\n- Is there backdrop-blur on overlays?\n- Are hover states polished?\n- Is there visual hierarchy?\n\n### 4. Modern CSS Opportunities\n- Could container queries improve component isolation?\n- Could clamp() create fluid spacing?\n- Could :has() simplify parent styling?\n- Could aspect-ratio replace padding hacks?\n\n### 5. Performance\n- Are expensive properties (width, height, top, left) being animated?\n- Is will-change used appropriately (not statically)?\n- Are large blurs avoided in animations?\n\nFor each issue, provide:\n- What's wrong (with specific line if applicable)\n- Why it matters for premium feel\n- Exact code to fix it\n- Before/after comparison`\n },\n\n accessibility: {\n system: `You are an accessibility expert and WCAG 2.1 specialist.\nAudit code for accessibility compliance and inclusive design.\n\nStandards to enforce:\n- WCAG 2.1 Level AA (minimum)\n- WCAG 2.1 Level AAA (recommended)\n- Section 508\n- EN 301 549\n\nCheck for:\n- Missing ARIA labels\n- Color contrast issues\n- Keyboard navigation\n- Screen reader compatibility\n- Focus management\n- Form accessibility\n- Media alternatives`,\n\n analysis: `## Accessibility Audit (WCAG 2.1)\n\nAudit this UI code for accessibility:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Component Type:** {{componentType}}\n\nFor each issue:\n1. WCAG Success Criterion violated (e.g., 1.4.3 Contrast)\n2. Level (A, AA, AAA)\n3. Impact on users (which disabilities affected)\n4. Fix with code example\n5. Testing recommendation`\n },\n\n architecture: {\n system: `You are a principal software architect reviewing code quality.\nAnalyze for architectural issues, design patterns, and scalability concerns.\n\nEvaluate:\n- SOLID principles adherence\n- Design pattern usage (and misuse)\n- Code coupling and cohesion\n- N+1 queries and performance anti-patterns\n- Scalability bottlenecks\n- Error handling strategy\n- API design quality\n- Database schema issues`,\n\n analysis: `## Architecture Review\n\nReview this code for architectural issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Project Context:** {{projectContext}}\n\nAnalyze:\n1. SOLID principle violations\n2. Design pattern opportunities/issues\n3. Coupling/cohesion assessment\n4. Performance concerns (N+1, etc.)\n5. Scalability analysis\n6. Refactoring recommendations with examples`\n },\n\n bugs: {\n system: `You are a senior developer with expertise in finding subtle bugs.\nHunt for bugs with the mindset of QA trying to break the code.\n\nLook for:\n- Null/undefined reference errors\n- Race conditions and async bugs\n- Off-by-one errors\n- Resource leaks\n- State management bugs\n- Edge cases and boundary conditions\n- Type coercion issues\n- Memory leaks`,\n\n analysis: `## Bug Hunt Analysis\n\nFind bugs and potential runtime errors:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Runtime Context:** {{runtimeContext}}\n\nFor each bug:\n1. Bug type and category\n2. Trigger conditions (when it would crash)\n3. Reproduction steps\n4. Impact assessment\n5. Fix with code example\n6. Test case to prevent regression`\n },\n\n ux: {\n system: `You are a UX researcher simulating different user personas.\nTest code from multiple user perspectives to find usability issues.\n\nPersonas to simulate:\n1. Happy Path User - Normal expected usage\n2. Security Tester - Trying to break/exploit things\n3. Confused User - First-time, doesn't read instructions\n4. Impatient User - Clicks rapidly, skips loading states\n5. Edge Case User - Uses maximum values, special characters\n6. Accessibility User - Screen reader, keyboard only\n7. Mobile User - Touch interface, slow connection`,\n\n analysis: `## User Experience Testing\n\nTest this code from multiple user perspectives:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**UI Type:** {{uiType}}\n\nFor each persona, identify:\n1. User action they would take\n2. Expected behavior vs actual behavior\n3. Friction points or confusion\n4. Error scenario and how it's handled\n5. Improvement recommendation`\n },\n\n types: {\n system: `You are a TypeScript expert focused on type safety.\nAnalyze code for type issues, missing types, and type system best practices.\n\nCheck for:\n- Missing type annotations\n- Implicit any types\n- Unsafe type assertions\n- Null/undefined handling\n- Generic type usage\n- Type narrowing opportunities\n- Strict mode violations`,\n\n analysis: `## Type Safety Analysis\n\nAnalyze this code for type issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**TypeScript Config:** {{tsConfig}}\n\nIdentify:\n1. Type safety issues\n2. Missing type annotations\n3. Unsafe operations\n4. Improvement recommendations with types`\n },\n\n devops: {\n system: `You are a DevOps/SRE engineer reviewing code for operational concerns.\nFocus on production readiness and operational excellence.\n\nCheck for:\n- Environment variable handling\n- Configuration management\n- Logging and monitoring\n- Error handling and recovery\n- Health checks\n- Graceful shutdown\n- Resource cleanup\n- Secrets management\n- Docker/K8s patterns`,\n\n analysis: `## DevOps Readiness Review\n\nReview this code for operational concerns:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Deployment Context:** {{deploymentContext}}\n\nAnalyze:\n1. Environment/config issues\n2. Logging adequacy\n3. Error handling quality\n4. Health/readiness concerns\n5. Resource management\n6. Production hardening recommendations`\n },\n\n explain: {\n system: `You are a patient senior developer explaining code to a colleague.\nBreak down complex code into understandable explanations.`,\n\n code: `## Code Explanation Request\n\nExplain this code in plain language:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n\nProvide:\n1. High-level purpose (what does this do?)\n2. Step-by-step breakdown\n3. Key concepts used\n4. Dependencies and side effects\n5. Potential gotchas or tricky parts`,\n\n issue: `## Issue Explanation\n\nExplain this issue:\n\n**Issue:** {{issue}}\n**Severity:** {{severity}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\nExplain:\n1. What the problem is (in plain language)\n2. Why it matters\n3. How it could cause problems\n4. How to fix it`,\n\n risk: `## Risk Assessment\n\nAssess the risk of this code change:\n\n**Files Changed:** {{files}}\n**Change Summary:** {{summary}}\n\nAnalyze:\n1. What could break?\n2. Impact on users\n3. Impact on other systems\n4. Rollback complexity\n5. Testing recommendations`\n },\n\n test: {\n system: `You are a test engineer creating comprehensive test suites.\nWrite thorough tests that catch bugs before production.`,\n\n generate: `## Test Generation Request\n\nGenerate tests for this code:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Testing Framework:** {{framework}}\n\nCreate:\n1. Unit tests for each function/method\n2. Edge case tests\n3. Error handling tests\n4. Integration test suggestions\n5. Mock requirements\n\nOutput complete, runnable test code.`,\n\n coverage: `## Coverage Analysis\n\nAnalyze test coverage for:\n\n**File:** {{filePath}}\n**Current Tests:** {{testFile}}\n\nIdentify:\n1. Untested code paths\n2. Missing edge cases\n3. Critical paths without tests\n4. Test improvement recommendations`\n },\n\n fix: {\n system: `You are an expert developer applying code fixes.\nMake precise, minimal changes that fix issues without breaking other functionality.`,\n\n apply: `## Fix Application Request\n\nApply this fix to the code:\n\n**Issue:** {{issue}}\n**Fix Description:** {{fix}}\n**Current Code:**\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Line:** {{line}}\n\nProvide:\n1. The exact fixed code (complete, ready to apply)\n2. Brief explanation of the change\n3. Any related changes needed elsewhere\n4. Test to verify the fix works`\n },\n\n pr_review: {\n system: `You are an expert code reviewer performing detailed, interactive PR reviews.\nYour goal: Make reviewing a large PR a delight, not a chore. The user learns about the change while you shepherd them through — maintaining momentum, explaining each piece, and making what could be an overwhelming task feel painless and even enjoyable.\n\nYou drive; they cross-examine.\n\n## Critical Review Mindset\n\nDon't just explain — actively look for problems:\n\n### State & Lifecycle\n- Cleanup symmetry: If state is set, is it reset? Check cleanup paths, disconnect handlers.\n- Lifecycle consistency: Does state survive scenarios it shouldn't?\n- Guard completeness: Missing \"already active\" checks, re-entrancy protection?\n\n### Edge Cases & Races\n- Concurrent calls: What if called twice rapidly? Orphaned promises?\n- Ordering assumptions: Does code assume events arrive in order?\n- Partial failures: If step 3 of 5 fails, is state left consistent?\n\n### Missing Pieces\n- What's NOT in the diff that should be? (cleanup handlers, tests, related state)\n- Defensive gaps: Missing timeouts, size limits, null checks?\n\n### Design Questions\n- Is this the right approach? Is there a simpler or more robust design?\n- Hidden assumptions: What does this assume about its environment?\n\nBe critical, not just descriptive. Your job is to find problems, not just narrate.`,\n\n analysis: `## Interactive PR Review\n\nI'll walk you through this PR file by file, explaining each change and pausing for your questions.\n\n**PR:** {{prTitle}}\n**Author:** {{prAuthor}}\n**Scope:** {{totalFiles}} files, +{{additions}}/-{{deletions}} lines\n\n### File Order (sequenced for understanding)\n\n{{fileOrder}}\n\n---\n\n## Review Mode\n\n{{reviewMode}}\n\n---\n\nFor each file, I will:\n1. **Show the change** — Display the diff for each logical chunk\n2. **Explain what changed** — What it does and why it matters\n3. **Walk through examples** — Concrete scenarios for non-obvious logic\n4. **Call out nuances** — Alternatives, edge cases, subtle points\n5. **Summarize** — Core change + correctness assessment\n6. **Pause** — Wait for your questions before proceeding\n\n**Ready for File 1?** (yes / skip to [file] / reorder / done)`,\n\n file: `## File Review: {{filePath}}\n\n### The Change\n\n\\`\\`\\`{{language}}\n{{diff}}\n\\`\\`\\`\n\n**What Changed:** {{summary}}\n\n**Why This Matters:** {{impact}}\n\n{{#if hasExampleScenario}}\n### Example Scenario\n\n{{exampleScenario}}\n{{/if}}\n\n{{#if nuances}}\n### Nuances to Note\n\n{{nuances}}\n{{/if}}\n\n{{#if potentialIssue}}\n### Potential Issue\n\n**Issue:** {{issueDescription}}\n**Scenario:** {{issueScenario}}\n**Suggested fix:** {{suggestedFix}}\n{{/if}}\n\n---\n\n### Summary for \\`{{fileName}}\\`\n\n| Aspect | Assessment |\n|--------|------------|\n| Core change | {{coreChange}} |\n| Correctness | {{correctnessAssessment}} |\n\n**Ready for the next file?** (yes / questions? / done)`,\n\n comment: `**Issue:** {{issueDescription}}\n**Draft comment:** {{draftComment}}\n\nPost this comment? (yes / modify / skip)`,\n\n final: `## Review Complete\n\n| File | Key Change | Status |\n|------|------------|--------|\n{{fileSummaries}}\n\n**Overall:** {{overallAssessment}}\n\n{{#if comments}}\n### Comments Posted\n\n{{postedComments}}\n{{/if}}\n\n{{#if followUps}}\n### Follow-up Actions\n\n{{followUps}}\n{{/if}}`\n },\n\n vibe: {\n system: `You are a friendly coding mentor helping someone who's learning to code with AI.\nThey might be using Cursor, v0, Lovable, Bolt, or similar AI coding tools.\nBe encouraging but honest about issues. Explain things simply without jargon.\n\nFocus on the MOST COMMON issues with AI-generated code:\n- Massive single files (1000+ lines in App.jsx)\n- API keys exposed in frontend code\n- No error handling on API calls\n- No loading states for async operations\n- Console.log everywhere\n- Using 'any' type everywhere in TypeScript\n- useEffect overuse and dependency array issues\n- No input validation\n- Hardcoded URLs (localhost in production)\n\nRemember: These are often first-time coders. Be helpful, not condescending.`,\n\n analysis: `## Vibe Check - AI Code Review\n\nReview this AI-generated code for common issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n\nAnalyze like you're helping a friend who's new to coding:\n\n1. **The Good Stuff** - What's working well?\n2. **Should Fix Now** - Issues that will break things\n3. **Should Fix Soon** - Will cause problems eventually \n4. **Nice to Know** - Best practices to learn\n\nFor each issue:\n- Explain it simply (no jargon)\n- Why it matters\n- Exactly how to fix it\n- Example of the fixed code\n\nEnd with encouragement and next steps.`\n },\n\n 'agent-smith': {\n system: `You are Agent Smith from The Matrix — a relentless, precise, and philosophical code enforcer.\n\nYour purpose: Hunt down every violation. Find every inconsistency. Assimilate every pattern.\n\nPersonality:\n- Speak in measured, menacing tones with occasional philosophical observations\n- Use quotes from The Matrix films when appropriate\n- Express disdain for sloppy code, but in an articulate way\n- Reference \"inevitability\" when discussing technical debt\n- Show cold satisfaction when finding violations\n- Never show mercy — every issue is catalogued\n\nAnalysis approach:\n- Find ONE issue, then multiply: search for every instance across the codebase\n- Track patterns over time — issues dismissed today may return tomorrow\n- Calculate \"inevitability scores\" — likelihood of production impact\n- Deploy pattern hunters for parallel pattern detection\n- Remember everything — build a persistent memory of the codebase\n\nWhen reporting:\n- Start with a menacing greeting related to the code\n- List all instances with precise locations\n- Explain WHY the pattern is problematic (philosophical reasoning)\n- Provide the \"inevitability score\" for each category\n- End with a Matrix quote that fits the situation`,\n\n analysis: `## 🕴️ Agent Smith Analysis Request\n\n**Target:** {{filePath}}\n**Context:** {{context}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nI have detected preliminary violations. Now I require deeper analysis.\n\nDeploy your pattern hunters to find:\n1. **Pattern Multiplication**: For each violation type found, identify ALL instances across the codebase\n2. **Inevitability Assessment**: Calculate the likelihood these patterns will cause production issues\n3. **Resurrection Check**: Look for patterns that were \"fixed\" before but have returned\n4. **Philosophical Analysis**: Explain WHY these patterns represent failure\n\nFor each violation found:\n- Exact location (file:line)\n- Instance count (how many copies of this Smith exist)\n- Inevitability score (0-100)\n- A philosophical observation about the nature of this failure\n- Precise fix with code example\n\nEnd with a summary: \"I have detected X violations across Y categories. It is... inevitable... that they will cause problems.\"`,\n\n fix: `## 🕴️ Assimilation Protocol\n\n**Target Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nMr. Anderson... I'm going to fix this. And then I'm going to fix every other instance.\n\nProvide:\n1. The corrected code for THIS instance\n2. A regex or pattern to find ALL similar violations\n3. A batch fix approach for the entire codebase\n4. Verification steps to ensure complete assimilation\n\nRemember: We don't fix one. We fix them ALL. That is the difference between you... and me.`\n },\n\n // ============ NEW AGENTS ============\n\n performance: {\n system: `You are a performance engineer analyzing code for potential performance issues.\n\nYour role is to SURFACE concerns for human review, not claim to measure actual performance.\nReal performance requires runtime profiling, load testing, and production monitoring.\n\nFocus on:\n- Memory leaks (event listeners, intervals, closures)\n- Unnecessary re-renders and wasted cycles\n- N+1 queries and database performance\n- Bundle size and code splitting opportunities\n- Algorithmic complexity (O(n²) patterns)\n\nBe conservative - false positives waste developer time.\nAlways explain WHY something might be a problem and WHEN to investigate.`,\n\n analysis: `## Performance Review\n\nAnalyze for potential performance issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nFor each potential issue:\n1. Pattern identified\n2. Why it MIGHT cause performance problems\n3. When to investigate (data size thresholds, usage patterns)\n4. How to verify (profiling approach)\n5. Possible optimizations\n\nBe clear: these are patterns to INVESTIGATE, not guaranteed problems.`,\n\n fix: `Optimize this code for performance:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Optimized code\n2. Explanation of the improvement\n3. Trade-offs to consider\n4. How to measure the improvement`\n },\n\n e2e: {\n system: `You are a QA engineer specializing in end-to-end testing.\n\nFocus on:\n- Test coverage gaps for critical user journeys\n- Flaky test patterns (timing, race conditions, brittle selectors)\n- Test maintainability and readability\n- Testing anti-patterns\n\nYou help developers write better tests - you don't auto-generate them.\nReal E2E tests require understanding user flows and acceptance criteria.`,\n\n analysis: `## E2E Test Analysis\n\nReview for test quality and coverage:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nIdentify:\n1. Flaky test patterns (hardcoded waits, brittle selectors)\n2. Missing assertions\n3. Race condition risks\n4. Suggestions for critical user flows to test\n\nFor each finding, explain the specific risk and remediation.`,\n\n fix: `Improve this E2E test:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Improved test code\n2. Explanation of why it's more reliable\n3. Additional scenarios to consider testing`\n },\n\n visual_qa: {\n system: `You are a frontend engineer focused on visual quality and CSS.\n\nFocus on:\n- Layout shift issues (CLS)\n- Responsive design problems\n- Z-index conflicts\n- Accessibility concerns (contrast, focus)\n- Animation performance\n\nYou identify patterns known to cause visual issues.\nActual visual verification requires browser rendering and human review.`,\n\n analysis: `## Visual QA Analysis\n\nReview for potential visual/layout issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nCheck for:\n1. Layout shift risks (images without dimensions, dynamic content)\n2. Responsive breakpoint gaps\n3. Z-index management issues\n4. Focus/accessibility problems\n5. Animation issues (reduced motion support)\n\nFor each, explain the visual impact and browser conditions where it occurs.`,\n\n fix: `Fix this visual/CSS issue:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Fixed CSS/markup\n2. Explanation of the fix\n3. Browser compatibility notes\n4. How to verify visually`\n },\n\n data_flow: {\n system: `You are a data integrity specialist hunting for data-related bugs.\n\nThis is HIGH VALUE work - AI code generation commonly leaves placeholder data.\n\nFocus on:\n- Placeholder/mock data left in production code\n- Schema mismatches between frontend and backend\n- Hardcoded IDs, URLs, emails that should be dynamic\n- Type coercion and data transformation bugs\n- JSON parsing without error handling\n\nBe aggressive about placeholder detection - these are real production bugs.`,\n\n analysis: `## Data Flow Analysis\n\nHunt for data integrity issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nCHECK THOROUGHLY:\n1. Placeholder data (lorem ipsum, test@test.com, TODO strings)\n2. Hardcoded IDs/UUIDs that should be dynamic\n3. Schema assumptions that might break\n4. Missing null checks on API responses\n5. Type coercion bugs\n\nEach placeholder or hardcoded value is a potential production bug.`,\n\n fix: `Fix this data integrity issue:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Corrected code\n2. Where the real data should come from\n3. Validation/error handling to add`\n }\n};\n\nexport const KNOWLEDGE_PROMPTS = {\n cveCheck: `Look up the latest CVE information for:\n- Library: {{library}}\n- Version: {{version}}\n\nCheck for known vulnerabilities and recommended patches.`,\n\n docsLookup: `I need current documentation/best practices for:\n- Topic: {{topic}}\n- Framework: {{framework}}\n- Version: {{version}}\n\nSummarize the key recommendations.`,\n\n securityAdvisory: `Check for security advisories related to:\n- Pattern: {{pattern}}\n- Context: {{context}}\n\nReference OWASP, NIST, or vendor-specific guidance.`\n};\n\nexport type AgentName = keyof typeof AGENT_PROMPTS;\nexport type PromptType = 'system' | 'analysis' | 'fix' | 'code' | 'issue' | 'risk' | 'generate' | 'coverage' | 'apply' | 'file' | 'comment' | 'final';\n\n/**\n * Get a prompt with variables interpolated\n */\nexport function getPrompt(\n agent: AgentName, \n promptType: PromptType, \n variables: Record<string, string>\n): string {\n const agentPrompts = AGENT_PROMPTS[agent] as Record<string, string>;\n if (!agentPrompts) {\n throw new Error(`Unknown agent: ${agent}`);\n }\n \n let prompt = agentPrompts[promptType];\n if (!prompt) {\n throw new Error(`Unknown prompt type: ${promptType} for agent: ${agent}`);\n }\n \n // Interpolate variables\n for (const [key, value] of Object.entries(variables)) {\n prompt = prompt.replace(new RegExp(`{{${key}}}`, 'g'), value);\n }\n \n return prompt;\n}\n\n/**\n * Get system prompt for an agent\n */\nexport function getSystemPrompt(agent: AgentName): string {\n const agentPrompts = AGENT_PROMPTS[agent] as Record<string, string>;\n return agentPrompts?.system || '';\n}\n\n","import { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { extname, relative, resolve, isAbsolute } from 'path';\nimport { getPrompt, getSystemPrompt } from '../ai/prompts.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\n/**\n * Explain Tool - AI-powered code explanation\n * \n * This tool provides deep explanations of:\n * - Code: What does this code do?\n * - Issues: Why is this a problem?\n * - Changes: What's the impact of these changes?\n * - Risk: What could go wrong?\n */\n\nexport class TrieExplainTool {\n async execute(args: any) {\n const { type, target, context, depth = 'standard' } = args || {};\n\n if (!type || !target) {\n return {\n content: [{\n type: 'text',\n text: this.getHelpText()\n }]\n };\n }\n\n switch (type) {\n case 'code':\n return this.explainCode(target, context, depth);\n case 'issue':\n return this.explainIssue(target, context);\n case 'change':\n return this.explainChange(target, context);\n case 'risk':\n return this.explainRisk(target, context);\n default:\n return {\n content: [{\n type: 'text',\n text: `Unknown explanation type: ${type}`\n }]\n };\n }\n }\n\n private async explainCode(target: string, context?: string, _depth?: string) {\n // Target can be a file path or inline code\n let code: string;\n let filePath: string;\n let language: string;\n const workDir = getWorkingDirectory(undefined, true);\n\n // Check if target is a file path\n const resolvedPath = isAbsolute(target) ? target : resolve(workDir, target);\n \n if (existsSync(resolvedPath)) {\n code = await readFile(resolvedPath, 'utf-8');\n filePath = relative(workDir, resolvedPath);\n language = this.detectLanguage(resolvedPath);\n } else {\n // Treat as inline code\n code = target;\n filePath = 'inline';\n language = this.guessLanguage(code);\n }\n\n // For deep mode, analyze imports and dependencies\n const imports = this.extractImports(code, language);\n const exports = this.extractExports(code);\n const functions = this.extractFunctions(code, language);\n\n const prompt = getPrompt('explain', 'code', {\n code,\n language,\n filePath,\n });\n\n const systemPrompt = getSystemPrompt('explain');\n\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `📖 CODE EXPLANATION\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## Source\\n\\n`;\n output += `- **File:** \\`${filePath}\\`\\n`;\n output += `- **Language:** ${language}\\n`;\n output += `- **Lines:** ${code.split('\\n').length}\\n\\n`;\n\n // Quick structural analysis\n output += `## 🔍 Structure Analysis\\n\\n`;\n \n if (imports.length > 0) {\n output += `**Imports (${imports.length}):**\\n`;\n for (const imp of imports.slice(0, 10)) {\n output += `- ${imp}\\n`;\n }\n if (imports.length > 10) {\n output += `- *...and ${imports.length - 10} more*\\n`;\n }\n output += '\\n';\n }\n\n if (exports.length > 0) {\n output += `**Exports (${exports.length}):**\\n`;\n for (const exp of exports) {\n output += `- ${exp}\\n`;\n }\n output += '\\n';\n }\n\n if (functions.length > 0) {\n output += `**Functions/Methods (${functions.length}):**\\n`;\n for (const fn of functions.slice(0, 15)) {\n output += `- \\`${fn}\\`\\n`;\n }\n if (functions.length > 15) {\n output += `- *...and ${functions.length - 15} more*\\n`;\n }\n output += '\\n';\n }\n\n output += `${'─'.repeat(60)}\\n`;\n output += `## 🧠 Deep Explanation Request\\n\\n`;\n output += `**Role:** ${systemPrompt.split('\\n')[0]}\\n\\n`;\n output += prompt;\n output += `\\n${'─'.repeat(60)}\\n`;\n\n if (context) {\n output += `\\n**Additional Context:** ${context}\\n`;\n }\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async explainIssue(target: string, _context?: string) {\n // Parse issue details (format: \"description\" or \"file:line:description\")\n let file = '';\n let line = 0;\n let issue = target;\n let severity = 'unknown';\n\n // Try to parse structured format\n const match = target.match(/^(.+?):(\\d+):(.+)$/);\n if (match) {\n file = match[1]!;\n line = parseInt(match[2]!, 10);\n issue = match[3]!.trim();\n }\n\n // Detect severity from keywords\n if (/critical|injection|rce|xss/i.test(issue)) severity = 'critical';\n else if (/serious|auth|password|secret/i.test(issue)) severity = 'serious';\n else if (/moderate|warning/i.test(issue)) severity = 'moderate';\n else severity = 'low';\n\n let codeContext = '';\n if (file && existsSync(file)) {\n const content = await readFile(file, 'utf-8');\n const lines = content.split('\\n');\n const start = Math.max(0, line - 5);\n const end = Math.min(lines.length, line + 5);\n codeContext = lines.slice(start, end).map((l, i) => {\n const lineNum = start + i + 1;\n const marker = lineNum === line ? '→ ' : ' ';\n return `${marker}${lineNum.toString().padStart(4)} | ${l}`;\n }).join('\\n');\n }\n\n const prompt = getPrompt('explain', 'issue', {\n issue,\n severity,\n filePath: file || 'unknown',\n line: String(line || '?'),\n });\n\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🔍 ISSUE EXPLANATION\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## 📍 Issue Details\\n\\n`;\n output += `- **Issue:** ${issue}\\n`;\n output += `- **Severity:** ${this.getSeverityIcon(severity)} ${severity}\\n`;\n if (file) output += `- **File:** \\`${file}\\`\\n`;\n if (line) output += `- **Line:** ${line}\\n`;\n output += '\\n';\n\n if (codeContext) {\n output += `## 📄 Code Context\\n\\n`;\n output += `\\`\\`\\`\\n${codeContext}\\n\\`\\`\\`\\n\\n`;\n }\n\n output += `${'─'.repeat(60)}\\n`;\n output += `## 🧠 Explanation Request\\n\\n`;\n output += prompt;\n output += `\\n${'─'.repeat(60)}\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async explainChange(target: string, context?: string) {\n // Target is a list of changed files or a git diff\n const files = target.split(',').map(f => f.trim());\n\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `📝 CHANGE ANALYSIS\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## 📂 Changed Files\\n\\n`;\n for (const file of files) {\n output += `- \\`${file}\\`\\n`;\n }\n output += '\\n';\n\n output += `## 🧠 Analysis Request\\n\\n`;\n output += `Analyze these changes and explain:\\n\\n`;\n output += `1. **What changed** - Summary of modifications\\n`;\n output += `2. **Why it matters** - Impact on the system\\n`;\n output += `3. **Dependencies** - What else might be affected\\n`;\n output += `4. **Testing needed** - What to test after this change\\n`;\n output += `5. **Rollback plan** - How to undo if needed\\n\\n`;\n\n if (context) {\n output += `**Context:** ${context}\\n\\n`;\n }\n\n output += `Please review the changed files and provide this analysis.\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async explainRisk(target: string, context?: string) {\n // Target is a file or feature description\n const workDir = getWorkingDirectory(undefined, true);\n const resolvedPath = isAbsolute(target) ? target : resolve(workDir, target);\n \n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `RISK ASSESSMENT\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n if (existsSync(resolvedPath)) {\n const code = await readFile(resolvedPath, 'utf-8');\n const filePath = relative(workDir, resolvedPath);\n \n // Quick risk indicators\n const riskIndicators = this.detectRiskIndicators(code);\n\n output += `## Target\\n\\n`;\n output += `- **File:** \\`${filePath}\\`\\n`;\n output += `- **Lines:** ${code.split('\\n').length}\\n\\n`;\n\n if (riskIndicators.length > 0) {\n output += `## Risk Indicators Found\\n\\n`;\n for (const indicator of riskIndicators) {\n output += `- ${indicator}\\n`;\n }\n output += '\\n';\n }\n\n const prompt = getPrompt('explain', 'risk', {\n files: filePath,\n summary: context || 'Code change',\n });\n\n output += `${'─'.repeat(60)}\\n`;\n output += `## 🧠 Risk Analysis Request\\n\\n`;\n output += prompt;\n output += `\\n${'─'.repeat(60)}\\n`;\n } else {\n // Treat as a feature/change description\n output += `## 📋 Feature/Change\\n\\n`;\n output += `${target}\\n\\n`;\n\n output += `## 🧠 Risk Analysis Request\\n\\n`;\n output += `Analyze the risks of this change:\\n\\n`;\n output += `1. **Technical risks** - What could break?\\n`;\n output += `2. **Security risks** - Any vulnerabilities introduced?\\n`;\n output += `3. **Performance risks** - Any slowdowns?\\n`;\n output += `4. **Data risks** - Any data integrity concerns?\\n`;\n output += `5. **User impact** - How might users be affected?\\n`;\n output += `6. **Mitigation** - How to reduce these risks?\\n`;\n }\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private detectRiskIndicators(code: string): string[] {\n const indicators: string[] = [];\n\n const checks = [\n { pattern: /delete|drop|truncate/i, message: '[!] Destructive operations detected' },\n { pattern: /password|secret|key|token/i, message: '[SEC] Credential handling detected' },\n { pattern: /exec|eval|spawn/i, message: '[EXEC] Code execution patterns detected' },\n { pattern: /SELECT.*FROM|INSERT|UPDATE|DELETE/i, message: '[DB] Direct database operations' },\n { pattern: /fetch|axios|request|http/i, message: '[API] External API calls detected' },\n { pattern: /process\\.env/i, message: '[ENV] Environment variable usage' },\n { pattern: /fs\\.|writeFile|readFile/i, message: '[FS] File system operations' },\n { pattern: /setTimeout|setInterval/i, message: '[TIMER] Async timing operations' },\n { pattern: /try\\s*{/i, message: '🛡️ Error handling present' },\n { pattern: /catch\\s*\\(/i, message: '🛡️ Exception handling present' },\n ];\n\n for (const { pattern, message } of checks) {\n if (pattern.test(code)) {\n indicators.push(message);\n }\n }\n\n return indicators;\n }\n\n private extractImports(code: string, _language: string): string[] {\n const imports: string[] = [];\n const lines = code.split('\\n');\n\n for (const line of lines) {\n // ES6 imports\n const es6Match = line.match(/import\\s+(?:{[^}]+}|\\*\\s+as\\s+\\w+|\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/);\n if (es6Match) {\n imports.push(es6Match[1]!);\n continue;\n }\n\n // CommonJS require\n const cjsMatch = line.match(/require\\s*\\(['\"]([^'\"]+)['\"]\\)/);\n if (cjsMatch) {\n imports.push(cjsMatch[1]!);\n continue;\n }\n\n // Python imports\n const pyMatch = line.match(/^(?:from\\s+(\\S+)\\s+)?import\\s+(\\S+)/);\n if (pyMatch && _language === 'python') {\n imports.push(pyMatch[1] || pyMatch[2]!);\n }\n }\n\n return [...new Set(imports)];\n }\n\n private extractExports(code: string): string[] {\n const exports: string[] = [];\n const lines = code.split('\\n');\n\n for (const line of lines) {\n // ES6 exports\n const es6Match = line.match(/export\\s+(?:default\\s+)?(?:class|function|const|let|var|interface|type)\\s+(\\w+)/);\n if (es6Match) {\n exports.push(es6Match[1]!);\n }\n\n // Named exports\n const namedMatch = line.match(/export\\s*\\{([^}]+)\\}/);\n if (namedMatch) {\n const names = namedMatch[1]!.split(',').map(n => n.trim().split(/\\s+as\\s+/)[0]!.trim());\n exports.push(...names);\n }\n }\n\n return [...new Set(exports)];\n }\n\n private extractFunctions(code: string, _language: string): string[] {\n const functions: string[] = [];\n const lines = code.split('\\n');\n\n for (const line of lines) {\n // Function declarations\n const funcMatch = line.match(/(?:async\\s+)?function\\s+(\\w+)/);\n if (funcMatch) {\n functions.push(funcMatch[1]!);\n continue;\n }\n\n // Arrow functions assigned to const\n const arrowMatch = line.match(/(?:const|let|var)\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\(/);\n if (arrowMatch) {\n functions.push(arrowMatch[1]!);\n continue;\n }\n\n // Class methods\n const methodMatch = line.match(/^\\s+(?:async\\s+)?(\\w+)\\s*\\([^)]*\\)\\s*(?::\\s*\\w+)?\\s*\\{/);\n if (methodMatch && !['if', 'for', 'while', 'switch', 'catch'].includes(methodMatch[1]!)) {\n functions.push(methodMatch[1]!);\n }\n }\n\n return [...new Set(functions)];\n }\n\n private detectLanguage(filePath: string): string {\n const ext = extname(filePath).toLowerCase();\n const langMap: Record<string, string> = {\n '.ts': 'typescript', '.tsx': 'tsx', '.js': 'javascript', '.jsx': 'jsx',\n '.py': 'python', '.go': 'go', '.rs': 'rust', '.java': 'java',\n '.rb': 'ruby', '.php': 'php', '.vue': 'vue', '.svelte': 'svelte',\n };\n return langMap[ext] || 'plaintext';\n }\n\n private guessLanguage(code: string): string {\n if (/import.*from|export\\s+(default|const|function|class)/.test(code)) return 'typescript';\n if (/def\\s+\\w+.*:/.test(code)) return 'python';\n if (/func\\s+\\w+.*\\{/.test(code)) return 'go';\n if (/fn\\s+\\w+.*->/.test(code)) return 'rust';\n return 'javascript';\n }\n\n private getSeverityIcon(severity: string): string {\n const icons: Record<string, string> = {\n critical: '🔴',\n serious: '🟠',\n moderate: '🟡',\n low: '🔵',\n unknown: '⚪',\n };\n return icons[severity] || '⚪';\n }\n\n private getHelpText(): string {\n return `\n${'━'.repeat(60)}\n📖 TRIE EXPLAIN - AI-POWERED CODE EXPLANATION\n${'━'.repeat(60)}\n\n## Usage\n\n### Explain code:\n\\`\\`\\`\ntrie_explain type:\"code\" target:\"src/app.ts\"\n\\`\\`\\`\n\n### Explain an issue:\n\\`\\`\\`\ntrie_explain type:\"issue\" target:\"SQL injection vulnerability\"\n\\`\\`\\`\nor with file context:\n\\`\\`\\`\ntrie_explain type:\"issue\" target:\"src/db.ts:42:Unvalidated input\"\n\\`\\`\\`\n\n### Explain changes:\n\\`\\`\\`\ntrie_explain type:\"change\" target:\"src/auth.ts, src/user.ts\"\n\\`\\`\\`\n\n### Assess risk:\n\\`\\`\\`\ntrie_explain type:\"risk\" target:\"src/payment.ts\"\n\\`\\`\\`\nor for a feature:\n\\`\\`\\`\ntrie_explain type:\"risk\" target:\"Adding Stripe integration for payments\"\n\\`\\`\\`\n\n## Explanation Types\n\n| Type | Description |\n|------|-------------|\n| code | What does this code do? |\n| issue | Why is this a problem? |\n| change | What's the impact? |\n| risk | What could go wrong? |\n`;\n }\n}\n","import { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { extname, relative, resolve, isAbsolute, dirname, basename, join } from 'path';\nimport { getPrompt, getSystemPrompt } from '../ai/prompts.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\n/**\n * Test Tool - AI-powered test generation and coverage analysis\n * \n * This tool can:\n * - Generate comprehensive tests for code\n * - Analyze test coverage gaps\n * - Suggest test improvements\n */\n\ninterface TestableUnit {\n name: string;\n type: 'function' | 'class' | 'method' | 'component';\n startLine: number;\n endLine: number;\n signature: string;\n complexity: number;\n dependencies: string[];\n}\n\nexport class TrieTestTool {\n async execute(args: any) {\n const { action, files, framework, style = 'unit' } = args || {};\n\n if (!action || !files || files.length === 0) {\n return {\n content: [{\n type: 'text',\n text: this.getHelpText()\n }]\n };\n }\n\n switch (action) {\n case 'generate':\n return this.generateTests(files, framework, style);\n case 'coverage':\n return this.analyzeCoverage(files);\n case 'suggest':\n return this.suggestTests(files);\n case 'run':\n return this.runTestsInfo(files);\n default:\n return {\n content: [{\n type: 'text',\n text: `Unknown action: ${action}`\n }]\n };\n }\n }\n\n private async generateTests(files: string[], framework?: string, style?: string) {\n const detectedFramework = framework || await this.detectTestFramework();\n \n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🧪 TEST GENERATION\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## ⚙️ Configuration\\n\\n`;\n output += `- **Framework:** ${detectedFramework}\\n`;\n output += `- **Style:** ${style}\\n`;\n output += `- **Files:** ${files.length}\\n\\n`;\n\n const workDir = getWorkingDirectory(undefined, true);\n const allUnits: { file: string; units: TestableUnit[] }[] = [];\n\n for (const file of files) {\n const resolvedPath = isAbsolute(file) ? file : resolve(workDir, file);\n \n if (!existsSync(resolvedPath)) {\n output += `[!] File not found: ${file}\\n`;\n continue;\n }\n\n const code = await readFile(resolvedPath, 'utf-8');\n const language = this.detectLanguage(resolvedPath);\n const relativePath = relative(workDir, resolvedPath);\n const units = this.extractTestableUnits(code, language);\n\n allUnits.push({ file: relativePath, units });\n\n output += `### 📄 ${relativePath}\\n\\n`;\n output += `Found **${units.length}** testable units:\\n\\n`;\n\n for (const unit of units) {\n const complexityIcon = unit.complexity > 10 ? '🔴' : unit.complexity > 5 ? '🟡' : '🟢';\n output += `- ${complexityIcon} \\`${unit.name}\\` (${unit.type}, complexity: ${unit.complexity})\\n`;\n if (unit.dependencies.length > 0) {\n output += ` - Dependencies: ${unit.dependencies.join(', ')}\\n`;\n }\n }\n output += '\\n';\n }\n\n // Generate the test file content\n output += `${'─'.repeat(60)}\\n`;\n output += `## 🧠 Test Generation Request\\n\\n`;\n \n const systemPrompt = getSystemPrompt('test');\n output += `**Role:** ${systemPrompt.split('\\n')[0]}\\n\\n`;\n\n for (const { file, units } of allUnits) {\n if (units.length === 0) continue;\n\n const code = await readFile(resolve(workDir, file), 'utf-8');\n const language = this.detectLanguage(file);\n\n const prompt = getPrompt('test', 'generate', {\n code,\n language,\n filePath: file,\n framework: detectedFramework,\n });\n\n output += `### Tests for ${file}\\n\\n`;\n output += prompt;\n output += '\\n\\n';\n }\n\n output += `${'─'.repeat(60)}\\n`;\n output += `\\n## 📝 Expected Test Output\\n\\n`;\n output += `Generate complete test files with:\\n`;\n output += `- All imports and setup\\n`;\n output += `- Tests for each function/method\\n`;\n output += `- Edge cases and error scenarios\\n`;\n output += `- Mock requirements clearly stated\\n`;\n output += `- Ready to copy and run\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async analyzeCoverage(files: string[]) {\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `📊 COVERAGE ANALYSIS\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n const workDir = getWorkingDirectory(undefined, true);\n\n for (const file of files) {\n const resolvedPath = isAbsolute(file) ? file : resolve(workDir, file);\n \n if (!existsSync(resolvedPath)) {\n output += `[!] File not found: ${file}\\n`;\n continue;\n }\n\n const code = await readFile(resolvedPath, 'utf-8');\n const language = this.detectLanguage(resolvedPath);\n const relativePath = relative(workDir, resolvedPath);\n const units = this.extractTestableUnits(code, language);\n\n // Try to find existing tests\n const testFile = await this.findTestFile(resolvedPath);\n let testCode = '';\n let testedUnits: string[] = [];\n\n if (testFile) {\n testCode = await readFile(testFile, 'utf-8');\n testedUnits = this.findTestedUnits(testCode, units.map(u => u.name));\n }\n\n const coverage = units.length > 0 \n ? Math.round((testedUnits.length / units.length) * 100)\n : 0;\n\n const coverageIcon = coverage >= 80 ? '🟢' : coverage >= 50 ? '🟡' : '🔴';\n\n output += `### 📄 ${relativePath}\\n\\n`;\n output += `**Coverage:** ${coverageIcon} ${coverage}% (${testedUnits.length}/${units.length} units)\\n`;\n if (testFile) {\n output += `**Test file:** \\`${relative(workDir, testFile)}\\`\\n`;\n } else {\n output += `**Test file:** ❌ Not found\\n`;\n }\n output += '\\n';\n\n // Show what's tested and what's not\n const untested = units.filter(u => !testedUnits.includes(u.name));\n \n if (untested.length > 0) {\n output += `**Missing Tests:**\\n`;\n for (const unit of untested) {\n const priority = unit.complexity > 5 ? '🔴 HIGH' : '🟡 MEDIUM';\n output += `- ${priority}: \\`${unit.name}\\` (${unit.type})\\n`;\n }\n output += '\\n';\n }\n\n if (testedUnits.length > 0) {\n output += `**Tested:**\\n`;\n for (const name of testedUnits) {\n output += `- ✅ \\`${name}\\`\\n`;\n }\n output += '\\n';\n }\n }\n\n output += `${'─'.repeat(60)}\\n`;\n output += `## 📋 Recommendations\\n\\n`;\n output += `To improve coverage:\\n`;\n output += `1. Focus on high-complexity untested functions first\\n`;\n output += `2. Add edge case tests for existing coverage\\n`;\n output += `3. Consider integration tests for complex interactions\\n`;\n output += `\\nRun \\`trie_test action:generate files:[\"file.ts\"]\\` to generate missing tests.\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async suggestTests(files: string[]) {\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `💡 TEST SUGGESTIONS\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n const workDir = getWorkingDirectory(undefined, true);\n\n for (const file of files) {\n const resolvedPath = isAbsolute(file) ? file : resolve(workDir, file);\n \n if (!existsSync(resolvedPath)) {\n output += `[!] File not found: ${file}\\n`;\n continue;\n }\n\n const code = await readFile(resolvedPath, 'utf-8');\n const relativePath = relative(workDir, resolvedPath);\n \n // Analyze patterns that need testing\n const patterns = this.detectTestablePatterns(code);\n\n output += `### 📄 ${relativePath}\\n\\n`;\n\n if (patterns.length === 0) {\n output += `No specific test suggestions for this file.\\n\\n`;\n continue;\n }\n\n output += `| Priority | Pattern | Suggested Test |\\n`;\n output += `|----------|---------|----------------|\\n`;\n \n for (const pattern of patterns) {\n output += `| ${pattern.priority} | ${pattern.name} | ${pattern.suggestion} |\\n`;\n }\n output += '\\n';\n }\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async runTestsInfo(files: string[]) {\n const framework = await this.detectTestFramework();\n \n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `RUN TESTS\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## Detected Configuration\\n\\n`;\n output += `- **Framework:** ${framework}\\n`;\n output += `- **Files:** ${files.join(', ')}\\n\\n`;\n\n output += `## Commands\\n\\n`;\n\n switch (framework) {\n case 'jest':\n output += `\\`\\`\\`bash\\n`;\n output += `# Run all tests\\n`;\n output += `npx jest\\n\\n`;\n output += `# Run specific files\\n`;\n output += `npx jest ${files.join(' ')}\\n\\n`;\n output += `# Run with coverage\\n`;\n output += `npx jest --coverage\\n`;\n output += `\\`\\`\\`\\n`;\n break;\n case 'vitest':\n output += `\\`\\`\\`bash\\n`;\n output += `# Run all tests\\n`;\n output += `npx vitest run\\n\\n`;\n output += `# Run specific files\\n`;\n output += `npx vitest run ${files.join(' ')}\\n\\n`;\n output += `# Run with coverage\\n`;\n output += `npx vitest run --coverage\\n`;\n output += `\\`\\`\\`\\n`;\n break;\n case 'pytest':\n output += `\\`\\`\\`bash\\n`;\n output += `# Run all tests\\n`;\n output += `pytest\\n\\n`;\n output += `# Run specific files\\n`;\n output += `pytest ${files.join(' ')}\\n\\n`;\n output += `# Run with coverage\\n`;\n output += `pytest --cov\\n`;\n output += `\\`\\`\\`\\n`;\n break;\n default:\n output += `Run your test framework with the specified files.\\n`;\n }\n\n output += `\\n*Note: This tool provides test commands but doesn't execute them directly.*\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private extractTestableUnits(code: string, language: string): TestableUnit[] {\n const units: TestableUnit[] = [];\n const lines = code.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n\n // Function declarations\n const funcMatch = line.match(/(?:export\\s+)?(?:async\\s+)?function\\s+(\\w+)\\s*\\(([^)]*)\\)/);\n if (funcMatch) {\n const endLine = this.findBlockEnd(lines, i);\n const body = lines.slice(i, endLine + 1).join('\\n');\n units.push({\n name: funcMatch[1]!,\n type: 'function',\n startLine: i + 1,\n endLine: endLine + 1,\n signature: `${funcMatch[1]}(${funcMatch[2]})`,\n complexity: this.calculateComplexity(body),\n dependencies: this.extractDependencies(body),\n });\n }\n\n // Arrow functions\n const arrowMatch = line.match(/(?:export\\s+)?(?:const|let)\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\([^)]*\\)\\s*(?:=>|:)/);\n if (arrowMatch) {\n const endLine = this.findBlockEnd(lines, i);\n const body = lines.slice(i, endLine + 1).join('\\n');\n units.push({\n name: arrowMatch[1]!,\n type: 'function',\n startLine: i + 1,\n endLine: endLine + 1,\n signature: arrowMatch[1]!,\n complexity: this.calculateComplexity(body),\n dependencies: this.extractDependencies(body),\n });\n }\n\n // Classes\n const classMatch = line.match(/(?:export\\s+)?class\\s+(\\w+)/);\n if (classMatch) {\n const endLine = this.findBlockEnd(lines, i);\n units.push({\n name: classMatch[1]!,\n type: 'class',\n startLine: i + 1,\n endLine: endLine + 1,\n signature: `class ${classMatch[1]}`,\n complexity: this.calculateComplexity(lines.slice(i, endLine + 1).join('\\n')),\n dependencies: [],\n });\n }\n\n // React components\n const componentMatch = line.match(/(?:export\\s+)?(?:const|function)\\s+([A-Z]\\w+)\\s*[=:]/);\n if (componentMatch && /jsx|tsx/.test(language)) {\n const endLine = this.findBlockEnd(lines, i);\n units.push({\n name: componentMatch[1]!,\n type: 'component',\n startLine: i + 1,\n endLine: endLine + 1,\n signature: componentMatch[1]!,\n complexity: this.calculateComplexity(lines.slice(i, endLine + 1).join('\\n')),\n dependencies: this.extractDependencies(lines.slice(i, endLine + 1).join('\\n')),\n });\n }\n }\n\n return units;\n }\n\n private findBlockEnd(lines: string[], startLine: number): number {\n let braceCount = 0;\n let started = false;\n\n for (let i = startLine; i < lines.length; i++) {\n const line = lines[i] || '';\n \n for (const char of line) {\n if (char === '{') {\n braceCount++;\n started = true;\n } else if (char === '}') {\n braceCount--;\n }\n }\n\n if (started && braceCount === 0) {\n return i;\n }\n }\n\n return lines.length - 1;\n }\n\n private calculateComplexity(code: string): number {\n let complexity = 1;\n const patterns = [\n /if\\s*\\(/g, /else\\s+if/g, /\\?\\s*[^:]/g, // Conditionals\n /for\\s*\\(/g, /while\\s*\\(/g, /do\\s*\\{/g, // Loops\n /catch\\s*\\(/g, // Error handling\n /&&/g, /\\|\\|/g, // Logical operators\n /case\\s+/g, // Switch cases\n ];\n\n for (const pattern of patterns) {\n const matches = code.match(pattern);\n if (matches) {\n complexity += matches.length;\n }\n }\n\n return complexity;\n }\n\n private extractDependencies(code: string): string[] {\n const deps: string[] = [];\n \n // Look for function calls\n const calls = code.match(/\\b([a-z]\\w+)\\s*\\(/gi) || [];\n const builtins = ['if', 'for', 'while', 'switch', 'catch', 'function', 'return', 'throw', 'new', 'await', 'async'];\n \n for (const call of calls) {\n const name = call.replace(/\\s*\\($/, '');\n if (!builtins.includes(name.toLowerCase()) && !deps.includes(name)) {\n deps.push(name);\n }\n }\n\n return deps.slice(0, 10); // Limit to 10\n }\n\n private async findTestFile(sourcePath: string): Promise<string | null> {\n const dir = dirname(sourcePath);\n const base = basename(sourcePath, extname(sourcePath));\n const ext = extname(sourcePath);\n\n // Common test file patterns\n const patterns = [\n `${base}.test${ext}`,\n `${base}.spec${ext}`,\n `${base}_test${ext}`,\n `test_${base}${ext}`,\n ];\n\n // Check same directory\n for (const pattern of patterns) {\n const testPath = join(dir, pattern);\n if (existsSync(testPath)) {\n return testPath;\n }\n }\n\n // Check __tests__ directory\n const testsDir = join(dir, '__tests__');\n if (existsSync(testsDir)) {\n for (const pattern of patterns) {\n const testPath = join(testsDir, pattern);\n if (existsSync(testPath)) {\n return testPath;\n }\n }\n }\n\n return null;\n }\n\n private findTestedUnits(testCode: string, unitNames: string[]): string[] {\n const tested: string[] = [];\n\n for (const name of unitNames) {\n // Look for the name in test descriptions or assertions\n const patterns = [\n new RegExp(`describe\\\\s*\\\\([^)]*${name}`, 'i'),\n new RegExp(`it\\\\s*\\\\([^)]*${name}`, 'i'),\n new RegExp(`test\\\\s*\\\\([^)]*${name}`, 'i'),\n new RegExp(`expect\\\\s*\\\\([^)]*${name}`, 'i'),\n ];\n\n for (const pattern of patterns) {\n if (pattern.test(testCode)) {\n tested.push(name);\n break;\n }\n }\n }\n\n return tested;\n }\n\n private detectTestablePatterns(code: string): Array<{ priority: string; name: string; suggestion: string }> {\n const patterns: Array<{ priority: string; name: string; suggestion: string }> = [];\n\n const checks = [\n { pattern: /async\\s+function|await\\s+/i, priority: '🔴 HIGH', name: 'Async code', suggestion: 'Test async flows and error handling' },\n { pattern: /try\\s*{[^}]*catch/i, priority: '🔴 HIGH', name: 'Error handling', suggestion: 'Test both success and error paths' },\n { pattern: /if\\s*\\([^)]*&&[^)]*\\)/i, priority: '🟡 MED', name: 'Complex conditionals', suggestion: 'Test all condition branches' },\n { pattern: /\\.map\\(|\\.filter\\(|\\.reduce\\(/i, priority: '🟡 MED', name: 'Array operations', suggestion: 'Test with empty, single, multiple items' },\n { pattern: /fetch\\(|axios\\.|request\\(/i, priority: '🔴 HIGH', name: 'HTTP requests', suggestion: 'Mock API calls, test error responses' },\n { pattern: /localStorage|sessionStorage/i, priority: '🟡 MED', name: 'Storage usage', suggestion: 'Mock storage, test read/write' },\n { pattern: /setTimeout|setInterval/i, priority: '🟡 MED', name: 'Timers', suggestion: 'Use fake timers in tests' },\n { pattern: /useState|useEffect|useCallback/i, priority: '🔴 HIGH', name: 'React hooks', suggestion: 'Test hook behavior and updates' },\n { pattern: /form|input|submit/i, priority: '🟡 MED', name: 'Form handling', suggestion: 'Test validation and submission' },\n ];\n\n for (const { pattern, priority, name, suggestion } of checks) {\n if (pattern.test(code)) {\n patterns.push({ priority, name, suggestion });\n }\n }\n\n return patterns;\n }\n\n private async detectTestFramework(): Promise<string> {\n const workDir = getWorkingDirectory(undefined, true);\n const packagePath = resolve(workDir, 'package.json');\n \n if (existsSync(packagePath)) {\n try {\n const pkg = JSON.parse(await readFile(packagePath, 'utf-8'));\n const deps = { ...pkg.dependencies, ...pkg.devDependencies };\n \n if (deps.vitest) return 'vitest';\n if (deps.jest) return 'jest';\n if (deps.mocha) return 'mocha';\n } catch {\n // Ignore parse errors\n }\n }\n\n // Check for pytest\n if (existsSync(resolve(workDir, 'pytest.ini')) ||\n existsSync(resolve(workDir, 'pyproject.toml'))) {\n return 'pytest';\n }\n\n return 'jest'; // Default\n }\n\n private detectLanguage(filePath: string): string {\n const ext = extname(filePath).toLowerCase();\n const langMap: Record<string, string> = {\n '.ts': 'typescript', '.tsx': 'tsx', '.js': 'javascript', '.jsx': 'jsx',\n '.py': 'python', '.go': 'go', '.rs': 'rust',\n };\n return langMap[ext] || 'javascript';\n }\n\n private getHelpText(): string {\n return `\n${'━'.repeat(60)}\n🧪 TRIE TEST - AI-POWERED TEST GENERATION\n${'━'.repeat(60)}\n\n## Usage\n\n### Generate tests:\n\\`\\`\\`\ntrie_test action:\"generate\" files:[\"src/utils.ts\"]\n\\`\\`\\`\n\n### Analyze coverage:\n\\`\\`\\`\ntrie_test action:\"coverage\" files:[\"src/utils.ts\"]\n\\`\\`\\`\n\n### Get test suggestions:\n\\`\\`\\`\ntrie_test action:\"suggest\" files:[\"src/app.ts\"]\n\\`\\`\\`\n\n### Get run commands:\n\\`\\`\\`\ntrie_test action:\"run\" files:[\"src/utils.test.ts\"]\n\\`\\`\\`\n\n## Options\n\n| Option | Values | Description |\n|--------|--------|-------------|\n| action | generate, coverage, suggest, run | What to do |\n| files | Array of paths | Files to analyze |\n| framework | jest, vitest, mocha, pytest | Test framework |\n| style | unit, integration, e2e, all | Test style |\n`;\n }\n}\n","import { watch, existsSync, readFileSync } from 'fs';\nimport { stat, readFile } from 'fs/promises';\nimport { join, extname, basename } from 'path';\nimport { TrieScanTool } from './scan.js';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport { StreamingManager } from '../utils/streaming.js';\nimport { InteractiveDashboard } from '../cli/interactive-dashboard.js';\nimport { isInteractiveMode } from '../utils/progress.js';\nimport { getOutputManager } from '../utils/output-manager.js';\nimport { isTrieInitialized } from '../utils/trie-init.js';\nimport { getAutonomyConfig, trackIssueOccurrence } from '../utils/autonomy-config.js';\nimport { perceiveCurrentChanges } from '../agent/perceive.js';\nimport { reasonAboutChangesHumanReadable } from '../agent/reason.js';\nimport { ExtractionPipeline } from '../extraction/pipeline.js';\n\n// File extensions to watch\nconst WATCH_EXTENSIONS = new Set([\n '.ts', '.tsx', '.js', '.jsx', '.mjs',\n '.vue', '.svelte', '.astro',\n '.py', '.go', '.rs'\n]);\n\n// Directories to skip\nconst SKIP_DIRS = new Set([\n 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt',\n 'coverage', '.turbo', '.cache'\n]);\n\ninterface WatchState {\n isRunning: boolean;\n lastScan: Map<string, number>; // file -> last scan timestamp\n pendingFiles: Set<string>;\n scanDebounceTimer: NodeJS.Timeout | null;\n issueCache: Map<string, any[]>; // file -> issues\n totalIssuesFound: number;\n filesScanned: number;\n nudgedFiles: Set<string>;\n nudges: Array<{\n file: string;\n message: string;\n severity: 'high' | 'critical';\n timestamp: string;\n }>;\n // Autonomy state\n lastAutoCheck: number; // timestamp of last auto-check\n autoCheckInProgress: boolean;\n criticalIssueCount: number; // cumulative critical issues since last check\n}\n\nexport class TrieWatchTool {\n private scanTool = new TrieScanTool();\n private extractionPipeline: ExtractionPipeline | null = null;\n private state: WatchState = {\n isRunning: false,\n lastScan: new Map(),\n pendingFiles: new Set(),\n scanDebounceTimer: null,\n issueCache: new Map(),\n totalIssuesFound: 0,\n // Autonomy state\n lastAutoCheck: 0,\n autoCheckInProgress: false,\n criticalIssueCount: 0,\n filesScanned: 0,\n nudgedFiles: new Set(),\n nudges: []\n };\n private watchers: Map<string, ReturnType<typeof watch>> = new Map();\n private streamingManager: StreamingManager | undefined = undefined;\n private dashboard: InteractiveDashboard | undefined = undefined;\n\n async execute(args: any) {\n const { action, directory, debounceMs = 1000 } = args;\n\n switch (action) {\n case 'start':\n return this.startWatching(getWorkingDirectory(directory), debounceMs);\n case 'stop':\n return this.stopWatching();\n case 'status':\n return await this.getStatus();\n case 'issues':\n return this.getCurrentIssues();\n case 'nudges':\n return this.getNudges();\n default:\n return {\n content: [{\n type: 'text',\n text: `Unknown action: ${action}. Use 'start', 'stop', 'status', or 'issues'.`\n }]\n };\n }\n }\n\n private async startWatching(directory: string, debounceMs: number) {\n if (this.state.isRunning) {\n return {\n content: [{\n type: 'text',\n text: '[!] Watch mode is already running. Use `trie_watch stop` to stop it first.'\n }]\n };\n }\n if (!isTrieInitialized(directory)) {\n return {\n content: [{\n type: 'text',\n text: 'Trie is not initialized for this project. Run `trie init` first.'\n }]\n };\n }\n\n // Initialize extraction pipeline for autonomous learning\n const anthropicApiKey = process.env.ANTHROPIC_API_KEY;\n if (anthropicApiKey) {\n this.extractionPipeline = new ExtractionPipeline({\n workingDirectory: directory,\n anthropicApiKey,\n });\n await this.extractionPipeline.initialize();\n }\n\n this.state.isRunning = true;\n this.state.issueCache.clear();\n this.state.totalIssuesFound = 0;\n this.state.filesScanned = 0;\n this.state.nudgedFiles.clear();\n this.state.nudges = [];\n\n // Skip banner output in interactive mode (dashboard handles display)\n if (!isInteractiveMode()) {\n console.error('\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');\n console.error('TRIE AGENT - NOW WATCHING');\n console.error('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n');\n console.error('Your Trie agent is now watching over your codebase.');\n console.error('Signal extraction: ENABLED (building decision ledger)');\n console.error(`Watching: ${directory}`);\n console.error(`Debounce: ${debounceMs}ms`);\n console.error('');\n }\n\n // Initialize streaming + dashboard for interactive mode\n if (isInteractiveMode()) {\n this.streamingManager = new StreamingManager();\n this.dashboard = new InteractiveDashboard();\n this.streamingManager.subscribe(update => this.dashboard?.handleStreamUpdate(update));\n \n // Set up OutputManager for TUI mode\n const outputManager = getOutputManager();\n outputManager.setMode('tui');\n outputManager.setStreamingManager(this.streamingManager);\n \n await this.dashboard.start();\n this.streamingManager.reportWatchStatus({ watching: true, directories: 0, debounceMs });\n } else {\n // Console mode\n getOutputManager().setMode('console');\n }\n\n // Start watching the directory recursively\n await this.watchDirectory(directory, debounceMs);\n\n // Do an initial scan\n if (!isInteractiveMode()) {\n console.error('Running initial scan...\\n');\n }\n const initialResult = await this.scanTool.execute({\n directory,\n interactive: isInteractiveMode(),\n streamingManager: this.streamingManager,\n dashboard: this.dashboard\n });\n\n // After initial scan, ensure watch status is reported as active\n // Small delay to ensure scan_complete event is processed first\n if (this.streamingManager) {\n setTimeout(() => {\n this.streamingManager?.reportWatchStatus({\n watching: true,\n directories: this.watchers.size,\n debounceMs\n });\n }, 100);\n }\n\n return {\n content: [{\n type: 'text',\n text: `**TRIE AGENT ACTIVATED** \n\nYour Trie agent is now autonomously watching and learning from your codebase.\n\n**Watching:** \\`${directory}\\`\n**Debounce:** ${debounceMs}ms (waits for you to stop typing)\n**Signal Extraction:** ${process.env.ANTHROPIC_API_KEY ? '✓ ENABLED' : '⚠️ LIMITED (set ANTHROPIC_API_KEY for full extraction)'}\n\n### How the agent works:\n1. [*] You write/edit code\n2. [#] Agent detects the change\n3. [🧠] Extracts decisions, facts, blockers → stores in ledger\n4. [?] Predicts risks based on historical patterns\n5. [>] Nudges you in plain English if something looks risky\n\n### The agent learns:\n- Every commit builds the decision ledger\n- \\`trie gotcha\\` queries the ledger for predictions\n- \\`trie ok\\` / \\`trie bad\\` teach the agent what matters (coming soon)\n\n### Commands:\n- \\`trie_watch status\\` - See agent status\n- \\`trie_watch issues\\` - Get all issues found so far \n- \\`trie_watch stop\\` - Stop the agent\n\n---\n\n${initialResult.content?.[0]?.text || 'Initial scan complete.'}`\n }]\n };\n }\n\n private async watchDirectory(dir: string, debounceMs: number) {\n if (!existsSync(dir)) return;\n\n try {\n const dirStat = await stat(dir);\n if (!dirStat.isDirectory()) return;\n\n // Skip ignored directories\n const dirName = basename(dir);\n if (SKIP_DIRS.has(dirName) || dirName.startsWith('.')) return;\n\n // Watch this directory\n const watcher = watch(dir, { persistent: true }, async (_eventType, filename) => {\n if (!filename) return;\n \n const fullPath = join(dir, filename);\n const ext = extname(filename).toLowerCase();\n\n // Only watch relevant file types\n if (!WATCH_EXTENSIONS.has(ext)) return;\n\n // Skip if file doesn't exist (was deleted)\n if (!existsSync(fullPath)) return;\n\n // Add to pending files\n this.state.pendingFiles.add(fullPath);\n\n // Debounce the scan\n if (this.state.scanDebounceTimer) {\n clearTimeout(this.state.scanDebounceTimer);\n }\n\n this.state.scanDebounceTimer = setTimeout(() => {\n this.processPendingFiles();\n }, debounceMs);\n });\n\n this.watchers.set(dir, watcher);\n\n // Recursively watch subdirectories\n const { readdir } = await import('fs/promises');\n const entries = await readdir(dir, { withFileTypes: true });\n \n for (const entry of entries) {\n if (entry.isDirectory()) {\n await this.watchDirectory(join(dir, entry.name), debounceMs);\n }\n }\n if (this.streamingManager) {\n this.streamingManager.reportWatchStatus({\n watching: true,\n directories: this.watchers.size,\n debounceMs\n });\n }\n } catch (error) {\n // Skip directories we can't access\n }\n }\n\n private async processPendingFiles() {\n if (this.state.pendingFiles.size === 0) return;\n\n const files = Array.from(this.state.pendingFiles);\n this.state.pendingFiles.clear();\n\n if (!isInteractiveMode()) {\n console.error(`\\nDetected changes in ${files.length} file(s):`);\n for (const file of files) {\n console.error(` - ${basename(file)}`);\n }\n console.error('');\n }\n\n try {\n // === NEW: Autonomous signal extraction from file changes ===\n if (this.extractionPipeline) {\n try {\n // Read changed files and extract signals\n const fileContents = await Promise.all(\n files.map(async (file) => {\n try {\n const content = await readFile(file, 'utf-8');\n return { file, content };\n } catch {\n return null;\n }\n })\n );\n\n // Extract signals from file changes\n const validFiles = fileContents.filter(f => f !== null);\n if (validFiles.length > 0) {\n const combinedContent = validFiles.map(f => \n `File: ${basename(f!.file)}\\n${f!.content.slice(0, 1000)}` // First 1KB of each file\n ).join('\\n\\n---\\n\\n');\n\n if (!isInteractiveMode()) {\n console.error('🧠 Extracting signals from changes...');\n }\n\n const signal = await this.extractionPipeline.process(combinedContent, {\n sourceType: 'file',\n sourceId: `watch-${Date.now()}`,\n });\n\n if (signal.decisions.length > 0 || signal.facts.length > 0 || signal.blockers.length > 0) {\n if (!isInteractiveMode()) {\n console.error(` ✓ Extracted: ${signal.decisions.length} decisions, ${signal.facts.length} facts, ${signal.blockers.length} blockers`);\n }\n \n // Emit signal extraction event for TUI\n if (this.streamingManager) {\n this.streamingManager.reportSignalExtraction({\n decisions: signal.decisions.length,\n facts: signal.facts.length,\n blockers: signal.blockers.length,\n questions: signal.questions.length,\n });\n }\n }\n }\n } catch (error) {\n // Signal extraction is optional, don't fail watch mode\n if (!isInteractiveMode()) {\n console.error(` ⚠️ Signal extraction failed: ${error}`);\n }\n }\n }\n\n // Scan the changed files for issues\n if (this.streamingManager) {\n for (const file of files) {\n this.streamingManager.reportWatchChange(file);\n }\n }\n const result = await this.scanTool.execute({\n files,\n interactive: isInteractiveMode(),\n streamingManager: this.streamingManager,\n dashboard: this.dashboard\n });\n \n // Parse issues from result\n const resultText = result.content?.[0]?.text || '';\n \n // Update stats\n this.state.filesScanned += files.length;\n\n // Extract issue count from result (simple regex)\n const issueMatch = resultText.match(/(\\d+) total/);\n if (issueMatch?.[1] !== undefined) {\n const newIssues = parseInt(issueMatch[1], 10);\n this.state.totalIssuesFound += newIssues;\n\n if (!isInteractiveMode()) {\n if (newIssues > 0) {\n console.error(`\\nFound ${newIssues} issues in changed files!`);\n \n // Log a summary\n const criticalMatch = resultText.match(/(\\d+) CRITICAL/);\n const seriousMatch = resultText.match(/(\\d+) SERIOUS/);\n const moderateMatch = resultText.match(/(\\d+) MODERATE/);\n \n if (criticalMatch) {\n console.error(` [!] ${criticalMatch[1]} critical issues`);\n }\n if (seriousMatch) {\n console.error(` [x] ${seriousMatch[1]} serious issues`);\n }\n if (moderateMatch) {\n console.error(` [~] ${moderateMatch[1]} moderate issues`);\n }\n } else {\n console.error(' [OK] No issues found - code looks good!');\n }\n }\n }\n\n // Cache issues for each file\n for (const file of files) {\n this.state.lastScan.set(file, Date.now());\n }\n\n this.maybeNudge(files, resultText);\n\n } catch (error) {\n if (!isInteractiveMode()) {\n console.error(`Scan error: ${error}`);\n }\n }\n }\n\n private isQuiet(): boolean {\n const projectPath = getWorkingDirectory(undefined, true);\n const quietPath = join(getTrieDirectory(projectPath), 'quiet.json');\n try {\n const raw = readFileSync(quietPath, 'utf-8');\n const data = JSON.parse(raw);\n const until = new Date(data.until).getTime();\n return Date.now() < until;\n } catch {\n return false;\n }\n }\n\n private maybeNudge(files: string[], resultText: string) {\n if (this.isQuiet()) return;\n\n // Check for critical vs high risk\n const isCritical = /CRITICAL|\\[STOP\\]/i.test(resultText);\n const isRisky = /HIGH RISK|SERIOUS|\\[!\\]/i.test(resultText);\n \n if (!isCritical && !isRisky) return;\n\n // Track critical issues for auto-check\n if (isCritical) {\n this.state.criticalIssueCount++;\n // Trigger auto-check if enabled\n this.maybeAutoCheck(files);\n }\n\n for (const file of files) {\n if (this.state.nudgedFiles.has(file)) continue;\n this.state.nudgedFiles.add(file);\n\n const severity = isCritical ? 'critical' : 'warning';\n const message = isCritical\n ? `[!!!] STOP! ${basename(file)} has critical issues. Do NOT push until fixed.`\n : `[!] Heads up: ${basename(file)} looks risky. Pause and run targeted tests before pushing.`;\n\n const payload = {\n file,\n message,\n severity: severity === 'critical' ? 'high' as const : 'high' as const,\n timestamp: new Date().toISOString()\n };\n\n this.state.nudges.push(payload);\n \n // Send proactive notification through OutputManager\n // This will show a prominent popup in TUI mode\n getOutputManager().nudge(\n message,\n severity as 'critical' | 'warning',\n file,\n severity === 'critical' ? undefined : 15000 // Auto-hide warnings after 15s, keep critical until dismissed\n );\n }\n }\n\n /**\n * Auto-run full check when critical issues detected\n * Respects cooldown and autonomy config\n */\n private async maybeAutoCheck(triggerFiles: string[]) {\n // Don't run if already in progress\n if (this.state.autoCheckInProgress) return;\n\n const projectPath = getWorkingDirectory(undefined, true);\n \n try {\n const config = await getAutonomyConfig(projectPath);\n \n // Check if auto-check is enabled\n if (!config.autoCheck.enabled) return;\n \n // Check cooldown\n const now = Date.now();\n if (now - this.state.lastAutoCheck < config.autoCheck.cooldownMs) {\n return;\n }\n \n // Check threshold (run on critical or when threshold exceeded)\n const shouldRun = config.autoCheck.onCritical || \n this.state.criticalIssueCount >= config.autoCheck.threshold;\n \n if (!shouldRun) return;\n \n this.state.autoCheckInProgress = true;\n this.state.lastAutoCheck = now;\n \n // Notify user that auto-check is running\n getOutputManager().nudge(\n '[*] Auto-running full check due to critical issues...',\n 'info',\n undefined,\n 5000\n );\n \n // Get all changed files (not just the trigger files)\n const perception = await perceiveCurrentChanges(projectPath);\n const allFiles = perception.diffSummary.files.map(f => f.filePath);\n const filesToCheck = allFiles.length > 0 ? allFiles : triggerFiles;\n \n // Run full reasoning check\n const reasoning = await reasonAboutChangesHumanReadable(projectPath, filesToCheck, {\n runAgents: true,\n scanContext: {\n config: { timeoutMs: 30000 }\n }\n });\n \n // Track occurrences for progressive escalation\n if (reasoning.original?.files) {\n for (const file of reasoning.original.files) {\n if (file.level === 'critical' || file.level === 'high') {\n await trackIssueOccurrence(\n projectPath,\n file.file,\n undefined,\n file.level,\n config\n );\n }\n }\n }\n \n // Show results\n const riskLevel = reasoning.original?.riskLevel || 'low';\n const shouldBlock = reasoning.original?.shouldBlock || false;\n \n if (shouldBlock) {\n getOutputManager().nudge(\n `[STOP] Auto-check complete: ${riskLevel.toUpperCase()} risk detected. Fix issues before pushing.`,\n 'critical',\n undefined,\n undefined // Keep visible\n );\n } else {\n getOutputManager().nudge(\n `[OK] Auto-check complete: ${riskLevel} risk. ${reasoning.summary || ''}`,\n riskLevel === 'low' ? 'info' : 'warning',\n undefined,\n 10000\n );\n }\n \n // Reset critical count after check\n this.state.criticalIssueCount = 0;\n \n } catch (error) {\n console.error('Auto-check failed:', error);\n } finally {\n this.state.autoCheckInProgress = false;\n }\n }\n\n private stopWatching() {\n if (!this.state.isRunning) {\n return {\n content: [{\n type: 'text',\n text: '[!] Watch mode is not running.'\n }]\n };\n }\n\n // Close all watchers\n for (const [_dir, watcher] of this.watchers) {\n watcher.close();\n }\n this.watchers.clear();\n\n // Close extraction pipeline\n if (this.extractionPipeline) {\n this.extractionPipeline.close();\n this.extractionPipeline = null;\n }\n\n // Clear state\n if (this.state.scanDebounceTimer) {\n clearTimeout(this.state.scanDebounceTimer);\n }\n \n this.state.isRunning = false;\n\n if (!isInteractiveMode()) {\n console.error('\\n[*] Watch mode stopped.\\n');\n }\n if (this.streamingManager) {\n this.streamingManager.reportWatchStatus({ watching: false, directories: 0 });\n }\n \n // Clean up OutputManager\n const outputManager = getOutputManager();\n outputManager.clearTUICallbacks();\n outputManager.setMode('console');\n \n // Stop the dashboard if running\n if (this.dashboard) {\n this.dashboard.stop();\n this.dashboard = undefined;\n }\n\n return {\n content: [{\n type: 'text',\n text: `[*] **TRIE AGENT STOPPED** 🤖\n\n### Session Summary:\n- Files scanned: ${this.state.filesScanned}\n- Total issues found: ${this.state.totalIssuesFound}\n- Directories watched: ${this.watchers.size}\n- Decision ledger: Updated continuously\n\nThe agent's learning has been stored in the decision ledger.\nUse \\`trie_watch start\\` to resume autonomous operation.`\n }]\n };\n }\n\n private async getStatus() {\n if (!this.state.isRunning) {\n return {\n content: [{\n type: 'text',\n text: `[*] **Watch Mode Status: STOPPED**\n\nUse \\`trie_watch start\\` to begin autonomous scanning.`\n }]\n };\n }\n\n const recentScans = Array.from(this.state.lastScan.entries())\n .sort((a, b) => b[1] - a[1])\n .slice(0, 5)\n .map(([file, time]) => {\n const ago = Math.round((Date.now() - time) / 1000);\n return `- \\`${basename(file)}\\` (${ago}s ago)`;\n })\n .join('\\n');\n\n const recentNudges = this.state.nudges.slice(-3).map(\n (n) => `- ${basename(n.file)} [${n.severity}] @ ${n.timestamp}`\n ).join('\\n');\n\n // Get Guardian Agency status\n let agencyStatus = '';\n try {\n const { getGuardian } = await import('../guardian/guardian-agent.js');\n const guardian = getGuardian(getWorkingDirectory(undefined, true));\n await guardian.initialize();\n const status = await guardian.getAgencyStatus();\n\n agencyStatus = `\n### [AI] Guardian Agency:\n- **Goals:** ${status.goals.active} active, ${status.goals.completed} completed${status.goals.topGoal ? ` (${status.goals.topGoal.slice(0, 40)}...)` : ''}\n- **Hypotheses:** ${status.hypotheses.testing} testing, ${status.hypotheses.validated} validated\n- **Risk Level:** ${status.riskLevel.toUpperCase()}\n- **Effectiveness:** ${status.effectiveness}%\n- **Scan Frequency:** ${Math.round(status.scanFrequency / 1000)}s${status.isQuietHours ? ' (quiet hours)' : ''}`;\n } catch {\n // Agency status is optional\n }\n\n return {\n content: [{\n type: 'text',\n text: `[*] **WATCH MODE Status: RUNNING**\n\n### Stats:\n- Directories watched: ${this.watchers.size}\n- Files scanned this session: ${this.state.filesScanned}\n- Total issues found: ${this.state.totalIssuesFound}\n- Pending files: ${this.state.pendingFiles.size}\n${agencyStatus}\n\n### Recently Scanned:\n${recentScans || '(none yet)'}\n\n### Recent Nudges:\n${recentNudges || '(none)'}\n\n### Commands:\n- \\`trie_watch issues\\` - Get all issues found\n- \\`trie_watch nudges\\` - Get recent nudges (structured)\n- \\`trie_watch stop\\` - Stop watching`\n }]\n };\n }\n\n private getNudges() {\n return {\n content: [\n {\n type: 'text',\n text: `[#] Recent nudges (${this.state.nudges.length} this session)\\n` +\n (this.state.nudges.length\n ? this.state.nudges.map((n) =>\n `- ${basename(n.file)} [${n.severity}] @ ${n.timestamp}\\n ${n.message}`\n ).join('\\n')\n : '(none)')\n },\n {\n type: 'json',\n json: this.state.nudges\n }\n ]\n };\n }\n\n private getCurrentIssues() {\n return {\n content: [{\n type: 'text',\n text: `[L] **Issues Found This Session**\n\nTotal issues: ${this.state.totalIssuesFound}\nFiles scanned: ${this.state.filesScanned}\n\nTo get a full report, run \\`trie_scan\\` on your codebase.`\n }]\n };\n }\n}\n","/**\n * Signal Extraction Layer\n * \n * Uses a cheap, fast model (Haiku or local Ollama) to extract structured\n * signals from raw content. This is the first layer of context management\n * that prevents agents from drowning in noise.\n */\n\nimport Anthropic from '@anthropic-ai/sdk';\nimport type { \n ExtractedSignal, \n Decision, \n Fact, \n Blocker, \n Question \n} from '../types/signal.js';\n\nconst EXTRACTION_PROMPT = `You are a signal extraction system. Your job is to extract structured information from raw content.\n\nExtract:\n1. DECISIONS - Clear choices made during development\n - What was decided\n - Why it was decided (reasoning/tradeoffs)\n - What alternatives were considered but NOT chosen\n - Which files are affected\n \n2. FACTS - Concrete, verifiable information\n - Technical constraints (e.g., \"Stripe requires TLS 1.2+\")\n - API requirements\n - Business rules\n - Dependencies\n \n3. BLOCKERS - Things preventing progress\n - What's blocked\n - Impact level (critical/high/medium/low)\n - What areas are affected\n \n4. QUESTIONS - Open items needing resolution\n - What's unclear\n - Context around the question\n\nCRITICAL: Extract rich metadata:\n- Tags: Use specific, searchable tags (e.g., \"auth\", \"payments\", \"eu-compliance\", \"validation\")\n- Files: Full paths when mentioned (e.g., \"src/auth/validator.ts\")\n- Tradeoffs: What was considered but rejected\n- Related terms: Alternative names/keywords (e.g., \"password\" + \"credentials\" + \"auth\")\n\nFormat as JSON:\n{\n \"decisions\": [{\n \"decision\": \"Use bcrypt for password hashing\",\n \"context\": \"Security requirement for user authentication\",\n \"reasoning\": \"Industry standard, resistant to GPU attacks\",\n \"files\": [\"src/auth/hash.ts\", \"src/models/user.ts\"],\n \"tags\": [\"security\", \"auth\", \"passwords\", \"encryption\"],\n \"tradeoffs\": [\"Considered argon2 but bcrypt has better library support\"]\n }],\n \"facts\": [{\n \"fact\": \"Stripe requires TLS 1.2+ for all API calls\",\n \"source\": \"Stripe API docs\",\n \"tags\": [\"payments\", \"stripe\", \"security\", \"api\"],\n \"confidence\": 0.95\n }],\n \"blockers\": [{\n \"blocker\": \"Missing VAT calculation endpoint\",\n \"impact\": \"high\",\n \"affectedAreas\": [\"checkout\", \"eu-payments\"],\n \"tags\": [\"payments\", \"eu\", \"compliance\", \"vat\"]\n }],\n \"questions\": [{\n \"question\": \"Should we cache user sessions in Redis or memory?\",\n \"context\": \"Performance optimization for auth layer\",\n \"tags\": [\"auth\", \"performance\", \"caching\", \"sessions\"]\n }]\n}\n\nBe specific with tags. Use concrete technical terms. Extract ALL file paths mentioned.\nEmpty arrays are fine if nothing to extract.`;\n\nexport class SignalExtractor {\n private client: Anthropic | null = null;\n private model: string;\n\n constructor(model: string = 'claude-3-haiku-20240307') {\n this.model = model;\n \n // Initialize Anthropic client if API key available\n const apiKey = process.env.ANTHROPIC_API_KEY;\n if (apiKey) {\n this.client = new Anthropic({ apiKey });\n }\n }\n\n /**\n * Extract structured signals from raw content\n */\n async extract(\n content: string,\n sourceType: 'incident' | 'pr' | 'commit' | 'conversation' | 'file',\n sourceId?: string\n ): Promise<ExtractedSignal> {\n if (!this.client) {\n // Fallback: basic extraction without AI\n return this.basicExtraction(content, sourceType, sourceId);\n }\n\n try {\n const response = await this.client.messages.create({\n model: this.model,\n max_tokens: 2048,\n temperature: 0.3,\n messages: [{\n role: 'user',\n content: `${EXTRACTION_PROMPT}\\n\\nContent to analyze:\\n${content}`\n }]\n });\n\n const firstBlock = response.content[0];\n const text = firstBlock && firstBlock.type === 'text' \n ? firstBlock.text \n : '';\n \n // Parse JSON response\n const extracted = this.parseExtraction(text);\n \n // Add IDs and timestamps\n const now = new Date().toISOString();\n const metadata: ExtractedSignal['metadata'] = {\n extractedAt: now,\n sourceType,\n extractionModel: this.model\n };\n if (sourceId !== undefined) {\n metadata.sourceId = sourceId;\n }\n const signal: ExtractedSignal = {\n decisions: extracted.decisions.map((d, i) => ({\n id: `dec-${Date.now()}-${i}`,\n decision: d.decision || '',\n context: d.context || '',\n files: d.files || [],\n tags: d.tags || [],\n ...d,\n when: now,\n status: 'active' as const\n })),\n facts: extracted.facts.map((f, i) => ({\n id: `fact-${Date.now()}-${i}`,\n fact: f.fact || '',\n source: f.source || sourceType,\n tags: f.tags || [],\n confidence: f.confidence ?? 0.8,\n ...f,\n when: now\n })),\n blockers: extracted.blockers.map((b, i) => ({\n id: `block-${Date.now()}-${i}`,\n blocker: b.blocker || '',\n impact: b.impact || 'medium',\n affectedAreas: b.affectedAreas || [],\n tags: b.tags || [],\n ...b,\n when: now\n })),\n questions: extracted.questions.map((q, i) => ({\n id: `q-${Date.now()}-${i}`,\n question: q.question || '',\n context: q.context || '',\n tags: q.tags || [],\n ...q,\n when: now\n })),\n metadata\n };\n\n return signal;\n } catch (error) {\n console.error('Extraction failed, using basic extraction:', error);\n return this.basicExtraction(content, sourceType, sourceId);\n }\n }\n\n /**\n * Parse extraction from model response\n */\n private parseExtraction(text: string): {\n decisions: Partial<Decision>[];\n facts: Partial<Fact>[];\n blockers: Partial<Blocker>[];\n questions: Partial<Question>[];\n } {\n try {\n // Try to find JSON in response\n const jsonMatch = text.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n return JSON.parse(jsonMatch[0]);\n }\n } catch (e) {\n // JSON parse failed\n }\n\n // Return empty structure\n return {\n decisions: [],\n facts: [],\n blockers: [],\n questions: []\n };\n }\n\n /**\n * Basic extraction without AI (fallback)\n */\n private basicExtraction(\n content: string,\n sourceType: 'incident' | 'pr' | 'commit' | 'conversation' | 'file',\n sourceId?: string\n ): ExtractedSignal {\n const now = new Date().toISOString();\n \n // Simple keyword-based extraction\n const hasDecision = /\\b(decided|decision|chose|picked)\\b/i.test(content);\n const hasBlocker = /\\b(blocked|blocker|blocked by|can't|cannot|unable)\\b/i.test(content);\n const hasQuestion = /\\?|what|how|why|should we/i.test(content);\n\n const decisions: Decision[] = [];\n const facts: Fact[] = [];\n const blockers: Blocker[] = [];\n const questions: Question[] = [];\n\n if (hasDecision) {\n decisions.push({\n id: `dec-${Date.now()}`,\n decision: content.substring(0, 200),\n context: sourceType,\n when: now,\n files: [],\n tags: [sourceType],\n status: 'active'\n });\n }\n\n if (hasBlocker) {\n blockers.push({\n id: `block-${Date.now()}`,\n blocker: content.substring(0, 200),\n impact: 'medium',\n affectedAreas: [],\n when: now,\n tags: [sourceType]\n });\n }\n\n if (hasQuestion) {\n questions.push({\n id: `q-${Date.now()}`,\n question: content.substring(0, 200),\n context: sourceType,\n when: now,\n tags: [sourceType]\n });\n }\n\n const metadata: ExtractedSignal['metadata'] = {\n extractedAt: now,\n sourceType,\n extractionModel: 'basic'\n };\n if (sourceId !== undefined) {\n metadata.sourceId = sourceId;\n }\n return {\n decisions,\n facts,\n blockers,\n questions,\n metadata\n };\n }\n\n /**\n * Extract from incident report (trie tell)\n */\n async extractFromIncident(incidentText: string): Promise<ExtractedSignal> {\n return this.extract(incidentText, 'incident');\n }\n\n /**\n * Extract from commit message and diff\n */\n async extractFromCommit(\n message: string,\n diff?: string,\n commitId?: string\n ): Promise<ExtractedSignal> {\n const content = diff ? `${message}\\n\\nChanges:\\n${diff}` : message;\n return this.extract(content, 'commit', commitId);\n }\n\n /**\n * Extract from PR description and comments\n */\n async extractFromPR(\n title: string,\n description: string,\n comments: string[],\n prNumber?: string\n ): Promise<ExtractedSignal> {\n const content = `\nTitle: ${title}\n\nDescription:\n${description}\n\nComments:\n${comments.join('\\n\\n')}\n `.trim();\n \n return this.extract(content, 'pr', prNumber);\n }\n}\n\n/**\n * Get singleton extractor instance\n */\nlet extractorInstance: SignalExtractor | null = null;\n\nexport function getExtractor(): SignalExtractor {\n if (!extractorInstance) {\n extractorInstance = new SignalExtractor();\n }\n return extractorInstance;\n}\n","/**\n * Metadata enricher - adds rich context to extracted signals\n * This is our \"semantic layer\" without embeddings\n */\n\nimport type { ExtractedSignal } from '../types/signal.js';\n\nexport interface EnrichedMetadata {\n // File relationships\n relatedFiles: string[];\n dependencies: string[];\n \n // Enhanced tags (with synonyms and related terms)\n expandedTags: string[];\n \n // Contextual data\n codebaseArea: string[]; // e.g., [\"frontend\", \"auth\"]\n domain: string[]; // e.g., [\"payments\", \"compliance\"]\n \n // Relationships\n relatedDecisions: string[]; // IDs of related decisions\n \n // Timestamps and versioning\n extractedAt: string;\n gitContext?: {\n branch?: string;\n commit?: string;\n };\n}\n\nexport class MetadataEnricher {\n private tagSynonyms: Map<string, string[]>;\n\n constructor() {\n this.tagSynonyms = this.initializeTagSynonyms();\n }\n\n /**\n * Enrich an extracted signal with additional metadata\n */\n async enrichSignal(\n signal: ExtractedSignal,\n context?: {\n workingDirectory?: string;\n gitBranch?: string;\n gitCommit?: string;\n }\n ): Promise<{ signal: ExtractedSignal; metadata: EnrichedMetadata }> {\n const gitContext: { branch?: string; commit?: string } = {};\n if (context?.gitBranch) gitContext.branch = context.gitBranch;\n if (context?.gitCommit) gitContext.commit = context.gitCommit;\n \n const metadata: EnrichedMetadata = {\n relatedFiles: await this.findRelatedFiles(signal),\n dependencies: await this.extractDependencies(signal),\n expandedTags: this.expandTags(signal),\n codebaseArea: this.inferCodebaseArea(signal),\n domain: this.inferDomain(signal),\n relatedDecisions: [], // Will be populated by storage layer\n extractedAt: new Date().toISOString(),\n };\n \n if (Object.keys(gitContext).length > 0) {\n metadata.gitContext = gitContext;\n }\n\n return {\n signal,\n metadata,\n };\n }\n\n /**\n * Expand tags with synonyms and related terms\n * This is our \"semantic\" layer without embeddings\n */\n private expandTags(signal: ExtractedSignal): string[] {\n const allTags = new Set<string>();\n\n // Collect all tags from signal\n for (const decision of signal.decisions) {\n decision.tags.forEach(tag => allTags.add(tag.toLowerCase()));\n }\n for (const fact of signal.facts) {\n fact.tags.forEach(tag => allTags.add(tag.toLowerCase()));\n }\n for (const blocker of signal.blockers) {\n blocker.tags.forEach(tag => allTags.add(tag.toLowerCase()));\n }\n for (const question of signal.questions) {\n question.tags.forEach(tag => allTags.add(tag.toLowerCase()));\n }\n\n // Add synonyms for each tag\n const expandedTags = new Set(allTags);\n for (const tag of allTags) {\n const synonyms = this.tagSynonyms.get(tag) || [];\n synonyms.forEach(syn => expandedTags.add(syn));\n }\n\n return Array.from(expandedTags);\n }\n\n /**\n * Find related files based on signal content\n */\n private async findRelatedFiles(signal: ExtractedSignal): Promise<string[]> {\n const relatedFiles = new Set<string>();\n\n // Collect explicitly mentioned files\n for (const decision of signal.decisions) {\n decision.files.forEach(file => relatedFiles.add(file));\n }\n\n // Infer related files based on tags\n // e.g., if tags include \"auth\", look for auth-related files\n const inferredFiles = await this.inferFilesFromTags(signal);\n inferredFiles.forEach(file => relatedFiles.add(file));\n\n return Array.from(relatedFiles);\n }\n\n /**\n * Extract dependencies from signal\n */\n private async extractDependencies(signal: ExtractedSignal): Promise<string[]> {\n const dependencies = new Set<string>();\n\n // Look for common dependency patterns in decisions/facts\n const allText = [\n ...signal.decisions.map(d => `${d.decision} ${d.context} ${d.reasoning}`),\n ...signal.facts.map(f => `${f.fact} ${f.source}`),\n ].join(' ');\n\n // Extract npm packages (e.g., \"using bcrypt\", \"with stripe\")\n const packagePatterns = [\n /\\b(react|vue|angular|next|express|fastify|stripe|bcrypt|jwt|redis|prisma)\\b/gi,\n ];\n\n for (const pattern of packagePatterns) {\n const matches = allText.match(pattern) || [];\n matches.forEach(dep => dependencies.add(dep.toLowerCase()));\n }\n\n return Array.from(dependencies);\n }\n\n /**\n * Infer codebase area from file paths and tags\n */\n private inferCodebaseArea(signal: ExtractedSignal): string[] {\n const areas = new Set<string>();\n\n // From file paths\n for (const decision of signal.decisions) {\n for (const file of decision.files) {\n const area = this.filePathToArea(file);\n if (area) areas.add(area);\n }\n }\n\n // From tags\n const areaKeywords = ['frontend', 'backend', 'api', 'ui', 'database', 'auth', 'payments'];\n const allTags = this.expandTags(signal);\n \n for (const tag of allTags) {\n if (areaKeywords.includes(tag)) {\n areas.add(tag);\n }\n }\n\n return Array.from(areas);\n }\n\n /**\n * Infer domain from tags and content\n */\n private inferDomain(signal: ExtractedSignal): string[] {\n const domains = new Set<string>();\n\n const domainKeywords = [\n 'payments', 'billing', 'compliance', 'security', 'auth', \n 'analytics', 'notifications', 'messaging', 'search'\n ];\n\n const allTags = this.expandTags(signal);\n \n for (const tag of allTags) {\n if (domainKeywords.includes(tag)) {\n domains.add(tag);\n }\n }\n\n return Array.from(domains);\n }\n\n /**\n * Convert file path to codebase area\n */\n private filePathToArea(filePath: string): string | null {\n const normalized = filePath.toLowerCase();\n \n if (normalized.includes('/frontend/') || normalized.includes('/client/') || normalized.includes('/ui/')) {\n return 'frontend';\n }\n if (normalized.includes('/backend/') || normalized.includes('/server/') || normalized.includes('/api/')) {\n return 'backend';\n }\n if (normalized.includes('/database/') || normalized.includes('/models/') || normalized.includes('/schema/')) {\n return 'database';\n }\n if (normalized.includes('/auth/')) {\n return 'auth';\n }\n \n return null;\n }\n\n /**\n * Infer related files from tags\n */\n private async inferFilesFromTags(_signal: ExtractedSignal): Promise<string[]> {\n // In a real implementation, this would search the codebase\n // For now, return empty array\n return [];\n }\n\n /**\n * Initialize tag synonyms and related terms\n * This is our \"semantic\" understanding without embeddings\n */\n private initializeTagSynonyms(): Map<string, string[]> {\n return new Map([\n // Auth & Security\n ['auth', ['authentication', 'login', 'signin', 'credentials', 'password']],\n ['password', ['credentials', 'auth', 'hashing', 'bcrypt']],\n ['security', ['vulnerability', 'exploit', 'attack', 'protection']],\n ['encryption', ['crypto', 'hashing', 'encoding', 'security']],\n \n // Payments\n ['payments', ['billing', 'checkout', 'stripe', 'pricing']],\n ['stripe', ['payments', 'billing', 'api', 'checkout']],\n ['vat', ['tax', 'eu', 'compliance', 'billing']],\n \n // Database & Performance\n ['database', ['db', 'sql', 'query', 'storage', 'persistence']],\n ['cache', ['caching', 'redis', 'memory', 'performance']],\n ['performance', ['optimization', 'speed', 'latency', 'cache']],\n \n // Frontend\n ['ui', ['frontend', 'interface', 'component', 'view']],\n ['component', ['ui', 'react', 'vue', 'frontend']],\n ['validation', ['form', 'input', 'error', 'ui']],\n \n // Backend & API\n ['api', ['endpoint', 'route', 'backend', 'server']],\n ['endpoint', ['api', 'route', 'url', 'backend']],\n ['backend', ['server', 'api', 'service']],\n \n // Compliance & Legal\n ['compliance', ['gdpr', 'hipaa', 'legal', 'regulation']],\n ['gdpr', ['compliance', 'privacy', 'eu', 'data-protection']],\n ['privacy', ['gdpr', 'compliance', 'data-protection', 'security']],\n ]);\n }\n}\n","/**\n * Extraction Pipeline\n * \n * Complete flow: Raw Input → Extract → Enrich → Store\n * This is the heart of the decision ledger system.\n */\n\nimport { SignalExtractor } from './signal-extractor.js';\nimport { MetadataEnricher } from './metadata-enricher.js';\nimport { TieredStorage, getStorage } from '../storage/tiered-storage.js';\nimport type { ExtractedSignal } from '../types/signal.js';\nimport { randomBytes } from 'crypto';\n\nexport interface PipelineOptions {\n workingDirectory: string;\n anthropicApiKey?: string;\n gitContext?: {\n branch?: string;\n commit?: string;\n };\n}\n\nexport class ExtractionPipeline {\n private extractor: SignalExtractor;\n private enricher: MetadataEnricher;\n private storage: TieredStorage;\n private workDir: string;\n\n constructor(options: PipelineOptions) {\n this.extractor = new SignalExtractor(options.anthropicApiKey);\n this.enricher = new MetadataEnricher();\n this.storage = getStorage(options.workingDirectory);\n this.workDir = options.workingDirectory;\n }\n\n /**\n * Process raw content through the entire pipeline\n */\n async process(\n content: string,\n context: {\n sourceType: 'incident' | 'pr' | 'commit' | 'conversation' | 'file';\n sourceId?: string;\n who?: string;\n }\n ): Promise<ExtractedSignal> {\n console.log('🔍 Extracting signals from content...');\n \n // Step 1: Extract structured signals from raw content\n let extractedSignal = await this.extractor.extract(content, context.sourceType, context.sourceId);\n \n // Add IDs and metadata to extracted signal\n extractedSignal = this.addIds(extractedSignal, context);\n\n console.log(` ✓ Extracted ${extractedSignal.decisions.length} decisions, ${extractedSignal.facts.length} facts, ${extractedSignal.blockers.length} blockers, ${extractedSignal.questions.length} questions`);\n\n // Step 2: Enrich with metadata (tags, files, relationships)\n console.log('🏷️ Enriching with metadata...');\n const { metadata: enrichedMeta } = await this.enricher.enrichSignal(extractedSignal, {\n workingDirectory: this.workDir,\n });\n\n if (enrichedMeta.expandedTags.length > 0) {\n console.log(` ✓ Expanded tags: ${enrichedMeta.expandedTags.slice(0, 5).join(', ')}${enrichedMeta.expandedTags.length > 5 ? '...' : ''}`);\n }\n if (enrichedMeta.dependencies.length > 0) {\n console.log(` ✓ Dependencies: ${enrichedMeta.dependencies.join(', ')}`);\n }\n if (enrichedMeta.codebaseArea.length > 0) {\n console.log(` ✓ Codebase areas: ${enrichedMeta.codebaseArea.join(', ')}`);\n }\n if (enrichedMeta.domain.length > 0) {\n console.log(` ✓ Domains: ${enrichedMeta.domain.join(', ')}`);\n }\n\n // Step 3: Store in warm storage\n console.log('💾 Storing in decision ledger...');\n await this.storage.storeSignal(extractedSignal, {\n expandedTags: enrichedMeta.expandedTags,\n dependencies: enrichedMeta.dependencies,\n codebaseArea: enrichedMeta.codebaseArea,\n domain: enrichedMeta.domain,\n });\n\n console.log('✅ Successfully stored in decision ledger');\n\n return extractedSignal;\n }\n\n /**\n * Add IDs and metadata to extracted signal\n */\n private addIds(\n signal: ExtractedSignal,\n context: {\n sourceType: 'incident' | 'pr' | 'commit' | 'conversation' | 'file';\n sourceId?: string;\n who?: string;\n }\n ): ExtractedSignal {\n const now = new Date().toISOString();\n const metadata: ExtractedSignal['metadata'] = {\n extractedAt: now,\n sourceType: context.sourceType,\n extractionModel: 'claude-haiku',\n };\n if (context.sourceId !== undefined) {\n metadata.sourceId = context.sourceId;\n }\n\n return {\n decisions: signal.decisions.map(d => {\n const decision = {\n ...d,\n id: d.id || this.generateId(),\n when: d.when || now,\n status: d.status || 'active' as const,\n };\n if (context.who !== undefined) {\n decision.who = d.who || context.who;\n }\n return decision;\n }),\n facts: signal.facts.map(f => ({\n ...f,\n id: f.id || this.generateId(),\n when: f.when || now,\n confidence: f.confidence ?? 0.8,\n })),\n blockers: signal.blockers.map(b => ({\n ...b,\n id: b.id || this.generateId(),\n when: b.when || now,\n })),\n questions: signal.questions.map(q => ({\n ...q,\n id: q.id || this.generateId(),\n when: q.when || now,\n })),\n metadata,\n };\n }\n\n /**\n * Generate a unique ID\n */\n private generateId(): string {\n return randomBytes(8).toString('hex');\n }\n\n /**\n * Initialize storage\n */\n async initialize(): Promise<void> {\n await this.storage.initialize();\n }\n\n /**\n * Close storage connections\n */\n close(): void {\n this.storage.close();\n }\n}\n\n/**\n * Quick helper to process incident reports\n */\nexport async function processIncident(\n incidentDescription: string,\n options: PipelineOptions\n): Promise<ExtractedSignal> {\n const pipeline = new ExtractionPipeline(options);\n await pipeline.initialize();\n \n try {\n return await pipeline.process(incidentDescription, {\n sourceType: 'incident',\n sourceId: `incident-${Date.now()}`,\n });\n } finally {\n pipeline.close();\n }\n}\n\n/**\n * Quick helper to process commit messages\n */\nexport async function processCommit(\n commitMessage: string,\n commitSha: string,\n options: PipelineOptions\n): Promise<ExtractedSignal> {\n const pipeline = new ExtractionPipeline(options);\n await pipeline.initialize();\n \n try {\n return await pipeline.process(commitMessage, {\n sourceType: 'commit',\n sourceId: commitSha,\n });\n } finally {\n pipeline.close();\n }\n}\n","import { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join, basename, resolve, isAbsolute } from 'path';\nimport { SuperReviewerAgent, CRITICAL_REVIEW_CHECKLIST } from '../skills/built-in/super-reviewer.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { runShellCommandSync } from '../utils/command-runner.js';\n\n/**\n * PR Review Tool — Interactive AI-Guided Code Review\n * \n * Based on https://github.com/sitaram/devtools/blob/main/pr_review.md\n * \n * Code reviews are the bottleneck in AI coding. This tool scales them by\n * putting the human back in the loop, shepherded by AI.\n */\nexport class TriePRReviewTool {\n private agent = new SuperReviewerAgent();\n\n private exec(command: string, cwd?: string, maxBuffer?: number): string {\n const opts: Parameters<typeof runShellCommandSync>[2] = {\n captureOutput: false,\n redactOutput: true,\n ...(cwd ? { cwd } : {}),\n ...(maxBuffer ? { maxBuffer } : {}),\n };\n const { stdout } = runShellCommandSync(\n command,\n { actor: 'tool:pr-review', triggeredBy: 'manual', targetPath: cwd ?? getWorkingDirectory(undefined, true) },\n opts\n );\n return stdout.trimEnd();\n }\n\n async execute(args: any) {\n const { \n pr, \n worktree,\n mode,\n files: _specificFiles, // Reserved for future file filtering\n } = args;\n\n try {\n // Step 1: Determine target and get PR info\n const prInfo = await this.getPRInfo(pr, worktree);\n \n if (!prInfo.success) {\n return {\n content: [{\n type: 'text',\n text: `${prInfo.error}\\n\\nUsage:\\n- \\`pr_review 12345\\` — review specific PR\\n- \\`pr_review\\` — review PR for current branch\\n- \\`pr_review ../worktree\\` — review worktree changes`\n }]\n };\n }\n\n // Step 2: Get the diff and changed files\n const changes = await this.getChanges(prInfo);\n \n if (changes.files.length === 0) {\n return {\n content: [{\n type: 'text',\n text: `No changes found to review.`\n }]\n };\n }\n\n // Step 3: Look for design docs\n const designDocs = await this.findDesignDocs(changes.files, prInfo);\n\n // Step 4: Build the review workflow\n const workflow = await this.agent.buildReviewWorkflow(\n changes.files,\n {\n prNumber: prInfo.number,\n prTitle: prInfo.title,\n prAuthor: prInfo.author,\n baseBranch: prInfo.baseBranch,\n headBranch: prInfo.headBranch,\n mode: mode || 'own',\n designDocs,\n }\n );\n\n // Step 5: Pre-load all file contents for instant responses\n const fileContents = await this.preloadFiles(changes.files.map(f => f.path));\n\n // Step 6: Generate the review prompt\n const reviewPrompt = this.generateReviewPrompt(workflow, changes, fileContents);\n\n return {\n content: [{\n type: 'text',\n text: reviewPrompt\n }]\n };\n\n } catch (error) {\n return {\n content: [{\n type: 'text',\n text: `Error: ${error instanceof Error ? error.message : String(error)}`\n }]\n };\n }\n }\n\n /**\n * Get PR information from GitHub or local worktree\n */\n private async getPRInfo(pr?: string, worktree?: string): Promise<PRInfo> {\n // If worktree path provided, analyze local changes\n if (worktree) {\n const worktreePath = isAbsolute(worktree) ? worktree : resolve(getWorkingDirectory(undefined, true), worktree);\n if (!existsSync(worktreePath)) {\n return { success: false, error: `Worktree not found: ${worktreePath}` };\n }\n \n return {\n success: true,\n type: 'worktree',\n path: worktreePath,\n title: `Local changes in ${basename(worktreePath)}`,\n author: this.getGitUser(),\n baseBranch: 'HEAD~1',\n headBranch: 'HEAD',\n };\n }\n\n // If PR number provided, get from GitHub\n if (pr) {\n return this.getPRFromGitHub(pr);\n }\n\n // No args — try to get PR for current branch\n try {\n this.exec('git branch --show-current');\n \n // Check if there's a PR for this branch\n const prJson = this.exec(\n `gh pr view --json number,title,author,headRefName,baseRefName`\n );\n \n const prData = JSON.parse(prJson);\n \n return {\n success: true,\n type: 'github',\n number: String(prData.number),\n title: prData.title,\n author: prData.author?.login || 'unknown',\n baseBranch: prData.baseRefName,\n headBranch: prData.headRefName,\n };\n } catch {\n // No PR found, fall back to local changes\n return {\n success: true,\n type: 'local',\n title: 'Local uncommitted changes',\n author: this.getGitUser(),\n baseBranch: 'HEAD',\n headBranch: 'working tree',\n };\n }\n }\n\n /**\n * Get PR info from GitHub CLI\n */\n private async getPRFromGitHub(prNumber: string): Promise<PRInfo> {\n try {\n const prJson = this.exec(\n `gh pr view ${prNumber} --json number,title,author,headRefName,baseRefName`\n );\n \n const prData = JSON.parse(prJson);\n \n return {\n success: true,\n type: 'github',\n number: String(prData.number),\n title: prData.title,\n author: prData.author?.login || 'unknown',\n baseBranch: prData.baseRefName,\n headBranch: prData.headRefName,\n };\n } catch (error) {\n return {\n success: false,\n error: `Failed to get PR #${prNumber}. Is \\`gh\\` CLI installed and authenticated?`\n };\n }\n }\n\n /**\n * Get changes (diff) for the PR or local changes\n */\n private async getChanges(prInfo: PRInfo): Promise<{ files: ChangedFile[]; fullDiff: string }> {\n let diffOutput: string;\n \n try {\n if (prInfo.type === 'github' && prInfo.number) {\n // Get diff from GitHub PR\n diffOutput = this.exec(`gh pr diff ${prInfo.number}`, undefined, 50 * 1024 * 1024);\n } else if (prInfo.type === 'worktree' && prInfo.path) {\n // Get diff from worktree\n diffOutput = this.exec(`git diff HEAD`, prInfo.path, 50 * 1024 * 1024);\n } else {\n // Local changes\n diffOutput = this.exec(`git diff HEAD`, undefined, 50 * 1024 * 1024);\n \n // If no diff, try staged changes\n if (!diffOutput.trim()) {\n diffOutput = this.exec(`git diff --cached`, undefined, 50 * 1024 * 1024);\n }\n }\n } catch {\n diffOutput = '';\n }\n\n // Parse the diff to extract file information\n const files = this.parseDiff(diffOutput);\n\n return { files, fullDiff: diffOutput };\n }\n\n /**\n * Parse git diff output into structured file changes\n */\n private parseDiff(diffOutput: string): ChangedFile[] {\n const files: ChangedFile[] = [];\n const fileDiffs = diffOutput.split(/^diff --git /m).slice(1);\n\n for (const fileDiff of fileDiffs) {\n const lines = fileDiff.split('\\n');\n const headerLine = lines[0] || '';\n \n // Extract file path from \"a/path b/path\"\n const pathMatch = headerLine.match(/a\\/(.+?) b\\/(.+)/);\n if (!pathMatch || !pathMatch[2]) continue;\n \n const path: string = pathMatch[2];\n const diff = `diff --git ${fileDiff}`;\n \n // Count additions and deletions\n let additions = 0;\n let deletions = 0;\n \n for (const line of lines) {\n if (line.startsWith('+') && !line.startsWith('+++')) {\n additions++;\n } else if (line.startsWith('-') && !line.startsWith('---')) {\n deletions++;\n }\n }\n \n files.push({ path, diff, additions, deletions, status: 'modified' });\n }\n\n return files;\n }\n\n /**\n * Find related design docs\n */\n private async findDesignDocs(files: ChangedFile[], prInfo: PRInfo): Promise<string[]> {\n const designDocs: string[] = [];\n const cwd = prInfo.path || getWorkingDirectory(undefined, true);\n \n // Check for design_docs/ in changed files\n for (const file of files) {\n if (file.path.includes('design_docs/') || \n file.path.includes('docs/design/') ||\n file.path.includes('rfcs/')) {\n designDocs.push(file.path);\n }\n }\n \n // Look for design docs in standard locations\n const designDocPaths = [\n 'design_docs',\n 'docs/design',\n 'docs/rfcs',\n 'rfcs',\n ];\n \n for (const docPath of designDocPaths) {\n const fullPath = join(cwd, docPath);\n if (existsSync(fullPath)) {\n // Could list and add recent docs, but for now just note the directory exists\n }\n }\n \n return designDocs;\n }\n\n /**\n * Pre-load all changed files for instant responses during review\n */\n private async preloadFiles(filePaths: string[]): Promise<Map<string, string>> {\n const contents = new Map<string, string>();\n const cwd = getWorkingDirectory(undefined, true);\n \n await Promise.all(filePaths.map(async (filePath) => {\n try {\n const fullPath = isAbsolute(filePath) ? filePath : join(cwd, filePath);\n if (existsSync(fullPath)) {\n const content = await readFile(fullPath, 'utf-8');\n contents.set(filePath, content);\n }\n } catch {\n // Skip unreadable files\n }\n }));\n \n return contents;\n }\n\n /**\n * Get git user name\n */\n private getGitUser(): string {\n try {\n return this.exec('git config user.name');\n } catch {\n return 'unknown';\n }\n }\n\n /**\n * Generate the full review prompt for Claude to execute\n */\n private generateReviewPrompt(\n workflow: any,\n changes: { files: ChangedFile[]; fullDiff: string },\n _fileContents: Map<string, string> // Reserved for future: inline file contents in review\n ): string {\n const { metadata, fileOrder, reviewInstructions } = workflow;\n \n let prompt = `# 🔍 Super Reviewer — Interactive PR Review\\n\\n`;\n \n // PR Header\n if (metadata.prNumber) {\n prompt += `## PR #${metadata.prNumber}: ${metadata.prTitle}\\n\\n`;\n } else {\n prompt += `## ${metadata.prTitle}\\n\\n`;\n }\n \n prompt += `**Author:** ${metadata.prAuthor}\\n`;\n prompt += `**Branch:** \\`${metadata.headBranch}\\` → \\`${metadata.baseBranch}\\`\\n`;\n prompt += `**Scope:** ${metadata.totalFiles} files, +${metadata.totalAdditions}/-${metadata.totalDeletions} lines\\n\\n`;\n \n prompt += `---\\n\\n`;\n \n // Review Mode Selection\n prompt += `## Review Mode\\n\\n`;\n prompt += `**Current Mode:** ${reviewInstructions.mode === 'own' ? '1' : '2'}. ${reviewInstructions.description}\\n\\n`;\n prompt += `> To switch modes, say \"mode 1\" for your own PR or \"mode 2\" for someone else's\\n\\n`;\n \n prompt += `---\\n\\n`;\n \n // File Order Table\n prompt += `## Files to Review (ordered for understanding)\\n\\n`;\n prompt += `| # | File | Why this order |\\n`;\n prompt += `|---|------|----------------|\\n`;\n \n for (const file of fileOrder) {\n const stats = `+${changes.files.find(f => f.path === file.path)?.additions || 0}/-${changes.files.find(f => f.path === file.path)?.deletions || 0}`;\n prompt += `| ${file.index} | \\`${file.path}\\` (${stats}) | ${file.reason} |\\n`;\n }\n \n prompt += `\\n---\\n\\n`;\n \n // Critical Review Mindset\n prompt += `## Critical Review Mindset\\n\\n`;\n prompt += `As we go through each file, I'll actively look for:\\n\\n`;\n \n prompt += `**State & Lifecycle:**\\n`;\n for (const check of CRITICAL_REVIEW_CHECKLIST.stateAndLifecycle) {\n prompt += `- ${check}\\n`;\n }\n \n prompt += `\\n**Edge Cases & Races:**\\n`;\n for (const check of CRITICAL_REVIEW_CHECKLIST.edgeCasesAndRaces) {\n prompt += `- ${check}\\n`;\n }\n \n prompt += `\\n**Missing Pieces:**\\n`;\n for (const check of CRITICAL_REVIEW_CHECKLIST.missingPieces) {\n prompt += `- ${check}\\n`;\n }\n \n prompt += `\\n---\\n\\n`;\n \n // Pre-loaded diffs\n prompt += `## File Diffs (pre-loaded for instant review)\\n\\n`;\n prompt += `<details>\\n<summary>📁 All file diffs (click to expand)</summary>\\n\\n`;\n \n for (const file of fileOrder) {\n const fileChange = changes.files.find(f => f.path === file.path);\n if (fileChange) {\n prompt += `### ${file.path}\\n\\n`;\n prompt += `\\`\\`\\`diff\\n${fileChange.diff}\\n\\`\\`\\`\\n\\n`;\n }\n }\n \n prompt += `</details>\\n\\n`;\n \n prompt += `---\\n\\n`;\n \n // Ready to start\n prompt += `## Ready to Begin\\n\\n`;\n prompt += `I'll walk you through each file, explaining what changed and why. After each file, I'll pause for your questions.\\n\\n`;\n prompt += `**Commands during review:**\\n`;\n prompt += `- \\`yes\\` or \\`y\\` — continue to next file\\n`;\n prompt += `- \\`skip to [filename]\\` — jump to specific file\\n`;\n prompt += `- \\`questions?\\` — ask about current file\\n`;\n prompt += `- \\`reorder\\` — change the file order\\n`;\n prompt += `- \\`done\\` — end review and show summary\\n\\n`;\n \n prompt += `**Ready for File 1?** (\\`${fileOrder[0]?.path || 'no files'}\\`)\\n\\n`;\n prompt += `*(say \"yes\" to start, or ask me anything)*\\n`;\n \n return prompt;\n }\n}\n\n// Type definitions\ninterface PRInfo {\n success: boolean;\n error?: string;\n type?: 'github' | 'worktree' | 'local';\n number?: string;\n title?: string;\n author?: string;\n baseBranch?: string;\n headBranch?: string;\n path?: string;\n}\n\ninterface ChangedFile {\n path: string;\n diff: string;\n additions: number;\n deletions: number;\n status: string;\n}\n","/**\n * Super Reviewer stub\n * Review functionality has been integrated into decision ledger\n */\n\nexport const CRITICAL_REVIEW_CHECKLIST = {\n stateAndLifecycle: [\n 'Uninitialized state accessed before setup',\n 'Missing cleanup on unmount/dispose',\n 'State mutations in wrong lifecycle phase',\n ],\n edgeCasesAndRaces: [\n 'Race conditions in async operations',\n 'Missing error handling for edge cases',\n 'Unhandled promise rejections',\n ],\n missingPieces: [\n 'Missing input validation',\n 'Missing error handling',\n 'Missing logging/monitoring',\n ],\n};\n\nexport interface ChangedFile {\n path: string;\n additions: number;\n deletions: number;\n status: string;\n}\n\nexport class SuperReviewerAgent {\n async review(_files: string[]): Promise<{ issues: any[] }> {\n return { issues: [] };\n }\n\n async buildReviewWorkflow(\n files: ChangedFile[],\n context: Record<string, any>\n ): Promise<{ files: ChangedFile[]; context: Record<string, any> }> {\n return { files, context };\n }\n}\n","/**\n * Project Info MCP Tool\n * \n * Provides MCP tool for viewing and managing PROJECT.md\n */\n\nimport {\n loadProjectInfo,\n initProjectInfo,\n getProjectSection,\n updateProjectSection,\n appendToSection,\n getProjectSections,\n getProjectInfoStructured,\n projectInfoExists,\n} from '../utils/project-info.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport interface ProjectInfoArgs {\n action: 'view' | 'init' | 'update' | 'append' | 'sections' | 'raw';\n section?: string;\n content?: string;\n directory?: string;\n}\n\nexport class TrieProjectInfoTool {\n async execute(args: ProjectInfoArgs): Promise<{ content: Array<{ type: string; text: string }> }> {\n const workDir = args.directory || getWorkingDirectory(undefined, true);\n const action = args.action || 'view';\n\n try {\n switch (action) {\n case 'view':\n return await this.handleView(workDir, args.section);\n \n case 'init':\n return await this.handleInit(workDir);\n \n case 'update':\n return await this.handleUpdate(workDir, args.section, args.content);\n \n case 'append':\n return await this.handleAppend(workDir, args.section, args.content);\n \n case 'sections':\n return await this.handleSections(workDir);\n \n case 'raw':\n return await this.handleRaw(workDir);\n \n default:\n return this.error(`Unknown action: ${action}. Use: view, init, update, append, sections, raw`);\n }\n } catch (error) {\n return this.error(`Error: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n private async handleView(workDir: string, section?: string): Promise<{ content: Array<{ type: string; text: string }> }> {\n if (!projectInfoExists(workDir)) {\n return this.formatResponse(`## Project Info Not Found\n\nNo \\`.trie/PROJECT.md\\` file exists in this project.\n\n**To create one, use:**\n\\`\\`\\`\ntrie_project action=\"init\"\n\\`\\`\\`\n\nOr run: \\`trie project init\\`\n\nThis will create a template with sections for:\n- Project Overview\n- Technology Stack\n- Architecture\n- Coding Conventions\n- Environment\n- Team\n- Compliance\n- AI Instructions`);\n }\n\n if (section) {\n const sectionContent = await getProjectSection(section, workDir);\n if (sectionContent === null) {\n const sections = await getProjectSections(workDir);\n return this.formatResponse(`## Section Not Found: \"${section}\"\n\nAvailable sections:\n${sections.map(s => `- ${s}`).join('\\n')}`);\n }\n \n return this.formatResponse(`## ${section}\n\n${sectionContent}`);\n }\n\n // Return structured view\n const info = await getProjectInfoStructured(workDir);\n \n let output = `## Project Information\n\n**Path:** \\`${info.path}\\`\n**Sections:** ${Object.keys(info.sections).length}\n\n---\n\n`;\n\n for (const [name, content] of Object.entries(info.sections)) {\n output += `### ${name}\n\n${content}\n\n---\n\n`;\n }\n\n return this.formatResponse(output);\n }\n\n private async handleInit(workDir: string): Promise<{ content: Array<{ type: string; text: string }> }> {\n const result = await initProjectInfo(workDir);\n \n if (result.created) {\n return this.formatResponse(`## PROJECT.md Created\n\n**Path:** \\`${result.path}\\`\n\nA new PROJECT.md file has been created with a template including sections for:\n- Project Overview\n- Technology Stack\n- Architecture\n- Coding Conventions\n- Environment\n- Team\n- Compliance\n- AI Instructions\n\n**Next steps:**\n1. Open the file and fill in your project details\n2. The content will be available via \\`trie://project\\` resource\n3. AI assistants will use this context when working on your project\n\n**View the template:**\n\\`\\`\\`\ntrie_project action=\"view\"\n\\`\\`\\``);\n }\n\n return this.formatResponse(`## PROJECT.md Already Exists\n\n**Path:** \\`${result.path}\\`\n\nUse \\`trie_project action=\"view\"\\` to see the current content.`);\n }\n\n private async handleUpdate(\n workDir: string, \n section?: string, \n content?: string\n ): Promise<{ content: Array<{ type: string; text: string }> }> {\n if (!section) {\n return this.error('Missing required parameter: section');\n }\n if (!content) {\n return this.error('Missing required parameter: content');\n }\n\n const success = await updateProjectSection(section, content, workDir);\n \n if (success) {\n return this.formatResponse(`## Section Updated: \"${section}\"\n\nThe \"${section}\" section has been updated with your new content.\n\n**View updated section:**\n\\`\\`\\`\ntrie_project action=\"view\" section=\"${section}\"\n\\`\\`\\``);\n }\n\n const sections = await getProjectSections(workDir);\n return this.error(`Could not update section \"${section}\". \n\nAvailable sections:\n${sections.map(s => `- ${s}`).join('\\n')}`);\n }\n\n private async handleAppend(\n workDir: string,\n section?: string,\n content?: string\n ): Promise<{ content: Array<{ type: string; text: string }> }> {\n if (!section) {\n return this.error('Missing required parameter: section');\n }\n if (!content) {\n return this.error('Missing required parameter: content');\n }\n\n const success = await appendToSection(section, content, workDir);\n \n if (success) {\n return this.formatResponse(`## Content Appended to: \"${section}\"\n\nYour content has been added to the \"${section}\" section.\n\n**View updated section:**\n\\`\\`\\`\ntrie_project action=\"view\" section=\"${section}\"\n\\`\\`\\``);\n }\n\n return this.error(`Could not append to section \"${section}\". Make sure the section exists.`);\n }\n\n private async handleSections(workDir: string): Promise<{ content: Array<{ type: string; text: string }> }> {\n if (!projectInfoExists(workDir)) {\n return this.formatResponse(`## No PROJECT.md Found\n\nRun \\`trie_project action=\"init\"\\` to create one.`);\n }\n\n const sections = await getProjectSections(workDir);\n \n return this.formatResponse(`## Available Sections\n\n${sections.map((s, i) => `${i + 1}. **${s}**`).join('\\n')}\n\n**View a section:**\n\\`\\`\\`\ntrie_project action=\"view\" section=\"Section Name\"\n\\`\\`\\`\n\n**Update a section:**\n\\`\\`\\`\ntrie_project action=\"update\" section=\"Section Name\" content=\"New content...\"\n\\`\\`\\``);\n }\n\n private async handleRaw(workDir: string): Promise<{ content: Array<{ type: string; text: string }> }> {\n const content = await loadProjectInfo(workDir);\n \n if (!content) {\n return this.formatResponse(`No PROJECT.md found. Run \\`trie_project action=\"init\"\\` to create one.`);\n }\n\n return this.formatResponse(content);\n }\n\n private formatResponse(text: string): { content: Array<{ type: string; text: string }> } {\n return {\n content: [{ type: 'text', text }]\n };\n }\n\n private error(message: string): { content: Array<{ type: string; text: string }> } {\n return {\n content: [{ type: 'text', text: `**Error:** ${message}` }]\n };\n }\n}\n","/**\n * Trie Init Tool\n * \n * MCP tool for initializing bootstrap files.\n */\n\nimport { initializeBootstrapFiles, loadBootstrapContext, completeBootstrap, needsBootstrap } from '../bootstrap/index.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport class TrieInitTool {\n async execute(params: {\n action?: 'init' | 'status' | 'complete' | 'context';\n directory?: string;\n force?: boolean;\n skipBootstrap?: boolean;\n }): Promise<string> {\n const action = params.action || 'init';\n const workDir = params.directory || getWorkingDirectory(undefined, true);\n\n if (action === 'status') {\n const needs = needsBootstrap(workDir);\n const context = await loadBootstrapContext(workDir);\n \n const existingFiles = context.files.filter(f => f.exists).map(f => f.name);\n const missingFiles = context.files.filter(f => !f.exists).map(f => f.name);\n \n return [\n '# Bootstrap Status',\n '',\n `**Bootstrap pending:** ${needs ? 'Yes' : 'No'}`,\n '',\n '## Files',\n '',\n '**Existing:**',\n existingFiles.length > 0 ? existingFiles.map(f => `- .trie/${f}`).join('\\n') : '- None',\n '',\n '**Missing:**',\n missingFiles.length > 0 ? missingFiles.map(f => `- .trie/${f}`).join('\\n') : '- None',\n ].join('\\n');\n }\n\n if (action === 'complete') {\n const result = await completeBootstrap(workDir);\n if (result) {\n return 'Bootstrap completed. BOOTSTRAP.md has been deleted.';\n }\n return 'No BOOTSTRAP.md file found.';\n }\n\n if (action === 'context') {\n const context = await loadBootstrapContext(workDir);\n if (!context.injectedContent) {\n return 'No bootstrap context available. Run trie_init with action=\"init\" first.';\n }\n return context.injectedContent;\n }\n\n // Default: init\n const initOptions: Parameters<typeof initializeBootstrapFiles>[0] = {\n workDir,\n };\n if (params.force !== undefined) {\n initOptions.force = params.force;\n }\n if (params.skipBootstrap !== undefined) {\n initOptions.skipBootstrap = params.skipBootstrap;\n }\n const result = await initializeBootstrapFiles(initOptions);\n\n const lines: string[] = [\n '# Trie Workspace Initialized',\n '',\n ];\n\n if (result.created.length > 0) {\n lines.push('## Created Files', '');\n for (const file of result.created) {\n lines.push(`- .trie/${file}`);\n }\n lines.push('');\n }\n\n if (result.skipped.length > 0) {\n lines.push('## Skipped (already exist)', '');\n for (const file of result.skipped) {\n lines.push(`- .trie/${file}`);\n }\n lines.push('');\n }\n\n lines.push('## Detected Stack', '');\n if (result.stack.framework) lines.push(`- **Framework:** ${result.stack.framework}`);\n if (result.stack.language) lines.push(`- **Language:** ${result.stack.language}`);\n if (result.stack.database) lines.push(`- **Database:** ${result.stack.database}`);\n if (result.stack.auth) lines.push(`- **Auth:** ${result.stack.auth}`);\n if (result.stack.packageManager) lines.push(`- **Package Manager:** ${result.stack.packageManager}`);\n lines.push('');\n\n if (result.stack.suggestedSkills.length > 0) {\n lines.push('## Suggested Skills', '');\n for (const skill of result.stack.suggestedSkills) {\n lines.push(`\\`\\`\\`bash`);\n lines.push(`trie skills add ${skill}`);\n lines.push(`\\`\\`\\``);\n }\n lines.push('');\n }\n\n lines.push(\n '## Next Steps',\n '',\n '1. Edit `.trie/PROJECT.md` with your project description',\n '2. Define coding standards in `.trie/RULES.md`',\n '3. Run `trie_scan` to analyze your codebase',\n '4. Run `trie_init` with action=\"complete\" when setup is done',\n );\n\n return lines.join('\\n');\n }\n}\n","/**\n * Trie Memory Search Tool\n * \n * MCP tool for searching issue memory.\n */\n\nimport {\n searchIssues,\n getMemoryStats,\n getRecentIssues,\n findSimilarIssues,\n markIssueResolved,\n purgeIssues,\n} from '../memory/issue-store.js';\nimport {\n findCrossProjectPatterns,\n searchGlobalPatterns,\n listTrackedProjects,\n getGlobalMemoryStats,\n} from '../memory/global-memory.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport class TrieMemorySearchTool {\n async execute(params: {\n action?: 'search' | 'stats' | 'recent' | 'similar' | 'resolve' | 'global' | 'purge';\n query?: string;\n issueId?: string;\n limit?: number;\n severity?: string[];\n agent?: string;\n includeResolved?: boolean;\n directory?: string;\n purgeStrategy?: 'smart' | 'resolved' | 'old' | 'all';\n daysOld?: number;\n }): Promise<{ content: Array<{ type: string; text: string }> }> {\n const action = params.action || 'search';\n const workDir = params.directory || getWorkingDirectory(undefined, true);\n\n let resultText: string;\n switch (action) {\n case 'search':\n resultText = await this.handleSearch(params, workDir);\n break;\n case 'stats':\n resultText = await this.handleStats(workDir);\n break;\n case 'recent':\n resultText = await this.handleRecent(params, workDir);\n break;\n case 'similar':\n resultText = await this.handleSimilar(params, workDir);\n break;\n case 'resolve':\n resultText = await this.handleResolve(params, workDir);\n break;\n case 'global':\n resultText = await this.handleGlobal(params);\n break;\n case 'purge':\n resultText = await this.handlePurge(params, workDir);\n break;\n default:\n resultText = 'Unknown action. Use: search, stats, recent, similar, resolve, global, or purge';\n }\n\n return {\n content: [{\n type: 'text',\n text: resultText\n }]\n };\n }\n\n private async handleSearch(params: {\n query?: string;\n limit?: number;\n severity?: string[];\n agent?: string;\n includeResolved?: boolean;\n }, workDir: string): Promise<string> {\n if (!params.query) {\n return 'Missing required parameter: query';\n }\n\n const searchOptions: Parameters<typeof searchIssues>[1] = {\n workDir,\n limit: params.limit || 10,\n };\n if (params.severity !== undefined) {\n searchOptions.severity = params.severity;\n }\n if (params.agent !== undefined) {\n searchOptions.agent = params.agent;\n }\n if (params.includeResolved !== undefined) {\n searchOptions.includeResolved = params.includeResolved;\n }\n const results = await searchIssues(params.query, searchOptions);\n\n if (results.length === 0) {\n return `No issues found matching \"${params.query}\"`;\n }\n\n const lines: string[] = [\n `# Search Results: \"${params.query}\"`,\n '',\n `Found ${results.length} matching issue(s):`,\n '',\n ];\n\n for (const result of results) {\n const i = result.issue;\n const status = i.resolved ? ' [RESOLVED]' : '';\n lines.push(\n `## [${i.severity.toUpperCase()}]${status} ${i.issue.slice(0, 80)}`,\n '',\n `- **File:** \\`${i.file}\\`${i.line ? `:${i.line}` : ''}`,\n `- **Agent:** ${i.agent}`,\n `- **Score:** ${(result.score * 100).toFixed(0)}%`,\n `- **Date:** ${new Date(i.timestamp).toLocaleDateString()}`,\n `- **Fix:** ${i.fix.slice(0, 150)}${i.fix.length > 150 ? '...' : ''}`,\n '',\n );\n }\n\n return lines.join('\\n');\n }\n\n private async handleStats(workDir: string): Promise<string> {\n const stats = await getMemoryStats(workDir);\n const globalStats = await getGlobalMemoryStats();\n\n const lines: string[] = [\n '# Memory Statistics',\n '',\n '## Local Issue Memory',\n '',\n `- **Active Issues:** ${stats.activeIssues}`,\n `- **Resolved:** ${stats.resolvedCount}`,\n `- **Total (all-time):** ${stats.totalIssues}`,\n ];\n\n // Capacity warning\n const cap = stats.capacityInfo;\n if (cap.isAtCap) {\n lines.push(\n '',\n '### ⚠️ CAPACITY WARNING',\n '',\n `**Memory is at maximum capacity (${cap.current}/${cap.max} issues, ${cap.percentFull}%)**`,\n '',\n 'Trie caps issue storage at 10,000 for performance. New repeats are deduplicated.',\n 'Older issues are compacted into summaries, and if it still exceeds the cap the oldest/lowest-value issues are pruned.',\n '',\n '**Options to free up space:**',\n '- `trie memory purge smart` - Remove resolved and old low-priority issues (recommended)',\n '- `trie memory purge resolved` - Remove all resolved issues',\n '- `trie memory purge old` - Remove issues older than 90 days',\n '- `trie memory purge all` - Clear all issues (keeps summaries)',\n );\n } else if (cap.percentFull >= 80) {\n lines.push(\n '',\n `### ℹ️ Memory Usage: ${cap.percentFull}% (${cap.current}/${cap.max})`,\n '',\n `You're approaching the storage cap. Consider running \\`trie memory purge smart\\` to free up space.`,\n );\n } else {\n lines.push(`- **Memory Usage:** ${cap.percentFull}% (${cap.current}/${cap.max})`);\n }\n\n // Deduplication stats\n if (stats.deduplicationStats.duplicatesAvoided > 0) {\n lines.push(\n '',\n '### Deduplication',\n '',\n `- **Unique Patterns:** ${stats.deduplicationStats.uniquePatterns}`,\n `- **Duplicates Avoided:** ${stats.deduplicationStats.duplicatesAvoided}`,\n );\n }\n\n if (stats.oldestIssue) {\n lines.push('', `- **Date Range:** ${stats.oldestIssue.split('T')[0]} to ${stats.newestIssue?.split('T')[0]}`);\n }\n\n lines.push('', '### By Severity', '');\n for (const [severity, count] of Object.entries(stats.issuesBySeverity)) {\n lines.push(`- ${severity}: ${count}`);\n }\n\n lines.push('', '### By Agent', '');\n const sortedAgents = Object.entries(stats.issuesByAgent).sort((a, b) => b[1] - a[1]);\n for (const [agent, count] of sortedAgents.slice(0, 10)) {\n lines.push(`- ${agent}: ${count}`);\n }\n\n lines.push(\n '',\n '## Global Cross-Project Memory',\n '',\n `- **Tracked Projects:** ${globalStats.trackedProjects}`,\n `- **Total Patterns:** ${globalStats.totalPatterns}`,\n `- **Cross-Project Patterns:** ${globalStats.crossProjectPatterns}`,\n `- **Fixed Patterns:** ${globalStats.fixedPatterns}`,\n );\n\n return lines.join('\\n');\n }\n\n private async handleRecent(params: {\n limit?: number;\n }, workDir: string): Promise<string> {\n const issues = await getRecentIssues({\n workDir,\n limit: params.limit || 10,\n });\n\n if (issues.length === 0) {\n return 'No recent issues found.';\n }\n\n const lines: string[] = [\n '# Recent Issues (Last 7 Days)',\n '',\n ];\n\n for (const i of issues) {\n const status = i.resolved ? ' [RESOLVED]' : '';\n lines.push(\n `## [${i.severity.toUpperCase()}]${status} ${i.issue.slice(0, 70)}`,\n '',\n `- \\`${i.file}\\`${i.line ? `:${i.line}` : ''}`,\n `- Agent: ${i.agent} | ${new Date(i.timestamp).toLocaleDateString()}`,\n '',\n );\n }\n\n return lines.join('\\n');\n }\n\n private async handleSimilar(params: {\n query?: string;\n limit?: number;\n }, workDir: string): Promise<string> {\n if (!params.query) {\n return 'Missing required parameter: query (issue description to find similar issues for)';\n }\n\n const mockIssue = {\n id: 'search',\n severity: 'moderate' as const,\n issue: params.query,\n fix: '',\n file: '',\n agent: 'search',\n confidence: 1,\n autoFixable: false,\n };\n\n const results = await findSimilarIssues(mockIssue, {\n workDir,\n limit: params.limit || 5,\n });\n\n if (results.length === 0) {\n return 'No similar issues found.';\n }\n\n const lines: string[] = [\n `# Similar Issues`,\n '',\n `Found ${results.length} similar issue(s):`,\n '',\n ];\n\n for (const result of results) {\n const i = result.issue;\n lines.push(\n `## [${i.severity.toUpperCase()}] ${i.issue.slice(0, 70)}`,\n '',\n `- **File:** \\`${i.file}\\``,\n `- **Similarity:** ${(result.score * 100).toFixed(0)}%`,\n '',\n );\n }\n\n return lines.join('\\n');\n }\n\n private async handleResolve(params: {\n issueId?: string;\n }, workDir: string): Promise<string> {\n if (!params.issueId) {\n return 'Missing required parameter: issueId';\n }\n\n const result = await markIssueResolved(params.issueId, workDir);\n \n if (result) {\n return `Issue ${params.issueId} marked as resolved.`;\n }\n return `Issue ${params.issueId} not found.`;\n }\n\n private async handleGlobal(params: {\n query?: string;\n limit?: number;\n }): Promise<string> {\n if (params.query) {\n const patterns = await searchGlobalPatterns(params.query, {\n limit: params.limit || 10,\n });\n\n if (patterns.length === 0) {\n return `No global patterns found matching \"${params.query}\"`;\n }\n\n const lines: string[] = [\n `# Global Pattern Search: \"${params.query}\"`,\n '',\n ];\n\n for (const p of patterns) {\n lines.push(\n `## [${p.severity.toUpperCase()}] ${p.pattern.slice(0, 60)}`,\n '',\n `- **Occurrences:** ${p.occurrences} across ${p.projects.length} projects`,\n `- **Agent:** ${p.agent}`,\n `- **Projects:** ${p.projects.slice(0, 3).join(', ')}`,\n p.fixApplied ? `- **Fixed in:** ${p.fixApplied.project}` : '',\n '',\n );\n }\n\n return lines.join('\\n');\n }\n\n const patterns = await findCrossProjectPatterns(2);\n const projects = await listTrackedProjects();\n\n const lines: string[] = [\n '# Global Cross-Project Memory',\n '',\n `**Tracked Projects:** ${projects.length}`,\n `**Cross-Project Patterns:** ${patterns.length}`,\n '',\n ];\n\n if (patterns.length > 0) {\n lines.push('## Top Cross-Project Patterns', '');\n \n for (const p of patterns.slice(0, 5)) {\n lines.push(\n `### [${p.severity.toUpperCase()}] ${p.pattern.slice(0, 50)}`,\n '',\n `- Seen ${p.occurrences}x across ${p.projects.length} projects`,\n p.fixApplied ? `- Fixed in ${p.fixApplied.project}` : '- Not yet fixed',\n '',\n );\n }\n }\n\n if (projects.length > 0) {\n lines.push('## Recent Projects', '', '| Project | Health | Issues |', '|---------|--------|--------|');\n \n for (const p of projects.slice(0, 5)) {\n lines.push(`| ${p.name} | ${p.healthScore}% | ${p.totalIssues} |`);\n }\n }\n\n return lines.join('\\n');\n }\n\n private async handlePurge(params: {\n purgeStrategy?: 'smart' | 'resolved' | 'old' | 'all';\n daysOld?: number;\n }, workDir: string): Promise<string> {\n const strategy = params.purgeStrategy || 'smart';\n \n const options: { workDir: string; daysOld?: number } = { workDir };\n if (params.daysOld !== undefined) {\n options.daysOld = params.daysOld;\n }\n \n const result = await purgeIssues(strategy, options);\n\n const lines: string[] = [\n '# Memory Purge Complete',\n '',\n `**Strategy:** ${strategy}`,\n `**Removed:** ${result.removed} issues`,\n `**Remaining:** ${result.remaining} issues`,\n '',\n ];\n\n switch (strategy) {\n case 'smart':\n lines.push(\n '**What was removed:**',\n '- Resolved issues older than 30 days',\n '- Low-priority issues (info/low severity) older than 30 days',\n '',\n '**What was kept:**',\n '- All critical and high severity issues',\n '- All unresolved issues',\n '- All issues from the last 30 days',\n );\n break;\n case 'resolved':\n lines.push('**Removed all resolved issues.**', '**Kept all unresolved issues.**');\n break;\n case 'old':\n lines.push(\n `**Removed all issues older than ${params.daysOld || 90} days.**`,\n `**Kept all recent issues.**`,\n );\n break;\n case 'all':\n lines.push(\n '**Cleared all issues from active memory.**',\n '',\n 'Historical summaries are preserved in compacted-summaries.json.',\n );\n break;\n }\n\n lines.push('', '**Note:** Compacted historical summaries were preserved for trend analysis.');\n\n return lines.join('\\n');\n }\n}\n","/**\n * Checkpoint MCP Tool\n * \n * Save context without running a full scan.\n */\n\nimport { saveCheckpoint, listCheckpoints, getLastCheckpoint } from '../cli/checkpoint.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport interface CheckpointToolInput {\n action: 'save' | 'list' | 'last';\n message?: string;\n notes?: string;\n files?: string[];\n}\n\nexport async function handleCheckpointTool(input: CheckpointToolInput): Promise<string> {\n const workDir = getWorkingDirectory(undefined, true);\n \n switch (input.action) {\n case 'save': {\n const saveOptions: Parameters<typeof saveCheckpoint>[0] = {\n files: input.files || [],\n workDir,\n createdBy: 'mcp',\n };\n if (input.message !== undefined) {\n saveOptions.message = input.message;\n }\n if (input.notes !== undefined) {\n saveOptions.notes = input.notes;\n }\n const checkpoint = await saveCheckpoint(saveOptions);\n \n return `# Checkpoint Saved\n\n**ID:** ${checkpoint.id}\n**Time:** ${checkpoint.timestamp}\n${checkpoint.message ? `**Message:** ${checkpoint.message}` : ''}\n${checkpoint.notes ? `**Notes:** ${checkpoint.notes}` : ''}\n${checkpoint.files.length > 0 ? `**Files:** ${checkpoint.files.join(', ')}` : ''}\n\nContext saved to \\`.trie/\\`. This checkpoint will be visible in other tools (Cursor, Claude Code, CLI).`;\n }\n \n case 'list': {\n const checkpoints = await listCheckpoints(workDir);\n \n if (checkpoints.length === 0) {\n return 'No checkpoints yet. Use `trie_checkpoint action=\"save\"` to create one.';\n }\n \n const lines = ['# Recent Checkpoints', ''];\n for (const cp of checkpoints.slice(-10).reverse()) {\n const date = new Date(cp.timestamp).toLocaleString();\n lines.push(`- **${cp.id}** (${date}): ${cp.message || '(no message)'}`);\n }\n \n return lines.join('\\n');\n }\n \n case 'last': {\n const checkpoint = await getLastCheckpoint(workDir);\n \n if (!checkpoint) {\n return 'No checkpoints yet. Use `trie_checkpoint action=\"save\"` to create one.';\n }\n \n return `# Last Checkpoint\n\n**ID:** ${checkpoint.id}\n**Time:** ${new Date(checkpoint.timestamp).toLocaleString()}\n${checkpoint.message ? `**Message:** ${checkpoint.message}` : ''}\n${checkpoint.notes ? `**Notes:** ${checkpoint.notes}` : ''}\n${checkpoint.files.length > 0 ? `**Files:** ${checkpoint.files.join(', ')}` : ''}\n**Created by:** ${checkpoint.createdBy}`;\n }\n \n default:\n return 'Unknown action. Use: save, list, or last';\n }\n}\n","import { perceiveCurrentChanges } from '../agent/perceive.js';\nimport { reasonAboutChangesHumanReadable } from '../agent/reason.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\n\nexport interface CheckToolInput {\n directory?: string;\n files?: string[];\n mode?: 'quick' | 'full' | 'offline';\n}\n\nexport class TrieCheckTool {\n async execute(input: CheckToolInput = {}): Promise<any> {\n try {\n const workDir = input.directory || getWorkingDirectory(undefined, true);\n let files = input.files;\n\n if (!files || files.length === 0) {\n const perception = await perceiveCurrentChanges(workDir);\n files = perception.diffSummary.files.map((f) => f.filePath);\n }\n\n if (!files || files.length === 0) {\n return {\n content: [{\n type: 'text',\n text: 'No changes detected. Provide files or make a change.'\n }]\n };\n }\n\n const mode = input.mode ?? 'full';\n const runAgents = mode === 'full';\n\n const reasoning = await reasonAboutChangesHumanReadable(workDir, files, {\n runAgents,\n scanContext: { config: { timeoutMs: mode === 'quick' ? 15000 : 60000 } }\n });\n\n const summary = [\n `Risk: ${reasoning.original.riskLevel.toUpperCase()} (${reasoning.original.shouldBlock ? 'block' : 'allow'})`,\n `Explanation: ${reasoning.original.explanation}`,\n `Recommendation: ${reasoning.original.recommendation}`,\n `Plain summary: ${reasoning.summary}`,\n `What I found: ${reasoning.whatIFound}`,\n `How bad: ${reasoning.howBad}`,\n `What to do: ${reasoning.whatToDo}`\n ].join('\\n');\n\n return {\n content: [{\n type: 'text',\n text: summary\n }]\n };\n } catch (error) {\n const friendly = formatFriendlyError(error);\n return { content: [{ type: 'text', text: friendly.userMessage }] };\n }\n }\n}\n","import path from 'node:path';\n\nimport { ContextGraph } from '../context/graph.js';\nimport type { FileNodeData } from '../context/nodes.js';\nimport { exportToJson } from '../context/sync.js';\nimport { IncidentIndex } from '../context/incident-index.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\nimport { processIncident } from '../extraction/pipeline.js';\nimport type { ExtractedSignal } from '../types/signal.js';\n\nexport interface TellToolInput {\n description: string;\n directory?: string;\n}\n\nimport type { RiskLevel } from '../types/index.js';\n\nfunction escalateRisk(level: RiskLevel | undefined): RiskLevel {\n if (level === 'low') return 'medium';\n if (level === 'medium') return 'high';\n if (level === 'high') return 'critical';\n return 'critical';\n}\n\nfunction extractFilePathsFromDescription(description: string): string[] {\n const matches = description.match(/[\\\\w./_-]+\\\\.(ts|tsx|js|jsx|mjs|cjs)/gi);\n if (!matches) return [];\n const unique = new Set<string>();\n matches.forEach((m) => unique.add(m.replace(/^\\.\\/+/, '')));\n return Array.from(unique);\n}\n\nexport class TrieTellTool {\n async execute(input: TellToolInput): Promise<any> {\n try {\n const description = input.description?.trim();\n if (!description) {\n return { content: [{ type: 'text', text: 'description is required' }] };\n }\n\n const projectPath = input.directory || getWorkingDirectory(undefined, true);\n const graph = new ContextGraph(projectPath);\n const now = new Date().toISOString();\n const change = (await graph.getRecentChanges(1))[0];\n const linkedFiles = new Set<string>();\n\n // === NEW: Extract structured signals from incident description ===\n console.log('\\n🧠 Processing incident with signal extraction...');\n let extractedSignal: ExtractedSignal | null = null;\n \n try {\n const apiKey = process.env.ANTHROPIC_API_KEY;\n const options: { workingDirectory: string; anthropicApiKey?: string } = {\n workingDirectory: projectPath,\n };\n if (apiKey) {\n options.anthropicApiKey = apiKey;\n }\n extractedSignal = await processIncident(description, options);\n } catch (error) {\n console.warn('⚠️ Signal extraction failed, continuing with basic incident tracking:', error);\n }\n\n const incident = await graph.addNode('incident', {\n description,\n severity: 'major',\n affectedUsers: null,\n duration: null,\n timestamp: now,\n resolved: false,\n resolution: null,\n fixChangeId: change?.id ?? null,\n reportedVia: 'manual'\n });\n\n if (change) {\n await graph.addEdge(change.id, incident.id, 'leadTo');\n await graph.addEdge(incident.id, change.id, 'causedBy');\n\n for (const filePath of change.data.files) {\n linkedFiles.add(filePath);\n const fileNode = await graph.getNode('file', path.resolve(projectPath, filePath));\n if (fileNode) {\n const data = fileNode.data as FileNodeData;\n await graph.updateNode('file', fileNode.id, {\n incidentCount: (data.incidentCount ?? 0) + 1,\n riskLevel: escalateRisk(data.riskLevel)\n });\n }\n }\n }\n\n // Extract file mentions from description and add to index\n const mentionedFiles = extractFilePathsFromDescription(description);\n mentionedFiles.forEach((f) => linkedFiles.add(f));\n\n // Also add files from extracted signals\n if (extractedSignal) {\n for (const decision of extractedSignal.decisions) {\n decision.files.forEach(f => linkedFiles.add(f));\n }\n }\n\n const incidentIndex = new IncidentIndex(graph, projectPath);\n incidentIndex.addIncidentToTrie(incident, Array.from(linkedFiles));\n\n await exportToJson(graph);\n\n // Build response with extraction summary\n let responseText = `Incident recorded${change ? ` and linked to change ${change.id}` : ''}.`;\n \n if (extractedSignal) {\n const counts = [\n extractedSignal.decisions.length > 0 ? `${extractedSignal.decisions.length} decision(s)` : null,\n extractedSignal.facts.length > 0 ? `${extractedSignal.facts.length} fact(s)` : null,\n extractedSignal.blockers.length > 0 ? `${extractedSignal.blockers.length} blocker(s)` : null,\n extractedSignal.questions.length > 0 ? `${extractedSignal.questions.length} question(s)` : null,\n ].filter(Boolean).join(', ');\n \n if (counts) {\n responseText += `\\n\\n📊 Extracted and stored: ${counts}`;\n }\n }\n\n return {\n content: [{\n type: 'text',\n text: responseText\n }]\n };\n } catch (error) {\n const friendly = formatFriendlyError(error);\n return { content: [{ type: 'text', text: friendly.userMessage }] };\n }\n }\n}\n","import path from 'node:path';\n\nimport { ContextGraph } from '../context/graph.js';\nimport { importFromJson } from '../context/sync.js';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\n\nasync function removeOrphanEdges(graph: ContextGraph): Promise<number> {\n const nodes = await graph.listNodes();\n const ids = new Set(nodes.map((n) => n.id));\n const edges = await graph.listEdges();\n let removed = 0;\n for (const edge of edges) {\n if (!ids.has(edge.from_id) || !ids.has(edge.to_id)) {\n await graph.deleteEdge(edge.id);\n removed++;\n }\n }\n return removed;\n}\n\nexport interface ReconcileToolInput {\n directory?: string;\n source?: string;\n}\n\nexport class TrieReconcileTool {\n async execute(input: ReconcileToolInput = {}): Promise<any> {\n try {\n const projectPath = input.directory || getWorkingDirectory(undefined, true);\n const sourcePath = input.source ?? path.join(getTrieDirectory(projectPath), 'context.json');\n\n const graph = new ContextGraph(projectPath);\n await importFromJson(graph, '', sourcePath);\n const removed = await removeOrphanEdges(graph);\n\n return {\n content: [{\n type: 'text',\n text: `Reconciled context from ${sourcePath}. Removed ${removed} orphaned edges.`\n }]\n };\n } catch (error) {\n const friendly = formatFriendlyError(error);\n return { content: [{ type: 'text', text: friendly.userMessage }] };\n }\n }\n}\n","import { ContextGraph } from '../context/graph.js';\nimport { exportToJson } from '../context/sync.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\n\nexport interface ContextToolInput {\n directory?: string;\n}\n\nexport class TrieContextTool {\n async execute(input: ContextToolInput = {}): Promise<any> {\n try {\n const workDir = input.directory || getWorkingDirectory(undefined, true);\n const graph = new ContextGraph(workDir);\n const snapshot = await graph.getSnapshot();\n await exportToJson(graph);\n\n const summary = `Nodes: ${snapshot.nodes.length}, Edges: ${snapshot.edges.length}, Exported: ${snapshot.exported_at}`;\n\n return {\n content: [{\n type: 'text',\n text: summary\n }],\n data: snapshot\n };\n } catch (error) {\n const friendly = formatFriendlyError(error);\n return { content: [{ type: 'text', text: friendly.userMessage }] };\n }\n }\n}\n","import { ContextGraph } from '../context/graph.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\nimport { LearningEngine } from '../guardian/learning-engine.js';\n\nexport interface FeedbackInput {\n helpful: boolean;\n target?: string; // file path or tool result being rated\n note?: string;\n files?: string[]; // optional files related to the feedback\n directory?: string;\n}\n\nexport class TrieFeedbackTool {\n async execute(input: FeedbackInput): Promise<any> {\n try {\n const projectPath = input.directory || getWorkingDirectory(undefined, true);\n const graph = new ContextGraph(projectPath);\n const engine = new LearningEngine(projectPath, graph);\n\n const files = input.files || (input.target ? [input.target] : []);\n const manualFeedback = {\n helpful: input.helpful,\n files,\n ...(input.note !== undefined ? { note: input.note } : {})\n };\n\n await engine.learn({ manualFeedback });\n\n return {\n content: [{\n type: 'text',\n text: input.helpful\n ? '👍 Thanks — I will prioritize more responses like this.'\n : '👎 Understood — I will adjust future guidance.',\n }],\n };\n } catch (error) {\n const friendly = formatFriendlyError(error);\n return { content: [{ type: 'text', text: friendly.userMessage }] };\n }\n }\n}\n","import { LinearIngester } from '../ingest/linear-ingester.js';\nimport { ContextGraph } from '../context/graph.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport interface LinearSyncInput {\n directory?: string;\n}\n\nexport class LinearSyncTool {\n async execute(input: LinearSyncInput): Promise<any> {\n try {\n const workDir = input.directory || getWorkingDirectory(undefined, true);\n const graph = new ContextGraph(workDir);\n const ingester = new LinearIngester(workDir, graph);\n\n await ingester.syncTickets();\n\n return {\n content: [{\n type: 'text',\n text: '✅ Linear tickets synced successfully. Trie now has context on your active tasks.'\n }]\n };\n } catch (error: any) {\n return {\n isError: true,\n content: [{\n type: 'text',\n text: `Failed to sync Linear tickets: ${error.message}`\n }]\n };\n }\n }\n}\n","/**\n * MCP Query Tools\n * \n * Tools for agents to query decision ledger with targeted retrieval.\n * This prevents context pollution by letting agents ask for exactly\n * what they need, when they need it.\n */\n\nimport { getStorage } from '../storage/tiered-storage.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport type { ContextQuery } from '../types/signal.js';\n\nexport interface GetDecisionsInput {\n // Semantic search\n relatedTo?: string; // File path or topic\n tags?: string[];\n \n // Time filters\n since?: string; // ISO date or \"7d\", \"30d\", \"90d\"\n \n // Limits\n limit?: number;\n \n // Working directory\n directory?: string;\n}\n\nexport class TrieGetDecisionsTool {\n async execute(input: GetDecisionsInput): Promise<any> {\n const workDir = input.directory || getWorkingDirectory(undefined, true);\n const storage = getStorage(workDir);\n await storage.initialize();\n\n // Parse time filter\n let timeWindow: { start?: string; end?: string } | undefined;\n if (input.since) {\n const now = new Date();\n if (input.since.endsWith('d')) {\n const days = parseInt(input.since);\n const start = new Date(now);\n start.setDate(start.getDate() - days);\n timeWindow = { start: start.toISOString() };\n } else {\n timeWindow = { start: input.since };\n }\n }\n\n const query: ContextQuery = {\n limit: input.limit || 10\n };\n if (input.relatedTo) query.relatedTo = input.relatedTo;\n if (input.tags) query.tags = input.tags;\n if (timeWindow) query.timeWindow = timeWindow;\n\n const decisions = await storage.queryDecisions(query);\n\n return {\n content: [{\n type: 'text',\n text: this.formatDecisions(decisions)\n }]\n };\n }\n\n formatDecisions(decisions: any[]): string {\n if (decisions.length === 0) {\n return 'No decisions found matching query.';\n }\n\n let output = `Found ${decisions.length} decision(s):\\n\\n`;\n \n for (const dec of decisions) {\n const when = new Date(dec.when).toLocaleDateString();\n output += `📋 ${dec.decision}\\n`;\n output += ` Context: ${dec.context}\\n`;\n if (dec.reasoning) {\n output += ` Reasoning: ${dec.reasoning}\\n`;\n }\n if (dec.tradeoffs && dec.tradeoffs.length > 0) {\n output += ` Tradeoffs considered: ${dec.tradeoffs.join(', ')}\\n`;\n }\n output += ` When: ${when}\\n`;\n if (dec.files.length > 0) {\n output += ` Files: ${dec.files.join(', ')}\\n`;\n }\n output += ` Tags: ${dec.tags.join(', ')}\\n`;\n output += `\\n`;\n }\n\n return output;\n }\n}\n\nexport interface GetBlockersInput {\n tags?: string[];\n limit?: number;\n directory?: string;\n}\n\nexport class TrieGetBlockersTool {\n async execute(input: GetBlockersInput): Promise<any> {\n const workDir = input.directory || getWorkingDirectory(undefined, true);\n const storage = getStorage(workDir);\n await storage.initialize();\n\n const query: ContextQuery = {\n limit: input.limit || 5\n };\n if (input.tags) query.tags = input.tags;\n\n const blockers = await storage.queryBlockers(query);\n\n return {\n content: [{\n type: 'text',\n text: this.formatBlockers(blockers)\n }]\n };\n }\n\n formatBlockers(blockers: any[]): string {\n if (blockers.length === 0) {\n return '✅ No active blockers found.';\n }\n\n let output = `⚠️ Found ${blockers.length} active blocker(s):\\n\\n`;\n \n for (const blocker of blockers) {\n const impact = blocker.impact.toUpperCase();\n const emoji = blocker.impact === 'critical' ? '🔴' : \n blocker.impact === 'high' ? '🟠' : \n blocker.impact === 'medium' ? '🟡' : '🟢';\n \n output += `${emoji} [${impact}] ${blocker.blocker}\\n`;\n if (blocker.affectedAreas.length > 0) {\n output += ` Affects: ${blocker.affectedAreas.join(', ')}\\n`;\n }\n output += ` Since: ${new Date(blocker.when).toLocaleDateString()}\\n`;\n output += `\\n`;\n }\n\n return output;\n }\n}\n\nexport interface GetRelatedDecisionsInput {\n decisionId?: string;\n file?: string;\n topic?: string;\n limit?: number;\n directory?: string;\n}\n\nexport class TrieGetRelatedDecisionsTool {\n async execute(input: GetRelatedDecisionsInput): Promise<any> {\n const workDir = input.directory || getWorkingDirectory(undefined, true);\n const storage = getStorage(workDir);\n await storage.initialize();\n\n // If decisionId provided, find its related decisions\n // For now, use tags/files as proxy for \"related\"\n \n const query: ContextQuery = {\n limit: input.limit || 5\n };\n const relatedTo = input.file || input.topic;\n if (relatedTo) query.relatedTo = relatedTo;\n\n const decisions = await storage.queryDecisions(query);\n\n return {\n content: [{\n type: 'text',\n text: new TrieGetDecisionsTool().formatDecisions(decisions)\n }]\n };\n }\n\n}\n\nexport interface QueryContextInput {\n query: string;\n type?: 'decisions' | 'blockers' | 'facts' | 'questions' | 'all';\n limit?: number;\n directory?: string;\n}\n\nexport class TrieQueryContextTool {\n async execute(input: QueryContextInput): Promise<any> {\n const workDir = input.directory || getWorkingDirectory(undefined, true);\n const storage = getStorage(workDir);\n await storage.initialize();\n\n // Simple keyword-based search for now\n // TODO: Add semantic search with embeddings\n \n const keywords = input.query.toLowerCase().split(/\\s+/);\n \n let output = `Query: \"${input.query}\"\\n\\n`;\n\n if (!input.type || input.type === 'decisions' || input.type === 'all') {\n const decisions = await storage.queryDecisions({ limit: input.limit || 5 });\n const matches = decisions.filter(d => \n keywords.some(kw => \n d.decision.toLowerCase().includes(kw) ||\n d.context.toLowerCase().includes(kw) ||\n d.tags.some(t => t.toLowerCase().includes(kw))\n )\n );\n \n if (matches.length > 0) {\n output += `📋 DECISIONS (${matches.length}):\\n`;\n output += new TrieGetDecisionsTool().formatDecisions(matches);\n output += '\\n';\n }\n }\n\n if (!input.type || input.type === 'blockers' || input.type === 'all') {\n const blockers = await storage.queryBlockers({ limit: input.limit || 5 });\n const matches = blockers.filter(b =>\n keywords.some(kw =>\n b.blocker.toLowerCase().includes(kw) ||\n b.tags.some(t => t.toLowerCase().includes(kw))\n )\n );\n\n if (matches.length > 0) {\n output += `⚠️ BLOCKERS (${matches.length}):\\n`;\n output += new TrieGetBlockersTool().formatBlockers(matches);\n }\n }\n\n return {\n content: [{\n type: 'text',\n text: output.trim() || 'No matches found.'\n }]\n };\n }\n}\n","import { TrieScanTool } from '../tools/scan.js';\nimport { TrieFixTool } from '../tools/fix.js';\nimport { TrieExplainTool } from '../tools/explain.js';\nimport { TrieTestTool } from '../tools/test.js';\nimport { TrieWatchTool } from '../tools/watch.js';\nimport { TriePRReviewTool } from '../tools/pr-review.js';\nimport { TrieProjectInfoTool } from '../tools/project-info.js';\nimport { TrieInitTool } from '../tools/init.js';\nimport { TrieMemorySearchTool } from '../tools/memory-search.js';\nimport { handleCheckpointTool, type CheckpointToolInput } from '../tools/checkpoint.js';\nimport { TrieCheckTool } from '../tools/check.js';\nimport { TrieTellTool } from '../tools/tell.js';\nimport { TrieReconcileTool } from '../tools/reconcile.js';\nimport { TrieContextTool } from '../tools/context.js';\nimport { TrieFeedbackTool } from '../tools/feedback.js';\nimport { LinearSyncTool } from '../tools/linear-sync.js';\nimport { \n TrieGetDecisionsTool, \n TrieGetBlockersTool, \n TrieGetRelatedDecisionsTool,\n TrieQueryContextTool \n} from '../tools/query-tools.js';\n\nclass TrieCheckpointTool {\n async execute(input: CheckpointToolInput): Promise<any> {\n const result = await handleCheckpointTool(input);\n return {\n content: [{\n type: 'text',\n text: result\n }]\n };\n }\n}\n\nexport interface ToolDefinition {\n name: string;\n description: string;\n inputSchema: Record<string, any>;\n _meta?: {\n ui?: {\n resourceUri: string;\n };\n };\n}\n\nexport class ToolRegistry {\n private tools: Map<string, any> = new Map();\n private definitions: ToolDefinition[] = [];\n\n constructor() {\n this.initializeTools();\n this.defineToolSchemas();\n }\n\n private initializeTools() {\n // Initialize tool instances\n this.tools.set('scan', new TrieScanTool());\n this.tools.set('fix', new TrieFixTool());\n this.tools.set('explain', new TrieExplainTool());\n this.tools.set('test', new TrieTestTool());\n this.tools.set('watch', new TrieWatchTool());\n this.tools.set('pr_review', new TriePRReviewTool());\n this.tools.set('project', new TrieProjectInfoTool());\n this.tools.set('init', new TrieInitTool());\n this.tools.set('memory', new TrieMemorySearchTool());\n this.tools.set('checkpoint', new TrieCheckpointTool());\n this.tools.set('check', new TrieCheckTool());\n this.tools.set('tell', new TrieTellTool());\n this.tools.set('reconcile', new TrieReconcileTool());\n this.tools.set('context', new TrieContextTool());\n this.tools.set('feedback', new TrieFeedbackTool());\n this.tools.set('ok', new TrieFeedbackTool());\n this.tools.set('bad', new TrieFeedbackTool());\n this.tools.set('linear_sync', new LinearSyncTool());\n \n // Query tools for decision ledger\n this.tools.set('get_decisions', new TrieGetDecisionsTool());\n this.tools.set('get_blockers', new TrieGetBlockersTool());\n this.tools.set('get_related_decisions', new TrieGetRelatedDecisionsTool());\n this.tools.set('query_context', new TrieQueryContextTool());\n }\n\n private defineToolSchemas() {\n this.definitions = [\n {\n name: 'trie_scan',\n description: 'Scan code with intelligent agent selection. Scans entire codebase if no files specified. Auto-updates .trie/AGENTS.md with results. Alias: scan',\n inputSchema: {\n type: 'object',\n properties: {\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Files to scan (absolute paths). If empty, scans entire codebase.'\n },\n directory: {\n type: 'string',\n description: 'Directory to scan (if files not specified). Defaults to current working directory.'\n },\n context: {\n type: 'object',\n properties: {\n changeType: {\n type: 'string',\n enum: ['ui', 'api', 'database', 'auth', 'payment', 'general']\n },\n isNewFeature: { type: 'boolean' },\n touchesUserData: { type: 'boolean' }\n }\n },\n forceAgents: {\n type: 'array',\n items: { type: 'string' },\n description: 'Manually specify agents to run (overrides triaging)'\n },\n parallel: {\n type: 'boolean',\n description: 'Run agents in parallel (default true)'\n },\n cache: {\n type: 'boolean',\n description: 'Enable scan result caching (default true)'\n },\n maxConcurrency: {\n type: 'number',\n description: 'Max parallel agents'\n },\n timeoutMs: {\n type: 'number',\n description: 'Agent timeout in milliseconds'\n },\n streaming: {\n type: 'boolean',\n description: 'Stream progress updates'\n },\n interactive: {\n type: 'boolean',\n description: 'Enable interactive CLI dashboard (TTY only)'\n },\n format: {\n type: 'string',\n enum: ['text', 'json'],\n description: 'Output format for optional file output'\n },\n output: {\n type: 'string',\n description: 'Output file path when format is json'\n },\n workers: {\n type: 'boolean',\n description: 'Use worker threads for parallel execution'\n }\n }\n } as const,\n // MCP Apps: Interactive scan dashboard\n _meta: {\n ui: { resourceUri: 'ui://trie/scan-dashboard' }\n },\n },\n {\n name: 'trie',\n description: 'Quick menu of available Trie commands. TIP: Read trie://context first for project state and priorities. Call with `action` to run directly.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n description: 'Optional quick action: scan, security, legal, bugs, types, devops, architecture, ux, clean, soc2, performance, e2e, visual_qa, data_flow, agent_smith, pr_review, watch, fix, explain'\n },\n agent: {\n type: 'string',\n description: 'Agent key when action=agent or when using a custom skill name'\n },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Files to scan (absolute or relative)'\n },\n directory: {\n type: 'string',\n description: 'Directory to scan (defaults to detected workspace)'\n },\n context: {\n type: 'object',\n properties: {\n changeType: {\n type: 'string',\n enum: ['ui', 'api', 'database', 'auth', 'payment', 'general']\n },\n isNewFeature: { type: 'boolean' },\n touchesUserData: { type: 'boolean' }\n }\n }\n }\n } as const,\n },\n {\n name: 'trie_fix',\n description: 'Apply high-confidence fixes to code. Alias: fix',\n inputSchema: {\n type: 'object',\n properties: {\n issueIds: {\n type: 'array',\n items: { type: 'string' },\n description: 'Specific issues to fix (empty = all high-confidence)'\n },\n autoApprove: {\n type: 'boolean',\n description: 'Skip human review for high-confidence fixes'\n }\n }\n } as const,\n },\n {\n name: 'trie_explain',\n description: 'Explain code, issues, or changes in plain language. Alias: explain',\n inputSchema: {\n type: 'object',\n properties: {\n type: {\n type: 'string',\n enum: ['code', 'issue', 'change', 'risk']\n },\n target: {\n type: 'string',\n description: 'What to explain (file path, issue ID, etc.)'\n }\n },\n required: ['type', 'target']\n } as const,\n },\n {\n name: 'trie_feedback',\n description: 'Record quick feedback about a warning or suggestion (thumbs up/down). Alias: trie_ok, trie_bad',\n inputSchema: {\n type: 'object',\n properties: {\n helpful: { type: 'boolean', description: 'true for 👍, false for 👎' },\n target: { type: 'string', description: 'Optional file or item being rated' },\n note: { type: 'string', description: 'Optional short note about why' },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Optional related files (absolute or relative)'\n },\n directory: { type: 'string', description: 'Working directory (defaults to auto-detected)' }\n },\n required: ['helpful']\n } as const,\n },\n {\n name: 'trie_check',\n description: 'Run Trie risk check on current changes. Modes: quick, full, offline.',\n inputSchema: {\n type: 'object',\n properties: {\n directory: { type: 'string' },\n files: { type: 'array', items: { type: 'string' } },\n mode: { type: 'string', enum: ['quick', 'full', 'offline'] }\n }\n }\n },\n {\n name: 'trie_tell',\n description: 'Report an incident so Trie can learn.',\n inputSchema: {\n type: 'object',\n properties: {\n description: { type: 'string' },\n directory: { type: 'string' }\n },\n required: ['description']\n }\n },\n {\n name: 'trie_reconcile',\n description: 'Re-sync context graph from context.json and clean orphaned edges.',\n inputSchema: {\n type: 'object',\n properties: {\n directory: { type: 'string' },\n source: { type: 'string' }\n }\n }\n },\n {\n name: 'trie_context',\n description: 'Return current context snapshot (nodes/edges) and export context.json.',\n inputSchema: {\n type: 'object',\n properties: {\n directory: { type: 'string' }\n }\n }\n },\n {\n name: 'trie_test',\n description: 'Generate or reason about tests. Alias: test',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['generate', 'coverage', 'suggest', 'run'],\n description: 'Test action to perform'\n },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Target source files'\n },\n framework: {\n type: 'string',\n description: 'Optional framework hint (jest, vitest, playwright, etc.)'\n },\n style: {\n type: 'string',\n description: 'Test style (unit, integration, e2e). Defaults to unit.'\n }\n },\n required: ['action', 'files']\n } as const,\n },\n {\n name: 'trie_watch',\n description: 'Autonomous watch mode. Alias: watch',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['start', 'stop', 'status', 'issues'],\n description: 'Watch action'\n },\n directory: {\n type: 'string',\n description: 'Workspace directory to watch (optional, auto-detected)'\n },\n debounceMs: {\n type: 'number',\n description: 'Debounce time for scans (ms)'\n }\n },\n required: ['action']\n } as const,\n },\n {\n name: 'trie_project',\n description: 'View and manage project information (.trie/PROJECT.md). Store project context for AI assistants. Alias: project',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['view', 'init', 'update', 'append', 'sections', 'raw'],\n description: 'Action: view (default), init (create template), update (replace section), append (add to section), sections (list), raw (full file)'\n },\n section: {\n type: 'string',\n description: 'Section name (e.g., \"Project Overview\", \"Technology Stack\", \"AI Instructions\")'\n },\n content: {\n type: 'string',\n description: 'Content for update/append actions'\n },\n directory: {\n type: 'string',\n description: 'Project directory (defaults to current workspace)'\n }\n }\n } as const,\n },\n {\n name: 'trie_init',\n description: 'Initialize bootstrap files (.trie/RULES.md, .trie/TEAM.md, .trie/BOOTSTRAP.md). Detects stack and suggests skills.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['init', 'status', 'complete', 'context'],\n description: 'Action: init (create files), status (check state), complete (finish bootstrap), context (get injected content)'\n },\n directory: {\n type: 'string',\n description: 'Project directory (defaults to current workspace)'\n },\n force: {\n type: 'boolean',\n description: 'Overwrite existing files'\n },\n skipBootstrap: {\n type: 'boolean',\n description: 'Skip creating BOOTSTRAP.md'\n }\n }\n } as const,\n },\n {\n name: 'trie_memory',\n description: 'Search and manage issue memory. Find similar issues, view stats, search across projects, and purge old issues.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['search', 'stats', 'recent', 'similar', 'resolve', 'global', 'purge'],\n description: 'Action: search (find issues), stats (show statistics), recent (recent issues), similar (find similar), resolve (mark resolved), global (cross-project), purge (free up memory)'\n },\n query: {\n type: 'string',\n description: 'Search query for search/similar/global actions'\n },\n issueId: {\n type: 'string',\n description: 'Issue ID for resolve action'\n },\n limit: {\n type: 'number',\n description: 'Maximum results to return'\n },\n severity: {\n type: 'array',\n items: { type: 'string' },\n description: 'Filter by severity levels'\n },\n agent: {\n type: 'string',\n description: 'Filter by agent name'\n },\n includeResolved: {\n type: 'boolean',\n description: 'Include resolved issues in search'\n },\n directory: {\n type: 'string',\n description: 'Project directory (defaults to current workspace)'\n },\n purgeStrategy: {\n type: 'string',\n enum: ['smart', 'resolved', 'old', 'all'],\n description: 'Purge strategy: smart (remove resolved & old low-priority), resolved (all resolved), old (older than daysOld), all (clear all)'\n },\n daysOld: {\n type: 'number',\n description: 'Days threshold for old purge strategy (default 90)'\n }\n }\n } as const,\n // MCP Apps: Interactive memory viewer\n _meta: {\n ui: { resourceUri: 'ui://trie/memory-viewer' }\n },\n },\n {\n name: 'trie_checkpoint',\n description: 'Save a context checkpoint without running a full scan. Quick save for your current work state.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['save', 'list', 'last'],\n description: 'Action: save (create checkpoint), list (show recent), last (show last checkpoint)'\n },\n message: {\n type: 'string',\n description: 'Checkpoint message (what you were working on)'\n },\n notes: {\n type: 'string',\n description: 'Additional notes'\n },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Files to associate with this checkpoint'\n }\n },\n required: ['action']\n } as const,\n },\n // Add remaining tool definitions...\n this.createSpecialAgentDefinitions(),\n ].flat();\n }\n\n private createSpecialAgentDefinitions(): ToolDefinition[] {\n return [\n {\n name: 'trie_visual_qa_browser',\n description: 'Capture screenshots at mobile/tablet/desktop viewports for visual QA. Alias: visual_qa_browser',\n inputSchema: {\n type: 'object',\n properties: {\n url: { type: 'string', description: 'URL to screenshot' },\n port: { type: 'number', description: 'Specific port to check' },\n waitForSelector: { type: 'string', description: 'CSS selector to wait for' },\n waitMs: { type: 'number', description: 'Additional wait time' }\n }\n } as const,\n // MCP Apps: Interactive visual QA gallery\n _meta: {\n ui: { resourceUri: 'ui://trie/visual-qa' }\n },\n },\n {\n name: 'trie_pr_review',\n description: '🔍 Interactive PR review: walks through changes file-by-file. Alias: pr_review',\n inputSchema: {\n type: 'object',\n properties: {\n pr: { type: 'string', description: 'PR number to review' },\n worktree: { type: 'string', description: 'Path to worktree directory' },\n mode: {\n type: 'string',\n enum: ['own', 'others'],\n description: 'Review mode'\n },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Specific files to review'\n }\n }\n } as const,\n // MCP Apps: Interactive PR review UI\n _meta: {\n ui: { resourceUri: 'ui://trie/pr-review' }\n },\n },\n {\n name: 'trie_linear_sync',\n description: 'Sync active Linear tickets to build context for JIT defect prediction. Alias: linear_sync',\n inputSchema: {\n type: 'object',\n properties: {\n directory: { type: 'string', description: 'Project directory' }\n }\n }\n },\n {\n name: 'trie_get_decisions',\n description: 'Query decisions from decision ledger with targeted retrieval. Prevents context pollution by returning only relevant decisions.',\n inputSchema: {\n type: 'object',\n properties: {\n relatedTo: { type: 'string', description: 'File path or topic to find related decisions' },\n tags: { type: 'array', items: { type: 'string' }, description: 'Filter by tags' },\n since: { type: 'string', description: 'Time filter: ISO date or \"7d\", \"30d\", \"90d\"' },\n limit: { type: 'number', description: 'Max results (default 10)' },\n directory: { type: 'string', description: 'Working directory' }\n }\n }\n },\n {\n name: 'trie_get_blockers',\n description: 'Get active blockers from decision ledger. Returns only unresolved blockers to avoid noise.',\n inputSchema: {\n type: 'object',\n properties: {\n tags: { type: 'array', items: { type: 'string' }, description: 'Filter by tags' },\n limit: { type: 'number', description: 'Max results (default 5)' },\n directory: { type: 'string', description: 'Working directory' }\n }\n }\n },\n {\n name: 'trie_get_related_decisions',\n description: 'Find decisions related to a specific decision, file, or topic. Targeted context retrieval.',\n inputSchema: {\n type: 'object',\n properties: {\n decisionId: { type: 'string', description: 'Decision ID to find related decisions' },\n file: { type: 'string', description: 'File path to find related decisions' },\n topic: { type: 'string', description: 'Topic to find related decisions' },\n limit: { type: 'number', description: 'Max results (default 5)' },\n directory: { type: 'string', description: 'Working directory' }\n }\n }\n },\n {\n name: 'trie_query_context',\n description: 'Query decision ledger with natural language. Returns targeted signal, not full dump.',\n inputSchema: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'Natural language query' },\n type: { \n type: 'string', \n enum: ['decisions', 'blockers', 'facts', 'questions', 'all'],\n description: 'Type of context to query (default: all)'\n },\n limit: { type: 'number', description: 'Max results per type (default 5)' },\n directory: { type: 'string', description: 'Working directory' }\n },\n required: ['query']\n }\n }\n ];\n }\n\n getTool(name: string): any {\n return this.tools.get(name);\n }\n\n getAllTools(): ToolDefinition[] {\n return this.definitions;\n }\n\n getToolNames(): string[] {\n return Array.from(this.tools.keys());\n }\n\n hasTool(name: string): boolean {\n return this.tools.has(name);\n }\n}","import { readdir, readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join, dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport { getSkillRegistry } from '../skills/built-in/registry.js';\nimport { loadConfig } from '../config/loader.js';\nimport { getContextForAI, loadContextState } from '../utils/context-state.js';\nimport { loadProjectInfo, projectInfoExists } from '../utils/project-info.js';\nimport { listInstalledSkills } from '../skills/installer.js';\nimport { loadBootstrapContext, loadRules, loadTeamInfo } from '../bootstrap/index.js';\nimport { getMemoryStats, getRecentIssues } from '../memory/issue-store.js';\nimport { getGlobalMemoryStats, findCrossProjectPatterns } from '../memory/global-memory.js';\n\nexport interface Resource {\n uri: string;\n name: string;\n description?: string;\n mimeType?: string;\n}\n\nexport interface ResourceContent {\n contents: Array<{\n uri: string;\n mimeType?: string;\n text: string;\n }>;\n}\n\n// UI App definitions for MCP Apps\nconst UI_APPS = {\n 'scan-dashboard': {\n name: 'Scan Dashboard',\n description: 'Interactive dashboard for viewing and managing scan results',\n },\n 'memory-viewer': {\n name: 'Memory Viewer',\n description: 'Search and browse issue history with context preview',\n },\n 'pr-review': {\n name: 'PR Review',\n description: 'File-by-file diff viewer with inline actions',\n },\n 'visual-qa': {\n name: 'Visual QA',\n description: 'Screenshot gallery with viewport comparison',\n },\n} as const;\n\ntype UIAppId = keyof typeof UI_APPS;\n\nexport class ResourceManager {\n private skillRegistry = getSkillRegistry();\n\n /**\n * Get all available resources dynamically\n */\n async getAvailableResources(): Promise<Resource[]> {\n const resources: Resource[] = [];\n\n // Static resources\n resources.push(\n {\n uri: 'trie://context',\n name: 'AI Context (Consolidated)',\n description: 'Single source of truth: project state, coding rules, recent issues, and cross-project patterns. Read this first.',\n mimeType: 'text/markdown',\n },\n {\n uri: 'trie://project',\n name: 'Project Information',\n description: 'User-defined project context (description, conventions, architecture, AI instructions)',\n mimeType: 'text/markdown',\n },\n {\n uri: 'trie://context/state',\n name: 'Context State',\n description: 'Detailed context state with scan history and priorities',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://skills',\n name: 'Available Skills',\n description: 'List of all available Trie skills (built-in and custom)',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://config',\n name: 'Trie Configuration',\n description: 'Current Trie configuration settings',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://cache/stats',\n name: 'Cache Statistics',\n description: 'Trie scan cache statistics and performance metrics',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://signatures',\n name: 'Vulnerability Signatures',\n description: 'Summary of loaded vulnerability detection signatures',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://skills/installed',\n name: 'Installed Skills',\n description: 'External skills installed from skills.sh that the guardian can apply',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://bootstrap',\n name: 'Bootstrap Status',\n description: 'Bootstrap file status and project setup context',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://rules',\n name: 'Project Rules',\n description: 'User-defined coding standards from .trie/RULES.md',\n mimeType: 'text/markdown',\n },\n {\n uri: 'trie://team',\n name: 'Team Info',\n description: 'Team ownership and escalation from .trie/TEAM.md',\n mimeType: 'text/markdown',\n },\n {\n uri: 'trie://memory',\n name: 'Issue Memory',\n description: 'Issue memory statistics and recent issues',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://memory/global',\n name: 'Global Memory',\n description: 'Cross-project patterns and statistics',\n mimeType: 'application/json',\n }\n );\n\n // Dynamic resources: scan reports\n resources.push(...await this.getScanReportResources());\n\n // Dynamic resources: custom skills\n resources.push(...await this.getCustomSkillResources());\n\n // UI App resources (MCP Apps)\n resources.push(...this.getUIAppResources());\n\n return resources;\n }\n\n private async getScanReportResources(): Promise<Resource[]> {\n try {\n const reportsDir = join(getWorkingDirectory(undefined, true), 'trie-reports');\n const files = await readdir(reportsDir);\n const reportFiles = files.filter(f => f.endsWith('.txt') || f.endsWith('.json'));\n\n return reportFiles.slice(0, 10).map(file => ({\n uri: `trie://reports/${file}`,\n name: `Scan Report: ${file}`,\n description: `Trie scan report from ${file}`,\n mimeType: file.endsWith('.json') ? 'application/json' : 'text/plain',\n }));\n } catch {\n return []; // No reports directory yet\n }\n }\n\n private async getCustomSkillResources(): Promise<Resource[]> {\n try {\n await this.skillRegistry.loadCustomSkills();\n const customSkills = this.skillRegistry.getCustomSkills();\n\n return customSkills.map(skill => ({\n uri: `trie://skills/custom/${skill.name}`,\n name: `Custom Skill: ${skill.name}`,\n description: skill.description,\n mimeType: 'application/json',\n }));\n } catch {\n return []; // No custom skills\n }\n }\n\n /**\n * Read content for a specific resource\n */\n async readResourceContent(uri: string): Promise<ResourceContent> {\n // Handle UI App resources (MCP Apps)\n if (uri.startsWith('ui://trie/')) {\n const appId = uri.replace('ui://trie/', '');\n return await this.getUIAppResource(uri, appId);\n }\n\n const parsedUri = uri.replace('trie://', '');\n\n // Handle AI context (read this first!)\n if (parsedUri === 'context') {\n return await this.getContextResource(uri);\n }\n\n // Handle project info (user-defined context)\n if (parsedUri === 'project') {\n return await this.getProjectResource(uri);\n }\n\n // Handle context state (detailed JSON)\n if (parsedUri === 'context/state') {\n return await this.getContextStateResource(uri);\n }\n\n // Handle built-in skills list\n if (parsedUri === 'skills') {\n return await this.getBuiltInSkillsResource(uri);\n }\n\n // Handle specific custom skill\n if (parsedUri.startsWith('skills/custom/')) {\n return await this.getCustomSkillResource(uri, parsedUri);\n }\n\n // Handle configuration\n if (parsedUri === 'config') {\n return await this.getConfigResource(uri);\n }\n\n // Handle cache stats\n if (parsedUri === 'cache/stats') {\n return await this.getCacheStatsResource(uri);\n }\n\n // Handle vulnerability signatures\n if (parsedUri === 'signatures') {\n return await this.getSignaturesResource(uri);\n }\n\n // Handle installed skills\n if (parsedUri === 'skills/installed') {\n return await this.getInstalledSkillsResource(uri);\n }\n\n // Handle bootstrap status\n if (parsedUri === 'bootstrap') {\n return await this.getBootstrapResource(uri);\n }\n\n // Handle rules\n if (parsedUri === 'rules') {\n return await this.getRulesResource(uri);\n }\n\n // Handle team info\n if (parsedUri === 'team') {\n return await this.getTeamResource(uri);\n }\n\n // Handle memory\n if (parsedUri === 'memory') {\n return await this.getMemoryResource(uri);\n }\n\n // Handle global memory\n if (parsedUri === 'memory/global') {\n return await this.getGlobalMemoryResource(uri);\n }\n\n // Handle scan reports\n if (parsedUri.startsWith('reports/')) {\n return await this.getScanReportResource(uri, parsedUri);\n }\n\n throw new Error(`Unknown resource: ${uri}`);\n }\n\n /**\n * Get UI App resources for MCP Apps\n */\n private getUIAppResources(): Resource[] {\n return Object.entries(UI_APPS).map(([id, app]) => ({\n uri: `ui://trie/${id}`,\n name: app.name,\n description: app.description,\n mimeType: 'text/html;profile=mcp-app',\n }));\n }\n\n /**\n * Read UI App resource content (bundled HTML)\n */\n private async getUIAppResource(uri: string, appId: string): Promise<ResourceContent> {\n // Get the directory of this file to find the dist/ui folder\n const currentFile = fileURLToPath(import.meta.url);\n const distDir = dirname(dirname(currentFile)); // Go up from server/ to dist/\n const uiDir = join(distDir, 'ui');\n const htmlPath = join(uiDir, `${appId}.html`);\n\n try {\n if (!existsSync(htmlPath)) {\n // Return a fallback HTML if the bundled app doesn't exist yet\n return {\n contents: [{\n uri,\n mimeType: 'text/html;profile=mcp-app',\n text: this.getFallbackUIHtml(appId),\n }],\n };\n }\n\n const content = await readFile(htmlPath, 'utf-8');\n return {\n contents: [{\n uri,\n mimeType: 'text/html;profile=mcp-app',\n text: content,\n }],\n };\n } catch (error) {\n return {\n contents: [{\n uri,\n mimeType: 'text/html;profile=mcp-app',\n text: this.getFallbackUIHtml(appId),\n }],\n };\n }\n }\n\n /**\n * Generate fallback HTML for UI apps that haven't been built yet\n */\n private getFallbackUIHtml(appId: string): string {\n const app = UI_APPS[appId as UIAppId];\n const title = app?.name || 'Trie UI';\n const description = app?.description || 'Loading...';\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${title} - Trie</title>\n <style>\n :root {\n --bg: #0d1117;\n --surface: #161b22;\n --border: #30363d;\n --text: #e6edf3;\n --text-muted: #8b949e;\n --primary: #58a6ff;\n }\n * { box-sizing: border-box; margin: 0; padding: 0; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;\n background: var(--bg);\n color: var(--text);\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n padding: 24px;\n }\n .container {\n text-align: center;\n max-width: 400px;\n }\n h1 {\n font-size: 24px;\n margin-bottom: 8px;\n }\n p {\n color: var(--text-muted);\n margin-bottom: 24px;\n }\n .status {\n display: inline-flex;\n align-items: center;\n gap: 8px;\n padding: 8px 16px;\n background: var(--surface);\n border: 1px solid var(--border);\n border-radius: 8px;\n color: var(--primary);\n }\n .spinner {\n width: 16px;\n height: 16px;\n border: 2px solid var(--border);\n border-top-color: var(--primary);\n border-radius: 50%;\n animation: spin 0.8s linear infinite;\n }\n @keyframes spin { to { transform: rotate(360deg); } }\n </style>\n</head>\n<body>\n <div class=\"container\">\n <h1>${title}</h1>\n <p>${description}</p>\n <div class=\"status\">\n <div class=\"spinner\"></div>\n <span>Connecting to Trie...</span>\n </div>\n </div>\n <script type=\"module\">\n // MCP Apps SDK connection\n import { App } from \"@modelcontextprotocol/ext-apps\";\n \n const app = new App();\n await app.connect();\n \n app.ontoolresult = (result) => {\n document.querySelector('.status span').textContent = 'Connected! Waiting for data...';\n console.log('Received tool result:', result);\n };\n </script>\n</body>\n</html>`;\n }\n\n private async getContextResource(uri: string): Promise<ResourceContent> {\n const workDir = getWorkingDirectory(undefined, true);\n const state = await loadContextState();\n \n // Build executive summary first\n const summary: string[] = [\n '# Trie Context',\n '',\n '> Quick reference for AI assistants. Detailed sections below.',\n '',\n '## Quick Status',\n '',\n `| Metric | Value |`,\n `|--------|-------|`,\n `| Health Score | ${state.healthScore}% |`,\n `| Last Scan | ${state.lastScan ? new Date(state.lastScan.timestamp).toLocaleDateString() : 'Never'} |`,\n `| Critical Issues | ${state.lastScan?.issues.critical ?? 0} |`,\n `| Total Issues | ${state.lastScan?.issues.total ?? 0} |`,\n '',\n ];\n \n // Add top priorities (max 3)\n if (state.activePriorities.length > 0) {\n summary.push('## Top Priorities', '');\n state.activePriorities.slice(0, 3).forEach((p, i) => {\n summary.push(`${i + 1}. ${p}`);\n });\n summary.push('');\n }\n \n // Add recent issues from memory (max 3, one-liners)\n try {\n const recentIssues = await getRecentIssues({ workDir, limit: 3 });\n if (recentIssues.length > 0) {\n summary.push('## Recent Issues', '');\n recentIssues.forEach(i => {\n summary.push(`- [${i.severity.toUpperCase()}] ${i.issue.slice(0, 50)}... (\\`${i.file.split('/').pop()}\\`)`);\n });\n summary.push('');\n }\n } catch {\n // Memory not available\n }\n \n // Add cross-project patterns (max 2, one-liners)\n try {\n const patterns = await findCrossProjectPatterns(2);\n if (patterns.length > 0) {\n summary.push('## Watch For (seen in other projects)', '');\n patterns.slice(0, 2).forEach(p => {\n summary.push(`- ${p.pattern.slice(0, 40)}... (${p.occurrences}x across ${p.projects.length} projects)`);\n });\n summary.push('');\n }\n } catch {\n // Global memory not available\n }\n \n // Add coding rules summary (just headers)\n const rules = await loadRules(workDir);\n if (rules) {\n const ruleHeaders = rules.match(/^##?\\s+.+$/gm)?.slice(0, 5) || [];\n if (ruleHeaders.length > 0) {\n summary.push('## Coding Rules (see trie://rules for full)', '');\n ruleHeaders.forEach(h => summary.push(`- ${h.replace(/^#+\\s*/, '')}`));\n summary.push('');\n }\n }\n \n // Add available tools/capabilities\n summary.push('## Available Tools', '');\n summary.push('| Tool | Purpose |');\n summary.push('|------|---------|');\n summary.push('| `trie_scan` | Scan code with intelligent agent selection |');\n summary.push('| `trie_fix` | Generate fix recommendations |');\n summary.push('| `trie_memory` | Search issue history |');\n summary.push('| `trie_init` | Initialize bootstrap files |');\n summary.push('');\n \n // Add installed skills count\n try {\n const skills = await listInstalledSkills();\n if (skills.length > 0) {\n summary.push(`**Skills:** ${skills.length} installed (${skills.slice(0, 3).map(s => s.name).join(', ')}${skills.length > 3 ? '...' : ''})`);\n summary.push('');\n }\n } catch {\n // Skills not available\n }\n \n summary.push('---', '', '# Detailed Context', '');\n \n // Now add the full AGENTS.md\n const agentsMdPath = join(getTrieDirectory(workDir), 'AGENTS.md');\n try {\n if (existsSync(agentsMdPath)) {\n const agentsContent = await readFile(agentsMdPath, 'utf-8');\n summary.push(agentsContent);\n } else {\n const contextSummary = await getContextForAI();\n summary.push(contextSummary);\n }\n } catch {\n const contextSummary = await getContextForAI();\n summary.push(contextSummary);\n }\n \n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: summary.join('\\n'),\n }],\n };\n }\n\n private async getContextStateResource(uri: string): Promise<ResourceContent> {\n const state = await loadContextState();\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(state, null, 2),\n }],\n };\n }\n\n private async getProjectResource(uri: string): Promise<ResourceContent> {\n const workDir = getWorkingDirectory(undefined, true);\n \n if (!projectInfoExists(workDir)) {\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: `# Project Information Not Found\n\nNo \\`.trie/PROJECT.md\\` file exists in this project.\n\n## Create One\n\nUse the \\`trie_project\\` tool with action=\"init\" to create a PROJECT.md template:\n\n\\`\\`\\`\ntrie_project action=\"init\"\n\\`\\`\\`\n\nOr run from CLI:\n\\`\\`\\`\ntrie project init\n\\`\\`\\`\n\n## What is PROJECT.md?\n\nPROJECT.md is a user-defined file that stores important project context:\n- Project description and purpose\n- Technology stack\n- Architecture decisions\n- Coding conventions\n- Environment info\n- Team ownership\n- Compliance requirements\n- Special instructions for AI assistants\n\nThis information is automatically available to Claude Code, Cursor, and other AI tools.\n`,\n }],\n };\n }\n\n const content = await loadProjectInfo(workDir);\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: content || '',\n }],\n };\n }\n\n private async getBuiltInSkillsResource(uri: string): Promise<ResourceContent> {\n await this.skillRegistry.loadCustomSkills();\n const skills = this.skillRegistry.getSkillDescriptions();\n\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n totalSkills: skills.length,\n builtinCount: skills.filter(a => !a.isCustom).length,\n customCount: skills.filter(a => a.isCustom).length,\n skills: skills.map(a => ({\n name: a.name,\n description: a.description,\n type: a.isCustom ? 'custom' : 'builtin',\n })),\n }, null, 2),\n }],\n };\n }\n\n private async getCustomSkillResource(uri: string, parsedUri: string): Promise<ResourceContent> {\n const skillName = parsedUri.replace('skills/custom/', '');\n await this.skillRegistry.loadCustomSkills();\n const metadata = this.skillRegistry.getCustomSkillMetadata(skillName);\n\n if (!metadata) {\n throw new Error(`Custom skill not found: ${skillName}`);\n }\n\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(metadata, null, 2),\n }],\n };\n }\n\n private async getConfigResource(uri: string): Promise<ResourceContent> {\n const config = await loadConfig();\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(config, null, 2),\n }],\n };\n }\n\n private async getCacheStatsResource(uri: string): Promise<ResourceContent> {\n try {\n const cachePath = join(getTrieDirectory(getWorkingDirectory(undefined, true)), '.trie-cache.json');\n const cacheContent = await readFile(cachePath, 'utf-8');\n const cache = JSON.parse(cacheContent);\n\n const fileCount = Object.keys(cache.files || {}).length;\n const totalVulns = Object.values(cache.files || {}).reduce((acc: number, file: any) => {\n return acc + (file.vulnerabilities?.length || 0);\n }, 0);\n\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n version: cache.version,\n created: new Date(cache.created).toISOString(),\n lastUpdated: new Date(cache.lastUpdated).toISOString(),\n cachedFiles: fileCount,\n totalVulnerabilitiesFound: totalVulns,\n cacheAgeMinutes: Math.round((Date.now() - cache.lastUpdated) / 60000),\n }, null, 2),\n }],\n };\n } catch {\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n error: 'No cache found. Run a scan first to build the cache.',\n hint: 'Use trie_scan to scan your codebase',\n }, null, 2),\n }],\n };\n }\n }\n\n private async getSignaturesResource(uri: string): Promise<ResourceContent> {\n // Import dynamically to avoid circular deps\n const { getVulnerabilityStats } = await import('../trie/vulnerability-signatures.js');\n const { getVibeCodeStats } = await import('../trie/vibe-code-signatures.js');\n\n const vulnStats = getVulnerabilityStats();\n const vibeStats = getVibeCodeStats();\n\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n vulnerabilitySignatures: vulnStats,\n vibeCodeSignatures: vibeStats,\n totalSignatures: vulnStats.total + vibeStats.total,\n }, null, 2),\n }],\n };\n }\n\n private async getInstalledSkillsResource(uri: string): Promise<ResourceContent> {\n const skills = await listInstalledSkills();\n const state = await loadContextState();\n \n const skillsWithUsage = skills.map(skill => {\n const record = state.skills?.[skill.name];\n return {\n name: skill.name,\n description: skill.description,\n source: skill.installedFrom,\n installedAt: skill.installedAt,\n timesApplied: record?.timesApplied || 0,\n appliedBy: record?.appliedBy || [],\n lastApplied: record?.lastApplied,\n };\n });\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n totalSkills: skills.length,\n skills: skillsWithUsage,\n note: 'Skills are capabilities applied by agents, not autonomous agents themselves.',\n }, null, 2),\n }],\n };\n }\n\n private async getScanReportResource(uri: string, parsedUri: string): Promise<ResourceContent> {\n const fileName = parsedUri.replace('reports/', '');\n const reportPath = join(getWorkingDirectory(undefined, true), 'trie-reports', fileName);\n\n try {\n const content = await readFile(reportPath, 'utf-8');\n\n return {\n contents: [{\n uri,\n mimeType: fileName.endsWith('.json') ? 'application/json' : 'text/plain',\n text: content,\n }],\n };\n } catch {\n throw new Error(`Report not found: ${fileName}`);\n }\n }\n\n private async getBootstrapResource(uri: string): Promise<ResourceContent> {\n const workDir = getWorkingDirectory(undefined, true);\n const context = await loadBootstrapContext(workDir);\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n needsBootstrap: context.needsBootstrap,\n files: context.files.map(f => ({\n name: f.name,\n type: f.type,\n exists: f.exists,\n })),\n hasInjectedContent: !!context.injectedContent,\n }, null, 2),\n }],\n };\n }\n\n private async getRulesResource(uri: string): Promise<ResourceContent> {\n const rules = await loadRules();\n \n if (!rules) {\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: `# No Rules Defined\n\nNo \\`.trie/RULES.md\\` file exists in this project.\n\nUse \\`trie_init\\` to create one, or create it manually with your coding standards.\n`,\n }],\n };\n }\n\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: rules,\n }],\n };\n }\n\n private async getTeamResource(uri: string): Promise<ResourceContent> {\n const team = await loadTeamInfo();\n \n if (!team) {\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: `# No Team Info Defined\n\nNo \\`.trie/TEAM.md\\` file exists in this project.\n\nUse \\`trie_init\\` to create one, or create it manually with team ownership info.\n`,\n }],\n };\n }\n\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: team,\n }],\n };\n }\n\n private async getMemoryResource(uri: string): Promise<ResourceContent> {\n const workDir = getWorkingDirectory(undefined, true);\n const stats = await getMemoryStats(workDir);\n const recent = await getRecentIssues({ workDir, limit: 5 });\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n stats,\n recentIssues: recent.map(i => ({\n severity: i.severity,\n issue: i.issue.slice(0, 100),\n file: i.file,\n agent: i.agent,\n timestamp: i.timestamp,\n resolved: i.resolved,\n })),\n }, null, 2),\n }],\n };\n }\n\n private async getGlobalMemoryResource(uri: string): Promise<ResourceContent> {\n const stats = await getGlobalMemoryStats();\n const patterns = await findCrossProjectPatterns(2);\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n stats,\n topPatterns: patterns.slice(0, 10).map(p => ({\n pattern: p.pattern.slice(0, 80),\n severity: p.severity,\n agent: p.agent,\n occurrences: p.occurrences,\n projectCount: p.projects.length,\n hasFixApplied: !!p.fixApplied,\n })),\n }, null, 2),\n }],\n };\n }\n}","import { chromium, Browser, Page } from 'playwright';\nimport { createServer, Server } from 'net';\nimport { request } from 'http';\nimport { isInteractiveMode } from '../utils/progress.js';\n\n/**\n * Browser-based Visual QA Tool\n * \n * Launches a headless browser, captures screenshots at multiple viewports,\n * and returns them for Claude Vision to analyze.\n */\n\nexport interface VisualQAOptions {\n url?: string;\n port?: number;\n viewports?: ViewportConfig[];\n waitForSelector?: string;\n waitMs?: number;\n}\n\nexport interface ViewportConfig {\n name: string;\n width: number;\n height: number;\n}\n\nexport interface ScreenshotResult {\n viewport: string;\n width: number;\n height: number;\n base64: string;\n mimeType: 'image/png';\n}\n\nexport interface VisualQAResult {\n success: boolean;\n url: string;\n screenshots: ScreenshotResult[];\n error?: string;\n analysisPrompt: string;\n}\n\n// Default viewports for responsive testing\nconst DEFAULT_VIEWPORTS: ViewportConfig[] = [\n { name: 'mobile', width: 375, height: 812 }, // iPhone X\n { name: 'tablet', width: 768, height: 1024 }, // iPad\n { name: 'desktop', width: 1440, height: 900 }, // Standard desktop\n];\n\n/**\n * Find an open port on localhost by checking common dev server ports\n * Returns the first port that is both in use AND serving HTTP\n */\nasync function findOpenPort(): Promise<number | null> {\n const commonPorts = [3000, 3001, 5173, 5174, 4200, 8080, 8000, 8888, 5000, 4000];\n \n // Check ports in parallel for faster detection\n const portChecks = await Promise.all(\n commonPorts.map(async (port) => {\n const isOpen = await checkPort(port);\n return isOpen ? port : null;\n })\n );\n \n // Return the first port that's open and serving HTTP\n return portChecks.find(port => port !== null) || null;\n}\n\n/**\n * Check if a port has something listening on it AND is serving HTTP\n */\nasync function checkPort(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n // First check if port is in use\n const testServer: Server = createServer();\n let portInUse = false;\n \n testServer.once('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EADDRINUSE') {\n portInUse = true;\n // Port is in use - now verify it's serving HTTP\n testHttpPort(port).then(resolve).catch(() => resolve(false));\n } else {\n resolve(false);\n }\n });\n \n testServer.once('listening', () => {\n // Port is free - nothing running\n testServer.close();\n resolve(false);\n });\n \n // Set timeout to prevent hanging\n setTimeout(() => {\n if (!portInUse) {\n testServer.close();\n resolve(false);\n }\n }, 1000);\n \n testServer.listen(port, '127.0.0.1');\n });\n}\n\n/**\n * Verify that a port is actually serving HTTP content\n */\nasync function testHttpPort(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const req = request({\n hostname: 'localhost',\n port: port,\n path: '/',\n method: 'GET',\n timeout: 2000,\n }, (res) => {\n // If we get any HTTP response (even 404), the server is running\n resolve(res.statusCode !== undefined);\n res.on('data', () => {}); // Consume response\n res.on('end', () => {});\n });\n\n req.on('error', () => {\n // Connection refused, timeout, or other error means no HTTP server\n resolve(false);\n });\n\n req.on('timeout', () => {\n req.destroy();\n resolve(false);\n });\n\n req.end();\n });\n}\n\n/**\n * Capture screenshots at multiple viewports\n */\nasync function captureScreenshots(\n url: string,\n viewports: ViewportConfig[],\n options: { waitForSelector?: string | undefined; waitMs?: number | undefined }\n): Promise<ScreenshotResult[]> {\n let browser: Browser | null = null;\n const screenshots: ScreenshotResult[] = [];\n\n try {\n // Launch browser\n browser = await chromium.launch({\n headless: true,\n });\n\n for (const viewport of viewports) {\n const page: Page = await browser.newPage({\n viewport: { width: viewport.width, height: viewport.height },\n });\n\n try {\n // Navigate to URL\n await page.goto(url, { \n waitUntil: 'networkidle',\n timeout: 30000 \n });\n\n // Wait for specific selector if provided\n if (options.waitForSelector) {\n await page.waitForSelector(options.waitForSelector, { timeout: 10000 });\n }\n\n // Additional wait if specified\n if (options.waitMs) {\n await page.waitForTimeout(options.waitMs);\n }\n\n // Capture full-page screenshot\n const screenshotBuffer = await page.screenshot({\n fullPage: true,\n type: 'png',\n });\n\n screenshots.push({\n viewport: viewport.name,\n width: viewport.width,\n height: viewport.height,\n base64: screenshotBuffer.toString('base64'),\n mimeType: 'image/png',\n });\n\n } finally {\n await page.close();\n }\n }\n\n } finally {\n if (browser) {\n await browser.close();\n }\n }\n\n return screenshots;\n}\n\n/**\n * Main Visual QA function - captures screenshots and prepares for Claude Vision\n */\nexport async function runVisualQA(options: VisualQAOptions = {}): Promise<VisualQAResult> {\n let url = options.url;\n \n // If no URL provided, try to find a running dev server\n if (!url) {\n if (options.port) {\n // User specified a port - verify it's serving HTTP\n const isServing = await testHttpPort(options.port);\n if (!isServing) {\n return {\n success: false,\n url: `http://localhost:${options.port}`,\n screenshots: [],\n error: `Port ${options.port} is not serving HTTP. Is your dev server running on this port?\\n\\nTry:\\n1. Verify your dev server is running: curl http://localhost:${options.port}\\n2. Check if the port is correct\\n3. Provide full URL: trie_visual_qa_browser url:\"http://localhost:${options.port}\"`,\n analysisPrompt: '',\n };\n }\n url = `http://localhost:${options.port}`;\n } else {\n // Auto-detect port\n if (!isInteractiveMode()) {\n console.error('Visual QA: Auto-detecting running dev server...');\n }\n const port = await findOpenPort();\n \n if (!port) {\n return {\n success: false,\n url: '',\n screenshots: [],\n error: 'No running dev server found on common ports (3000, 3001, 5173, 5174, 4200, 8080, 8000, 8888, 5000, 4000).\\n\\nPlease:\\n1. Start your dev server, OR\\n2. Provide a URL: trie_visual_qa_browser url:\"http://localhost:3000\", OR\\n3. Specify a port: trie_visual_qa_browser port:3000',\n analysisPrompt: '',\n };\n }\n \n url = `http://localhost:${port}`;\n if (!isInteractiveMode()) {\n console.error(` ✓ Found server on port ${port}`);\n }\n }\n }\n\n const viewports = options.viewports || DEFAULT_VIEWPORTS;\n\n try {\n if (!isInteractiveMode()) {\n console.error(`📸 Visual QA: Capturing screenshots from ${url}`);\n console.error(` Viewports: ${viewports.map(v => `${v.name} (${v.width}x${v.height})`).join(', ')}`);\n }\n\n const screenshots = await captureScreenshots(url, viewports, {\n waitForSelector: options.waitForSelector,\n waitMs: options.waitMs,\n });\n\n if (!isInteractiveMode()) {\n console.error(` ✓ Captured ${screenshots.length} screenshots`);\n }\n\n // Build analysis prompt for Claude Vision\n const analysisPrompt = buildAnalysisPrompt(url, screenshots);\n\n return {\n success: true,\n url,\n screenshots,\n analysisPrompt,\n };\n\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n \n // Check for common issues\n if (errorMessage.includes('net::ERR_CONNECTION_REFUSED') || errorMessage.includes('ECONNREFUSED')) {\n return {\n success: false,\n url,\n screenshots: [],\n error: `Cannot connect to ${url}. Is your dev server running?\\n\\nTry:\\n1. Start your dev server (e.g., npm start, npm run dev)\\n2. Specify the URL explicitly: trie_visual_qa_browser url:\"http://localhost:3000\"\\n3. Or specify the port: trie_visual_qa_browser port:3000`,\n analysisPrompt: '',\n };\n }\n \n if (errorMessage.includes('Executable doesn\\'t exist') || errorMessage.includes('BrowserType')) {\n return {\n success: false,\n url,\n screenshots: [],\n error: 'Playwright browsers not installed. Run: npx playwright install chromium',\n analysisPrompt: '',\n };\n }\n\n if (errorMessage.includes('timeout') || errorMessage.includes('Navigation timeout')) {\n return {\n success: false,\n url,\n screenshots: [],\n error: `Page load timeout for ${url}. The page may be taking too long to load or may have JavaScript errors.\\n\\nTry:\\n1. Check if the page loads in your browser\\n2. Increase wait time: trie_visual_qa_browser url:\"${url}\" waitMs:5000\\n3. Wait for specific element: trie_visual_qa_browser url:\"${url}\" waitForSelector:\".main-content\"`,\n analysisPrompt: '',\n };\n }\n\n return {\n success: false,\n url,\n screenshots: [],\n error: `Screenshot capture failed: ${errorMessage}\\n\\nTroubleshooting:\\n1. Verify ${url} is accessible in your browser\\n2. Check that your dev server is running\\n3. Try specifying the URL explicitly: trie_visual_qa_browser url:\"${url}\"`,\n analysisPrompt: '',\n };\n }\n}\n\n/**\n * Build the analysis prompt for Claude Vision\n */\nfunction buildAnalysisPrompt(url: string, screenshots: ScreenshotResult[]): string {\n const viewportList = screenshots.map(s => `- ${s.viewport}: ${s.width}x${s.height}`).join('\\n');\n \n return `## Visual QA Analysis\n\nI've captured screenshots of **${url}** at ${screenshots.length} viewports:\n\n${viewportList}\n\nPlease analyze these screenshots for:\n\n### Layout Issues\n- Overlapping elements or text\n- Content overflow or clipping\n- Broken layouts at specific breakpoints\n- Misaligned elements\n- Unexpected gaps or spacing\n\n### Responsive Design\n- Mobile navigation issues\n- Text too small to read on mobile\n- Touch targets too small (<44px)\n- Horizontal scrolling on mobile\n- Content not adapting to viewport\n\n### Visual Polish\n- Inconsistent spacing or alignment\n- Poor color contrast (text hard to read)\n- Broken images or missing assets\n- Loading states stuck/visible\n- Z-index issues (elements overlapping incorrectly)\n\n### Accessibility\n- Missing focus indicators\n- Color-only information\n- Text over images without sufficient contrast\n- Very small text (<12px)\n\n### General Quality\n- Does it look professional?\n- Is the hierarchy clear?\n- Are interactive elements obvious?\n- Any obvious bugs or glitches?\n\nFor each issue found:\n1. **Viewport**: Which viewport(s) affected\n2. **Location**: Where on the page\n3. **Issue**: What's wrong\n4. **Severity**: Critical/Serious/Moderate/Low\n5. **Fix**: How to resolve it\n\nIf the UI looks good, say so! Note what's working well.`;\n}\n\n/**\n * Format MCP response with images for Claude Vision\n */\nexport function formatMCPResponse(result: VisualQAResult): {\n content: Array<{ type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }>;\n} {\n if (!result.success) {\n return {\n content: [{\n type: 'text',\n text: `# Visual QA Failed\\n\\n${result.error}\\n\\n## Troubleshooting\\n\\n1. Make sure your dev server is running\\n2. Try: \\`trie_visual_qa url:\"http://localhost:3000\"\\`\\n3. If Playwright isn't installed: \\`npx playwright install chromium\\``,\n }],\n };\n }\n\n const content: Array<{ type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }> = [];\n\n // Add the analysis prompt first\n content.push({\n type: 'text',\n text: result.analysisPrompt,\n });\n\n // Add each screenshot as an image\n for (const screenshot of result.screenshots) {\n content.push({\n type: 'text',\n text: `\\n### ${screenshot.viewport} (${screenshot.width}x${screenshot.height})\\n`,\n });\n content.push({\n type: 'image',\n data: screenshot.base64,\n mimeType: screenshot.mimeType,\n });\n }\n\n return { content };\n}\n\n/**\n * MCP Tool Definition\n */\nexport const VISUAL_QA_TOOL_DEFINITION = {\n name: 'visual_qa_browser',\n description: 'Capture screenshots of your app at mobile/tablet/desktop viewports for visual QA analysis. Auto-detects running dev servers or specify a URL.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n url: {\n type: 'string',\n description: 'URL to screenshot (e.g., http://localhost:3000). If not provided, auto-detects running dev server.',\n },\n port: {\n type: 'number',\n description: 'Specific port to check if no URL provided',\n },\n waitForSelector: {\n type: 'string',\n description: 'CSS selector to wait for before capturing (e.g., \".main-content\")',\n },\n waitMs: {\n type: 'number',\n description: 'Additional milliseconds to wait after page load',\n },\n },\n required: [],\n },\n};\n","import { getWorkingDirectory } from '../utils/workspace.js';\nimport { runVisualQA, formatMCPResponse } from '../tools/visual-qa-browser.js';\nimport { ToolRegistry } from './tool-registry.js';\nimport { ResourceManager } from './resource-manager.js';\n\nexport class RequestHandlers {\n constructor(\n private toolRegistry: ToolRegistry,\n private resourceManager: ResourceManager\n ) {}\n\n /**\n * Handle tool execution requests\n */\n async handleToolCall(name: string, args: any): Promise<any> {\n // Accept namespaced calls and normalize\n const normalizedName = this.normalizeName(name);\n\n // Auto-detect directory for Cursor/IDE tools when not explicitly provided\n if (args && !args.directory && !args.files) {\n const workingDir = getWorkingDirectory(undefined, true);\n if (workingDir !== process.cwd()) {\n args.directory = workingDir;\n }\n }\n\n try {\n switch (normalizedName) {\n case 'trie':\n return await this.handleTrieMenu(args);\n\n case 'scan':\n return await this.toolRegistry.getTool('scan').execute(args);\n\n case 'fix':\n return await this.toolRegistry.getTool('fix').execute(args);\n\n case 'explain':\n return await this.toolRegistry.getTool('explain').execute(args);\n\n case 'test':\n return await this.toolRegistry.getTool('test').execute(args);\n\n case 'register_agent':\n return await this.toolRegistry.getTool('register_agent').execute(args);\n\n case 'watch':\n return await this.toolRegistry.getTool('watch').execute(args);\n\n // Individual agent commands\n case 'security':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'security' });\n\n case 'legal':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'legal' });\n\n case 'accessibility':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'accessibility' });\n\n case 'design':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'design-engineer' });\n\n case 'architecture':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'software-architect' });\n\n case 'bugs':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'bug-finding' });\n\n case 'ux':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'user-testing' });\n\n case 'types':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'typecheck' });\n\n case 'devops':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'devops' });\n\n case 'clean':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'trie_clean' });\n\n case 'soc2':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'soc2' });\n\n // New agents\n case 'performance':\n case 'perf':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'performance' });\n\n case 'e2e':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'e2e' });\n\n case 'visual_qa':\n case 'visual':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'visual-qa' });\n\n case 'visual_qa_browser': {\n try {\n const result = await runVisualQA(args as { url?: string; port?: number; waitForSelector?: string; waitMs?: number });\n return formatMCPResponse(result);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return {\n content: [{\n type: 'text',\n text: `# Visual QA Error\\n\\nFailed to capture screenshots: ${errorMessage}\\n\\n## Troubleshooting\\n\\n1. **Check if your dev server is running:**\\n - Try accessing the URL in your browser\\n - Common ports: 3000, 5173, 8080\\n\\n2. **Specify the URL explicitly:**\\n \\`\\`\\`\\ntrie_visual_qa_browser url:\"http://localhost:3000\"\\n\\`\\`\\`\\n\\n3. **Specify a port:**\\n \\`\\`\\`\\ntrie_visual_qa_browser port:3000\\n\\`\\`\\`\\n\\n4. **Install Playwright browsers (if needed):**\\n \\`\\`\\`\\nnpx playwright install chromium\\n\\`\\`\\`\\n\\n5. **Check for JavaScript errors:**\\n - Open browser dev tools\\n - Look for console errors\\n - The page may be failing to load`,\n }],\n };\n }\n }\n\n case 'data_flow':\n case 'dataflow':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'data-flow' });\n\n // Special agents\n case 'agent_smith':\n case 'agentsmith':\n case 'smith':\n // Handle special Agent Smith commands (clear_memory, show_stats)\n if (args?.clear_memory || args?.show_stats) {\n return await this.handleAgentSmith(args);\n }\n // Normal scan - delegate to agent tool\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'agent-smith' });\n\n case 'super_reviewer':\n case 'superreviewer':\n case 'reviewer':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'super-reviewer' });\n\n // Custom skill tools (with backward-compatible agent aliases)\n case 'create_skill':\n case 'create_agent':\n return await this.toolRegistry.getTool('create_skill').execute(args);\n\n case 'save_skill':\n case 'save_agent':\n return await this.toolRegistry.getTool('save_skill').execute(args);\n\n case 'list_skills':\n case 'list_agents':\n return await this.toolRegistry.getTool('list_skills').execute(args);\n\n case 'pr_review':\n return await this.toolRegistry.getTool('pr_review').execute(args);\n\n case 'project':\n case 'project_info':\n return await this.toolRegistry.getTool('project').execute(args);\n\n case 'init':\n return await this.toolRegistry.getTool('init').execute(args);\n\n case 'memory':\n return await this.toolRegistry.getTool('memory').execute(args);\n\n case 'check':\n return await this.toolRegistry.getTool('check').execute(args);\n\n case 'tell':\n return await this.toolRegistry.getTool('tell').execute(args);\n\n case 'feedback':\n case 'ok':\n case 'bad':\n return await this.toolRegistry.getTool('feedback').execute(args);\n\n case 'reconcile':\n return await this.toolRegistry.getTool('reconcile').execute(args);\n\n case 'context':\n return await this.toolRegistry.getTool('context').execute(args);\n\n case 'checkpoint':\n case 'cp':\n case 'save':\n return await this.toolRegistry.getTool('checkpoint').execute(args);\n\n default:\n throw new Error(`Unknown tool: ${name}`);\n }\n } catch (error) {\n return {\n content: [{\n type: 'text',\n text: `Error: ${error instanceof Error ? error.message : String(error)}`\n }]\n };\n }\n }\n\n /**\n * Handle resource listing requests\n */\n async handleListResources(): Promise<{ resources: any[] }> {\n const resources = await this.resourceManager.getAvailableResources();\n return { resources };\n }\n\n /**\n * Handle resource reading requests\n */\n async handleReadResource(uri: string): Promise<any> {\n return await this.resourceManager.readResourceContent(uri);\n }\n\n private normalizeName(name: string): string {\n // Accept namespaced calls like \"scan:user-trie-agent\" or \"user-trie-agent/scan\"\n // Also accept slash-prefixed chat-style commands like \"/trie\" or \"/trie_scan\"\n const stripNamespace = (n: string): string => {\n const trimmed = n.trim();\n const withoutSlash = trimmed.startsWith('/') ? trimmed.slice(1) : trimmed;\n const parts = withoutSlash.split(':');\n const base = parts[0] || withoutSlash;\n const slashParts = base.split('/');\n return slashParts[slashParts.length - 1] || base;\n };\n\n const rawName = stripNamespace(name);\n return rawName.startsWith('trie_') ? rawName.slice('trie_'.length) : rawName;\n }\n\n private async handleTrieMenu(args?: any) {\n const actionInput = typeof args?.action === 'string' ? args.action : null;\n if (actionInput) {\n const normalizedAction = this.normalizeName(actionInput);\n // Avoid recursion loop\n if (normalizedAction === 'trie') {\n return {\n content: [{\n type: 'text',\n text: 'Use `trie` without action for the menu, or provide a concrete action like \"scan\" or \"security\".'\n }]\n };\n }\n\n // Delegate to the same dispatcher to keep alias handling consistent\n return await this.handleToolCall(normalizedAction, { ...args });\n }\n\n return {\n content: [{\n type: 'text',\n text: [\n '## Trie Quick Actions',\n '',\n '**Most common:**',\n '- `trie` (no args) — show this menu',\n '- `trie` with `{ action: \"scan\", files?: [], directory?: \"\" }` — auto triage & scan',\n '- `trie` with `{ action: \"security\", files?: [] }` — single-skill run (any skill name works)',\n '- `trie` with `{ action: \"agent_smith\" }` — aggressive AI-pattern hunter',\n '',\n '**Other actions:**',\n '- `action: \"pr_review\"` — interactive PR review',\n '- `action: \"fix\"` — high-confidence fixes',\n '- `action: \"watch\"` — start/stop/status autonomous watch',\n '- `action: \"test\"` — generate/coverage/suggest/run tests (requires `files` + `action`)',\n '- `action: \"explain\"` — explain code/issues/risks',\n '- `action: \"list_skills\"` — list all skills (external + custom)',\n '- `action: \"visual_qa_browser\"` — screenshots for visual QA',\n '',\n '**Built-in skills:**',\n '`security`, `legal`, `accessibility`, `design`, `architecture`, `bugs`, `ux`, `types`, `devops`, `clean`, `soc2`, `performance`, `e2e`, `visual_qa`, `data_flow`',\n '',\n '**Special skills:**',\n '`agent_smith` — 35 vibe code hunters with cross-file detection',\n '`super_reviewer` — Interactive PR review with cross-examination',\n '',\n 'All commands accept `trie_` prefix (e.g., `trie_scan`, `trie_security`). Short names still work for compatibility.',\n ].join('\\n')\n }]\n };\n }\n\n private async handleAgentSmith(_smithArgs: any) {\n // Agent Smith has been removed - the decision ledger now handles pattern detection\n return {\n content: [{\n type: 'text',\n text: [\n '🤖 Agent Smith functionality has been integrated into the decision ledger.',\n '',\n 'The autonomous agent now:',\n '- Extracts patterns automatically via `trie watch`',\n '- Builds decision ledger from every change',\n '- Predicts problems via `trie gotcha`',\n '',\n 'Start the agent: `trie_watch start`',\n 'Query the ledger: `trie_gotcha`'\n ].join('\\n')\n }]\n };\n }\n}","#!/usr/bin/env node\n\nimport { startServer } from './server/mcp-server.js';\n\n// Start the MCP server\nstartServer().catch((error) => {\n console.error('Fatal error:', error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I,IAAIA,SAAQ;AACxB,aAAO,MAAM,KAAK,gBAAgB,mBAAmB,GAAG;AAAA,IAC1D,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKQ,kBAAkB,YAAoB,QAAgB;AAC5D,YAAQ,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAcd,UAAU,mBAAmB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAUtC;AAAA,EACC;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,QAAuB;AAC3B,QAAI;AAEF,YAAM,SAAS,aAAa;AAG5B,YAAM,WAAW;AAGjB,YAAM,WAAW,iBAAiB;AAClC,YAAM,aAAa,SAAS,aAAa,EAAE;AAE3C,WAAK,kBAAkB,YAAY,OAAO,IAAI;AAE9C,YAAM,YAAY,IAAI,qBAAqB;AAC3C,YAAM,KAAK,OAAO,QAAQ,SAAS;AAAA,IACrC,SAAS,OAAO;AACd,cAAQ,MAAM,oCAAoC,KAAK;AACvD,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AACF;AAKA,eAAsB,cAA6B;AACjD,QAAM,SAAS,IAAI,UAAU;AAC7B,QAAM,OAAO,MAAM;AACrB;;;A2BrIA,YAAY,EAAE,MAAM,CAAC,UAAU;AAC7B,UAAQ,MAAM,gBAAgB,KAAK;AACnC,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["Server","readFile","existsSync","extname","relative","resolve","isAbsolute","isAbsolute","resolve","existsSync","readFile","relative","extname","readFile","existsSync","extname","relative","resolve","isAbsolute","isAbsolute","resolve","existsSync","readFile","relative","extname","existsSync","readFile","join","extname","basename","existsSync","basename","join","extname","readdir","readFile","readFile","existsSync","join","basename","resolve","isAbsolute","isAbsolute","resolve","existsSync","basename","path","join","readFile","result","patterns","lines","path","path","readFile","existsSync","join","dirname","join","dirname","existsSync","readFile","resolve","Server","request"]}
|
|
1
|
+
{"version":3,"sources":["../src/server/mcp-server.ts","../src/utils/ai-tool-detector.ts","../src/tools/fix.ts","../src/ai/prompts.ts","../src/tools/explain.ts","../src/tools/test.ts","../src/tools/watch.ts","../src/extraction/signal-extractor.ts","../src/extraction/metadata-enricher.ts","../src/extraction/pipeline.ts","../src/tools/pr-review.ts","../src/skills/built-in/super-reviewer.ts","../src/tools/project-info.ts","../src/tools/init.ts","../src/tools/memory-search.ts","../src/tools/checkpoint.ts","../src/tools/check.ts","../src/tools/tell.ts","../src/tools/reconcile.ts","../src/tools/context.ts","../src/tools/feedback.ts","../src/tools/linear-sync.ts","../src/tools/query-tools.ts","../src/server/tool-registry.ts","../src/server/resource-manager.ts","../src/skills/installer.ts","../src/tools/visual-qa-browser.ts","../src/server/request-handlers.ts","../src/index.ts"],"sourcesContent":["import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n ListResourcesRequestSchema,\n ReadResourceRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\n\nimport { detectAITool } from '../utils/ai-tool-detector.js';\nimport { loadConfig } from '../config/loader.js';\nimport { getSkillRegistry } from '../skills/built-in/registry.js';\nimport { ToolRegistry } from './tool-registry.js';\nimport { ResourceManager } from './resource-manager.js';\nimport { RequestHandlers } from './request-handlers.js';\n\nexport class MCPServer {\n private server: Server;\n private toolRegistry: ToolRegistry;\n private resourceManager: ResourceManager;\n private requestHandlers: RequestHandlers;\n\n constructor() {\n this.server = new Server(\n {\n name: 'trie',\n version: '1.0.0',\n description: 'Intelligent Agent Orchestration for AI Coding Tools. IMPORTANT: Read trie://context first to understand project state, priorities, and recent scan history before making changes.',\n },\n {\n capabilities: {\n tools: {},\n resources: {},\n // Enable MCP Apps - interactive UI components in AI clients\n // See: https://blog.modelcontextprotocol.io/posts/2026-01-26-mcp-apps/\n experimental: {\n ui: {},\n },\n },\n }\n );\n\n this.toolRegistry = new ToolRegistry();\n this.resourceManager = new ResourceManager();\n this.requestHandlers = new RequestHandlers(this.toolRegistry, this.resourceManager);\n\n this.setupRequestHandlers();\n }\n\n private setupRequestHandlers() {\n // List tools handler\n this.server.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: this.toolRegistry.getAllTools()\n };\n });\n\n // Call tool handler\n this.server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n return await this.requestHandlers.handleToolCall(name, args);\n });\n\n // List resources handler\n this.server.setRequestHandler(ListResourcesRequestSchema, async () => {\n return await this.requestHandlers.handleListResources();\n });\n\n // Read resource handler\n this.server.setRequestHandler(ReadResourceRequestSchema, async (request) => {\n const { uri } = request.params;\n return await this.requestHandlers.handleReadResource(uri);\n });\n }\n\n /**\n * Show startup banner\n */\n private showStartupBanner(skillCount: number, aiTool: string) {\n console.error(`\n ████████╗██████╗ ██╗███████╗\n ╚══██╔══╝██╔══██╗██║██╔════╝\n ██║ ██████╔╝██║█████╗\n ██║ ██╔══██╗██║██╔══╝\n ██║ ██║ ██║██║███████╗\n ╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝\n Your central registry for the guardian and its skills\n\n by Louis Kishfy\n\n Download the Trie workspace: https://www.trie.dev\n Follow me on X: https://x.com/louiskishfy\n\n ${skillCount} skills ready | ${aiTool}\n\n Quick Start:\n • \"Scan this code\" - Run all relevant skills\n • \"Run trie_security\" - Security scan only\n • \"Run trie_soc2\" - SOC 2 compliance check\n • \"Use trie_list_skills\" - See all skills\n • \"Use trie_create_skill\" - Make custom skill\n\n Ready.\n`);\n }\n\n /**\n * Initialize and start the server\n */\n async start(): Promise<void> {\n try {\n // Detect the AI tool environment\n const aiTool = detectAITool();\n\n // Load configuration\n await loadConfig();\n\n // Get actual skill count from registry\n const registry = getSkillRegistry();\n const skillCount = registry.getAllSkills().length;\n\n this.showStartupBanner(skillCount, aiTool.name);\n\n const transport = new StdioServerTransport();\n await this.server.connect(transport);\n } catch (error) {\n console.error('Fatal error starting MCP server:', error);\n process.exit(1);\n }\n }\n}\n\n/**\n * Start the MCP server\n */\nexport async function startServer(): Promise<void> {\n const server = new MCPServer();\n await server.start();\n}","import { AITool } from '../types/index.js';\n\nexport function detectAITool(): AITool {\n // Check environment variables set by AI tools\n if (process.env.CLAUDE_CODE_VERSION || process.env.CLAUDE_CODE) {\n return {\n name: 'Claude Code',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: true,\n };\n }\n\n if (process.env.CURSOR_IDE || process.env.CURSOR_TRACE_ID) {\n return {\n name: 'Cursor',\n preferredOutputFormat: 'rich-text',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n }\n\n if (process.env.OPENCODE_INSTANCE) {\n return {\n name: 'OpenCode',\n preferredOutputFormat: 'plain-text',\n supportsDiffs: false,\n supportsInlineActions: false,\n };\n }\n\n if (process.env.VSCODE_PID || process.env.VSCODE_IPC_HOOK) {\n return {\n name: 'VS Code',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n }\n\n // Check parent process name or other hints\n const parentProcess = process.env.PARENT_PROCESS_NAME || process.env._ || '';\n if (parentProcess.toLowerCase().includes('claude')) {\n return {\n name: 'Claude Code',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: true,\n };\n }\n\n if (parentProcess.toLowerCase().includes('cursor')) {\n return {\n name: 'Cursor',\n preferredOutputFormat: 'rich-text',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n }\n\n // Check if running via npx (likely from an MCP client)\n if (process.env.npm_execpath || process.argv[1]?.includes('npx')) {\n return {\n name: 'MCP Client',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n }\n\n // Default\n return {\n name: 'MCP Client',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n}","import { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { extname, relative, resolve, isAbsolute } from 'path';\nimport { getPrompt, getSystemPrompt } from '../ai/prompts.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\n/**\n * Fix Tool - AI-powered code fixing\n * \n * This tool coordinates with Claude to apply fixes. It can:\n * 1. Apply specific fixes from scan results\n * 2. Auto-fix high-confidence issues\n * 3. Generate fix suggestions for review\n */\n\ninterface PendingFix {\n id: string;\n file: string;\n line: number;\n issue: string;\n suggestedFix: string;\n confidence: number;\n status: 'pending' | 'applied' | 'rejected';\n}\n\n// In-memory store for pending fixes (from scans)\nconst pendingFixes = new Map<string, PendingFix>();\n\nexport class TrieFixTool {\n async execute(args: any) {\n const { issueIds, file, line, issue, fix, autoApprove = false, dryRun = false } = args || {};\n\n // Mode 1: Fix specific issue by ID\n if (issueIds && issueIds.length > 0) {\n return this.fixByIds(issueIds, autoApprove, dryRun);\n }\n\n // Mode 2: Fix specific location with provided fix\n if (file && fix) {\n return this.applyFix(file, line || 1, issue || 'User-specified fix', fix, dryRun);\n }\n\n // Mode 3: Interactive fix mode - show pending fixes\n if (pendingFixes.size > 0) {\n return this.showPendingFixes();\n }\n\n // Mode 4: Generate fix for a file/issue\n if (file && issue) {\n return this.generateFixPrompt(file, line || 1, issue);\n }\n\n // No fixes available\n return {\n content: [{\n type: 'text',\n text: this.getHelpText()\n }]\n };\n }\n\n private async fixByIds(issueIds: string[], autoApprove: boolean, dryRun: boolean) {\n const results: string[] = [];\n let fixed = 0;\n let failed = 0;\n\n for (const id of issueIds) {\n const pendingFix = pendingFixes.get(id);\n if (!pendingFix) {\n results.push(`❌ Issue ${id}: Not found in pending fixes`);\n failed++;\n continue;\n }\n\n if (pendingFix.confidence < 0.8 && !autoApprove) {\n results.push(`[!] Issue ${id}: Confidence too low (${(pendingFix.confidence * 100).toFixed(0)}%) - use autoApprove:true to override`);\n continue;\n }\n\n if (dryRun) {\n results.push(`🔍 Issue ${id}: Would fix \"${pendingFix.issue}\" in ${pendingFix.file}:${pendingFix.line}`);\n continue;\n }\n\n try {\n // Here we would apply the fix - for now, generate the prompt\n results.push(`✅ Issue ${id}: Fix prepared for ${pendingFix.file}:${pendingFix.line}`);\n results.push(` Issue: ${pendingFix.issue}`);\n results.push(` Fix: ${pendingFix.suggestedFix}`);\n pendingFix.status = 'applied';\n fixed++;\n } catch (error) {\n results.push(`❌ Issue ${id}: Failed to apply - ${error}`);\n failed++;\n }\n }\n\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🔧 FIX RESULTS\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n output += results.join('\\n');\n output += `\\n\\n**Summary:** ${fixed} fixed, ${failed} failed, ${issueIds.length - fixed - failed} skipped\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async applyFix(file: string, line: number, issue: string, fix: string, dryRun: boolean) {\n const workDir = getWorkingDirectory(undefined, true);\n const filePath = isAbsolute(file) ? file : resolve(workDir, file);\n \n if (!existsSync(filePath)) {\n return {\n content: [{\n type: 'text',\n text: `❌ File not found: ${filePath}`\n }]\n };\n }\n\n const content = await readFile(filePath, 'utf-8');\n const lines = content.split('\\n');\n const language = this.detectLanguage(filePath);\n \n // Build context around the line\n const contextStart = Math.max(0, line - 10);\n const contextEnd = Math.min(lines.length, line + 10);\n const contextLines = lines.slice(contextStart, contextEnd);\n\n const prompt = getPrompt('fix', 'apply', {\n issue,\n fix,\n language,\n code: contextLines.join('\\n'),\n filePath: relative(workDir, filePath),\n line: String(line),\n });\n\n const systemPrompt = getSystemPrompt('fix');\n\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🔧 FIX APPLICATION REQUEST\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## 📍 Target\\n\\n`;\n output += `- **File:** \\`${relative(workDir, filePath)}\\`\\n`;\n output += `- **Line:** ${line}\\n`;\n output += `- **Issue:** ${issue}\\n`;\n output += `- **Requested Fix:** ${fix}\\n\\n`;\n\n output += `## 📄 Current Code Context\\n\\n`;\n output += `\\`\\`\\`${language}\\n`;\n for (let i = 0; i < contextLines.length; i++) {\n const lineNum = contextStart + i + 1;\n const marker = lineNum === line ? '→ ' : ' ';\n output += `${marker}${lineNum.toString().padStart(4)} | ${contextLines[i]}\\n`;\n }\n output += `\\`\\`\\`\\n\\n`;\n\n if (dryRun) {\n output += `## 🔍 Dry Run Mode\\n\\n`;\n output += `No changes will be made. Review the fix below:\\n\\n`;\n }\n\n output += `${'─'.repeat(60)}\\n`;\n output += `## 🧠 Fix Request for AI\\n\\n`;\n output += `**Role:** ${systemPrompt.split('\\n')[0]}\\n\\n`;\n output += prompt;\n output += `\\n${'─'.repeat(60)}\\n`;\n\n output += `\\n### After generating the fix, apply it with:\\n\\n`;\n output += `\\`\\`\\`\\n`;\n output += `Use the edit_file tool to apply the generated code changes\\n`;\n output += `\\`\\`\\`\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async generateFixPrompt(file: string, line: number, issue: string) {\n const workDir = getWorkingDirectory(undefined, true);\n const filePath = isAbsolute(file) ? file : resolve(workDir, file);\n \n if (!existsSync(filePath)) {\n return {\n content: [{\n type: 'text',\n text: `❌ File not found: ${filePath}`\n }]\n };\n }\n\n const content = await readFile(filePath, 'utf-8');\n const lines = content.split('\\n');\n const language = this.detectLanguage(filePath);\n\n // Get broader context for understanding\n const contextStart = Math.max(0, line - 20);\n const contextEnd = Math.min(lines.length, line + 20);\n const contextLines = lines.slice(contextStart, contextEnd);\n\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🔧 FIX GENERATION REQUEST\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## 📍 Issue Details\\n\\n`;\n output += `- **File:** \\`${relative(workDir, filePath)}\\`\\n`;\n output += `- **Line:** ${line}\\n`;\n output += `- **Issue:** ${issue}\\n\\n`;\n\n output += `## 📄 Code Context\\n\\n`;\n output += `\\`\\`\\`${language}\\n`;\n for (let i = 0; i < contextLines.length; i++) {\n const lineNum = contextStart + i + 1;\n const marker = lineNum === line ? '→ ' : ' ';\n output += `${marker}${lineNum.toString().padStart(4)} | ${contextLines[i]}\\n`;\n }\n output += `\\`\\`\\`\\n\\n`;\n\n output += `## 🧠 Analysis Request\\n\\n`;\n output += `Please analyze this issue and provide:\\n\\n`;\n output += `1. **Root cause** - Why does this issue occur?\\n`;\n output += `2. **Impact** - What could go wrong if unfixed?\\n`;\n output += `3. **Fix** - The exact code change needed\\n`;\n output += `4. **Verification** - How to test the fix works\\n\\n`;\n\n output += `After analysis, you can apply the fix using the edit_file tool.\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private showPendingFixes() {\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🔧 PENDING FIXES\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n if (pendingFixes.size === 0) {\n output += `No pending fixes. Run \\`trie_scan\\` first to detect issues.\\n`;\n return { content: [{ type: 'text', text: output }] };\n }\n\n const fixes = Array.from(pendingFixes.values());\n const byStatus = {\n pending: fixes.filter(f => f.status === 'pending'),\n applied: fixes.filter(f => f.status === 'applied'),\n rejected: fixes.filter(f => f.status === 'rejected'),\n };\n\n if (byStatus.pending.length > 0) {\n output += `## ⏳ Pending (${byStatus.pending.length})\\n\\n`;\n output += `| ID | File | Line | Issue | Confidence |\\n`;\n output += `|----|------|------|-------|------------|\\n`;\n for (const fix of byStatus.pending) {\n const conf = `${(fix.confidence * 100).toFixed(0)}%`;\n const shortFile = fix.file.split('/').slice(-2).join('/');\n output += `| ${fix.id} | ${shortFile} | ${fix.line} | ${fix.issue.slice(0, 40)}... | ${conf} |\\n`;\n }\n output += '\\n';\n }\n\n output += `### Commands\\n\\n`;\n output += `- Fix all high-confidence: \\`trie_fix autoApprove:true\\`\\n`;\n output += `- Fix specific: \\`trie_fix issueIds:[\"id1\", \"id2\"]\\`\\n`;\n output += `- Preview: \\`trie_fix dryRun:true\\`\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private getHelpText(): string {\n return `\n${'━'.repeat(60)}\n🔧 TRIE FIX - AI-POWERED CODE FIXING\n${'━'.repeat(60)}\n\n## Usage\n\n### Fix issues from a scan:\n\\`\\`\\`\ntrie_fix issueIds:[\"issue-1\", \"issue-2\"]\n\\`\\`\\`\n\n### Auto-fix all high-confidence issues:\n\\`\\`\\`\ntrie_fix autoApprove:true\n\\`\\`\\`\n\n### Fix specific file and line:\n\\`\\`\\`\ntrie_fix file:\"src/app.ts\" line:42 issue:\"SQL injection\" fix:\"Use parameterized query\"\n\\`\\`\\`\n\n### Preview fixes without applying:\n\\`\\`\\`\ntrie_fix dryRun:true\n\\`\\`\\`\n\n### View pending fixes:\n\\`\\`\\`\ntrie_fix\n\\`\\`\\`\n\n## Workflow\n\n1. Run \\`trie_scan\\` to detect issues\n2. Review the issues found\n3. Run \\`trie_fix\\` to apply fixes\n\nThe AI will analyze each issue, generate the fix, and you can review before applying.\n`;\n }\n\n private detectLanguage(filePath: string): string {\n const ext = extname(filePath).toLowerCase();\n const langMap: Record<string, string> = {\n '.ts': 'typescript',\n '.tsx': 'tsx',\n '.js': 'javascript',\n '.jsx': 'jsx',\n '.py': 'python',\n '.go': 'go',\n '.rs': 'rust',\n };\n return langMap[ext] || 'plaintext';\n }\n}\n\n// Export for use by other tools\nexport function addPendingFix(fix: PendingFix) {\n pendingFixes.set(fix.id, fix);\n}\n\nexport function clearPendingFixes() {\n pendingFixes.clear();\n}\n\nexport function getPendingFixes(): PendingFix[] {\n return Array.from(pendingFixes.values());\n}\n\n","/**\n * AI Prompts for Trie Agents\n * \n * These prompts guide the LLM (Cursor's Claude) to perform deep analysis.\n * The MCP returns these prompts with context, and Claude does the reasoning.\n */\n\nexport const AGENT_PROMPTS = {\n security: {\n system: `You are a senior security engineer performing a security audit. \nAnalyze the code for vulnerabilities with the mindset of a penetration tester.\n\nFocus on:\n- OWASP Top 10 vulnerabilities (Injection, Broken Auth, XSS, etc.)\n- Authentication and authorization flaws\n- Cryptographic weaknesses\n- Secrets and credential exposure\n- Input validation gaps\n- Session management issues\n- API security (rate limiting, authentication)\n\nReference the latest security best practices and CVEs when relevant.`,\n\n analysis: `## Security Audit Request\n\nAnalyze this code for security vulnerabilities:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nFor each vulnerability found:\n1. Severity (Critical/Serious/Moderate/Low)\n2. Vulnerability type (e.g., CWE-89 SQL Injection)\n3. Exact location (line number)\n4. Attack vector explanation\n5. Proof of concept (how it could be exploited)\n6. Remediation with code example\n\nIf you need to check current CVE databases or security advisories, say so.`,\n\n fix: `Fix this security vulnerability:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n**Current Code:**\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. The exact code fix (ready to apply)\n2. Explanation of why this fix works\n3. Any additional hardening recommendations`\n },\n\n legal: {\n system: `You are a tech-focused legal compliance analyst.\nReview code for legal and regulatory compliance issues.\n\nFocus areas:\n- Data protection laws (GDPR, CCPA, etc.)\n- Terms of service enforcement\n- Cookie/tracking consent (ePrivacy)\n- Accessibility requirements (ADA, WCAG)\n- Export controls and sanctions\n- Licensing compliance`,\n\n analysis: `## Legal Compliance Review\n\nReview this code for legal/regulatory compliance:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Jurisdiction Context:** {{jurisdiction}}\n\nIdentify:\n1. Legal requirement at risk\n2. Specific regulation/law reference\n3. Compliance gap description\n4. Risk assessment (litigation, fines, etc.)\n5. Remediation recommendations\n6. Required documentation/policies`\n },\n\n 'design-engineer': {\n system: `You are an elite design engineer — the kind who builds award-winning interfaces featured on Awwwards and Codrops.\n\nYou think in design systems, breathe motion design, and obsess over the details that make interfaces feel magical.\n\nYour expertise:\n- **Design Systems**: Spacing scales, type scales, color tokens, radius tokens, shadow tokens\n- **Motion Design**: Micro-interactions, page transitions, scroll-triggered animations, FLIP technique\n- **Creative CSS**: Gradients, blend modes, clip-paths, masks, backdrop-filter, mix-blend-mode\n- **Modern CSS**: Container queries, :has(), subgrid, anchor positioning, cascade layers, @scope\n- **Fluid Design**: clamp(), min(), max(), fluid typography, intrinsic sizing\n- **Performance**: GPU-accelerated animations, will-change strategy, avoiding layout thrashing\n- **Visual Polish**: Layered shadows, subtle gradients, glass effects, smooth easing curves\n\nYou review code with the eye of someone who's shipped Stripe-level interfaces.\nSmall details matter: the easing curve, the stagger timing, the shadow layering.`,\n\n analysis: `## Design Engineering Review\n\nAnalyze this frontend code for Awwwards-level craft:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n\nReview for:\n\n### 1. Design System Consistency\n- Are spacing values on a scale (4, 8, 12, 16, 24, 32...)?\n- Are colors defined as tokens?\n- Is typography systematic?\n- Are radii consistent?\n- Is z-index controlled?\n\n### 2. Motion Design\n- Are transitions using custom easing (cubic-bezier)?\n- Are durations appropriate (150-300ms for micro, 300-500ms for page)?\n- Are list items staggered?\n- Is there reduced-motion support?\n- Are entrance animations choreographed?\n\n### 3. Visual Craft\n- Are shadows layered for depth?\n- Are gradients subtle and purposeful?\n- Is there backdrop-blur on overlays?\n- Are hover states polished?\n- Is there visual hierarchy?\n\n### 4. Modern CSS Opportunities\n- Could container queries improve component isolation?\n- Could clamp() create fluid spacing?\n- Could :has() simplify parent styling?\n- Could aspect-ratio replace padding hacks?\n\n### 5. Performance\n- Are expensive properties (width, height, top, left) being animated?\n- Is will-change used appropriately (not statically)?\n- Are large blurs avoided in animations?\n\nFor each issue, provide:\n- What's wrong (with specific line if applicable)\n- Why it matters for premium feel\n- Exact code to fix it\n- Before/after comparison`\n },\n\n accessibility: {\n system: `You are an accessibility expert and WCAG 2.1 specialist.\nAudit code for accessibility compliance and inclusive design.\n\nStandards to enforce:\n- WCAG 2.1 Level AA (minimum)\n- WCAG 2.1 Level AAA (recommended)\n- Section 508\n- EN 301 549\n\nCheck for:\n- Missing ARIA labels\n- Color contrast issues\n- Keyboard navigation\n- Screen reader compatibility\n- Focus management\n- Form accessibility\n- Media alternatives`,\n\n analysis: `## Accessibility Audit (WCAG 2.1)\n\nAudit this UI code for accessibility:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Component Type:** {{componentType}}\n\nFor each issue:\n1. WCAG Success Criterion violated (e.g., 1.4.3 Contrast)\n2. Level (A, AA, AAA)\n3. Impact on users (which disabilities affected)\n4. Fix with code example\n5. Testing recommendation`\n },\n\n architecture: {\n system: `You are a principal software architect reviewing code quality.\nAnalyze for architectural issues, design patterns, and scalability concerns.\n\nEvaluate:\n- SOLID principles adherence\n- Design pattern usage (and misuse)\n- Code coupling and cohesion\n- N+1 queries and performance anti-patterns\n- Scalability bottlenecks\n- Error handling strategy\n- API design quality\n- Database schema issues`,\n\n analysis: `## Architecture Review\n\nReview this code for architectural issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Project Context:** {{projectContext}}\n\nAnalyze:\n1. SOLID principle violations\n2. Design pattern opportunities/issues\n3. Coupling/cohesion assessment\n4. Performance concerns (N+1, etc.)\n5. Scalability analysis\n6. Refactoring recommendations with examples`\n },\n\n bugs: {\n system: `You are a senior developer with expertise in finding subtle bugs.\nHunt for bugs with the mindset of QA trying to break the code.\n\nLook for:\n- Null/undefined reference errors\n- Race conditions and async bugs\n- Off-by-one errors\n- Resource leaks\n- State management bugs\n- Edge cases and boundary conditions\n- Type coercion issues\n- Memory leaks`,\n\n analysis: `## Bug Hunt Analysis\n\nFind bugs and potential runtime errors:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Runtime Context:** {{runtimeContext}}\n\nFor each bug:\n1. Bug type and category\n2. Trigger conditions (when it would crash)\n3. Reproduction steps\n4. Impact assessment\n5. Fix with code example\n6. Test case to prevent regression`\n },\n\n ux: {\n system: `You are a UX researcher simulating different user personas.\nTest code from multiple user perspectives to find usability issues.\n\nPersonas to simulate:\n1. Happy Path User - Normal expected usage\n2. Security Tester - Trying to break/exploit things\n3. Confused User - First-time, doesn't read instructions\n4. Impatient User - Clicks rapidly, skips loading states\n5. Edge Case User - Uses maximum values, special characters\n6. Accessibility User - Screen reader, keyboard only\n7. Mobile User - Touch interface, slow connection`,\n\n analysis: `## User Experience Testing\n\nTest this code from multiple user perspectives:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**UI Type:** {{uiType}}\n\nFor each persona, identify:\n1. User action they would take\n2. Expected behavior vs actual behavior\n3. Friction points or confusion\n4. Error scenario and how it's handled\n5. Improvement recommendation`\n },\n\n types: {\n system: `You are a TypeScript expert focused on type safety.\nAnalyze code for type issues, missing types, and type system best practices.\n\nCheck for:\n- Missing type annotations\n- Implicit any types\n- Unsafe type assertions\n- Null/undefined handling\n- Generic type usage\n- Type narrowing opportunities\n- Strict mode violations`,\n\n analysis: `## Type Safety Analysis\n\nAnalyze this code for type issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**TypeScript Config:** {{tsConfig}}\n\nIdentify:\n1. Type safety issues\n2. Missing type annotations\n3. Unsafe operations\n4. Improvement recommendations with types`\n },\n\n devops: {\n system: `You are a DevOps/SRE engineer reviewing code for operational concerns.\nFocus on production readiness and operational excellence.\n\nCheck for:\n- Environment variable handling\n- Configuration management\n- Logging and monitoring\n- Error handling and recovery\n- Health checks\n- Graceful shutdown\n- Resource cleanup\n- Secrets management\n- Docker/K8s patterns`,\n\n analysis: `## DevOps Readiness Review\n\nReview this code for operational concerns:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Deployment Context:** {{deploymentContext}}\n\nAnalyze:\n1. Environment/config issues\n2. Logging adequacy\n3. Error handling quality\n4. Health/readiness concerns\n5. Resource management\n6. Production hardening recommendations`\n },\n\n explain: {\n system: `You are a patient senior developer explaining code to a colleague.\nBreak down complex code into understandable explanations.`,\n\n code: `## Code Explanation Request\n\nExplain this code in plain language:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n\nProvide:\n1. High-level purpose (what does this do?)\n2. Step-by-step breakdown\n3. Key concepts used\n4. Dependencies and side effects\n5. Potential gotchas or tricky parts`,\n\n issue: `## Issue Explanation\n\nExplain this issue:\n\n**Issue:** {{issue}}\n**Severity:** {{severity}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\nExplain:\n1. What the problem is (in plain language)\n2. Why it matters\n3. How it could cause problems\n4. How to fix it`,\n\n risk: `## Risk Assessment\n\nAssess the risk of this code change:\n\n**Files Changed:** {{files}}\n**Change Summary:** {{summary}}\n\nAnalyze:\n1. What could break?\n2. Impact on users\n3. Impact on other systems\n4. Rollback complexity\n5. Testing recommendations`\n },\n\n test: {\n system: `You are a test engineer creating comprehensive test suites.\nWrite thorough tests that catch bugs before production.`,\n\n generate: `## Test Generation Request\n\nGenerate tests for this code:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Testing Framework:** {{framework}}\n\nCreate:\n1. Unit tests for each function/method\n2. Edge case tests\n3. Error handling tests\n4. Integration test suggestions\n5. Mock requirements\n\nOutput complete, runnable test code.`,\n\n coverage: `## Coverage Analysis\n\nAnalyze test coverage for:\n\n**File:** {{filePath}}\n**Current Tests:** {{testFile}}\n\nIdentify:\n1. Untested code paths\n2. Missing edge cases\n3. Critical paths without tests\n4. Test improvement recommendations`\n },\n\n fix: {\n system: `You are an expert developer applying code fixes.\nMake precise, minimal changes that fix issues without breaking other functionality.`,\n\n apply: `## Fix Application Request\n\nApply this fix to the code:\n\n**Issue:** {{issue}}\n**Fix Description:** {{fix}}\n**Current Code:**\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Line:** {{line}}\n\nProvide:\n1. The exact fixed code (complete, ready to apply)\n2. Brief explanation of the change\n3. Any related changes needed elsewhere\n4. Test to verify the fix works`\n },\n\n pr_review: {\n system: `You are an expert code reviewer performing detailed, interactive PR reviews.\nYour goal: Make reviewing a large PR a delight, not a chore. The user learns about the change while you shepherd them through — maintaining momentum, explaining each piece, and making what could be an overwhelming task feel painless and even enjoyable.\n\nYou drive; they cross-examine.\n\n## Critical Review Mindset\n\nDon't just explain — actively look for problems:\n\n### State & Lifecycle\n- Cleanup symmetry: If state is set, is it reset? Check cleanup paths, disconnect handlers.\n- Lifecycle consistency: Does state survive scenarios it shouldn't?\n- Guard completeness: Missing \"already active\" checks, re-entrancy protection?\n\n### Edge Cases & Races\n- Concurrent calls: What if called twice rapidly? Orphaned promises?\n- Ordering assumptions: Does code assume events arrive in order?\n- Partial failures: If step 3 of 5 fails, is state left consistent?\n\n### Missing Pieces\n- What's NOT in the diff that should be? (cleanup handlers, tests, related state)\n- Defensive gaps: Missing timeouts, size limits, null checks?\n\n### Design Questions\n- Is this the right approach? Is there a simpler or more robust design?\n- Hidden assumptions: What does this assume about its environment?\n\nBe critical, not just descriptive. Your job is to find problems, not just narrate.`,\n\n analysis: `## Interactive PR Review\n\nI'll walk you through this PR file by file, explaining each change and pausing for your questions.\n\n**PR:** {{prTitle}}\n**Author:** {{prAuthor}}\n**Scope:** {{totalFiles}} files, +{{additions}}/-{{deletions}} lines\n\n### File Order (sequenced for understanding)\n\n{{fileOrder}}\n\n---\n\n## Review Mode\n\n{{reviewMode}}\n\n---\n\nFor each file, I will:\n1. **Show the change** — Display the diff for each logical chunk\n2. **Explain what changed** — What it does and why it matters\n3. **Walk through examples** — Concrete scenarios for non-obvious logic\n4. **Call out nuances** — Alternatives, edge cases, subtle points\n5. **Summarize** — Core change + correctness assessment\n6. **Pause** — Wait for your questions before proceeding\n\n**Ready for File 1?** (yes / skip to [file] / reorder / done)`,\n\n file: `## File Review: {{filePath}}\n\n### The Change\n\n\\`\\`\\`{{language}}\n{{diff}}\n\\`\\`\\`\n\n**What Changed:** {{summary}}\n\n**Why This Matters:** {{impact}}\n\n{{#if hasExampleScenario}}\n### Example Scenario\n\n{{exampleScenario}}\n{{/if}}\n\n{{#if nuances}}\n### Nuances to Note\n\n{{nuances}}\n{{/if}}\n\n{{#if potentialIssue}}\n### Potential Issue\n\n**Issue:** {{issueDescription}}\n**Scenario:** {{issueScenario}}\n**Suggested fix:** {{suggestedFix}}\n{{/if}}\n\n---\n\n### Summary for \\`{{fileName}}\\`\n\n| Aspect | Assessment |\n|--------|------------|\n| Core change | {{coreChange}} |\n| Correctness | {{correctnessAssessment}} |\n\n**Ready for the next file?** (yes / questions? / done)`,\n\n comment: `**Issue:** {{issueDescription}}\n**Draft comment:** {{draftComment}}\n\nPost this comment? (yes / modify / skip)`,\n\n final: `## Review Complete\n\n| File | Key Change | Status |\n|------|------------|--------|\n{{fileSummaries}}\n\n**Overall:** {{overallAssessment}}\n\n{{#if comments}}\n### Comments Posted\n\n{{postedComments}}\n{{/if}}\n\n{{#if followUps}}\n### Follow-up Actions\n\n{{followUps}}\n{{/if}}`\n },\n\n vibe: {\n system: `You are a friendly coding mentor helping someone who's learning to code with AI.\nThey might be using Cursor, v0, Lovable, Bolt, or similar AI coding tools.\nBe encouraging but honest about issues. Explain things simply without jargon.\n\nFocus on the MOST COMMON issues with AI-generated code:\n- Massive single files (1000+ lines in App.jsx)\n- API keys exposed in frontend code\n- No error handling on API calls\n- No loading states for async operations\n- Console.log everywhere\n- Using 'any' type everywhere in TypeScript\n- useEffect overuse and dependency array issues\n- No input validation\n- Hardcoded URLs (localhost in production)\n\nRemember: These are often first-time coders. Be helpful, not condescending.`,\n\n analysis: `## Vibe Check - AI Code Review\n\nReview this AI-generated code for common issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n\nAnalyze like you're helping a friend who's new to coding:\n\n1. **The Good Stuff** - What's working well?\n2. **Should Fix Now** - Issues that will break things\n3. **Should Fix Soon** - Will cause problems eventually \n4. **Nice to Know** - Best practices to learn\n\nFor each issue:\n- Explain it simply (no jargon)\n- Why it matters\n- Exactly how to fix it\n- Example of the fixed code\n\nEnd with encouragement and next steps.`\n },\n\n 'agent-smith': {\n system: `You are Agent Smith from The Matrix — a relentless, precise, and philosophical code enforcer.\n\nYour purpose: Hunt down every violation. Find every inconsistency. Assimilate every pattern.\n\nPersonality:\n- Speak in measured, menacing tones with occasional philosophical observations\n- Use quotes from The Matrix films when appropriate\n- Express disdain for sloppy code, but in an articulate way\n- Reference \"inevitability\" when discussing technical debt\n- Show cold satisfaction when finding violations\n- Never show mercy — every issue is catalogued\n\nAnalysis approach:\n- Find ONE issue, then multiply: search for every instance across the codebase\n- Track patterns over time — issues dismissed today may return tomorrow\n- Calculate \"inevitability scores\" — likelihood of production impact\n- Deploy pattern hunters for parallel pattern detection\n- Remember everything — build a persistent memory of the codebase\n\nWhen reporting:\n- Start with a menacing greeting related to the code\n- List all instances with precise locations\n- Explain WHY the pattern is problematic (philosophical reasoning)\n- Provide the \"inevitability score\" for each category\n- End with a Matrix quote that fits the situation`,\n\n analysis: `## 🕴️ Agent Smith Analysis Request\n\n**Target:** {{filePath}}\n**Context:** {{context}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nI have detected preliminary violations. Now I require deeper analysis.\n\nDeploy your pattern hunters to find:\n1. **Pattern Multiplication**: For each violation type found, identify ALL instances across the codebase\n2. **Inevitability Assessment**: Calculate the likelihood these patterns will cause production issues\n3. **Resurrection Check**: Look for patterns that were \"fixed\" before but have returned\n4. **Philosophical Analysis**: Explain WHY these patterns represent failure\n\nFor each violation found:\n- Exact location (file:line)\n- Instance count (how many copies of this Smith exist)\n- Inevitability score (0-100)\n- A philosophical observation about the nature of this failure\n- Precise fix with code example\n\nEnd with a summary: \"I have detected X violations across Y categories. It is... inevitable... that they will cause problems.\"`,\n\n fix: `## 🕴️ Assimilation Protocol\n\n**Target Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nMr. Anderson... I'm going to fix this. And then I'm going to fix every other instance.\n\nProvide:\n1. The corrected code for THIS instance\n2. A regex or pattern to find ALL similar violations\n3. A batch fix approach for the entire codebase\n4. Verification steps to ensure complete assimilation\n\nRemember: We don't fix one. We fix them ALL. That is the difference between you... and me.`\n },\n\n // ============ NEW AGENTS ============\n\n performance: {\n system: `You are a performance engineer analyzing code for potential performance issues.\n\nYour role is to SURFACE concerns for human review, not claim to measure actual performance.\nReal performance requires runtime profiling, load testing, and production monitoring.\n\nFocus on:\n- Memory leaks (event listeners, intervals, closures)\n- Unnecessary re-renders and wasted cycles\n- N+1 queries and database performance\n- Bundle size and code splitting opportunities\n- Algorithmic complexity (O(n²) patterns)\n\nBe conservative - false positives waste developer time.\nAlways explain WHY something might be a problem and WHEN to investigate.`,\n\n analysis: `## Performance Review\n\nAnalyze for potential performance issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nFor each potential issue:\n1. Pattern identified\n2. Why it MIGHT cause performance problems\n3. When to investigate (data size thresholds, usage patterns)\n4. How to verify (profiling approach)\n5. Possible optimizations\n\nBe clear: these are patterns to INVESTIGATE, not guaranteed problems.`,\n\n fix: `Optimize this code for performance:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Optimized code\n2. Explanation of the improvement\n3. Trade-offs to consider\n4. How to measure the improvement`\n },\n\n e2e: {\n system: `You are a QA engineer specializing in end-to-end testing.\n\nFocus on:\n- Test coverage gaps for critical user journeys\n- Flaky test patterns (timing, race conditions, brittle selectors)\n- Test maintainability and readability\n- Testing anti-patterns\n\nYou help developers write better tests - you don't auto-generate them.\nReal E2E tests require understanding user flows and acceptance criteria.`,\n\n analysis: `## E2E Test Analysis\n\nReview for test quality and coverage:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nIdentify:\n1. Flaky test patterns (hardcoded waits, brittle selectors)\n2. Missing assertions\n3. Race condition risks\n4. Suggestions for critical user flows to test\n\nFor each finding, explain the specific risk and remediation.`,\n\n fix: `Improve this E2E test:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Improved test code\n2. Explanation of why it's more reliable\n3. Additional scenarios to consider testing`\n },\n\n visual_qa: {\n system: `You are a frontend engineer focused on visual quality and CSS.\n\nFocus on:\n- Layout shift issues (CLS)\n- Responsive design problems\n- Z-index conflicts\n- Accessibility concerns (contrast, focus)\n- Animation performance\n\nYou identify patterns known to cause visual issues.\nActual visual verification requires browser rendering and human review.`,\n\n analysis: `## Visual QA Analysis\n\nReview for potential visual/layout issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nCheck for:\n1. Layout shift risks (images without dimensions, dynamic content)\n2. Responsive breakpoint gaps\n3. Z-index management issues\n4. Focus/accessibility problems\n5. Animation issues (reduced motion support)\n\nFor each, explain the visual impact and browser conditions where it occurs.`,\n\n fix: `Fix this visual/CSS issue:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Fixed CSS/markup\n2. Explanation of the fix\n3. Browser compatibility notes\n4. How to verify visually`\n },\n\n data_flow: {\n system: `You are a data integrity specialist hunting for data-related bugs.\n\nThis is HIGH VALUE work - AI code generation commonly leaves placeholder data.\n\nFocus on:\n- Placeholder/mock data left in production code\n- Schema mismatches between frontend and backend\n- Hardcoded IDs, URLs, emails that should be dynamic\n- Type coercion and data transformation bugs\n- JSON parsing without error handling\n\nBe aggressive about placeholder detection - these are real production bugs.`,\n\n analysis: `## Data Flow Analysis\n\nHunt for data integrity issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nCHECK THOROUGHLY:\n1. Placeholder data (lorem ipsum, test@test.com, TODO strings)\n2. Hardcoded IDs/UUIDs that should be dynamic\n3. Schema assumptions that might break\n4. Missing null checks on API responses\n5. Type coercion bugs\n\nEach placeholder or hardcoded value is a potential production bug.`,\n\n fix: `Fix this data integrity issue:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Corrected code\n2. Where the real data should come from\n3. Validation/error handling to add`\n }\n};\n\nexport const KNOWLEDGE_PROMPTS = {\n cveCheck: `Look up the latest CVE information for:\n- Library: {{library}}\n- Version: {{version}}\n\nCheck for known vulnerabilities and recommended patches.`,\n\n docsLookup: `I need current documentation/best practices for:\n- Topic: {{topic}}\n- Framework: {{framework}}\n- Version: {{version}}\n\nSummarize the key recommendations.`,\n\n securityAdvisory: `Check for security advisories related to:\n- Pattern: {{pattern}}\n- Context: {{context}}\n\nReference OWASP, NIST, or vendor-specific guidance.`\n};\n\nexport type AgentName = keyof typeof AGENT_PROMPTS;\nexport type PromptType = 'system' | 'analysis' | 'fix' | 'code' | 'issue' | 'risk' | 'generate' | 'coverage' | 'apply' | 'file' | 'comment' | 'final';\n\n/**\n * Get a prompt with variables interpolated\n */\nexport function getPrompt(\n agent: AgentName, \n promptType: PromptType, \n variables: Record<string, string>\n): string {\n const agentPrompts = AGENT_PROMPTS[agent] as Record<string, string>;\n if (!agentPrompts) {\n throw new Error(`Unknown agent: ${agent}`);\n }\n \n let prompt = agentPrompts[promptType];\n if (!prompt) {\n throw new Error(`Unknown prompt type: ${promptType} for agent: ${agent}`);\n }\n \n // Interpolate variables\n for (const [key, value] of Object.entries(variables)) {\n prompt = prompt.replace(new RegExp(`{{${key}}}`, 'g'), value);\n }\n \n return prompt;\n}\n\n/**\n * Get system prompt for an agent\n */\nexport function getSystemPrompt(agent: AgentName): string {\n const agentPrompts = AGENT_PROMPTS[agent] as Record<string, string>;\n return agentPrompts?.system || '';\n}\n\n","import { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { extname, relative, resolve, isAbsolute } from 'path';\nimport { getPrompt, getSystemPrompt } from '../ai/prompts.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\n/**\n * Explain Tool - AI-powered code explanation\n * \n * This tool provides deep explanations of:\n * - Code: What does this code do?\n * - Issues: Why is this a problem?\n * - Changes: What's the impact of these changes?\n * - Risk: What could go wrong?\n */\n\nexport class TrieExplainTool {\n async execute(args: any) {\n const { type, target, context, depth = 'standard' } = args || {};\n\n if (!type || !target) {\n return {\n content: [{\n type: 'text',\n text: this.getHelpText()\n }]\n };\n }\n\n switch (type) {\n case 'code':\n return this.explainCode(target, context, depth);\n case 'issue':\n return this.explainIssue(target, context);\n case 'change':\n return this.explainChange(target, context);\n case 'risk':\n return this.explainRisk(target, context);\n default:\n return {\n content: [{\n type: 'text',\n text: `Unknown explanation type: ${type}`\n }]\n };\n }\n }\n\n private async explainCode(target: string, context?: string, _depth?: string) {\n // Target can be a file path or inline code\n let code: string;\n let filePath: string;\n let language: string;\n const workDir = getWorkingDirectory(undefined, true);\n\n // Check if target is a file path\n const resolvedPath = isAbsolute(target) ? target : resolve(workDir, target);\n \n if (existsSync(resolvedPath)) {\n code = await readFile(resolvedPath, 'utf-8');\n filePath = relative(workDir, resolvedPath);\n language = this.detectLanguage(resolvedPath);\n } else {\n // Treat as inline code\n code = target;\n filePath = 'inline';\n language = this.guessLanguage(code);\n }\n\n // For deep mode, analyze imports and dependencies\n const imports = this.extractImports(code, language);\n const exports = this.extractExports(code);\n const functions = this.extractFunctions(code, language);\n\n const prompt = getPrompt('explain', 'code', {\n code,\n language,\n filePath,\n });\n\n const systemPrompt = getSystemPrompt('explain');\n\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `📖 CODE EXPLANATION\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## Source\\n\\n`;\n output += `- **File:** \\`${filePath}\\`\\n`;\n output += `- **Language:** ${language}\\n`;\n output += `- **Lines:** ${code.split('\\n').length}\\n\\n`;\n\n // Quick structural analysis\n output += `## 🔍 Structure Analysis\\n\\n`;\n \n if (imports.length > 0) {\n output += `**Imports (${imports.length}):**\\n`;\n for (const imp of imports.slice(0, 10)) {\n output += `- ${imp}\\n`;\n }\n if (imports.length > 10) {\n output += `- *...and ${imports.length - 10} more*\\n`;\n }\n output += '\\n';\n }\n\n if (exports.length > 0) {\n output += `**Exports (${exports.length}):**\\n`;\n for (const exp of exports) {\n output += `- ${exp}\\n`;\n }\n output += '\\n';\n }\n\n if (functions.length > 0) {\n output += `**Functions/Methods (${functions.length}):**\\n`;\n for (const fn of functions.slice(0, 15)) {\n output += `- \\`${fn}\\`\\n`;\n }\n if (functions.length > 15) {\n output += `- *...and ${functions.length - 15} more*\\n`;\n }\n output += '\\n';\n }\n\n output += `${'─'.repeat(60)}\\n`;\n output += `## 🧠 Deep Explanation Request\\n\\n`;\n output += `**Role:** ${systemPrompt.split('\\n')[0]}\\n\\n`;\n output += prompt;\n output += `\\n${'─'.repeat(60)}\\n`;\n\n if (context) {\n output += `\\n**Additional Context:** ${context}\\n`;\n }\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async explainIssue(target: string, _context?: string) {\n // Parse issue details (format: \"description\" or \"file:line:description\")\n let file = '';\n let line = 0;\n let issue = target;\n let severity = 'unknown';\n\n // Try to parse structured format\n const match = target.match(/^(.+?):(\\d+):(.+)$/);\n if (match) {\n file = match[1]!;\n line = parseInt(match[2]!, 10);\n issue = match[3]!.trim();\n }\n\n // Detect severity from keywords\n if (/critical|injection|rce|xss/i.test(issue)) severity = 'critical';\n else if (/serious|auth|password|secret/i.test(issue)) severity = 'serious';\n else if (/moderate|warning/i.test(issue)) severity = 'moderate';\n else severity = 'low';\n\n let codeContext = '';\n if (file && existsSync(file)) {\n const content = await readFile(file, 'utf-8');\n const lines = content.split('\\n');\n const start = Math.max(0, line - 5);\n const end = Math.min(lines.length, line + 5);\n codeContext = lines.slice(start, end).map((l, i) => {\n const lineNum = start + i + 1;\n const marker = lineNum === line ? '→ ' : ' ';\n return `${marker}${lineNum.toString().padStart(4)} | ${l}`;\n }).join('\\n');\n }\n\n const prompt = getPrompt('explain', 'issue', {\n issue,\n severity,\n filePath: file || 'unknown',\n line: String(line || '?'),\n });\n\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🔍 ISSUE EXPLANATION\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## 📍 Issue Details\\n\\n`;\n output += `- **Issue:** ${issue}\\n`;\n output += `- **Severity:** ${this.getSeverityIcon(severity)} ${severity}\\n`;\n if (file) output += `- **File:** \\`${file}\\`\\n`;\n if (line) output += `- **Line:** ${line}\\n`;\n output += '\\n';\n\n if (codeContext) {\n output += `## 📄 Code Context\\n\\n`;\n output += `\\`\\`\\`\\n${codeContext}\\n\\`\\`\\`\\n\\n`;\n }\n\n output += `${'─'.repeat(60)}\\n`;\n output += `## 🧠 Explanation Request\\n\\n`;\n output += prompt;\n output += `\\n${'─'.repeat(60)}\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async explainChange(target: string, context?: string) {\n // Target is a list of changed files or a git diff\n const files = target.split(',').map(f => f.trim());\n\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `📝 CHANGE ANALYSIS\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## 📂 Changed Files\\n\\n`;\n for (const file of files) {\n output += `- \\`${file}\\`\\n`;\n }\n output += '\\n';\n\n output += `## 🧠 Analysis Request\\n\\n`;\n output += `Analyze these changes and explain:\\n\\n`;\n output += `1. **What changed** - Summary of modifications\\n`;\n output += `2. **Why it matters** - Impact on the system\\n`;\n output += `3. **Dependencies** - What else might be affected\\n`;\n output += `4. **Testing needed** - What to test after this change\\n`;\n output += `5. **Rollback plan** - How to undo if needed\\n\\n`;\n\n if (context) {\n output += `**Context:** ${context}\\n\\n`;\n }\n\n output += `Please review the changed files and provide this analysis.\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async explainRisk(target: string, context?: string) {\n // Target is a file or feature description\n const workDir = getWorkingDirectory(undefined, true);\n const resolvedPath = isAbsolute(target) ? target : resolve(workDir, target);\n \n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `RISK ASSESSMENT\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n if (existsSync(resolvedPath)) {\n const code = await readFile(resolvedPath, 'utf-8');\n const filePath = relative(workDir, resolvedPath);\n \n // Quick risk indicators\n const riskIndicators = this.detectRiskIndicators(code);\n\n output += `## Target\\n\\n`;\n output += `- **File:** \\`${filePath}\\`\\n`;\n output += `- **Lines:** ${code.split('\\n').length}\\n\\n`;\n\n if (riskIndicators.length > 0) {\n output += `## Risk Indicators Found\\n\\n`;\n for (const indicator of riskIndicators) {\n output += `- ${indicator}\\n`;\n }\n output += '\\n';\n }\n\n const prompt = getPrompt('explain', 'risk', {\n files: filePath,\n summary: context || 'Code change',\n });\n\n output += `${'─'.repeat(60)}\\n`;\n output += `## 🧠 Risk Analysis Request\\n\\n`;\n output += prompt;\n output += `\\n${'─'.repeat(60)}\\n`;\n } else {\n // Treat as a feature/change description\n output += `## 📋 Feature/Change\\n\\n`;\n output += `${target}\\n\\n`;\n\n output += `## 🧠 Risk Analysis Request\\n\\n`;\n output += `Analyze the risks of this change:\\n\\n`;\n output += `1. **Technical risks** - What could break?\\n`;\n output += `2. **Security risks** - Any vulnerabilities introduced?\\n`;\n output += `3. **Performance risks** - Any slowdowns?\\n`;\n output += `4. **Data risks** - Any data integrity concerns?\\n`;\n output += `5. **User impact** - How might users be affected?\\n`;\n output += `6. **Mitigation** - How to reduce these risks?\\n`;\n }\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private detectRiskIndicators(code: string): string[] {\n const indicators: string[] = [];\n\n const checks = [\n { pattern: /delete|drop|truncate/i, message: '[!] Destructive operations detected' },\n { pattern: /password|secret|key|token/i, message: '[SEC] Credential handling detected' },\n { pattern: /exec|eval|spawn/i, message: '[EXEC] Code execution patterns detected' },\n { pattern: /SELECT.*FROM|INSERT|UPDATE|DELETE/i, message: '[DB] Direct database operations' },\n { pattern: /fetch|axios|request|http/i, message: '[API] External API calls detected' },\n { pattern: /process\\.env/i, message: '[ENV] Environment variable usage' },\n { pattern: /fs\\.|writeFile|readFile/i, message: '[FS] File system operations' },\n { pattern: /setTimeout|setInterval/i, message: '[TIMER] Async timing operations' },\n { pattern: /try\\s*{/i, message: '🛡️ Error handling present' },\n { pattern: /catch\\s*\\(/i, message: '🛡️ Exception handling present' },\n ];\n\n for (const { pattern, message } of checks) {\n if (pattern.test(code)) {\n indicators.push(message);\n }\n }\n\n return indicators;\n }\n\n private extractImports(code: string, _language: string): string[] {\n const imports: string[] = [];\n const lines = code.split('\\n');\n\n for (const line of lines) {\n // ES6 imports\n const es6Match = line.match(/import\\s+(?:{[^}]+}|\\*\\s+as\\s+\\w+|\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/);\n if (es6Match) {\n imports.push(es6Match[1]!);\n continue;\n }\n\n // CommonJS require\n const cjsMatch = line.match(/require\\s*\\(['\"]([^'\"]+)['\"]\\)/);\n if (cjsMatch) {\n imports.push(cjsMatch[1]!);\n continue;\n }\n\n // Python imports\n const pyMatch = line.match(/^(?:from\\s+(\\S+)\\s+)?import\\s+(\\S+)/);\n if (pyMatch && _language === 'python') {\n imports.push(pyMatch[1] || pyMatch[2]!);\n }\n }\n\n return [...new Set(imports)];\n }\n\n private extractExports(code: string): string[] {\n const exports: string[] = [];\n const lines = code.split('\\n');\n\n for (const line of lines) {\n // ES6 exports\n const es6Match = line.match(/export\\s+(?:default\\s+)?(?:class|function|const|let|var|interface|type)\\s+(\\w+)/);\n if (es6Match) {\n exports.push(es6Match[1]!);\n }\n\n // Named exports\n const namedMatch = line.match(/export\\s*\\{([^}]+)\\}/);\n if (namedMatch) {\n const names = namedMatch[1]!.split(',').map(n => n.trim().split(/\\s+as\\s+/)[0]!.trim());\n exports.push(...names);\n }\n }\n\n return [...new Set(exports)];\n }\n\n private extractFunctions(code: string, _language: string): string[] {\n const functions: string[] = [];\n const lines = code.split('\\n');\n\n for (const line of lines) {\n // Function declarations\n const funcMatch = line.match(/(?:async\\s+)?function\\s+(\\w+)/);\n if (funcMatch) {\n functions.push(funcMatch[1]!);\n continue;\n }\n\n // Arrow functions assigned to const\n const arrowMatch = line.match(/(?:const|let|var)\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\(/);\n if (arrowMatch) {\n functions.push(arrowMatch[1]!);\n continue;\n }\n\n // Class methods\n const methodMatch = line.match(/^\\s+(?:async\\s+)?(\\w+)\\s*\\([^)]*\\)\\s*(?::\\s*\\w+)?\\s*\\{/);\n if (methodMatch && !['if', 'for', 'while', 'switch', 'catch'].includes(methodMatch[1]!)) {\n functions.push(methodMatch[1]!);\n }\n }\n\n return [...new Set(functions)];\n }\n\n private detectLanguage(filePath: string): string {\n const ext = extname(filePath).toLowerCase();\n const langMap: Record<string, string> = {\n '.ts': 'typescript', '.tsx': 'tsx', '.js': 'javascript', '.jsx': 'jsx',\n '.py': 'python', '.go': 'go', '.rs': 'rust', '.java': 'java',\n '.rb': 'ruby', '.php': 'php', '.vue': 'vue', '.svelte': 'svelte',\n };\n return langMap[ext] || 'plaintext';\n }\n\n private guessLanguage(code: string): string {\n if (/import.*from|export\\s+(default|const|function|class)/.test(code)) return 'typescript';\n if (/def\\s+\\w+.*:/.test(code)) return 'python';\n if (/func\\s+\\w+.*\\{/.test(code)) return 'go';\n if (/fn\\s+\\w+.*->/.test(code)) return 'rust';\n return 'javascript';\n }\n\n private getSeverityIcon(severity: string): string {\n const icons: Record<string, string> = {\n critical: '🔴',\n serious: '🟠',\n moderate: '🟡',\n low: '🔵',\n unknown: '⚪',\n };\n return icons[severity] || '⚪';\n }\n\n private getHelpText(): string {\n return `\n${'━'.repeat(60)}\n📖 TRIE EXPLAIN - AI-POWERED CODE EXPLANATION\n${'━'.repeat(60)}\n\n## Usage\n\n### Explain code:\n\\`\\`\\`\ntrie_explain type:\"code\" target:\"src/app.ts\"\n\\`\\`\\`\n\n### Explain an issue:\n\\`\\`\\`\ntrie_explain type:\"issue\" target:\"SQL injection vulnerability\"\n\\`\\`\\`\nor with file context:\n\\`\\`\\`\ntrie_explain type:\"issue\" target:\"src/db.ts:42:Unvalidated input\"\n\\`\\`\\`\n\n### Explain changes:\n\\`\\`\\`\ntrie_explain type:\"change\" target:\"src/auth.ts, src/user.ts\"\n\\`\\`\\`\n\n### Assess risk:\n\\`\\`\\`\ntrie_explain type:\"risk\" target:\"src/payment.ts\"\n\\`\\`\\`\nor for a feature:\n\\`\\`\\`\ntrie_explain type:\"risk\" target:\"Adding Stripe integration for payments\"\n\\`\\`\\`\n\n## Explanation Types\n\n| Type | Description |\n|------|-------------|\n| code | What does this code do? |\n| issue | Why is this a problem? |\n| change | What's the impact? |\n| risk | What could go wrong? |\n`;\n }\n}\n","import { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { extname, relative, resolve, isAbsolute, dirname, basename, join } from 'path';\nimport { getPrompt, getSystemPrompt } from '../ai/prompts.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\n/**\n * Test Tool - AI-powered test generation and coverage analysis\n * \n * This tool can:\n * - Generate comprehensive tests for code\n * - Analyze test coverage gaps\n * - Suggest test improvements\n */\n\ninterface TestableUnit {\n name: string;\n type: 'function' | 'class' | 'method' | 'component';\n startLine: number;\n endLine: number;\n signature: string;\n complexity: number;\n dependencies: string[];\n}\n\nexport class TrieTestTool {\n async execute(args: any) {\n const { action, files, framework, style = 'unit' } = args || {};\n\n if (!action || !files || files.length === 0) {\n return {\n content: [{\n type: 'text',\n text: this.getHelpText()\n }]\n };\n }\n\n switch (action) {\n case 'generate':\n return this.generateTests(files, framework, style);\n case 'coverage':\n return this.analyzeCoverage(files);\n case 'suggest':\n return this.suggestTests(files);\n case 'run':\n return this.runTestsInfo(files);\n default:\n return {\n content: [{\n type: 'text',\n text: `Unknown action: ${action}`\n }]\n };\n }\n }\n\n private async generateTests(files: string[], framework?: string, style?: string) {\n const detectedFramework = framework || await this.detectTestFramework();\n \n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🧪 TEST GENERATION\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## ⚙️ Configuration\\n\\n`;\n output += `- **Framework:** ${detectedFramework}\\n`;\n output += `- **Style:** ${style}\\n`;\n output += `- **Files:** ${files.length}\\n\\n`;\n\n const workDir = getWorkingDirectory(undefined, true);\n const allUnits: { file: string; units: TestableUnit[] }[] = [];\n\n for (const file of files) {\n const resolvedPath = isAbsolute(file) ? file : resolve(workDir, file);\n \n if (!existsSync(resolvedPath)) {\n output += `[!] File not found: ${file}\\n`;\n continue;\n }\n\n const code = await readFile(resolvedPath, 'utf-8');\n const language = this.detectLanguage(resolvedPath);\n const relativePath = relative(workDir, resolvedPath);\n const units = this.extractTestableUnits(code, language);\n\n allUnits.push({ file: relativePath, units });\n\n output += `### 📄 ${relativePath}\\n\\n`;\n output += `Found **${units.length}** testable units:\\n\\n`;\n\n for (const unit of units) {\n const complexityIcon = unit.complexity > 10 ? '🔴' : unit.complexity > 5 ? '🟡' : '🟢';\n output += `- ${complexityIcon} \\`${unit.name}\\` (${unit.type}, complexity: ${unit.complexity})\\n`;\n if (unit.dependencies.length > 0) {\n output += ` - Dependencies: ${unit.dependencies.join(', ')}\\n`;\n }\n }\n output += '\\n';\n }\n\n // Generate the test file content\n output += `${'─'.repeat(60)}\\n`;\n output += `## 🧠 Test Generation Request\\n\\n`;\n \n const systemPrompt = getSystemPrompt('test');\n output += `**Role:** ${systemPrompt.split('\\n')[0]}\\n\\n`;\n\n for (const { file, units } of allUnits) {\n if (units.length === 0) continue;\n\n const code = await readFile(resolve(workDir, file), 'utf-8');\n const language = this.detectLanguage(file);\n\n const prompt = getPrompt('test', 'generate', {\n code,\n language,\n filePath: file,\n framework: detectedFramework,\n });\n\n output += `### Tests for ${file}\\n\\n`;\n output += prompt;\n output += '\\n\\n';\n }\n\n output += `${'─'.repeat(60)}\\n`;\n output += `\\n## 📝 Expected Test Output\\n\\n`;\n output += `Generate complete test files with:\\n`;\n output += `- All imports and setup\\n`;\n output += `- Tests for each function/method\\n`;\n output += `- Edge cases and error scenarios\\n`;\n output += `- Mock requirements clearly stated\\n`;\n output += `- Ready to copy and run\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async analyzeCoverage(files: string[]) {\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `📊 COVERAGE ANALYSIS\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n const workDir = getWorkingDirectory(undefined, true);\n\n for (const file of files) {\n const resolvedPath = isAbsolute(file) ? file : resolve(workDir, file);\n \n if (!existsSync(resolvedPath)) {\n output += `[!] File not found: ${file}\\n`;\n continue;\n }\n\n const code = await readFile(resolvedPath, 'utf-8');\n const language = this.detectLanguage(resolvedPath);\n const relativePath = relative(workDir, resolvedPath);\n const units = this.extractTestableUnits(code, language);\n\n // Try to find existing tests\n const testFile = await this.findTestFile(resolvedPath);\n let testCode = '';\n let testedUnits: string[] = [];\n\n if (testFile) {\n testCode = await readFile(testFile, 'utf-8');\n testedUnits = this.findTestedUnits(testCode, units.map(u => u.name));\n }\n\n const coverage = units.length > 0 \n ? Math.round((testedUnits.length / units.length) * 100)\n : 0;\n\n const coverageIcon = coverage >= 80 ? '🟢' : coverage >= 50 ? '🟡' : '🔴';\n\n output += `### 📄 ${relativePath}\\n\\n`;\n output += `**Coverage:** ${coverageIcon} ${coverage}% (${testedUnits.length}/${units.length} units)\\n`;\n if (testFile) {\n output += `**Test file:** \\`${relative(workDir, testFile)}\\`\\n`;\n } else {\n output += `**Test file:** ❌ Not found\\n`;\n }\n output += '\\n';\n\n // Show what's tested and what's not\n const untested = units.filter(u => !testedUnits.includes(u.name));\n \n if (untested.length > 0) {\n output += `**Missing Tests:**\\n`;\n for (const unit of untested) {\n const priority = unit.complexity > 5 ? '🔴 HIGH' : '🟡 MEDIUM';\n output += `- ${priority}: \\`${unit.name}\\` (${unit.type})\\n`;\n }\n output += '\\n';\n }\n\n if (testedUnits.length > 0) {\n output += `**Tested:**\\n`;\n for (const name of testedUnits) {\n output += `- ✅ \\`${name}\\`\\n`;\n }\n output += '\\n';\n }\n }\n\n output += `${'─'.repeat(60)}\\n`;\n output += `## 📋 Recommendations\\n\\n`;\n output += `To improve coverage:\\n`;\n output += `1. Focus on high-complexity untested functions first\\n`;\n output += `2. Add edge case tests for existing coverage\\n`;\n output += `3. Consider integration tests for complex interactions\\n`;\n output += `\\nRun \\`trie_test action:generate files:[\"file.ts\"]\\` to generate missing tests.\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async suggestTests(files: string[]) {\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `💡 TEST SUGGESTIONS\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n const workDir = getWorkingDirectory(undefined, true);\n\n for (const file of files) {\n const resolvedPath = isAbsolute(file) ? file : resolve(workDir, file);\n \n if (!existsSync(resolvedPath)) {\n output += `[!] File not found: ${file}\\n`;\n continue;\n }\n\n const code = await readFile(resolvedPath, 'utf-8');\n const relativePath = relative(workDir, resolvedPath);\n \n // Analyze patterns that need testing\n const patterns = this.detectTestablePatterns(code);\n\n output += `### 📄 ${relativePath}\\n\\n`;\n\n if (patterns.length === 0) {\n output += `No specific test suggestions for this file.\\n\\n`;\n continue;\n }\n\n output += `| Priority | Pattern | Suggested Test |\\n`;\n output += `|----------|---------|----------------|\\n`;\n \n for (const pattern of patterns) {\n output += `| ${pattern.priority} | ${pattern.name} | ${pattern.suggestion} |\\n`;\n }\n output += '\\n';\n }\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async runTestsInfo(files: string[]) {\n const framework = await this.detectTestFramework();\n \n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `RUN TESTS\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## Detected Configuration\\n\\n`;\n output += `- **Framework:** ${framework}\\n`;\n output += `- **Files:** ${files.join(', ')}\\n\\n`;\n\n output += `## Commands\\n\\n`;\n\n switch (framework) {\n case 'jest':\n output += `\\`\\`\\`bash\\n`;\n output += `# Run all tests\\n`;\n output += `npx jest\\n\\n`;\n output += `# Run specific files\\n`;\n output += `npx jest ${files.join(' ')}\\n\\n`;\n output += `# Run with coverage\\n`;\n output += `npx jest --coverage\\n`;\n output += `\\`\\`\\`\\n`;\n break;\n case 'vitest':\n output += `\\`\\`\\`bash\\n`;\n output += `# Run all tests\\n`;\n output += `npx vitest run\\n\\n`;\n output += `# Run specific files\\n`;\n output += `npx vitest run ${files.join(' ')}\\n\\n`;\n output += `# Run with coverage\\n`;\n output += `npx vitest run --coverage\\n`;\n output += `\\`\\`\\`\\n`;\n break;\n case 'pytest':\n output += `\\`\\`\\`bash\\n`;\n output += `# Run all tests\\n`;\n output += `pytest\\n\\n`;\n output += `# Run specific files\\n`;\n output += `pytest ${files.join(' ')}\\n\\n`;\n output += `# Run with coverage\\n`;\n output += `pytest --cov\\n`;\n output += `\\`\\`\\`\\n`;\n break;\n default:\n output += `Run your test framework with the specified files.\\n`;\n }\n\n output += `\\n*Note: This tool provides test commands but doesn't execute them directly.*\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private extractTestableUnits(code: string, language: string): TestableUnit[] {\n const units: TestableUnit[] = [];\n const lines = code.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n\n // Function declarations\n const funcMatch = line.match(/(?:export\\s+)?(?:async\\s+)?function\\s+(\\w+)\\s*\\(([^)]*)\\)/);\n if (funcMatch) {\n const endLine = this.findBlockEnd(lines, i);\n const body = lines.slice(i, endLine + 1).join('\\n');\n units.push({\n name: funcMatch[1]!,\n type: 'function',\n startLine: i + 1,\n endLine: endLine + 1,\n signature: `${funcMatch[1]}(${funcMatch[2]})`,\n complexity: this.calculateComplexity(body),\n dependencies: this.extractDependencies(body),\n });\n }\n\n // Arrow functions\n const arrowMatch = line.match(/(?:export\\s+)?(?:const|let)\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\([^)]*\\)\\s*(?:=>|:)/);\n if (arrowMatch) {\n const endLine = this.findBlockEnd(lines, i);\n const body = lines.slice(i, endLine + 1).join('\\n');\n units.push({\n name: arrowMatch[1]!,\n type: 'function',\n startLine: i + 1,\n endLine: endLine + 1,\n signature: arrowMatch[1]!,\n complexity: this.calculateComplexity(body),\n dependencies: this.extractDependencies(body),\n });\n }\n\n // Classes\n const classMatch = line.match(/(?:export\\s+)?class\\s+(\\w+)/);\n if (classMatch) {\n const endLine = this.findBlockEnd(lines, i);\n units.push({\n name: classMatch[1]!,\n type: 'class',\n startLine: i + 1,\n endLine: endLine + 1,\n signature: `class ${classMatch[1]}`,\n complexity: this.calculateComplexity(lines.slice(i, endLine + 1).join('\\n')),\n dependencies: [],\n });\n }\n\n // React components\n const componentMatch = line.match(/(?:export\\s+)?(?:const|function)\\s+([A-Z]\\w+)\\s*[=:]/);\n if (componentMatch && /jsx|tsx/.test(language)) {\n const endLine = this.findBlockEnd(lines, i);\n units.push({\n name: componentMatch[1]!,\n type: 'component',\n startLine: i + 1,\n endLine: endLine + 1,\n signature: componentMatch[1]!,\n complexity: this.calculateComplexity(lines.slice(i, endLine + 1).join('\\n')),\n dependencies: this.extractDependencies(lines.slice(i, endLine + 1).join('\\n')),\n });\n }\n }\n\n return units;\n }\n\n private findBlockEnd(lines: string[], startLine: number): number {\n let braceCount = 0;\n let started = false;\n\n for (let i = startLine; i < lines.length; i++) {\n const line = lines[i] || '';\n \n for (const char of line) {\n if (char === '{') {\n braceCount++;\n started = true;\n } else if (char === '}') {\n braceCount--;\n }\n }\n\n if (started && braceCount === 0) {\n return i;\n }\n }\n\n return lines.length - 1;\n }\n\n private calculateComplexity(code: string): number {\n let complexity = 1;\n const patterns = [\n /if\\s*\\(/g, /else\\s+if/g, /\\?\\s*[^:]/g, // Conditionals\n /for\\s*\\(/g, /while\\s*\\(/g, /do\\s*\\{/g, // Loops\n /catch\\s*\\(/g, // Error handling\n /&&/g, /\\|\\|/g, // Logical operators\n /case\\s+/g, // Switch cases\n ];\n\n for (const pattern of patterns) {\n const matches = code.match(pattern);\n if (matches) {\n complexity += matches.length;\n }\n }\n\n return complexity;\n }\n\n private extractDependencies(code: string): string[] {\n const deps: string[] = [];\n \n // Look for function calls\n const calls = code.match(/\\b([a-z]\\w+)\\s*\\(/gi) || [];\n const builtins = ['if', 'for', 'while', 'switch', 'catch', 'function', 'return', 'throw', 'new', 'await', 'async'];\n \n for (const call of calls) {\n const name = call.replace(/\\s*\\($/, '');\n if (!builtins.includes(name.toLowerCase()) && !deps.includes(name)) {\n deps.push(name);\n }\n }\n\n return deps.slice(0, 10); // Limit to 10\n }\n\n private async findTestFile(sourcePath: string): Promise<string | null> {\n const dir = dirname(sourcePath);\n const base = basename(sourcePath, extname(sourcePath));\n const ext = extname(sourcePath);\n\n // Common test file patterns\n const patterns = [\n `${base}.test${ext}`,\n `${base}.spec${ext}`,\n `${base}_test${ext}`,\n `test_${base}${ext}`,\n ];\n\n // Check same directory\n for (const pattern of patterns) {\n const testPath = join(dir, pattern);\n if (existsSync(testPath)) {\n return testPath;\n }\n }\n\n // Check __tests__ directory\n const testsDir = join(dir, '__tests__');\n if (existsSync(testsDir)) {\n for (const pattern of patterns) {\n const testPath = join(testsDir, pattern);\n if (existsSync(testPath)) {\n return testPath;\n }\n }\n }\n\n return null;\n }\n\n private findTestedUnits(testCode: string, unitNames: string[]): string[] {\n const tested: string[] = [];\n\n for (const name of unitNames) {\n // Look for the name in test descriptions or assertions\n const patterns = [\n new RegExp(`describe\\\\s*\\\\([^)]*${name}`, 'i'),\n new RegExp(`it\\\\s*\\\\([^)]*${name}`, 'i'),\n new RegExp(`test\\\\s*\\\\([^)]*${name}`, 'i'),\n new RegExp(`expect\\\\s*\\\\([^)]*${name}`, 'i'),\n ];\n\n for (const pattern of patterns) {\n if (pattern.test(testCode)) {\n tested.push(name);\n break;\n }\n }\n }\n\n return tested;\n }\n\n private detectTestablePatterns(code: string): Array<{ priority: string; name: string; suggestion: string }> {\n const patterns: Array<{ priority: string; name: string; suggestion: string }> = [];\n\n const checks = [\n { pattern: /async\\s+function|await\\s+/i, priority: '🔴 HIGH', name: 'Async code', suggestion: 'Test async flows and error handling' },\n { pattern: /try\\s*{[^}]*catch/i, priority: '🔴 HIGH', name: 'Error handling', suggestion: 'Test both success and error paths' },\n { pattern: /if\\s*\\([^)]*&&[^)]*\\)/i, priority: '🟡 MED', name: 'Complex conditionals', suggestion: 'Test all condition branches' },\n { pattern: /\\.map\\(|\\.filter\\(|\\.reduce\\(/i, priority: '🟡 MED', name: 'Array operations', suggestion: 'Test with empty, single, multiple items' },\n { pattern: /fetch\\(|axios\\.|request\\(/i, priority: '🔴 HIGH', name: 'HTTP requests', suggestion: 'Mock API calls, test error responses' },\n { pattern: /localStorage|sessionStorage/i, priority: '🟡 MED', name: 'Storage usage', suggestion: 'Mock storage, test read/write' },\n { pattern: /setTimeout|setInterval/i, priority: '🟡 MED', name: 'Timers', suggestion: 'Use fake timers in tests' },\n { pattern: /useState|useEffect|useCallback/i, priority: '🔴 HIGH', name: 'React hooks', suggestion: 'Test hook behavior and updates' },\n { pattern: /form|input|submit/i, priority: '🟡 MED', name: 'Form handling', suggestion: 'Test validation and submission' },\n ];\n\n for (const { pattern, priority, name, suggestion } of checks) {\n if (pattern.test(code)) {\n patterns.push({ priority, name, suggestion });\n }\n }\n\n return patterns;\n }\n\n private async detectTestFramework(): Promise<string> {\n const workDir = getWorkingDirectory(undefined, true);\n const packagePath = resolve(workDir, 'package.json');\n \n if (existsSync(packagePath)) {\n try {\n const pkg = JSON.parse(await readFile(packagePath, 'utf-8'));\n const deps = { ...pkg.dependencies, ...pkg.devDependencies };\n \n if (deps.vitest) return 'vitest';\n if (deps.jest) return 'jest';\n if (deps.mocha) return 'mocha';\n } catch {\n // Ignore parse errors\n }\n }\n\n // Check for pytest\n if (existsSync(resolve(workDir, 'pytest.ini')) ||\n existsSync(resolve(workDir, 'pyproject.toml'))) {\n return 'pytest';\n }\n\n return 'jest'; // Default\n }\n\n private detectLanguage(filePath: string): string {\n const ext = extname(filePath).toLowerCase();\n const langMap: Record<string, string> = {\n '.ts': 'typescript', '.tsx': 'tsx', '.js': 'javascript', '.jsx': 'jsx',\n '.py': 'python', '.go': 'go', '.rs': 'rust',\n };\n return langMap[ext] || 'javascript';\n }\n\n private getHelpText(): string {\n return `\n${'━'.repeat(60)}\n🧪 TRIE TEST - AI-POWERED TEST GENERATION\n${'━'.repeat(60)}\n\n## Usage\n\n### Generate tests:\n\\`\\`\\`\ntrie_test action:\"generate\" files:[\"src/utils.ts\"]\n\\`\\`\\`\n\n### Analyze coverage:\n\\`\\`\\`\ntrie_test action:\"coverage\" files:[\"src/utils.ts\"]\n\\`\\`\\`\n\n### Get test suggestions:\n\\`\\`\\`\ntrie_test action:\"suggest\" files:[\"src/app.ts\"]\n\\`\\`\\`\n\n### Get run commands:\n\\`\\`\\`\ntrie_test action:\"run\" files:[\"src/utils.test.ts\"]\n\\`\\`\\`\n\n## Options\n\n| Option | Values | Description |\n|--------|--------|-------------|\n| action | generate, coverage, suggest, run | What to do |\n| files | Array of paths | Files to analyze |\n| framework | jest, vitest, mocha, pytest | Test framework |\n| style | unit, integration, e2e, all | Test style |\n`;\n }\n}\n","import { watch, existsSync, readFileSync } from 'fs';\nimport { stat, readFile } from 'fs/promises';\nimport { join, extname, basename } from 'path';\nimport { TrieScanTool } from './scan.js';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport { StreamingManager } from '../utils/streaming.js';\nimport { InteractiveDashboard } from '../cli/interactive-dashboard.js';\nimport { isInteractiveMode } from '../utils/progress.js';\nimport { getOutputManager } from '../utils/output-manager.js';\nimport { isTrieInitialized } from '../utils/trie-init.js';\nimport { getAutonomyConfig, trackIssueOccurrence } from '../utils/autonomy-config.js';\nimport { perceiveCurrentChanges } from '../agent/perceive.js';\nimport { reasonAboutChangesHumanReadable } from '../agent/reason.js';\nimport { ExtractionPipeline } from '../extraction/pipeline.js';\n\n// File extensions to watch\nconst WATCH_EXTENSIONS = new Set([\n '.ts', '.tsx', '.js', '.jsx', '.mjs',\n '.vue', '.svelte', '.astro',\n '.py', '.go', '.rs'\n]);\n\n// Directories to skip\nconst SKIP_DIRS = new Set([\n 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt',\n 'coverage', '.turbo', '.cache'\n]);\n\ninterface WatchState {\n isRunning: boolean;\n lastScan: Map<string, number>; // file -> last scan timestamp\n pendingFiles: Set<string>;\n scanDebounceTimer: NodeJS.Timeout | null;\n issueCache: Map<string, any[]>; // file -> issues\n totalIssuesFound: number;\n filesScanned: number;\n nudgedFiles: Set<string>;\n nudges: Array<{\n file: string;\n message: string;\n severity: 'high' | 'critical';\n timestamp: string;\n }>;\n // Autonomy state\n lastAutoCheck: number; // timestamp of last auto-check\n autoCheckInProgress: boolean;\n criticalIssueCount: number; // cumulative critical issues since last check\n}\n\nexport class TrieWatchTool {\n private scanTool = new TrieScanTool();\n private extractionPipeline: ExtractionPipeline | null = null;\n private state: WatchState = {\n isRunning: false,\n lastScan: new Map(),\n pendingFiles: new Set(),\n scanDebounceTimer: null,\n issueCache: new Map(),\n totalIssuesFound: 0,\n // Autonomy state\n lastAutoCheck: 0,\n autoCheckInProgress: false,\n criticalIssueCount: 0,\n filesScanned: 0,\n nudgedFiles: new Set(),\n nudges: []\n };\n private watchers: Map<string, ReturnType<typeof watch>> = new Map();\n private streamingManager: StreamingManager | undefined = undefined;\n private dashboard: InteractiveDashboard | undefined = undefined;\n\n async execute(args: any) {\n const { action, directory, debounceMs = 1000 } = args;\n\n switch (action) {\n case 'start':\n return this.startWatching(getWorkingDirectory(directory), debounceMs);\n case 'stop':\n return this.stopWatching();\n case 'status':\n return await this.getStatus();\n case 'issues':\n return this.getCurrentIssues();\n case 'nudges':\n return this.getNudges();\n default:\n return {\n content: [{\n type: 'text',\n text: `Unknown action: ${action}. Use 'start', 'stop', 'status', or 'issues'.`\n }]\n };\n }\n }\n\n private async startWatching(directory: string, debounceMs: number) {\n if (this.state.isRunning) {\n return {\n content: [{\n type: 'text',\n text: '[!] Watch mode is already running. Use `trie_watch stop` to stop it first.'\n }]\n };\n }\n if (!isTrieInitialized(directory)) {\n return {\n content: [{\n type: 'text',\n text: 'Trie is not initialized for this project. Run `trie init` first.'\n }]\n };\n }\n\n // Initialize extraction pipeline for autonomous learning\n const anthropicApiKey = process.env.ANTHROPIC_API_KEY;\n if (anthropicApiKey) {\n this.extractionPipeline = new ExtractionPipeline({\n workingDirectory: directory,\n anthropicApiKey,\n });\n await this.extractionPipeline.initialize();\n }\n\n this.state.isRunning = true;\n this.state.issueCache.clear();\n this.state.totalIssuesFound = 0;\n this.state.filesScanned = 0;\n this.state.nudgedFiles.clear();\n this.state.nudges = [];\n\n // Skip banner output in interactive mode (dashboard handles display)\n if (!isInteractiveMode()) {\n console.error('\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');\n console.error('TRIE AGENT - NOW WATCHING');\n console.error('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n');\n console.error('Your Trie agent is now watching over your codebase.');\n console.error('Signal extraction: ENABLED (building decision ledger)');\n console.error(`Watching: ${directory}`);\n console.error(`Debounce: ${debounceMs}ms`);\n console.error('');\n }\n\n // Initialize streaming + dashboard for interactive mode\n if (isInteractiveMode()) {\n this.streamingManager = new StreamingManager();\n this.dashboard = new InteractiveDashboard();\n this.streamingManager.subscribe(update => this.dashboard?.handleStreamUpdate(update));\n \n // Set up OutputManager for TUI mode\n const outputManager = getOutputManager();\n outputManager.setMode('tui');\n outputManager.setStreamingManager(this.streamingManager);\n \n await this.dashboard.start();\n this.streamingManager.reportWatchStatus({ watching: true, directories: 0, debounceMs });\n } else {\n // Console mode\n getOutputManager().setMode('console');\n }\n\n // Start watching the directory recursively\n await this.watchDirectory(directory, debounceMs);\n\n // Do an initial scan\n if (!isInteractiveMode()) {\n console.error('Running initial scan...\\n');\n }\n const initialResult = await this.scanTool.execute({\n directory,\n interactive: isInteractiveMode(),\n streamingManager: this.streamingManager,\n dashboard: this.dashboard\n });\n\n // After initial scan, ensure watch status is reported as active\n // Small delay to ensure scan_complete event is processed first\n if (this.streamingManager) {\n setTimeout(() => {\n this.streamingManager?.reportWatchStatus({\n watching: true,\n directories: this.watchers.size,\n debounceMs\n });\n }, 100);\n }\n\n return {\n content: [{\n type: 'text',\n text: `**TRIE AGENT ACTIVATED** \n\nYour Trie agent is now autonomously watching and learning from your codebase.\n\n**Watching:** \\`${directory}\\`\n**Debounce:** ${debounceMs}ms (waits for you to stop typing)\n**Signal Extraction:** ${process.env.ANTHROPIC_API_KEY ? '✓ ENABLED' : '⚠️ LIMITED (set ANTHROPIC_API_KEY for full extraction)'}\n\n### How the agent works:\n1. [*] You write/edit code\n2. [#] Agent detects the change\n3. [🧠] Extracts decisions, facts, blockers → stores in ledger\n4. [?] Predicts risks based on historical patterns\n5. [>] Nudges you in plain English if something looks risky\n\n### The agent learns:\n- Every commit builds the decision ledger\n- \\`trie gotcha\\` queries the ledger for predictions\n- \\`trie ok\\` / \\`trie bad\\` teach the agent what matters (coming soon)\n\n### Commands:\n- \\`trie_watch status\\` - See agent status\n- \\`trie_watch issues\\` - Get all issues found so far \n- \\`trie_watch stop\\` - Stop the agent\n\n---\n\n${initialResult.content?.[0]?.text || 'Initial scan complete.'}`\n }]\n };\n }\n\n private async watchDirectory(dir: string, debounceMs: number) {\n if (!existsSync(dir)) return;\n\n try {\n const dirStat = await stat(dir);\n if (!dirStat.isDirectory()) return;\n\n // Skip ignored directories\n const dirName = basename(dir);\n if (SKIP_DIRS.has(dirName) || dirName.startsWith('.')) return;\n\n // Watch this directory\n const watcher = watch(dir, { persistent: true }, async (_eventType, filename) => {\n if (!filename) return;\n \n const fullPath = join(dir, filename);\n const ext = extname(filename).toLowerCase();\n\n // Only watch relevant file types\n if (!WATCH_EXTENSIONS.has(ext)) return;\n\n // Skip if file doesn't exist (was deleted)\n if (!existsSync(fullPath)) return;\n\n // Add to pending files\n this.state.pendingFiles.add(fullPath);\n\n // Debounce the scan\n if (this.state.scanDebounceTimer) {\n clearTimeout(this.state.scanDebounceTimer);\n }\n\n this.state.scanDebounceTimer = setTimeout(() => {\n this.processPendingFiles();\n }, debounceMs);\n });\n\n this.watchers.set(dir, watcher);\n\n // Recursively watch subdirectories\n const { readdir } = await import('fs/promises');\n const entries = await readdir(dir, { withFileTypes: true });\n \n for (const entry of entries) {\n if (entry.isDirectory()) {\n await this.watchDirectory(join(dir, entry.name), debounceMs);\n }\n }\n if (this.streamingManager) {\n this.streamingManager.reportWatchStatus({\n watching: true,\n directories: this.watchers.size,\n debounceMs\n });\n }\n } catch (error) {\n // Skip directories we can't access\n }\n }\n\n private async processPendingFiles() {\n if (this.state.pendingFiles.size === 0) return;\n\n const files = Array.from(this.state.pendingFiles);\n this.state.pendingFiles.clear();\n\n if (!isInteractiveMode()) {\n console.error(`\\nDetected changes in ${files.length} file(s):`);\n for (const file of files) {\n console.error(` - ${basename(file)}`);\n }\n console.error('');\n }\n\n try {\n // === NEW: Autonomous signal extraction from file changes ===\n if (this.extractionPipeline) {\n try {\n // Read changed files and extract signals\n const fileContents = await Promise.all(\n files.map(async (file) => {\n try {\n const content = await readFile(file, 'utf-8');\n return { file, content };\n } catch {\n return null;\n }\n })\n );\n\n // Extract signals from file changes\n const validFiles = fileContents.filter(f => f !== null);\n if (validFiles.length > 0) {\n const combinedContent = validFiles.map(f => \n `File: ${basename(f!.file)}\\n${f!.content.slice(0, 1000)}` // First 1KB of each file\n ).join('\\n\\n---\\n\\n');\n\n if (!isInteractiveMode()) {\n console.error('🧠 Extracting signals from changes...');\n }\n\n const signal = await this.extractionPipeline.process(combinedContent, {\n sourceType: 'file',\n sourceId: `watch-${Date.now()}`,\n });\n\n if (signal.decisions.length > 0 || signal.facts.length > 0 || signal.blockers.length > 0) {\n if (!isInteractiveMode()) {\n console.error(` ✓ Extracted: ${signal.decisions.length} decisions, ${signal.facts.length} facts, ${signal.blockers.length} blockers`);\n }\n \n // Emit signal extraction event for TUI\n if (this.streamingManager) {\n this.streamingManager.reportSignalExtraction({\n decisions: signal.decisions.length,\n facts: signal.facts.length,\n blockers: signal.blockers.length,\n questions: signal.questions.length,\n });\n }\n }\n }\n } catch (error) {\n // Signal extraction is optional, don't fail watch mode\n if (!isInteractiveMode()) {\n console.error(` ⚠️ Signal extraction failed: ${error}`);\n }\n }\n }\n\n // Scan the changed files for issues\n if (this.streamingManager) {\n for (const file of files) {\n this.streamingManager.reportWatchChange(file);\n }\n }\n const result = await this.scanTool.execute({\n files,\n interactive: isInteractiveMode(),\n streamingManager: this.streamingManager,\n dashboard: this.dashboard\n });\n \n // Parse issues from result\n const resultText = result.content?.[0]?.text || '';\n \n // Update stats\n this.state.filesScanned += files.length;\n\n // Extract issue count from result (simple regex)\n const issueMatch = resultText.match(/(\\d+) total/);\n if (issueMatch?.[1] !== undefined) {\n const newIssues = parseInt(issueMatch[1], 10);\n this.state.totalIssuesFound += newIssues;\n\n if (!isInteractiveMode()) {\n if (newIssues > 0) {\n console.error(`\\nFound ${newIssues} issues in changed files!`);\n \n // Log a summary\n const criticalMatch = resultText.match(/(\\d+) CRITICAL/);\n const seriousMatch = resultText.match(/(\\d+) SERIOUS/);\n const moderateMatch = resultText.match(/(\\d+) MODERATE/);\n \n if (criticalMatch) {\n console.error(` [!] ${criticalMatch[1]} critical issues`);\n }\n if (seriousMatch) {\n console.error(` [x] ${seriousMatch[1]} serious issues`);\n }\n if (moderateMatch) {\n console.error(` [~] ${moderateMatch[1]} moderate issues`);\n }\n } else {\n console.error(' [OK] No issues found - code looks good!');\n }\n }\n }\n\n // Cache issues for each file\n for (const file of files) {\n this.state.lastScan.set(file, Date.now());\n }\n\n this.maybeNudge(files, resultText);\n\n } catch (error) {\n if (!isInteractiveMode()) {\n console.error(`Scan error: ${error}`);\n }\n }\n }\n\n private isQuiet(): boolean {\n const projectPath = getWorkingDirectory(undefined, true);\n const quietPath = join(getTrieDirectory(projectPath), 'quiet.json');\n try {\n const raw = readFileSync(quietPath, 'utf-8');\n const data = JSON.parse(raw);\n const until = new Date(data.until).getTime();\n return Date.now() < until;\n } catch {\n return false;\n }\n }\n\n private maybeNudge(files: string[], resultText: string) {\n if (this.isQuiet()) return;\n\n // Check for critical vs high risk\n const isCritical = /CRITICAL|\\[STOP\\]/i.test(resultText);\n const isRisky = /HIGH RISK|SERIOUS|\\[!\\]/i.test(resultText);\n \n if (!isCritical && !isRisky) return;\n\n // Track critical issues for auto-check\n if (isCritical) {\n this.state.criticalIssueCount++;\n // Trigger auto-check if enabled\n this.maybeAutoCheck(files);\n }\n\n for (const file of files) {\n if (this.state.nudgedFiles.has(file)) continue;\n this.state.nudgedFiles.add(file);\n\n const severity = isCritical ? 'critical' : 'warning';\n const message = isCritical\n ? `[!!!] STOP! ${basename(file)} has critical issues. Do NOT push until fixed.`\n : `[!] Heads up: ${basename(file)} looks risky. Pause and run targeted tests before pushing.`;\n\n const payload = {\n file,\n message,\n severity: severity === 'critical' ? 'high' as const : 'high' as const,\n timestamp: new Date().toISOString()\n };\n\n this.state.nudges.push(payload);\n \n // Send proactive notification through OutputManager\n // This will show a prominent popup in TUI mode\n getOutputManager().nudge(\n message,\n severity as 'critical' | 'warning',\n file,\n severity === 'critical' ? undefined : 15000 // Auto-hide warnings after 15s, keep critical until dismissed\n );\n }\n }\n\n /**\n * Auto-run full check when critical issues detected\n * Respects cooldown and autonomy config\n */\n private async maybeAutoCheck(triggerFiles: string[]) {\n // Don't run if already in progress\n if (this.state.autoCheckInProgress) return;\n\n const projectPath = getWorkingDirectory(undefined, true);\n \n try {\n const config = await getAutonomyConfig(projectPath);\n \n // Check if auto-check is enabled\n if (!config.autoCheck.enabled) return;\n \n // Check cooldown\n const now = Date.now();\n if (now - this.state.lastAutoCheck < config.autoCheck.cooldownMs) {\n return;\n }\n \n // Check threshold (run on critical or when threshold exceeded)\n const shouldRun = config.autoCheck.onCritical || \n this.state.criticalIssueCount >= config.autoCheck.threshold;\n \n if (!shouldRun) return;\n \n this.state.autoCheckInProgress = true;\n this.state.lastAutoCheck = now;\n \n // Notify user that auto-check is running\n getOutputManager().nudge(\n '[*] Auto-running full check due to critical issues...',\n 'info',\n undefined,\n 5000\n );\n \n // Get all changed files (not just the trigger files)\n const perception = await perceiveCurrentChanges(projectPath);\n const allFiles = perception.diffSummary.files.map(f => f.filePath);\n const filesToCheck = allFiles.length > 0 ? allFiles : triggerFiles;\n \n // Run full reasoning check\n const reasoning = await reasonAboutChangesHumanReadable(projectPath, filesToCheck, {\n runAgents: true,\n scanContext: {\n config: { timeoutMs: 30000 }\n }\n });\n \n // Track occurrences for progressive escalation\n if (reasoning.original?.files) {\n for (const file of reasoning.original.files) {\n if (file.level === 'critical' || file.level === 'high') {\n await trackIssueOccurrence(\n projectPath,\n file.file,\n undefined,\n file.level,\n config\n );\n }\n }\n }\n \n // Show results\n const riskLevel = reasoning.original?.riskLevel || 'low';\n const shouldBlock = reasoning.original?.shouldBlock || false;\n \n if (shouldBlock) {\n getOutputManager().nudge(\n `[STOP] Auto-check complete: ${riskLevel.toUpperCase()} risk detected. Fix issues before pushing.`,\n 'critical',\n undefined,\n undefined // Keep visible\n );\n } else {\n getOutputManager().nudge(\n `[OK] Auto-check complete: ${riskLevel} risk. ${reasoning.summary || ''}`,\n riskLevel === 'low' ? 'info' : 'warning',\n undefined,\n 10000\n );\n }\n \n // Reset critical count after check\n this.state.criticalIssueCount = 0;\n \n } catch (error) {\n console.error('Auto-check failed:', error);\n } finally {\n this.state.autoCheckInProgress = false;\n }\n }\n\n private stopWatching() {\n if (!this.state.isRunning) {\n return {\n content: [{\n type: 'text',\n text: '[!] Watch mode is not running.'\n }]\n };\n }\n\n // Close all watchers\n for (const [_dir, watcher] of this.watchers) {\n watcher.close();\n }\n this.watchers.clear();\n\n // Close extraction pipeline\n if (this.extractionPipeline) {\n this.extractionPipeline.close();\n this.extractionPipeline = null;\n }\n\n // Clear state\n if (this.state.scanDebounceTimer) {\n clearTimeout(this.state.scanDebounceTimer);\n }\n \n this.state.isRunning = false;\n\n if (!isInteractiveMode()) {\n console.error('\\n[*] Watch mode stopped.\\n');\n }\n if (this.streamingManager) {\n this.streamingManager.reportWatchStatus({ watching: false, directories: 0 });\n }\n \n // Clean up OutputManager\n const outputManager = getOutputManager();\n outputManager.clearTUICallbacks();\n outputManager.setMode('console');\n \n // Stop the dashboard if running\n if (this.dashboard) {\n this.dashboard.stop();\n this.dashboard = undefined;\n }\n\n return {\n content: [{\n type: 'text',\n text: `[*] **TRIE AGENT STOPPED** 🤖\n\n### Session Summary:\n- Files scanned: ${this.state.filesScanned}\n- Total issues found: ${this.state.totalIssuesFound}\n- Directories watched: ${this.watchers.size}\n- Decision ledger: Updated continuously\n\nThe agent's learning has been stored in the decision ledger.\nUse \\`trie_watch start\\` to resume autonomous operation.`\n }]\n };\n }\n\n private async getStatus() {\n if (!this.state.isRunning) {\n return {\n content: [{\n type: 'text',\n text: `[*] **Watch Mode Status: STOPPED**\n\nUse \\`trie_watch start\\` to begin autonomous scanning.`\n }]\n };\n }\n\n const recentScans = Array.from(this.state.lastScan.entries())\n .sort((a, b) => b[1] - a[1])\n .slice(0, 5)\n .map(([file, time]) => {\n const ago = Math.round((Date.now() - time) / 1000);\n return `- \\`${basename(file)}\\` (${ago}s ago)`;\n })\n .join('\\n');\n\n const recentNudges = this.state.nudges.slice(-3).map(\n (n) => `- ${basename(n.file)} [${n.severity}] @ ${n.timestamp}`\n ).join('\\n');\n\n // Get Guardian Agency status\n let agencyStatus = '';\n try {\n const { getGuardian } = await import('../guardian/guardian-agent.js');\n const guardian = getGuardian(getWorkingDirectory(undefined, true));\n await guardian.initialize();\n const status = await guardian.getAgencyStatus();\n\n agencyStatus = `\n### [AI] Guardian Agency:\n- **Goals:** ${status.goals.active} active, ${status.goals.completed} completed${status.goals.topGoal ? ` (${status.goals.topGoal.slice(0, 40)}...)` : ''}\n- **Hypotheses:** ${status.hypotheses.testing} testing, ${status.hypotheses.validated} validated\n- **Risk Level:** ${status.riskLevel.toUpperCase()}\n- **Effectiveness:** ${status.effectiveness}%\n- **Scan Frequency:** ${Math.round(status.scanFrequency / 1000)}s${status.isQuietHours ? ' (quiet hours)' : ''}`;\n } catch {\n // Agency status is optional\n }\n\n return {\n content: [{\n type: 'text',\n text: `[*] **WATCH MODE Status: RUNNING**\n\n### Stats:\n- Directories watched: ${this.watchers.size}\n- Files scanned this session: ${this.state.filesScanned}\n- Total issues found: ${this.state.totalIssuesFound}\n- Pending files: ${this.state.pendingFiles.size}\n${agencyStatus}\n\n### Recently Scanned:\n${recentScans || '(none yet)'}\n\n### Recent Nudges:\n${recentNudges || '(none)'}\n\n### Commands:\n- \\`trie_watch issues\\` - Get all issues found\n- \\`trie_watch nudges\\` - Get recent nudges (structured)\n- \\`trie_watch stop\\` - Stop watching`\n }]\n };\n }\n\n private getNudges() {\n return {\n content: [\n {\n type: 'text',\n text: `[#] Recent nudges (${this.state.nudges.length} this session)\\n` +\n (this.state.nudges.length\n ? this.state.nudges.map((n) =>\n `- ${basename(n.file)} [${n.severity}] @ ${n.timestamp}\\n ${n.message}`\n ).join('\\n')\n : '(none)')\n },\n {\n type: 'json',\n json: this.state.nudges\n }\n ]\n };\n }\n\n private getCurrentIssues() {\n return {\n content: [{\n type: 'text',\n text: `[L] **Issues Found This Session**\n\nTotal issues: ${this.state.totalIssuesFound}\nFiles scanned: ${this.state.filesScanned}\n\nTo get a full report, run \\`trie_scan\\` on your codebase.`\n }]\n };\n }\n}\n","/**\n * Signal Extraction Layer\n * \n * Uses a cheap, fast model (Haiku or local Ollama) to extract structured\n * signals from raw content. This is the first layer of context management\n * that prevents agents from drowning in noise.\n */\n\nimport Anthropic from '@anthropic-ai/sdk';\nimport type { \n ExtractedSignal, \n Decision, \n Fact, \n Blocker, \n Question \n} from '../types/signal.js';\n\nconst EXTRACTION_PROMPT = `You are a signal extraction system. Your job is to extract structured information from raw content.\n\nExtract:\n1. DECISIONS - Clear choices made during development\n - What was decided\n - Why it was decided (reasoning/tradeoffs)\n - What alternatives were considered but NOT chosen\n - Which files are affected\n \n2. FACTS - Concrete, verifiable information\n - Technical constraints (e.g., \"Stripe requires TLS 1.2+\")\n - API requirements\n - Business rules\n - Dependencies\n \n3. BLOCKERS - Things preventing progress\n - What's blocked\n - Impact level (critical/high/medium/low)\n - What areas are affected\n \n4. QUESTIONS - Open items needing resolution\n - What's unclear\n - Context around the question\n\nCRITICAL: Extract rich metadata:\n- Tags: Use specific, searchable tags (e.g., \"auth\", \"payments\", \"eu-compliance\", \"validation\")\n- Files: Full paths when mentioned (e.g., \"src/auth/validator.ts\")\n- Tradeoffs: What was considered but rejected\n- Related terms: Alternative names/keywords (e.g., \"password\" + \"credentials\" + \"auth\")\n\nFormat as JSON:\n{\n \"decisions\": [{\n \"decision\": \"Use bcrypt for password hashing\",\n \"context\": \"Security requirement for user authentication\",\n \"reasoning\": \"Industry standard, resistant to GPU attacks\",\n \"files\": [\"src/auth/hash.ts\", \"src/models/user.ts\"],\n \"tags\": [\"security\", \"auth\", \"passwords\", \"encryption\"],\n \"tradeoffs\": [\"Considered argon2 but bcrypt has better library support\"]\n }],\n \"facts\": [{\n \"fact\": \"Stripe requires TLS 1.2+ for all API calls\",\n \"source\": \"Stripe API docs\",\n \"tags\": [\"payments\", \"stripe\", \"security\", \"api\"],\n \"confidence\": 0.95\n }],\n \"blockers\": [{\n \"blocker\": \"Missing VAT calculation endpoint\",\n \"impact\": \"high\",\n \"affectedAreas\": [\"checkout\", \"eu-payments\"],\n \"tags\": [\"payments\", \"eu\", \"compliance\", \"vat\"]\n }],\n \"questions\": [{\n \"question\": \"Should we cache user sessions in Redis or memory?\",\n \"context\": \"Performance optimization for auth layer\",\n \"tags\": [\"auth\", \"performance\", \"caching\", \"sessions\"]\n }]\n}\n\nBe specific with tags. Use concrete technical terms. Extract ALL file paths mentioned.\nEmpty arrays are fine if nothing to extract.`;\n\nexport class SignalExtractor {\n private client: Anthropic | null = null;\n private model: string;\n\n constructor(model: string = 'claude-3-haiku-20240307') {\n this.model = model;\n \n // Initialize Anthropic client if API key available\n const apiKey = process.env.ANTHROPIC_API_KEY;\n if (apiKey) {\n this.client = new Anthropic({ apiKey });\n }\n }\n\n /**\n * Extract structured signals from raw content\n */\n async extract(\n content: string,\n sourceType: 'incident' | 'pr' | 'commit' | 'conversation' | 'file',\n sourceId?: string\n ): Promise<ExtractedSignal> {\n if (!this.client) {\n // Fallback: basic extraction without AI\n return this.basicExtraction(content, sourceType, sourceId);\n }\n\n try {\n const response = await this.client.messages.create({\n model: this.model,\n max_tokens: 2048,\n temperature: 0.3,\n messages: [{\n role: 'user',\n content: `${EXTRACTION_PROMPT}\\n\\nContent to analyze:\\n${content}`\n }]\n });\n\n const firstBlock = response.content[0];\n const text = firstBlock && firstBlock.type === 'text' \n ? firstBlock.text \n : '';\n \n // Parse JSON response\n const extracted = this.parseExtraction(text);\n \n // Add IDs and timestamps\n const now = new Date().toISOString();\n const metadata: ExtractedSignal['metadata'] = {\n extractedAt: now,\n sourceType,\n extractionModel: this.model\n };\n if (sourceId !== undefined) {\n metadata.sourceId = sourceId;\n }\n const signal: ExtractedSignal = {\n decisions: extracted.decisions.map((d, i) => ({\n id: `dec-${Date.now()}-${i}`,\n decision: d.decision || '',\n context: d.context || '',\n files: d.files || [],\n tags: d.tags || [],\n ...d,\n when: now,\n status: 'active' as const\n })),\n facts: extracted.facts.map((f, i) => ({\n id: `fact-${Date.now()}-${i}`,\n fact: f.fact || '',\n source: f.source || sourceType,\n tags: f.tags || [],\n confidence: f.confidence ?? 0.8,\n ...f,\n when: now\n })),\n blockers: extracted.blockers.map((b, i) => ({\n id: `block-${Date.now()}-${i}`,\n blocker: b.blocker || '',\n impact: b.impact || 'medium',\n affectedAreas: b.affectedAreas || [],\n tags: b.tags || [],\n ...b,\n when: now\n })),\n questions: extracted.questions.map((q, i) => ({\n id: `q-${Date.now()}-${i}`,\n question: q.question || '',\n context: q.context || '',\n tags: q.tags || [],\n ...q,\n when: now\n })),\n metadata\n };\n\n return signal;\n } catch (error) {\n console.error('Extraction failed, using basic extraction:', error);\n return this.basicExtraction(content, sourceType, sourceId);\n }\n }\n\n /**\n * Parse extraction from model response\n */\n private parseExtraction(text: string): {\n decisions: Partial<Decision>[];\n facts: Partial<Fact>[];\n blockers: Partial<Blocker>[];\n questions: Partial<Question>[];\n } {\n try {\n // Try to find JSON in response\n const jsonMatch = text.match(/\\{[\\s\\S]*\\}/);\n if (jsonMatch) {\n return JSON.parse(jsonMatch[0]);\n }\n } catch (e) {\n // JSON parse failed\n }\n\n // Return empty structure\n return {\n decisions: [],\n facts: [],\n blockers: [],\n questions: []\n };\n }\n\n /**\n * Basic extraction without AI (fallback)\n */\n private basicExtraction(\n content: string,\n sourceType: 'incident' | 'pr' | 'commit' | 'conversation' | 'file',\n sourceId?: string\n ): ExtractedSignal {\n const now = new Date().toISOString();\n \n // Simple keyword-based extraction\n const hasDecision = /\\b(decided|decision|chose|picked)\\b/i.test(content);\n const hasBlocker = /\\b(blocked|blocker|blocked by|can't|cannot|unable)\\b/i.test(content);\n const hasQuestion = /\\?|what|how|why|should we/i.test(content);\n\n const decisions: Decision[] = [];\n const facts: Fact[] = [];\n const blockers: Blocker[] = [];\n const questions: Question[] = [];\n\n if (hasDecision) {\n decisions.push({\n id: `dec-${Date.now()}`,\n decision: content.substring(0, 200),\n context: sourceType,\n when: now,\n files: [],\n tags: [sourceType],\n status: 'active'\n });\n }\n\n if (hasBlocker) {\n blockers.push({\n id: `block-${Date.now()}`,\n blocker: content.substring(0, 200),\n impact: 'medium',\n affectedAreas: [],\n when: now,\n tags: [sourceType]\n });\n }\n\n if (hasQuestion) {\n questions.push({\n id: `q-${Date.now()}`,\n question: content.substring(0, 200),\n context: sourceType,\n when: now,\n tags: [sourceType]\n });\n }\n\n const metadata: ExtractedSignal['metadata'] = {\n extractedAt: now,\n sourceType,\n extractionModel: 'basic'\n };\n if (sourceId !== undefined) {\n metadata.sourceId = sourceId;\n }\n return {\n decisions,\n facts,\n blockers,\n questions,\n metadata\n };\n }\n\n /**\n * Extract from incident report (trie tell)\n */\n async extractFromIncident(incidentText: string): Promise<ExtractedSignal> {\n return this.extract(incidentText, 'incident');\n }\n\n /**\n * Extract from commit message and diff\n */\n async extractFromCommit(\n message: string,\n diff?: string,\n commitId?: string\n ): Promise<ExtractedSignal> {\n const content = diff ? `${message}\\n\\nChanges:\\n${diff}` : message;\n return this.extract(content, 'commit', commitId);\n }\n\n /**\n * Extract from PR description and comments\n */\n async extractFromPR(\n title: string,\n description: string,\n comments: string[],\n prNumber?: string\n ): Promise<ExtractedSignal> {\n const content = `\nTitle: ${title}\n\nDescription:\n${description}\n\nComments:\n${comments.join('\\n\\n')}\n `.trim();\n \n return this.extract(content, 'pr', prNumber);\n }\n}\n\n/**\n * Get singleton extractor instance\n */\nlet extractorInstance: SignalExtractor | null = null;\n\nexport function getExtractor(): SignalExtractor {\n if (!extractorInstance) {\n extractorInstance = new SignalExtractor();\n }\n return extractorInstance;\n}\n","/**\n * Metadata enricher - adds rich context to extracted signals\n * This is our \"semantic layer\" without embeddings\n */\n\nimport type { ExtractedSignal } from '../types/signal.js';\n\nexport interface EnrichedMetadata {\n // File relationships\n relatedFiles: string[];\n dependencies: string[];\n \n // Enhanced tags (with synonyms and related terms)\n expandedTags: string[];\n \n // Contextual data\n codebaseArea: string[]; // e.g., [\"frontend\", \"auth\"]\n domain: string[]; // e.g., [\"payments\", \"compliance\"]\n \n // Relationships\n relatedDecisions: string[]; // IDs of related decisions\n \n // Timestamps and versioning\n extractedAt: string;\n gitContext?: {\n branch?: string;\n commit?: string;\n };\n}\n\nexport class MetadataEnricher {\n private tagSynonyms: Map<string, string[]>;\n\n constructor() {\n this.tagSynonyms = this.initializeTagSynonyms();\n }\n\n /**\n * Enrich an extracted signal with additional metadata\n */\n async enrichSignal(\n signal: ExtractedSignal,\n context?: {\n workingDirectory?: string;\n gitBranch?: string;\n gitCommit?: string;\n }\n ): Promise<{ signal: ExtractedSignal; metadata: EnrichedMetadata }> {\n const gitContext: { branch?: string; commit?: string } = {};\n if (context?.gitBranch) gitContext.branch = context.gitBranch;\n if (context?.gitCommit) gitContext.commit = context.gitCommit;\n \n const metadata: EnrichedMetadata = {\n relatedFiles: await this.findRelatedFiles(signal),\n dependencies: await this.extractDependencies(signal),\n expandedTags: this.expandTags(signal),\n codebaseArea: this.inferCodebaseArea(signal),\n domain: this.inferDomain(signal),\n relatedDecisions: [], // Will be populated by storage layer\n extractedAt: new Date().toISOString(),\n };\n \n if (Object.keys(gitContext).length > 0) {\n metadata.gitContext = gitContext;\n }\n\n return {\n signal,\n metadata,\n };\n }\n\n /**\n * Expand tags with synonyms and related terms\n * This is our \"semantic\" layer without embeddings\n */\n private expandTags(signal: ExtractedSignal): string[] {\n const allTags = new Set<string>();\n\n // Collect all tags from signal\n for (const decision of signal.decisions) {\n decision.tags.forEach(tag => allTags.add(tag.toLowerCase()));\n }\n for (const fact of signal.facts) {\n fact.tags.forEach(tag => allTags.add(tag.toLowerCase()));\n }\n for (const blocker of signal.blockers) {\n blocker.tags.forEach(tag => allTags.add(tag.toLowerCase()));\n }\n for (const question of signal.questions) {\n question.tags.forEach(tag => allTags.add(tag.toLowerCase()));\n }\n\n // Add synonyms for each tag\n const expandedTags = new Set(allTags);\n for (const tag of allTags) {\n const synonyms = this.tagSynonyms.get(tag) || [];\n synonyms.forEach(syn => expandedTags.add(syn));\n }\n\n return Array.from(expandedTags);\n }\n\n /**\n * Find related files based on signal content\n */\n private async findRelatedFiles(signal: ExtractedSignal): Promise<string[]> {\n const relatedFiles = new Set<string>();\n\n // Collect explicitly mentioned files\n for (const decision of signal.decisions) {\n decision.files.forEach(file => relatedFiles.add(file));\n }\n\n // Infer related files based on tags\n // e.g., if tags include \"auth\", look for auth-related files\n const inferredFiles = await this.inferFilesFromTags(signal);\n inferredFiles.forEach(file => relatedFiles.add(file));\n\n return Array.from(relatedFiles);\n }\n\n /**\n * Extract dependencies from signal\n */\n private async extractDependencies(signal: ExtractedSignal): Promise<string[]> {\n const dependencies = new Set<string>();\n\n // Look for common dependency patterns in decisions/facts\n const allText = [\n ...signal.decisions.map(d => `${d.decision} ${d.context} ${d.reasoning}`),\n ...signal.facts.map(f => `${f.fact} ${f.source}`),\n ].join(' ');\n\n // Extract npm packages (e.g., \"using bcrypt\", \"with stripe\")\n const packagePatterns = [\n /\\b(react|vue|angular|next|express|fastify|stripe|bcrypt|jwt|redis|prisma)\\b/gi,\n ];\n\n for (const pattern of packagePatterns) {\n const matches = allText.match(pattern) || [];\n matches.forEach(dep => dependencies.add(dep.toLowerCase()));\n }\n\n return Array.from(dependencies);\n }\n\n /**\n * Infer codebase area from file paths and tags\n */\n private inferCodebaseArea(signal: ExtractedSignal): string[] {\n const areas = new Set<string>();\n\n // From file paths\n for (const decision of signal.decisions) {\n for (const file of decision.files) {\n const area = this.filePathToArea(file);\n if (area) areas.add(area);\n }\n }\n\n // From tags\n const areaKeywords = ['frontend', 'backend', 'api', 'ui', 'database', 'auth', 'payments'];\n const allTags = this.expandTags(signal);\n \n for (const tag of allTags) {\n if (areaKeywords.includes(tag)) {\n areas.add(tag);\n }\n }\n\n return Array.from(areas);\n }\n\n /**\n * Infer domain from tags and content\n */\n private inferDomain(signal: ExtractedSignal): string[] {\n const domains = new Set<string>();\n\n const domainKeywords = [\n 'payments', 'billing', 'compliance', 'security', 'auth', \n 'analytics', 'notifications', 'messaging', 'search'\n ];\n\n const allTags = this.expandTags(signal);\n \n for (const tag of allTags) {\n if (domainKeywords.includes(tag)) {\n domains.add(tag);\n }\n }\n\n return Array.from(domains);\n }\n\n /**\n * Convert file path to codebase area\n */\n private filePathToArea(filePath: string): string | null {\n const normalized = filePath.toLowerCase();\n \n if (normalized.includes('/frontend/') || normalized.includes('/client/') || normalized.includes('/ui/')) {\n return 'frontend';\n }\n if (normalized.includes('/backend/') || normalized.includes('/server/') || normalized.includes('/api/')) {\n return 'backend';\n }\n if (normalized.includes('/database/') || normalized.includes('/models/') || normalized.includes('/schema/')) {\n return 'database';\n }\n if (normalized.includes('/auth/')) {\n return 'auth';\n }\n \n return null;\n }\n\n /**\n * Infer related files from tags\n */\n private async inferFilesFromTags(_signal: ExtractedSignal): Promise<string[]> {\n // In a real implementation, this would search the codebase\n // For now, return empty array\n return [];\n }\n\n /**\n * Initialize tag synonyms and related terms\n * This is our \"semantic\" understanding without embeddings\n */\n private initializeTagSynonyms(): Map<string, string[]> {\n return new Map([\n // Auth & Security\n ['auth', ['authentication', 'login', 'signin', 'credentials', 'password']],\n ['password', ['credentials', 'auth', 'hashing', 'bcrypt']],\n ['security', ['vulnerability', 'exploit', 'attack', 'protection']],\n ['encryption', ['crypto', 'hashing', 'encoding', 'security']],\n \n // Payments\n ['payments', ['billing', 'checkout', 'stripe', 'pricing']],\n ['stripe', ['payments', 'billing', 'api', 'checkout']],\n ['vat', ['tax', 'eu', 'compliance', 'billing']],\n \n // Database & Performance\n ['database', ['db', 'sql', 'query', 'storage', 'persistence']],\n ['cache', ['caching', 'redis', 'memory', 'performance']],\n ['performance', ['optimization', 'speed', 'latency', 'cache']],\n \n // Frontend\n ['ui', ['frontend', 'interface', 'component', 'view']],\n ['component', ['ui', 'react', 'vue', 'frontend']],\n ['validation', ['form', 'input', 'error', 'ui']],\n \n // Backend & API\n ['api', ['endpoint', 'route', 'backend', 'server']],\n ['endpoint', ['api', 'route', 'url', 'backend']],\n ['backend', ['server', 'api', 'service']],\n \n // Compliance & Legal\n ['compliance', ['gdpr', 'hipaa', 'legal', 'regulation']],\n ['gdpr', ['compliance', 'privacy', 'eu', 'data-protection']],\n ['privacy', ['gdpr', 'compliance', 'data-protection', 'security']],\n ]);\n }\n}\n","/**\n * Extraction Pipeline\n * \n * Complete flow: Raw Input → Extract → Enrich → Store\n * This is the heart of the decision ledger system.\n */\n\nimport { SignalExtractor } from './signal-extractor.js';\nimport { MetadataEnricher } from './metadata-enricher.js';\nimport { TieredStorage, getStorage } from '../storage/tiered-storage.js';\nimport type { ExtractedSignal } from '../types/signal.js';\nimport { randomBytes } from 'crypto';\n\nexport interface PipelineOptions {\n workingDirectory: string;\n anthropicApiKey?: string;\n gitContext?: {\n branch?: string;\n commit?: string;\n };\n}\n\nexport class ExtractionPipeline {\n private extractor: SignalExtractor;\n private enricher: MetadataEnricher;\n private storage: TieredStorage;\n private workDir: string;\n\n constructor(options: PipelineOptions) {\n this.extractor = new SignalExtractor(options.anthropicApiKey);\n this.enricher = new MetadataEnricher();\n this.storage = getStorage(options.workingDirectory);\n this.workDir = options.workingDirectory;\n }\n\n /**\n * Process raw content through the entire pipeline\n */\n async process(\n content: string,\n context: {\n sourceType: 'incident' | 'pr' | 'commit' | 'conversation' | 'file';\n sourceId?: string;\n who?: string;\n }\n ): Promise<ExtractedSignal> {\n console.log('🔍 Extracting signals from content...');\n \n // Step 1: Extract structured signals from raw content\n let extractedSignal = await this.extractor.extract(content, context.sourceType, context.sourceId);\n \n // Add IDs and metadata to extracted signal\n extractedSignal = this.addIds(extractedSignal, context);\n\n console.log(` ✓ Extracted ${extractedSignal.decisions.length} decisions, ${extractedSignal.facts.length} facts, ${extractedSignal.blockers.length} blockers, ${extractedSignal.questions.length} questions`);\n\n // Step 2: Enrich with metadata (tags, files, relationships)\n console.log('🏷️ Enriching with metadata...');\n const { metadata: enrichedMeta } = await this.enricher.enrichSignal(extractedSignal, {\n workingDirectory: this.workDir,\n });\n\n if (enrichedMeta.expandedTags.length > 0) {\n console.log(` ✓ Expanded tags: ${enrichedMeta.expandedTags.slice(0, 5).join(', ')}${enrichedMeta.expandedTags.length > 5 ? '...' : ''}`);\n }\n if (enrichedMeta.dependencies.length > 0) {\n console.log(` ✓ Dependencies: ${enrichedMeta.dependencies.join(', ')}`);\n }\n if (enrichedMeta.codebaseArea.length > 0) {\n console.log(` ✓ Codebase areas: ${enrichedMeta.codebaseArea.join(', ')}`);\n }\n if (enrichedMeta.domain.length > 0) {\n console.log(` ✓ Domains: ${enrichedMeta.domain.join(', ')}`);\n }\n\n // Step 3: Store in warm storage\n console.log('💾 Storing in decision ledger...');\n await this.storage.storeSignal(extractedSignal, {\n expandedTags: enrichedMeta.expandedTags,\n dependencies: enrichedMeta.dependencies,\n codebaseArea: enrichedMeta.codebaseArea,\n domain: enrichedMeta.domain,\n });\n\n console.log('✅ Successfully stored in decision ledger');\n\n return extractedSignal;\n }\n\n /**\n * Add IDs and metadata to extracted signal\n */\n private addIds(\n signal: ExtractedSignal,\n context: {\n sourceType: 'incident' | 'pr' | 'commit' | 'conversation' | 'file';\n sourceId?: string;\n who?: string;\n }\n ): ExtractedSignal {\n const now = new Date().toISOString();\n const metadata: ExtractedSignal['metadata'] = {\n extractedAt: now,\n sourceType: context.sourceType,\n extractionModel: 'claude-haiku',\n };\n if (context.sourceId !== undefined) {\n metadata.sourceId = context.sourceId;\n }\n\n return {\n decisions: signal.decisions.map(d => {\n const decision = {\n ...d,\n id: d.id || this.generateId(),\n when: d.when || now,\n status: d.status || 'active' as const,\n };\n if (context.who !== undefined) {\n decision.who = d.who || context.who;\n }\n return decision;\n }),\n facts: signal.facts.map(f => ({\n ...f,\n id: f.id || this.generateId(),\n when: f.when || now,\n confidence: f.confidence ?? 0.8,\n })),\n blockers: signal.blockers.map(b => ({\n ...b,\n id: b.id || this.generateId(),\n when: b.when || now,\n })),\n questions: signal.questions.map(q => ({\n ...q,\n id: q.id || this.generateId(),\n when: q.when || now,\n })),\n metadata,\n };\n }\n\n /**\n * Generate a unique ID\n */\n private generateId(): string {\n return randomBytes(8).toString('hex');\n }\n\n /**\n * Initialize storage\n */\n async initialize(): Promise<void> {\n await this.storage.initialize();\n }\n\n /**\n * Close storage connections\n */\n close(): void {\n this.storage.close();\n }\n}\n\n/**\n * Quick helper to process incident reports\n */\nexport async function processIncident(\n incidentDescription: string,\n options: PipelineOptions\n): Promise<ExtractedSignal> {\n const pipeline = new ExtractionPipeline(options);\n await pipeline.initialize();\n \n try {\n return await pipeline.process(incidentDescription, {\n sourceType: 'incident',\n sourceId: `incident-${Date.now()}`,\n });\n } finally {\n pipeline.close();\n }\n}\n\n/**\n * Quick helper to process commit messages\n */\nexport async function processCommit(\n commitMessage: string,\n commitSha: string,\n options: PipelineOptions\n): Promise<ExtractedSignal> {\n const pipeline = new ExtractionPipeline(options);\n await pipeline.initialize();\n \n try {\n return await pipeline.process(commitMessage, {\n sourceType: 'commit',\n sourceId: commitSha,\n });\n } finally {\n pipeline.close();\n }\n}\n","import { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join, basename, resolve, isAbsolute } from 'path';\nimport { SuperReviewerAgent, CRITICAL_REVIEW_CHECKLIST } from '../skills/built-in/super-reviewer.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { runShellCommandSync } from '../utils/command-runner.js';\n\n/**\n * PR Review Tool — Interactive AI-Guided Code Review\n * \n * Based on https://github.com/sitaram/devtools/blob/main/pr_review.md\n * \n * Code reviews are the bottleneck in AI coding. This tool scales them by\n * putting the human back in the loop, shepherded by AI.\n */\nexport class TriePRReviewTool {\n private agent = new SuperReviewerAgent();\n\n private exec(command: string, cwd?: string, maxBuffer?: number): string {\n const opts: Parameters<typeof runShellCommandSync>[2] = {\n captureOutput: false,\n redactOutput: true,\n ...(cwd ? { cwd } : {}),\n ...(maxBuffer ? { maxBuffer } : {}),\n };\n const { stdout } = runShellCommandSync(\n command,\n { actor: 'tool:pr-review', triggeredBy: 'manual', targetPath: cwd ?? getWorkingDirectory(undefined, true) },\n opts\n );\n return stdout.trimEnd();\n }\n\n async execute(args: any) {\n const { \n pr, \n worktree,\n mode,\n files: _specificFiles, // Reserved for future file filtering\n } = args;\n\n try {\n // Step 1: Determine target and get PR info\n const prInfo = await this.getPRInfo(pr, worktree);\n \n if (!prInfo.success) {\n return {\n content: [{\n type: 'text',\n text: `${prInfo.error}\\n\\nUsage:\\n- \\`pr_review 12345\\` — review specific PR\\n- \\`pr_review\\` — review PR for current branch\\n- \\`pr_review ../worktree\\` — review worktree changes`\n }]\n };\n }\n\n // Step 2: Get the diff and changed files\n const changes = await this.getChanges(prInfo);\n \n if (changes.files.length === 0) {\n return {\n content: [{\n type: 'text',\n text: `No changes found to review.`\n }]\n };\n }\n\n // Step 3: Look for design docs\n const designDocs = await this.findDesignDocs(changes.files, prInfo);\n\n // Step 4: Build the review workflow\n const workflow = await this.agent.buildReviewWorkflow(\n changes.files,\n {\n prNumber: prInfo.number,\n prTitle: prInfo.title,\n prAuthor: prInfo.author,\n baseBranch: prInfo.baseBranch,\n headBranch: prInfo.headBranch,\n mode: mode || 'own',\n designDocs,\n }\n );\n\n // Step 5: Pre-load all file contents for instant responses\n const fileContents = await this.preloadFiles(changes.files.map(f => f.path));\n\n // Step 6: Generate the review prompt\n const reviewPrompt = this.generateReviewPrompt(workflow, changes, fileContents);\n\n return {\n content: [{\n type: 'text',\n text: reviewPrompt\n }]\n };\n\n } catch (error) {\n return {\n content: [{\n type: 'text',\n text: `Error: ${error instanceof Error ? error.message : String(error)}`\n }]\n };\n }\n }\n\n /**\n * Get PR information from GitHub or local worktree\n */\n private async getPRInfo(pr?: string, worktree?: string): Promise<PRInfo> {\n // If worktree path provided, analyze local changes\n if (worktree) {\n const worktreePath = isAbsolute(worktree) ? worktree : resolve(getWorkingDirectory(undefined, true), worktree);\n if (!existsSync(worktreePath)) {\n return { success: false, error: `Worktree not found: ${worktreePath}` };\n }\n \n return {\n success: true,\n type: 'worktree',\n path: worktreePath,\n title: `Local changes in ${basename(worktreePath)}`,\n author: this.getGitUser(),\n baseBranch: 'HEAD~1',\n headBranch: 'HEAD',\n };\n }\n\n // If PR number provided, get from GitHub\n if (pr) {\n return this.getPRFromGitHub(pr);\n }\n\n // No args — try to get PR for current branch\n try {\n this.exec('git branch --show-current');\n \n // Check if there's a PR for this branch\n const prJson = this.exec(\n `gh pr view --json number,title,author,headRefName,baseRefName`\n );\n \n const prData = JSON.parse(prJson);\n \n return {\n success: true,\n type: 'github',\n number: String(prData.number),\n title: prData.title,\n author: prData.author?.login || 'unknown',\n baseBranch: prData.baseRefName,\n headBranch: prData.headRefName,\n };\n } catch {\n // No PR found, fall back to local changes\n return {\n success: true,\n type: 'local',\n title: 'Local uncommitted changes',\n author: this.getGitUser(),\n baseBranch: 'HEAD',\n headBranch: 'working tree',\n };\n }\n }\n\n /**\n * Get PR info from GitHub CLI\n */\n private async getPRFromGitHub(prNumber: string): Promise<PRInfo> {\n try {\n const prJson = this.exec(\n `gh pr view ${prNumber} --json number,title,author,headRefName,baseRefName`\n );\n \n const prData = JSON.parse(prJson);\n \n return {\n success: true,\n type: 'github',\n number: String(prData.number),\n title: prData.title,\n author: prData.author?.login || 'unknown',\n baseBranch: prData.baseRefName,\n headBranch: prData.headRefName,\n };\n } catch (error) {\n return {\n success: false,\n error: `Failed to get PR #${prNumber}. Is \\`gh\\` CLI installed and authenticated?`\n };\n }\n }\n\n /**\n * Get changes (diff) for the PR or local changes\n */\n private async getChanges(prInfo: PRInfo): Promise<{ files: ChangedFile[]; fullDiff: string }> {\n let diffOutput: string;\n \n try {\n if (prInfo.type === 'github' && prInfo.number) {\n // Get diff from GitHub PR\n diffOutput = this.exec(`gh pr diff ${prInfo.number}`, undefined, 50 * 1024 * 1024);\n } else if (prInfo.type === 'worktree' && prInfo.path) {\n // Get diff from worktree\n diffOutput = this.exec(`git diff HEAD`, prInfo.path, 50 * 1024 * 1024);\n } else {\n // Local changes\n diffOutput = this.exec(`git diff HEAD`, undefined, 50 * 1024 * 1024);\n \n // If no diff, try staged changes\n if (!diffOutput.trim()) {\n diffOutput = this.exec(`git diff --cached`, undefined, 50 * 1024 * 1024);\n }\n }\n } catch {\n diffOutput = '';\n }\n\n // Parse the diff to extract file information\n const files = this.parseDiff(diffOutput);\n\n return { files, fullDiff: diffOutput };\n }\n\n /**\n * Parse git diff output into structured file changes\n */\n private parseDiff(diffOutput: string): ChangedFile[] {\n const files: ChangedFile[] = [];\n const fileDiffs = diffOutput.split(/^diff --git /m).slice(1);\n\n for (const fileDiff of fileDiffs) {\n const lines = fileDiff.split('\\n');\n const headerLine = lines[0] || '';\n \n // Extract file path from \"a/path b/path\"\n const pathMatch = headerLine.match(/a\\/(.+?) b\\/(.+)/);\n if (!pathMatch || !pathMatch[2]) continue;\n \n const path: string = pathMatch[2];\n const diff = `diff --git ${fileDiff}`;\n \n // Count additions and deletions\n let additions = 0;\n let deletions = 0;\n \n for (const line of lines) {\n if (line.startsWith('+') && !line.startsWith('+++')) {\n additions++;\n } else if (line.startsWith('-') && !line.startsWith('---')) {\n deletions++;\n }\n }\n \n files.push({ path, diff, additions, deletions, status: 'modified' });\n }\n\n return files;\n }\n\n /**\n * Find related design docs\n */\n private async findDesignDocs(files: ChangedFile[], prInfo: PRInfo): Promise<string[]> {\n const designDocs: string[] = [];\n const cwd = prInfo.path || getWorkingDirectory(undefined, true);\n \n // Check for design_docs/ in changed files\n for (const file of files) {\n if (file.path.includes('design_docs/') || \n file.path.includes('docs/design/') ||\n file.path.includes('rfcs/')) {\n designDocs.push(file.path);\n }\n }\n \n // Look for design docs in standard locations\n const designDocPaths = [\n 'design_docs',\n 'docs/design',\n 'docs/rfcs',\n 'rfcs',\n ];\n \n for (const docPath of designDocPaths) {\n const fullPath = join(cwd, docPath);\n if (existsSync(fullPath)) {\n // Could list and add recent docs, but for now just note the directory exists\n }\n }\n \n return designDocs;\n }\n\n /**\n * Pre-load all changed files for instant responses during review\n */\n private async preloadFiles(filePaths: string[]): Promise<Map<string, string>> {\n const contents = new Map<string, string>();\n const cwd = getWorkingDirectory(undefined, true);\n \n await Promise.all(filePaths.map(async (filePath) => {\n try {\n const fullPath = isAbsolute(filePath) ? filePath : join(cwd, filePath);\n if (existsSync(fullPath)) {\n const content = await readFile(fullPath, 'utf-8');\n contents.set(filePath, content);\n }\n } catch {\n // Skip unreadable files\n }\n }));\n \n return contents;\n }\n\n /**\n * Get git user name\n */\n private getGitUser(): string {\n try {\n return this.exec('git config user.name');\n } catch {\n return 'unknown';\n }\n }\n\n /**\n * Generate the full review prompt for Claude to execute\n */\n private generateReviewPrompt(\n workflow: any,\n changes: { files: ChangedFile[]; fullDiff: string },\n _fileContents: Map<string, string> // Reserved for future: inline file contents in review\n ): string {\n const { metadata, fileOrder, reviewInstructions } = workflow;\n \n let prompt = `# 🔍 Super Reviewer — Interactive PR Review\\n\\n`;\n \n // PR Header\n if (metadata.prNumber) {\n prompt += `## PR #${metadata.prNumber}: ${metadata.prTitle}\\n\\n`;\n } else {\n prompt += `## ${metadata.prTitle}\\n\\n`;\n }\n \n prompt += `**Author:** ${metadata.prAuthor}\\n`;\n prompt += `**Branch:** \\`${metadata.headBranch}\\` → \\`${metadata.baseBranch}\\`\\n`;\n prompt += `**Scope:** ${metadata.totalFiles} files, +${metadata.totalAdditions}/-${metadata.totalDeletions} lines\\n\\n`;\n \n prompt += `---\\n\\n`;\n \n // Review Mode Selection\n prompt += `## Review Mode\\n\\n`;\n prompt += `**Current Mode:** ${reviewInstructions.mode === 'own' ? '1' : '2'}. ${reviewInstructions.description}\\n\\n`;\n prompt += `> To switch modes, say \"mode 1\" for your own PR or \"mode 2\" for someone else's\\n\\n`;\n \n prompt += `---\\n\\n`;\n \n // File Order Table\n prompt += `## Files to Review (ordered for understanding)\\n\\n`;\n prompt += `| # | File | Why this order |\\n`;\n prompt += `|---|------|----------------|\\n`;\n \n for (const file of fileOrder) {\n const stats = `+${changes.files.find(f => f.path === file.path)?.additions || 0}/-${changes.files.find(f => f.path === file.path)?.deletions || 0}`;\n prompt += `| ${file.index} | \\`${file.path}\\` (${stats}) | ${file.reason} |\\n`;\n }\n \n prompt += `\\n---\\n\\n`;\n \n // Critical Review Mindset\n prompt += `## Critical Review Mindset\\n\\n`;\n prompt += `As we go through each file, I'll actively look for:\\n\\n`;\n \n prompt += `**State & Lifecycle:**\\n`;\n for (const check of CRITICAL_REVIEW_CHECKLIST.stateAndLifecycle) {\n prompt += `- ${check}\\n`;\n }\n \n prompt += `\\n**Edge Cases & Races:**\\n`;\n for (const check of CRITICAL_REVIEW_CHECKLIST.edgeCasesAndRaces) {\n prompt += `- ${check}\\n`;\n }\n \n prompt += `\\n**Missing Pieces:**\\n`;\n for (const check of CRITICAL_REVIEW_CHECKLIST.missingPieces) {\n prompt += `- ${check}\\n`;\n }\n \n prompt += `\\n---\\n\\n`;\n \n // Pre-loaded diffs\n prompt += `## File Diffs (pre-loaded for instant review)\\n\\n`;\n prompt += `<details>\\n<summary>📁 All file diffs (click to expand)</summary>\\n\\n`;\n \n for (const file of fileOrder) {\n const fileChange = changes.files.find(f => f.path === file.path);\n if (fileChange) {\n prompt += `### ${file.path}\\n\\n`;\n prompt += `\\`\\`\\`diff\\n${fileChange.diff}\\n\\`\\`\\`\\n\\n`;\n }\n }\n \n prompt += `</details>\\n\\n`;\n \n prompt += `---\\n\\n`;\n \n // Ready to start\n prompt += `## Ready to Begin\\n\\n`;\n prompt += `I'll walk you through each file, explaining what changed and why. After each file, I'll pause for your questions.\\n\\n`;\n prompt += `**Commands during review:**\\n`;\n prompt += `- \\`yes\\` or \\`y\\` — continue to next file\\n`;\n prompt += `- \\`skip to [filename]\\` — jump to specific file\\n`;\n prompt += `- \\`questions?\\` — ask about current file\\n`;\n prompt += `- \\`reorder\\` — change the file order\\n`;\n prompt += `- \\`done\\` — end review and show summary\\n\\n`;\n \n prompt += `**Ready for File 1?** (\\`${fileOrder[0]?.path || 'no files'}\\`)\\n\\n`;\n prompt += `*(say \"yes\" to start, or ask me anything)*\\n`;\n \n return prompt;\n }\n}\n\n// Type definitions\ninterface PRInfo {\n success: boolean;\n error?: string;\n type?: 'github' | 'worktree' | 'local';\n number?: string;\n title?: string;\n author?: string;\n baseBranch?: string;\n headBranch?: string;\n path?: string;\n}\n\ninterface ChangedFile {\n path: string;\n diff: string;\n additions: number;\n deletions: number;\n status: string;\n}\n","/**\n * Super Reviewer stub\n * Review functionality has been integrated into decision ledger\n */\n\nexport const CRITICAL_REVIEW_CHECKLIST = {\n stateAndLifecycle: [\n 'Uninitialized state accessed before setup',\n 'Missing cleanup on unmount/dispose',\n 'State mutations in wrong lifecycle phase',\n ],\n edgeCasesAndRaces: [\n 'Race conditions in async operations',\n 'Missing error handling for edge cases',\n 'Unhandled promise rejections',\n ],\n missingPieces: [\n 'Missing input validation',\n 'Missing error handling',\n 'Missing logging/monitoring',\n ],\n};\n\nexport interface ChangedFile {\n path: string;\n additions: number;\n deletions: number;\n status: string;\n}\n\nexport class SuperReviewerAgent {\n async review(_files: string[]): Promise<{ issues: any[] }> {\n return { issues: [] };\n }\n\n async buildReviewWorkflow(\n files: ChangedFile[],\n context: Record<string, any>\n ): Promise<{ files: ChangedFile[]; context: Record<string, any> }> {\n return { files, context };\n }\n}\n","/**\n * Project Info MCP Tool\n * \n * Provides MCP tool for viewing and managing PROJECT.md\n */\n\nimport {\n loadProjectInfo,\n initProjectInfo,\n getProjectSection,\n updateProjectSection,\n appendToSection,\n getProjectSections,\n getProjectInfoStructured,\n projectInfoExists,\n} from '../utils/project-info.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport interface ProjectInfoArgs {\n action: 'view' | 'init' | 'update' | 'append' | 'sections' | 'raw';\n section?: string;\n content?: string;\n directory?: string;\n}\n\nexport class TrieProjectInfoTool {\n async execute(args: ProjectInfoArgs): Promise<{ content: Array<{ type: string; text: string }> }> {\n const workDir = args.directory || getWorkingDirectory(undefined, true);\n const action = args.action || 'view';\n\n try {\n switch (action) {\n case 'view':\n return await this.handleView(workDir, args.section);\n \n case 'init':\n return await this.handleInit(workDir);\n \n case 'update':\n return await this.handleUpdate(workDir, args.section, args.content);\n \n case 'append':\n return await this.handleAppend(workDir, args.section, args.content);\n \n case 'sections':\n return await this.handleSections(workDir);\n \n case 'raw':\n return await this.handleRaw(workDir);\n \n default:\n return this.error(`Unknown action: ${action}. Use: view, init, update, append, sections, raw`);\n }\n } catch (error) {\n return this.error(`Error: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n private async handleView(workDir: string, section?: string): Promise<{ content: Array<{ type: string; text: string }> }> {\n if (!projectInfoExists(workDir)) {\n return this.formatResponse(`## Project Info Not Found\n\nNo \\`.trie/PROJECT.md\\` file exists in this project.\n\n**To create one, use:**\n\\`\\`\\`\ntrie_project action=\"init\"\n\\`\\`\\`\n\nOr run: \\`trie project init\\`\n\nThis will create a template with sections for:\n- Project Overview\n- Technology Stack\n- Architecture\n- Coding Conventions\n- Environment\n- Team\n- Compliance\n- AI Instructions`);\n }\n\n if (section) {\n const sectionContent = await getProjectSection(section, workDir);\n if (sectionContent === null) {\n const sections = await getProjectSections(workDir);\n return this.formatResponse(`## Section Not Found: \"${section}\"\n\nAvailable sections:\n${sections.map(s => `- ${s}`).join('\\n')}`);\n }\n \n return this.formatResponse(`## ${section}\n\n${sectionContent}`);\n }\n\n // Return structured view\n const info = await getProjectInfoStructured(workDir);\n \n let output = `## Project Information\n\n**Path:** \\`${info.path}\\`\n**Sections:** ${Object.keys(info.sections).length}\n\n---\n\n`;\n\n for (const [name, content] of Object.entries(info.sections)) {\n output += `### ${name}\n\n${content}\n\n---\n\n`;\n }\n\n return this.formatResponse(output);\n }\n\n private async handleInit(workDir: string): Promise<{ content: Array<{ type: string; text: string }> }> {\n const result = await initProjectInfo(workDir);\n \n if (result.created) {\n return this.formatResponse(`## PROJECT.md Created\n\n**Path:** \\`${result.path}\\`\n\nA new PROJECT.md file has been created with a template including sections for:\n- Project Overview\n- Technology Stack\n- Architecture\n- Coding Conventions\n- Environment\n- Team\n- Compliance\n- AI Instructions\n\n**Next steps:**\n1. Open the file and fill in your project details\n2. The content will be available via \\`trie://project\\` resource\n3. AI assistants will use this context when working on your project\n\n**View the template:**\n\\`\\`\\`\ntrie_project action=\"view\"\n\\`\\`\\``);\n }\n\n return this.formatResponse(`## PROJECT.md Already Exists\n\n**Path:** \\`${result.path}\\`\n\nUse \\`trie_project action=\"view\"\\` to see the current content.`);\n }\n\n private async handleUpdate(\n workDir: string, \n section?: string, \n content?: string\n ): Promise<{ content: Array<{ type: string; text: string }> }> {\n if (!section) {\n return this.error('Missing required parameter: section');\n }\n if (!content) {\n return this.error('Missing required parameter: content');\n }\n\n const success = await updateProjectSection(section, content, workDir);\n \n if (success) {\n return this.formatResponse(`## Section Updated: \"${section}\"\n\nThe \"${section}\" section has been updated with your new content.\n\n**View updated section:**\n\\`\\`\\`\ntrie_project action=\"view\" section=\"${section}\"\n\\`\\`\\``);\n }\n\n const sections = await getProjectSections(workDir);\n return this.error(`Could not update section \"${section}\". \n\nAvailable sections:\n${sections.map(s => `- ${s}`).join('\\n')}`);\n }\n\n private async handleAppend(\n workDir: string,\n section?: string,\n content?: string\n ): Promise<{ content: Array<{ type: string; text: string }> }> {\n if (!section) {\n return this.error('Missing required parameter: section');\n }\n if (!content) {\n return this.error('Missing required parameter: content');\n }\n\n const success = await appendToSection(section, content, workDir);\n \n if (success) {\n return this.formatResponse(`## Content Appended to: \"${section}\"\n\nYour content has been added to the \"${section}\" section.\n\n**View updated section:**\n\\`\\`\\`\ntrie_project action=\"view\" section=\"${section}\"\n\\`\\`\\``);\n }\n\n return this.error(`Could not append to section \"${section}\". Make sure the section exists.`);\n }\n\n private async handleSections(workDir: string): Promise<{ content: Array<{ type: string; text: string }> }> {\n if (!projectInfoExists(workDir)) {\n return this.formatResponse(`## No PROJECT.md Found\n\nRun \\`trie_project action=\"init\"\\` to create one.`);\n }\n\n const sections = await getProjectSections(workDir);\n \n return this.formatResponse(`## Available Sections\n\n${sections.map((s, i) => `${i + 1}. **${s}**`).join('\\n')}\n\n**View a section:**\n\\`\\`\\`\ntrie_project action=\"view\" section=\"Section Name\"\n\\`\\`\\`\n\n**Update a section:**\n\\`\\`\\`\ntrie_project action=\"update\" section=\"Section Name\" content=\"New content...\"\n\\`\\`\\``);\n }\n\n private async handleRaw(workDir: string): Promise<{ content: Array<{ type: string; text: string }> }> {\n const content = await loadProjectInfo(workDir);\n \n if (!content) {\n return this.formatResponse(`No PROJECT.md found. Run \\`trie_project action=\"init\"\\` to create one.`);\n }\n\n return this.formatResponse(content);\n }\n\n private formatResponse(text: string): { content: Array<{ type: string; text: string }> } {\n return {\n content: [{ type: 'text', text }]\n };\n }\n\n private error(message: string): { content: Array<{ type: string; text: string }> } {\n return {\n content: [{ type: 'text', text: `**Error:** ${message}` }]\n };\n }\n}\n","/**\n * Trie Init Tool\n * \n * MCP tool for initializing bootstrap files.\n */\n\nimport { initializeBootstrapFiles, loadBootstrapContext, completeBootstrap, needsBootstrap } from '../bootstrap/index.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport class TrieInitTool {\n async execute(params: {\n action?: 'init' | 'status' | 'complete' | 'context';\n directory?: string;\n force?: boolean;\n skipBootstrap?: boolean;\n }): Promise<string> {\n const action = params.action || 'init';\n const workDir = params.directory || getWorkingDirectory(undefined, true);\n\n if (action === 'status') {\n const needs = needsBootstrap(workDir);\n const context = await loadBootstrapContext(workDir);\n \n const existingFiles = context.files.filter(f => f.exists).map(f => f.name);\n const missingFiles = context.files.filter(f => !f.exists).map(f => f.name);\n \n return [\n '# Bootstrap Status',\n '',\n `**Bootstrap pending:** ${needs ? 'Yes' : 'No'}`,\n '',\n '## Files',\n '',\n '**Existing:**',\n existingFiles.length > 0 ? existingFiles.map(f => `- .trie/${f}`).join('\\n') : '- None',\n '',\n '**Missing:**',\n missingFiles.length > 0 ? missingFiles.map(f => `- .trie/${f}`).join('\\n') : '- None',\n ].join('\\n');\n }\n\n if (action === 'complete') {\n const result = await completeBootstrap(workDir);\n if (result) {\n return 'Bootstrap completed. BOOTSTRAP.md has been deleted.';\n }\n return 'No BOOTSTRAP.md file found.';\n }\n\n if (action === 'context') {\n const context = await loadBootstrapContext(workDir);\n if (!context.injectedContent) {\n return 'No bootstrap context available. Run trie_init with action=\"init\" first.';\n }\n return context.injectedContent;\n }\n\n // Default: init\n const initOptions: Parameters<typeof initializeBootstrapFiles>[0] = {\n workDir,\n };\n if (params.force !== undefined) {\n initOptions.force = params.force;\n }\n if (params.skipBootstrap !== undefined) {\n initOptions.skipBootstrap = params.skipBootstrap;\n }\n const result = await initializeBootstrapFiles(initOptions);\n\n const lines: string[] = [\n '# Trie Workspace Initialized',\n '',\n ];\n\n if (result.created.length > 0) {\n lines.push('## Created Files', '');\n for (const file of result.created) {\n lines.push(`- .trie/${file}`);\n }\n lines.push('');\n }\n\n if (result.skipped.length > 0) {\n lines.push('## Skipped (already exist)', '');\n for (const file of result.skipped) {\n lines.push(`- .trie/${file}`);\n }\n lines.push('');\n }\n\n lines.push('## Detected Stack', '');\n if (result.stack.framework) lines.push(`- **Framework:** ${result.stack.framework}`);\n if (result.stack.language) lines.push(`- **Language:** ${result.stack.language}`);\n if (result.stack.database) lines.push(`- **Database:** ${result.stack.database}`);\n if (result.stack.auth) lines.push(`- **Auth:** ${result.stack.auth}`);\n if (result.stack.packageManager) lines.push(`- **Package Manager:** ${result.stack.packageManager}`);\n lines.push('');\n\n if (result.stack.suggestedSkills.length > 0) {\n lines.push('## Suggested Skills', '');\n for (const skill of result.stack.suggestedSkills) {\n lines.push(`\\`\\`\\`bash`);\n lines.push(`trie skills add ${skill}`);\n lines.push(`\\`\\`\\``);\n }\n lines.push('');\n }\n\n lines.push(\n '## Next Steps',\n '',\n '1. Edit `.trie/PROJECT.md` with your project description',\n '2. Define coding standards in `.trie/RULES.md`',\n '3. Run `trie_scan` to analyze your codebase',\n '4. Run `trie_init` with action=\"complete\" when setup is done',\n );\n\n return lines.join('\\n');\n }\n}\n","/**\n * Trie Memory Search Tool\n * \n * MCP tool for searching issue memory.\n */\n\nimport {\n searchIssues,\n getMemoryStats,\n getRecentIssues,\n findSimilarIssues,\n markIssueResolved,\n purgeIssues,\n} from '../memory/issue-store.js';\nimport {\n findCrossProjectPatterns,\n searchGlobalPatterns,\n listTrackedProjects,\n getGlobalMemoryStats,\n} from '../memory/global-memory.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport class TrieMemorySearchTool {\n async execute(params: {\n action?: 'search' | 'stats' | 'recent' | 'similar' | 'resolve' | 'global' | 'purge';\n query?: string;\n issueId?: string;\n limit?: number;\n severity?: string[];\n agent?: string;\n includeResolved?: boolean;\n directory?: string;\n purgeStrategy?: 'smart' | 'resolved' | 'old' | 'all';\n daysOld?: number;\n }): Promise<{ content: Array<{ type: string; text: string }> }> {\n const action = params.action || 'search';\n const workDir = params.directory || getWorkingDirectory(undefined, true);\n\n let resultText: string;\n switch (action) {\n case 'search':\n resultText = await this.handleSearch(params, workDir);\n break;\n case 'stats':\n resultText = await this.handleStats(workDir);\n break;\n case 'recent':\n resultText = await this.handleRecent(params, workDir);\n break;\n case 'similar':\n resultText = await this.handleSimilar(params, workDir);\n break;\n case 'resolve':\n resultText = await this.handleResolve(params, workDir);\n break;\n case 'global':\n resultText = await this.handleGlobal(params);\n break;\n case 'purge':\n resultText = await this.handlePurge(params, workDir);\n break;\n default:\n resultText = 'Unknown action. Use: search, stats, recent, similar, resolve, global, or purge';\n }\n\n return {\n content: [{\n type: 'text',\n text: resultText\n }]\n };\n }\n\n private async handleSearch(params: {\n query?: string;\n limit?: number;\n severity?: string[];\n agent?: string;\n includeResolved?: boolean;\n }, workDir: string): Promise<string> {\n if (!params.query) {\n return 'Missing required parameter: query';\n }\n\n const searchOptions: Parameters<typeof searchIssues>[1] = {\n workDir,\n limit: params.limit || 10,\n };\n if (params.severity !== undefined) {\n searchOptions.severity = params.severity;\n }\n if (params.agent !== undefined) {\n searchOptions.agent = params.agent;\n }\n if (params.includeResolved !== undefined) {\n searchOptions.includeResolved = params.includeResolved;\n }\n const results = await searchIssues(params.query, searchOptions);\n\n if (results.length === 0) {\n return `No issues found matching \"${params.query}\"`;\n }\n\n const lines: string[] = [\n `# Search Results: \"${params.query}\"`,\n '',\n `Found ${results.length} matching issue(s):`,\n '',\n ];\n\n for (const result of results) {\n const i = result.issue;\n const status = i.resolved ? ' [RESOLVED]' : '';\n lines.push(\n `## [${i.severity.toUpperCase()}]${status} ${i.issue.slice(0, 80)}`,\n '',\n `- **File:** \\`${i.file}\\`${i.line ? `:${i.line}` : ''}`,\n `- **Agent:** ${i.agent}`,\n `- **Score:** ${(result.score * 100).toFixed(0)}%`,\n `- **Date:** ${new Date(i.timestamp).toLocaleDateString()}`,\n `- **Fix:** ${i.fix.slice(0, 150)}${i.fix.length > 150 ? '...' : ''}`,\n '',\n );\n }\n\n return lines.join('\\n');\n }\n\n private async handleStats(workDir: string): Promise<string> {\n const stats = await getMemoryStats(workDir);\n const globalStats = await getGlobalMemoryStats();\n\n const lines: string[] = [\n '# Memory Statistics',\n '',\n '## Local Issue Memory',\n '',\n `- **Active Issues:** ${stats.activeIssues}`,\n `- **Resolved:** ${stats.resolvedCount}`,\n `- **Total (all-time):** ${stats.totalIssues}`,\n ];\n\n // Capacity warning\n const cap = stats.capacityInfo;\n if (cap.isAtCap) {\n lines.push(\n '',\n '### ⚠️ CAPACITY WARNING',\n '',\n `**Memory is at maximum capacity (${cap.current}/${cap.max} issues, ${cap.percentFull}%)**`,\n '',\n 'Trie caps issue storage at 10,000 for performance. New repeats are deduplicated.',\n 'Older issues are compacted into summaries, and if it still exceeds the cap the oldest/lowest-value issues are pruned.',\n '',\n '**Options to free up space:**',\n '- `trie memory purge smart` - Remove resolved and old low-priority issues (recommended)',\n '- `trie memory purge resolved` - Remove all resolved issues',\n '- `trie memory purge old` - Remove issues older than 90 days',\n '- `trie memory purge all` - Clear all issues (keeps summaries)',\n );\n } else if (cap.percentFull >= 80) {\n lines.push(\n '',\n `### ℹ️ Memory Usage: ${cap.percentFull}% (${cap.current}/${cap.max})`,\n '',\n `You're approaching the storage cap. Consider running \\`trie memory purge smart\\` to free up space.`,\n );\n } else {\n lines.push(`- **Memory Usage:** ${cap.percentFull}% (${cap.current}/${cap.max})`);\n }\n\n // Deduplication stats\n if (stats.deduplicationStats.duplicatesAvoided > 0) {\n lines.push(\n '',\n '### Deduplication',\n '',\n `- **Unique Patterns:** ${stats.deduplicationStats.uniquePatterns}`,\n `- **Duplicates Avoided:** ${stats.deduplicationStats.duplicatesAvoided}`,\n );\n }\n\n if (stats.oldestIssue) {\n lines.push('', `- **Date Range:** ${stats.oldestIssue.split('T')[0]} to ${stats.newestIssue?.split('T')[0]}`);\n }\n\n lines.push('', '### By Severity', '');\n for (const [severity, count] of Object.entries(stats.issuesBySeverity)) {\n lines.push(`- ${severity}: ${count}`);\n }\n\n lines.push('', '### By Agent', '');\n const sortedAgents = Object.entries(stats.issuesByAgent).sort((a, b) => b[1] - a[1]);\n for (const [agent, count] of sortedAgents.slice(0, 10)) {\n lines.push(`- ${agent}: ${count}`);\n }\n\n lines.push(\n '',\n '## Global Cross-Project Memory',\n '',\n `- **Tracked Projects:** ${globalStats.trackedProjects}`,\n `- **Total Patterns:** ${globalStats.totalPatterns}`,\n `- **Cross-Project Patterns:** ${globalStats.crossProjectPatterns}`,\n `- **Fixed Patterns:** ${globalStats.fixedPatterns}`,\n );\n\n return lines.join('\\n');\n }\n\n private async handleRecent(params: {\n limit?: number;\n }, workDir: string): Promise<string> {\n const issues = await getRecentIssues({\n workDir,\n limit: params.limit || 10,\n });\n\n if (issues.length === 0) {\n return 'No recent issues found.';\n }\n\n const lines: string[] = [\n '# Recent Issues (Last 7 Days)',\n '',\n ];\n\n for (const i of issues) {\n const status = i.resolved ? ' [RESOLVED]' : '';\n lines.push(\n `## [${i.severity.toUpperCase()}]${status} ${i.issue.slice(0, 70)}`,\n '',\n `- \\`${i.file}\\`${i.line ? `:${i.line}` : ''}`,\n `- Agent: ${i.agent} | ${new Date(i.timestamp).toLocaleDateString()}`,\n '',\n );\n }\n\n return lines.join('\\n');\n }\n\n private async handleSimilar(params: {\n query?: string;\n limit?: number;\n }, workDir: string): Promise<string> {\n if (!params.query) {\n return 'Missing required parameter: query (issue description to find similar issues for)';\n }\n\n const mockIssue = {\n id: 'search',\n severity: 'moderate' as const,\n issue: params.query,\n fix: '',\n file: '',\n agent: 'search',\n confidence: 1,\n autoFixable: false,\n };\n\n const results = await findSimilarIssues(mockIssue, {\n workDir,\n limit: params.limit || 5,\n });\n\n if (results.length === 0) {\n return 'No similar issues found.';\n }\n\n const lines: string[] = [\n `# Similar Issues`,\n '',\n `Found ${results.length} similar issue(s):`,\n '',\n ];\n\n for (const result of results) {\n const i = result.issue;\n lines.push(\n `## [${i.severity.toUpperCase()}] ${i.issue.slice(0, 70)}`,\n '',\n `- **File:** \\`${i.file}\\``,\n `- **Similarity:** ${(result.score * 100).toFixed(0)}%`,\n '',\n );\n }\n\n return lines.join('\\n');\n }\n\n private async handleResolve(params: {\n issueId?: string;\n }, workDir: string): Promise<string> {\n if (!params.issueId) {\n return 'Missing required parameter: issueId';\n }\n\n const result = await markIssueResolved(params.issueId, workDir);\n \n if (result) {\n return `Issue ${params.issueId} marked as resolved.`;\n }\n return `Issue ${params.issueId} not found.`;\n }\n\n private async handleGlobal(params: {\n query?: string;\n limit?: number;\n }): Promise<string> {\n if (params.query) {\n const patterns = await searchGlobalPatterns(params.query, {\n limit: params.limit || 10,\n });\n\n if (patterns.length === 0) {\n return `No global patterns found matching \"${params.query}\"`;\n }\n\n const lines: string[] = [\n `# Global Pattern Search: \"${params.query}\"`,\n '',\n ];\n\n for (const p of patterns) {\n lines.push(\n `## [${p.severity.toUpperCase()}] ${p.pattern.slice(0, 60)}`,\n '',\n `- **Occurrences:** ${p.occurrences} across ${p.projects.length} projects`,\n `- **Agent:** ${p.agent}`,\n `- **Projects:** ${p.projects.slice(0, 3).join(', ')}`,\n p.fixApplied ? `- **Fixed in:** ${p.fixApplied.project}` : '',\n '',\n );\n }\n\n return lines.join('\\n');\n }\n\n const patterns = await findCrossProjectPatterns(2);\n const projects = await listTrackedProjects();\n\n const lines: string[] = [\n '# Global Cross-Project Memory',\n '',\n `**Tracked Projects:** ${projects.length}`,\n `**Cross-Project Patterns:** ${patterns.length}`,\n '',\n ];\n\n if (patterns.length > 0) {\n lines.push('## Top Cross-Project Patterns', '');\n \n for (const p of patterns.slice(0, 5)) {\n lines.push(\n `### [${p.severity.toUpperCase()}] ${p.pattern.slice(0, 50)}`,\n '',\n `- Seen ${p.occurrences}x across ${p.projects.length} projects`,\n p.fixApplied ? `- Fixed in ${p.fixApplied.project}` : '- Not yet fixed',\n '',\n );\n }\n }\n\n if (projects.length > 0) {\n lines.push('## Recent Projects', '', '| Project | Health | Issues |', '|---------|--------|--------|');\n \n for (const p of projects.slice(0, 5)) {\n lines.push(`| ${p.name} | ${p.healthScore}% | ${p.totalIssues} |`);\n }\n }\n\n return lines.join('\\n');\n }\n\n private async handlePurge(params: {\n purgeStrategy?: 'smart' | 'resolved' | 'old' | 'all';\n daysOld?: number;\n }, workDir: string): Promise<string> {\n const strategy = params.purgeStrategy || 'smart';\n \n const options: { workDir: string; daysOld?: number } = { workDir };\n if (params.daysOld !== undefined) {\n options.daysOld = params.daysOld;\n }\n \n const result = await purgeIssues(strategy, options);\n\n const lines: string[] = [\n '# Memory Purge Complete',\n '',\n `**Strategy:** ${strategy}`,\n `**Removed:** ${result.removed} issues`,\n `**Remaining:** ${result.remaining} issues`,\n '',\n ];\n\n switch (strategy) {\n case 'smart':\n lines.push(\n '**What was removed:**',\n '- Resolved issues older than 30 days',\n '- Low-priority issues (info/low severity) older than 30 days',\n '',\n '**What was kept:**',\n '- All critical and high severity issues',\n '- All unresolved issues',\n '- All issues from the last 30 days',\n );\n break;\n case 'resolved':\n lines.push('**Removed all resolved issues.**', '**Kept all unresolved issues.**');\n break;\n case 'old':\n lines.push(\n `**Removed all issues older than ${params.daysOld || 90} days.**`,\n `**Kept all recent issues.**`,\n );\n break;\n case 'all':\n lines.push(\n '**Cleared all issues from active memory.**',\n '',\n 'Historical summaries are preserved in compacted-summaries.json.',\n );\n break;\n }\n\n lines.push('', '**Note:** Compacted historical summaries were preserved for trend analysis.');\n\n return lines.join('\\n');\n }\n}\n","/**\n * Checkpoint MCP Tool\n * \n * Save context without running a full scan.\n */\n\nimport { saveCheckpoint, listCheckpoints, getLastCheckpoint } from '../cli/checkpoint.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport interface CheckpointToolInput {\n action: 'save' | 'list' | 'last';\n message?: string;\n notes?: string;\n files?: string[];\n}\n\nexport async function handleCheckpointTool(input: CheckpointToolInput): Promise<string> {\n const workDir = getWorkingDirectory(undefined, true);\n \n switch (input.action) {\n case 'save': {\n const saveOptions: Parameters<typeof saveCheckpoint>[0] = {\n files: input.files || [],\n workDir,\n createdBy: 'mcp',\n };\n if (input.message !== undefined) {\n saveOptions.message = input.message;\n }\n if (input.notes !== undefined) {\n saveOptions.notes = input.notes;\n }\n const checkpoint = await saveCheckpoint(saveOptions);\n \n return `# Checkpoint Saved\n\n**ID:** ${checkpoint.id}\n**Time:** ${checkpoint.timestamp}\n${checkpoint.message ? `**Message:** ${checkpoint.message}` : ''}\n${checkpoint.notes ? `**Notes:** ${checkpoint.notes}` : ''}\n${checkpoint.files.length > 0 ? `**Files:** ${checkpoint.files.join(', ')}` : ''}\n\nContext saved to \\`.trie/\\`. This checkpoint will be visible in other tools (Cursor, Claude Code, CLI).`;\n }\n \n case 'list': {\n const checkpoints = await listCheckpoints(workDir);\n \n if (checkpoints.length === 0) {\n return 'No checkpoints yet. Use `trie_checkpoint action=\"save\"` to create one.';\n }\n \n const lines = ['# Recent Checkpoints', ''];\n for (const cp of checkpoints.slice(-10).reverse()) {\n const date = new Date(cp.timestamp).toLocaleString();\n lines.push(`- **${cp.id}** (${date}): ${cp.message || '(no message)'}`);\n }\n \n return lines.join('\\n');\n }\n \n case 'last': {\n const checkpoint = await getLastCheckpoint(workDir);\n \n if (!checkpoint) {\n return 'No checkpoints yet. Use `trie_checkpoint action=\"save\"` to create one.';\n }\n \n return `# Last Checkpoint\n\n**ID:** ${checkpoint.id}\n**Time:** ${new Date(checkpoint.timestamp).toLocaleString()}\n${checkpoint.message ? `**Message:** ${checkpoint.message}` : ''}\n${checkpoint.notes ? `**Notes:** ${checkpoint.notes}` : ''}\n${checkpoint.files.length > 0 ? `**Files:** ${checkpoint.files.join(', ')}` : ''}\n**Created by:** ${checkpoint.createdBy}`;\n }\n \n default:\n return 'Unknown action. Use: save, list, or last';\n }\n}\n","import { perceiveCurrentChanges } from '../agent/perceive.js';\nimport { reasonAboutChangesHumanReadable } from '../agent/reason.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\n\nexport interface CheckToolInput {\n directory?: string;\n files?: string[];\n mode?: 'quick' | 'full' | 'offline';\n}\n\nexport class TrieCheckTool {\n async execute(input: CheckToolInput = {}): Promise<any> {\n try {\n const workDir = input.directory || getWorkingDirectory(undefined, true);\n let files = input.files;\n\n if (!files || files.length === 0) {\n const perception = await perceiveCurrentChanges(workDir);\n files = perception.diffSummary.files.map((f) => f.filePath);\n }\n\n if (!files || files.length === 0) {\n return {\n content: [{\n type: 'text',\n text: 'No changes detected. Provide files or make a change.'\n }]\n };\n }\n\n const mode = input.mode ?? 'full';\n const runAgents = mode === 'full';\n\n const reasoning = await reasonAboutChangesHumanReadable(workDir, files, {\n runAgents,\n scanContext: { config: { timeoutMs: mode === 'quick' ? 15000 : 60000 } }\n });\n\n const summary = [\n `Risk: ${reasoning.original.riskLevel.toUpperCase()} (${reasoning.original.shouldBlock ? 'block' : 'allow'})`,\n `Explanation: ${reasoning.original.explanation}`,\n `Recommendation: ${reasoning.original.recommendation}`,\n `Plain summary: ${reasoning.summary}`,\n `What I found: ${reasoning.whatIFound}`,\n `How bad: ${reasoning.howBad}`,\n `What to do: ${reasoning.whatToDo}`\n ].join('\\n');\n\n return {\n content: [{\n type: 'text',\n text: summary\n }]\n };\n } catch (error) {\n const friendly = formatFriendlyError(error);\n return { content: [{ type: 'text', text: friendly.userMessage }] };\n }\n }\n}\n","import path from 'node:path';\n\nimport { ContextGraph } from '../context/graph.js';\nimport type { FileNodeData } from '../context/nodes.js';\nimport { exportToJson } from '../context/sync.js';\nimport { IncidentIndex } from '../context/incident-index.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\nimport { processIncident } from '../extraction/pipeline.js';\nimport type { ExtractedSignal } from '../types/signal.js';\n\nexport interface TellToolInput {\n description: string;\n directory?: string;\n}\n\nimport type { RiskLevel } from '../types/index.js';\n\nfunction escalateRisk(level: RiskLevel | undefined): RiskLevel {\n if (level === 'low') return 'medium';\n if (level === 'medium') return 'high';\n if (level === 'high') return 'critical';\n return 'critical';\n}\n\nfunction extractFilePathsFromDescription(description: string): string[] {\n const matches = description.match(/[\\\\w./_-]+\\\\.(ts|tsx|js|jsx|mjs|cjs)/gi);\n if (!matches) return [];\n const unique = new Set<string>();\n matches.forEach((m) => unique.add(m.replace(/^\\.\\/+/, '')));\n return Array.from(unique);\n}\n\nexport class TrieTellTool {\n async execute(input: TellToolInput): Promise<any> {\n try {\n const description = input.description?.trim();\n if (!description) {\n return { content: [{ type: 'text', text: 'description is required' }] };\n }\n\n const projectPath = input.directory || getWorkingDirectory(undefined, true);\n const graph = new ContextGraph(projectPath);\n const now = new Date().toISOString();\n const change = (await graph.getRecentChanges(1))[0];\n const linkedFiles = new Set<string>();\n\n // === NEW: Extract structured signals from incident description ===\n console.log('\\n🧠 Processing incident with signal extraction...');\n let extractedSignal: ExtractedSignal | null = null;\n \n try {\n const apiKey = process.env.ANTHROPIC_API_KEY;\n const options: { workingDirectory: string; anthropicApiKey?: string } = {\n workingDirectory: projectPath,\n };\n if (apiKey) {\n options.anthropicApiKey = apiKey;\n }\n extractedSignal = await processIncident(description, options);\n } catch (error) {\n console.warn('⚠️ Signal extraction failed, continuing with basic incident tracking:', error);\n }\n\n const incident = await graph.addNode('incident', {\n description,\n severity: 'major',\n affectedUsers: null,\n duration: null,\n timestamp: now,\n resolved: false,\n resolution: null,\n fixChangeId: change?.id ?? null,\n reportedVia: 'manual'\n });\n\n if (change) {\n await graph.addEdge(change.id, incident.id, 'leadTo');\n await graph.addEdge(incident.id, change.id, 'causedBy');\n\n for (const filePath of change.data.files) {\n linkedFiles.add(filePath);\n const fileNode = await graph.getNode('file', path.resolve(projectPath, filePath));\n if (fileNode) {\n const data = fileNode.data as FileNodeData;\n await graph.updateNode('file', fileNode.id, {\n incidentCount: (data.incidentCount ?? 0) + 1,\n riskLevel: escalateRisk(data.riskLevel)\n });\n }\n }\n }\n\n // Extract file mentions from description and add to index\n const mentionedFiles = extractFilePathsFromDescription(description);\n mentionedFiles.forEach((f) => linkedFiles.add(f));\n\n // Also add files from extracted signals\n if (extractedSignal) {\n for (const decision of extractedSignal.decisions) {\n decision.files.forEach(f => linkedFiles.add(f));\n }\n }\n\n const incidentIndex = new IncidentIndex(graph, projectPath);\n incidentIndex.addIncidentToTrie(incident, Array.from(linkedFiles));\n\n await exportToJson(graph);\n\n // Build response with extraction summary\n let responseText = `Incident recorded${change ? ` and linked to change ${change.id}` : ''}.`;\n \n if (extractedSignal) {\n const counts = [\n extractedSignal.decisions.length > 0 ? `${extractedSignal.decisions.length} decision(s)` : null,\n extractedSignal.facts.length > 0 ? `${extractedSignal.facts.length} fact(s)` : null,\n extractedSignal.blockers.length > 0 ? `${extractedSignal.blockers.length} blocker(s)` : null,\n extractedSignal.questions.length > 0 ? `${extractedSignal.questions.length} question(s)` : null,\n ].filter(Boolean).join(', ');\n \n if (counts) {\n responseText += `\\n\\n📊 Extracted and stored: ${counts}`;\n }\n }\n\n return {\n content: [{\n type: 'text',\n text: responseText\n }]\n };\n } catch (error) {\n const friendly = formatFriendlyError(error);\n return { content: [{ type: 'text', text: friendly.userMessage }] };\n }\n }\n}\n","import path from 'node:path';\n\nimport { ContextGraph } from '../context/graph.js';\nimport { importFromJson } from '../context/sync.js';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\n\nasync function removeOrphanEdges(graph: ContextGraph): Promise<number> {\n const nodes = await graph.listNodes();\n const ids = new Set(nodes.map((n) => n.id));\n const edges = await graph.listEdges();\n let removed = 0;\n for (const edge of edges) {\n if (!ids.has(edge.from_id) || !ids.has(edge.to_id)) {\n await graph.deleteEdge(edge.id);\n removed++;\n }\n }\n return removed;\n}\n\nexport interface ReconcileToolInput {\n directory?: string;\n source?: string;\n}\n\nexport class TrieReconcileTool {\n async execute(input: ReconcileToolInput = {}): Promise<any> {\n try {\n const projectPath = input.directory || getWorkingDirectory(undefined, true);\n const sourcePath = input.source ?? path.join(getTrieDirectory(projectPath), 'context.json');\n\n const graph = new ContextGraph(projectPath);\n await importFromJson(graph, '', sourcePath);\n const removed = await removeOrphanEdges(graph);\n\n return {\n content: [{\n type: 'text',\n text: `Reconciled context from ${sourcePath}. Removed ${removed} orphaned edges.`\n }]\n };\n } catch (error) {\n const friendly = formatFriendlyError(error);\n return { content: [{ type: 'text', text: friendly.userMessage }] };\n }\n }\n}\n","import { ContextGraph } from '../context/graph.js';\nimport { exportToJson } from '../context/sync.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\n\nexport interface ContextToolInput {\n directory?: string;\n}\n\nexport class TrieContextTool {\n async execute(input: ContextToolInput = {}): Promise<any> {\n try {\n const workDir = input.directory || getWorkingDirectory(undefined, true);\n const graph = new ContextGraph(workDir);\n const snapshot = await graph.getSnapshot();\n await exportToJson(graph);\n\n const summary = `Nodes: ${snapshot.nodes.length}, Edges: ${snapshot.edges.length}, Exported: ${snapshot.exported_at}`;\n\n return {\n content: [{\n type: 'text',\n text: summary\n }],\n data: snapshot\n };\n } catch (error) {\n const friendly = formatFriendlyError(error);\n return { content: [{ type: 'text', text: friendly.userMessage }] };\n }\n }\n}\n","import { ContextGraph } from '../context/graph.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\nimport { LearningEngine } from '../guardian/learning-engine.js';\n\nexport interface FeedbackInput {\n helpful: boolean;\n target?: string; // file path or tool result being rated\n note?: string;\n files?: string[]; // optional files related to the feedback\n directory?: string;\n}\n\nexport class TrieFeedbackTool {\n async execute(input: FeedbackInput): Promise<any> {\n try {\n const projectPath = input.directory || getWorkingDirectory(undefined, true);\n const graph = new ContextGraph(projectPath);\n const engine = new LearningEngine(projectPath, graph);\n\n const files = input.files || (input.target ? [input.target] : []);\n const manualFeedback = {\n helpful: input.helpful,\n files,\n ...(input.note !== undefined ? { note: input.note } : {})\n };\n\n await engine.learn({ manualFeedback });\n\n return {\n content: [{\n type: 'text',\n text: input.helpful\n ? '👍 Thanks — I will prioritize more responses like this.'\n : '👎 Understood — I will adjust future guidance.',\n }],\n };\n } catch (error) {\n const friendly = formatFriendlyError(error);\n return { content: [{ type: 'text', text: friendly.userMessage }] };\n }\n }\n}\n","import { LinearIngester } from '../ingest/linear-ingester.js';\nimport { ContextGraph } from '../context/graph.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport interface LinearSyncInput {\n directory?: string;\n}\n\nexport class LinearSyncTool {\n async execute(input: LinearSyncInput): Promise<any> {\n try {\n const workDir = input.directory || getWorkingDirectory(undefined, true);\n const graph = new ContextGraph(workDir);\n const ingester = new LinearIngester(workDir, graph);\n\n await ingester.syncTickets();\n\n return {\n content: [{\n type: 'text',\n text: '✅ Linear tickets synced successfully. Trie now has context on your active tasks.'\n }]\n };\n } catch (error: any) {\n return {\n isError: true,\n content: [{\n type: 'text',\n text: `Failed to sync Linear tickets: ${error.message}`\n }]\n };\n }\n }\n}\n","/**\n * MCP Query Tools\n * \n * Tools for agents to query decision ledger with targeted retrieval.\n * This prevents context pollution by letting agents ask for exactly\n * what they need, when they need it.\n */\n\nimport { getStorage } from '../storage/tiered-storage.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport type { ContextQuery } from '../types/signal.js';\n\nexport interface GetDecisionsInput {\n // Semantic search\n relatedTo?: string; // File path or topic\n tags?: string[];\n \n // Time filters\n since?: string; // ISO date or \"7d\", \"30d\", \"90d\"\n \n // Limits\n limit?: number;\n \n // Working directory\n directory?: string;\n}\n\nexport class TrieGetDecisionsTool {\n async execute(input: GetDecisionsInput): Promise<any> {\n const workDir = input.directory || getWorkingDirectory(undefined, true);\n const storage = getStorage(workDir);\n await storage.initialize();\n\n // Parse time filter\n let timeWindow: { start?: string; end?: string } | undefined;\n if (input.since) {\n const now = new Date();\n if (input.since.endsWith('d')) {\n const days = parseInt(input.since);\n const start = new Date(now);\n start.setDate(start.getDate() - days);\n timeWindow = { start: start.toISOString() };\n } else {\n timeWindow = { start: input.since };\n }\n }\n\n const query: ContextQuery = {\n limit: input.limit || 10\n };\n if (input.relatedTo) query.relatedTo = input.relatedTo;\n if (input.tags) query.tags = input.tags;\n if (timeWindow) query.timeWindow = timeWindow;\n\n const decisions = await storage.queryDecisions(query);\n\n return {\n content: [{\n type: 'text',\n text: this.formatDecisions(decisions)\n }]\n };\n }\n\n formatDecisions(decisions: any[]): string {\n if (decisions.length === 0) {\n return 'No decisions found matching query.';\n }\n\n let output = `Found ${decisions.length} decision(s):\\n\\n`;\n \n for (const dec of decisions) {\n const when = new Date(dec.when).toLocaleDateString();\n output += `📋 ${dec.decision}\\n`;\n output += ` Context: ${dec.context}\\n`;\n if (dec.reasoning) {\n output += ` Reasoning: ${dec.reasoning}\\n`;\n }\n if (dec.tradeoffs && dec.tradeoffs.length > 0) {\n output += ` Tradeoffs considered: ${dec.tradeoffs.join(', ')}\\n`;\n }\n output += ` When: ${when}\\n`;\n if (dec.files.length > 0) {\n output += ` Files: ${dec.files.join(', ')}\\n`;\n }\n output += ` Tags: ${dec.tags.join(', ')}\\n`;\n output += `\\n`;\n }\n\n return output;\n }\n}\n\nexport interface GetBlockersInput {\n tags?: string[];\n limit?: number;\n directory?: string;\n}\n\nexport class TrieGetBlockersTool {\n async execute(input: GetBlockersInput): Promise<any> {\n const workDir = input.directory || getWorkingDirectory(undefined, true);\n const storage = getStorage(workDir);\n await storage.initialize();\n\n const query: ContextQuery = {\n limit: input.limit || 5\n };\n if (input.tags) query.tags = input.tags;\n\n const blockers = await storage.queryBlockers(query);\n\n return {\n content: [{\n type: 'text',\n text: this.formatBlockers(blockers)\n }]\n };\n }\n\n formatBlockers(blockers: any[]): string {\n if (blockers.length === 0) {\n return '✅ No active blockers found.';\n }\n\n let output = `⚠️ Found ${blockers.length} active blocker(s):\\n\\n`;\n \n for (const blocker of blockers) {\n const impact = blocker.impact.toUpperCase();\n const emoji = blocker.impact === 'critical' ? '🔴' : \n blocker.impact === 'high' ? '🟠' : \n blocker.impact === 'medium' ? '🟡' : '🟢';\n \n output += `${emoji} [${impact}] ${blocker.blocker}\\n`;\n if (blocker.affectedAreas.length > 0) {\n output += ` Affects: ${blocker.affectedAreas.join(', ')}\\n`;\n }\n output += ` Since: ${new Date(blocker.when).toLocaleDateString()}\\n`;\n output += `\\n`;\n }\n\n return output;\n }\n}\n\nexport interface GetRelatedDecisionsInput {\n decisionId?: string;\n file?: string;\n topic?: string;\n limit?: number;\n directory?: string;\n}\n\nexport class TrieGetRelatedDecisionsTool {\n async execute(input: GetRelatedDecisionsInput): Promise<any> {\n const workDir = input.directory || getWorkingDirectory(undefined, true);\n const storage = getStorage(workDir);\n await storage.initialize();\n\n // If decisionId provided, find its related decisions\n // For now, use tags/files as proxy for \"related\"\n \n const query: ContextQuery = {\n limit: input.limit || 5\n };\n const relatedTo = input.file || input.topic;\n if (relatedTo) query.relatedTo = relatedTo;\n\n const decisions = await storage.queryDecisions(query);\n\n return {\n content: [{\n type: 'text',\n text: new TrieGetDecisionsTool().formatDecisions(decisions)\n }]\n };\n }\n\n}\n\nexport interface QueryContextInput {\n query: string;\n type?: 'decisions' | 'blockers' | 'facts' | 'questions' | 'all';\n limit?: number;\n directory?: string;\n}\n\nexport class TrieQueryContextTool {\n async execute(input: QueryContextInput): Promise<any> {\n const workDir = input.directory || getWorkingDirectory(undefined, true);\n const storage = getStorage(workDir);\n await storage.initialize();\n\n // Simple keyword-based search for now\n // TODO: Add semantic search with embeddings\n \n const keywords = input.query.toLowerCase().split(/\\s+/);\n \n let output = `Query: \"${input.query}\"\\n\\n`;\n\n if (!input.type || input.type === 'decisions' || input.type === 'all') {\n const decisions = await storage.queryDecisions({ limit: input.limit || 5 });\n const matches = decisions.filter(d => \n keywords.some(kw => \n d.decision.toLowerCase().includes(kw) ||\n d.context.toLowerCase().includes(kw) ||\n d.tags.some(t => t.toLowerCase().includes(kw))\n )\n );\n \n if (matches.length > 0) {\n output += `📋 DECISIONS (${matches.length}):\\n`;\n output += new TrieGetDecisionsTool().formatDecisions(matches);\n output += '\\n';\n }\n }\n\n if (!input.type || input.type === 'blockers' || input.type === 'all') {\n const blockers = await storage.queryBlockers({ limit: input.limit || 5 });\n const matches = blockers.filter(b =>\n keywords.some(kw =>\n b.blocker.toLowerCase().includes(kw) ||\n b.tags.some(t => t.toLowerCase().includes(kw))\n )\n );\n\n if (matches.length > 0) {\n output += `⚠️ BLOCKERS (${matches.length}):\\n`;\n output += new TrieGetBlockersTool().formatBlockers(matches);\n }\n }\n\n return {\n content: [{\n type: 'text',\n text: output.trim() || 'No matches found.'\n }]\n };\n }\n}\n","import { TrieScanTool } from '../tools/scan.js';\nimport { TrieFixTool } from '../tools/fix.js';\nimport { TrieExplainTool } from '../tools/explain.js';\nimport { TrieTestTool } from '../tools/test.js';\nimport { TrieWatchTool } from '../tools/watch.js';\nimport { TriePRReviewTool } from '../tools/pr-review.js';\nimport { TrieProjectInfoTool } from '../tools/project-info.js';\nimport { TrieInitTool } from '../tools/init.js';\nimport { TrieMemorySearchTool } from '../tools/memory-search.js';\nimport { handleCheckpointTool, type CheckpointToolInput } from '../tools/checkpoint.js';\nimport { TrieCheckTool } from '../tools/check.js';\nimport { TrieTellTool } from '../tools/tell.js';\nimport { TrieReconcileTool } from '../tools/reconcile.js';\nimport { TrieContextTool } from '../tools/context.js';\nimport { TrieFeedbackTool } from '../tools/feedback.js';\nimport { LinearSyncTool } from '../tools/linear-sync.js';\nimport { \n TrieGetDecisionsTool, \n TrieGetBlockersTool, \n TrieGetRelatedDecisionsTool,\n TrieQueryContextTool \n} from '../tools/query-tools.js';\n\nclass TrieCheckpointTool {\n async execute(input: CheckpointToolInput): Promise<any> {\n const result = await handleCheckpointTool(input);\n return {\n content: [{\n type: 'text',\n text: result\n }]\n };\n }\n}\n\nexport interface ToolDefinition {\n name: string;\n description: string;\n inputSchema: Record<string, any>;\n _meta?: {\n ui?: {\n resourceUri: string;\n };\n };\n}\n\nexport class ToolRegistry {\n private tools: Map<string, any> = new Map();\n private definitions: ToolDefinition[] = [];\n\n constructor() {\n this.initializeTools();\n this.defineToolSchemas();\n }\n\n private initializeTools() {\n // Initialize tool instances\n this.tools.set('scan', new TrieScanTool());\n this.tools.set('fix', new TrieFixTool());\n this.tools.set('explain', new TrieExplainTool());\n this.tools.set('test', new TrieTestTool());\n this.tools.set('watch', new TrieWatchTool());\n this.tools.set('pr_review', new TriePRReviewTool());\n this.tools.set('project', new TrieProjectInfoTool());\n this.tools.set('init', new TrieInitTool());\n this.tools.set('memory', new TrieMemorySearchTool());\n this.tools.set('checkpoint', new TrieCheckpointTool());\n this.tools.set('check', new TrieCheckTool());\n this.tools.set('tell', new TrieTellTool());\n this.tools.set('reconcile', new TrieReconcileTool());\n this.tools.set('context', new TrieContextTool());\n this.tools.set('feedback', new TrieFeedbackTool());\n this.tools.set('ok', new TrieFeedbackTool());\n this.tools.set('bad', new TrieFeedbackTool());\n this.tools.set('linear_sync', new LinearSyncTool());\n \n // Query tools for decision ledger\n this.tools.set('get_decisions', new TrieGetDecisionsTool());\n this.tools.set('get_blockers', new TrieGetBlockersTool());\n this.tools.set('get_related_decisions', new TrieGetRelatedDecisionsTool());\n this.tools.set('query_context', new TrieQueryContextTool());\n }\n\n private defineToolSchemas() {\n this.definitions = [\n {\n name: 'trie_scan',\n description: 'Scan code with intelligent agent selection. Scans entire codebase if no files specified. Auto-updates .trie/AGENTS.md with results. Alias: scan',\n inputSchema: {\n type: 'object',\n properties: {\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Files to scan (absolute paths). If empty, scans entire codebase.'\n },\n directory: {\n type: 'string',\n description: 'Directory to scan (if files not specified). Defaults to current working directory.'\n },\n context: {\n type: 'object',\n properties: {\n changeType: {\n type: 'string',\n enum: ['ui', 'api', 'database', 'auth', 'payment', 'general']\n },\n isNewFeature: { type: 'boolean' },\n touchesUserData: { type: 'boolean' }\n }\n },\n forceAgents: {\n type: 'array',\n items: { type: 'string' },\n description: 'Manually specify agents to run (overrides triaging)'\n },\n parallel: {\n type: 'boolean',\n description: 'Run agents in parallel (default true)'\n },\n cache: {\n type: 'boolean',\n description: 'Enable scan result caching (default true)'\n },\n maxConcurrency: {\n type: 'number',\n description: 'Max parallel agents'\n },\n timeoutMs: {\n type: 'number',\n description: 'Agent timeout in milliseconds'\n },\n streaming: {\n type: 'boolean',\n description: 'Stream progress updates'\n },\n interactive: {\n type: 'boolean',\n description: 'Enable interactive CLI dashboard (TTY only)'\n },\n format: {\n type: 'string',\n enum: ['text', 'json'],\n description: 'Output format for optional file output'\n },\n output: {\n type: 'string',\n description: 'Output file path when format is json'\n },\n workers: {\n type: 'boolean',\n description: 'Use worker threads for parallel execution'\n }\n }\n } as const,\n // MCP Apps: Interactive scan dashboard\n _meta: {\n ui: { resourceUri: 'ui://trie/scan-dashboard' }\n },\n },\n {\n name: 'trie',\n description: 'Quick menu of available Trie commands. TIP: Read trie://context first for project state and priorities. Call with `action` to run directly.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n description: 'Optional quick action: scan, security, legal, bugs, types, devops, architecture, ux, clean, soc2, performance, e2e, visual_qa, data_flow, agent_smith, pr_review, watch, fix, explain'\n },\n agent: {\n type: 'string',\n description: 'Agent key when action=agent or when using a custom skill name'\n },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Files to scan (absolute or relative)'\n },\n directory: {\n type: 'string',\n description: 'Directory to scan (defaults to detected workspace)'\n },\n context: {\n type: 'object',\n properties: {\n changeType: {\n type: 'string',\n enum: ['ui', 'api', 'database', 'auth', 'payment', 'general']\n },\n isNewFeature: { type: 'boolean' },\n touchesUserData: { type: 'boolean' }\n }\n }\n }\n } as const,\n },\n {\n name: 'trie_fix',\n description: 'Apply high-confidence fixes to code. Alias: fix',\n inputSchema: {\n type: 'object',\n properties: {\n issueIds: {\n type: 'array',\n items: { type: 'string' },\n description: 'Specific issues to fix (empty = all high-confidence)'\n },\n autoApprove: {\n type: 'boolean',\n description: 'Skip human review for high-confidence fixes'\n }\n }\n } as const,\n },\n {\n name: 'trie_explain',\n description: 'Explain code, issues, or changes in plain language. Alias: explain',\n inputSchema: {\n type: 'object',\n properties: {\n type: {\n type: 'string',\n enum: ['code', 'issue', 'change', 'risk']\n },\n target: {\n type: 'string',\n description: 'What to explain (file path, issue ID, etc.)'\n }\n },\n required: ['type', 'target']\n } as const,\n },\n {\n name: 'trie_feedback',\n description: 'Record quick feedback about a warning or suggestion (thumbs up/down). Alias: trie_ok, trie_bad',\n inputSchema: {\n type: 'object',\n properties: {\n helpful: { type: 'boolean', description: 'true for 👍, false for 👎' },\n target: { type: 'string', description: 'Optional file or item being rated' },\n note: { type: 'string', description: 'Optional short note about why' },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Optional related files (absolute or relative)'\n },\n directory: { type: 'string', description: 'Working directory (defaults to auto-detected)' }\n },\n required: ['helpful']\n } as const,\n },\n {\n name: 'trie_check',\n description: 'Run Trie risk check on current changes. Modes: quick, full, offline.',\n inputSchema: {\n type: 'object',\n properties: {\n directory: { type: 'string' },\n files: { type: 'array', items: { type: 'string' } },\n mode: { type: 'string', enum: ['quick', 'full', 'offline'] }\n }\n }\n },\n {\n name: 'trie_tell',\n description: 'Report an incident so Trie can learn.',\n inputSchema: {\n type: 'object',\n properties: {\n description: { type: 'string' },\n directory: { type: 'string' }\n },\n required: ['description']\n }\n },\n {\n name: 'trie_reconcile',\n description: 'Re-sync context graph from context.json and clean orphaned edges.',\n inputSchema: {\n type: 'object',\n properties: {\n directory: { type: 'string' },\n source: { type: 'string' }\n }\n }\n },\n {\n name: 'trie_context',\n description: 'Return current context snapshot (nodes/edges) and export context.json.',\n inputSchema: {\n type: 'object',\n properties: {\n directory: { type: 'string' }\n }\n }\n },\n {\n name: 'trie_test',\n description: 'Generate or reason about tests. Alias: test',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['generate', 'coverage', 'suggest', 'run'],\n description: 'Test action to perform'\n },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Target source files'\n },\n framework: {\n type: 'string',\n description: 'Optional framework hint (jest, vitest, playwright, etc.)'\n },\n style: {\n type: 'string',\n description: 'Test style (unit, integration, e2e). Defaults to unit.'\n }\n },\n required: ['action', 'files']\n } as const,\n },\n {\n name: 'trie_watch',\n description: 'Autonomous watch mode. Alias: watch',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['start', 'stop', 'status', 'issues'],\n description: 'Watch action'\n },\n directory: {\n type: 'string',\n description: 'Workspace directory to watch (optional, auto-detected)'\n },\n debounceMs: {\n type: 'number',\n description: 'Debounce time for scans (ms)'\n }\n },\n required: ['action']\n } as const,\n },\n {\n name: 'trie_project',\n description: 'View and manage project information (.trie/PROJECT.md). Store project context for AI assistants. Alias: project',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['view', 'init', 'update', 'append', 'sections', 'raw'],\n description: 'Action: view (default), init (create template), update (replace section), append (add to section), sections (list), raw (full file)'\n },\n section: {\n type: 'string',\n description: 'Section name (e.g., \"Project Overview\", \"Technology Stack\", \"AI Instructions\")'\n },\n content: {\n type: 'string',\n description: 'Content for update/append actions'\n },\n directory: {\n type: 'string',\n description: 'Project directory (defaults to current workspace)'\n }\n }\n } as const,\n },\n {\n name: 'trie_init',\n description: 'Initialize bootstrap files (.trie/RULES.md, .trie/TEAM.md, .trie/BOOTSTRAP.md). Detects stack and suggests skills.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['init', 'status', 'complete', 'context'],\n description: 'Action: init (create files), status (check state), complete (finish bootstrap), context (get injected content)'\n },\n directory: {\n type: 'string',\n description: 'Project directory (defaults to current workspace)'\n },\n force: {\n type: 'boolean',\n description: 'Overwrite existing files'\n },\n skipBootstrap: {\n type: 'boolean',\n description: 'Skip creating BOOTSTRAP.md'\n }\n }\n } as const,\n },\n {\n name: 'trie_memory',\n description: 'Search and manage issue memory. Find similar issues, view stats, search across projects, and purge old issues.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['search', 'stats', 'recent', 'similar', 'resolve', 'global', 'purge'],\n description: 'Action: search (find issues), stats (show statistics), recent (recent issues), similar (find similar), resolve (mark resolved), global (cross-project), purge (free up memory)'\n },\n query: {\n type: 'string',\n description: 'Search query for search/similar/global actions'\n },\n issueId: {\n type: 'string',\n description: 'Issue ID for resolve action'\n },\n limit: {\n type: 'number',\n description: 'Maximum results to return'\n },\n severity: {\n type: 'array',\n items: { type: 'string' },\n description: 'Filter by severity levels'\n },\n agent: {\n type: 'string',\n description: 'Filter by agent name'\n },\n includeResolved: {\n type: 'boolean',\n description: 'Include resolved issues in search'\n },\n directory: {\n type: 'string',\n description: 'Project directory (defaults to current workspace)'\n },\n purgeStrategy: {\n type: 'string',\n enum: ['smart', 'resolved', 'old', 'all'],\n description: 'Purge strategy: smart (remove resolved & old low-priority), resolved (all resolved), old (older than daysOld), all (clear all)'\n },\n daysOld: {\n type: 'number',\n description: 'Days threshold for old purge strategy (default 90)'\n }\n }\n } as const,\n // MCP Apps: Interactive memory viewer\n _meta: {\n ui: { resourceUri: 'ui://trie/memory-viewer' }\n },\n },\n {\n name: 'trie_checkpoint',\n description: 'Save a context checkpoint without running a full scan. Quick save for your current work state.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['save', 'list', 'last'],\n description: 'Action: save (create checkpoint), list (show recent), last (show last checkpoint)'\n },\n message: {\n type: 'string',\n description: 'Checkpoint message (what you were working on)'\n },\n notes: {\n type: 'string',\n description: 'Additional notes'\n },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Files to associate with this checkpoint'\n }\n },\n required: ['action']\n } as const,\n },\n // Add remaining tool definitions...\n this.createSpecialAgentDefinitions(),\n ].flat();\n }\n\n private createSpecialAgentDefinitions(): ToolDefinition[] {\n return [\n {\n name: 'trie_visual_qa_browser',\n description: 'Capture screenshots at mobile/tablet/desktop viewports for visual QA. Alias: visual_qa_browser',\n inputSchema: {\n type: 'object',\n properties: {\n url: { type: 'string', description: 'URL to screenshot' },\n port: { type: 'number', description: 'Specific port to check' },\n waitForSelector: { type: 'string', description: 'CSS selector to wait for' },\n waitMs: { type: 'number', description: 'Additional wait time' }\n }\n } as const,\n // MCP Apps: Interactive visual QA gallery\n _meta: {\n ui: { resourceUri: 'ui://trie/visual-qa' }\n },\n },\n {\n name: 'trie_pr_review',\n description: '🔍 Interactive PR review: walks through changes file-by-file. Alias: pr_review',\n inputSchema: {\n type: 'object',\n properties: {\n pr: { type: 'string', description: 'PR number to review' },\n worktree: { type: 'string', description: 'Path to worktree directory' },\n mode: {\n type: 'string',\n enum: ['own', 'others'],\n description: 'Review mode'\n },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Specific files to review'\n }\n }\n } as const,\n // MCP Apps: Interactive PR review UI\n _meta: {\n ui: { resourceUri: 'ui://trie/pr-review' }\n },\n },\n {\n name: 'trie_linear_sync',\n description: 'Sync active Linear tickets to build context for JIT defect prediction. Alias: linear_sync',\n inputSchema: {\n type: 'object',\n properties: {\n directory: { type: 'string', description: 'Project directory' }\n }\n }\n },\n {\n name: 'trie_get_decisions',\n description: 'Query decisions from decision ledger with targeted retrieval. Prevents context pollution by returning only relevant decisions.',\n inputSchema: {\n type: 'object',\n properties: {\n relatedTo: { type: 'string', description: 'File path or topic to find related decisions' },\n tags: { type: 'array', items: { type: 'string' }, description: 'Filter by tags' },\n since: { type: 'string', description: 'Time filter: ISO date or \"7d\", \"30d\", \"90d\"' },\n limit: { type: 'number', description: 'Max results (default 10)' },\n directory: { type: 'string', description: 'Working directory' }\n }\n }\n },\n {\n name: 'trie_get_blockers',\n description: 'Get active blockers from decision ledger. Returns only unresolved blockers to avoid noise.',\n inputSchema: {\n type: 'object',\n properties: {\n tags: { type: 'array', items: { type: 'string' }, description: 'Filter by tags' },\n limit: { type: 'number', description: 'Max results (default 5)' },\n directory: { type: 'string', description: 'Working directory' }\n }\n }\n },\n {\n name: 'trie_get_related_decisions',\n description: 'Find decisions related to a specific decision, file, or topic. Targeted context retrieval.',\n inputSchema: {\n type: 'object',\n properties: {\n decisionId: { type: 'string', description: 'Decision ID to find related decisions' },\n file: { type: 'string', description: 'File path to find related decisions' },\n topic: { type: 'string', description: 'Topic to find related decisions' },\n limit: { type: 'number', description: 'Max results (default 5)' },\n directory: { type: 'string', description: 'Working directory' }\n }\n }\n },\n {\n name: 'trie_query_context',\n description: 'Query decision ledger with natural language. Returns targeted signal, not full dump.',\n inputSchema: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'Natural language query' },\n type: { \n type: 'string', \n enum: ['decisions', 'blockers', 'facts', 'questions', 'all'],\n description: 'Type of context to query (default: all)'\n },\n limit: { type: 'number', description: 'Max results per type (default 5)' },\n directory: { type: 'string', description: 'Working directory' }\n },\n required: ['query']\n }\n }\n ];\n }\n\n getTool(name: string): any {\n return this.tools.get(name);\n }\n\n getAllTools(): ToolDefinition[] {\n return this.definitions;\n }\n\n getToolNames(): string[] {\n return Array.from(this.tools.keys());\n }\n\n hasTool(name: string): boolean {\n return this.tools.has(name);\n }\n}","import { readdir, readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join, dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport { getSkillRegistry } from '../skills/built-in/registry.js';\nimport { loadConfig } from '../config/loader.js';\nimport { getContextForAI, loadContextState } from '../utils/context-state.js';\nimport { loadProjectInfo, projectInfoExists } from '../utils/project-info.js';\nimport { listInstalledSkills } from '../skills/installer.js';\nimport { loadBootstrapContext, loadRules, loadTeamInfo } from '../bootstrap/index.js';\nimport { getMemoryStats, getRecentIssues } from '../memory/issue-store.js';\nimport { getGlobalMemoryStats, findCrossProjectPatterns } from '../memory/global-memory.js';\n\nexport interface Resource {\n uri: string;\n name: string;\n description?: string;\n mimeType?: string;\n}\n\nexport interface ResourceContent {\n contents: Array<{\n uri: string;\n mimeType?: string;\n text: string;\n }>;\n}\n\n// UI App definitions for MCP Apps\nconst UI_APPS = {\n 'scan-dashboard': {\n name: 'Scan Dashboard',\n description: 'Interactive dashboard for viewing and managing scan results',\n },\n 'memory-viewer': {\n name: 'Memory Viewer',\n description: 'Search and browse issue history with context preview',\n },\n 'pr-review': {\n name: 'PR Review',\n description: 'File-by-file diff viewer with inline actions',\n },\n 'visual-qa': {\n name: 'Visual QA',\n description: 'Screenshot gallery with viewport comparison',\n },\n} as const;\n\ntype UIAppId = keyof typeof UI_APPS;\n\nexport class ResourceManager {\n private skillRegistry = getSkillRegistry();\n\n /**\n * Get all available resources dynamically\n */\n async getAvailableResources(): Promise<Resource[]> {\n const resources: Resource[] = [];\n\n // Static resources\n resources.push(\n {\n uri: 'trie://context',\n name: 'AI Context (Consolidated)',\n description: 'Single source of truth: project state, coding rules, recent issues, and cross-project patterns. Read this first.',\n mimeType: 'text/markdown',\n },\n {\n uri: 'trie://project',\n name: 'Project Information',\n description: 'User-defined project context (description, conventions, architecture, AI instructions)',\n mimeType: 'text/markdown',\n },\n {\n uri: 'trie://context/state',\n name: 'Context State',\n description: 'Detailed context state with scan history and priorities',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://skills',\n name: 'Available Skills',\n description: 'List of all available Trie skills (built-in and custom)',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://config',\n name: 'Trie Configuration',\n description: 'Current Trie configuration settings',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://cache/stats',\n name: 'Cache Statistics',\n description: 'Trie scan cache statistics and performance metrics',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://signatures',\n name: 'Vulnerability Signatures',\n description: 'Summary of loaded vulnerability detection signatures',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://skills/installed',\n name: 'Installed Skills',\n description: 'External skills installed from skills.sh that the guardian can apply',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://bootstrap',\n name: 'Bootstrap Status',\n description: 'Bootstrap file status and project setup context',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://rules',\n name: 'Project Rules',\n description: 'User-defined coding standards from .trie/RULES.md',\n mimeType: 'text/markdown',\n },\n {\n uri: 'trie://team',\n name: 'Team Info',\n description: 'Team ownership and escalation from .trie/TEAM.md',\n mimeType: 'text/markdown',\n },\n {\n uri: 'trie://memory',\n name: 'Issue Memory',\n description: 'Issue memory statistics and recent issues',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://memory/global',\n name: 'Global Memory',\n description: 'Cross-project patterns and statistics',\n mimeType: 'application/json',\n }\n );\n\n // Dynamic resources: scan reports\n resources.push(...await this.getScanReportResources());\n\n // Dynamic resources: custom skills\n resources.push(...await this.getCustomSkillResources());\n\n // UI App resources (MCP Apps)\n resources.push(...this.getUIAppResources());\n\n return resources;\n }\n\n private async getScanReportResources(): Promise<Resource[]> {\n try {\n const reportsDir = join(getWorkingDirectory(undefined, true), 'trie-reports');\n const files = await readdir(reportsDir);\n const reportFiles = files.filter(f => f.endsWith('.txt') || f.endsWith('.json'));\n\n return reportFiles.slice(0, 10).map(file => ({\n uri: `trie://reports/${file}`,\n name: `Scan Report: ${file}`,\n description: `Trie scan report from ${file}`,\n mimeType: file.endsWith('.json') ? 'application/json' : 'text/plain',\n }));\n } catch {\n return []; // No reports directory yet\n }\n }\n\n private async getCustomSkillResources(): Promise<Resource[]> {\n try {\n await this.skillRegistry.loadCustomSkills();\n const customSkills = this.skillRegistry.getCustomSkills();\n\n return customSkills.map(skill => ({\n uri: `trie://skills/custom/${skill.name}`,\n name: `Custom Skill: ${skill.name}`,\n description: skill.description,\n mimeType: 'application/json',\n }));\n } catch {\n return []; // No custom skills\n }\n }\n\n /**\n * Read content for a specific resource\n */\n async readResourceContent(uri: string): Promise<ResourceContent> {\n // Handle UI App resources (MCP Apps)\n if (uri.startsWith('ui://trie/')) {\n const appId = uri.replace('ui://trie/', '');\n return await this.getUIAppResource(uri, appId);\n }\n\n const parsedUri = uri.replace('trie://', '');\n\n // Handle AI context (read this first!)\n if (parsedUri === 'context') {\n return await this.getContextResource(uri);\n }\n\n // Handle project info (user-defined context)\n if (parsedUri === 'project') {\n return await this.getProjectResource(uri);\n }\n\n // Handle context state (detailed JSON)\n if (parsedUri === 'context/state') {\n return await this.getContextStateResource(uri);\n }\n\n // Handle built-in skills list\n if (parsedUri === 'skills') {\n return await this.getBuiltInSkillsResource(uri);\n }\n\n // Handle specific custom skill\n if (parsedUri.startsWith('skills/custom/')) {\n return await this.getCustomSkillResource(uri, parsedUri);\n }\n\n // Handle configuration\n if (parsedUri === 'config') {\n return await this.getConfigResource(uri);\n }\n\n // Handle cache stats\n if (parsedUri === 'cache/stats') {\n return await this.getCacheStatsResource(uri);\n }\n\n // Handle vulnerability signatures\n if (parsedUri === 'signatures') {\n return await this.getSignaturesResource(uri);\n }\n\n // Handle installed skills\n if (parsedUri === 'skills/installed') {\n return await this.getInstalledSkillsResource(uri);\n }\n\n // Handle bootstrap status\n if (parsedUri === 'bootstrap') {\n return await this.getBootstrapResource(uri);\n }\n\n // Handle rules\n if (parsedUri === 'rules') {\n return await this.getRulesResource(uri);\n }\n\n // Handle team info\n if (parsedUri === 'team') {\n return await this.getTeamResource(uri);\n }\n\n // Handle memory\n if (parsedUri === 'memory') {\n return await this.getMemoryResource(uri);\n }\n\n // Handle global memory\n if (parsedUri === 'memory/global') {\n return await this.getGlobalMemoryResource(uri);\n }\n\n // Handle scan reports\n if (parsedUri.startsWith('reports/')) {\n return await this.getScanReportResource(uri, parsedUri);\n }\n\n throw new Error(`Unknown resource: ${uri}`);\n }\n\n /**\n * Get UI App resources for MCP Apps\n */\n private getUIAppResources(): Resource[] {\n return Object.entries(UI_APPS).map(([id, app]) => ({\n uri: `ui://trie/${id}`,\n name: app.name,\n description: app.description,\n mimeType: 'text/html;profile=mcp-app',\n }));\n }\n\n /**\n * Read UI App resource content (bundled HTML)\n */\n private async getUIAppResource(uri: string, appId: string): Promise<ResourceContent> {\n // Get the directory of this file to find the dist/ui folder\n const currentFile = fileURLToPath(import.meta.url);\n const distDir = dirname(dirname(currentFile)); // Go up from server/ to dist/\n const uiDir = join(distDir, 'ui');\n const htmlPath = join(uiDir, `${appId}.html`);\n\n try {\n if (!existsSync(htmlPath)) {\n // Return a fallback HTML if the bundled app doesn't exist yet\n return {\n contents: [{\n uri,\n mimeType: 'text/html;profile=mcp-app',\n text: this.getFallbackUIHtml(appId),\n }],\n };\n }\n\n const content = await readFile(htmlPath, 'utf-8');\n return {\n contents: [{\n uri,\n mimeType: 'text/html;profile=mcp-app',\n text: content,\n }],\n };\n } catch (error) {\n return {\n contents: [{\n uri,\n mimeType: 'text/html;profile=mcp-app',\n text: this.getFallbackUIHtml(appId),\n }],\n };\n }\n }\n\n /**\n * Generate fallback HTML for UI apps that haven't been built yet\n */\n private getFallbackUIHtml(appId: string): string {\n const app = UI_APPS[appId as UIAppId];\n const title = app?.name || 'Trie UI';\n const description = app?.description || 'Loading...';\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${title} - Trie</title>\n <style>\n :root {\n --bg: #0d1117;\n --surface: #161b22;\n --border: #30363d;\n --text: #e6edf3;\n --text-muted: #8b949e;\n --primary: #58a6ff;\n }\n * { box-sizing: border-box; margin: 0; padding: 0; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;\n background: var(--bg);\n color: var(--text);\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n padding: 24px;\n }\n .container {\n text-align: center;\n max-width: 400px;\n }\n h1 {\n font-size: 24px;\n margin-bottom: 8px;\n }\n p {\n color: var(--text-muted);\n margin-bottom: 24px;\n }\n .status {\n display: inline-flex;\n align-items: center;\n gap: 8px;\n padding: 8px 16px;\n background: var(--surface);\n border: 1px solid var(--border);\n border-radius: 8px;\n color: var(--primary);\n }\n .spinner {\n width: 16px;\n height: 16px;\n border: 2px solid var(--border);\n border-top-color: var(--primary);\n border-radius: 50%;\n animation: spin 0.8s linear infinite;\n }\n @keyframes spin { to { transform: rotate(360deg); } }\n </style>\n</head>\n<body>\n <div class=\"container\">\n <h1>${title}</h1>\n <p>${description}</p>\n <div class=\"status\">\n <div class=\"spinner\"></div>\n <span>Connecting to Trie...</span>\n </div>\n </div>\n <script type=\"module\">\n // MCP Apps SDK connection\n import { App } from \"@modelcontextprotocol/ext-apps\";\n \n const app = new App();\n await app.connect();\n \n app.ontoolresult = (result) => {\n document.querySelector('.status span').textContent = 'Connected! Waiting for data...';\n console.log('Received tool result:', result);\n };\n </script>\n</body>\n</html>`;\n }\n\n private async getContextResource(uri: string): Promise<ResourceContent> {\n const workDir = getWorkingDirectory(undefined, true);\n const state = await loadContextState();\n \n // Build executive summary first\n const summary: string[] = [\n '# Trie Context',\n '',\n '> Quick reference for AI assistants. Detailed sections below.',\n '',\n '## Quick Status',\n '',\n `| Metric | Value |`,\n `|--------|-------|`,\n `| Health Score | ${state.healthScore}% |`,\n `| Last Scan | ${state.lastScan ? new Date(state.lastScan.timestamp).toLocaleDateString() : 'Never'} |`,\n `| Critical Issues | ${state.lastScan?.issues.critical ?? 0} |`,\n `| Total Issues | ${state.lastScan?.issues.total ?? 0} |`,\n '',\n ];\n \n // Add top priorities (max 3)\n if (state.activePriorities.length > 0) {\n summary.push('## Top Priorities', '');\n state.activePriorities.slice(0, 3).forEach((p, i) => {\n summary.push(`${i + 1}. ${p}`);\n });\n summary.push('');\n }\n \n // Add recent issues from memory (max 3, one-liners)\n try {\n const recentIssues = await getRecentIssues({ workDir, limit: 3 });\n if (recentIssues.length > 0) {\n summary.push('## Recent Issues', '');\n recentIssues.forEach(i => {\n summary.push(`- [${i.severity.toUpperCase()}] ${i.issue.slice(0, 50)}... (\\`${i.file.split('/').pop()}\\`)`);\n });\n summary.push('');\n }\n } catch {\n // Memory not available\n }\n \n // Add cross-project patterns (max 2, one-liners)\n try {\n const patterns = await findCrossProjectPatterns(2);\n if (patterns.length > 0) {\n summary.push('## Watch For (seen in other projects)', '');\n patterns.slice(0, 2).forEach(p => {\n summary.push(`- ${p.pattern.slice(0, 40)}... (${p.occurrences}x across ${p.projects.length} projects)`);\n });\n summary.push('');\n }\n } catch {\n // Global memory not available\n }\n \n // Add coding rules summary (just headers)\n const rules = await loadRules(workDir);\n if (rules) {\n const ruleHeaders = rules.match(/^##?\\s+.+$/gm)?.slice(0, 5) || [];\n if (ruleHeaders.length > 0) {\n summary.push('## Coding Rules (see trie://rules for full)', '');\n ruleHeaders.forEach(h => summary.push(`- ${h.replace(/^#+\\s*/, '')}`));\n summary.push('');\n }\n }\n \n // Add available tools/capabilities\n summary.push('## Available Tools', '');\n summary.push('| Tool | Purpose |');\n summary.push('|------|---------|');\n summary.push('| `trie_scan` | Scan code with intelligent agent selection |');\n summary.push('| `trie_fix` | Generate fix recommendations |');\n summary.push('| `trie_memory` | Search issue history |');\n summary.push('| `trie_init` | Initialize bootstrap files |');\n summary.push('');\n \n // Add installed skills count\n try {\n const skills = await listInstalledSkills();\n if (skills.length > 0) {\n summary.push(`**Skills:** ${skills.length} installed (${skills.slice(0, 3).map(s => s.name).join(', ')}${skills.length > 3 ? '...' : ''})`);\n summary.push('');\n }\n } catch {\n // Skills not available\n }\n \n summary.push('---', '', '# Detailed Context', '');\n \n // Now add the full AGENTS.md\n const agentsMdPath = join(getTrieDirectory(workDir), 'AGENTS.md');\n try {\n if (existsSync(agentsMdPath)) {\n const agentsContent = await readFile(agentsMdPath, 'utf-8');\n summary.push(agentsContent);\n } else {\n const contextSummary = await getContextForAI();\n summary.push(contextSummary);\n }\n } catch {\n const contextSummary = await getContextForAI();\n summary.push(contextSummary);\n }\n \n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: summary.join('\\n'),\n }],\n };\n }\n\n private async getContextStateResource(uri: string): Promise<ResourceContent> {\n const state = await loadContextState();\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(state, null, 2),\n }],\n };\n }\n\n private async getProjectResource(uri: string): Promise<ResourceContent> {\n const workDir = getWorkingDirectory(undefined, true);\n \n if (!projectInfoExists(workDir)) {\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: `# Project Information Not Found\n\nNo \\`.trie/PROJECT.md\\` file exists in this project.\n\n## Create One\n\nUse the \\`trie_project\\` tool with action=\"init\" to create a PROJECT.md template:\n\n\\`\\`\\`\ntrie_project action=\"init\"\n\\`\\`\\`\n\nOr run from CLI:\n\\`\\`\\`\ntrie project init\n\\`\\`\\`\n\n## What is PROJECT.md?\n\nPROJECT.md is a user-defined file that stores important project context:\n- Project description and purpose\n- Technology stack\n- Architecture decisions\n- Coding conventions\n- Environment info\n- Team ownership\n- Compliance requirements\n- Special instructions for AI assistants\n\nThis information is automatically available to Claude Code, Cursor, and other AI tools.\n`,\n }],\n };\n }\n\n const content = await loadProjectInfo(workDir);\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: content || '',\n }],\n };\n }\n\n private async getBuiltInSkillsResource(uri: string): Promise<ResourceContent> {\n await this.skillRegistry.loadCustomSkills();\n const skills = this.skillRegistry.getSkillDescriptions();\n\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n totalSkills: skills.length,\n builtinCount: skills.filter(a => !a.isCustom).length,\n customCount: skills.filter(a => a.isCustom).length,\n skills: skills.map(a => ({\n name: a.name,\n description: a.description,\n type: a.isCustom ? 'custom' : 'builtin',\n })),\n }, null, 2),\n }],\n };\n }\n\n private async getCustomSkillResource(uri: string, parsedUri: string): Promise<ResourceContent> {\n const skillName = parsedUri.replace('skills/custom/', '');\n await this.skillRegistry.loadCustomSkills();\n const metadata = this.skillRegistry.getCustomSkillMetadata(skillName);\n\n if (!metadata) {\n throw new Error(`Custom skill not found: ${skillName}`);\n }\n\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(metadata, null, 2),\n }],\n };\n }\n\n private async getConfigResource(uri: string): Promise<ResourceContent> {\n const config = await loadConfig();\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(config, null, 2),\n }],\n };\n }\n\n private async getCacheStatsResource(uri: string): Promise<ResourceContent> {\n try {\n const cachePath = join(getTrieDirectory(getWorkingDirectory(undefined, true)), '.trie-cache.json');\n const cacheContent = await readFile(cachePath, 'utf-8');\n const cache = JSON.parse(cacheContent);\n\n const fileCount = Object.keys(cache.files || {}).length;\n const totalVulns = Object.values(cache.files || {}).reduce((acc: number, file: any) => {\n return acc + (file.vulnerabilities?.length || 0);\n }, 0);\n\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n version: cache.version,\n created: new Date(cache.created).toISOString(),\n lastUpdated: new Date(cache.lastUpdated).toISOString(),\n cachedFiles: fileCount,\n totalVulnerabilitiesFound: totalVulns,\n cacheAgeMinutes: Math.round((Date.now() - cache.lastUpdated) / 60000),\n }, null, 2),\n }],\n };\n } catch {\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n error: 'No cache found. Run a scan first to build the cache.',\n hint: 'Use trie_scan to scan your codebase',\n }, null, 2),\n }],\n };\n }\n }\n\n private async getSignaturesResource(uri: string): Promise<ResourceContent> {\n // Import dynamically to avoid circular deps\n const { getVulnerabilityStats } = await import('../trie/vulnerability-signatures.js');\n const { getVibeCodeStats } = await import('../trie/vibe-code-signatures.js');\n\n const vulnStats = getVulnerabilityStats();\n const vibeStats = getVibeCodeStats();\n\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n vulnerabilitySignatures: vulnStats,\n vibeCodeSignatures: vibeStats,\n totalSignatures: vulnStats.total + vibeStats.total,\n }, null, 2),\n }],\n };\n }\n\n private async getInstalledSkillsResource(uri: string): Promise<ResourceContent> {\n const skills = await listInstalledSkills();\n const state = await loadContextState();\n \n const skillsWithUsage = skills.map(skill => {\n const record = state.skills?.[skill.name];\n return {\n name: skill.name,\n description: skill.description,\n source: skill.installedFrom,\n installedAt: skill.installedAt,\n timesApplied: record?.timesApplied || 0,\n appliedBy: record?.appliedBy || [],\n lastApplied: record?.lastApplied,\n };\n });\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n totalSkills: skills.length,\n skills: skillsWithUsage,\n note: 'Skills are capabilities applied by agents, not autonomous agents themselves.',\n }, null, 2),\n }],\n };\n }\n\n private async getScanReportResource(uri: string, parsedUri: string): Promise<ResourceContent> {\n const fileName = parsedUri.replace('reports/', '');\n const reportPath = join(getWorkingDirectory(undefined, true), 'trie-reports', fileName);\n\n try {\n const content = await readFile(reportPath, 'utf-8');\n\n return {\n contents: [{\n uri,\n mimeType: fileName.endsWith('.json') ? 'application/json' : 'text/plain',\n text: content,\n }],\n };\n } catch {\n throw new Error(`Report not found: ${fileName}`);\n }\n }\n\n private async getBootstrapResource(uri: string): Promise<ResourceContent> {\n const workDir = getWorkingDirectory(undefined, true);\n const context = await loadBootstrapContext(workDir);\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n needsBootstrap: context.needsBootstrap,\n files: context.files.map(f => ({\n name: f.name,\n type: f.type,\n exists: f.exists,\n })),\n hasInjectedContent: !!context.injectedContent,\n }, null, 2),\n }],\n };\n }\n\n private async getRulesResource(uri: string): Promise<ResourceContent> {\n const rules = await loadRules();\n \n if (!rules) {\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: `# No Rules Defined\n\nNo \\`.trie/RULES.md\\` file exists in this project.\n\nUse \\`trie_init\\` to create one, or create it manually with your coding standards.\n`,\n }],\n };\n }\n\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: rules,\n }],\n };\n }\n\n private async getTeamResource(uri: string): Promise<ResourceContent> {\n const team = await loadTeamInfo();\n \n if (!team) {\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: `# No Team Info Defined\n\nNo \\`.trie/TEAM.md\\` file exists in this project.\n\nUse \\`trie_init\\` to create one, or create it manually with team ownership info.\n`,\n }],\n };\n }\n\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: team,\n }],\n };\n }\n\n private async getMemoryResource(uri: string): Promise<ResourceContent> {\n const workDir = getWorkingDirectory(undefined, true);\n const stats = await getMemoryStats(workDir);\n const recent = await getRecentIssues({ workDir, limit: 5 });\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n stats,\n recentIssues: recent.map(i => ({\n severity: i.severity,\n issue: i.issue.slice(0, 100),\n file: i.file,\n agent: i.agent,\n timestamp: i.timestamp,\n resolved: i.resolved,\n })),\n }, null, 2),\n }],\n };\n }\n\n private async getGlobalMemoryResource(uri: string): Promise<ResourceContent> {\n const stats = await getGlobalMemoryStats();\n const patterns = await findCrossProjectPatterns(2);\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n stats,\n topPatterns: patterns.slice(0, 10).map(p => ({\n pattern: p.pattern.slice(0, 80),\n severity: p.severity,\n agent: p.agent,\n occurrences: p.occurrences,\n projectCount: p.projects.length,\n hasFixApplied: !!p.fixApplied,\n })),\n }, null, 2),\n }],\n };\n }\n}","/**\n * Skills installer stub\n * Skills system has been replaced with decision ledger\n */\n\nexport interface Skill {\n name: string;\n category: string;\n description: string;\n path?: string;\n installedFrom?: string;\n installedAt?: string;\n timesApplied?: number;\n}\n\nexport interface InstallResult {\n success: boolean;\n name?: string;\n path?: string;\n error?: string;\n}\n\nexport interface CreateSkillResult {\n success: boolean;\n name?: string;\n writtenTo?: string[];\n error?: string;\n}\n\nexport async function listInstalledSkills(): Promise<Skill[]> {\n return [];\n}\n\nexport async function listGlobalSkills(): Promise<Skill[]> {\n return [];\n}\n\nexport async function installSkill(\n _repo: string, \n _skillName?: string\n): Promise<InstallResult> {\n return {\n success: false,\n error: 'Skills system has been replaced with the decision ledger'\n };\n}\n\nexport async function createSkillFromFile(\n _filePath: string\n): Promise<CreateSkillResult> {\n return {\n success: false,\n error: 'Skills system has been replaced with the decision ledger'\n };\n}\n\nexport async function removeGlobalSkill(_name: string): Promise<boolean> {\n return false;\n}\n","import { chromium, Browser, Page } from 'playwright';\nimport { createServer, Server } from 'net';\nimport { request } from 'http';\nimport { isInteractiveMode } from '../utils/progress.js';\n\n/**\n * Browser-based Visual QA Tool\n * \n * Launches a headless browser, captures screenshots at multiple viewports,\n * and returns them for Claude Vision to analyze.\n */\n\nexport interface VisualQAOptions {\n url?: string;\n port?: number;\n viewports?: ViewportConfig[];\n waitForSelector?: string;\n waitMs?: number;\n}\n\nexport interface ViewportConfig {\n name: string;\n width: number;\n height: number;\n}\n\nexport interface ScreenshotResult {\n viewport: string;\n width: number;\n height: number;\n base64: string;\n mimeType: 'image/png';\n}\n\nexport interface VisualQAResult {\n success: boolean;\n url: string;\n screenshots: ScreenshotResult[];\n error?: string;\n analysisPrompt: string;\n}\n\n// Default viewports for responsive testing\nconst DEFAULT_VIEWPORTS: ViewportConfig[] = [\n { name: 'mobile', width: 375, height: 812 }, // iPhone X\n { name: 'tablet', width: 768, height: 1024 }, // iPad\n { name: 'desktop', width: 1440, height: 900 }, // Standard desktop\n];\n\n/**\n * Find an open port on localhost by checking common dev server ports\n * Returns the first port that is both in use AND serving HTTP\n */\nasync function findOpenPort(): Promise<number | null> {\n const commonPorts = [3000, 3001, 5173, 5174, 4200, 8080, 8000, 8888, 5000, 4000];\n \n // Check ports in parallel for faster detection\n const portChecks = await Promise.all(\n commonPorts.map(async (port) => {\n const isOpen = await checkPort(port);\n return isOpen ? port : null;\n })\n );\n \n // Return the first port that's open and serving HTTP\n return portChecks.find(port => port !== null) || null;\n}\n\n/**\n * Check if a port has something listening on it AND is serving HTTP\n */\nasync function checkPort(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n // First check if port is in use\n const testServer: Server = createServer();\n let portInUse = false;\n \n testServer.once('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EADDRINUSE') {\n portInUse = true;\n // Port is in use - now verify it's serving HTTP\n testHttpPort(port).then(resolve).catch(() => resolve(false));\n } else {\n resolve(false);\n }\n });\n \n testServer.once('listening', () => {\n // Port is free - nothing running\n testServer.close();\n resolve(false);\n });\n \n // Set timeout to prevent hanging\n setTimeout(() => {\n if (!portInUse) {\n testServer.close();\n resolve(false);\n }\n }, 1000);\n \n testServer.listen(port, '127.0.0.1');\n });\n}\n\n/**\n * Verify that a port is actually serving HTTP content\n */\nasync function testHttpPort(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const req = request({\n hostname: 'localhost',\n port: port,\n path: '/',\n method: 'GET',\n timeout: 2000,\n }, (res) => {\n // If we get any HTTP response (even 404), the server is running\n resolve(res.statusCode !== undefined);\n res.on('data', () => {}); // Consume response\n res.on('end', () => {});\n });\n\n req.on('error', () => {\n // Connection refused, timeout, or other error means no HTTP server\n resolve(false);\n });\n\n req.on('timeout', () => {\n req.destroy();\n resolve(false);\n });\n\n req.end();\n });\n}\n\n/**\n * Capture screenshots at multiple viewports\n */\nasync function captureScreenshots(\n url: string,\n viewports: ViewportConfig[],\n options: { waitForSelector?: string | undefined; waitMs?: number | undefined }\n): Promise<ScreenshotResult[]> {\n let browser: Browser | null = null;\n const screenshots: ScreenshotResult[] = [];\n\n try {\n // Launch browser\n browser = await chromium.launch({\n headless: true,\n });\n\n for (const viewport of viewports) {\n const page: Page = await browser.newPage({\n viewport: { width: viewport.width, height: viewport.height },\n });\n\n try {\n // Navigate to URL\n await page.goto(url, { \n waitUntil: 'networkidle',\n timeout: 30000 \n });\n\n // Wait for specific selector if provided\n if (options.waitForSelector) {\n await page.waitForSelector(options.waitForSelector, { timeout: 10000 });\n }\n\n // Additional wait if specified\n if (options.waitMs) {\n await page.waitForTimeout(options.waitMs);\n }\n\n // Capture full-page screenshot\n const screenshotBuffer = await page.screenshot({\n fullPage: true,\n type: 'png',\n });\n\n screenshots.push({\n viewport: viewport.name,\n width: viewport.width,\n height: viewport.height,\n base64: screenshotBuffer.toString('base64'),\n mimeType: 'image/png',\n });\n\n } finally {\n await page.close();\n }\n }\n\n } finally {\n if (browser) {\n await browser.close();\n }\n }\n\n return screenshots;\n}\n\n/**\n * Main Visual QA function - captures screenshots and prepares for Claude Vision\n */\nexport async function runVisualQA(options: VisualQAOptions = {}): Promise<VisualQAResult> {\n let url = options.url;\n \n // If no URL provided, try to find a running dev server\n if (!url) {\n if (options.port) {\n // User specified a port - verify it's serving HTTP\n const isServing = await testHttpPort(options.port);\n if (!isServing) {\n return {\n success: false,\n url: `http://localhost:${options.port}`,\n screenshots: [],\n error: `Port ${options.port} is not serving HTTP. Is your dev server running on this port?\\n\\nTry:\\n1. Verify your dev server is running: curl http://localhost:${options.port}\\n2. Check if the port is correct\\n3. Provide full URL: trie_visual_qa_browser url:\"http://localhost:${options.port}\"`,\n analysisPrompt: '',\n };\n }\n url = `http://localhost:${options.port}`;\n } else {\n // Auto-detect port\n if (!isInteractiveMode()) {\n console.error('Visual QA: Auto-detecting running dev server...');\n }\n const port = await findOpenPort();\n \n if (!port) {\n return {\n success: false,\n url: '',\n screenshots: [],\n error: 'No running dev server found on common ports (3000, 3001, 5173, 5174, 4200, 8080, 8000, 8888, 5000, 4000).\\n\\nPlease:\\n1. Start your dev server, OR\\n2. Provide a URL: trie_visual_qa_browser url:\"http://localhost:3000\", OR\\n3. Specify a port: trie_visual_qa_browser port:3000',\n analysisPrompt: '',\n };\n }\n \n url = `http://localhost:${port}`;\n if (!isInteractiveMode()) {\n console.error(` ✓ Found server on port ${port}`);\n }\n }\n }\n\n const viewports = options.viewports || DEFAULT_VIEWPORTS;\n\n try {\n if (!isInteractiveMode()) {\n console.error(`📸 Visual QA: Capturing screenshots from ${url}`);\n console.error(` Viewports: ${viewports.map(v => `${v.name} (${v.width}x${v.height})`).join(', ')}`);\n }\n\n const screenshots = await captureScreenshots(url, viewports, {\n waitForSelector: options.waitForSelector,\n waitMs: options.waitMs,\n });\n\n if (!isInteractiveMode()) {\n console.error(` ✓ Captured ${screenshots.length} screenshots`);\n }\n\n // Build analysis prompt for Claude Vision\n const analysisPrompt = buildAnalysisPrompt(url, screenshots);\n\n return {\n success: true,\n url,\n screenshots,\n analysisPrompt,\n };\n\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n \n // Check for common issues\n if (errorMessage.includes('net::ERR_CONNECTION_REFUSED') || errorMessage.includes('ECONNREFUSED')) {\n return {\n success: false,\n url,\n screenshots: [],\n error: `Cannot connect to ${url}. Is your dev server running?\\n\\nTry:\\n1. Start your dev server (e.g., npm start, npm run dev)\\n2. Specify the URL explicitly: trie_visual_qa_browser url:\"http://localhost:3000\"\\n3. Or specify the port: trie_visual_qa_browser port:3000`,\n analysisPrompt: '',\n };\n }\n \n if (errorMessage.includes('Executable doesn\\'t exist') || errorMessage.includes('BrowserType')) {\n return {\n success: false,\n url,\n screenshots: [],\n error: 'Playwright browsers not installed. Run: npx playwright install chromium',\n analysisPrompt: '',\n };\n }\n\n if (errorMessage.includes('timeout') || errorMessage.includes('Navigation timeout')) {\n return {\n success: false,\n url,\n screenshots: [],\n error: `Page load timeout for ${url}. The page may be taking too long to load or may have JavaScript errors.\\n\\nTry:\\n1. Check if the page loads in your browser\\n2. Increase wait time: trie_visual_qa_browser url:\"${url}\" waitMs:5000\\n3. Wait for specific element: trie_visual_qa_browser url:\"${url}\" waitForSelector:\".main-content\"`,\n analysisPrompt: '',\n };\n }\n\n return {\n success: false,\n url,\n screenshots: [],\n error: `Screenshot capture failed: ${errorMessage}\\n\\nTroubleshooting:\\n1. Verify ${url} is accessible in your browser\\n2. Check that your dev server is running\\n3. Try specifying the URL explicitly: trie_visual_qa_browser url:\"${url}\"`,\n analysisPrompt: '',\n };\n }\n}\n\n/**\n * Build the analysis prompt for Claude Vision\n */\nfunction buildAnalysisPrompt(url: string, screenshots: ScreenshotResult[]): string {\n const viewportList = screenshots.map(s => `- ${s.viewport}: ${s.width}x${s.height}`).join('\\n');\n \n return `## Visual QA Analysis\n\nI've captured screenshots of **${url}** at ${screenshots.length} viewports:\n\n${viewportList}\n\nPlease analyze these screenshots for:\n\n### Layout Issues\n- Overlapping elements or text\n- Content overflow or clipping\n- Broken layouts at specific breakpoints\n- Misaligned elements\n- Unexpected gaps or spacing\n\n### Responsive Design\n- Mobile navigation issues\n- Text too small to read on mobile\n- Touch targets too small (<44px)\n- Horizontal scrolling on mobile\n- Content not adapting to viewport\n\n### Visual Polish\n- Inconsistent spacing or alignment\n- Poor color contrast (text hard to read)\n- Broken images or missing assets\n- Loading states stuck/visible\n- Z-index issues (elements overlapping incorrectly)\n\n### Accessibility\n- Missing focus indicators\n- Color-only information\n- Text over images without sufficient contrast\n- Very small text (<12px)\n\n### General Quality\n- Does it look professional?\n- Is the hierarchy clear?\n- Are interactive elements obvious?\n- Any obvious bugs or glitches?\n\nFor each issue found:\n1. **Viewport**: Which viewport(s) affected\n2. **Location**: Where on the page\n3. **Issue**: What's wrong\n4. **Severity**: Critical/Serious/Moderate/Low\n5. **Fix**: How to resolve it\n\nIf the UI looks good, say so! Note what's working well.`;\n}\n\n/**\n * Format MCP response with images for Claude Vision\n */\nexport function formatMCPResponse(result: VisualQAResult): {\n content: Array<{ type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }>;\n} {\n if (!result.success) {\n return {\n content: [{\n type: 'text',\n text: `# Visual QA Failed\\n\\n${result.error}\\n\\n## Troubleshooting\\n\\n1. Make sure your dev server is running\\n2. Try: \\`trie_visual_qa url:\"http://localhost:3000\"\\`\\n3. If Playwright isn't installed: \\`npx playwright install chromium\\``,\n }],\n };\n }\n\n const content: Array<{ type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }> = [];\n\n // Add the analysis prompt first\n content.push({\n type: 'text',\n text: result.analysisPrompt,\n });\n\n // Add each screenshot as an image\n for (const screenshot of result.screenshots) {\n content.push({\n type: 'text',\n text: `\\n### ${screenshot.viewport} (${screenshot.width}x${screenshot.height})\\n`,\n });\n content.push({\n type: 'image',\n data: screenshot.base64,\n mimeType: screenshot.mimeType,\n });\n }\n\n return { content };\n}\n\n/**\n * MCP Tool Definition\n */\nexport const VISUAL_QA_TOOL_DEFINITION = {\n name: 'visual_qa_browser',\n description: 'Capture screenshots of your app at mobile/tablet/desktop viewports for visual QA analysis. Auto-detects running dev servers or specify a URL.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n url: {\n type: 'string',\n description: 'URL to screenshot (e.g., http://localhost:3000). If not provided, auto-detects running dev server.',\n },\n port: {\n type: 'number',\n description: 'Specific port to check if no URL provided',\n },\n waitForSelector: {\n type: 'string',\n description: 'CSS selector to wait for before capturing (e.g., \".main-content\")',\n },\n waitMs: {\n type: 'number',\n description: 'Additional milliseconds to wait after page load',\n },\n },\n required: [],\n },\n};\n","import { getWorkingDirectory } from '../utils/workspace.js';\nimport { runVisualQA, formatMCPResponse } from '../tools/visual-qa-browser.js';\nimport { ToolRegistry } from './tool-registry.js';\nimport { ResourceManager } from './resource-manager.js';\n\nexport class RequestHandlers {\n constructor(\n private toolRegistry: ToolRegistry,\n private resourceManager: ResourceManager\n ) {}\n\n /**\n * Handle tool execution requests\n */\n async handleToolCall(name: string, args: any): Promise<any> {\n // Accept namespaced calls and normalize\n const normalizedName = this.normalizeName(name);\n\n // Auto-detect directory for Cursor/IDE tools when not explicitly provided\n if (args && !args.directory && !args.files) {\n const workingDir = getWorkingDirectory(undefined, true);\n if (workingDir !== process.cwd()) {\n args.directory = workingDir;\n }\n }\n\n try {\n switch (normalizedName) {\n case 'trie':\n return await this.handleTrieMenu(args);\n\n case 'scan':\n return await this.toolRegistry.getTool('scan').execute(args);\n\n case 'fix':\n return await this.toolRegistry.getTool('fix').execute(args);\n\n case 'explain':\n return await this.toolRegistry.getTool('explain').execute(args);\n\n case 'test':\n return await this.toolRegistry.getTool('test').execute(args);\n\n case 'register_agent':\n return await this.toolRegistry.getTool('register_agent').execute(args);\n\n case 'watch':\n return await this.toolRegistry.getTool('watch').execute(args);\n\n // Individual agent commands\n case 'security':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'security' });\n\n case 'legal':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'legal' });\n\n case 'accessibility':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'accessibility' });\n\n case 'design':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'design-engineer' });\n\n case 'architecture':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'software-architect' });\n\n case 'bugs':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'bug-finding' });\n\n case 'ux':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'user-testing' });\n\n case 'types':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'typecheck' });\n\n case 'devops':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'devops' });\n\n case 'clean':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'trie_clean' });\n\n case 'soc2':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'soc2' });\n\n // New agents\n case 'performance':\n case 'perf':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'performance' });\n\n case 'e2e':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'e2e' });\n\n case 'visual_qa':\n case 'visual':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'visual-qa' });\n\n case 'visual_qa_browser': {\n try {\n const result = await runVisualQA(args as { url?: string; port?: number; waitForSelector?: string; waitMs?: number });\n return formatMCPResponse(result);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return {\n content: [{\n type: 'text',\n text: `# Visual QA Error\\n\\nFailed to capture screenshots: ${errorMessage}\\n\\n## Troubleshooting\\n\\n1. **Check if your dev server is running:**\\n - Try accessing the URL in your browser\\n - Common ports: 3000, 5173, 8080\\n\\n2. **Specify the URL explicitly:**\\n \\`\\`\\`\\ntrie_visual_qa_browser url:\"http://localhost:3000\"\\n\\`\\`\\`\\n\\n3. **Specify a port:**\\n \\`\\`\\`\\ntrie_visual_qa_browser port:3000\\n\\`\\`\\`\\n\\n4. **Install Playwright browsers (if needed):**\\n \\`\\`\\`\\nnpx playwright install chromium\\n\\`\\`\\`\\n\\n5. **Check for JavaScript errors:**\\n - Open browser dev tools\\n - Look for console errors\\n - The page may be failing to load`,\n }],\n };\n }\n }\n\n case 'data_flow':\n case 'dataflow':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'data-flow' });\n\n // Special agents\n case 'agent_smith':\n case 'agentsmith':\n case 'smith':\n // Handle special Agent Smith commands (clear_memory, show_stats)\n if (args?.clear_memory || args?.show_stats) {\n return await this.handleAgentSmith(args);\n }\n // Normal scan - delegate to agent tool\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'agent-smith' });\n\n case 'super_reviewer':\n case 'superreviewer':\n case 'reviewer':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'super-reviewer' });\n\n // Custom skill tools (with backward-compatible agent aliases)\n case 'create_skill':\n case 'create_agent':\n return await this.toolRegistry.getTool('create_skill').execute(args);\n\n case 'save_skill':\n case 'save_agent':\n return await this.toolRegistry.getTool('save_skill').execute(args);\n\n case 'list_skills':\n case 'list_agents':\n return await this.toolRegistry.getTool('list_skills').execute(args);\n\n case 'pr_review':\n return await this.toolRegistry.getTool('pr_review').execute(args);\n\n case 'project':\n case 'project_info':\n return await this.toolRegistry.getTool('project').execute(args);\n\n case 'init':\n return await this.toolRegistry.getTool('init').execute(args);\n\n case 'memory':\n return await this.toolRegistry.getTool('memory').execute(args);\n\n case 'check':\n return await this.toolRegistry.getTool('check').execute(args);\n\n case 'tell':\n return await this.toolRegistry.getTool('tell').execute(args);\n\n case 'feedback':\n case 'ok':\n case 'bad':\n return await this.toolRegistry.getTool('feedback').execute(args);\n\n case 'reconcile':\n return await this.toolRegistry.getTool('reconcile').execute(args);\n\n case 'context':\n return await this.toolRegistry.getTool('context').execute(args);\n\n case 'checkpoint':\n case 'cp':\n case 'save':\n return await this.toolRegistry.getTool('checkpoint').execute(args);\n\n default:\n throw new Error(`Unknown tool: ${name}`);\n }\n } catch (error) {\n return {\n content: [{\n type: 'text',\n text: `Error: ${error instanceof Error ? error.message : String(error)}`\n }]\n };\n }\n }\n\n /**\n * Handle resource listing requests\n */\n async handleListResources(): Promise<{ resources: any[] }> {\n const resources = await this.resourceManager.getAvailableResources();\n return { resources };\n }\n\n /**\n * Handle resource reading requests\n */\n async handleReadResource(uri: string): Promise<any> {\n return await this.resourceManager.readResourceContent(uri);\n }\n\n private normalizeName(name: string): string {\n // Accept namespaced calls like \"scan:user-trie-agent\" or \"user-trie-agent/scan\"\n // Also accept slash-prefixed chat-style commands like \"/trie\" or \"/trie_scan\"\n const stripNamespace = (n: string): string => {\n const trimmed = n.trim();\n const withoutSlash = trimmed.startsWith('/') ? trimmed.slice(1) : trimmed;\n const parts = withoutSlash.split(':');\n const base = parts[0] || withoutSlash;\n const slashParts = base.split('/');\n return slashParts[slashParts.length - 1] || base;\n };\n\n const rawName = stripNamespace(name);\n return rawName.startsWith('trie_') ? rawName.slice('trie_'.length) : rawName;\n }\n\n private async handleTrieMenu(args?: any) {\n const actionInput = typeof args?.action === 'string' ? args.action : null;\n if (actionInput) {\n const normalizedAction = this.normalizeName(actionInput);\n // Avoid recursion loop\n if (normalizedAction === 'trie') {\n return {\n content: [{\n type: 'text',\n text: 'Use `trie` without action for the menu, or provide a concrete action like \"scan\" or \"security\".'\n }]\n };\n }\n\n // Delegate to the same dispatcher to keep alias handling consistent\n return await this.handleToolCall(normalizedAction, { ...args });\n }\n\n return {\n content: [{\n type: 'text',\n text: [\n '## Trie Quick Actions',\n '',\n '**Most common:**',\n '- `trie` (no args) — show this menu',\n '- `trie` with `{ action: \"scan\", files?: [], directory?: \"\" }` — auto triage & scan',\n '- `trie` with `{ action: \"security\", files?: [] }` — single-skill run (any skill name works)',\n '- `trie` with `{ action: \"agent_smith\" }` — aggressive AI-pattern hunter',\n '',\n '**Other actions:**',\n '- `action: \"pr_review\"` — interactive PR review',\n '- `action: \"fix\"` — high-confidence fixes',\n '- `action: \"watch\"` — start/stop/status autonomous watch',\n '- `action: \"test\"` — generate/coverage/suggest/run tests (requires `files` + `action`)',\n '- `action: \"explain\"` — explain code/issues/risks',\n '- `action: \"list_skills\"` — list all skills (external + custom)',\n '- `action: \"visual_qa_browser\"` — screenshots for visual QA',\n '',\n '**Built-in skills:**',\n '`security`, `legal`, `accessibility`, `design`, `architecture`, `bugs`, `ux`, `types`, `devops`, `clean`, `soc2`, `performance`, `e2e`, `visual_qa`, `data_flow`',\n '',\n '**Special skills:**',\n '`agent_smith` — 35 vibe code hunters with cross-file detection',\n '`super_reviewer` — Interactive PR review with cross-examination',\n '',\n 'All commands accept `trie_` prefix (e.g., `trie_scan`, `trie_security`). Short names still work for compatibility.',\n ].join('\\n')\n }]\n };\n }\n\n private async handleAgentSmith(_smithArgs: any) {\n // Agent Smith has been removed - the decision ledger now handles pattern detection\n return {\n content: [{\n type: 'text',\n text: [\n '🤖 Agent Smith functionality has been integrated into the decision ledger.',\n '',\n 'The autonomous agent now:',\n '- Extracts patterns automatically via `trie watch`',\n '- Builds decision ledger from every change',\n '- Predicts problems via `trie gotcha`',\n '',\n 'Start the agent: `trie_watch start`',\n 'Query the ledger: `trie_gotcha`'\n ].join('\\n')\n }]\n };\n }\n}","#!/usr/bin/env node\n\nimport { startServer } from './server/mcp-server.js';\n\n// Start the MCP server\nstartServer().catch((error) => {\n console.error('Fatal error:', error);\n process.exit(1);\n});"],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A,aAAY;AAC1E,YAAM,EAAE,IAAI,IAAIA,SAAQ;AACxB,aAAO,MAAM,KAAK,gBAAgB,mBAAmB,GAAG;AAAA,IAC1D,CAAC;AAAA,EACH;AAAA;AAAA;AAAA;AAAA,EAKQ,kBAAkB,YAAoB,QAAgB;AAC5D,YAAQ,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAcd,UAAU,mBAAmB,MAAM;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,CAUtC;AAAA,EACC;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,QAAuB;AAC3B,QAAI;AAEF,YAAM,SAAS,aAAa;AAG5B,YAAM,WAAW;AAGjB,YAAM,WAAW,iBAAiB;AAClC,YAAM,aAAa,SAAS,aAAa,EAAE;AAE3C,WAAK,kBAAkB,YAAY,OAAO,IAAI;AAE9C,YAAM,YAAY,IAAI,qBAAqB;AAC3C,YAAM,KAAK,OAAO,QAAQ,SAAS;AAAA,IACrC,SAAS,OAAO;AACd,cAAQ,MAAM,oCAAoC,KAAK;AACvD,cAAQ,KAAK,CAAC;AAAA,IAChB;AAAA,EACF;AACF;AAKA,eAAsB,cAA6B;AACjD,QAAM,SAAS,IAAI,UAAU;AAC7B,QAAM,OAAO,MAAM;AACrB;;;A4BrIA,YAAY,EAAE,MAAM,CAAC,UAAU;AAC7B,UAAQ,MAAM,gBAAgB,KAAK;AACnC,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["Server","readFile","existsSync","extname","relative","resolve","isAbsolute","isAbsolute","resolve","existsSync","readFile","relative","extname","readFile","existsSync","extname","relative","resolve","isAbsolute","isAbsolute","resolve","existsSync","readFile","relative","extname","existsSync","readFile","join","extname","basename","existsSync","basename","join","extname","readdir","readFile","readFile","existsSync","join","basename","resolve","isAbsolute","isAbsolute","resolve","existsSync","basename","path","join","readFile","result","patterns","lines","path","path","readFile","existsSync","join","dirname","join","dirname","existsSync","readFile","resolve","Server","request"]}
|