@triedotdev/mcp 1.0.141 → 1.0.142

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (25) hide show
  1. package/dist/{chunk-GXF6JOCN.js → chunk-4PAAGLKO.js} +7 -7
  2. package/dist/{chunk-LHPWSUVT.js → chunk-N2EDZTKG.js} +5 -5
  3. package/dist/{chunk-75ADWWUF.js → chunk-T6PS3MXJ.js} +2 -2
  4. package/dist/{chunk-AF2APASP.js → chunk-V7AY2EJO.js} +4 -4
  5. package/dist/{chunk-M5R6DZQY.js → chunk-WMDFK7LI.js} +10 -10
  6. package/dist/{chunk-ROVR5OHR.js → chunk-Y2LYDCJD.js} +19 -19
  7. package/dist/cli/main.js +16 -16
  8. package/dist/cli/yolo-daemon.js +9 -9
  9. package/dist/{codebase-index-5SEOESWM.js → codebase-index-FMIULFZQ.js} +3 -3
  10. package/dist/{fast-analyzer-AYLZB5TW.js → fast-analyzer-MWKCDRGD.js} +5 -5
  11. package/dist/{goal-validator-HNXXUCPW.js → goal-validator-DA3JQ6JN.js} +2 -2
  12. package/dist/index.js +91 -31
  13. package/dist/index.js.map +1 -1
  14. package/dist/{trie-agent-CZ5CGATT.js → trie-agent-6A7YBNTQ.js} +6 -6
  15. package/package.json +1 -1
  16. /package/dist/{chunk-GXF6JOCN.js.map → chunk-4PAAGLKO.js.map} +0 -0
  17. /package/dist/{chunk-LHPWSUVT.js.map → chunk-N2EDZTKG.js.map} +0 -0
  18. /package/dist/{chunk-75ADWWUF.js.map → chunk-T6PS3MXJ.js.map} +0 -0
  19. /package/dist/{chunk-AF2APASP.js.map → chunk-V7AY2EJO.js.map} +0 -0
  20. /package/dist/{chunk-M5R6DZQY.js.map → chunk-WMDFK7LI.js.map} +0 -0
  21. /package/dist/{chunk-ROVR5OHR.js.map → chunk-Y2LYDCJD.js.map} +0 -0
  22. /package/dist/{codebase-index-5SEOESWM.js.map → codebase-index-FMIULFZQ.js.map} +0 -0
  23. /package/dist/{fast-analyzer-AYLZB5TW.js.map → fast-analyzer-MWKCDRGD.js.map} +0 -0
  24. /package/dist/{goal-validator-HNXXUCPW.js.map → goal-validator-DA3JQ6JN.js.map} +0 -0
  25. /package/dist/{trie-agent-CZ5CGATT.js.map → trie-agent-6A7YBNTQ.js.map} +0 -0
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/tools/fix-triage.ts","../src/tools/cloud-fix.ts","../src/integrations/cursor-cloud-agent.ts","../src/tools/test.ts","../src/tools/watch.ts","../src/tools/pr-review.ts","../src/skills/built-in/super-reviewer.ts","../src/tools/project-info.ts","../src/tools/init.ts","../src/tools/memory-search.ts","../src/tools/reconcile.ts","../src/tools/context.ts","../src/tools/linear-sync.ts","../src/tools/github-sync.ts","../src/tools/index-codebase.ts","../src/server/tool-registry.ts","../src/server/resource-manager.ts","../src/skills/installer.ts","../src/tools/visual-qa-browser.ts","../src/server/request-handlers.ts","../src/index.ts"],"sourcesContent":["import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n ListResourcesRequestSchema,\n ReadResourceRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\n\nimport { detectAITool } from '../utils/ai-tool-detector.js';\nimport { loadConfig } from '../config/loader.js';\nimport { getSkillRegistry } from '../skills/built-in/registry.js';\nimport { ToolRegistry } from './tool-registry.js';\nimport { ResourceManager } from './resource-manager.js';\nimport { RequestHandlers } from './request-handlers.js';\n\nexport class MCPServer {\n private server: Server;\n private toolRegistry: ToolRegistry;\n private resourceManager: ResourceManager;\n private requestHandlers: RequestHandlers;\n\n constructor() {\n this.server = new Server(\n {\n name: 'trie',\n version: '1.0.0',\n description: 'Intelligent Agent Orchestration for AI Coding Tools. IMPORTANT: Read trie://context first to understand project state, priorities, and recent scan history before making changes.',\n },\n {\n capabilities: {\n tools: {},\n resources: {},\n // Enable MCP Apps - interactive UI components in AI clients\n // See: https://blog.modelcontextprotocol.io/posts/2026-01-26-mcp-apps/\n experimental: {\n ui: {},\n },\n },\n }\n );\n\n this.toolRegistry = new ToolRegistry();\n this.resourceManager = new ResourceManager();\n this.requestHandlers = new RequestHandlers(this.toolRegistry, this.resourceManager);\n\n this.setupRequestHandlers();\n }\n\n private setupRequestHandlers() {\n // List tools handler\n this.server.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: this.toolRegistry.getAllTools()\n };\n });\n\n // Call tool handler\n this.server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n return await this.requestHandlers.handleToolCall(name, args);\n });\n\n // List resources handler\n this.server.setRequestHandler(ListResourcesRequestSchema, async () => {\n return await this.requestHandlers.handleListResources();\n });\n\n // Read resource handler\n this.server.setRequestHandler(ReadResourceRequestSchema, async (request) => {\n const { uri } = request.params;\n return await this.requestHandlers.handleReadResource(uri);\n });\n }\n\n /**\n * Show startup banner\n */\n private showStartupBanner(skillCount: number, aiTool: string) {\n console.error(`\n ████████╗██████╗ ██╗███████╗\n ╚══██╔══╝██╔══██╗██║██╔════╝\n ██║ ██████╔╝██║█████╗\n ██║ ██╔══██╗██║██╔══╝\n ██║ ██║ ██║██║███████╗\n ╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝\n Your central registry for Trie and its skills\n\n by Louis Kishfy\n\n Download the Trie workspace: https://www.trie.dev\n Follow me on X: https://x.com/louiskishfy\n\n ${skillCount} skills ready | ${aiTool}\n\n Quick Start:\n • \"Scan this code\" - Run all relevant skills\n • \"Run trie_security\" - Security scan only\n • \"Run trie_soc2\" - SOC 2 compliance check\n • \"Use trie_list_skills\" - See all skills\n • \"Use trie_create_skill\" - Make custom skill\n\n Ready.\n`);\n }\n\n /**\n * Initialize and start the server\n */\n async start(): Promise<void> {\n try {\n // Detect the AI tool environment\n const aiTool = detectAITool();\n\n // Load configuration\n await loadConfig();\n\n // Get actual skill count from registry\n const registry = getSkillRegistry();\n const skillCount = registry.getAllSkills().length;\n\n this.showStartupBanner(skillCount, aiTool.name);\n\n const transport = new StdioServerTransport();\n await this.server.connect(transport);\n } catch (error) {\n console.error('Fatal error starting MCP server:', error);\n process.exit(1);\n }\n }\n}\n\n/**\n * Start the MCP server\n */\nexport async function startServer(): Promise<void> {\n const server = new MCPServer();\n await server.start();\n}","import { AITool } from '../types/index.js';\n\nexport function detectAITool(): AITool {\n // Check environment variables set by AI tools\n if (process.env.CLAUDE_CODE_VERSION || process.env.CLAUDE_CODE) {\n return {\n name: 'Claude Code',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: true,\n };\n }\n\n if (process.env.CURSOR_IDE || process.env.CURSOR_TRACE_ID) {\n return {\n name: 'Cursor',\n preferredOutputFormat: 'rich-text',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n }\n\n if (process.env.OPENCODE_INSTANCE) {\n return {\n name: 'OpenCode',\n preferredOutputFormat: 'plain-text',\n supportsDiffs: false,\n supportsInlineActions: false,\n };\n }\n\n if (process.env.VSCODE_PID || process.env.VSCODE_IPC_HOOK) {\n return {\n name: 'VS Code',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n }\n\n // Check parent process name or other hints\n const parentProcess = process.env.PARENT_PROCESS_NAME || process.env._ || '';\n if (parentProcess.toLowerCase().includes('claude')) {\n return {\n name: 'Claude Code',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: true,\n };\n }\n\n if (parentProcess.toLowerCase().includes('cursor')) {\n return {\n name: 'Cursor',\n preferredOutputFormat: 'rich-text',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n }\n\n // Check if running via npx (likely from an MCP client)\n if (process.env.npm_execpath || process.argv[1]?.includes('npx')) {\n return {\n name: 'MCP Client',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n }\n\n // Default\n return {\n name: 'MCP Client',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n}","import { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { extname, relative, resolve, isAbsolute } from 'path';\nimport { getPrompt, getSystemPrompt } from '../ai/prompts.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { triageIssues, formatTriageTable, formatCloudRecommendation } from './fix-triage.js';\nimport { loadAutonomyConfig } from '../utils/autonomy-config.js';\nimport type { Issue } from '../types/index.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\nexport interface 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 /** Optional triage metadata (from scan agents) */\n severity?: Issue['severity'];\n effort?: Issue['effort'];\n autoFixable?: boolean;\n cwe?: string;\n owasp?: string;\n category?: string;\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, action } = args || {};\n\n // Mode 0: Route — show triage decisions without applying fixes\n if (action === 'route') {\n return this.routeIssues(issueIds);\n }\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 routeIssues(issueIds?: string[]) {\n const pending = getPendingFixes();\n if (pending.length === 0) {\n return {\n content: [{ type: 'text', text: 'No pending issues. Run `trie_scan` first to detect issues.' }],\n };\n }\n\n const issues: Issue[] = pending.map(p => ({\n id: p.id,\n severity: p.severity ?? 'moderate',\n effort: p.effort,\n issue: p.issue,\n fix: p.suggestedFix,\n file: p.file,\n line: p.line,\n confidence: p.confidence,\n autoFixable: p.autoFixable ?? false,\n agent: 'trie_scan',\n cwe: p.cwe,\n owasp: p.owasp,\n category: p.category,\n }));\n\n const filtered = issueIds && issueIds.length > 0\n ? issues.filter(i => issueIds.includes(i.id))\n : issues;\n\n const workDir = getWorkingDirectory(undefined, true);\n const config = await loadAutonomyConfig(workDir);\n const { results } = triageIssues(filtered, undefined, undefined, config);\n const table = formatTriageTable(results, filtered);\n\n return { content: [{ type: 'text', text: `\\n${table}\\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 // Append cloud recommendation for remaining high-score issues\n output += await this.appendCloudRecommendation(issueIds);\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 async appendCloudRecommendation(handledIds: string[]): Promise<string> {\n try {\n const pending = getPendingFixes();\n const remaining = pending.filter(p => !handledIds.includes(p.id) || pendingFixes.get(p.id)?.status === 'pending');\n if (remaining.length === 0) return '';\n\n const issues: Issue[] = remaining.map(p => ({\n id: p.id,\n severity: 'moderate' as const,\n issue: p.issue,\n fix: p.suggestedFix,\n file: p.file,\n line: p.line,\n confidence: p.confidence,\n autoFixable: false,\n agent: 'trie_scan',\n }));\n\n const workDir = getWorkingDirectory(undefined, true);\n const config = await loadAutonomyConfig(workDir);\n const { results } = triageIssues(issues, undefined, undefined, config);\n const footer = formatCloudRecommendation(results, issues);\n return footer ? `\\n${footer}\\n` : '';\n } catch {\n return '';\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 * Fix Triage Engine\n *\n * Scores each issue across four signal groups (issue shape, code context,\n * occurrence history, user configuration) and recommends one of three\n * fix strategies: inline-auto, local-ai, or cloud-agent.\n *\n * Used by both `trie_fix` and `trie_cloud_fix`.\n */\n\nimport type { Issue, CodeContext } from '../types/index.js';\nimport type { AutonomyConfig, IssueOccurrence } from '../types/autonomy.js';\n\nexport interface PipelineContext {\n hasLinkedPR: boolean;\n prState?: 'open' | 'closed' | 'merged' | 'draft';\n hasLinkedTicket: boolean;\n ticketStatus?: string;\n ticketPriority?: string;\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type FixStrategy = 'inline-auto' | 'local-ai' | 'cloud-agent';\n\nexport interface TriageResult {\n strategy: FixStrategy;\n score: number;\n confidence: number;\n reasons: string[];\n fallback: 'local-ai';\n}\n\nexport interface TriageSummary {\n inlineAuto: Issue[];\n localAi: Issue[];\n cloudAgent: Issue[];\n cloudAgentScore: number;\n}\n\n// ============================================================================\n// Signal scoring constants\n// ============================================================================\n\nconst EFFORT_SCORES: Record<string, number> = {\n trivial: -6,\n easy: -3,\n medium: 0,\n hard: 4,\n};\n\nconst SEVERITY_SCORES: Record<string, number> = {\n critical: 4,\n serious: 2,\n moderate: -1,\n low: -3,\n};\n\n// ============================================================================\n// Core triage function\n// ============================================================================\n\nexport function triageIssue(\n issue: Issue,\n context?: CodeContext,\n occurrence?: IssueOccurrence,\n config?: AutonomyConfig,\n pipeline?: PipelineContext,\n): TriageResult {\n const reasons: string[] = [];\n\n // --- Hard overrides (checked before scoring) ---\n if (config?.level === 'passive') {\n return {\n strategy: 'local-ai',\n score: 0,\n confidence: 1,\n reasons: ['Autonomy level is passive — cloud dispatch disabled'],\n fallback: 'local-ai',\n };\n }\n\n if (config?.cloudAgentEnabled === false) {\n return {\n strategy: 'local-ai',\n score: 0,\n confidence: 1,\n reasons: ['Cloud agent not enabled (run trie_cloud_fix action:configure)'],\n fallback: 'local-ai',\n };\n }\n\n let score = 0;\n\n // --- Signal Group 1: Issue Shape ---\n const effort = issue.effort ?? 'medium';\n const effortScore = EFFORT_SCORES[effort] ?? 0;\n if (effortScore !== 0) {\n score += effortScore;\n reasons.push(`effort:${effort}`);\n }\n\n const severityScore = SEVERITY_SCORES[issue.severity] ?? 0;\n if (severityScore !== 0) {\n score += severityScore;\n reasons.push(`severity:${issue.severity}`);\n }\n\n if (issue.autoFixable) {\n score -= 2;\n reasons.push('autoFixable');\n }\n\n if (issue.confidence < 0.7) {\n score -= 2;\n reasons.push(`low confidence (${(issue.confidence * 100).toFixed(0)}%)`);\n }\n\n if (issue.cwe) {\n score += 3;\n reasons.push(`cwe:${issue.cwe}`);\n }\n\n if (issue.owasp) {\n score += 2;\n reasons.push(`owasp:${issue.owasp}`);\n }\n\n if (issue.category === 'security') {\n score += 2;\n reasons.push('category:security');\n }\n\n // --- Signal Group 2: Context ---\n if (context) {\n if (context.hasTests) {\n score += 1;\n reasons.push('has tests');\n } else {\n score -= 2;\n reasons.push('no tests');\n }\n\n if (context.complexity === 'high') {\n score += 1;\n reasons.push('high complexity');\n }\n\n if (context.touchesAuth || context.touchesCrypto || context.touchesPayments) {\n score += 2;\n reasons.push('touches auth/crypto/payments');\n }\n\n if (context.touchesDatabase) {\n score += 1;\n reasons.push('touches database');\n }\n }\n\n // --- Signal Group 3: Occurrence History ---\n if (occurrence) {\n if (occurrence.count >= 5) {\n score += 3;\n reasons.push(`${occurrence.count}× seen`);\n } else if (occurrence.count >= 3) {\n score += 1;\n reasons.push(`${occurrence.count}× seen`);\n }\n\n if (occurrence.escalationLevel === 'block') {\n score += 4;\n reasons.push('escalation:block');\n } else if (occurrence.escalationLevel === 'escalate') {\n score += 2;\n reasons.push('escalation:escalate');\n }\n }\n\n // --- Signal Group 4: User Configuration ---\n if (config?.level === 'aggressive') {\n score -= 1;\n reasons.push('aggressive mode (−1 threshold)');\n }\n\n // --- Signal Group 5: Pipeline Context ---\n if (pipeline) {\n if (pipeline.hasLinkedPR && pipeline.prState === 'open') {\n score -= 2;\n reasons.push('has open PR');\n }\n\n if (pipeline.hasLinkedTicket && pipeline.ticketStatus?.toLowerCase().includes('started')) {\n score -= 1;\n reasons.push('ticket in active sprint');\n }\n\n if (pipeline.hasLinkedTicket && pipeline.ticketPriority === 'urgent') {\n score += 1;\n reasons.push('ticket:urgent');\n }\n\n if (!pipeline.hasLinkedTicket && !pipeline.hasLinkedPR && issue.severity === 'critical') {\n score += 2;\n reasons.push('critical, no ticket/PR (falling through cracks)');\n }\n }\n\n // --- Score → Strategy ---\n let strategy: FixStrategy;\n if (score < 0 && issue.autoFixable) {\n strategy = 'inline-auto';\n } else if (score < 4) {\n strategy = 'local-ai';\n } else {\n strategy = 'cloud-agent';\n }\n\n const confidence = Math.min(1, Math.abs(score) / 8);\n\n return { strategy, score, confidence, reasons, fallback: 'local-ai' };\n}\n\n// ============================================================================\n// Batch triage\n// ============================================================================\n\nexport function triageIssues(\n issues: Issue[],\n context?: CodeContext,\n occurrences?: Map<string, IssueOccurrence>,\n config?: AutonomyConfig,\n pipelineContexts?: Map<string, PipelineContext>,\n): { results: Map<string, TriageResult>; summary: TriageSummary } {\n const results = new Map<string, TriageResult>();\n const summary: TriageSummary = {\n inlineAuto: [],\n localAi: [],\n cloudAgent: [],\n cloudAgentScore: 0,\n };\n\n for (const issue of issues) {\n const occurrence = occurrences?.get(issue.id);\n const pipeline = pipelineContexts?.get(issue.id);\n const result = triageIssue(issue, context, occurrence, config, pipeline);\n results.set(issue.id, result);\n\n switch (result.strategy) {\n case 'inline-auto':\n summary.inlineAuto.push(issue);\n break;\n case 'local-ai':\n summary.localAi.push(issue);\n break;\n case 'cloud-agent':\n summary.cloudAgent.push(issue);\n summary.cloudAgentScore += result.score;\n break;\n }\n }\n\n return { results, summary };\n}\n\n// ============================================================================\n// Formatted output\n// ============================================================================\n\nexport function formatTriageTable(\n results: Map<string, TriageResult>,\n issues: Issue[],\n): string {\n const LINE = '\\u2500'.repeat(68);\n const lines: string[] = [];\n\n lines.push('FIX ROUTING PLAN');\n lines.push(LINE);\n lines.push(\n padEnd('Issue', 32) +\n padEnd('Strategy', 14) +\n padEnd('Score', 7) +\n 'Reason',\n );\n\n for (const issue of issues) {\n const r = results.get(issue.id);\n if (!r) continue;\n const loc = `${shortPath(issue.file)}:${issue.line ?? '?'}`;\n const scoreStr = r.score >= 0 ? `+${r.score}` : String(r.score);\n lines.push(\n padEnd(loc, 32) +\n padEnd(r.strategy, 14) +\n padEnd(scoreStr, 7) +\n r.reasons.join(', '),\n );\n }\n\n lines.push(LINE);\n\n const counts: string[] = [];\n const cloud = issues.filter(i => results.get(i.id)?.strategy === 'cloud-agent');\n const local = issues.filter(i => results.get(i.id)?.strategy === 'local-ai');\n const auto = issues.filter(i => results.get(i.id)?.strategy === 'inline-auto');\n\n if (cloud.length) counts.push(`${cloud.length} for cloud agent`);\n if (local.length) counts.push(`${local.length} for local AI`);\n if (auto.length) counts.push(`${auto.length} auto-fixable`);\n lines.push(counts.join(', '));\n\n if (cloud.length > 0) {\n const ids = cloud.map(i => `\"${i.id}\"`).join(',');\n lines.push('');\n lines.push(`To dispatch cloud issues: trie_cloud_fix action:dispatch issueIds:[${ids}]`);\n }\n if (local.length > 0) {\n const ids = local.map(i => `\"${i.id}\"`).join(',');\n lines.push(`To fix local issues: trie_fix issueIds:[${ids}]`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Build the cloud recommendation footer appended after trie_fix completes,\n * when skipped/pending issues score >= 4.\n */\nexport function formatCloudRecommendation(\n results: Map<string, TriageResult>,\n issues: Issue[],\n): string | null {\n const cloud = issues.filter(i => {\n const r = results.get(i.id);\n return r && r.score >= 4;\n });\n\n if (cloud.length === 0) return null;\n\n const LINE = '\\u2500'.repeat(65);\n const lines: string[] = [];\n\n lines.push(LINE);\n lines.push(\n `${cloud.length} issue${cloud.length > 1 ? 's' : ''} qualify for cloud agent verification (test-verified fix + PR):`,\n );\n\n for (const issue of cloud) {\n const r = results.get(issue.id)!;\n const loc = `${shortPath(issue.file)}:${issue.line ?? '?'}`;\n const scoreStr = r.score >= 0 ? `+${r.score}` : String(r.score);\n lines.push(` \\u2022 ${padEnd(loc, 30)} \\u2014 score ${scoreStr} (${r.reasons.join(', ')})`);\n }\n\n const ids = cloud.map(i => `\"${i.id}\"`).join(',');\n lines.push('');\n lines.push(`Run: trie_cloud_fix action:dispatch issueIds:[${ids}]`);\n lines.push(LINE);\n\n return lines.join('\\n');\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction shortPath(file: string): string {\n const parts = file.split('/');\n return parts.length > 2 ? parts.slice(-2).join('/') : file;\n}\n\nfunction padEnd(str: string, len: number): string {\n if (str.length >= len) return str.slice(0, len);\n return str + ' '.repeat(len - str.length);\n}\n","/**\n * Cloud Fix Tool — `trie_cloud_fix`\n *\n * Dispatches issues to Cursor cloud agents for verified, test-passing fixes.\n * Modes: configure, dispatch, status, artifacts, cancel.\n *\n * Job state persists in `.trie/cloud-jobs.json`.\n */\n\nimport { readFile, writeFile, mkdir } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { execSync } from 'child_process';\n\nimport type { Issue } from '../types/index.js';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport { loadAutonomyConfig, saveAutonomyConfig } from '../utils/autonomy-config.js';\nimport { CursorCloudAgentClient } from '../integrations/cursor-cloud-agent.js';\nimport { triageIssues, formatTriageTable } from './fix-triage.js';\nimport { getPendingFixes } from './fix.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\ninterface CloudJobRecord {\n issueId: string;\n jobId: string;\n status: 'dispatched' | 'running' | 'verified' | 'failed';\n score: number;\n strategy: 'cloud-agent';\n dispatchedAt: string;\n artifactUrls: string[];\n prUrl: string | null;\n}\n\ninterface CloudJobsStore {\n jobs: Record<string, CloudJobRecord>;\n}\n\n// ============================================================================\n// Tool\n// ============================================================================\n\nexport class TrieCloudFixTool {\n async execute(args: any) {\n const { action = 'status' } = args || {};\n\n switch (action) {\n case 'configure':\n return this.configure(args);\n case 'dispatch':\n return this.dispatch(args);\n case 'status':\n return this.status();\n case 'artifacts':\n return this.artifacts(args);\n case 'cancel':\n return this.cancel(args);\n default:\n return this.text(`Unknown action \"${action}\". Use: configure | dispatch | status | artifacts | cancel`);\n }\n }\n\n // --------------------------------------------------------------------------\n // configure\n // --------------------------------------------------------------------------\n\n private async configure(args: any) {\n const apiKey: string | undefined = args?.apiKey || process.env.CURSOR_API_KEY;\n if (!apiKey) {\n return this.text(\n 'Missing API key.\\n\\n' +\n 'Usage: trie_cloud_fix action:configure apiKey:\"key-...\"\\n' +\n 'Or set: export CURSOR_API_KEY=\"key-...\"',\n );\n }\n\n const workDir = getWorkingDirectory(undefined, true);\n await saveAutonomyConfig(workDir, { cloudAgentEnabled: true, cursorApiKey: apiKey });\n\n return this.text('Cursor API key saved. Cloud agent dispatch enabled.');\n }\n\n // --------------------------------------------------------------------------\n // dispatch\n // --------------------------------------------------------------------------\n\n private async dispatch(args: any) {\n const workDir = getWorkingDirectory(undefined, true);\n\n const apiKey = await this.resolveApiKey(workDir);\n if (!apiKey) return this.setupGuard();\n\n const config = await loadAutonomyConfig(workDir);\n const allIssues = this.resolveIssues(args?.issueIds);\n if (allIssues.length === 0) {\n return this.text('No issues to dispatch. Run trie_scan first, then trie_fix action:route.');\n }\n\n const { results, summary } = triageIssues(allIssues, undefined, undefined, config);\n\n const lines: string[] = [];\n\n // Print routing table for transparency\n lines.push(formatTriageTable(results, allIssues));\n lines.push('');\n\n // Skip non-cloud issues with a reason\n for (const issue of allIssues) {\n const r = results.get(issue.id);\n if (r && r.strategy !== 'cloud-agent') {\n lines.push(`Skipped ${issue.id}: routed to ${r.strategy} (score ${r.score >= 0 ? '+' : ''}${r.score} — ${r.reasons.join(', ')})`);\n }\n }\n\n if (summary.cloudAgent.length === 0) {\n lines.push('\\nNo issues qualify for cloud dispatch. Use trie_fix for local fixes.');\n return this.text(lines.join('\\n'));\n }\n\n // Dispatch\n const client = new CursorCloudAgentClient(apiKey);\n const repoUrl = this.getRepoUrl(workDir);\n const branch = this.getBranch(workDir);\n const store = await this.loadJobs(workDir);\n\n lines.push('\\nDISPATCHED');\n\n for (const issue of summary.cloudAgent) {\n const triageResult = results.get(issue.id)!;\n try {\n const job = await client.dispatch(issue, triageResult, repoUrl, branch);\n\n store.jobs[issue.id] = {\n issueId: issue.id,\n jobId: job.jobId,\n status: 'dispatched',\n score: triageResult.score,\n strategy: 'cloud-agent',\n dispatchedAt: job.dispatchedAt,\n artifactUrls: [],\n prUrl: null,\n };\n\n lines.push(` ${issue.id} ${shortPath(issue.file)}:${issue.line ?? '?'} job:${job.jobId} (score +${triageResult.score})`);\n } catch (err: any) {\n lines.push(` ${issue.id} FAILED: ${err.message}`);\n }\n }\n\n await this.saveJobs(workDir, store);\n\n lines.push('');\n lines.push('Cloud agents are running in isolated VMs. Check back with:');\n lines.push('trie_cloud_fix action:status');\n\n return this.text(lines.join('\\n'));\n }\n\n // --------------------------------------------------------------------------\n // status\n // --------------------------------------------------------------------------\n\n private async status() {\n const workDir = getWorkingDirectory(undefined, true);\n const apiKey = await this.resolveApiKey(workDir);\n if (!apiKey) return this.setupGuard();\n\n const store = await this.loadJobs(workDir);\n const entries = Object.values(store.jobs);\n\n if (entries.length === 0) {\n return this.text('No cloud jobs. Dispatch with: trie_cloud_fix action:dispatch');\n }\n\n const client = new CursorCloudAgentClient(apiKey);\n const LINE = '\\u2500'.repeat(68);\n const lines: string[] = ['JOB STATUS', LINE];\n lines.push(padEnd('Issue', 32) + padEnd('Status', 12) + padEnd('PR', 28) + 'Age');\n\n for (const job of entries) {\n if (job.status === 'dispatched' || job.status === 'running') {\n try {\n const poll = await client.poll(job.jobId);\n if (poll.status === 'completed' && poll.prUrl) {\n job.status = 'verified';\n job.prUrl = poll.prUrl;\n } else if (poll.status === 'running') {\n job.status = 'running';\n } else if (poll.status === 'failed') {\n job.status = 'failed';\n }\n if (poll.artifactUrls.length) {\n job.artifactUrls = poll.artifactUrls;\n }\n } catch {\n // poll failure is non-fatal; show last known status\n }\n }\n\n const age = formatAge(job.dispatchedAt);\n const pr = job.prUrl ?? '\\u2014';\n lines.push(padEnd(job.issueId, 32) + padEnd(job.status, 12) + padEnd(pr, 28) + age);\n }\n\n lines.push(LINE);\n await this.saveJobs(workDir, store);\n\n return this.text(lines.join('\\n'));\n }\n\n // --------------------------------------------------------------------------\n // artifacts\n // --------------------------------------------------------------------------\n\n private async artifacts(args: any) {\n const workDir = getWorkingDirectory(undefined, true);\n const apiKey = await this.resolveApiKey(workDir);\n if (!apiKey) return this.setupGuard();\n\n const store = await this.loadJobs(workDir);\n const jobId: string | undefined = args?.jobId;\n\n const targets = jobId\n ? Object.values(store.jobs).filter(j => j.jobId === jobId)\n : Object.values(store.jobs).filter(j => j.status === 'verified');\n\n if (targets.length === 0) {\n return this.text(jobId ? `No job found with id ${jobId}` : 'No completed jobs with artifacts.');\n }\n\n const client = new CursorCloudAgentClient(apiKey);\n const lines: string[] = [];\n\n for (const job of targets) {\n try {\n const artifacts = await client.getArtifacts(job.jobId);\n job.artifactUrls = artifacts;\n } catch {\n // use cached artifacts\n }\n\n lines.push(`Issue: ${job.issueId}`);\n lines.push(`PR: ${job.prUrl ?? 'N/A'}`);\n for (const url of job.artifactUrls) {\n const ext = url.split('.').pop();\n const label = ext === 'mp4' || ext === 'webm' ? 'Video' : 'Screenshot';\n lines.push(`${label}: ${url}`);\n }\n if (job.status === 'verified') {\n lines.push('Agent verified: all tests pass with this fix applied.');\n }\n lines.push('');\n }\n\n await this.saveJobs(workDir, store);\n return this.text(lines.join('\\n'));\n }\n\n // --------------------------------------------------------------------------\n // cancel\n // --------------------------------------------------------------------------\n\n private async cancel(args: any) {\n const workDir = getWorkingDirectory(undefined, true);\n const apiKey = await this.resolveApiKey(workDir);\n if (!apiKey) return this.setupGuard();\n\n const jobId: string | undefined = args?.jobId;\n if (!jobId) {\n return this.text('Provide jobId to cancel. Example: trie_cloud_fix action:cancel jobId:\"cursor-task-xyz\"');\n }\n\n const store = await this.loadJobs(workDir);\n const entry = Object.values(store.jobs).find(j => j.jobId === jobId);\n if (!entry) {\n return this.text(`Job ${jobId} not found in cloud-jobs.json.`);\n }\n\n const client = new CursorCloudAgentClient(apiKey);\n try {\n await client.cancelJob(jobId);\n } catch (err: any) {\n return this.text(`Cancel failed: ${err.message}`);\n }\n\n delete store.jobs[entry.issueId];\n await this.saveJobs(workDir, store);\n\n return this.text(`Job ${jobId} cancelled and removed.`);\n }\n\n // --------------------------------------------------------------------------\n // Helpers\n // --------------------------------------------------------------------------\n\n private async resolveApiKey(workDir: string): Promise<string | null> {\n if (process.env.CURSOR_API_KEY) return process.env.CURSOR_API_KEY;\n const config = await loadAutonomyConfig(workDir);\n return config.cursorApiKey ?? null;\n }\n\n private setupGuard() {\n return this.text(\n 'Cloud Agent dispatch requires a Cursor API key.\\n\\n' +\n 'Get your key at: cursor.com/settings \\u2192 API Keys\\n' +\n 'Then run: trie_cloud_fix action:configure apiKey:\"key-...\"\\n\\n' +\n 'Or set the environment variable: export CURSOR_API_KEY=\"key-...\"',\n );\n }\n\n private resolveIssues(issueIds?: string[]): Issue[] {\n const pending = getPendingFixes();\n const issues: Issue[] = pending.map(p => ({\n id: p.id,\n severity: p.severity ?? 'moderate',\n effort: p.effort,\n issue: p.issue,\n fix: p.suggestedFix,\n file: p.file,\n line: p.line,\n confidence: p.confidence,\n autoFixable: p.autoFixable ?? false,\n agent: 'trie_scan',\n cwe: p.cwe,\n owasp: p.owasp,\n category: p.category,\n }));\n\n if (issueIds && issueIds.length > 0) {\n return issues.filter(i => issueIds.includes(i.id));\n }\n return issues;\n }\n\n private getRepoUrl(workDir: string): string {\n try {\n return execSync('git remote get-url origin', { cwd: workDir, encoding: 'utf-8' }).trim();\n } catch {\n return 'unknown';\n }\n }\n\n private getBranch(workDir: string): string {\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', { cwd: workDir, encoding: 'utf-8' }).trim();\n } catch {\n return 'main';\n }\n }\n\n private async loadJobs(workDir: string): Promise<CloudJobsStore> {\n const path = join(getTrieDirectory(workDir), 'cloud-jobs.json');\n try {\n if (existsSync(path)) {\n const raw = await readFile(path, 'utf-8');\n return JSON.parse(raw) as CloudJobsStore;\n }\n } catch {\n // corrupt file — start fresh\n }\n return { jobs: {} };\n }\n\n private async saveJobs(workDir: string, store: CloudJobsStore): Promise<void> {\n const trieDir = getTrieDirectory(workDir);\n if (!existsSync(trieDir)) await mkdir(trieDir, { recursive: true });\n const path = join(trieDir, 'cloud-jobs.json');\n await writeFile(path, JSON.stringify(store, null, 2));\n }\n\n private text(msg: string) {\n return { content: [{ type: 'text' as const, text: msg }] };\n }\n}\n\n// ============================================================================\n// Formatting helpers\n// ============================================================================\n\nfunction formatAge(isoDate: string): string {\n const ms = Date.now() - new Date(isoDate).getTime();\n const mins = Math.floor(ms / 60_000);\n if (mins < 60) return `${mins}m`;\n const hrs = Math.floor(mins / 60);\n if (hrs < 24) return `${hrs}h ${mins % 60}m`;\n return `${Math.floor(hrs / 24)}d`;\n}\n\nfunction shortPath(file: string): string {\n const parts = file.split('/');\n return parts.length > 2 ? parts.slice(-2).join('/') : file;\n}\n\nfunction padEnd(str: string, len: number): string {\n if (str.length >= len) return str.slice(0, len);\n return str + ' '.repeat(len - str.length);\n}\n","/**\n * Cursor Cloud Agent REST Client\n *\n * Thin wrapper around the Cursor Cloud Agent API.\n * Uses native `fetch` — no new npm dependencies.\n */\n\nimport type { Issue } from '../types/index.js';\nimport type { TriageResult } from '../tools/fix-triage.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface CloudAgentJob {\n jobId: string;\n status: 'dispatched' | 'running' | 'verified' | 'failed';\n prUrl?: string;\n artifactUrls: string[];\n dispatchedAt: string;\n verifiedAt?: string;\n}\n\nexport interface CloudAgentStatus {\n status: 'pending' | 'running' | 'completed' | 'failed';\n prUrl?: string | undefined;\n artifactUrls: string[];\n}\n\n// ============================================================================\n// Client\n// ============================================================================\n\nconst BASE_URL = 'https://api.cursor.com/v1';\n\nexport class CursorCloudAgentClient {\n private apiKey: string;\n\n constructor(apiKey: string) {\n this.apiKey = apiKey;\n }\n\n /**\n * Dispatch an issue to a cloud agent for fixing.\n */\n async dispatch(\n issue: Issue,\n triageResult: TriageResult,\n repoUrl: string,\n branch: string,\n ): Promise<CloudAgentJob> {\n const prompt = this.buildPrompt(issue, triageResult);\n\n const body = {\n prompt,\n repo: repoUrl,\n branch,\n metadata: {\n issueId: issue.id,\n file: issue.file,\n line: issue.line,\n severity: issue.severity,\n agent: issue.agent,\n },\n };\n\n const res = await this.request('POST', '/agents/tasks', body);\n\n return {\n jobId: res.id ?? res.taskId ?? res.jobId,\n status: 'dispatched',\n artifactUrls: [],\n dispatchedAt: new Date().toISOString(),\n };\n }\n\n /**\n * Poll job status.\n */\n async poll(jobId: string): Promise<CloudAgentStatus> {\n const res = await this.request('GET', `/agents/tasks/${jobId}`);\n\n const status = mapStatus(res.status);\n const prUrl = extractPrUrl(res);\n const artifactUrls = this.extractArtifacts(res);\n\n return { status, prUrl, artifactUrls };\n }\n\n /**\n * Get artifact URLs for a completed job.\n */\n async getArtifacts(jobId: string): Promise<string[]> {\n const res = await this.request('GET', `/agents/tasks/${jobId}`);\n return this.extractArtifacts(res);\n }\n\n /**\n * Cancel a running job.\n */\n async cancelJob(jobId: string): Promise<void> {\n await this.request('DELETE', `/agents/tasks/${jobId}`);\n }\n\n // --------------------------------------------------------------------------\n // Internal\n // --------------------------------------------------------------------------\n\n private buildPrompt(issue: Issue, triageResult: TriageResult): string {\n const parts: string[] = [\n 'You are fixing a verified issue in the codebase.',\n '',\n `Issue: ${issue.issue}`,\n `File: ${issue.file}${issue.line ? `:${issue.line}` : ''}`,\n `Severity: ${issue.severity} | Effort: ${issue.effort ?? 'medium'}`,\n `Agent that found it: ${issue.agent}`,\n `Suggested fix: ${issue.fix}`,\n ];\n\n if (issue.cwe) parts.push(`CWE: ${issue.cwe}`);\n if (issue.owasp) parts.push(`OWASP: ${issue.owasp}`);\n\n parts.push(`Triage confidence: ${triageResult.confidence.toFixed(2)}`);\n parts.push(`Why cloud agent: ${triageResult.reasons.join(', ')}`);\n parts.push('');\n parts.push('Steps:');\n parts.push(`1. Apply the minimal fix described above to ${issue.file}`);\n parts.push('2. Run the existing test suite (detect test runner from package.json scripts)');\n parts.push('3. Screenshot the passing test output — this is the verification artifact');\n parts.push('4. If tests fail, iterate on the fix until they pass (max 3 attempts)');\n parts.push('5. Open a PR with only this single change — do not bundle other fixes');\n parts.push('6. Include the screenshot in the PR description as evidence');\n\n return parts.join('\\n');\n }\n\n private async request(method: string, path: string, body?: unknown): Promise<any> {\n const url = `${BASE_URL}${path}`;\n const headers: Record<string, string> = {\n 'Authorization': `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n };\n\n const init: RequestInit = { method, headers };\n if (body) init.body = JSON.stringify(body);\n\n const res = await fetch(url, init);\n\n if (res.status === 401) {\n throw new Error(\n 'Cursor API key is invalid or expired.\\n' +\n 'Update it: trie_cloud_fix action:configure apiKey:\"key-...\"',\n );\n }\n if (res.status === 404) {\n throw new Error(`Job not found: ${path}`);\n }\n if (res.status >= 500) {\n throw new Error(\n `Cursor API returned ${res.status}. The service may be temporarily unavailable — retry in a few minutes.`,\n );\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '');\n throw new Error(`Cursor API error ${res.status}: ${text}`);\n }\n\n return res.json();\n }\n\n private extractArtifacts(res: any): string[] {\n const urls: string[] = [];\n\n if (Array.isArray(res.messages)) {\n for (const msg of res.messages) {\n if (typeof msg.content === 'string') {\n const matches = msg.content.match(/https:\\/\\/[^\\s)]+\\.(png|jpg|mp4|webm)/g);\n if (matches) urls.push(...matches);\n }\n }\n }\n\n if (Array.isArray(res.artifacts)) {\n for (const a of res.artifacts) {\n if (a.url) urls.push(a.url);\n }\n }\n\n return [...new Set(urls)];\n }\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction mapStatus(raw: string | undefined): CloudAgentStatus['status'] {\n switch (raw) {\n case 'pending':\n case 'queued':\n return 'pending';\n case 'running':\n case 'in_progress':\n return 'running';\n case 'completed':\n case 'succeeded':\n case 'verified':\n return 'completed';\n default:\n return 'failed';\n }\n}\n\nfunction extractPrUrl(res: any): string | undefined {\n if (typeof res.prUrl === 'string') return res.prUrl;\n if (typeof res.pr_url === 'string') return res.pr_url;\n if (typeof res.pullRequestUrl === 'string') return res.pullRequestUrl;\n\n if (Array.isArray(res.messages)) {\n for (const msg of res.messages) {\n if (typeof msg.content === 'string') {\n const match = msg.content.match(/https:\\/\\/github\\.com\\/[^\\s)]+\\/pull\\/\\d+/);\n if (match) return match[0];\n }\n }\n }\n\n return undefined;\n}\n","import { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { extname, relative, resolve, isAbsolute, dirname, basename, join } from 'path';\nimport { getPrompt, getSystemPrompt } from '../ai/prompts.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\n/**\n * Test Tool - AI-powered test generation and coverage analysis\n * \n * This tool can:\n * - Generate comprehensive tests for code\n * - Analyze test coverage gaps\n * - Suggest test improvements\n */\n\ninterface TestableUnit {\n name: string;\n type: 'function' | 'class' | 'method' | 'component';\n startLine: number;\n endLine: number;\n signature: string;\n complexity: number;\n dependencies: string[];\n}\n\nexport class TrieTestTool {\n async execute(args: any) {\n const { action, files, framework, style = 'unit' } = args || {};\n\n if (!action || !files || files.length === 0) {\n return {\n content: [{\n type: 'text',\n text: this.getHelpText()\n }]\n };\n }\n\n switch (action) {\n case 'generate':\n return this.generateTests(files, framework, style);\n case 'coverage':\n return this.analyzeCoverage(files);\n case 'suggest':\n return this.suggestTests(files);\n case 'run':\n return this.runTestsInfo(files);\n default:\n return {\n content: [{\n type: 'text',\n text: `Unknown action: ${action}`\n }]\n };\n }\n }\n\n private async generateTests(files: string[], framework?: string, style?: string) {\n const detectedFramework = framework || await this.detectTestFramework();\n \n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🧪 TEST GENERATION\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## ⚙️ Configuration\\n\\n`;\n output += `- **Framework:** ${detectedFramework}\\n`;\n output += `- **Style:** ${style}\\n`;\n output += `- **Files:** ${files.length}\\n\\n`;\n\n const workDir = getWorkingDirectory(undefined, true);\n const allUnits: { file: string; units: TestableUnit[] }[] = [];\n\n for (const file of files) {\n const resolvedPath = isAbsolute(file) ? file : resolve(workDir, file);\n \n if (!existsSync(resolvedPath)) {\n output += `[!] File not found: ${file}\\n`;\n continue;\n }\n\n const code = await readFile(resolvedPath, 'utf-8');\n const language = this.detectLanguage(resolvedPath);\n const relativePath = relative(workDir, resolvedPath);\n const units = this.extractTestableUnits(code, language);\n\n allUnits.push({ file: relativePath, units });\n\n output += `### 📄 ${relativePath}\\n\\n`;\n output += `Found **${units.length}** testable units:\\n\\n`;\n\n for (const unit of units) {\n const complexityIcon = unit.complexity > 10 ? '🔴' : unit.complexity > 5 ? '🟡' : '🟢';\n output += `- ${complexityIcon} \\`${unit.name}\\` (${unit.type}, complexity: ${unit.complexity})\\n`;\n if (unit.dependencies.length > 0) {\n output += ` - Dependencies: ${unit.dependencies.join(', ')}\\n`;\n }\n }\n output += '\\n';\n }\n\n // Generate the test file content\n output += `${'─'.repeat(60)}\\n`;\n output += `## 🧠 Test Generation Request\\n\\n`;\n \n const systemPrompt = getSystemPrompt('test');\n output += `**Role:** ${systemPrompt.split('\\n')[0]}\\n\\n`;\n\n for (const { file, units } of allUnits) {\n if (units.length === 0) continue;\n\n const code = await readFile(resolve(workDir, file), 'utf-8');\n const language = this.detectLanguage(file);\n\n const prompt = getPrompt('test', 'generate', {\n code,\n language,\n filePath: file,\n framework: detectedFramework,\n });\n\n output += `### Tests for ${file}\\n\\n`;\n output += prompt;\n output += '\\n\\n';\n }\n\n output += `${'─'.repeat(60)}\\n`;\n output += `\\n## 📝 Expected Test Output\\n\\n`;\n output += `Generate complete test files with:\\n`;\n output += `- All imports and setup\\n`;\n output += `- Tests for each function/method\\n`;\n output += `- Edge cases and error scenarios\\n`;\n output += `- Mock requirements clearly stated\\n`;\n output += `- Ready to copy and run\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async analyzeCoverage(files: string[]) {\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `📊 COVERAGE ANALYSIS\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n const workDir = getWorkingDirectory(undefined, true);\n\n for (const file of files) {\n const resolvedPath = isAbsolute(file) ? file : resolve(workDir, file);\n \n if (!existsSync(resolvedPath)) {\n output += `[!] File not found: ${file}\\n`;\n continue;\n }\n\n const code = await readFile(resolvedPath, 'utf-8');\n const language = this.detectLanguage(resolvedPath);\n const relativePath = relative(workDir, resolvedPath);\n const units = this.extractTestableUnits(code, language);\n\n // Try to find existing tests\n const testFile = await this.findTestFile(resolvedPath);\n let testCode = '';\n let testedUnits: string[] = [];\n\n if (testFile) {\n testCode = await readFile(testFile, 'utf-8');\n testedUnits = this.findTestedUnits(testCode, units.map(u => u.name));\n }\n\n const coverage = units.length > 0 \n ? Math.round((testedUnits.length / units.length) * 100)\n : 0;\n\n const coverageIcon = coverage >= 80 ? '🟢' : coverage >= 50 ? '🟡' : '🔴';\n\n output += `### 📄 ${relativePath}\\n\\n`;\n output += `**Coverage:** ${coverageIcon} ${coverage}% (${testedUnits.length}/${units.length} units)\\n`;\n if (testFile) {\n output += `**Test file:** \\`${relative(workDir, testFile)}\\`\\n`;\n } else {\n output += `**Test file:** ❌ Not found\\n`;\n }\n output += '\\n';\n\n // Show what's tested and what's not\n const untested = units.filter(u => !testedUnits.includes(u.name));\n \n if (untested.length > 0) {\n output += `**Missing Tests:**\\n`;\n for (const unit of untested) {\n const priority = unit.complexity > 5 ? '🔴 HIGH' : '🟡 MEDIUM';\n output += `- ${priority}: \\`${unit.name}\\` (${unit.type})\\n`;\n }\n output += '\\n';\n }\n\n if (testedUnits.length > 0) {\n output += `**Tested:**\\n`;\n for (const name of testedUnits) {\n output += `- ✅ \\`${name}\\`\\n`;\n }\n output += '\\n';\n }\n }\n\n output += `${'─'.repeat(60)}\\n`;\n output += `## 📋 Recommendations\\n\\n`;\n output += `To improve coverage:\\n`;\n output += `1. Focus on high-complexity untested functions first\\n`;\n output += `2. Add edge case tests for existing coverage\\n`;\n output += `3. Consider integration tests for complex interactions\\n`;\n output += `\\nRun \\`trie_test action:generate files:[\"file.ts\"]\\` to generate missing tests.\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async suggestTests(files: string[]) {\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `💡 TEST SUGGESTIONS\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n const workDir = getWorkingDirectory(undefined, true);\n\n for (const file of files) {\n const resolvedPath = isAbsolute(file) ? file : resolve(workDir, file);\n \n if (!existsSync(resolvedPath)) {\n output += `[!] File not found: ${file}\\n`;\n continue;\n }\n\n const code = await readFile(resolvedPath, 'utf-8');\n const relativePath = relative(workDir, resolvedPath);\n \n // Analyze patterns that need testing\n const patterns = this.detectTestablePatterns(code);\n\n output += `### 📄 ${relativePath}\\n\\n`;\n\n if (patterns.length === 0) {\n output += `No specific test suggestions for this file.\\n\\n`;\n continue;\n }\n\n output += `| Priority | Pattern | Suggested Test |\\n`;\n output += `|----------|---------|----------------|\\n`;\n \n for (const pattern of patterns) {\n output += `| ${pattern.priority} | ${pattern.name} | ${pattern.suggestion} |\\n`;\n }\n output += '\\n';\n }\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async runTestsInfo(files: string[]) {\n const framework = await this.detectTestFramework();\n \n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `RUN TESTS\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## Detected Configuration\\n\\n`;\n output += `- **Framework:** ${framework}\\n`;\n output += `- **Files:** ${files.join(', ')}\\n\\n`;\n\n output += `## Commands\\n\\n`;\n\n switch (framework) {\n case 'jest':\n output += `\\`\\`\\`bash\\n`;\n output += `# Run all tests\\n`;\n output += `npx jest\\n\\n`;\n output += `# Run specific files\\n`;\n output += `npx jest ${files.join(' ')}\\n\\n`;\n output += `# Run with coverage\\n`;\n output += `npx jest --coverage\\n`;\n output += `\\`\\`\\`\\n`;\n break;\n case 'vitest':\n output += `\\`\\`\\`bash\\n`;\n output += `# Run all tests\\n`;\n output += `npx vitest run\\n\\n`;\n output += `# Run specific files\\n`;\n output += `npx vitest run ${files.join(' ')}\\n\\n`;\n output += `# Run with coverage\\n`;\n output += `npx vitest run --coverage\\n`;\n output += `\\`\\`\\`\\n`;\n break;\n case 'pytest':\n output += `\\`\\`\\`bash\\n`;\n output += `# Run all tests\\n`;\n output += `pytest\\n\\n`;\n output += `# Run specific files\\n`;\n output += `pytest ${files.join(' ')}\\n\\n`;\n output += `# Run with coverage\\n`;\n output += `pytest --cov\\n`;\n output += `\\`\\`\\`\\n`;\n break;\n default:\n output += `Run your test framework with the specified files.\\n`;\n }\n\n output += `\\n*Note: This tool provides test commands but doesn't execute them directly.*\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private extractTestableUnits(code: string, language: string): TestableUnit[] {\n const units: TestableUnit[] = [];\n const lines = code.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n\n // Function declarations\n const funcMatch = line.match(/(?:export\\s+)?(?:async\\s+)?function\\s+(\\w+)\\s*\\(([^)]*)\\)/);\n if (funcMatch) {\n const endLine = this.findBlockEnd(lines, i);\n const body = lines.slice(i, endLine + 1).join('\\n');\n units.push({\n name: funcMatch[1]!,\n type: 'function',\n startLine: i + 1,\n endLine: endLine + 1,\n signature: `${funcMatch[1]}(${funcMatch[2]})`,\n complexity: this.calculateComplexity(body),\n dependencies: this.extractDependencies(body),\n });\n }\n\n // Arrow functions\n const arrowMatch = line.match(/(?:export\\s+)?(?:const|let)\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\([^)]*\\)\\s*(?:=>|:)/);\n if (arrowMatch) {\n const endLine = this.findBlockEnd(lines, i);\n const body = lines.slice(i, endLine + 1).join('\\n');\n units.push({\n name: arrowMatch[1]!,\n type: 'function',\n startLine: i + 1,\n endLine: endLine + 1,\n signature: arrowMatch[1]!,\n complexity: this.calculateComplexity(body),\n dependencies: this.extractDependencies(body),\n });\n }\n\n // Classes\n const classMatch = line.match(/(?:export\\s+)?class\\s+(\\w+)/);\n if (classMatch) {\n const endLine = this.findBlockEnd(lines, i);\n units.push({\n name: classMatch[1]!,\n type: 'class',\n startLine: i + 1,\n endLine: endLine + 1,\n signature: `class ${classMatch[1]}`,\n complexity: this.calculateComplexity(lines.slice(i, endLine + 1).join('\\n')),\n dependencies: [],\n });\n }\n\n // React components\n const componentMatch = line.match(/(?:export\\s+)?(?:const|function)\\s+([A-Z]\\w+)\\s*[=:]/);\n if (componentMatch && /jsx|tsx/.test(language)) {\n const endLine = this.findBlockEnd(lines, i);\n units.push({\n name: componentMatch[1]!,\n type: 'component',\n startLine: i + 1,\n endLine: endLine + 1,\n signature: componentMatch[1]!,\n complexity: this.calculateComplexity(lines.slice(i, endLine + 1).join('\\n')),\n dependencies: this.extractDependencies(lines.slice(i, endLine + 1).join('\\n')),\n });\n }\n }\n\n return units;\n }\n\n private findBlockEnd(lines: string[], startLine: number): number {\n let braceCount = 0;\n let started = false;\n\n for (let i = startLine; i < lines.length; i++) {\n const line = lines[i] || '';\n \n for (const char of line) {\n if (char === '{') {\n braceCount++;\n started = true;\n } else if (char === '}') {\n braceCount--;\n }\n }\n\n if (started && braceCount === 0) {\n return i;\n }\n }\n\n return lines.length - 1;\n }\n\n private calculateComplexity(code: string): number {\n let complexity = 1;\n const patterns = [\n /if\\s*\\(/g, /else\\s+if/g, /\\?\\s*[^:]/g, // Conditionals\n /for\\s*\\(/g, /while\\s*\\(/g, /do\\s*\\{/g, // Loops\n /catch\\s*\\(/g, // Error handling\n /&&/g, /\\|\\|/g, // Logical operators\n /case\\s+/g, // Switch cases\n ];\n\n for (const pattern of patterns) {\n const matches = code.match(pattern);\n if (matches) {\n complexity += matches.length;\n }\n }\n\n return complexity;\n }\n\n private extractDependencies(code: string): string[] {\n const deps: string[] = [];\n \n // Look for function calls\n const calls = code.match(/\\b([a-z]\\w+)\\s*\\(/gi) || [];\n const builtins = ['if', 'for', 'while', 'switch', 'catch', 'function', 'return', 'throw', 'new', 'await', 'async'];\n \n for (const call of calls) {\n const name = call.replace(/\\s*\\($/, '');\n if (!builtins.includes(name.toLowerCase()) && !deps.includes(name)) {\n deps.push(name);\n }\n }\n\n return deps.slice(0, 10); // Limit to 10\n }\n\n private async findTestFile(sourcePath: string): Promise<string | null> {\n const dir = dirname(sourcePath);\n const base = basename(sourcePath, extname(sourcePath));\n const ext = extname(sourcePath);\n\n // Common test file patterns\n const patterns = [\n `${base}.test${ext}`,\n `${base}.spec${ext}`,\n `${base}_test${ext}`,\n `test_${base}${ext}`,\n ];\n\n // Check same directory\n for (const pattern of patterns) {\n const testPath = join(dir, pattern);\n if (existsSync(testPath)) {\n return testPath;\n }\n }\n\n // Check __tests__ directory\n const testsDir = join(dir, '__tests__');\n if (existsSync(testsDir)) {\n for (const pattern of patterns) {\n const testPath = join(testsDir, pattern);\n if (existsSync(testPath)) {\n return testPath;\n }\n }\n }\n\n return null;\n }\n\n private findTestedUnits(testCode: string, unitNames: string[]): string[] {\n const tested: string[] = [];\n\n for (const name of unitNames) {\n // Look for the name in test descriptions or assertions\n const patterns = [\n new RegExp(`describe\\\\s*\\\\([^)]*${name}`, 'i'),\n new RegExp(`it\\\\s*\\\\([^)]*${name}`, 'i'),\n new RegExp(`test\\\\s*\\\\([^)]*${name}`, 'i'),\n new RegExp(`expect\\\\s*\\\\([^)]*${name}`, 'i'),\n ];\n\n for (const pattern of patterns) {\n if (pattern.test(testCode)) {\n tested.push(name);\n break;\n }\n }\n }\n\n return tested;\n }\n\n private detectTestablePatterns(code: string): Array<{ priority: string; name: string; suggestion: string }> {\n const patterns: Array<{ priority: string; name: string; suggestion: string }> = [];\n\n const checks = [\n { pattern: /async\\s+function|await\\s+/i, priority: '🔴 HIGH', name: 'Async code', suggestion: 'Test async flows and error handling' },\n { pattern: /try\\s*{[^}]*catch/i, priority: '🔴 HIGH', name: 'Error handling', suggestion: 'Test both success and error paths' },\n { pattern: /if\\s*\\([^)]*&&[^)]*\\)/i, priority: '🟡 MED', name: 'Complex conditionals', suggestion: 'Test all condition branches' },\n { pattern: /\\.map\\(|\\.filter\\(|\\.reduce\\(/i, priority: '🟡 MED', name: 'Array operations', suggestion: 'Test with empty, single, multiple items' },\n { pattern: /fetch\\(|axios\\.|request\\(/i, priority: '🔴 HIGH', name: 'HTTP requests', suggestion: 'Mock API calls, test error responses' },\n { pattern: /localStorage|sessionStorage/i, priority: '🟡 MED', name: 'Storage usage', suggestion: 'Mock storage, test read/write' },\n { pattern: /setTimeout|setInterval/i, priority: '🟡 MED', name: 'Timers', suggestion: 'Use fake timers in tests' },\n { pattern: /useState|useEffect|useCallback/i, priority: '🔴 HIGH', name: 'React hooks', suggestion: 'Test hook behavior and updates' },\n { pattern: /form|input|submit/i, priority: '🟡 MED', name: 'Form handling', suggestion: 'Test validation and submission' },\n ];\n\n for (const { pattern, priority, name, suggestion } of checks) {\n if (pattern.test(code)) {\n patterns.push({ priority, name, suggestion });\n }\n }\n\n return patterns;\n }\n\n private async detectTestFramework(): Promise<string> {\n const workDir = getWorkingDirectory(undefined, true);\n const packagePath = resolve(workDir, 'package.json');\n \n if (existsSync(packagePath)) {\n try {\n const pkg = JSON.parse(await readFile(packagePath, 'utf-8'));\n const deps = { ...pkg.dependencies, ...pkg.devDependencies };\n \n if (deps.vitest) return 'vitest';\n if (deps.jest) return 'jest';\n if (deps.mocha) return 'mocha';\n } catch {\n // Ignore parse errors\n }\n }\n\n // Check for pytest\n if (existsSync(resolve(workDir, 'pytest.ini')) ||\n existsSync(resolve(workDir, 'pyproject.toml'))) {\n return 'pytest';\n }\n\n return 'jest'; // Default\n }\n\n private detectLanguage(filePath: string): string {\n const ext = extname(filePath).toLowerCase();\n const langMap: Record<string, string> = {\n '.ts': 'typescript', '.tsx': 'tsx', '.js': 'javascript', '.jsx': 'jsx',\n '.py': 'python', '.go': 'go', '.rs': 'rust',\n };\n return langMap[ext] || 'javascript';\n }\n\n private getHelpText(): string {\n return `\n${'━'.repeat(60)}\n🧪 TRIE TEST - AI-POWERED TEST GENERATION\n${'━'.repeat(60)}\n\n## Usage\n\n### Generate tests:\n\\`\\`\\`\ntrie_test action:\"generate\" files:[\"src/utils.ts\"]\n\\`\\`\\`\n\n### Analyze coverage:\n\\`\\`\\`\ntrie_test action:\"coverage\" files:[\"src/utils.ts\"]\n\\`\\`\\`\n\n### Get test suggestions:\n\\`\\`\\`\ntrie_test action:\"suggest\" files:[\"src/app.ts\"]\n\\`\\`\\`\n\n### Get run commands:\n\\`\\`\\`\ntrie_test action:\"run\" files:[\"src/utils.test.ts\"]\n\\`\\`\\`\n\n## Options\n\n| Option | Values | Description |\n|--------|--------|-------------|\n| action | generate, coverage, suggest, run | What to do |\n| files | Array of paths | Files to analyze |\n| framework | jest, vitest, mocha, pytest | Test framework |\n| style | unit, integration, e2e, all | Test style |\n`;\n }\n}\n","import { watch, existsSync, readFileSync } from 'fs';\nimport { stat, readFile } from 'fs/promises';\nimport { join, extname, basename } from 'path';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport { StreamingManager } from '../utils/streaming.js';\nimport { InteractiveDashboard } from '../cli/interactive-dashboard.js';\nimport { isInteractiveMode } from '../utils/progress.js';\nimport { getOutputManager } from '../utils/output-manager.js';\nimport { isTrieInitialized } from '../utils/trie-init.js';\nimport { ExtractionPipeline } from '../extraction/pipeline.js';\nimport { isAIAvailable, runAIAnalysis } from '../ai/client.js';\nimport { ContextGraph } from '../context/graph.js';\nimport type { FileNodeData } from '../context/nodes.js';\nimport { getAutonomyConfig } from '../utils/autonomy-config.js';\nimport { loadConfig } from '../config/loader.js';\nimport { getGitChangedFiles, getChangedFilesSinceTimestamp } from '../agent/git.js';\nimport { CodebaseIndex } from '../context/codebase-index.js';\nimport { getStorage } from '../storage/tiered-storage.js';\nimport type { Nudge } from '../types/signal.js';\nimport { createHash } from 'crypto';\nimport { storeIssues } from '../memory/issue-store.js';\nimport type { Issue } from '../types/index.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 TokenBudget {\n used: number;\n windowStart: number;\n hourlyLimit: number;\n scansSaved: number;\n}\n\ninterface WatchState {\n isRunning: boolean;\n lastScan: Map<string, number>;\n pendingFiles: Set<string>;\n scanDebounceTimer: NodeJS.Timeout | null;\n issueCache: Map<string, any[]>;\n totalIssuesFound: number;\n filesScanned: number;\n nudgedFiles: Set<string>;\n nudges: Array<{\n file: string;\n message: string;\n severity: 'high' | 'critical';\n timestamp: string;\n }>;\n lastAutoScan: number;\n autoScanInProgress: boolean;\n tokenBudget: TokenBudget;\n cleanFiles: Map<string, number>; // file -> timestamp of last clean scan (no issues found)\n}\n\nexport class TrieWatchTool {\n private extractionPipeline: ExtractionPipeline | null = null;\n private watchedDirectory: string = '';\n private codebaseIndex: CodebaseIndex | null = null;\n\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 nudgedFiles: new Set(),\n nudges: [],\n lastAutoScan: 0,\n autoScanInProgress: false,\n tokenBudget: {\n used: 0,\n windowStart: Date.now(),\n hourlyLimit: 50_000,\n scansSaved: 0,\n },\n cleanFiles: new Map(),\n };\n private watchers: Map<string, ReturnType<typeof watch>> = new Map();\n private streamingManager: StreamingManager | undefined = undefined;\n private dashboard: InteractiveDashboard | undefined = undefined;\n private lastHypothesisCheck: number = 0;\n private pipelineSyncTimer: NodeJS.Timeout | null = null;\n private static HYPOTHESIS_CHECK_INTERVAL_MS = 300_000; // Check every 5 minutes\n private static PIPELINE_SYNC_INTERVAL_MS = 30 * 60 * 1000; // 30 minutes\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 await this.stopWatching();\n case 'status':\n return await this.getStatus();\n case 'issues':\n return this.getCurrentIssues();\n case 'nudges':\n return this.getNudges();\n default:\n return {\n content: [{\n type: 'text',\n text: `Unknown action: ${action}. Use 'start', 'stop', 'status', or 'issues'.`\n }]\n };\n }\n }\n\n private async startWatching(directory: string, debounceMs: number) {\n if (this.state.isRunning) {\n return {\n content: [{\n type: 'text',\n text: '[!] Watch mode is already running. Use `trie_watch stop` to stop it first.'\n }]\n };\n }\n if (!isTrieInitialized(directory)) {\n return {\n content: [{\n type: 'text',\n text: 'Trie is not initialized for this project. Run `trie init` first.'\n }]\n };\n }\n\n // Initialize extraction pipeline for autonomous learning\n const anthropicApiKey = process.env.ANTHROPIC_API_KEY;\n if (anthropicApiKey) {\n this.extractionPipeline = new ExtractionPipeline({\n workingDirectory: directory,\n anthropicApiKey,\n });\n await this.extractionPipeline.initialize();\n }\n\n // Initialize codebase index for fast file lookups and goal checking\n this.codebaseIndex = new CodebaseIndex(directory);\n\n this.state.isRunning = true;\n this.watchedDirectory = directory;\n this.state.issueCache.clear();\n this.state.totalIssuesFound = 0;\n this.state.filesScanned = 0;\n this.state.nudgedFiles.clear();\n this.state.nudges = [];\n\n // Load existing unresolved nudges from SQL storage\n try {\n const storage = getStorage(directory);\n await storage.initialize();\n const unresolvedNudges = await storage.queryNudges({ resolved: false });\n\n console.debug(`[Watch] Found ${unresolvedNudges.length} unresolved nudges in storage`);\n\n // Convert stored nudges to in-memory format\n for (const nudge of unresolvedNudges) {\n // Map all severity levels to the in-memory format\n let mappedSeverity: 'high' | 'critical' = 'high';\n if (nudge.severity === 'critical') {\n mappedSeverity = 'critical';\n } else if (nudge.severity === 'high') {\n mappedSeverity = 'high';\n }\n // For 'warning' and 'info', we map to 'high' since those are the only two supported in-memory\n\n this.state.nudges.push({\n file: nudge.file || 'unknown', // Keep full path, don't use basename\n message: nudge.message,\n severity: mappedSeverity,\n timestamp: new Date(nudge.timestamp).toLocaleTimeString('en-US', { hour12: false }),\n });\n\n console.debug(`[Watch] Loaded nudge: ${nudge.message.slice(0, 60)}... (${nudge.severity} -> ${mappedSeverity})`);\n }\n\n if (unresolvedNudges.length > 0) {\n console.log(`[Watch] ✓ Loaded ${unresolvedNudges.length} unresolved nudges from storage`);\n } else {\n console.debug(`[Watch] No unresolved nudges found in storage`);\n }\n } catch (error) {\n console.error('[Watch] Failed to load nudges from storage:', error);\n }\n\n // Skip banner output in interactive mode (dashboard handles display)\n if (!isInteractiveMode()) {\n console.error('\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');\n console.error('TRIE AGENT - NOW WATCHING');\n console.error('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n');\n console.error('Your Trie agent is now watching over your codebase.');\n console.error('Signal extraction: ENABLED (building governance ledger)');\n console.error(`Watching: ${directory}`);\n console.error(`Debounce: ${debounceMs}ms`);\n console.error('');\n }\n\n // Initialize streaming + dashboard for interactive mode\n if (isInteractiveMode()) {\n this.streamingManager = new StreamingManager();\n this.dashboard = new InteractiveDashboard();\n this.streamingManager.subscribe(update => this.dashboard?.handleStreamUpdate(update));\n \n // Set up OutputManager for TUI mode\n const outputManager = getOutputManager();\n outputManager.setMode('tui');\n outputManager.setStreamingManager(this.streamingManager);\n \n await this.dashboard.start();\n this.streamingManager.reportWatchStatus({ watching: true, directories: 0, debounceMs });\n } else {\n // Console mode\n getOutputManager().setMode('console');\n }\n\n // Start watching the directory recursively\n await this.watchDirectory(directory, debounceMs);\n\n // Report watch status immediately\n if (this.streamingManager) {\n this.streamingManager.reportWatchStatus({\n watching: true,\n directories: this.watchers.size,\n debounceMs\n });\n }\n\n // Run initial scans after a small delay to ensure proper initialization\n setTimeout(() => {\n // Check recent files against active goals so users get immediate feedback\n void this.initialGoalComplianceScan();\n\n // Run initial hypothesis generation to provide insights from the start\n void this.initialHypothesisGeneration();\n\n // Initial pipeline sync + start periodic timer\n void this.syncPipelineIntegrations();\n }, 1000); // 1 second delay to allow proper initialization\n\n this.pipelineSyncTimer = setInterval(() => {\n void this.syncPipelineIntegrations();\n }, TrieWatchTool.PIPELINE_SYNC_INTERVAL_MS);\n\n // Check if codebase index exists\n const indexStatus = this.codebaseIndex?.isEmpty() \n ? 'BUILDING (one-time, speeds up goal checks)' \n : 'READY';\n\n return {\n content: [{\n type: 'text',\n text: `**TRIE AGENT ACTIVATED** \n\nYour Trie agent is now autonomously watching and learning from your codebase.\n\n**Watching:** \\`${directory}\\`\n**Debounce:** ${debounceMs}ms (waits for you to stop typing)\n**Signal Extraction:** ${process.env.ANTHROPIC_API_KEY ? 'ENABLED' : 'LIMITED (set ANTHROPIC_API_KEY for full extraction)'}\n**Codebase Index:** ${indexStatus}\n\n### How the agent works:\n1. You write/edit code\n2. Agent detects the change\n3. Extracts governance, facts, blockers -> stores in ledger\n4. Predicts risks based on historical patterns\n5. Nudges you if something looks risky\n\n### The agent learns:\n- Every commit builds the governance ledger\n- \\`trie gotcha\\` queries the ledger for predictions\n- \\`trie ok\\` / \\`trie bad\\` teach the agent what matters\n\n### Commands:\n- \\`trie_watch status\\` - See agent status\n- \\`trie_watch stop\\` - Stop the agent\n- \\`trie_index status\\` - Check codebase index`\n }]\n };\n }\n\n private shouldSkipPath(filePath: string): boolean {\n const parts = filePath.split('/');\n return parts.some(p => SKIP_DIRS.has(p) || (p.startsWith('.') && p !== '.'));\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 const watcher = watch(dir, { persistent: true, recursive: true }, (_eventType, filename) => {\n if (!filename) return;\n\n if (this.shouldSkipPath(filename)) return;\n\n const ext = extname(filename).toLowerCase();\n if (!WATCH_EXTENSIONS.has(ext)) return;\n\n const fullPath = join(dir, filename);\n if (!existsSync(fullPath)) return;\n\n this.state.pendingFiles.add(fullPath);\n\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 watcher.on('error', (err) => {\n if (!isInteractiveMode()) {\n console.error(`[!] Watcher error: ${err.message}`);\n }\n // Close the watcher and remove from map to prevent memory leak\n watcher.close();\n this.watchers.delete(dir);\n });\n\n this.watchers.set(dir, watcher);\n\n if (this.streamingManager) {\n this.streamingManager.reportWatchStatus({\n watching: true,\n directories: 1,\n debounceMs\n });\n }\n } catch {\n // Skip directories we can't access\n }\n }\n\n private async processPendingFiles() {\n if (this.state.pendingFiles.size === 0) return;\n\n const files = Array.from(this.state.pendingFiles);\n this.state.pendingFiles.clear();\n\n if (!isInteractiveMode()) {\n console.error(`\\nDetected changes in ${files.length} file(s):`);\n for (const file of files) {\n console.error(` - ${basename(file)}`);\n }\n console.error('');\n }\n\n try {\n const projectPath = this.watchedDirectory || getWorkingDirectory(undefined, true);\n \n // === Autonomous signal extraction from file changes ===\n if (this.extractionPipeline) {\n try {\n // Read changed files and extract signals\n const fileContents = await Promise.all(\n files.map(async (file) => {\n try {\n const content = await readFile(file, 'utf-8');\n return { file, content };\n } catch {\n return null;\n }\n })\n );\n\n // Extract signals from file changes\n const validFiles = fileContents.filter(f => f !== null);\n if (validFiles.length > 0) {\n const combinedContent = validFiles.map(f => \n `File: ${basename(f!.file)}\\n${f!.content.slice(0, 1000)}` // First 1KB of each file\n ).join('\\n\\n---\\n\\n');\n\n if (!isInteractiveMode()) {\n console.error('[*] Extracting signals from changes...');\n }\n\n const signal = await this.extractionPipeline.process(combinedContent, {\n sourceType: 'file',\n sourceId: `watch-${Date.now()}`,\n });\n\n if (signal.governance.length > 0 || signal.facts.length > 0 || signal.blockers.length > 0) {\n const govCount = signal.governance.length;\n if (!isInteractiveMode()) {\n console.error(` [+] Extracted: ${govCount} governance, ${signal.facts.length} facts, ${signal.blockers.length} blockers`);\n }\n \n if (this.streamingManager) {\n this.streamingManager.reportSignalExtraction({\n governance: govCount,\n facts: signal.facts.length,\n blockers: signal.blockers.length,\n questions: signal.questions.length,\n });\n }\n }\n }\n } catch (error) {\n if (!isInteractiveMode()) {\n console.error(` [!] Signal extraction failed: ${error}`);\n }\n }\n }\n\n // AI watcher: primary detection system for code issues AND goal violations.\n // Always runs -- the method itself handles throttling and budget.\n void this.autoScanFiles(files).catch(err => {\n getOutputManager().log('warn', `Auto scan failed: ${err}`);\n });\n \n // Autonomous pattern discovery from recent issues\n await this.discoverPatternsFromIssues(projectPath);\n \n // Autonomous hypothesis generation (periodic check)\n const now = Date.now();\n if (now - this.lastHypothesisCheck > TrieWatchTool.HYPOTHESIS_CHECK_INTERVAL_MS) {\n this.checkAndGenerateHypotheses(projectPath);\n this.lastHypothesisCheck = now;\n }\n\n // Report file changes to TUI (deduplicate within 2s window)\n if (this.streamingManager) {\n const now = Date.now();\n for (const file of files) {\n const lastReport = this.state.lastScan.get(file) || 0;\n if (now - lastReport > 2000) {\n this.streamingManager.reportWatchChange(file);\n }\n }\n }\n \n // Update stats\n this.state.filesScanned += files.length;\n\n // Track processed files and update codebase index\n for (const file of files) {\n this.state.lastScan.set(file, Date.now());\n \n // Index the changed file for faster goal checking\n if (this.codebaseIndex) {\n const relativePath = file.replace(projectPath + '/', '');\n // Index and save immediately - ensures index is always up to date\n void this.codebaseIndex.indexFile(relativePath).then(() => {\n void this.codebaseIndex?.save();\n });\n }\n }\n\n } catch (error) {\n if (!isInteractiveMode()) {\n console.error(`Scan error: ${error}`);\n }\n }\n }\n\n private isQuiet(): boolean {\n const projectPath = this.watchedDirectory || getWorkingDirectory(undefined, true);\n const quietPath = join(getTrieDirectory(projectPath), 'quiet.json');\n try {\n const raw = readFileSync(quietPath, 'utf-8');\n const data = JSON.parse(raw);\n const until = new Date(data.until).getTime();\n return Date.now() < until;\n } catch {\n return false;\n }\n }\n\n\n /**\n * Check and generate hypotheses autonomously\n * Claude observes patterns and creates new hypotheses to test\n */\n private async checkAndGenerateHypotheses(projectPath: string): Promise<void> {\n if (!isAIAvailable()) return;\n \n try {\n const { getHypothesisEngine } = await import('../agent/hypothesis.js');\n const { getOutputManager } = await import('../utils/output-manager.js');\n \n const hypothesisEngine = getHypothesisEngine(projectPath);\n \n // Gather recent patterns and observations\n const recentIssues = Array.from(this.state.issueCache.values()).flat();\n const patterns: string[] = [];\n const observations: string[] = [];\n \n // Collect observable patterns from watch session\n if (this.state.nudges.length > 0) {\n const nudgesByFile: Record<string, number> = {};\n for (const nudge of this.state.nudges) {\n nudgesByFile[nudge.file] = (nudgesByFile[nudge.file] || 0) + 1;\n }\n \n const topFiles = Object.entries(nudgesByFile)\n .sort(([, a], [, b]) => b - a)\n .slice(0, 3);\n \n if (topFiles[0] && topFiles[0][1] > 2) {\n observations.push(`File ${topFiles[0][0]} has ${topFiles[0][1]} repeated issues this session`);\n }\n }\n \n if (this.state.nudges.length > 5) {\n observations.push(`High issue detection rate: ${this.state.nudges.length} violations detected in watch session`);\n }\n \n // Try AI-powered hypothesis generation first\n let generated = await hypothesisEngine.generateHypothesesWithAI({\n recentIssues,\n patterns,\n observations,\n });\n \n // Fall back to template-based if AI didn't generate any\n if (generated.length === 0) {\n generated = await hypothesisEngine.autoGenerateHypotheses();\n }\n \n // Nudge user about new hypotheses\n for (const hypothesis of generated) {\n const message = `[New Hypothesis] \"${hypothesis.statement}\" (${Math.round(hypothesis.confidence * 100)}% confidence)`;\n \n getOutputManager().nudge(\n message,\n 'info',\n undefined,\n 10000\n );\n \n if (!isInteractiveMode()) {\n console.error(`\\n [?] ${message}`);\n console.error(` Test: ${hypothesis.testCriteria || 'Collecting evidence...'}`);\n }\n \n // Report to TUI\n if (this.streamingManager) {\n this.streamingManager.reportSignalExtraction({\n governance: 0,\n facts: 0,\n blockers: 0,\n questions: 1, // Hypotheses are questions to answer\n });\n }\n }\n \n // Also update confidence on existing hypotheses\n if (recentIssues.length > 10) {\n await hypothesisEngine.updateConfidenceFromOutcomes();\n }\n \n } catch (error) {\n // Hypothesis generation is best-effort\n if (!isInteractiveMode()) {\n console.error(` [!] Hypothesis check failed: ${error}`);\n }\n }\n }\n\n /**\n * Discover patterns from accumulated issues\n * Patterns emerge naturally from your coding workflow\n */\n private async discoverPatternsFromIssues(projectPath: string): Promise<void> {\n // Only discover patterns if we have enough data\n const totalIssues = Array.from(this.state.issueCache.values())\n .flat()\n .length;\n \n if (totalIssues < 5) return; // Need at least 5 issues to find patterns\n \n try {\n const { ContextGraph } = await import('../context/graph.js');\n const { IncidentIndex } = await import('../context/incident-index.js');\n const { TriePatternDiscovery } = await import('../agent/pattern-discovery.js');\n \n const graph = new ContextGraph(projectPath);\n const incidentIndex = await IncidentIndex.build(graph, projectPath);\n const discovery = new TriePatternDiscovery(graph, incidentIndex);\n \n // Discover hot patterns (files/directories with 2+ issues)\n const hotPatterns = discovery.discoverHotPatterns(2); // Lower threshold for faster discovery\n \n for (const hot of hotPatterns) {\n // Check if pattern already exists\n const existingPatterns = await graph.listNodes();\n const alreadyExists = existingPatterns.some(\n n => n.type === 'pattern' && \n (n.data as any).description?.includes(hot.path)\n );\n \n if (!alreadyExists) {\n await graph.addNode('pattern', {\n description: `${hot.type === 'directory' ? 'Directory' : 'File'} hot zone: ${hot.path}`,\n appliesTo: [hot.path],\n confidence: Math.min(0.95, hot.confidence),\n occurrences: hot.incidentCount,\n firstSeen: new Date().toISOString(),\n lastSeen: new Date().toISOString(),\n isAntiPattern: hot.incidentCount >= 3, // 3+ incidents = anti-pattern\n source: 'local'\n });\n \n if (!isInteractiveMode()) {\n console.error(` [+] Pattern discovered: ${hot.path} (${hot.incidentCount} issues)`);\n }\n \n // Report to TUI\n if (this.streamingManager) {\n this.streamingManager.reportSignalExtraction({\n governance: 0,\n facts: 1, // Patterns are facts about the codebase\n blockers: 0,\n questions: 0,\n });\n }\n }\n }\n \n // Discover co-occurrence patterns (files that break together)\n if (totalIssues >= 10) {\n const coOccurrences = await discovery.discoverCoOccurrences(2); // 2+ co-occurrences\n \n for (const coOcc of coOccurrences.slice(0, 3)) { // Top 3 co-occurrence patterns\n const desc = `Files break together: ${coOcc.files[0]} + ${coOcc.files[1]}`;\n \n const existingPatterns = await graph.listNodes();\n const alreadyExists = existingPatterns.some(\n n => n.type === 'pattern' && \n (n.data as any).description === desc\n );\n \n if (!alreadyExists) {\n await graph.addNode('pattern', {\n description: desc,\n appliesTo: [...coOcc.files],\n confidence: Math.min(0.95, coOcc.confidence),\n occurrences: coOcc.coOccurrences,\n firstSeen: new Date().toISOString(),\n lastSeen: new Date().toISOString(),\n isAntiPattern: coOcc.confidence > 0.7,\n source: 'local'\n });\n \n if (!isInteractiveMode()) {\n console.error(` [+] Co-occurrence pattern: ${coOcc.files[0]} + ${coOcc.files[1]}`);\n }\n }\n }\n }\n } catch (error) {\n // Pattern discovery is best-effort\n if (!isInteractiveMode()) {\n console.error(` [!] Pattern discovery failed: ${error}`);\n }\n }\n }\n\n // Defaults -- overridden by config when loaded\n private aiWatcherCooldownMs = 30_000;\n private cleanFileCooldownMs = 300_000;\n private maxFilesPerScan = 5;\n private maxCharsPerFile = 4000;\n\n /**\n * Use the trie (context graph) to score how urgently a file needs scanning.\n * Higher score = more worth spending tokens on.\n */\n private async scoreScanPriority(\n file: string,\n graph: ContextGraph,\n projectPath: string,\n ): Promise<number> {\n let score = 1; // baseline: every changed file gets at least 1\n\n // Recently scanned clean → skip entirely\n const lastClean = this.state.cleanFiles.get(file);\n if (lastClean && Date.now() - lastClean < this.cleanFileCooldownMs) {\n return 0;\n }\n\n const fileNode = await graph.getNode('file', join(projectPath, file));\n if (!fileNode) return score; // unknown file, scan at baseline\n\n const data = fileNode.data as FileNodeData;\n\n // Risk level is the biggest signal\n const riskScores: Record<string, number> = { critical: 10, high: 6, medium: 2, low: 1 };\n score += riskScores[data.riskLevel] ?? 1;\n\n // Past incidents make a file worth watching closely\n score += Math.min(data.incidentCount * 3, 12);\n\n // High churn files have more surface area for bugs\n if (data.changeCount > 10) score += 2;\n\n return score;\n }\n\n /**\n * Roll the token budget window if an hour has passed.\n * Returns remaining tokens in the current window.\n */\n private getRemainingBudget(): number {\n const budget = this.state.tokenBudget;\n const elapsed = Date.now() - budget.windowStart;\n if (elapsed > 3_600_000) {\n budget.used = 0;\n budget.windowStart = Date.now();\n }\n return Math.max(0, budget.hourlyLimit - budget.used);\n }\n\n private recordTokenUsage(tokens: number) {\n this.state.tokenBudget.used += tokens;\n }\n\n /**\n * AI-powered watcher -- the primary detection system.\n * \n * This is the single AI call that handles:\n * 1. Code review (bugs, security, logic errors)\n * 2. Goal violation detection (user-defined quality goals)\n * \n * When goals are active, files with goal violations bypass priority scoring\n * so violations are always caught. Throttled by cooldown + token budget.\n */\n private async autoScanFiles(files: string[]) {\n if (!isAIAvailable()) return;\n if (this.state.autoScanInProgress) return;\n\n const now = Date.now();\n if (now - this.state.lastAutoScan < this.aiWatcherCooldownMs) return;\n\n // Set the flag early to prevent concurrent scans - will be reset in finally block\n this.state.autoScanInProgress = true;\n this.state.lastAutoScan = now;\n\n const projectPath = this.watchedDirectory || getWorkingDirectory(undefined, true);\n\n try {\n // Load AI watcher config\n try {\n const config = await getAutonomyConfig(projectPath);\n const wc = config.aiWatcher;\n if (!wc.enabled) return;\n this.state.tokenBudget.hourlyLimit = wc.hourlyTokenLimit;\n this.aiWatcherCooldownMs = wc.scanCooldownSec * 1000;\n this.cleanFileCooldownMs = wc.cleanFileCooldownSec * 1000;\n this.maxFilesPerScan = wc.maxFilesPerScan;\n this.maxCharsPerFile = wc.maxCharsPerFile;\n } catch { /* use current values */ }\n\n const remaining = this.getRemainingBudget();\n if (remaining < 500) return;\n\n try {\n const graph = new ContextGraph(projectPath);\n\n // Load active goals -- these drive the AI watcher's behavior\n const { getActiveGoals, recordGoalViolationCaught } = await import('../agent/goal-validator.js');\n\n console.debug('[AI Watcher] Loading active goals...');\n const activeGoals = await getActiveGoals(projectPath);\n const hasGoals = activeGoals.length > 0;\n\n console.debug('[AI Watcher] Goals loaded:', {\n totalGoals: activeGoals.length,\n hasGoals,\n goals: activeGoals.map(g => ({ id: g.id, description: g.description, status: g.status }))\n });\n\n // In quiet mode, only run if goals are active (goals always get checked)\n if (this.isQuiet() && !hasGoals) return;\n\n // Use the Trie's priority scoring to rank files by risk.\n // When goals are active, every changed file is included (min score 1)\n // so the AI can check them all against user goals.\n // When no goals, low-risk files are skipped to save tokens.\n const scored: Array<{ file: string; relativePath: string; score: number }> = [];\n for (const file of files) {\n const relativePath = file.replace(projectPath + '/', '');\n const score = await this.scoreScanPriority(relativePath, graph, projectPath);\n if (hasGoals || score > 0) {\n scored.push({ file, relativePath, score: Math.max(score, hasGoals ? 1 : 0) });\n } else {\n this.state.tokenBudget.scansSaved++;\n }\n }\n\n if (scored.length === 0) return;\n\n // Sort by Trie priority -- highest-risk files first\n scored.sort((a, b) => b.score - a.score);\n\n // Budget-aware file cap: use configured max, scale down when budget is low\n const budgetScale = remaining > 20_000 ? 1.0 : remaining > 10_000 ? 0.6 : 0.4;\n const maxFiles = Math.max(1, Math.round(this.maxFilesPerScan * budgetScale));\n const filesToScan = scored.slice(0, maxFiles);\n\n // Truncate content per file -- scale down with budget\n const charLimit = Math.round(this.maxCharsPerFile * (remaining > 15_000 ? 1.0 : 0.5));\n\n const fileContents = await Promise.all(\n filesToScan.map(async ({ file, relativePath }) => {\n try {\n const content = await readFile(file, 'utf-8');\n return { path: relativePath, content: content.slice(0, charLimit) };\n } catch { return null; }\n })\n );\n const valid = fileContents.filter(Boolean) as Array<{ path: string; content: string }>;\n if (valid.length === 0) return;\n\n const filesBlock = valid.map(f =>\n `### ${f.path}\\n\\`\\`\\`\\n${f.content}\\n\\`\\`\\``\n ).join('\\n\\n');\n\n // Build the prompt -- goals are first-class\n let goalsSection = '';\n if (hasGoals) {\n goalsSection = `\nUSER-DEFINED GOALS (IMPORTANT - check EVERY file against ALL goals):\n${activeGoals.map((g, i) => ` ${i + 1}. \"${g.description}\"`).join('\\n')}\n\nGoal violations are HIGH PRIORITY. If a file violates any goal, you MUST report it.\n`;\n }\n\n console.debug('[AI Watcher] Sending files to AI analysis:', {\n fileCount: valid.length,\n hasGoals,\n goalsIncluded: hasGoals,\n filePaths: valid.map(f => f.path),\n goalsSection: goalsSection.slice(0, 200) + (goalsSection.length > 200 ? '...' : '')\n });\n\n const result = await runAIAnalysis({\n systemPrompt: `You are a code quality watcher. You review code for two things:\n\n1. CODE ISSUES: bugs, security vulnerabilities, logic errors, risky patterns\n2. GOAL VIOLATIONS: check every file against the user's quality goals\n${goalsSection}\nReply ONLY with a JSON array. Each element must have:\n- \"file\": relative file path\n- \"severity\": \"critical\" | \"major\" | \"minor\"\n- \"description\": 1-sentence description of what you found\n- \"confidence\": number 0-100, how confident you are this is a real issue\n- \"suggestedFix\": 1-sentence description of what should change to fix it\n- \"isGoalViolation\": true if this violates a user goal, false otherwise\n- \"goalIndex\": 0-based index of the violated goal (only if isGoalViolation is true)\n\nBe thorough with goal checking. If a goal says \"no emojis\" and you see an emoji anywhere in the file, report it with the exact location. If a goal says \"no inline styles\" and you see a style attribute, report it.\n\nIf no issues or violations found, reply with: []\nOutput ONLY the JSON array, no markdown fences, no commentary.`,\n userPrompt: `Review these changed files:\\n\\n${filesBlock}`,\n maxTokens: 2048,\n temperature: 0.1,\n });\n\n if (result.tokensUsed) {\n this.recordTokenUsage(result.tokensUsed.input + result.tokensUsed.output);\n }\n\n console.debug('[AI Watcher] AI analysis result:', {\n success: result.success,\n contentLength: result.content ? result.content.length : 0,\n tokensUsed: result.tokensUsed,\n contentPreview: result.content ? result.content.slice(0, 500) : 'null'\n });\n\n if (!result.success || !result.content.trim()) {\n console.debug('[AI Watcher] AI analysis failed or returned empty content');\n return;\n }\n\n let issues: Array<{\n file: string;\n severity: string;\n description: string;\n confidence?: number;\n suggestedFix?: string;\n isGoalViolation?: boolean;\n goalIndex?: number;\n }> = [];\n try {\n const cleaned = result.content.replace(/```json?\\n?|\\n?```/g, '').trim();\n console.debug('[AI Watcher] Parsing AI response:', { cleanedContent: cleaned.slice(0, 300) });\n issues = JSON.parse(cleaned);\n if (!Array.isArray(issues)) issues = [];\n console.debug('[AI Watcher] Parsed issues:', {\n totalIssues: issues.length,\n goalViolations: issues.filter(i => i.isGoalViolation).length,\n issueTypes: issues.map(i => ({ file: i.file, isGoalViolation: i.isGoalViolation, goalIndex: i.goalIndex }))\n });\n } catch (error) {\n console.debug('[AI Watcher] Failed to parse AI response:', error);\n return;\n }\n\n // Mark clean files\n const issuedFiles = new Set(issues.map(i => i.file));\n for (const { relativePath } of filesToScan) {\n if (!issuedFiles.has(relativePath)) {\n this.state.cleanFiles.set(relativePath, Date.now());\n }\n }\n\n if (issues.length === 0) return;\n\n for (const issue of issues.slice(0, 10)) {\n const severity = issue.severity === 'critical' ? 'critical'\n : issue.severity === 'major' ? 'major' : 'minor';\n\n // Handle goal violations: create a pending fix for user approval\n if (issue.isGoalViolation && issue.goalIndex != null && issue.goalIndex >= 0 && issue.goalIndex < activeGoals.length) {\n const goal = activeGoals[issue.goalIndex];\n if (!goal) continue; // Defensive check\n const confidence = Math.min(100, Math.max(0, issue.confidence ?? 80));\n const fixId = `fix-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n\n console.debug('[AI Watcher] Goal violation detected:', {\n goalDescription: goal.description,\n file: issue.file,\n violation: issue.description,\n confidence,\n goalIndex: issue.goalIndex,\n totalActiveGoals: activeGoals.length\n });\n\n // Store as a proper Issue so it's queryable by measureGoalMetric\n const goalViolationIssue: Issue = {\n id: fixId,\n file: issue.file,\n agent: 'goal-violation',\n severity: severity === 'critical' ? 'critical' : severity === 'major' ? 'serious' : 'moderate',\n issue: `Goal \"${goal.description}\" violated: ${issue.description}`,\n fix: issue.suggestedFix || 'Review and fix',\n category: 'goal-violation',\n confidence,\n autoFixable: true,\n };\n await storeIssues([goalViolationIssue], basename(projectPath), projectPath);\n await recordGoalViolationCaught(goal, issue.file, projectPath);\n\n // Nudge with confidence -- ask the user if they want it fixed\n const confidenceStr = `${confidence}%`;\n const nudgeMsg = `Goal \"${goal.description}\" violated in ${issue.file}: ${issue.description} [${confidenceStr} confidence]`;\n\n console.debug('[AI Watcher] Sending nudge:', {\n message: nudgeMsg,\n file: issue.file,\n severity: 'warning'\n });\n\n getOutputManager().nudge(nudgeMsg, 'warning', issue.file);\n\n // Persist nudge to both memory and SQL\n await this.persistNudge({\n message: nudgeMsg,\n severity: 'warning',\n file: issue.file,\n category: 'quality',\n goalId: goal.id,\n priority: 7,\n suggestedAction: issue.suggestedFix || 'Review and fix manually',\n relatedIssues: [fixId]\n });\n\n // Emit a pending fix to the TUI for interactive approval\n if (this.streamingManager) {\n this.streamingManager.reportPendingFix({\n id: fixId,\n file: issue.file,\n description: issue.description,\n goalDescription: goal.description,\n confidence,\n severity: issue.severity,\n suggestedFix: issue.suggestedFix || 'Remove the violating code',\n });\n }\n\n if (!isInteractiveMode()) {\n console.error(` [!] Goal violation (${confidenceStr}): ${issue.description}`);\n console.error(` Fix: ${issue.suggestedFix || 'Review and fix manually'}`);\n }\n continue;\n }\n\n // Standard code issue -- add to context graph\n const incident = await graph.addNode('incident', {\n description: issue.description,\n severity,\n affectedUsers: null,\n duration: null,\n timestamp: new Date().toISOString(),\n resolved: false,\n resolution: null,\n fixChangeId: null,\n reportedVia: 'detected',\n });\n\n const filePath = join(projectPath, issue.file);\n const fileNode = await graph.getNode('file', filePath);\n if (fileNode) {\n await graph.addEdge(fileNode.id, incident.id, 'affects');\n const data = fileNode.data as FileNodeData;\n const newRisk = severity === 'critical' ? 'critical'\n : severity === 'major' ? 'high'\n : data.riskLevel === 'low' ? 'medium' : data.riskLevel;\n await graph.updateNode('file', fileNode.id, {\n incidentCount: (data.incidentCount ?? 0) + 1,\n riskLevel: newRisk,\n });\n }\n\n this.state.totalIssuesFound++;\n\n if (severity !== 'minor') {\n getOutputManager().nudge(\n `${issue.description}`,\n severity === 'critical' ? 'critical' : 'warning',\n issue.file,\n severity === 'critical' ? undefined : 15000,\n );\n \n // Persist nudge to both memory and SQL\n await this.persistNudge({\n message: issue.description,\n severity: severity === 'critical' ? 'critical' : 'warning',\n file: issue.file,\n category: 'quality',\n priority: severity === 'critical' ? 9 : 6,\n ...(issue.suggestedFix && { suggestedAction: issue.suggestedFix }),\n });\n }\n }\n\n if (this.streamingManager && issues.length > 0) {\n this.streamingManager.reportSignalExtraction({\n governance: 0,\n facts: 0,\n blockers: issues.length,\n questions: 0,\n });\n }\n } catch (error) {\n getOutputManager().log('warn', `AI watcher error: ${error}`);\n }\n } finally {\n this.state.autoScanInProgress = false;\n }\n }\n\n /**\n * Initial hypothesis generation when watch starts.\n *\n * This generates hypotheses from existing patterns and issues to give\n * users immediate insights about their codebase.\n */\n private async initialHypothesisGeneration() {\n if (!isAIAvailable()) {\n console.debug('[Initial Hypothesis] AI not available, skipping initial hypothesis generation');\n return;\n }\n\n const projectPath = this.watchedDirectory || getWorkingDirectory(undefined, true);\n\n console.debug('[Initial Hypothesis] Starting initial hypothesis generation', { projectPath });\n\n try {\n const { getHypothesisEngine } = await import('../agent/hypothesis.js');\n const hypothesisEngine = getHypothesisEngine(projectPath);\n\n console.debug('[Initial Hypothesis] Running AI-powered hypothesis generation...');\n\n // Generate hypotheses from existing patterns and codebase state\n const generated = await hypothesisEngine.generateHypothesesWithAI({\n recentIssues: [], // No recent issues yet on startup\n patterns: [],\n observations: ['Initial watch session started', 'Analyzing codebase for potential patterns'],\n });\n\n console.debug('[Initial Hypothesis] Generated hypotheses on startup:', {\n count: generated.length,\n hypotheses: generated.map(h => ({ statement: h.statement, confidence: h.confidence }))\n });\n\n // Notify user about new hypotheses\n if (generated.length > 0) {\n const { getOutputManager } = await import('../utils/output-manager.js');\n const outputManager = getOutputManager();\n\n for (const hypothesis of generated.slice(0, 2)) { // Limit to 2 on startup to avoid spam\n const message = `[Initial Hypothesis] \"${hypothesis.statement}\" (${Math.round(hypothesis.confidence * 100)}% confidence)`;\n\n outputManager.nudge(message, 'info', undefined, 10000);\n\n if (!isInteractiveMode()) {\n console.error(` [?] ${message}`);\n }\n }\n\n // Report to TUI\n if (this.streamingManager) {\n this.streamingManager.reportSignalExtraction({\n governance: 0,\n facts: 0,\n blockers: 0,\n questions: generated.length,\n });\n }\n }\n\n } catch (error) {\n console.debug('[Initial Hypothesis] Failed to generate initial hypotheses:', error);\n }\n }\n\n /**\n * Initial goal compliance scan when watch starts.\n * \n * This checks recently modified files against active goals so the user\n * gets immediate feedback about goal violations without waiting for files\n * to be changed.\n * \n * Strategy:\n * 1. Check if there are any active goals - if not, skip\n * 2. Find recently modified files (last 24 hours OR uncommitted changes)\n * 3. Filter to watched file types\n * 4. Run a quick AI scan focused only on goal violations\n * 5. Nudge the user about any violations found\n */\n private async initialGoalComplianceScan() {\n if (!isAIAvailable()) {\n console.debug('[Initial Scan] AI not available, skipping initial goal compliance scan');\n return;\n }\n\n const projectPath = this.watchedDirectory || getWorkingDirectory(undefined, true);\n\n console.debug('[Initial Scan] Starting initial goal compliance scan', { projectPath });\n\n try {\n // Load active goals\n const { getActiveGoals, recordGoalViolationCaught } = await import('../agent/goal-validator.js');\n const activeGoals = await getActiveGoals(projectPath);\n\n console.debug('[Initial Scan] Loaded goals for initial scan:', {\n goalCount: activeGoals.length,\n goals: activeGoals.map(g => ({ id: g.id, description: g.description }))\n });\n\n // Skip if no goals are active\n if (activeGoals.length === 0) {\n console.debug('[Initial Scan] No active goals found, skipping initial scan');\n return;\n }\n \n if (!isInteractiveMode()) {\n console.error('[*] Checking recent files against active goals...');\n }\n \n // Find recently modified files\n const recentFiles = new Set<string>();\n \n // 1. Get uncommitted changes (high priority - user is actively working on these)\n const uncommittedFiles = await getGitChangedFiles(projectPath);\n if (uncommittedFiles) {\n uncommittedFiles.forEach(f => recentFiles.add(join(projectPath, f)));\n }\n \n // 2. Get files changed in last 24 hours (recent work)\n const oneDayAgo = Date.now() - (24 * 60 * 60 * 1000);\n const recentChanges = await getChangedFilesSinceTimestamp(projectPath, oneDayAgo);\n if (recentChanges) {\n recentChanges.forEach(f => recentFiles.add(f));\n }\n \n // Filter to watched file types and existing files\n const filesToCheck = Array.from(recentFiles).filter(file => {\n const ext = extname(file).toLowerCase();\n return WATCH_EXTENSIONS.has(ext) && existsSync(file);\n });\n\n console.debug('[Initial Scan] Files discovered for initial scan:', {\n totalRecentFiles: recentFiles.size,\n filteredFiles: filesToCheck.length,\n filePaths: filesToCheck.slice(0, 5).map(f => f.replace(projectPath + '/', '')), // Show first 5\n watchedExtensions: Array.from(WATCH_EXTENSIONS)\n });\n\n if (filesToCheck.length === 0) {\n console.debug('[Initial Scan] No recent files found for initial scan');\n return;\n }\n \n // Limit to a reasonable number for initial scan (don't overwhelm)\n const maxInitialFiles = 10;\n const filesToScan = filesToCheck.slice(0, maxInitialFiles);\n \n if (!isInteractiveMode()) {\n console.error(` Scanning ${filesToScan.length} recent file(s) against ${activeGoals.length} goal(s)...`);\n }\n \n // Read file contents (limit to prevent token overuse)\n const maxCharsPerFile = 3000; // Smaller limit for initial scan\n const fileContents = await Promise.all(\n filesToScan.map(async (file) => {\n try {\n const content = await readFile(file, 'utf-8');\n const relativePath = file.replace(projectPath + '/', '');\n return { path: relativePath, content: content.slice(0, maxCharsPerFile) };\n } catch {\n return null;\n }\n })\n );\n \n const valid = fileContents.filter(Boolean) as Array<{ path: string; content: string }>;\n if (valid.length === 0) return;\n \n const filesBlock = valid.map(f =>\n `### ${f.path}\\n\\`\\`\\`\\n${f.content}\\n\\`\\`\\``\n ).join('\\n\\n');\n \n // Build goal-focused prompt\n const goalsSection = `\nUSER-DEFINED GOALS (check EVERY file against ALL goals):\n${activeGoals.map((g, i) => ` ${i + 1}. \"${g.description}\"`).join('\\n')}\n\nThis is an INITIAL SCAN at watch startup. Report ALL goal violations you find.\n`;\n \n const result = await runAIAnalysis({\n systemPrompt: `You are checking code for GOAL VIOLATIONS ONLY.\n${goalsSection}\nReply ONLY with a JSON array. Each element must have:\n- \"file\": relative file path\n- \"severity\": \"critical\" | \"major\" | \"minor\"\n- \"description\": 1-sentence description of the goal violation\n- \"confidence\": number 0-100, how confident you are this is a violation\n- \"suggestedFix\": 1-sentence description of what should change\n- \"isGoalViolation\": true (always true for this scan)\n- \"goalIndex\": 0-based index of the violated goal\n\nBe thorough. If a goal says \"no emojis\" and you see ANY emoji in the file, report it. If a goal says \"no console.log\" and you see console.log, report it.\n\nIf no violations found, reply with: []\nOutput ONLY the JSON array, no markdown fences, no commentary.`,\n userPrompt: `Check these files for goal violations:\\n\\n${filesBlock}`,\n maxTokens: 2048,\n temperature: 0.1,\n });\n \n if (result.tokensUsed) {\n this.recordTokenUsage(result.tokensUsed.input + result.tokensUsed.output);\n }\n \n if (!result.success || !result.content.trim()) return;\n \n // Parse issues\n let issues: Array<{\n file: string;\n severity: 'critical' | 'major' | 'minor';\n description: string;\n confidence: number;\n suggestedFix?: string;\n isGoalViolation: boolean;\n goalIndex?: number;\n }> = [];\n \n try {\n const parsed = JSON.parse(result.content.trim());\n issues = Array.isArray(parsed) ? parsed : [];\n } catch {\n return;\n }\n \n // Process goal violations\n const issuesToStore: Issue[] = [];\n let violationsFound = 0;\n \n for (const issue of issues) {\n if (!issue.isGoalViolation || issue.confidence < 40) continue;\n \n violationsFound++;\n \n // Track goal violation\n if (issue.goalIndex != null && issue.goalIndex >= 0 && issue.goalIndex < activeGoals.length) {\n const goal = activeGoals[issue.goalIndex];\n if (!goal) continue; // Defensive check\n \n // Store as a proper Issue so it's queryable by measureGoalMetric\n const fixId = `fix-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n issuesToStore.push({\n id: fixId,\n file: issue.file,\n agent: 'goal-violation',\n severity: issue.severity === 'critical' ? 'critical' : issue.severity === 'major' ? 'serious' : 'moderate',\n issue: `Goal \"${goal.description}\" violated: ${issue.description}`,\n fix: issue.suggestedFix || 'Review and fix',\n category: 'goal-violation',\n confidence: issue.confidence,\n autoFixable: true,\n });\n \n await recordGoalViolationCaught(goal, issue.file, projectPath);\n \n // Nudge the user\n const confidenceStr = issue.confidence >= 80 ? 'high' : issue.confidence >= 60 ? 'medium' : 'low';\n const nudgeMsg = `Goal \"${goal.description}\" violated in ${issue.file}: ${issue.description} [${confidenceStr} confidence]`;\n getOutputManager().nudge(nudgeMsg, 'warning', issue.file);\n \n // Persist nudge to both memory and SQL\n await this.persistNudge({\n message: nudgeMsg,\n severity: 'warning',\n file: issue.file,\n category: 'quality',\n goalId: goal.id,\n priority: issue.confidence >= 80 ? 8 : issue.confidence >= 60 ? 6 : 4,\n ...(issue.suggestedFix && { suggestedAction: issue.suggestedFix }),\n });\n }\n }\n \n if (issuesToStore.length > 0) {\n await storeIssues(issuesToStore, basename(projectPath), projectPath);\n }\n \n if (!isInteractiveMode()) {\n if (violationsFound > 0) {\n console.error(` [!] Found ${violationsFound} goal violation(s) in recent files`);\n } else {\n console.error(` [✓] No goal violations found in recent files`);\n }\n }\n \n } catch (error) {\n if (!isInteractiveMode()) {\n console.error(` [!] Initial goal scan error: ${error}`);\n }\n }\n }\n\n private async syncPipelineIntegrations(): Promise<void> {\n const projectPath = this.watchedDirectory || getWorkingDirectory(undefined, true);\n try {\n const config = await loadConfig();\n\n const hasLinear = !!(config.apiKeys?.linear ?? process.env.LINEAR_API_KEY);\n const hasGithub = !!(config.apiKeys?.github ?? process.env.GITHUB_TOKEN);\n\n if (!hasLinear && !hasGithub) return;\n\n const graph = new ContextGraph(projectPath);\n\n if (hasLinear) {\n try {\n const { LinearIngester } = await import('../ingest/linear-ingester.js');\n const ingester = new LinearIngester(projectPath, graph);\n await ingester.syncTickets();\n if (!isInteractiveMode()) {\n console.error('[Pipeline] Linear tickets synced');\n }\n } catch (error) {\n if (!isInteractiveMode()) {\n console.error(`[Pipeline] Linear sync failed: ${error}`);\n }\n }\n }\n\n if (hasGithub) {\n try {\n const { GitHubIngester } = await import('../ingest/github-ingester.js');\n const ingester = new GitHubIngester(graph);\n const token = (await ingester.getApiToken())!;\n const repoInfo = ingester.getRepoInfo(projectPath);\n if (repoInfo) {\n await ingester.syncPullRequests(repoInfo.owner, repoInfo.name, token);\n await ingester.syncIssues(repoInfo.owner, repoInfo.name, token);\n if (!isInteractiveMode()) {\n console.error('[Pipeline] GitHub PRs/issues synced');\n }\n }\n } catch (error) {\n if (!isInteractiveMode()) {\n console.error(`[Pipeline] GitHub sync failed: ${error}`);\n }\n }\n }\n } catch {\n // Pipeline sync is best-effort\n }\n }\n\n private async 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 watcher of this.watchers.values()) {\n watcher.close();\n }\n this.watchers.clear();\n\n // Close extraction pipeline\n if (this.extractionPipeline) {\n this.extractionPipeline.close();\n this.extractionPipeline = null;\n }\n\n // Stop pipeline sync timer\n if (this.pipelineSyncTimer) {\n clearInterval(this.pipelineSyncTimer);\n this.pipelineSyncTimer = null;\n }\n\n // Save codebase index before stopping\n if (this.codebaseIndex) {\n await this.codebaseIndex.save();\n this.codebaseIndex = null;\n }\n\n // Clear state\n if (this.state.scanDebounceTimer) {\n clearTimeout(this.state.scanDebounceTimer);\n }\n \n this.state.isRunning = false;\n\n if (!isInteractiveMode()) {\n console.error('\\n[*] Watch mode stopped.\\n');\n }\n if (this.streamingManager) {\n this.streamingManager.reportWatchStatus({ watching: false, directories: 0 });\n }\n \n // Clean up OutputManager\n const outputManager = getOutputManager();\n outputManager.clearTUICallbacks();\n outputManager.setMode('console');\n \n // Stop the dashboard if running\n if (this.dashboard) {\n this.dashboard.stop();\n this.dashboard = undefined;\n }\n\n const budget = this.state.tokenBudget;\n const tokensK = (budget.used / 1000).toFixed(1);\n\n return {\n content: [{\n type: 'text',\n text: `[*] **TRIE AGENT STOPPED**\n\n### Session Summary:\n- Files scanned: ${this.state.filesScanned}\n- Issues found: ${this.state.totalIssuesFound}\n- Tokens used: ${tokensK}k / ${(budget.hourlyLimit / 1000).toFixed(0)}k hourly limit\n- Scans skipped (trie-throttled): ${budget.scansSaved}\n- Governance ledger: Updated continuously\n\nUse \\`trie_watch start\\` to resume.`\n }]\n };\n }\n\n private async getStatus() {\n if (!this.state.isRunning) {\n return {\n content: [{\n type: 'text',\n text: `[*] **Watch Mode Status: STOPPED**\n\nUse \\`trie_watch start\\` to begin autonomous scanning.`\n }]\n };\n }\n\n const recentScans = Array.from(this.state.lastScan.entries())\n .sort((a, b) => b[1] - a[1])\n .slice(0, 5)\n .map(([file, time]) => {\n const ago = Math.round((Date.now() - time) / 1000);\n return `- \\`${basename(file)}\\` (${ago}s ago)`;\n })\n .join('\\n');\n\n const recentNudges = this.state.nudges.slice(-3).map(\n (n) => `- ${basename(n.file)} [${n.severity}] @ ${n.timestamp}`\n ).join('\\n');\n\n // Get Trie Agent agency status\n let agencyStatus = '';\n try {\n const { getTrieAgent } = await import('../agent/trie-agent.js');\n const trieAgent = getTrieAgent(this.watchedDirectory || getWorkingDirectory(undefined, true));\n await trieAgent.initialize();\n const status = await trieAgent.getAgencyStatus();\n\n agencyStatus = `\n### [AI] Trie Agent:\n- **Goals:** ${status.goals.active} active, ${status.goals.completed} completed${status.goals.topGoal ? ` (${status.goals.topGoal.slice(0, 40)}...)` : ''}\n- **Hypotheses:** ${status.hypotheses.testing} testing, ${status.hypotheses.validated} validated\n- **Risk Level:** ${status.riskLevel.toUpperCase()}\n- **Effectiveness:** ${status.effectiveness}%\n- **Scan Frequency:** ${Math.round(status.scanFrequency / 1000)}s${status.isQuietHours ? ' (quiet hours)' : ''}`;\n } catch {\n // Agency status is optional\n }\n\n const budget = this.state.tokenBudget;\n const remaining = this.getRemainingBudget();\n const tokensK = (budget.used / 1000).toFixed(1);\n const remainingK = (remaining / 1000).toFixed(1);\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.state.filesScanned}\n- Issues found: ${this.state.totalIssuesFound}\n- Pending: ${this.state.pendingFiles.size}\n\n### Token Budget:\n- Used: ${tokensK}k / ${(budget.hourlyLimit / 1000).toFixed(0)}k hourly\n- Remaining: ${remainingK}k\n- Scans skipped (trie-throttled): ${budget.scansSaved}\n${agencyStatus}\n\n### Recently Scanned:\n${recentScans || '(none yet)'}\n\n### Recent Nudges:\n${recentNudges || '(none)'}\n\n### Commands:\n- \\`trie_watch issues\\` - Get all issues found\n- \\`trie_watch stop\\` - Stop watching`\n }]\n };\n }\n\n /**\n * Helper to persist a nudge to both in-memory state and SQL storage\n */\n private async persistNudge(params: {\n message: string;\n severity: 'critical' | 'high' | 'warning' | 'info';\n file?: string;\n category?: string;\n goalId?: string;\n priority?: number;\n suggestedAction?: string;\n relatedIssues?: string[];\n }): Promise<void> {\n const timestamp = new Date().toISOString();\n const nudgeId = createHash('sha256')\n .update(`${params.message}|${params.file || ''}|${timestamp}`)\n .digest('hex')\n .slice(0, 16);\n\n const nudge: Nudge = {\n id: nudgeId,\n message: params.message,\n severity: params.severity,\n timestamp,\n resolved: false,\n dismissed: false,\n priority: params.priority ?? 5,\n relatedIssues: params.relatedIssues ?? [],\n metadata: {},\n ...(params.file && { file: params.file }),\n ...(params.category && { category: params.category }),\n ...(params.goalId && { goalId: params.goalId }),\n ...(params.suggestedAction && { suggestedAction: params.suggestedAction }),\n };\n\n // Store in memory for current session\n this.state.nudges.push({\n file: params.file || 'unknown', // Keep full path for consistency with loaded nudges\n message: params.message,\n severity: params.severity === 'warning' || params.severity === 'info' ? 'high' : params.severity,\n timestamp: new Date().toLocaleTimeString('en-US', { hour12: false }),\n });\n\n // Persist to SQL\n try {\n const storage = getStorage(this.watchedDirectory);\n await storage.storeNudge(nudge);\n console.debug(`[Watch] ✓ Persisted nudge to storage: ${nudge.message.slice(0, 60)}...`);\n } catch (error) {\n console.error('[Watch] Failed to persist nudge to storage:', error);\n }\n }\n\n private getNudges() {\n return {\n content: [\n {\n type: 'text',\n text: `[#] Recent nudges (${this.state.nudges.length} this session)\\n` +\n (this.state.nudges.length\n ? this.state.nudges.map((n) =>\n `- ${basename(n.file)} [${n.severity}] @ ${n.timestamp}\\n ${n.message}`\n ).join('\\n')\n : '(none)')\n },\n {\n type: 'json',\n json: this.state.nudges\n }\n ]\n };\n }\n\n private getCurrentIssues() {\n return {\n content: [{\n type: 'text',\n text: `[L] **Issues Found This Session**\n\nTotal issues: ${this.state.totalIssuesFound}\nFiles scanned: ${this.state.filesScanned}\n\nTo get a full report, run \\`trie_scan\\` on your codebase.`\n }]\n };\n }\n}\n","import { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join, basename, resolve, isAbsolute } from 'path';\nimport { SuperReviewerAgent, CRITICAL_REVIEW_CHECKLIST } from '../skills/built-in/super-reviewer.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { runShellCommandSync } from '../utils/command-runner.js';\n\n/**\n * PR Review Tool — Interactive AI-Guided Code Review\n * \n * Based on https://github.com/sitaram/devtools/blob/main/pr_review.md\n * \n * Code reviews are the bottleneck in AI coding. This tool scales them by\n * putting the human back in the loop, shepherded by AI.\n */\nexport class TriePRReviewTool {\n private agent = new SuperReviewerAgent();\n\n private exec(command: string, cwd?: string, maxBuffer?: number): string {\n const opts: Parameters<typeof runShellCommandSync>[2] = {\n captureOutput: false,\n redactOutput: true,\n ...(cwd ? { cwd } : {}),\n ...(maxBuffer ? { maxBuffer } : {}),\n };\n const { stdout } = runShellCommandSync(\n command,\n { actor: 'tool:pr-review', triggeredBy: 'manual', targetPath: cwd ?? getWorkingDirectory(undefined, true) },\n opts\n );\n return stdout.trimEnd();\n }\n\n async execute(args: any) {\n const { \n pr, \n worktree,\n mode,\n files: _specificFiles, // Reserved for future file filtering\n } = args;\n\n try {\n // Step 1: Determine target and get PR info\n const prInfo = await this.getPRInfo(pr, worktree);\n \n if (!prInfo.success) {\n return {\n content: [{\n type: 'text',\n text: `${prInfo.error}\\n\\nUsage:\\n- \\`pr_review 12345\\` — review specific PR\\n- \\`pr_review\\` — review PR for current branch\\n- \\`pr_review ../worktree\\` — review worktree changes`\n }]\n };\n }\n\n // Step 2: Get the diff and changed files\n const changes = await this.getChanges(prInfo);\n \n if (changes.files.length === 0) {\n return {\n content: [{\n type: 'text',\n text: `No changes found to review.`\n }]\n };\n }\n\n // Step 3: Look for design docs\n const designDocs = await this.findDesignDocs(changes.files, prInfo);\n\n // Step 4: Build the review workflow\n const workflow = await this.agent.buildReviewWorkflow(\n changes.files,\n {\n prNumber: prInfo.number,\n prTitle: prInfo.title,\n prAuthor: prInfo.author,\n baseBranch: prInfo.baseBranch,\n headBranch: prInfo.headBranch,\n mode: mode || 'own',\n designDocs,\n }\n );\n\n // Step 5: Pre-load all file contents for instant responses\n const fileContents = await this.preloadFiles(changes.files.map(f => f.path));\n\n // Step 6: Generate the review prompt\n const reviewPrompt = this.generateReviewPrompt(workflow, changes, fileContents);\n\n return {\n content: [{\n type: 'text',\n text: reviewPrompt\n }]\n };\n\n } catch (error) {\n return {\n content: [{\n type: 'text',\n text: `Error: ${error instanceof Error ? error.message : String(error)}`\n }]\n };\n }\n }\n\n /**\n * Get PR information from GitHub or local worktree\n */\n private async getPRInfo(pr?: string, worktree?: string): Promise<PRInfo> {\n // If worktree path provided, analyze local changes\n if (worktree) {\n const worktreePath = isAbsolute(worktree) ? worktree : resolve(getWorkingDirectory(undefined, true), worktree);\n if (!existsSync(worktreePath)) {\n return { success: false, error: `Worktree not found: ${worktreePath}` };\n }\n \n return {\n success: true,\n type: 'worktree',\n path: worktreePath,\n title: `Local changes in ${basename(worktreePath)}`,\n author: this.getGitUser(),\n baseBranch: 'HEAD~1',\n headBranch: 'HEAD',\n };\n }\n\n // If PR number provided, get from GitHub\n if (pr) {\n return this.getPRFromGitHub(pr);\n }\n\n // No args — try to get PR for current branch\n try {\n this.exec('git branch --show-current');\n \n // Check if there's a PR for this branch\n const prJson = this.exec(\n `gh pr view --json number,title,author,headRefName,baseRefName`\n );\n \n const prData = JSON.parse(prJson);\n \n return {\n success: true,\n type: 'github',\n number: String(prData.number),\n title: prData.title,\n author: prData.author?.login || 'unknown',\n baseBranch: prData.baseRefName,\n headBranch: prData.headRefName,\n };\n } catch {\n // No PR found, fall back to local changes\n return {\n success: true,\n type: 'local',\n title: 'Local uncommitted changes',\n author: this.getGitUser(),\n baseBranch: 'HEAD',\n headBranch: 'working tree',\n };\n }\n }\n\n /**\n * Get PR info from GitHub CLI\n */\n private async getPRFromGitHub(prNumber: string): Promise<PRInfo> {\n try {\n const prJson = this.exec(\n `gh pr view ${prNumber} --json number,title,author,headRefName,baseRefName`\n );\n \n const prData = JSON.parse(prJson);\n \n return {\n success: true,\n type: 'github',\n number: String(prData.number),\n title: prData.title,\n author: prData.author?.login || 'unknown',\n baseBranch: prData.baseRefName,\n headBranch: prData.headRefName,\n };\n } catch (error) {\n return {\n success: false,\n error: `Failed to get PR #${prNumber}. Is \\`gh\\` CLI installed and authenticated?`\n };\n }\n }\n\n /**\n * Get changes (diff) for the PR or local changes\n */\n private async getChanges(prInfo: PRInfo): Promise<{ files: ChangedFile[]; fullDiff: string }> {\n let diffOutput: string;\n \n try {\n if (prInfo.type === 'github' && prInfo.number) {\n // Get diff from GitHub PR\n diffOutput = this.exec(`gh pr diff ${prInfo.number}`, undefined, 50 * 1024 * 1024);\n } else if (prInfo.type === 'worktree' && prInfo.path) {\n // Get diff from worktree\n diffOutput = this.exec(`git diff HEAD`, prInfo.path, 50 * 1024 * 1024);\n } else {\n // Local changes\n diffOutput = this.exec(`git diff HEAD`, undefined, 50 * 1024 * 1024);\n \n // If no diff, try staged changes\n if (!diffOutput.trim()) {\n diffOutput = this.exec(`git diff --cached`, undefined, 50 * 1024 * 1024);\n }\n }\n } catch {\n diffOutput = '';\n }\n\n // Parse the diff to extract file information\n const files = this.parseDiff(diffOutput);\n\n return { files, fullDiff: diffOutput };\n }\n\n /**\n * Parse git diff output into structured file changes\n */\n private parseDiff(diffOutput: string): ChangedFile[] {\n const files: ChangedFile[] = [];\n const fileDiffs = diffOutput.split(/^diff --git /m).slice(1);\n\n for (const fileDiff of fileDiffs) {\n const lines = fileDiff.split('\\n');\n const headerLine = lines[0] || '';\n \n // Extract file path from \"a/path b/path\"\n const pathMatch = headerLine.match(/a\\/(.+?) b\\/(.+)/);\n if (!pathMatch || !pathMatch[2]) continue;\n \n const path: string = pathMatch[2];\n const diff = `diff --git ${fileDiff}`;\n \n // Count additions and deletions\n let additions = 0;\n let deletions = 0;\n \n for (const line of lines) {\n if (line.startsWith('+') && !line.startsWith('+++')) {\n additions++;\n } else if (line.startsWith('-') && !line.startsWith('---')) {\n deletions++;\n }\n }\n \n files.push({ path, diff, additions, deletions, status: 'modified' });\n }\n\n return files;\n }\n\n /**\n * Find related design docs\n */\n private async findDesignDocs(files: ChangedFile[], prInfo: PRInfo): Promise<string[]> {\n const designDocs: string[] = [];\n const cwd = prInfo.path || getWorkingDirectory(undefined, true);\n \n // Check for design_docs/ in changed files\n for (const file of files) {\n if (file.path.includes('design_docs/') || \n file.path.includes('docs/design/') ||\n file.path.includes('rfcs/')) {\n designDocs.push(file.path);\n }\n }\n \n // Look for design docs in standard locations\n const designDocPaths = [\n 'design_docs',\n 'docs/design',\n 'docs/rfcs',\n 'rfcs',\n ];\n \n for (const docPath of designDocPaths) {\n const fullPath = join(cwd, docPath);\n if (existsSync(fullPath)) {\n // Could list and add recent docs, but for now just note the directory exists\n }\n }\n \n return designDocs;\n }\n\n /**\n * Pre-load all changed files for instant responses during review\n */\n private async preloadFiles(filePaths: string[]): Promise<Map<string, string>> {\n const contents = new Map<string, string>();\n const cwd = getWorkingDirectory(undefined, true);\n \n await Promise.all(filePaths.map(async (filePath) => {\n try {\n const fullPath = isAbsolute(filePath) ? filePath : join(cwd, filePath);\n if (existsSync(fullPath)) {\n const content = await readFile(fullPath, 'utf-8');\n contents.set(filePath, content);\n }\n } catch {\n // Skip unreadable files\n }\n }));\n \n return contents;\n }\n\n /**\n * Get git user name\n */\n private getGitUser(): string {\n try {\n return this.exec('git config user.name');\n } catch {\n return 'unknown';\n }\n }\n\n /**\n * Generate the full review prompt for Claude to execute\n */\n private generateReviewPrompt(\n workflow: any,\n changes: { files: ChangedFile[]; fullDiff: string },\n _fileContents: Map<string, string> // Reserved for future: inline file contents in review\n ): string {\n const { metadata, fileOrder, reviewInstructions } = workflow;\n \n let prompt = `# 🔍 Super Reviewer — Interactive PR Review\\n\\n`;\n \n // PR Header\n if (metadata.prNumber) {\n prompt += `## PR #${metadata.prNumber}: ${metadata.prTitle}\\n\\n`;\n } else {\n prompt += `## ${metadata.prTitle}\\n\\n`;\n }\n \n prompt += `**Author:** ${metadata.prAuthor}\\n`;\n prompt += `**Branch:** \\`${metadata.headBranch}\\` → \\`${metadata.baseBranch}\\`\\n`;\n prompt += `**Scope:** ${metadata.totalFiles} files, +${metadata.totalAdditions}/-${metadata.totalDeletions} lines\\n\\n`;\n \n prompt += `---\\n\\n`;\n \n // Review Mode Selection\n prompt += `## Review Mode\\n\\n`;\n prompt += `**Current Mode:** ${reviewInstructions.mode === 'own' ? '1' : '2'}. ${reviewInstructions.description}\\n\\n`;\n prompt += `> To switch modes, say \"mode 1\" for your own PR or \"mode 2\" for someone else's\\n\\n`;\n \n prompt += `---\\n\\n`;\n \n // File Order Table\n prompt += `## Files to Review (ordered for understanding)\\n\\n`;\n prompt += `| # | File | Why this order |\\n`;\n prompt += `|---|------|----------------|\\n`;\n \n for (const file of fileOrder) {\n const stats = `+${changes.files.find(f => f.path === file.path)?.additions || 0}/-${changes.files.find(f => f.path === file.path)?.deletions || 0}`;\n prompt += `| ${file.index} | \\`${file.path}\\` (${stats}) | ${file.reason} |\\n`;\n }\n \n prompt += `\\n---\\n\\n`;\n \n // Critical Review Mindset\n prompt += `## Critical Review Mindset\\n\\n`;\n prompt += `As we go through each file, I'll actively look for:\\n\\n`;\n \n prompt += `**State & Lifecycle:**\\n`;\n for (const check of CRITICAL_REVIEW_CHECKLIST.stateAndLifecycle) {\n prompt += `- ${check}\\n`;\n }\n \n prompt += `\\n**Edge Cases & Races:**\\n`;\n for (const check of CRITICAL_REVIEW_CHECKLIST.edgeCasesAndRaces) {\n prompt += `- ${check}\\n`;\n }\n \n prompt += `\\n**Missing Pieces:**\\n`;\n for (const check of CRITICAL_REVIEW_CHECKLIST.missingPieces) {\n prompt += `- ${check}\\n`;\n }\n \n prompt += `\\n---\\n\\n`;\n \n // Pre-loaded diffs\n prompt += `## File Diffs (pre-loaded for instant review)\\n\\n`;\n prompt += `<details>\\n<summary>📁 All file diffs (click to expand)</summary>\\n\\n`;\n \n for (const file of fileOrder) {\n const fileChange = changes.files.find(f => f.path === file.path);\n if (fileChange) {\n prompt += `### ${file.path}\\n\\n`;\n prompt += `\\`\\`\\`diff\\n${fileChange.diff}\\n\\`\\`\\`\\n\\n`;\n }\n }\n \n prompt += `</details>\\n\\n`;\n \n prompt += `---\\n\\n`;\n \n // Ready to start\n prompt += `## Ready to Begin\\n\\n`;\n prompt += `I'll walk you through each file, explaining what changed and why. After each file, I'll pause for your questions.\\n\\n`;\n prompt += `**Commands during review:**\\n`;\n prompt += `- \\`yes\\` or \\`y\\` — continue to next file\\n`;\n prompt += `- \\`skip to [filename]\\` — jump to specific file\\n`;\n prompt += `- \\`questions?\\` — ask about current file\\n`;\n prompt += `- \\`reorder\\` — change the file order\\n`;\n prompt += `- \\`done\\` — end review and show summary\\n\\n`;\n \n prompt += `**Ready for File 1?** (\\`${fileOrder[0]?.path || 'no files'}\\`)\\n\\n`;\n prompt += `*(say \"yes\" to start, or ask me anything)*\\n`;\n \n return prompt;\n }\n}\n\n// Type definitions\ninterface PRInfo {\n success: boolean;\n error?: string;\n type?: 'github' | 'worktree' | 'local';\n number?: string;\n title?: string;\n author?: string;\n baseBranch?: string;\n headBranch?: string;\n path?: string;\n}\n\ninterface ChangedFile {\n path: string;\n diff: string;\n additions: number;\n deletions: number;\n status: string;\n}\n","/**\n * Super Reviewer stub\n * Review functionality has been integrated into decision ledger\n */\n\nexport const CRITICAL_REVIEW_CHECKLIST = {\n stateAndLifecycle: [\n 'Uninitialized state accessed before setup',\n 'Missing cleanup on unmount/dispose',\n 'State mutations in wrong lifecycle phase',\n ],\n edgeCasesAndRaces: [\n 'Race conditions in async operations',\n 'Missing error handling for edge cases',\n 'Unhandled promise rejections',\n ],\n missingPieces: [\n 'Missing input validation',\n 'Missing error handling',\n 'Missing logging/monitoring',\n ],\n};\n\nexport interface ChangedFile {\n path: string;\n additions: number;\n deletions: number;\n status: string;\n}\n\nexport class SuperReviewerAgent {\n async review(_files: string[]): Promise<{ issues: any[] }> {\n return { issues: [] };\n }\n\n async buildReviewWorkflow(\n files: ChangedFile[],\n context: Record<string, any>\n ): Promise<{ files: ChangedFile[]; context: Record<string, any> }> {\n return { files, context };\n }\n}\n","/**\n * Project Info MCP Tool\n * \n * Provides MCP tool for viewing and managing PROJECT.md\n */\n\nimport {\n loadProjectInfo,\n initProjectInfo,\n getProjectSection,\n updateProjectSection,\n appendToSection,\n getProjectSections,\n getProjectInfoStructured,\n projectInfoExists,\n} from '../utils/project-info.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport interface ProjectInfoArgs {\n action: 'view' | 'init' | 'update' | 'append' | 'sections' | 'raw';\n section?: string;\n content?: string;\n directory?: string;\n}\n\nexport class TrieProjectInfoTool {\n async execute(args: ProjectInfoArgs): Promise<{ content: Array<{ type: string; text: string }> }> {\n const workDir = args.directory || getWorkingDirectory(undefined, true);\n const action = args.action || 'view';\n\n try {\n switch (action) {\n case 'view':\n return await this.handleView(workDir, args.section);\n \n case 'init':\n return await this.handleInit(workDir);\n \n case 'update':\n return await this.handleUpdate(workDir, args.section, args.content);\n \n case 'append':\n return await this.handleAppend(workDir, args.section, args.content);\n \n case 'sections':\n return await this.handleSections(workDir);\n \n case 'raw':\n return await this.handleRaw(workDir);\n \n default:\n return this.error(`Unknown action: ${action}. Use: view, init, update, append, sections, raw`);\n }\n } catch (error) {\n return this.error(`Error: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n private async handleView(workDir: string, section?: string): Promise<{ content: Array<{ type: string; text: string }> }> {\n if (!projectInfoExists(workDir)) {\n return this.formatResponse(`## Project Info Not Found\n\nNo \\`.trie/PROJECT.md\\` file exists in this project.\n\n**To create one, use:**\n\\`\\`\\`\ntrie_project action=\"init\"\n\\`\\`\\`\n\nOr run: \\`trie project init\\`\n\nThis will create a template with sections for:\n- Project Overview\n- Technology Stack\n- Architecture\n- Coding Conventions\n- Environment\n- Team\n- Compliance\n- AI Instructions`);\n }\n\n if (section) {\n const sectionContent = await getProjectSection(section, workDir);\n if (sectionContent === null) {\n const sections = await getProjectSections(workDir);\n return this.formatResponse(`## Section Not Found: \"${section}\"\n\nAvailable sections:\n${sections.map(s => `- ${s}`).join('\\n')}`);\n }\n \n return this.formatResponse(`## ${section}\n\n${sectionContent}`);\n }\n\n // Return structured view\n const info = await getProjectInfoStructured(workDir);\n \n let output = `## Project Information\n\n**Path:** \\`${info.path}\\`\n**Sections:** ${Object.keys(info.sections).length}\n\n---\n\n`;\n\n for (const [name, content] of Object.entries(info.sections)) {\n output += `### ${name}\n\n${content}\n\n---\n\n`;\n }\n\n return this.formatResponse(output);\n }\n\n private async handleInit(workDir: string): Promise<{ content: Array<{ type: string; text: string }> }> {\n const result = await initProjectInfo(workDir);\n \n if (result.created) {\n return this.formatResponse(`## PROJECT.md Created\n\n**Path:** \\`${result.path}\\`\n\nA new PROJECT.md file has been created with a template including sections for:\n- Project Overview\n- Technology Stack\n- Architecture\n- Coding Conventions\n- Environment\n- Team\n- Compliance\n- AI Instructions\n\n**Next steps:**\n1. Open the file and fill in your project details\n2. The content will be available via \\`trie://project\\` resource\n3. AI assistants will use this context when working on your project\n\n**View the template:**\n\\`\\`\\`\ntrie_project action=\"view\"\n\\`\\`\\``);\n }\n\n return this.formatResponse(`## PROJECT.md Already Exists\n\n**Path:** \\`${result.path}\\`\n\nUse \\`trie_project action=\"view\"\\` to see the current content.`);\n }\n\n private async handleUpdate(\n workDir: string, \n section?: string, \n content?: string\n ): Promise<{ content: Array<{ type: string; text: string }> }> {\n if (!section) {\n return this.error('Missing required parameter: section');\n }\n if (!content) {\n return this.error('Missing required parameter: content');\n }\n\n const success = await updateProjectSection(section, content, workDir);\n \n if (success) {\n return this.formatResponse(`## Section Updated: \"${section}\"\n\nThe \"${section}\" section has been updated with your new content.\n\n**View updated section:**\n\\`\\`\\`\ntrie_project action=\"view\" section=\"${section}\"\n\\`\\`\\``);\n }\n\n const sections = await getProjectSections(workDir);\n return this.error(`Could not update section \"${section}\". \n\nAvailable sections:\n${sections.map(s => `- ${s}`).join('\\n')}`);\n }\n\n private async handleAppend(\n workDir: string,\n section?: string,\n content?: string\n ): Promise<{ content: Array<{ type: string; text: string }> }> {\n if (!section) {\n return this.error('Missing required parameter: section');\n }\n if (!content) {\n return this.error('Missing required parameter: content');\n }\n\n const success = await appendToSection(section, content, workDir);\n \n if (success) {\n return this.formatResponse(`## Content Appended to: \"${section}\"\n\nYour content has been added to the \"${section}\" section.\n\n**View updated section:**\n\\`\\`\\`\ntrie_project action=\"view\" section=\"${section}\"\n\\`\\`\\``);\n }\n\n return this.error(`Could not append to section \"${section}\". Make sure the section exists.`);\n }\n\n private async handleSections(workDir: string): Promise<{ content: Array<{ type: string; text: string }> }> {\n if (!projectInfoExists(workDir)) {\n return this.formatResponse(`## No PROJECT.md Found\n\nRun \\`trie_project action=\"init\"\\` to create one.`);\n }\n\n const sections = await getProjectSections(workDir);\n \n return this.formatResponse(`## Available Sections\n\n${sections.map((s, i) => `${i + 1}. **${s}**`).join('\\n')}\n\n**View a section:**\n\\`\\`\\`\ntrie_project action=\"view\" section=\"Section Name\"\n\\`\\`\\`\n\n**Update a section:**\n\\`\\`\\`\ntrie_project action=\"update\" section=\"Section Name\" content=\"New content...\"\n\\`\\`\\``);\n }\n\n private async handleRaw(workDir: string): Promise<{ content: Array<{ type: string; text: string }> }> {\n const content = await loadProjectInfo(workDir);\n \n if (!content) {\n return this.formatResponse(`No PROJECT.md found. Run \\`trie_project action=\"init\"\\` to create one.`);\n }\n\n return this.formatResponse(content);\n }\n\n private formatResponse(text: string): { content: Array<{ type: string; text: string }> } {\n return {\n content: [{ type: 'text', text }]\n };\n }\n\n private error(message: string): { content: Array<{ type: string; text: string }> } {\n return {\n content: [{ type: 'text', text: `**Error:** ${message}` }]\n };\n }\n}\n","/**\n * Trie Init Tool\n * \n * MCP tool for initializing bootstrap files.\n */\n\nimport { initializeBootstrapFiles, loadBootstrapContext, completeBootstrap, needsBootstrap } from '../bootstrap/index.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport class TrieInitTool {\n async execute(params: {\n action?: 'init' | 'status' | 'complete' | 'context';\n directory?: string;\n force?: boolean;\n skipBootstrap?: boolean;\n }): Promise<string> {\n const action = params.action || 'init';\n const workDir = params.directory || getWorkingDirectory(undefined, true);\n\n if (action === 'status') {\n const needs = needsBootstrap(workDir);\n const context = await loadBootstrapContext(workDir);\n \n const existingFiles = context.files.filter(f => f.exists).map(f => f.name);\n const missingFiles = context.files.filter(f => !f.exists).map(f => f.name);\n \n return [\n '# Bootstrap Status',\n '',\n `**Bootstrap pending:** ${needs ? 'Yes' : 'No'}`,\n '',\n '## Files',\n '',\n '**Existing:**',\n existingFiles.length > 0 ? existingFiles.map(f => `- .trie/${f}`).join('\\n') : '- None',\n '',\n '**Missing:**',\n missingFiles.length > 0 ? missingFiles.map(f => `- .trie/${f}`).join('\\n') : '- None',\n ].join('\\n');\n }\n\n if (action === 'complete') {\n const result = await completeBootstrap(workDir);\n if (result) {\n return 'Bootstrap completed. BOOTSTRAP.md has been deleted.';\n }\n return 'No BOOTSTRAP.md file found.';\n }\n\n if (action === 'context') {\n const context = await loadBootstrapContext(workDir);\n if (!context.injectedContent) {\n return 'No bootstrap context available. Run trie_init with action=\"init\" first.';\n }\n return context.injectedContent;\n }\n\n // Default: init\n const initOptions: Parameters<typeof initializeBootstrapFiles>[0] = {\n workDir,\n };\n if (params.force !== undefined) {\n initOptions.force = params.force;\n }\n if (params.skipBootstrap !== undefined) {\n initOptions.skipBootstrap = params.skipBootstrap;\n }\n const result = await initializeBootstrapFiles(initOptions);\n\n const lines: string[] = [\n '# Trie Workspace Initialized',\n '',\n ];\n\n if (result.created.length > 0) {\n lines.push('## Created Files', '');\n for (const file of result.created) {\n lines.push(`- .trie/${file}`);\n }\n lines.push('');\n }\n\n if (result.skipped.length > 0) {\n lines.push('## Skipped (already exist)', '');\n for (const file of result.skipped) {\n lines.push(`- .trie/${file}`);\n }\n lines.push('');\n }\n\n lines.push('## Detected Stack', '');\n if (result.stack.framework) lines.push(`- **Framework:** ${result.stack.framework}`);\n if (result.stack.language) lines.push(`- **Language:** ${result.stack.language}`);\n if (result.stack.database) lines.push(`- **Database:** ${result.stack.database}`);\n if (result.stack.auth) lines.push(`- **Auth:** ${result.stack.auth}`);\n if (result.stack.packageManager) lines.push(`- **Package Manager:** ${result.stack.packageManager}`);\n lines.push('');\n\n if (result.stack.suggestedSkills.length > 0) {\n lines.push('## Suggested Skills', '');\n for (const skill of result.stack.suggestedSkills) {\n lines.push(`\\`\\`\\`bash`);\n lines.push(`trie skills add ${skill}`);\n lines.push(`\\`\\`\\``);\n }\n lines.push('');\n }\n\n lines.push(\n '## Next Steps',\n '',\n '1. Edit `.trie/PROJECT.md` with your project description',\n '2. Define coding standards in `.trie/RULES.md`',\n '3. Run `trie_scan` to analyze your codebase',\n '4. Run `trie_init` with action=\"complete\" when setup is done',\n );\n\n return lines.join('\\n');\n }\n}\n","/**\n * Trie Memory Search Tool\n * \n * MCP tool for searching issue memory.\n */\n\nimport {\n searchIssues,\n getMemoryStats,\n getRecentIssues,\n findSimilarIssues,\n markIssueResolved,\n purgeIssues,\n} from '../memory/issue-store.js';\nimport {\n findCrossProjectPatterns,\n searchGlobalPatterns,\n listTrackedProjects,\n getGlobalMemoryStats,\n} from '../memory/global-memory.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport class TrieMemorySearchTool {\n async execute(params: {\n action?: 'search' | 'stats' | 'recent' | 'similar' | 'resolve' | 'global' | 'purge';\n query?: string;\n issueId?: string;\n limit?: number;\n severity?: string[];\n agent?: string;\n includeResolved?: boolean;\n directory?: string;\n purgeStrategy?: 'smart' | 'resolved' | 'old' | 'all';\n daysOld?: number;\n }): Promise<{ content: Array<{ type: string; text: string }> }> {\n const action = params.action || 'search';\n const workDir = params.directory || getWorkingDirectory(undefined, true);\n\n let resultText: string;\n switch (action) {\n case 'search':\n resultText = await this.handleSearch(params, workDir);\n break;\n case 'stats':\n resultText = await this.handleStats(workDir);\n break;\n case 'recent':\n resultText = await this.handleRecent(params, workDir);\n break;\n case 'similar':\n resultText = await this.handleSimilar(params, workDir);\n break;\n case 'resolve':\n resultText = await this.handleResolve(params, workDir);\n break;\n case 'global':\n resultText = await this.handleGlobal(params);\n break;\n case 'purge':\n resultText = await this.handlePurge(params, workDir);\n break;\n default:\n resultText = 'Unknown action. Use: search, stats, recent, similar, resolve, global, or purge';\n }\n\n return {\n content: [{\n type: 'text',\n text: resultText\n }]\n };\n }\n\n private async handleSearch(params: {\n query?: string;\n limit?: number;\n severity?: string[];\n agent?: string;\n includeResolved?: boolean;\n }, workDir: string): Promise<string> {\n if (!params.query) {\n return 'Missing required parameter: query';\n }\n\n const searchOptions: Parameters<typeof searchIssues>[1] = {\n workDir,\n limit: params.limit || 10,\n };\n if (params.severity !== undefined) {\n searchOptions.severity = params.severity;\n }\n if (params.agent !== undefined) {\n searchOptions.agent = params.agent;\n }\n if (params.includeResolved !== undefined) {\n searchOptions.includeResolved = params.includeResolved;\n }\n const results = await searchIssues(params.query, searchOptions);\n\n if (results.length === 0) {\n return `No issues found matching \"${params.query}\"`;\n }\n\n const lines: string[] = [\n `# Search Results: \"${params.query}\"`,\n '',\n `Found ${results.length} matching issue(s):`,\n '',\n ];\n\n for (const result of results) {\n const i = result.issue;\n const status = i.resolved ? ' [RESOLVED]' : '';\n lines.push(\n `## [${i.severity.toUpperCase()}]${status} ${i.issue.slice(0, 80)}`,\n '',\n `- **File:** \\`${i.file}\\`${i.line ? `:${i.line}` : ''}`,\n `- **Agent:** ${i.agent}`,\n `- **Score:** ${(result.score * 100).toFixed(0)}%`,\n `- **Date:** ${new Date(i.timestamp).toLocaleDateString()}`,\n `- **Fix:** ${i.fix.slice(0, 150)}${i.fix.length > 150 ? '...' : ''}`,\n '',\n );\n }\n\n return lines.join('\\n');\n }\n\n private async handleStats(workDir: string): Promise<string> {\n const stats = await getMemoryStats(workDir);\n const globalStats = await getGlobalMemoryStats();\n\n const lines: string[] = [\n '# Memory Statistics',\n '',\n '## Local Issue Memory',\n '',\n `- **Active Issues:** ${stats.activeIssues}`,\n `- **Resolved:** ${stats.resolvedCount}`,\n `- **Total (all-time):** ${stats.totalIssues}`,\n ];\n\n // Capacity warning\n const cap = stats.capacityInfo;\n if (cap.isAtCap) {\n lines.push(\n '',\n '### ⚠️ CAPACITY WARNING',\n '',\n `**Memory is at maximum capacity (${cap.current}/${cap.max} issues, ${cap.percentFull}%)**`,\n '',\n 'Trie caps issue storage at 10,000 for performance. New repeats are deduplicated.',\n 'Older issues are compacted into summaries, and if it still exceeds the cap the oldest/lowest-value issues are pruned.',\n '',\n '**Options to free up space:**',\n '- `trie memory purge smart` - Remove resolved and old low-priority issues (recommended)',\n '- `trie memory purge resolved` - Remove all resolved issues',\n '- `trie memory purge old` - Remove issues older than 90 days',\n '- `trie memory purge all` - Clear all issues (keeps summaries)',\n );\n } else if (cap.percentFull >= 80) {\n lines.push(\n '',\n `### ℹ️ Memory Usage: ${cap.percentFull}% (${cap.current}/${cap.max})`,\n '',\n `You're approaching the storage cap. Consider running \\`trie memory purge smart\\` to free up space.`,\n );\n } else {\n lines.push(`- **Memory Usage:** ${cap.percentFull}% (${cap.current}/${cap.max})`);\n }\n\n // Deduplication stats\n if (stats.deduplicationStats.duplicatesAvoided > 0) {\n lines.push(\n '',\n '### Deduplication',\n '',\n `- **Unique Patterns:** ${stats.deduplicationStats.uniquePatterns}`,\n `- **Duplicates Avoided:** ${stats.deduplicationStats.duplicatesAvoided}`,\n );\n }\n\n if (stats.oldestIssue) {\n lines.push('', `- **Date Range:** ${stats.oldestIssue.split('T')[0]} to ${stats.newestIssue?.split('T')[0]}`);\n }\n\n lines.push('', '### By Severity', '');\n for (const [severity, count] of Object.entries(stats.issuesBySeverity)) {\n lines.push(`- ${severity}: ${count}`);\n }\n\n lines.push('', '### By Agent', '');\n const sortedAgents = Object.entries(stats.issuesByAgent).sort((a, b) => b[1] - a[1]);\n for (const [agent, count] of sortedAgents.slice(0, 10)) {\n lines.push(`- ${agent}: ${count}`);\n }\n\n lines.push(\n '',\n '## Global Cross-Project Memory',\n '',\n `- **Tracked Projects:** ${globalStats.trackedProjects}`,\n `- **Total Patterns:** ${globalStats.totalPatterns}`,\n `- **Cross-Project Patterns:** ${globalStats.crossProjectPatterns}`,\n `- **Fixed Patterns:** ${globalStats.fixedPatterns}`,\n );\n\n return lines.join('\\n');\n }\n\n private async handleRecent(params: {\n limit?: number;\n }, workDir: string): Promise<string> {\n const issues = await getRecentIssues({\n workDir,\n limit: params.limit || 10,\n });\n\n if (issues.length === 0) {\n return 'No recent issues found.';\n }\n\n const lines: string[] = [\n '# Recent Issues (Last 7 Days)',\n '',\n ];\n\n for (const i of issues) {\n const status = i.resolved ? ' [RESOLVED]' : '';\n lines.push(\n `## [${i.severity.toUpperCase()}]${status} ${i.issue.slice(0, 70)}`,\n '',\n `- \\`${i.file}\\`${i.line ? `:${i.line}` : ''}`,\n `- Agent: ${i.agent} | ${new Date(i.timestamp).toLocaleDateString()}`,\n '',\n );\n }\n\n return lines.join('\\n');\n }\n\n private async handleSimilar(params: {\n query?: string;\n limit?: number;\n }, workDir: string): Promise<string> {\n if (!params.query) {\n return 'Missing required parameter: query (issue description to find similar issues for)';\n }\n\n const mockIssue = {\n id: 'search',\n severity: 'moderate' as const,\n issue: params.query,\n fix: '',\n file: '',\n agent: 'search',\n confidence: 1,\n autoFixable: false,\n };\n\n const results = await findSimilarIssues(mockIssue, {\n workDir,\n limit: params.limit || 5,\n });\n\n if (results.length === 0) {\n return 'No similar issues found.';\n }\n\n const lines: string[] = [\n `# Similar Issues`,\n '',\n `Found ${results.length} similar issue(s):`,\n '',\n ];\n\n for (const result of results) {\n const i = result.issue;\n lines.push(\n `## [${i.severity.toUpperCase()}] ${i.issue.slice(0, 70)}`,\n '',\n `- **File:** \\`${i.file}\\``,\n `- **Similarity:** ${(result.score * 100).toFixed(0)}%`,\n '',\n );\n }\n\n return lines.join('\\n');\n }\n\n private async handleResolve(params: {\n issueId?: string;\n }, workDir: string): Promise<string> {\n if (!params.issueId) {\n return 'Missing required parameter: issueId';\n }\n\n const result = await markIssueResolved(params.issueId, workDir);\n \n if (result) {\n return `Issue ${params.issueId} marked as resolved.`;\n }\n return `Issue ${params.issueId} not found.`;\n }\n\n private async handleGlobal(params: {\n query?: string;\n limit?: number;\n }): Promise<string> {\n if (params.query) {\n const patterns = await searchGlobalPatterns(params.query, {\n limit: params.limit || 10,\n });\n\n if (patterns.length === 0) {\n return `No global patterns found matching \"${params.query}\"`;\n }\n\n const lines: string[] = [\n `# Global Pattern Search: \"${params.query}\"`,\n '',\n ];\n\n for (const p of patterns) {\n lines.push(\n `## [${p.severity.toUpperCase()}] ${p.pattern.slice(0, 60)}`,\n '',\n `- **Occurrences:** ${p.occurrences} across ${p.projects.length} projects`,\n `- **Agent:** ${p.agent}`,\n `- **Projects:** ${p.projects.slice(0, 3).join(', ')}`,\n p.fixApplied ? `- **Fixed in:** ${p.fixApplied.project}` : '',\n '',\n );\n }\n\n return lines.join('\\n');\n }\n\n const patterns = await findCrossProjectPatterns(2);\n const projects = await listTrackedProjects();\n\n const lines: string[] = [\n '# Global Cross-Project Memory',\n '',\n `**Tracked Projects:** ${projects.length}`,\n `**Cross-Project Patterns:** ${patterns.length}`,\n '',\n ];\n\n if (patterns.length > 0) {\n lines.push('## Top Cross-Project Patterns', '');\n \n for (const p of patterns.slice(0, 5)) {\n lines.push(\n `### [${p.severity.toUpperCase()}] ${p.pattern.slice(0, 50)}`,\n '',\n `- Seen ${p.occurrences}x across ${p.projects.length} projects`,\n p.fixApplied ? `- Fixed in ${p.fixApplied.project}` : '- Not yet fixed',\n '',\n );\n }\n }\n\n if (projects.length > 0) {\n lines.push('## Recent Projects', '', '| Project | Issues |', '|---------|--------|');\n \n for (const p of projects.slice(0, 5)) {\n lines.push(`| ${p.name} | ${p.totalIssues} |`);\n }\n }\n\n return lines.join('\\n');\n }\n\n private async handlePurge(params: {\n purgeStrategy?: 'smart' | 'resolved' | 'old' | 'all';\n daysOld?: number;\n }, workDir: string): Promise<string> {\n const strategy = params.purgeStrategy || 'smart';\n \n const options: { workDir: string; daysOld?: number } = { workDir };\n if (params.daysOld !== undefined) {\n options.daysOld = params.daysOld;\n }\n \n const result = await purgeIssues(strategy, options);\n\n const lines: string[] = [\n '# Memory Purge Complete',\n '',\n `**Strategy:** ${strategy}`,\n `**Removed:** ${result.removed} issues`,\n `**Remaining:** ${result.remaining} issues`,\n '',\n ];\n\n switch (strategy) {\n case 'smart':\n lines.push(\n '**What was removed:**',\n '- Resolved issues older than 30 days',\n '- Low-priority issues (info/low severity) older than 30 days',\n '',\n '**What was kept:**',\n '- All critical and high severity issues',\n '- All unresolved issues',\n '- All issues from the last 30 days',\n );\n break;\n case 'resolved':\n lines.push('**Removed all resolved issues.**', '**Kept all unresolved issues.**');\n break;\n case 'old':\n lines.push(\n `**Removed all issues older than ${params.daysOld || 90} days.**`,\n `**Kept all recent issues.**`,\n );\n break;\n case 'all':\n lines.push(\n '**Cleared all issues from active memory.**',\n '',\n 'Historical summaries are preserved in compacted-summaries.json.',\n );\n break;\n }\n\n lines.push('', '**Note:** Compacted historical summaries were preserved for trend analysis.');\n\n return lines.join('\\n');\n }\n}\n","import path from 'node:path';\n\nimport { ContextGraph } from '../context/graph.js';\nimport { importFromJson } from '../context/sync.js';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\n\nasync function removeOrphanEdges(graph: ContextGraph): Promise<number> {\n const nodes = await graph.listNodes();\n const ids = new Set(nodes.map((n) => n.id));\n const edges = await graph.listEdges();\n let removed = 0;\n for (const edge of edges) {\n if (!ids.has(edge.from_id) || !ids.has(edge.to_id)) {\n await graph.deleteEdge(edge.id);\n removed++;\n }\n }\n return removed;\n}\n\nexport interface ReconcileToolInput {\n directory?: string;\n source?: string;\n}\n\nexport class TrieReconcileTool {\n async execute(input: ReconcileToolInput = {}): Promise<any> {\n try {\n const projectPath = input.directory || getWorkingDirectory(undefined, true);\n const sourcePath = input.source ?? path.join(getTrieDirectory(projectPath), 'context.json');\n\n const graph = new ContextGraph(projectPath);\n await importFromJson(graph, '', sourcePath);\n const removed = await removeOrphanEdges(graph);\n\n return {\n content: [{\n type: 'text',\n text: `Reconciled context from ${sourcePath}. Removed ${removed} orphaned edges.`\n }]\n };\n } catch (error) {\n const friendly = formatFriendlyError(error);\n return { content: [{ type: 'text', text: friendly.userMessage }] };\n }\n }\n}\n","import { ContextGraph } from '../context/graph.js';\nimport { exportToJson } from '../context/sync.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\n\nexport interface ContextToolInput {\n directory?: string;\n}\n\nexport class TrieContextTool {\n async execute(input: ContextToolInput = {}): Promise<any> {\n try {\n const workDir = input.directory || getWorkingDirectory(undefined, true);\n const graph = new ContextGraph(workDir);\n const snapshot = await graph.getSnapshot();\n await exportToJson(graph);\n\n const summary = `Nodes: ${snapshot.nodes.length}, Edges: ${snapshot.edges.length}, Exported: ${snapshot.exported_at}`;\n\n return {\n content: [{\n type: 'text',\n text: summary\n }],\n data: snapshot\n };\n } catch (error) {\n const friendly = formatFriendlyError(error);\n return { content: [{ type: 'text', text: friendly.userMessage }] };\n }\n }\n}\n","import { LinearIngester } from '../ingest/linear-ingester.js';\nimport { ContextGraph } from '../context/graph.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport interface LinearSyncInput {\n directory?: string;\n}\n\nexport class LinearSyncTool {\n async execute(input: LinearSyncInput): Promise<any> {\n try {\n const workDir = input.directory || getWorkingDirectory(undefined, true);\n const graph = new ContextGraph(workDir);\n const ingester = new LinearIngester(workDir, graph);\n\n await ingester.syncTickets();\n\n return {\n content: [{\n type: 'text',\n text: '✅ Linear tickets synced successfully. Trie now has context on your active tasks.'\n }]\n };\n } catch (error: any) {\n return {\n isError: true,\n content: [{\n type: 'text',\n text: `Failed to sync Linear tickets: ${error.message}`\n }]\n };\n }\n }\n}\n","import { GitHubIngester } from '../ingest/github-ingester.js';\nimport { ContextGraph } from '../context/graph.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport interface GitHubSyncInput {\n directory?: string;\n}\n\nexport class GitHubSyncTool {\n async execute(input: GitHubSyncInput): Promise<any> {\n try {\n const workDir = input.directory || getWorkingDirectory(undefined, true);\n const graph = new ContextGraph(workDir);\n const ingester = new GitHubIngester(graph);\n\n const token = await ingester.getApiToken();\n if (!token) {\n return {\n isError: true,\n content: [{\n type: 'text',\n text: 'GitHub token not configured.\\n\\n' +\n 'Set one of:\\n' +\n ' • Environment variable: GITHUB_TOKEN=ghp_...\\n' +\n ' • Config dialog (C key) → API Keys → GitHub\\n' +\n ' • .trie/config.json: { \"apiKeys\": { \"github\": \"ghp_...\" } }\\n\\n' +\n 'Token needs `repo` scope for private repos, `public_repo` for public.',\n }],\n };\n }\n\n const repoInfo = ingester.getRepoInfo(workDir);\n if (!repoInfo) {\n return {\n isError: true,\n content: [{\n type: 'text',\n text: 'Could not detect GitHub repository.\\n\\n' +\n 'Make sure this directory is a git repo with a GitHub remote:\\n' +\n ' git remote get-url origin',\n }],\n };\n }\n\n const prResult = await ingester.syncPullRequests(repoInfo.owner, repoInfo.name, token);\n const issueResult = await ingester.syncIssues(repoInfo.owner, repoInfo.name, token);\n\n const LINE = '\\u2500'.repeat(45);\n const lines = [\n 'GITHUB SYNC',\n LINE,\n `Repo: ${repoInfo.owner}/${repoInfo.name}`,\n `Pulled ${prResult.prs} open PR${prResult.prs !== 1 ? 's' : ''}, ${issueResult.issues} open issue${issueResult.issues !== 1 ? 's' : ''}`,\n `Linked ${prResult.linkedTickets} PR${prResult.linkedTickets !== 1 ? 's' : ''} to Linear tickets`,\n `Linked ${prResult.linkedFiles} PR${prResult.linkedFiles !== 1 ? 's' : ''} to changed files in context graph`,\n LINE,\n 'Next sync: trie_github_sync',\n 'Or use trie_pipeline for consolidated view.',\n ];\n\n return {\n content: [{\n type: 'text',\n text: lines.join('\\n'),\n }],\n };\n } catch (error: any) {\n return {\n isError: true,\n content: [{\n type: 'text',\n text: `GitHub sync failed: ${error.message}`,\n }],\n };\n }\n }\n}\n","/**\n * Trie Index Tool\n * \n * MCP tool for indexing the codebase for fast goal checking and file lookups.\n * The index is automatically updated when files change during watch mode,\n * but this tool allows manual full indexing.\n */\n\nimport { glob } from 'glob';\nimport { CodebaseIndex } from '../context/codebase-index.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { isTrieInitialized } from '../utils/trie-init.js';\n\nconst INDEXABLE_EXTENSIONS = [\n 'ts', 'tsx', 'js', 'jsx', 'mjs',\n 'vue', 'svelte', 'astro',\n 'py', 'go', 'rs', 'java', 'c', 'cpp', 'h', 'hpp',\n 'cs', 'rb', 'php', 'css', 'scss', 'html',\n];\n\nexport class TrieIndexTool {\n async execute(params: {\n action?: 'full' | 'status' | 'clear';\n directory?: string;\n }): Promise<string> {\n const action = params.action || 'full';\n const workDir = getWorkingDirectory(params.directory, true);\n\n if (!isTrieInitialized(workDir)) {\n return 'Trie is not initialized for this project. Run `trie init` first.';\n }\n\n const codebaseIndex = new CodebaseIndex(workDir);\n\n if (action === 'status') {\n const stats = codebaseIndex.getStats();\n \n let lastUpdatedStr = 'Never';\n if (stats.lastUpdated) {\n try {\n const date = new Date(stats.lastUpdated);\n lastUpdatedStr = date.toLocaleString('en-US', {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n hour: 'numeric',\n minute: '2-digit',\n });\n } catch {\n lastUpdatedStr = 'Unknown';\n }\n }\n \n return [\n '# Codebase Index Status',\n '',\n `**Total files indexed:** ${stats.totalFiles}`,\n `**Total size:** ${(stats.totalSize / 1024 / 1024).toFixed(2)} MB`,\n `**Files scanned for goals:** ${stats.scannedFiles}`,\n `**Files with violations:** ${stats.filesWithViolations}`,\n `**Last updated:** ${lastUpdatedStr}`,\n '',\n '## Files by Type',\n '',\n ...Object.entries(stats.filesByType)\n .sort(([, a], [, b]) => b - a)\n .slice(0, 10)\n .map(([type, count]) => `- .${type}: ${count} files`),\n '',\n '---',\n '',\n 'Run `trie_index` with action=\"full\" to re-index the codebase.',\n 'Run `trie_index` with action=\"clear\" to clear stale cache entries.',\n ].join('\\n');\n }\n\n if (action === 'clear') {\n const cleared = codebaseIndex.clearStaleCache();\n await codebaseIndex.save();\n return `Cleared ${cleared} stale cache entries.`;\n }\n\n // Full indexing\n const pattern = `${workDir}/**/*.{${INDEXABLE_EXTENSIONS.join(',')}}`;\n const allFiles = await glob(pattern, {\n ignore: ['**/node_modules/**', '**/dist/**', '**/build/**', '**/.git/**', '**/.trie/**', '**/coverage/**'],\n nodir: true,\n });\n\n let indexed = 0;\n let failed = 0;\n const startTime = Date.now();\n\n // Process files in batches to avoid overwhelming the system\n const BATCH_SIZE = 50;\n for (let i = 0; i < allFiles.length; i += BATCH_SIZE) {\n const batch = allFiles.slice(i, i + BATCH_SIZE);\n \n await Promise.all(batch.map(async (filePath) => {\n try {\n // Get relative path (handle case-insensitive filesystems)\n let relativePath = filePath;\n if (filePath.toLowerCase().startsWith(workDir.toLowerCase() + '/')) {\n relativePath = filePath.slice(workDir.length + 1);\n }\n \n const result = await codebaseIndex.indexFile(relativePath);\n if (result) {\n indexed++;\n } else {\n failed++;\n }\n } catch {\n failed++;\n }\n }));\n }\n\n await codebaseIndex.save();\n const duration = ((Date.now() - startTime) / 1000).toFixed(1);\n const stats = codebaseIndex.getStats();\n\n return [\n '# Codebase Indexing Complete',\n '',\n `**Files indexed:** ${indexed}`,\n `**Files failed:** ${failed}`,\n `**Duration:** ${duration}s`,\n '',\n '## Index Statistics',\n '',\n `- Total files: ${stats.totalFiles}`,\n `- Total size: ${(stats.totalSize / 1024 / 1024).toFixed(2)} MB`,\n '',\n '## Files by Type',\n '',\n ...Object.entries(stats.filesByType)\n .sort(([, a], [, b]) => b - a)\n .slice(0, 10)\n .map(([type, count]) => `- .${type}: ${count} files`),\n '',\n '---',\n '',\n 'The index will be automatically updated when files change during watch mode.',\n 'Goal checks will now use cached results for unchanged files.',\n ].join('\\n');\n }\n}\n","import { TrieScanTool } from '../tools/scan.js';\nimport { TrieFixTool } from '../tools/fix.js';\nimport { TrieCloudFixTool } from '../tools/cloud-fix.js';\nimport { TrieExplainTool } from '../tools/explain.js';\nimport { TrieTestTool } from '../tools/test.js';\nimport { TrieWatchTool } from '../tools/watch.js';\nimport { TriePRReviewTool } from '../tools/pr-review.js';\nimport { TrieProjectInfoTool } from '../tools/project-info.js';\nimport { TrieInitTool } from '../tools/init.js';\nimport { TrieMemorySearchTool } from '../tools/memory-search.js';\nimport { handleCheckpointTool, type CheckpointToolInput } from '../tools/checkpoint.js';\nimport { TrieCheckTool } from '../tools/check.js';\nimport { TrieTellTool } from '../tools/tell.js';\nimport { TrieReconcileTool } from '../tools/reconcile.js';\nimport { TrieContextTool } from '../tools/context.js';\nimport { TrieFeedbackTool } from '../tools/feedback.js';\nimport { LinearSyncTool } from '../tools/linear-sync.js';\nimport { GitHubSyncTool } from '../tools/github-sync.js';\nimport { GitHubBranchesTool } from '../tools/github-branches.js';\nimport { TriePipelineTool } from '../tools/pipeline.js';\nimport { TrieIndexTool } from '../tools/index-codebase.js';\nimport { \n TrieGetGovernanceTool,\n TrieGetDecisionsTool,\n TrieGetBlockersTool, \n TrieGetRelatedGovernanceTool,\n TrieGetRelatedDecisionsTool,\n TrieQueryContextTool \n} from '../tools/query-tools.js';\n\nclass TrieCheckpointTool {\n async execute(input: CheckpointToolInput): Promise<any> {\n const result = await handleCheckpointTool(input);\n return {\n content: [{\n type: 'text',\n text: result\n }]\n };\n }\n}\n\nexport interface ToolDefinition {\n name: string;\n description: string;\n inputSchema: Record<string, any>;\n _meta?: {\n ui?: {\n resourceUri: string;\n };\n };\n}\n\nexport class ToolRegistry {\n private tools: Map<string, any> = new Map();\n private definitions: ToolDefinition[] = [];\n\n constructor() {\n this.initializeTools();\n this.defineToolSchemas();\n }\n\n private initializeTools() {\n // Initialize tool instances\n this.tools.set('scan', new TrieScanTool());\n this.tools.set('fix', new TrieFixTool());\n this.tools.set('cloud_fix', new TrieCloudFixTool());\n this.tools.set('explain', new TrieExplainTool());\n this.tools.set('test', new TrieTestTool());\n this.tools.set('watch', new TrieWatchTool());\n this.tools.set('pr_review', new TriePRReviewTool());\n this.tools.set('project', new TrieProjectInfoTool());\n this.tools.set('init', new TrieInitTool());\n this.tools.set('memory', new TrieMemorySearchTool());\n this.tools.set('checkpoint', new TrieCheckpointTool());\n this.tools.set('check', new TrieCheckTool());\n this.tools.set('tell', new TrieTellTool());\n this.tools.set('reconcile', new TrieReconcileTool());\n this.tools.set('context', new TrieContextTool());\n this.tools.set('feedback', new TrieFeedbackTool());\n this.tools.set('ok', new TrieFeedbackTool());\n this.tools.set('bad', new TrieFeedbackTool());\n this.tools.set('linear_sync', new LinearSyncTool());\n this.tools.set('github_sync', new GitHubSyncTool());\n this.tools.set('github_branches', new GitHubBranchesTool());\n this.tools.set('pipeline', new TriePipelineTool());\n this.tools.set('index', new TrieIndexTool());\n \n // Query tools for governance ledger\n this.tools.set('get_governance', new TrieGetGovernanceTool());\n this.tools.set('get_decisions', new TrieGetDecisionsTool()); // Backward compatibility\n this.tools.set('get_blockers', new TrieGetBlockersTool());\n this.tools.set('get_related_governance', new TrieGetRelatedGovernanceTool());\n this.tools.set('get_related_decisions', new TrieGetRelatedDecisionsTool()); // Backward compatibility\n this.tools.set('query_context', new TrieQueryContextTool());\n }\n\n private defineToolSchemas() {\n this.definitions = [\n {\n name: 'trie_scan',\n description: 'Scan code with intelligent agent selection. Scans entire codebase if no files specified. Auto-updates .trie/AGENTS.md with results. Alias: scan',\n inputSchema: {\n type: 'object',\n properties: {\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Files to scan (absolute paths). If empty, scans entire codebase.'\n },\n directory: {\n type: 'string',\n description: 'Directory to scan (if files not specified). Defaults to current working directory.'\n },\n context: {\n type: 'object',\n properties: {\n changeType: {\n type: 'string',\n enum: ['ui', 'api', 'database', 'auth', 'payment', 'general']\n },\n isNewFeature: { type: 'boolean' },\n touchesUserData: { type: 'boolean' }\n }\n },\n forceAgents: {\n type: 'array',\n items: { type: 'string' },\n description: 'Manually specify agents to run (overrides triaging)'\n },\n parallel: {\n type: 'boolean',\n description: 'Run agents in parallel (default true)'\n },\n cache: {\n type: 'boolean',\n description: 'Enable scan result caching (default true)'\n },\n maxConcurrency: {\n type: 'number',\n description: 'Max parallel agents'\n },\n timeoutMs: {\n type: 'number',\n description: 'Agent timeout in milliseconds'\n },\n streaming: {\n type: 'boolean',\n description: 'Stream progress updates'\n },\n interactive: {\n type: 'boolean',\n description: 'Enable interactive CLI dashboard (TTY only)'\n },\n format: {\n type: 'string',\n enum: ['text', 'json'],\n description: 'Output format for optional file output'\n },\n output: {\n type: 'string',\n description: 'Output file path when format is json'\n },\n workers: {\n type: 'boolean',\n description: 'Use worker threads for parallel execution'\n }\n }\n } as const,\n // MCP Apps: Interactive scan dashboard\n _meta: {\n ui: { resourceUri: 'ui://trie/scan-dashboard' }\n },\n },\n {\n name: 'trie',\n description: 'Quick menu of available Trie commands. TIP: Read trie://context first for project state and priorities. Call with `action` to run directly.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n description: 'Optional quick action: scan, security, legal, bugs, types, devops, architecture, ux, clean, soc2, performance, e2e, visual_qa, data_flow, agent_smith, pr_review, watch, fix, explain'\n },\n agent: {\n type: 'string',\n description: 'Agent key when action=agent or when using a custom skill name'\n },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Files to scan (absolute or relative)'\n },\n directory: {\n type: 'string',\n description: 'Directory to scan (defaults to detected workspace)'\n },\n context: {\n type: 'object',\n properties: {\n changeType: {\n type: 'string',\n enum: ['ui', 'api', 'database', 'auth', 'payment', 'general']\n },\n isNewFeature: { type: 'boolean' },\n touchesUserData: { type: 'boolean' }\n }\n }\n }\n } as const,\n },\n {\n name: 'trie_fix',\n description: 'Apply high-confidence fixes to code. Use action:route to see triage plan first. Alias: fix',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['route'],\n description: 'route: show fix routing plan without applying fixes'\n },\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_cloud_fix',\n description: 'Dispatch issues to Cursor cloud agents for verified, test-passing fixes. The cloud agent runs in an isolated VM, applies the fix, runs tests, screenshots the result, and opens a PR. Use trie_fix action:route first to see which issues qualify.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['configure', 'dispatch', 'status', 'artifacts', 'cancel'],\n description: 'configure: save API key | dispatch: send to cloud | status: poll jobs | artifacts: get screenshots + PR links | cancel: abort a job'\n },\n issueIds: {\n type: 'array',\n items: { type: 'string' },\n description: 'Issue IDs to dispatch (from trie_scan). If omitted, dispatches all cloud-eligible pending issues.'\n },\n apiKey: {\n type: 'string',\n description: 'Cursor API key (configure action only)'\n },\n jobId: {\n type: 'string',\n description: 'Job ID for cancel or artifacts actions'\n }\n },\n required: ['action']\n } as const,\n },\n {\n name: 'trie_explain',\n description: 'Explain code, issues, or changes in plain language. Alias: explain',\n inputSchema: {\n type: 'object',\n properties: {\n type: {\n type: 'string',\n enum: ['code', 'issue', 'change', 'risk']\n },\n target: {\n type: 'string',\n description: 'What to explain (file path, issue ID, etc.)'\n }\n },\n required: ['type', 'target']\n } as const,\n },\n {\n name: 'trie_feedback',\n description: 'Record quick feedback about a warning or suggestion (thumbs up/down). Alias: trie_ok, trie_bad',\n inputSchema: {\n type: 'object',\n properties: {\n helpful: { type: 'boolean', description: 'true for 👍, false for 👎' },\n target: { type: 'string', description: 'Optional file or item being rated' },\n note: { type: 'string', description: 'Optional short note about why' },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Optional related files (absolute or relative)'\n },\n directory: { type: 'string', description: 'Working directory (defaults to auto-detected)' }\n },\n required: ['helpful']\n } as const,\n },\n {\n name: 'trie_check',\n description: 'Run Trie risk check on current changes. Modes: quick, full, offline.',\n inputSchema: {\n type: 'object',\n properties: {\n directory: { type: 'string' },\n files: { type: 'array', items: { type: 'string' } },\n mode: { type: 'string', enum: ['quick', 'full', 'offline'] }\n }\n }\n },\n {\n name: 'trie_tell',\n description: 'Report an incident so Trie can learn.',\n inputSchema: {\n type: 'object',\n properties: {\n description: { type: 'string' },\n directory: { type: 'string' }\n },\n required: ['description']\n }\n },\n {\n name: 'trie_reconcile',\n description: 'Re-sync context graph from context.json and clean orphaned edges.',\n inputSchema: {\n type: 'object',\n properties: {\n directory: { type: 'string' },\n source: { type: 'string' }\n }\n }\n },\n {\n name: 'trie_context',\n description: 'Return current context snapshot (nodes/edges) and export context.json.',\n inputSchema: {\n type: 'object',\n properties: {\n directory: { type: 'string' }\n }\n }\n },\n {\n name: 'trie_test',\n description: 'Generate or reason about tests. Alias: test',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['generate', 'coverage', 'suggest', 'run'],\n description: 'Test action to perform'\n },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Target source files'\n },\n framework: {\n type: 'string',\n description: 'Optional framework hint (jest, vitest, playwright, etc.)'\n },\n style: {\n type: 'string',\n description: 'Test style (unit, integration, e2e). Defaults to unit.'\n }\n },\n required: ['action', 'files']\n } as const,\n },\n {\n name: 'trie_watch',\n description: 'Autonomous watch mode. Alias: watch',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['start', 'stop', 'status', 'issues'],\n description: 'Watch action'\n },\n directory: {\n type: 'string',\n description: 'Workspace directory to watch (optional, auto-detected)'\n },\n debounceMs: {\n type: 'number',\n description: 'Debounce time for scans (ms)'\n }\n },\n required: ['action']\n } as const,\n },\n {\n name: 'trie_project',\n description: 'View and manage project information (.trie/PROJECT.md). Store project context for AI assistants. Alias: project',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['view', 'init', 'update', 'append', 'sections', 'raw'],\n description: 'Action: view (default), init (create template), update (replace section), append (add to section), sections (list), raw (full file)'\n },\n section: {\n type: 'string',\n description: 'Section name (e.g., \"Project Overview\", \"Technology Stack\", \"AI Instructions\")'\n },\n content: {\n type: 'string',\n description: 'Content for update/append actions'\n },\n directory: {\n type: 'string',\n description: 'Project directory (defaults to current workspace)'\n }\n }\n } as const,\n },\n {\n name: 'trie_init',\n description: 'Initialize bootstrap files (.trie/RULES.md, .trie/TEAM.md, .trie/BOOTSTRAP.md). Detects stack and suggests skills.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['init', 'status', 'complete', 'context'],\n description: 'Action: init (create files), status (check state), complete (finish bootstrap), context (get injected content)'\n },\n directory: {\n type: 'string',\n description: 'Project directory (defaults to current workspace)'\n },\n force: {\n type: 'boolean',\n description: 'Overwrite existing files'\n },\n skipBootstrap: {\n type: 'boolean',\n description: 'Skip creating BOOTSTRAP.md'\n }\n }\n } as const,\n },\n {\n name: 'trie_memory',\n description: 'Search and manage issue memory. Find similar issues, view stats, search across projects, and purge old issues.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['search', 'stats', 'recent', 'similar', 'resolve', 'global', 'purge'],\n description: 'Action: search (find issues), stats (show statistics), recent (recent issues), similar (find similar), resolve (mark resolved), global (cross-project), purge (free up memory)'\n },\n query: {\n type: 'string',\n description: 'Search query for search/similar/global actions'\n },\n issueId: {\n type: 'string',\n description: 'Issue ID for resolve action'\n },\n limit: {\n type: 'number',\n description: 'Maximum results to return'\n },\n severity: {\n type: 'array',\n items: { type: 'string' },\n description: 'Filter by severity levels'\n },\n agent: {\n type: 'string',\n description: 'Filter by agent name'\n },\n includeResolved: {\n type: 'boolean',\n description: 'Include resolved issues in search'\n },\n directory: {\n type: 'string',\n description: 'Project directory (defaults to current workspace)'\n },\n purgeStrategy: {\n type: 'string',\n enum: ['smart', 'resolved', 'old', 'all'],\n description: 'Purge strategy: smart (remove resolved & old low-priority), resolved (all resolved), old (older than daysOld), all (clear all)'\n },\n daysOld: {\n type: 'number',\n description: 'Days threshold for old purge strategy (default 90)'\n }\n }\n } as const,\n // MCP Apps: Interactive memory viewer\n _meta: {\n ui: { resourceUri: 'ui://trie/memory-viewer' }\n },\n },\n {\n name: 'trie_checkpoint',\n description: 'Save a context checkpoint without running a full scan. Quick save for your current work state.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['save', 'list', 'last'],\n description: 'Action: save (create checkpoint), list (show recent), last (show last checkpoint)'\n },\n message: {\n type: 'string',\n description: 'Checkpoint message (what you were working on)'\n },\n notes: {\n type: 'string',\n description: 'Additional notes'\n },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Files to associate with this checkpoint'\n }\n },\n required: ['action']\n } as const,\n },\n {\n name: 'trie_index',\n description: 'Index codebase for fast goal checking and file lookups. Index is auto-updated during watch mode. Use this for initial indexing or to rebuild the index.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['full', 'status', 'clear'],\n description: 'Action: full (index all files), status (show index stats), clear (remove stale cache)'\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.createSpecialAgentDefinitions(),\n ].flat();\n }\n\n private createSpecialAgentDefinitions(): ToolDefinition[] {\n return [\n {\n name: 'trie_visual_qa_browser',\n description: 'Capture screenshots at mobile/tablet/desktop viewports for visual QA. Alias: visual_qa_browser',\n inputSchema: {\n type: 'object',\n properties: {\n url: { type: 'string', description: 'URL to screenshot' },\n port: { type: 'number', description: 'Specific port to check' },\n waitForSelector: { type: 'string', description: 'CSS selector to wait for' },\n waitMs: { type: 'number', description: 'Additional wait time' }\n }\n } as const,\n // MCP Apps: Interactive visual QA gallery\n _meta: {\n ui: { resourceUri: 'ui://trie/visual-qa' }\n },\n },\n {\n name: 'trie_pr_review',\n description: '🔍 Interactive PR review: walks through changes file-by-file. Alias: pr_review',\n inputSchema: {\n type: 'object',\n properties: {\n pr: { type: 'string', description: 'PR number to review' },\n worktree: { type: 'string', description: 'Path to worktree directory' },\n mode: {\n type: 'string',\n enum: ['own', 'others'],\n description: 'Review mode'\n },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Specific files to review'\n }\n }\n } as const,\n // MCP Apps: Interactive PR review UI\n _meta: {\n ui: { resourceUri: 'ui://trie/pr-review' }\n },\n },\n {\n name: 'trie_linear_sync',\n description: 'Sync active Linear tickets to build context for JIT defect prediction. Alias: linear_sync',\n inputSchema: {\n type: 'object',\n properties: {\n directory: { type: 'string', description: 'Project directory' }\n }\n }\n },\n {\n name: 'trie_github_sync',\n description: 'Sync open PRs and issues from GitHub into the Trie context graph. Links PRs to files they touch and to Linear tickets mentioned in PR descriptions. Run once to initialize, or periodically to stay current.',\n inputSchema: {\n type: 'object',\n properties: {\n directory: { type: 'string', description: 'Project directory (defaults to current workspace)' }\n }\n }\n },\n {\n name: 'trie_github_branches',\n description: 'Fetch GitHub branches with latest commit info. Use when the user asks which branch has the latest updates, what branches exist, or when branches were last updated. Requires GitHub API key.',\n inputSchema: {\n type: 'object',\n properties: {\n directory: { type: 'string', description: 'Project directory (defaults to current workspace)' },\n limit: { type: 'number', description: 'Max branches to return (default 15, max 30)' }\n }\n }\n },\n {\n name: 'trie_pipeline',\n description: 'Get consolidated pipeline status: open PRs, active Linear tickets, open GitHub issues, and Trie scan issues not yet in any ticket or PR (coverage gaps). Use to understand where work stands and what is falling through the cracks.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['status', 'coverage', 'create_tickets'],\n description: 'status: full pipeline view | coverage: only show Trie issues with no ticket/PR | create_tickets: open Linear tickets for uncovered issues'\n },\n focus: {\n type: 'string',\n description: 'Optional file path or Linear ticket ID to narrow the view'\n },\n issueIds: {\n type: 'array',\n items: { type: 'string' },\n description: 'Issue IDs to create tickets for (create_tickets action only)'\n },\n directory: { type: 'string', description: 'Project directory' }\n }\n }\n },\n {\n name: 'trie_get_governance',\n description: 'Query governance records (architectural decisions, standards, team agreements) from governance ledger with targeted retrieval. Prevents context pollution by returning only relevant records.',\n inputSchema: {\n type: 'object',\n properties: {\n relatedTo: { type: 'string', description: 'File path or topic to find related governance' },\n tags: { type: 'array', items: { type: 'string' }, description: 'Filter by tags' },\n since: { type: 'string', description: 'Time filter: ISO date or \"7d\", \"30d\", \"90d\"' },\n limit: { type: 'number', description: 'Max results (default 10)' },\n directory: { type: 'string', description: 'Working directory' }\n }\n }\n },\n {\n name: 'trie_get_decisions',\n description: '[DEPRECATED - use trie_get_governance] Query governance records from ledger. Backward compatibility alias.',\n inputSchema: {\n type: 'object',\n properties: {\n relatedTo: { type: 'string', description: 'File path or topic to find related governance' },\n tags: { type: 'array', items: { type: 'string' }, description: 'Filter by tags' },\n since: { type: 'string', description: 'Time filter: ISO date or \"7d\", \"30d\", \"90d\"' },\n limit: { type: 'number', description: 'Max results (default 10)' },\n directory: { type: 'string', description: 'Working directory' }\n }\n }\n },\n {\n name: 'trie_get_blockers',\n description: 'Get active blockers from governance ledger. Returns only unresolved blockers to avoid noise.',\n inputSchema: {\n type: 'object',\n properties: {\n tags: { type: 'array', items: { type: 'string' }, description: 'Filter by tags' },\n limit: { type: 'number', description: 'Max results (default 5)' },\n directory: { type: 'string', description: 'Working directory' }\n }\n }\n },\n {\n name: 'trie_get_related_governance',\n description: 'Find governance records related to a specific governance record, file, or topic. Targeted context retrieval.',\n inputSchema: {\n type: 'object',\n properties: {\n governanceId: { type: 'string', description: 'Governance ID to find related records' },\n file: { type: 'string', description: 'File path to find related governance' },\n topic: { type: 'string', description: 'Topic to find related governance' },\n limit: { type: 'number', description: 'Max results (default 5)' },\n directory: { type: 'string', description: 'Working directory' }\n }\n }\n },\n {\n name: 'trie_get_related_decisions',\n description: '[DEPRECATED - use trie_get_related_governance] Find related governance records. Backward compatibility alias.',\n inputSchema: {\n type: 'object',\n properties: {\n decisionId: { type: 'string', description: 'Decision ID to find related records' },\n file: { type: 'string', description: 'File path to find related governance' },\n topic: { type: 'string', description: 'Topic to find related governance' },\n limit: { type: 'number', description: 'Max results (default 5)' },\n directory: { type: 'string', description: 'Working directory' }\n }\n }\n },\n {\n name: 'trie_query_context',\n description: 'Natural-language search across ALL Trie context: goals, hypotheses, nudges (goal violations), governance, blockers. Use for \"what are my goals\", \"show hypotheses\", \"any nudges\", \"recent governance\", etc.',\n inputSchema: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'Natural language query (e.g. goals, hypotheses, nudges, governance)' },\n type: { \n type: 'string', \n enum: ['goals', 'hypotheses', 'nudges', 'governance', 'decisions', 'blockers', 'facts', 'questions', 'all'],\n description: 'Type of context to query (default: all). \"decisions\" is deprecated, use \"governance\"'\n },\n limit: { type: 'number', description: 'Max results per type (default 10)' },\n directory: { type: 'string', description: 'Working directory' }\n },\n required: ['query']\n }\n }\n ];\n }\n\n getTool(name: string): any {\n return this.tools.get(name);\n }\n\n getAllTools(): ToolDefinition[] {\n return this.definitions;\n }\n\n getToolNames(): string[] {\n return Array.from(this.tools.keys());\n }\n\n hasTool(name: string): boolean {\n return this.tools.has(name);\n }\n}","import { readdir, readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join, dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport { getSkillRegistry } from '../skills/built-in/registry.js';\nimport { loadConfig } from '../config/loader.js';\nimport { getContextForAI, loadContextState } from '../utils/context-state.js';\nimport { loadProjectInfo, projectInfoExists } from '../utils/project-info.js';\nimport { listInstalledSkills } from '../skills/installer.js';\nimport { loadBootstrapContext, loadRules, loadTeamInfo } from '../bootstrap/index.js';\nimport { getMemoryStats, getRecentIssues } from '../memory/issue-store.js';\nimport { getGlobalMemoryStats, findCrossProjectPatterns } from '../memory/global-memory.js';\n\nexport interface Resource {\n uri: string;\n name: string;\n description?: string;\n mimeType?: string;\n}\n\nexport interface ResourceContent {\n contents: Array<{\n uri: string;\n mimeType?: string;\n text: string;\n }>;\n}\n\n// UI App definitions for MCP Apps\nconst UI_APPS = {\n 'ledger': {\n name: 'Decision Ledger',\n description: 'Track decisions, blockers, facts, and questions across your project',\n },\n 'goals': {\n name: 'Goals & Progress',\n description: 'Monitor code quality goals and track progress with visual indicators',\n },\n 'hypotheses': {\n name: 'Hypotheses',\n description: 'Test and validate development theories with evidence-based reasoning',\n },\n 'nudges': {\n name: 'Nudges & Insights',\n description: 'AI-powered code quality insights, warnings, and suggestions',\n },\n 'chat': {\n name: 'AI Chat',\n description: 'Interactive chat with Trie assistant for code analysis and guidance',\n },\n} as const;\n\ntype UIAppId = keyof typeof UI_APPS;\n\nexport class ResourceManager {\n private skillRegistry = getSkillRegistry();\n\n /**\n * Get all available resources dynamically\n */\n async getAvailableResources(): Promise<Resource[]> {\n const resources: Resource[] = [];\n\n // Static resources\n resources.push(\n {\n uri: 'trie://context',\n name: 'AI Context (Consolidated)',\n description: 'Single source of truth: project state, coding rules, recent issues, and cross-project patterns. Read this first.',\n mimeType: 'text/markdown',\n },\n {\n uri: 'trie://project',\n name: 'Project Information',\n description: 'User-defined project context (description, conventions, architecture, AI instructions)',\n mimeType: 'text/markdown',\n },\n {\n uri: 'trie://context/state',\n name: 'Context State',\n description: 'Detailed context state with scan history and priorities',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://skills',\n name: 'Available Skills',\n description: 'List of all available Trie skills (built-in and custom)',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://config',\n name: 'Trie Configuration',\n description: 'Current Trie configuration settings',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://cache/stats',\n name: 'Cache Statistics',\n description: 'Trie scan cache statistics and performance metrics',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://signatures',\n name: 'Vulnerability Signatures',\n description: 'Summary of loaded vulnerability detection signatures',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://skills/installed',\n name: 'Installed Skills',\n description: 'External skills installed from skills.sh that Trie can apply',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://bootstrap',\n name: 'Bootstrap Status',\n description: 'Bootstrap file status and project setup context',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://rules',\n name: 'Project Rules',\n description: 'User-defined coding standards from .trie/RULES.md',\n mimeType: 'text/markdown',\n },\n {\n uri: 'trie://team',\n name: 'Team Info',\n description: 'Team ownership and escalation from .trie/TEAM.md',\n mimeType: 'text/markdown',\n },\n {\n uri: 'trie://memory',\n name: 'Issue Memory',\n description: 'Issue memory statistics and recent issues',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://memory/global',\n name: 'Global Memory',\n description: 'Cross-project patterns and statistics',\n mimeType: 'application/json',\n }\n );\n\n // Dynamic resources: scan reports\n resources.push(...await this.getScanReportResources());\n\n // Dynamic resources: custom skills\n resources.push(...await this.getCustomSkillResources());\n\n // UI App resources (MCP Apps)\n resources.push(...this.getUIAppResources());\n\n return resources;\n }\n\n private async getScanReportResources(): Promise<Resource[]> {\n try {\n const reportsDir = join(getWorkingDirectory(undefined, true), 'trie-reports');\n const files = await readdir(reportsDir);\n const reportFiles = files.filter(f => f.endsWith('.txt') || f.endsWith('.json'));\n\n return reportFiles.slice(0, 10).map(file => ({\n uri: `trie://reports/${file}`,\n name: `Scan Report: ${file}`,\n description: `Trie scan report from ${file}`,\n mimeType: file.endsWith('.json') ? 'application/json' : 'text/plain',\n }));\n } catch {\n return []; // No reports directory yet\n }\n }\n\n private async getCustomSkillResources(): Promise<Resource[]> {\n try {\n await this.skillRegistry.loadCustomSkills();\n const customSkills = this.skillRegistry.getCustomSkills();\n\n return customSkills.map(skill => ({\n uri: `trie://skills/custom/${skill.name}`,\n name: `Custom Skill: ${skill.name}`,\n description: skill.description,\n mimeType: 'application/json',\n }));\n } catch {\n return []; // No custom skills\n }\n }\n\n /**\n * Read content for a specific resource\n */\n async readResourceContent(uri: string): Promise<ResourceContent> {\n // Handle UI App resources (MCP Apps)\n if (uri.startsWith('ui://trie/')) {\n const appId = uri.replace('ui://trie/', '');\n return await this.getUIAppResource(uri, appId);\n }\n\n const parsedUri = uri.replace('trie://', '');\n\n // Handle AI context (read this first!)\n if (parsedUri === 'context') {\n return await this.getContextResource(uri);\n }\n\n // Handle project info (user-defined context)\n if (parsedUri === 'project') {\n return await this.getProjectResource(uri);\n }\n\n // Handle context state (detailed JSON)\n if (parsedUri === 'context/state') {\n return await this.getContextStateResource(uri);\n }\n\n // Handle built-in skills list\n if (parsedUri === 'skills') {\n return await this.getBuiltInSkillsResource(uri);\n }\n\n // Handle specific custom skill\n if (parsedUri.startsWith('skills/custom/')) {\n return await this.getCustomSkillResource(uri, parsedUri);\n }\n\n // Handle configuration\n if (parsedUri === 'config') {\n return await this.getConfigResource(uri);\n }\n\n // Handle cache stats\n if (parsedUri === 'cache/stats') {\n return await this.getCacheStatsResource(uri);\n }\n\n // Handle vulnerability signatures\n if (parsedUri === 'signatures') {\n return await this.getSignaturesResource(uri);\n }\n\n // Handle installed skills\n if (parsedUri === 'skills/installed') {\n return await this.getInstalledSkillsResource(uri);\n }\n\n // Handle bootstrap status\n if (parsedUri === 'bootstrap') {\n return await this.getBootstrapResource(uri);\n }\n\n // Handle rules\n if (parsedUri === 'rules') {\n return await this.getRulesResource(uri);\n }\n\n // Handle team info\n if (parsedUri === 'team') {\n return await this.getTeamResource(uri);\n }\n\n // Handle memory\n if (parsedUri === 'memory') {\n return await this.getMemoryResource(uri);\n }\n\n // Handle global memory\n if (parsedUri === 'memory/global') {\n return await this.getGlobalMemoryResource(uri);\n }\n\n // Handle scan reports\n if (parsedUri.startsWith('reports/')) {\n return await this.getScanReportResource(uri, parsedUri);\n }\n\n throw new Error(`Unknown resource: ${uri}`);\n }\n\n /**\n * Get UI App resources for MCP Apps\n */\n private getUIAppResources(): Resource[] {\n return Object.entries(UI_APPS).map(([id, app]) => ({\n uri: `ui://trie/${id}`,\n name: app.name,\n description: app.description,\n mimeType: 'text/html;profile=mcp-app',\n }));\n }\n\n /**\n * Read UI App resource content (bundled HTML)\n */\n private async getUIAppResource(uri: string, appId: string): Promise<ResourceContent> {\n // Get the directory of this file to find the dist/ui folder\n const currentFile = fileURLToPath(import.meta.url);\n const distDir = dirname(dirname(currentFile)); // Go up from server/ to dist/\n const uiDir = join(distDir, 'ui');\n const htmlPath = join(uiDir, `${appId}.html`);\n\n try {\n if (!existsSync(htmlPath)) {\n // Return a fallback HTML if the bundled app doesn't exist yet\n return {\n contents: [{\n uri,\n mimeType: 'text/html;profile=mcp-app',\n text: this.getFallbackUIHtml(appId),\n }],\n };\n }\n\n const content = await readFile(htmlPath, 'utf-8');\n return {\n contents: [{\n uri,\n mimeType: 'text/html;profile=mcp-app',\n text: content,\n }],\n };\n } catch (error) {\n return {\n contents: [{\n uri,\n mimeType: 'text/html;profile=mcp-app',\n text: this.getFallbackUIHtml(appId),\n }],\n };\n }\n }\n\n /**\n * Generate fallback HTML for UI apps that haven't been built yet\n */\n private getFallbackUIHtml(appId: string): string {\n const app = UI_APPS[appId as UIAppId];\n const title = app?.name || 'Trie UI';\n const description = app?.description || 'Loading...';\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${title} - Trie</title>\n <style>\n :root {\n --bg: #0d1117;\n --surface: #161b22;\n --border: #30363d;\n --text: #e6edf3;\n --text-muted: #8b949e;\n --primary: #58a6ff;\n }\n * { box-sizing: border-box; margin: 0; padding: 0; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;\n background: var(--bg);\n color: var(--text);\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n padding: 24px;\n }\n .container {\n text-align: center;\n max-width: 400px;\n }\n h1 {\n font-size: 24px;\n margin-bottom: 8px;\n }\n p {\n color: var(--text-muted);\n margin-bottom: 24px;\n }\n .status {\n display: inline-flex;\n align-items: center;\n gap: 8px;\n padding: 8px 16px;\n background: var(--surface);\n border: 1px solid var(--border);\n border-radius: 8px;\n color: var(--primary);\n }\n .spinner {\n width: 16px;\n height: 16px;\n border: 2px solid var(--border);\n border-top-color: var(--primary);\n border-radius: 50%;\n animation: spin 0.8s linear infinite;\n }\n @keyframes spin { to { transform: rotate(360deg); } }\n </style>\n</head>\n<body>\n <div class=\"container\">\n <h1>${title}</h1>\n <p>${description}</p>\n <div class=\"status\">\n <div class=\"spinner\"></div>\n <span>Connecting to Trie...</span>\n </div>\n </div>\n <script type=\"module\">\n // MCP Apps SDK connection\n import { App } from \"@modelcontextprotocol/ext-apps\";\n \n const app = new App();\n await app.connect();\n \n app.ontoolresult = (result) => {\n document.querySelector('.status span').textContent = 'Connected! Waiting for data...';\n console.log('Received tool result:', result);\n };\n </script>\n</body>\n</html>`;\n }\n\n private async getContextResource(uri: string): Promise<ResourceContent> {\n const workDir = getWorkingDirectory(undefined, true);\n const state = await loadContextState();\n \n // Build executive summary first\n const summary: string[] = [\n '# Trie Context',\n '',\n '> Quick reference for AI assistants. Detailed sections below.',\n '',\n '## Quick Status',\n '',\n `| Metric | Value |`,\n `|--------|-------|`,\n `| Last Scan | ${state.lastScan ? new Date(state.lastScan.timestamp).toLocaleDateString() : 'Never'} |`,\n `| Critical Issues | ${state.lastScan?.issues.critical ?? 0} |`,\n `| Total Issues | ${state.lastScan?.issues.total ?? 0} |`,\n '',\n ];\n \n // Add top priorities (max 3)\n if (state.activePriorities.length > 0) {\n summary.push('## Top Priorities', '');\n state.activePriorities.slice(0, 3).forEach((p, i) => {\n summary.push(`${i + 1}. ${p}`);\n });\n summary.push('');\n }\n \n // Add recent issues from memory (max 3, one-liners)\n try {\n const recentIssues = await getRecentIssues({ workDir, limit: 3 });\n if (recentIssues.length > 0) {\n summary.push('## Recent Issues', '');\n recentIssues.forEach(i => {\n summary.push(`- [${i.severity.toUpperCase()}] ${i.issue.slice(0, 50)}... (\\`${i.file.split('/').pop()}\\`)`);\n });\n summary.push('');\n }\n } catch {\n // Memory not available\n }\n \n // Add cross-project patterns (max 2, one-liners)\n try {\n const patterns = await findCrossProjectPatterns(2);\n if (patterns.length > 0) {\n summary.push('## Watch For (seen in other projects)', '');\n patterns.slice(0, 2).forEach(p => {\n summary.push(`- ${p.pattern.slice(0, 40)}... (${p.occurrences}x across ${p.projects.length} projects)`);\n });\n summary.push('');\n }\n } catch {\n // Global memory not available\n }\n \n // Add coding rules summary (just headers)\n const rules = await loadRules(workDir);\n if (rules) {\n const ruleHeaders = rules.match(/^##?\\s+.+$/gm)?.slice(0, 5) || [];\n if (ruleHeaders.length > 0) {\n summary.push('## Coding Rules (see trie://rules for full)', '');\n ruleHeaders.forEach(h => summary.push(`- ${h.replace(/^#+\\s*/, '')}`));\n summary.push('');\n }\n }\n \n // Add available tools/capabilities\n summary.push('## Available Tools', '');\n summary.push('| Tool | Purpose |');\n summary.push('|------|---------|');\n summary.push('| `trie_scan` | Scan code with intelligent agent selection |');\n summary.push('| `trie_fix` | Generate fix recommendations |');\n summary.push('| `trie_memory` | Search issue history |');\n summary.push('| `trie_init` | Initialize bootstrap files |');\n summary.push('');\n \n // Add installed skills count\n try {\n const skills = await listInstalledSkills();\n if (skills.length > 0) {\n summary.push(`**Skills:** ${skills.length} installed (${skills.slice(0, 3).map(s => s.name).join(', ')}${skills.length > 3 ? '...' : ''})`);\n summary.push('');\n }\n } catch {\n // Skills not available\n }\n \n summary.push('---', '', '# Detailed Context', '');\n \n // Now add the full AGENTS.md\n const agentsMdPath = join(getTrieDirectory(workDir), 'AGENTS.md');\n try {\n if (existsSync(agentsMdPath)) {\n const agentsContent = await readFile(agentsMdPath, 'utf-8');\n summary.push(agentsContent);\n } else {\n const contextSummary = await getContextForAI();\n summary.push(contextSummary);\n }\n } catch {\n const contextSummary = await getContextForAI();\n summary.push(contextSummary);\n }\n \n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: summary.join('\\n'),\n }],\n };\n }\n\n private async getContextStateResource(uri: string): Promise<ResourceContent> {\n const state = await loadContextState();\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(state, null, 2),\n }],\n };\n }\n\n private async getProjectResource(uri: string): Promise<ResourceContent> {\n const workDir = getWorkingDirectory(undefined, true);\n \n if (!projectInfoExists(workDir)) {\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: `# Project Information Not Found\n\nNo \\`.trie/PROJECT.md\\` file exists in this project.\n\n## Create One\n\nUse the \\`trie_project\\` tool with action=\"init\" to create a PROJECT.md template:\n\n\\`\\`\\`\ntrie_project action=\"init\"\n\\`\\`\\`\n\nOr run from CLI:\n\\`\\`\\`\ntrie project init\n\\`\\`\\`\n\n## What is PROJECT.md?\n\nPROJECT.md is a user-defined file that stores important project context:\n- Project description and purpose\n- Technology stack\n- Architecture decisions\n- Coding conventions\n- Environment info\n- Team ownership\n- Compliance requirements\n- Special instructions for AI assistants\n\nThis information is automatically available to Claude Code, Cursor, and other AI tools.\n`,\n }],\n };\n }\n\n const content = await loadProjectInfo(workDir);\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: content || '',\n }],\n };\n }\n\n private async getBuiltInSkillsResource(uri: string): Promise<ResourceContent> {\n await this.skillRegistry.loadCustomSkills();\n const skills = this.skillRegistry.getSkillDescriptions();\n\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n totalSkills: skills.length,\n builtinCount: skills.filter(a => !a.isCustom).length,\n customCount: skills.filter(a => a.isCustom).length,\n skills: skills.map(a => ({\n name: a.name,\n description: a.description,\n type: a.isCustom ? 'custom' : 'builtin',\n })),\n }, null, 2),\n }],\n };\n }\n\n private async getCustomSkillResource(uri: string, parsedUri: string): Promise<ResourceContent> {\n const skillName = parsedUri.replace('skills/custom/', '');\n await this.skillRegistry.loadCustomSkills();\n const metadata = this.skillRegistry.getCustomSkillMetadata(skillName);\n\n if (!metadata) {\n throw new Error(`Custom skill not found: ${skillName}`);\n }\n\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(metadata, null, 2),\n }],\n };\n }\n\n private async getConfigResource(uri: string): Promise<ResourceContent> {\n const config = await loadConfig();\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(config, null, 2),\n }],\n };\n }\n\n private async getCacheStatsResource(uri: string): Promise<ResourceContent> {\n try {\n const cachePath = join(getTrieDirectory(getWorkingDirectory(undefined, true)), '.trie-cache.json');\n const cacheContent = await readFile(cachePath, 'utf-8');\n const cache = JSON.parse(cacheContent);\n\n const fileCount = Object.keys(cache.files || {}).length;\n const totalVulns = Object.values(cache.files || {}).reduce((acc: number, file: any) => {\n return acc + (file.vulnerabilities?.length || 0);\n }, 0);\n\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n version: cache.version,\n created: new Date(cache.created).toISOString(),\n lastUpdated: new Date(cache.lastUpdated).toISOString(),\n cachedFiles: fileCount,\n totalVulnerabilitiesFound: totalVulns,\n cacheAgeMinutes: Math.round((Date.now() - cache.lastUpdated) / 60000),\n }, null, 2),\n }],\n };\n } catch {\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n error: 'No cache found. Run a scan first to build the cache.',\n hint: 'Use trie_scan to scan your codebase',\n }, null, 2),\n }],\n };\n }\n }\n\n private async getSignaturesResource(uri: string): Promise<ResourceContent> {\n // Import dynamically to avoid circular deps\n const { getVulnerabilityStats } = await import('../trie/vulnerability-signatures.js');\n const { getVibeCodeStats } = await import('../trie/vibe-code-signatures.js');\n\n const vulnStats = getVulnerabilityStats();\n const vibeStats = getVibeCodeStats();\n\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n vulnerabilitySignatures: vulnStats,\n vibeCodeSignatures: vibeStats,\n totalSignatures: vulnStats.total + vibeStats.total,\n }, null, 2),\n }],\n };\n }\n\n private async getInstalledSkillsResource(uri: string): Promise<ResourceContent> {\n const skills = await listInstalledSkills();\n const state = await loadContextState();\n \n const skillsWithUsage = skills.map(skill => {\n const record = state.skills?.[skill.name];\n return {\n name: skill.name,\n description: skill.description,\n source: skill.installedFrom,\n installedAt: skill.installedAt,\n timesApplied: record?.timesApplied || 0,\n appliedBy: record?.appliedBy || [],\n lastApplied: record?.lastApplied,\n };\n });\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n totalSkills: skills.length,\n skills: skillsWithUsage,\n note: 'Skills are capabilities applied by agents, not autonomous agents themselves.',\n }, null, 2),\n }],\n };\n }\n\n private async getScanReportResource(uri: string, parsedUri: string): Promise<ResourceContent> {\n const fileName = parsedUri.replace('reports/', '');\n const reportPath = join(getWorkingDirectory(undefined, true), 'trie-reports', fileName);\n\n try {\n const content = await readFile(reportPath, 'utf-8');\n\n return {\n contents: [{\n uri,\n mimeType: fileName.endsWith('.json') ? 'application/json' : 'text/plain',\n text: content,\n }],\n };\n } catch {\n throw new Error(`Report not found: ${fileName}`);\n }\n }\n\n private async getBootstrapResource(uri: string): Promise<ResourceContent> {\n const workDir = getWorkingDirectory(undefined, true);\n const context = await loadBootstrapContext(workDir);\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n needsBootstrap: context.needsBootstrap,\n files: context.files.map(f => ({\n name: f.name,\n type: f.type,\n exists: f.exists,\n })),\n hasInjectedContent: !!context.injectedContent,\n }, null, 2),\n }],\n };\n }\n\n private async getRulesResource(uri: string): Promise<ResourceContent> {\n const rules = await loadRules();\n \n if (!rules) {\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: `# No Rules Defined\n\nNo \\`.trie/RULES.md\\` file exists in this project.\n\nUse \\`trie_init\\` to create one, or create it manually with your coding standards.\n`,\n }],\n };\n }\n\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: rules,\n }],\n };\n }\n\n private async getTeamResource(uri: string): Promise<ResourceContent> {\n const team = await loadTeamInfo();\n \n if (!team) {\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: `# No Team Info Defined\n\nNo \\`.trie/TEAM.md\\` file exists in this project.\n\nUse \\`trie_init\\` to create one, or create it manually with team ownership info.\n`,\n }],\n };\n }\n\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: team,\n }],\n };\n }\n\n private async getMemoryResource(uri: string): Promise<ResourceContent> {\n const workDir = getWorkingDirectory(undefined, true);\n const stats = await getMemoryStats(workDir);\n const recent = await getRecentIssues({ workDir, limit: 5 });\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n stats,\n recentIssues: recent.map(i => ({\n severity: i.severity,\n issue: i.issue.slice(0, 100),\n file: i.file,\n agent: i.agent,\n timestamp: i.timestamp,\n resolved: i.resolved,\n })),\n }, null, 2),\n }],\n };\n }\n\n private async getGlobalMemoryResource(uri: string): Promise<ResourceContent> {\n const stats = await getGlobalMemoryStats();\n const patterns = await findCrossProjectPatterns(2);\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n stats,\n topPatterns: patterns.slice(0, 10).map(p => ({\n pattern: p.pattern.slice(0, 80),\n severity: p.severity,\n agent: p.agent,\n occurrences: p.occurrences,\n projectCount: p.projects.length,\n hasFixApplied: !!p.fixApplied,\n })),\n }, null, 2),\n }],\n };\n }\n}","/**\n * Skills installer stub\n * Skills system has been replaced with decision ledger\n */\n\nexport interface Skill {\n name: string;\n category: string;\n description: string;\n path?: string;\n installedFrom?: string;\n installedAt?: string;\n timesApplied?: number;\n}\n\nexport interface InstallResult {\n success: boolean;\n name?: string;\n path?: string;\n error?: string;\n}\n\nexport interface CreateSkillResult {\n success: boolean;\n name?: string;\n writtenTo?: string[];\n error?: string;\n}\n\nexport async function listInstalledSkills(): Promise<Skill[]> {\n return [];\n}\n\nexport async function listGlobalSkills(): Promise<Skill[]> {\n return [];\n}\n\nexport async function installSkill(\n _repo: string, \n _skillName?: string\n): Promise<InstallResult> {\n return {\n success: false,\n error: 'Skills system has been replaced with the decision ledger'\n };\n}\n\nexport async function createSkillFromFile(\n _filePath: string\n): Promise<CreateSkillResult> {\n return {\n success: false,\n error: 'Skills system has been replaced with the decision ledger'\n };\n}\n\nexport async function removeGlobalSkill(_name: string): Promise<boolean> {\n return false;\n}\n","import { chromium, Browser, Page } from 'playwright';\nimport { createServer, Server } from 'net';\nimport { request } from 'http';\nimport { isInteractiveMode } from '../utils/progress.js';\n\n/**\n * Browser-based Visual QA Tool\n * \n * Launches a headless browser, captures screenshots at multiple viewports,\n * and returns them for Claude Vision to analyze.\n */\n\nexport interface VisualQAOptions {\n url?: string;\n port?: number;\n viewports?: ViewportConfig[];\n waitForSelector?: string;\n waitMs?: number;\n}\n\nexport interface ViewportConfig {\n name: string;\n width: number;\n height: number;\n}\n\nexport interface ScreenshotResult {\n viewport: string;\n width: number;\n height: number;\n base64: string;\n mimeType: 'image/png';\n}\n\nexport interface VisualQAResult {\n success: boolean;\n url: string;\n screenshots: ScreenshotResult[];\n error?: string;\n analysisPrompt: string;\n}\n\n// Default viewports for responsive testing\nconst DEFAULT_VIEWPORTS: ViewportConfig[] = [\n { name: 'mobile', width: 375, height: 812 }, // iPhone X\n { name: 'tablet', width: 768, height: 1024 }, // iPad\n { name: 'desktop', width: 1440, height: 900 }, // Standard desktop\n];\n\n/**\n * Find an open port on localhost by checking common dev server ports\n * Returns the first port that is both in use AND serving HTTP\n */\nasync function findOpenPort(): Promise<number | null> {\n const commonPorts = [3000, 3001, 5173, 5174, 4200, 8080, 8000, 8888, 5000, 4000];\n \n // Check ports in parallel for faster detection\n const portChecks = await Promise.all(\n commonPorts.map(async (port) => {\n const isOpen = await checkPort(port);\n return isOpen ? port : null;\n })\n );\n \n // Return the first port that's open and serving HTTP\n return portChecks.find(port => port !== null) || null;\n}\n\n/**\n * Check if a port has something listening on it AND is serving HTTP\n */\nasync function checkPort(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n // First check if port is in use\n const testServer: Server = createServer();\n let portInUse = false;\n \n testServer.once('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EADDRINUSE') {\n portInUse = true;\n // Port is in use - now verify it's serving HTTP\n testHttpPort(port).then(resolve).catch(() => resolve(false));\n } else {\n resolve(false);\n }\n });\n \n testServer.once('listening', () => {\n // Port is free - nothing running\n testServer.close();\n resolve(false);\n });\n \n // Set timeout to prevent hanging\n setTimeout(() => {\n if (!portInUse) {\n testServer.close();\n resolve(false);\n }\n }, 1000);\n \n testServer.listen(port, '127.0.0.1');\n });\n}\n\n/**\n * Verify that a port is actually serving HTTP content\n */\nasync function testHttpPort(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const req = request({\n hostname: 'localhost',\n port: port,\n path: '/',\n method: 'GET',\n timeout: 2000,\n }, (res) => {\n // If we get any HTTP response (even 404), the server is running\n resolve(res.statusCode !== undefined);\n res.on('data', () => {}); // Consume response\n res.on('end', () => {});\n });\n\n req.on('error', () => {\n // Connection refused, timeout, or other error means no HTTP server\n resolve(false);\n });\n\n req.on('timeout', () => {\n req.destroy();\n resolve(false);\n });\n\n req.end();\n });\n}\n\n/**\n * Capture screenshots at multiple viewports\n */\nasync function captureScreenshots(\n url: string,\n viewports: ViewportConfig[],\n options: { waitForSelector?: string | undefined; waitMs?: number | undefined }\n): Promise<ScreenshotResult[]> {\n let browser: Browser | null = null;\n const screenshots: ScreenshotResult[] = [];\n\n try {\n // Launch browser\n browser = await chromium.launch({\n headless: true,\n });\n\n for (const viewport of viewports) {\n const page: Page = await browser.newPage({\n viewport: { width: viewport.width, height: viewport.height },\n });\n\n try {\n // Navigate to URL\n await page.goto(url, { \n waitUntil: 'networkidle',\n timeout: 30000 \n });\n\n // Wait for specific selector if provided\n if (options.waitForSelector) {\n await page.waitForSelector(options.waitForSelector, { timeout: 10000 });\n }\n\n // Additional wait if specified\n if (options.waitMs) {\n await page.waitForTimeout(options.waitMs);\n }\n\n // Capture full-page screenshot\n const screenshotBuffer = await page.screenshot({\n fullPage: true,\n type: 'png',\n });\n\n screenshots.push({\n viewport: viewport.name,\n width: viewport.width,\n height: viewport.height,\n base64: screenshotBuffer.toString('base64'),\n mimeType: 'image/png',\n });\n\n } finally {\n await page.close();\n }\n }\n\n } finally {\n if (browser) {\n await browser.close();\n }\n }\n\n return screenshots;\n}\n\n/**\n * Main Visual QA function - captures screenshots and prepares for Claude Vision\n */\nexport async function runVisualQA(options: VisualQAOptions = {}): Promise<VisualQAResult> {\n let url = options.url;\n \n // If no URL provided, try to find a running dev server\n if (!url) {\n if (options.port) {\n // User specified a port - verify it's serving HTTP\n const isServing = await testHttpPort(options.port);\n if (!isServing) {\n return {\n success: false,\n url: `http://localhost:${options.port}`,\n screenshots: [],\n error: `Port ${options.port} is not serving HTTP. Is your dev server running on this port?\\n\\nTry:\\n1. Verify your dev server is running: curl http://localhost:${options.port}\\n2. Check if the port is correct\\n3. Provide full URL: trie_visual_qa_browser url:\"http://localhost:${options.port}\"`,\n analysisPrompt: '',\n };\n }\n url = `http://localhost:${options.port}`;\n } else {\n // Auto-detect port\n if (!isInteractiveMode()) {\n console.error('Visual QA: Auto-detecting running dev server...');\n }\n const port = await findOpenPort();\n \n if (!port) {\n return {\n success: false,\n url: '',\n screenshots: [],\n error: 'No running dev server found on common ports (3000, 3001, 5173, 5174, 4200, 8080, 8000, 8888, 5000, 4000).\\n\\nPlease:\\n1. Start your dev server, OR\\n2. Provide a URL: trie_visual_qa_browser url:\"http://localhost:3000\", OR\\n3. Specify a port: trie_visual_qa_browser port:3000',\n analysisPrompt: '',\n };\n }\n \n url = `http://localhost:${port}`;\n if (!isInteractiveMode()) {\n console.error(` ✓ Found server on port ${port}`);\n }\n }\n }\n\n const viewports = options.viewports || DEFAULT_VIEWPORTS;\n\n try {\n if (!isInteractiveMode()) {\n console.error(`📸 Visual QA: Capturing screenshots from ${url}`);\n console.error(` Viewports: ${viewports.map(v => `${v.name} (${v.width}x${v.height})`).join(', ')}`);\n }\n\n const screenshots = await captureScreenshots(url, viewports, {\n waitForSelector: options.waitForSelector,\n waitMs: options.waitMs,\n });\n\n if (!isInteractiveMode()) {\n console.error(` ✓ Captured ${screenshots.length} screenshots`);\n }\n\n // Build analysis prompt for Claude Vision\n const analysisPrompt = buildAnalysisPrompt(url, screenshots);\n\n return {\n success: true,\n url,\n screenshots,\n analysisPrompt,\n };\n\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n \n // Check for common issues\n if (errorMessage.includes('net::ERR_CONNECTION_REFUSED') || errorMessage.includes('ECONNREFUSED')) {\n return {\n success: false,\n url,\n screenshots: [],\n error: `Cannot connect to ${url}. Is your dev server running?\\n\\nTry:\\n1. Start your dev server (e.g., npm start, npm run dev)\\n2. Specify the URL explicitly: trie_visual_qa_browser url:\"http://localhost:3000\"\\n3. Or specify the port: trie_visual_qa_browser port:3000`,\n analysisPrompt: '',\n };\n }\n \n if (errorMessage.includes('Executable doesn\\'t exist') || errorMessage.includes('BrowserType')) {\n return {\n success: false,\n url,\n screenshots: [],\n error: 'Playwright browsers not installed. Run: npx playwright install chromium',\n analysisPrompt: '',\n };\n }\n\n if (errorMessage.includes('timeout') || errorMessage.includes('Navigation timeout')) {\n return {\n success: false,\n url,\n screenshots: [],\n error: `Page load timeout for ${url}. The page may be taking too long to load or may have JavaScript errors.\\n\\nTry:\\n1. Check if the page loads in your browser\\n2. Increase wait time: trie_visual_qa_browser url:\"${url}\" waitMs:5000\\n3. Wait for specific element: trie_visual_qa_browser url:\"${url}\" waitForSelector:\".main-content\"`,\n analysisPrompt: '',\n };\n }\n\n return {\n success: false,\n url,\n screenshots: [],\n error: `Screenshot capture failed: ${errorMessage}\\n\\nTroubleshooting:\\n1. Verify ${url} is accessible in your browser\\n2. Check that your dev server is running\\n3. Try specifying the URL explicitly: trie_visual_qa_browser url:\"${url}\"`,\n analysisPrompt: '',\n };\n }\n}\n\n/**\n * Build the analysis prompt for Claude Vision\n */\nfunction buildAnalysisPrompt(url: string, screenshots: ScreenshotResult[]): string {\n const viewportList = screenshots.map(s => `- ${s.viewport}: ${s.width}x${s.height}`).join('\\n');\n \n return `## Visual QA Analysis\n\nI've captured screenshots of **${url}** at ${screenshots.length} viewports:\n\n${viewportList}\n\nPlease analyze these screenshots for:\n\n### Layout Issues\n- Overlapping elements or text\n- Content overflow or clipping\n- Broken layouts at specific breakpoints\n- Misaligned elements\n- Unexpected gaps or spacing\n\n### Responsive Design\n- Mobile navigation issues\n- Text too small to read on mobile\n- Touch targets too small (<44px)\n- Horizontal scrolling on mobile\n- Content not adapting to viewport\n\n### Visual Polish\n- Inconsistent spacing or alignment\n- Poor color contrast (text hard to read)\n- Broken images or missing assets\n- Loading states stuck/visible\n- Z-index issues (elements overlapping incorrectly)\n\n### Accessibility\n- Missing focus indicators\n- Color-only information\n- Text over images without sufficient contrast\n- Very small text (<12px)\n\n### General Quality\n- Does it look professional?\n- Is the hierarchy clear?\n- Are interactive elements obvious?\n- Any obvious bugs or glitches?\n\nFor each issue found:\n1. **Viewport**: Which viewport(s) affected\n2. **Location**: Where on the page\n3. **Issue**: What's wrong\n4. **Severity**: Critical/Serious/Moderate/Low\n5. **Fix**: How to resolve it\n\nIf the UI looks good, say so! Note what's working well.`;\n}\n\n/**\n * Format MCP response with images for Claude Vision\n */\nexport function formatMCPResponse(result: VisualQAResult): {\n content: Array<{ type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }>;\n} {\n if (!result.success) {\n return {\n content: [{\n type: 'text',\n text: `# Visual QA Failed\\n\\n${result.error}\\n\\n## Troubleshooting\\n\\n1. Make sure your dev server is running\\n2. Try: \\`trie_visual_qa url:\"http://localhost:3000\"\\`\\n3. If Playwright isn't installed: \\`npx playwright install chromium\\``,\n }],\n };\n }\n\n const content: Array<{ type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }> = [];\n\n // Add the analysis prompt first\n content.push({\n type: 'text',\n text: result.analysisPrompt,\n });\n\n // Add each screenshot as an image\n for (const screenshot of result.screenshots) {\n content.push({\n type: 'text',\n text: `\\n### ${screenshot.viewport} (${screenshot.width}x${screenshot.height})\\n`,\n });\n content.push({\n type: 'image',\n data: screenshot.base64,\n mimeType: screenshot.mimeType,\n });\n }\n\n return { content };\n}\n\n/**\n * MCP Tool Definition\n */\nexport const VISUAL_QA_TOOL_DEFINITION = {\n name: 'visual_qa_browser',\n description: 'Capture screenshots of your app at mobile/tablet/desktop viewports for visual QA analysis. Auto-detects running dev servers or specify a URL.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n url: {\n type: 'string',\n description: 'URL to screenshot (e.g., http://localhost:3000). If not provided, auto-detects running dev server.',\n },\n port: {\n type: 'number',\n description: 'Specific port to check if no URL provided',\n },\n waitForSelector: {\n type: 'string',\n description: 'CSS selector to wait for before capturing (e.g., \".main-content\")',\n },\n waitMs: {\n type: 'number',\n description: 'Additional milliseconds to wait after page load',\n },\n },\n required: [],\n },\n};\n","import { getWorkingDirectory } from '../utils/workspace.js';\nimport { runVisualQA, formatMCPResponse } from '../tools/visual-qa-browser.js';\nimport { ToolRegistry } from './tool-registry.js';\nimport { ResourceManager } from './resource-manager.js';\n\nexport class RequestHandlers {\n constructor(\n private toolRegistry: ToolRegistry,\n private resourceManager: ResourceManager\n ) {}\n\n /**\n * Handle tool execution requests\n */\n async handleToolCall(name: string, args: any): Promise<any> {\n // Accept namespaced calls and normalize\n const normalizedName = this.normalizeName(name);\n\n // Auto-detect directory for Cursor/IDE tools when not explicitly provided\n if (args && !args.directory && !args.files) {\n const workingDir = getWorkingDirectory(undefined, true);\n if (workingDir !== process.cwd()) {\n args.directory = workingDir;\n }\n }\n\n try {\n switch (normalizedName) {\n case 'trie':\n return await this.handleTrieMenu(args);\n\n case 'scan':\n return await this.toolRegistry.getTool('scan').execute(args);\n\n case 'fix':\n return await this.toolRegistry.getTool('fix').execute(args);\n\n case 'explain':\n return await this.toolRegistry.getTool('explain').execute(args);\n\n case 'test':\n return await this.toolRegistry.getTool('test').execute(args);\n\n case 'register_agent':\n return await this.toolRegistry.getTool('register_agent').execute(args);\n\n case 'watch':\n return await this.toolRegistry.getTool('watch').execute(args);\n\n // Individual agent commands\n case 'security':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'security' });\n\n case 'legal':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'legal' });\n\n case 'accessibility':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'accessibility' });\n\n case 'design':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'design-engineer' });\n\n case 'architecture':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'software-architect' });\n\n case 'bugs':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'bug-finding' });\n\n case 'ux':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'user-testing' });\n\n case 'types':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'typecheck' });\n\n case 'devops':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'devops' });\n\n case 'clean':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'trie_clean' });\n\n case 'soc2':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'soc2' });\n\n // New agents\n case 'performance':\n case 'perf':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'performance' });\n\n case 'e2e':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'e2e' });\n\n case 'visual_qa':\n case 'visual':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'visual-qa' });\n\n case 'visual_qa_browser': {\n try {\n const result = await runVisualQA(args as { url?: string; port?: number; waitForSelector?: string; waitMs?: number });\n return formatMCPResponse(result);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return {\n content: [{\n type: 'text',\n text: `# Visual QA Error\\n\\nFailed to capture screenshots: ${errorMessage}\\n\\n## Troubleshooting\\n\\n1. **Check if your dev server is running:**\\n - Try accessing the URL in your browser\\n - Common ports: 3000, 5173, 8080\\n\\n2. **Specify the URL explicitly:**\\n \\`\\`\\`\\ntrie_visual_qa_browser url:\"http://localhost:3000\"\\n\\`\\`\\`\\n\\n3. **Specify a port:**\\n \\`\\`\\`\\ntrie_visual_qa_browser port:3000\\n\\`\\`\\`\\n\\n4. **Install Playwright browsers (if needed):**\\n \\`\\`\\`\\nnpx playwright install chromium\\n\\`\\`\\`\\n\\n5. **Check for JavaScript errors:**\\n - Open browser dev tools\\n - Look for console errors\\n - The page may be failing to load`,\n }],\n };\n }\n }\n\n case 'data_flow':\n case 'dataflow':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'data-flow' });\n\n // Special agents\n case 'agent_smith':\n case 'agentsmith':\n case 'smith':\n // Handle special Agent Smith commands (clear_memory, show_stats)\n if (args?.clear_memory || args?.show_stats) {\n return await this.handleAgentSmith(args);\n }\n // Normal scan - delegate to agent tool\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'agent-smith' });\n\n case 'super_reviewer':\n case 'superreviewer':\n case 'reviewer':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'super-reviewer' });\n\n // Custom skill tools (with backward-compatible agent aliases)\n case 'create_skill':\n case 'create_agent':\n return await this.toolRegistry.getTool('create_skill').execute(args);\n\n case 'save_skill':\n case 'save_agent':\n return await this.toolRegistry.getTool('save_skill').execute(args);\n\n case 'list_skills':\n case 'list_agents':\n return await this.toolRegistry.getTool('list_skills').execute(args);\n\n case 'pr_review':\n return await this.toolRegistry.getTool('pr_review').execute(args);\n\n case 'project':\n case 'project_info':\n return await this.toolRegistry.getTool('project').execute(args);\n\n case 'init':\n return await this.toolRegistry.getTool('init').execute(args);\n\n case 'memory':\n return await this.toolRegistry.getTool('memory').execute(args);\n\n case 'check':\n return await this.toolRegistry.getTool('check').execute(args);\n\n case 'tell':\n return await this.toolRegistry.getTool('tell').execute(args);\n\n case 'feedback':\n case 'ok':\n case 'bad':\n return await this.toolRegistry.getTool('feedback').execute(args);\n\n case 'reconcile':\n return await this.toolRegistry.getTool('reconcile').execute(args);\n\n case 'context':\n return await this.toolRegistry.getTool('context').execute(args);\n\n case 'checkpoint':\n case 'cp':\n case 'save':\n return await this.toolRegistry.getTool('checkpoint').execute(args);\n\n case 'cloud_fix':\n return await this.toolRegistry.getTool('cloud_fix').execute(args);\n\n case 'linear_sync':\n return await this.toolRegistry.getTool('linear_sync').execute(args);\n\n case 'github_sync':\n return await this.toolRegistry.getTool('github_sync').execute(args);\n\n case 'github_branches':\n return await this.toolRegistry.getTool('github_branches').execute(args);\n\n case 'pipeline':\n return await this.toolRegistry.getTool('pipeline').execute(args);\n\n case 'index':\n return await this.toolRegistry.getTool('index').execute(args);\n\n default: {\n // Fallback: try tool by normalized name (handles trie_index, trie_github_branches, etc.)\n const tool = this.toolRegistry.getTool(normalizedName);\n if (tool) {\n return await tool.execute(args);\n }\n throw new Error(`Unknown tool: ${name}`);\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 * 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 // Strip trailing \"(MCP)\" or \"(action: ...)\" that some clients append\n const stripNamespace = (n: string): string => {\n const trimmed = n.trim().replace(/\\s*\\([^)]*\\)\\s*$/, '').trim();\n const withoutSlash = trimmed.startsWith('/') ? trimmed.slice(1) : trimmed;\n const parts = withoutSlash.split(':');\n const base = (parts[0] || withoutSlash).trim();\n const slashParts = base.split('/');\n return (slashParts[slashParts.length - 1] || base).trim();\n };\n\n const rawName = stripNamespace(name);\n return rawName.startsWith('trie_') ? rawName.slice('trie_'.length) : rawName;\n }\n\n private async handleTrieMenu(args?: any) {\n const actionInput = typeof args?.action === 'string' ? args.action : null;\n if (actionInput) {\n const normalizedAction = this.normalizeName(actionInput);\n // Avoid recursion loop\n if (normalizedAction === 'trie') {\n return {\n content: [{\n type: 'text',\n text: 'Use `trie` without action for the menu, or provide a concrete action like \"scan\" or \"security\".'\n }]\n };\n }\n\n // Delegate to the same dispatcher to keep alias handling consistent\n return await this.handleToolCall(normalizedAction, { ...args });\n }\n\n return {\n content: [{\n type: 'text',\n text: [\n '## Trie Quick Actions',\n '',\n '**Most common:**',\n '- `trie` (no args) — show this menu',\n '- `trie` with `{ action: \"scan\", files?: [], directory?: \"\" }` — auto triage & scan',\n '- `trie` with `{ action: \"security\", files?: [] }` — single-skill run (any skill name works)',\n '- `trie` with `{ action: \"agent_smith\" }` — aggressive AI-pattern hunter',\n '',\n '**Other actions:**',\n '- `action: \"pr_review\"` — interactive PR review',\n '- `action: \"fix\"` — high-confidence fixes',\n '- `action: \"watch\"` — start/stop/status autonomous watch',\n '- `action: \"test\"` — generate/coverage/suggest/run tests (requires `files` + `action`)',\n '- `action: \"explain\"` — explain code/issues/risks',\n '- `action: \"list_skills\"` — list all skills (external + custom)',\n '- `action: \"visual_qa_browser\"` — screenshots for visual QA',\n '',\n '**Built-in skills:**',\n '`security`, `legal`, `accessibility`, `design`, `architecture`, `bugs`, `ux`, `types`, `devops`, `clean`, `soc2`, `performance`, `e2e`, `visual_qa`, `data_flow`',\n '',\n '**Special skills:**',\n '`agent_smith` — 35 vibe code hunters with cross-file detection',\n '`super_reviewer` — Interactive PR review with cross-examination',\n '',\n 'All commands accept `trie_` prefix (e.g., `trie_scan`, `trie_security`). Short names still work for compatibility.',\n ].join('\\n')\n }]\n };\n }\n\n private async handleAgentSmith(_smithArgs: any) {\n // Agent Smith has been removed - the decision ledger now handles pattern detection\n return {\n content: [{\n type: 'text',\n text: [\n '🤖 Agent Smith functionality has been integrated into the decision ledger.',\n '',\n 'The autonomous agent now:',\n '- Extracts patterns automatically via `trie watch`',\n '- Builds decision ledger from every change',\n '- Predicts problems via `trie gotcha`',\n '',\n 'Start the agent: `trie_watch start`',\n 'Query the ledger: `trie_gotcha`'\n ].join('\\n')\n }]\n };\n }\n}","#!/usr/bin/env node\n\nimport { startServer } from './server/mcp-server.js';\n\n// Start the MCP server\nstartServer().catch((error) => {\n console.error('Fatal error:', error);\n process.exit(1);\n});"],"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,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AC7B,UAAQ,MAAM,gBAAgB,KAAK;AACnC,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["Server","readFile","existsSync","path","shortPath","padEnd","path","existsSync","readFile","readFile","existsSync","extname","relative","resolve","isAbsolute","join","isAbsolute","resolve","existsSync","readFile","relative","extname","join","existsSync","readFile","join","extname","basename","existsSync","extname","join","basename","readFile","now","getOutputManager","ContextGraph","LinearIngester","GitHubIngester","readFile","existsSync","join","basename","resolve","isAbsolute","isAbsolute","resolve","existsSync","basename","path","join","readFile","result","patterns","lines","stats","readFile","existsSync","join","dirname","join","dirname","existsSync","readFile","resolve","Server","request"]}
1
+ {"version":3,"sources":["../src/server/mcp-server.ts","../src/utils/ai-tool-detector.ts","../src/tools/fix.ts","../src/tools/fix-triage.ts","../src/tools/cloud-fix.ts","../src/integrations/cursor-cloud-agent.ts","../src/tools/test.ts","../src/tools/watch.ts","../src/tools/pr-review.ts","../src/skills/built-in/super-reviewer.ts","../src/tools/project-info.ts","../src/tools/init.ts","../src/tools/memory-search.ts","../src/tools/reconcile.ts","../src/tools/context.ts","../src/tools/linear-sync.ts","../src/tools/github-sync.ts","../src/tools/index-codebase.ts","../src/server/tool-registry.ts","../src/server/resource-manager.ts","../src/skills/installer.ts","../src/tools/visual-qa-browser.ts","../src/server/request-handlers.ts","../src/index.ts"],"sourcesContent":["import { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport {\n CallToolRequestSchema,\n ListToolsRequestSchema,\n ListResourcesRequestSchema,\n ReadResourceRequestSchema,\n} from '@modelcontextprotocol/sdk/types.js';\n\nimport { detectAITool } from '../utils/ai-tool-detector.js';\nimport { loadConfig } from '../config/loader.js';\nimport { getSkillRegistry } from '../skills/built-in/registry.js';\nimport { ToolRegistry } from './tool-registry.js';\nimport { ResourceManager } from './resource-manager.js';\nimport { RequestHandlers } from './request-handlers.js';\n\nexport class MCPServer {\n private server: Server;\n private toolRegistry: ToolRegistry;\n private resourceManager: ResourceManager;\n private requestHandlers: RequestHandlers;\n\n constructor() {\n this.server = new Server(\n {\n name: 'trie',\n version: '1.0.0',\n description: 'Intelligent Agent Orchestration for AI Coding Tools. IMPORTANT: Read trie://context first to understand project state, priorities, and recent scan history before making changes.',\n },\n {\n capabilities: {\n tools: {},\n resources: {},\n // Enable MCP Apps - interactive UI components in AI clients\n // See: https://blog.modelcontextprotocol.io/posts/2026-01-26-mcp-apps/\n experimental: {\n ui: {},\n },\n },\n }\n );\n\n this.toolRegistry = new ToolRegistry();\n this.resourceManager = new ResourceManager();\n this.requestHandlers = new RequestHandlers(this.toolRegistry, this.resourceManager);\n\n this.setupRequestHandlers();\n }\n\n private setupRequestHandlers() {\n // List tools handler\n this.server.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools: this.toolRegistry.getAllTools()\n };\n });\n\n // Call tool handler\n this.server.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n return await this.requestHandlers.handleToolCall(name, args);\n });\n\n // List resources handler\n this.server.setRequestHandler(ListResourcesRequestSchema, async () => {\n return await this.requestHandlers.handleListResources();\n });\n\n // Read resource handler\n this.server.setRequestHandler(ReadResourceRequestSchema, async (request) => {\n const { uri } = request.params;\n return await this.requestHandlers.handleReadResource(uri);\n });\n }\n\n /**\n * Show startup banner\n */\n private showStartupBanner(skillCount: number, aiTool: string) {\n console.error(`\n ████████╗██████╗ ██╗███████╗\n ╚══██╔══╝██╔══██╗██║██╔════╝\n ██║ ██████╔╝██║█████╗\n ██║ ██╔══██╗██║██╔══╝\n ██║ ██║ ██║██║███████╗\n ╚═╝ ╚═╝ ╚═╝╚═╝╚══════╝\n Your central registry for Trie and its skills\n\n by Louis Kishfy\n\n Download the Trie workspace: https://www.trie.dev\n Follow me on X: https://x.com/louiskishfy\n\n ${skillCount} skills ready | ${aiTool}\n\n Quick Start:\n • \"Scan this code\" - Run all relevant skills\n • \"Run trie_security\" - Security scan only\n • \"Run trie_soc2\" - SOC 2 compliance check\n • \"Use trie_list_skills\" - See all skills\n • \"Use trie_create_skill\" - Make custom skill\n\n Ready.\n`);\n }\n\n /**\n * Initialize and start the server\n */\n async start(): Promise<void> {\n try {\n // Detect the AI tool environment\n const aiTool = detectAITool();\n\n // Load configuration\n await loadConfig();\n\n // Get actual skill count from registry\n const registry = getSkillRegistry();\n const skillCount = registry.getAllSkills().length;\n\n this.showStartupBanner(skillCount, aiTool.name);\n\n const transport = new StdioServerTransport();\n await this.server.connect(transport);\n } catch (error) {\n console.error('Fatal error starting MCP server:', error);\n process.exit(1);\n }\n }\n}\n\n/**\n * Start the MCP server\n */\nexport async function startServer(): Promise<void> {\n const server = new MCPServer();\n await server.start();\n}","import { AITool } from '../types/index.js';\n\nexport function detectAITool(): AITool {\n // Check environment variables set by AI tools\n if (process.env.CLAUDE_CODE_VERSION || process.env.CLAUDE_CODE) {\n return {\n name: 'Claude Code',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: true,\n };\n }\n\n if (process.env.CURSOR_IDE || process.env.CURSOR_TRACE_ID) {\n return {\n name: 'Cursor',\n preferredOutputFormat: 'rich-text',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n }\n\n if (process.env.OPENCODE_INSTANCE) {\n return {\n name: 'OpenCode',\n preferredOutputFormat: 'plain-text',\n supportsDiffs: false,\n supportsInlineActions: false,\n };\n }\n\n if (process.env.VSCODE_PID || process.env.VSCODE_IPC_HOOK) {\n return {\n name: 'VS Code',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n }\n\n // Check parent process name or other hints\n const parentProcess = process.env.PARENT_PROCESS_NAME || process.env._ || '';\n if (parentProcess.toLowerCase().includes('claude')) {\n return {\n name: 'Claude Code',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: true,\n };\n }\n\n if (parentProcess.toLowerCase().includes('cursor')) {\n return {\n name: 'Cursor',\n preferredOutputFormat: 'rich-text',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n }\n\n // Check if running via npx (likely from an MCP client)\n if (process.env.npm_execpath || process.argv[1]?.includes('npx')) {\n return {\n name: 'MCP Client',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n }\n\n // Default\n return {\n name: 'MCP Client',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n}","import { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { extname, relative, resolve, isAbsolute } from 'path';\nimport { getPrompt, getSystemPrompt } from '../ai/prompts.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { triageIssues, formatTriageTable, formatCloudRecommendation } from './fix-triage.js';\nimport { loadAutonomyConfig } from '../utils/autonomy-config.js';\nimport type { Issue } from '../types/index.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\nexport interface 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 /** Optional triage metadata (from scan agents) */\n severity?: Issue['severity'];\n effort?: Issue['effort'];\n autoFixable?: boolean;\n cwe?: string;\n owasp?: string;\n category?: string;\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, action } = args || {};\n\n // Mode 0: Route — show triage decisions without applying fixes\n if (action === 'route') {\n return this.routeIssues(issueIds);\n }\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 routeIssues(issueIds?: string[]) {\n // Load issues from memory if no issues are currently pending\n await loadPendingFixesFromMemory();\n\n const pending = getPendingFixes();\n if (pending.length === 0) {\n return {\n content: [{ type: 'text', text: 'No pending issues. Run trie_scan to detect new issues, or check memory with trie_memory action:recent.' }],\n };\n }\n\n const issues: Issue[] = pending.map(p => ({\n id: p.id,\n severity: p.severity ?? 'moderate',\n effort: p.effort,\n issue: p.issue,\n fix: p.suggestedFix,\n file: p.file,\n line: p.line,\n confidence: p.confidence,\n autoFixable: p.autoFixable ?? false,\n agent: 'trie_scan',\n cwe: p.cwe,\n owasp: p.owasp,\n category: p.category,\n }));\n\n const filtered = issueIds && issueIds.length > 0\n ? issues.filter(i => issueIds.includes(i.id))\n : issues;\n\n const workDir = getWorkingDirectory(undefined, true);\n const config = await loadAutonomyConfig(workDir);\n const { results } = triageIssues(filtered, undefined, undefined, config);\n const table = formatTriageTable(results, filtered);\n\n return { content: [{ type: 'text', text: `\\n${table}\\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 // Append cloud recommendation for remaining high-score issues\n output += await this.appendCloudRecommendation(issueIds);\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 async appendCloudRecommendation(handledIds: string[]): Promise<string> {\n try {\n const pending = getPendingFixes();\n const remaining = pending.filter(p => !handledIds.includes(p.id) || pendingFixes.get(p.id)?.status === 'pending');\n if (remaining.length === 0) return '';\n\n const issues: Issue[] = remaining.map(p => ({\n id: p.id,\n severity: 'moderate' as const,\n issue: p.issue,\n fix: p.suggestedFix,\n file: p.file,\n line: p.line,\n confidence: p.confidence,\n autoFixable: false,\n agent: 'trie_scan',\n }));\n\n const workDir = getWorkingDirectory(undefined, true);\n const config = await loadAutonomyConfig(workDir);\n const { results } = triageIssues(issues, undefined, undefined, config);\n const footer = formatCloudRecommendation(results, issues);\n return footer ? `\\n${footer}\\n` : '';\n } catch {\n return '';\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\nexport async function loadPendingFixesFromMemory(): Promise<void> {\n try {\n // Import here to avoid circular dependency\n const { getRecentIssues } = await import('../memory/issue-store.js');\n\n // Clear existing fixes\n pendingFixes.clear();\n\n // Get recent unresolved issues from memory\n const recentIssues = await getRecentIssues({ limit: 50, includeResolved: false });\n\n // Convert StoredIssue to PendingFix format\n for (const storedIssue of recentIssues) {\n const fix: PendingFix = {\n id: storedIssue.id,\n file: storedIssue.file,\n line: storedIssue.line || 0,\n issue: storedIssue.issue,\n suggestedFix: storedIssue.fix,\n confidence: 0.8, // Default confidence for memory issues\n status: 'pending',\n severity: storedIssue.severity as any,\n autoFixable: true, // Memory issues are generally auto-fixable\n category: storedIssue.category,\n };\n\n pendingFixes.set(fix.id, fix);\n }\n } catch (error) {\n console.warn('Failed to load pending fixes from memory:', error);\n }\n}\n\n","/**\n * Fix Triage Engine\n *\n * Scores each issue across four signal groups (issue shape, code context,\n * occurrence history, user configuration) and recommends one of three\n * fix strategies: inline-auto, local-ai, or cloud-agent.\n *\n * Used by both `trie_fix` and `trie_cloud_fix`.\n */\n\nimport type { Issue, CodeContext } from '../types/index.js';\nimport type { AutonomyConfig, IssueOccurrence } from '../types/autonomy.js';\n\nexport interface PipelineContext {\n hasLinkedPR: boolean;\n prState?: 'open' | 'closed' | 'merged' | 'draft';\n hasLinkedTicket: boolean;\n ticketStatus?: string;\n ticketPriority?: string;\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport type FixStrategy = 'inline-auto' | 'local-ai' | 'cloud-agent';\n\nexport interface TriageResult {\n strategy: FixStrategy;\n score: number;\n confidence: number;\n reasons: string[];\n fallback: 'local-ai';\n}\n\nexport interface TriageSummary {\n inlineAuto: Issue[];\n localAi: Issue[];\n cloudAgent: Issue[];\n cloudAgentScore: number;\n}\n\n// ============================================================================\n// Signal scoring constants\n// ============================================================================\n\nconst EFFORT_SCORES: Record<string, number> = {\n trivial: -6,\n easy: -3,\n medium: 0,\n hard: 4,\n};\n\nconst SEVERITY_SCORES: Record<string, number> = {\n critical: 4,\n serious: 2,\n moderate: -1,\n low: -3,\n};\n\n// ============================================================================\n// Core triage function\n// ============================================================================\n\nexport function triageIssue(\n issue: Issue,\n context?: CodeContext,\n occurrence?: IssueOccurrence,\n config?: AutonomyConfig,\n pipeline?: PipelineContext,\n): TriageResult {\n const reasons: string[] = [];\n\n // --- Hard overrides (checked before scoring) ---\n if (config?.level === 'passive') {\n return {\n strategy: 'local-ai',\n score: 0,\n confidence: 1,\n reasons: ['Autonomy level is passive — cloud dispatch disabled'],\n fallback: 'local-ai',\n };\n }\n\n if (config?.cloudAgentEnabled === false) {\n return {\n strategy: 'local-ai',\n score: 0,\n confidence: 1,\n reasons: ['Cloud agent not enabled (run trie_cloud_fix action:configure)'],\n fallback: 'local-ai',\n };\n }\n\n let score = 0;\n\n // --- Signal Group 1: Issue Shape ---\n const effort = issue.effort ?? 'medium';\n const effortScore = EFFORT_SCORES[effort] ?? 0;\n if (effortScore !== 0) {\n score += effortScore;\n reasons.push(`effort:${effort}`);\n }\n\n const severityScore = SEVERITY_SCORES[issue.severity] ?? 0;\n if (severityScore !== 0) {\n score += severityScore;\n reasons.push(`severity:${issue.severity}`);\n }\n\n if (issue.autoFixable) {\n score -= 2;\n reasons.push('autoFixable');\n }\n\n if (issue.confidence < 0.7) {\n score -= 2;\n reasons.push(`low confidence (${(issue.confidence * 100).toFixed(0)}%)`);\n }\n\n if (issue.cwe) {\n score += 3;\n reasons.push(`cwe:${issue.cwe}`);\n }\n\n if (issue.owasp) {\n score += 2;\n reasons.push(`owasp:${issue.owasp}`);\n }\n\n if (issue.category === 'security') {\n score += 2;\n reasons.push('category:security');\n }\n\n // --- Signal Group 2: Context ---\n if (context) {\n if (context.hasTests) {\n score += 1;\n reasons.push('has tests');\n } else {\n score -= 2;\n reasons.push('no tests');\n }\n\n if (context.complexity === 'high') {\n score += 1;\n reasons.push('high complexity');\n }\n\n if (context.touchesAuth || context.touchesCrypto || context.touchesPayments) {\n score += 2;\n reasons.push('touches auth/crypto/payments');\n }\n\n if (context.touchesDatabase) {\n score += 1;\n reasons.push('touches database');\n }\n }\n\n // --- Signal Group 3: Occurrence History ---\n if (occurrence) {\n if (occurrence.count >= 5) {\n score += 3;\n reasons.push(`${occurrence.count}× seen`);\n } else if (occurrence.count >= 3) {\n score += 1;\n reasons.push(`${occurrence.count}× seen`);\n }\n\n if (occurrence.escalationLevel === 'block') {\n score += 4;\n reasons.push('escalation:block');\n } else if (occurrence.escalationLevel === 'escalate') {\n score += 2;\n reasons.push('escalation:escalate');\n }\n }\n\n // --- Signal Group 4: User Configuration ---\n if (config?.level === 'aggressive') {\n score -= 1;\n reasons.push('aggressive mode (−1 threshold)');\n }\n\n // --- Signal Group 5: Pipeline Context ---\n if (pipeline) {\n if (pipeline.hasLinkedPR && pipeline.prState === 'open') {\n score -= 2;\n reasons.push('has open PR');\n }\n\n if (pipeline.hasLinkedTicket && pipeline.ticketStatus?.toLowerCase().includes('started')) {\n score -= 1;\n reasons.push('ticket in active sprint');\n }\n\n if (pipeline.hasLinkedTicket && pipeline.ticketPriority === 'urgent') {\n score += 1;\n reasons.push('ticket:urgent');\n }\n\n if (!pipeline.hasLinkedTicket && !pipeline.hasLinkedPR && issue.severity === 'critical') {\n score += 2;\n reasons.push('critical, no ticket/PR (falling through cracks)');\n }\n }\n\n // --- Score → Strategy ---\n let strategy: FixStrategy;\n if (score < 0 && issue.autoFixable) {\n strategy = 'inline-auto';\n } else if (score < 4) {\n strategy = 'local-ai';\n } else {\n strategy = 'cloud-agent';\n }\n\n const confidence = Math.min(1, Math.abs(score) / 8);\n\n return { strategy, score, confidence, reasons, fallback: 'local-ai' };\n}\n\n// ============================================================================\n// Batch triage\n// ============================================================================\n\nexport function triageIssues(\n issues: Issue[],\n context?: CodeContext,\n occurrences?: Map<string, IssueOccurrence>,\n config?: AutonomyConfig,\n pipelineContexts?: Map<string, PipelineContext>,\n): { results: Map<string, TriageResult>; summary: TriageSummary } {\n const results = new Map<string, TriageResult>();\n const summary: TriageSummary = {\n inlineAuto: [],\n localAi: [],\n cloudAgent: [],\n cloudAgentScore: 0,\n };\n\n for (const issue of issues) {\n const occurrence = occurrences?.get(issue.id);\n const pipeline = pipelineContexts?.get(issue.id);\n const result = triageIssue(issue, context, occurrence, config, pipeline);\n results.set(issue.id, result);\n\n switch (result.strategy) {\n case 'inline-auto':\n summary.inlineAuto.push(issue);\n break;\n case 'local-ai':\n summary.localAi.push(issue);\n break;\n case 'cloud-agent':\n summary.cloudAgent.push(issue);\n summary.cloudAgentScore += result.score;\n break;\n }\n }\n\n return { results, summary };\n}\n\n// ============================================================================\n// Formatted output\n// ============================================================================\n\nexport function formatTriageTable(\n results: Map<string, TriageResult>,\n issues: Issue[],\n): string {\n const LINE = '\\u2500'.repeat(68);\n const lines: string[] = [];\n\n lines.push('FIX ROUTING PLAN');\n lines.push(LINE);\n lines.push(\n padEnd('Issue', 32) +\n padEnd('Strategy', 14) +\n padEnd('Score', 7) +\n 'Reason',\n );\n\n for (const issue of issues) {\n const r = results.get(issue.id);\n if (!r) continue;\n const loc = `${shortPath(issue.file)}:${issue.line ?? '?'}`;\n const scoreStr = r.score >= 0 ? `+${r.score}` : String(r.score);\n lines.push(\n padEnd(loc, 32) +\n padEnd(r.strategy, 14) +\n padEnd(scoreStr, 7) +\n r.reasons.join(', '),\n );\n }\n\n lines.push(LINE);\n\n const counts: string[] = [];\n const cloud = issues.filter(i => results.get(i.id)?.strategy === 'cloud-agent');\n const local = issues.filter(i => results.get(i.id)?.strategy === 'local-ai');\n const auto = issues.filter(i => results.get(i.id)?.strategy === 'inline-auto');\n\n if (cloud.length) counts.push(`${cloud.length} for cloud agent`);\n if (local.length) counts.push(`${local.length} for local AI`);\n if (auto.length) counts.push(`${auto.length} auto-fixable`);\n lines.push(counts.join(', '));\n\n if (cloud.length > 0) {\n const ids = cloud.map(i => `\"${i.id}\"`).join(',');\n lines.push('');\n lines.push(`To dispatch cloud issues: trie_cloud_fix action:dispatch issueIds:[${ids}]`);\n }\n if (local.length > 0) {\n const ids = local.map(i => `\"${i.id}\"`).join(',');\n lines.push(`To fix local issues: trie_fix issueIds:[${ids}]`);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Build the cloud recommendation footer appended after trie_fix completes,\n * when skipped/pending issues score >= 4.\n */\nexport function formatCloudRecommendation(\n results: Map<string, TriageResult>,\n issues: Issue[],\n): string | null {\n const cloud = issues.filter(i => {\n const r = results.get(i.id);\n return r && r.score >= 4;\n });\n\n if (cloud.length === 0) return null;\n\n const LINE = '\\u2500'.repeat(65);\n const lines: string[] = [];\n\n lines.push(LINE);\n lines.push(\n `${cloud.length} issue${cloud.length > 1 ? 's' : ''} qualify for cloud agent verification (test-verified fix + PR):`,\n );\n\n for (const issue of cloud) {\n const r = results.get(issue.id)!;\n const loc = `${shortPath(issue.file)}:${issue.line ?? '?'}`;\n const scoreStr = r.score >= 0 ? `+${r.score}` : String(r.score);\n lines.push(` \\u2022 ${padEnd(loc, 30)} \\u2014 score ${scoreStr} (${r.reasons.join(', ')})`);\n }\n\n const ids = cloud.map(i => `\"${i.id}\"`).join(',');\n lines.push('');\n lines.push(`Run: trie_cloud_fix action:dispatch issueIds:[${ids}]`);\n lines.push(LINE);\n\n return lines.join('\\n');\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction shortPath(file: string): string {\n const parts = file.split('/');\n return parts.length > 2 ? parts.slice(-2).join('/') : file;\n}\n\nfunction padEnd(str: string, len: number): string {\n if (str.length >= len) return str.slice(0, len);\n return str + ' '.repeat(len - str.length);\n}\n","/**\n * Cloud Fix Tool — `trie_cloud_fix`\n *\n * Dispatches issues to Cursor cloud agents for verified, test-passing fixes.\n * Modes: configure, dispatch, status, artifacts, cancel.\n *\n * Job state persists in `.trie/cloud-jobs.json`.\n */\n\nimport { readFile, writeFile, mkdir } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join } from 'path';\nimport { execSync } from 'child_process';\n\nimport type { Issue } from '../types/index.js';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport { loadAutonomyConfig, saveAutonomyConfig } from '../utils/autonomy-config.js';\nimport { CursorCloudAgentClient } from '../integrations/cursor-cloud-agent.js';\nimport { triageIssues, formatTriageTable } from './fix-triage.js';\nimport { getPendingFixes } from './fix.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\ninterface CloudJobRecord {\n issueId: string;\n jobId: string;\n status: 'dispatched' | 'running' | 'verified' | 'failed';\n score: number;\n strategy: 'cloud-agent';\n dispatchedAt: string;\n artifactUrls: string[];\n prUrl: string | null;\n}\n\ninterface CloudJobsStore {\n jobs: Record<string, CloudJobRecord>;\n}\n\n// ============================================================================\n// Tool\n// ============================================================================\n\nexport class TrieCloudFixTool {\n async execute(args: any) {\n const { action = 'status' } = args || {};\n\n switch (action) {\n case 'configure':\n return this.configure(args);\n case 'dispatch':\n return this.dispatch(args);\n case 'status':\n return this.status();\n case 'artifacts':\n return this.artifacts(args);\n case 'cancel':\n return this.cancel(args);\n default:\n return this.text(`Unknown action \"${action}\". Use: configure | dispatch | status | artifacts | cancel`);\n }\n }\n\n // --------------------------------------------------------------------------\n // configure\n // --------------------------------------------------------------------------\n\n private async configure(args: any) {\n const apiKey: string | undefined = args?.apiKey || process.env.CURSOR_API_KEY;\n if (!apiKey) {\n return this.text(\n 'Missing API key.\\n\\n' +\n 'Usage: trie_cloud_fix action:configure apiKey:\"key-...\"\\n' +\n 'Or set: export CURSOR_API_KEY=\"key-...\"',\n );\n }\n\n const workDir = getWorkingDirectory(undefined, true);\n await saveAutonomyConfig(workDir, { cloudAgentEnabled: true, cursorApiKey: apiKey });\n\n return this.text('Cursor API key saved. Cloud agent dispatch enabled.');\n }\n\n // --------------------------------------------------------------------------\n // dispatch\n // --------------------------------------------------------------------------\n\n private async dispatch(args: any) {\n console.log('Cloud dispatch starting...');\n const workDir = getWorkingDirectory(undefined, true);\n\n const apiKey = await this.resolveApiKey(workDir);\n if (!apiKey) return this.setupGuard();\n\n const config = await loadAutonomyConfig(workDir);\n\n console.log('About to resolve issues...');\n const allIssues = await this.resolveIssues(args?.issueIds);\n console.log(`Resolved ${allIssues.length} issues`);\n\n if (allIssues.length === 0) {\n return this.text('No issues to dispatch. Run trie_scan to detect new issues, or check memory with trie_memory action:recent.');\n }\n\n const { results, summary } = triageIssues(allIssues, undefined, undefined, config);\n\n const lines: string[] = [];\n\n // Print routing table for transparency\n lines.push(formatTriageTable(results, allIssues));\n lines.push('');\n\n // Skip non-cloud issues with a reason\n for (const issue of allIssues) {\n const r = results.get(issue.id);\n if (r && r.strategy !== 'cloud-agent') {\n lines.push(`Skipped ${issue.id}: routed to ${r.strategy} (score ${r.score >= 0 ? '+' : ''}${r.score} — ${r.reasons.join(', ')})`);\n }\n }\n\n if (summary.cloudAgent.length === 0) {\n lines.push('\\nNo issues qualify for cloud dispatch. Use trie_fix for local fixes.');\n return this.text(lines.join('\\n'));\n }\n\n // Dispatch\n const client = new CursorCloudAgentClient(apiKey);\n const repoUrl = this.getRepoUrl(workDir);\n const branch = this.getBranch(workDir);\n const store = await this.loadJobs(workDir);\n\n lines.push('\\nDISPATCHED');\n\n for (const issue of summary.cloudAgent) {\n const triageResult = results.get(issue.id)!;\n try {\n const job = await client.dispatch(issue, triageResult, repoUrl, branch);\n\n store.jobs[issue.id] = {\n issueId: issue.id,\n jobId: job.jobId,\n status: 'dispatched',\n score: triageResult.score,\n strategy: 'cloud-agent',\n dispatchedAt: job.dispatchedAt,\n artifactUrls: [],\n prUrl: null,\n };\n\n lines.push(` ${issue.id} ${shortPath(issue.file)}:${issue.line ?? '?'} job:${job.jobId} (score +${triageResult.score})`);\n } catch (err: any) {\n lines.push(` ${issue.id} FAILED: ${err.message}`);\n }\n }\n\n await this.saveJobs(workDir, store);\n\n lines.push('');\n lines.push('Cloud agents are running in isolated VMs. Check back with:');\n lines.push('trie_cloud_fix action:status');\n\n return this.text(lines.join('\\n'));\n }\n\n // --------------------------------------------------------------------------\n // status\n // --------------------------------------------------------------------------\n\n private async status() {\n const workDir = getWorkingDirectory(undefined, true);\n const apiKey = await this.resolveApiKey(workDir);\n if (!apiKey) return this.setupGuard();\n\n const store = await this.loadJobs(workDir);\n const entries = Object.values(store.jobs);\n\n if (entries.length === 0) {\n return this.text('No cloud jobs. Dispatch with: trie_cloud_fix action:dispatch');\n }\n\n const client = new CursorCloudAgentClient(apiKey);\n const LINE = '\\u2500'.repeat(68);\n const lines: string[] = ['JOB STATUS', LINE];\n lines.push(padEnd('Issue', 32) + padEnd('Status', 12) + padEnd('PR', 28) + 'Age');\n\n for (const job of entries) {\n if (job.status === 'dispatched' || job.status === 'running') {\n try {\n const poll = await client.poll(job.jobId);\n if (poll.status === 'completed' && poll.prUrl) {\n job.status = 'verified';\n job.prUrl = poll.prUrl;\n } else if (poll.status === 'running') {\n job.status = 'running';\n } else if (poll.status === 'failed') {\n job.status = 'failed';\n }\n if (poll.artifactUrls.length) {\n job.artifactUrls = poll.artifactUrls;\n }\n } catch {\n // poll failure is non-fatal; show last known status\n }\n }\n\n const age = formatAge(job.dispatchedAt);\n const pr = job.prUrl ?? '\\u2014';\n lines.push(padEnd(job.issueId, 32) + padEnd(job.status, 12) + padEnd(pr, 28) + age);\n }\n\n lines.push(LINE);\n await this.saveJobs(workDir, store);\n\n return this.text(lines.join('\\n'));\n }\n\n // --------------------------------------------------------------------------\n // artifacts\n // --------------------------------------------------------------------------\n\n private async artifacts(args: any) {\n const workDir = getWorkingDirectory(undefined, true);\n const apiKey = await this.resolveApiKey(workDir);\n if (!apiKey) return this.setupGuard();\n\n const store = await this.loadJobs(workDir);\n const jobId: string | undefined = args?.jobId;\n\n const targets = jobId\n ? Object.values(store.jobs).filter(j => j.jobId === jobId)\n : Object.values(store.jobs).filter(j => j.status === 'verified');\n\n if (targets.length === 0) {\n return this.text(jobId ? `No job found with id ${jobId}` : 'No completed jobs with artifacts.');\n }\n\n const client = new CursorCloudAgentClient(apiKey);\n const lines: string[] = [];\n\n for (const job of targets) {\n try {\n const artifacts = await client.getArtifacts(job.jobId);\n job.artifactUrls = artifacts;\n } catch {\n // use cached artifacts\n }\n\n lines.push(`Issue: ${job.issueId}`);\n lines.push(`PR: ${job.prUrl ?? 'N/A'}`);\n for (const url of job.artifactUrls) {\n const ext = url.split('.').pop();\n const label = ext === 'mp4' || ext === 'webm' ? 'Video' : 'Screenshot';\n lines.push(`${label}: ${url}`);\n }\n if (job.status === 'verified') {\n lines.push('Agent verified: all tests pass with this fix applied.');\n }\n lines.push('');\n }\n\n await this.saveJobs(workDir, store);\n return this.text(lines.join('\\n'));\n }\n\n // --------------------------------------------------------------------------\n // cancel\n // --------------------------------------------------------------------------\n\n private async cancel(args: any) {\n const workDir = getWorkingDirectory(undefined, true);\n const apiKey = await this.resolveApiKey(workDir);\n if (!apiKey) return this.setupGuard();\n\n const jobId: string | undefined = args?.jobId;\n if (!jobId) {\n return this.text('Provide jobId to cancel. Example: trie_cloud_fix action:cancel jobId:\"cursor-task-xyz\"');\n }\n\n const store = await this.loadJobs(workDir);\n const entry = Object.values(store.jobs).find(j => j.jobId === jobId);\n if (!entry) {\n return this.text(`Job ${jobId} not found in cloud-jobs.json.`);\n }\n\n const client = new CursorCloudAgentClient(apiKey);\n try {\n await client.cancelJob(jobId);\n } catch (err: any) {\n return this.text(`Cancel failed: ${err.message}`);\n }\n\n delete store.jobs[entry.issueId];\n await this.saveJobs(workDir, store);\n\n return this.text(`Job ${jobId} cancelled and removed.`);\n }\n\n // --------------------------------------------------------------------------\n // Helpers\n // --------------------------------------------------------------------------\n\n private async resolveApiKey(workDir: string): Promise<string | null> {\n if (process.env.CURSOR_API_KEY) return process.env.CURSOR_API_KEY;\n const config = await loadAutonomyConfig(workDir);\n return config.cursorApiKey ?? null;\n }\n\n private setupGuard() {\n return this.text(\n 'Cloud Agent dispatch requires a Cursor API key.\\n\\n' +\n 'Get your key at: cursor.com/settings \\u2192 API Keys\\n' +\n 'Then run: trie_cloud_fix action:configure apiKey:\"key-...\"\\n\\n' +\n 'Or set the environment variable: export CURSOR_API_KEY=\"key-...\"',\n );\n }\n\n private async resolveIssues(issueIds?: string[]): Promise<Issue[]> {\n // First try to get pending fixes\n let pending = getPendingFixes();\n\n // If no pending fixes, try to load from memory directly\n if (pending.length === 0) {\n try {\n console.log('Loading issues from memory...');\n const { getRecentIssues } = await import('../memory/issue-store.js');\n const recentIssues = await getRecentIssues({ limit: 50, includeResolved: false });\n console.log(`Found ${recentIssues.length} recent issues in memory`);\n\n // Convert StoredIssue to Issue format for cloud dispatch\n const memoryIssues: Issue[] = recentIssues.map(storedIssue => ({\n id: storedIssue.id,\n severity: (storedIssue.severity || 'moderate') as any,\n issue: storedIssue.issue,\n fix: storedIssue.fix,\n file: storedIssue.file,\n line: storedIssue.line,\n confidence: 0.8, // Default confidence for memory issues\n autoFixable: true, // Memory issues are generally auto-fixable\n agent: storedIssue.agent,\n category: storedIssue.category,\n }));\n\n console.log(`Converted ${memoryIssues.length} memory issues for cloud dispatch`);\n\n if (issueIds && issueIds.length > 0) {\n return memoryIssues.filter(i => issueIds.includes(i.id));\n }\n return memoryIssues;\n } catch (error) {\n console.warn('Failed to load issues from memory:', error);\n console.warn('Error details:', error);\n }\n }\n\n const issues: Issue[] = pending.map(p => ({\n id: p.id,\n severity: p.severity ?? 'moderate',\n effort: p.effort,\n issue: p.issue,\n fix: p.suggestedFix,\n file: p.file,\n line: p.line,\n confidence: p.confidence,\n autoFixable: p.autoFixable ?? false,\n agent: 'trie_scan',\n cwe: p.cwe,\n owasp: p.owasp,\n category: p.category,\n }));\n\n if (issueIds && issueIds.length > 0) {\n return issues.filter(i => issueIds.includes(i.id));\n }\n return issues;\n }\n\n private getRepoUrl(workDir: string): string {\n try {\n return execSync('git remote get-url origin', { cwd: workDir, encoding: 'utf-8' }).trim();\n } catch {\n return 'unknown';\n }\n }\n\n private getBranch(workDir: string): string {\n try {\n return execSync('git rev-parse --abbrev-ref HEAD', { cwd: workDir, encoding: 'utf-8' }).trim();\n } catch {\n return 'main';\n }\n }\n\n private async loadJobs(workDir: string): Promise<CloudJobsStore> {\n const path = join(getTrieDirectory(workDir), 'cloud-jobs.json');\n try {\n if (existsSync(path)) {\n const raw = await readFile(path, 'utf-8');\n return JSON.parse(raw) as CloudJobsStore;\n }\n } catch {\n // corrupt file — start fresh\n }\n return { jobs: {} };\n }\n\n private async saveJobs(workDir: string, store: CloudJobsStore): Promise<void> {\n const trieDir = getTrieDirectory(workDir);\n if (!existsSync(trieDir)) await mkdir(trieDir, { recursive: true });\n const path = join(trieDir, 'cloud-jobs.json');\n await writeFile(path, JSON.stringify(store, null, 2));\n }\n\n private text(msg: string) {\n return { content: [{ type: 'text' as const, text: msg }] };\n }\n}\n\n// ============================================================================\n// Formatting helpers\n// ============================================================================\n\nfunction formatAge(isoDate: string): string {\n const ms = Date.now() - new Date(isoDate).getTime();\n const mins = Math.floor(ms / 60_000);\n if (mins < 60) return `${mins}m`;\n const hrs = Math.floor(mins / 60);\n if (hrs < 24) return `${hrs}h ${mins % 60}m`;\n return `${Math.floor(hrs / 24)}d`;\n}\n\nfunction shortPath(file: string): string {\n const parts = file.split('/');\n return parts.length > 2 ? parts.slice(-2).join('/') : file;\n}\n\nfunction padEnd(str: string, len: number): string {\n if (str.length >= len) return str.slice(0, len);\n return str + ' '.repeat(len - str.length);\n}\n","/**\n * Cursor Cloud Agent REST Client\n *\n * Thin wrapper around the Cursor Cloud Agent API.\n * Uses native `fetch` — no new npm dependencies.\n */\n\nimport type { Issue } from '../types/index.js';\nimport type { TriageResult } from '../tools/fix-triage.js';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface CloudAgentJob {\n jobId: string;\n status: 'dispatched' | 'running' | 'verified' | 'failed';\n prUrl?: string;\n artifactUrls: string[];\n dispatchedAt: string;\n verifiedAt?: string;\n}\n\nexport interface CloudAgentStatus {\n status: 'pending' | 'running' | 'completed' | 'failed';\n prUrl?: string | undefined;\n artifactUrls: string[];\n}\n\n// ============================================================================\n// Client\n// ============================================================================\n\nconst BASE_URL = 'https://api.cursor.com/v1';\n\nexport class CursorCloudAgentClient {\n private apiKey: string;\n\n constructor(apiKey: string) {\n this.apiKey = apiKey;\n }\n\n /**\n * Dispatch an issue to a cloud agent for fixing.\n */\n async dispatch(\n issue: Issue,\n triageResult: TriageResult,\n repoUrl: string,\n branch: string,\n ): Promise<CloudAgentJob> {\n const prompt = this.buildPrompt(issue, triageResult);\n\n const body = {\n prompt,\n repo: repoUrl,\n branch,\n metadata: {\n issueId: issue.id,\n file: issue.file,\n line: issue.line,\n severity: issue.severity,\n agent: issue.agent,\n },\n };\n\n const res = await this.request('POST', '/agents/tasks', body);\n\n return {\n jobId: res.id ?? res.taskId ?? res.jobId,\n status: 'dispatched',\n artifactUrls: [],\n dispatchedAt: new Date().toISOString(),\n };\n }\n\n /**\n * Poll job status.\n */\n async poll(jobId: string): Promise<CloudAgentStatus> {\n const res = await this.request('GET', `/agents/tasks/${jobId}`);\n\n const status = mapStatus(res.status);\n const prUrl = extractPrUrl(res);\n const artifactUrls = this.extractArtifacts(res);\n\n return { status, prUrl, artifactUrls };\n }\n\n /**\n * Get artifact URLs for a completed job.\n */\n async getArtifacts(jobId: string): Promise<string[]> {\n const res = await this.request('GET', `/agents/tasks/${jobId}`);\n return this.extractArtifacts(res);\n }\n\n /**\n * Cancel a running job.\n */\n async cancelJob(jobId: string): Promise<void> {\n await this.request('DELETE', `/agents/tasks/${jobId}`);\n }\n\n // --------------------------------------------------------------------------\n // Internal\n // --------------------------------------------------------------------------\n\n private buildPrompt(issue: Issue, triageResult: TriageResult): string {\n const parts: string[] = [\n 'You are fixing a verified issue in the codebase.',\n '',\n `Issue: ${issue.issue}`,\n `File: ${issue.file}${issue.line ? `:${issue.line}` : ''}`,\n `Severity: ${issue.severity} | Effort: ${issue.effort ?? 'medium'}`,\n `Agent that found it: ${issue.agent}`,\n `Suggested fix: ${issue.fix}`,\n ];\n\n if (issue.cwe) parts.push(`CWE: ${issue.cwe}`);\n if (issue.owasp) parts.push(`OWASP: ${issue.owasp}`);\n\n parts.push(`Triage confidence: ${triageResult.confidence.toFixed(2)}`);\n parts.push(`Why cloud agent: ${triageResult.reasons.join(', ')}`);\n parts.push('');\n parts.push('Steps:');\n parts.push(`1. Apply the minimal fix described above to ${issue.file}`);\n parts.push('2. Run the existing test suite (detect test runner from package.json scripts)');\n parts.push('3. Screenshot the passing test output — this is the verification artifact');\n parts.push('4. If tests fail, iterate on the fix until they pass (max 3 attempts)');\n parts.push('5. Open a PR with only this single change — do not bundle other fixes');\n parts.push('6. Include the screenshot in the PR description as evidence');\n\n return parts.join('\\n');\n }\n\n private async request(method: string, path: string, body?: unknown): Promise<any> {\n const url = `${BASE_URL}${path}`;\n const headers: Record<string, string> = {\n 'Authorization': `Bearer ${this.apiKey}`,\n 'Content-Type': 'application/json',\n };\n\n const init: RequestInit = { method, headers };\n if (body) init.body = JSON.stringify(body);\n\n const res = await fetch(url, init);\n\n if (res.status === 401) {\n throw new Error(\n 'Cursor API key is invalid or expired.\\n' +\n 'Update it: trie_cloud_fix action:configure apiKey:\"key-...\"',\n );\n }\n if (res.status === 404) {\n throw new Error(`Job not found: ${path}`);\n }\n if (res.status >= 500) {\n throw new Error(\n `Cursor API returned ${res.status}. The service may be temporarily unavailable — retry in a few minutes.`,\n );\n }\n if (!res.ok) {\n const text = await res.text().catch(() => '');\n throw new Error(`Cursor API error ${res.status}: ${text}`);\n }\n\n return res.json();\n }\n\n private extractArtifacts(res: any): string[] {\n const urls: string[] = [];\n\n if (Array.isArray(res.messages)) {\n for (const msg of res.messages) {\n if (typeof msg.content === 'string') {\n const matches = msg.content.match(/https:\\/\\/[^\\s)]+\\.(png|jpg|mp4|webm)/g);\n if (matches) urls.push(...matches);\n }\n }\n }\n\n if (Array.isArray(res.artifacts)) {\n for (const a of res.artifacts) {\n if (a.url) urls.push(a.url);\n }\n }\n\n return [...new Set(urls)];\n }\n}\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction mapStatus(raw: string | undefined): CloudAgentStatus['status'] {\n switch (raw) {\n case 'pending':\n case 'queued':\n return 'pending';\n case 'running':\n case 'in_progress':\n return 'running';\n case 'completed':\n case 'succeeded':\n case 'verified':\n return 'completed';\n default:\n return 'failed';\n }\n}\n\nfunction extractPrUrl(res: any): string | undefined {\n if (typeof res.prUrl === 'string') return res.prUrl;\n if (typeof res.pr_url === 'string') return res.pr_url;\n if (typeof res.pullRequestUrl === 'string') return res.pullRequestUrl;\n\n if (Array.isArray(res.messages)) {\n for (const msg of res.messages) {\n if (typeof msg.content === 'string') {\n const match = msg.content.match(/https:\\/\\/github\\.com\\/[^\\s)]+\\/pull\\/\\d+/);\n if (match) return match[0];\n }\n }\n }\n\n return undefined;\n}\n","import { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { extname, relative, resolve, isAbsolute, dirname, basename, join } from 'path';\nimport { getPrompt, getSystemPrompt } from '../ai/prompts.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\n/**\n * Test Tool - AI-powered test generation and coverage analysis\n * \n * This tool can:\n * - Generate comprehensive tests for code\n * - Analyze test coverage gaps\n * - Suggest test improvements\n */\n\ninterface TestableUnit {\n name: string;\n type: 'function' | 'class' | 'method' | 'component';\n startLine: number;\n endLine: number;\n signature: string;\n complexity: number;\n dependencies: string[];\n}\n\nexport class TrieTestTool {\n async execute(args: any) {\n const { action, files, framework, style = 'unit' } = args || {};\n\n if (!action || !files || files.length === 0) {\n return {\n content: [{\n type: 'text',\n text: this.getHelpText()\n }]\n };\n }\n\n switch (action) {\n case 'generate':\n return this.generateTests(files, framework, style);\n case 'coverage':\n return this.analyzeCoverage(files);\n case 'suggest':\n return this.suggestTests(files);\n case 'run':\n return this.runTestsInfo(files);\n default:\n return {\n content: [{\n type: 'text',\n text: `Unknown action: ${action}`\n }]\n };\n }\n }\n\n private async generateTests(files: string[], framework?: string, style?: string) {\n const detectedFramework = framework || await this.detectTestFramework();\n \n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `🧪 TEST GENERATION\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## ⚙️ Configuration\\n\\n`;\n output += `- **Framework:** ${detectedFramework}\\n`;\n output += `- **Style:** ${style}\\n`;\n output += `- **Files:** ${files.length}\\n\\n`;\n\n const workDir = getWorkingDirectory(undefined, true);\n const allUnits: { file: string; units: TestableUnit[] }[] = [];\n\n for (const file of files) {\n const resolvedPath = isAbsolute(file) ? file : resolve(workDir, file);\n \n if (!existsSync(resolvedPath)) {\n output += `[!] File not found: ${file}\\n`;\n continue;\n }\n\n const code = await readFile(resolvedPath, 'utf-8');\n const language = this.detectLanguage(resolvedPath);\n const relativePath = relative(workDir, resolvedPath);\n const units = this.extractTestableUnits(code, language);\n\n allUnits.push({ file: relativePath, units });\n\n output += `### 📄 ${relativePath}\\n\\n`;\n output += `Found **${units.length}** testable units:\\n\\n`;\n\n for (const unit of units) {\n const complexityIcon = unit.complexity > 10 ? '🔴' : unit.complexity > 5 ? '🟡' : '🟢';\n output += `- ${complexityIcon} \\`${unit.name}\\` (${unit.type}, complexity: ${unit.complexity})\\n`;\n if (unit.dependencies.length > 0) {\n output += ` - Dependencies: ${unit.dependencies.join(', ')}\\n`;\n }\n }\n output += '\\n';\n }\n\n // Generate the test file content\n output += `${'─'.repeat(60)}\\n`;\n output += `## 🧠 Test Generation Request\\n\\n`;\n \n const systemPrompt = getSystemPrompt('test');\n output += `**Role:** ${systemPrompt.split('\\n')[0]}\\n\\n`;\n\n for (const { file, units } of allUnits) {\n if (units.length === 0) continue;\n\n const code = await readFile(resolve(workDir, file), 'utf-8');\n const language = this.detectLanguage(file);\n\n const prompt = getPrompt('test', 'generate', {\n code,\n language,\n filePath: file,\n framework: detectedFramework,\n });\n\n output += `### Tests for ${file}\\n\\n`;\n output += prompt;\n output += '\\n\\n';\n }\n\n output += `${'─'.repeat(60)}\\n`;\n output += `\\n## 📝 Expected Test Output\\n\\n`;\n output += `Generate complete test files with:\\n`;\n output += `- All imports and setup\\n`;\n output += `- Tests for each function/method\\n`;\n output += `- Edge cases and error scenarios\\n`;\n output += `- Mock requirements clearly stated\\n`;\n output += `- Ready to copy and run\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async analyzeCoverage(files: string[]) {\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `📊 COVERAGE ANALYSIS\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n const workDir = getWorkingDirectory(undefined, true);\n\n for (const file of files) {\n const resolvedPath = isAbsolute(file) ? file : resolve(workDir, file);\n \n if (!existsSync(resolvedPath)) {\n output += `[!] File not found: ${file}\\n`;\n continue;\n }\n\n const code = await readFile(resolvedPath, 'utf-8');\n const language = this.detectLanguage(resolvedPath);\n const relativePath = relative(workDir, resolvedPath);\n const units = this.extractTestableUnits(code, language);\n\n // Try to find existing tests\n const testFile = await this.findTestFile(resolvedPath);\n let testCode = '';\n let testedUnits: string[] = [];\n\n if (testFile) {\n testCode = await readFile(testFile, 'utf-8');\n testedUnits = this.findTestedUnits(testCode, units.map(u => u.name));\n }\n\n const coverage = units.length > 0 \n ? Math.round((testedUnits.length / units.length) * 100)\n : 0;\n\n const coverageIcon = coverage >= 80 ? '🟢' : coverage >= 50 ? '🟡' : '🔴';\n\n output += `### 📄 ${relativePath}\\n\\n`;\n output += `**Coverage:** ${coverageIcon} ${coverage}% (${testedUnits.length}/${units.length} units)\\n`;\n if (testFile) {\n output += `**Test file:** \\`${relative(workDir, testFile)}\\`\\n`;\n } else {\n output += `**Test file:** ❌ Not found\\n`;\n }\n output += '\\n';\n\n // Show what's tested and what's not\n const untested = units.filter(u => !testedUnits.includes(u.name));\n \n if (untested.length > 0) {\n output += `**Missing Tests:**\\n`;\n for (const unit of untested) {\n const priority = unit.complexity > 5 ? '🔴 HIGH' : '🟡 MEDIUM';\n output += `- ${priority}: \\`${unit.name}\\` (${unit.type})\\n`;\n }\n output += '\\n';\n }\n\n if (testedUnits.length > 0) {\n output += `**Tested:**\\n`;\n for (const name of testedUnits) {\n output += `- ✅ \\`${name}\\`\\n`;\n }\n output += '\\n';\n }\n }\n\n output += `${'─'.repeat(60)}\\n`;\n output += `## 📋 Recommendations\\n\\n`;\n output += `To improve coverage:\\n`;\n output += `1. Focus on high-complexity untested functions first\\n`;\n output += `2. Add edge case tests for existing coverage\\n`;\n output += `3. Consider integration tests for complex interactions\\n`;\n output += `\\nRun \\`trie_test action:generate files:[\"file.ts\"]\\` to generate missing tests.\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async suggestTests(files: string[]) {\n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `💡 TEST SUGGESTIONS\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n const workDir = getWorkingDirectory(undefined, true);\n\n for (const file of files) {\n const resolvedPath = isAbsolute(file) ? file : resolve(workDir, file);\n \n if (!existsSync(resolvedPath)) {\n output += `[!] File not found: ${file}\\n`;\n continue;\n }\n\n const code = await readFile(resolvedPath, 'utf-8');\n const relativePath = relative(workDir, resolvedPath);\n \n // Analyze patterns that need testing\n const patterns = this.detectTestablePatterns(code);\n\n output += `### 📄 ${relativePath}\\n\\n`;\n\n if (patterns.length === 0) {\n output += `No specific test suggestions for this file.\\n\\n`;\n continue;\n }\n\n output += `| Priority | Pattern | Suggested Test |\\n`;\n output += `|----------|---------|----------------|\\n`;\n \n for (const pattern of patterns) {\n output += `| ${pattern.priority} | ${pattern.name} | ${pattern.suggestion} |\\n`;\n }\n output += '\\n';\n }\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async runTestsInfo(files: string[]) {\n const framework = await this.detectTestFramework();\n \n let output = `\\n${'━'.repeat(60)}\\n`;\n output += `RUN TESTS\\n`;\n output += `${'━'.repeat(60)}\\n\\n`;\n\n output += `## Detected Configuration\\n\\n`;\n output += `- **Framework:** ${framework}\\n`;\n output += `- **Files:** ${files.join(', ')}\\n\\n`;\n\n output += `## Commands\\n\\n`;\n\n switch (framework) {\n case 'jest':\n output += `\\`\\`\\`bash\\n`;\n output += `# Run all tests\\n`;\n output += `npx jest\\n\\n`;\n output += `# Run specific files\\n`;\n output += `npx jest ${files.join(' ')}\\n\\n`;\n output += `# Run with coverage\\n`;\n output += `npx jest --coverage\\n`;\n output += `\\`\\`\\`\\n`;\n break;\n case 'vitest':\n output += `\\`\\`\\`bash\\n`;\n output += `# Run all tests\\n`;\n output += `npx vitest run\\n\\n`;\n output += `# Run specific files\\n`;\n output += `npx vitest run ${files.join(' ')}\\n\\n`;\n output += `# Run with coverage\\n`;\n output += `npx vitest run --coverage\\n`;\n output += `\\`\\`\\`\\n`;\n break;\n case 'pytest':\n output += `\\`\\`\\`bash\\n`;\n output += `# Run all tests\\n`;\n output += `pytest\\n\\n`;\n output += `# Run specific files\\n`;\n output += `pytest ${files.join(' ')}\\n\\n`;\n output += `# Run with coverage\\n`;\n output += `pytest --cov\\n`;\n output += `\\`\\`\\`\\n`;\n break;\n default:\n output += `Run your test framework with the specified files.\\n`;\n }\n\n output += `\\n*Note: This tool provides test commands but doesn't execute them directly.*\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private extractTestableUnits(code: string, language: string): TestableUnit[] {\n const units: TestableUnit[] = [];\n const lines = code.split('\\n');\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i] || '';\n\n // Function declarations\n const funcMatch = line.match(/(?:export\\s+)?(?:async\\s+)?function\\s+(\\w+)\\s*\\(([^)]*)\\)/);\n if (funcMatch) {\n const endLine = this.findBlockEnd(lines, i);\n const body = lines.slice(i, endLine + 1).join('\\n');\n units.push({\n name: funcMatch[1]!,\n type: 'function',\n startLine: i + 1,\n endLine: endLine + 1,\n signature: `${funcMatch[1]}(${funcMatch[2]})`,\n complexity: this.calculateComplexity(body),\n dependencies: this.extractDependencies(body),\n });\n }\n\n // Arrow functions\n const arrowMatch = line.match(/(?:export\\s+)?(?:const|let)\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\([^)]*\\)\\s*(?:=>|:)/);\n if (arrowMatch) {\n const endLine = this.findBlockEnd(lines, i);\n const body = lines.slice(i, endLine + 1).join('\\n');\n units.push({\n name: arrowMatch[1]!,\n type: 'function',\n startLine: i + 1,\n endLine: endLine + 1,\n signature: arrowMatch[1]!,\n complexity: this.calculateComplexity(body),\n dependencies: this.extractDependencies(body),\n });\n }\n\n // Classes\n const classMatch = line.match(/(?:export\\s+)?class\\s+(\\w+)/);\n if (classMatch) {\n const endLine = this.findBlockEnd(lines, i);\n units.push({\n name: classMatch[1]!,\n type: 'class',\n startLine: i + 1,\n endLine: endLine + 1,\n signature: `class ${classMatch[1]}`,\n complexity: this.calculateComplexity(lines.slice(i, endLine + 1).join('\\n')),\n dependencies: [],\n });\n }\n\n // React components\n const componentMatch = line.match(/(?:export\\s+)?(?:const|function)\\s+([A-Z]\\w+)\\s*[=:]/);\n if (componentMatch && /jsx|tsx/.test(language)) {\n const endLine = this.findBlockEnd(lines, i);\n units.push({\n name: componentMatch[1]!,\n type: 'component',\n startLine: i + 1,\n endLine: endLine + 1,\n signature: componentMatch[1]!,\n complexity: this.calculateComplexity(lines.slice(i, endLine + 1).join('\\n')),\n dependencies: this.extractDependencies(lines.slice(i, endLine + 1).join('\\n')),\n });\n }\n }\n\n return units;\n }\n\n private findBlockEnd(lines: string[], startLine: number): number {\n let braceCount = 0;\n let started = false;\n\n for (let i = startLine; i < lines.length; i++) {\n const line = lines[i] || '';\n \n for (const char of line) {\n if (char === '{') {\n braceCount++;\n started = true;\n } else if (char === '}') {\n braceCount--;\n }\n }\n\n if (started && braceCount === 0) {\n return i;\n }\n }\n\n return lines.length - 1;\n }\n\n private calculateComplexity(code: string): number {\n let complexity = 1;\n const patterns = [\n /if\\s*\\(/g, /else\\s+if/g, /\\?\\s*[^:]/g, // Conditionals\n /for\\s*\\(/g, /while\\s*\\(/g, /do\\s*\\{/g, // Loops\n /catch\\s*\\(/g, // Error handling\n /&&/g, /\\|\\|/g, // Logical operators\n /case\\s+/g, // Switch cases\n ];\n\n for (const pattern of patterns) {\n const matches = code.match(pattern);\n if (matches) {\n complexity += matches.length;\n }\n }\n\n return complexity;\n }\n\n private extractDependencies(code: string): string[] {\n const deps: string[] = [];\n \n // Look for function calls\n const calls = code.match(/\\b([a-z]\\w+)\\s*\\(/gi) || [];\n const builtins = ['if', 'for', 'while', 'switch', 'catch', 'function', 'return', 'throw', 'new', 'await', 'async'];\n \n for (const call of calls) {\n const name = call.replace(/\\s*\\($/, '');\n if (!builtins.includes(name.toLowerCase()) && !deps.includes(name)) {\n deps.push(name);\n }\n }\n\n return deps.slice(0, 10); // Limit to 10\n }\n\n private async findTestFile(sourcePath: string): Promise<string | null> {\n const dir = dirname(sourcePath);\n const base = basename(sourcePath, extname(sourcePath));\n const ext = extname(sourcePath);\n\n // Common test file patterns\n const patterns = [\n `${base}.test${ext}`,\n `${base}.spec${ext}`,\n `${base}_test${ext}`,\n `test_${base}${ext}`,\n ];\n\n // Check same directory\n for (const pattern of patterns) {\n const testPath = join(dir, pattern);\n if (existsSync(testPath)) {\n return testPath;\n }\n }\n\n // Check __tests__ directory\n const testsDir = join(dir, '__tests__');\n if (existsSync(testsDir)) {\n for (const pattern of patterns) {\n const testPath = join(testsDir, pattern);\n if (existsSync(testPath)) {\n return testPath;\n }\n }\n }\n\n return null;\n }\n\n private findTestedUnits(testCode: string, unitNames: string[]): string[] {\n const tested: string[] = [];\n\n for (const name of unitNames) {\n // Look for the name in test descriptions or assertions\n const patterns = [\n new RegExp(`describe\\\\s*\\\\([^)]*${name}`, 'i'),\n new RegExp(`it\\\\s*\\\\([^)]*${name}`, 'i'),\n new RegExp(`test\\\\s*\\\\([^)]*${name}`, 'i'),\n new RegExp(`expect\\\\s*\\\\([^)]*${name}`, 'i'),\n ];\n\n for (const pattern of patterns) {\n if (pattern.test(testCode)) {\n tested.push(name);\n break;\n }\n }\n }\n\n return tested;\n }\n\n private detectTestablePatterns(code: string): Array<{ priority: string; name: string; suggestion: string }> {\n const patterns: Array<{ priority: string; name: string; suggestion: string }> = [];\n\n const checks = [\n { pattern: /async\\s+function|await\\s+/i, priority: '🔴 HIGH', name: 'Async code', suggestion: 'Test async flows and error handling' },\n { pattern: /try\\s*{[^}]*catch/i, priority: '🔴 HIGH', name: 'Error handling', suggestion: 'Test both success and error paths' },\n { pattern: /if\\s*\\([^)]*&&[^)]*\\)/i, priority: '🟡 MED', name: 'Complex conditionals', suggestion: 'Test all condition branches' },\n { pattern: /\\.map\\(|\\.filter\\(|\\.reduce\\(/i, priority: '🟡 MED', name: 'Array operations', suggestion: 'Test with empty, single, multiple items' },\n { pattern: /fetch\\(|axios\\.|request\\(/i, priority: '🔴 HIGH', name: 'HTTP requests', suggestion: 'Mock API calls, test error responses' },\n { pattern: /localStorage|sessionStorage/i, priority: '🟡 MED', name: 'Storage usage', suggestion: 'Mock storage, test read/write' },\n { pattern: /setTimeout|setInterval/i, priority: '🟡 MED', name: 'Timers', suggestion: 'Use fake timers in tests' },\n { pattern: /useState|useEffect|useCallback/i, priority: '🔴 HIGH', name: 'React hooks', suggestion: 'Test hook behavior and updates' },\n { pattern: /form|input|submit/i, priority: '🟡 MED', name: 'Form handling', suggestion: 'Test validation and submission' },\n ];\n\n for (const { pattern, priority, name, suggestion } of checks) {\n if (pattern.test(code)) {\n patterns.push({ priority, name, suggestion });\n }\n }\n\n return patterns;\n }\n\n private async detectTestFramework(): Promise<string> {\n const workDir = getWorkingDirectory(undefined, true);\n const packagePath = resolve(workDir, 'package.json');\n \n if (existsSync(packagePath)) {\n try {\n const pkg = JSON.parse(await readFile(packagePath, 'utf-8'));\n const deps = { ...pkg.dependencies, ...pkg.devDependencies };\n \n if (deps.vitest) return 'vitest';\n if (deps.jest) return 'jest';\n if (deps.mocha) return 'mocha';\n } catch {\n // Ignore parse errors\n }\n }\n\n // Check for pytest\n if (existsSync(resolve(workDir, 'pytest.ini')) ||\n existsSync(resolve(workDir, 'pyproject.toml'))) {\n return 'pytest';\n }\n\n return 'jest'; // Default\n }\n\n private detectLanguage(filePath: string): string {\n const ext = extname(filePath).toLowerCase();\n const langMap: Record<string, string> = {\n '.ts': 'typescript', '.tsx': 'tsx', '.js': 'javascript', '.jsx': 'jsx',\n '.py': 'python', '.go': 'go', '.rs': 'rust',\n };\n return langMap[ext] || 'javascript';\n }\n\n private getHelpText(): string {\n return `\n${'━'.repeat(60)}\n🧪 TRIE TEST - AI-POWERED TEST GENERATION\n${'━'.repeat(60)}\n\n## Usage\n\n### Generate tests:\n\\`\\`\\`\ntrie_test action:\"generate\" files:[\"src/utils.ts\"]\n\\`\\`\\`\n\n### Analyze coverage:\n\\`\\`\\`\ntrie_test action:\"coverage\" files:[\"src/utils.ts\"]\n\\`\\`\\`\n\n### Get test suggestions:\n\\`\\`\\`\ntrie_test action:\"suggest\" files:[\"src/app.ts\"]\n\\`\\`\\`\n\n### Get run commands:\n\\`\\`\\`\ntrie_test action:\"run\" files:[\"src/utils.test.ts\"]\n\\`\\`\\`\n\n## Options\n\n| Option | Values | Description |\n|--------|--------|-------------|\n| action | generate, coverage, suggest, run | What to do |\n| files | Array of paths | Files to analyze |\n| framework | jest, vitest, mocha, pytest | Test framework |\n| style | unit, integration, e2e, all | Test style |\n`;\n }\n}\n","import { watch, existsSync, readFileSync } from 'fs';\nimport { stat, readFile } from 'fs/promises';\nimport { join, extname, basename } from 'path';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport { StreamingManager } from '../utils/streaming.js';\nimport { InteractiveDashboard } from '../cli/interactive-dashboard.js';\nimport { isInteractiveMode } from '../utils/progress.js';\nimport { getOutputManager } from '../utils/output-manager.js';\nimport { isTrieInitialized } from '../utils/trie-init.js';\nimport { ExtractionPipeline } from '../extraction/pipeline.js';\nimport { isAIAvailable, runAIAnalysis } from '../ai/client.js';\nimport { ContextGraph } from '../context/graph.js';\nimport type { FileNodeData } from '../context/nodes.js';\nimport { getAutonomyConfig } from '../utils/autonomy-config.js';\nimport { loadConfig } from '../config/loader.js';\nimport { getGitChangedFiles, getChangedFilesSinceTimestamp } from '../agent/git.js';\nimport { CodebaseIndex } from '../context/codebase-index.js';\nimport { getStorage } from '../storage/tiered-storage.js';\nimport type { Nudge } from '../types/signal.js';\nimport { createHash } from 'crypto';\nimport { storeIssues } from '../memory/issue-store.js';\nimport type { Issue } from '../types/index.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 TokenBudget {\n used: number;\n windowStart: number;\n hourlyLimit: number;\n scansSaved: number;\n}\n\ninterface WatchState {\n isRunning: boolean;\n lastScan: Map<string, number>;\n pendingFiles: Set<string>;\n scanDebounceTimer: NodeJS.Timeout | null;\n issueCache: Map<string, any[]>;\n totalIssuesFound: number;\n filesScanned: number;\n nudgedFiles: Set<string>;\n nudges: Array<{\n file: string;\n message: string;\n severity: 'high' | 'critical';\n timestamp: string;\n }>;\n lastAutoScan: number;\n autoScanInProgress: boolean;\n tokenBudget: TokenBudget;\n cleanFiles: Map<string, number>; // file -> timestamp of last clean scan (no issues found)\n}\n\nexport class TrieWatchTool {\n private extractionPipeline: ExtractionPipeline | null = null;\n private watchedDirectory: string = '';\n private codebaseIndex: CodebaseIndex | null = null;\n\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 nudgedFiles: new Set(),\n nudges: [],\n lastAutoScan: 0,\n autoScanInProgress: false,\n tokenBudget: {\n used: 0,\n windowStart: Date.now(),\n hourlyLimit: 50_000,\n scansSaved: 0,\n },\n cleanFiles: new Map(),\n };\n private watchers: Map<string, ReturnType<typeof watch>> = new Map();\n private streamingManager: StreamingManager | undefined = undefined;\n private dashboard: InteractiveDashboard | undefined = undefined;\n private lastHypothesisCheck: number = 0;\n private pipelineSyncTimer: NodeJS.Timeout | null = null;\n private static HYPOTHESIS_CHECK_INTERVAL_MS = 300_000; // Check every 5 minutes\n private static PIPELINE_SYNC_INTERVAL_MS = 30 * 60 * 1000; // 30 minutes\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 await this.stopWatching();\n case 'status':\n return await this.getStatus();\n case 'issues':\n return this.getCurrentIssues();\n case 'nudges':\n return this.getNudges();\n default:\n return {\n content: [{\n type: 'text',\n text: `Unknown action: ${action}. Use 'start', 'stop', 'status', or 'issues'.`\n }]\n };\n }\n }\n\n private async startWatching(directory: string, debounceMs: number) {\n if (this.state.isRunning) {\n return {\n content: [{\n type: 'text',\n text: '[!] Watch mode is already running. Use `trie_watch stop` to stop it first.'\n }]\n };\n }\n if (!isTrieInitialized(directory)) {\n return {\n content: [{\n type: 'text',\n text: 'Trie is not initialized for this project. Run `trie init` first.'\n }]\n };\n }\n\n // Initialize extraction pipeline for autonomous learning\n const anthropicApiKey = process.env.ANTHROPIC_API_KEY;\n if (anthropicApiKey) {\n this.extractionPipeline = new ExtractionPipeline({\n workingDirectory: directory,\n anthropicApiKey,\n });\n await this.extractionPipeline.initialize();\n }\n\n // Initialize codebase index for fast file lookups and goal checking\n this.codebaseIndex = new CodebaseIndex(directory);\n\n this.state.isRunning = true;\n this.watchedDirectory = directory;\n this.state.issueCache.clear();\n this.state.totalIssuesFound = 0;\n this.state.filesScanned = 0;\n this.state.nudgedFiles.clear();\n this.state.nudges = [];\n\n // Load existing unresolved nudges from SQL storage\n try {\n const storage = getStorage(directory);\n await storage.initialize();\n const unresolvedNudges = await storage.queryNudges({ resolved: false });\n\n console.debug(`[Watch] Found ${unresolvedNudges.length} unresolved nudges in storage`);\n\n // Convert stored nudges to in-memory format\n for (const nudge of unresolvedNudges) {\n // Map all severity levels to the in-memory format\n let mappedSeverity: 'high' | 'critical' = 'high';\n if (nudge.severity === 'critical') {\n mappedSeverity = 'critical';\n } else if (nudge.severity === 'high') {\n mappedSeverity = 'high';\n }\n // For 'warning' and 'info', we map to 'high' since those are the only two supported in-memory\n\n this.state.nudges.push({\n file: nudge.file || 'unknown', // Keep full path, don't use basename\n message: nudge.message,\n severity: mappedSeverity,\n timestamp: new Date(nudge.timestamp).toLocaleTimeString('en-US', { hour12: false }),\n });\n\n console.debug(`[Watch] Loaded nudge: ${nudge.message.slice(0, 60)}... (${nudge.severity} -> ${mappedSeverity})`);\n }\n\n if (unresolvedNudges.length > 0) {\n console.log(`[Watch] ✓ Loaded ${unresolvedNudges.length} unresolved nudges from storage`);\n } else {\n console.debug(`[Watch] No unresolved nudges found in storage`);\n }\n } catch (error) {\n console.error('[Watch] Failed to load nudges from storage:', error);\n }\n\n // Skip banner output in interactive mode (dashboard handles display)\n if (!isInteractiveMode()) {\n console.error('\\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');\n console.error('TRIE AGENT - NOW WATCHING');\n console.error('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\\n');\n console.error('Your Trie agent is now watching over your codebase.');\n console.error('Signal extraction: ENABLED (building governance ledger)');\n console.error(`Watching: ${directory}`);\n console.error(`Debounce: ${debounceMs}ms`);\n console.error('');\n }\n\n // Initialize streaming + dashboard for interactive mode\n if (isInteractiveMode()) {\n this.streamingManager = new StreamingManager();\n this.dashboard = new InteractiveDashboard();\n this.streamingManager.subscribe(update => this.dashboard?.handleStreamUpdate(update));\n \n // Set up OutputManager for TUI mode\n const outputManager = getOutputManager();\n outputManager.setMode('tui');\n outputManager.setStreamingManager(this.streamingManager);\n \n await this.dashboard.start();\n this.streamingManager.reportWatchStatus({ watching: true, directories: 0, debounceMs });\n } else {\n // Console mode\n getOutputManager().setMode('console');\n }\n\n // Start watching the directory recursively\n await this.watchDirectory(directory, debounceMs);\n\n // Report watch status immediately\n if (this.streamingManager) {\n this.streamingManager.reportWatchStatus({\n watching: true,\n directories: this.watchers.size,\n debounceMs\n });\n }\n\n // Run initial scans after a small delay to ensure proper initialization\n setTimeout(() => {\n // Check recent files against active goals so users get immediate feedback\n void this.initialGoalComplianceScan();\n\n // Run initial hypothesis generation to provide insights from the start\n void this.initialHypothesisGeneration();\n\n // Initial pipeline sync + start periodic timer\n void this.syncPipelineIntegrations();\n }, 1000); // 1 second delay to allow proper initialization\n\n this.pipelineSyncTimer = setInterval(() => {\n void this.syncPipelineIntegrations();\n }, TrieWatchTool.PIPELINE_SYNC_INTERVAL_MS);\n\n // Check if codebase index exists\n const indexStatus = this.codebaseIndex?.isEmpty() \n ? 'BUILDING (one-time, speeds up goal checks)' \n : 'READY';\n\n return {\n content: [{\n type: 'text',\n text: `**TRIE AGENT ACTIVATED** \n\nYour Trie agent is now autonomously watching and learning from your codebase.\n\n**Watching:** \\`${directory}\\`\n**Debounce:** ${debounceMs}ms (waits for you to stop typing)\n**Signal Extraction:** ${process.env.ANTHROPIC_API_KEY ? 'ENABLED' : 'LIMITED (set ANTHROPIC_API_KEY for full extraction)'}\n**Codebase Index:** ${indexStatus}\n\n### How the agent works:\n1. You write/edit code\n2. Agent detects the change\n3. Extracts governance, facts, blockers -> stores in ledger\n4. Predicts risks based on historical patterns\n5. Nudges you if something looks risky\n\n### The agent learns:\n- Every commit builds the governance ledger\n- \\`trie gotcha\\` queries the ledger for predictions\n- \\`trie ok\\` / \\`trie bad\\` teach the agent what matters\n\n### Commands:\n- \\`trie_watch status\\` - See agent status\n- \\`trie_watch stop\\` - Stop the agent\n- \\`trie_index status\\` - Check codebase index`\n }]\n };\n }\n\n private shouldSkipPath(filePath: string): boolean {\n const parts = filePath.split('/');\n return parts.some(p => SKIP_DIRS.has(p) || (p.startsWith('.') && p !== '.'));\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 const watcher = watch(dir, { persistent: true, recursive: true }, (_eventType, filename) => {\n if (!filename) return;\n\n if (this.shouldSkipPath(filename)) return;\n\n const ext = extname(filename).toLowerCase();\n if (!WATCH_EXTENSIONS.has(ext)) return;\n\n const fullPath = join(dir, filename);\n if (!existsSync(fullPath)) return;\n\n this.state.pendingFiles.add(fullPath);\n\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 watcher.on('error', (err) => {\n if (!isInteractiveMode()) {\n console.error(`[!] Watcher error: ${err.message}`);\n }\n // Close the watcher and remove from map to prevent memory leak\n watcher.close();\n this.watchers.delete(dir);\n });\n\n this.watchers.set(dir, watcher);\n\n if (this.streamingManager) {\n this.streamingManager.reportWatchStatus({\n watching: true,\n directories: 1,\n debounceMs\n });\n }\n } catch {\n // Skip directories we can't access\n }\n }\n\n private async processPendingFiles() {\n if (this.state.pendingFiles.size === 0) return;\n\n const files = Array.from(this.state.pendingFiles);\n this.state.pendingFiles.clear();\n\n if (!isInteractiveMode()) {\n console.error(`\\nDetected changes in ${files.length} file(s):`);\n for (const file of files) {\n console.error(` - ${basename(file)}`);\n }\n console.error('');\n }\n\n try {\n const projectPath = this.watchedDirectory || getWorkingDirectory(undefined, true);\n \n // === Autonomous signal extraction from file changes ===\n if (this.extractionPipeline) {\n try {\n // Read changed files and extract signals\n const fileContents = await Promise.all(\n files.map(async (file) => {\n try {\n const content = await readFile(file, 'utf-8');\n return { file, content };\n } catch {\n return null;\n }\n })\n );\n\n // Extract signals from file changes\n const validFiles = fileContents.filter(f => f !== null);\n if (validFiles.length > 0) {\n const combinedContent = validFiles.map(f => \n `File: ${basename(f!.file)}\\n${f!.content.slice(0, 1000)}` // First 1KB of each file\n ).join('\\n\\n---\\n\\n');\n\n if (!isInteractiveMode()) {\n console.error('[*] Extracting signals from changes...');\n }\n\n const signal = await this.extractionPipeline.process(combinedContent, {\n sourceType: 'file',\n sourceId: `watch-${Date.now()}`,\n });\n\n if (signal.governance.length > 0 || signal.facts.length > 0 || signal.blockers.length > 0) {\n const govCount = signal.governance.length;\n if (!isInteractiveMode()) {\n console.error(` [+] Extracted: ${govCount} governance, ${signal.facts.length} facts, ${signal.blockers.length} blockers`);\n }\n \n if (this.streamingManager) {\n this.streamingManager.reportSignalExtraction({\n governance: govCount,\n facts: signal.facts.length,\n blockers: signal.blockers.length,\n questions: signal.questions.length,\n });\n }\n }\n }\n } catch (error) {\n if (!isInteractiveMode()) {\n console.error(` [!] Signal extraction failed: ${error}`);\n }\n }\n }\n\n // AI watcher: primary detection system for code issues AND goal violations.\n // Always runs -- the method itself handles throttling and budget.\n void this.autoScanFiles(files).catch(err => {\n getOutputManager().log('warn', `Auto scan failed: ${err}`);\n });\n \n // Autonomous pattern discovery from recent issues\n await this.discoverPatternsFromIssues(projectPath);\n \n // Autonomous hypothesis generation (periodic check)\n const now = Date.now();\n if (now - this.lastHypothesisCheck > TrieWatchTool.HYPOTHESIS_CHECK_INTERVAL_MS) {\n this.checkAndGenerateHypotheses(projectPath);\n this.lastHypothesisCheck = now;\n }\n\n // Report file changes to TUI (deduplicate within 2s window)\n if (this.streamingManager) {\n const now = Date.now();\n for (const file of files) {\n const lastReport = this.state.lastScan.get(file) || 0;\n if (now - lastReport > 2000) {\n this.streamingManager.reportWatchChange(file);\n }\n }\n }\n \n // Update stats\n this.state.filesScanned += files.length;\n\n // Track processed files and update codebase index\n for (const file of files) {\n this.state.lastScan.set(file, Date.now());\n \n // Index the changed file for faster goal checking\n if (this.codebaseIndex) {\n const relativePath = file.replace(projectPath + '/', '');\n // Index and save immediately - ensures index is always up to date\n void this.codebaseIndex.indexFile(relativePath).then(() => {\n void this.codebaseIndex?.save();\n });\n }\n }\n\n } catch (error) {\n if (!isInteractiveMode()) {\n console.error(`Scan error: ${error}`);\n }\n }\n }\n\n private isQuiet(): boolean {\n const projectPath = this.watchedDirectory || getWorkingDirectory(undefined, true);\n const quietPath = join(getTrieDirectory(projectPath), 'quiet.json');\n try {\n const raw = readFileSync(quietPath, 'utf-8');\n const data = JSON.parse(raw);\n const until = new Date(data.until).getTime();\n return Date.now() < until;\n } catch {\n return false;\n }\n }\n\n\n /**\n * Check and generate hypotheses autonomously\n * Claude observes patterns and creates new hypotheses to test\n */\n private async checkAndGenerateHypotheses(projectPath: string): Promise<void> {\n if (!isAIAvailable()) return;\n \n try {\n const { getHypothesisEngine } = await import('../agent/hypothesis.js');\n const { getOutputManager } = await import('../utils/output-manager.js');\n \n const hypothesisEngine = getHypothesisEngine(projectPath);\n \n // Gather recent patterns and observations\n const recentIssues = Array.from(this.state.issueCache.values()).flat();\n const patterns: string[] = [];\n const observations: string[] = [];\n \n // Collect observable patterns from watch session\n if (this.state.nudges.length > 0) {\n const nudgesByFile: Record<string, number> = {};\n for (const nudge of this.state.nudges) {\n nudgesByFile[nudge.file] = (nudgesByFile[nudge.file] || 0) + 1;\n }\n \n const topFiles = Object.entries(nudgesByFile)\n .sort(([, a], [, b]) => b - a)\n .slice(0, 3);\n \n if (topFiles[0] && topFiles[0][1] > 2) {\n observations.push(`File ${topFiles[0][0]} has ${topFiles[0][1]} repeated issues this session`);\n }\n }\n \n if (this.state.nudges.length > 5) {\n observations.push(`High issue detection rate: ${this.state.nudges.length} violations detected in watch session`);\n }\n \n // Try AI-powered hypothesis generation first\n let generated = await hypothesisEngine.generateHypothesesWithAI({\n recentIssues,\n patterns,\n observations,\n });\n \n // Fall back to template-based if AI didn't generate any\n if (generated.length === 0) {\n generated = await hypothesisEngine.autoGenerateHypotheses();\n }\n \n // Nudge user about new hypotheses\n for (const hypothesis of generated) {\n const message = `[New Hypothesis] \"${hypothesis.statement}\" (${Math.round(hypothesis.confidence * 100)}% confidence)`;\n \n getOutputManager().nudge(\n message,\n 'info',\n undefined,\n 10000\n );\n \n if (!isInteractiveMode()) {\n console.error(`\\n [?] ${message}`);\n console.error(` Test: ${hypothesis.testCriteria || 'Collecting evidence...'}`);\n }\n \n // Report to TUI\n if (this.streamingManager) {\n this.streamingManager.reportSignalExtraction({\n governance: 0,\n facts: 0,\n blockers: 0,\n questions: 1, // Hypotheses are questions to answer\n });\n }\n }\n \n // Also update confidence on existing hypotheses\n if (recentIssues.length > 10) {\n await hypothesisEngine.updateConfidenceFromOutcomes();\n }\n \n } catch (error) {\n // Hypothesis generation is best-effort\n if (!isInteractiveMode()) {\n console.error(` [!] Hypothesis check failed: ${error}`);\n }\n }\n }\n\n /**\n * Discover patterns from accumulated issues\n * Patterns emerge naturally from your coding workflow\n */\n private async discoverPatternsFromIssues(projectPath: string): Promise<void> {\n // Only discover patterns if we have enough data\n const totalIssues = Array.from(this.state.issueCache.values())\n .flat()\n .length;\n \n if (totalIssues < 5) return; // Need at least 5 issues to find patterns\n \n try {\n const { ContextGraph } = await import('../context/graph.js');\n const { IncidentIndex } = await import('../context/incident-index.js');\n const { TriePatternDiscovery } = await import('../agent/pattern-discovery.js');\n \n const graph = new ContextGraph(projectPath);\n const incidentIndex = await IncidentIndex.build(graph, projectPath);\n const discovery = new TriePatternDiscovery(graph, incidentIndex);\n \n // Discover hot patterns (files/directories with 2+ issues)\n const hotPatterns = discovery.discoverHotPatterns(2); // Lower threshold for faster discovery\n \n for (const hot of hotPatterns) {\n // Check if pattern already exists\n const existingPatterns = await graph.listNodes();\n const alreadyExists = existingPatterns.some(\n n => n.type === 'pattern' && \n (n.data as any).description?.includes(hot.path)\n );\n \n if (!alreadyExists) {\n await graph.addNode('pattern', {\n description: `${hot.type === 'directory' ? 'Directory' : 'File'} hot zone: ${hot.path}`,\n appliesTo: [hot.path],\n confidence: Math.min(0.95, hot.confidence),\n occurrences: hot.incidentCount,\n firstSeen: new Date().toISOString(),\n lastSeen: new Date().toISOString(),\n isAntiPattern: hot.incidentCount >= 3, // 3+ incidents = anti-pattern\n source: 'local'\n });\n \n if (!isInteractiveMode()) {\n console.error(` [+] Pattern discovered: ${hot.path} (${hot.incidentCount} issues)`);\n }\n \n // Report to TUI\n if (this.streamingManager) {\n this.streamingManager.reportSignalExtraction({\n governance: 0,\n facts: 1, // Patterns are facts about the codebase\n blockers: 0,\n questions: 0,\n });\n }\n }\n }\n \n // Discover co-occurrence patterns (files that break together)\n if (totalIssues >= 10) {\n const coOccurrences = await discovery.discoverCoOccurrences(2); // 2+ co-occurrences\n \n for (const coOcc of coOccurrences.slice(0, 3)) { // Top 3 co-occurrence patterns\n const desc = `Files break together: ${coOcc.files[0]} + ${coOcc.files[1]}`;\n \n const existingPatterns = await graph.listNodes();\n const alreadyExists = existingPatterns.some(\n n => n.type === 'pattern' && \n (n.data as any).description === desc\n );\n \n if (!alreadyExists) {\n await graph.addNode('pattern', {\n description: desc,\n appliesTo: [...coOcc.files],\n confidence: Math.min(0.95, coOcc.confidence),\n occurrences: coOcc.coOccurrences,\n firstSeen: new Date().toISOString(),\n lastSeen: new Date().toISOString(),\n isAntiPattern: coOcc.confidence > 0.7,\n source: 'local'\n });\n \n if (!isInteractiveMode()) {\n console.error(` [+] Co-occurrence pattern: ${coOcc.files[0]} + ${coOcc.files[1]}`);\n }\n }\n }\n }\n } catch (error) {\n // Pattern discovery is best-effort\n if (!isInteractiveMode()) {\n console.error(` [!] Pattern discovery failed: ${error}`);\n }\n }\n }\n\n // Defaults -- overridden by config when loaded\n private aiWatcherCooldownMs = 30_000;\n private cleanFileCooldownMs = 300_000;\n private maxFilesPerScan = 5;\n private maxCharsPerFile = 4000;\n\n /**\n * Use the trie (context graph) to score how urgently a file needs scanning.\n * Higher score = more worth spending tokens on.\n */\n private async scoreScanPriority(\n file: string,\n graph: ContextGraph,\n projectPath: string,\n ): Promise<number> {\n let score = 1; // baseline: every changed file gets at least 1\n\n // Recently scanned clean → skip entirely\n const lastClean = this.state.cleanFiles.get(file);\n if (lastClean && Date.now() - lastClean < this.cleanFileCooldownMs) {\n return 0;\n }\n\n const fileNode = await graph.getNode('file', join(projectPath, file));\n if (!fileNode) return score; // unknown file, scan at baseline\n\n const data = fileNode.data as FileNodeData;\n\n // Risk level is the biggest signal\n const riskScores: Record<string, number> = { critical: 10, high: 6, medium: 2, low: 1 };\n score += riskScores[data.riskLevel] ?? 1;\n\n // Past incidents make a file worth watching closely\n score += Math.min(data.incidentCount * 3, 12);\n\n // High churn files have more surface area for bugs\n if (data.changeCount > 10) score += 2;\n\n return score;\n }\n\n /**\n * Roll the token budget window if an hour has passed.\n * Returns remaining tokens in the current window.\n */\n private getRemainingBudget(): number {\n const budget = this.state.tokenBudget;\n const elapsed = Date.now() - budget.windowStart;\n if (elapsed > 3_600_000) {\n budget.used = 0;\n budget.windowStart = Date.now();\n }\n return Math.max(0, budget.hourlyLimit - budget.used);\n }\n\n private recordTokenUsage(tokens: number) {\n this.state.tokenBudget.used += tokens;\n }\n\n /**\n * AI-powered watcher -- the primary detection system.\n * \n * This is the single AI call that handles:\n * 1. Code review (bugs, security, logic errors)\n * 2. Goal violation detection (user-defined quality goals)\n * \n * When goals are active, files with goal violations bypass priority scoring\n * so violations are always caught. Throttled by cooldown + token budget.\n */\n private async autoScanFiles(files: string[]) {\n if (!isAIAvailable()) return;\n if (this.state.autoScanInProgress) return;\n\n const now = Date.now();\n if (now - this.state.lastAutoScan < this.aiWatcherCooldownMs) return;\n\n // Set the flag early to prevent concurrent scans - will be reset in finally block\n this.state.autoScanInProgress = true;\n this.state.lastAutoScan = now;\n\n const projectPath = this.watchedDirectory || getWorkingDirectory(undefined, true);\n\n try {\n // Load AI watcher config\n try {\n const config = await getAutonomyConfig(projectPath);\n const wc = config.aiWatcher;\n if (!wc.enabled) return;\n this.state.tokenBudget.hourlyLimit = wc.hourlyTokenLimit;\n this.aiWatcherCooldownMs = wc.scanCooldownSec * 1000;\n this.cleanFileCooldownMs = wc.cleanFileCooldownSec * 1000;\n this.maxFilesPerScan = wc.maxFilesPerScan;\n this.maxCharsPerFile = wc.maxCharsPerFile;\n } catch { /* use current values */ }\n\n const remaining = this.getRemainingBudget();\n if (remaining < 500) return;\n\n try {\n const graph = new ContextGraph(projectPath);\n\n // Load active goals -- these drive the AI watcher's behavior\n const { getActiveGoals, recordGoalViolationCaught } = await import('../agent/goal-validator.js');\n\n console.debug('[AI Watcher] Loading active goals...');\n const activeGoals = await getActiveGoals(projectPath);\n const hasGoals = activeGoals.length > 0;\n\n console.debug('[AI Watcher] Goals loaded:', {\n totalGoals: activeGoals.length,\n hasGoals,\n goals: activeGoals.map(g => ({ id: g.id, description: g.description, status: g.status }))\n });\n\n // In quiet mode, only run if goals are active (goals always get checked)\n if (this.isQuiet() && !hasGoals) return;\n\n // Use the Trie's priority scoring to rank files by risk.\n // When goals are active, every changed file is included (min score 1)\n // so the AI can check them all against user goals.\n // When no goals, low-risk files are skipped to save tokens.\n const scored: Array<{ file: string; relativePath: string; score: number }> = [];\n for (const file of files) {\n const relativePath = file.replace(projectPath + '/', '');\n const score = await this.scoreScanPriority(relativePath, graph, projectPath);\n if (hasGoals || score > 0) {\n scored.push({ file, relativePath, score: Math.max(score, hasGoals ? 1 : 0) });\n } else {\n this.state.tokenBudget.scansSaved++;\n }\n }\n\n if (scored.length === 0) return;\n\n // Sort by Trie priority -- highest-risk files first\n scored.sort((a, b) => b.score - a.score);\n\n // Budget-aware file cap: use configured max, scale down when budget is low\n const budgetScale = remaining > 20_000 ? 1.0 : remaining > 10_000 ? 0.6 : 0.4;\n const maxFiles = Math.max(1, Math.round(this.maxFilesPerScan * budgetScale));\n const filesToScan = scored.slice(0, maxFiles);\n\n // Truncate content per file -- scale down with budget\n const charLimit = Math.round(this.maxCharsPerFile * (remaining > 15_000 ? 1.0 : 0.5));\n\n const fileContents = await Promise.all(\n filesToScan.map(async ({ file, relativePath }) => {\n try {\n const content = await readFile(file, 'utf-8');\n return { path: relativePath, content: content.slice(0, charLimit) };\n } catch { return null; }\n })\n );\n const valid = fileContents.filter(Boolean) as Array<{ path: string; content: string }>;\n if (valid.length === 0) return;\n\n const filesBlock = valid.map(f =>\n `### ${f.path}\\n\\`\\`\\`\\n${f.content}\\n\\`\\`\\``\n ).join('\\n\\n');\n\n // Build the prompt -- goals are first-class\n let goalsSection = '';\n if (hasGoals) {\n goalsSection = `\nUSER-DEFINED GOALS (IMPORTANT - check EVERY file against ALL goals):\n${activeGoals.map((g, i) => ` ${i + 1}. \"${g.description}\"`).join('\\n')}\n\nGoal violations are HIGH PRIORITY. If a file violates any goal, you MUST report it.\n`;\n }\n\n console.debug('[AI Watcher] Sending files to AI analysis:', {\n fileCount: valid.length,\n hasGoals,\n goalsIncluded: hasGoals,\n filePaths: valid.map(f => f.path),\n goalsSection: goalsSection.slice(0, 200) + (goalsSection.length > 200 ? '...' : '')\n });\n\n const result = await runAIAnalysis({\n systemPrompt: `You are a code quality watcher. You review code for two things:\n\n1. CODE ISSUES: bugs, security vulnerabilities, logic errors, risky patterns\n2. GOAL VIOLATIONS: check every file against the user's quality goals\n${goalsSection}\nReply ONLY with a JSON array. Each element must have:\n- \"file\": relative file path\n- \"severity\": \"critical\" | \"major\" | \"minor\"\n- \"description\": 1-sentence description of what you found\n- \"confidence\": number 0-100, how confident you are this is a real issue\n- \"suggestedFix\": 1-sentence description of what should change to fix it\n- \"isGoalViolation\": true if this violates a user goal, false otherwise\n- \"goalIndex\": 0-based index of the violated goal (only if isGoalViolation is true)\n\nBe thorough with goal checking. If a goal says \"no emojis\" and you see an emoji anywhere in the file, report it with the exact location. If a goal says \"no inline styles\" and you see a style attribute, report it.\n\nIf no issues or violations found, reply with: []\nOutput ONLY the JSON array, no markdown fences, no commentary.`,\n userPrompt: `Review these changed files:\\n\\n${filesBlock}`,\n maxTokens: 2048,\n temperature: 0.1,\n });\n\n if (result.tokensUsed) {\n this.recordTokenUsage(result.tokensUsed.input + result.tokensUsed.output);\n }\n\n console.debug('[AI Watcher] AI analysis result:', {\n success: result.success,\n contentLength: result.content ? result.content.length : 0,\n tokensUsed: result.tokensUsed,\n contentPreview: result.content ? result.content.slice(0, 500) : 'null'\n });\n\n if (!result.success || !result.content.trim()) {\n console.debug('[AI Watcher] AI analysis failed or returned empty content');\n return;\n }\n\n let issues: Array<{\n file: string;\n severity: string;\n description: string;\n confidence?: number;\n suggestedFix?: string;\n isGoalViolation?: boolean;\n goalIndex?: number;\n }> = [];\n try {\n const cleaned = result.content.replace(/```json?\\n?|\\n?```/g, '').trim();\n console.debug('[AI Watcher] Parsing AI response:', { cleanedContent: cleaned.slice(0, 300) });\n issues = JSON.parse(cleaned);\n if (!Array.isArray(issues)) issues = [];\n console.debug('[AI Watcher] Parsed issues:', {\n totalIssues: issues.length,\n goalViolations: issues.filter(i => i.isGoalViolation).length,\n issueTypes: issues.map(i => ({ file: i.file, isGoalViolation: i.isGoalViolation, goalIndex: i.goalIndex }))\n });\n } catch (error) {\n console.debug('[AI Watcher] Failed to parse AI response:', error);\n return;\n }\n\n // Mark clean files\n const issuedFiles = new Set(issues.map(i => i.file));\n for (const { relativePath } of filesToScan) {\n if (!issuedFiles.has(relativePath)) {\n this.state.cleanFiles.set(relativePath, Date.now());\n }\n }\n\n if (issues.length === 0) return;\n\n for (const issue of issues.slice(0, 10)) {\n const severity = issue.severity === 'critical' ? 'critical'\n : issue.severity === 'major' ? 'major' : 'minor';\n\n // Handle goal violations: create a pending fix for user approval\n if (issue.isGoalViolation && issue.goalIndex != null && issue.goalIndex >= 0 && issue.goalIndex < activeGoals.length) {\n const goal = activeGoals[issue.goalIndex];\n if (!goal) continue; // Defensive check\n const confidence = Math.min(100, Math.max(0, issue.confidence ?? 80));\n const fixId = `fix-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n\n console.debug('[AI Watcher] Goal violation detected:', {\n goalDescription: goal.description,\n file: issue.file,\n violation: issue.description,\n confidence,\n goalIndex: issue.goalIndex,\n totalActiveGoals: activeGoals.length\n });\n\n // Store as a proper Issue so it's queryable by measureGoalMetric\n const goalViolationIssue: Issue = {\n id: fixId,\n file: issue.file,\n agent: 'goal-violation',\n severity: severity === 'critical' ? 'critical' : severity === 'major' ? 'serious' : 'moderate',\n issue: `Goal \"${goal.description}\" violated: ${issue.description}`,\n fix: issue.suggestedFix || 'Review and fix',\n category: 'goal-violation',\n confidence,\n autoFixable: true,\n };\n await storeIssues([goalViolationIssue], basename(projectPath), projectPath);\n await recordGoalViolationCaught(goal, issue.file, projectPath);\n\n // Nudge with confidence -- ask the user if they want it fixed\n const confidenceStr = `${confidence}%`;\n const nudgeMsg = `Goal \"${goal.description}\" violated in ${issue.file}: ${issue.description} [${confidenceStr} confidence]`;\n\n console.debug('[AI Watcher] Sending nudge:', {\n message: nudgeMsg,\n file: issue.file,\n severity: 'warning'\n });\n\n getOutputManager().nudge(nudgeMsg, 'warning', issue.file);\n\n // Persist nudge to both memory and SQL\n await this.persistNudge({\n message: nudgeMsg,\n severity: 'warning',\n file: issue.file,\n category: 'quality',\n goalId: goal.id,\n priority: 7,\n suggestedAction: issue.suggestedFix || 'Review and fix manually',\n relatedIssues: [fixId]\n });\n\n // Emit a pending fix to the TUI for interactive approval\n if (this.streamingManager) {\n this.streamingManager.reportPendingFix({\n id: fixId,\n file: issue.file,\n description: issue.description,\n goalDescription: goal.description,\n confidence,\n severity: issue.severity,\n suggestedFix: issue.suggestedFix || 'Remove the violating code',\n });\n }\n\n if (!isInteractiveMode()) {\n console.error(` [!] Goal violation (${confidenceStr}): ${issue.description}`);\n console.error(` Fix: ${issue.suggestedFix || 'Review and fix manually'}`);\n }\n continue;\n }\n\n // Standard code issue -- add to context graph\n const incident = await graph.addNode('incident', {\n description: issue.description,\n severity,\n affectedUsers: null,\n duration: null,\n timestamp: new Date().toISOString(),\n resolved: false,\n resolution: null,\n fixChangeId: null,\n reportedVia: 'detected',\n });\n\n const filePath = join(projectPath, issue.file);\n const fileNode = await graph.getNode('file', filePath);\n if (fileNode) {\n await graph.addEdge(fileNode.id, incident.id, 'affects');\n const data = fileNode.data as FileNodeData;\n const newRisk = severity === 'critical' ? 'critical'\n : severity === 'major' ? 'high'\n : data.riskLevel === 'low' ? 'medium' : data.riskLevel;\n await graph.updateNode('file', fileNode.id, {\n incidentCount: (data.incidentCount ?? 0) + 1,\n riskLevel: newRisk,\n });\n }\n\n this.state.totalIssuesFound++;\n\n if (severity !== 'minor') {\n getOutputManager().nudge(\n `${issue.description}`,\n severity === 'critical' ? 'critical' : 'warning',\n issue.file,\n severity === 'critical' ? undefined : 15000,\n );\n \n // Persist nudge to both memory and SQL\n await this.persistNudge({\n message: issue.description,\n severity: severity === 'critical' ? 'critical' : 'warning',\n file: issue.file,\n category: 'quality',\n priority: severity === 'critical' ? 9 : 6,\n ...(issue.suggestedFix && { suggestedAction: issue.suggestedFix }),\n });\n }\n }\n\n if (this.streamingManager && issues.length > 0) {\n this.streamingManager.reportSignalExtraction({\n governance: 0,\n facts: 0,\n blockers: issues.length,\n questions: 0,\n });\n }\n } catch (error) {\n getOutputManager().log('warn', `AI watcher error: ${error}`);\n }\n } finally {\n this.state.autoScanInProgress = false;\n }\n }\n\n /**\n * Initial hypothesis generation when watch starts.\n *\n * This generates hypotheses from existing patterns and issues to give\n * users immediate insights about their codebase.\n */\n private async initialHypothesisGeneration() {\n if (!isAIAvailable()) {\n console.debug('[Initial Hypothesis] AI not available, skipping initial hypothesis generation');\n return;\n }\n\n const projectPath = this.watchedDirectory || getWorkingDirectory(undefined, true);\n\n console.debug('[Initial Hypothesis] Starting initial hypothesis generation', { projectPath });\n\n try {\n const { getHypothesisEngine } = await import('../agent/hypothesis.js');\n const hypothesisEngine = getHypothesisEngine(projectPath);\n\n console.debug('[Initial Hypothesis] Running AI-powered hypothesis generation...');\n\n // Generate hypotheses from existing patterns and codebase state\n const generated = await hypothesisEngine.generateHypothesesWithAI({\n recentIssues: [], // No recent issues yet on startup\n patterns: [],\n observations: ['Initial watch session started', 'Analyzing codebase for potential patterns'],\n });\n\n console.debug('[Initial Hypothesis] Generated hypotheses on startup:', {\n count: generated.length,\n hypotheses: generated.map(h => ({ statement: h.statement, confidence: h.confidence }))\n });\n\n // Notify user about new hypotheses\n if (generated.length > 0) {\n const { getOutputManager } = await import('../utils/output-manager.js');\n const outputManager = getOutputManager();\n\n for (const hypothesis of generated.slice(0, 2)) { // Limit to 2 on startup to avoid spam\n const message = `[Initial Hypothesis] \"${hypothesis.statement}\" (${Math.round(hypothesis.confidence * 100)}% confidence)`;\n\n outputManager.nudge(message, 'info', undefined, 10000);\n\n if (!isInteractiveMode()) {\n console.error(` [?] ${message}`);\n }\n }\n\n // Report to TUI\n if (this.streamingManager) {\n this.streamingManager.reportSignalExtraction({\n governance: 0,\n facts: 0,\n blockers: 0,\n questions: generated.length,\n });\n }\n }\n\n } catch (error) {\n console.debug('[Initial Hypothesis] Failed to generate initial hypotheses:', error);\n }\n }\n\n /**\n * Initial goal compliance scan when watch starts.\n * \n * This checks recently modified files against active goals so the user\n * gets immediate feedback about goal violations without waiting for files\n * to be changed.\n * \n * Strategy:\n * 1. Check if there are any active goals - if not, skip\n * 2. Find recently modified files (last 24 hours OR uncommitted changes)\n * 3. Filter to watched file types\n * 4. Run a quick AI scan focused only on goal violations\n * 5. Nudge the user about any violations found\n */\n private async initialGoalComplianceScan() {\n if (!isAIAvailable()) {\n console.debug('[Initial Scan] AI not available, skipping initial goal compliance scan');\n return;\n }\n\n const projectPath = this.watchedDirectory || getWorkingDirectory(undefined, true);\n\n console.debug('[Initial Scan] Starting initial goal compliance scan', { projectPath });\n\n try {\n // Load active goals\n const { getActiveGoals, recordGoalViolationCaught } = await import('../agent/goal-validator.js');\n const activeGoals = await getActiveGoals(projectPath);\n\n console.debug('[Initial Scan] Loaded goals for initial scan:', {\n goalCount: activeGoals.length,\n goals: activeGoals.map(g => ({ id: g.id, description: g.description }))\n });\n\n // Skip if no goals are active\n if (activeGoals.length === 0) {\n console.debug('[Initial Scan] No active goals found, skipping initial scan');\n return;\n }\n \n if (!isInteractiveMode()) {\n console.error('[*] Checking recent files against active goals...');\n }\n \n // Find recently modified files\n const recentFiles = new Set<string>();\n \n // 1. Get uncommitted changes (high priority - user is actively working on these)\n const uncommittedFiles = await getGitChangedFiles(projectPath);\n if (uncommittedFiles) {\n uncommittedFiles.forEach(f => recentFiles.add(join(projectPath, f)));\n }\n \n // 2. Get files changed in last 24 hours (recent work)\n const oneDayAgo = Date.now() - (24 * 60 * 60 * 1000);\n const recentChanges = await getChangedFilesSinceTimestamp(projectPath, oneDayAgo);\n if (recentChanges) {\n recentChanges.forEach(f => recentFiles.add(f));\n }\n \n // Filter to watched file types and existing files\n const filesToCheck = Array.from(recentFiles).filter(file => {\n const ext = extname(file).toLowerCase();\n return WATCH_EXTENSIONS.has(ext) && existsSync(file);\n });\n\n console.debug('[Initial Scan] Files discovered for initial scan:', {\n totalRecentFiles: recentFiles.size,\n filteredFiles: filesToCheck.length,\n filePaths: filesToCheck.slice(0, 5).map(f => f.replace(projectPath + '/', '')), // Show first 5\n watchedExtensions: Array.from(WATCH_EXTENSIONS)\n });\n\n if (filesToCheck.length === 0) {\n console.debug('[Initial Scan] No recent files found for initial scan');\n return;\n }\n \n // Limit to a reasonable number for initial scan (don't overwhelm)\n const maxInitialFiles = 10;\n const filesToScan = filesToCheck.slice(0, maxInitialFiles);\n \n if (!isInteractiveMode()) {\n console.error(` Scanning ${filesToScan.length} recent file(s) against ${activeGoals.length} goal(s)...`);\n }\n \n // Read file contents (limit to prevent token overuse)\n const maxCharsPerFile = 3000; // Smaller limit for initial scan\n const fileContents = await Promise.all(\n filesToScan.map(async (file) => {\n try {\n const content = await readFile(file, 'utf-8');\n const relativePath = file.replace(projectPath + '/', '');\n return { path: relativePath, content: content.slice(0, maxCharsPerFile) };\n } catch {\n return null;\n }\n })\n );\n \n const valid = fileContents.filter(Boolean) as Array<{ path: string; content: string }>;\n if (valid.length === 0) return;\n \n const filesBlock = valid.map(f =>\n `### ${f.path}\\n\\`\\`\\`\\n${f.content}\\n\\`\\`\\``\n ).join('\\n\\n');\n \n // Build goal-focused prompt\n const goalsSection = `\nUSER-DEFINED GOALS (check EVERY file against ALL goals):\n${activeGoals.map((g, i) => ` ${i + 1}. \"${g.description}\"`).join('\\n')}\n\nThis is an INITIAL SCAN at watch startup. Report ALL goal violations you find.\n`;\n \n const result = await runAIAnalysis({\n systemPrompt: `You are checking code for GOAL VIOLATIONS ONLY.\n${goalsSection}\nReply ONLY with a JSON array. Each element must have:\n- \"file\": relative file path\n- \"severity\": \"critical\" | \"major\" | \"minor\"\n- \"description\": 1-sentence description of the goal violation\n- \"confidence\": number 0-100, how confident you are this is a violation\n- \"suggestedFix\": 1-sentence description of what should change\n- \"isGoalViolation\": true (always true for this scan)\n- \"goalIndex\": 0-based index of the violated goal\n\nBe thorough. If a goal says \"no emojis\" and you see ANY emoji in the file, report it. If a goal says \"no console.log\" and you see console.log, report it.\n\nIf no violations found, reply with: []\nOutput ONLY the JSON array, no markdown fences, no commentary.`,\n userPrompt: `Check these files for goal violations:\\n\\n${filesBlock}`,\n maxTokens: 2048,\n temperature: 0.1,\n });\n \n if (result.tokensUsed) {\n this.recordTokenUsage(result.tokensUsed.input + result.tokensUsed.output);\n }\n \n if (!result.success || !result.content.trim()) return;\n \n // Parse issues\n let issues: Array<{\n file: string;\n severity: 'critical' | 'major' | 'minor';\n description: string;\n confidence: number;\n suggestedFix?: string;\n isGoalViolation: boolean;\n goalIndex?: number;\n }> = [];\n \n try {\n const parsed = JSON.parse(result.content.trim());\n issues = Array.isArray(parsed) ? parsed : [];\n } catch {\n return;\n }\n \n // Process goal violations\n const issuesToStore: Issue[] = [];\n let violationsFound = 0;\n \n for (const issue of issues) {\n if (!issue.isGoalViolation || issue.confidence < 40) continue;\n \n violationsFound++;\n \n // Track goal violation\n if (issue.goalIndex != null && issue.goalIndex >= 0 && issue.goalIndex < activeGoals.length) {\n const goal = activeGoals[issue.goalIndex];\n if (!goal) continue; // Defensive check\n \n // Store as a proper Issue so it's queryable by measureGoalMetric\n const fixId = `fix-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n issuesToStore.push({\n id: fixId,\n file: issue.file,\n agent: 'goal-violation',\n severity: issue.severity === 'critical' ? 'critical' : issue.severity === 'major' ? 'serious' : 'moderate',\n issue: `Goal \"${goal.description}\" violated: ${issue.description}`,\n fix: issue.suggestedFix || 'Review and fix',\n category: 'goal-violation',\n confidence: issue.confidence,\n autoFixable: true,\n });\n \n await recordGoalViolationCaught(goal, issue.file, projectPath);\n \n // Nudge the user\n const confidenceStr = issue.confidence >= 80 ? 'high' : issue.confidence >= 60 ? 'medium' : 'low';\n const nudgeMsg = `Goal \"${goal.description}\" violated in ${issue.file}: ${issue.description} [${confidenceStr} confidence]`;\n getOutputManager().nudge(nudgeMsg, 'warning', issue.file);\n \n // Persist nudge to both memory and SQL\n await this.persistNudge({\n message: nudgeMsg,\n severity: 'warning',\n file: issue.file,\n category: 'quality',\n goalId: goal.id,\n priority: issue.confidence >= 80 ? 8 : issue.confidence >= 60 ? 6 : 4,\n ...(issue.suggestedFix && { suggestedAction: issue.suggestedFix }),\n });\n }\n }\n \n if (issuesToStore.length > 0) {\n await storeIssues(issuesToStore, basename(projectPath), projectPath);\n }\n \n if (!isInteractiveMode()) {\n if (violationsFound > 0) {\n console.error(` [!] Found ${violationsFound} goal violation(s) in recent files`);\n } else {\n console.error(` [✓] No goal violations found in recent files`);\n }\n }\n \n } catch (error) {\n if (!isInteractiveMode()) {\n console.error(` [!] Initial goal scan error: ${error}`);\n }\n }\n }\n\n private async syncPipelineIntegrations(): Promise<void> {\n const projectPath = this.watchedDirectory || getWorkingDirectory(undefined, true);\n try {\n const config = await loadConfig();\n\n const hasLinear = !!(config.apiKeys?.linear ?? process.env.LINEAR_API_KEY);\n const hasGithub = !!(config.apiKeys?.github ?? process.env.GITHUB_TOKEN);\n\n if (!hasLinear && !hasGithub) return;\n\n const graph = new ContextGraph(projectPath);\n\n if (hasLinear) {\n try {\n const { LinearIngester } = await import('../ingest/linear-ingester.js');\n const ingester = new LinearIngester(projectPath, graph);\n await ingester.syncTickets();\n if (!isInteractiveMode()) {\n console.error('[Pipeline] Linear tickets synced');\n }\n } catch (error) {\n if (!isInteractiveMode()) {\n console.error(`[Pipeline] Linear sync failed: ${error}`);\n }\n }\n }\n\n if (hasGithub) {\n try {\n const { GitHubIngester } = await import('../ingest/github-ingester.js');\n const ingester = new GitHubIngester(graph);\n const token = (await ingester.getApiToken())!;\n const repoInfo = ingester.getRepoInfo(projectPath);\n if (repoInfo) {\n await ingester.syncPullRequests(repoInfo.owner, repoInfo.name, token);\n await ingester.syncIssues(repoInfo.owner, repoInfo.name, token);\n if (!isInteractiveMode()) {\n console.error('[Pipeline] GitHub PRs/issues synced');\n }\n }\n } catch (error) {\n if (!isInteractiveMode()) {\n console.error(`[Pipeline] GitHub sync failed: ${error}`);\n }\n }\n }\n } catch {\n // Pipeline sync is best-effort\n }\n }\n\n private async 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 watcher of this.watchers.values()) {\n watcher.close();\n }\n this.watchers.clear();\n\n // Close extraction pipeline\n if (this.extractionPipeline) {\n this.extractionPipeline.close();\n this.extractionPipeline = null;\n }\n\n // Stop pipeline sync timer\n if (this.pipelineSyncTimer) {\n clearInterval(this.pipelineSyncTimer);\n this.pipelineSyncTimer = null;\n }\n\n // Save codebase index before stopping\n if (this.codebaseIndex) {\n await this.codebaseIndex.save();\n this.codebaseIndex = null;\n }\n\n // Clear state\n if (this.state.scanDebounceTimer) {\n clearTimeout(this.state.scanDebounceTimer);\n }\n \n this.state.isRunning = false;\n\n if (!isInteractiveMode()) {\n console.error('\\n[*] Watch mode stopped.\\n');\n }\n if (this.streamingManager) {\n this.streamingManager.reportWatchStatus({ watching: false, directories: 0 });\n }\n \n // Clean up OutputManager\n const outputManager = getOutputManager();\n outputManager.clearTUICallbacks();\n outputManager.setMode('console');\n \n // Stop the dashboard if running\n if (this.dashboard) {\n this.dashboard.stop();\n this.dashboard = undefined;\n }\n\n const budget = this.state.tokenBudget;\n const tokensK = (budget.used / 1000).toFixed(1);\n\n return {\n content: [{\n type: 'text',\n text: `[*] **TRIE AGENT STOPPED**\n\n### Session Summary:\n- Files scanned: ${this.state.filesScanned}\n- Issues found: ${this.state.totalIssuesFound}\n- Tokens used: ${tokensK}k / ${(budget.hourlyLimit / 1000).toFixed(0)}k hourly limit\n- Scans skipped (trie-throttled): ${budget.scansSaved}\n- Governance ledger: Updated continuously\n\nUse \\`trie_watch start\\` to resume.`\n }]\n };\n }\n\n private async getStatus() {\n if (!this.state.isRunning) {\n return {\n content: [{\n type: 'text',\n text: `[*] **Watch Mode Status: STOPPED**\n\nUse \\`trie_watch start\\` to begin autonomous scanning.`\n }]\n };\n }\n\n const recentScans = Array.from(this.state.lastScan.entries())\n .sort((a, b) => b[1] - a[1])\n .slice(0, 5)\n .map(([file, time]) => {\n const ago = Math.round((Date.now() - time) / 1000);\n return `- \\`${basename(file)}\\` (${ago}s ago)`;\n })\n .join('\\n');\n\n const recentNudges = this.state.nudges.slice(-3).map(\n (n) => `- ${basename(n.file)} [${n.severity}] @ ${n.timestamp}`\n ).join('\\n');\n\n // Get Trie Agent agency status\n let agencyStatus = '';\n try {\n const { getTrieAgent } = await import('../agent/trie-agent.js');\n const trieAgent = getTrieAgent(this.watchedDirectory || getWorkingDirectory(undefined, true));\n await trieAgent.initialize();\n const status = await trieAgent.getAgencyStatus();\n\n agencyStatus = `\n### [AI] Trie Agent:\n- **Goals:** ${status.goals.active} active, ${status.goals.completed} completed${status.goals.topGoal ? ` (${status.goals.topGoal.slice(0, 40)}...)` : ''}\n- **Hypotheses:** ${status.hypotheses.testing} testing, ${status.hypotheses.validated} validated\n- **Risk Level:** ${status.riskLevel.toUpperCase()}\n- **Effectiveness:** ${status.effectiveness}%\n- **Scan Frequency:** ${Math.round(status.scanFrequency / 1000)}s${status.isQuietHours ? ' (quiet hours)' : ''}`;\n } catch {\n // Agency status is optional\n }\n\n const budget = this.state.tokenBudget;\n const remaining = this.getRemainingBudget();\n const tokensK = (budget.used / 1000).toFixed(1);\n const remainingK = (remaining / 1000).toFixed(1);\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.state.filesScanned}\n- Issues found: ${this.state.totalIssuesFound}\n- Pending: ${this.state.pendingFiles.size}\n\n### Token Budget:\n- Used: ${tokensK}k / ${(budget.hourlyLimit / 1000).toFixed(0)}k hourly\n- Remaining: ${remainingK}k\n- Scans skipped (trie-throttled): ${budget.scansSaved}\n${agencyStatus}\n\n### Recently Scanned:\n${recentScans || '(none yet)'}\n\n### Recent Nudges:\n${recentNudges || '(none)'}\n\n### Commands:\n- \\`trie_watch issues\\` - Get all issues found\n- \\`trie_watch stop\\` - Stop watching`\n }]\n };\n }\n\n /**\n * Helper to persist a nudge to both in-memory state and SQL storage\n */\n private async persistNudge(params: {\n message: string;\n severity: 'critical' | 'high' | 'warning' | 'info';\n file?: string;\n category?: string;\n goalId?: string;\n priority?: number;\n suggestedAction?: string;\n relatedIssues?: string[];\n }): Promise<void> {\n const timestamp = new Date().toISOString();\n const nudgeId = createHash('sha256')\n .update(`${params.message}|${params.file || ''}|${timestamp}`)\n .digest('hex')\n .slice(0, 16);\n\n const nudge: Nudge = {\n id: nudgeId,\n message: params.message,\n severity: params.severity,\n timestamp,\n resolved: false,\n dismissed: false,\n priority: params.priority ?? 5,\n relatedIssues: params.relatedIssues ?? [],\n metadata: {},\n ...(params.file && { file: params.file }),\n ...(params.category && { category: params.category }),\n ...(params.goalId && { goalId: params.goalId }),\n ...(params.suggestedAction && { suggestedAction: params.suggestedAction }),\n };\n\n // Store in memory for current session\n this.state.nudges.push({\n file: params.file || 'unknown', // Keep full path for consistency with loaded nudges\n message: params.message,\n severity: params.severity === 'warning' || params.severity === 'info' ? 'high' : params.severity,\n timestamp: new Date().toLocaleTimeString('en-US', { hour12: false }),\n });\n\n // Persist to SQL\n try {\n const storage = getStorage(this.watchedDirectory);\n await storage.storeNudge(nudge);\n console.debug(`[Watch] ✓ Persisted nudge to storage: ${nudge.message.slice(0, 60)}...`);\n } catch (error) {\n console.error('[Watch] Failed to persist nudge to storage:', error);\n }\n }\n\n private getNudges() {\n return {\n content: [\n {\n type: 'text',\n text: `[#] Recent nudges (${this.state.nudges.length} this session)\\n` +\n (this.state.nudges.length\n ? this.state.nudges.map((n) =>\n `- ${basename(n.file)} [${n.severity}] @ ${n.timestamp}\\n ${n.message}`\n ).join('\\n')\n : '(none)')\n },\n {\n type: 'json',\n json: this.state.nudges\n }\n ]\n };\n }\n\n private getCurrentIssues() {\n return {\n content: [{\n type: 'text',\n text: `[L] **Issues Found This Session**\n\nTotal issues: ${this.state.totalIssuesFound}\nFiles scanned: ${this.state.filesScanned}\n\nTo get a full report, run \\`trie_scan\\` on your codebase.`\n }]\n };\n }\n}\n","import { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join, basename, resolve, isAbsolute } from 'path';\nimport { SuperReviewerAgent, CRITICAL_REVIEW_CHECKLIST } from '../skills/built-in/super-reviewer.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { runShellCommandSync } from '../utils/command-runner.js';\n\n/**\n * PR Review Tool — Interactive AI-Guided Code Review\n * \n * Based on https://github.com/sitaram/devtools/blob/main/pr_review.md\n * \n * Code reviews are the bottleneck in AI coding. This tool scales them by\n * putting the human back in the loop, shepherded by AI.\n */\nexport class TriePRReviewTool {\n private agent = new SuperReviewerAgent();\n\n private exec(command: string, cwd?: string, maxBuffer?: number): string {\n const opts: Parameters<typeof runShellCommandSync>[2] = {\n captureOutput: false,\n redactOutput: true,\n ...(cwd ? { cwd } : {}),\n ...(maxBuffer ? { maxBuffer } : {}),\n };\n const { stdout } = runShellCommandSync(\n command,\n { actor: 'tool:pr-review', triggeredBy: 'manual', targetPath: cwd ?? getWorkingDirectory(undefined, true) },\n opts\n );\n return stdout.trimEnd();\n }\n\n async execute(args: any) {\n const { \n pr, \n worktree,\n mode,\n files: _specificFiles, // Reserved for future file filtering\n } = args;\n\n try {\n // Step 1: Determine target and get PR info\n const prInfo = await this.getPRInfo(pr, worktree);\n \n if (!prInfo.success) {\n return {\n content: [{\n type: 'text',\n text: `${prInfo.error}\\n\\nUsage:\\n- \\`pr_review 12345\\` — review specific PR\\n- \\`pr_review\\` — review PR for current branch\\n- \\`pr_review ../worktree\\` — review worktree changes`\n }]\n };\n }\n\n // Step 2: Get the diff and changed files\n const changes = await this.getChanges(prInfo);\n \n if (changes.files.length === 0) {\n return {\n content: [{\n type: 'text',\n text: `No changes found to review.`\n }]\n };\n }\n\n // Step 3: Look for design docs\n const designDocs = await this.findDesignDocs(changes.files, prInfo);\n\n // Step 4: Build the review workflow\n const workflow = await this.agent.buildReviewWorkflow(\n changes.files,\n {\n prNumber: prInfo.number,\n prTitle: prInfo.title,\n prAuthor: prInfo.author,\n baseBranch: prInfo.baseBranch,\n headBranch: prInfo.headBranch,\n mode: mode || 'own',\n designDocs,\n }\n );\n\n // Step 5: Pre-load all file contents for instant responses\n const fileContents = await this.preloadFiles(changes.files.map(f => f.path));\n\n // Step 6: Generate the review prompt\n const reviewPrompt = this.generateReviewPrompt(workflow, changes, fileContents);\n\n return {\n content: [{\n type: 'text',\n text: reviewPrompt\n }]\n };\n\n } catch (error) {\n return {\n content: [{\n type: 'text',\n text: `Error: ${error instanceof Error ? error.message : String(error)}`\n }]\n };\n }\n }\n\n /**\n * Get PR information from GitHub or local worktree\n */\n private async getPRInfo(pr?: string, worktree?: string): Promise<PRInfo> {\n // If worktree path provided, analyze local changes\n if (worktree) {\n const worktreePath = isAbsolute(worktree) ? worktree : resolve(getWorkingDirectory(undefined, true), worktree);\n if (!existsSync(worktreePath)) {\n return { success: false, error: `Worktree not found: ${worktreePath}` };\n }\n \n return {\n success: true,\n type: 'worktree',\n path: worktreePath,\n title: `Local changes in ${basename(worktreePath)}`,\n author: this.getGitUser(),\n baseBranch: 'HEAD~1',\n headBranch: 'HEAD',\n };\n }\n\n // If PR number provided, get from GitHub\n if (pr) {\n return this.getPRFromGitHub(pr);\n }\n\n // No args — try to get PR for current branch\n try {\n this.exec('git branch --show-current');\n \n // Check if there's a PR for this branch\n const prJson = this.exec(\n `gh pr view --json number,title,author,headRefName,baseRefName`\n );\n \n const prData = JSON.parse(prJson);\n \n return {\n success: true,\n type: 'github',\n number: String(prData.number),\n title: prData.title,\n author: prData.author?.login || 'unknown',\n baseBranch: prData.baseRefName,\n headBranch: prData.headRefName,\n };\n } catch {\n // No PR found, fall back to local changes\n return {\n success: true,\n type: 'local',\n title: 'Local uncommitted changes',\n author: this.getGitUser(),\n baseBranch: 'HEAD',\n headBranch: 'working tree',\n };\n }\n }\n\n /**\n * Get PR info from GitHub CLI\n */\n private async getPRFromGitHub(prNumber: string): Promise<PRInfo> {\n try {\n const prJson = this.exec(\n `gh pr view ${prNumber} --json number,title,author,headRefName,baseRefName`\n );\n \n const prData = JSON.parse(prJson);\n \n return {\n success: true,\n type: 'github',\n number: String(prData.number),\n title: prData.title,\n author: prData.author?.login || 'unknown',\n baseBranch: prData.baseRefName,\n headBranch: prData.headRefName,\n };\n } catch (error) {\n return {\n success: false,\n error: `Failed to get PR #${prNumber}. Is \\`gh\\` CLI installed and authenticated?`\n };\n }\n }\n\n /**\n * Get changes (diff) for the PR or local changes\n */\n private async getChanges(prInfo: PRInfo): Promise<{ files: ChangedFile[]; fullDiff: string }> {\n let diffOutput: string;\n \n try {\n if (prInfo.type === 'github' && prInfo.number) {\n // Get diff from GitHub PR\n diffOutput = this.exec(`gh pr diff ${prInfo.number}`, undefined, 50 * 1024 * 1024);\n } else if (prInfo.type === 'worktree' && prInfo.path) {\n // Get diff from worktree\n diffOutput = this.exec(`git diff HEAD`, prInfo.path, 50 * 1024 * 1024);\n } else {\n // Local changes\n diffOutput = this.exec(`git diff HEAD`, undefined, 50 * 1024 * 1024);\n \n // If no diff, try staged changes\n if (!diffOutput.trim()) {\n diffOutput = this.exec(`git diff --cached`, undefined, 50 * 1024 * 1024);\n }\n }\n } catch {\n diffOutput = '';\n }\n\n // Parse the diff to extract file information\n const files = this.parseDiff(diffOutput);\n\n return { files, fullDiff: diffOutput };\n }\n\n /**\n * Parse git diff output into structured file changes\n */\n private parseDiff(diffOutput: string): ChangedFile[] {\n const files: ChangedFile[] = [];\n const fileDiffs = diffOutput.split(/^diff --git /m).slice(1);\n\n for (const fileDiff of fileDiffs) {\n const lines = fileDiff.split('\\n');\n const headerLine = lines[0] || '';\n \n // Extract file path from \"a/path b/path\"\n const pathMatch = headerLine.match(/a\\/(.+?) b\\/(.+)/);\n if (!pathMatch || !pathMatch[2]) continue;\n \n const path: string = pathMatch[2];\n const diff = `diff --git ${fileDiff}`;\n \n // Count additions and deletions\n let additions = 0;\n let deletions = 0;\n \n for (const line of lines) {\n if (line.startsWith('+') && !line.startsWith('+++')) {\n additions++;\n } else if (line.startsWith('-') && !line.startsWith('---')) {\n deletions++;\n }\n }\n \n files.push({ path, diff, additions, deletions, status: 'modified' });\n }\n\n return files;\n }\n\n /**\n * Find related design docs\n */\n private async findDesignDocs(files: ChangedFile[], prInfo: PRInfo): Promise<string[]> {\n const designDocs: string[] = [];\n const cwd = prInfo.path || getWorkingDirectory(undefined, true);\n \n // Check for design_docs/ in changed files\n for (const file of files) {\n if (file.path.includes('design_docs/') || \n file.path.includes('docs/design/') ||\n file.path.includes('rfcs/')) {\n designDocs.push(file.path);\n }\n }\n \n // Look for design docs in standard locations\n const designDocPaths = [\n 'design_docs',\n 'docs/design',\n 'docs/rfcs',\n 'rfcs',\n ];\n \n for (const docPath of designDocPaths) {\n const fullPath = join(cwd, docPath);\n if (existsSync(fullPath)) {\n // Could list and add recent docs, but for now just note the directory exists\n }\n }\n \n return designDocs;\n }\n\n /**\n * Pre-load all changed files for instant responses during review\n */\n private async preloadFiles(filePaths: string[]): Promise<Map<string, string>> {\n const contents = new Map<string, string>();\n const cwd = getWorkingDirectory(undefined, true);\n \n await Promise.all(filePaths.map(async (filePath) => {\n try {\n const fullPath = isAbsolute(filePath) ? filePath : join(cwd, filePath);\n if (existsSync(fullPath)) {\n const content = await readFile(fullPath, 'utf-8');\n contents.set(filePath, content);\n }\n } catch {\n // Skip unreadable files\n }\n }));\n \n return contents;\n }\n\n /**\n * Get git user name\n */\n private getGitUser(): string {\n try {\n return this.exec('git config user.name');\n } catch {\n return 'unknown';\n }\n }\n\n /**\n * Generate the full review prompt for Claude to execute\n */\n private generateReviewPrompt(\n workflow: any,\n changes: { files: ChangedFile[]; fullDiff: string },\n _fileContents: Map<string, string> // Reserved for future: inline file contents in review\n ): string {\n const { metadata, fileOrder, reviewInstructions } = workflow;\n \n let prompt = `# 🔍 Super Reviewer — Interactive PR Review\\n\\n`;\n \n // PR Header\n if (metadata.prNumber) {\n prompt += `## PR #${metadata.prNumber}: ${metadata.prTitle}\\n\\n`;\n } else {\n prompt += `## ${metadata.prTitle}\\n\\n`;\n }\n \n prompt += `**Author:** ${metadata.prAuthor}\\n`;\n prompt += `**Branch:** \\`${metadata.headBranch}\\` → \\`${metadata.baseBranch}\\`\\n`;\n prompt += `**Scope:** ${metadata.totalFiles} files, +${metadata.totalAdditions}/-${metadata.totalDeletions} lines\\n\\n`;\n \n prompt += `---\\n\\n`;\n \n // Review Mode Selection\n prompt += `## Review Mode\\n\\n`;\n prompt += `**Current Mode:** ${reviewInstructions.mode === 'own' ? '1' : '2'}. ${reviewInstructions.description}\\n\\n`;\n prompt += `> To switch modes, say \"mode 1\" for your own PR or \"mode 2\" for someone else's\\n\\n`;\n \n prompt += `---\\n\\n`;\n \n // File Order Table\n prompt += `## Files to Review (ordered for understanding)\\n\\n`;\n prompt += `| # | File | Why this order |\\n`;\n prompt += `|---|------|----------------|\\n`;\n \n for (const file of fileOrder) {\n const stats = `+${changes.files.find(f => f.path === file.path)?.additions || 0}/-${changes.files.find(f => f.path === file.path)?.deletions || 0}`;\n prompt += `| ${file.index} | \\`${file.path}\\` (${stats}) | ${file.reason} |\\n`;\n }\n \n prompt += `\\n---\\n\\n`;\n \n // Critical Review Mindset\n prompt += `## Critical Review Mindset\\n\\n`;\n prompt += `As we go through each file, I'll actively look for:\\n\\n`;\n \n prompt += `**State & Lifecycle:**\\n`;\n for (const check of CRITICAL_REVIEW_CHECKLIST.stateAndLifecycle) {\n prompt += `- ${check}\\n`;\n }\n \n prompt += `\\n**Edge Cases & Races:**\\n`;\n for (const check of CRITICAL_REVIEW_CHECKLIST.edgeCasesAndRaces) {\n prompt += `- ${check}\\n`;\n }\n \n prompt += `\\n**Missing Pieces:**\\n`;\n for (const check of CRITICAL_REVIEW_CHECKLIST.missingPieces) {\n prompt += `- ${check}\\n`;\n }\n \n prompt += `\\n---\\n\\n`;\n \n // Pre-loaded diffs\n prompt += `## File Diffs (pre-loaded for instant review)\\n\\n`;\n prompt += `<details>\\n<summary>📁 All file diffs (click to expand)</summary>\\n\\n`;\n \n for (const file of fileOrder) {\n const fileChange = changes.files.find(f => f.path === file.path);\n if (fileChange) {\n prompt += `### ${file.path}\\n\\n`;\n prompt += `\\`\\`\\`diff\\n${fileChange.diff}\\n\\`\\`\\`\\n\\n`;\n }\n }\n \n prompt += `</details>\\n\\n`;\n \n prompt += `---\\n\\n`;\n \n // Ready to start\n prompt += `## Ready to Begin\\n\\n`;\n prompt += `I'll walk you through each file, explaining what changed and why. After each file, I'll pause for your questions.\\n\\n`;\n prompt += `**Commands during review:**\\n`;\n prompt += `- \\`yes\\` or \\`y\\` — continue to next file\\n`;\n prompt += `- \\`skip to [filename]\\` — jump to specific file\\n`;\n prompt += `- \\`questions?\\` — ask about current file\\n`;\n prompt += `- \\`reorder\\` — change the file order\\n`;\n prompt += `- \\`done\\` — end review and show summary\\n\\n`;\n \n prompt += `**Ready for File 1?** (\\`${fileOrder[0]?.path || 'no files'}\\`)\\n\\n`;\n prompt += `*(say \"yes\" to start, or ask me anything)*\\n`;\n \n return prompt;\n }\n}\n\n// Type definitions\ninterface PRInfo {\n success: boolean;\n error?: string;\n type?: 'github' | 'worktree' | 'local';\n number?: string;\n title?: string;\n author?: string;\n baseBranch?: string;\n headBranch?: string;\n path?: string;\n}\n\ninterface ChangedFile {\n path: string;\n diff: string;\n additions: number;\n deletions: number;\n status: string;\n}\n","/**\n * Super Reviewer stub\n * Review functionality has been integrated into decision ledger\n */\n\nexport const CRITICAL_REVIEW_CHECKLIST = {\n stateAndLifecycle: [\n 'Uninitialized state accessed before setup',\n 'Missing cleanup on unmount/dispose',\n 'State mutations in wrong lifecycle phase',\n ],\n edgeCasesAndRaces: [\n 'Race conditions in async operations',\n 'Missing error handling for edge cases',\n 'Unhandled promise rejections',\n ],\n missingPieces: [\n 'Missing input validation',\n 'Missing error handling',\n 'Missing logging/monitoring',\n ],\n};\n\nexport interface ChangedFile {\n path: string;\n additions: number;\n deletions: number;\n status: string;\n}\n\nexport class SuperReviewerAgent {\n async review(_files: string[]): Promise<{ issues: any[] }> {\n return { issues: [] };\n }\n\n async buildReviewWorkflow(\n files: ChangedFile[],\n context: Record<string, any>\n ): Promise<{ files: ChangedFile[]; context: Record<string, any> }> {\n return { files, context };\n }\n}\n","/**\n * Project Info MCP Tool\n * \n * Provides MCP tool for viewing and managing PROJECT.md\n */\n\nimport {\n loadProjectInfo,\n initProjectInfo,\n getProjectSection,\n updateProjectSection,\n appendToSection,\n getProjectSections,\n getProjectInfoStructured,\n projectInfoExists,\n} from '../utils/project-info.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport interface ProjectInfoArgs {\n action: 'view' | 'init' | 'update' | 'append' | 'sections' | 'raw';\n section?: string;\n content?: string;\n directory?: string;\n}\n\nexport class TrieProjectInfoTool {\n async execute(args: ProjectInfoArgs): Promise<{ content: Array<{ type: string; text: string }> }> {\n const workDir = args.directory || getWorkingDirectory(undefined, true);\n const action = args.action || 'view';\n\n try {\n switch (action) {\n case 'view':\n return await this.handleView(workDir, args.section);\n \n case 'init':\n return await this.handleInit(workDir);\n \n case 'update':\n return await this.handleUpdate(workDir, args.section, args.content);\n \n case 'append':\n return await this.handleAppend(workDir, args.section, args.content);\n \n case 'sections':\n return await this.handleSections(workDir);\n \n case 'raw':\n return await this.handleRaw(workDir);\n \n default:\n return this.error(`Unknown action: ${action}. Use: view, init, update, append, sections, raw`);\n }\n } catch (error) {\n return this.error(`Error: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n private async handleView(workDir: string, section?: string): Promise<{ content: Array<{ type: string; text: string }> }> {\n if (!projectInfoExists(workDir)) {\n return this.formatResponse(`## Project Info Not Found\n\nNo \\`.trie/PROJECT.md\\` file exists in this project.\n\n**To create one, use:**\n\\`\\`\\`\ntrie_project action=\"init\"\n\\`\\`\\`\n\nOr run: \\`trie project init\\`\n\nThis will create a template with sections for:\n- Project Overview\n- Technology Stack\n- Architecture\n- Coding Conventions\n- Environment\n- Team\n- Compliance\n- AI Instructions`);\n }\n\n if (section) {\n const sectionContent = await getProjectSection(section, workDir);\n if (sectionContent === null) {\n const sections = await getProjectSections(workDir);\n return this.formatResponse(`## Section Not Found: \"${section}\"\n\nAvailable sections:\n${sections.map(s => `- ${s}`).join('\\n')}`);\n }\n \n return this.formatResponse(`## ${section}\n\n${sectionContent}`);\n }\n\n // Return structured view\n const info = await getProjectInfoStructured(workDir);\n \n let output = `## Project Information\n\n**Path:** \\`${info.path}\\`\n**Sections:** ${Object.keys(info.sections).length}\n\n---\n\n`;\n\n for (const [name, content] of Object.entries(info.sections)) {\n output += `### ${name}\n\n${content}\n\n---\n\n`;\n }\n\n return this.formatResponse(output);\n }\n\n private async handleInit(workDir: string): Promise<{ content: Array<{ type: string; text: string }> }> {\n const result = await initProjectInfo(workDir);\n \n if (result.created) {\n return this.formatResponse(`## PROJECT.md Created\n\n**Path:** \\`${result.path}\\`\n\nA new PROJECT.md file has been created with a template including sections for:\n- Project Overview\n- Technology Stack\n- Architecture\n- Coding Conventions\n- Environment\n- Team\n- Compliance\n- AI Instructions\n\n**Next steps:**\n1. Open the file and fill in your project details\n2. The content will be available via \\`trie://project\\` resource\n3. AI assistants will use this context when working on your project\n\n**View the template:**\n\\`\\`\\`\ntrie_project action=\"view\"\n\\`\\`\\``);\n }\n\n return this.formatResponse(`## PROJECT.md Already Exists\n\n**Path:** \\`${result.path}\\`\n\nUse \\`trie_project action=\"view\"\\` to see the current content.`);\n }\n\n private async handleUpdate(\n workDir: string, \n section?: string, \n content?: string\n ): Promise<{ content: Array<{ type: string; text: string }> }> {\n if (!section) {\n return this.error('Missing required parameter: section');\n }\n if (!content) {\n return this.error('Missing required parameter: content');\n }\n\n const success = await updateProjectSection(section, content, workDir);\n \n if (success) {\n return this.formatResponse(`## Section Updated: \"${section}\"\n\nThe \"${section}\" section has been updated with your new content.\n\n**View updated section:**\n\\`\\`\\`\ntrie_project action=\"view\" section=\"${section}\"\n\\`\\`\\``);\n }\n\n const sections = await getProjectSections(workDir);\n return this.error(`Could not update section \"${section}\". \n\nAvailable sections:\n${sections.map(s => `- ${s}`).join('\\n')}`);\n }\n\n private async handleAppend(\n workDir: string,\n section?: string,\n content?: string\n ): Promise<{ content: Array<{ type: string; text: string }> }> {\n if (!section) {\n return this.error('Missing required parameter: section');\n }\n if (!content) {\n return this.error('Missing required parameter: content');\n }\n\n const success = await appendToSection(section, content, workDir);\n \n if (success) {\n return this.formatResponse(`## Content Appended to: \"${section}\"\n\nYour content has been added to the \"${section}\" section.\n\n**View updated section:**\n\\`\\`\\`\ntrie_project action=\"view\" section=\"${section}\"\n\\`\\`\\``);\n }\n\n return this.error(`Could not append to section \"${section}\". Make sure the section exists.`);\n }\n\n private async handleSections(workDir: string): Promise<{ content: Array<{ type: string; text: string }> }> {\n if (!projectInfoExists(workDir)) {\n return this.formatResponse(`## No PROJECT.md Found\n\nRun \\`trie_project action=\"init\"\\` to create one.`);\n }\n\n const sections = await getProjectSections(workDir);\n \n return this.formatResponse(`## Available Sections\n\n${sections.map((s, i) => `${i + 1}. **${s}**`).join('\\n')}\n\n**View a section:**\n\\`\\`\\`\ntrie_project action=\"view\" section=\"Section Name\"\n\\`\\`\\`\n\n**Update a section:**\n\\`\\`\\`\ntrie_project action=\"update\" section=\"Section Name\" content=\"New content...\"\n\\`\\`\\``);\n }\n\n private async handleRaw(workDir: string): Promise<{ content: Array<{ type: string; text: string }> }> {\n const content = await loadProjectInfo(workDir);\n \n if (!content) {\n return this.formatResponse(`No PROJECT.md found. Run \\`trie_project action=\"init\"\\` to create one.`);\n }\n\n return this.formatResponse(content);\n }\n\n private formatResponse(text: string): { content: Array<{ type: string; text: string }> } {\n return {\n content: [{ type: 'text', text }]\n };\n }\n\n private error(message: string): { content: Array<{ type: string; text: string }> } {\n return {\n content: [{ type: 'text', text: `**Error:** ${message}` }]\n };\n }\n}\n","/**\n * Trie Init Tool\n * \n * MCP tool for initializing bootstrap files.\n */\n\nimport { initializeBootstrapFiles, loadBootstrapContext, completeBootstrap, needsBootstrap } from '../bootstrap/index.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport class TrieInitTool {\n async execute(params: {\n action?: 'init' | 'status' | 'complete' | 'context';\n directory?: string;\n force?: boolean;\n skipBootstrap?: boolean;\n }): Promise<string> {\n const action = params.action || 'init';\n const workDir = params.directory || getWorkingDirectory(undefined, true);\n\n if (action === 'status') {\n const needs = needsBootstrap(workDir);\n const context = await loadBootstrapContext(workDir);\n \n const existingFiles = context.files.filter(f => f.exists).map(f => f.name);\n const missingFiles = context.files.filter(f => !f.exists).map(f => f.name);\n \n return [\n '# Bootstrap Status',\n '',\n `**Bootstrap pending:** ${needs ? 'Yes' : 'No'}`,\n '',\n '## Files',\n '',\n '**Existing:**',\n existingFiles.length > 0 ? existingFiles.map(f => `- .trie/${f}`).join('\\n') : '- None',\n '',\n '**Missing:**',\n missingFiles.length > 0 ? missingFiles.map(f => `- .trie/${f}`).join('\\n') : '- None',\n ].join('\\n');\n }\n\n if (action === 'complete') {\n const result = await completeBootstrap(workDir);\n if (result) {\n return 'Bootstrap completed. BOOTSTRAP.md has been deleted.';\n }\n return 'No BOOTSTRAP.md file found.';\n }\n\n if (action === 'context') {\n const context = await loadBootstrapContext(workDir);\n if (!context.injectedContent) {\n return 'No bootstrap context available. Run trie_init with action=\"init\" first.';\n }\n return context.injectedContent;\n }\n\n // Default: init\n const initOptions: Parameters<typeof initializeBootstrapFiles>[0] = {\n workDir,\n };\n if (params.force !== undefined) {\n initOptions.force = params.force;\n }\n if (params.skipBootstrap !== undefined) {\n initOptions.skipBootstrap = params.skipBootstrap;\n }\n const result = await initializeBootstrapFiles(initOptions);\n\n const lines: string[] = [\n '# Trie Workspace Initialized',\n '',\n ];\n\n if (result.created.length > 0) {\n lines.push('## Created Files', '');\n for (const file of result.created) {\n lines.push(`- .trie/${file}`);\n }\n lines.push('');\n }\n\n if (result.skipped.length > 0) {\n lines.push('## Skipped (already exist)', '');\n for (const file of result.skipped) {\n lines.push(`- .trie/${file}`);\n }\n lines.push('');\n }\n\n lines.push('## Detected Stack', '');\n if (result.stack.framework) lines.push(`- **Framework:** ${result.stack.framework}`);\n if (result.stack.language) lines.push(`- **Language:** ${result.stack.language}`);\n if (result.stack.database) lines.push(`- **Database:** ${result.stack.database}`);\n if (result.stack.auth) lines.push(`- **Auth:** ${result.stack.auth}`);\n if (result.stack.packageManager) lines.push(`- **Package Manager:** ${result.stack.packageManager}`);\n lines.push('');\n\n if (result.stack.suggestedSkills.length > 0) {\n lines.push('## Suggested Skills', '');\n for (const skill of result.stack.suggestedSkills) {\n lines.push(`\\`\\`\\`bash`);\n lines.push(`trie skills add ${skill}`);\n lines.push(`\\`\\`\\``);\n }\n lines.push('');\n }\n\n lines.push(\n '## Next Steps',\n '',\n '1. Edit `.trie/PROJECT.md` with your project description',\n '2. Define coding standards in `.trie/RULES.md`',\n '3. Run `trie_scan` to analyze your codebase',\n '4. Run `trie_init` with action=\"complete\" when setup is done',\n );\n\n return lines.join('\\n');\n }\n}\n","/**\n * Trie Memory Search Tool\n * \n * MCP tool for searching issue memory.\n */\n\nimport {\n searchIssues,\n getMemoryStats,\n getRecentIssues,\n findSimilarIssues,\n markIssueResolved,\n purgeIssues,\n} from '../memory/issue-store.js';\nimport {\n findCrossProjectPatterns,\n searchGlobalPatterns,\n listTrackedProjects,\n getGlobalMemoryStats,\n} from '../memory/global-memory.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport class TrieMemorySearchTool {\n async execute(params: {\n action?: 'search' | 'stats' | 'recent' | 'similar' | 'resolve' | 'global' | 'purge';\n query?: string;\n issueId?: string;\n limit?: number;\n severity?: string[];\n agent?: string;\n includeResolved?: boolean;\n directory?: string;\n purgeStrategy?: 'smart' | 'resolved' | 'old' | 'all';\n daysOld?: number;\n }): Promise<{ content: Array<{ type: string; text: string }> }> {\n const action = params.action || 'search';\n const workDir = params.directory || getWorkingDirectory(undefined, true);\n\n let resultText: string;\n switch (action) {\n case 'search':\n resultText = await this.handleSearch(params, workDir);\n break;\n case 'stats':\n resultText = await this.handleStats(workDir);\n break;\n case 'recent':\n resultText = await this.handleRecent(params, workDir);\n break;\n case 'similar':\n resultText = await this.handleSimilar(params, workDir);\n break;\n case 'resolve':\n resultText = await this.handleResolve(params, workDir);\n break;\n case 'global':\n resultText = await this.handleGlobal(params);\n break;\n case 'purge':\n resultText = await this.handlePurge(params, workDir);\n break;\n default:\n resultText = 'Unknown action. Use: search, stats, recent, similar, resolve, global, or purge';\n }\n\n return {\n content: [{\n type: 'text',\n text: resultText\n }]\n };\n }\n\n private async handleSearch(params: {\n query?: string;\n limit?: number;\n severity?: string[];\n agent?: string;\n includeResolved?: boolean;\n }, workDir: string): Promise<string> {\n if (!params.query) {\n return 'Missing required parameter: query';\n }\n\n const searchOptions: Parameters<typeof searchIssues>[1] = {\n workDir,\n limit: params.limit || 10,\n };\n if (params.severity !== undefined) {\n searchOptions.severity = params.severity;\n }\n if (params.agent !== undefined) {\n searchOptions.agent = params.agent;\n }\n if (params.includeResolved !== undefined) {\n searchOptions.includeResolved = params.includeResolved;\n }\n const results = await searchIssues(params.query, searchOptions);\n\n if (results.length === 0) {\n return `No issues found matching \"${params.query}\"`;\n }\n\n const lines: string[] = [\n `# Search Results: \"${params.query}\"`,\n '',\n `Found ${results.length} matching issue(s):`,\n '',\n ];\n\n for (const result of results) {\n const i = result.issue;\n const status = i.resolved ? ' [RESOLVED]' : '';\n lines.push(\n `## [${i.severity.toUpperCase()}]${status} ${i.issue.slice(0, 80)}`,\n '',\n `- **File:** \\`${i.file}\\`${i.line ? `:${i.line}` : ''}`,\n `- **Agent:** ${i.agent}`,\n `- **Score:** ${(result.score * 100).toFixed(0)}%`,\n `- **Date:** ${new Date(i.timestamp).toLocaleDateString()}`,\n `- **Fix:** ${i.fix.slice(0, 150)}${i.fix.length > 150 ? '...' : ''}`,\n '',\n );\n }\n\n return lines.join('\\n');\n }\n\n private async handleStats(workDir: string): Promise<string> {\n const stats = await getMemoryStats(workDir);\n const globalStats = await getGlobalMemoryStats();\n\n const lines: string[] = [\n '# Memory Statistics',\n '',\n '## Local Issue Memory',\n '',\n `- **Active Issues:** ${stats.activeIssues}`,\n `- **Resolved:** ${stats.resolvedCount}`,\n `- **Total (all-time):** ${stats.totalIssues}`,\n ];\n\n // Capacity warning\n const cap = stats.capacityInfo;\n if (cap.isAtCap) {\n lines.push(\n '',\n '### ⚠️ CAPACITY WARNING',\n '',\n `**Memory is at maximum capacity (${cap.current}/${cap.max} issues, ${cap.percentFull}%)**`,\n '',\n 'Trie caps issue storage at 10,000 for performance. New repeats are deduplicated.',\n 'Older issues are compacted into summaries, and if it still exceeds the cap the oldest/lowest-value issues are pruned.',\n '',\n '**Options to free up space:**',\n '- `trie memory purge smart` - Remove resolved and old low-priority issues (recommended)',\n '- `trie memory purge resolved` - Remove all resolved issues',\n '- `trie memory purge old` - Remove issues older than 90 days',\n '- `trie memory purge all` - Clear all issues (keeps summaries)',\n );\n } else if (cap.percentFull >= 80) {\n lines.push(\n '',\n `### ℹ️ Memory Usage: ${cap.percentFull}% (${cap.current}/${cap.max})`,\n '',\n `You're approaching the storage cap. Consider running \\`trie memory purge smart\\` to free up space.`,\n );\n } else {\n lines.push(`- **Memory Usage:** ${cap.percentFull}% (${cap.current}/${cap.max})`);\n }\n\n // Deduplication stats\n if (stats.deduplicationStats.duplicatesAvoided > 0) {\n lines.push(\n '',\n '### Deduplication',\n '',\n `- **Unique Patterns:** ${stats.deduplicationStats.uniquePatterns}`,\n `- **Duplicates Avoided:** ${stats.deduplicationStats.duplicatesAvoided}`,\n );\n }\n\n if (stats.oldestIssue) {\n lines.push('', `- **Date Range:** ${stats.oldestIssue.split('T')[0]} to ${stats.newestIssue?.split('T')[0]}`);\n }\n\n lines.push('', '### By Severity', '');\n for (const [severity, count] of Object.entries(stats.issuesBySeverity)) {\n lines.push(`- ${severity}: ${count}`);\n }\n\n lines.push('', '### By Agent', '');\n const sortedAgents = Object.entries(stats.issuesByAgent).sort((a, b) => b[1] - a[1]);\n for (const [agent, count] of sortedAgents.slice(0, 10)) {\n lines.push(`- ${agent}: ${count}`);\n }\n\n lines.push(\n '',\n '## Global Cross-Project Memory',\n '',\n `- **Tracked Projects:** ${globalStats.trackedProjects}`,\n `- **Total Patterns:** ${globalStats.totalPatterns}`,\n `- **Cross-Project Patterns:** ${globalStats.crossProjectPatterns}`,\n `- **Fixed Patterns:** ${globalStats.fixedPatterns}`,\n );\n\n return lines.join('\\n');\n }\n\n private async handleRecent(params: {\n limit?: number;\n }, workDir: string): Promise<string> {\n const issues = await getRecentIssues({\n workDir,\n limit: params.limit || 10,\n });\n\n if (issues.length === 0) {\n return 'No recent issues found.';\n }\n\n const lines: string[] = [\n '# Recent Issues (Last 7 Days)',\n '',\n ];\n\n for (const i of issues) {\n const status = i.resolved ? ' [RESOLVED]' : '';\n lines.push(\n `## [${i.severity.toUpperCase()}]${status} ${i.issue.slice(0, 70)}`,\n '',\n `- \\`${i.file}\\`${i.line ? `:${i.line}` : ''}`,\n `- Agent: ${i.agent} | ${new Date(i.timestamp).toLocaleDateString()}`,\n '',\n );\n }\n\n return lines.join('\\n');\n }\n\n private async handleSimilar(params: {\n query?: string;\n limit?: number;\n }, workDir: string): Promise<string> {\n if (!params.query) {\n return 'Missing required parameter: query (issue description to find similar issues for)';\n }\n\n const mockIssue = {\n id: 'search',\n severity: 'moderate' as const,\n issue: params.query,\n fix: '',\n file: '',\n agent: 'search',\n confidence: 1,\n autoFixable: false,\n };\n\n const results = await findSimilarIssues(mockIssue, {\n workDir,\n limit: params.limit || 5,\n });\n\n if (results.length === 0) {\n return 'No similar issues found.';\n }\n\n const lines: string[] = [\n `# Similar Issues`,\n '',\n `Found ${results.length} similar issue(s):`,\n '',\n ];\n\n for (const result of results) {\n const i = result.issue;\n lines.push(\n `## [${i.severity.toUpperCase()}] ${i.issue.slice(0, 70)}`,\n '',\n `- **File:** \\`${i.file}\\``,\n `- **Similarity:** ${(result.score * 100).toFixed(0)}%`,\n '',\n );\n }\n\n return lines.join('\\n');\n }\n\n private async handleResolve(params: {\n issueId?: string;\n }, workDir: string): Promise<string> {\n if (!params.issueId) {\n return 'Missing required parameter: issueId';\n }\n\n const result = await markIssueResolved(params.issueId, workDir);\n \n if (result) {\n return `Issue ${params.issueId} marked as resolved.`;\n }\n return `Issue ${params.issueId} not found.`;\n }\n\n private async handleGlobal(params: {\n query?: string;\n limit?: number;\n }): Promise<string> {\n if (params.query) {\n const patterns = await searchGlobalPatterns(params.query, {\n limit: params.limit || 10,\n });\n\n if (patterns.length === 0) {\n return `No global patterns found matching \"${params.query}\"`;\n }\n\n const lines: string[] = [\n `# Global Pattern Search: \"${params.query}\"`,\n '',\n ];\n\n for (const p of patterns) {\n lines.push(\n `## [${p.severity.toUpperCase()}] ${p.pattern.slice(0, 60)}`,\n '',\n `- **Occurrences:** ${p.occurrences} across ${p.projects.length} projects`,\n `- **Agent:** ${p.agent}`,\n `- **Projects:** ${p.projects.slice(0, 3).join(', ')}`,\n p.fixApplied ? `- **Fixed in:** ${p.fixApplied.project}` : '',\n '',\n );\n }\n\n return lines.join('\\n');\n }\n\n const patterns = await findCrossProjectPatterns(2);\n const projects = await listTrackedProjects();\n\n const lines: string[] = [\n '# Global Cross-Project Memory',\n '',\n `**Tracked Projects:** ${projects.length}`,\n `**Cross-Project Patterns:** ${patterns.length}`,\n '',\n ];\n\n if (patterns.length > 0) {\n lines.push('## Top Cross-Project Patterns', '');\n \n for (const p of patterns.slice(0, 5)) {\n lines.push(\n `### [${p.severity.toUpperCase()}] ${p.pattern.slice(0, 50)}`,\n '',\n `- Seen ${p.occurrences}x across ${p.projects.length} projects`,\n p.fixApplied ? `- Fixed in ${p.fixApplied.project}` : '- Not yet fixed',\n '',\n );\n }\n }\n\n if (projects.length > 0) {\n lines.push('## Recent Projects', '', '| Project | Issues |', '|---------|--------|');\n \n for (const p of projects.slice(0, 5)) {\n lines.push(`| ${p.name} | ${p.totalIssues} |`);\n }\n }\n\n return lines.join('\\n');\n }\n\n private async handlePurge(params: {\n purgeStrategy?: 'smart' | 'resolved' | 'old' | 'all';\n daysOld?: number;\n }, workDir: string): Promise<string> {\n const strategy = params.purgeStrategy || 'smart';\n \n const options: { workDir: string; daysOld?: number } = { workDir };\n if (params.daysOld !== undefined) {\n options.daysOld = params.daysOld;\n }\n \n const result = await purgeIssues(strategy, options);\n\n const lines: string[] = [\n '# Memory Purge Complete',\n '',\n `**Strategy:** ${strategy}`,\n `**Removed:** ${result.removed} issues`,\n `**Remaining:** ${result.remaining} issues`,\n '',\n ];\n\n switch (strategy) {\n case 'smart':\n lines.push(\n '**What was removed:**',\n '- Resolved issues older than 30 days',\n '- Low-priority issues (info/low severity) older than 30 days',\n '',\n '**What was kept:**',\n '- All critical and high severity issues',\n '- All unresolved issues',\n '- All issues from the last 30 days',\n );\n break;\n case 'resolved':\n lines.push('**Removed all resolved issues.**', '**Kept all unresolved issues.**');\n break;\n case 'old':\n lines.push(\n `**Removed all issues older than ${params.daysOld || 90} days.**`,\n `**Kept all recent issues.**`,\n );\n break;\n case 'all':\n lines.push(\n '**Cleared all issues from active memory.**',\n '',\n 'Historical summaries are preserved in compacted-summaries.json.',\n );\n break;\n }\n\n lines.push('', '**Note:** Compacted historical summaries were preserved for trend analysis.');\n\n return lines.join('\\n');\n }\n}\n","import path from 'node:path';\n\nimport { ContextGraph } from '../context/graph.js';\nimport { importFromJson } from '../context/sync.js';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\n\nasync function removeOrphanEdges(graph: ContextGraph): Promise<number> {\n const nodes = await graph.listNodes();\n const ids = new Set(nodes.map((n) => n.id));\n const edges = await graph.listEdges();\n let removed = 0;\n for (const edge of edges) {\n if (!ids.has(edge.from_id) || !ids.has(edge.to_id)) {\n await graph.deleteEdge(edge.id);\n removed++;\n }\n }\n return removed;\n}\n\nexport interface ReconcileToolInput {\n directory?: string;\n source?: string;\n}\n\nexport class TrieReconcileTool {\n async execute(input: ReconcileToolInput = {}): Promise<any> {\n try {\n const projectPath = input.directory || getWorkingDirectory(undefined, true);\n const sourcePath = input.source ?? path.join(getTrieDirectory(projectPath), 'context.json');\n\n const graph = new ContextGraph(projectPath);\n await importFromJson(graph, '', sourcePath);\n const removed = await removeOrphanEdges(graph);\n\n return {\n content: [{\n type: 'text',\n text: `Reconciled context from ${sourcePath}. Removed ${removed} orphaned edges.`\n }]\n };\n } catch (error) {\n const friendly = formatFriendlyError(error);\n return { content: [{ type: 'text', text: friendly.userMessage }] };\n }\n }\n}\n","import { ContextGraph } from '../context/graph.js';\nimport { exportToJson } from '../context/sync.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { formatFriendlyError } from '../utils/errors.js';\n\nexport interface ContextToolInput {\n directory?: string;\n}\n\nexport class TrieContextTool {\n async execute(input: ContextToolInput = {}): Promise<any> {\n try {\n const workDir = input.directory || getWorkingDirectory(undefined, true);\n const graph = new ContextGraph(workDir);\n const snapshot = await graph.getSnapshot();\n await exportToJson(graph);\n\n const summary = `Nodes: ${snapshot.nodes.length}, Edges: ${snapshot.edges.length}, Exported: ${snapshot.exported_at}`;\n\n return {\n content: [{\n type: 'text',\n text: summary\n }],\n data: snapshot\n };\n } catch (error) {\n const friendly = formatFriendlyError(error);\n return { content: [{ type: 'text', text: friendly.userMessage }] };\n }\n }\n}\n","import { LinearIngester } from '../ingest/linear-ingester.js';\nimport { ContextGraph } from '../context/graph.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport interface LinearSyncInput {\n directory?: string;\n}\n\nexport class LinearSyncTool {\n async execute(input: LinearSyncInput): Promise<any> {\n try {\n const workDir = input.directory || getWorkingDirectory(undefined, true);\n const graph = new ContextGraph(workDir);\n const ingester = new LinearIngester(workDir, graph);\n\n await ingester.syncTickets();\n\n return {\n content: [{\n type: 'text',\n text: '✅ Linear tickets synced successfully. Trie now has context on your active tasks.'\n }]\n };\n } catch (error: any) {\n return {\n isError: true,\n content: [{\n type: 'text',\n text: `Failed to sync Linear tickets: ${error.message}`\n }]\n };\n }\n }\n}\n","import { GitHubIngester } from '../ingest/github-ingester.js';\nimport { ContextGraph } from '../context/graph.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\n\nexport interface GitHubSyncInput {\n directory?: string;\n}\n\nexport class GitHubSyncTool {\n async execute(input: GitHubSyncInput): Promise<any> {\n try {\n const workDir = input.directory || getWorkingDirectory(undefined, true);\n const graph = new ContextGraph(workDir);\n const ingester = new GitHubIngester(graph);\n\n const token = await ingester.getApiToken();\n if (!token) {\n return {\n isError: true,\n content: [{\n type: 'text',\n text: 'GitHub token not configured.\\n\\n' +\n 'Set one of:\\n' +\n ' • Environment variable: GITHUB_TOKEN=ghp_...\\n' +\n ' • Config dialog (C key) → API Keys → GitHub\\n' +\n ' • .trie/config.json: { \"apiKeys\": { \"github\": \"ghp_...\" } }\\n\\n' +\n 'Token needs `repo` scope for private repos, `public_repo` for public.',\n }],\n };\n }\n\n const repoInfo = ingester.getRepoInfo(workDir);\n if (!repoInfo) {\n return {\n isError: true,\n content: [{\n type: 'text',\n text: 'Could not detect GitHub repository.\\n\\n' +\n 'Make sure this directory is a git repo with a GitHub remote:\\n' +\n ' git remote get-url origin',\n }],\n };\n }\n\n const prResult = await ingester.syncPullRequests(repoInfo.owner, repoInfo.name, token);\n const issueResult = await ingester.syncIssues(repoInfo.owner, repoInfo.name, token);\n\n const LINE = '\\u2500'.repeat(45);\n const lines = [\n 'GITHUB SYNC',\n LINE,\n `Repo: ${repoInfo.owner}/${repoInfo.name}`,\n `Pulled ${prResult.prs} open PR${prResult.prs !== 1 ? 's' : ''}, ${issueResult.issues} open issue${issueResult.issues !== 1 ? 's' : ''}`,\n `Linked ${prResult.linkedTickets} PR${prResult.linkedTickets !== 1 ? 's' : ''} to Linear tickets`,\n `Linked ${prResult.linkedFiles} PR${prResult.linkedFiles !== 1 ? 's' : ''} to changed files in context graph`,\n LINE,\n 'Next sync: trie_github_sync',\n 'Or use trie_pipeline for consolidated view.',\n ];\n\n return {\n content: [{\n type: 'text',\n text: lines.join('\\n'),\n }],\n };\n } catch (error: any) {\n return {\n isError: true,\n content: [{\n type: 'text',\n text: `GitHub sync failed: ${error.message}`,\n }],\n };\n }\n }\n}\n","/**\n * Trie Index Tool\n * \n * MCP tool for indexing the codebase for fast goal checking and file lookups.\n * The index is automatically updated when files change during watch mode,\n * but this tool allows manual full indexing.\n */\n\nimport { glob } from 'glob';\nimport { CodebaseIndex } from '../context/codebase-index.js';\nimport { getWorkingDirectory } from '../utils/workspace.js';\nimport { isTrieInitialized } from '../utils/trie-init.js';\n\nconst INDEXABLE_EXTENSIONS = [\n 'ts', 'tsx', 'js', 'jsx', 'mjs',\n 'vue', 'svelte', 'astro',\n 'py', 'go', 'rs', 'java', 'c', 'cpp', 'h', 'hpp',\n 'cs', 'rb', 'php', 'css', 'scss', 'html',\n];\n\nexport class TrieIndexTool {\n async execute(params: {\n action?: 'full' | 'status' | 'clear';\n directory?: string;\n }): Promise<string> {\n const action = params.action || 'full';\n const workDir = getWorkingDirectory(params.directory, true);\n\n if (!isTrieInitialized(workDir)) {\n return 'Trie is not initialized for this project. Run `trie init` first.';\n }\n\n const codebaseIndex = new CodebaseIndex(workDir);\n\n if (action === 'status') {\n const stats = codebaseIndex.getStats();\n \n let lastUpdatedStr = 'Never';\n if (stats.lastUpdated) {\n try {\n const date = new Date(stats.lastUpdated);\n lastUpdatedStr = date.toLocaleString('en-US', {\n year: 'numeric',\n month: 'short',\n day: 'numeric',\n hour: 'numeric',\n minute: '2-digit',\n });\n } catch {\n lastUpdatedStr = 'Unknown';\n }\n }\n \n return [\n '# Codebase Index Status',\n '',\n `**Total files indexed:** ${stats.totalFiles}`,\n `**Total size:** ${(stats.totalSize / 1024 / 1024).toFixed(2)} MB`,\n `**Files scanned for goals:** ${stats.scannedFiles}`,\n `**Files with violations:** ${stats.filesWithViolations}`,\n `**Last updated:** ${lastUpdatedStr}`,\n '',\n '## Files by Type',\n '',\n ...Object.entries(stats.filesByType)\n .sort(([, a], [, b]) => b - a)\n .slice(0, 10)\n .map(([type, count]) => `- .${type}: ${count} files`),\n '',\n '---',\n '',\n 'Run `trie_index` with action=\"full\" to re-index the codebase.',\n 'Run `trie_index` with action=\"clear\" to clear stale cache entries.',\n ].join('\\n');\n }\n\n if (action === 'clear') {\n const cleared = codebaseIndex.clearStaleCache();\n await codebaseIndex.save();\n return `Cleared ${cleared} stale cache entries.`;\n }\n\n // Full indexing\n const pattern = `${workDir}/**/*.{${INDEXABLE_EXTENSIONS.join(',')}}`;\n const allFiles = await glob(pattern, {\n ignore: ['**/node_modules/**', '**/dist/**', '**/build/**', '**/.git/**', '**/.trie/**', '**/coverage/**'],\n nodir: true,\n });\n\n let indexed = 0;\n let failed = 0;\n const startTime = Date.now();\n\n // Process files in batches to avoid overwhelming the system\n const BATCH_SIZE = 50;\n for (let i = 0; i < allFiles.length; i += BATCH_SIZE) {\n const batch = allFiles.slice(i, i + BATCH_SIZE);\n \n await Promise.all(batch.map(async (filePath) => {\n try {\n // Get relative path (handle case-insensitive filesystems)\n let relativePath = filePath;\n if (filePath.toLowerCase().startsWith(workDir.toLowerCase() + '/')) {\n relativePath = filePath.slice(workDir.length + 1);\n }\n \n const result = await codebaseIndex.indexFile(relativePath);\n if (result) {\n indexed++;\n } else {\n failed++;\n }\n } catch {\n failed++;\n }\n }));\n }\n\n await codebaseIndex.save();\n const duration = ((Date.now() - startTime) / 1000).toFixed(1);\n const stats = codebaseIndex.getStats();\n\n return [\n '# Codebase Indexing Complete',\n '',\n `**Files indexed:** ${indexed}`,\n `**Files failed:** ${failed}`,\n `**Duration:** ${duration}s`,\n '',\n '## Index Statistics',\n '',\n `- Total files: ${stats.totalFiles}`,\n `- Total size: ${(stats.totalSize / 1024 / 1024).toFixed(2)} MB`,\n '',\n '## Files by Type',\n '',\n ...Object.entries(stats.filesByType)\n .sort(([, a], [, b]) => b - a)\n .slice(0, 10)\n .map(([type, count]) => `- .${type}: ${count} files`),\n '',\n '---',\n '',\n 'The index will be automatically updated when files change during watch mode.',\n 'Goal checks will now use cached results for unchanged files.',\n ].join('\\n');\n }\n}\n","import { TrieScanTool } from '../tools/scan.js';\nimport { TrieFixTool } from '../tools/fix.js';\nimport { TrieCloudFixTool } from '../tools/cloud-fix.js';\nimport { TrieExplainTool } from '../tools/explain.js';\nimport { TrieTestTool } from '../tools/test.js';\nimport { TrieWatchTool } from '../tools/watch.js';\nimport { TriePRReviewTool } from '../tools/pr-review.js';\nimport { TrieProjectInfoTool } from '../tools/project-info.js';\nimport { TrieInitTool } from '../tools/init.js';\nimport { TrieMemorySearchTool } from '../tools/memory-search.js';\nimport { handleCheckpointTool, type CheckpointToolInput } from '../tools/checkpoint.js';\nimport { TrieCheckTool } from '../tools/check.js';\nimport { TrieTellTool } from '../tools/tell.js';\nimport { TrieReconcileTool } from '../tools/reconcile.js';\nimport { TrieContextTool } from '../tools/context.js';\nimport { TrieFeedbackTool } from '../tools/feedback.js';\nimport { LinearSyncTool } from '../tools/linear-sync.js';\nimport { GitHubSyncTool } from '../tools/github-sync.js';\nimport { GitHubBranchesTool } from '../tools/github-branches.js';\nimport { TriePipelineTool } from '../tools/pipeline.js';\nimport { TrieIndexTool } from '../tools/index-codebase.js';\nimport { \n TrieGetGovernanceTool,\n TrieGetDecisionsTool,\n TrieGetBlockersTool, \n TrieGetRelatedGovernanceTool,\n TrieGetRelatedDecisionsTool,\n TrieQueryContextTool \n} from '../tools/query-tools.js';\n\nclass TrieCheckpointTool {\n async execute(input: CheckpointToolInput): Promise<any> {\n const result = await handleCheckpointTool(input);\n return {\n content: [{\n type: 'text',\n text: result\n }]\n };\n }\n}\n\nexport interface ToolDefinition {\n name: string;\n description: string;\n inputSchema: Record<string, any>;\n _meta?: {\n ui?: {\n resourceUri: string;\n };\n };\n}\n\nexport class ToolRegistry {\n private tools: Map<string, any> = new Map();\n private definitions: ToolDefinition[] = [];\n\n constructor() {\n this.initializeTools();\n this.defineToolSchemas();\n }\n\n private initializeTools() {\n // Initialize tool instances\n this.tools.set('scan', new TrieScanTool());\n this.tools.set('fix', new TrieFixTool());\n this.tools.set('cloud_fix', new TrieCloudFixTool());\n this.tools.set('explain', new TrieExplainTool());\n this.tools.set('test', new TrieTestTool());\n this.tools.set('watch', new TrieWatchTool());\n this.tools.set('pr_review', new TriePRReviewTool());\n this.tools.set('project', new TrieProjectInfoTool());\n this.tools.set('init', new TrieInitTool());\n this.tools.set('memory', new TrieMemorySearchTool());\n this.tools.set('checkpoint', new TrieCheckpointTool());\n this.tools.set('check', new TrieCheckTool());\n this.tools.set('tell', new TrieTellTool());\n this.tools.set('reconcile', new TrieReconcileTool());\n this.tools.set('context', new TrieContextTool());\n this.tools.set('feedback', new TrieFeedbackTool());\n this.tools.set('ok', new TrieFeedbackTool());\n this.tools.set('bad', new TrieFeedbackTool());\n this.tools.set('linear_sync', new LinearSyncTool());\n this.tools.set('github_sync', new GitHubSyncTool());\n this.tools.set('github_branches', new GitHubBranchesTool());\n this.tools.set('pipeline', new TriePipelineTool());\n this.tools.set('index', new TrieIndexTool());\n \n // Query tools for governance ledger\n this.tools.set('get_governance', new TrieGetGovernanceTool());\n this.tools.set('get_decisions', new TrieGetDecisionsTool()); // Backward compatibility\n this.tools.set('get_blockers', new TrieGetBlockersTool());\n this.tools.set('get_related_governance', new TrieGetRelatedGovernanceTool());\n this.tools.set('get_related_decisions', new TrieGetRelatedDecisionsTool()); // Backward compatibility\n this.tools.set('query_context', new TrieQueryContextTool());\n }\n\n private defineToolSchemas() {\n this.definitions = [\n {\n name: 'trie_scan',\n description: 'Scan code with intelligent agent selection. Scans entire codebase if no files specified. Auto-updates .trie/AGENTS.md with results. Alias: scan',\n inputSchema: {\n type: 'object',\n properties: {\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Files to scan (absolute paths). If empty, scans entire codebase.'\n },\n directory: {\n type: 'string',\n description: 'Directory to scan (if files not specified). Defaults to current working directory.'\n },\n context: {\n type: 'object',\n properties: {\n changeType: {\n type: 'string',\n enum: ['ui', 'api', 'database', 'auth', 'payment', 'general']\n },\n isNewFeature: { type: 'boolean' },\n touchesUserData: { type: 'boolean' }\n }\n },\n forceAgents: {\n type: 'array',\n items: { type: 'string' },\n description: 'Manually specify agents to run (overrides triaging)'\n },\n parallel: {\n type: 'boolean',\n description: 'Run agents in parallel (default true)'\n },\n cache: {\n type: 'boolean',\n description: 'Enable scan result caching (default true)'\n },\n maxConcurrency: {\n type: 'number',\n description: 'Max parallel agents'\n },\n timeoutMs: {\n type: 'number',\n description: 'Agent timeout in milliseconds'\n },\n streaming: {\n type: 'boolean',\n description: 'Stream progress updates'\n },\n interactive: {\n type: 'boolean',\n description: 'Enable interactive CLI dashboard (TTY only)'\n },\n format: {\n type: 'string',\n enum: ['text', 'json'],\n description: 'Output format for optional file output'\n },\n output: {\n type: 'string',\n description: 'Output file path when format is json'\n },\n workers: {\n type: 'boolean',\n description: 'Use worker threads for parallel execution'\n }\n }\n } as const,\n // MCP Apps: Interactive scan dashboard\n _meta: {\n ui: { resourceUri: 'ui://trie/scan-dashboard' }\n },\n },\n {\n name: 'trie',\n description: 'Quick menu of available Trie commands. TIP: Read trie://context first for project state and priorities. Call with `action` to run directly.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n description: 'Optional quick action: scan, security, legal, bugs, types, devops, architecture, ux, clean, soc2, performance, e2e, visual_qa, data_flow, agent_smith, pr_review, watch, fix, explain'\n },\n agent: {\n type: 'string',\n description: 'Agent key when action=agent or when using a custom skill name'\n },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Files to scan (absolute or relative)'\n },\n directory: {\n type: 'string',\n description: 'Directory to scan (defaults to detected workspace)'\n },\n context: {\n type: 'object',\n properties: {\n changeType: {\n type: 'string',\n enum: ['ui', 'api', 'database', 'auth', 'payment', 'general']\n },\n isNewFeature: { type: 'boolean' },\n touchesUserData: { type: 'boolean' }\n }\n }\n }\n } as const,\n },\n {\n name: 'trie_fix',\n description: 'Apply high-confidence fixes to code. Use action:route to see triage plan first. Alias: fix',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['route'],\n description: 'route: show fix routing plan without applying fixes'\n },\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_cloud_fix',\n description: 'Dispatch issues to Cursor cloud agents for verified, test-passing fixes. The cloud agent runs in an isolated VM, applies the fix, runs tests, screenshots the result, and opens a PR. Use trie_fix action:route first to see which issues qualify.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['configure', 'dispatch', 'status', 'artifacts', 'cancel'],\n description: 'configure: save API key | dispatch: send to cloud | status: poll jobs | artifacts: get screenshots + PR links | cancel: abort a job'\n },\n issueIds: {\n type: 'array',\n items: { type: 'string' },\n description: 'Issue IDs to dispatch (from trie_scan). If omitted, dispatches all cloud-eligible pending issues.'\n },\n apiKey: {\n type: 'string',\n description: 'Cursor API key (configure action only)'\n },\n jobId: {\n type: 'string',\n description: 'Job ID for cancel or artifacts actions'\n }\n },\n required: ['action']\n } as const,\n },\n {\n name: 'trie_explain',\n description: 'Explain code, issues, or changes in plain language. Alias: explain',\n inputSchema: {\n type: 'object',\n properties: {\n type: {\n type: 'string',\n enum: ['code', 'issue', 'change', 'risk']\n },\n target: {\n type: 'string',\n description: 'What to explain (file path, issue ID, etc.)'\n }\n },\n required: ['type', 'target']\n } as const,\n },\n {\n name: 'trie_feedback',\n description: 'Record quick feedback about a warning or suggestion (thumbs up/down). Alias: trie_ok, trie_bad',\n inputSchema: {\n type: 'object',\n properties: {\n helpful: { type: 'boolean', description: 'true for 👍, false for 👎' },\n target: { type: 'string', description: 'Optional file or item being rated' },\n note: { type: 'string', description: 'Optional short note about why' },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Optional related files (absolute or relative)'\n },\n directory: { type: 'string', description: 'Working directory (defaults to auto-detected)' }\n },\n required: ['helpful']\n } as const,\n },\n {\n name: 'trie_check',\n description: 'Run Trie risk check on current changes. Modes: quick, full, offline.',\n inputSchema: {\n type: 'object',\n properties: {\n directory: { type: 'string' },\n files: { type: 'array', items: { type: 'string' } },\n mode: { type: 'string', enum: ['quick', 'full', 'offline'] }\n }\n }\n },\n {\n name: 'trie_tell',\n description: 'Report an incident so Trie can learn.',\n inputSchema: {\n type: 'object',\n properties: {\n description: { type: 'string' },\n directory: { type: 'string' }\n },\n required: ['description']\n }\n },\n {\n name: 'trie_reconcile',\n description: 'Re-sync context graph from context.json and clean orphaned edges.',\n inputSchema: {\n type: 'object',\n properties: {\n directory: { type: 'string' },\n source: { type: 'string' }\n }\n }\n },\n {\n name: 'trie_context',\n description: 'Return current context snapshot (nodes/edges) and export context.json.',\n inputSchema: {\n type: 'object',\n properties: {\n directory: { type: 'string' }\n }\n }\n },\n {\n name: 'trie_test',\n description: 'Generate or reason about tests. Alias: test',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['generate', 'coverage', 'suggest', 'run'],\n description: 'Test action to perform'\n },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Target source files'\n },\n framework: {\n type: 'string',\n description: 'Optional framework hint (jest, vitest, playwright, etc.)'\n },\n style: {\n type: 'string',\n description: 'Test style (unit, integration, e2e). Defaults to unit.'\n }\n },\n required: ['action', 'files']\n } as const,\n },\n {\n name: 'trie_watch',\n description: 'Autonomous watch mode. Alias: watch',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['start', 'stop', 'status', 'issues'],\n description: 'Watch action'\n },\n directory: {\n type: 'string',\n description: 'Workspace directory to watch (optional, auto-detected)'\n },\n debounceMs: {\n type: 'number',\n description: 'Debounce time for scans (ms)'\n }\n },\n required: ['action']\n } as const,\n },\n {\n name: 'trie_project',\n description: 'View and manage project information (.trie/PROJECT.md). Store project context for AI assistants. Alias: project',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['view', 'init', 'update', 'append', 'sections', 'raw'],\n description: 'Action: view (default), init (create template), update (replace section), append (add to section), sections (list), raw (full file)'\n },\n section: {\n type: 'string',\n description: 'Section name (e.g., \"Project Overview\", \"Technology Stack\", \"AI Instructions\")'\n },\n content: {\n type: 'string',\n description: 'Content for update/append actions'\n },\n directory: {\n type: 'string',\n description: 'Project directory (defaults to current workspace)'\n }\n }\n } as const,\n },\n {\n name: 'trie_init',\n description: 'Initialize bootstrap files (.trie/RULES.md, .trie/TEAM.md, .trie/BOOTSTRAP.md). Detects stack and suggests skills.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['init', 'status', 'complete', 'context'],\n description: 'Action: init (create files), status (check state), complete (finish bootstrap), context (get injected content)'\n },\n directory: {\n type: 'string',\n description: 'Project directory (defaults to current workspace)'\n },\n force: {\n type: 'boolean',\n description: 'Overwrite existing files'\n },\n skipBootstrap: {\n type: 'boolean',\n description: 'Skip creating BOOTSTRAP.md'\n }\n }\n } as const,\n },\n {\n name: 'trie_memory',\n description: 'Search and manage issue memory. Find similar issues, view stats, search across projects, and purge old issues.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['search', 'stats', 'recent', 'similar', 'resolve', 'global', 'purge'],\n description: 'Action: search (find issues), stats (show statistics), recent (recent issues), similar (find similar), resolve (mark resolved), global (cross-project), purge (free up memory)'\n },\n query: {\n type: 'string',\n description: 'Search query for search/similar/global actions'\n },\n issueId: {\n type: 'string',\n description: 'Issue ID for resolve action'\n },\n limit: {\n type: 'number',\n description: 'Maximum results to return'\n },\n severity: {\n type: 'array',\n items: { type: 'string' },\n description: 'Filter by severity levels'\n },\n agent: {\n type: 'string',\n description: 'Filter by agent name'\n },\n includeResolved: {\n type: 'boolean',\n description: 'Include resolved issues in search'\n },\n directory: {\n type: 'string',\n description: 'Project directory (defaults to current workspace)'\n },\n purgeStrategy: {\n type: 'string',\n enum: ['smart', 'resolved', 'old', 'all'],\n description: 'Purge strategy: smart (remove resolved & old low-priority), resolved (all resolved), old (older than daysOld), all (clear all)'\n },\n daysOld: {\n type: 'number',\n description: 'Days threshold for old purge strategy (default 90)'\n }\n }\n } as const,\n // MCP Apps: Interactive memory viewer\n _meta: {\n ui: { resourceUri: 'ui://trie/memory-viewer' }\n },\n },\n {\n name: 'trie_checkpoint',\n description: 'Save a context checkpoint without running a full scan. Quick save for your current work state.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['save', 'list', 'last'],\n description: 'Action: save (create checkpoint), list (show recent), last (show last checkpoint)'\n },\n message: {\n type: 'string',\n description: 'Checkpoint message (what you were working on)'\n },\n notes: {\n type: 'string',\n description: 'Additional notes'\n },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Files to associate with this checkpoint'\n }\n },\n required: ['action']\n } as const,\n },\n {\n name: 'trie_index',\n description: 'Index codebase for fast goal checking and file lookups. Index is auto-updated during watch mode. Use this for initial indexing or to rebuild the index.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['full', 'status', 'clear'],\n description: 'Action: full (index all files), status (show index stats), clear (remove stale cache)'\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.createSpecialAgentDefinitions(),\n ].flat();\n }\n\n private createSpecialAgentDefinitions(): ToolDefinition[] {\n return [\n {\n name: 'trie_visual_qa_browser',\n description: 'Capture screenshots at mobile/tablet/desktop viewports for visual QA. Alias: visual_qa_browser',\n inputSchema: {\n type: 'object',\n properties: {\n url: { type: 'string', description: 'URL to screenshot' },\n port: { type: 'number', description: 'Specific port to check' },\n waitForSelector: { type: 'string', description: 'CSS selector to wait for' },\n waitMs: { type: 'number', description: 'Additional wait time' }\n }\n } as const,\n // MCP Apps: Interactive visual QA gallery\n _meta: {\n ui: { resourceUri: 'ui://trie/visual-qa' }\n },\n },\n {\n name: 'trie_pr_review',\n description: '🔍 Interactive PR review: walks through changes file-by-file. Alias: pr_review',\n inputSchema: {\n type: 'object',\n properties: {\n pr: { type: 'string', description: 'PR number to review' },\n worktree: { type: 'string', description: 'Path to worktree directory' },\n mode: {\n type: 'string',\n enum: ['own', 'others'],\n description: 'Review mode'\n },\n files: {\n type: 'array',\n items: { type: 'string' },\n description: 'Specific files to review'\n }\n }\n } as const,\n // MCP Apps: Interactive PR review UI\n _meta: {\n ui: { resourceUri: 'ui://trie/pr-review' }\n },\n },\n {\n name: 'trie_linear_sync',\n description: 'Sync active Linear tickets to build context for JIT defect prediction. Alias: linear_sync',\n inputSchema: {\n type: 'object',\n properties: {\n directory: { type: 'string', description: 'Project directory' }\n }\n }\n },\n {\n name: 'trie_github_sync',\n description: 'Sync open PRs and issues from GitHub into the Trie context graph. Links PRs to files they touch and to Linear tickets mentioned in PR descriptions. Run once to initialize, or periodically to stay current.',\n inputSchema: {\n type: 'object',\n properties: {\n directory: { type: 'string', description: 'Project directory (defaults to current workspace)' }\n }\n }\n },\n {\n name: 'trie_github_branches',\n description: 'Fetch GitHub branches with latest commit info. Use when the user asks which branch has the latest updates, what branches exist, or when branches were last updated. Requires GitHub API key.',\n inputSchema: {\n type: 'object',\n properties: {\n directory: { type: 'string', description: 'Project directory (defaults to current workspace)' },\n limit: { type: 'number', description: 'Max branches to return (default 15, max 30)' }\n }\n }\n },\n {\n name: 'trie_pipeline',\n description: 'Get consolidated pipeline status: open PRs, active Linear tickets, open GitHub issues, and Trie scan issues not yet in any ticket or PR (coverage gaps). Use to understand where work stands and what is falling through the cracks.',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['status', 'coverage', 'create_tickets'],\n description: 'status: full pipeline view | coverage: only show Trie issues with no ticket/PR | create_tickets: open Linear tickets for uncovered issues'\n },\n focus: {\n type: 'string',\n description: 'Optional file path or Linear ticket ID to narrow the view'\n },\n issueIds: {\n type: 'array',\n items: { type: 'string' },\n description: 'Issue IDs to create tickets for (create_tickets action only)'\n },\n directory: { type: 'string', description: 'Project directory' }\n }\n }\n },\n {\n name: 'trie_get_governance',\n description: 'Query governance records (architectural decisions, standards, team agreements) from governance ledger with targeted retrieval. Prevents context pollution by returning only relevant records.',\n inputSchema: {\n type: 'object',\n properties: {\n relatedTo: { type: 'string', description: 'File path or topic to find related governance' },\n tags: { type: 'array', items: { type: 'string' }, description: 'Filter by tags' },\n since: { type: 'string', description: 'Time filter: ISO date or \"7d\", \"30d\", \"90d\"' },\n limit: { type: 'number', description: 'Max results (default 10)' },\n directory: { type: 'string', description: 'Working directory' }\n }\n }\n },\n {\n name: 'trie_get_decisions',\n description: '[DEPRECATED - use trie_get_governance] Query governance records from ledger. Backward compatibility alias.',\n inputSchema: {\n type: 'object',\n properties: {\n relatedTo: { type: 'string', description: 'File path or topic to find related governance' },\n tags: { type: 'array', items: { type: 'string' }, description: 'Filter by tags' },\n since: { type: 'string', description: 'Time filter: ISO date or \"7d\", \"30d\", \"90d\"' },\n limit: { type: 'number', description: 'Max results (default 10)' },\n directory: { type: 'string', description: 'Working directory' }\n }\n }\n },\n {\n name: 'trie_get_blockers',\n description: 'Get active blockers from governance ledger. Returns only unresolved blockers to avoid noise.',\n inputSchema: {\n type: 'object',\n properties: {\n tags: { type: 'array', items: { type: 'string' }, description: 'Filter by tags' },\n limit: { type: 'number', description: 'Max results (default 5)' },\n directory: { type: 'string', description: 'Working directory' }\n }\n }\n },\n {\n name: 'trie_get_related_governance',\n description: 'Find governance records related to a specific governance record, file, or topic. Targeted context retrieval.',\n inputSchema: {\n type: 'object',\n properties: {\n governanceId: { type: 'string', description: 'Governance ID to find related records' },\n file: { type: 'string', description: 'File path to find related governance' },\n topic: { type: 'string', description: 'Topic to find related governance' },\n limit: { type: 'number', description: 'Max results (default 5)' },\n directory: { type: 'string', description: 'Working directory' }\n }\n }\n },\n {\n name: 'trie_get_related_decisions',\n description: '[DEPRECATED - use trie_get_related_governance] Find related governance records. Backward compatibility alias.',\n inputSchema: {\n type: 'object',\n properties: {\n decisionId: { type: 'string', description: 'Decision ID to find related records' },\n file: { type: 'string', description: 'File path to find related governance' },\n topic: { type: 'string', description: 'Topic to find related governance' },\n limit: { type: 'number', description: 'Max results (default 5)' },\n directory: { type: 'string', description: 'Working directory' }\n }\n }\n },\n {\n name: 'trie_query_context',\n description: 'Natural-language search across ALL Trie context: goals, hypotheses, nudges (goal violations), governance, blockers. Use for \"what are my goals\", \"show hypotheses\", \"any nudges\", \"recent governance\", etc.',\n inputSchema: {\n type: 'object',\n properties: {\n query: { type: 'string', description: 'Natural language query (e.g. goals, hypotheses, nudges, governance)' },\n type: { \n type: 'string', \n enum: ['goals', 'hypotheses', 'nudges', 'governance', 'decisions', 'blockers', 'facts', 'questions', 'all'],\n description: 'Type of context to query (default: all). \"decisions\" is deprecated, use \"governance\"'\n },\n limit: { type: 'number', description: 'Max results per type (default 10)' },\n directory: { type: 'string', description: 'Working directory' }\n },\n required: ['query']\n }\n }\n ];\n }\n\n getTool(name: string): any {\n return this.tools.get(name);\n }\n\n getAllTools(): ToolDefinition[] {\n return this.definitions;\n }\n\n getToolNames(): string[] {\n return Array.from(this.tools.keys());\n }\n\n hasTool(name: string): boolean {\n return this.tools.has(name);\n }\n}","import { readdir, readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join, dirname } from 'path';\nimport { fileURLToPath } from 'url';\nimport { getWorkingDirectory, getTrieDirectory } from '../utils/workspace.js';\nimport { getSkillRegistry } from '../skills/built-in/registry.js';\nimport { loadConfig } from '../config/loader.js';\nimport { getContextForAI, loadContextState } from '../utils/context-state.js';\nimport { loadProjectInfo, projectInfoExists } from '../utils/project-info.js';\nimport { listInstalledSkills } from '../skills/installer.js';\nimport { loadBootstrapContext, loadRules, loadTeamInfo } from '../bootstrap/index.js';\nimport { getMemoryStats, getRecentIssues } from '../memory/issue-store.js';\nimport { getGlobalMemoryStats, findCrossProjectPatterns } from '../memory/global-memory.js';\n\nexport interface Resource {\n uri: string;\n name: string;\n description?: string;\n mimeType?: string;\n}\n\nexport interface ResourceContent {\n contents: Array<{\n uri: string;\n mimeType?: string;\n text: string;\n }>;\n}\n\n// UI App definitions for MCP Apps\nconst UI_APPS = {\n 'ledger': {\n name: 'Decision Ledger',\n description: 'Track decisions, blockers, facts, and questions across your project',\n },\n 'goals': {\n name: 'Goals & Progress',\n description: 'Monitor code quality goals and track progress with visual indicators',\n },\n 'hypotheses': {\n name: 'Hypotheses',\n description: 'Test and validate development theories with evidence-based reasoning',\n },\n 'nudges': {\n name: 'Nudges & Insights',\n description: 'AI-powered code quality insights, warnings, and suggestions',\n },\n 'chat': {\n name: 'AI Chat',\n description: 'Interactive chat with Trie assistant for code analysis and guidance',\n },\n} as const;\n\ntype UIAppId = keyof typeof UI_APPS;\n\nexport class ResourceManager {\n private skillRegistry = getSkillRegistry();\n\n /**\n * Get all available resources dynamically\n */\n async getAvailableResources(): Promise<Resource[]> {\n const resources: Resource[] = [];\n\n // Static resources\n resources.push(\n {\n uri: 'trie://context',\n name: 'AI Context (Consolidated)',\n description: 'Single source of truth: project state, coding rules, recent issues, and cross-project patterns. Read this first.',\n mimeType: 'text/markdown',\n },\n {\n uri: 'trie://project',\n name: 'Project Information',\n description: 'User-defined project context (description, conventions, architecture, AI instructions)',\n mimeType: 'text/markdown',\n },\n {\n uri: 'trie://context/state',\n name: 'Context State',\n description: 'Detailed context state with scan history and priorities',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://skills',\n name: 'Available Skills',\n description: 'List of all available Trie skills (built-in and custom)',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://config',\n name: 'Trie Configuration',\n description: 'Current Trie configuration settings',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://cache/stats',\n name: 'Cache Statistics',\n description: 'Trie scan cache statistics and performance metrics',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://signatures',\n name: 'Vulnerability Signatures',\n description: 'Summary of loaded vulnerability detection signatures',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://skills/installed',\n name: 'Installed Skills',\n description: 'External skills installed from skills.sh that Trie can apply',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://bootstrap',\n name: 'Bootstrap Status',\n description: 'Bootstrap file status and project setup context',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://rules',\n name: 'Project Rules',\n description: 'User-defined coding standards from .trie/RULES.md',\n mimeType: 'text/markdown',\n },\n {\n uri: 'trie://team',\n name: 'Team Info',\n description: 'Team ownership and escalation from .trie/TEAM.md',\n mimeType: 'text/markdown',\n },\n {\n uri: 'trie://memory',\n name: 'Issue Memory',\n description: 'Issue memory statistics and recent issues',\n mimeType: 'application/json',\n },\n {\n uri: 'trie://memory/global',\n name: 'Global Memory',\n description: 'Cross-project patterns and statistics',\n mimeType: 'application/json',\n }\n );\n\n // Dynamic resources: scan reports\n resources.push(...await this.getScanReportResources());\n\n // Dynamic resources: custom skills\n resources.push(...await this.getCustomSkillResources());\n\n // UI App resources (MCP Apps)\n resources.push(...this.getUIAppResources());\n\n return resources;\n }\n\n private async getScanReportResources(): Promise<Resource[]> {\n try {\n const reportsDir = join(getWorkingDirectory(undefined, true), 'trie-reports');\n const files = await readdir(reportsDir);\n const reportFiles = files.filter(f => f.endsWith('.txt') || f.endsWith('.json'));\n\n return reportFiles.slice(0, 10).map(file => ({\n uri: `trie://reports/${file}`,\n name: `Scan Report: ${file}`,\n description: `Trie scan report from ${file}`,\n mimeType: file.endsWith('.json') ? 'application/json' : 'text/plain',\n }));\n } catch {\n return []; // No reports directory yet\n }\n }\n\n private async getCustomSkillResources(): Promise<Resource[]> {\n try {\n await this.skillRegistry.loadCustomSkills();\n const customSkills = this.skillRegistry.getCustomSkills();\n\n return customSkills.map(skill => ({\n uri: `trie://skills/custom/${skill.name}`,\n name: `Custom Skill: ${skill.name}`,\n description: skill.description,\n mimeType: 'application/json',\n }));\n } catch {\n return []; // No custom skills\n }\n }\n\n /**\n * Read content for a specific resource\n */\n async readResourceContent(uri: string): Promise<ResourceContent> {\n // Handle UI App resources (MCP Apps)\n if (uri.startsWith('ui://trie/')) {\n const appId = uri.replace('ui://trie/', '');\n return await this.getUIAppResource(uri, appId);\n }\n\n const parsedUri = uri.replace('trie://', '');\n\n // Handle AI context (read this first!)\n if (parsedUri === 'context') {\n return await this.getContextResource(uri);\n }\n\n // Handle project info (user-defined context)\n if (parsedUri === 'project') {\n return await this.getProjectResource(uri);\n }\n\n // Handle context state (detailed JSON)\n if (parsedUri === 'context/state') {\n return await this.getContextStateResource(uri);\n }\n\n // Handle built-in skills list\n if (parsedUri === 'skills') {\n return await this.getBuiltInSkillsResource(uri);\n }\n\n // Handle specific custom skill\n if (parsedUri.startsWith('skills/custom/')) {\n return await this.getCustomSkillResource(uri, parsedUri);\n }\n\n // Handle configuration\n if (parsedUri === 'config') {\n return await this.getConfigResource(uri);\n }\n\n // Handle cache stats\n if (parsedUri === 'cache/stats') {\n return await this.getCacheStatsResource(uri);\n }\n\n // Handle vulnerability signatures\n if (parsedUri === 'signatures') {\n return await this.getSignaturesResource(uri);\n }\n\n // Handle installed skills\n if (parsedUri === 'skills/installed') {\n return await this.getInstalledSkillsResource(uri);\n }\n\n // Handle bootstrap status\n if (parsedUri === 'bootstrap') {\n return await this.getBootstrapResource(uri);\n }\n\n // Handle rules\n if (parsedUri === 'rules') {\n return await this.getRulesResource(uri);\n }\n\n // Handle team info\n if (parsedUri === 'team') {\n return await this.getTeamResource(uri);\n }\n\n // Handle memory\n if (parsedUri === 'memory') {\n return await this.getMemoryResource(uri);\n }\n\n // Handle global memory\n if (parsedUri === 'memory/global') {\n return await this.getGlobalMemoryResource(uri);\n }\n\n // Handle scan reports\n if (parsedUri.startsWith('reports/')) {\n return await this.getScanReportResource(uri, parsedUri);\n }\n\n throw new Error(`Unknown resource: ${uri}`);\n }\n\n /**\n * Get UI App resources for MCP Apps\n */\n private getUIAppResources(): Resource[] {\n return Object.entries(UI_APPS).map(([id, app]) => ({\n uri: `ui://trie/${id}`,\n name: app.name,\n description: app.description,\n mimeType: 'text/html;profile=mcp-app',\n }));\n }\n\n /**\n * Read UI App resource content (bundled HTML)\n */\n private async getUIAppResource(uri: string, appId: string): Promise<ResourceContent> {\n // Get the directory of this file to find the dist/ui folder\n const currentFile = fileURLToPath(import.meta.url);\n const distDir = dirname(dirname(currentFile)); // Go up from server/ to dist/\n const uiDir = join(distDir, 'ui');\n const htmlPath = join(uiDir, `${appId}.html`);\n\n try {\n if (!existsSync(htmlPath)) {\n // Return a fallback HTML if the bundled app doesn't exist yet\n return {\n contents: [{\n uri,\n mimeType: 'text/html;profile=mcp-app',\n text: this.getFallbackUIHtml(appId),\n }],\n };\n }\n\n const content = await readFile(htmlPath, 'utf-8');\n return {\n contents: [{\n uri,\n mimeType: 'text/html;profile=mcp-app',\n text: content,\n }],\n };\n } catch (error) {\n return {\n contents: [{\n uri,\n mimeType: 'text/html;profile=mcp-app',\n text: this.getFallbackUIHtml(appId),\n }],\n };\n }\n }\n\n /**\n * Generate fallback HTML for UI apps that haven't been built yet\n */\n private getFallbackUIHtml(appId: string): string {\n const app = UI_APPS[appId as UIAppId];\n const title = app?.name || 'Trie UI';\n const description = app?.description || 'Loading...';\n\n return `<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <title>${title} - Trie</title>\n <style>\n :root {\n --bg: #0d1117;\n --surface: #161b22;\n --border: #30363d;\n --text: #e6edf3;\n --text-muted: #8b949e;\n --primary: #58a6ff;\n }\n * { box-sizing: border-box; margin: 0; padding: 0; }\n body {\n font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;\n background: var(--bg);\n color: var(--text);\n display: flex;\n align-items: center;\n justify-content: center;\n min-height: 100vh;\n padding: 24px;\n }\n .container {\n text-align: center;\n max-width: 400px;\n }\n h1 {\n font-size: 24px;\n margin-bottom: 8px;\n }\n p {\n color: var(--text-muted);\n margin-bottom: 24px;\n }\n .status {\n display: inline-flex;\n align-items: center;\n gap: 8px;\n padding: 8px 16px;\n background: var(--surface);\n border: 1px solid var(--border);\n border-radius: 8px;\n color: var(--primary);\n }\n .spinner {\n width: 16px;\n height: 16px;\n border: 2px solid var(--border);\n border-top-color: var(--primary);\n border-radius: 50%;\n animation: spin 0.8s linear infinite;\n }\n @keyframes spin { to { transform: rotate(360deg); } }\n </style>\n</head>\n<body>\n <div class=\"container\">\n <h1>${title}</h1>\n <p>${description}</p>\n <div class=\"status\">\n <div class=\"spinner\"></div>\n <span>Connecting to Trie...</span>\n </div>\n </div>\n <script type=\"module\">\n // MCP Apps SDK connection\n import { App } from \"@modelcontextprotocol/ext-apps\";\n \n const app = new App();\n await app.connect();\n \n app.ontoolresult = (result) => {\n document.querySelector('.status span').textContent = 'Connected! Waiting for data...';\n console.log('Received tool result:', result);\n };\n </script>\n</body>\n</html>`;\n }\n\n private async getContextResource(uri: string): Promise<ResourceContent> {\n const workDir = getWorkingDirectory(undefined, true);\n const state = await loadContextState();\n \n // Build executive summary first\n const summary: string[] = [\n '# Trie Context',\n '',\n '> Quick reference for AI assistants. Detailed sections below.',\n '',\n '## Quick Status',\n '',\n `| Metric | Value |`,\n `|--------|-------|`,\n `| Last Scan | ${state.lastScan ? new Date(state.lastScan.timestamp).toLocaleDateString() : 'Never'} |`,\n `| Critical Issues | ${state.lastScan?.issues.critical ?? 0} |`,\n `| Total Issues | ${state.lastScan?.issues.total ?? 0} |`,\n '',\n ];\n \n // Add top priorities (max 3)\n if (state.activePriorities.length > 0) {\n summary.push('## Top Priorities', '');\n state.activePriorities.slice(0, 3).forEach((p, i) => {\n summary.push(`${i + 1}. ${p}`);\n });\n summary.push('');\n }\n \n // Add recent issues from memory (max 3, one-liners)\n try {\n const recentIssues = await getRecentIssues({ workDir, limit: 3 });\n if (recentIssues.length > 0) {\n summary.push('## Recent Issues', '');\n recentIssues.forEach(i => {\n summary.push(`- [${i.severity.toUpperCase()}] ${i.issue.slice(0, 50)}... (\\`${i.file.split('/').pop()}\\`)`);\n });\n summary.push('');\n }\n } catch {\n // Memory not available\n }\n \n // Add cross-project patterns (max 2, one-liners)\n try {\n const patterns = await findCrossProjectPatterns(2);\n if (patterns.length > 0) {\n summary.push('## Watch For (seen in other projects)', '');\n patterns.slice(0, 2).forEach(p => {\n summary.push(`- ${p.pattern.slice(0, 40)}... (${p.occurrences}x across ${p.projects.length} projects)`);\n });\n summary.push('');\n }\n } catch {\n // Global memory not available\n }\n \n // Add coding rules summary (just headers)\n const rules = await loadRules(workDir);\n if (rules) {\n const ruleHeaders = rules.match(/^##?\\s+.+$/gm)?.slice(0, 5) || [];\n if (ruleHeaders.length > 0) {\n summary.push('## Coding Rules (see trie://rules for full)', '');\n ruleHeaders.forEach(h => summary.push(`- ${h.replace(/^#+\\s*/, '')}`));\n summary.push('');\n }\n }\n \n // Add available tools/capabilities\n summary.push('## Available Tools', '');\n summary.push('| Tool | Purpose |');\n summary.push('|------|---------|');\n summary.push('| `trie_scan` | Scan code with intelligent agent selection |');\n summary.push('| `trie_fix` | Generate fix recommendations |');\n summary.push('| `trie_memory` | Search issue history |');\n summary.push('| `trie_init` | Initialize bootstrap files |');\n summary.push('');\n \n // Add installed skills count\n try {\n const skills = await listInstalledSkills();\n if (skills.length > 0) {\n summary.push(`**Skills:** ${skills.length} installed (${skills.slice(0, 3).map(s => s.name).join(', ')}${skills.length > 3 ? '...' : ''})`);\n summary.push('');\n }\n } catch {\n // Skills not available\n }\n \n summary.push('---', '', '# Detailed Context', '');\n \n // Now add the full AGENTS.md\n const agentsMdPath = join(getTrieDirectory(workDir), 'AGENTS.md');\n try {\n if (existsSync(agentsMdPath)) {\n const agentsContent = await readFile(agentsMdPath, 'utf-8');\n summary.push(agentsContent);\n } else {\n const contextSummary = await getContextForAI();\n summary.push(contextSummary);\n }\n } catch {\n const contextSummary = await getContextForAI();\n summary.push(contextSummary);\n }\n \n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: summary.join('\\n'),\n }],\n };\n }\n\n private async getContextStateResource(uri: string): Promise<ResourceContent> {\n const state = await loadContextState();\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(state, null, 2),\n }],\n };\n }\n\n private async getProjectResource(uri: string): Promise<ResourceContent> {\n const workDir = getWorkingDirectory(undefined, true);\n \n if (!projectInfoExists(workDir)) {\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: `# Project Information Not Found\n\nNo \\`.trie/PROJECT.md\\` file exists in this project.\n\n## Create One\n\nUse the \\`trie_project\\` tool with action=\"init\" to create a PROJECT.md template:\n\n\\`\\`\\`\ntrie_project action=\"init\"\n\\`\\`\\`\n\nOr run from CLI:\n\\`\\`\\`\ntrie project init\n\\`\\`\\`\n\n## What is PROJECT.md?\n\nPROJECT.md is a user-defined file that stores important project context:\n- Project description and purpose\n- Technology stack\n- Architecture decisions\n- Coding conventions\n- Environment info\n- Team ownership\n- Compliance requirements\n- Special instructions for AI assistants\n\nThis information is automatically available to Claude Code, Cursor, and other AI tools.\n`,\n }],\n };\n }\n\n const content = await loadProjectInfo(workDir);\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: content || '',\n }],\n };\n }\n\n private async getBuiltInSkillsResource(uri: string): Promise<ResourceContent> {\n await this.skillRegistry.loadCustomSkills();\n const skills = this.skillRegistry.getSkillDescriptions();\n\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n totalSkills: skills.length,\n builtinCount: skills.filter(a => !a.isCustom).length,\n customCount: skills.filter(a => a.isCustom).length,\n skills: skills.map(a => ({\n name: a.name,\n description: a.description,\n type: a.isCustom ? 'custom' : 'builtin',\n })),\n }, null, 2),\n }],\n };\n }\n\n private async getCustomSkillResource(uri: string, parsedUri: string): Promise<ResourceContent> {\n const skillName = parsedUri.replace('skills/custom/', '');\n await this.skillRegistry.loadCustomSkills();\n const metadata = this.skillRegistry.getCustomSkillMetadata(skillName);\n\n if (!metadata) {\n throw new Error(`Custom skill not found: ${skillName}`);\n }\n\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(metadata, null, 2),\n }],\n };\n }\n\n private async getConfigResource(uri: string): Promise<ResourceContent> {\n const config = await loadConfig();\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(config, null, 2),\n }],\n };\n }\n\n private async getCacheStatsResource(uri: string): Promise<ResourceContent> {\n try {\n const cachePath = join(getTrieDirectory(getWorkingDirectory(undefined, true)), '.trie-cache.json');\n const cacheContent = await readFile(cachePath, 'utf-8');\n const cache = JSON.parse(cacheContent);\n\n const fileCount = Object.keys(cache.files || {}).length;\n const totalVulns = Object.values(cache.files || {}).reduce((acc: number, file: any) => {\n return acc + (file.vulnerabilities?.length || 0);\n }, 0);\n\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n version: cache.version,\n created: new Date(cache.created).toISOString(),\n lastUpdated: new Date(cache.lastUpdated).toISOString(),\n cachedFiles: fileCount,\n totalVulnerabilitiesFound: totalVulns,\n cacheAgeMinutes: Math.round((Date.now() - cache.lastUpdated) / 60000),\n }, null, 2),\n }],\n };\n } catch {\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n error: 'No cache found. Run a scan first to build the cache.',\n hint: 'Use trie_scan to scan your codebase',\n }, null, 2),\n }],\n };\n }\n }\n\n private async getSignaturesResource(uri: string): Promise<ResourceContent> {\n // Import dynamically to avoid circular deps\n const { getVulnerabilityStats } = await import('../trie/vulnerability-signatures.js');\n const { getVibeCodeStats } = await import('../trie/vibe-code-signatures.js');\n\n const vulnStats = getVulnerabilityStats();\n const vibeStats = getVibeCodeStats();\n\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n vulnerabilitySignatures: vulnStats,\n vibeCodeSignatures: vibeStats,\n totalSignatures: vulnStats.total + vibeStats.total,\n }, null, 2),\n }],\n };\n }\n\n private async getInstalledSkillsResource(uri: string): Promise<ResourceContent> {\n const skills = await listInstalledSkills();\n const state = await loadContextState();\n \n const skillsWithUsage = skills.map(skill => {\n const record = state.skills?.[skill.name];\n return {\n name: skill.name,\n description: skill.description,\n source: skill.installedFrom,\n installedAt: skill.installedAt,\n timesApplied: record?.timesApplied || 0,\n appliedBy: record?.appliedBy || [],\n lastApplied: record?.lastApplied,\n };\n });\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n totalSkills: skills.length,\n skills: skillsWithUsage,\n note: 'Skills are capabilities applied by agents, not autonomous agents themselves.',\n }, null, 2),\n }],\n };\n }\n\n private async getScanReportResource(uri: string, parsedUri: string): Promise<ResourceContent> {\n const fileName = parsedUri.replace('reports/', '');\n const reportPath = join(getWorkingDirectory(undefined, true), 'trie-reports', fileName);\n\n try {\n const content = await readFile(reportPath, 'utf-8');\n\n return {\n contents: [{\n uri,\n mimeType: fileName.endsWith('.json') ? 'application/json' : 'text/plain',\n text: content,\n }],\n };\n } catch {\n throw new Error(`Report not found: ${fileName}`);\n }\n }\n\n private async getBootstrapResource(uri: string): Promise<ResourceContent> {\n const workDir = getWorkingDirectory(undefined, true);\n const context = await loadBootstrapContext(workDir);\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n needsBootstrap: context.needsBootstrap,\n files: context.files.map(f => ({\n name: f.name,\n type: f.type,\n exists: f.exists,\n })),\n hasInjectedContent: !!context.injectedContent,\n }, null, 2),\n }],\n };\n }\n\n private async getRulesResource(uri: string): Promise<ResourceContent> {\n const rules = await loadRules();\n \n if (!rules) {\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: `# No Rules Defined\n\nNo \\`.trie/RULES.md\\` file exists in this project.\n\nUse \\`trie_init\\` to create one, or create it manually with your coding standards.\n`,\n }],\n };\n }\n\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: rules,\n }],\n };\n }\n\n private async getTeamResource(uri: string): Promise<ResourceContent> {\n const team = await loadTeamInfo();\n \n if (!team) {\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: `# No Team Info Defined\n\nNo \\`.trie/TEAM.md\\` file exists in this project.\n\nUse \\`trie_init\\` to create one, or create it manually with team ownership info.\n`,\n }],\n };\n }\n\n return {\n contents: [{\n uri,\n mimeType: 'text/markdown',\n text: team,\n }],\n };\n }\n\n private async getMemoryResource(uri: string): Promise<ResourceContent> {\n const workDir = getWorkingDirectory(undefined, true);\n const stats = await getMemoryStats(workDir);\n const recent = await getRecentIssues({ workDir, limit: 5 });\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n stats,\n recentIssues: recent.map(i => ({\n severity: i.severity,\n issue: i.issue.slice(0, 100),\n file: i.file,\n agent: i.agent,\n timestamp: i.timestamp,\n resolved: i.resolved,\n })),\n }, null, 2),\n }],\n };\n }\n\n private async getGlobalMemoryResource(uri: string): Promise<ResourceContent> {\n const stats = await getGlobalMemoryStats();\n const patterns = await findCrossProjectPatterns(2);\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n stats,\n topPatterns: patterns.slice(0, 10).map(p => ({\n pattern: p.pattern.slice(0, 80),\n severity: p.severity,\n agent: p.agent,\n occurrences: p.occurrences,\n projectCount: p.projects.length,\n hasFixApplied: !!p.fixApplied,\n })),\n }, null, 2),\n }],\n };\n }\n}","/**\n * Skills installer stub\n * Skills system has been replaced with decision ledger\n */\n\nexport interface Skill {\n name: string;\n category: string;\n description: string;\n path?: string;\n installedFrom?: string;\n installedAt?: string;\n timesApplied?: number;\n}\n\nexport interface InstallResult {\n success: boolean;\n name?: string;\n path?: string;\n error?: string;\n}\n\nexport interface CreateSkillResult {\n success: boolean;\n name?: string;\n writtenTo?: string[];\n error?: string;\n}\n\nexport async function listInstalledSkills(): Promise<Skill[]> {\n return [];\n}\n\nexport async function listGlobalSkills(): Promise<Skill[]> {\n return [];\n}\n\nexport async function installSkill(\n _repo: string, \n _skillName?: string\n): Promise<InstallResult> {\n return {\n success: false,\n error: 'Skills system has been replaced with the decision ledger'\n };\n}\n\nexport async function createSkillFromFile(\n _filePath: string\n): Promise<CreateSkillResult> {\n return {\n success: false,\n error: 'Skills system has been replaced with the decision ledger'\n };\n}\n\nexport async function removeGlobalSkill(_name: string): Promise<boolean> {\n return false;\n}\n","import { chromium, Browser, Page } from 'playwright';\nimport { createServer, Server } from 'net';\nimport { request } from 'http';\nimport { isInteractiveMode } from '../utils/progress.js';\n\n/**\n * Browser-based Visual QA Tool\n * \n * Launches a headless browser, captures screenshots at multiple viewports,\n * and returns them for Claude Vision to analyze.\n */\n\nexport interface VisualQAOptions {\n url?: string;\n port?: number;\n viewports?: ViewportConfig[];\n waitForSelector?: string;\n waitMs?: number;\n}\n\nexport interface ViewportConfig {\n name: string;\n width: number;\n height: number;\n}\n\nexport interface ScreenshotResult {\n viewport: string;\n width: number;\n height: number;\n base64: string;\n mimeType: 'image/png';\n}\n\nexport interface VisualQAResult {\n success: boolean;\n url: string;\n screenshots: ScreenshotResult[];\n error?: string;\n analysisPrompt: string;\n}\n\n// Default viewports for responsive testing\nconst DEFAULT_VIEWPORTS: ViewportConfig[] = [\n { name: 'mobile', width: 375, height: 812 }, // iPhone X\n { name: 'tablet', width: 768, height: 1024 }, // iPad\n { name: 'desktop', width: 1440, height: 900 }, // Standard desktop\n];\n\n/**\n * Find an open port on localhost by checking common dev server ports\n * Returns the first port that is both in use AND serving HTTP\n */\nasync function findOpenPort(): Promise<number | null> {\n const commonPorts = [3000, 3001, 5173, 5174, 4200, 8080, 8000, 8888, 5000, 4000];\n \n // Check ports in parallel for faster detection\n const portChecks = await Promise.all(\n commonPorts.map(async (port) => {\n const isOpen = await checkPort(port);\n return isOpen ? port : null;\n })\n );\n \n // Return the first port that's open and serving HTTP\n return portChecks.find(port => port !== null) || null;\n}\n\n/**\n * Check if a port has something listening on it AND is serving HTTP\n */\nasync function checkPort(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n // First check if port is in use\n const testServer: Server = createServer();\n let portInUse = false;\n \n testServer.once('error', (err: NodeJS.ErrnoException) => {\n if (err.code === 'EADDRINUSE') {\n portInUse = true;\n // Port is in use - now verify it's serving HTTP\n testHttpPort(port).then(resolve).catch(() => resolve(false));\n } else {\n resolve(false);\n }\n });\n \n testServer.once('listening', () => {\n // Port is free - nothing running\n testServer.close();\n resolve(false);\n });\n \n // Set timeout to prevent hanging\n setTimeout(() => {\n if (!portInUse) {\n testServer.close();\n resolve(false);\n }\n }, 1000);\n \n testServer.listen(port, '127.0.0.1');\n });\n}\n\n/**\n * Verify that a port is actually serving HTTP content\n */\nasync function testHttpPort(port: number): Promise<boolean> {\n return new Promise((resolve) => {\n const req = request({\n hostname: 'localhost',\n port: port,\n path: '/',\n method: 'GET',\n timeout: 2000,\n }, (res) => {\n // If we get any HTTP response (even 404), the server is running\n resolve(res.statusCode !== undefined);\n res.on('data', () => {}); // Consume response\n res.on('end', () => {});\n });\n\n req.on('error', () => {\n // Connection refused, timeout, or other error means no HTTP server\n resolve(false);\n });\n\n req.on('timeout', () => {\n req.destroy();\n resolve(false);\n });\n\n req.end();\n });\n}\n\n/**\n * Capture screenshots at multiple viewports\n */\nasync function captureScreenshots(\n url: string,\n viewports: ViewportConfig[],\n options: { waitForSelector?: string | undefined; waitMs?: number | undefined }\n): Promise<ScreenshotResult[]> {\n let browser: Browser | null = null;\n const screenshots: ScreenshotResult[] = [];\n\n try {\n // Launch browser\n browser = await chromium.launch({\n headless: true,\n });\n\n for (const viewport of viewports) {\n const page: Page = await browser.newPage({\n viewport: { width: viewport.width, height: viewport.height },\n });\n\n try {\n // Navigate to URL\n await page.goto(url, { \n waitUntil: 'networkidle',\n timeout: 30000 \n });\n\n // Wait for specific selector if provided\n if (options.waitForSelector) {\n await page.waitForSelector(options.waitForSelector, { timeout: 10000 });\n }\n\n // Additional wait if specified\n if (options.waitMs) {\n await page.waitForTimeout(options.waitMs);\n }\n\n // Capture full-page screenshot\n const screenshotBuffer = await page.screenshot({\n fullPage: true,\n type: 'png',\n });\n\n screenshots.push({\n viewport: viewport.name,\n width: viewport.width,\n height: viewport.height,\n base64: screenshotBuffer.toString('base64'),\n mimeType: 'image/png',\n });\n\n } finally {\n await page.close();\n }\n }\n\n } finally {\n if (browser) {\n await browser.close();\n }\n }\n\n return screenshots;\n}\n\n/**\n * Main Visual QA function - captures screenshots and prepares for Claude Vision\n */\nexport async function runVisualQA(options: VisualQAOptions = {}): Promise<VisualQAResult> {\n let url = options.url;\n \n // If no URL provided, try to find a running dev server\n if (!url) {\n if (options.port) {\n // User specified a port - verify it's serving HTTP\n const isServing = await testHttpPort(options.port);\n if (!isServing) {\n return {\n success: false,\n url: `http://localhost:${options.port}`,\n screenshots: [],\n error: `Port ${options.port} is not serving HTTP. Is your dev server running on this port?\\n\\nTry:\\n1. Verify your dev server is running: curl http://localhost:${options.port}\\n2. Check if the port is correct\\n3. Provide full URL: trie_visual_qa_browser url:\"http://localhost:${options.port}\"`,\n analysisPrompt: '',\n };\n }\n url = `http://localhost:${options.port}`;\n } else {\n // Auto-detect port\n if (!isInteractiveMode()) {\n console.error('Visual QA: Auto-detecting running dev server...');\n }\n const port = await findOpenPort();\n \n if (!port) {\n return {\n success: false,\n url: '',\n screenshots: [],\n error: 'No running dev server found on common ports (3000, 3001, 5173, 5174, 4200, 8080, 8000, 8888, 5000, 4000).\\n\\nPlease:\\n1. Start your dev server, OR\\n2. Provide a URL: trie_visual_qa_browser url:\"http://localhost:3000\", OR\\n3. Specify a port: trie_visual_qa_browser port:3000',\n analysisPrompt: '',\n };\n }\n \n url = `http://localhost:${port}`;\n if (!isInteractiveMode()) {\n console.error(` ✓ Found server on port ${port}`);\n }\n }\n }\n\n const viewports = options.viewports || DEFAULT_VIEWPORTS;\n\n try {\n if (!isInteractiveMode()) {\n console.error(`📸 Visual QA: Capturing screenshots from ${url}`);\n console.error(` Viewports: ${viewports.map(v => `${v.name} (${v.width}x${v.height})`).join(', ')}`);\n }\n\n const screenshots = await captureScreenshots(url, viewports, {\n waitForSelector: options.waitForSelector,\n waitMs: options.waitMs,\n });\n\n if (!isInteractiveMode()) {\n console.error(` ✓ Captured ${screenshots.length} screenshots`);\n }\n\n // Build analysis prompt for Claude Vision\n const analysisPrompt = buildAnalysisPrompt(url, screenshots);\n\n return {\n success: true,\n url,\n screenshots,\n analysisPrompt,\n };\n\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n \n // Check for common issues\n if (errorMessage.includes('net::ERR_CONNECTION_REFUSED') || errorMessage.includes('ECONNREFUSED')) {\n return {\n success: false,\n url,\n screenshots: [],\n error: `Cannot connect to ${url}. Is your dev server running?\\n\\nTry:\\n1. Start your dev server (e.g., npm start, npm run dev)\\n2. Specify the URL explicitly: trie_visual_qa_browser url:\"http://localhost:3000\"\\n3. Or specify the port: trie_visual_qa_browser port:3000`,\n analysisPrompt: '',\n };\n }\n \n if (errorMessage.includes('Executable doesn\\'t exist') || errorMessage.includes('BrowserType')) {\n return {\n success: false,\n url,\n screenshots: [],\n error: 'Playwright browsers not installed. Run: npx playwright install chromium',\n analysisPrompt: '',\n };\n }\n\n if (errorMessage.includes('timeout') || errorMessage.includes('Navigation timeout')) {\n return {\n success: false,\n url,\n screenshots: [],\n error: `Page load timeout for ${url}. The page may be taking too long to load or may have JavaScript errors.\\n\\nTry:\\n1. Check if the page loads in your browser\\n2. Increase wait time: trie_visual_qa_browser url:\"${url}\" waitMs:5000\\n3. Wait for specific element: trie_visual_qa_browser url:\"${url}\" waitForSelector:\".main-content\"`,\n analysisPrompt: '',\n };\n }\n\n return {\n success: false,\n url,\n screenshots: [],\n error: `Screenshot capture failed: ${errorMessage}\\n\\nTroubleshooting:\\n1. Verify ${url} is accessible in your browser\\n2. Check that your dev server is running\\n3. Try specifying the URL explicitly: trie_visual_qa_browser url:\"${url}\"`,\n analysisPrompt: '',\n };\n }\n}\n\n/**\n * Build the analysis prompt for Claude Vision\n */\nfunction buildAnalysisPrompt(url: string, screenshots: ScreenshotResult[]): string {\n const viewportList = screenshots.map(s => `- ${s.viewport}: ${s.width}x${s.height}`).join('\\n');\n \n return `## Visual QA Analysis\n\nI've captured screenshots of **${url}** at ${screenshots.length} viewports:\n\n${viewportList}\n\nPlease analyze these screenshots for:\n\n### Layout Issues\n- Overlapping elements or text\n- Content overflow or clipping\n- Broken layouts at specific breakpoints\n- Misaligned elements\n- Unexpected gaps or spacing\n\n### Responsive Design\n- Mobile navigation issues\n- Text too small to read on mobile\n- Touch targets too small (<44px)\n- Horizontal scrolling on mobile\n- Content not adapting to viewport\n\n### Visual Polish\n- Inconsistent spacing or alignment\n- Poor color contrast (text hard to read)\n- Broken images or missing assets\n- Loading states stuck/visible\n- Z-index issues (elements overlapping incorrectly)\n\n### Accessibility\n- Missing focus indicators\n- Color-only information\n- Text over images without sufficient contrast\n- Very small text (<12px)\n\n### General Quality\n- Does it look professional?\n- Is the hierarchy clear?\n- Are interactive elements obvious?\n- Any obvious bugs or glitches?\n\nFor each issue found:\n1. **Viewport**: Which viewport(s) affected\n2. **Location**: Where on the page\n3. **Issue**: What's wrong\n4. **Severity**: Critical/Serious/Moderate/Low\n5. **Fix**: How to resolve it\n\nIf the UI looks good, say so! Note what's working well.`;\n}\n\n/**\n * Format MCP response with images for Claude Vision\n */\nexport function formatMCPResponse(result: VisualQAResult): {\n content: Array<{ type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }>;\n} {\n if (!result.success) {\n return {\n content: [{\n type: 'text',\n text: `# Visual QA Failed\\n\\n${result.error}\\n\\n## Troubleshooting\\n\\n1. Make sure your dev server is running\\n2. Try: \\`trie_visual_qa url:\"http://localhost:3000\"\\`\\n3. If Playwright isn't installed: \\`npx playwright install chromium\\``,\n }],\n };\n }\n\n const content: Array<{ type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }> = [];\n\n // Add the analysis prompt first\n content.push({\n type: 'text',\n text: result.analysisPrompt,\n });\n\n // Add each screenshot as an image\n for (const screenshot of result.screenshots) {\n content.push({\n type: 'text',\n text: `\\n### ${screenshot.viewport} (${screenshot.width}x${screenshot.height})\\n`,\n });\n content.push({\n type: 'image',\n data: screenshot.base64,\n mimeType: screenshot.mimeType,\n });\n }\n\n return { content };\n}\n\n/**\n * MCP Tool Definition\n */\nexport const VISUAL_QA_TOOL_DEFINITION = {\n name: 'visual_qa_browser',\n description: 'Capture screenshots of your app at mobile/tablet/desktop viewports for visual QA analysis. Auto-detects running dev servers or specify a URL.',\n inputSchema: {\n type: 'object' as const,\n properties: {\n url: {\n type: 'string',\n description: 'URL to screenshot (e.g., http://localhost:3000). If not provided, auto-detects running dev server.',\n },\n port: {\n type: 'number',\n description: 'Specific port to check if no URL provided',\n },\n waitForSelector: {\n type: 'string',\n description: 'CSS selector to wait for before capturing (e.g., \".main-content\")',\n },\n waitMs: {\n type: 'number',\n description: 'Additional milliseconds to wait after page load',\n },\n },\n required: [],\n },\n};\n","import { getWorkingDirectory } from '../utils/workspace.js';\nimport { runVisualQA, formatMCPResponse } from '../tools/visual-qa-browser.js';\nimport { ToolRegistry } from './tool-registry.js';\nimport { ResourceManager } from './resource-manager.js';\n\nexport class RequestHandlers {\n constructor(\n private toolRegistry: ToolRegistry,\n private resourceManager: ResourceManager\n ) {}\n\n /**\n * Handle tool execution requests\n */\n async handleToolCall(name: string, args: any): Promise<any> {\n // Accept namespaced calls and normalize\n const normalizedName = this.normalizeName(name);\n\n // Auto-detect directory for Cursor/IDE tools when not explicitly provided\n if (args && !args.directory && !args.files) {\n const workingDir = getWorkingDirectory(undefined, true);\n if (workingDir !== process.cwd()) {\n args.directory = workingDir;\n }\n }\n\n try {\n switch (normalizedName) {\n case 'trie':\n return await this.handleTrieMenu(args);\n\n case 'scan':\n return await this.toolRegistry.getTool('scan').execute(args);\n\n case 'fix':\n return await this.toolRegistry.getTool('fix').execute(args);\n\n case 'explain':\n return await this.toolRegistry.getTool('explain').execute(args);\n\n case 'test':\n return await this.toolRegistry.getTool('test').execute(args);\n\n case 'register_agent':\n return await this.toolRegistry.getTool('register_agent').execute(args);\n\n case 'watch':\n return await this.toolRegistry.getTool('watch').execute(args);\n\n // Individual agent commands\n case 'security':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'security' });\n\n case 'legal':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'legal' });\n\n case 'accessibility':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'accessibility' });\n\n case 'design':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'design-engineer' });\n\n case 'architecture':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'software-architect' });\n\n case 'bugs':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'bug-finding' });\n\n case 'ux':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'user-testing' });\n\n case 'types':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'typecheck' });\n\n case 'devops':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'devops' });\n\n case 'clean':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'trie_clean' });\n\n case 'soc2':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'soc2' });\n\n // New agents\n case 'performance':\n case 'perf':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'performance' });\n\n case 'e2e':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'e2e' });\n\n case 'visual_qa':\n case 'visual':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'visual-qa' });\n\n case 'visual_qa_browser': {\n try {\n const result = await runVisualQA(args as { url?: string; port?: number; waitForSelector?: string; waitMs?: number });\n return formatMCPResponse(result);\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return {\n content: [{\n type: 'text',\n text: `# Visual QA Error\\n\\nFailed to capture screenshots: ${errorMessage}\\n\\n## Troubleshooting\\n\\n1. **Check if your dev server is running:**\\n - Try accessing the URL in your browser\\n - Common ports: 3000, 5173, 8080\\n\\n2. **Specify the URL explicitly:**\\n \\`\\`\\`\\ntrie_visual_qa_browser url:\"http://localhost:3000\"\\n\\`\\`\\`\\n\\n3. **Specify a port:**\\n \\`\\`\\`\\ntrie_visual_qa_browser port:3000\\n\\`\\`\\`\\n\\n4. **Install Playwright browsers (if needed):**\\n \\`\\`\\`\\nnpx playwright install chromium\\n\\`\\`\\`\\n\\n5. **Check for JavaScript errors:**\\n - Open browser dev tools\\n - Look for console errors\\n - The page may be failing to load`,\n }],\n };\n }\n }\n\n case 'data_flow':\n case 'dataflow':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'data-flow' });\n\n // Special agents\n case 'agent_smith':\n case 'agentsmith':\n case 'smith':\n // Handle special Agent Smith commands (clear_memory, show_stats)\n if (args?.clear_memory || args?.show_stats) {\n return await this.handleAgentSmith(args);\n }\n // Normal scan - delegate to agent tool\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'agent-smith' });\n\n case 'super_reviewer':\n case 'superreviewer':\n case 'reviewer':\n return await this.toolRegistry.getTool('agent').execute({ ...args, agent: 'super-reviewer' });\n\n // Custom skill tools (with backward-compatible agent aliases)\n case 'create_skill':\n case 'create_agent':\n return await this.toolRegistry.getTool('create_skill').execute(args);\n\n case 'save_skill':\n case 'save_agent':\n return await this.toolRegistry.getTool('save_skill').execute(args);\n\n case 'list_skills':\n case 'list_agents':\n return await this.toolRegistry.getTool('list_skills').execute(args);\n\n case 'pr_review':\n return await this.toolRegistry.getTool('pr_review').execute(args);\n\n case 'project':\n case 'project_info':\n return await this.toolRegistry.getTool('project').execute(args);\n\n case 'init':\n return await this.toolRegistry.getTool('init').execute(args);\n\n case 'memory':\n return await this.toolRegistry.getTool('memory').execute(args);\n\n case 'check':\n return await this.toolRegistry.getTool('check').execute(args);\n\n case 'tell':\n return await this.toolRegistry.getTool('tell').execute(args);\n\n case 'feedback':\n case 'ok':\n case 'bad':\n return await this.toolRegistry.getTool('feedback').execute(args);\n\n case 'reconcile':\n return await this.toolRegistry.getTool('reconcile').execute(args);\n\n case 'context':\n return await this.toolRegistry.getTool('context').execute(args);\n\n case 'checkpoint':\n case 'cp':\n case 'save':\n return await this.toolRegistry.getTool('checkpoint').execute(args);\n\n case 'cloud_fix':\n return await this.toolRegistry.getTool('cloud_fix').execute(args);\n\n case 'linear_sync':\n return await this.toolRegistry.getTool('linear_sync').execute(args);\n\n case 'github_sync':\n return await this.toolRegistry.getTool('github_sync').execute(args);\n\n case 'github_branches':\n return await this.toolRegistry.getTool('github_branches').execute(args);\n\n case 'pipeline':\n return await this.toolRegistry.getTool('pipeline').execute(args);\n\n case 'index':\n return await this.toolRegistry.getTool('index').execute(args);\n\n default: {\n // Fallback: try tool by normalized name (handles trie_index, trie_github_branches, etc.)\n const tool = this.toolRegistry.getTool(normalizedName);\n if (tool) {\n return await tool.execute(args);\n }\n throw new Error(`Unknown tool: ${name}`);\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 * 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 // Strip trailing \"(MCP)\" or \"(action: ...)\" that some clients append\n const stripNamespace = (n: string): string => {\n const trimmed = n.trim().replace(/\\s*\\([^)]*\\)\\s*$/, '').trim();\n const withoutSlash = trimmed.startsWith('/') ? trimmed.slice(1) : trimmed;\n const parts = withoutSlash.split(':');\n const base = (parts[0] || withoutSlash).trim();\n const slashParts = base.split('/');\n return (slashParts[slashParts.length - 1] || base).trim();\n };\n\n const rawName = stripNamespace(name);\n return rawName.startsWith('trie_') ? rawName.slice('trie_'.length) : rawName;\n }\n\n private async handleTrieMenu(args?: any) {\n const actionInput = typeof args?.action === 'string' ? args.action : null;\n if (actionInput) {\n const normalizedAction = this.normalizeName(actionInput);\n // Avoid recursion loop\n if (normalizedAction === 'trie') {\n return {\n content: [{\n type: 'text',\n text: 'Use `trie` without action for the menu, or provide a concrete action like \"scan\" or \"security\".'\n }]\n };\n }\n\n // Delegate to the same dispatcher to keep alias handling consistent\n return await this.handleToolCall(normalizedAction, { ...args });\n }\n\n return {\n content: [{\n type: 'text',\n text: [\n '## Trie Quick Actions',\n '',\n '**Most common:**',\n '- `trie` (no args) — show this menu',\n '- `trie` with `{ action: \"scan\", files?: [], directory?: \"\" }` — auto triage & scan',\n '- `trie` with `{ action: \"security\", files?: [] }` — single-skill run (any skill name works)',\n '- `trie` with `{ action: \"agent_smith\" }` — aggressive AI-pattern hunter',\n '',\n '**Other actions:**',\n '- `action: \"pr_review\"` — interactive PR review',\n '- `action: \"fix\"` — high-confidence fixes',\n '- `action: \"watch\"` — start/stop/status autonomous watch',\n '- `action: \"test\"` — generate/coverage/suggest/run tests (requires `files` + `action`)',\n '- `action: \"explain\"` — explain code/issues/risks',\n '- `action: \"list_skills\"` — list all skills (external + custom)',\n '- `action: \"visual_qa_browser\"` — screenshots for visual QA',\n '',\n '**Built-in skills:**',\n '`security`, `legal`, `accessibility`, `design`, `architecture`, `bugs`, `ux`, `types`, `devops`, `clean`, `soc2`, `performance`, `e2e`, `visual_qa`, `data_flow`',\n '',\n '**Special skills:**',\n '`agent_smith` — 35 vibe code hunters with cross-file detection',\n '`super_reviewer` — Interactive PR review with cross-examination',\n '',\n 'All commands accept `trie_` prefix (e.g., `trie_scan`, `trie_security`). Short names still work for compatibility.',\n ].join('\\n')\n }]\n };\n }\n\n private async handleAgentSmith(_smithArgs: any) {\n // Agent Smith has been removed - the decision ledger now handles pattern detection\n return {\n content: [{\n type: 'text',\n text: [\n '🤖 Agent Smith functionality has been integrated into the decision ledger.',\n '',\n 'The autonomous agent now:',\n '- Extracts patterns automatically via `trie watch`',\n '- Builds decision ledger from every change',\n '- Predicts problems via `trie gotcha`',\n '',\n 'Start the agent: `trie_watch start`',\n 'Query the ledger: `trie_gotcha`'\n ].join('\\n')\n }]\n };\n }\n}","#!/usr/bin/env node\n\nimport { startServer } from './server/mcp-server.js';\n\n// Start the MCP server\nstartServer().catch((error) => {\n console.error('Fatal error:', error);\n process.exit(1);\n});"],"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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AAA;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;;;AuBrIA,YAAY,EAAE,MAAM,CAAC,UAAU;AAC7B,UAAQ,MAAM,gBAAgB,KAAK;AACnC,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["Server","getRecentIssues","readFile","existsSync","path","shortPath","padEnd","getRecentIssues","path","existsSync","readFile","readFile","existsSync","extname","relative","resolve","isAbsolute","join","isAbsolute","resolve","existsSync","readFile","relative","extname","join","existsSync","readFile","join","extname","basename","existsSync","extname","join","basename","readFile","now","getOutputManager","ContextGraph","LinearIngester","GitHubIngester","readFile","existsSync","join","basename","resolve","isAbsolute","isAbsolute","resolve","existsSync","basename","path","join","readFile","result","patterns","lines","stats","readFile","existsSync","join","dirname","join","dirname","existsSync","readFile","resolve","Server","request"]}