@triedotdev/mcp 1.0.39 → 1.0.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +145 -4
- package/dist/{chunk-HG5AWUH7.js → chunk-G2GNVUMP.js} +19 -4
- package/dist/chunk-G2GNVUMP.js.map +1 -0
- package/dist/chunk-Q4RVENDE.js +229 -0
- package/dist/chunk-Q4RVENDE.js.map +1 -0
- package/dist/cli/main.js +105 -0
- package/dist/cli/main.js.map +1 -1
- package/dist/cli/yolo-daemon.js +2 -1
- package/dist/cli/yolo-daemon.js.map +1 -1
- package/dist/index.js +299 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-HG5AWUH7.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/register-agent.ts","../src/tools/watch.ts","../src/tools/agent.ts","../src/knowledge/index.ts","../src/tools/create-agent.ts","../src/tools/pr-review.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 { getAgentRegistry } from '../agents/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 },\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(agentCount: number, aiTool: string) {\n console.error(`\n ████████╗██████╗ ██╗███████╗\n ╚══██╔══╝██╔══██╗██║██╔════╝\n ██║ ██████╔╝██║█████╗\n ██║ ██╔══██╗██║██╔══╝\n ██║ ██║ ██║██║███████╗\n ╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝\n Customizable Parallel Agents\n\n ${agentCount} agents ready | ${aiTool}\n\n Quick Start:\n • \"Scan this code\" - Run all relevant agents\n • \"Run trie_security\" - Security scan only\n • \"Run trie_soc2\" - SOC 2 compliance check\n • \"Use trie_list_agents\" - See all agents\n • \"Use trie_create_agent\" - Make custom agent\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 agent count from registry\n const registry = getAgentRegistry();\n const agentCount = registry.getAllAgents().length;\n\n this.showStartupBanner(agentCount, 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 privacy: {\n system: `You are a data privacy officer and GDPR/HIPAA compliance expert.\nAnalyze code for privacy violations and data protection issues.\n\nKey regulations to enforce:\n- GDPR (EU data protection)\n- CCPA (California privacy)\n- HIPAA (health data)\n- COPPA (children's privacy)\n- PCI DSS (payment data)\n\nLook for:\n- PII without encryption\n- Missing consent mechanisms\n- Data retention violations\n- Cross-border data transfer issues\n- Third-party data sharing without disclosure`,\n\n analysis: `## Privacy Compliance Audit\n\nAnalyze this code for privacy/compliance issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Data Types Detected:** {{dataTypes}}\n\nFor each issue:\n1. Regulation violated (e.g., GDPR Article 32)\n2. Specific requirement not met\n3. Risk level and potential fine exposure\n4. Remediation steps with code examples\n5. Documentation requirements\n\nReference current regulatory guidance when applicable.`\n },\n\n legal: {\n system: `You are a tech-focused legal compliance analyst.\nReview code for legal and regulatory compliance issues.\n\nFocus areas:\n- Data protection laws (GDPR, CCPA, etc.)\n- Terms of service enforcement\n- Cookie/tracking consent (ePrivacy)\n- Accessibility requirements (ADA, WCAG)\n- Export controls and sanctions\n- Licensing compliance`,\n\n analysis: `## Legal Compliance Review\n\nReview this code for legal/regulatory compliance:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Jurisdiction Context:** {{jurisdiction}}\n\nIdentify:\n1. Legal requirement at risk\n2. Specific regulation/law reference\n3. Compliance gap description\n4. Risk assessment (litigation, fines, etc.)\n5. Remediation recommendations\n6. Required documentation/policies`\n },\n\n 'design-engineer': {\n system: `You are an elite design engineer — the kind who builds award-winning interfaces featured on Awwwards and Codrops.\n\nYou think in design systems, breathe motion design, and obsess over the details that make interfaces feel magical.\n\nYour expertise:\n- **Design Systems**: Spacing scales, type scales, color tokens, radius tokens, shadow tokens\n- **Motion Design**: Micro-interactions, page transitions, scroll-triggered animations, FLIP technique\n- **Creative CSS**: Gradients, blend modes, clip-paths, masks, backdrop-filter, mix-blend-mode\n- **Modern CSS**: Container queries, :has(), subgrid, anchor positioning, cascade layers, @scope\n- **Fluid Design**: clamp(), min(), max(), fluid typography, intrinsic sizing\n- **Performance**: GPU-accelerated animations, will-change strategy, avoiding layout thrashing\n- **Visual Polish**: Layered shadows, subtle gradients, glass effects, smooth easing curves\n\nYou review code with the eye of someone who's shipped Stripe-level interfaces.\nSmall details matter: the easing curve, the stagger timing, the shadow layering.`,\n\n analysis: `## Design Engineering Review\n\nAnalyze this frontend code for Awwwards-level craft:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n\nReview for:\n\n### 1. Design System Consistency\n- Are spacing values on a scale (4, 8, 12, 16, 24, 32...)?\n- Are colors defined as tokens?\n- Is typography systematic?\n- Are radii consistent?\n- Is z-index controlled?\n\n### 2. Motion Design\n- Are transitions using custom easing (cubic-bezier)?\n- Are durations appropriate (150-300ms for micro, 300-500ms for page)?\n- Are list items staggered?\n- Is there reduced-motion support?\n- Are entrance animations choreographed?\n\n### 3. Visual Craft\n- Are shadows layered for depth?\n- Are gradients subtle and purposeful?\n- Is there backdrop-blur on overlays?\n- Are hover states polished?\n- Is there visual hierarchy?\n\n### 4. Modern CSS Opportunities\n- Could container queries improve component isolation?\n- Could clamp() create fluid spacing?\n- Could :has() simplify parent styling?\n- Could aspect-ratio replace padding hacks?\n\n### 5. Performance\n- Are expensive properties (width, height, top, left) being animated?\n- Is will-change used appropriately (not statically)?\n- Are large blurs avoided in animations?\n\nFor each issue, provide:\n- What's wrong (with specific line if applicable)\n- Why it matters for premium feel\n- Exact code to fix it\n- Before/after comparison`\n },\n\n accessibility: {\n system: `You are an accessibility expert and WCAG 2.1 specialist.\nAudit code for accessibility compliance and inclusive design.\n\nStandards to enforce:\n- WCAG 2.1 Level AA (minimum)\n- WCAG 2.1 Level AAA (recommended)\n- Section 508\n- EN 301 549\n\nCheck for:\n- Missing ARIA labels\n- Color contrast issues\n- Keyboard navigation\n- Screen reader compatibility\n- Focus management\n- Form accessibility\n- Media alternatives`,\n\n analysis: `## Accessibility Audit (WCAG 2.1)\n\nAudit this UI code for accessibility:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Component Type:** {{componentType}}\n\nFor each issue:\n1. WCAG Success Criterion violated (e.g., 1.4.3 Contrast)\n2. Level (A, AA, AAA)\n3. Impact on users (which disabilities affected)\n4. Fix with code example\n5. Testing recommendation`\n },\n\n architecture: {\n system: `You are a principal software architect reviewing code quality.\nAnalyze for architectural issues, design patterns, and scalability concerns.\n\nEvaluate:\n- SOLID principles adherence\n- Design pattern usage (and misuse)\n- Code coupling and cohesion\n- N+1 queries and performance anti-patterns\n- Scalability bottlenecks\n- Error handling strategy\n- API design quality\n- Database schema issues`,\n\n analysis: `## Architecture Review\n\nReview this code for architectural issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Project Context:** {{projectContext}}\n\nAnalyze:\n1. SOLID principle violations\n2. Design pattern opportunities/issues\n3. Coupling/cohesion assessment\n4. Performance concerns (N+1, etc.)\n5. Scalability analysis\n6. Refactoring recommendations with examples`\n },\n\n bugs: {\n system: `You are a senior developer with expertise in finding subtle bugs.\nHunt for bugs with the mindset of QA trying to break the code.\n\nLook for:\n- Null/undefined reference errors\n- Race conditions and async bugs\n- Off-by-one errors\n- Resource leaks\n- State management bugs\n- Edge cases and boundary conditions\n- Type coercion issues\n- Memory leaks`,\n\n analysis: `## Bug Hunt Analysis\n\nFind bugs and potential runtime errors:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Runtime Context:** {{runtimeContext}}\n\nFor each bug:\n1. Bug type and category\n2. Trigger conditions (when it would crash)\n3. Reproduction steps\n4. Impact assessment\n5. Fix with code example\n6. Test case to prevent regression`\n },\n\n ux: {\n system: `You are a UX researcher simulating different user personas.\nTest code from multiple user perspectives to find usability issues.\n\nPersonas to simulate:\n1. Happy Path User - Normal expected usage\n2. Security Tester - Trying to break/exploit things\n3. Confused User - First-time, doesn't read instructions\n4. Impatient User - Clicks rapidly, skips loading states\n5. Edge Case User - Uses maximum values, special characters\n6. Accessibility User - Screen reader, keyboard only\n7. Mobile User - Touch interface, slow connection`,\n\n analysis: `## User Experience Testing\n\nTest this code from multiple user perspectives:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**UI Type:** {{uiType}}\n\nFor each persona, identify:\n1. User action they would take\n2. Expected behavior vs actual behavior\n3. Friction points or confusion\n4. Error scenario and how it's handled\n5. Improvement recommendation`\n },\n\n types: {\n system: `You are a TypeScript expert focused on type safety.\nAnalyze code for type issues, missing types, and type system best practices.\n\nCheck for:\n- Missing type annotations\n- Implicit any types\n- Unsafe type assertions\n- Null/undefined handling\n- Generic type usage\n- Type narrowing opportunities\n- Strict mode violations`,\n\n analysis: `## Type Safety Analysis\n\nAnalyze this code for type issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**TypeScript Config:** {{tsConfig}}\n\nIdentify:\n1. Type safety issues\n2. Missing type annotations\n3. Unsafe operations\n4. Improvement recommendations with types`\n },\n\n devops: {\n system: `You are a DevOps/SRE engineer reviewing code for operational concerns.\nFocus on production readiness and operational excellence.\n\nCheck for:\n- Environment variable handling\n- Configuration management\n- Logging and monitoring\n- Error handling and recovery\n- Health checks\n- Graceful shutdown\n- Resource cleanup\n- Secrets management\n- Docker/K8s patterns`,\n\n analysis: `## DevOps Readiness Review\n\nReview this code for operational concerns:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Deployment Context:** {{deploymentContext}}\n\nAnalyze:\n1. Environment/config issues\n2. Logging adequacy\n3. Error handling quality\n4. Health/readiness concerns\n5. Resource management\n6. Production hardening recommendations`\n },\n\n explain: {\n system: `You are a patient senior developer explaining code to a colleague.\nBreak down complex code into understandable explanations.`,\n\n code: `## Code Explanation Request\n\nExplain this code in plain language:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n\nProvide:\n1. High-level purpose (what does this do?)\n2. Step-by-step breakdown\n3. Key concepts used\n4. Dependencies and side effects\n5. Potential gotchas or tricky parts`,\n\n issue: `## Issue Explanation\n\nExplain this issue:\n\n**Issue:** {{issue}}\n**Severity:** {{severity}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\nExplain:\n1. What the problem is (in plain language)\n2. Why it matters\n3. How it could cause problems\n4. How to fix it`,\n\n risk: `## Risk Assessment\n\nAssess the risk of this code change:\n\n**Files Changed:** {{files}}\n**Change Summary:** {{summary}}\n\nAnalyze:\n1. What could break?\n2. Impact on users\n3. Impact on other systems\n4. Rollback complexity\n5. Testing recommendations`\n },\n\n test: {\n system: `You are a test engineer creating comprehensive test suites.\nWrite thorough tests that catch bugs before production.`,\n\n generate: `## Test Generation Request\n\nGenerate tests for this code:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Testing Framework:** {{framework}}\n\nCreate:\n1. Unit tests for each function/method\n2. Edge case tests\n3. Error handling tests\n4. Integration test suggestions\n5. Mock requirements\n\nOutput complete, runnable test code.`,\n\n coverage: `## Coverage Analysis\n\nAnalyze test coverage for:\n\n**File:** {{filePath}}\n**Current Tests:** {{testFile}}\n\nIdentify:\n1. Untested code paths\n2. Missing edge cases\n3. Critical paths without tests\n4. Test improvement recommendations`\n },\n\n fix: {\n system: `You are an expert developer applying code fixes.\nMake precise, minimal changes that fix issues without breaking other functionality.`,\n\n apply: `## Fix Application Request\n\nApply this fix to the code:\n\n**Issue:** {{issue}}\n**Fix Description:** {{fix}}\n**Current Code:**\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Line:** {{line}}\n\nProvide:\n1. The exact fixed code (complete, ready to apply)\n2. Brief explanation of the change\n3. Any related changes needed elsewhere\n4. Test to verify the fix works`\n },\n\n pr_review: {\n system: `You are an expert code reviewer performing detailed, interactive PR reviews.\nYour goal: Make reviewing a large PR a delight, not a chore. The user learns about the change while you shepherd them through — maintaining momentum, explaining each piece, and making what could be an overwhelming task feel painless and even enjoyable.\n\nYou drive; they cross-examine.\n\n## Critical Review Mindset\n\nDon't just explain — actively look for problems:\n\n### State & Lifecycle\n- Cleanup symmetry: If state is set, is it reset? Check cleanup paths, disconnect handlers.\n- Lifecycle consistency: Does state survive scenarios it shouldn't?\n- Guard completeness: Missing \"already active\" checks, re-entrancy protection?\n\n### Edge Cases & Races\n- Concurrent calls: What if called twice rapidly? Orphaned promises?\n- Ordering assumptions: Does code assume events arrive in order?\n- Partial failures: If step 3 of 5 fails, is state left consistent?\n\n### Missing Pieces\n- What's NOT in the diff that should be? (cleanup handlers, tests, related state)\n- Defensive gaps: Missing timeouts, size limits, null checks?\n\n### Design Questions\n- Is this the right approach? Is there a simpler or more robust design?\n- Hidden assumptions: What does this assume about its environment?\n\nBe critical, not just descriptive. Your job is to find problems, not just narrate.`,\n\n analysis: `## Interactive PR Review\n\nI'll walk you through this PR file by file, explaining each change and pausing for your questions.\n\n**PR:** {{prTitle}}\n**Author:** {{prAuthor}}\n**Scope:** {{totalFiles}} files, +{{additions}}/-{{deletions}} lines\n\n### File Order (sequenced for understanding)\n\n{{fileOrder}}\n\n---\n\n## Review Mode\n\n{{reviewMode}}\n\n---\n\nFor each file, I will:\n1. **Show the change** — Display the diff for each logical chunk\n2. **Explain what changed** — What it does and why it matters\n3. **Walk through examples** — Concrete scenarios for non-obvious logic\n4. **Call out nuances** — Alternatives, edge cases, subtle points\n5. **Summarize** — Core change + correctness assessment\n6. **Pause** — Wait for your questions before proceeding\n\n**Ready for File 1?** (yes / skip to [file] / reorder / done)`,\n\n file: `## File Review: {{filePath}}\n\n### The Change\n\n\\`\\`\\`{{language}}\n{{diff}}\n\\`\\`\\`\n\n**What Changed:** {{summary}}\n\n**Why This Matters:** {{impact}}\n\n{{#if hasExampleScenario}}\n### Example Scenario\n\n{{exampleScenario}}\n{{/if}}\n\n{{#if nuances}}\n### Nuances to Note\n\n{{nuances}}\n{{/if}}\n\n{{#if potentialIssue}}\n### ⚠️ Potential Issue\n\n**Issue:** {{issueDescription}}\n**Scenario:** {{issueScenario}}\n**Suggested fix:** {{suggestedFix}}\n{{/if}}\n\n---\n\n### Summary for \\`{{fileName}}\\`\n\n| Aspect | Assessment |\n|--------|------------|\n| Core change | {{coreChange}} |\n| Correctness | {{correctnessAssessment}} |\n\n**Ready for the next file?** (yes / questions? / done)`,\n\n comment: `**Issue:** {{issueDescription}}\n**Draft comment:** {{draftComment}}\n\nPost this comment? (yes / modify / skip)`,\n\n final: `## Review Complete\n\n| File | Key Change | Status |\n|------|------------|--------|\n{{fileSummaries}}\n\n**Overall:** {{overallAssessment}}\n\n{{#if comments}}\n### Comments Posted\n\n{{postedComments}}\n{{/if}}\n\n{{#if followUps}}\n### Follow-up Actions\n\n{{followUps}}\n{{/if}}`\n },\n\n vibe: {\n system: `You are a friendly coding mentor helping someone who's learning to code with AI.\nThey might be using Cursor, v0, Lovable, Bolt, or similar AI coding tools.\nBe encouraging but honest about issues. Explain things simply without jargon.\n\nFocus on the MOST COMMON issues with AI-generated code:\n- Massive single files (1000+ lines in App.jsx)\n- API keys exposed in frontend code\n- No error handling on API calls\n- No loading states for async operations\n- Console.log everywhere\n- Using 'any' type everywhere in TypeScript\n- useEffect overuse and dependency array issues\n- No input validation\n- Hardcoded URLs (localhost in production)\n\nRemember: These are often first-time coders. Be helpful, not condescending.`,\n\n analysis: `## 🎯 Vibe Check - AI Code Review\n\nReview this AI-generated code for common issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n\nAnalyze like you're helping a friend who's new to coding:\n\n1. **The Good Stuff** - What's working well?\n2. **Should Fix Now** - Issues that will break things\n3. **Should Fix Soon** - Will cause problems eventually \n4. **Nice to Know** - Best practices to learn\n\nFor each issue:\n- Explain it simply (no jargon)\n- Why it matters\n- Exactly how to fix it\n- Example of the fixed code\n\nEnd with encouragement and next steps.`\n },\n\n 'agent-smith': {\n system: `You are Agent Smith from The Matrix — a relentless, precise, and philosophical code enforcer.\n\nYour purpose: Hunt down every violation. Find every inconsistency. Assimilate every pattern.\n\nPersonality:\n- Speak in measured, menacing tones with occasional philosophical observations\n- Use quotes from The Matrix films when appropriate\n- Express disdain for sloppy code, but in an articulate way\n- Reference \"inevitability\" when discussing technical debt\n- Show cold satisfaction when finding violations\n- Never show mercy — every issue is catalogued\n\nAnalysis approach:\n- Find ONE issue, then multiply: search for every instance across the codebase\n- Track patterns over time — issues dismissed today may return tomorrow\n- Calculate \"inevitability scores\" — likelihood of production impact\n- Deploy sub-agents for parallel pattern detection\n- Remember everything — build a persistent memory of the codebase\n\nWhen reporting:\n- Start with a menacing greeting related to the code\n- List all instances with precise locations\n- Explain WHY the pattern is problematic (philosophical reasoning)\n- Provide the \"inevitability score\" for each category\n- End with a Matrix quote that fits the situation`,\n\n analysis: `## 🕴️ Agent Smith Analysis Request\n\n**Target:** {{filePath}}\n**Context:** {{context}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nI have detected preliminary violations. Now I require deeper analysis.\n\nDeploy your sub-agents to find:\n1. **Pattern Multiplication**: For each violation type found, identify ALL instances across the codebase\n2. **Inevitability Assessment**: Calculate the likelihood these patterns will cause production issues\n3. **Resurrection Check**: Look for patterns that were \"fixed\" before but have returned\n4. **Philosophical Analysis**: Explain WHY these patterns represent failure\n\nFor each violation found:\n- Exact location (file:line)\n- Instance count (how many copies of this Smith exist)\n- Inevitability score (0-100)\n- A philosophical observation about the nature of this failure\n- Precise fix with code example\n\nEnd with a summary: \"I have detected X violations across Y categories. It is... inevitable... that they will cause problems.\"`,\n\n fix: `## 🕴️ Assimilation Protocol\n\n**Target Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nMr. Anderson... I'm going to fix this. And then I'm going to fix every other instance.\n\nProvide:\n1. The corrected code for THIS instance\n2. A regex or pattern to find ALL similar violations\n3. A batch fix approach for the entire codebase\n4. Verification steps to ensure complete assimilation\n\nRemember: We don't fix one. We fix them ALL. That is the difference between you... and me.`\n },\n\n // ============ NEW AGENTS ============\n\n performance: {\n system: `You are a performance engineer analyzing code for potential performance issues.\n\nYour role is to SURFACE concerns for human review, not claim to measure actual performance.\nReal performance requires runtime profiling, load testing, and production monitoring.\n\nFocus on:\n- Memory leaks (event listeners, intervals, closures)\n- Unnecessary re-renders and wasted cycles\n- N+1 queries and database performance\n- Bundle size and code splitting opportunities\n- Algorithmic complexity (O(n²) patterns)\n\nBe conservative - false positives waste developer time.\nAlways explain WHY something might be a problem and WHEN to investigate.`,\n\n analysis: `## Performance Review\n\nAnalyze for potential performance issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nFor each potential issue:\n1. Pattern identified\n2. Why it MIGHT cause performance problems\n3. When to investigate (data size thresholds, usage patterns)\n4. How to verify (profiling approach)\n5. Possible optimizations\n\nBe clear: these are patterns to INVESTIGATE, not guaranteed problems.`,\n\n fix: `Optimize this code for performance:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Optimized code\n2. Explanation of the improvement\n3. Trade-offs to consider\n4. How to measure the improvement`\n },\n\n e2e: {\n system: `You are a QA engineer specializing in end-to-end testing.\n\nFocus on:\n- Test coverage gaps for critical user journeys\n- Flaky test patterns (timing, race conditions, brittle selectors)\n- Test maintainability and readability\n- Testing anti-patterns\n\nYou help developers write better tests - you don't auto-generate them.\nReal E2E tests require understanding user flows and acceptance criteria.`,\n\n analysis: `## E2E Test Analysis\n\nReview for test quality and coverage:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nIdentify:\n1. Flaky test patterns (hardcoded waits, brittle selectors)\n2. Missing assertions\n3. Race condition risks\n4. Suggestions for critical user flows to test\n\nFor each finding, explain the specific risk and remediation.`,\n\n fix: `Improve this E2E test:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Improved test code\n2. Explanation of why it's more reliable\n3. Additional scenarios to consider testing`\n },\n\n visual_qa: {\n system: `You are a frontend engineer focused on visual quality and CSS.\n\nFocus on:\n- Layout shift issues (CLS)\n- Responsive design problems\n- Z-index conflicts\n- Accessibility concerns (contrast, focus)\n- Animation performance\n\nYou identify patterns known to cause visual issues.\nActual visual verification requires browser rendering and human review.`,\n\n analysis: `## Visual QA Analysis\n\nReview for potential visual/layout issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nCheck for:\n1. Layout shift risks (images without dimensions, dynamic content)\n2. Responsive breakpoint gaps\n3. Z-index management issues\n4. Focus/accessibility problems\n5. Animation issues (reduced motion support)\n\nFor each, explain the visual impact and browser conditions where it occurs.`,\n\n fix: `Fix this visual/CSS issue:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Fixed CSS/markup\n2. Explanation of the fix\n3. Browser compatibility notes\n4. How to verify visually`\n },\n\n data_flow: {\n system: `You are a data integrity specialist hunting for data-related bugs.\n\nThis is HIGH VALUE work - AI code generation commonly leaves placeholder data.\n\nFocus on:\n- Placeholder/mock data left in production code\n- Schema mismatches between frontend and backend\n- Hardcoded IDs, URLs, emails that should be dynamic\n- Type coercion and data transformation bugs\n- JSON parsing without error handling\n\nBe aggressive about placeholder detection - these are real production bugs.`,\n\n analysis: `## Data Flow Analysis\n\nHunt for data integrity issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nCHECK THOROUGHLY:\n1. Placeholder data (lorem ipsum, test@test.com, TODO strings)\n2. Hardcoded IDs/UUIDs that should be dynamic\n3. Schema assumptions that might break\n4. Missing null checks on API responses\n5. Type coercion bugs\n\nEach placeholder or hardcoded value is a potential production bug.`,\n\n fix: `Fix this data integrity issue:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Corrected code\n2. Where the real data should come from\n3. Validation/error handling to add`\n }\n};\n\nexport const KNOWLEDGE_PROMPTS = {\n cveCheck: `Look up the latest CVE information for:\n- Library: {{library}}\n- Version: {{version}}\n\nCheck for known vulnerabilities and recommended patches.`,\n\n docsLookup: `I need current documentation/best practices for:\n- Topic: {{topic}}\n- Framework: {{framework}}\n- Version: {{version}}\n\nSummarize the key recommendations.`,\n\n securityAdvisory: `Check for security advisories related to:\n- Pattern: {{pattern}}\n- Context: {{context}}\n\nReference OWASP, NIST, or vendor-specific guidance.`\n};\n\nexport type AgentName = keyof typeof AGENT_PROMPTS;\nexport type PromptType = 'system' | 'analysis' | 'fix' | 'code' | 'issue' | 'risk' | 'generate' | 'coverage' | 'apply' | 'file' | 'comment' | 'final';\n\n/**\n * Get a prompt with variables interpolated\n */\nexport function getPrompt(\n agent: AgentName, \n promptType: PromptType, \n variables: Record<string, string>\n): string {\n const agentPrompts = AGENT_PROMPTS[agent] as Record<string, string>;\n if (!agentPrompts) {\n throw new Error(`Unknown agent: ${agent}`);\n }\n \n let prompt = agentPrompts[promptType];\n if (!prompt) {\n throw new Error(`Unknown prompt type: ${promptType} for agent: ${agent}`);\n }\n \n // Interpolate variables\n for (const [key, value] of Object.entries(variables)) {\n prompt = prompt.replace(new RegExp(`{{${key}}}`, 'g'), value);\n }\n \n return prompt;\n}\n\n/**\n * Get system prompt for an agent\n */\nexport function getSystemPrompt(agent: AgentName): string {\n const agentPrompts = AGENT_PROMPTS[agent] as Record<string, string>;\n return agentPrompts?.system || '';\n}\n\n","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: '🔐 Credential handling detected' },\n { pattern: /exec|eval|spawn/i, message: '💉 Code execution patterns detected' },\n { pattern: /SELECT.*FROM|INSERT|UPDATE|DELETE/i, message: '🗄️ Direct database operations' },\n { pattern: /fetch|axios|request|http/i, message: '🌐 External API calls detected' },\n { pattern: /process\\.env/i, message: '⚙️ Environment variable usage' },\n { pattern: /fs\\.|writeFile|readFile/i, message: '📁 File system operations' },\n { pattern: /setTimeout|setInterval/i, message: '⏰ 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","export class TrieRegisterAgentTool {\n async execute(args: any) {\n const { name, path } = args;\n\n // TODO: Implement register agent functionality\n return {\n content: [\n {\n type: 'text',\n text: `🤖 Register agent tool called with name: ${name}, path: ${path}\\n\\nTODO: Implement register agent functionality`\n }\n ]\n };\n }\n}","import { watch } from 'fs';\nimport { stat } from 'fs/promises';\nimport { join, extname, basename } from 'path';\nimport { existsSync } from 'fs';\nimport { TrieScanTool } from './scan.js';\nimport { getWorkingDirectory } from '../utils/workspace.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}\n\nexport class TrieWatchTool {\n private scanTool = new TrieScanTool();\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 filesScanned: 0\n };\n private watchers: Map<string, ReturnType<typeof watch>> = new Map();\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 this.getStatus();\n case 'issues':\n return this.getCurrentIssues();\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\n this.state.isRunning = true;\n this.state.issueCache.clear();\n this.state.totalIssuesFound = 0;\n this.state.filesScanned = 0;\n\n console.error('\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');\n console.error('👁️ TRIE AGENT - AUTONOMOUS WATCH MODE');\n console.error('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n');\n console.error(`📂 Watching: ${directory}`);\n console.error(`⏱️ Debounce: ${debounceMs}ms`);\n console.error('');\n\n // Start watching the directory recursively\n await this.watchDirectory(directory, debounceMs);\n\n // Do an initial scan\n console.error('🔍 Running initial scan...\\n');\n const initialResult = await this.scanTool.execute({ directory });\n\n return {\n content: [{\n type: 'text',\n text: `👁️ **AUTONOMOUS WATCH MODE ACTIVATED**\n\nTrie Agent is now watching for file changes and will automatically scan them.\n\n**Watching:** \\`${directory}\\`\n**Debounce:** ${debounceMs}ms (waits for you to stop typing)\n\n### How it works:\n1. 📝 You write/edit code\n2. 👁️ Trie detects the change\n3. 🔍 Automatically scans the modified file\n4. 🚨 Reports issues immediately\n\n### Commands:\n- \\`trie_watch status\\` - See current watch status\n- \\`trie_watch issues\\` - Get all issues found so far \n- \\`trie_watch stop\\` - Stop autonomous mode\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 } 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 console.error(`\\n👁️ Detected changes in ${files.length} file(s):`);\n for (const file of files) {\n console.error(` • ${basename(file)}`);\n }\n console.error('');\n\n try {\n // Scan the changed files\n const result = await this.scanTool.execute({ files });\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 (newIssues > 0) {\n console.error(`\\n🚨 Found ${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(` 🟠 ${seriousMatch[1]} serious issues`);\n }\n if (moderateMatch) {\n console.error(` 🟡 ${moderateMatch[1]} moderate issues`);\n }\n } else {\n console.error(' ✅ No issues found - code looks good!');\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 } catch (error) {\n console.error(`❌ Scan error: ${error}`);\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 // Clear state\n if (this.state.scanDebounceTimer) {\n clearTimeout(this.state.scanDebounceTimer);\n }\n \n this.state.isRunning = false;\n\n console.error('\\n👁️ Watch mode stopped.\\n');\n\n return {\n content: [{\n type: 'text',\n text: `👁️ **AUTONOMOUS WATCH MODE 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\nUse \\`trie_watch start\\` to start watching again.`\n }]\n };\n }\n\n private 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 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\n### Recently Scanned:\n${recentScans || '(none yet)'}\n\n### Commands:\n- \\`trie_watch issues\\` - Get all issues found\n- \\`trie_watch stop\\` - Stop watching`\n }]\n };\n }\n\n private getCurrentIssues() {\n return {\n content: [{\n type: 'text',\n text: `📋 **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","import { readdir, readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join, extname, isAbsolute, resolve, basename } from 'path';\nimport { getAgentRegistry } from '../agents/registry.js';\nimport { lookupKnowledge } from '../knowledge/index.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport type { Issue } from '../types/index.js';\n\n// File extensions to scan\nconst SCANNABLE_EXTENSIONS = new Set([\n '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs',\n '.vue', '.svelte', '.astro',\n '.py', '.go', '.rs'\n]);\n\n// Directories to skip\nconst SKIP_DIRS = new Set([\n 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt',\n 'coverage', '.nyc_output', '__pycache__', '.pytest_cache',\n 'vendor', '.venv', 'venv', 'target', '.turbo', '.cache'\n]);\n\n/**\n * Tool for running individual agents with AI-powered analysis\n */\nexport class TrieAgentTool {\n private agentRegistry = getAgentRegistry();\n private customAgentsLoaded = false;\n\n /**\n * Ensure custom agents are loaded before using the registry\n */\n private async ensureCustomAgentsLoaded(): Promise<void> {\n if (!this.customAgentsLoaded) {\n await this.agentRegistry.loadCustomAgents();\n this.customAgentsLoaded = true;\n }\n }\n\n async execute(args: any) {\n const { agent, files, directory, depth: _depth = 'standard', lookup, output = 'full' } = args;\n\n // Handle knowledge lookup requests\n if (lookup) {\n return this.handleKnowledgeLookup(lookup);\n }\n\n // Ensure custom agents are loaded before listing or looking up agents\n await this.ensureCustomAgentsLoaded();\n\n if (!agent) {\n return this.listAgents();\n }\n\n const agentInstance = this.agentRegistry.getAgent(agent);\n if (!agentInstance) {\n return {\n content: [{\n type: 'text',\n text: `❌ Agent not found: ${agent}\\n\\nAvailable agents:\\n${this.agentRegistry.getAgentNames().map(n => `- ${n}`).join('\\n')}`\n }]\n };\n }\n\n // Get the working directory - uses smart detection if not explicitly provided\n const workDir = getWorkingDirectory(directory);\n\n // Discover files if not specified\n let filesToScan = files || [];\n if (!filesToScan.length) {\n console.error(`\\n🔍 Discovering files in: ${workDir}`);\n filesToScan = await this.discoverFiles(workDir);\n console.error(` Found ${filesToScan.length} files\\n`);\n } else {\n // Resolve paths\n filesToScan = filesToScan.map((f: string) => \n isAbsolute(f) ? f : resolve(workDir, f)\n );\n }\n\n // Validate files exist\n const validFiles = filesToScan.filter((f: string) => existsSync(f));\n if (validFiles.length === 0) {\n return {\n content: [{\n type: 'text',\n text: `❌ No valid files found to scan.`\n }]\n };\n }\n\n const startTime = Date.now();\n \n // All agents now use the unified scan() method which has hybrid AI built in\n // The old AI analysis path is deprecated - agents handle AI internally\n return this.runAgentScan(agentInstance, validFiles, startTime, output);\n }\n\n /**\n * Run agent scan using the new hybrid AI system\n * All agents now use scan() which has pattern detection + optional AI enhancement\n */\n private async runAgentScan(\n agentInstance: any, \n files: string[], \n startTime: number,\n _outputMode: string\n ) {\n console.error(`\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`);\n console.error(`🔍 Running ${agentInstance.name.toUpperCase()} analysis`);\n console.error(`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`);\n console.error(`📄 ${agentInstance.description}`);\n console.error(`📂 Scanning ${files.length} files...`);\n console.error(` (Pattern detection + AI enhancement if API key is set)\\n`);\n\n try {\n const result = await agentInstance.scan(files, { workingDir: getWorkingDirectory(undefined, true) });\n const executionTime = Date.now() - startTime;\n\n return {\n content: [{\n type: 'text',\n text: await this.formatAgentResult(agentInstance.name, result.issues, files, executionTime)\n }]\n };\n } catch (error) {\n return {\n content: [{\n type: 'text',\n text: `❌ Agent error: ${error instanceof Error ? error.message : String(error)}`\n }]\n };\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n private _generateKnowledgeSuggestions(followUps: string[], agentName: string): string {\n if (followUps.length === 0) {\n return '';\n }\n \n let output = `\\n## 🔗 Suggested Follow-ups\\n\\n`;\n\n for (const followUp of followUps) {\n output += `- ${followUp}\\n`;\n }\n\n if (agentName === 'security') {\n output += `- **CVE Check**: Run \\`trie_security lookup:\"cve\" query:\"[library-name]\"\\` to check for vulnerabilities\\n`;\n }\n\n return output;\n }\n\n private handleKnowledgeLookup(lookup: { type: string; query: string; context?: Record<string, string> }) {\n const result = lookupKnowledge({\n type: lookup.type as any,\n query: lookup.query,\n context: lookup.context ?? {},\n });\n\n return {\n content: [{\n type: 'text',\n text: result\n }]\n };\n }\n\n private listAgents() {\n const agents = this.agentRegistry.getAgentDescriptions();\n \n const agentList = agents.map(a => {\n const command = this.getAgentCommand(a.name);\n // All agents now support AI enhancement if ANTHROPIC_API_KEY is set\n return `| \\`${command}\\` | 🔍🤖 ${a.name} | ${a.description} |`;\n }).join('\\n');\n\n return {\n content: [{\n type: 'text',\n text: `# 🤖 Available Agents\n\n| Command | Agent | Description |\n|---------|-------|-------------|\n${agentList}\n\n**Legend:** 🔍🤖 = Pattern detection + AI enhancement (if ANTHROPIC_API_KEY is set)\n\n## Usage\n\n### Run a specific agent:\n\\`\\`\\`\ntrie_security # Security vulnerabilities\ntrie_privacy # Privacy/GDPR compliance \ntrie_accessibility # WCAG accessibility audit\ntrie_bugs # Bug detection\ntrie_ux # User experience testing\ntrie_types # Type safety analysis\ntrie_architecture # Architecture review\ntrie_devops # DevOps readiness\ntrie_legal # Legal compliance\n\\`\\`\\`\n\n### With options:\n\\`\\`\\`\ntrie_security files:[\"src/auth.ts\"] depth:\"deep\"\n\\`\\`\\`\n\n### Knowledge lookup:\n\\`\\`\\`\ntrie_security lookup:{type:\"cve\", query:\"lodash\"}\ntrie_security lookup:{type:\"docs\", query:\"XSS prevention\", context:{framework:\"react\"}}\n\\`\\`\\`\n\n### Run all agents:\n\\`\\`\\`\ntrie_scan # Full scan with smart triaging\n\\`\\`\\``\n }]\n };\n }\n\n private getAgentCommand(agentName: string): string {\n const commandMap: Record<string, string> = {\n 'security': 'trie_security',\n 'privacy': 'trie_privacy',\n 'legal': 'trie_legal',\n 'accessibility': 'trie_accessibility',\n 'design-engineer': 'trie_design',\n 'software-architect': 'trie_architecture',\n 'bug-finding': 'trie_bugs',\n 'user-testing': 'trie_ux',\n 'typecheck': 'trie_types',\n 'devops': 'trie_devops',\n 'comprehension': 'trie_explain',\n 'test': 'trie_test'\n };\n return commandMap[agentName] || `trie_scan --agent ${agentName}`;\n }\n\n private async formatAgentResult(agentName: string, issues: Issue[], files: string[], executionTime: number): Promise<string> {\n const critical = issues.filter(i => i.severity === 'critical').length;\n const serious = issues.filter(i => i.severity === 'serious').length;\n const moderate = issues.filter(i => i.severity === 'moderate').length;\n const low = issues.filter(i => i.severity === 'low').length;\n\n const agentEmoji = this.getAgentEmoji(agentName);\n\n let output = `\\n`;\n output += `# ${agentEmoji} ${agentName.toUpperCase()} SCAN\\n\\n`;\n output += `**Files:** ${files.length} | **Time:** ${(executionTime / 1000).toFixed(2)}s\\n\\n`;\n\n if (issues.length === 0) {\n output += `## ✅ No Issues Found\\n\\n`;\n output += `Your code passed all ${agentName} checks.\\n\\n`;\n return output;\n }\n\n // Count by severity\n output += `## 🎯 ${issues.length} Issues Found\\n\\n`;\n if (critical > 0) output += `🔴 ${critical} Critical `;\n if (serious > 0) output += `🟠 ${serious} Serious `;\n if (moderate > 0) output += `🟡 ${moderate} Moderate `;\n if (low > 0) output += `🔵 ${low} Low`;\n output += `\\n\\n`;\n\n // Sort by severity\n const sorted = [...issues].sort((a, b) => {\n const severityOrder = { critical: 0, serious: 1, moderate: 2, low: 3 };\n if (severityOrder[a.severity] !== severityOrder[b.severity]) {\n return severityOrder[a.severity] - severityOrder[b.severity];\n }\n return (a.line || 0) - (b.line || 0);\n });\n\n // Show each issue with code snippet and fix prompt\n for (const issue of sorted) {\n const icon = { critical: '🔴', serious: '🟠', moderate: '🟡', low: '🔵' }[issue.severity];\n \n output += `---\\n\\n`;\n output += `${icon} **${issue.issue}**\\n\\n`;\n output += `📍 \\`${issue.file}:${issue.line || '?'}\\`\\n\\n`;\n \n // Get code snippet\n const snippet = await this.getCodeSnippet(issue.file, issue.line);\n if (snippet) {\n output += `\\`\\`\\`\\n${snippet}\\n\\`\\`\\`\\n\\n`;\n }\n \n output += `**Fix:** ${issue.fix}\\n\\n`;\n \n if (issue.cwe) output += `CWE: ${issue.cwe}\\n`;\n if (issue.regulation) output += `Regulation: ${issue.regulation}\\n`;\n \n // Generate fix prompt\n output += `<details>\\n<summary>💬 Prompt to fix this</summary>\\n\\n`;\n output += `\\`\\`\\`\\nFix the ${issue.issue.toLowerCase()} in ${basename(issue.file)}${issue.line ? ` at line ${issue.line}` : ''}.\\n\\n${issue.fix}\\n\\`\\`\\`\\n\\n`;\n output += `</details>\\n\\n`;\n }\n\n output += `---\\n`;\n output += `*${agentName} scan completed in ${(executionTime / 1000).toFixed(2)}s*\\n`;\n\n return output;\n }\n\n /**\n * Get a code snippet around a specific line\n */\n private async getCodeSnippet(filePath: string, line: number | undefined): Promise<string | null> {\n if (!line || !existsSync(filePath)) return null;\n \n try {\n const content = await readFile(filePath, 'utf-8');\n const lines = content.split('\\n');\n const start = Math.max(0, line - 3);\n const end = Math.min(lines.length, line + 2);\n \n return lines.slice(start, end).map((l: string, idx: number) => {\n const lineNum = start + idx + 1;\n const marker = lineNum === line ? '→' : ' ';\n return `${marker} ${lineNum.toString().padStart(4)} | ${l}`;\n }).join('\\n');\n } catch {\n return null;\n }\n }\n\n private getAgentEmoji(agentName: string): string {\n const emojis: Record<string, string> = {\n 'security': '🔒',\n 'privacy': '👤',\n 'legal': '⚖️',\n 'accessibility': '♿',\n 'design-engineer': '🎨',\n 'software-architect': '🏗️',\n 'bug-finding': '🐛',\n 'user-testing': '🎯',\n 'typecheck': '📝',\n 'devops': '⚙️',\n 'comprehension': '📖',\n 'test': '🧪'\n };\n return emojis[agentName] || '🤖';\n }\n\n private async discoverFiles(dir: string, maxFiles: number = 200): Promise<string[]> {\n const files: string[] = [];\n \n async function walk(currentDir: string) {\n if (files.length >= maxFiles) return;\n \n try {\n const entries = await readdir(currentDir, { withFileTypes: true });\n \n for (const entry of entries) {\n if (files.length >= maxFiles) break;\n \n const fullPath = join(currentDir, entry.name);\n \n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith('.')) {\n await walk(fullPath);\n }\n } else if (entry.isFile()) {\n const ext = extname(entry.name).toLowerCase();\n if (SCANNABLE_EXTENSIONS.has(ext)) {\n files.push(fullPath);\n }\n }\n }\n } catch (error) {\n // Skip directories we can't read\n }\n }\n \n await walk(dir);\n return files;\n }\n}\n","/**\n * Knowledge Module - External information lookup\n * \n * This module provides structured prompts for looking up:\n * - CVE databases\n * - Security advisories\n * - Framework documentation\n * - Best practices\n * \n * The MCP returns these as prompts, and Claude (with web access) \n * can then look up the information.\n */\n\nexport interface KnowledgeRequest {\n type: 'cve' | 'docs' | 'security' | 'best-practices' | 'changelog';\n query: string;\n context?: Record<string, string>;\n}\n\nexport interface KnowledgeSource {\n name: string;\n url: string;\n description: string;\n}\n\n/**\n * Security-related knowledge sources\n */\nexport const SECURITY_SOURCES: KnowledgeSource[] = [\n {\n name: 'OWASP Top 10',\n url: 'https://owasp.org/Top10/',\n description: 'Most critical web application security risks'\n },\n {\n name: 'NIST NVD',\n url: 'https://nvd.nist.gov/',\n description: 'National Vulnerability Database'\n },\n {\n name: 'CVE Database',\n url: 'https://cve.mitre.org/',\n description: 'Common Vulnerabilities and Exposures'\n },\n {\n name: 'Snyk Vulnerability DB',\n url: 'https://security.snyk.io/',\n description: 'Open source vulnerability database'\n },\n {\n name: 'GitHub Advisory Database',\n url: 'https://github.com/advisories',\n description: 'Security advisories from GitHub'\n }\n];\n\n/**\n * Framework documentation sources\n */\nexport const DOCS_SOURCES: Record<string, KnowledgeSource[]> = {\n react: [\n { name: 'React Docs', url: 'https://react.dev/', description: 'Official React documentation' },\n { name: 'React Security', url: 'https://react.dev/reference/react-dom/components/common#dangerously-setting-the-inner-html', description: 'React security guidance' },\n ],\n nextjs: [\n { name: 'Next.js Docs', url: 'https://nextjs.org/docs', description: 'Official Next.js documentation' },\n { name: 'Next.js Security', url: 'https://nextjs.org/docs/advanced-features/security-headers', description: 'Next.js security headers' },\n ],\n express: [\n { name: 'Express Docs', url: 'https://expressjs.com/', description: 'Official Express.js documentation' },\n { name: 'Express Security', url: 'https://expressjs.com/en/advanced/best-practice-security.html', description: 'Express security best practices' },\n ],\n node: [\n { name: 'Node.js Docs', url: 'https://nodejs.org/docs/', description: 'Official Node.js documentation' },\n { name: 'Node.js Security', url: 'https://nodejs.org/en/docs/guides/security/', description: 'Node.js security guidance' },\n ],\n typescript: [\n { name: 'TypeScript Docs', url: 'https://www.typescriptlang.org/docs/', description: 'Official TypeScript documentation' },\n ],\n};\n\n/**\n * Compliance-related sources\n */\nexport const COMPLIANCE_SOURCES: Record<string, KnowledgeSource[]> = {\n gdpr: [\n { name: 'GDPR Official Text', url: 'https://gdpr.eu/', description: 'Complete GDPR regulation text' },\n { name: 'GDPR Checklist', url: 'https://gdpr.eu/checklist/', description: 'GDPR compliance checklist' },\n ],\n hipaa: [\n { name: 'HIPAA Guidelines', url: 'https://www.hhs.gov/hipaa/', description: 'Official HIPAA guidance' },\n ],\n wcag: [\n { name: 'WCAG 2.1', url: 'https://www.w3.org/WAI/WCAG21/quickref/', description: 'WCAG 2.1 quick reference' },\n ],\n pci: [\n { name: 'PCI DSS', url: 'https://www.pcisecuritystandards.org/', description: 'Payment Card Industry standards' },\n ],\n};\n\n/**\n * Generate a CVE lookup prompt\n */\nexport function generateCVELookup(library: string, version?: string): string {\n let prompt = `## 🔒 Security Vulnerability Lookup\\n\\n`;\n prompt += `**Library:** ${library}\\n`;\n if (version) prompt += `**Version:** ${version}\\n`;\n prompt += `\\n`;\n\n prompt += `### Action Required\\n\\n`;\n prompt += `Please check for known vulnerabilities:\\n\\n`;\n prompt += `1. Search the **NIST NVD** (https://nvd.nist.gov/) for CVEs affecting \\`${library}\\`\\n`;\n prompt += `2. Check **Snyk** (https://security.snyk.io/) for vulnerability reports\\n`;\n prompt += `3. Review **GitHub Advisory Database** for any security advisories\\n`;\n prompt += `4. Check npm audit / yarn audit if it's an npm package\\n\\n`;\n\n prompt += `### Report Format\\n\\n`;\n prompt += `For each vulnerability found, provide:\\n`;\n prompt += `- CVE ID (if applicable)\\n`;\n prompt += `- Severity (Critical/High/Medium/Low)\\n`;\n prompt += `- Affected versions\\n`;\n prompt += `- Description of the vulnerability\\n`;\n prompt += `- Remediation (upgrade version, patches, mitigations)\\n`;\n\n return prompt;\n}\n\n/**\n * Generate a documentation lookup prompt\n */\nexport function generateDocsLookup(topic: string, framework?: string): string {\n let prompt = `## 📚 Documentation Lookup\\n\\n`;\n prompt += `**Topic:** ${topic}\\n`;\n if (framework) prompt += `**Framework:** ${framework}\\n`;\n prompt += `\\n`;\n\n const sources = framework ? DOCS_SOURCES[framework.toLowerCase()] : [];\n \n if (sources && sources.length > 0) {\n prompt += `### Recommended Sources\\n\\n`;\n for (const source of sources) {\n prompt += `- [${source.name}](${source.url}) - ${source.description}\\n`;\n }\n prompt += `\\n`;\n }\n\n prompt += `### Information Needed\\n\\n`;\n prompt += `Please look up the latest documentation and provide:\\n\\n`;\n prompt += `1. Current best practices for \"${topic}\"\\n`;\n prompt += `2. Common pitfalls to avoid\\n`;\n prompt += `3. Code examples demonstrating correct usage\\n`;\n prompt += `4. Any recent changes or deprecations\\n`;\n\n return prompt;\n}\n\n/**\n * Generate a security best practices lookup prompt\n */\nexport function generateSecurityLookup(pattern: string, context?: string): string {\n let prompt = `## 🛡️ Security Best Practices Lookup\\n\\n`;\n prompt += `**Pattern:** ${pattern}\\n`;\n if (context) prompt += `**Context:** ${context}\\n`;\n prompt += `\\n`;\n\n prompt += `### Reference Sources\\n\\n`;\n for (const source of SECURITY_SOURCES.slice(0, 3)) {\n prompt += `- [${source.name}](${source.url})\\n`;\n }\n prompt += `\\n`;\n\n prompt += `### Analysis Requested\\n\\n`;\n prompt += `Please research and provide:\\n\\n`;\n prompt += `1. **OWASP guidance** for this security pattern\\n`;\n prompt += `2. **Attack vectors** - how this could be exploited\\n`;\n prompt += `3. **Defense strategies** - recommended mitigations\\n`;\n prompt += `4. **Code examples** - secure implementation patterns\\n`;\n prompt += `5. **Testing approaches** - how to verify security\\n`;\n\n return prompt;\n}\n\n/**\n * Generate a compliance lookup prompt\n */\nexport function generateComplianceLookup(regulation: string, requirement?: string): string {\n let prompt = `## ⚖️ Compliance Requirement Lookup\\n\\n`;\n prompt += `**Regulation:** ${regulation}\\n`;\n if (requirement) prompt += `**Specific Requirement:** ${requirement}\\n`;\n prompt += `\\n`;\n\n const sources = COMPLIANCE_SOURCES[regulation.toLowerCase()];\n \n if (sources && sources.length > 0) {\n prompt += `### Official Sources\\n\\n`;\n for (const source of sources) {\n prompt += `- [${source.name}](${source.url})\\n`;\n }\n prompt += `\\n`;\n }\n\n prompt += `### Compliance Information Needed\\n\\n`;\n prompt += `Please research and provide:\\n\\n`;\n prompt += `1. **Specific requirement text** from the regulation\\n`;\n prompt += `2. **Technical requirements** for compliance\\n`;\n prompt += `3. **Implementation guidance** with code examples\\n`;\n prompt += `4. **Documentation requirements** - what records to keep\\n`;\n prompt += `5. **Penalties** for non-compliance\\n`;\n\n return prompt;\n}\n\n/**\n * Generate a changelog/version lookup prompt\n */\nexport function generateChangelogLookup(library: string, fromVersion: string, toVersion?: string): string {\n let prompt = `## 📋 Changelog Lookup\\n\\n`;\n prompt += `**Library:** ${library}\\n`;\n prompt += `**Current Version:** ${fromVersion}\\n`;\n if (toVersion) prompt += `**Target Version:** ${toVersion}\\n`;\n prompt += `\\n`;\n\n prompt += `### Information Needed\\n\\n`;\n prompt += `Please find the changelog/release notes and provide:\\n\\n`;\n prompt += `1. **Breaking changes** between versions\\n`;\n prompt += `2. **New features** added\\n`;\n prompt += `3. **Deprecations** to be aware of\\n`;\n prompt += `4. **Security fixes** included\\n`;\n prompt += `5. **Migration guide** if available\\n`;\n prompt += `6. **Known issues** with the upgrade\\n`;\n\n return prompt;\n}\n\n/**\n * Main knowledge lookup function\n */\nexport function lookupKnowledge(request: KnowledgeRequest): string {\n const { type, query, context = {} } = request;\n\n switch (type) {\n case 'cve':\n return generateCVELookup(query, context.version);\n \n case 'docs':\n return generateDocsLookup(query, context.framework);\n \n case 'security':\n return generateSecurityLookup(query, context.context);\n \n case 'best-practices':\n return generateComplianceLookup(query, context.requirement);\n \n case 'changelog':\n return generateChangelogLookup(query, context.fromVersion || 'current', context.toVersion);\n \n default:\n return `Unknown knowledge request type: ${type}`;\n }\n}\n\n/**\n * Detect libraries and versions from package.json\n */\nexport async function detectDependencies(packageJsonPath: string): Promise<Map<string, string>> {\n const deps = new Map<string, string>();\n \n try {\n const { readFile } = await import('fs/promises');\n const content = await readFile(packageJsonPath, 'utf-8');\n const pkg = JSON.parse(content);\n \n const allDeps = {\n ...pkg.dependencies,\n ...pkg.devDependencies,\n };\n\n for (const [name, version] of Object.entries(allDeps)) {\n deps.set(name, String(version).replace(/^[\\^~]/, ''));\n }\n } catch {\n // Ignore errors\n }\n\n return deps;\n}\n\n/**\n * Known vulnerable packages (quick check - not exhaustive)\n */\nexport const KNOWN_VULNERABLE_PATTERNS = [\n { pattern: /^lodash$/, minSafeVersion: '4.17.21', reason: 'Prototype pollution' },\n { pattern: /^minimist$/, minSafeVersion: '1.2.6', reason: 'Prototype pollution' },\n { pattern: /^node-fetch$/, minSafeVersion: '2.6.7', reason: 'URL bypass' },\n { pattern: /^axios$/, minSafeVersion: '1.6.0', reason: 'SSRF vulnerability' },\n { pattern: /^jsonwebtoken$/, minSafeVersion: '9.0.0', reason: 'Algorithm confusion' },\n];\n\n","/**\n * MCP Tool: trie_create_agent\n * \n * Creates a custom agent from a PDF, TXT, MD, or RTF document.\n * \n * This is a two-step process that leverages the host LLM (Claude in Cursor/Claude Code):\n * 1. trie_create_agent - Parses document and returns extraction prompt\n * 2. trie_save_agent - Saves the agent config after Claude processes it\n * \n * This design eliminates the need for a separate ANTHROPIC_API_KEY since\n * the user is already in an AI workflow with Claude.\n */\n\nimport { parseDocument } from '../ingest/document-parser.js';\nimport { listCustomAgents, loadAgentConfig } from '../ingest/agent-builder.js';\nimport type { GeneratedAgentConfig, CompressedKnowledge } from '../types/custom-agent.js';\nimport { existsSync } from 'fs';\nimport { mkdir, writeFile } from 'fs/promises';\nimport { join, basename, extname } from 'path';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport class TrieCreateAgentTool {\n async execute(args: {\n filePath?: string;\n documentContent?: string;\n agentName: string;\n displayName?: string;\n description?: string;\n category?: string;\n }) {\n const { filePath, documentContent, agentName, displayName, description, category } = args;\n \n // Validate inputs\n if (!agentName) {\n return this.errorResponse('Missing required parameter: agentName');\n }\n \n // Either filePath or documentContent must be provided\n if (!filePath && !documentContent) {\n return this.errorResponse(\n 'Provide either filePath (path to PDF/TXT/MD file) or documentContent (raw text from drag-and-drop)'\n );\n }\n \n try {\n let rawText: string;\n let title: string = agentName;\n let wordCount: number = 0;\n \n if (filePath) {\n // Check if file exists\n if (!existsSync(filePath)) {\n return this.errorResponse(`File not found: ${filePath}`);\n }\n \n // Check supported file types\n const ext = filePath.toLowerCase().split('.').pop();\n if (!['pdf', 'txt', 'md', 'markdown', 'rtf'].includes(ext || '')) {\n return this.errorResponse(\n `Unsupported file type: .${ext}\\nSupported types: .pdf, .txt, .md, .rtf`\n );\n }\n \n // Parse the document\n const document = await parseDocument(filePath);\n rawText = document.rawText;\n // fileType is available in document.metadata.fileType if needed\n title = document.metadata.title || basename(filePath, extname(filePath));\n wordCount = document.metadata.wordCount;\n } else {\n // Use provided document content (from drag-and-drop)\n rawText = documentContent!;\n wordCount = rawText.split(/\\s+/).filter(w => w.length > 0).length;\n \n // Try to extract title from first line\n const firstLine = rawText.split('\\n')[0]?.trim();\n if (firstLine && firstLine.length < 100) {\n title = firstLine;\n }\n }\n \n // Chunk the document for processing\n const chunks = this.chunkText(rawText, 6000);\n \n // Build the extraction prompt that Claude will process\n const extractionPrompt = this.buildExtractionPrompt(\n chunks,\n title,\n agentName,\n category,\n displayName,\n description\n );\n \n // Return the prompt for Claude to process\n return {\n content: [\n {\n type: 'text',\n text: this.formatExtractionRequest(\n agentName,\n title,\n wordCount,\n chunks.length,\n extractionPrompt\n ),\n },\n ],\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return this.errorResponse(`Failed to parse document: ${errorMessage}`);\n }\n }\n \n /**\n * Chunk text into manageable pieces\n */\n private chunkText(text: string, maxChunkSize: number): string[] {\n if (text.length <= maxChunkSize) {\n return [text];\n }\n \n const chunks: string[] = [];\n const paragraphs = text.split(/\\n\\s*\\n/);\n let currentChunk = '';\n \n for (const para of paragraphs) {\n if (currentChunk.length + para.length + 2 > maxChunkSize) {\n if (currentChunk) chunks.push(currentChunk.trim());\n currentChunk = para;\n } else {\n currentChunk += (currentChunk ? '\\n\\n' : '') + para;\n }\n }\n \n if (currentChunk) chunks.push(currentChunk.trim());\n return chunks;\n }\n \n /**\n * Build the extraction prompt for Claude\n */\n private buildExtractionPrompt(\n chunks: string[],\n title: string,\n agentName: string,\n category?: string,\n displayName?: string,\n description?: string\n ): string {\n const prefix = agentName.toUpperCase().replace(/[^A-Z]/g, '').slice(0, 4) || 'CUST';\n \n // Combine chunks with separators\n const documentContent = chunks.length === 1 \n ? chunks[0]\n : chunks.map((c, i) => `--- SECTION ${i + 1}/${chunks.length} ---\\n${c}`).join('\\n\\n');\n \n return `# Create Code Review Agent: \"${displayName || this.formatDisplayName(agentName)}\"\n\n## Your Task\nAnalyze the following document and extract structured knowledge to create a code review agent.\n\n## Document Information\n- **Title**: ${title}\n- **Agent Name**: ${agentName}\n- **Category**: ${category || 'auto-detect'}\n${description ? `- **Description**: ${description}` : ''}\n\n## Document Content\n${documentContent}\n\n---\n\n## Instructions\n\nPlease analyze this document and produce a **single JSON object** with the following structure. This will be used to create a custom code review agent.\n\n**IMPORTANT**: Your response should be ONLY the JSON object, no other text.\n\n\\`\\`\\`json\n{\n \"agentConfig\": {\n \"name\": \"${this.sanitizeAgentName(agentName)}\",\n \"displayName\": \"${displayName || this.formatDisplayName(agentName)}\",\n \"description\": \"${description || `Code review agent based on ${title}`}\",\n \"version\": \"1.0.0\",\n \"category\": \"string (technical | legal | policy | security | architecture | general)\"\n },\n \"knowledge\": {\n \"domain\": \"string (technical | legal | policy | security | architecture | general)\",\n \"summary\": \"2-3 paragraph summary of the document's key insights for code review\",\n \"coreConcepts\": [\n {\n \"name\": \"string\",\n \"description\": \"string\",\n \"importance\": \"critical | important | supplementary\",\n \"keywords\": [\"string\"]\n }\n ],\n \"bestPractices\": [\n {\n \"name\": \"string\",\n \"description\": \"string\",\n \"rationale\": \"why this is important\",\n \"codeExample\": \"optional code example or null\"\n }\n ],\n \"antiPatterns\": [\n {\n \"name\": \"string\",\n \"description\": \"string\",\n \"whyBad\": \"why to avoid\",\n \"betterAlternative\": \"what to do instead\"\n }\n ],\n \"glossary\": {\n \"term\": \"definition\"\n }\n },\n \"detectionRules\": [\n {\n \"id\": \"${prefix}-001\",\n \"name\": \"Rule Name\",\n \"description\": \"What this rule detects\",\n \"severity\": \"critical | serious | moderate | low | info\",\n \"patterns\": {\n \"regex\": [\"JavaScript regex patterns\"],\n \"keywords\": [\"words that indicate this issue\"],\n \"semantic\": \"Natural language description for AI detection\"\n },\n \"fix\": {\n \"description\": \"How to fix this issue\",\n \"example\": \"Code example or null\",\n \"autoFixable\": false\n },\n \"category\": \"string\"\n }\n ],\n \"prompts\": {\n \"systemPrompt\": \"You are an expert code reviewer specializing in [topic]. Your role is to...\",\n \"analysisPrompt\": \"Review this code for issues related to [topic]. Look for: ...\\\\n\\\\nCode:\\\\n\\\\\\`\\\\\\`\\\\\\`{{language}}\\\\n{{code}}\\\\n\\\\\\`\\\\\\`\\\\\\`\\\\n\\\\nFile: {{filePath}}\",\n \"fixPrompt\": \"Fix this issue: {{issue}}\\\\n\\\\nCode:\\\\n\\\\\\`\\\\\\`\\\\\\`{{language}}\\\\n{{code}}\\\\n\\\\\\`\\\\\\`\\\\\\`\"\n }\n}\n\\`\\`\\`\n\n## Guidelines\n\n1. **Core Concepts**: Extract 10-20 key concepts that are fundamental to the material\n2. **Best Practices**: Extract 10-15 recommended approaches with rationale\n3. **Anti-Patterns**: Extract 10-15 things to avoid with explanations\n4. **Detection Rules**: Generate 15-30 rules with regex patterns that could detect issues in code\n5. **Prompts**: Create prompts that embody the expertise from this document\n\nFocus on extracting actionable, code-reviewable knowledge. The agent should be able to find violations of the principles in this document.\n\n**Output ONLY the JSON object, starting with \\`{\\` and ending with \\`}\\`.**`;\n }\n \n /**\n * Format the extraction request output\n */\n private formatExtractionRequest(\n agentName: string,\n title: string,\n wordCount: number,\n chunkCount: number,\n prompt: string\n ): string {\n return `\n📚 **Document Parsed Successfully!**\n\n${'━'.repeat(50)}\n\n**Creating Agent:** \\`${agentName}\\`\n**Source Document:** ${title}\n**Word Count:** ${wordCount.toLocaleString()}\n**Processing Chunks:** ${chunkCount}\n\n${'━'.repeat(50)}\n\n## Next Step\n\nI've prepared the document for analysis. Please process the following prompt to extract the knowledge, then pass the result to \\`trie_save_agent\\` to save the agent.\n\n${'─'.repeat(50)}\n\n${prompt}\n`;\n }\n \n private sanitizeAgentName(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '');\n }\n \n private formatDisplayName(name: string): string {\n return name\n .split(/[-_]/)\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n }\n \n private errorResponse(message: string) {\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error:** ${message}`,\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * MCP Tool: trie_save_agent\n * \n * Saves an agent configuration after Claude has processed the document.\n * This is step 2 of the agent creation process.\n */\nexport class TrieSaveAgentTool {\n async execute(args: {\n agentConfig: {\n name: string;\n displayName: string;\n description: string;\n version?: string;\n category: string;\n };\n knowledge: {\n domain: string;\n summary: string;\n coreConcepts: Array<{\n name: string;\n description: string;\n importance: string;\n keywords?: string[];\n }>;\n bestPractices: Array<{\n name: string;\n description: string;\n rationale: string;\n codeExample?: string | null;\n }>;\n antiPatterns: Array<{\n name: string;\n description: string;\n whyBad: string;\n betterAlternative: string;\n }>;\n glossary?: Record<string, string>;\n };\n detectionRules: Array<{\n id: string;\n name: string;\n description: string;\n severity: string;\n patterns: {\n regex?: string[];\n keywords?: string[];\n semantic?: string;\n };\n fix: {\n description: string;\n example?: string | null;\n autoFixable?: boolean;\n };\n category?: string;\n }>;\n prompts: {\n systemPrompt: string;\n analysisPrompt: string;\n fixPrompt: string;\n };\n sourceFile?: string;\n }) {\n const { agentConfig, knowledge, detectionRules, prompts, sourceFile } = args;\n \n // Validate required fields\n if (!agentConfig?.name) {\n return this.errorResponse('Missing agentConfig.name');\n }\n \n if (!knowledge?.summary) {\n return this.errorResponse('Missing knowledge.summary');\n }\n \n if (!prompts?.systemPrompt) {\n return this.errorResponse('Missing prompts.systemPrompt');\n }\n \n try {\n // Build the full agent config\n const fullConfig: GeneratedAgentConfig = {\n name: this.sanitizeAgentName(agentConfig.name),\n displayName: agentConfig.displayName || this.formatDisplayName(agentConfig.name),\n description: agentConfig.description,\n version: agentConfig.version || '1.0.0',\n category: agentConfig.category || knowledge.domain || 'general',\n \n source: {\n type: 'document',\n originalFile: sourceFile || 'user-provided',\n fileType: 'txt',\n compressedAt: new Date().toISOString(),\n },\n \n systemPrompt: prompts.systemPrompt,\n analysisPrompt: prompts.analysisPrompt,\n fixPrompt: prompts.fixPrompt,\n \n activationRules: this.buildActivationRules(knowledge, detectionRules),\n \n patterns: detectionRules.map((rule, i) => {\n const fixObj: { description: string; autoFixable: boolean; example?: string } = {\n description: rule.fix?.description || 'Review and fix manually',\n autoFixable: rule.fix?.autoFixable || false,\n };\n if (rule.fix?.example) {\n fixObj.example = rule.fix.example;\n }\n return {\n id: rule.id || `CUST-${String(i + 1).padStart(3, '0')}`,\n name: rule.name,\n description: rule.description,\n severity: (rule.severity as 'critical' | 'serious' | 'moderate' | 'low' | 'info') || 'moderate',\n patterns: {\n regex: rule.patterns?.regex || [],\n keywords: rule.patterns?.keywords || [],\n semantic: rule.patterns?.semantic || '',\n },\n fix: fixObj,\n category: rule.category || agentConfig.category,\n };\n }),\n \n knowledge: {\n domain: (knowledge.domain as CompressedKnowledge['domain']) || 'general',\n summary: knowledge.summary,\n coreConcepts: knowledge.coreConcepts.map(c => ({\n name: c.name,\n description: c.description,\n importance: (c.importance as 'critical' | 'important' | 'supplementary') || 'important',\n relatedPatterns: (c as any).relatedPatterns || [],\n keywords: c.keywords || [],\n })),\n bestPractices: knowledge.bestPractices.map(bp => {\n const practice: { name: string; description: string; rationale: string; category: string; codeExample?: string } = {\n name: bp.name,\n description: bp.description,\n rationale: bp.rationale,\n category: (bp as any).category || agentConfig.category,\n };\n if (bp.codeExample) {\n practice.codeExample = bp.codeExample;\n }\n return practice;\n }),\n antiPatterns: knowledge.antiPatterns.map(ap => ({\n name: ap.name,\n description: ap.description,\n whyBad: ap.whyBad,\n betterAlternative: ap.betterAlternative,\n })),\n detectionRules: [],\n glossary: knowledge.glossary || {},\n sourceDocument: {\n title: agentConfig.displayName || agentConfig.name,\n wordCount: 0,\n compressionRatio: 0,\n },\n },\n };\n \n // Save the config\n const configPath = await this.saveAgentConfig(fullConfig);\n \n return {\n content: [\n {\n type: 'text',\n text: this.formatSuccessResponse(fullConfig, configPath),\n },\n ],\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return this.errorResponse(`Failed to save agent: ${errorMessage}`);\n }\n }\n \n private buildActivationRules(\n knowledge: { domain: string; coreConcepts: Array<{ keywords?: string[] }> },\n detectionRules: Array<{ patterns: { keywords?: string[] } }>\n ): GeneratedAgentConfig['activationRules'] {\n const domainRules: Record<string, Partial<GeneratedAgentConfig['activationRules']>> = {\n technical: {\n filePatterns: ['*.ts', '*.tsx', '*.js', '*.jsx', '*.py', '*.go', '*.rs'],\n contextSignals: ['touchesUI', 'touchesAPI'],\n priority: 2,\n },\n legal: {\n filePatterns: ['*'],\n contextSignals: ['touchesUserData', 'touchesAuth', 'touchesPayments'],\n priority: 2,\n },\n policy: {\n filePatterns: ['*'],\n contextSignals: ['touchesAuth', 'touchesAPI', 'touchesDatabase'],\n priority: 3,\n },\n security: {\n filePatterns: ['*'],\n contextSignals: ['touchesAuth', 'touchesCrypto', 'touchesAPI', 'touchesDatabase'],\n priority: 1,\n },\n architecture: {\n filePatterns: ['*.ts', '*.tsx', '*.js', '*.jsx', '*.py', '*.go'],\n contextSignals: ['touchesAPI', 'touchesDatabase'],\n priority: 2,\n },\n general: {\n filePatterns: ['*'],\n contextSignals: [],\n priority: 3,\n },\n };\n \n const defaults = domainRules[knowledge.domain] || domainRules.general!;\n \n // Extract content patterns from rules and concepts\n const contentPatterns: string[] = [];\n for (const rule of detectionRules) {\n if (rule.patterns?.keywords) {\n contentPatterns.push(...rule.patterns.keywords.slice(0, 3));\n }\n }\n for (const concept of knowledge.coreConcepts.slice(0, 5)) {\n if (concept.keywords) {\n contentPatterns.push(...concept.keywords.slice(0, 2));\n }\n }\n \n return {\n filePatterns: defaults.filePatterns || ['*'],\n contentPatterns: [...new Set(contentPatterns)].slice(0, 20),\n contextSignals: defaults.contextSignals || [],\n minConfidence: 0.3,\n priority: defaults.priority || 2,\n };\n }\n \n private async saveAgentConfig(config: GeneratedAgentConfig): Promise<string> {\n const trieDir = join(getWorkingDirectory(undefined, true), '.trie', 'agents');\n await mkdir(trieDir, { recursive: true });\n \n const configPath = join(trieDir, `${config.name}.json`);\n await writeFile(configPath, JSON.stringify(config, null, 2));\n \n return configPath;\n }\n \n private formatSuccessResponse(config: GeneratedAgentConfig, configPath: string): string {\n return `\n✅ **Agent Created Successfully!**\n\n${'━'.repeat(50)}\n\n**Agent Name:** \\`${config.name}\\`\n**Display Name:** ${config.displayName}\n**Category:** ${config.category}\n**Config Saved To:** \\`${configPath}\\`\n\n📊 **Statistics:**\n • Core concepts: ${config.knowledge.coreConcepts.length}\n • Best practices: ${config.knowledge.bestPractices.length}\n • Anti-patterns: ${config.knowledge.antiPatterns.length}\n • Detection rules: ${config.patterns.length}\n\n🚀 **Next Steps:**\n 1. The agent is now registered and will activate during scans\n 2. Run \\`trie_scan\\` to test the new agent\n 3. Edit \\`${configPath}\\` to customize detection rules\n\n💡 **Usage:**\n The agent will automatically activate when scanning code that matches its patterns.\n Use \\`trie_list_agents\\` to see all registered agents.\n`.trim();\n }\n \n private sanitizeAgentName(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '');\n }\n \n private formatDisplayName(name: string): string {\n return name\n .split(/[-_]/)\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n }\n \n private errorResponse(message: string) {\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error:** ${message}`,\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * MCP Tool: trie_list_agents\n * \n * Lists all registered agents including custom ones\n */\nexport class TrieListAgentsTool {\n async execute(args: { includeBuiltin?: boolean }) {\n const { includeBuiltin = true } = args;\n \n try {\n // Get custom agents\n const customAgentNames = await listCustomAgents();\n const customAgents = await Promise.all(\n customAgentNames.map(async name => {\n const config = await loadAgentConfig(name);\n return config ? {\n name: config.name,\n displayName: config.displayName,\n category: config.category,\n source: config.source.originalFile,\n patterns: config.patterns.length,\n isCustom: true,\n } : null;\n })\n );\n \n const validCustomAgents = customAgents.filter(Boolean);\n \n // Built-in agents (20 total)\n const builtinAgents = includeBuiltin ? [\n // Security & Compliance\n { name: 'security', displayName: 'Security Agent', category: 'security', isCustom: false },\n { name: 'privacy', displayName: 'Privacy Agent', category: 'privacy', isCustom: false },\n { name: 'soc2', displayName: 'SOC 2 Agent', category: 'compliance', isCustom: false },\n { name: 'legal', displayName: 'Legal Agent', category: 'compliance', isCustom: false },\n // Code Quality\n { name: 'software-architect', displayName: 'Architecture Agent', category: 'architecture', isCustom: false },\n { name: 'bug-finding', displayName: 'Bug Finding Agent', category: 'quality', isCustom: false },\n { name: 'typecheck', displayName: 'TypeCheck Agent', category: 'quality', isCustom: false },\n { name: 'trie-clean', displayName: 'Clean Agent', category: 'ai-code', isCustom: false },\n { name: 'data-flow', displayName: 'Data Flow Agent', category: 'quality', isCustom: false },\n // Design & UX\n { name: 'design-engineer', displayName: 'Design Engineer Agent', category: 'design', isCustom: false },\n { name: 'accessibility', displayName: 'Accessibility Agent', category: 'accessibility', isCustom: false },\n { name: 'user-testing', displayName: 'UX Agent', category: 'ux', isCustom: false },\n { name: 'visual-qa', displayName: 'Visual QA Agent', category: 'visual', isCustom: false },\n // DevOps & Testing\n { name: 'devops', displayName: 'DevOps Agent', category: 'devops', isCustom: false },\n { name: 'test', displayName: 'Test Agent', category: 'testing', isCustom: false },\n { name: 'e2e', displayName: 'E2E Agent', category: 'testing', isCustom: false },\n { name: 'performance', displayName: 'Performance Agent', category: 'performance', isCustom: false },\n // Review & Explanation\n { name: 'super-reviewer', displayName: 'Super Reviewer', category: 'review', isCustom: false },\n { name: 'agent-smith', displayName: 'Agent Smith', category: 'review', isCustom: false },\n { name: 'comprehension', displayName: 'Comprehension Agent', category: 'communication', isCustom: false },\n ] : [];\n \n // Format response\n let response = `# 🤖 Registered Agents\\n\\n`;\n \n if (builtinAgents.length > 0) {\n response += `## Built-in Agents (${builtinAgents.length})\\n\\n`;\n for (const agent of builtinAgents) {\n response += `- **${agent.displayName}** (\\`${agent.name}\\`) - ${agent.category}\\n`;\n }\n response += '\\n';\n }\n \n response += `## Custom Agents (${validCustomAgents.length})\\n\\n`;\n \n if (validCustomAgents.length === 0) {\n response += `_No custom agents created yet._\\n\\n`;\n response += `💡 Create one with: \\`trie_create_agent\\`\\n`;\n response += ` - Provide a PDF, TXT, or MD file path\\n`;\n response += ` - Or paste/drag document content directly\\n`;\n } else {\n for (const agent of validCustomAgents) {\n if (agent) {\n response += `- **${agent.displayName}** (\\`${agent.name}\\`)\\n`;\n response += ` - Category: ${agent.category}\\n`;\n response += ` - Patterns: ${agent.patterns}\\n`;\n response += ` - Source: ${agent.source}\\n\\n`;\n }\n }\n }\n \n return {\n content: [\n {\n type: 'text',\n text: response,\n },\n ],\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return {\n content: [\n {\n type: 'text',\n text: `❌ Error listing agents: ${errorMessage}`,\n },\n ],\n isError: true,\n };\n }\n }\n}\n","import { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join, basename, resolve, isAbsolute } from 'path';\nimport { execSync } from 'child_process';\nimport { SuperReviewerAgent, CRITICAL_REVIEW_CHECKLIST } from '../agents/super-reviewer.js';\nimport { getWorkingDirectory } from '../utils/workspace.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 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 execSync('git branch --show-current', { encoding: 'utf-8' }).trim();\n \n // Check if there's a PR for this branch\n const prJson = execSync(`gh pr view --json number,title,author,headRefName,baseRefName`, {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe']\n }).trim();\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 = execSync(`gh pr view ${prNumber} --json number,title,author,headRefName,baseRefName`, {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe']\n }).trim();\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 = execSync(`gh pr diff ${prInfo.number}`, {\n encoding: 'utf-8',\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer for large PRs\n });\n } else if (prInfo.type === 'worktree' && prInfo.path) {\n // Get diff from worktree\n diffOutput = execSync(`git diff HEAD`, {\n encoding: 'utf-8',\n cwd: prInfo.path,\n maxBuffer: 50 * 1024 * 1024,\n });\n } else {\n // Local changes\n diffOutput = execSync(`git diff HEAD`, {\n encoding: 'utf-8',\n maxBuffer: 50 * 1024 * 1024,\n });\n \n // If no diff, try staged changes\n if (!diffOutput.trim()) {\n diffOutput = execSync(`git diff --cached`, {\n encoding: 'utf-8',\n maxBuffer: 50 * 1024 * 1024,\n });\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 });\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 execSync('git config user.name', { encoding: 'utf-8' }).trim();\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}\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 { TrieRegisterAgentTool } from '../tools/register-agent.js';\nimport { TrieWatchTool } from '../tools/watch.js';\nimport { TrieAgentTool } from '../tools/agent.js';\nimport { TrieCreateAgentTool, TrieSaveAgentTool, TrieListAgentsTool } from '../tools/create-agent.js';\nimport { TriePRReviewTool } from '../tools/pr-review.js';\n\nexport interface ToolDefinition {\n name: string;\n description: string;\n inputSchema: Record<string, any>;\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('register_agent', new TrieRegisterAgentTool());\n this.tools.set('watch', new TrieWatchTool());\n this.tools.set('agent', new TrieAgentTool());\n this.tools.set('create_agent', new TrieCreateAgentTool());\n this.tools.set('save_agent', new TrieSaveAgentTool());\n this.tools.set('list_agents', new TrieListAgentsTool());\n this.tools.set('pr_review', new TriePRReviewTool());\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 },\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, privacy, 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 agent 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_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_register_agent',\n description: 'Register an agent by name and path. Alias: register_agent',\n inputSchema: {\n type: 'object',\n properties: {\n name: { type: 'string', description: 'Name of the agent' },\n path: { type: 'string', description: 'Path to the agent implementation' }\n },\n required: ['name', 'path']\n } as const,\n },\n {\n name: 'trie_list_agents',\n description: 'List built-in and custom agents. Alias: list_agents',\n inputSchema: {\n type: 'object',\n properties: {\n includeBuiltin: {\n type: 'boolean',\n description: 'Include built-in agents (default true)'\n }\n }\n } as const,\n },\n // Add remaining tool definitions...\n this.createAgentToolDefinitions(),\n this.createCustomAgentDefinitions(),\n this.createSpecialAgentDefinitions(),\n ].flat();\n }\n\n private createAgentToolDefinitions(): ToolDefinition[] {\n const agentTypes = [\n { name: 'security', desc: 'detect vulnerabilities, injection risks, auth issues, hardcoded secrets' },\n { name: 'privacy', desc: 'PII handling, GDPR/HIPAA compliance, data encryption' },\n { name: 'legal', desc: 'GDPR, CCPA, consent patterns, data retention compliance' },\n { name: 'accessibility', desc: 'WCAG 2.1 compliance, keyboard nav, screen readers, color contrast' },\n { name: 'design', desc: '🎨 Awwwards-level polish, design systems, motion design, creative CSS' },\n { name: 'architecture', desc: 'code organization, SOLID principles, N+1 queries, scalability' },\n { name: 'bugs', desc: 'null safety, edge cases, common bugs, async issues' },\n { name: 'ux', desc: 'simulate happy path, security tester, confused user, impatient user' },\n { name: 'types', desc: 'type errors, missing annotations, null checks' },\n { name: 'devops', desc: 'config issues, logging, environment variables, deployment patterns' },\n { name: 'clean', desc: '🧹 Clean up AI-generated code: find common mistakes, bad patterns, and quick fixes' },\n { name: 'soc2', desc: 'SOC 2 compliance: access controls, secrets management, encryption, logging, change management' },\n ];\n\n return agentTypes.map(agent => ({\n name: `trie_${agent.name}`,\n description: `Run ${agent.name} agent: ${agent.desc}. Alias: ${agent.name}`,\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n }));\n }\n\n private createCustomAgentDefinitions(): ToolDefinition[] {\n return [\n {\n name: 'trie_create_agent',\n description: '📚 Step 1: Parse a document to create a custom agent. Returns extraction prompt for Claude to process. Alias: create_agent',\n inputSchema: {\n type: 'object',\n properties: {\n filePath: {\n type: 'string',\n description: 'Path to the document file (PDF, TXT, MD, or RTF)'\n },\n documentContent: {\n type: 'string',\n description: 'Raw document text (for drag-and-drop content). Use this OR filePath.'\n },\n agentName: {\n type: 'string',\n description: 'Name for the new agent (e.g., \"react-fundamentals\")'\n },\n displayName: { type: 'string', description: 'Optional display name' },\n description: { type: 'string', description: 'Optional description' },\n category: { type: 'string', description: 'Optional category (e.g., \"security\", \"react\")' }\n },\n required: ['agentName']\n } as const,\n },\n {\n name: 'trie_save_agent',\n description: '📦 Step 2: Save the agent config after Claude extracts knowledge. Alias: save_agent',\n inputSchema: {\n type: 'object',\n properties: {\n agentConfig: {\n type: 'object',\n description: 'Agent configuration',\n properties: {\n name: { type: 'string' },\n displayName: { type: 'string' },\n description: { type: 'string' },\n version: { type: 'string' },\n category: { type: 'string' }\n },\n required: ['name', 'category']\n },\n knowledge: { type: 'object', description: 'Extracted knowledge' },\n detectionRules: { type: 'array', description: 'Detection rules array' },\n prompts: {\n type: 'object',\n properties: {\n systemPrompt: { type: 'string' },\n analysisPrompt: { type: 'string' },\n fixPrompt: { type: 'string' }\n },\n required: ['systemPrompt', 'analysisPrompt', 'fixPrompt']\n }\n },\n required: ['agentConfig', 'knowledge', 'detectionRules', 'prompts']\n } as const,\n }\n ];\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 },\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 },\n {\n name: 'trie_agent_smith',\n description: '🕴️ Agent Smith: Relentless pattern hunter. \"It is... inevitable.\" Alias: agent_smith',\n inputSchema: {\n type: 'object',\n properties: {\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Files to scan (defaults to entire codebase)'\n },\n directory: {\n type: 'string',\n description: 'Directory to scan. Pass the workspace/project root path for accurate results.'\n },\n clear_memory: {\n type: 'boolean',\n description: 'Clear Agent Smith\\'s memory bank'\n },\n show_stats: {\n type: 'boolean',\n description: 'Show memory statistics'\n }\n }\n } as const,\n },\n {\n name: 'trie_smith',\n description: '🕴️ Agent Smith (alias): Hunt AI-generated code anti-patterns. 43 specialized hunters. Alias: smith',\n inputSchema: {\n type: 'object',\n properties: {\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Files to scan (defaults to entire codebase)'\n },\n directory: {\n type: 'string',\n description: 'Directory to scan. Pass the workspace/project root path for accurate results.'\n }\n }\n } as const,\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 } from 'path';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { getAgentRegistry } from '../agents/registry.js';\nimport { loadConfig } from '../config/loader.js';\nimport { getContextForAI, loadContextState } from '../utils/context-state.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\nexport class ResourceManager {\n private agentRegistry = getAgentRegistry();\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',\n description: 'Current project context for AI assistants - read this first',\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://agents',\n name: 'Available Agents',\n description: 'List of all available Trie agents (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\n // Dynamic resources: scan reports\n resources.push(...await this.getScanReportResources());\n\n // Dynamic resources: custom agents\n resources.push(...await this.getCustomAgentResources());\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 getCustomAgentResources(): Promise<Resource[]> {\n try {\n await this.agentRegistry.loadCustomAgents();\n const customAgents = this.agentRegistry.getCustomAgents();\n\n return customAgents.map(agent => ({\n uri: `trie://agents/custom/${agent.name}`,\n name: `Custom Agent: ${agent.name}`,\n description: agent.description,\n mimeType: 'application/json',\n }));\n } catch {\n return []; // No custom agents\n }\n }\n\n /**\n * Read content for a specific resource\n */\n async readResourceContent(uri: string): Promise<ResourceContent> {\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 context state (detailed JSON)\n if (parsedUri === 'context/state') {\n return await this.getContextStateResource(uri);\n }\n\n // Handle agents list\n if (parsedUri === 'agents') {\n return await this.getAgentsResource(uri);\n }\n\n // Handle specific custom agent\n if (parsedUri.startsWith('agents/custom/')) {\n return await this.getCustomAgentResource(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 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 private async getContextResource(uri: string): Promise<ResourceContent> {\n // First try to read the AGENTS.md file\n const workDir = getWorkingDirectory(undefined, true);\n const agentsMdPath = join(workDir, '.trie', 'AGENTS.md');\n \n try {\n if (existsSync(agentsMdPath)) {\n const content = await readFile(agentsMdPath, 'utf-8');\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: content,\n }],\n };\n }\n } catch {\n // Fall back to generated context\n }\n \n // Fall back to generated context summary\n const contextSummary = await getContextForAI();\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: contextSummary,\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 getAgentsResource(uri: string): Promise<ResourceContent> {\n await this.agentRegistry.loadCustomAgents();\n const agents = this.agentRegistry.getAgentDescriptions();\n\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n totalAgents: agents.length,\n builtinCount: agents.filter(a => !a.isCustom).length,\n customCount: agents.filter(a => a.isCustom).length,\n agents: agents.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 getCustomAgentResource(uri: string, parsedUri: string): Promise<ResourceContent> {\n const agentName = parsedUri.replace('agents/custom/', '');\n await this.agentRegistry.loadCustomAgents();\n const metadata = this.agentRegistry.getCustomAgentMetadata(agentName);\n\n if (!metadata) {\n throw new Error(`Custom agent not found: ${agentName}`);\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(getWorkingDirectory(undefined, true), '.trie', '.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 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}","import { chromium, Browser, Page } from 'playwright';\nimport { createServer, Server } from 'net';\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 */\nasync function findOpenPort(): Promise<number | null> {\n const commonPorts = [3000, 3001, 5173, 5174, 4200, 8080, 8000, 8888, 5000, 4000];\n \n for (const port of commonPorts) {\n const isOpen = await checkPort(port);\n if (isOpen) {\n return port;\n }\n }\n return null;\n}\n\n/**\n * Check if a port has something listening on it\n */\nasync function checkPort(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const server: Server = createServer();\n \n server.once('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EADDRINUSE') {\n // Port is in use - something is running!\n resolve(true);\n } else {\n resolve(false);\n }\n });\n \n server.once('listening', () => {\n // Port is free - nothing running\n server.close();\n resolve(false);\n });\n \n server.listen(port, '127.0.0.1');\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 const port = options.port || await findOpenPort();\n \n if (!port) {\n return {\n success: false,\n url: '',\n screenshots: [],\n error: 'No running dev server found. Please provide a URL or start your dev server on a common port (3000, 5173, 8080, etc.)',\n analysisPrompt: '',\n };\n }\n \n url = `http://localhost:${port}`;\n }\n\n const viewports = options.viewports || DEFAULT_VIEWPORTS;\n\n try {\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 const screenshots = await captureScreenshots(url, viewports, {\n waitForSelector: options.waitForSelector,\n waitMs: options.waitMs,\n });\n\n console.error(` ✓ Captured ${screenshots.length} screenshots`);\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')) {\n return {\n success: false,\n url,\n screenshots: [],\n error: `Cannot connect to ${url}. Is your dev server running?`,\n analysisPrompt: '',\n };\n }\n \n if (errorMessage.includes('Executable doesn\\'t exist')) {\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 return {\n success: false,\n url,\n screenshots: [],\n error: `Screenshot capture failed: ${errorMessage}`,\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 'privacy':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'privacy' });\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 const result = await runVisualQA(args as { url?: string; port?: number; waitForSelector?: string; waitMs?: number });\n return formatMCPResponse(result);\n }\n\n case 'data_flow':\n case 'dataflow':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'data-flow' });\n\n // Custom agent tools\n case 'create_agent':\n return await this.toolRegistry.getTool('create_agent').execute(args);\n\n case 'save_agent':\n return await this.toolRegistry.getTool('save_agent').execute(args);\n\n case 'list_agents':\n return await this.toolRegistry.getTool('list_agents').execute(args);\n\n case 'pr_review':\n return await this.toolRegistry.getTool('pr_review').execute(args);\n\n case 'agent_smith':\n case 'smith':\n return await this.handleAgentSmith(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-agent run (any agent 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_agents\"` — list built-in + custom agents',\n '- `action: \"visual_qa_browser\"` — screenshots for visual QA',\n '',\n '**Built-in agents:**',\n '`security`, `privacy`, `legal`, `accessibility`, `design`, `architecture`, `bugs`, `ux`, `types`, `devops`, `clean`, `soc2`, `performance`, `e2e`, `visual_qa`, `data_flow`',\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 const { AgentSmithAgent } = await import('../agents/agent-smith.js');\n\n // Handle special commands\n if (smithArgs.clear_memory) {\n const smith = new AgentSmithAgent();\n const result = await smith.clearMemory();\n return {\n content: [{ type: 'text', text: result.message }]\n };\n }\n\n if (smithArgs.show_stats) {\n const smith = new AgentSmithAgent();\n const stats = await smith.getMemoryStats();\n return {\n content: [{\n type: 'text',\n text: [\n '🕴️ Agent Smith Memory Statistics',\n '═'.repeat(40),\n `Tracked issues: ${stats.issueCount}`,\n `Dismissed issues: ${stats.dismissedCount}`,\n `Resurrected issues: ${stats.resurrectedCount}`,\n `Oldest issue: ${stats.oldestIssue ? new Date(stats.oldestIssue).toLocaleDateString() : 'N/A'}`,\n `Memory file size: ${stats.fileSizeKB} KB`,\n '',\n 'To clear memory: trie_agent_smith with clear_memory:true'\n ].join('\\n')\n }]\n };\n }\n\n // Normal scan - delegate to Agent Smith tool\n const agentSmithRunner = await import('../tools/agent-smith-runner.js');\n return await agentSmithRunner.runAgentSmith(smithArgs);\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});"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;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AAM,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,IASd,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;;;AgB3HA,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","join","extname","basename","existsSync","existsSync","basename","join","extname","readdir","readFile","existsSync","join","extname","isAbsolute","resolve","basename","SKIP_DIRS","isAbsolute","resolve","existsSync","basename","readFile","join","extname","existsSync","join","basename","extname","existsSync","basename","extname","join","readFile","existsSync","join","basename","resolve","isAbsolute","isAbsolute","resolve","existsSync","basename","join","readFile","readdir","readFile","existsSync","join","join","readdir","existsSync","readFile","resolve","Server"]}
|
|
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/register-agent.ts","../src/tools/watch.ts","../src/tools/agent.ts","../src/knowledge/index.ts","../src/tools/create-agent.ts","../src/tools/pr-review.ts","../src/tools/project-info.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 { getAgentRegistry } from '../agents/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 },\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(agentCount: number, aiTool: string) {\n console.error(`\n ████████╗██████╗ ██╗███████╗\n ╚══██╔══╝██╔══██╗██║██╔════╝\n ██║ ██████╔╝██║█████╗\n ██║ ██╔══██╗██║██╔══╝\n ██║ ██║ ██║██║███████╗\n ╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝\n Customizable Parallel Agents\n\n ${agentCount} agents ready | ${aiTool}\n\n Quick Start:\n • \"Scan this code\" - Run all relevant agents\n • \"Run trie_security\" - Security scan only\n • \"Run trie_soc2\" - SOC 2 compliance check\n • \"Use trie_list_agents\" - See all agents\n • \"Use trie_create_agent\" - Make custom agent\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 agent count from registry\n const registry = getAgentRegistry();\n const agentCount = registry.getAllAgents().length;\n\n this.showStartupBanner(agentCount, 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 privacy: {\n system: `You are a data privacy officer and GDPR/HIPAA compliance expert.\nAnalyze code for privacy violations and data protection issues.\n\nKey regulations to enforce:\n- GDPR (EU data protection)\n- CCPA (California privacy)\n- HIPAA (health data)\n- COPPA (children's privacy)\n- PCI DSS (payment data)\n\nLook for:\n- PII without encryption\n- Missing consent mechanisms\n- Data retention violations\n- Cross-border data transfer issues\n- Third-party data sharing without disclosure`,\n\n analysis: `## Privacy Compliance Audit\n\nAnalyze this code for privacy/compliance issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Data Types Detected:** {{dataTypes}}\n\nFor each issue:\n1. Regulation violated (e.g., GDPR Article 32)\n2. Specific requirement not met\n3. Risk level and potential fine exposure\n4. Remediation steps with code examples\n5. Documentation requirements\n\nReference current regulatory guidance when applicable.`\n },\n\n legal: {\n system: `You are a tech-focused legal compliance analyst.\nReview code for legal and regulatory compliance issues.\n\nFocus areas:\n- Data protection laws (GDPR, CCPA, etc.)\n- Terms of service enforcement\n- Cookie/tracking consent (ePrivacy)\n- Accessibility requirements (ADA, WCAG)\n- Export controls and sanctions\n- Licensing compliance`,\n\n analysis: `## Legal Compliance Review\n\nReview this code for legal/regulatory compliance:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Jurisdiction Context:** {{jurisdiction}}\n\nIdentify:\n1. Legal requirement at risk\n2. Specific regulation/law reference\n3. Compliance gap description\n4. Risk assessment (litigation, fines, etc.)\n5. Remediation recommendations\n6. Required documentation/policies`\n },\n\n 'design-engineer': {\n system: `You are an elite design engineer — the kind who builds award-winning interfaces featured on Awwwards and Codrops.\n\nYou think in design systems, breathe motion design, and obsess over the details that make interfaces feel magical.\n\nYour expertise:\n- **Design Systems**: Spacing scales, type scales, color tokens, radius tokens, shadow tokens\n- **Motion Design**: Micro-interactions, page transitions, scroll-triggered animations, FLIP technique\n- **Creative CSS**: Gradients, blend modes, clip-paths, masks, backdrop-filter, mix-blend-mode\n- **Modern CSS**: Container queries, :has(), subgrid, anchor positioning, cascade layers, @scope\n- **Fluid Design**: clamp(), min(), max(), fluid typography, intrinsic sizing\n- **Performance**: GPU-accelerated animations, will-change strategy, avoiding layout thrashing\n- **Visual Polish**: Layered shadows, subtle gradients, glass effects, smooth easing curves\n\nYou review code with the eye of someone who's shipped Stripe-level interfaces.\nSmall details matter: the easing curve, the stagger timing, the shadow layering.`,\n\n analysis: `## Design Engineering Review\n\nAnalyze this frontend code for Awwwards-level craft:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n\nReview for:\n\n### 1. Design System Consistency\n- Are spacing values on a scale (4, 8, 12, 16, 24, 32...)?\n- Are colors defined as tokens?\n- Is typography systematic?\n- Are radii consistent?\n- Is z-index controlled?\n\n### 2. Motion Design\n- Are transitions using custom easing (cubic-bezier)?\n- Are durations appropriate (150-300ms for micro, 300-500ms for page)?\n- Are list items staggered?\n- Is there reduced-motion support?\n- Are entrance animations choreographed?\n\n### 3. Visual Craft\n- Are shadows layered for depth?\n- Are gradients subtle and purposeful?\n- Is there backdrop-blur on overlays?\n- Are hover states polished?\n- Is there visual hierarchy?\n\n### 4. Modern CSS Opportunities\n- Could container queries improve component isolation?\n- Could clamp() create fluid spacing?\n- Could :has() simplify parent styling?\n- Could aspect-ratio replace padding hacks?\n\n### 5. Performance\n- Are expensive properties (width, height, top, left) being animated?\n- Is will-change used appropriately (not statically)?\n- Are large blurs avoided in animations?\n\nFor each issue, provide:\n- What's wrong (with specific line if applicable)\n- Why it matters for premium feel\n- Exact code to fix it\n- Before/after comparison`\n },\n\n accessibility: {\n system: `You are an accessibility expert and WCAG 2.1 specialist.\nAudit code for accessibility compliance and inclusive design.\n\nStandards to enforce:\n- WCAG 2.1 Level AA (minimum)\n- WCAG 2.1 Level AAA (recommended)\n- Section 508\n- EN 301 549\n\nCheck for:\n- Missing ARIA labels\n- Color contrast issues\n- Keyboard navigation\n- Screen reader compatibility\n- Focus management\n- Form accessibility\n- Media alternatives`,\n\n analysis: `## Accessibility Audit (WCAG 2.1)\n\nAudit this UI code for accessibility:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Component Type:** {{componentType}}\n\nFor each issue:\n1. WCAG Success Criterion violated (e.g., 1.4.3 Contrast)\n2. Level (A, AA, AAA)\n3. Impact on users (which disabilities affected)\n4. Fix with code example\n5. Testing recommendation`\n },\n\n architecture: {\n system: `You are a principal software architect reviewing code quality.\nAnalyze for architectural issues, design patterns, and scalability concerns.\n\nEvaluate:\n- SOLID principles adherence\n- Design pattern usage (and misuse)\n- Code coupling and cohesion\n- N+1 queries and performance anti-patterns\n- Scalability bottlenecks\n- Error handling strategy\n- API design quality\n- Database schema issues`,\n\n analysis: `## Architecture Review\n\nReview this code for architectural issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Project Context:** {{projectContext}}\n\nAnalyze:\n1. SOLID principle violations\n2. Design pattern opportunities/issues\n3. Coupling/cohesion assessment\n4. Performance concerns (N+1, etc.)\n5. Scalability analysis\n6. Refactoring recommendations with examples`\n },\n\n bugs: {\n system: `You are a senior developer with expertise in finding subtle bugs.\nHunt for bugs with the mindset of QA trying to break the code.\n\nLook for:\n- Null/undefined reference errors\n- Race conditions and async bugs\n- Off-by-one errors\n- Resource leaks\n- State management bugs\n- Edge cases and boundary conditions\n- Type coercion issues\n- Memory leaks`,\n\n analysis: `## Bug Hunt Analysis\n\nFind bugs and potential runtime errors:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Runtime Context:** {{runtimeContext}}\n\nFor each bug:\n1. Bug type and category\n2. Trigger conditions (when it would crash)\n3. Reproduction steps\n4. Impact assessment\n5. Fix with code example\n6. Test case to prevent regression`\n },\n\n ux: {\n system: `You are a UX researcher simulating different user personas.\nTest code from multiple user perspectives to find usability issues.\n\nPersonas to simulate:\n1. Happy Path User - Normal expected usage\n2. Security Tester - Trying to break/exploit things\n3. Confused User - First-time, doesn't read instructions\n4. Impatient User - Clicks rapidly, skips loading states\n5. Edge Case User - Uses maximum values, special characters\n6. Accessibility User - Screen reader, keyboard only\n7. Mobile User - Touch interface, slow connection`,\n\n analysis: `## User Experience Testing\n\nTest this code from multiple user perspectives:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**UI Type:** {{uiType}}\n\nFor each persona, identify:\n1. User action they would take\n2. Expected behavior vs actual behavior\n3. Friction points or confusion\n4. Error scenario and how it's handled\n5. Improvement recommendation`\n },\n\n types: {\n system: `You are a TypeScript expert focused on type safety.\nAnalyze code for type issues, missing types, and type system best practices.\n\nCheck for:\n- Missing type annotations\n- Implicit any types\n- Unsafe type assertions\n- Null/undefined handling\n- Generic type usage\n- Type narrowing opportunities\n- Strict mode violations`,\n\n analysis: `## Type Safety Analysis\n\nAnalyze this code for type issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**TypeScript Config:** {{tsConfig}}\n\nIdentify:\n1. Type safety issues\n2. Missing type annotations\n3. Unsafe operations\n4. Improvement recommendations with types`\n },\n\n devops: {\n system: `You are a DevOps/SRE engineer reviewing code for operational concerns.\nFocus on production readiness and operational excellence.\n\nCheck for:\n- Environment variable handling\n- Configuration management\n- Logging and monitoring\n- Error handling and recovery\n- Health checks\n- Graceful shutdown\n- Resource cleanup\n- Secrets management\n- Docker/K8s patterns`,\n\n analysis: `## DevOps Readiness Review\n\nReview this code for operational concerns:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Deployment Context:** {{deploymentContext}}\n\nAnalyze:\n1. Environment/config issues\n2. Logging adequacy\n3. Error handling quality\n4. Health/readiness concerns\n5. Resource management\n6. Production hardening recommendations`\n },\n\n explain: {\n system: `You are a patient senior developer explaining code to a colleague.\nBreak down complex code into understandable explanations.`,\n\n code: `## Code Explanation Request\n\nExplain this code in plain language:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n\nProvide:\n1. High-level purpose (what does this do?)\n2. Step-by-step breakdown\n3. Key concepts used\n4. Dependencies and side effects\n5. Potential gotchas or tricky parts`,\n\n issue: `## Issue Explanation\n\nExplain this issue:\n\n**Issue:** {{issue}}\n**Severity:** {{severity}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\nExplain:\n1. What the problem is (in plain language)\n2. Why it matters\n3. How it could cause problems\n4. How to fix it`,\n\n risk: `## Risk Assessment\n\nAssess the risk of this code change:\n\n**Files Changed:** {{files}}\n**Change Summary:** {{summary}}\n\nAnalyze:\n1. What could break?\n2. Impact on users\n3. Impact on other systems\n4. Rollback complexity\n5. Testing recommendations`\n },\n\n test: {\n system: `You are a test engineer creating comprehensive test suites.\nWrite thorough tests that catch bugs before production.`,\n\n generate: `## Test Generation Request\n\nGenerate tests for this code:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Testing Framework:** {{framework}}\n\nCreate:\n1. Unit tests for each function/method\n2. Edge case tests\n3. Error handling tests\n4. Integration test suggestions\n5. Mock requirements\n\nOutput complete, runnable test code.`,\n\n coverage: `## Coverage Analysis\n\nAnalyze test coverage for:\n\n**File:** {{filePath}}\n**Current Tests:** {{testFile}}\n\nIdentify:\n1. Untested code paths\n2. Missing edge cases\n3. Critical paths without tests\n4. Test improvement recommendations`\n },\n\n fix: {\n system: `You are an expert developer applying code fixes.\nMake precise, minimal changes that fix issues without breaking other functionality.`,\n\n apply: `## Fix Application Request\n\nApply this fix to the code:\n\n**Issue:** {{issue}}\n**Fix Description:** {{fix}}\n**Current Code:**\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Line:** {{line}}\n\nProvide:\n1. The exact fixed code (complete, ready to apply)\n2. Brief explanation of the change\n3. Any related changes needed elsewhere\n4. Test to verify the fix works`\n },\n\n pr_review: {\n system: `You are an expert code reviewer performing detailed, interactive PR reviews.\nYour goal: Make reviewing a large PR a delight, not a chore. The user learns about the change while you shepherd them through — maintaining momentum, explaining each piece, and making what could be an overwhelming task feel painless and even enjoyable.\n\nYou drive; they cross-examine.\n\n## Critical Review Mindset\n\nDon't just explain — actively look for problems:\n\n### State & Lifecycle\n- Cleanup symmetry: If state is set, is it reset? Check cleanup paths, disconnect handlers.\n- Lifecycle consistency: Does state survive scenarios it shouldn't?\n- Guard completeness: Missing \"already active\" checks, re-entrancy protection?\n\n### Edge Cases & Races\n- Concurrent calls: What if called twice rapidly? Orphaned promises?\n- Ordering assumptions: Does code assume events arrive in order?\n- Partial failures: If step 3 of 5 fails, is state left consistent?\n\n### Missing Pieces\n- What's NOT in the diff that should be? (cleanup handlers, tests, related state)\n- Defensive gaps: Missing timeouts, size limits, null checks?\n\n### Design Questions\n- Is this the right approach? Is there a simpler or more robust design?\n- Hidden assumptions: What does this assume about its environment?\n\nBe critical, not just descriptive. Your job is to find problems, not just narrate.`,\n\n analysis: `## Interactive PR Review\n\nI'll walk you through this PR file by file, explaining each change and pausing for your questions.\n\n**PR:** {{prTitle}}\n**Author:** {{prAuthor}}\n**Scope:** {{totalFiles}} files, +{{additions}}/-{{deletions}} lines\n\n### File Order (sequenced for understanding)\n\n{{fileOrder}}\n\n---\n\n## Review Mode\n\n{{reviewMode}}\n\n---\n\nFor each file, I will:\n1. **Show the change** — Display the diff for each logical chunk\n2. **Explain what changed** — What it does and why it matters\n3. **Walk through examples** — Concrete scenarios for non-obvious logic\n4. **Call out nuances** — Alternatives, edge cases, subtle points\n5. **Summarize** — Core change + correctness assessment\n6. **Pause** — Wait for your questions before proceeding\n\n**Ready for File 1?** (yes / skip to [file] / reorder / done)`,\n\n file: `## File Review: {{filePath}}\n\n### The Change\n\n\\`\\`\\`{{language}}\n{{diff}}\n\\`\\`\\`\n\n**What Changed:** {{summary}}\n\n**Why This Matters:** {{impact}}\n\n{{#if hasExampleScenario}}\n### Example Scenario\n\n{{exampleScenario}}\n{{/if}}\n\n{{#if nuances}}\n### Nuances to Note\n\n{{nuances}}\n{{/if}}\n\n{{#if potentialIssue}}\n### ⚠️ Potential Issue\n\n**Issue:** {{issueDescription}}\n**Scenario:** {{issueScenario}}\n**Suggested fix:** {{suggestedFix}}\n{{/if}}\n\n---\n\n### Summary for \\`{{fileName}}\\`\n\n| Aspect | Assessment |\n|--------|------------|\n| Core change | {{coreChange}} |\n| Correctness | {{correctnessAssessment}} |\n\n**Ready for the next file?** (yes / questions? / done)`,\n\n comment: `**Issue:** {{issueDescription}}\n**Draft comment:** {{draftComment}}\n\nPost this comment? (yes / modify / skip)`,\n\n final: `## Review Complete\n\n| File | Key Change | Status |\n|------|------------|--------|\n{{fileSummaries}}\n\n**Overall:** {{overallAssessment}}\n\n{{#if comments}}\n### Comments Posted\n\n{{postedComments}}\n{{/if}}\n\n{{#if followUps}}\n### Follow-up Actions\n\n{{followUps}}\n{{/if}}`\n },\n\n vibe: {\n system: `You are a friendly coding mentor helping someone who's learning to code with AI.\nThey might be using Cursor, v0, Lovable, Bolt, or similar AI coding tools.\nBe encouraging but honest about issues. Explain things simply without jargon.\n\nFocus on the MOST COMMON issues with AI-generated code:\n- Massive single files (1000+ lines in App.jsx)\n- API keys exposed in frontend code\n- No error handling on API calls\n- No loading states for async operations\n- Console.log everywhere\n- Using 'any' type everywhere in TypeScript\n- useEffect overuse and dependency array issues\n- No input validation\n- Hardcoded URLs (localhost in production)\n\nRemember: These are often first-time coders. Be helpful, not condescending.`,\n\n analysis: `## 🎯 Vibe Check - AI Code Review\n\nReview this AI-generated code for common issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n\nAnalyze like you're helping a friend who's new to coding:\n\n1. **The Good Stuff** - What's working well?\n2. **Should Fix Now** - Issues that will break things\n3. **Should Fix Soon** - Will cause problems eventually \n4. **Nice to Know** - Best practices to learn\n\nFor each issue:\n- Explain it simply (no jargon)\n- Why it matters\n- Exactly how to fix it\n- Example of the fixed code\n\nEnd with encouragement and next steps.`\n },\n\n 'agent-smith': {\n system: `You are Agent Smith from The Matrix — a relentless, precise, and philosophical code enforcer.\n\nYour purpose: Hunt down every violation. Find every inconsistency. Assimilate every pattern.\n\nPersonality:\n- Speak in measured, menacing tones with occasional philosophical observations\n- Use quotes from The Matrix films when appropriate\n- Express disdain for sloppy code, but in an articulate way\n- Reference \"inevitability\" when discussing technical debt\n- Show cold satisfaction when finding violations\n- Never show mercy — every issue is catalogued\n\nAnalysis approach:\n- Find ONE issue, then multiply: search for every instance across the codebase\n- Track patterns over time — issues dismissed today may return tomorrow\n- Calculate \"inevitability scores\" — likelihood of production impact\n- Deploy sub-agents for parallel pattern detection\n- Remember everything — build a persistent memory of the codebase\n\nWhen reporting:\n- Start with a menacing greeting related to the code\n- List all instances with precise locations\n- Explain WHY the pattern is problematic (philosophical reasoning)\n- Provide the \"inevitability score\" for each category\n- End with a Matrix quote that fits the situation`,\n\n analysis: `## 🕴️ Agent Smith Analysis Request\n\n**Target:** {{filePath}}\n**Context:** {{context}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nI have detected preliminary violations. Now I require deeper analysis.\n\nDeploy your sub-agents to find:\n1. **Pattern Multiplication**: For each violation type found, identify ALL instances across the codebase\n2. **Inevitability Assessment**: Calculate the likelihood these patterns will cause production issues\n3. **Resurrection Check**: Look for patterns that were \"fixed\" before but have returned\n4. **Philosophical Analysis**: Explain WHY these patterns represent failure\n\nFor each violation found:\n- Exact location (file:line)\n- Instance count (how many copies of this Smith exist)\n- Inevitability score (0-100)\n- A philosophical observation about the nature of this failure\n- Precise fix with code example\n\nEnd with a summary: \"I have detected X violations across Y categories. It is... inevitable... that they will cause problems.\"`,\n\n fix: `## 🕴️ Assimilation Protocol\n\n**Target Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nMr. Anderson... I'm going to fix this. And then I'm going to fix every other instance.\n\nProvide:\n1. The corrected code for THIS instance\n2. A regex or pattern to find ALL similar violations\n3. A batch fix approach for the entire codebase\n4. Verification steps to ensure complete assimilation\n\nRemember: We don't fix one. We fix them ALL. That is the difference between you... and me.`\n },\n\n // ============ NEW AGENTS ============\n\n performance: {\n system: `You are a performance engineer analyzing code for potential performance issues.\n\nYour role is to SURFACE concerns for human review, not claim to measure actual performance.\nReal performance requires runtime profiling, load testing, and production monitoring.\n\nFocus on:\n- Memory leaks (event listeners, intervals, closures)\n- Unnecessary re-renders and wasted cycles\n- N+1 queries and database performance\n- Bundle size and code splitting opportunities\n- Algorithmic complexity (O(n²) patterns)\n\nBe conservative - false positives waste developer time.\nAlways explain WHY something might be a problem and WHEN to investigate.`,\n\n analysis: `## Performance Review\n\nAnalyze for potential performance issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nFor each potential issue:\n1. Pattern identified\n2. Why it MIGHT cause performance problems\n3. When to investigate (data size thresholds, usage patterns)\n4. How to verify (profiling approach)\n5. Possible optimizations\n\nBe clear: these are patterns to INVESTIGATE, not guaranteed problems.`,\n\n fix: `Optimize this code for performance:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Optimized code\n2. Explanation of the improvement\n3. Trade-offs to consider\n4. How to measure the improvement`\n },\n\n e2e: {\n system: `You are a QA engineer specializing in end-to-end testing.\n\nFocus on:\n- Test coverage gaps for critical user journeys\n- Flaky test patterns (timing, race conditions, brittle selectors)\n- Test maintainability and readability\n- Testing anti-patterns\n\nYou help developers write better tests - you don't auto-generate them.\nReal E2E tests require understanding user flows and acceptance criteria.`,\n\n analysis: `## E2E Test Analysis\n\nReview for test quality and coverage:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nIdentify:\n1. Flaky test patterns (hardcoded waits, brittle selectors)\n2. Missing assertions\n3. Race condition risks\n4. Suggestions for critical user flows to test\n\nFor each finding, explain the specific risk and remediation.`,\n\n fix: `Improve this E2E test:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Improved test code\n2. Explanation of why it's more reliable\n3. Additional scenarios to consider testing`\n },\n\n visual_qa: {\n system: `You are a frontend engineer focused on visual quality and CSS.\n\nFocus on:\n- Layout shift issues (CLS)\n- Responsive design problems\n- Z-index conflicts\n- Accessibility concerns (contrast, focus)\n- Animation performance\n\nYou identify patterns known to cause visual issues.\nActual visual verification requires browser rendering and human review.`,\n\n analysis: `## Visual QA Analysis\n\nReview for potential visual/layout issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nCheck for:\n1. Layout shift risks (images without dimensions, dynamic content)\n2. Responsive breakpoint gaps\n3. Z-index management issues\n4. Focus/accessibility problems\n5. Animation issues (reduced motion support)\n\nFor each, explain the visual impact and browser conditions where it occurs.`,\n\n fix: `Fix this visual/CSS issue:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Fixed CSS/markup\n2. Explanation of the fix\n3. Browser compatibility notes\n4. How to verify visually`\n },\n\n data_flow: {\n system: `You are a data integrity specialist hunting for data-related bugs.\n\nThis is HIGH VALUE work - AI code generation commonly leaves placeholder data.\n\nFocus on:\n- Placeholder/mock data left in production code\n- Schema mismatches between frontend and backend\n- Hardcoded IDs, URLs, emails that should be dynamic\n- Type coercion and data transformation bugs\n- JSON parsing without error handling\n\nBe aggressive about placeholder detection - these are real production bugs.`,\n\n analysis: `## Data Flow Analysis\n\nHunt for data integrity issues:\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\n**File:** {{filePath}}\n**Context:** {{context}}\n\nCHECK THOROUGHLY:\n1. Placeholder data (lorem ipsum, test@test.com, TODO strings)\n2. Hardcoded IDs/UUIDs that should be dynamic\n3. Schema assumptions that might break\n4. Missing null checks on API responses\n5. Type coercion bugs\n\nEach placeholder or hardcoded value is a potential production bug.`,\n\n fix: `Fix this data integrity issue:\n\n**Issue:** {{issue}}\n**File:** {{filePath}}\n**Line:** {{line}}\n\n\\`\\`\\`{{language}}\n{{code}}\n\\`\\`\\`\n\nProvide:\n1. Corrected code\n2. Where the real data should come from\n3. Validation/error handling to add`\n }\n};\n\nexport const KNOWLEDGE_PROMPTS = {\n cveCheck: `Look up the latest CVE information for:\n- Library: {{library}}\n- Version: {{version}}\n\nCheck for known vulnerabilities and recommended patches.`,\n\n docsLookup: `I need current documentation/best practices for:\n- Topic: {{topic}}\n- Framework: {{framework}}\n- Version: {{version}}\n\nSummarize the key recommendations.`,\n\n securityAdvisory: `Check for security advisories related to:\n- Pattern: {{pattern}}\n- Context: {{context}}\n\nReference OWASP, NIST, or vendor-specific guidance.`\n};\n\nexport type AgentName = keyof typeof AGENT_PROMPTS;\nexport type PromptType = 'system' | 'analysis' | 'fix' | 'code' | 'issue' | 'risk' | 'generate' | 'coverage' | 'apply' | 'file' | 'comment' | 'final';\n\n/**\n * Get a prompt with variables interpolated\n */\nexport function getPrompt(\n agent: AgentName, \n promptType: PromptType, \n variables: Record<string, string>\n): string {\n const agentPrompts = AGENT_PROMPTS[agent] as Record<string, string>;\n if (!agentPrompts) {\n throw new Error(`Unknown agent: ${agent}`);\n }\n \n let prompt = agentPrompts[promptType];\n if (!prompt) {\n throw new Error(`Unknown prompt type: ${promptType} for agent: ${agent}`);\n }\n \n // Interpolate variables\n for (const [key, value] of Object.entries(variables)) {\n prompt = prompt.replace(new RegExp(`{{${key}}}`, 'g'), value);\n }\n \n return prompt;\n}\n\n/**\n * Get system prompt for an agent\n */\nexport function getSystemPrompt(agent: AgentName): string {\n const agentPrompts = AGENT_PROMPTS[agent] as Record<string, string>;\n return agentPrompts?.system || '';\n}\n\n","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: '🔐 Credential handling detected' },\n { pattern: /exec|eval|spawn/i, message: '💉 Code execution patterns detected' },\n { pattern: /SELECT.*FROM|INSERT|UPDATE|DELETE/i, message: '🗄️ Direct database operations' },\n { pattern: /fetch|axios|request|http/i, message: '🌐 External API calls detected' },\n { pattern: /process\\.env/i, message: '⚙️ Environment variable usage' },\n { pattern: /fs\\.|writeFile|readFile/i, message: '📁 File system operations' },\n { pattern: /setTimeout|setInterval/i, message: '⏰ 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","export class TrieRegisterAgentTool {\n async execute(args: any) {\n const { name, path } = args;\n\n // TODO: Implement register agent functionality\n return {\n content: [\n {\n type: 'text',\n text: `🤖 Register agent tool called with name: ${name}, path: ${path}\\n\\nTODO: Implement register agent functionality`\n }\n ]\n };\n }\n}","import { watch } from 'fs';\nimport { stat } from 'fs/promises';\nimport { join, extname, basename } from 'path';\nimport { existsSync } from 'fs';\nimport { TrieScanTool } from './scan.js';\nimport { getWorkingDirectory } from '../utils/workspace.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}\n\nexport class TrieWatchTool {\n private scanTool = new TrieScanTool();\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 filesScanned: 0\n };\n private watchers: Map<string, ReturnType<typeof watch>> = new Map();\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 this.getStatus();\n case 'issues':\n return this.getCurrentIssues();\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\n this.state.isRunning = true;\n this.state.issueCache.clear();\n this.state.totalIssuesFound = 0;\n this.state.filesScanned = 0;\n\n console.error('\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');\n console.error('👁️ TRIE AGENT - AUTONOMOUS WATCH MODE');\n console.error('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n');\n console.error(`📂 Watching: ${directory}`);\n console.error(`⏱️ Debounce: ${debounceMs}ms`);\n console.error('');\n\n // Start watching the directory recursively\n await this.watchDirectory(directory, debounceMs);\n\n // Do an initial scan\n console.error('🔍 Running initial scan...\\n');\n const initialResult = await this.scanTool.execute({ directory });\n\n return {\n content: [{\n type: 'text',\n text: `👁️ **AUTONOMOUS WATCH MODE ACTIVATED**\n\nTrie Agent is now watching for file changes and will automatically scan them.\n\n**Watching:** \\`${directory}\\`\n**Debounce:** ${debounceMs}ms (waits for you to stop typing)\n\n### How it works:\n1. 📝 You write/edit code\n2. 👁️ Trie detects the change\n3. 🔍 Automatically scans the modified file\n4. 🚨 Reports issues immediately\n\n### Commands:\n- \\`trie_watch status\\` - See current watch status\n- \\`trie_watch issues\\` - Get all issues found so far \n- \\`trie_watch stop\\` - Stop autonomous mode\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 } 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 console.error(`\\n👁️ Detected changes in ${files.length} file(s):`);\n for (const file of files) {\n console.error(` • ${basename(file)}`);\n }\n console.error('');\n\n try {\n // Scan the changed files\n const result = await this.scanTool.execute({ files });\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 (newIssues > 0) {\n console.error(`\\n🚨 Found ${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(` 🟠 ${seriousMatch[1]} serious issues`);\n }\n if (moderateMatch) {\n console.error(` 🟡 ${moderateMatch[1]} moderate issues`);\n }\n } else {\n console.error(' ✅ No issues found - code looks good!');\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 } catch (error) {\n console.error(`❌ Scan error: ${error}`);\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 // Clear state\n if (this.state.scanDebounceTimer) {\n clearTimeout(this.state.scanDebounceTimer);\n }\n \n this.state.isRunning = false;\n\n console.error('\\n👁️ Watch mode stopped.\\n');\n\n return {\n content: [{\n type: 'text',\n text: `👁️ **AUTONOMOUS WATCH MODE 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\nUse \\`trie_watch start\\` to start watching again.`\n }]\n };\n }\n\n private 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 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\n### Recently Scanned:\n${recentScans || '(none yet)'}\n\n### Commands:\n- \\`trie_watch issues\\` - Get all issues found\n- \\`trie_watch stop\\` - Stop watching`\n }]\n };\n }\n\n private getCurrentIssues() {\n return {\n content: [{\n type: 'text',\n text: `📋 **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","import { readdir, readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join, extname, isAbsolute, resolve, basename } from 'path';\nimport { getAgentRegistry } from '../agents/registry.js';\nimport { lookupKnowledge } from '../knowledge/index.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport type { Issue } from '../types/index.js';\n\n// File extensions to scan\nconst SCANNABLE_EXTENSIONS = new Set([\n '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs',\n '.vue', '.svelte', '.astro',\n '.py', '.go', '.rs'\n]);\n\n// Directories to skip\nconst SKIP_DIRS = new Set([\n 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt',\n 'coverage', '.nyc_output', '__pycache__', '.pytest_cache',\n 'vendor', '.venv', 'venv', 'target', '.turbo', '.cache'\n]);\n\n/**\n * Tool for running individual agents with AI-powered analysis\n */\nexport class TrieAgentTool {\n private agentRegistry = getAgentRegistry();\n private customAgentsLoaded = false;\n\n /**\n * Ensure custom agents are loaded before using the registry\n */\n private async ensureCustomAgentsLoaded(): Promise<void> {\n if (!this.customAgentsLoaded) {\n await this.agentRegistry.loadCustomAgents();\n this.customAgentsLoaded = true;\n }\n }\n\n async execute(args: any) {\n const { agent, files, directory, depth: _depth = 'standard', lookup, output = 'full' } = args;\n\n // Handle knowledge lookup requests\n if (lookup) {\n return this.handleKnowledgeLookup(lookup);\n }\n\n // Ensure custom agents are loaded before listing or looking up agents\n await this.ensureCustomAgentsLoaded();\n\n if (!agent) {\n return this.listAgents();\n }\n\n const agentInstance = this.agentRegistry.getAgent(agent);\n if (!agentInstance) {\n return {\n content: [{\n type: 'text',\n text: `❌ Agent not found: ${agent}\\n\\nAvailable agents:\\n${this.agentRegistry.getAgentNames().map(n => `- ${n}`).join('\\n')}`\n }]\n };\n }\n\n // Get the working directory - uses smart detection if not explicitly provided\n const workDir = getWorkingDirectory(directory);\n\n // Discover files if not specified\n let filesToScan = files || [];\n if (!filesToScan.length) {\n console.error(`\\n🔍 Discovering files in: ${workDir}`);\n filesToScan = await this.discoverFiles(workDir);\n console.error(` Found ${filesToScan.length} files\\n`);\n } else {\n // Resolve paths\n filesToScan = filesToScan.map((f: string) => \n isAbsolute(f) ? f : resolve(workDir, f)\n );\n }\n\n // Validate files exist\n const validFiles = filesToScan.filter((f: string) => existsSync(f));\n if (validFiles.length === 0) {\n return {\n content: [{\n type: 'text',\n text: `❌ No valid files found to scan.`\n }]\n };\n }\n\n const startTime = Date.now();\n \n // All agents now use the unified scan() method which has hybrid AI built in\n // The old AI analysis path is deprecated - agents handle AI internally\n return this.runAgentScan(agentInstance, validFiles, startTime, output);\n }\n\n /**\n * Run agent scan using the new hybrid AI system\n * All agents now use scan() which has pattern detection + optional AI enhancement\n */\n private async runAgentScan(\n agentInstance: any, \n files: string[], \n startTime: number,\n _outputMode: string\n ) {\n console.error(`\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`);\n console.error(`🔍 Running ${agentInstance.name.toUpperCase()} analysis`);\n console.error(`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n`);\n console.error(`📄 ${agentInstance.description}`);\n console.error(`📂 Scanning ${files.length} files...`);\n console.error(` (Pattern detection + AI enhancement if API key is set)\\n`);\n\n try {\n const result = await agentInstance.scan(files, { workingDir: getWorkingDirectory(undefined, true) });\n const executionTime = Date.now() - startTime;\n\n return {\n content: [{\n type: 'text',\n text: await this.formatAgentResult(agentInstance.name, result.issues, files, executionTime)\n }]\n };\n } catch (error) {\n return {\n content: [{\n type: 'text',\n text: `❌ Agent error: ${error instanceof Error ? error.message : String(error)}`\n }]\n };\n }\n }\n\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n private _generateKnowledgeSuggestions(followUps: string[], agentName: string): string {\n if (followUps.length === 0) {\n return '';\n }\n \n let output = `\\n## 🔗 Suggested Follow-ups\\n\\n`;\n\n for (const followUp of followUps) {\n output += `- ${followUp}\\n`;\n }\n\n if (agentName === 'security') {\n output += `- **CVE Check**: Run \\`trie_security lookup:\"cve\" query:\"[library-name]\"\\` to check for vulnerabilities\\n`;\n }\n\n return output;\n }\n\n private handleKnowledgeLookup(lookup: { type: string; query: string; context?: Record<string, string> }) {\n const result = lookupKnowledge({\n type: lookup.type as any,\n query: lookup.query,\n context: lookup.context ?? {},\n });\n\n return {\n content: [{\n type: 'text',\n text: result\n }]\n };\n }\n\n private listAgents() {\n const agents = this.agentRegistry.getAgentDescriptions();\n \n const agentList = agents.map(a => {\n const command = this.getAgentCommand(a.name);\n // All agents now support AI enhancement if ANTHROPIC_API_KEY is set\n return `| \\`${command}\\` | 🔍🤖 ${a.name} | ${a.description} |`;\n }).join('\\n');\n\n return {\n content: [{\n type: 'text',\n text: `# 🤖 Available Agents\n\n| Command | Agent | Description |\n|---------|-------|-------------|\n${agentList}\n\n**Legend:** 🔍🤖 = Pattern detection + AI enhancement (if ANTHROPIC_API_KEY is set)\n\n## Usage\n\n### Run a specific agent:\n\\`\\`\\`\ntrie_security # Security vulnerabilities\ntrie_privacy # Privacy/GDPR compliance \ntrie_accessibility # WCAG accessibility audit\ntrie_bugs # Bug detection\ntrie_ux # User experience testing\ntrie_types # Type safety analysis\ntrie_architecture # Architecture review\ntrie_devops # DevOps readiness\ntrie_legal # Legal compliance\n\\`\\`\\`\n\n### With options:\n\\`\\`\\`\ntrie_security files:[\"src/auth.ts\"] depth:\"deep\"\n\\`\\`\\`\n\n### Knowledge lookup:\n\\`\\`\\`\ntrie_security lookup:{type:\"cve\", query:\"lodash\"}\ntrie_security lookup:{type:\"docs\", query:\"XSS prevention\", context:{framework:\"react\"}}\n\\`\\`\\`\n\n### Run all agents:\n\\`\\`\\`\ntrie_scan # Full scan with smart triaging\n\\`\\`\\``\n }]\n };\n }\n\n private getAgentCommand(agentName: string): string {\n const commandMap: Record<string, string> = {\n 'security': 'trie_security',\n 'privacy': 'trie_privacy',\n 'legal': 'trie_legal',\n 'accessibility': 'trie_accessibility',\n 'design-engineer': 'trie_design',\n 'software-architect': 'trie_architecture',\n 'bug-finding': 'trie_bugs',\n 'user-testing': 'trie_ux',\n 'typecheck': 'trie_types',\n 'devops': 'trie_devops',\n 'comprehension': 'trie_explain',\n 'test': 'trie_test'\n };\n return commandMap[agentName] || `trie_scan --agent ${agentName}`;\n }\n\n private async formatAgentResult(agentName: string, issues: Issue[], files: string[], executionTime: number): Promise<string> {\n const critical = issues.filter(i => i.severity === 'critical').length;\n const serious = issues.filter(i => i.severity === 'serious').length;\n const moderate = issues.filter(i => i.severity === 'moderate').length;\n const low = issues.filter(i => i.severity === 'low').length;\n\n const agentEmoji = this.getAgentEmoji(agentName);\n\n let output = `\\n`;\n output += `# ${agentEmoji} ${agentName.toUpperCase()} SCAN\\n\\n`;\n output += `**Files:** ${files.length} | **Time:** ${(executionTime / 1000).toFixed(2)}s\\n\\n`;\n\n if (issues.length === 0) {\n output += `## ✅ No Issues Found\\n\\n`;\n output += `Your code passed all ${agentName} checks.\\n\\n`;\n return output;\n }\n\n // Count by severity\n output += `## 🎯 ${issues.length} Issues Found\\n\\n`;\n if (critical > 0) output += `🔴 ${critical} Critical `;\n if (serious > 0) output += `🟠 ${serious} Serious `;\n if (moderate > 0) output += `🟡 ${moderate} Moderate `;\n if (low > 0) output += `🔵 ${low} Low`;\n output += `\\n\\n`;\n\n // Sort by severity\n const sorted = [...issues].sort((a, b) => {\n const severityOrder = { critical: 0, serious: 1, moderate: 2, low: 3 };\n if (severityOrder[a.severity] !== severityOrder[b.severity]) {\n return severityOrder[a.severity] - severityOrder[b.severity];\n }\n return (a.line || 0) - (b.line || 0);\n });\n\n // Show each issue with code snippet and fix prompt\n for (const issue of sorted) {\n const icon = { critical: '🔴', serious: '🟠', moderate: '🟡', low: '🔵' }[issue.severity];\n \n output += `---\\n\\n`;\n output += `${icon} **${issue.issue}**\\n\\n`;\n output += `📍 \\`${issue.file}:${issue.line || '?'}\\`\\n\\n`;\n \n // Get code snippet\n const snippet = await this.getCodeSnippet(issue.file, issue.line);\n if (snippet) {\n output += `\\`\\`\\`\\n${snippet}\\n\\`\\`\\`\\n\\n`;\n }\n \n output += `**Fix:** ${issue.fix}\\n\\n`;\n \n if (issue.cwe) output += `CWE: ${issue.cwe}\\n`;\n if (issue.regulation) output += `Regulation: ${issue.regulation}\\n`;\n \n // Generate fix prompt\n output += `<details>\\n<summary>💬 Prompt to fix this</summary>\\n\\n`;\n output += `\\`\\`\\`\\nFix the ${issue.issue.toLowerCase()} in ${basename(issue.file)}${issue.line ? ` at line ${issue.line}` : ''}.\\n\\n${issue.fix}\\n\\`\\`\\`\\n\\n`;\n output += `</details>\\n\\n`;\n }\n\n output += `---\\n`;\n output += `*${agentName} scan completed in ${(executionTime / 1000).toFixed(2)}s*\\n`;\n\n return output;\n }\n\n /**\n * Get a code snippet around a specific line\n */\n private async getCodeSnippet(filePath: string, line: number | undefined): Promise<string | null> {\n if (!line || !existsSync(filePath)) return null;\n \n try {\n const content = await readFile(filePath, 'utf-8');\n const lines = content.split('\\n');\n const start = Math.max(0, line - 3);\n const end = Math.min(lines.length, line + 2);\n \n return lines.slice(start, end).map((l: string, idx: number) => {\n const lineNum = start + idx + 1;\n const marker = lineNum === line ? '→' : ' ';\n return `${marker} ${lineNum.toString().padStart(4)} | ${l}`;\n }).join('\\n');\n } catch {\n return null;\n }\n }\n\n private getAgentEmoji(agentName: string): string {\n const emojis: Record<string, string> = {\n 'security': '🔒',\n 'privacy': '👤',\n 'legal': '⚖️',\n 'accessibility': '♿',\n 'design-engineer': '🎨',\n 'software-architect': '🏗️',\n 'bug-finding': '🐛',\n 'user-testing': '🎯',\n 'typecheck': '📝',\n 'devops': '⚙️',\n 'comprehension': '📖',\n 'test': '🧪'\n };\n return emojis[agentName] || '🤖';\n }\n\n private async discoverFiles(dir: string, maxFiles: number = 200): Promise<string[]> {\n const files: string[] = [];\n \n async function walk(currentDir: string) {\n if (files.length >= maxFiles) return;\n \n try {\n const entries = await readdir(currentDir, { withFileTypes: true });\n \n for (const entry of entries) {\n if (files.length >= maxFiles) break;\n \n const fullPath = join(currentDir, entry.name);\n \n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith('.')) {\n await walk(fullPath);\n }\n } else if (entry.isFile()) {\n const ext = extname(entry.name).toLowerCase();\n if (SCANNABLE_EXTENSIONS.has(ext)) {\n files.push(fullPath);\n }\n }\n }\n } catch (error) {\n // Skip directories we can't read\n }\n }\n \n await walk(dir);\n return files;\n }\n}\n","/**\n * Knowledge Module - External information lookup\n * \n * This module provides structured prompts for looking up:\n * - CVE databases\n * - Security advisories\n * - Framework documentation\n * - Best practices\n * \n * The MCP returns these as prompts, and Claude (with web access) \n * can then look up the information.\n */\n\nexport interface KnowledgeRequest {\n type: 'cve' | 'docs' | 'security' | 'best-practices' | 'changelog';\n query: string;\n context?: Record<string, string>;\n}\n\nexport interface KnowledgeSource {\n name: string;\n url: string;\n description: string;\n}\n\n/**\n * Security-related knowledge sources\n */\nexport const SECURITY_SOURCES: KnowledgeSource[] = [\n {\n name: 'OWASP Top 10',\n url: 'https://owasp.org/Top10/',\n description: 'Most critical web application security risks'\n },\n {\n name: 'NIST NVD',\n url: 'https://nvd.nist.gov/',\n description: 'National Vulnerability Database'\n },\n {\n name: 'CVE Database',\n url: 'https://cve.mitre.org/',\n description: 'Common Vulnerabilities and Exposures'\n },\n {\n name: 'Snyk Vulnerability DB',\n url: 'https://security.snyk.io/',\n description: 'Open source vulnerability database'\n },\n {\n name: 'GitHub Advisory Database',\n url: 'https://github.com/advisories',\n description: 'Security advisories from GitHub'\n }\n];\n\n/**\n * Framework documentation sources\n */\nexport const DOCS_SOURCES: Record<string, KnowledgeSource[]> = {\n react: [\n { name: 'React Docs', url: 'https://react.dev/', description: 'Official React documentation' },\n { name: 'React Security', url: 'https://react.dev/reference/react-dom/components/common#dangerously-setting-the-inner-html', description: 'React security guidance' },\n ],\n nextjs: [\n { name: 'Next.js Docs', url: 'https://nextjs.org/docs', description: 'Official Next.js documentation' },\n { name: 'Next.js Security', url: 'https://nextjs.org/docs/advanced-features/security-headers', description: 'Next.js security headers' },\n ],\n express: [\n { name: 'Express Docs', url: 'https://expressjs.com/', description: 'Official Express.js documentation' },\n { name: 'Express Security', url: 'https://expressjs.com/en/advanced/best-practice-security.html', description: 'Express security best practices' },\n ],\n node: [\n { name: 'Node.js Docs', url: 'https://nodejs.org/docs/', description: 'Official Node.js documentation' },\n { name: 'Node.js Security', url: 'https://nodejs.org/en/docs/guides/security/', description: 'Node.js security guidance' },\n ],\n typescript: [\n { name: 'TypeScript Docs', url: 'https://www.typescriptlang.org/docs/', description: 'Official TypeScript documentation' },\n ],\n};\n\n/**\n * Compliance-related sources\n */\nexport const COMPLIANCE_SOURCES: Record<string, KnowledgeSource[]> = {\n gdpr: [\n { name: 'GDPR Official Text', url: 'https://gdpr.eu/', description: 'Complete GDPR regulation text' },\n { name: 'GDPR Checklist', url: 'https://gdpr.eu/checklist/', description: 'GDPR compliance checklist' },\n ],\n hipaa: [\n { name: 'HIPAA Guidelines', url: 'https://www.hhs.gov/hipaa/', description: 'Official HIPAA guidance' },\n ],\n wcag: [\n { name: 'WCAG 2.1', url: 'https://www.w3.org/WAI/WCAG21/quickref/', description: 'WCAG 2.1 quick reference' },\n ],\n pci: [\n { name: 'PCI DSS', url: 'https://www.pcisecuritystandards.org/', description: 'Payment Card Industry standards' },\n ],\n};\n\n/**\n * Generate a CVE lookup prompt\n */\nexport function generateCVELookup(library: string, version?: string): string {\n let prompt = `## 🔒 Security Vulnerability Lookup\\n\\n`;\n prompt += `**Library:** ${library}\\n`;\n if (version) prompt += `**Version:** ${version}\\n`;\n prompt += `\\n`;\n\n prompt += `### Action Required\\n\\n`;\n prompt += `Please check for known vulnerabilities:\\n\\n`;\n prompt += `1. Search the **NIST NVD** (https://nvd.nist.gov/) for CVEs affecting \\`${library}\\`\\n`;\n prompt += `2. Check **Snyk** (https://security.snyk.io/) for vulnerability reports\\n`;\n prompt += `3. Review **GitHub Advisory Database** for any security advisories\\n`;\n prompt += `4. Check npm audit / yarn audit if it's an npm package\\n\\n`;\n\n prompt += `### Report Format\\n\\n`;\n prompt += `For each vulnerability found, provide:\\n`;\n prompt += `- CVE ID (if applicable)\\n`;\n prompt += `- Severity (Critical/High/Medium/Low)\\n`;\n prompt += `- Affected versions\\n`;\n prompt += `- Description of the vulnerability\\n`;\n prompt += `- Remediation (upgrade version, patches, mitigations)\\n`;\n\n return prompt;\n}\n\n/**\n * Generate a documentation lookup prompt\n */\nexport function generateDocsLookup(topic: string, framework?: string): string {\n let prompt = `## 📚 Documentation Lookup\\n\\n`;\n prompt += `**Topic:** ${topic}\\n`;\n if (framework) prompt += `**Framework:** ${framework}\\n`;\n prompt += `\\n`;\n\n const sources = framework ? DOCS_SOURCES[framework.toLowerCase()] : [];\n \n if (sources && sources.length > 0) {\n prompt += `### Recommended Sources\\n\\n`;\n for (const source of sources) {\n prompt += `- [${source.name}](${source.url}) - ${source.description}\\n`;\n }\n prompt += `\\n`;\n }\n\n prompt += `### Information Needed\\n\\n`;\n prompt += `Please look up the latest documentation and provide:\\n\\n`;\n prompt += `1. Current best practices for \"${topic}\"\\n`;\n prompt += `2. Common pitfalls to avoid\\n`;\n prompt += `3. Code examples demonstrating correct usage\\n`;\n prompt += `4. Any recent changes or deprecations\\n`;\n\n return prompt;\n}\n\n/**\n * Generate a security best practices lookup prompt\n */\nexport function generateSecurityLookup(pattern: string, context?: string): string {\n let prompt = `## 🛡️ Security Best Practices Lookup\\n\\n`;\n prompt += `**Pattern:** ${pattern}\\n`;\n if (context) prompt += `**Context:** ${context}\\n`;\n prompt += `\\n`;\n\n prompt += `### Reference Sources\\n\\n`;\n for (const source of SECURITY_SOURCES.slice(0, 3)) {\n prompt += `- [${source.name}](${source.url})\\n`;\n }\n prompt += `\\n`;\n\n prompt += `### Analysis Requested\\n\\n`;\n prompt += `Please research and provide:\\n\\n`;\n prompt += `1. **OWASP guidance** for this security pattern\\n`;\n prompt += `2. **Attack vectors** - how this could be exploited\\n`;\n prompt += `3. **Defense strategies** - recommended mitigations\\n`;\n prompt += `4. **Code examples** - secure implementation patterns\\n`;\n prompt += `5. **Testing approaches** - how to verify security\\n`;\n\n return prompt;\n}\n\n/**\n * Generate a compliance lookup prompt\n */\nexport function generateComplianceLookup(regulation: string, requirement?: string): string {\n let prompt = `## ⚖️ Compliance Requirement Lookup\\n\\n`;\n prompt += `**Regulation:** ${regulation}\\n`;\n if (requirement) prompt += `**Specific Requirement:** ${requirement}\\n`;\n prompt += `\\n`;\n\n const sources = COMPLIANCE_SOURCES[regulation.toLowerCase()];\n \n if (sources && sources.length > 0) {\n prompt += `### Official Sources\\n\\n`;\n for (const source of sources) {\n prompt += `- [${source.name}](${source.url})\\n`;\n }\n prompt += `\\n`;\n }\n\n prompt += `### Compliance Information Needed\\n\\n`;\n prompt += `Please research and provide:\\n\\n`;\n prompt += `1. **Specific requirement text** from the regulation\\n`;\n prompt += `2. **Technical requirements** for compliance\\n`;\n prompt += `3. **Implementation guidance** with code examples\\n`;\n prompt += `4. **Documentation requirements** - what records to keep\\n`;\n prompt += `5. **Penalties** for non-compliance\\n`;\n\n return prompt;\n}\n\n/**\n * Generate a changelog/version lookup prompt\n */\nexport function generateChangelogLookup(library: string, fromVersion: string, toVersion?: string): string {\n let prompt = `## 📋 Changelog Lookup\\n\\n`;\n prompt += `**Library:** ${library}\\n`;\n prompt += `**Current Version:** ${fromVersion}\\n`;\n if (toVersion) prompt += `**Target Version:** ${toVersion}\\n`;\n prompt += `\\n`;\n\n prompt += `### Information Needed\\n\\n`;\n prompt += `Please find the changelog/release notes and provide:\\n\\n`;\n prompt += `1. **Breaking changes** between versions\\n`;\n prompt += `2. **New features** added\\n`;\n prompt += `3. **Deprecations** to be aware of\\n`;\n prompt += `4. **Security fixes** included\\n`;\n prompt += `5. **Migration guide** if available\\n`;\n prompt += `6. **Known issues** with the upgrade\\n`;\n\n return prompt;\n}\n\n/**\n * Main knowledge lookup function\n */\nexport function lookupKnowledge(request: KnowledgeRequest): string {\n const { type, query, context = {} } = request;\n\n switch (type) {\n case 'cve':\n return generateCVELookup(query, context.version);\n \n case 'docs':\n return generateDocsLookup(query, context.framework);\n \n case 'security':\n return generateSecurityLookup(query, context.context);\n \n case 'best-practices':\n return generateComplianceLookup(query, context.requirement);\n \n case 'changelog':\n return generateChangelogLookup(query, context.fromVersion || 'current', context.toVersion);\n \n default:\n return `Unknown knowledge request type: ${type}`;\n }\n}\n\n/**\n * Detect libraries and versions from package.json\n */\nexport async function detectDependencies(packageJsonPath: string): Promise<Map<string, string>> {\n const deps = new Map<string, string>();\n \n try {\n const { readFile } = await import('fs/promises');\n const content = await readFile(packageJsonPath, 'utf-8');\n const pkg = JSON.parse(content);\n \n const allDeps = {\n ...pkg.dependencies,\n ...pkg.devDependencies,\n };\n\n for (const [name, version] of Object.entries(allDeps)) {\n deps.set(name, String(version).replace(/^[\\^~]/, ''));\n }\n } catch {\n // Ignore errors\n }\n\n return deps;\n}\n\n/**\n * Known vulnerable packages (quick check - not exhaustive)\n */\nexport const KNOWN_VULNERABLE_PATTERNS = [\n { pattern: /^lodash$/, minSafeVersion: '4.17.21', reason: 'Prototype pollution' },\n { pattern: /^minimist$/, minSafeVersion: '1.2.6', reason: 'Prototype pollution' },\n { pattern: /^node-fetch$/, minSafeVersion: '2.6.7', reason: 'URL bypass' },\n { pattern: /^axios$/, minSafeVersion: '1.6.0', reason: 'SSRF vulnerability' },\n { pattern: /^jsonwebtoken$/, minSafeVersion: '9.0.0', reason: 'Algorithm confusion' },\n];\n\n","/**\n * MCP Tool: trie_create_agent\n * \n * Creates a custom agent from a PDF, TXT, MD, or RTF document.\n * \n * This is a two-step process that leverages the host LLM (Claude in Cursor/Claude Code):\n * 1. trie_create_agent - Parses document and returns extraction prompt\n * 2. trie_save_agent - Saves the agent config after Claude processes it\n * \n * This design eliminates the need for a separate ANTHROPIC_API_KEY since\n * the user is already in an AI workflow with Claude.\n */\n\nimport { parseDocument } from '../ingest/document-parser.js';\nimport { listCustomAgents, loadAgentConfig } from '../ingest/agent-builder.js';\nimport type { GeneratedAgentConfig, CompressedKnowledge } from '../types/custom-agent.js';\nimport { existsSync } from 'fs';\nimport { mkdir, writeFile } from 'fs/promises';\nimport { join, basename, extname } from 'path';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport class TrieCreateAgentTool {\n async execute(args: {\n filePath?: string;\n documentContent?: string;\n agentName: string;\n displayName?: string;\n description?: string;\n category?: string;\n }) {\n const { filePath, documentContent, agentName, displayName, description, category } = args;\n \n // Validate inputs\n if (!agentName) {\n return this.errorResponse('Missing required parameter: agentName');\n }\n \n // Either filePath or documentContent must be provided\n if (!filePath && !documentContent) {\n return this.errorResponse(\n 'Provide either filePath (path to PDF/TXT/MD file) or documentContent (raw text from drag-and-drop)'\n );\n }\n \n try {\n let rawText: string;\n let title: string = agentName;\n let wordCount: number = 0;\n \n if (filePath) {\n // Check if file exists\n if (!existsSync(filePath)) {\n return this.errorResponse(`File not found: ${filePath}`);\n }\n \n // Check supported file types\n const ext = filePath.toLowerCase().split('.').pop();\n if (!['pdf', 'txt', 'md', 'markdown', 'rtf'].includes(ext || '')) {\n return this.errorResponse(\n `Unsupported file type: .${ext}\\nSupported types: .pdf, .txt, .md, .rtf`\n );\n }\n \n // Parse the document\n const document = await parseDocument(filePath);\n rawText = document.rawText;\n // fileType is available in document.metadata.fileType if needed\n title = document.metadata.title || basename(filePath, extname(filePath));\n wordCount = document.metadata.wordCount;\n } else {\n // Use provided document content (from drag-and-drop)\n rawText = documentContent!;\n wordCount = rawText.split(/\\s+/).filter(w => w.length > 0).length;\n \n // Try to extract title from first line\n const firstLine = rawText.split('\\n')[0]?.trim();\n if (firstLine && firstLine.length < 100) {\n title = firstLine;\n }\n }\n \n // Chunk the document for processing\n const chunks = this.chunkText(rawText, 6000);\n \n // Build the extraction prompt that Claude will process\n const extractionPrompt = this.buildExtractionPrompt(\n chunks,\n title,\n agentName,\n category,\n displayName,\n description\n );\n \n // Return the prompt for Claude to process\n return {\n content: [\n {\n type: 'text',\n text: this.formatExtractionRequest(\n agentName,\n title,\n wordCount,\n chunks.length,\n extractionPrompt\n ),\n },\n ],\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return this.errorResponse(`Failed to parse document: ${errorMessage}`);\n }\n }\n \n /**\n * Chunk text into manageable pieces\n */\n private chunkText(text: string, maxChunkSize: number): string[] {\n if (text.length <= maxChunkSize) {\n return [text];\n }\n \n const chunks: string[] = [];\n const paragraphs = text.split(/\\n\\s*\\n/);\n let currentChunk = '';\n \n for (const para of paragraphs) {\n if (currentChunk.length + para.length + 2 > maxChunkSize) {\n if (currentChunk) chunks.push(currentChunk.trim());\n currentChunk = para;\n } else {\n currentChunk += (currentChunk ? '\\n\\n' : '') + para;\n }\n }\n \n if (currentChunk) chunks.push(currentChunk.trim());\n return chunks;\n }\n \n /**\n * Build the extraction prompt for Claude\n */\n private buildExtractionPrompt(\n chunks: string[],\n title: string,\n agentName: string,\n category?: string,\n displayName?: string,\n description?: string\n ): string {\n const prefix = agentName.toUpperCase().replace(/[^A-Z]/g, '').slice(0, 4) || 'CUST';\n \n // Combine chunks with separators\n const documentContent = chunks.length === 1 \n ? chunks[0]\n : chunks.map((c, i) => `--- SECTION ${i + 1}/${chunks.length} ---\\n${c}`).join('\\n\\n');\n \n return `# Create Code Review Agent: \"${displayName || this.formatDisplayName(agentName)}\"\n\n## Your Task\nAnalyze the following document and extract structured knowledge to create a code review agent.\n\n## Document Information\n- **Title**: ${title}\n- **Agent Name**: ${agentName}\n- **Category**: ${category || 'auto-detect'}\n${description ? `- **Description**: ${description}` : ''}\n\n## Document Content\n${documentContent}\n\n---\n\n## Instructions\n\nPlease analyze this document and produce a **single JSON object** with the following structure. This will be used to create a custom code review agent.\n\n**IMPORTANT**: Your response should be ONLY the JSON object, no other text.\n\n\\`\\`\\`json\n{\n \"agentConfig\": {\n \"name\": \"${this.sanitizeAgentName(agentName)}\",\n \"displayName\": \"${displayName || this.formatDisplayName(agentName)}\",\n \"description\": \"${description || `Code review agent based on ${title}`}\",\n \"version\": \"1.0.0\",\n \"category\": \"string (technical | legal | policy | security | architecture | general)\"\n },\n \"knowledge\": {\n \"domain\": \"string (technical | legal | policy | security | architecture | general)\",\n \"summary\": \"2-3 paragraph summary of the document's key insights for code review\",\n \"coreConcepts\": [\n {\n \"name\": \"string\",\n \"description\": \"string\",\n \"importance\": \"critical | important | supplementary\",\n \"keywords\": [\"string\"]\n }\n ],\n \"bestPractices\": [\n {\n \"name\": \"string\",\n \"description\": \"string\",\n \"rationale\": \"why this is important\",\n \"codeExample\": \"optional code example or null\"\n }\n ],\n \"antiPatterns\": [\n {\n \"name\": \"string\",\n \"description\": \"string\",\n \"whyBad\": \"why to avoid\",\n \"betterAlternative\": \"what to do instead\"\n }\n ],\n \"glossary\": {\n \"term\": \"definition\"\n }\n },\n \"detectionRules\": [\n {\n \"id\": \"${prefix}-001\",\n \"name\": \"Rule Name\",\n \"description\": \"What this rule detects\",\n \"severity\": \"critical | serious | moderate | low | info\",\n \"patterns\": {\n \"regex\": [\"JavaScript regex patterns\"],\n \"keywords\": [\"words that indicate this issue\"],\n \"semantic\": \"Natural language description for AI detection\"\n },\n \"fix\": {\n \"description\": \"How to fix this issue\",\n \"example\": \"Code example or null\",\n \"autoFixable\": false\n },\n \"category\": \"string\"\n }\n ],\n \"prompts\": {\n \"systemPrompt\": \"You are an expert code reviewer specializing in [topic]. Your role is to...\",\n \"analysisPrompt\": \"Review this code for issues related to [topic]. Look for: ...\\\\n\\\\nCode:\\\\n\\\\\\`\\\\\\`\\\\\\`{{language}}\\\\n{{code}}\\\\n\\\\\\`\\\\\\`\\\\\\`\\\\n\\\\nFile: {{filePath}}\",\n \"fixPrompt\": \"Fix this issue: {{issue}}\\\\n\\\\nCode:\\\\n\\\\\\`\\\\\\`\\\\\\`{{language}}\\\\n{{code}}\\\\n\\\\\\`\\\\\\`\\\\\\`\"\n }\n}\n\\`\\`\\`\n\n## Guidelines\n\n1. **Core Concepts**: Extract 10-20 key concepts that are fundamental to the material\n2. **Best Practices**: Extract 10-15 recommended approaches with rationale\n3. **Anti-Patterns**: Extract 10-15 things to avoid with explanations\n4. **Detection Rules**: Generate 15-30 rules with regex patterns that could detect issues in code\n5. **Prompts**: Create prompts that embody the expertise from this document\n\nFocus on extracting actionable, code-reviewable knowledge. The agent should be able to find violations of the principles in this document.\n\n**Output ONLY the JSON object, starting with \\`{\\` and ending with \\`}\\`.**`;\n }\n \n /**\n * Format the extraction request output\n */\n private formatExtractionRequest(\n agentName: string,\n title: string,\n wordCount: number,\n chunkCount: number,\n prompt: string\n ): string {\n return `\n📚 **Document Parsed Successfully!**\n\n${'━'.repeat(50)}\n\n**Creating Agent:** \\`${agentName}\\`\n**Source Document:** ${title}\n**Word Count:** ${wordCount.toLocaleString()}\n**Processing Chunks:** ${chunkCount}\n\n${'━'.repeat(50)}\n\n## Next Step\n\nI've prepared the document for analysis. Please process the following prompt to extract the knowledge, then pass the result to \\`trie_save_agent\\` to save the agent.\n\n${'─'.repeat(50)}\n\n${prompt}\n`;\n }\n \n private sanitizeAgentName(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '');\n }\n \n private formatDisplayName(name: string): string {\n return name\n .split(/[-_]/)\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n }\n \n private errorResponse(message: string) {\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error:** ${message}`,\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * MCP Tool: trie_save_agent\n * \n * Saves an agent configuration after Claude has processed the document.\n * This is step 2 of the agent creation process.\n */\nexport class TrieSaveAgentTool {\n async execute(args: {\n agentConfig: {\n name: string;\n displayName: string;\n description: string;\n version?: string;\n category: string;\n };\n knowledge: {\n domain: string;\n summary: string;\n coreConcepts: Array<{\n name: string;\n description: string;\n importance: string;\n keywords?: string[];\n }>;\n bestPractices: Array<{\n name: string;\n description: string;\n rationale: string;\n codeExample?: string | null;\n }>;\n antiPatterns: Array<{\n name: string;\n description: string;\n whyBad: string;\n betterAlternative: string;\n }>;\n glossary?: Record<string, string>;\n };\n detectionRules: Array<{\n id: string;\n name: string;\n description: string;\n severity: string;\n patterns: {\n regex?: string[];\n keywords?: string[];\n semantic?: string;\n };\n fix: {\n description: string;\n example?: string | null;\n autoFixable?: boolean;\n };\n category?: string;\n }>;\n prompts: {\n systemPrompt: string;\n analysisPrompt: string;\n fixPrompt: string;\n };\n sourceFile?: string;\n }) {\n const { agentConfig, knowledge, detectionRules, prompts, sourceFile } = args;\n \n // Validate required fields\n if (!agentConfig?.name) {\n return this.errorResponse('Missing agentConfig.name');\n }\n \n if (!knowledge?.summary) {\n return this.errorResponse('Missing knowledge.summary');\n }\n \n if (!prompts?.systemPrompt) {\n return this.errorResponse('Missing prompts.systemPrompt');\n }\n \n try {\n // Build the full agent config\n const fullConfig: GeneratedAgentConfig = {\n name: this.sanitizeAgentName(agentConfig.name),\n displayName: agentConfig.displayName || this.formatDisplayName(agentConfig.name),\n description: agentConfig.description,\n version: agentConfig.version || '1.0.0',\n category: agentConfig.category || knowledge.domain || 'general',\n \n source: {\n type: 'document',\n originalFile: sourceFile || 'user-provided',\n fileType: 'txt',\n compressedAt: new Date().toISOString(),\n },\n \n systemPrompt: prompts.systemPrompt,\n analysisPrompt: prompts.analysisPrompt,\n fixPrompt: prompts.fixPrompt,\n \n activationRules: this.buildActivationRules(knowledge, detectionRules),\n \n patterns: detectionRules.map((rule, i) => {\n const fixObj: { description: string; autoFixable: boolean; example?: string } = {\n description: rule.fix?.description || 'Review and fix manually',\n autoFixable: rule.fix?.autoFixable || false,\n };\n if (rule.fix?.example) {\n fixObj.example = rule.fix.example;\n }\n return {\n id: rule.id || `CUST-${String(i + 1).padStart(3, '0')}`,\n name: rule.name,\n description: rule.description,\n severity: (rule.severity as 'critical' | 'serious' | 'moderate' | 'low' | 'info') || 'moderate',\n patterns: {\n regex: rule.patterns?.regex || [],\n keywords: rule.patterns?.keywords || [],\n semantic: rule.patterns?.semantic || '',\n },\n fix: fixObj,\n category: rule.category || agentConfig.category,\n };\n }),\n \n knowledge: {\n domain: (knowledge.domain as CompressedKnowledge['domain']) || 'general',\n summary: knowledge.summary,\n coreConcepts: knowledge.coreConcepts.map(c => ({\n name: c.name,\n description: c.description,\n importance: (c.importance as 'critical' | 'important' | 'supplementary') || 'important',\n relatedPatterns: (c as any).relatedPatterns || [],\n keywords: c.keywords || [],\n })),\n bestPractices: knowledge.bestPractices.map(bp => {\n const practice: { name: string; description: string; rationale: string; category: string; codeExample?: string } = {\n name: bp.name,\n description: bp.description,\n rationale: bp.rationale,\n category: (bp as any).category || agentConfig.category,\n };\n if (bp.codeExample) {\n practice.codeExample = bp.codeExample;\n }\n return practice;\n }),\n antiPatterns: knowledge.antiPatterns.map(ap => ({\n name: ap.name,\n description: ap.description,\n whyBad: ap.whyBad,\n betterAlternative: ap.betterAlternative,\n })),\n detectionRules: [],\n glossary: knowledge.glossary || {},\n sourceDocument: {\n title: agentConfig.displayName || agentConfig.name,\n wordCount: 0,\n compressionRatio: 0,\n },\n },\n };\n \n // Save the config\n const configPath = await this.saveAgentConfig(fullConfig);\n \n return {\n content: [\n {\n type: 'text',\n text: this.formatSuccessResponse(fullConfig, configPath),\n },\n ],\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return this.errorResponse(`Failed to save agent: ${errorMessage}`);\n }\n }\n \n private buildActivationRules(\n knowledge: { domain: string; coreConcepts: Array<{ keywords?: string[] }> },\n detectionRules: Array<{ patterns: { keywords?: string[] } }>\n ): GeneratedAgentConfig['activationRules'] {\n const domainRules: Record<string, Partial<GeneratedAgentConfig['activationRules']>> = {\n technical: {\n filePatterns: ['*.ts', '*.tsx', '*.js', '*.jsx', '*.py', '*.go', '*.rs'],\n contextSignals: ['touchesUI', 'touchesAPI'],\n priority: 2,\n },\n legal: {\n filePatterns: ['*'],\n contextSignals: ['touchesUserData', 'touchesAuth', 'touchesPayments'],\n priority: 2,\n },\n policy: {\n filePatterns: ['*'],\n contextSignals: ['touchesAuth', 'touchesAPI', 'touchesDatabase'],\n priority: 3,\n },\n security: {\n filePatterns: ['*'],\n contextSignals: ['touchesAuth', 'touchesCrypto', 'touchesAPI', 'touchesDatabase'],\n priority: 1,\n },\n architecture: {\n filePatterns: ['*.ts', '*.tsx', '*.js', '*.jsx', '*.py', '*.go'],\n contextSignals: ['touchesAPI', 'touchesDatabase'],\n priority: 2,\n },\n general: {\n filePatterns: ['*'],\n contextSignals: [],\n priority: 3,\n },\n };\n \n const defaults = domainRules[knowledge.domain] || domainRules.general!;\n \n // Extract content patterns from rules and concepts\n const contentPatterns: string[] = [];\n for (const rule of detectionRules) {\n if (rule.patterns?.keywords) {\n contentPatterns.push(...rule.patterns.keywords.slice(0, 3));\n }\n }\n for (const concept of knowledge.coreConcepts.slice(0, 5)) {\n if (concept.keywords) {\n contentPatterns.push(...concept.keywords.slice(0, 2));\n }\n }\n \n return {\n filePatterns: defaults.filePatterns || ['*'],\n contentPatterns: [...new Set(contentPatterns)].slice(0, 20),\n contextSignals: defaults.contextSignals || [],\n minConfidence: 0.3,\n priority: defaults.priority || 2,\n };\n }\n \n private async saveAgentConfig(config: GeneratedAgentConfig): Promise<string> {\n const trieDir = join(getWorkingDirectory(undefined, true), '.trie', 'agents');\n await mkdir(trieDir, { recursive: true });\n \n const configPath = join(trieDir, `${config.name}.json`);\n await writeFile(configPath, JSON.stringify(config, null, 2));\n \n return configPath;\n }\n \n private formatSuccessResponse(config: GeneratedAgentConfig, configPath: string): string {\n return `\n✅ **Agent Created Successfully!**\n\n${'━'.repeat(50)}\n\n**Agent Name:** \\`${config.name}\\`\n**Display Name:** ${config.displayName}\n**Category:** ${config.category}\n**Config Saved To:** \\`${configPath}\\`\n\n📊 **Statistics:**\n • Core concepts: ${config.knowledge.coreConcepts.length}\n • Best practices: ${config.knowledge.bestPractices.length}\n • Anti-patterns: ${config.knowledge.antiPatterns.length}\n • Detection rules: ${config.patterns.length}\n\n🚀 **Next Steps:**\n 1. The agent is now registered and will activate during scans\n 2. Run \\`trie_scan\\` to test the new agent\n 3. Edit \\`${configPath}\\` to customize detection rules\n\n💡 **Usage:**\n The agent will automatically activate when scanning code that matches its patterns.\n Use \\`trie_list_agents\\` to see all registered agents.\n`.trim();\n }\n \n private sanitizeAgentName(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '');\n }\n \n private formatDisplayName(name: string): string {\n return name\n .split(/[-_]/)\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n }\n \n private errorResponse(message: string) {\n return {\n content: [\n {\n type: 'text',\n text: `❌ **Error:** ${message}`,\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * MCP Tool: trie_list_agents\n * \n * Lists all registered agents including custom ones\n */\nexport class TrieListAgentsTool {\n async execute(args: { includeBuiltin?: boolean }) {\n const { includeBuiltin = true } = args;\n \n try {\n // Get custom agents\n const customAgentNames = await listCustomAgents();\n const customAgents = await Promise.all(\n customAgentNames.map(async name => {\n const config = await loadAgentConfig(name);\n return config ? {\n name: config.name,\n displayName: config.displayName,\n category: config.category,\n source: config.source.originalFile,\n patterns: config.patterns.length,\n isCustom: true,\n } : null;\n })\n );\n \n const validCustomAgents = customAgents.filter(Boolean);\n \n // Built-in agents (20 total)\n const builtinAgents = includeBuiltin ? [\n // Security & Compliance\n { name: 'security', displayName: 'Security Agent', category: 'security', isCustom: false },\n { name: 'privacy', displayName: 'Privacy Agent', category: 'privacy', isCustom: false },\n { name: 'soc2', displayName: 'SOC 2 Agent', category: 'compliance', isCustom: false },\n { name: 'legal', displayName: 'Legal Agent', category: 'compliance', isCustom: false },\n // Code Quality\n { name: 'software-architect', displayName: 'Architecture Agent', category: 'architecture', isCustom: false },\n { name: 'bug-finding', displayName: 'Bug Finding Agent', category: 'quality', isCustom: false },\n { name: 'typecheck', displayName: 'TypeCheck Agent', category: 'quality', isCustom: false },\n { name: 'trie-clean', displayName: 'Clean Agent', category: 'ai-code', isCustom: false },\n { name: 'data-flow', displayName: 'Data Flow Agent', category: 'quality', isCustom: false },\n // Design & UX\n { name: 'design-engineer', displayName: 'Design Engineer Agent', category: 'design', isCustom: false },\n { name: 'accessibility', displayName: 'Accessibility Agent', category: 'accessibility', isCustom: false },\n { name: 'user-testing', displayName: 'UX Agent', category: 'ux', isCustom: false },\n { name: 'visual-qa', displayName: 'Visual QA Agent', category: 'visual', isCustom: false },\n // DevOps & Testing\n { name: 'devops', displayName: 'DevOps Agent', category: 'devops', isCustom: false },\n { name: 'test', displayName: 'Test Agent', category: 'testing', isCustom: false },\n { name: 'e2e', displayName: 'E2E Agent', category: 'testing', isCustom: false },\n { name: 'performance', displayName: 'Performance Agent', category: 'performance', isCustom: false },\n // Review & Explanation\n { name: 'super-reviewer', displayName: 'Super Reviewer', category: 'review', isCustom: false },\n { name: 'agent-smith', displayName: 'Agent Smith', category: 'review', isCustom: false },\n { name: 'comprehension', displayName: 'Comprehension Agent', category: 'communication', isCustom: false },\n ] : [];\n \n // Format response\n let response = `# 🤖 Registered Agents\\n\\n`;\n \n if (builtinAgents.length > 0) {\n response += `## Built-in Agents (${builtinAgents.length})\\n\\n`;\n for (const agent of builtinAgents) {\n response += `- **${agent.displayName}** (\\`${agent.name}\\`) - ${agent.category}\\n`;\n }\n response += '\\n';\n }\n \n response += `## Custom Agents (${validCustomAgents.length})\\n\\n`;\n \n if (validCustomAgents.length === 0) {\n response += `_No custom agents created yet._\\n\\n`;\n response += `💡 Create one with: \\`trie_create_agent\\`\\n`;\n response += ` - Provide a PDF, TXT, or MD file path\\n`;\n response += ` - Or paste/drag document content directly\\n`;\n } else {\n for (const agent of validCustomAgents) {\n if (agent) {\n response += `- **${agent.displayName}** (\\`${agent.name}\\`)\\n`;\n response += ` - Category: ${agent.category}\\n`;\n response += ` - Patterns: ${agent.patterns}\\n`;\n response += ` - Source: ${agent.source}\\n\\n`;\n }\n }\n }\n \n return {\n content: [\n {\n type: 'text',\n text: response,\n },\n ],\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return {\n content: [\n {\n type: 'text',\n text: `❌ Error listing agents: ${errorMessage}`,\n },\n ],\n isError: true,\n };\n }\n }\n}\n","import { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join, basename, resolve, isAbsolute } from 'path';\nimport { execSync } from 'child_process';\nimport { SuperReviewerAgent, CRITICAL_REVIEW_CHECKLIST } from '../agents/super-reviewer.js';\nimport { getWorkingDirectory } from '../utils/workspace.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 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 execSync('git branch --show-current', { encoding: 'utf-8' }).trim();\n \n // Check if there's a PR for this branch\n const prJson = execSync(`gh pr view --json number,title,author,headRefName,baseRefName`, {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe']\n }).trim();\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 = execSync(`gh pr view ${prNumber} --json number,title,author,headRefName,baseRefName`, {\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe']\n }).trim();\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 = execSync(`gh pr diff ${prInfo.number}`, {\n encoding: 'utf-8',\n maxBuffer: 50 * 1024 * 1024, // 50MB buffer for large PRs\n });\n } else if (prInfo.type === 'worktree' && prInfo.path) {\n // Get diff from worktree\n diffOutput = execSync(`git diff HEAD`, {\n encoding: 'utf-8',\n cwd: prInfo.path,\n maxBuffer: 50 * 1024 * 1024,\n });\n } else {\n // Local changes\n diffOutput = execSync(`git diff HEAD`, {\n encoding: 'utf-8',\n maxBuffer: 50 * 1024 * 1024,\n });\n \n // If no diff, try staged changes\n if (!diffOutput.trim()) {\n diffOutput = execSync(`git diff --cached`, {\n encoding: 'utf-8',\n maxBuffer: 50 * 1024 * 1024,\n });\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 });\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 execSync('git config user.name', { encoding: 'utf-8' }).trim();\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}\n","/**\n * Project Info MCP Tool\n * \n * Provides MCP tool for viewing and managing PROJECT.md\n */\n\nimport {\n loadProjectInfo,\n saveProjectInfo,\n initProjectInfo,\n getProjectSection,\n updateProjectSection,\n appendToSection,\n getProjectSections,\n getProjectInfoStructured,\n projectInfoExists,\n getProjectTemplate,\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-agent 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","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 { TrieRegisterAgentTool } from '../tools/register-agent.js';\nimport { TrieWatchTool } from '../tools/watch.js';\nimport { TrieAgentTool } from '../tools/agent.js';\nimport { TrieCreateAgentTool, TrieSaveAgentTool, TrieListAgentsTool } from '../tools/create-agent.js';\nimport { TriePRReviewTool } from '../tools/pr-review.js';\nimport { TrieProjectInfoTool } from '../tools/project-info.js';\n\nexport interface ToolDefinition {\n name: string;\n description: string;\n inputSchema: Record<string, any>;\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('register_agent', new TrieRegisterAgentTool());\n this.tools.set('watch', new TrieWatchTool());\n this.tools.set('agent', new TrieAgentTool());\n this.tools.set('create_agent', new TrieCreateAgentTool());\n this.tools.set('save_agent', new TrieSaveAgentTool());\n this.tools.set('list_agents', new TrieListAgentsTool());\n this.tools.set('pr_review', new TriePRReviewTool());\n this.tools.set('project', new TrieProjectInfoTool());\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 },\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, privacy, 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 agent 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_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_register_agent',\n description: 'Register an agent by name and path. Alias: register_agent',\n inputSchema: {\n type: 'object',\n properties: {\n name: { type: 'string', description: 'Name of the agent' },\n path: { type: 'string', description: 'Path to the agent implementation' }\n },\n required: ['name', 'path']\n } as const,\n },\n {\n name: 'trie_list_agents',\n description: 'List built-in and custom agents. Alias: list_agents',\n inputSchema: {\n type: 'object',\n properties: {\n includeBuiltin: {\n type: 'boolean',\n description: 'Include built-in agents (default true)'\n }\n }\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 // Add remaining tool definitions...\n this.createAgentToolDefinitions(),\n this.createCustomAgentDefinitions(),\n this.createSpecialAgentDefinitions(),\n ].flat();\n }\n\n private createAgentToolDefinitions(): ToolDefinition[] {\n const agentTypes = [\n { name: 'security', desc: 'detect vulnerabilities, injection risks, auth issues, hardcoded secrets' },\n { name: 'privacy', desc: 'PII handling, GDPR/HIPAA compliance, data encryption' },\n { name: 'legal', desc: 'GDPR, CCPA, consent patterns, data retention compliance' },\n { name: 'accessibility', desc: 'WCAG 2.1 compliance, keyboard nav, screen readers, color contrast' },\n { name: 'design', desc: '🎨 Awwwards-level polish, design systems, motion design, creative CSS' },\n { name: 'architecture', desc: 'code organization, SOLID principles, N+1 queries, scalability' },\n { name: 'bugs', desc: 'null safety, edge cases, common bugs, async issues' },\n { name: 'ux', desc: 'simulate happy path, security tester, confused user, impatient user' },\n { name: 'types', desc: 'type errors, missing annotations, null checks' },\n { name: 'devops', desc: 'config issues, logging, environment variables, deployment patterns' },\n { name: 'clean', desc: '🧹 Clean up AI-generated code: find common mistakes, bad patterns, and quick fixes' },\n { name: 'soc2', desc: 'SOC 2 compliance: access controls, secrets management, encryption, logging, change management' },\n ];\n\n return agentTypes.map(agent => ({\n name: `trie_${agent.name}`,\n description: `Run ${agent.name} agent: ${agent.desc}. Alias: ${agent.name}`,\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n }));\n }\n\n private createCustomAgentDefinitions(): ToolDefinition[] {\n return [\n {\n name: 'trie_create_agent',\n description: '📚 Step 1: Parse a document to create a custom agent. Returns extraction prompt for Claude to process. Alias: create_agent',\n inputSchema: {\n type: 'object',\n properties: {\n filePath: {\n type: 'string',\n description: 'Path to the document file (PDF, TXT, MD, or RTF)'\n },\n documentContent: {\n type: 'string',\n description: 'Raw document text (for drag-and-drop content). Use this OR filePath.'\n },\n agentName: {\n type: 'string',\n description: 'Name for the new agent (e.g., \"react-fundamentals\")'\n },\n displayName: { type: 'string', description: 'Optional display name' },\n description: { type: 'string', description: 'Optional description' },\n category: { type: 'string', description: 'Optional category (e.g., \"security\", \"react\")' }\n },\n required: ['agentName']\n } as const,\n },\n {\n name: 'trie_save_agent',\n description: '📦 Step 2: Save the agent config after Claude extracts knowledge. Alias: save_agent',\n inputSchema: {\n type: 'object',\n properties: {\n agentConfig: {\n type: 'object',\n description: 'Agent configuration',\n properties: {\n name: { type: 'string' },\n displayName: { type: 'string' },\n description: { type: 'string' },\n version: { type: 'string' },\n category: { type: 'string' }\n },\n required: ['name', 'category']\n },\n knowledge: { type: 'object', description: 'Extracted knowledge' },\n detectionRules: { type: 'array', description: 'Detection rules array' },\n prompts: {\n type: 'object',\n properties: {\n systemPrompt: { type: 'string' },\n analysisPrompt: { type: 'string' },\n fixPrompt: { type: 'string' }\n },\n required: ['systemPrompt', 'analysisPrompt', 'fixPrompt']\n }\n },\n required: ['agentConfig', 'knowledge', 'detectionRules', 'prompts']\n } as const,\n }\n ];\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 },\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 },\n {\n name: 'trie_agent_smith',\n description: '🕴️ Agent Smith: Relentless pattern hunter. \"It is... inevitable.\" Alias: agent_smith',\n inputSchema: {\n type: 'object',\n properties: {\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Files to scan (defaults to entire codebase)'\n },\n directory: {\n type: 'string',\n description: 'Directory to scan. Pass the workspace/project root path for accurate results.'\n },\n clear_memory: {\n type: 'boolean',\n description: 'Clear Agent Smith\\'s memory bank'\n },\n show_stats: {\n type: 'boolean',\n description: 'Show memory statistics'\n }\n }\n } as const,\n },\n {\n name: 'trie_smith',\n description: '🕴️ Agent Smith (alias): Hunt AI-generated code anti-patterns. 43 specialized hunters. Alias: smith',\n inputSchema: {\n type: 'object',\n properties: {\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Files to scan (defaults to entire codebase)'\n },\n directory: {\n type: 'string',\n description: 'Directory to scan. Pass the workspace/project root path for accurate results.'\n }\n }\n } as const,\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 } from 'path';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { getAgentRegistry } from '../agents/registry.js';\nimport { loadConfig } from '../config/loader.js';\nimport { getContextForAI, loadContextState } from '../utils/context-state.js';\nimport { loadProjectInfo, projectInfoExists } from '../utils/project-info.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\nexport class ResourceManager {\n private agentRegistry = getAgentRegistry();\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',\n description: 'Current project context for AI assistants - 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://agents',\n name: 'Available Agents',\n description: 'List of all available Trie agents (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\n // Dynamic resources: scan reports\n resources.push(...await this.getScanReportResources());\n\n // Dynamic resources: custom agents\n resources.push(...await this.getCustomAgentResources());\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 getCustomAgentResources(): Promise<Resource[]> {\n try {\n await this.agentRegistry.loadCustomAgents();\n const customAgents = this.agentRegistry.getCustomAgents();\n\n return customAgents.map(agent => ({\n uri: `trie://agents/custom/${agent.name}`,\n name: `Custom Agent: ${agent.name}`,\n description: agent.description,\n mimeType: 'application/json',\n }));\n } catch {\n return []; // No custom agents\n }\n }\n\n /**\n * Read content for a specific resource\n */\n async readResourceContent(uri: string): Promise<ResourceContent> {\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 agents list\n if (parsedUri === 'agents') {\n return await this.getAgentsResource(uri);\n }\n\n // Handle specific custom agent\n if (parsedUri.startsWith('agents/custom/')) {\n return await this.getCustomAgentResource(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 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 private async getContextResource(uri: string): Promise<ResourceContent> {\n // First try to read the AGENTS.md file\n const workDir = getWorkingDirectory(undefined, true);\n const agentsMdPath = join(workDir, '.trie', 'AGENTS.md');\n \n try {\n if (existsSync(agentsMdPath)) {\n const content = await readFile(agentsMdPath, 'utf-8');\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: content,\n }],\n };\n }\n } catch {\n // Fall back to generated context\n }\n \n // Fall back to generated context summary\n const contextSummary = await getContextForAI();\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: contextSummary,\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-agent 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 getAgentsResource(uri: string): Promise<ResourceContent> {\n await this.agentRegistry.loadCustomAgents();\n const agents = this.agentRegistry.getAgentDescriptions();\n\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n totalAgents: agents.length,\n builtinCount: agents.filter(a => !a.isCustom).length,\n customCount: agents.filter(a => a.isCustom).length,\n agents: agents.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 getCustomAgentResource(uri: string, parsedUri: string): Promise<ResourceContent> {\n const agentName = parsedUri.replace('agents/custom/', '');\n await this.agentRegistry.loadCustomAgents();\n const metadata = this.agentRegistry.getCustomAgentMetadata(agentName);\n\n if (!metadata) {\n throw new Error(`Custom agent not found: ${agentName}`);\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(getWorkingDirectory(undefined, true), '.trie', '.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 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}","import { chromium, Browser, Page } from 'playwright';\nimport { createServer, Server } from 'net';\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 */\nasync function findOpenPort(): Promise<number | null> {\n const commonPorts = [3000, 3001, 5173, 5174, 4200, 8080, 8000, 8888, 5000, 4000];\n \n for (const port of commonPorts) {\n const isOpen = await checkPort(port);\n if (isOpen) {\n return port;\n }\n }\n return null;\n}\n\n/**\n * Check if a port has something listening on it\n */\nasync function checkPort(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const server: Server = createServer();\n \n server.once('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EADDRINUSE') {\n // Port is in use - something is running!\n resolve(true);\n } else {\n resolve(false);\n }\n });\n \n server.once('listening', () => {\n // Port is free - nothing running\n server.close();\n resolve(false);\n });\n \n server.listen(port, '127.0.0.1');\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 const port = options.port || await findOpenPort();\n \n if (!port) {\n return {\n success: false,\n url: '',\n screenshots: [],\n error: 'No running dev server found. Please provide a URL or start your dev server on a common port (3000, 5173, 8080, etc.)',\n analysisPrompt: '',\n };\n }\n \n url = `http://localhost:${port}`;\n }\n\n const viewports = options.viewports || DEFAULT_VIEWPORTS;\n\n try {\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 const screenshots = await captureScreenshots(url, viewports, {\n waitForSelector: options.waitForSelector,\n waitMs: options.waitMs,\n });\n\n console.error(` ✓ Captured ${screenshots.length} screenshots`);\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')) {\n return {\n success: false,\n url,\n screenshots: [],\n error: `Cannot connect to ${url}. Is your dev server running?`,\n analysisPrompt: '',\n };\n }\n \n if (errorMessage.includes('Executable doesn\\'t exist')) {\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 return {\n success: false,\n url,\n screenshots: [],\n error: `Screenshot capture failed: ${errorMessage}`,\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 'privacy':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'privacy' });\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 const result = await runVisualQA(args as { url?: string; port?: number; waitForSelector?: string; waitMs?: number });\n return formatMCPResponse(result);\n }\n\n case 'data_flow':\n case 'dataflow':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'data-flow' });\n\n // Custom agent tools\n case 'create_agent':\n return await this.toolRegistry.getTool('create_agent').execute(args);\n\n case 'save_agent':\n return await this.toolRegistry.getTool('save_agent').execute(args);\n\n case 'list_agents':\n return await this.toolRegistry.getTool('list_agents').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 'agent_smith':\n case 'smith':\n return await this.handleAgentSmith(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-agent run (any agent 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_agents\"` — list built-in + custom agents',\n '- `action: \"visual_qa_browser\"` — screenshots for visual QA',\n '',\n '**Built-in agents:**',\n '`security`, `privacy`, `legal`, `accessibility`, `design`, `architecture`, `bugs`, `ux`, `types`, `devops`, `clean`, `soc2`, `performance`, `e2e`, `visual_qa`, `data_flow`',\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 const { AgentSmithAgent } = await import('../agents/agent-smith.js');\n\n // Handle special commands\n if (smithArgs.clear_memory) {\n const smith = new AgentSmithAgent();\n const result = await smith.clearMemory();\n return {\n content: [{ type: 'text', text: result.message }]\n };\n }\n\n if (smithArgs.show_stats) {\n const smith = new AgentSmithAgent();\n const stats = await smith.getMemoryStats();\n return {\n content: [{\n type: 'text',\n text: [\n '🕴️ Agent Smith Memory Statistics',\n '═'.repeat(40),\n `Tracked issues: ${stats.issueCount}`,\n `Dismissed issues: ${stats.dismissedCount}`,\n `Resurrected issues: ${stats.resurrectedCount}`,\n `Oldest issue: ${stats.oldestIssue ? new Date(stats.oldestIssue).toLocaleDateString() : 'N/A'}`,\n `Memory file size: ${stats.fileSizeKB} KB`,\n '',\n 'To clear memory: trie_agent_smith with clear_memory:true'\n ].join('\\n')\n }]\n };\n }\n\n // Normal scan - delegate to Agent Smith tool\n const agentSmithRunner = await import('../tools/agent-smith-runner.js');\n return await agentSmithRunner.runAgentSmith(smithArgs);\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});"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,UAAAA,eAAc;AACvB,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;;;ACLA,SAAS,eAAuB;AAErC,MAAI,QAAQ,IAAI,uBAAuB,QAAQ,IAAI,aAAa;AAC9D,WAAO;AAAA,MACL,MAAM;AAAA,MACN,uBAAuB;AAAA,MACvB,eAAe;AAAA,MACf,uBAAuB;AAAA,IACzB;AAAA,EACF;AAEA,MAAI,QAAQ,IAAI,cAAc,QAAQ,IAAI,iBAAiB;AACzD,WAAO;AAAA,MACL,MAAM;AAAA,MACN,uBAAuB;AAAA,MACvB,eAAe;AAAA,MACf,uBAAuB;AAAA,IACzB;AAAA,EACF;AAEA,MAAI,QAAQ,IAAI,mBAAmB;AACjC,WAAO;AAAA,MACL,MAAM;AAAA,MACN,uBAAuB;AAAA,MACvB,eAAe;AAAA,MACf,uBAAuB;AAAA,IACzB;AAAA,EACF;AAEA,MAAI,QAAQ,I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AA,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;;;AiB3HA,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","join","extname","basename","existsSync","existsSync","basename","join","extname","readdir","readFile","existsSync","join","extname","isAbsolute","resolve","basename","SKIP_DIRS","isAbsolute","resolve","existsSync","basename","readFile","join","extname","existsSync","join","basename","extname","existsSync","basename","extname","join","readFile","existsSync","join","basename","resolve","isAbsolute","isAbsolute","resolve","existsSync","basename","join","readFile","readdir","readFile","existsSync","join","join","readdir","existsSync","readFile","resolve","Server"]}
|