@triedotdev/mcp 1.0.1 โ†’ 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -3873,10 +3873,8 @@ async function main() {
3873
3873
  await server.connect(transport);
3874
3874
  console.error("Trie Agent MCP Server running...");
3875
3875
  }
3876
- if (import.meta.url === `file://${process.argv[1]}`) {
3877
- main().catch((error) => {
3878
- console.error("Fatal error:", error);
3879
- process.exit(1);
3880
- });
3881
- }
3876
+ main().catch((error) => {
3877
+ console.error("Fatal error:", error);
3878
+ process.exit(1);
3879
+ });
3882
3880
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/tools/explain.ts","../src/tools/test.ts","../src/tools/register-agent.ts","../src/tools/watch.ts","../src/tools/agent.ts","../src/ai/engine.ts","../src/knowledge/index.ts","../src/tools/create-agent.ts","../src/utils/ai-tool-detector.ts","../src/config/loader.ts","../src/config/defaults.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { 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 { readdir, readFile } from 'fs/promises';\nimport { join } from 'path';\n\nimport { TrieScanTool } from './tools/scan.js';\nimport { TrieFixTool } from './tools/fix.js';\nimport { TrieExplainTool } from './tools/explain.js';\nimport { TrieTestTool } from './tools/test.js';\nimport { TrieRegisterAgentTool } from './tools/register-agent.js';\nimport { TrieWatchTool } from './tools/watch.js';\nimport { TrieAgentTool } from './tools/agent.js';\nimport { TrieCreateAgentTool, TrieSaveAgentTool, TrieListAgentsTool } from './tools/create-agent.js';\nimport { detectAITool } from './utils/ai-tool-detector.js';\nimport { loadConfig } from './config/loader.js';\nimport { AgentRegistry } from './agents/registry.js';\n\nconst server = new Server(\n {\n name: 'trie',\n version: '1.0.0',\n description: 'Intelligent Agent Orchestration for AI Coding Tools',\n },\n {\n capabilities: {\n tools: {},\n resources: {},\n },\n }\n);\n\n// Initialize tools\nconst scanTool = new TrieScanTool();\nconst fixTool = new TrieFixTool();\nconst explainTool = new TrieExplainTool();\nconst testTool = new TrieTestTool();\nconst registerAgentTool = new TrieRegisterAgentTool();\nconst watchTool = new TrieWatchTool();\nconst agentTool = new TrieAgentTool();\nconst createAgentTool = new TrieCreateAgentTool();\nconst saveAgentTool = new TrieSaveAgentTool();\nconst listAgentsTool = new TrieListAgentsTool();\n\n// Tool definitions\nconst tools = [\n {\n name: 'scan',\n description: 'Scan code with intelligent agent selection. Scans entire codebase if no files specified.',\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 }\n } as const,\n },\n {\n name: 'trie',\n description: 'Quick menu of available Trie commands and aliases.',\n inputSchema: {\n type: 'object',\n properties: {}\n } as const,\n },\n // Alias so users can call `trie_scan` directly (no server prefix needed)\n {\n name: 'trie_scan',\n description: 'Alias for scan (same behavior as 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 }\n } as const,\n },\n {\n name: 'fix',\n description: 'Apply high-confidence fixes to code',\n inputSchema: {\n type: 'object',\n properties: {\n issueIds: {\n type: 'array',\n items: { type: 'string' },\n description: 'Specific issues to fix (empty = all high-confidence)'\n },\n autoApprove: {\n type: 'boolean',\n description: 'Skip human review for high-confidence fixes'\n }\n }\n } as const,\n },\n {\n name: 'explain',\n description: 'Explain code, issues, or changes in plain language',\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: 'test',\n description: 'Generate tests or check test coverage',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['generate', 'coverage', 'run']\n },\n files: {\n type: 'array',\n items: { type: 'string' }\n }\n },\n required: ['action', 'files']\n } as const,\n },\n {\n name: 'register_agent',\n description: 'Register a custom agent for your project',\n inputSchema: {\n type: 'object',\n properties: {\n name: { type: 'string' },\n path: {\n type: 'string',\n description: 'Path to agent implementation'\n },\n activationRules: {\n type: 'object',\n description: 'When to activate this agent'\n }\n },\n required: ['name', 'path']\n } as const,\n },\n {\n name: 'watch',\n description: 'Autonomous mode: watch for file changes and scan/fix automatically. Use yolo:true for auto-fix!',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['start', 'stop', 'status', 'issues', 'yolo'],\n description: 'start = begin watching, stop = end, status = check, issues = list, yolo = toggle auto-fix'\n },\n directory: {\n type: 'string',\n description: 'Directory to watch (defaults to current working directory)'\n },\n yolo: {\n type: 'boolean',\n description: '๐Ÿ”ฅ YOLO MODE: Auto-fix issues as they occur! (default: false)'\n },\n debounceMs: {\n type: 'number',\n description: 'Milliseconds to wait after file change before scanning (default: 1000)'\n }\n },\n required: ['action']\n } as const,\n },\n // Individual agent commands\n {\n name: 'security',\n description: 'Run security agent: detect vulnerabilities, injection risks, auth issues, hardcoded secrets',\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan (or scans codebase)' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n },\n {\n name: 'privacy',\n description: 'Run privacy agent: PII handling, GDPR/HIPAA compliance, data encryption',\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n },\n {\n name: 'legal',\n description: 'Run legal agent: GDPR, CCPA, consent patterns, data retention compliance',\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n },\n {\n name: 'accessibility',\n description: 'Run accessibility agent: WCAG 2.1 compliance, keyboard nav, screen readers, color contrast',\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n },\n {\n name: 'architecture',\n description: 'Run architecture agent: code organization, SOLID principles, N+1 queries, scalability',\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n },\n {\n name: 'bugs',\n description: 'Run bug-finding agent: null safety, edge cases, common bugs, async issues',\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n },\n {\n name: 'ux',\n description: 'Run UX testing agent: simulate happy path, security tester, confused user, impatient user',\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n },\n {\n name: 'types',\n description: 'Run type safety agent: type errors, missing annotations, null checks',\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n },\n {\n name: 'devops',\n description: 'Run devops agent: config issues, logging, environment variables, deployment patterns',\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n },\n {\n name: 'clean',\n description: '๐Ÿงน Clean up AI-generated code: find common mistakes, bad patterns, and quick fixes',\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n },\n // Custom agent creation tools (two-step process - no API key needed!)\n {\n name: 'create_agent',\n description: '๐Ÿ“š Step 1: Parse a document to create a custom agent. Supports file path OR drag-and-drop content. Returns extraction prompt for Claude to process.',\n inputSchema: {\n type: 'object',\n properties: {\n filePath: {\n type: 'string',\n description: 'Path to the document file (PDF, TXT, MD, or RTF)'\n },\n documentContent: {\n type: 'string',\n description: 'Raw document text (for drag-and-drop or pasted content). Use this OR filePath.'\n },\n agentName: {\n type: 'string',\n description: 'Name for the new agent (e.g., \"react-fundamentals\", \"gdpr-compliance\")'\n },\n displayName: {\n type: 'string',\n description: 'Optional display name (e.g., \"React Fundamentals Expert\")'\n },\n description: {\n type: 'string',\n description: 'Optional description of what the agent does'\n },\n category: {\n type: 'string',\n description: 'Optional category (e.g., \"react\", \"security\", \"compliance\", \"architecture\")'\n }\n },\n required: ['agentName']\n } as const,\n },\n {\n name: 'save_agent',\n description: '๐Ÿ“ฆ Step 2: Save the agent config after Claude extracts knowledge from the document. Pass the JSON output from trie_create_agent.',\n inputSchema: {\n type: 'object',\n properties: {\n agentConfig: {\n type: 'object',\n description: 'Agent configuration (name, displayName, description, category)',\n properties: {\n name: { type: 'string' },\n displayName: { type: 'string' },\n description: { type: 'string' },\n version: { type: 'string' },\n category: { type: 'string' }\n },\n required: ['name', 'category']\n },\n knowledge: {\n type: 'object',\n description: 'Extracted knowledge (domain, summary, coreConcepts, bestPractices, antiPatterns, glossary)'\n },\n detectionRules: {\n type: 'array',\n description: 'Array of detection rules with patterns and fixes'\n },\n prompts: {\n type: 'object',\n description: 'Agent prompts (systemPrompt, analysisPrompt, fixPrompt)',\n properties: {\n systemPrompt: { type: 'string' },\n analysisPrompt: { type: 'string' },\n fixPrompt: { type: 'string' }\n },\n required: ['systemPrompt', 'analysisPrompt', 'fixPrompt']\n },\n sourceFile: {\n type: 'string',\n description: 'Original source file path (optional)'\n }\n },\n required: ['agentConfig', 'knowledge', 'detectionRules', 'prompts']\n } as const,\n },\n {\n name: 'list_agents',\n description: '๐Ÿ“‹ List all registered agents including custom agents created from documents',\n inputSchema: {\n type: 'object',\n properties: {\n includeBuiltin: {\n type: 'boolean',\n description: 'Include built-in agents in the list (default: true)'\n }\n }\n } as const,\n }\n];\n\n// List tools handler\nserver.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools\n };\n});\n\n// Call tool handler\nserver.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n\n // Accept namespaced calls like \"scan:user-trie-agent\" or \"user-trie-agent/scan\"\n // and our aliases like \"trie_scan\" without forcing the server name.\n const stripNamespace = (n: string): string => {\n const parts = n.split(':');\n const base = parts[0] || n;\n const slashParts = base.split('/');\n return slashParts[slashParts.length - 1] || base;\n };\n\n const rawName = stripNamespace(name);\n const normalizedName = rawName.startsWith('trie_') ? rawName.slice('trie_'.length) : rawName;\n\n try {\n switch (normalizedName) {\n case 'trie':\n return {\n content: [\n {\n type: 'text',\n text: [\n '## Trie Menu',\n '',\n '- `trie_scan` or `scan`: Full intelligent scan (auto triage agents)',\n '- `fix`: Apply high-confidence fixes',\n '- `explain`: Explain code/issues/risks',\n '- `watch`: Watch mode (scan on change)',\n '- `security`, `privacy`, `legal`, `bugs`, `types`, `devops`, `architecture`, `ux`, `clean`: Run a specific agent',\n '- `test`: Generate/check tests',\n '- `register_agent`, `create_agent`, `save_agent`, `list_agents`: Custom agent lifecycle',\n '',\n 'You can call these without any namespace; `trie_` aliases also work.',\n ].join('\\n')\n }\n ]\n };\n case 'scan':\n return await scanTool.execute(args);\n case 'fix':\n return await fixTool.execute(args);\n case 'explain':\n return await explainTool.execute(args);\n case 'test':\n return await testTool.execute(args);\n case 'register_agent':\n return await registerAgentTool.execute(args);\n case 'watch':\n return await watchTool.execute(args);\n // Individual agent commands\n case 'security':\n return await agentTool.execute({ ...args, agent: 'security' });\n case 'privacy':\n return await agentTool.execute({ ...args, agent: 'privacy' });\n case 'legal':\n return await agentTool.execute({ ...args, agent: 'legal' });\n case 'accessibility':\n return await agentTool.execute({ ...args, agent: 'design-engineer' });\n case 'architecture':\n return await agentTool.execute({ ...args, agent: 'software-architect' });\n case 'bugs':\n return await agentTool.execute({ ...args, agent: 'bug-finding' });\n case 'ux':\n return await agentTool.execute({ ...args, agent: 'user-testing' });\n case 'types':\n return await agentTool.execute({ ...args, agent: 'typecheck' });\n case 'devops':\n return await agentTool.execute({ ...args, agent: 'devops' });\n case 'clean':\n return await agentTool.execute({ ...args, agent: 'trie_clean' });\n // Custom agent creation tools (two-step process)\n case 'create_agent':\n return await createAgentTool.execute(args as any);\n case 'save_agent':\n return await saveAgentTool.execute(args as any);\n case 'list_agents':\n return await listAgentsTool.execute(args as any);\n default:\n throw new Error(`Unknown tool: ${name}`);\n }\n } catch (error) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: ${error instanceof Error ? error.message : String(error)}`\n }\n ]\n };\n }\n});\n\n// Initialize agent registry for resources\nconst agentRegistry = new AgentRegistry();\n\n// Resource definitions\ninterface Resource {\n uri: string;\n name: string;\n description?: string;\n mimeType?: string;\n}\n\n// Helper to get dynamic resources\nasync function getAvailableResources(): Promise<Resource[]> {\n const resources: Resource[] = [];\n\n // Static resources\n resources.push({\n uri: 'trie://agents',\n name: 'Available Agents',\n description: 'List of all available Trie agents (built-in and custom)',\n mimeType: 'application/json',\n });\n\n resources.push({\n uri: 'trie://config',\n name: 'Trie Configuration',\n description: 'Current Trie configuration settings',\n mimeType: 'application/json',\n });\n\n resources.push({\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 resources.push({\n uri: 'trie://signatures',\n name: 'Vulnerability Signatures',\n description: 'Summary of loaded vulnerability detection signatures',\n mimeType: 'application/json',\n });\n\n // Dynamic resources: scan reports\n try {\n const reportsDir = join(process.cwd(), 'trie-reports');\n const files = await readdir(reportsDir);\n const reportFiles = files.filter(f => f.endsWith('.txt') || f.endsWith('.json'));\n \n for (const file of reportFiles.slice(0, 10)) { // Limit to 10 most recent\n resources.push({\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 }\n } catch {\n // No reports directory yet\n }\n\n // Dynamic resources: custom agents\n try {\n await agentRegistry.loadCustomAgents();\n const customAgents = agentRegistry.getCustomAgents();\n \n for (const agent of customAgents) {\n resources.push({\n uri: `trie://agents/custom/${agent.name}`,\n name: `Custom Agent: ${agent.name}`,\n description: agent.description,\n mimeType: 'application/json',\n });\n }\n } catch {\n // No custom agents\n }\n\n return resources;\n}\n\n// Helper to read resource content\nasync function readResourceContent(uri: string): Promise<{ contents: Array<{ uri: string; mimeType?: string; text: string }> }> {\n const parsedUri = uri.replace('trie://', '');\n\n // Handle agents list\n if (parsedUri === 'agents') {\n await agentRegistry.loadCustomAgents();\n const agents = agentRegistry.getAgentDescriptions();\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n totalAgents: agents.length,\n builtinCount: agents.filter(a => !a.isCustom).length,\n customCount: agents.filter(a => a.isCustom).length,\n agents: agents.map(a => ({\n name: a.name,\n description: a.description,\n type: a.isCustom ? 'custom' : 'builtin',\n })),\n }, null, 2),\n }],\n };\n }\n\n // Handle specific custom agent\n if (parsedUri.startsWith('agents/custom/')) {\n const agentName = parsedUri.replace('agents/custom/', '');\n await agentRegistry.loadCustomAgents();\n const metadata = agentRegistry.getCustomAgentMetadata(agentName);\n \n if (!metadata) {\n throw new Error(`Custom agent not found: ${agentName}`);\n }\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(metadata, null, 2),\n }],\n };\n }\n\n // Handle configuration\n if (parsedUri === 'config') {\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 // Handle cache stats\n if (parsedUri === 'cache/stats') {\n try {\n const cachePath = join(process.cwd(), '.trie', '.trie-cache.json');\n const cacheContent = await readFile(cachePath, 'utf-8');\n const cache = JSON.parse(cacheContent);\n \n // Calculate stats without loading full cache\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 // Handle vulnerability signatures summary\n if (parsedUri === 'signatures') {\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 // Handle scan reports\n if (parsedUri.startsWith('reports/')) {\n const fileName = parsedUri.replace('reports/', '');\n const reportPath = join(process.cwd(), '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 throw new Error(`Unknown resource: ${uri}`);\n}\n\n// List resources handler\nserver.setRequestHandler(ListResourcesRequestSchema, async () => {\n const resources = await getAvailableResources();\n return { resources };\n});\n\n// Read resource handler\nserver.setRequestHandler(ReadResourceRequestSchema, async (request) => {\n const { uri } = request.params;\n return await readResourceContent(uri);\n});\n\n// Initialize and start server\nasync function main() {\n // Detect the AI tool environment\n const aiTool = detectAITool();\n console.error(`Detected AI Tool: ${aiTool.name}`);\n\n // Load configuration\n const config = await loadConfig();\n console.error(`Loaded config for ${config.agents.builtin ? Object.keys(config.agents.builtin).length : 0} built-in agents`);\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n console.error('Trie Agent MCP Server running...');\n}\n\nif (import.meta.url === `file://${process.argv[1]}`) {\n main().catch((error) => {\n console.error('Fatal error:', error);\n process.exit(1);\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';\n\n/**\n * Explain Tool - AI-powered code explanation\n * \n * This tool provides deep explanations of:\n * - Code: What does this code do?\n * - Issues: Why is this a problem?\n * - Changes: What's the impact of these changes?\n * - Risk: What could go wrong?\n */\n\nexport class TrieExplainTool {\n async execute(args: any) {\n const { type, target, context, depth = 'standard' } = args || {};\n\n if (!type || !target) {\n return {\n content: [{\n type: 'text',\n text: this.getHelpText()\n }]\n };\n }\n\n switch (type) {\n case 'code':\n return this.explainCode(target, context, depth);\n case 'issue':\n return this.explainIssue(target, context);\n case 'change':\n return this.explainChange(target, context);\n case 'risk':\n return this.explainRisk(target, context);\n default:\n return {\n content: [{\n type: 'text',\n text: `Unknown explanation type: ${type}`\n }]\n };\n }\n }\n\n private async explainCode(target: string, context?: string, _depth?: string) {\n // Target can be a file path or inline code\n let code: string;\n let filePath: string;\n let language: string;\n\n // Check if target is a file path\n const resolvedPath = isAbsolute(target) ? target : resolve(process.cwd(), target);\n \n if (existsSync(resolvedPath)) {\n code = await readFile(resolvedPath, 'utf-8');\n filePath = relative(process.cwd(), resolvedPath);\n language = this.detectLanguage(resolvedPath);\n } else {\n // Treat as inline code\n code = target;\n filePath = 'inline';\n language = this.guessLanguage(code);\n }\n\n // For deep mode, analyze imports and dependencies\n const imports = this.extractImports(code, language);\n const exports = this.extractExports(code);\n const functions = this.extractFunctions(code, language);\n\n const prompt = getPrompt('explain', 'code', {\n code,\n language,\n filePath,\n });\n\n const systemPrompt = getSystemPrompt('explain');\n\n let output = `\\n${'โ”'.repeat(60)}\\n`;\n output += `๐Ÿ“– CODE EXPLANATION\\n`;\n output += `${'โ”'.repeat(60)}\\n\\n`;\n\n output += `## ๐Ÿ“‚ Source\\n\\n`;\n output += `- **File:** \\`${filePath}\\`\\n`;\n output += `- **Language:** ${language}\\n`;\n output += `- **Lines:** ${code.split('\\n').length}\\n\\n`;\n\n // Quick structural analysis\n output += `## ๐Ÿ” Structure Analysis\\n\\n`;\n \n if (imports.length > 0) {\n output += `**Imports (${imports.length}):**\\n`;\n for (const imp of imports.slice(0, 10)) {\n output += `- ${imp}\\n`;\n }\n if (imports.length > 10) {\n output += `- *...and ${imports.length - 10} more*\\n`;\n }\n output += '\\n';\n }\n\n if (exports.length > 0) {\n output += `**Exports (${exports.length}):**\\n`;\n for (const exp of exports) {\n output += `- ${exp}\\n`;\n }\n output += '\\n';\n }\n\n if (functions.length > 0) {\n output += `**Functions/Methods (${functions.length}):**\\n`;\n for (const fn of functions.slice(0, 15)) {\n output += `- \\`${fn}\\`\\n`;\n }\n if (functions.length > 15) {\n output += `- *...and ${functions.length - 15} more*\\n`;\n }\n output += '\\n';\n }\n\n output += `${'โ”€'.repeat(60)}\\n`;\n output += `## ๐Ÿง  Deep Explanation Request\\n\\n`;\n output += `**Role:** ${systemPrompt.split('\\n')[0]}\\n\\n`;\n output += prompt;\n output += `\\n${'โ”€'.repeat(60)}\\n`;\n\n if (context) {\n output += `\\n**Additional Context:** ${context}\\n`;\n }\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async explainIssue(target: string, _context?: string) {\n // Parse issue details (format: \"description\" or \"file:line:description\")\n let file = '';\n let line = 0;\n let issue = target;\n let severity = 'unknown';\n\n // Try to parse structured format\n const match = target.match(/^(.+?):(\\d+):(.+)$/);\n if (match) {\n file = match[1]!;\n line = parseInt(match[2]!, 10);\n issue = match[3]!.trim();\n }\n\n // Detect severity from keywords\n if (/critical|injection|rce|xss/i.test(issue)) severity = 'critical';\n else if (/serious|auth|password|secret/i.test(issue)) severity = 'serious';\n else if (/moderate|warning/i.test(issue)) severity = 'moderate';\n else severity = 'low';\n\n let codeContext = '';\n if (file && existsSync(file)) {\n const content = await readFile(file, 'utf-8');\n const lines = content.split('\\n');\n const start = Math.max(0, line - 5);\n const end = Math.min(lines.length, line + 5);\n codeContext = lines.slice(start, end).map((l, i) => {\n const lineNum = start + i + 1;\n const marker = lineNum === line ? 'โ†’ ' : ' ';\n return `${marker}${lineNum.toString().padStart(4)} | ${l}`;\n }).join('\\n');\n }\n\n const prompt = getPrompt('explain', 'issue', {\n issue,\n severity,\n filePath: file || 'unknown',\n line: String(line || '?'),\n });\n\n let output = `\\n${'โ”'.repeat(60)}\\n`;\n output += `๐Ÿ” ISSUE EXPLANATION\\n`;\n output += `${'โ”'.repeat(60)}\\n\\n`;\n\n output += `## ๐Ÿ“ Issue Details\\n\\n`;\n output += `- **Issue:** ${issue}\\n`;\n output += `- **Severity:** ${this.getSeverityIcon(severity)} ${severity}\\n`;\n if (file) output += `- **File:** \\`${file}\\`\\n`;\n if (line) output += `- **Line:** ${line}\\n`;\n output += '\\n';\n\n if (codeContext) {\n output += `## ๐Ÿ“„ Code Context\\n\\n`;\n output += `\\`\\`\\`\\n${codeContext}\\n\\`\\`\\`\\n\\n`;\n }\n\n output += `${'โ”€'.repeat(60)}\\n`;\n output += `## ๐Ÿง  Explanation Request\\n\\n`;\n output += prompt;\n output += `\\n${'โ”€'.repeat(60)}\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async explainChange(target: string, context?: string) {\n // Target is a list of changed files or a git diff\n const files = target.split(',').map(f => f.trim());\n\n let output = `\\n${'โ”'.repeat(60)}\\n`;\n output += `๐Ÿ“ CHANGE ANALYSIS\\n`;\n output += `${'โ”'.repeat(60)}\\n\\n`;\n\n output += `## ๐Ÿ“‚ Changed Files\\n\\n`;\n for (const file of files) {\n output += `- \\`${file}\\`\\n`;\n }\n output += '\\n';\n\n output += `## ๐Ÿง  Analysis Request\\n\\n`;\n output += `Analyze these changes and explain:\\n\\n`;\n output += `1. **What changed** - Summary of modifications\\n`;\n output += `2. **Why it matters** - Impact on the system\\n`;\n output += `3. **Dependencies** - What else might be affected\\n`;\n output += `4. **Testing needed** - What to test after this change\\n`;\n output += `5. **Rollback plan** - How to undo if needed\\n\\n`;\n\n if (context) {\n output += `**Context:** ${context}\\n\\n`;\n }\n\n output += `Please review the changed files and provide this analysis.\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async explainRisk(target: string, context?: string) {\n // Target is a file or feature description\n const resolvedPath = isAbsolute(target) ? target : resolve(process.cwd(), target);\n \n let output = `\\n${'โ”'.repeat(60)}\\n`;\n output += `โš ๏ธ RISK ASSESSMENT\\n`;\n output += `${'โ”'.repeat(60)}\\n\\n`;\n\n if (existsSync(resolvedPath)) {\n const code = await readFile(resolvedPath, 'utf-8');\n const filePath = relative(process.cwd(), resolvedPath);\n \n // Quick risk indicators\n const riskIndicators = this.detectRiskIndicators(code);\n\n output += `## ๐Ÿ“‚ Target\\n\\n`;\n output += `- **File:** \\`${filePath}\\`\\n`;\n output += `- **Lines:** ${code.split('\\n').length}\\n\\n`;\n\n if (riskIndicators.length > 0) {\n output += `## ๐Ÿšจ Risk Indicators Found\\n\\n`;\n for (const indicator of riskIndicators) {\n output += `- ${indicator}\\n`;\n }\n output += '\\n';\n }\n\n const prompt = getPrompt('explain', 'risk', {\n files: filePath,\n summary: context || 'Code change',\n });\n\n output += `${'โ”€'.repeat(60)}\\n`;\n output += `## ๐Ÿง  Risk Analysis Request\\n\\n`;\n output += prompt;\n output += `\\n${'โ”€'.repeat(60)}\\n`;\n } else {\n // Treat as a feature/change description\n output += `## ๐Ÿ“‹ Feature/Change\\n\\n`;\n output += `${target}\\n\\n`;\n\n output += `## ๐Ÿง  Risk Analysis Request\\n\\n`;\n output += `Analyze the risks of this change:\\n\\n`;\n output += `1. **Technical risks** - What could break?\\n`;\n output += `2. **Security risks** - Any vulnerabilities introduced?\\n`;\n output += `3. **Performance risks** - Any slowdowns?\\n`;\n output += `4. **Data risks** - Any data integrity concerns?\\n`;\n output += `5. **User impact** - How might users be affected?\\n`;\n output += `6. **Mitigation** - How to reduce these risks?\\n`;\n }\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private detectRiskIndicators(code: string): string[] {\n const indicators: string[] = [];\n\n const checks = [\n { pattern: /delete|drop|truncate/i, message: 'โš ๏ธ Destructive operations detected' },\n { pattern: /password|secret|key|token/i, message: '๐Ÿ” Credential handling detected' },\n { pattern: /exec|eval|spawn/i, message: '๐Ÿ’‰ Code execution patterns detected' },\n { pattern: /SELECT.*FROM|INSERT|UPDATE|DELETE/i, message: '๐Ÿ—„๏ธ Direct database operations' },\n { pattern: /fetch|axios|request|http/i, message: '๐ŸŒ External API calls detected' },\n { pattern: /process\\.env/i, message: 'โš™๏ธ Environment variable usage' },\n { pattern: /fs\\.|writeFile|readFile/i, message: '๐Ÿ“ File system operations' },\n { pattern: /setTimeout|setInterval/i, message: 'โฐ Async timing operations' },\n { pattern: /try\\s*{/i, message: '๐Ÿ›ก๏ธ Error handling present' },\n { pattern: /catch\\s*\\(/i, message: '๐Ÿ›ก๏ธ Exception handling present' },\n ];\n\n for (const { pattern, message } of checks) {\n if (pattern.test(code)) {\n indicators.push(message);\n }\n }\n\n return indicators;\n }\n\n private extractImports(code: string, _language: string): string[] {\n const imports: string[] = [];\n const lines = code.split('\\n');\n\n for (const line of lines) {\n // ES6 imports\n const es6Match = line.match(/import\\s+(?:{[^}]+}|\\*\\s+as\\s+\\w+|\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/);\n if (es6Match) {\n imports.push(es6Match[1]!);\n continue;\n }\n\n // CommonJS require\n const cjsMatch = line.match(/require\\s*\\(['\"]([^'\"]+)['\"]\\)/);\n if (cjsMatch) {\n imports.push(cjsMatch[1]!);\n continue;\n }\n\n // Python imports\n const pyMatch = line.match(/^(?:from\\s+(\\S+)\\s+)?import\\s+(\\S+)/);\n if (pyMatch && _language === 'python') {\n imports.push(pyMatch[1] || pyMatch[2]!);\n }\n }\n\n return [...new Set(imports)];\n }\n\n private extractExports(code: string): string[] {\n const exports: string[] = [];\n const lines = code.split('\\n');\n\n for (const line of lines) {\n // ES6 exports\n const es6Match = line.match(/export\\s+(?:default\\s+)?(?:class|function|const|let|var|interface|type)\\s+(\\w+)/);\n if (es6Match) {\n exports.push(es6Match[1]!);\n }\n\n // Named exports\n const namedMatch = line.match(/export\\s*\\{([^}]+)\\}/);\n if (namedMatch) {\n const names = namedMatch[1]!.split(',').map(n => n.trim().split(/\\s+as\\s+/)[0]!.trim());\n exports.push(...names);\n }\n }\n\n return [...new Set(exports)];\n }\n\n private extractFunctions(code: string, _language: string): string[] {\n const functions: string[] = [];\n const lines = code.split('\\n');\n\n for (const line of lines) {\n // Function declarations\n const funcMatch = line.match(/(?:async\\s+)?function\\s+(\\w+)/);\n if (funcMatch) {\n functions.push(funcMatch[1]!);\n continue;\n }\n\n // Arrow functions assigned to const\n const arrowMatch = line.match(/(?:const|let|var)\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\(/);\n if (arrowMatch) {\n functions.push(arrowMatch[1]!);\n continue;\n }\n\n // Class methods\n const methodMatch = line.match(/^\\s+(?:async\\s+)?(\\w+)\\s*\\([^)]*\\)\\s*(?::\\s*\\w+)?\\s*\\{/);\n if (methodMatch && !['if', 'for', 'while', 'switch', 'catch'].includes(methodMatch[1]!)) {\n functions.push(methodMatch[1]!);\n }\n }\n\n return [...new Set(functions)];\n }\n\n private detectLanguage(filePath: string): string {\n const ext = extname(filePath).toLowerCase();\n const langMap: Record<string, string> = {\n '.ts': 'typescript', '.tsx': 'tsx', '.js': 'javascript', '.jsx': 'jsx',\n '.py': 'python', '.go': 'go', '.rs': 'rust', '.java': 'java',\n '.rb': 'ruby', '.php': 'php', '.vue': 'vue', '.svelte': 'svelte',\n };\n return langMap[ext] || 'plaintext';\n }\n\n private guessLanguage(code: string): string {\n if (/import.*from|export\\s+(default|const|function|class)/.test(code)) return 'typescript';\n if (/def\\s+\\w+.*:/.test(code)) return 'python';\n if (/func\\s+\\w+.*\\{/.test(code)) return 'go';\n if (/fn\\s+\\w+.*->/.test(code)) return 'rust';\n return 'javascript';\n }\n\n private getSeverityIcon(severity: string): string {\n const icons: Record<string, string> = {\n critical: '๐Ÿ”ด',\n serious: '๐ŸŸ ',\n moderate: '๐ŸŸก',\n low: '๐Ÿ”ต',\n unknown: 'โšช',\n };\n return icons[severity] || 'โšช';\n }\n\n private getHelpText(): string {\n return `\n${'โ”'.repeat(60)}\n๐Ÿ“– TRIE EXPLAIN - AI-POWERED CODE EXPLANATION\n${'โ”'.repeat(60)}\n\n## Usage\n\n### Explain code:\n\\`\\`\\`\ntrie_explain type:\"code\" target:\"src/app.ts\"\n\\`\\`\\`\n\n### Explain an issue:\n\\`\\`\\`\ntrie_explain type:\"issue\" target:\"SQL injection vulnerability\"\n\\`\\`\\`\nor with file context:\n\\`\\`\\`\ntrie_explain type:\"issue\" target:\"src/db.ts:42:Unvalidated input\"\n\\`\\`\\`\n\n### Explain changes:\n\\`\\`\\`\ntrie_explain type:\"change\" target:\"src/auth.ts, src/user.ts\"\n\\`\\`\\`\n\n### Assess risk:\n\\`\\`\\`\ntrie_explain type:\"risk\" target:\"src/payment.ts\"\n\\`\\`\\`\nor for a feature:\n\\`\\`\\`\ntrie_explain type:\"risk\" target:\"Adding Stripe integration for payments\"\n\\`\\`\\`\n\n## Explanation Types\n\n| Type | Description |\n|------|-------------|\n| code | What does this code do? |\n| issue | Why is this a problem? |\n| change | What's the impact? |\n| risk | What could go wrong? |\n`;\n }\n}\n","import { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { extname, relative, resolve, isAbsolute, dirname, basename, join } from 'path';\nimport { getPrompt, getSystemPrompt } from '../ai/prompts.js';\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 allUnits: { file: string; units: TestableUnit[] }[] = [];\n\n for (const file of files) {\n const resolvedPath = isAbsolute(file) ? file : resolve(process.cwd(), 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(process.cwd(), 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(process.cwd(), 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 for (const file of files) {\n const resolvedPath = isAbsolute(file) ? file : resolve(process.cwd(), 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(process.cwd(), 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(process.cwd(), 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 for (const file of files) {\n const resolvedPath = isAbsolute(file) ? file : resolve(process.cwd(), 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(process.cwd(), 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 packagePath = resolve(process.cwd(), '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(process.cwd(), 'pytest.ini')) ||\n existsSync(resolve(process.cwd(), 'pyproject.toml'))) {\n return 'pytest';\n }\n\n return 'jest'; // Default\n }\n\n private detectLanguage(filePath: string): string {\n const ext = extname(filePath).toLowerCase();\n const langMap: Record<string, string> = {\n '.ts': 'typescript', '.tsx': 'tsx', '.js': 'javascript', '.jsx': 'jsx',\n '.py': 'python', '.go': 'go', '.rs': 'rust',\n };\n return langMap[ext] || 'javascript';\n }\n\n private getHelpText(): string {\n return `\n${'โ”'.repeat(60)}\n๐Ÿงช TRIE TEST - AI-POWERED TEST GENERATION\n${'โ”'.repeat(60)}\n\n## Usage\n\n### Generate tests:\n\\`\\`\\`\ntrie_test action:\"generate\" files:[\"src/utils.ts\"]\n\\`\\`\\`\n\n### Analyze coverage:\n\\`\\`\\`\ntrie_test action:\"coverage\" files:[\"src/utils.ts\"]\n\\`\\`\\`\n\n### Get test suggestions:\n\\`\\`\\`\ntrie_test action:\"suggest\" files:[\"src/app.ts\"]\n\\`\\`\\`\n\n### Get run commands:\n\\`\\`\\`\ntrie_test action:\"run\" files:[\"src/utils.test.ts\"]\n\\`\\`\\`\n\n## Options\n\n| Option | Values | Description |\n|--------|--------|-------------|\n| action | generate, coverage, suggest, run | What to do |\n| files | Array of paths | Files to analyze |\n| framework | jest, vitest, mocha, pytest | Test framework |\n| style | unit, integration, e2e, all | Test style |\n`;\n }\n}\n","export class TrieRegisterAgentTool {\n async execute(args: any) {\n const { name, path } = args;\n\n // TODO: Implement register agent functionality\n return {\n content: [\n {\n type: 'text',\n text: `๐Ÿค– Register agent tool called with name: ${name}, path: ${path}\\n\\nTODO: Implement register agent functionality`\n }\n ]\n };\n }\n}","import { watch } from 'fs';\nimport { stat } from 'fs/promises';\nimport { join, extname, basename } from 'path';\nimport { existsSync } from 'fs';\nimport { TrieScanTool } from './scan.js';\nimport { TrieFixTool } from './fix.js';\n\n// File extensions to watch\nconst WATCH_EXTENSIONS = new Set([\n '.ts', '.tsx', '.js', '.jsx', '.mjs',\n '.vue', '.svelte', '.astro',\n '.py', '.go', '.rs'\n]);\n\n// Directories to skip\nconst SKIP_DIRS = new Set([\n 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt',\n 'coverage', '.turbo', '.cache'\n]);\n\ninterface WatchState {\n isRunning: boolean;\n yoloMode: boolean; // Auto-fix everything!\n lastScan: Map<string, number>; // file -> last scan timestamp\n pendingFiles: Set<string>;\n scanDebounceTimer: NodeJS.Timeout | null;\n issueCache: Map<string, any[]>; // file -> issues\n totalIssuesFound: number;\n totalIssuesFixed: number;\n filesScanned: number;\n}\n\nexport class TrieWatchTool {\n private scanTool = new TrieScanTool();\n private fixTool = new TrieFixTool();\n private state: WatchState = {\n isRunning: false,\n yoloMode: false,\n lastScan: new Map(),\n pendingFiles: new Set(),\n scanDebounceTimer: null,\n issueCache: new Map(),\n totalIssuesFound: 0,\n totalIssuesFixed: 0,\n filesScanned: 0\n };\n private watchers: Map<string, ReturnType<typeof watch>> = new Map();\n\n async execute(args: any) {\n const { action, directory, debounceMs = 1000, yolo = false } = args;\n\n switch (action) {\n case 'start':\n return this.startWatching(directory || process.cwd(), debounceMs, yolo);\n case 'stop':\n return this.stopWatching();\n case 'status':\n return this.getStatus();\n case 'issues':\n return this.getCurrentIssues();\n case 'yolo':\n return this.toggleYoloMode();\n default:\n return {\n content: [{\n type: 'text',\n text: `Unknown action: ${action}. Use 'start', 'stop', 'status', 'issues', or 'yolo'.`\n }]\n };\n }\n }\n\n private async startWatching(directory: string, debounceMs: number, yoloMode: boolean) {\n if (this.state.isRunning) {\n return {\n content: [{\n type: 'text',\n text: 'โš ๏ธ Watch mode is already running. Use `trie_watch stop` to stop it first.'\n }]\n };\n }\n\n this.state.isRunning = true;\n this.state.yoloMode = yoloMode;\n this.state.issueCache.clear();\n this.state.totalIssuesFound = 0;\n this.state.totalIssuesFixed = 0;\n this.state.filesScanned = 0;\n\n const modeEmoji = yoloMode ? '๐Ÿ”ฅ' : '๐Ÿ‘๏ธ';\n const modeName = yoloMode ? 'YOLO MODE' : 'WATCH MODE';\n\n console.error('\\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”');\n console.error(`${modeEmoji} TRIE AGENT - AUTONOMOUS ${modeName}`);\n console.error('โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\\n');\n console.error(`๐Ÿ“‚ Watching: ${directory}`);\n console.error(`โฑ๏ธ Debounce: ${debounceMs}ms`);\n if (yoloMode) {\n console.error('๐Ÿ”ฅ YOLO MODE: Auto-fixing issues as they occur!');\n }\n console.error('');\n\n // Start watching the directory recursively\n await this.watchDirectory(directory, debounceMs);\n\n // Do an initial scan\n console.error('๐Ÿ” Running initial scan...\\n');\n const initialResult = await this.scanTool.execute({ directory });\n\n const yoloMessage = yoloMode ? `\n### ๐Ÿ”ฅ YOLO MODE ENABLED\nIssues will be **automatically fixed** as they're detected!\n- High-confidence fixes applied immediately\n- No confirmation needed\n- Living on the edge ๐Ÿš€\n\n` : `\n### ๐Ÿ’ก Want auto-fixes?\nRun \\`trie_watch yolo\\` to enable YOLO mode and auto-fix issues as they occur!\n\n`;\n\n return {\n content: [{\n type: 'text',\n text: `${modeEmoji} **AUTONOMOUS ${modeName} ACTIVATED**\n\nTrie Agent is now watching for file changes and will automatically scan them.\n\n**Watching:** \\`${directory}\\`\n**Debounce:** ${debounceMs}ms (waits for you to stop typing)\n**YOLO Mode:** ${yoloMode ? '๐Ÿ”ฅ ON - Auto-fixing!' : 'โŒ OFF'}\n\n### How it works:\n1. ๐Ÿ“ You write/edit code\n2. ๐Ÿ‘๏ธ Trie detects the change\n3. ๐Ÿ” Automatically scans the modified file\n4. ${yoloMode ? '๐Ÿ”ง Auto-fixes issues immediately!' : '๐Ÿšจ Reports issues immediately'}\n${yoloMessage}\n### Commands:\n- \\`trie_watch status\\` - See current watch status\n- \\`trie_watch yolo\\` - Toggle YOLO mode (auto-fix)\n- \\`trie_watch issues\\` - Get all issues found so far \n- \\`trie_watch stop\\` - Stop autonomous mode\n\n---\n\n${initialResult.content?.[0]?.text || 'Initial scan complete.'}`\n }]\n };\n }\n\n private toggleYoloMode() {\n if (!this.state.isRunning) {\n return {\n content: [{\n type: 'text',\n text: `โš ๏ธ Watch mode is not running. Start it first with:\n \n\\`trie_watch start\\` - Normal mode\n\\`trie_watch start yolo:true\\` - YOLO mode from the start`\n }]\n };\n }\n\n this.state.yoloMode = !this.state.yoloMode;\n\n if (this.state.yoloMode) {\n console.error('\\n๐Ÿ”ฅ YOLO MODE ACTIVATED! Auto-fixing issues as they occur...\\n');\n return {\n content: [{\n type: 'text',\n text: `๐Ÿ”ฅ **YOLO MODE ACTIVATED**\n\nIssues will now be **automatically fixed** as they're detected!\n\nโš ๏ธ **Warning:** This will modify your files without confirmation.\n- High-confidence fixes only\n- Backs up original code in memory\n- You can always undo with git\n\nRun \\`trie_watch yolo\\` again to disable.`\n }]\n };\n } else {\n console.error('\\n๐Ÿ‘๏ธ YOLO mode disabled. Back to watch-only mode.\\n');\n return {\n content: [{\n type: 'text',\n text: `๐Ÿ‘๏ธ **YOLO MODE DISABLED**\n\nBack to normal watch mode. Issues will be reported but not auto-fixed.\n\nRun \\`trie_watch yolo\\` to re-enable.`\n }]\n };\n }\n }\n\n private async watchDirectory(dir: string, debounceMs: number) {\n if (!existsSync(dir)) return;\n\n try {\n const dirStat = await stat(dir);\n if (!dirStat.isDirectory()) return;\n\n // Skip ignored directories\n const dirName = basename(dir);\n if (SKIP_DIRS.has(dirName) || dirName.startsWith('.')) return;\n\n // Watch this directory\n const watcher = watch(dir, { persistent: true }, async (_eventType, filename) => {\n if (!filename) return;\n \n const fullPath = join(dir, filename);\n const ext = extname(filename).toLowerCase();\n\n // Only watch relevant file types\n if (!WATCH_EXTENSIONS.has(ext)) return;\n\n // Skip if file doesn't exist (was deleted)\n if (!existsSync(fullPath)) return;\n\n // Add to pending files\n this.state.pendingFiles.add(fullPath);\n\n // Debounce the scan\n if (this.state.scanDebounceTimer) {\n clearTimeout(this.state.scanDebounceTimer);\n }\n\n this.state.scanDebounceTimer = setTimeout(() => {\n this.processPendingFiles();\n }, debounceMs);\n });\n\n this.watchers.set(dir, watcher);\n\n // Recursively watch subdirectories\n const { readdir } = await import('fs/promises');\n const entries = await readdir(dir, { withFileTypes: true });\n \n for (const entry of entries) {\n if (entry.isDirectory()) {\n await this.watchDirectory(join(dir, entry.name), debounceMs);\n }\n }\n } catch (error) {\n // Skip directories we can't access\n }\n }\n\n private async processPendingFiles() {\n if (this.state.pendingFiles.size === 0) return;\n\n const files = Array.from(this.state.pendingFiles);\n this.state.pendingFiles.clear();\n\n const modeEmoji = this.state.yoloMode ? '๐Ÿ”ฅ' : '๐Ÿ‘๏ธ';\n console.error(`\\n${modeEmoji} Detected changes in ${files.length} file(s):`);\n for (const file of files) {\n console.error(` โ€ข ${basename(file)}`);\n }\n console.error('');\n\n try {\n // Scan the changed files\n const result = await this.scanTool.execute({ files });\n \n // Parse issues from result\n const resultText = result.content?.[0]?.text || '';\n \n // Update stats\n this.state.filesScanned += files.length;\n\n // Extract issue count from result (simple regex)\n const issueMatch = resultText.match(/(\\d+) total/);\n if (issueMatch?.[1] !== undefined) {\n const newIssues = parseInt(issueMatch[1], 10);\n this.state.totalIssuesFound += newIssues;\n\n if (newIssues > 0) {\n console.error(`\\n๐Ÿšจ Found ${newIssues} issues in changed files!`);\n \n // Log a summary\n const criticalMatch = resultText.match(/(\\d+) CRITICAL/);\n const seriousMatch = resultText.match(/(\\d+) SERIOUS/);\n const moderateMatch = resultText.match(/(\\d+) MODERATE/);\n \n if (criticalMatch) {\n console.error(` ๐Ÿ”ด ${criticalMatch[1]} critical issues`);\n }\n if (seriousMatch) {\n console.error(` ๐ŸŸ  ${seriousMatch[1]} serious issues`);\n }\n if (moderateMatch) {\n console.error(` ๐ŸŸก ${moderateMatch[1]} moderate issues`);\n }\n\n // ๐Ÿ”ฅ YOLO MODE: Auto-fix!\n if (this.state.yoloMode) {\n console.error('\\n๐Ÿ”ฅ YOLO MODE: Attempting auto-fix...');\n await this.autoFixIssues(files);\n } else {\n console.error('\\n๐Ÿ’ก Run `trie_watch yolo` to auto-fix issues');\n }\n } else {\n console.error(' โœ… No issues found - code looks good!');\n }\n }\n\n // Cache issues for each file\n for (const file of files) {\n this.state.lastScan.set(file, Date.now());\n }\n\n } catch (error) {\n console.error(`โŒ Scan error: ${error}`);\n }\n }\n\n private async autoFixIssues(files: string[]) {\n try {\n // Call the fix tool with auto-approve for high-confidence fixes\n const fixResult = await this.fixTool.execute({\n files,\n autoApprove: true,\n minConfidence: 0.8 // Only fix high-confidence issues\n });\n\n const fixText = fixResult.content?.[0]?.text || '';\n \n // Parse how many were fixed\n const fixedMatch = fixText.match(/(\\d+) issues? fixed/i);\n if (fixedMatch?.[1] !== undefined) {\n const fixed = parseInt(fixedMatch[1], 10);\n this.state.totalIssuesFixed += fixed;\n console.error(` โœ… Auto-fixed ${fixed} issues!`);\n } else if (fixText.includes('No issues')) {\n console.error(' โ„น๏ธ No auto-fixable issues found');\n } else {\n // Show first line of result\n const firstLine = fixText.split('\\n')[0];\n console.error(` ๐Ÿ”ง ${firstLine}`);\n }\n } catch (error) {\n console.error(` โš ๏ธ Auto-fix error: ${error}`);\n }\n }\n\n private stopWatching() {\n if (!this.state.isRunning) {\n return {\n content: [{\n type: 'text',\n text: 'โš ๏ธ Watch mode is not running.'\n }]\n };\n }\n\n // Close all watchers\n for (const [_dir, watcher] of this.watchers) {\n watcher.close();\n }\n this.watchers.clear();\n\n // Clear state\n if (this.state.scanDebounceTimer) {\n clearTimeout(this.state.scanDebounceTimer);\n }\n \n const wasYolo = this.state.yoloMode;\n this.state.isRunning = false;\n this.state.yoloMode = false;\n\n const modeEmoji = wasYolo ? '๐Ÿ”ฅ' : '๐Ÿ‘๏ธ';\n console.error(`\\n${modeEmoji} Watch mode stopped.\\n`);\n\n const yoloStats = wasYolo ? `\n- ๐Ÿ”ฅ **Issues auto-fixed: ${this.state.totalIssuesFixed}**` : '';\n\n return {\n content: [{\n type: 'text',\n text: `${modeEmoji} **AUTONOMOUS MODE STOPPED**\n\n### Session Summary:\n- Files scanned: ${this.state.filesScanned}\n- Total issues found: ${this.state.totalIssuesFound}${yoloStats}\n- Directories watched: ${this.watchers.size}\n${wasYolo ? `\\n๐Ÿ”ฅ YOLO mode was ON - issues were auto-fixed as they occurred!` : ''}\n\nUse \\`trie_watch start\\` to start watching again.\nUse \\`trie_watch start yolo:true\\` for YOLO mode.`\n }]\n };\n }\n\n private getStatus() {\n if (!this.state.isRunning) {\n return {\n content: [{\n type: 'text',\n text: `๐Ÿ‘๏ธ **Watch Mode Status: STOPPED**\n\nUse \\`trie_watch start\\` to begin autonomous scanning.\nUse \\`trie_watch start yolo:true\\` for YOLO mode (auto-fix).`\n }]\n };\n }\n\n const modeEmoji = this.state.yoloMode ? '๐Ÿ”ฅ' : '๐Ÿ‘๏ธ';\n const modeName = this.state.yoloMode ? 'YOLO MODE' : 'WATCH MODE';\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 yoloStats = this.state.yoloMode ? `\n- ๐Ÿ”ฅ Issues auto-fixed: ${this.state.totalIssuesFixed}` : '';\n\n return {\n content: [{\n type: 'text',\n text: `${modeEmoji} **${modeName} Status: RUNNING**\n\n### Stats:\n- Directories watched: ${this.watchers.size}\n- Files scanned this session: ${this.state.filesScanned}\n- Total issues found: ${this.state.totalIssuesFound}${yoloStats}\n- Pending files: ${this.state.pendingFiles.size}\n- YOLO Mode: ${this.state.yoloMode ? '๐Ÿ”ฅ ON' : 'โŒ OFF'}\n\n### Recently Scanned:\n${recentScans || '(none yet)'}\n\n### Commands:\n- \\`trie_watch yolo\\` - ${this.state.yoloMode ? 'Disable' : 'Enable'} YOLO mode\n- \\`trie_watch issues\\` - Get all issues found\n- \\`trie_watch stop\\` - Stop watching`\n }]\n };\n }\n\n private getCurrentIssues() {\n return {\n content: [{\n type: 'text',\n text: `๐Ÿ“‹ **Issues Found This Session**\n\nTotal issues: ${this.state.totalIssuesFound}\nFiles scanned: ${this.state.filesScanned}\n\nTo get a full report, run \\`trie_scan\\` on your codebase.`\n }]\n };\n }\n}\n\n","import { readdir, readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join, extname, isAbsolute, resolve, basename } from 'path';\nimport { AgentRegistry } from '../agents/registry.js';\nimport { buildAnalysis, formatAnalysisResponse } from '../ai/engine.js';\nimport { lookupKnowledge } from '../knowledge/index.js';\nimport type { Issue } from '../types/index.js';\nimport type { AgentName } from '../ai/prompts.js';\n\n// File extensions to scan\nconst SCANNABLE_EXTENSIONS = new Set([\n '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs',\n '.vue', '.svelte', '.astro',\n '.py', '.go', '.rs'\n]);\n\n// Directories to skip\nconst SKIP_DIRS = new Set([\n 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt',\n 'coverage', '.nyc_output', '__pycache__', '.pytest_cache',\n 'vendor', '.venv', 'venv', 'target', '.turbo', '.cache'\n]);\n\n// Map agent names to AI engine agent types\nconst AGENT_TO_AI_TYPE: Record<string, AgentName> = {\n 'security': 'security',\n 'privacy': 'privacy',\n 'legal': 'legal',\n 'design-engineer': 'accessibility',\n 'software-architect': 'architecture',\n 'bug-finding': 'bugs',\n 'user-testing': 'ux',\n 'typecheck': 'types',\n 'devops': 'devops',\n 'comprehension': 'explain',\n 'test': 'test',\n 'trie_clean': 'vibe',\n};\n\n/**\n * Tool for running individual agents with AI-powered analysis\n */\nexport class TrieAgentTool {\n private agentRegistry = new AgentRegistry();\n\n async execute(args: any) {\n const { agent, files, directory, depth = 'standard', lookup, output = 'full' } = args;\n\n // Handle knowledge lookup requests\n if (lookup) {\n return this.handleKnowledgeLookup(lookup);\n }\n\n if (!agent) {\n return this.listAgents();\n }\n\n const agentInstance = this.agentRegistry.getAgent(agent);\n if (!agentInstance) {\n return {\n content: [{\n type: 'text',\n text: `โŒ Agent not found: ${agent}\\n\\nAvailable agents:\\n${this.agentRegistry.getAgentNames().map(n => `- ${n}`).join('\\n')}`\n }]\n };\n }\n\n // Discover files if not specified\n let filesToScan = files || [];\n if (!filesToScan.length) {\n const scanDir = directory || process.cwd();\n console.error(`\\n๐Ÿ” Discovering files in: ${scanDir}`);\n filesToScan = await this.discoverFiles(scanDir);\n console.error(` Found ${filesToScan.length} files\\n`);\n } else {\n // Resolve paths\n filesToScan = filesToScan.map((f: string) => \n isAbsolute(f) ? f : resolve(process.cwd(), f)\n );\n }\n\n // Validate files exist\n const validFiles = filesToScan.filter((f: string) => existsSync(f));\n if (validFiles.length === 0) {\n return {\n content: [{\n type: 'text',\n text: `โŒ No valid files found to scan.`\n }]\n };\n }\n\n const startTime = Date.now();\n \n // Determine AI agent type\n const aiAgentType = AGENT_TO_AI_TYPE[agent];\n \n if (aiAgentType) {\n // Use AI-powered analysis\n return this.runAIAnalysis(\n aiAgentType,\n validFiles,\n agentInstance.name,\n agentInstance.description,\n depth,\n output\n );\n } else {\n // Fallback to static analysis\n return this.runStaticAnalysis(agentInstance, validFiles, startTime);\n }\n }\n\n private async runAIAnalysis(\n agentType: AgentName, \n files: string[], \n agentName: string,\n agentDescription: string,\n depth: string,\n outputMode: string\n ) {\n const startTime = Date.now();\n\n console.error(`\\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”`);\n console.error(`๐Ÿง  Running AI-POWERED ${agentName.toUpperCase()} analysis`);\n console.error(`โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\\n`);\n console.error(`๐Ÿ“„ ${agentDescription}`);\n console.error(`๐Ÿ“‚ Analyzing ${files.length} files (${depth} depth)...\\n`);\n\n try {\n // Build AI analysis\n const analysis = await buildAnalysis({\n agent: agentType,\n files,\n depth: depth as 'quick' | 'standard' | 'deep',\n });\n\n const executionTime = Date.now() - startTime;\n\n // Format the response\n const includePrompt = outputMode === 'full';\n let output = formatAnalysisResponse(analysis, { includePrompt });\n\n // Add knowledge lookup suggestions based on follow-ups\n if (analysis.suggestedFollowUps.length > 0) {\n output += this.generateKnowledgeSuggestions(analysis.suggestedFollowUps, agentType);\n }\n\n output += `\\n*Analysis completed in ${(executionTime / 1000).toFixed(2)}s*\\n`;\n\n return {\n content: [{\n type: 'text',\n text: output\n }]\n };\n } catch (error) {\n return {\n content: [{\n type: 'text',\n text: `โŒ Analysis error: ${error instanceof Error ? error.message : String(error)}`\n }]\n };\n }\n }\n\n private async runStaticAnalysis(agentInstance: any, files: string[], startTime: number) {\n console.error(`\\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”`);\n console.error(`๐Ÿ” Running ${agentInstance.name.toUpperCase()} static analysis`);\n console.error(`โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\\n`);\n console.error(`๐Ÿ“„ ${agentInstance.description}`);\n console.error(`๐Ÿ“‚ Scanning ${files.length} files...\\n`);\n\n try {\n const result = await agentInstance.scan(files, { workingDir: process.cwd() });\n const executionTime = Date.now() - startTime;\n\n return {\n content: [{\n type: 'text',\n text: await this.formatStaticResult(agentInstance.name, result.issues, files, executionTime)\n }]\n };\n } catch (error) {\n return {\n content: [{\n type: 'text',\n text: `โŒ Agent error: ${error instanceof Error ? error.message : String(error)}`\n }]\n };\n }\n }\n\n private generateKnowledgeSuggestions(followUps: string[], agentType: AgentName): string {\n if (followUps.length === 0) {\n return '';\n }\n \n let output = `\\n## ๐Ÿ”— Suggested Follow-ups\\n\\n`;\n\n for (const followUp of followUps) {\n output += `- ${followUp}\\n`;\n }\n\n if (agentType === 'security') {\n output += `- **CVE Check**: Run \\`trie_security lookup:\"cve\" query:\"[library-name]\"\\` to check for vulnerabilities\\n`;\n }\n\n return output;\n }\n\n private handleKnowledgeLookup(lookup: { type: string; query: string; context?: Record<string, string> }) {\n const result = lookupKnowledge({\n type: lookup.type as any,\n query: lookup.query,\n context: lookup.context ?? {},\n });\n\n return {\n content: [{\n type: 'text',\n text: result\n }]\n };\n }\n\n private listAgents() {\n const agents = this.agentRegistry.getAgentDescriptions();\n \n const agentList = agents.map(a => {\n const command = this.getAgentCommand(a.name);\n const aiPowered = AGENT_TO_AI_TYPE[a.name] ? '๐Ÿง ' : '๐Ÿ”';\n return `| \\`${command}\\` | ${aiPowered} ${a.name} | ${a.description} |`;\n }).join('\\n');\n\n return {\n content: [{\n type: 'text',\n text: `# ๐Ÿค– Available Agents\n\n| Command | Agent | Description |\n|---------|-------|-------------|\n${agentList}\n\n**Legend:** ๐Ÿง  = AI-powered deep analysis, ๐Ÿ” = Static pattern matching\n\n## Usage\n\n### Run a specific agent:\n\\`\\`\\`\ntrie_security # Security vulnerabilities\ntrie_privacy # Privacy/GDPR compliance \ntrie_accessibility # WCAG accessibility audit\ntrie_bugs # Bug detection\ntrie_ux # User experience testing\ntrie_types # Type safety analysis\ntrie_architecture # Architecture review\ntrie_devops # DevOps readiness\ntrie_legal # Legal compliance\n\\`\\`\\`\n\n### With options:\n\\`\\`\\`\ntrie_security files:[\"src/auth.ts\"] depth:\"deep\"\n\\`\\`\\`\n\n### Knowledge lookup:\n\\`\\`\\`\ntrie_security lookup:{type:\"cve\", query:\"lodash\"}\ntrie_security lookup:{type:\"docs\", query:\"XSS prevention\", context:{framework:\"react\"}}\n\\`\\`\\`\n\n### Run all agents:\n\\`\\`\\`\ntrie_scan # Full scan with smart triaging\n\\`\\`\\``\n }]\n };\n }\n\n private getAgentCommand(agentName: string): string {\n const commandMap: Record<string, string> = {\n 'security': 'trie_security',\n 'privacy': 'trie_privacy',\n 'legal': 'trie_legal',\n 'design-engineer': 'trie_accessibility',\n 'software-architect': 'trie_architecture',\n 'bug-finding': 'trie_bugs',\n 'user-testing': 'trie_ux',\n 'typecheck': 'trie_types',\n 'devops': 'trie_devops',\n 'comprehension': 'trie_explain',\n 'test': 'trie_test'\n };\n return commandMap[agentName] || `trie_scan --agent ${agentName}`;\n }\n\n private async formatStaticResult(agentName: string, issues: Issue[], files: string[], executionTime: number): Promise<string> {\n const critical = issues.filter(i => i.severity === 'critical').length;\n const serious = issues.filter(i => i.severity === 'serious').length;\n const moderate = issues.filter(i => i.severity === 'moderate').length;\n const low = issues.filter(i => i.severity === 'low').length;\n\n const agentEmoji = this.getAgentEmoji(agentName);\n\n let output = `\\n`;\n output += `# ${agentEmoji} ${agentName.toUpperCase()} SCAN\\n\\n`;\n output += `**Files:** ${files.length} | **Time:** ${(executionTime / 1000).toFixed(2)}s\\n\\n`;\n\n if (issues.length === 0) {\n output += `## โœ… No Issues Found\\n\\n`;\n output += `Your code passed all ${agentName} checks.\\n\\n`;\n return output;\n }\n\n // Count by severity\n output += `## ๐ŸŽฏ ${issues.length} Issues Found\\n\\n`;\n if (critical > 0) output += `๐Ÿ”ด ${critical} Critical `;\n if (serious > 0) output += `๐ŸŸ  ${serious} Serious `;\n if (moderate > 0) output += `๐ŸŸก ${moderate} Moderate `;\n if (low > 0) output += `๐Ÿ”ต ${low} Low`;\n output += `\\n\\n`;\n\n // Sort by severity\n const sorted = [...issues].sort((a, b) => {\n const severityOrder = { critical: 0, serious: 1, moderate: 2, low: 3 };\n if (severityOrder[a.severity] !== severityOrder[b.severity]) {\n return severityOrder[a.severity] - severityOrder[b.severity];\n }\n return (a.line || 0) - (b.line || 0);\n });\n\n // Show each issue with code snippet and fix prompt\n for (const issue of sorted) {\n const icon = { critical: '๐Ÿ”ด', serious: '๐ŸŸ ', moderate: '๐ŸŸก', low: '๐Ÿ”ต' }[issue.severity];\n \n output += `---\\n\\n`;\n output += `${icon} **${issue.issue}**\\n\\n`;\n output += `๐Ÿ“ \\`${issue.file}:${issue.line || '?'}\\`\\n\\n`;\n \n // Get code snippet\n const snippet = await this.getCodeSnippet(issue.file, issue.line);\n if (snippet) {\n output += `\\`\\`\\`\\n${snippet}\\n\\`\\`\\`\\n\\n`;\n }\n \n output += `**Fix:** ${issue.fix}\\n\\n`;\n \n if (issue.cwe) output += `CWE: ${issue.cwe}\\n`;\n if (issue.regulation) output += `Regulation: ${issue.regulation}\\n`;\n \n // Generate fix prompt\n output += `<details>\\n<summary>๐Ÿ’ฌ Prompt to fix this</summary>\\n\\n`;\n output += `\\`\\`\\`\\nFix the ${issue.issue.toLowerCase()} in ${basename(issue.file)}${issue.line ? ` at line ${issue.line}` : ''}.\\n\\n${issue.fix}\\n\\`\\`\\`\\n\\n`;\n output += `</details>\\n\\n`;\n }\n\n output += `---\\n`;\n output += `*${agentName} scan completed in ${(executionTime / 1000).toFixed(2)}s*\\n`;\n\n return output;\n }\n\n /**\n * Get a code snippet around a specific line\n */\n private async getCodeSnippet(filePath: string, line: number | undefined): Promise<string | null> {\n if (!line || !existsSync(filePath)) return null;\n \n try {\n const content = await readFile(filePath, 'utf-8');\n const lines = content.split('\\n');\n const start = Math.max(0, line - 3);\n const end = Math.min(lines.length, line + 2);\n \n return lines.slice(start, end).map((l, idx) => {\n const lineNum = start + idx + 1;\n const marker = lineNum === line ? 'โ†’' : ' ';\n return `${marker} ${lineNum.toString().padStart(4)} | ${l}`;\n }).join('\\n');\n } catch {\n return null;\n }\n }\n\n private getAgentEmoji(agentName: string): string {\n const emojis: Record<string, string> = {\n 'security': '๐Ÿ”’',\n 'privacy': '๐Ÿ‘ค',\n 'legal': 'โš–๏ธ',\n 'design-engineer': 'โ™ฟ',\n 'software-architect': '๐Ÿ—๏ธ',\n 'bug-finding': '๐Ÿ›',\n 'user-testing': '๐ŸŽฏ',\n 'typecheck': '๐Ÿ“',\n 'devops': 'โš™๏ธ',\n 'comprehension': '๐Ÿ“–',\n 'test': '๐Ÿงช'\n };\n return emojis[agentName] || '๐Ÿค–';\n }\n\n private async discoverFiles(dir: string, maxFiles: number = 200): Promise<string[]> {\n const files: string[] = [];\n \n async function walk(currentDir: string) {\n if (files.length >= maxFiles) return;\n \n try {\n const entries = await readdir(currentDir, { withFileTypes: true });\n \n for (const entry of entries) {\n if (files.length >= maxFiles) break;\n \n const fullPath = join(currentDir, entry.name);\n \n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith('.')) {\n await walk(fullPath);\n }\n } else if (entry.isFile()) {\n const ext = extname(entry.name).toLowerCase();\n if (SCANNABLE_EXTENSIONS.has(ext)) {\n files.push(fullPath);\n }\n }\n }\n } catch (error) {\n // Skip directories we can't read\n }\n }\n \n await walk(dir);\n return files;\n }\n}\n","import { readFile } from 'fs/promises';\nimport { extname, relative, basename } from 'path';\nimport { getPrompt, getSystemPrompt, AgentName } from './prompts.js';\n\n/**\n * AI Engine - Generates rich prompts for Claude to analyze code\n * \n * KEY INSIGHT: This is an MCP tool. We don't call an LLM API - we return\n * structured output that Claude (the host AI) will read and act on.\n * \n * The goal is to:\n * 1. Read and understand the code context\n * 2. Build comprehensive prompts that give Claude everything it needs\n * 3. Format output so Claude can provide actionable analysis\n */\n\nexport interface AnalysisRequest {\n agent: AgentName;\n files: string[];\n context?: Record<string, string>;\n depth?: 'quick' | 'standard' | 'deep';\n}\n\nexport interface AnalysisResult {\n agent: string;\n prompt: string;\n systemPrompt: string;\n codeContext: CodeContext[];\n suggestedFollowUps: string[];\n filesSummary: string;\n}\n\nexport interface CodeContext {\n filePath: string;\n relativePath: string;\n language: string;\n content: string;\n lineCount: number;\n summary?: FileSummary;\n}\n\nexport interface FileSummary {\n hasAuth: boolean;\n hasDatabase: boolean;\n hasUserInput: boolean;\n hasFileOps: boolean;\n hasCrypto: boolean;\n hasExternalAPIs: boolean;\n framework?: string;\n exports: string[];\n imports: string[];\n}\n\n/**\n * Language detection based on file extension\n */\nfunction 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 '.java': 'java',\n '.rb': 'ruby',\n '.php': 'php',\n '.vue': 'vue',\n '.svelte': 'svelte',\n '.sql': 'sql',\n '.json': 'json',\n '.yaml': 'yaml',\n '.yml': 'yaml',\n '.md': 'markdown',\n '.html': 'html',\n '.css': 'css',\n '.scss': 'scss',\n };\n return langMap[ext] || 'plaintext';\n}\n\n/**\n * Analyze file content to understand its context\n * This helps build smarter prompts for the AI\n */\nfunction analyzeFileContext(content: string, _filePath: string): FileSummary {\n const summary: FileSummary = {\n hasAuth: false,\n hasDatabase: false,\n hasUserInput: false,\n hasFileOps: false,\n hasCrypto: false,\n hasExternalAPIs: false,\n exports: [],\n imports: [],\n };\n\n // Detect auth-related code\n if (/auth|login|session|jwt|token|password|credential|oauth/i.test(content)) {\n summary.hasAuth = true;\n }\n\n // Detect database operations\n if (/prisma|sequelize|knex|mongodb|sql|query|database|postgres|mysql|sqlite/i.test(content)) {\n summary.hasDatabase = true;\n }\n\n // Detect user input handling\n if (/req\\.body|req\\.params|req\\.query|formData|input|textarea|userinput/i.test(content)) {\n summary.hasUserInput = true;\n }\n\n // Detect file operations\n if (/readFile|writeFile|createReadStream|createWriteStream|fs\\.|multer|upload/i.test(content)) {\n summary.hasFileOps = true;\n }\n\n // Detect crypto\n if (/crypto|bcrypt|argon|scrypt|encrypt|decrypt|hash|sign|verify/i.test(content)) {\n summary.hasCrypto = true;\n }\n\n // Detect external API calls\n if (/fetch\\(|axios|http\\.|https\\.|request\\(|got\\(|api\\//i.test(content)) {\n summary.hasExternalAPIs = true;\n }\n\n // Detect framework\n if (/from\\s+['\"]react['\"]|import\\s+React/i.test(content)) {\n summary.framework = 'React';\n } else if (/from\\s+['\"]next|NextRequest|getServerSideProps/i.test(content)) {\n summary.framework = 'Next.js';\n } else if (/from\\s+['\"]express['\"]|express\\(\\)/i.test(content)) {\n summary.framework = 'Express';\n } else if (/from\\s+['\"]fastify['\"]|fastify\\(\\)/i.test(content)) {\n summary.framework = 'Fastify';\n } else if (/from\\s+['\"]vue['\"]|defineComponent/i.test(content)) {\n summary.framework = 'Vue';\n }\n\n // Extract exports (simplified)\n const exportMatches = content.match(/export\\s+(const|function|class|interface|type)\\s+(\\w+)/g) || [];\n summary.exports = exportMatches.map(m => m.split(/\\s+/).pop() || '').filter(Boolean).slice(0, 10);\n\n // Extract imports (simplified)\n const importMatches = content.match(/import\\s+.*from\\s+['\"]([^'\"]+)['\"]/g) || [];\n summary.imports = importMatches.map(m => {\n const match = m.match(/from\\s+['\"]([^'\"]+)['\"]/);\n return match ? match[1] : '';\n }).filter((s): s is string => Boolean(s)).slice(0, 10);\n\n return summary;\n}\n\n/**\n * Build a rich prompt context for AI analysis\n */\nfunction buildPromptContext(contexts: CodeContext[], agent: AgentName): string {\n let contextSummary = '';\n \n // Aggregate insights\n const hasAuth = contexts.some(c => c.summary?.hasAuth);\n const hasDatabase = contexts.some(c => c.summary?.hasDatabase);\n const hasUserInput = contexts.some(c => c.summary?.hasUserInput);\n const hasFileOps = contexts.some(c => c.summary?.hasFileOps);\n const hasCrypto = contexts.some(c => c.summary?.hasCrypto);\n const hasExternalAPIs = contexts.some(c => c.summary?.hasExternalAPIs);\n const frameworks = [...new Set(contexts.map(c => c.summary?.framework).filter(Boolean))];\n\n contextSummary += '## Code Context Summary\\n\\n';\n contextSummary += `**Files analyzed:** ${contexts.length}\\n`;\n contextSummary += `**Total lines:** ${contexts.reduce((sum, c) => sum + c.lineCount, 0)}\\n`;\n \n if (frameworks.length > 0) {\n contextSummary += `**Frameworks detected:** ${frameworks.join(', ')}\\n`;\n }\n \n const features = [];\n if (hasAuth) features.push('Authentication/Authorization');\n if (hasDatabase) features.push('Database operations');\n if (hasUserInput) features.push('User input handling');\n if (hasFileOps) features.push('File operations');\n if (hasCrypto) features.push('Cryptography');\n if (hasExternalAPIs) features.push('External API calls');\n \n if (features.length > 0) {\n contextSummary += `**Key features:** ${features.join(', ')}\\n`;\n }\n \n contextSummary += '\\n';\n\n // Agent-specific focus areas\n if (agent === 'security') {\n if (hasAuth) contextSummary += 'โš ๏ธ **Auth code detected** - Review authentication flows carefully\\n';\n if (hasDatabase) contextSummary += 'โš ๏ธ **Database ops detected** - Check for injection vulnerabilities\\n';\n if (hasUserInput) contextSummary += 'โš ๏ธ **User input detected** - Verify input validation\\n';\n } else if (agent === 'privacy') {\n if (hasAuth) contextSummary += 'โš ๏ธ **Auth code detected** - Review credential handling\\n';\n if (hasDatabase) contextSummary += 'โš ๏ธ **Database ops detected** - Check PII storage\\n';\n } else if (agent === 'bugs') {\n if (hasExternalAPIs) contextSummary += 'โš ๏ธ **External APIs detected** - Check error handling\\n';\n if (hasFileOps) contextSummary += 'โš ๏ธ **File ops detected** - Verify error handling and cleanup\\n';\n }\n\n return contextSummary;\n}\n\n/**\n * Build the full analysis for Claude\n */\nexport async function buildAnalysis(request: AnalysisRequest): Promise<AnalysisResult> {\n const { agent, files, context = {}, depth = 'standard' } = request;\n \n const codeContexts: CodeContext[] = [];\n\n console.error(`๐Ÿ”ฌ AI Engine: Preparing ${agent} analysis for ${files.length} files...`);\n\n // Process each file\n for (const filePath of files) {\n try {\n const content = await readFile(filePath, 'utf-8');\n const language = detectLanguage(filePath);\n const summary = analyzeFileContext(content, filePath);\n\n console.error(` ๐Ÿ“„ ${basename(filePath)} - ${content.split('\\n').length} lines`);\n\n codeContexts.push({\n filePath,\n relativePath: relative(process.cwd(), filePath),\n language,\n content: depth === 'quick' && content.length > 5000\n ? content.substring(0, 5000) + '\\n\\n... (truncated for quick analysis)'\n : content,\n lineCount: content.split('\\n').length,\n summary,\n });\n } catch (error) {\n console.error(` โš ๏ธ Error reading ${filePath}:`, error);\n }\n }\n\n // Build the analysis prompt\n const codeBlocks = codeContexts.map(ctx => \n `### File: ${ctx.relativePath}\\n\\`\\`\\`${ctx.language}\\n${ctx.content}\\n\\`\\`\\``\n ).join('\\n\\n');\n\n // Build context summary\n const promptContext = buildPromptContext(codeContexts, agent);\n\n // Get prompt template and fill in variables\n const variables: Record<string, string> = {\n ...context,\n code: codeBlocks,\n language: codeContexts[0]?.language || 'unknown',\n filePath: codeContexts.map(c => c.relativePath).join(', '),\n };\n\n const analysisPrompt = getPrompt(agent, 'analysis', variables);\n const systemPrompt = getSystemPrompt(agent);\n\n // Build suggested follow-ups based on context\n const suggestedFollowUps: string[] = [];\n \n if (codeContexts.some(c => c.summary?.hasAuth)) {\n suggestedFollowUps.push('๐Ÿ” Review authentication implementation');\n }\n if (codeContexts.some(c => c.summary?.hasDatabase)) {\n suggestedFollowUps.push('๐Ÿ—„๏ธ Check database query security');\n }\n if (codeContexts.some(c => c.summary?.hasUserInput)) {\n suggestedFollowUps.push('๐Ÿ“ Verify input validation');\n }\n\n // Generate files summary for display\n const filesSummary = codeContexts.map(c => {\n const features = [];\n if (c.summary?.hasAuth) features.push('auth');\n if (c.summary?.hasDatabase) features.push('db');\n if (c.summary?.hasUserInput) features.push('input');\n if (c.summary?.framework) features.push(c.summary.framework);\n \n const featureStr = features.length > 0 ? ` [${features.join(', ')}]` : '';\n return `\\`${c.relativePath}\\` (${c.lineCount} lines)${featureStr}`;\n }).join('\\n');\n\n console.error(`๐Ÿง  AI Engine: Analysis prepared - ready for Claude`);\n\n return {\n agent,\n systemPrompt,\n prompt: promptContext + '\\n' + analysisPrompt,\n codeContext: codeContexts,\n suggestedFollowUps,\n filesSummary,\n };\n}\n\n/**\n * Format analysis result for MCP response\n * This is what Claude sees and acts on\n */\nexport function formatAnalysisResponse(\n result: AnalysisResult,\n options: { includePrompt?: boolean } = {}\n): string {\n const { agent, systemPrompt, prompt, codeContext, suggestedFollowUps, filesSummary } = result;\n const includePrompt = options.includePrompt ?? true; // Default to showing prompt now\n\n let output = '';\n\n // Header\n output += `\\n${'โ”'.repeat(60)}\\n`;\n output += `๐Ÿง  ${agent.toUpperCase()} AGENT - AI ANALYSIS\\n`;\n output += `${'โ”'.repeat(60)}\\n\\n`;\n\n // Files summary\n output += `## ๐Ÿ“‚ Files for Analysis\\n\\n`;\n output += filesSummary + '\\n\\n';\n\n // Follow-up suggestions\n if (suggestedFollowUps.length > 0) {\n output += `## ๐ŸŽฏ Focus Areas\\n\\n`;\n for (const followUp of suggestedFollowUps) {\n output += `- ${followUp}\\n`;\n }\n output += '\\n';\n }\n\n // The AI analysis request - this is what Claude will process\n output += `${'โ”€'.repeat(60)}\\n`;\n output += `## ๐Ÿง  Analysis Request for Claude\\n\\n`;\n \n if (includePrompt) {\n output += `**Role:** ${systemPrompt.split('\\n')[0]}\\n\\n`;\n output += `---\\n\\n`;\n output += prompt;\n output += `\\n\\n${'โ”€'.repeat(60)}\\n`;\n } else {\n output += `*Run with \\`output: \"full\"\\` to see the complete analysis prompt.*\\n\\n`;\n output += `**Summary:** ${codeContext.length} files ready for ${agent} analysis\\n`;\n }\n\n output += `\\n**Claude:** Please analyze the code above according to the ${agent} analysis instructions and provide your findings.\\n`;\n\n return output;\n}\n\n/**\n * Generate a concise AI prompt for a specific issue type\n */\nexport function generateFocusedPrompt(\n code: string,\n filePath: string,\n focusArea: 'sql-injection' | 'xss' | 'auth' | 'secrets' | 'general'\n): string {\n const relPath = relative(process.cwd(), filePath);\n \n const focusPrompts: Record<string, string> = {\n 'sql-injection': `Check this code for SQL injection vulnerabilities. Look for:\n- String concatenation in SQL queries\n- Template literals with user input in queries\n- Missing parameterized queries\n- ORM misuse that could lead to injection`,\n \n 'xss': `Check this code for XSS vulnerabilities. Look for:\n- innerHTML/outerHTML with user content\n- dangerouslySetInnerHTML without sanitization\n- Template rendering without escaping\n- URL parameters reflected without encoding`,\n \n 'auth': `Check this code for authentication/authorization issues. Look for:\n- Password comparison without hashing\n- Missing authentication on sensitive routes\n- Weak session token generation\n- JWT validation issues\n- Authorization bypass opportunities`,\n \n 'secrets': `Check this code for exposed secrets. Look for:\n- Hardcoded API keys, passwords, tokens\n- Credentials in code (not environment variables)\n- Private keys or certificates in code\n- Database connection strings with passwords`,\n \n 'general': `Perform a general security review of this code.`\n };\n\n return `## Security Analysis: ${focusArea}\n\n**File:** \\`${relPath}\\`\n\n${focusPrompts[focusArea]}\n\n\\`\\`\\`\n${code}\n\\`\\`\\`\n\nFor each issue found, provide:\n1. **Line number** where the issue occurs\n2. **Severity** (critical/serious/moderate/low)\n3. **Description** of the vulnerability\n4. **Attack scenario** showing how it could be exploited\n5. **Fix** with specific code changes`;\n}\n","/**\n * Knowledge Module - External information lookup\n * \n * This module provides structured prompts for looking up:\n * - CVE databases\n * - Security advisories\n * - Framework documentation\n * - Best practices\n * \n * The MCP returns these as prompts, and Claude (with web access) \n * can then look up the information.\n */\n\nexport interface KnowledgeRequest {\n type: 'cve' | 'docs' | 'security' | 'best-practices' | 'changelog';\n query: string;\n context?: Record<string, string>;\n}\n\nexport interface KnowledgeSource {\n name: string;\n url: string;\n description: string;\n}\n\n/**\n * Security-related knowledge sources\n */\nexport const SECURITY_SOURCES: KnowledgeSource[] = [\n {\n name: 'OWASP Top 10',\n url: 'https://owasp.org/Top10/',\n description: 'Most critical web application security risks'\n },\n {\n name: 'NIST NVD',\n url: 'https://nvd.nist.gov/',\n description: 'National Vulnerability Database'\n },\n {\n name: 'CVE Database',\n url: 'https://cve.mitre.org/',\n description: 'Common Vulnerabilities and Exposures'\n },\n {\n name: 'Snyk Vulnerability DB',\n url: 'https://security.snyk.io/',\n description: 'Open source vulnerability database'\n },\n {\n name: 'GitHub Advisory Database',\n url: 'https://github.com/advisories',\n description: 'Security advisories from GitHub'\n }\n];\n\n/**\n * Framework documentation sources\n */\nexport const DOCS_SOURCES: Record<string, KnowledgeSource[]> = {\n react: [\n { name: 'React Docs', url: 'https://react.dev/', description: 'Official React documentation' },\n { name: 'React Security', url: 'https://react.dev/reference/react-dom/components/common#dangerously-setting-the-inner-html', description: 'React security guidance' },\n ],\n nextjs: [\n { name: 'Next.js Docs', url: 'https://nextjs.org/docs', description: 'Official Next.js documentation' },\n { name: 'Next.js Security', url: 'https://nextjs.org/docs/advanced-features/security-headers', description: 'Next.js security headers' },\n ],\n express: [\n { name: 'Express Docs', url: 'https://expressjs.com/', description: 'Official Express.js documentation' },\n { name: 'Express Security', url: 'https://expressjs.com/en/advanced/best-practice-security.html', description: 'Express security best practices' },\n ],\n node: [\n { name: 'Node.js Docs', url: 'https://nodejs.org/docs/', description: 'Official Node.js documentation' },\n { name: 'Node.js Security', url: 'https://nodejs.org/en/docs/guides/security/', description: 'Node.js security guidance' },\n ],\n typescript: [\n { name: 'TypeScript Docs', url: 'https://www.typescriptlang.org/docs/', description: 'Official TypeScript documentation' },\n ],\n};\n\n/**\n * Compliance-related sources\n */\nexport const COMPLIANCE_SOURCES: Record<string, KnowledgeSource[]> = {\n gdpr: [\n { name: 'GDPR Official Text', url: 'https://gdpr.eu/', description: 'Complete GDPR regulation text' },\n { name: 'GDPR Checklist', url: 'https://gdpr.eu/checklist/', description: 'GDPR compliance checklist' },\n ],\n hipaa: [\n { name: 'HIPAA Guidelines', url: 'https://www.hhs.gov/hipaa/', description: 'Official HIPAA guidance' },\n ],\n wcag: [\n { name: 'WCAG 2.1', url: 'https://www.w3.org/WAI/WCAG21/quickref/', description: 'WCAG 2.1 quick reference' },\n ],\n pci: [\n { name: 'PCI DSS', url: 'https://www.pcisecuritystandards.org/', description: 'Payment Card Industry standards' },\n ],\n};\n\n/**\n * Generate a CVE lookup prompt\n */\nexport function generateCVELookup(library: string, version?: string): string {\n let prompt = `## ๐Ÿ”’ Security Vulnerability Lookup\\n\\n`;\n prompt += `**Library:** ${library}\\n`;\n if (version) prompt += `**Version:** ${version}\\n`;\n prompt += `\\n`;\n\n prompt += `### Action Required\\n\\n`;\n prompt += `Please check for known vulnerabilities:\\n\\n`;\n prompt += `1. Search the **NIST NVD** (https://nvd.nist.gov/) for CVEs affecting \\`${library}\\`\\n`;\n prompt += `2. Check **Snyk** (https://security.snyk.io/) for vulnerability reports\\n`;\n prompt += `3. Review **GitHub Advisory Database** for any security advisories\\n`;\n prompt += `4. Check npm audit / yarn audit if it's an npm package\\n\\n`;\n\n prompt += `### Report Format\\n\\n`;\n prompt += `For each vulnerability found, provide:\\n`;\n prompt += `- CVE ID (if applicable)\\n`;\n prompt += `- Severity (Critical/High/Medium/Low)\\n`;\n prompt += `- Affected versions\\n`;\n prompt += `- Description of the vulnerability\\n`;\n prompt += `- Remediation (upgrade version, patches, mitigations)\\n`;\n\n return prompt;\n}\n\n/**\n * Generate a documentation lookup prompt\n */\nexport function generateDocsLookup(topic: string, framework?: string): string {\n let prompt = `## ๐Ÿ“š Documentation Lookup\\n\\n`;\n prompt += `**Topic:** ${topic}\\n`;\n if (framework) prompt += `**Framework:** ${framework}\\n`;\n prompt += `\\n`;\n\n const sources = framework ? DOCS_SOURCES[framework.toLowerCase()] : [];\n \n if (sources && sources.length > 0) {\n prompt += `### Recommended Sources\\n\\n`;\n for (const source of sources) {\n prompt += `- [${source.name}](${source.url}) - ${source.description}\\n`;\n }\n prompt += `\\n`;\n }\n\n prompt += `### Information Needed\\n\\n`;\n prompt += `Please look up the latest documentation and provide:\\n\\n`;\n prompt += `1. Current best practices for \"${topic}\"\\n`;\n prompt += `2. Common pitfalls to avoid\\n`;\n prompt += `3. Code examples demonstrating correct usage\\n`;\n prompt += `4. Any recent changes or deprecations\\n`;\n\n return prompt;\n}\n\n/**\n * Generate a security best practices lookup prompt\n */\nexport function generateSecurityLookup(pattern: string, context?: string): string {\n let prompt = `## ๐Ÿ›ก๏ธ Security Best Practices Lookup\\n\\n`;\n prompt += `**Pattern:** ${pattern}\\n`;\n if (context) prompt += `**Context:** ${context}\\n`;\n prompt += `\\n`;\n\n prompt += `### Reference Sources\\n\\n`;\n for (const source of SECURITY_SOURCES.slice(0, 3)) {\n prompt += `- [${source.name}](${source.url})\\n`;\n }\n prompt += `\\n`;\n\n prompt += `### Analysis Requested\\n\\n`;\n prompt += `Please research and provide:\\n\\n`;\n prompt += `1. **OWASP guidance** for this security pattern\\n`;\n prompt += `2. **Attack vectors** - how this could be exploited\\n`;\n prompt += `3. **Defense strategies** - recommended mitigations\\n`;\n prompt += `4. **Code examples** - secure implementation patterns\\n`;\n prompt += `5. **Testing approaches** - how to verify security\\n`;\n\n return prompt;\n}\n\n/**\n * Generate a compliance lookup prompt\n */\nexport function generateComplianceLookup(regulation: string, requirement?: string): string {\n let prompt = `## โš–๏ธ Compliance Requirement Lookup\\n\\n`;\n prompt += `**Regulation:** ${regulation}\\n`;\n if (requirement) prompt += `**Specific Requirement:** ${requirement}\\n`;\n prompt += `\\n`;\n\n const sources = COMPLIANCE_SOURCES[regulation.toLowerCase()];\n \n if (sources && sources.length > 0) {\n prompt += `### Official Sources\\n\\n`;\n for (const source of sources) {\n prompt += `- [${source.name}](${source.url})\\n`;\n }\n prompt += `\\n`;\n }\n\n prompt += `### Compliance Information Needed\\n\\n`;\n prompt += `Please research and provide:\\n\\n`;\n prompt += `1. **Specific requirement text** from the regulation\\n`;\n prompt += `2. **Technical requirements** for compliance\\n`;\n prompt += `3. **Implementation guidance** with code examples\\n`;\n prompt += `4. **Documentation requirements** - what records to keep\\n`;\n prompt += `5. **Penalties** for non-compliance\\n`;\n\n return prompt;\n}\n\n/**\n * Generate a changelog/version lookup prompt\n */\nexport function generateChangelogLookup(library: string, fromVersion: string, toVersion?: string): string {\n let prompt = `## ๐Ÿ“‹ Changelog Lookup\\n\\n`;\n prompt += `**Library:** ${library}\\n`;\n prompt += `**Current Version:** ${fromVersion}\\n`;\n if (toVersion) prompt += `**Target Version:** ${toVersion}\\n`;\n prompt += `\\n`;\n\n prompt += `### Information Needed\\n\\n`;\n prompt += `Please find the changelog/release notes and provide:\\n\\n`;\n prompt += `1. **Breaking changes** between versions\\n`;\n prompt += `2. **New features** added\\n`;\n prompt += `3. **Deprecations** to be aware of\\n`;\n prompt += `4. **Security fixes** included\\n`;\n prompt += `5. **Migration guide** if available\\n`;\n prompt += `6. **Known issues** with the upgrade\\n`;\n\n return prompt;\n}\n\n/**\n * Main knowledge lookup function\n */\nexport function lookupKnowledge(request: KnowledgeRequest): string {\n const { type, query, context = {} } = request;\n\n switch (type) {\n case 'cve':\n return generateCVELookup(query, context.version);\n \n case 'docs':\n return generateDocsLookup(query, context.framework);\n \n case 'security':\n return generateSecurityLookup(query, context.context);\n \n case 'best-practices':\n return generateComplianceLookup(query, context.requirement);\n \n case 'changelog':\n return generateChangelogLookup(query, context.fromVersion || 'current', context.toVersion);\n \n default:\n return `Unknown knowledge request type: ${type}`;\n }\n}\n\n/**\n * Detect libraries and versions from package.json\n */\nexport async function detectDependencies(packageJsonPath: string): Promise<Map<string, string>> {\n const deps = new Map<string, string>();\n \n try {\n const { readFile } = await import('fs/promises');\n const content = await readFile(packageJsonPath, 'utf-8');\n const pkg = JSON.parse(content);\n \n const allDeps = {\n ...pkg.dependencies,\n ...pkg.devDependencies,\n };\n\n for (const [name, version] of Object.entries(allDeps)) {\n deps.set(name, String(version).replace(/^[\\^~]/, ''));\n }\n } catch {\n // Ignore errors\n }\n\n return deps;\n}\n\n/**\n * Known vulnerable packages (quick check - not exhaustive)\n */\nexport const KNOWN_VULNERABLE_PATTERNS = [\n { pattern: /^lodash$/, minSafeVersion: '4.17.21', reason: 'Prototype pollution' },\n { pattern: /^minimist$/, minSafeVersion: '1.2.6', reason: 'Prototype pollution' },\n { pattern: /^node-fetch$/, minSafeVersion: '2.6.7', reason: 'URL bypass' },\n { pattern: /^axios$/, minSafeVersion: '1.6.0', reason: 'SSRF vulnerability' },\n { pattern: /^jsonwebtoken$/, minSafeVersion: '9.0.0', reason: 'Algorithm confusion' },\n];\n\n","/**\n * MCP Tool: trie_create_agent\n * \n * Creates a custom agent from a PDF, TXT, MD, or RTF document.\n * \n * This is a two-step process that leverages the host LLM (Claude in Cursor/Claude Code):\n * 1. trie_create_agent - Parses document and returns extraction prompt\n * 2. trie_save_agent - Saves the agent config after Claude processes it\n * \n * This design eliminates the need for a separate ANTHROPIC_API_KEY since\n * the user is already in an AI workflow with Claude.\n */\n\nimport { parseDocument } from '../ingest/document-parser.js';\nimport { listCustomAgents, loadAgentConfig } from '../ingest/agent-builder.js';\nimport type { GeneratedAgentConfig, CompressedKnowledge } from '../types/custom-agent.js';\nimport { existsSync } from 'fs';\nimport { mkdir, writeFile } from 'fs/promises';\nimport { join, basename, extname } from 'path';\n\nexport class TrieCreateAgentTool {\n async execute(args: {\n filePath?: string;\n documentContent?: string;\n agentName: string;\n displayName?: string;\n description?: string;\n category?: string;\n }) {\n const { filePath, documentContent, agentName, displayName, description, category } = args;\n \n // Validate inputs\n if (!agentName) {\n return this.errorResponse('Missing required parameter: agentName');\n }\n \n // Either filePath or documentContent must be provided\n if (!filePath && !documentContent) {\n return this.errorResponse(\n 'Provide either filePath (path to PDF/TXT/MD file) or documentContent (raw text from drag-and-drop)'\n );\n }\n \n try {\n let rawText: string;\n let title: string = agentName;\n let wordCount: number = 0;\n \n if (filePath) {\n // Check if file exists\n if (!existsSync(filePath)) {\n return this.errorResponse(`File not found: ${filePath}`);\n }\n \n // Check supported file types\n const ext = filePath.toLowerCase().split('.').pop();\n if (!['pdf', 'txt', 'md', 'markdown', 'rtf'].includes(ext || '')) {\n return this.errorResponse(\n `Unsupported file type: .${ext}\\nSupported types: .pdf, .txt, .md, .rtf`\n );\n }\n \n // Parse the document\n const document = await parseDocument(filePath);\n rawText = document.rawText;\n // fileType is available in document.metadata.fileType if needed\n title = document.metadata.title || basename(filePath, extname(filePath));\n wordCount = document.metadata.wordCount;\n } else {\n // Use provided document content (from drag-and-drop)\n rawText = documentContent!;\n wordCount = rawText.split(/\\s+/).filter(w => w.length > 0).length;\n \n // Try to extract title from first line\n const firstLine = rawText.split('\\n')[0]?.trim();\n if (firstLine && firstLine.length < 100) {\n title = firstLine;\n }\n }\n \n // Chunk the document for processing\n const chunks = this.chunkText(rawText, 6000);\n \n // Build the extraction prompt that Claude will process\n const extractionPrompt = this.buildExtractionPrompt(\n chunks,\n title,\n agentName,\n category,\n displayName,\n description\n );\n \n // Return the prompt for Claude to process\n return {\n content: [\n {\n type: 'text',\n text: this.formatExtractionRequest(\n agentName,\n title,\n wordCount,\n chunks.length,\n extractionPrompt\n ),\n },\n ],\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return this.errorResponse(`Failed to parse document: ${errorMessage}`);\n }\n }\n \n /**\n * Chunk text into manageable pieces\n */\n private chunkText(text: string, maxChunkSize: number): string[] {\n if (text.length <= maxChunkSize) {\n return [text];\n }\n \n const chunks: string[] = [];\n const paragraphs = text.split(/\\n\\s*\\n/);\n let currentChunk = '';\n \n for (const para of paragraphs) {\n if (currentChunk.length + para.length + 2 > maxChunkSize) {\n if (currentChunk) chunks.push(currentChunk.trim());\n currentChunk = para;\n } else {\n currentChunk += (currentChunk ? '\\n\\n' : '') + para;\n }\n }\n \n if (currentChunk) chunks.push(currentChunk.trim());\n return chunks;\n }\n \n /**\n * Build the extraction prompt for Claude\n */\n private buildExtractionPrompt(\n chunks: string[],\n title: string,\n agentName: string,\n category?: string,\n displayName?: string,\n description?: string\n ): string {\n const prefix = agentName.toUpperCase().replace(/[^A-Z]/g, '').slice(0, 4) || 'CUST';\n \n // Combine chunks with separators\n const documentContent = chunks.length === 1 \n ? chunks[0]\n : chunks.map((c, i) => `--- SECTION ${i + 1}/${chunks.length} ---\\n${c}`).join('\\n\\n');\n \n return `# Create Code Review Agent: \"${displayName || this.formatDisplayName(agentName)}\"\n\n## Your Task\nAnalyze the following document and extract structured knowledge to create a code review agent.\n\n## Document Information\n- **Title**: ${title}\n- **Agent Name**: ${agentName}\n- **Category**: ${category || 'auto-detect'}\n${description ? `- **Description**: ${description}` : ''}\n\n## Document Content\n${documentContent}\n\n---\n\n## Instructions\n\nPlease analyze this document and produce a **single JSON object** with the following structure. This will be used to create a custom code review agent.\n\n**IMPORTANT**: Your response should be ONLY the JSON object, no other text.\n\n\\`\\`\\`json\n{\n \"agentConfig\": {\n \"name\": \"${this.sanitizeAgentName(agentName)}\",\n \"displayName\": \"${displayName || this.formatDisplayName(agentName)}\",\n \"description\": \"${description || `Code review agent based on ${title}`}\",\n \"version\": \"1.0.0\",\n \"category\": \"string (technical | legal | policy | security | architecture | general)\"\n },\n \"knowledge\": {\n \"domain\": \"string (technical | legal | policy | security | architecture | general)\",\n \"summary\": \"2-3 paragraph summary of the document's key insights for code review\",\n \"coreConcepts\": [\n {\n \"name\": \"string\",\n \"description\": \"string\",\n \"importance\": \"critical | important | supplementary\",\n \"keywords\": [\"string\"]\n }\n ],\n \"bestPractices\": [\n {\n \"name\": \"string\",\n \"description\": \"string\",\n \"rationale\": \"why this is important\",\n \"codeExample\": \"optional code example or null\"\n }\n ],\n \"antiPatterns\": [\n {\n \"name\": \"string\",\n \"description\": \"string\",\n \"whyBad\": \"why to avoid\",\n \"betterAlternative\": \"what to do instead\"\n }\n ],\n \"glossary\": {\n \"term\": \"definition\"\n }\n },\n \"detectionRules\": [\n {\n \"id\": \"${prefix}-001\",\n \"name\": \"Rule Name\",\n \"description\": \"What this rule detects\",\n \"severity\": \"critical | serious | moderate | low | info\",\n \"patterns\": {\n \"regex\": [\"JavaScript regex patterns\"],\n \"keywords\": [\"words that indicate this issue\"],\n \"semantic\": \"Natural language description for AI detection\"\n },\n \"fix\": {\n \"description\": \"How to fix this issue\",\n \"example\": \"Code example or null\",\n \"autoFixable\": false\n },\n \"category\": \"string\"\n }\n ],\n \"prompts\": {\n \"systemPrompt\": \"You are an expert code reviewer specializing in [topic]. Your role is to...\",\n \"analysisPrompt\": \"Review this code for issues related to [topic]. Look for: ...\\\\n\\\\nCode:\\\\n\\\\\\`\\\\\\`\\\\\\`{{language}}\\\\n{{code}}\\\\n\\\\\\`\\\\\\`\\\\\\`\\\\n\\\\nFile: {{filePath}}\",\n \"fixPrompt\": \"Fix this issue: {{issue}}\\\\n\\\\nCode:\\\\n\\\\\\`\\\\\\`\\\\\\`{{language}}\\\\n{{code}}\\\\n\\\\\\`\\\\\\`\\\\\\`\"\n }\n}\n\\`\\`\\`\n\n## Guidelines\n\n1. **Core Concepts**: Extract 10-20 key concepts that are fundamental to the material\n2. **Best Practices**: Extract 10-15 recommended approaches with rationale\n3. **Anti-Patterns**: Extract 10-15 things to avoid with explanations\n4. **Detection Rules**: Generate 15-30 rules with regex patterns that could detect issues in code\n5. **Prompts**: Create prompts that embody the expertise from this document\n\nFocus on extracting actionable, code-reviewable knowledge. The agent should be able to find violations of the principles in this document.\n\n**Output ONLY the JSON object, starting with \\`{\\` and ending with \\`}\\`.**`;\n }\n \n /**\n * Format the extraction request output\n */\n private formatExtractionRequest(\n agentName: string,\n title: string,\n wordCount: number,\n chunkCount: number,\n prompt: string\n ): string {\n return `\n๐Ÿ“š **Document Parsed Successfully!**\n\n${'โ”'.repeat(50)}\n\n**Creating Agent:** \\`${agentName}\\`\n**Source Document:** ${title}\n**Word Count:** ${wordCount.toLocaleString()}\n**Processing Chunks:** ${chunkCount}\n\n${'โ”'.repeat(50)}\n\n## Next Step\n\nI've prepared the document for analysis. Please process the following prompt to extract the knowledge, then pass the result to \\`trie_save_agent\\` to save the agent.\n\n${'โ”€'.repeat(50)}\n\n${prompt}\n`;\n }\n \n private sanitizeAgentName(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '');\n }\n \n private formatDisplayName(name: string): string {\n return name\n .split(/[-_]/)\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n }\n \n private errorResponse(message: string) {\n return {\n content: [\n {\n type: 'text',\n text: `โŒ **Error:** ${message}`,\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * MCP Tool: trie_save_agent\n * \n * Saves an agent configuration after Claude has processed the document.\n * This is step 2 of the agent creation process.\n */\nexport class TrieSaveAgentTool {\n async execute(args: {\n agentConfig: {\n name: string;\n displayName: string;\n description: string;\n version?: string;\n category: string;\n };\n knowledge: {\n domain: string;\n summary: string;\n coreConcepts: Array<{\n name: string;\n description: string;\n importance: string;\n keywords?: string[];\n }>;\n bestPractices: Array<{\n name: string;\n description: string;\n rationale: string;\n codeExample?: string | null;\n }>;\n antiPatterns: Array<{\n name: string;\n description: string;\n whyBad: string;\n betterAlternative: string;\n }>;\n glossary?: Record<string, string>;\n };\n detectionRules: Array<{\n id: string;\n name: string;\n description: string;\n severity: string;\n patterns: {\n regex?: string[];\n keywords?: string[];\n semantic?: string;\n };\n fix: {\n description: string;\n example?: string | null;\n autoFixable?: boolean;\n };\n category?: string;\n }>;\n prompts: {\n systemPrompt: string;\n analysisPrompt: string;\n fixPrompt: string;\n };\n sourceFile?: string;\n }) {\n const { agentConfig, knowledge, detectionRules, prompts, sourceFile } = args;\n \n // Validate required fields\n if (!agentConfig?.name) {\n return this.errorResponse('Missing agentConfig.name');\n }\n \n if (!knowledge?.summary) {\n return this.errorResponse('Missing knowledge.summary');\n }\n \n if (!prompts?.systemPrompt) {\n return this.errorResponse('Missing prompts.systemPrompt');\n }\n \n try {\n // Build the full agent config\n const fullConfig: GeneratedAgentConfig = {\n name: this.sanitizeAgentName(agentConfig.name),\n displayName: agentConfig.displayName || this.formatDisplayName(agentConfig.name),\n description: agentConfig.description,\n version: agentConfig.version || '1.0.0',\n category: agentConfig.category || knowledge.domain || 'general',\n \n source: {\n type: 'document',\n originalFile: sourceFile || 'user-provided',\n fileType: 'txt',\n compressedAt: new Date().toISOString(),\n },\n \n systemPrompt: prompts.systemPrompt,\n analysisPrompt: prompts.analysisPrompt,\n fixPrompt: prompts.fixPrompt,\n \n activationRules: this.buildActivationRules(knowledge, detectionRules),\n \n patterns: detectionRules.map((rule, i) => {\n const fixObj: { description: string; autoFixable: boolean; example?: string } = {\n description: rule.fix?.description || 'Review and fix manually',\n autoFixable: rule.fix?.autoFixable || false,\n };\n if (rule.fix?.example) {\n fixObj.example = rule.fix.example;\n }\n return {\n id: rule.id || `CUST-${String(i + 1).padStart(3, '0')}`,\n name: rule.name,\n description: rule.description,\n severity: (rule.severity as 'critical' | 'serious' | 'moderate' | 'low' | 'info') || 'moderate',\n patterns: {\n regex: rule.patterns?.regex || [],\n keywords: rule.patterns?.keywords || [],\n semantic: rule.patterns?.semantic || '',\n },\n fix: fixObj,\n category: rule.category || agentConfig.category,\n };\n }),\n \n knowledge: {\n domain: (knowledge.domain as CompressedKnowledge['domain']) || 'general',\n summary: knowledge.summary,\n coreConcepts: knowledge.coreConcepts.map(c => ({\n name: c.name,\n description: c.description,\n importance: (c.importance as 'critical' | 'important' | 'supplementary') || 'important',\n relatedPatterns: (c as any).relatedPatterns || [],\n keywords: c.keywords || [],\n })),\n bestPractices: knowledge.bestPractices.map(bp => {\n const practice: { name: string; description: string; rationale: string; category: string; codeExample?: string } = {\n name: bp.name,\n description: bp.description,\n rationale: bp.rationale,\n category: (bp as any).category || agentConfig.category,\n };\n if (bp.codeExample) {\n practice.codeExample = bp.codeExample;\n }\n return practice;\n }),\n antiPatterns: knowledge.antiPatterns.map(ap => ({\n name: ap.name,\n description: ap.description,\n whyBad: ap.whyBad,\n betterAlternative: ap.betterAlternative,\n })),\n detectionRules: [],\n glossary: knowledge.glossary || {},\n sourceDocument: {\n title: agentConfig.displayName || agentConfig.name,\n wordCount: 0,\n compressionRatio: 0,\n },\n },\n };\n \n // Save the config\n const configPath = await this.saveAgentConfig(fullConfig);\n \n return {\n content: [\n {\n type: 'text',\n text: this.formatSuccessResponse(fullConfig, configPath),\n },\n ],\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return this.errorResponse(`Failed to save agent: ${errorMessage}`);\n }\n }\n \n private buildActivationRules(\n knowledge: { domain: string; coreConcepts: Array<{ keywords?: string[] }> },\n detectionRules: Array<{ patterns: { keywords?: string[] } }>\n ): GeneratedAgentConfig['activationRules'] {\n const domainRules: Record<string, Partial<GeneratedAgentConfig['activationRules']>> = {\n technical: {\n filePatterns: ['*.ts', '*.tsx', '*.js', '*.jsx', '*.py', '*.go', '*.rs'],\n contextSignals: ['touchesUI', 'touchesAPI'],\n priority: 2,\n },\n legal: {\n filePatterns: ['*'],\n contextSignals: ['touchesUserData', 'touchesAuth', 'touchesPayments'],\n priority: 2,\n },\n policy: {\n filePatterns: ['*'],\n contextSignals: ['touchesAuth', 'touchesAPI', 'touchesDatabase'],\n priority: 3,\n },\n security: {\n filePatterns: ['*'],\n contextSignals: ['touchesAuth', 'touchesCrypto', 'touchesAPI', 'touchesDatabase'],\n priority: 1,\n },\n architecture: {\n filePatterns: ['*.ts', '*.tsx', '*.js', '*.jsx', '*.py', '*.go'],\n contextSignals: ['touchesAPI', 'touchesDatabase'],\n priority: 2,\n },\n general: {\n filePatterns: ['*'],\n contextSignals: [],\n priority: 3,\n },\n };\n \n const defaults = domainRules[knowledge.domain] || domainRules.general!;\n \n // Extract content patterns from rules and concepts\n const contentPatterns: string[] = [];\n for (const rule of detectionRules) {\n if (rule.patterns?.keywords) {\n contentPatterns.push(...rule.patterns.keywords.slice(0, 3));\n }\n }\n for (const concept of knowledge.coreConcepts.slice(0, 5)) {\n if (concept.keywords) {\n contentPatterns.push(...concept.keywords.slice(0, 2));\n }\n }\n \n return {\n filePatterns: defaults.filePatterns || ['*'],\n contentPatterns: [...new Set(contentPatterns)].slice(0, 20),\n contextSignals: defaults.contextSignals || [],\n minConfidence: 0.3,\n priority: defaults.priority || 2,\n };\n }\n \n private async saveAgentConfig(config: GeneratedAgentConfig): Promise<string> {\n const trieDir = join(process.cwd(), '.trie', 'agents');\n await mkdir(trieDir, { recursive: true });\n \n const configPath = join(trieDir, `${config.name}.json`);\n await writeFile(configPath, JSON.stringify(config, null, 2));\n \n return configPath;\n }\n \n private formatSuccessResponse(config: GeneratedAgentConfig, configPath: string): string {\n return `\nโœ… **Agent Created Successfully!**\n\n${'โ”'.repeat(50)}\n\n**Agent Name:** \\`${config.name}\\`\n**Display Name:** ${config.displayName}\n**Category:** ${config.category}\n**Config Saved To:** \\`${configPath}\\`\n\n๐Ÿ“Š **Statistics:**\n โ€ข Core concepts: ${config.knowledge.coreConcepts.length}\n โ€ข Best practices: ${config.knowledge.bestPractices.length}\n โ€ข Anti-patterns: ${config.knowledge.antiPatterns.length}\n โ€ข Detection rules: ${config.patterns.length}\n\n๐Ÿš€ **Next Steps:**\n 1. The agent is now registered and will activate during scans\n 2. Run \\`trie_scan\\` to test the new agent\n 3. Edit \\`${configPath}\\` to customize detection rules\n\n๐Ÿ’ก **Usage:**\n The agent will automatically activate when scanning code that matches its patterns.\n Use \\`trie_list_agents\\` to see all registered agents.\n`.trim();\n }\n \n private sanitizeAgentName(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '');\n }\n \n private formatDisplayName(name: string): string {\n return name\n .split(/[-_]/)\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n }\n \n private errorResponse(message: string) {\n return {\n content: [\n {\n type: 'text',\n text: `โŒ **Error:** ${message}`,\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * MCP Tool: trie_list_agents\n * \n * Lists all registered agents including custom ones\n */\nexport class TrieListAgentsTool {\n async execute(args: { includeBuiltin?: boolean }) {\n const { includeBuiltin = true } = args;\n \n try {\n // Get custom agents\n const customAgentNames = await listCustomAgents();\n const customAgents = await Promise.all(\n customAgentNames.map(async name => {\n const config = await loadAgentConfig(name);\n return config ? {\n name: config.name,\n displayName: config.displayName,\n category: config.category,\n source: config.source.originalFile,\n patterns: config.patterns.length,\n isCustom: true,\n } : null;\n })\n );\n \n const validCustomAgents = customAgents.filter(Boolean);\n \n // Built-in agents\n const builtinAgents = includeBuiltin ? [\n { name: 'security', displayName: 'Security Agent', category: 'security', isCustom: false },\n { name: 'privacy', displayName: 'Privacy Agent', category: 'privacy', isCustom: false },\n { name: 'legal', displayName: 'Legal Agent', category: 'compliance', isCustom: false },\n { name: 'typecheck', displayName: 'TypeCheck Agent', category: 'quality', isCustom: false },\n { name: 'comprehension', displayName: 'Comprehension Agent', category: 'communication', isCustom: false },\n { name: 'design-engineer', displayName: 'Design Engineer Agent', category: 'accessibility', isCustom: false },\n { name: 'test', displayName: 'Test Agent', category: 'testing', isCustom: false },\n { name: 'software-architect', displayName: 'Software Architect Agent', category: 'architecture', isCustom: false },\n { name: 'devops', displayName: 'DevOps Agent', category: 'devops', isCustom: false },\n { name: 'bug-finding', displayName: 'Bug Finding Agent', category: 'quality', isCustom: false },\n { name: 'user-testing', displayName: 'User Testing Agent', category: 'ux', isCustom: false },\n { name: 'trie_clean', displayName: 'Trie Clean Agent', category: 'ai-code', isCustom: false },\n ] : [];\n \n // Format response\n let response = `# ๐Ÿค– Registered Agents\\n\\n`;\n \n if (builtinAgents.length > 0) {\n response += `## Built-in Agents (${builtinAgents.length})\\n\\n`;\n for (const agent of builtinAgents) {\n response += `- **${agent.displayName}** (\\`${agent.name}\\`) - ${agent.category}\\n`;\n }\n response += '\\n';\n }\n \n response += `## Custom Agents (${validCustomAgents.length})\\n\\n`;\n \n if (validCustomAgents.length === 0) {\n response += `_No custom agents created yet._\\n\\n`;\n response += `๐Ÿ’ก Create one with: \\`trie_create_agent\\`\\n`;\n response += ` - Provide a PDF, TXT, or MD file path\\n`;\n response += ` - Or paste/drag document content directly\\n`;\n } else {\n for (const agent of validCustomAgents) {\n if (agent) {\n response += `- **${agent.displayName}** (\\`${agent.name}\\`)\\n`;\n response += ` - Category: ${agent.category}\\n`;\n response += ` - Patterns: ${agent.patterns}\\n`;\n response += ` - Source: ${agent.source}\\n\\n`;\n }\n }\n }\n \n return {\n content: [\n {\n type: 'text',\n text: response,\n },\n ],\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return {\n content: [\n {\n type: 'text',\n text: `โŒ Error listing agents: ${errorMessage}`,\n },\n ],\n isError: true,\n };\n }\n }\n}\n","import { AITool } from '../types/index.js';\n\nexport function detectAITool(): AITool {\n // Check environment variables\n if (process.env.CLAUDE_CODE_VERSION) {\n return {\n name: 'claude-code',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: true,\n };\n }\n\n if (process.env.CURSOR_IDE) {\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 // Check parent process name\n const parentProcess = process.env.PARENT_PROCESS_NAME;\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 if (parentProcess?.toLowerCase().includes('opencode')) {\n return {\n name: 'opencode',\n preferredOutputFormat: 'plain-text',\n supportsDiffs: false,\n supportsInlineActions: false,\n };\n }\n\n // Default to unknown\n return {\n name: 'unknown',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n}","import { readFile } from 'fs/promises';\nimport { join } from 'path';\nimport { DEFAULT_CONFIG } from './defaults.js';\n\nexport async function loadConfig() {\n try {\n // Look for config in .trie/config.json\n const configPath = join(process.cwd(), '.trie', 'config.json');\n const configFile = await readFile(configPath, 'utf-8');\n const userConfig = JSON.parse(configFile);\n\n // Deep merge with defaults\n return mergeConfig(DEFAULT_CONFIG, userConfig);\n } catch (error) {\n // If no config found, return defaults\n console.error('No config found, using defaults');\n return DEFAULT_CONFIG;\n }\n}\n\nfunction mergeConfig(defaults: any, user: any): any {\n if (typeof user !== 'object' || user === null) {\n return defaults;\n }\n\n const result = { ...defaults };\n\n for (const [key, value] of Object.entries(user)) {\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n result[key] = mergeConfig(defaults[key] || {}, value);\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}","export const DEFAULT_CONFIG = {\n version: '1.0',\n triaging: {\n enabled: true,\n riskThresholds: {\n critical: 70,\n high: 40,\n medium: 20\n },\n autoFixConfidence: 0.95\n },\n agents: {\n builtin: {\n security: { enabled: true },\n privacy: { enabled: true },\n legal: { enabled: true },\n 'design-engineer': { enabled: true },\n 'software-architect': { enabled: true },\n comprehension: { enabled: true },\n devops: { enabled: true },\n git: { enabled: true },\n typecheck: { enabled: true },\n test: { enabled: true },\n 'user-testing': { enabled: true },\n 'bug-finding': { enabled: true }\n },\n custom: []\n },\n ai: {\n provider: 'hybrid' as const,\n cloudModel: 'claude-sonnet-4-20250514',\n localModel: 'codellama:13b',\n useLocalFor: ['privacy-sensitive', 'quick-checks']\n },\n output: {\n format: 'markdown' as const,\n verbosity: 'detailed' as const,\n showConfidenceScores: true,\n includeAgentReasonings: false\n },\n compliance: {\n standards: ['GDPR', 'HIPAA', 'SOC2'],\n generateDocumentation: true,\n auditTrail: true\n }\n} as const;"],"mappings":";;;;;;;;;;;;;;;;;;;AAEA,SAAS,cAAc;AACvB,SAAS,4BAA4B;AACrC;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAEP,SAAS,WAAAA,UAAS,YAAAC,iBAAgB;AAClC,SAAS,QAAAC,aAAY;;;ACZrB,SAAS,gBAAgB;AACzB,SAAS,kBAAkB;AAC3B,SAAS,SAAS,UAAU,SAAS,kBAAkB;AAahD,IAAM,kBAAN,MAAsB;AAAA,EAC3B,MAAM,QAAQ,MAAW;AACvB,UAAM,EAAE,MAAM,QAAQ,SAAS,QAAQ,WAAW,IAAI,QAAQ,CAAC;AAE/D,QAAI,CAAC,QAAQ,CAAC,QAAQ;AACtB,aAAO;AAAA,QACH,SAAS,CAAC;AAAA,UACR,MAAM;AAAA,UACN,MAAM,KAAK,YAAY;AAAA,QACzB,CAAC;AAAA,MACH;AAA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AAQ,EAAE;AAAA,IACjD;AAAA,EACF;AAEA,QAAM,IAAI,MAAM,qBAAqB,GAAG,EAAE;AAC5C;AAGA,OAAO,kBAAkB,4BAA4B,YAAY;AAC/D,QAAM,YAAY,MAAM,sBAAsB;AAC9C,SAAO,EAAE,UAAU;AACrB,CAAC;AAGD,OAAO,kBAAkB,2BAA2B,OAAO,YAAY;AACrE,QAAM,EAAE,IAAI,IAAI,QAAQ;AACxB,SAAO,MAAM,oBAAoB,GAAG;AACtC,CAAC;AAGD,eAAe,OAAO;AAEpB,QAAM,SAAS,aAAa;AAC5B,UAAQ,MAAM,qBAAqB,OAAO,IAAI,EAAE;AAGhD,QAAM,SAAS,MAAM,WAAW;AAChC,UAAQ,MAAM,qBAAqB,OAAO,OAAO,UAAU,OAAO,KAAK,OAAO,OAAO,OAAO,EAAE,SAAS,CAAC,kBAAkB;AAE1H,QAAM,YAAY,IAAI,qBAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAC9B,UAAQ,MAAM,kCAAkC;AAClD;AAEA,IAAI,YAAY,QAAQ,UAAU,QAAQ,KAAK,CAAC,CAAC,IAAI;AACnD,OAAK,EAAE,MAAM,CAAC,UAAU;AACtB,YAAQ,MAAM,gBAAgB,KAAK;AACnC,YAAQ,KAAK,CAAC;AAAA,EAChB,CAAC;AACH;","names":["readdir","readFile","join","readFile","existsSync","extname","relative","resolve","isAbsolute","isAbsolute","resolve","existsSync","readFile","relative","extname","join","extname","basename","existsSync","existsSync","basename","join","extname","readdir","readFile","existsSync","join","extname","isAbsolute","resolve","basename","readFile","extname","relative","basename","extname","readFile","basename","relative","SKIP_DIRS","isAbsolute","resolve","existsSync","basename","readFile","join","extname","existsSync","join","basename","extname","readFile","join","join","readFile","join","readdir","readFile"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/tools/explain.ts","../src/tools/test.ts","../src/tools/register-agent.ts","../src/tools/watch.ts","../src/tools/agent.ts","../src/ai/engine.ts","../src/knowledge/index.ts","../src/tools/create-agent.ts","../src/utils/ai-tool-detector.ts","../src/config/loader.ts","../src/config/defaults.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { 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 { readdir, readFile } from 'fs/promises';\nimport { join } from 'path';\n\nimport { TrieScanTool } from './tools/scan.js';\nimport { TrieFixTool } from './tools/fix.js';\nimport { TrieExplainTool } from './tools/explain.js';\nimport { TrieTestTool } from './tools/test.js';\nimport { TrieRegisterAgentTool } from './tools/register-agent.js';\nimport { TrieWatchTool } from './tools/watch.js';\nimport { TrieAgentTool } from './tools/agent.js';\nimport { TrieCreateAgentTool, TrieSaveAgentTool, TrieListAgentsTool } from './tools/create-agent.js';\nimport { detectAITool } from './utils/ai-tool-detector.js';\nimport { loadConfig } from './config/loader.js';\nimport { AgentRegistry } from './agents/registry.js';\n\nconst server = new Server(\n {\n name: 'trie',\n version: '1.0.0',\n description: 'Intelligent Agent Orchestration for AI Coding Tools',\n },\n {\n capabilities: {\n tools: {},\n resources: {},\n },\n }\n);\n\n// Initialize tools\nconst scanTool = new TrieScanTool();\nconst fixTool = new TrieFixTool();\nconst explainTool = new TrieExplainTool();\nconst testTool = new TrieTestTool();\nconst registerAgentTool = new TrieRegisterAgentTool();\nconst watchTool = new TrieWatchTool();\nconst agentTool = new TrieAgentTool();\nconst createAgentTool = new TrieCreateAgentTool();\nconst saveAgentTool = new TrieSaveAgentTool();\nconst listAgentsTool = new TrieListAgentsTool();\n\n// Tool definitions\nconst tools = [\n {\n name: 'scan',\n description: 'Scan code with intelligent agent selection. Scans entire codebase if no files specified.',\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 }\n } as const,\n },\n {\n name: 'trie',\n description: 'Quick menu of available Trie commands and aliases.',\n inputSchema: {\n type: 'object',\n properties: {}\n } as const,\n },\n // Alias so users can call `trie_scan` directly (no server prefix needed)\n {\n name: 'trie_scan',\n description: 'Alias for scan (same behavior as 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 }\n } as const,\n },\n {\n name: 'fix',\n description: 'Apply high-confidence fixes to code',\n inputSchema: {\n type: 'object',\n properties: {\n issueIds: {\n type: 'array',\n items: { type: 'string' },\n description: 'Specific issues to fix (empty = all high-confidence)'\n },\n autoApprove: {\n type: 'boolean',\n description: 'Skip human review for high-confidence fixes'\n }\n }\n } as const,\n },\n {\n name: 'explain',\n description: 'Explain code, issues, or changes in plain language',\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: 'test',\n description: 'Generate tests or check test coverage',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['generate', 'coverage', 'run']\n },\n files: {\n type: 'array',\n items: { type: 'string' }\n }\n },\n required: ['action', 'files']\n } as const,\n },\n {\n name: 'register_agent',\n description: 'Register a custom agent for your project',\n inputSchema: {\n type: 'object',\n properties: {\n name: { type: 'string' },\n path: {\n type: 'string',\n description: 'Path to agent implementation'\n },\n activationRules: {\n type: 'object',\n description: 'When to activate this agent'\n }\n },\n required: ['name', 'path']\n } as const,\n },\n {\n name: 'watch',\n description: 'Autonomous mode: watch for file changes and scan/fix automatically. Use yolo:true for auto-fix!',\n inputSchema: {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['start', 'stop', 'status', 'issues', 'yolo'],\n description: 'start = begin watching, stop = end, status = check, issues = list, yolo = toggle auto-fix'\n },\n directory: {\n type: 'string',\n description: 'Directory to watch (defaults to current working directory)'\n },\n yolo: {\n type: 'boolean',\n description: '๐Ÿ”ฅ YOLO MODE: Auto-fix issues as they occur! (default: false)'\n },\n debounceMs: {\n type: 'number',\n description: 'Milliseconds to wait after file change before scanning (default: 1000)'\n }\n },\n required: ['action']\n } as const,\n },\n // Individual agent commands\n {\n name: 'security',\n description: 'Run security agent: detect vulnerabilities, injection risks, auth issues, hardcoded secrets',\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan (or scans codebase)' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n },\n {\n name: 'privacy',\n description: 'Run privacy agent: PII handling, GDPR/HIPAA compliance, data encryption',\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n },\n {\n name: 'legal',\n description: 'Run legal agent: GDPR, CCPA, consent patterns, data retention compliance',\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n },\n {\n name: 'accessibility',\n description: 'Run accessibility agent: WCAG 2.1 compliance, keyboard nav, screen readers, color contrast',\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n },\n {\n name: 'architecture',\n description: 'Run architecture agent: code organization, SOLID principles, N+1 queries, scalability',\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n },\n {\n name: 'bugs',\n description: 'Run bug-finding agent: null safety, edge cases, common bugs, async issues',\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n },\n {\n name: 'ux',\n description: 'Run UX testing agent: simulate happy path, security tester, confused user, impatient user',\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n },\n {\n name: 'types',\n description: 'Run type safety agent: type errors, missing annotations, null checks',\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n },\n {\n name: 'devops',\n description: 'Run devops agent: config issues, logging, environment variables, deployment patterns',\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n },\n {\n name: 'clean',\n description: '๐Ÿงน Clean up AI-generated code: find common mistakes, bad patterns, and quick fixes',\n inputSchema: {\n type: 'object',\n properties: {\n files: { type: 'array', items: { type: 'string' }, description: 'Files to scan' },\n directory: { type: 'string', description: 'Directory to scan' },\n output: {\n type: 'string',\n enum: ['summary', 'full'],\n description: 'summary = concise (default), full = includes AI prompt/code (large output)'\n }\n }\n } as const,\n },\n // Custom agent creation tools (two-step process - no API key needed!)\n {\n name: 'create_agent',\n description: '๐Ÿ“š Step 1: Parse a document to create a custom agent. Supports file path OR drag-and-drop content. Returns extraction prompt for Claude to process.',\n inputSchema: {\n type: 'object',\n properties: {\n filePath: {\n type: 'string',\n description: 'Path to the document file (PDF, TXT, MD, or RTF)'\n },\n documentContent: {\n type: 'string',\n description: 'Raw document text (for drag-and-drop or pasted content). Use this OR filePath.'\n },\n agentName: {\n type: 'string',\n description: 'Name for the new agent (e.g., \"react-fundamentals\", \"gdpr-compliance\")'\n },\n displayName: {\n type: 'string',\n description: 'Optional display name (e.g., \"React Fundamentals Expert\")'\n },\n description: {\n type: 'string',\n description: 'Optional description of what the agent does'\n },\n category: {\n type: 'string',\n description: 'Optional category (e.g., \"react\", \"security\", \"compliance\", \"architecture\")'\n }\n },\n required: ['agentName']\n } as const,\n },\n {\n name: 'save_agent',\n description: '๐Ÿ“ฆ Step 2: Save the agent config after Claude extracts knowledge from the document. Pass the JSON output from trie_create_agent.',\n inputSchema: {\n type: 'object',\n properties: {\n agentConfig: {\n type: 'object',\n description: 'Agent configuration (name, displayName, description, category)',\n properties: {\n name: { type: 'string' },\n displayName: { type: 'string' },\n description: { type: 'string' },\n version: { type: 'string' },\n category: { type: 'string' }\n },\n required: ['name', 'category']\n },\n knowledge: {\n type: 'object',\n description: 'Extracted knowledge (domain, summary, coreConcepts, bestPractices, antiPatterns, glossary)'\n },\n detectionRules: {\n type: 'array',\n description: 'Array of detection rules with patterns and fixes'\n },\n prompts: {\n type: 'object',\n description: 'Agent prompts (systemPrompt, analysisPrompt, fixPrompt)',\n properties: {\n systemPrompt: { type: 'string' },\n analysisPrompt: { type: 'string' },\n fixPrompt: { type: 'string' }\n },\n required: ['systemPrompt', 'analysisPrompt', 'fixPrompt']\n },\n sourceFile: {\n type: 'string',\n description: 'Original source file path (optional)'\n }\n },\n required: ['agentConfig', 'knowledge', 'detectionRules', 'prompts']\n } as const,\n },\n {\n name: 'list_agents',\n description: '๐Ÿ“‹ List all registered agents including custom agents created from documents',\n inputSchema: {\n type: 'object',\n properties: {\n includeBuiltin: {\n type: 'boolean',\n description: 'Include built-in agents in the list (default: true)'\n }\n }\n } as const,\n }\n];\n\n// List tools handler\nserver.setRequestHandler(ListToolsRequestSchema, async () => {\n return {\n tools\n };\n});\n\n// Call tool handler\nserver.setRequestHandler(CallToolRequestSchema, async (request) => {\n const { name, arguments: args } = request.params;\n\n // Accept namespaced calls like \"scan:user-trie-agent\" or \"user-trie-agent/scan\"\n // and our aliases like \"trie_scan\" without forcing the server name.\n const stripNamespace = (n: string): string => {\n const parts = n.split(':');\n const base = parts[0] || n;\n const slashParts = base.split('/');\n return slashParts[slashParts.length - 1] || base;\n };\n\n const rawName = stripNamespace(name);\n const normalizedName = rawName.startsWith('trie_') ? rawName.slice('trie_'.length) : rawName;\n\n try {\n switch (normalizedName) {\n case 'trie':\n return {\n content: [\n {\n type: 'text',\n text: [\n '## Trie Menu',\n '',\n '- `trie_scan` or `scan`: Full intelligent scan (auto triage agents)',\n '- `fix`: Apply high-confidence fixes',\n '- `explain`: Explain code/issues/risks',\n '- `watch`: Watch mode (scan on change)',\n '- `security`, `privacy`, `legal`, `bugs`, `types`, `devops`, `architecture`, `ux`, `clean`: Run a specific agent',\n '- `test`: Generate/check tests',\n '- `register_agent`, `create_agent`, `save_agent`, `list_agents`: Custom agent lifecycle',\n '',\n 'You can call these without any namespace; `trie_` aliases also work.',\n ].join('\\n')\n }\n ]\n };\n case 'scan':\n return await scanTool.execute(args);\n case 'fix':\n return await fixTool.execute(args);\n case 'explain':\n return await explainTool.execute(args);\n case 'test':\n return await testTool.execute(args);\n case 'register_agent':\n return await registerAgentTool.execute(args);\n case 'watch':\n return await watchTool.execute(args);\n // Individual agent commands\n case 'security':\n return await agentTool.execute({ ...args, agent: 'security' });\n case 'privacy':\n return await agentTool.execute({ ...args, agent: 'privacy' });\n case 'legal':\n return await agentTool.execute({ ...args, agent: 'legal' });\n case 'accessibility':\n return await agentTool.execute({ ...args, agent: 'design-engineer' });\n case 'architecture':\n return await agentTool.execute({ ...args, agent: 'software-architect' });\n case 'bugs':\n return await agentTool.execute({ ...args, agent: 'bug-finding' });\n case 'ux':\n return await agentTool.execute({ ...args, agent: 'user-testing' });\n case 'types':\n return await agentTool.execute({ ...args, agent: 'typecheck' });\n case 'devops':\n return await agentTool.execute({ ...args, agent: 'devops' });\n case 'clean':\n return await agentTool.execute({ ...args, agent: 'trie_clean' });\n // Custom agent creation tools (two-step process)\n case 'create_agent':\n return await createAgentTool.execute(args as any);\n case 'save_agent':\n return await saveAgentTool.execute(args as any);\n case 'list_agents':\n return await listAgentsTool.execute(args as any);\n default:\n throw new Error(`Unknown tool: ${name}`);\n }\n } catch (error) {\n return {\n content: [\n {\n type: 'text',\n text: `Error: ${error instanceof Error ? error.message : String(error)}`\n }\n ]\n };\n }\n});\n\n// Initialize agent registry for resources\nconst agentRegistry = new AgentRegistry();\n\n// Resource definitions\ninterface Resource {\n uri: string;\n name: string;\n description?: string;\n mimeType?: string;\n}\n\n// Helper to get dynamic resources\nasync function getAvailableResources(): Promise<Resource[]> {\n const resources: Resource[] = [];\n\n // Static resources\n resources.push({\n uri: 'trie://agents',\n name: 'Available Agents',\n description: 'List of all available Trie agents (built-in and custom)',\n mimeType: 'application/json',\n });\n\n resources.push({\n uri: 'trie://config',\n name: 'Trie Configuration',\n description: 'Current Trie configuration settings',\n mimeType: 'application/json',\n });\n\n resources.push({\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 resources.push({\n uri: 'trie://signatures',\n name: 'Vulnerability Signatures',\n description: 'Summary of loaded vulnerability detection signatures',\n mimeType: 'application/json',\n });\n\n // Dynamic resources: scan reports\n try {\n const reportsDir = join(process.cwd(), 'trie-reports');\n const files = await readdir(reportsDir);\n const reportFiles = files.filter(f => f.endsWith('.txt') || f.endsWith('.json'));\n \n for (const file of reportFiles.slice(0, 10)) { // Limit to 10 most recent\n resources.push({\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 }\n } catch {\n // No reports directory yet\n }\n\n // Dynamic resources: custom agents\n try {\n await agentRegistry.loadCustomAgents();\n const customAgents = agentRegistry.getCustomAgents();\n \n for (const agent of customAgents) {\n resources.push({\n uri: `trie://agents/custom/${agent.name}`,\n name: `Custom Agent: ${agent.name}`,\n description: agent.description,\n mimeType: 'application/json',\n });\n }\n } catch {\n // No custom agents\n }\n\n return resources;\n}\n\n// Helper to read resource content\nasync function readResourceContent(uri: string): Promise<{ contents: Array<{ uri: string; mimeType?: string; text: string }> }> {\n const parsedUri = uri.replace('trie://', '');\n\n // Handle agents list\n if (parsedUri === 'agents') {\n await agentRegistry.loadCustomAgents();\n const agents = agentRegistry.getAgentDescriptions();\n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify({\n totalAgents: agents.length,\n builtinCount: agents.filter(a => !a.isCustom).length,\n customCount: agents.filter(a => a.isCustom).length,\n agents: agents.map(a => ({\n name: a.name,\n description: a.description,\n type: a.isCustom ? 'custom' : 'builtin',\n })),\n }, null, 2),\n }],\n };\n }\n\n // Handle specific custom agent\n if (parsedUri.startsWith('agents/custom/')) {\n const agentName = parsedUri.replace('agents/custom/', '');\n await agentRegistry.loadCustomAgents();\n const metadata = agentRegistry.getCustomAgentMetadata(agentName);\n \n if (!metadata) {\n throw new Error(`Custom agent not found: ${agentName}`);\n }\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(metadata, null, 2),\n }],\n };\n }\n\n // Handle configuration\n if (parsedUri === 'config') {\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 // Handle cache stats\n if (parsedUri === 'cache/stats') {\n try {\n const cachePath = join(process.cwd(), '.trie', '.trie-cache.json');\n const cacheContent = await readFile(cachePath, 'utf-8');\n const cache = JSON.parse(cacheContent);\n \n // Calculate stats without loading full cache\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 // Handle vulnerability signatures summary\n if (parsedUri === 'signatures') {\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 // Handle scan reports\n if (parsedUri.startsWith('reports/')) {\n const fileName = parsedUri.replace('reports/', '');\n const reportPath = join(process.cwd(), '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 throw new Error(`Unknown resource: ${uri}`);\n}\n\n// List resources handler\nserver.setRequestHandler(ListResourcesRequestSchema, async () => {\n const resources = await getAvailableResources();\n return { resources };\n});\n\n// Read resource handler\nserver.setRequestHandler(ReadResourceRequestSchema, async (request) => {\n const { uri } = request.params;\n return await readResourceContent(uri);\n});\n\n// Initialize and start server\nasync function main() {\n // Detect the AI tool environment\n const aiTool = detectAITool();\n console.error(`Detected AI Tool: ${aiTool.name}`);\n\n // Load configuration\n const config = await loadConfig();\n console.error(`Loaded config for ${config.agents.builtin ? Object.keys(config.agents.builtin).length : 0} built-in agents`);\n\n const transport = new StdioServerTransport();\n await server.connect(transport);\n console.error('Trie Agent MCP Server running...');\n}\n\n// Always run main() - this is the entry point\nmain().catch((error) => {\n console.error('Fatal error:', error);\n process.exit(1);\n});","import { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { extname, relative, resolve, isAbsolute } from 'path';\nimport { getPrompt, getSystemPrompt } from '../ai/prompts.js';\n\n/**\n * Explain Tool - AI-powered code explanation\n * \n * This tool provides deep explanations of:\n * - Code: What does this code do?\n * - Issues: Why is this a problem?\n * - Changes: What's the impact of these changes?\n * - Risk: What could go wrong?\n */\n\nexport class TrieExplainTool {\n async execute(args: any) {\n const { type, target, context, depth = 'standard' } = args || {};\n\n if (!type || !target) {\n return {\n content: [{\n type: 'text',\n text: this.getHelpText()\n }]\n };\n }\n\n switch (type) {\n case 'code':\n return this.explainCode(target, context, depth);\n case 'issue':\n return this.explainIssue(target, context);\n case 'change':\n return this.explainChange(target, context);\n case 'risk':\n return this.explainRisk(target, context);\n default:\n return {\n content: [{\n type: 'text',\n text: `Unknown explanation type: ${type}`\n }]\n };\n }\n }\n\n private async explainCode(target: string, context?: string, _depth?: string) {\n // Target can be a file path or inline code\n let code: string;\n let filePath: string;\n let language: string;\n\n // Check if target is a file path\n const resolvedPath = isAbsolute(target) ? target : resolve(process.cwd(), target);\n \n if (existsSync(resolvedPath)) {\n code = await readFile(resolvedPath, 'utf-8');\n filePath = relative(process.cwd(), resolvedPath);\n language = this.detectLanguage(resolvedPath);\n } else {\n // Treat as inline code\n code = target;\n filePath = 'inline';\n language = this.guessLanguage(code);\n }\n\n // For deep mode, analyze imports and dependencies\n const imports = this.extractImports(code, language);\n const exports = this.extractExports(code);\n const functions = this.extractFunctions(code, language);\n\n const prompt = getPrompt('explain', 'code', {\n code,\n language,\n filePath,\n });\n\n const systemPrompt = getSystemPrompt('explain');\n\n let output = `\\n${'โ”'.repeat(60)}\\n`;\n output += `๐Ÿ“– CODE EXPLANATION\\n`;\n output += `${'โ”'.repeat(60)}\\n\\n`;\n\n output += `## ๐Ÿ“‚ Source\\n\\n`;\n output += `- **File:** \\`${filePath}\\`\\n`;\n output += `- **Language:** ${language}\\n`;\n output += `- **Lines:** ${code.split('\\n').length}\\n\\n`;\n\n // Quick structural analysis\n output += `## ๐Ÿ” Structure Analysis\\n\\n`;\n \n if (imports.length > 0) {\n output += `**Imports (${imports.length}):**\\n`;\n for (const imp of imports.slice(0, 10)) {\n output += `- ${imp}\\n`;\n }\n if (imports.length > 10) {\n output += `- *...and ${imports.length - 10} more*\\n`;\n }\n output += '\\n';\n }\n\n if (exports.length > 0) {\n output += `**Exports (${exports.length}):**\\n`;\n for (const exp of exports) {\n output += `- ${exp}\\n`;\n }\n output += '\\n';\n }\n\n if (functions.length > 0) {\n output += `**Functions/Methods (${functions.length}):**\\n`;\n for (const fn of functions.slice(0, 15)) {\n output += `- \\`${fn}\\`\\n`;\n }\n if (functions.length > 15) {\n output += `- *...and ${functions.length - 15} more*\\n`;\n }\n output += '\\n';\n }\n\n output += `${'โ”€'.repeat(60)}\\n`;\n output += `## ๐Ÿง  Deep Explanation Request\\n\\n`;\n output += `**Role:** ${systemPrompt.split('\\n')[0]}\\n\\n`;\n output += prompt;\n output += `\\n${'โ”€'.repeat(60)}\\n`;\n\n if (context) {\n output += `\\n**Additional Context:** ${context}\\n`;\n }\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async explainIssue(target: string, _context?: string) {\n // Parse issue details (format: \"description\" or \"file:line:description\")\n let file = '';\n let line = 0;\n let issue = target;\n let severity = 'unknown';\n\n // Try to parse structured format\n const match = target.match(/^(.+?):(\\d+):(.+)$/);\n if (match) {\n file = match[1]!;\n line = parseInt(match[2]!, 10);\n issue = match[3]!.trim();\n }\n\n // Detect severity from keywords\n if (/critical|injection|rce|xss/i.test(issue)) severity = 'critical';\n else if (/serious|auth|password|secret/i.test(issue)) severity = 'serious';\n else if (/moderate|warning/i.test(issue)) severity = 'moderate';\n else severity = 'low';\n\n let codeContext = '';\n if (file && existsSync(file)) {\n const content = await readFile(file, 'utf-8');\n const lines = content.split('\\n');\n const start = Math.max(0, line - 5);\n const end = Math.min(lines.length, line + 5);\n codeContext = lines.slice(start, end).map((l, i) => {\n const lineNum = start + i + 1;\n const marker = lineNum === line ? 'โ†’ ' : ' ';\n return `${marker}${lineNum.toString().padStart(4)} | ${l}`;\n }).join('\\n');\n }\n\n const prompt = getPrompt('explain', 'issue', {\n issue,\n severity,\n filePath: file || 'unknown',\n line: String(line || '?'),\n });\n\n let output = `\\n${'โ”'.repeat(60)}\\n`;\n output += `๐Ÿ” ISSUE EXPLANATION\\n`;\n output += `${'โ”'.repeat(60)}\\n\\n`;\n\n output += `## ๐Ÿ“ Issue Details\\n\\n`;\n output += `- **Issue:** ${issue}\\n`;\n output += `- **Severity:** ${this.getSeverityIcon(severity)} ${severity}\\n`;\n if (file) output += `- **File:** \\`${file}\\`\\n`;\n if (line) output += `- **Line:** ${line}\\n`;\n output += '\\n';\n\n if (codeContext) {\n output += `## ๐Ÿ“„ Code Context\\n\\n`;\n output += `\\`\\`\\`\\n${codeContext}\\n\\`\\`\\`\\n\\n`;\n }\n\n output += `${'โ”€'.repeat(60)}\\n`;\n output += `## ๐Ÿง  Explanation Request\\n\\n`;\n output += prompt;\n output += `\\n${'โ”€'.repeat(60)}\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async explainChange(target: string, context?: string) {\n // Target is a list of changed files or a git diff\n const files = target.split(',').map(f => f.trim());\n\n let output = `\\n${'โ”'.repeat(60)}\\n`;\n output += `๐Ÿ“ CHANGE ANALYSIS\\n`;\n output += `${'โ”'.repeat(60)}\\n\\n`;\n\n output += `## ๐Ÿ“‚ Changed Files\\n\\n`;\n for (const file of files) {\n output += `- \\`${file}\\`\\n`;\n }\n output += '\\n';\n\n output += `## ๐Ÿง  Analysis Request\\n\\n`;\n output += `Analyze these changes and explain:\\n\\n`;\n output += `1. **What changed** - Summary of modifications\\n`;\n output += `2. **Why it matters** - Impact on the system\\n`;\n output += `3. **Dependencies** - What else might be affected\\n`;\n output += `4. **Testing needed** - What to test after this change\\n`;\n output += `5. **Rollback plan** - How to undo if needed\\n\\n`;\n\n if (context) {\n output += `**Context:** ${context}\\n\\n`;\n }\n\n output += `Please review the changed files and provide this analysis.\\n`;\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private async explainRisk(target: string, context?: string) {\n // Target is a file or feature description\n const resolvedPath = isAbsolute(target) ? target : resolve(process.cwd(), target);\n \n let output = `\\n${'โ”'.repeat(60)}\\n`;\n output += `โš ๏ธ RISK ASSESSMENT\\n`;\n output += `${'โ”'.repeat(60)}\\n\\n`;\n\n if (existsSync(resolvedPath)) {\n const code = await readFile(resolvedPath, 'utf-8');\n const filePath = relative(process.cwd(), resolvedPath);\n \n // Quick risk indicators\n const riskIndicators = this.detectRiskIndicators(code);\n\n output += `## ๐Ÿ“‚ Target\\n\\n`;\n output += `- **File:** \\`${filePath}\\`\\n`;\n output += `- **Lines:** ${code.split('\\n').length}\\n\\n`;\n\n if (riskIndicators.length > 0) {\n output += `## ๐Ÿšจ Risk Indicators Found\\n\\n`;\n for (const indicator of riskIndicators) {\n output += `- ${indicator}\\n`;\n }\n output += '\\n';\n }\n\n const prompt = getPrompt('explain', 'risk', {\n files: filePath,\n summary: context || 'Code change',\n });\n\n output += `${'โ”€'.repeat(60)}\\n`;\n output += `## ๐Ÿง  Risk Analysis Request\\n\\n`;\n output += prompt;\n output += `\\n${'โ”€'.repeat(60)}\\n`;\n } else {\n // Treat as a feature/change description\n output += `## ๐Ÿ“‹ Feature/Change\\n\\n`;\n output += `${target}\\n\\n`;\n\n output += `## ๐Ÿง  Risk Analysis Request\\n\\n`;\n output += `Analyze the risks of this change:\\n\\n`;\n output += `1. **Technical risks** - What could break?\\n`;\n output += `2. **Security risks** - Any vulnerabilities introduced?\\n`;\n output += `3. **Performance risks** - Any slowdowns?\\n`;\n output += `4. **Data risks** - Any data integrity concerns?\\n`;\n output += `5. **User impact** - How might users be affected?\\n`;\n output += `6. **Mitigation** - How to reduce these risks?\\n`;\n }\n\n return { content: [{ type: 'text', text: output }] };\n }\n\n private detectRiskIndicators(code: string): string[] {\n const indicators: string[] = [];\n\n const checks = [\n { pattern: /delete|drop|truncate/i, message: 'โš ๏ธ Destructive operations detected' },\n { pattern: /password|secret|key|token/i, message: '๐Ÿ” Credential handling detected' },\n { pattern: /exec|eval|spawn/i, message: '๐Ÿ’‰ Code execution patterns detected' },\n { pattern: /SELECT.*FROM|INSERT|UPDATE|DELETE/i, message: '๐Ÿ—„๏ธ Direct database operations' },\n { pattern: /fetch|axios|request|http/i, message: '๐ŸŒ External API calls detected' },\n { pattern: /process\\.env/i, message: 'โš™๏ธ Environment variable usage' },\n { pattern: /fs\\.|writeFile|readFile/i, message: '๐Ÿ“ File system operations' },\n { pattern: /setTimeout|setInterval/i, message: 'โฐ Async timing operations' },\n { pattern: /try\\s*{/i, message: '๐Ÿ›ก๏ธ Error handling present' },\n { pattern: /catch\\s*\\(/i, message: '๐Ÿ›ก๏ธ Exception handling present' },\n ];\n\n for (const { pattern, message } of checks) {\n if (pattern.test(code)) {\n indicators.push(message);\n }\n }\n\n return indicators;\n }\n\n private extractImports(code: string, _language: string): string[] {\n const imports: string[] = [];\n const lines = code.split('\\n');\n\n for (const line of lines) {\n // ES6 imports\n const es6Match = line.match(/import\\s+(?:{[^}]+}|\\*\\s+as\\s+\\w+|\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/);\n if (es6Match) {\n imports.push(es6Match[1]!);\n continue;\n }\n\n // CommonJS require\n const cjsMatch = line.match(/require\\s*\\(['\"]([^'\"]+)['\"]\\)/);\n if (cjsMatch) {\n imports.push(cjsMatch[1]!);\n continue;\n }\n\n // Python imports\n const pyMatch = line.match(/^(?:from\\s+(\\S+)\\s+)?import\\s+(\\S+)/);\n if (pyMatch && _language === 'python') {\n imports.push(pyMatch[1] || pyMatch[2]!);\n }\n }\n\n return [...new Set(imports)];\n }\n\n private extractExports(code: string): string[] {\n const exports: string[] = [];\n const lines = code.split('\\n');\n\n for (const line of lines) {\n // ES6 exports\n const es6Match = line.match(/export\\s+(?:default\\s+)?(?:class|function|const|let|var|interface|type)\\s+(\\w+)/);\n if (es6Match) {\n exports.push(es6Match[1]!);\n }\n\n // Named exports\n const namedMatch = line.match(/export\\s*\\{([^}]+)\\}/);\n if (namedMatch) {\n const names = namedMatch[1]!.split(',').map(n => n.trim().split(/\\s+as\\s+/)[0]!.trim());\n exports.push(...names);\n }\n }\n\n return [...new Set(exports)];\n }\n\n private extractFunctions(code: string, _language: string): string[] {\n const functions: string[] = [];\n const lines = code.split('\\n');\n\n for (const line of lines) {\n // Function declarations\n const funcMatch = line.match(/(?:async\\s+)?function\\s+(\\w+)/);\n if (funcMatch) {\n functions.push(funcMatch[1]!);\n continue;\n }\n\n // Arrow functions assigned to const\n const arrowMatch = line.match(/(?:const|let|var)\\s+(\\w+)\\s*=\\s*(?:async\\s*)?\\(/);\n if (arrowMatch) {\n functions.push(arrowMatch[1]!);\n continue;\n }\n\n // Class methods\n const methodMatch = line.match(/^\\s+(?:async\\s+)?(\\w+)\\s*\\([^)]*\\)\\s*(?::\\s*\\w+)?\\s*\\{/);\n if (methodMatch && !['if', 'for', 'while', 'switch', 'catch'].includes(methodMatch[1]!)) {\n functions.push(methodMatch[1]!);\n }\n }\n\n return [...new Set(functions)];\n }\n\n private detectLanguage(filePath: string): string {\n const ext = extname(filePath).toLowerCase();\n const langMap: Record<string, string> = {\n '.ts': 'typescript', '.tsx': 'tsx', '.js': 'javascript', '.jsx': 'jsx',\n '.py': 'python', '.go': 'go', '.rs': 'rust', '.java': 'java',\n '.rb': 'ruby', '.php': 'php', '.vue': 'vue', '.svelte': 'svelte',\n };\n return langMap[ext] || 'plaintext';\n }\n\n private guessLanguage(code: string): string {\n if (/import.*from|export\\s+(default|const|function|class)/.test(code)) return 'typescript';\n if (/def\\s+\\w+.*:/.test(code)) return 'python';\n if (/func\\s+\\w+.*\\{/.test(code)) return 'go';\n if (/fn\\s+\\w+.*->/.test(code)) return 'rust';\n return 'javascript';\n }\n\n private getSeverityIcon(severity: string): string {\n const icons: Record<string, string> = {\n critical: '๐Ÿ”ด',\n serious: '๐ŸŸ ',\n moderate: '๐ŸŸก',\n low: '๐Ÿ”ต',\n unknown: 'โšช',\n };\n return icons[severity] || 'โšช';\n }\n\n private getHelpText(): string {\n return `\n${'โ”'.repeat(60)}\n๐Ÿ“– TRIE EXPLAIN - AI-POWERED CODE EXPLANATION\n${'โ”'.repeat(60)}\n\n## Usage\n\n### Explain code:\n\\`\\`\\`\ntrie_explain type:\"code\" target:\"src/app.ts\"\n\\`\\`\\`\n\n### Explain an issue:\n\\`\\`\\`\ntrie_explain type:\"issue\" target:\"SQL injection vulnerability\"\n\\`\\`\\`\nor with file context:\n\\`\\`\\`\ntrie_explain type:\"issue\" target:\"src/db.ts:42:Unvalidated input\"\n\\`\\`\\`\n\n### Explain changes:\n\\`\\`\\`\ntrie_explain type:\"change\" target:\"src/auth.ts, src/user.ts\"\n\\`\\`\\`\n\n### Assess risk:\n\\`\\`\\`\ntrie_explain type:\"risk\" target:\"src/payment.ts\"\n\\`\\`\\`\nor for a feature:\n\\`\\`\\`\ntrie_explain type:\"risk\" target:\"Adding Stripe integration for payments\"\n\\`\\`\\`\n\n## Explanation Types\n\n| Type | Description |\n|------|-------------|\n| code | What does this code do? |\n| issue | Why is this a problem? |\n| change | What's the impact? |\n| risk | What could go wrong? |\n`;\n }\n}\n","import { readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { extname, relative, resolve, isAbsolute, dirname, basename, join } from 'path';\nimport { getPrompt, getSystemPrompt } from '../ai/prompts.js';\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 allUnits: { file: string; units: TestableUnit[] }[] = [];\n\n for (const file of files) {\n const resolvedPath = isAbsolute(file) ? file : resolve(process.cwd(), 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(process.cwd(), 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(process.cwd(), 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 for (const file of files) {\n const resolvedPath = isAbsolute(file) ? file : resolve(process.cwd(), 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(process.cwd(), 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(process.cwd(), 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 for (const file of files) {\n const resolvedPath = isAbsolute(file) ? file : resolve(process.cwd(), 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(process.cwd(), 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 packagePath = resolve(process.cwd(), '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(process.cwd(), 'pytest.ini')) ||\n existsSync(resolve(process.cwd(), 'pyproject.toml'))) {\n return 'pytest';\n }\n\n return 'jest'; // Default\n }\n\n private detectLanguage(filePath: string): string {\n const ext = extname(filePath).toLowerCase();\n const langMap: Record<string, string> = {\n '.ts': 'typescript', '.tsx': 'tsx', '.js': 'javascript', '.jsx': 'jsx',\n '.py': 'python', '.go': 'go', '.rs': 'rust',\n };\n return langMap[ext] || 'javascript';\n }\n\n private getHelpText(): string {\n return `\n${'โ”'.repeat(60)}\n๐Ÿงช TRIE TEST - AI-POWERED TEST GENERATION\n${'โ”'.repeat(60)}\n\n## Usage\n\n### Generate tests:\n\\`\\`\\`\ntrie_test action:\"generate\" files:[\"src/utils.ts\"]\n\\`\\`\\`\n\n### Analyze coverage:\n\\`\\`\\`\ntrie_test action:\"coverage\" files:[\"src/utils.ts\"]\n\\`\\`\\`\n\n### Get test suggestions:\n\\`\\`\\`\ntrie_test action:\"suggest\" files:[\"src/app.ts\"]\n\\`\\`\\`\n\n### Get run commands:\n\\`\\`\\`\ntrie_test action:\"run\" files:[\"src/utils.test.ts\"]\n\\`\\`\\`\n\n## Options\n\n| Option | Values | Description |\n|--------|--------|-------------|\n| action | generate, coverage, suggest, run | What to do |\n| files | Array of paths | Files to analyze |\n| framework | jest, vitest, mocha, pytest | Test framework |\n| style | unit, integration, e2e, all | Test style |\n`;\n }\n}\n","export class TrieRegisterAgentTool {\n async execute(args: any) {\n const { name, path } = args;\n\n // TODO: Implement register agent functionality\n return {\n content: [\n {\n type: 'text',\n text: `๐Ÿค– Register agent tool called with name: ${name}, path: ${path}\\n\\nTODO: Implement register agent functionality`\n }\n ]\n };\n }\n}","import { watch } from 'fs';\nimport { stat } from 'fs/promises';\nimport { join, extname, basename } from 'path';\nimport { existsSync } from 'fs';\nimport { TrieScanTool } from './scan.js';\nimport { TrieFixTool } from './fix.js';\n\n// File extensions to watch\nconst WATCH_EXTENSIONS = new Set([\n '.ts', '.tsx', '.js', '.jsx', '.mjs',\n '.vue', '.svelte', '.astro',\n '.py', '.go', '.rs'\n]);\n\n// Directories to skip\nconst SKIP_DIRS = new Set([\n 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt',\n 'coverage', '.turbo', '.cache'\n]);\n\ninterface WatchState {\n isRunning: boolean;\n yoloMode: boolean; // Auto-fix everything!\n lastScan: Map<string, number>; // file -> last scan timestamp\n pendingFiles: Set<string>;\n scanDebounceTimer: NodeJS.Timeout | null;\n issueCache: Map<string, any[]>; // file -> issues\n totalIssuesFound: number;\n totalIssuesFixed: number;\n filesScanned: number;\n}\n\nexport class TrieWatchTool {\n private scanTool = new TrieScanTool();\n private fixTool = new TrieFixTool();\n private state: WatchState = {\n isRunning: false,\n yoloMode: false,\n lastScan: new Map(),\n pendingFiles: new Set(),\n scanDebounceTimer: null,\n issueCache: new Map(),\n totalIssuesFound: 0,\n totalIssuesFixed: 0,\n filesScanned: 0\n };\n private watchers: Map<string, ReturnType<typeof watch>> = new Map();\n\n async execute(args: any) {\n const { action, directory, debounceMs = 1000, yolo = false } = args;\n\n switch (action) {\n case 'start':\n return this.startWatching(directory || process.cwd(), debounceMs, yolo);\n case 'stop':\n return this.stopWatching();\n case 'status':\n return this.getStatus();\n case 'issues':\n return this.getCurrentIssues();\n case 'yolo':\n return this.toggleYoloMode();\n default:\n return {\n content: [{\n type: 'text',\n text: `Unknown action: ${action}. Use 'start', 'stop', 'status', 'issues', or 'yolo'.`\n }]\n };\n }\n }\n\n private async startWatching(directory: string, debounceMs: number, yoloMode: boolean) {\n if (this.state.isRunning) {\n return {\n content: [{\n type: 'text',\n text: 'โš ๏ธ Watch mode is already running. Use `trie_watch stop` to stop it first.'\n }]\n };\n }\n\n this.state.isRunning = true;\n this.state.yoloMode = yoloMode;\n this.state.issueCache.clear();\n this.state.totalIssuesFound = 0;\n this.state.totalIssuesFixed = 0;\n this.state.filesScanned = 0;\n\n const modeEmoji = yoloMode ? '๐Ÿ”ฅ' : '๐Ÿ‘๏ธ';\n const modeName = yoloMode ? 'YOLO MODE' : 'WATCH MODE';\n\n console.error('\\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”');\n console.error(`${modeEmoji} TRIE AGENT - AUTONOMOUS ${modeName}`);\n console.error('โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\\n');\n console.error(`๐Ÿ“‚ Watching: ${directory}`);\n console.error(`โฑ๏ธ Debounce: ${debounceMs}ms`);\n if (yoloMode) {\n console.error('๐Ÿ”ฅ YOLO MODE: Auto-fixing issues as they occur!');\n }\n console.error('');\n\n // Start watching the directory recursively\n await this.watchDirectory(directory, debounceMs);\n\n // Do an initial scan\n console.error('๐Ÿ” Running initial scan...\\n');\n const initialResult = await this.scanTool.execute({ directory });\n\n const yoloMessage = yoloMode ? `\n### ๐Ÿ”ฅ YOLO MODE ENABLED\nIssues will be **automatically fixed** as they're detected!\n- High-confidence fixes applied immediately\n- No confirmation needed\n- Living on the edge ๐Ÿš€\n\n` : `\n### ๐Ÿ’ก Want auto-fixes?\nRun \\`trie_watch yolo\\` to enable YOLO mode and auto-fix issues as they occur!\n\n`;\n\n return {\n content: [{\n type: 'text',\n text: `${modeEmoji} **AUTONOMOUS ${modeName} ACTIVATED**\n\nTrie Agent is now watching for file changes and will automatically scan them.\n\n**Watching:** \\`${directory}\\`\n**Debounce:** ${debounceMs}ms (waits for you to stop typing)\n**YOLO Mode:** ${yoloMode ? '๐Ÿ”ฅ ON - Auto-fixing!' : 'โŒ OFF'}\n\n### How it works:\n1. ๐Ÿ“ You write/edit code\n2. ๐Ÿ‘๏ธ Trie detects the change\n3. ๐Ÿ” Automatically scans the modified file\n4. ${yoloMode ? '๐Ÿ”ง Auto-fixes issues immediately!' : '๐Ÿšจ Reports issues immediately'}\n${yoloMessage}\n### Commands:\n- \\`trie_watch status\\` - See current watch status\n- \\`trie_watch yolo\\` - Toggle YOLO mode (auto-fix)\n- \\`trie_watch issues\\` - Get all issues found so far \n- \\`trie_watch stop\\` - Stop autonomous mode\n\n---\n\n${initialResult.content?.[0]?.text || 'Initial scan complete.'}`\n }]\n };\n }\n\n private toggleYoloMode() {\n if (!this.state.isRunning) {\n return {\n content: [{\n type: 'text',\n text: `โš ๏ธ Watch mode is not running. Start it first with:\n \n\\`trie_watch start\\` - Normal mode\n\\`trie_watch start yolo:true\\` - YOLO mode from the start`\n }]\n };\n }\n\n this.state.yoloMode = !this.state.yoloMode;\n\n if (this.state.yoloMode) {\n console.error('\\n๐Ÿ”ฅ YOLO MODE ACTIVATED! Auto-fixing issues as they occur...\\n');\n return {\n content: [{\n type: 'text',\n text: `๐Ÿ”ฅ **YOLO MODE ACTIVATED**\n\nIssues will now be **automatically fixed** as they're detected!\n\nโš ๏ธ **Warning:** This will modify your files without confirmation.\n- High-confidence fixes only\n- Backs up original code in memory\n- You can always undo with git\n\nRun \\`trie_watch yolo\\` again to disable.`\n }]\n };\n } else {\n console.error('\\n๐Ÿ‘๏ธ YOLO mode disabled. Back to watch-only mode.\\n');\n return {\n content: [{\n type: 'text',\n text: `๐Ÿ‘๏ธ **YOLO MODE DISABLED**\n\nBack to normal watch mode. Issues will be reported but not auto-fixed.\n\nRun \\`trie_watch yolo\\` to re-enable.`\n }]\n };\n }\n }\n\n private async watchDirectory(dir: string, debounceMs: number) {\n if (!existsSync(dir)) return;\n\n try {\n const dirStat = await stat(dir);\n if (!dirStat.isDirectory()) return;\n\n // Skip ignored directories\n const dirName = basename(dir);\n if (SKIP_DIRS.has(dirName) || dirName.startsWith('.')) return;\n\n // Watch this directory\n const watcher = watch(dir, { persistent: true }, async (_eventType, filename) => {\n if (!filename) return;\n \n const fullPath = join(dir, filename);\n const ext = extname(filename).toLowerCase();\n\n // Only watch relevant file types\n if (!WATCH_EXTENSIONS.has(ext)) return;\n\n // Skip if file doesn't exist (was deleted)\n if (!existsSync(fullPath)) return;\n\n // Add to pending files\n this.state.pendingFiles.add(fullPath);\n\n // Debounce the scan\n if (this.state.scanDebounceTimer) {\n clearTimeout(this.state.scanDebounceTimer);\n }\n\n this.state.scanDebounceTimer = setTimeout(() => {\n this.processPendingFiles();\n }, debounceMs);\n });\n\n this.watchers.set(dir, watcher);\n\n // Recursively watch subdirectories\n const { readdir } = await import('fs/promises');\n const entries = await readdir(dir, { withFileTypes: true });\n \n for (const entry of entries) {\n if (entry.isDirectory()) {\n await this.watchDirectory(join(dir, entry.name), debounceMs);\n }\n }\n } catch (error) {\n // Skip directories we can't access\n }\n }\n\n private async processPendingFiles() {\n if (this.state.pendingFiles.size === 0) return;\n\n const files = Array.from(this.state.pendingFiles);\n this.state.pendingFiles.clear();\n\n const modeEmoji = this.state.yoloMode ? '๐Ÿ”ฅ' : '๐Ÿ‘๏ธ';\n console.error(`\\n${modeEmoji} Detected changes in ${files.length} file(s):`);\n for (const file of files) {\n console.error(` โ€ข ${basename(file)}`);\n }\n console.error('');\n\n try {\n // Scan the changed files\n const result = await this.scanTool.execute({ files });\n \n // Parse issues from result\n const resultText = result.content?.[0]?.text || '';\n \n // Update stats\n this.state.filesScanned += files.length;\n\n // Extract issue count from result (simple regex)\n const issueMatch = resultText.match(/(\\d+) total/);\n if (issueMatch?.[1] !== undefined) {\n const newIssues = parseInt(issueMatch[1], 10);\n this.state.totalIssuesFound += newIssues;\n\n if (newIssues > 0) {\n console.error(`\\n๐Ÿšจ Found ${newIssues} issues in changed files!`);\n \n // Log a summary\n const criticalMatch = resultText.match(/(\\d+) CRITICAL/);\n const seriousMatch = resultText.match(/(\\d+) SERIOUS/);\n const moderateMatch = resultText.match(/(\\d+) MODERATE/);\n \n if (criticalMatch) {\n console.error(` ๐Ÿ”ด ${criticalMatch[1]} critical issues`);\n }\n if (seriousMatch) {\n console.error(` ๐ŸŸ  ${seriousMatch[1]} serious issues`);\n }\n if (moderateMatch) {\n console.error(` ๐ŸŸก ${moderateMatch[1]} moderate issues`);\n }\n\n // ๐Ÿ”ฅ YOLO MODE: Auto-fix!\n if (this.state.yoloMode) {\n console.error('\\n๐Ÿ”ฅ YOLO MODE: Attempting auto-fix...');\n await this.autoFixIssues(files);\n } else {\n console.error('\\n๐Ÿ’ก Run `trie_watch yolo` to auto-fix issues');\n }\n } else {\n console.error(' โœ… No issues found - code looks good!');\n }\n }\n\n // Cache issues for each file\n for (const file of files) {\n this.state.lastScan.set(file, Date.now());\n }\n\n } catch (error) {\n console.error(`โŒ Scan error: ${error}`);\n }\n }\n\n private async autoFixIssues(files: string[]) {\n try {\n // Call the fix tool with auto-approve for high-confidence fixes\n const fixResult = await this.fixTool.execute({\n files,\n autoApprove: true,\n minConfidence: 0.8 // Only fix high-confidence issues\n });\n\n const fixText = fixResult.content?.[0]?.text || '';\n \n // Parse how many were fixed\n const fixedMatch = fixText.match(/(\\d+) issues? fixed/i);\n if (fixedMatch?.[1] !== undefined) {\n const fixed = parseInt(fixedMatch[1], 10);\n this.state.totalIssuesFixed += fixed;\n console.error(` โœ… Auto-fixed ${fixed} issues!`);\n } else if (fixText.includes('No issues')) {\n console.error(' โ„น๏ธ No auto-fixable issues found');\n } else {\n // Show first line of result\n const firstLine = fixText.split('\\n')[0];\n console.error(` ๐Ÿ”ง ${firstLine}`);\n }\n } catch (error) {\n console.error(` โš ๏ธ Auto-fix error: ${error}`);\n }\n }\n\n private stopWatching() {\n if (!this.state.isRunning) {\n return {\n content: [{\n type: 'text',\n text: 'โš ๏ธ Watch mode is not running.'\n }]\n };\n }\n\n // Close all watchers\n for (const [_dir, watcher] of this.watchers) {\n watcher.close();\n }\n this.watchers.clear();\n\n // Clear state\n if (this.state.scanDebounceTimer) {\n clearTimeout(this.state.scanDebounceTimer);\n }\n \n const wasYolo = this.state.yoloMode;\n this.state.isRunning = false;\n this.state.yoloMode = false;\n\n const modeEmoji = wasYolo ? '๐Ÿ”ฅ' : '๐Ÿ‘๏ธ';\n console.error(`\\n${modeEmoji} Watch mode stopped.\\n`);\n\n const yoloStats = wasYolo ? `\n- ๐Ÿ”ฅ **Issues auto-fixed: ${this.state.totalIssuesFixed}**` : '';\n\n return {\n content: [{\n type: 'text',\n text: `${modeEmoji} **AUTONOMOUS MODE STOPPED**\n\n### Session Summary:\n- Files scanned: ${this.state.filesScanned}\n- Total issues found: ${this.state.totalIssuesFound}${yoloStats}\n- Directories watched: ${this.watchers.size}\n${wasYolo ? `\\n๐Ÿ”ฅ YOLO mode was ON - issues were auto-fixed as they occurred!` : ''}\n\nUse \\`trie_watch start\\` to start watching again.\nUse \\`trie_watch start yolo:true\\` for YOLO mode.`\n }]\n };\n }\n\n private getStatus() {\n if (!this.state.isRunning) {\n return {\n content: [{\n type: 'text',\n text: `๐Ÿ‘๏ธ **Watch Mode Status: STOPPED**\n\nUse \\`trie_watch start\\` to begin autonomous scanning.\nUse \\`trie_watch start yolo:true\\` for YOLO mode (auto-fix).`\n }]\n };\n }\n\n const modeEmoji = this.state.yoloMode ? '๐Ÿ”ฅ' : '๐Ÿ‘๏ธ';\n const modeName = this.state.yoloMode ? 'YOLO MODE' : 'WATCH MODE';\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 yoloStats = this.state.yoloMode ? `\n- ๐Ÿ”ฅ Issues auto-fixed: ${this.state.totalIssuesFixed}` : '';\n\n return {\n content: [{\n type: 'text',\n text: `${modeEmoji} **${modeName} Status: RUNNING**\n\n### Stats:\n- Directories watched: ${this.watchers.size}\n- Files scanned this session: ${this.state.filesScanned}\n- Total issues found: ${this.state.totalIssuesFound}${yoloStats}\n- Pending files: ${this.state.pendingFiles.size}\n- YOLO Mode: ${this.state.yoloMode ? '๐Ÿ”ฅ ON' : 'โŒ OFF'}\n\n### Recently Scanned:\n${recentScans || '(none yet)'}\n\n### Commands:\n- \\`trie_watch yolo\\` - ${this.state.yoloMode ? 'Disable' : 'Enable'} YOLO mode\n- \\`trie_watch issues\\` - Get all issues found\n- \\`trie_watch stop\\` - Stop watching`\n }]\n };\n }\n\n private getCurrentIssues() {\n return {\n content: [{\n type: 'text',\n text: `๐Ÿ“‹ **Issues Found This Session**\n\nTotal issues: ${this.state.totalIssuesFound}\nFiles scanned: ${this.state.filesScanned}\n\nTo get a full report, run \\`trie_scan\\` on your codebase.`\n }]\n };\n }\n}\n\n","import { readdir, readFile } from 'fs/promises';\nimport { existsSync } from 'fs';\nimport { join, extname, isAbsolute, resolve, basename } from 'path';\nimport { AgentRegistry } from '../agents/registry.js';\nimport { buildAnalysis, formatAnalysisResponse } from '../ai/engine.js';\nimport { lookupKnowledge } from '../knowledge/index.js';\nimport type { Issue } from '../types/index.js';\nimport type { AgentName } from '../ai/prompts.js';\n\n// File extensions to scan\nconst SCANNABLE_EXTENSIONS = new Set([\n '.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs',\n '.vue', '.svelte', '.astro',\n '.py', '.go', '.rs'\n]);\n\n// Directories to skip\nconst SKIP_DIRS = new Set([\n 'node_modules', '.git', 'dist', 'build', '.next', '.nuxt',\n 'coverage', '.nyc_output', '__pycache__', '.pytest_cache',\n 'vendor', '.venv', 'venv', 'target', '.turbo', '.cache'\n]);\n\n// Map agent names to AI engine agent types\nconst AGENT_TO_AI_TYPE: Record<string, AgentName> = {\n 'security': 'security',\n 'privacy': 'privacy',\n 'legal': 'legal',\n 'design-engineer': 'accessibility',\n 'software-architect': 'architecture',\n 'bug-finding': 'bugs',\n 'user-testing': 'ux',\n 'typecheck': 'types',\n 'devops': 'devops',\n 'comprehension': 'explain',\n 'test': 'test',\n 'trie_clean': 'vibe',\n};\n\n/**\n * Tool for running individual agents with AI-powered analysis\n */\nexport class TrieAgentTool {\n private agentRegistry = new AgentRegistry();\n\n async execute(args: any) {\n const { agent, files, directory, depth = 'standard', lookup, output = 'full' } = args;\n\n // Handle knowledge lookup requests\n if (lookup) {\n return this.handleKnowledgeLookup(lookup);\n }\n\n if (!agent) {\n return this.listAgents();\n }\n\n const agentInstance = this.agentRegistry.getAgent(agent);\n if (!agentInstance) {\n return {\n content: [{\n type: 'text',\n text: `โŒ Agent not found: ${agent}\\n\\nAvailable agents:\\n${this.agentRegistry.getAgentNames().map(n => `- ${n}`).join('\\n')}`\n }]\n };\n }\n\n // Discover files if not specified\n let filesToScan = files || [];\n if (!filesToScan.length) {\n const scanDir = directory || process.cwd();\n console.error(`\\n๐Ÿ” Discovering files in: ${scanDir}`);\n filesToScan = await this.discoverFiles(scanDir);\n console.error(` Found ${filesToScan.length} files\\n`);\n } else {\n // Resolve paths\n filesToScan = filesToScan.map((f: string) => \n isAbsolute(f) ? f : resolve(process.cwd(), f)\n );\n }\n\n // Validate files exist\n const validFiles = filesToScan.filter((f: string) => existsSync(f));\n if (validFiles.length === 0) {\n return {\n content: [{\n type: 'text',\n text: `โŒ No valid files found to scan.`\n }]\n };\n }\n\n const startTime = Date.now();\n \n // Determine AI agent type\n const aiAgentType = AGENT_TO_AI_TYPE[agent];\n \n if (aiAgentType) {\n // Use AI-powered analysis\n return this.runAIAnalysis(\n aiAgentType,\n validFiles,\n agentInstance.name,\n agentInstance.description,\n depth,\n output\n );\n } else {\n // Fallback to static analysis\n return this.runStaticAnalysis(agentInstance, validFiles, startTime);\n }\n }\n\n private async runAIAnalysis(\n agentType: AgentName, \n files: string[], \n agentName: string,\n agentDescription: string,\n depth: string,\n outputMode: string\n ) {\n const startTime = Date.now();\n\n console.error(`\\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”`);\n console.error(`๐Ÿง  Running AI-POWERED ${agentName.toUpperCase()} analysis`);\n console.error(`โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\\n`);\n console.error(`๐Ÿ“„ ${agentDescription}`);\n console.error(`๐Ÿ“‚ Analyzing ${files.length} files (${depth} depth)...\\n`);\n\n try {\n // Build AI analysis\n const analysis = await buildAnalysis({\n agent: agentType,\n files,\n depth: depth as 'quick' | 'standard' | 'deep',\n });\n\n const executionTime = Date.now() - startTime;\n\n // Format the response\n const includePrompt = outputMode === 'full';\n let output = formatAnalysisResponse(analysis, { includePrompt });\n\n // Add knowledge lookup suggestions based on follow-ups\n if (analysis.suggestedFollowUps.length > 0) {\n output += this.generateKnowledgeSuggestions(analysis.suggestedFollowUps, agentType);\n }\n\n output += `\\n*Analysis completed in ${(executionTime / 1000).toFixed(2)}s*\\n`;\n\n return {\n content: [{\n type: 'text',\n text: output\n }]\n };\n } catch (error) {\n return {\n content: [{\n type: 'text',\n text: `โŒ Analysis error: ${error instanceof Error ? error.message : String(error)}`\n }]\n };\n }\n }\n\n private async runStaticAnalysis(agentInstance: any, files: string[], startTime: number) {\n console.error(`\\nโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”`);\n console.error(`๐Ÿ” Running ${agentInstance.name.toUpperCase()} static analysis`);\n console.error(`โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”\\n`);\n console.error(`๐Ÿ“„ ${agentInstance.description}`);\n console.error(`๐Ÿ“‚ Scanning ${files.length} files...\\n`);\n\n try {\n const result = await agentInstance.scan(files, { workingDir: process.cwd() });\n const executionTime = Date.now() - startTime;\n\n return {\n content: [{\n type: 'text',\n text: await this.formatStaticResult(agentInstance.name, result.issues, files, executionTime)\n }]\n };\n } catch (error) {\n return {\n content: [{\n type: 'text',\n text: `โŒ Agent error: ${error instanceof Error ? error.message : String(error)}`\n }]\n };\n }\n }\n\n private generateKnowledgeSuggestions(followUps: string[], agentType: AgentName): string {\n if (followUps.length === 0) {\n return '';\n }\n \n let output = `\\n## ๐Ÿ”— Suggested Follow-ups\\n\\n`;\n\n for (const followUp of followUps) {\n output += `- ${followUp}\\n`;\n }\n\n if (agentType === 'security') {\n output += `- **CVE Check**: Run \\`trie_security lookup:\"cve\" query:\"[library-name]\"\\` to check for vulnerabilities\\n`;\n }\n\n return output;\n }\n\n private handleKnowledgeLookup(lookup: { type: string; query: string; context?: Record<string, string> }) {\n const result = lookupKnowledge({\n type: lookup.type as any,\n query: lookup.query,\n context: lookup.context ?? {},\n });\n\n return {\n content: [{\n type: 'text',\n text: result\n }]\n };\n }\n\n private listAgents() {\n const agents = this.agentRegistry.getAgentDescriptions();\n \n const agentList = agents.map(a => {\n const command = this.getAgentCommand(a.name);\n const aiPowered = AGENT_TO_AI_TYPE[a.name] ? '๐Ÿง ' : '๐Ÿ”';\n return `| \\`${command}\\` | ${aiPowered} ${a.name} | ${a.description} |`;\n }).join('\\n');\n\n return {\n content: [{\n type: 'text',\n text: `# ๐Ÿค– Available Agents\n\n| Command | Agent | Description |\n|---------|-------|-------------|\n${agentList}\n\n**Legend:** ๐Ÿง  = AI-powered deep analysis, ๐Ÿ” = Static pattern matching\n\n## Usage\n\n### Run a specific agent:\n\\`\\`\\`\ntrie_security # Security vulnerabilities\ntrie_privacy # Privacy/GDPR compliance \ntrie_accessibility # WCAG accessibility audit\ntrie_bugs # Bug detection\ntrie_ux # User experience testing\ntrie_types # Type safety analysis\ntrie_architecture # Architecture review\ntrie_devops # DevOps readiness\ntrie_legal # Legal compliance\n\\`\\`\\`\n\n### With options:\n\\`\\`\\`\ntrie_security files:[\"src/auth.ts\"] depth:\"deep\"\n\\`\\`\\`\n\n### Knowledge lookup:\n\\`\\`\\`\ntrie_security lookup:{type:\"cve\", query:\"lodash\"}\ntrie_security lookup:{type:\"docs\", query:\"XSS prevention\", context:{framework:\"react\"}}\n\\`\\`\\`\n\n### Run all agents:\n\\`\\`\\`\ntrie_scan # Full scan with smart triaging\n\\`\\`\\``\n }]\n };\n }\n\n private getAgentCommand(agentName: string): string {\n const commandMap: Record<string, string> = {\n 'security': 'trie_security',\n 'privacy': 'trie_privacy',\n 'legal': 'trie_legal',\n 'design-engineer': 'trie_accessibility',\n 'software-architect': 'trie_architecture',\n 'bug-finding': 'trie_bugs',\n 'user-testing': 'trie_ux',\n 'typecheck': 'trie_types',\n 'devops': 'trie_devops',\n 'comprehension': 'trie_explain',\n 'test': 'trie_test'\n };\n return commandMap[agentName] || `trie_scan --agent ${agentName}`;\n }\n\n private async formatStaticResult(agentName: string, issues: Issue[], files: string[], executionTime: number): Promise<string> {\n const critical = issues.filter(i => i.severity === 'critical').length;\n const serious = issues.filter(i => i.severity === 'serious').length;\n const moderate = issues.filter(i => i.severity === 'moderate').length;\n const low = issues.filter(i => i.severity === 'low').length;\n\n const agentEmoji = this.getAgentEmoji(agentName);\n\n let output = `\\n`;\n output += `# ${agentEmoji} ${agentName.toUpperCase()} SCAN\\n\\n`;\n output += `**Files:** ${files.length} | **Time:** ${(executionTime / 1000).toFixed(2)}s\\n\\n`;\n\n if (issues.length === 0) {\n output += `## โœ… No Issues Found\\n\\n`;\n output += `Your code passed all ${agentName} checks.\\n\\n`;\n return output;\n }\n\n // Count by severity\n output += `## ๐ŸŽฏ ${issues.length} Issues Found\\n\\n`;\n if (critical > 0) output += `๐Ÿ”ด ${critical} Critical `;\n if (serious > 0) output += `๐ŸŸ  ${serious} Serious `;\n if (moderate > 0) output += `๐ŸŸก ${moderate} Moderate `;\n if (low > 0) output += `๐Ÿ”ต ${low} Low`;\n output += `\\n\\n`;\n\n // Sort by severity\n const sorted = [...issues].sort((a, b) => {\n const severityOrder = { critical: 0, serious: 1, moderate: 2, low: 3 };\n if (severityOrder[a.severity] !== severityOrder[b.severity]) {\n return severityOrder[a.severity] - severityOrder[b.severity];\n }\n return (a.line || 0) - (b.line || 0);\n });\n\n // Show each issue with code snippet and fix prompt\n for (const issue of sorted) {\n const icon = { critical: '๐Ÿ”ด', serious: '๐ŸŸ ', moderate: '๐ŸŸก', low: '๐Ÿ”ต' }[issue.severity];\n \n output += `---\\n\\n`;\n output += `${icon} **${issue.issue}**\\n\\n`;\n output += `๐Ÿ“ \\`${issue.file}:${issue.line || '?'}\\`\\n\\n`;\n \n // Get code snippet\n const snippet = await this.getCodeSnippet(issue.file, issue.line);\n if (snippet) {\n output += `\\`\\`\\`\\n${snippet}\\n\\`\\`\\`\\n\\n`;\n }\n \n output += `**Fix:** ${issue.fix}\\n\\n`;\n \n if (issue.cwe) output += `CWE: ${issue.cwe}\\n`;\n if (issue.regulation) output += `Regulation: ${issue.regulation}\\n`;\n \n // Generate fix prompt\n output += `<details>\\n<summary>๐Ÿ’ฌ Prompt to fix this</summary>\\n\\n`;\n output += `\\`\\`\\`\\nFix the ${issue.issue.toLowerCase()} in ${basename(issue.file)}${issue.line ? ` at line ${issue.line}` : ''}.\\n\\n${issue.fix}\\n\\`\\`\\`\\n\\n`;\n output += `</details>\\n\\n`;\n }\n\n output += `---\\n`;\n output += `*${agentName} scan completed in ${(executionTime / 1000).toFixed(2)}s*\\n`;\n\n return output;\n }\n\n /**\n * Get a code snippet around a specific line\n */\n private async getCodeSnippet(filePath: string, line: number | undefined): Promise<string | null> {\n if (!line || !existsSync(filePath)) return null;\n \n try {\n const content = await readFile(filePath, 'utf-8');\n const lines = content.split('\\n');\n const start = Math.max(0, line - 3);\n const end = Math.min(lines.length, line + 2);\n \n return lines.slice(start, end).map((l, idx) => {\n const lineNum = start + idx + 1;\n const marker = lineNum === line ? 'โ†’' : ' ';\n return `${marker} ${lineNum.toString().padStart(4)} | ${l}`;\n }).join('\\n');\n } catch {\n return null;\n }\n }\n\n private getAgentEmoji(agentName: string): string {\n const emojis: Record<string, string> = {\n 'security': '๐Ÿ”’',\n 'privacy': '๐Ÿ‘ค',\n 'legal': 'โš–๏ธ',\n 'design-engineer': 'โ™ฟ',\n 'software-architect': '๐Ÿ—๏ธ',\n 'bug-finding': '๐Ÿ›',\n 'user-testing': '๐ŸŽฏ',\n 'typecheck': '๐Ÿ“',\n 'devops': 'โš™๏ธ',\n 'comprehension': '๐Ÿ“–',\n 'test': '๐Ÿงช'\n };\n return emojis[agentName] || '๐Ÿค–';\n }\n\n private async discoverFiles(dir: string, maxFiles: number = 200): Promise<string[]> {\n const files: string[] = [];\n \n async function walk(currentDir: string) {\n if (files.length >= maxFiles) return;\n \n try {\n const entries = await readdir(currentDir, { withFileTypes: true });\n \n for (const entry of entries) {\n if (files.length >= maxFiles) break;\n \n const fullPath = join(currentDir, entry.name);\n \n if (entry.isDirectory()) {\n if (!SKIP_DIRS.has(entry.name) && !entry.name.startsWith('.')) {\n await walk(fullPath);\n }\n } else if (entry.isFile()) {\n const ext = extname(entry.name).toLowerCase();\n if (SCANNABLE_EXTENSIONS.has(ext)) {\n files.push(fullPath);\n }\n }\n }\n } catch (error) {\n // Skip directories we can't read\n }\n }\n \n await walk(dir);\n return files;\n }\n}\n","import { readFile } from 'fs/promises';\nimport { extname, relative, basename } from 'path';\nimport { getPrompt, getSystemPrompt, AgentName } from './prompts.js';\n\n/**\n * AI Engine - Generates rich prompts for Claude to analyze code\n * \n * KEY INSIGHT: This is an MCP tool. We don't call an LLM API - we return\n * structured output that Claude (the host AI) will read and act on.\n * \n * The goal is to:\n * 1. Read and understand the code context\n * 2. Build comprehensive prompts that give Claude everything it needs\n * 3. Format output so Claude can provide actionable analysis\n */\n\nexport interface AnalysisRequest {\n agent: AgentName;\n files: string[];\n context?: Record<string, string>;\n depth?: 'quick' | 'standard' | 'deep';\n}\n\nexport interface AnalysisResult {\n agent: string;\n prompt: string;\n systemPrompt: string;\n codeContext: CodeContext[];\n suggestedFollowUps: string[];\n filesSummary: string;\n}\n\nexport interface CodeContext {\n filePath: string;\n relativePath: string;\n language: string;\n content: string;\n lineCount: number;\n summary?: FileSummary;\n}\n\nexport interface FileSummary {\n hasAuth: boolean;\n hasDatabase: boolean;\n hasUserInput: boolean;\n hasFileOps: boolean;\n hasCrypto: boolean;\n hasExternalAPIs: boolean;\n framework?: string;\n exports: string[];\n imports: string[];\n}\n\n/**\n * Language detection based on file extension\n */\nfunction 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 '.java': 'java',\n '.rb': 'ruby',\n '.php': 'php',\n '.vue': 'vue',\n '.svelte': 'svelte',\n '.sql': 'sql',\n '.json': 'json',\n '.yaml': 'yaml',\n '.yml': 'yaml',\n '.md': 'markdown',\n '.html': 'html',\n '.css': 'css',\n '.scss': 'scss',\n };\n return langMap[ext] || 'plaintext';\n}\n\n/**\n * Analyze file content to understand its context\n * This helps build smarter prompts for the AI\n */\nfunction analyzeFileContext(content: string, _filePath: string): FileSummary {\n const summary: FileSummary = {\n hasAuth: false,\n hasDatabase: false,\n hasUserInput: false,\n hasFileOps: false,\n hasCrypto: false,\n hasExternalAPIs: false,\n exports: [],\n imports: [],\n };\n\n // Detect auth-related code\n if (/auth|login|session|jwt|token|password|credential|oauth/i.test(content)) {\n summary.hasAuth = true;\n }\n\n // Detect database operations\n if (/prisma|sequelize|knex|mongodb|sql|query|database|postgres|mysql|sqlite/i.test(content)) {\n summary.hasDatabase = true;\n }\n\n // Detect user input handling\n if (/req\\.body|req\\.params|req\\.query|formData|input|textarea|userinput/i.test(content)) {\n summary.hasUserInput = true;\n }\n\n // Detect file operations\n if (/readFile|writeFile|createReadStream|createWriteStream|fs\\.|multer|upload/i.test(content)) {\n summary.hasFileOps = true;\n }\n\n // Detect crypto\n if (/crypto|bcrypt|argon|scrypt|encrypt|decrypt|hash|sign|verify/i.test(content)) {\n summary.hasCrypto = true;\n }\n\n // Detect external API calls\n if (/fetch\\(|axios|http\\.|https\\.|request\\(|got\\(|api\\//i.test(content)) {\n summary.hasExternalAPIs = true;\n }\n\n // Detect framework\n if (/from\\s+['\"]react['\"]|import\\s+React/i.test(content)) {\n summary.framework = 'React';\n } else if (/from\\s+['\"]next|NextRequest|getServerSideProps/i.test(content)) {\n summary.framework = 'Next.js';\n } else if (/from\\s+['\"]express['\"]|express\\(\\)/i.test(content)) {\n summary.framework = 'Express';\n } else if (/from\\s+['\"]fastify['\"]|fastify\\(\\)/i.test(content)) {\n summary.framework = 'Fastify';\n } else if (/from\\s+['\"]vue['\"]|defineComponent/i.test(content)) {\n summary.framework = 'Vue';\n }\n\n // Extract exports (simplified)\n const exportMatches = content.match(/export\\s+(const|function|class|interface|type)\\s+(\\w+)/g) || [];\n summary.exports = exportMatches.map(m => m.split(/\\s+/).pop() || '').filter(Boolean).slice(0, 10);\n\n // Extract imports (simplified)\n const importMatches = content.match(/import\\s+.*from\\s+['\"]([^'\"]+)['\"]/g) || [];\n summary.imports = importMatches.map(m => {\n const match = m.match(/from\\s+['\"]([^'\"]+)['\"]/);\n return match ? match[1] : '';\n }).filter((s): s is string => Boolean(s)).slice(0, 10);\n\n return summary;\n}\n\n/**\n * Build a rich prompt context for AI analysis\n */\nfunction buildPromptContext(contexts: CodeContext[], agent: AgentName): string {\n let contextSummary = '';\n \n // Aggregate insights\n const hasAuth = contexts.some(c => c.summary?.hasAuth);\n const hasDatabase = contexts.some(c => c.summary?.hasDatabase);\n const hasUserInput = contexts.some(c => c.summary?.hasUserInput);\n const hasFileOps = contexts.some(c => c.summary?.hasFileOps);\n const hasCrypto = contexts.some(c => c.summary?.hasCrypto);\n const hasExternalAPIs = contexts.some(c => c.summary?.hasExternalAPIs);\n const frameworks = [...new Set(contexts.map(c => c.summary?.framework).filter(Boolean))];\n\n contextSummary += '## Code Context Summary\\n\\n';\n contextSummary += `**Files analyzed:** ${contexts.length}\\n`;\n contextSummary += `**Total lines:** ${contexts.reduce((sum, c) => sum + c.lineCount, 0)}\\n`;\n \n if (frameworks.length > 0) {\n contextSummary += `**Frameworks detected:** ${frameworks.join(', ')}\\n`;\n }\n \n const features = [];\n if (hasAuth) features.push('Authentication/Authorization');\n if (hasDatabase) features.push('Database operations');\n if (hasUserInput) features.push('User input handling');\n if (hasFileOps) features.push('File operations');\n if (hasCrypto) features.push('Cryptography');\n if (hasExternalAPIs) features.push('External API calls');\n \n if (features.length > 0) {\n contextSummary += `**Key features:** ${features.join(', ')}\\n`;\n }\n \n contextSummary += '\\n';\n\n // Agent-specific focus areas\n if (agent === 'security') {\n if (hasAuth) contextSummary += 'โš ๏ธ **Auth code detected** - Review authentication flows carefully\\n';\n if (hasDatabase) contextSummary += 'โš ๏ธ **Database ops detected** - Check for injection vulnerabilities\\n';\n if (hasUserInput) contextSummary += 'โš ๏ธ **User input detected** - Verify input validation\\n';\n } else if (agent === 'privacy') {\n if (hasAuth) contextSummary += 'โš ๏ธ **Auth code detected** - Review credential handling\\n';\n if (hasDatabase) contextSummary += 'โš ๏ธ **Database ops detected** - Check PII storage\\n';\n } else if (agent === 'bugs') {\n if (hasExternalAPIs) contextSummary += 'โš ๏ธ **External APIs detected** - Check error handling\\n';\n if (hasFileOps) contextSummary += 'โš ๏ธ **File ops detected** - Verify error handling and cleanup\\n';\n }\n\n return contextSummary;\n}\n\n/**\n * Build the full analysis for Claude\n */\nexport async function buildAnalysis(request: AnalysisRequest): Promise<AnalysisResult> {\n const { agent, files, context = {}, depth = 'standard' } = request;\n \n const codeContexts: CodeContext[] = [];\n\n console.error(`๐Ÿ”ฌ AI Engine: Preparing ${agent} analysis for ${files.length} files...`);\n\n // Process each file\n for (const filePath of files) {\n try {\n const content = await readFile(filePath, 'utf-8');\n const language = detectLanguage(filePath);\n const summary = analyzeFileContext(content, filePath);\n\n console.error(` ๐Ÿ“„ ${basename(filePath)} - ${content.split('\\n').length} lines`);\n\n codeContexts.push({\n filePath,\n relativePath: relative(process.cwd(), filePath),\n language,\n content: depth === 'quick' && content.length > 5000\n ? content.substring(0, 5000) + '\\n\\n... (truncated for quick analysis)'\n : content,\n lineCount: content.split('\\n').length,\n summary,\n });\n } catch (error) {\n console.error(` โš ๏ธ Error reading ${filePath}:`, error);\n }\n }\n\n // Build the analysis prompt\n const codeBlocks = codeContexts.map(ctx => \n `### File: ${ctx.relativePath}\\n\\`\\`\\`${ctx.language}\\n${ctx.content}\\n\\`\\`\\``\n ).join('\\n\\n');\n\n // Build context summary\n const promptContext = buildPromptContext(codeContexts, agent);\n\n // Get prompt template and fill in variables\n const variables: Record<string, string> = {\n ...context,\n code: codeBlocks,\n language: codeContexts[0]?.language || 'unknown',\n filePath: codeContexts.map(c => c.relativePath).join(', '),\n };\n\n const analysisPrompt = getPrompt(agent, 'analysis', variables);\n const systemPrompt = getSystemPrompt(agent);\n\n // Build suggested follow-ups based on context\n const suggestedFollowUps: string[] = [];\n \n if (codeContexts.some(c => c.summary?.hasAuth)) {\n suggestedFollowUps.push('๐Ÿ” Review authentication implementation');\n }\n if (codeContexts.some(c => c.summary?.hasDatabase)) {\n suggestedFollowUps.push('๐Ÿ—„๏ธ Check database query security');\n }\n if (codeContexts.some(c => c.summary?.hasUserInput)) {\n suggestedFollowUps.push('๐Ÿ“ Verify input validation');\n }\n\n // Generate files summary for display\n const filesSummary = codeContexts.map(c => {\n const features = [];\n if (c.summary?.hasAuth) features.push('auth');\n if (c.summary?.hasDatabase) features.push('db');\n if (c.summary?.hasUserInput) features.push('input');\n if (c.summary?.framework) features.push(c.summary.framework);\n \n const featureStr = features.length > 0 ? ` [${features.join(', ')}]` : '';\n return `\\`${c.relativePath}\\` (${c.lineCount} lines)${featureStr}`;\n }).join('\\n');\n\n console.error(`๐Ÿง  AI Engine: Analysis prepared - ready for Claude`);\n\n return {\n agent,\n systemPrompt,\n prompt: promptContext + '\\n' + analysisPrompt,\n codeContext: codeContexts,\n suggestedFollowUps,\n filesSummary,\n };\n}\n\n/**\n * Format analysis result for MCP response\n * This is what Claude sees and acts on\n */\nexport function formatAnalysisResponse(\n result: AnalysisResult,\n options: { includePrompt?: boolean } = {}\n): string {\n const { agent, systemPrompt, prompt, codeContext, suggestedFollowUps, filesSummary } = result;\n const includePrompt = options.includePrompt ?? true; // Default to showing prompt now\n\n let output = '';\n\n // Header\n output += `\\n${'โ”'.repeat(60)}\\n`;\n output += `๐Ÿง  ${agent.toUpperCase()} AGENT - AI ANALYSIS\\n`;\n output += `${'โ”'.repeat(60)}\\n\\n`;\n\n // Files summary\n output += `## ๐Ÿ“‚ Files for Analysis\\n\\n`;\n output += filesSummary + '\\n\\n';\n\n // Follow-up suggestions\n if (suggestedFollowUps.length > 0) {\n output += `## ๐ŸŽฏ Focus Areas\\n\\n`;\n for (const followUp of suggestedFollowUps) {\n output += `- ${followUp}\\n`;\n }\n output += '\\n';\n }\n\n // The AI analysis request - this is what Claude will process\n output += `${'โ”€'.repeat(60)}\\n`;\n output += `## ๐Ÿง  Analysis Request for Claude\\n\\n`;\n \n if (includePrompt) {\n output += `**Role:** ${systemPrompt.split('\\n')[0]}\\n\\n`;\n output += `---\\n\\n`;\n output += prompt;\n output += `\\n\\n${'โ”€'.repeat(60)}\\n`;\n } else {\n output += `*Run with \\`output: \"full\"\\` to see the complete analysis prompt.*\\n\\n`;\n output += `**Summary:** ${codeContext.length} files ready for ${agent} analysis\\n`;\n }\n\n output += `\\n**Claude:** Please analyze the code above according to the ${agent} analysis instructions and provide your findings.\\n`;\n\n return output;\n}\n\n/**\n * Generate a concise AI prompt for a specific issue type\n */\nexport function generateFocusedPrompt(\n code: string,\n filePath: string,\n focusArea: 'sql-injection' | 'xss' | 'auth' | 'secrets' | 'general'\n): string {\n const relPath = relative(process.cwd(), filePath);\n \n const focusPrompts: Record<string, string> = {\n 'sql-injection': `Check this code for SQL injection vulnerabilities. Look for:\n- String concatenation in SQL queries\n- Template literals with user input in queries\n- Missing parameterized queries\n- ORM misuse that could lead to injection`,\n \n 'xss': `Check this code for XSS vulnerabilities. Look for:\n- innerHTML/outerHTML with user content\n- dangerouslySetInnerHTML without sanitization\n- Template rendering without escaping\n- URL parameters reflected without encoding`,\n \n 'auth': `Check this code for authentication/authorization issues. Look for:\n- Password comparison without hashing\n- Missing authentication on sensitive routes\n- Weak session token generation\n- JWT validation issues\n- Authorization bypass opportunities`,\n \n 'secrets': `Check this code for exposed secrets. Look for:\n- Hardcoded API keys, passwords, tokens\n- Credentials in code (not environment variables)\n- Private keys or certificates in code\n- Database connection strings with passwords`,\n \n 'general': `Perform a general security review of this code.`\n };\n\n return `## Security Analysis: ${focusArea}\n\n**File:** \\`${relPath}\\`\n\n${focusPrompts[focusArea]}\n\n\\`\\`\\`\n${code}\n\\`\\`\\`\n\nFor each issue found, provide:\n1. **Line number** where the issue occurs\n2. **Severity** (critical/serious/moderate/low)\n3. **Description** of the vulnerability\n4. **Attack scenario** showing how it could be exploited\n5. **Fix** with specific code changes`;\n}\n","/**\n * Knowledge Module - External information lookup\n * \n * This module provides structured prompts for looking up:\n * - CVE databases\n * - Security advisories\n * - Framework documentation\n * - Best practices\n * \n * The MCP returns these as prompts, and Claude (with web access) \n * can then look up the information.\n */\n\nexport interface KnowledgeRequest {\n type: 'cve' | 'docs' | 'security' | 'best-practices' | 'changelog';\n query: string;\n context?: Record<string, string>;\n}\n\nexport interface KnowledgeSource {\n name: string;\n url: string;\n description: string;\n}\n\n/**\n * Security-related knowledge sources\n */\nexport const SECURITY_SOURCES: KnowledgeSource[] = [\n {\n name: 'OWASP Top 10',\n url: 'https://owasp.org/Top10/',\n description: 'Most critical web application security risks'\n },\n {\n name: 'NIST NVD',\n url: 'https://nvd.nist.gov/',\n description: 'National Vulnerability Database'\n },\n {\n name: 'CVE Database',\n url: 'https://cve.mitre.org/',\n description: 'Common Vulnerabilities and Exposures'\n },\n {\n name: 'Snyk Vulnerability DB',\n url: 'https://security.snyk.io/',\n description: 'Open source vulnerability database'\n },\n {\n name: 'GitHub Advisory Database',\n url: 'https://github.com/advisories',\n description: 'Security advisories from GitHub'\n }\n];\n\n/**\n * Framework documentation sources\n */\nexport const DOCS_SOURCES: Record<string, KnowledgeSource[]> = {\n react: [\n { name: 'React Docs', url: 'https://react.dev/', description: 'Official React documentation' },\n { name: 'React Security', url: 'https://react.dev/reference/react-dom/components/common#dangerously-setting-the-inner-html', description: 'React security guidance' },\n ],\n nextjs: [\n { name: 'Next.js Docs', url: 'https://nextjs.org/docs', description: 'Official Next.js documentation' },\n { name: 'Next.js Security', url: 'https://nextjs.org/docs/advanced-features/security-headers', description: 'Next.js security headers' },\n ],\n express: [\n { name: 'Express Docs', url: 'https://expressjs.com/', description: 'Official Express.js documentation' },\n { name: 'Express Security', url: 'https://expressjs.com/en/advanced/best-practice-security.html', description: 'Express security best practices' },\n ],\n node: [\n { name: 'Node.js Docs', url: 'https://nodejs.org/docs/', description: 'Official Node.js documentation' },\n { name: 'Node.js Security', url: 'https://nodejs.org/en/docs/guides/security/', description: 'Node.js security guidance' },\n ],\n typescript: [\n { name: 'TypeScript Docs', url: 'https://www.typescriptlang.org/docs/', description: 'Official TypeScript documentation' },\n ],\n};\n\n/**\n * Compliance-related sources\n */\nexport const COMPLIANCE_SOURCES: Record<string, KnowledgeSource[]> = {\n gdpr: [\n { name: 'GDPR Official Text', url: 'https://gdpr.eu/', description: 'Complete GDPR regulation text' },\n { name: 'GDPR Checklist', url: 'https://gdpr.eu/checklist/', description: 'GDPR compliance checklist' },\n ],\n hipaa: [\n { name: 'HIPAA Guidelines', url: 'https://www.hhs.gov/hipaa/', description: 'Official HIPAA guidance' },\n ],\n wcag: [\n { name: 'WCAG 2.1', url: 'https://www.w3.org/WAI/WCAG21/quickref/', description: 'WCAG 2.1 quick reference' },\n ],\n pci: [\n { name: 'PCI DSS', url: 'https://www.pcisecuritystandards.org/', description: 'Payment Card Industry standards' },\n ],\n};\n\n/**\n * Generate a CVE lookup prompt\n */\nexport function generateCVELookup(library: string, version?: string): string {\n let prompt = `## ๐Ÿ”’ Security Vulnerability Lookup\\n\\n`;\n prompt += `**Library:** ${library}\\n`;\n if (version) prompt += `**Version:** ${version}\\n`;\n prompt += `\\n`;\n\n prompt += `### Action Required\\n\\n`;\n prompt += `Please check for known vulnerabilities:\\n\\n`;\n prompt += `1. Search the **NIST NVD** (https://nvd.nist.gov/) for CVEs affecting \\`${library}\\`\\n`;\n prompt += `2. Check **Snyk** (https://security.snyk.io/) for vulnerability reports\\n`;\n prompt += `3. Review **GitHub Advisory Database** for any security advisories\\n`;\n prompt += `4. Check npm audit / yarn audit if it's an npm package\\n\\n`;\n\n prompt += `### Report Format\\n\\n`;\n prompt += `For each vulnerability found, provide:\\n`;\n prompt += `- CVE ID (if applicable)\\n`;\n prompt += `- Severity (Critical/High/Medium/Low)\\n`;\n prompt += `- Affected versions\\n`;\n prompt += `- Description of the vulnerability\\n`;\n prompt += `- Remediation (upgrade version, patches, mitigations)\\n`;\n\n return prompt;\n}\n\n/**\n * Generate a documentation lookup prompt\n */\nexport function generateDocsLookup(topic: string, framework?: string): string {\n let prompt = `## ๐Ÿ“š Documentation Lookup\\n\\n`;\n prompt += `**Topic:** ${topic}\\n`;\n if (framework) prompt += `**Framework:** ${framework}\\n`;\n prompt += `\\n`;\n\n const sources = framework ? DOCS_SOURCES[framework.toLowerCase()] : [];\n \n if (sources && sources.length > 0) {\n prompt += `### Recommended Sources\\n\\n`;\n for (const source of sources) {\n prompt += `- [${source.name}](${source.url}) - ${source.description}\\n`;\n }\n prompt += `\\n`;\n }\n\n prompt += `### Information Needed\\n\\n`;\n prompt += `Please look up the latest documentation and provide:\\n\\n`;\n prompt += `1. Current best practices for \"${topic}\"\\n`;\n prompt += `2. Common pitfalls to avoid\\n`;\n prompt += `3. Code examples demonstrating correct usage\\n`;\n prompt += `4. Any recent changes or deprecations\\n`;\n\n return prompt;\n}\n\n/**\n * Generate a security best practices lookup prompt\n */\nexport function generateSecurityLookup(pattern: string, context?: string): string {\n let prompt = `## ๐Ÿ›ก๏ธ Security Best Practices Lookup\\n\\n`;\n prompt += `**Pattern:** ${pattern}\\n`;\n if (context) prompt += `**Context:** ${context}\\n`;\n prompt += `\\n`;\n\n prompt += `### Reference Sources\\n\\n`;\n for (const source of SECURITY_SOURCES.slice(0, 3)) {\n prompt += `- [${source.name}](${source.url})\\n`;\n }\n prompt += `\\n`;\n\n prompt += `### Analysis Requested\\n\\n`;\n prompt += `Please research and provide:\\n\\n`;\n prompt += `1. **OWASP guidance** for this security pattern\\n`;\n prompt += `2. **Attack vectors** - how this could be exploited\\n`;\n prompt += `3. **Defense strategies** - recommended mitigations\\n`;\n prompt += `4. **Code examples** - secure implementation patterns\\n`;\n prompt += `5. **Testing approaches** - how to verify security\\n`;\n\n return prompt;\n}\n\n/**\n * Generate a compliance lookup prompt\n */\nexport function generateComplianceLookup(regulation: string, requirement?: string): string {\n let prompt = `## โš–๏ธ Compliance Requirement Lookup\\n\\n`;\n prompt += `**Regulation:** ${regulation}\\n`;\n if (requirement) prompt += `**Specific Requirement:** ${requirement}\\n`;\n prompt += `\\n`;\n\n const sources = COMPLIANCE_SOURCES[regulation.toLowerCase()];\n \n if (sources && sources.length > 0) {\n prompt += `### Official Sources\\n\\n`;\n for (const source of sources) {\n prompt += `- [${source.name}](${source.url})\\n`;\n }\n prompt += `\\n`;\n }\n\n prompt += `### Compliance Information Needed\\n\\n`;\n prompt += `Please research and provide:\\n\\n`;\n prompt += `1. **Specific requirement text** from the regulation\\n`;\n prompt += `2. **Technical requirements** for compliance\\n`;\n prompt += `3. **Implementation guidance** with code examples\\n`;\n prompt += `4. **Documentation requirements** - what records to keep\\n`;\n prompt += `5. **Penalties** for non-compliance\\n`;\n\n return prompt;\n}\n\n/**\n * Generate a changelog/version lookup prompt\n */\nexport function generateChangelogLookup(library: string, fromVersion: string, toVersion?: string): string {\n let prompt = `## ๐Ÿ“‹ Changelog Lookup\\n\\n`;\n prompt += `**Library:** ${library}\\n`;\n prompt += `**Current Version:** ${fromVersion}\\n`;\n if (toVersion) prompt += `**Target Version:** ${toVersion}\\n`;\n prompt += `\\n`;\n\n prompt += `### Information Needed\\n\\n`;\n prompt += `Please find the changelog/release notes and provide:\\n\\n`;\n prompt += `1. **Breaking changes** between versions\\n`;\n prompt += `2. **New features** added\\n`;\n prompt += `3. **Deprecations** to be aware of\\n`;\n prompt += `4. **Security fixes** included\\n`;\n prompt += `5. **Migration guide** if available\\n`;\n prompt += `6. **Known issues** with the upgrade\\n`;\n\n return prompt;\n}\n\n/**\n * Main knowledge lookup function\n */\nexport function lookupKnowledge(request: KnowledgeRequest): string {\n const { type, query, context = {} } = request;\n\n switch (type) {\n case 'cve':\n return generateCVELookup(query, context.version);\n \n case 'docs':\n return generateDocsLookup(query, context.framework);\n \n case 'security':\n return generateSecurityLookup(query, context.context);\n \n case 'best-practices':\n return generateComplianceLookup(query, context.requirement);\n \n case 'changelog':\n return generateChangelogLookup(query, context.fromVersion || 'current', context.toVersion);\n \n default:\n return `Unknown knowledge request type: ${type}`;\n }\n}\n\n/**\n * Detect libraries and versions from package.json\n */\nexport async function detectDependencies(packageJsonPath: string): Promise<Map<string, string>> {\n const deps = new Map<string, string>();\n \n try {\n const { readFile } = await import('fs/promises');\n const content = await readFile(packageJsonPath, 'utf-8');\n const pkg = JSON.parse(content);\n \n const allDeps = {\n ...pkg.dependencies,\n ...pkg.devDependencies,\n };\n\n for (const [name, version] of Object.entries(allDeps)) {\n deps.set(name, String(version).replace(/^[\\^~]/, ''));\n }\n } catch {\n // Ignore errors\n }\n\n return deps;\n}\n\n/**\n * Known vulnerable packages (quick check - not exhaustive)\n */\nexport const KNOWN_VULNERABLE_PATTERNS = [\n { pattern: /^lodash$/, minSafeVersion: '4.17.21', reason: 'Prototype pollution' },\n { pattern: /^minimist$/, minSafeVersion: '1.2.6', reason: 'Prototype pollution' },\n { pattern: /^node-fetch$/, minSafeVersion: '2.6.7', reason: 'URL bypass' },\n { pattern: /^axios$/, minSafeVersion: '1.6.0', reason: 'SSRF vulnerability' },\n { pattern: /^jsonwebtoken$/, minSafeVersion: '9.0.0', reason: 'Algorithm confusion' },\n];\n\n","/**\n * MCP Tool: trie_create_agent\n * \n * Creates a custom agent from a PDF, TXT, MD, or RTF document.\n * \n * This is a two-step process that leverages the host LLM (Claude in Cursor/Claude Code):\n * 1. trie_create_agent - Parses document and returns extraction prompt\n * 2. trie_save_agent - Saves the agent config after Claude processes it\n * \n * This design eliminates the need for a separate ANTHROPIC_API_KEY since\n * the user is already in an AI workflow with Claude.\n */\n\nimport { parseDocument } from '../ingest/document-parser.js';\nimport { listCustomAgents, loadAgentConfig } from '../ingest/agent-builder.js';\nimport type { GeneratedAgentConfig, CompressedKnowledge } from '../types/custom-agent.js';\nimport { existsSync } from 'fs';\nimport { mkdir, writeFile } from 'fs/promises';\nimport { join, basename, extname } from 'path';\n\nexport class TrieCreateAgentTool {\n async execute(args: {\n filePath?: string;\n documentContent?: string;\n agentName: string;\n displayName?: string;\n description?: string;\n category?: string;\n }) {\n const { filePath, documentContent, agentName, displayName, description, category } = args;\n \n // Validate inputs\n if (!agentName) {\n return this.errorResponse('Missing required parameter: agentName');\n }\n \n // Either filePath or documentContent must be provided\n if (!filePath && !documentContent) {\n return this.errorResponse(\n 'Provide either filePath (path to PDF/TXT/MD file) or documentContent (raw text from drag-and-drop)'\n );\n }\n \n try {\n let rawText: string;\n let title: string = agentName;\n let wordCount: number = 0;\n \n if (filePath) {\n // Check if file exists\n if (!existsSync(filePath)) {\n return this.errorResponse(`File not found: ${filePath}`);\n }\n \n // Check supported file types\n const ext = filePath.toLowerCase().split('.').pop();\n if (!['pdf', 'txt', 'md', 'markdown', 'rtf'].includes(ext || '')) {\n return this.errorResponse(\n `Unsupported file type: .${ext}\\nSupported types: .pdf, .txt, .md, .rtf`\n );\n }\n \n // Parse the document\n const document = await parseDocument(filePath);\n rawText = document.rawText;\n // fileType is available in document.metadata.fileType if needed\n title = document.metadata.title || basename(filePath, extname(filePath));\n wordCount = document.metadata.wordCount;\n } else {\n // Use provided document content (from drag-and-drop)\n rawText = documentContent!;\n wordCount = rawText.split(/\\s+/).filter(w => w.length > 0).length;\n \n // Try to extract title from first line\n const firstLine = rawText.split('\\n')[0]?.trim();\n if (firstLine && firstLine.length < 100) {\n title = firstLine;\n }\n }\n \n // Chunk the document for processing\n const chunks = this.chunkText(rawText, 6000);\n \n // Build the extraction prompt that Claude will process\n const extractionPrompt = this.buildExtractionPrompt(\n chunks,\n title,\n agentName,\n category,\n displayName,\n description\n );\n \n // Return the prompt for Claude to process\n return {\n content: [\n {\n type: 'text',\n text: this.formatExtractionRequest(\n agentName,\n title,\n wordCount,\n chunks.length,\n extractionPrompt\n ),\n },\n ],\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return this.errorResponse(`Failed to parse document: ${errorMessage}`);\n }\n }\n \n /**\n * Chunk text into manageable pieces\n */\n private chunkText(text: string, maxChunkSize: number): string[] {\n if (text.length <= maxChunkSize) {\n return [text];\n }\n \n const chunks: string[] = [];\n const paragraphs = text.split(/\\n\\s*\\n/);\n let currentChunk = '';\n \n for (const para of paragraphs) {\n if (currentChunk.length + para.length + 2 > maxChunkSize) {\n if (currentChunk) chunks.push(currentChunk.trim());\n currentChunk = para;\n } else {\n currentChunk += (currentChunk ? '\\n\\n' : '') + para;\n }\n }\n \n if (currentChunk) chunks.push(currentChunk.trim());\n return chunks;\n }\n \n /**\n * Build the extraction prompt for Claude\n */\n private buildExtractionPrompt(\n chunks: string[],\n title: string,\n agentName: string,\n category?: string,\n displayName?: string,\n description?: string\n ): string {\n const prefix = agentName.toUpperCase().replace(/[^A-Z]/g, '').slice(0, 4) || 'CUST';\n \n // Combine chunks with separators\n const documentContent = chunks.length === 1 \n ? chunks[0]\n : chunks.map((c, i) => `--- SECTION ${i + 1}/${chunks.length} ---\\n${c}`).join('\\n\\n');\n \n return `# Create Code Review Agent: \"${displayName || this.formatDisplayName(agentName)}\"\n\n## Your Task\nAnalyze the following document and extract structured knowledge to create a code review agent.\n\n## Document Information\n- **Title**: ${title}\n- **Agent Name**: ${agentName}\n- **Category**: ${category || 'auto-detect'}\n${description ? `- **Description**: ${description}` : ''}\n\n## Document Content\n${documentContent}\n\n---\n\n## Instructions\n\nPlease analyze this document and produce a **single JSON object** with the following structure. This will be used to create a custom code review agent.\n\n**IMPORTANT**: Your response should be ONLY the JSON object, no other text.\n\n\\`\\`\\`json\n{\n \"agentConfig\": {\n \"name\": \"${this.sanitizeAgentName(agentName)}\",\n \"displayName\": \"${displayName || this.formatDisplayName(agentName)}\",\n \"description\": \"${description || `Code review agent based on ${title}`}\",\n \"version\": \"1.0.0\",\n \"category\": \"string (technical | legal | policy | security | architecture | general)\"\n },\n \"knowledge\": {\n \"domain\": \"string (technical | legal | policy | security | architecture | general)\",\n \"summary\": \"2-3 paragraph summary of the document's key insights for code review\",\n \"coreConcepts\": [\n {\n \"name\": \"string\",\n \"description\": \"string\",\n \"importance\": \"critical | important | supplementary\",\n \"keywords\": [\"string\"]\n }\n ],\n \"bestPractices\": [\n {\n \"name\": \"string\",\n \"description\": \"string\",\n \"rationale\": \"why this is important\",\n \"codeExample\": \"optional code example or null\"\n }\n ],\n \"antiPatterns\": [\n {\n \"name\": \"string\",\n \"description\": \"string\",\n \"whyBad\": \"why to avoid\",\n \"betterAlternative\": \"what to do instead\"\n }\n ],\n \"glossary\": {\n \"term\": \"definition\"\n }\n },\n \"detectionRules\": [\n {\n \"id\": \"${prefix}-001\",\n \"name\": \"Rule Name\",\n \"description\": \"What this rule detects\",\n \"severity\": \"critical | serious | moderate | low | info\",\n \"patterns\": {\n \"regex\": [\"JavaScript regex patterns\"],\n \"keywords\": [\"words that indicate this issue\"],\n \"semantic\": \"Natural language description for AI detection\"\n },\n \"fix\": {\n \"description\": \"How to fix this issue\",\n \"example\": \"Code example or null\",\n \"autoFixable\": false\n },\n \"category\": \"string\"\n }\n ],\n \"prompts\": {\n \"systemPrompt\": \"You are an expert code reviewer specializing in [topic]. Your role is to...\",\n \"analysisPrompt\": \"Review this code for issues related to [topic]. Look for: ...\\\\n\\\\nCode:\\\\n\\\\\\`\\\\\\`\\\\\\`{{language}}\\\\n{{code}}\\\\n\\\\\\`\\\\\\`\\\\\\`\\\\n\\\\nFile: {{filePath}}\",\n \"fixPrompt\": \"Fix this issue: {{issue}}\\\\n\\\\nCode:\\\\n\\\\\\`\\\\\\`\\\\\\`{{language}}\\\\n{{code}}\\\\n\\\\\\`\\\\\\`\\\\\\`\"\n }\n}\n\\`\\`\\`\n\n## Guidelines\n\n1. **Core Concepts**: Extract 10-20 key concepts that are fundamental to the material\n2. **Best Practices**: Extract 10-15 recommended approaches with rationale\n3. **Anti-Patterns**: Extract 10-15 things to avoid with explanations\n4. **Detection Rules**: Generate 15-30 rules with regex patterns that could detect issues in code\n5. **Prompts**: Create prompts that embody the expertise from this document\n\nFocus on extracting actionable, code-reviewable knowledge. The agent should be able to find violations of the principles in this document.\n\n**Output ONLY the JSON object, starting with \\`{\\` and ending with \\`}\\`.**`;\n }\n \n /**\n * Format the extraction request output\n */\n private formatExtractionRequest(\n agentName: string,\n title: string,\n wordCount: number,\n chunkCount: number,\n prompt: string\n ): string {\n return `\n๐Ÿ“š **Document Parsed Successfully!**\n\n${'โ”'.repeat(50)}\n\n**Creating Agent:** \\`${agentName}\\`\n**Source Document:** ${title}\n**Word Count:** ${wordCount.toLocaleString()}\n**Processing Chunks:** ${chunkCount}\n\n${'โ”'.repeat(50)}\n\n## Next Step\n\nI've prepared the document for analysis. Please process the following prompt to extract the knowledge, then pass the result to \\`trie_save_agent\\` to save the agent.\n\n${'โ”€'.repeat(50)}\n\n${prompt}\n`;\n }\n \n private sanitizeAgentName(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '');\n }\n \n private formatDisplayName(name: string): string {\n return name\n .split(/[-_]/)\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n }\n \n private errorResponse(message: string) {\n return {\n content: [\n {\n type: 'text',\n text: `โŒ **Error:** ${message}`,\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * MCP Tool: trie_save_agent\n * \n * Saves an agent configuration after Claude has processed the document.\n * This is step 2 of the agent creation process.\n */\nexport class TrieSaveAgentTool {\n async execute(args: {\n agentConfig: {\n name: string;\n displayName: string;\n description: string;\n version?: string;\n category: string;\n };\n knowledge: {\n domain: string;\n summary: string;\n coreConcepts: Array<{\n name: string;\n description: string;\n importance: string;\n keywords?: string[];\n }>;\n bestPractices: Array<{\n name: string;\n description: string;\n rationale: string;\n codeExample?: string | null;\n }>;\n antiPatterns: Array<{\n name: string;\n description: string;\n whyBad: string;\n betterAlternative: string;\n }>;\n glossary?: Record<string, string>;\n };\n detectionRules: Array<{\n id: string;\n name: string;\n description: string;\n severity: string;\n patterns: {\n regex?: string[];\n keywords?: string[];\n semantic?: string;\n };\n fix: {\n description: string;\n example?: string | null;\n autoFixable?: boolean;\n };\n category?: string;\n }>;\n prompts: {\n systemPrompt: string;\n analysisPrompt: string;\n fixPrompt: string;\n };\n sourceFile?: string;\n }) {\n const { agentConfig, knowledge, detectionRules, prompts, sourceFile } = args;\n \n // Validate required fields\n if (!agentConfig?.name) {\n return this.errorResponse('Missing agentConfig.name');\n }\n \n if (!knowledge?.summary) {\n return this.errorResponse('Missing knowledge.summary');\n }\n \n if (!prompts?.systemPrompt) {\n return this.errorResponse('Missing prompts.systemPrompt');\n }\n \n try {\n // Build the full agent config\n const fullConfig: GeneratedAgentConfig = {\n name: this.sanitizeAgentName(agentConfig.name),\n displayName: agentConfig.displayName || this.formatDisplayName(agentConfig.name),\n description: agentConfig.description,\n version: agentConfig.version || '1.0.0',\n category: agentConfig.category || knowledge.domain || 'general',\n \n source: {\n type: 'document',\n originalFile: sourceFile || 'user-provided',\n fileType: 'txt',\n compressedAt: new Date().toISOString(),\n },\n \n systemPrompt: prompts.systemPrompt,\n analysisPrompt: prompts.analysisPrompt,\n fixPrompt: prompts.fixPrompt,\n \n activationRules: this.buildActivationRules(knowledge, detectionRules),\n \n patterns: detectionRules.map((rule, i) => {\n const fixObj: { description: string; autoFixable: boolean; example?: string } = {\n description: rule.fix?.description || 'Review and fix manually',\n autoFixable: rule.fix?.autoFixable || false,\n };\n if (rule.fix?.example) {\n fixObj.example = rule.fix.example;\n }\n return {\n id: rule.id || `CUST-${String(i + 1).padStart(3, '0')}`,\n name: rule.name,\n description: rule.description,\n severity: (rule.severity as 'critical' | 'serious' | 'moderate' | 'low' | 'info') || 'moderate',\n patterns: {\n regex: rule.patterns?.regex || [],\n keywords: rule.patterns?.keywords || [],\n semantic: rule.patterns?.semantic || '',\n },\n fix: fixObj,\n category: rule.category || agentConfig.category,\n };\n }),\n \n knowledge: {\n domain: (knowledge.domain as CompressedKnowledge['domain']) || 'general',\n summary: knowledge.summary,\n coreConcepts: knowledge.coreConcepts.map(c => ({\n name: c.name,\n description: c.description,\n importance: (c.importance as 'critical' | 'important' | 'supplementary') || 'important',\n relatedPatterns: (c as any).relatedPatterns || [],\n keywords: c.keywords || [],\n })),\n bestPractices: knowledge.bestPractices.map(bp => {\n const practice: { name: string; description: string; rationale: string; category: string; codeExample?: string } = {\n name: bp.name,\n description: bp.description,\n rationale: bp.rationale,\n category: (bp as any).category || agentConfig.category,\n };\n if (bp.codeExample) {\n practice.codeExample = bp.codeExample;\n }\n return practice;\n }),\n antiPatterns: knowledge.antiPatterns.map(ap => ({\n name: ap.name,\n description: ap.description,\n whyBad: ap.whyBad,\n betterAlternative: ap.betterAlternative,\n })),\n detectionRules: [],\n glossary: knowledge.glossary || {},\n sourceDocument: {\n title: agentConfig.displayName || agentConfig.name,\n wordCount: 0,\n compressionRatio: 0,\n },\n },\n };\n \n // Save the config\n const configPath = await this.saveAgentConfig(fullConfig);\n \n return {\n content: [\n {\n type: 'text',\n text: this.formatSuccessResponse(fullConfig, configPath),\n },\n ],\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return this.errorResponse(`Failed to save agent: ${errorMessage}`);\n }\n }\n \n private buildActivationRules(\n knowledge: { domain: string; coreConcepts: Array<{ keywords?: string[] }> },\n detectionRules: Array<{ patterns: { keywords?: string[] } }>\n ): GeneratedAgentConfig['activationRules'] {\n const domainRules: Record<string, Partial<GeneratedAgentConfig['activationRules']>> = {\n technical: {\n filePatterns: ['*.ts', '*.tsx', '*.js', '*.jsx', '*.py', '*.go', '*.rs'],\n contextSignals: ['touchesUI', 'touchesAPI'],\n priority: 2,\n },\n legal: {\n filePatterns: ['*'],\n contextSignals: ['touchesUserData', 'touchesAuth', 'touchesPayments'],\n priority: 2,\n },\n policy: {\n filePatterns: ['*'],\n contextSignals: ['touchesAuth', 'touchesAPI', 'touchesDatabase'],\n priority: 3,\n },\n security: {\n filePatterns: ['*'],\n contextSignals: ['touchesAuth', 'touchesCrypto', 'touchesAPI', 'touchesDatabase'],\n priority: 1,\n },\n architecture: {\n filePatterns: ['*.ts', '*.tsx', '*.js', '*.jsx', '*.py', '*.go'],\n contextSignals: ['touchesAPI', 'touchesDatabase'],\n priority: 2,\n },\n general: {\n filePatterns: ['*'],\n contextSignals: [],\n priority: 3,\n },\n };\n \n const defaults = domainRules[knowledge.domain] || domainRules.general!;\n \n // Extract content patterns from rules and concepts\n const contentPatterns: string[] = [];\n for (const rule of detectionRules) {\n if (rule.patterns?.keywords) {\n contentPatterns.push(...rule.patterns.keywords.slice(0, 3));\n }\n }\n for (const concept of knowledge.coreConcepts.slice(0, 5)) {\n if (concept.keywords) {\n contentPatterns.push(...concept.keywords.slice(0, 2));\n }\n }\n \n return {\n filePatterns: defaults.filePatterns || ['*'],\n contentPatterns: [...new Set(contentPatterns)].slice(0, 20),\n contextSignals: defaults.contextSignals || [],\n minConfidence: 0.3,\n priority: defaults.priority || 2,\n };\n }\n \n private async saveAgentConfig(config: GeneratedAgentConfig): Promise<string> {\n const trieDir = join(process.cwd(), '.trie', 'agents');\n await mkdir(trieDir, { recursive: true });\n \n const configPath = join(trieDir, `${config.name}.json`);\n await writeFile(configPath, JSON.stringify(config, null, 2));\n \n return configPath;\n }\n \n private formatSuccessResponse(config: GeneratedAgentConfig, configPath: string): string {\n return `\nโœ… **Agent Created Successfully!**\n\n${'โ”'.repeat(50)}\n\n**Agent Name:** \\`${config.name}\\`\n**Display Name:** ${config.displayName}\n**Category:** ${config.category}\n**Config Saved To:** \\`${configPath}\\`\n\n๐Ÿ“Š **Statistics:**\n โ€ข Core concepts: ${config.knowledge.coreConcepts.length}\n โ€ข Best practices: ${config.knowledge.bestPractices.length}\n โ€ข Anti-patterns: ${config.knowledge.antiPatterns.length}\n โ€ข Detection rules: ${config.patterns.length}\n\n๐Ÿš€ **Next Steps:**\n 1. The agent is now registered and will activate during scans\n 2. Run \\`trie_scan\\` to test the new agent\n 3. Edit \\`${configPath}\\` to customize detection rules\n\n๐Ÿ’ก **Usage:**\n The agent will automatically activate when scanning code that matches its patterns.\n Use \\`trie_list_agents\\` to see all registered agents.\n`.trim();\n }\n \n private sanitizeAgentName(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9-]/g, '-')\n .replace(/-+/g, '-')\n .replace(/^-|-$/g, '');\n }\n \n private formatDisplayName(name: string): string {\n return name\n .split(/[-_]/)\n .map(word => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n }\n \n private errorResponse(message: string) {\n return {\n content: [\n {\n type: 'text',\n text: `โŒ **Error:** ${message}`,\n },\n ],\n isError: true,\n };\n }\n}\n\n/**\n * MCP Tool: trie_list_agents\n * \n * Lists all registered agents including custom ones\n */\nexport class TrieListAgentsTool {\n async execute(args: { includeBuiltin?: boolean }) {\n const { includeBuiltin = true } = args;\n \n try {\n // Get custom agents\n const customAgentNames = await listCustomAgents();\n const customAgents = await Promise.all(\n customAgentNames.map(async name => {\n const config = await loadAgentConfig(name);\n return config ? {\n name: config.name,\n displayName: config.displayName,\n category: config.category,\n source: config.source.originalFile,\n patterns: config.patterns.length,\n isCustom: true,\n } : null;\n })\n );\n \n const validCustomAgents = customAgents.filter(Boolean);\n \n // Built-in agents\n const builtinAgents = includeBuiltin ? [\n { name: 'security', displayName: 'Security Agent', category: 'security', isCustom: false },\n { name: 'privacy', displayName: 'Privacy Agent', category: 'privacy', isCustom: false },\n { name: 'legal', displayName: 'Legal Agent', category: 'compliance', isCustom: false },\n { name: 'typecheck', displayName: 'TypeCheck Agent', category: 'quality', isCustom: false },\n { name: 'comprehension', displayName: 'Comprehension Agent', category: 'communication', isCustom: false },\n { name: 'design-engineer', displayName: 'Design Engineer Agent', category: 'accessibility', isCustom: false },\n { name: 'test', displayName: 'Test Agent', category: 'testing', isCustom: false },\n { name: 'software-architect', displayName: 'Software Architect Agent', category: 'architecture', isCustom: false },\n { name: 'devops', displayName: 'DevOps Agent', category: 'devops', isCustom: false },\n { name: 'bug-finding', displayName: 'Bug Finding Agent', category: 'quality', isCustom: false },\n { name: 'user-testing', displayName: 'User Testing Agent', category: 'ux', isCustom: false },\n { name: 'trie_clean', displayName: 'Trie Clean Agent', category: 'ai-code', isCustom: false },\n ] : [];\n \n // Format response\n let response = `# ๐Ÿค– Registered Agents\\n\\n`;\n \n if (builtinAgents.length > 0) {\n response += `## Built-in Agents (${builtinAgents.length})\\n\\n`;\n for (const agent of builtinAgents) {\n response += `- **${agent.displayName}** (\\`${agent.name}\\`) - ${agent.category}\\n`;\n }\n response += '\\n';\n }\n \n response += `## Custom Agents (${validCustomAgents.length})\\n\\n`;\n \n if (validCustomAgents.length === 0) {\n response += `_No custom agents created yet._\\n\\n`;\n response += `๐Ÿ’ก Create one with: \\`trie_create_agent\\`\\n`;\n response += ` - Provide a PDF, TXT, or MD file path\\n`;\n response += ` - Or paste/drag document content directly\\n`;\n } else {\n for (const agent of validCustomAgents) {\n if (agent) {\n response += `- **${agent.displayName}** (\\`${agent.name}\\`)\\n`;\n response += ` - Category: ${agent.category}\\n`;\n response += ` - Patterns: ${agent.patterns}\\n`;\n response += ` - Source: ${agent.source}\\n\\n`;\n }\n }\n }\n \n return {\n content: [\n {\n type: 'text',\n text: response,\n },\n ],\n };\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return {\n content: [\n {\n type: 'text',\n text: `โŒ Error listing agents: ${errorMessage}`,\n },\n ],\n isError: true,\n };\n }\n }\n}\n","import { AITool } from '../types/index.js';\n\nexport function detectAITool(): AITool {\n // Check environment variables\n if (process.env.CLAUDE_CODE_VERSION) {\n return {\n name: 'claude-code',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: true,\n };\n }\n\n if (process.env.CURSOR_IDE) {\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 // Check parent process name\n const parentProcess = process.env.PARENT_PROCESS_NAME;\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 if (parentProcess?.toLowerCase().includes('opencode')) {\n return {\n name: 'opencode',\n preferredOutputFormat: 'plain-text',\n supportsDiffs: false,\n supportsInlineActions: false,\n };\n }\n\n // Default to unknown\n return {\n name: 'unknown',\n preferredOutputFormat: 'markdown',\n supportsDiffs: true,\n supportsInlineActions: false,\n };\n}","import { readFile } from 'fs/promises';\nimport { join } from 'path';\nimport { DEFAULT_CONFIG } from './defaults.js';\n\nexport async function loadConfig() {\n try {\n // Look for config in .trie/config.json\n const configPath = join(process.cwd(), '.trie', 'config.json');\n const configFile = await readFile(configPath, 'utf-8');\n const userConfig = JSON.parse(configFile);\n\n // Deep merge with defaults\n return mergeConfig(DEFAULT_CONFIG, userConfig);\n } catch (error) {\n // If no config found, return defaults\n console.error('No config found, using defaults');\n return DEFAULT_CONFIG;\n }\n}\n\nfunction mergeConfig(defaults: any, user: any): any {\n if (typeof user !== 'object' || user === null) {\n return defaults;\n }\n\n const result = { ...defaults };\n\n for (const [key, value] of Object.entries(user)) {\n if (typeof value === 'object' && value !== null && !Array.isArray(value)) {\n result[key] = mergeConfig(defaults[key] || {}, value);\n } else {\n result[key] = value;\n }\n }\n\n return result;\n}","export const DEFAULT_CONFIG = {\n version: '1.0',\n triaging: {\n enabled: true,\n riskThresholds: {\n critical: 70,\n high: 40,\n medium: 20\n },\n autoFixConfidence: 0.95\n },\n agents: {\n builtin: {\n security: { enabled: true },\n privacy: { enabled: true },\n legal: { enabled: true },\n 'design-engineer': { enabled: true },\n 'software-architect': { enabled: true },\n comprehension: { enabled: true },\n devops: { enabled: true },\n git: { enabled: true },\n typecheck: { enabled: true },\n test: { enabled: true },\n 'user-testing': { enabled: true },\n 'bug-finding': { enabled: true }\n },\n custom: []\n },\n ai: {\n provider: 'hybrid' as const,\n cloudModel: 'claude-sonnet-4-20250514',\n localModel: 'codellama:13b',\n useLocalFor: ['privacy-sensitive', 'quick-checks']\n },\n output: {\n format: 'markdown' as const,\n verbosity: 'detailed' as const,\n showConfidenceScores: true,\n includeAgentReasonings: false\n },\n compliance: {\n standards: ['G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B,UAAQ,MAAM,kCAAkC;AAClD;AAGA,KAAK,EAAE,MAAM,CAAC,UAAU;AACtB,UAAQ,MAAM,gBAAgB,KAAK;AACnC,UAAQ,KAAK,CAAC;AAChB,CAAC;","names":["readdir","readFile","join","readFile","existsSync","extname","relative","resolve","isAbsolute","isAbsolute","resolve","existsSync","readFile","relative","extname","join","extname","basename","existsSync","existsSync","basename","join","extname","readdir","readFile","existsSync","join","extname","isAbsolute","resolve","basename","readFile","extname","relative","basename","extname","readFile","basename","relative","SKIP_DIRS","isAbsolute","resolve","existsSync","basename","readFile","join","extname","existsSync","join","basename","extname","readFile","join","join","readFile","join","readdir","readFile"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@triedotdev/mcp",
3
- "version": "1.0.1",
3
+ "version": "1.0.2",
4
4
  "description": "Intelligent Agent Orchestration for AI Coding Tools",
5
5
  "main": "dist/index.js",
6
6
  "type": "module",