@sashabogi/argus-mcp 2.0.8 → 2.0.10
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/cli.mjs +28 -4
- package/dist/cli.mjs.map +1 -1
- package/dist/index.mjs +10 -2
- package/dist/index.mjs.map +1 -1
- package/dist/mcp.mjs +10 -2
- package/dist/mcp.mjs.map +1 -1
- package/package.json +1 -1
- package/packages/ui/dist/assets/{index-BiXsOvsB.js → index-Bf7VYWmF.js} +11 -11
- package/packages/ui/dist/index.html +1 -1
package/dist/mcp.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../node_modules/tsup/assets/esm_shims.js","../src/core/semantic-search.ts","../src/mcp.ts","../src/core/config.ts","../src/core/enhanced-snapshot.ts","../src/core/snapshot.ts","../src/core/engine.ts","../src/core/prompts.ts","../src/providers/index.ts","../src/providers/openai-compatible.ts","../src/providers/ollama.ts","../src/providers/anthropic.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport { fileURLToPath } from 'url'\nimport path from 'path'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\n * Semantic Search using SQLite FTS5\n *\n * Provides full-text search capabilities for code symbols and content.\n * Uses SQLite's built-in FTS5 for efficient text search without external dependencies.\n */\n\nimport Database from 'better-sqlite3';\nimport { existsSync, mkdirSync, readFileSync } from 'fs';\nimport { dirname } from 'path';\n\nexport interface SearchResult {\n file: string;\n symbol: string;\n content: string;\n type: string;\n rank: number;\n}\n\nexport class SemanticIndex {\n private db: Database.Database;\n private initialized = false;\n\n constructor(dbPath: string) {\n // Ensure directory exists\n const dir = dirname(dbPath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n\n this.db = new Database(dbPath);\n this.initialize();\n }\n\n private initialize(): void {\n if (this.initialized) return;\n\n // Create FTS5 virtual table for code search\n this.db.exec(`\n CREATE VIRTUAL TABLE IF NOT EXISTS code_index USING fts5(\n file,\n symbol,\n content,\n type,\n tokenize='porter unicode61'\n );\n `);\n\n // Create metadata table\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS index_metadata (\n key TEXT PRIMARY KEY,\n value TEXT\n );\n `);\n\n this.initialized = true;\n }\n\n /**\n * Clear the index and rebuild from scratch\n */\n clear(): void {\n this.db.exec('DELETE FROM code_index');\n }\n\n /**\n * Index a file's symbols and content\n */\n indexFile(file: string, symbols: Array<{ name: string; content: string; type: string }>): void {\n const insert = this.db.prepare(`\n INSERT INTO code_index (file, symbol, content, type)\n VALUES (?, ?, ?, ?)\n `);\n\n const tx = this.db.transaction(() => {\n for (const sym of symbols) {\n insert.run(file, sym.name, sym.content, sym.type);\n }\n });\n\n tx();\n }\n\n /**\n * Index content from a snapshot file\n */\n indexFromSnapshot(snapshotPath: string): { filesIndexed: number; symbolsIndexed: number } {\n const content = readFileSync(snapshotPath, 'utf-8');\n\n this.clear();\n\n let filesIndexed = 0;\n let symbolsIndexed = 0;\n\n // Parse files from snapshot\n const fileRegex = /^FILE: \\.\\/(.+)$/gm;\n const files: Array<{ path: string; start: number; end: number }> = [];\n let match;\n\n while ((match = fileRegex.exec(content)) !== null) {\n if (files.length > 0) {\n files[files.length - 1].end = match.index;\n }\n files.push({ path: match[1], start: match.index, end: content.length });\n }\n\n // Find metadata start\n const metadataStart = content.indexOf('\\nMETADATA:');\n if (metadataStart !== -1 && files.length > 0) {\n files[files.length - 1].end = metadataStart;\n }\n\n // Index each file\n for (const file of files) {\n const fileContent = content.slice(file.start, file.end);\n const lines = fileContent.split('\\n').slice(2); // Skip header\n\n // Extract symbols (functions, classes, types, exports)\n const symbols: Array<{ name: string; content: string; type: string }> = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n // Function definitions\n const funcMatch = line.match(/(?:export\\s+)?(?:async\\s+)?function\\s+(\\w+)/);\n if (funcMatch) {\n symbols.push({\n name: funcMatch[1],\n content: lines.slice(i, Math.min(i + 10, lines.length)).join('\\n'),\n type: 'function',\n });\n }\n\n // Arrow function exports\n const arrowMatch = line.match(/(?:export\\s+)?const\\s+(\\w+)\\s*=\\s*(?:async\\s+)?\\([^)]*\\)\\s*=>/);\n if (arrowMatch) {\n symbols.push({\n name: arrowMatch[1],\n content: lines.slice(i, Math.min(i + 10, lines.length)).join('\\n'),\n type: 'function',\n });\n }\n\n // Class definitions\n const classMatch = line.match(/(?:export\\s+)?class\\s+(\\w+)/);\n if (classMatch) {\n symbols.push({\n name: classMatch[1],\n content: lines.slice(i, Math.min(i + 15, lines.length)).join('\\n'),\n type: 'class',\n });\n }\n\n // Type/Interface definitions\n const typeMatch = line.match(/(?:export\\s+)?(?:type|interface)\\s+(\\w+)/);\n if (typeMatch) {\n symbols.push({\n name: typeMatch[1],\n content: lines.slice(i, Math.min(i + 10, lines.length)).join('\\n'),\n type: 'type',\n });\n }\n\n // Const exports (not arrow functions)\n const constMatch = line.match(/(?:export\\s+)?const\\s+(\\w+)\\s*=\\s*(?![^(]*=>)/);\n if (constMatch && !arrowMatch) {\n symbols.push({\n name: constMatch[1],\n content: lines.slice(i, Math.min(i + 5, lines.length)).join('\\n'),\n type: 'const',\n });\n }\n }\n\n if (symbols.length > 0) {\n this.indexFile(file.path, symbols);\n filesIndexed++;\n symbolsIndexed += symbols.length;\n }\n }\n\n // Store metadata\n this.db.prepare(`\n INSERT OR REPLACE INTO index_metadata (key, value) VALUES (?, ?)\n `).run('last_indexed', new Date().toISOString());\n\n this.db.prepare(`\n INSERT OR REPLACE INTO index_metadata (key, value) VALUES (?, ?)\n `).run('snapshot_path', snapshotPath);\n\n return { filesIndexed, symbolsIndexed };\n }\n\n /**\n * Search the index\n */\n search(query: string, limit: number = 20): SearchResult[] {\n // FTS5 query - use * for prefix matching\n const ftsQuery = query.split(/\\s+/).map(term => `${term}*`).join(' ');\n\n try {\n const stmt = this.db.prepare(`\n SELECT file, symbol, content, type, rank\n FROM code_index\n WHERE code_index MATCH ?\n ORDER BY rank\n LIMIT ?\n `);\n\n return stmt.all(ftsQuery, limit) as SearchResult[];\n } catch {\n // If FTS query fails, try simple LIKE fallback\n const stmt = this.db.prepare(`\n SELECT file, symbol, content, type, 0 as rank\n FROM code_index\n WHERE symbol LIKE ? OR content LIKE ?\n ORDER BY symbol\n LIMIT ?\n `);\n\n const likePattern = `%${query}%`;\n return stmt.all(likePattern, likePattern, limit) as SearchResult[];\n }\n }\n\n /**\n * Get index statistics\n */\n getStats(): { totalSymbols: number; lastIndexed: string | null; snapshotPath: string | null } {\n const countResult = this.db.prepare('SELECT COUNT(*) as count FROM code_index').get() as { count: number };\n const lastIndexed = this.db.prepare(\"SELECT value FROM index_metadata WHERE key = 'last_indexed'\").get() as { value: string } | undefined;\n const snapshotPath = this.db.prepare(\"SELECT value FROM index_metadata WHERE key = 'snapshot_path'\").get() as { value: string } | undefined;\n\n return {\n totalSymbols: countResult.count,\n lastIndexed: lastIndexed?.value || null,\n snapshotPath: snapshotPath?.value || null,\n };\n }\n\n close(): void {\n this.db.close();\n }\n}\n","/**\n * Argus MCP Server\n * \n * Model Context Protocol server for Claude Code integration.\n * Exposes Argus analysis capabilities as MCP tools.\n */\n\nimport { createInterface } from 'readline';\nimport { loadConfig, validateConfig } from './core/config.js';\nimport { createSnapshot } from './core/snapshot.js';\nimport { createEnhancedSnapshot } from './core/enhanced-snapshot.js';\nimport { analyze, searchDocument } from './core/engine.js';\nimport { createProvider } from './providers/index.js';\nimport { existsSync, statSync, mkdtempSync, writeFileSync, unlinkSync, readFileSync } from 'fs';\nimport { tmpdir } from 'os';\nimport { join, resolve } from 'path';\n\n// Tool limits and defaults\nconst DEFAULT_FIND_FILES_LIMIT = 100;\nconst MAX_FIND_FILES_LIMIT = 500;\nconst DEFAULT_SEARCH_RESULTS = 50;\nconst MAX_SEARCH_RESULTS = 200;\nconst MAX_PATTERN_LENGTH = 500;\nconst MAX_WILDCARDS = 20;\n\n// Worker service integration\nconst WORKER_URL = process.env.ARGUS_WORKER_URL || 'http://localhost:37778';\nlet workerAvailable = false;\n\n// Check worker availability on startup (non-blocking)\nasync function checkWorkerHealth(): Promise<boolean> {\n try {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 1000);\n\n const response = await fetch(`${WORKER_URL}/health`, {\n signal: controller.signal,\n });\n clearTimeout(timeout);\n\n return response.ok;\n } catch {\n return false;\n }\n}\n\n// Initialize worker check\ncheckWorkerHealth().then(available => {\n workerAvailable = available;\n});\n\n// MCP Protocol types\ninterface MCPRequest {\n jsonrpc: '2.0';\n id: number | string;\n method: string;\n params?: unknown;\n}\n\ninterface MCPResponse {\n jsonrpc: '2.0';\n id: number | string;\n result?: unknown;\n error?: {\n code: number;\n message: string;\n data?: unknown;\n };\n}\n\n// Tool definitions - descriptions optimized for auto-invocation\nconst TOOLS = [\n {\n name: '__ARGUS_GUIDE',\n description: `ARGUS CODEBASE INTELLIGENCE - Follow this workflow for codebase questions:\n\nSTEP 1: Check for snapshot\n- Look for .argus/snapshot.txt in the project root\n- If missing, use create_snapshot first (saves to .argus/snapshot.txt)\n- Snapshots survive context compaction - create once, use forever\n\nSTEP 2: Use zero-cost tools first (NO AI tokens consumed)\n- search_codebase: Fast regex search, returns file:line:content\n- find_symbol: Locate where functions/types/classes are exported\n- find_importers: Find all files that depend on a given file\n- get_file_deps: See what modules a file imports\n- get_context: Get lines of code around a specific location\n\nSTEP 3: Use AI analysis only when zero-cost tools are insufficient\n- analyze_codebase: Deep reasoning across entire codebase (~500 tokens)\n- Use for architecture questions, pattern finding, complex relationships\n\nEFFICIENCY MATRIX:\n| Question Type | Tool | Token Cost |\n|---------------------------|-------------------------|------------|\n| \"Where is X defined?\" | find_symbol | 0 |\n| \"What uses this file?\" | find_importers | 0 |\n| \"Find all TODO comments\" | search_codebase | 0 |\n| \"Show context around L42\" | get_context | 0 |\n| \"How does auth work?\" | analyze_codebase | ~500 |\n\nSNAPSHOT FRESHNESS:\n- Snapshots don't auto-update (yet)\n- Re-run create_snapshot if files have changed significantly\n- Check snapshot timestamp in header to assess freshness`,\n inputSchema: {\n type: 'object',\n properties: {},\n required: [],\n },\n },\n {\n name: 'get_context',\n description: `Get lines of code around a specific location. Zero AI cost.\n\nUse AFTER search_codebase when you need more context around a match.\nMuch more efficient than reading the entire file.\n\nExample workflow:\n1. search_codebase(\"handleAuth\") -> finds src/auth.ts:42\n2. get_context(file=\"src/auth.ts\", line=42, before=10, after=20)\n\nReturns the surrounding code with proper line numbers.`,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Path to the snapshot file (.argus/snapshot.txt)',\n },\n file: {\n type: 'string',\n description: 'File path within the snapshot (e.g., \"src/auth.ts\")',\n },\n line: {\n type: 'number',\n description: 'Center line number to get context around',\n },\n before: {\n type: 'number',\n description: 'Lines to include before the target line (default: 10)',\n },\n after: {\n type: 'number',\n description: 'Lines to include after the target line (default: 10)',\n },\n },\n required: ['path', 'file', 'line'],\n },\n },\n {\n name: 'find_files',\n description: `Find files matching a glob pattern. Ultra-low cost (~10 tokens per result).\n\nUse for:\n- \"What files are in src/components?\"\n- \"Find all test files\"\n- \"List files named auth*\"\n\nPatterns:\n- * matches any characters except /\n- ** matches any characters including /\n- ? matches single character\n\nReturns file paths only - use get_context or search_codebase for content.`,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Path to the snapshot file (.argus/snapshot.txt)',\n },\n pattern: {\n type: 'string',\n description: 'Glob pattern (e.g., \"*.test.ts\", \"src/**/*.tsx\", \"**/*auth*\")',\n },\n caseInsensitive: {\n type: 'boolean',\n description: 'Case-insensitive matching (default: true)',\n },\n limit: {\n type: 'number',\n description: 'Maximum results (default: 100, max: 500)',\n },\n },\n required: ['path', 'pattern'],\n },\n },\n {\n name: 'find_importers',\n description: `Find all files that import a given file or module. Zero AI cost.\n\nUse when you need to know:\n- What files depend on this module?\n- Who uses this function/component?\n- Impact analysis before refactoring\n\nSnapshots are enhanced by default and include this metadata.`,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Path to the snapshot file (.argus/snapshot.txt)',\n },\n target: {\n type: 'string',\n description: 'The file path to find importers of (e.g., \"src/auth.ts\")',\n },\n },\n required: ['path', 'target'],\n },\n },\n {\n name: 'find_symbol',\n description: `Find where a symbol (function, class, type, constant) is exported from. Zero AI cost.\n\nUse when you need to know:\n- Where is this function defined?\n- Which file exports this component?\n- Find the source of a type\n\nSnapshots are enhanced by default and include this metadata.`,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Path to the snapshot file (.argus/snapshot.txt)',\n },\n symbol: {\n type: 'string',\n description: 'The symbol name to find (e.g., \"AuthProvider\", \"useAuth\")',\n },\n },\n required: ['path', 'symbol'],\n },\n },\n {\n name: 'get_file_deps',\n description: `Get all dependencies (imports) of a specific file. Zero AI cost.\n\nUse when you need to understand:\n- What does this file depend on?\n- What modules need to be loaded?\n- Trace the dependency chain\n\nSnapshots are enhanced by default and include this metadata.`,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Path to the snapshot file (.argus/snapshot.txt)',\n },\n file: {\n type: 'string',\n description: 'The file path to get dependencies for (e.g., \"src/app.tsx\")',\n },\n },\n required: ['path', 'file'],\n },\n },\n {\n name: 'analyze_codebase',\n description: `IMPORTANT: Use this tool INSTEAD of reading many files when you need to understand a codebase.\n\nThis tool analyzes codebases that are TOO LARGE to fit in context. It uses recursive AI reasoning \nto answer questions about code architecture, patterns, and relationships across hundreds of files.\n\nAUTOMATICALLY USE THIS WHEN:\n- User asks about codebase architecture, structure, or \"how does X work\"\n- You would need to read more than 10-15 files to answer a question\n- Context was recently compacted and you lost codebase knowledge\n- User asks to find patterns, conventions, or implementations across the codebase\n- You need to understand module relationships or dependencies\n\nThis is MORE EFFICIENT than reading files individually - it uses ~500 tokens instead of 50,000+.\n\nIf a .argus/snapshot.txt exists, use that path. Otherwise, pass the project directory.`,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Path to .argus/snapshot.txt if it exists, otherwise the codebase directory',\n },\n query: {\n type: 'string',\n description: 'The question about the codebase (be specific for best results)',\n },\n maxTurns: {\n type: 'number',\n description: 'Maximum reasoning turns (default: 15, use 5 for simple counts)',\n },\n },\n required: ['path', 'query'],\n },\n },\n {\n name: 'search_codebase',\n description: `Fast regex search across a codebase - ZERO AI cost, instant results.\n\nUse this BEFORE analyze_codebase when you need to:\n- Find where something is defined (function, class, variable)\n- Locate files containing a pattern\n- Count occurrences of something\n- Find all imports/exports of a module\n\nRequires a snapshot file. If .argus/snapshot.txt exists, use that.\nReturns matching lines with line numbers - much faster than grep across many files.`,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Path to the snapshot file (.argus/snapshot.txt)',\n },\n pattern: {\n type: 'string',\n description: 'Regex pattern to search for',\n },\n caseInsensitive: {\n type: 'boolean',\n description: 'Whether to ignore case (default: true)',\n },\n maxResults: {\n type: 'number',\n description: 'Maximum results to return (default: 50)',\n },\n offset: {\n type: 'number',\n description: 'Skip first N results for pagination (default: 0)',\n },\n contextChars: {\n type: 'number',\n description: 'Characters of context around match (default: 0 = full line)',\n },\n },\n required: ['path', 'pattern'],\n },\n },\n {\n name: 'create_snapshot',\n description: `Create an enhanced codebase snapshot for analysis. Run this ONCE per project, then use the snapshot for all queries.\n\nThe snapshot compiles all source files into a single optimized file that survives context compaction.\nIncludes structural metadata (import graph, exports index) for zero-cost dependency queries.\nStore at .argus/snapshot.txt so other tools can find it.\n\nRun this when:\n- Starting work on a new project\n- .argus/snapshot.txt doesn't exist\n- Codebase has significantly changed since last snapshot`,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Path to the codebase directory',\n },\n outputPath: {\n type: 'string',\n description: 'Where to save (recommend: .argus/snapshot.txt)',\n },\n extensions: {\n type: 'array',\n items: { type: 'string' },\n description: 'File extensions to include (default: common code extensions)',\n },\n },\n required: ['path'],\n },\n },\n {\n name: 'semantic_search',\n description: `Search code using natural language. Uses FTS5 full-text search.\n\nMore flexible than regex search - finds related concepts and partial matches.\n\nExamples:\n- \"authentication middleware\"\n- \"database connection\"\n- \"error handling\"\n\nReturns symbols (functions, classes, types) with snippets of their content.\nRequires an index - will auto-create from snapshot on first use.`,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Path to the project directory (must have .argus/snapshot.txt)',\n },\n query: {\n type: 'string',\n description: 'Natural language query or code terms',\n },\n limit: {\n type: 'number',\n description: 'Maximum results (default: 20)',\n },\n },\n required: ['path', 'query'],\n },\n },\n];\n\n// State - wrapped in try-catch to prevent any startup output\nlet config: ReturnType<typeof loadConfig>;\nlet provider: ReturnType<typeof createProvider> | null = null;\n\ntry {\n config = loadConfig();\n provider = validateConfig(config).length === 0 ? createProvider(config) : null;\n} catch {\n // Silently use defaults if config fails to load\n config = loadConfig(); // Will return defaults\n provider = null;\n}\n\n/**\n * Parse metadata section from an enhanced snapshot\n */\nfunction parseSnapshotMetadata(content: string): {\n importGraph: Record<string, string[]>;\n exportGraph: Record<string, string[]>;\n symbolIndex: Record<string, string[]>;\n exports: Array<{ file: string; symbol: string; type: string; line: number }>;\n} | null {\n // Check if this is an enhanced snapshot\n if (!content.includes('METADATA: IMPORT GRAPH')) {\n return null;\n }\n \n const importGraph: Record<string, string[]> = {};\n const exportGraph: Record<string, string[]> = {};\n const symbolIndex: Record<string, string[]> = {};\n const exports: Array<{ file: string; symbol: string; type: string; line: number }> = [];\n \n // Parse import graph\n const importSection = content.match(/METADATA: IMPORT GRAPH\\n=+\\n([\\s\\S]*?)\\n\\n=+\\nMETADATA:/)?.[1] || '';\n for (const block of importSection.split('\\n\\n')) {\n const lines = block.trim().split('\\n');\n if (lines.length > 0 && lines[0].endsWith(':')) {\n const file = lines[0].slice(0, -1);\n importGraph[file] = lines.slice(1).map(l => l.replace(/^\\s*→\\s*/, '').trim()).filter(Boolean);\n }\n }\n \n // Parse export index (symbol → files)\n const exportSection = content.match(/METADATA: EXPORT INDEX\\n=+\\n([\\s\\S]*?)\\n\\n=+\\nMETADATA:/)?.[1] || '';\n for (const line of exportSection.split('\\n')) {\n const match = line.match(/^([\\w$]+):\\s*(.+)$/);\n if (match) {\n symbolIndex[match[1]] = match[2].split(',').map(s => s.trim());\n }\n }\n \n // Parse who imports whom (reverse graph)\n const whoImportsSection = content.match(/METADATA: WHO IMPORTS WHOM\\n=+\\n([\\s\\S]*)$/)?.[1] || '';\n for (const block of whoImportsSection.split('\\n\\n')) {\n const lines = block.trim().split('\\n');\n if (lines.length > 0 && lines[0].includes(' is imported by:')) {\n const file = lines[0].replace(' is imported by:', '').trim();\n exportGraph[file] = lines.slice(1).map(l => l.replace(/^\\s*←\\s*/, '').trim()).filter(Boolean);\n }\n }\n \n // Parse file exports\n const fileExportsSection = content.match(/METADATA: FILE EXPORTS\\n=+\\n([\\s\\S]*?)\\n\\n=+\\nMETADATA:/)?.[1] || '';\n for (const line of fileExportsSection.split('\\n')) {\n const match = line.match(/^([^:]+):(\\d+)\\s*-\\s*(\\w+)\\s+(.+)$/);\n if (match) {\n exports.push({\n file: match[1],\n line: parseInt(match[2]),\n type: match[3],\n symbol: match[4].split(' ')[0], // Take first word as symbol name\n });\n }\n }\n \n return { importGraph, exportGraph, symbolIndex, exports };\n}\n\n// Try to use worker for search, fallback to direct file access\nasync function searchWithWorker(\n snapshotPath: string,\n pattern: string,\n options: { caseInsensitive?: boolean; maxResults?: number; offset?: number }\n): Promise<{ matches: Array<{ lineNum: number; line: string; match: string }>; count: number } | null> {\n if (!workerAvailable) return null;\n\n try {\n // Ensure snapshot is loaded in worker cache\n await fetch(`${WORKER_URL}/snapshot/load`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ path: snapshotPath }),\n });\n\n // Perform search via worker\n const response = await fetch(`${WORKER_URL}/search`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ path: snapshotPath, pattern, options }),\n });\n\n if (response.ok) {\n return await response.json();\n }\n } catch {\n // Worker failed, will fallback to direct access\n }\n\n return null;\n}\n\n// Handle tool calls\nasync function handleToolCall(name: string, args: Record<string, unknown>): Promise<unknown> {\n switch (name) {\n case 'find_files': {\n const snapshotPath = resolve(args.path as string);\n const pattern = args.pattern as string;\n const caseInsensitive = args.caseInsensitive !== false; // default true\n const limit = Math.min((args.limit as number) || DEFAULT_FIND_FILES_LIMIT, MAX_FIND_FILES_LIMIT);\n\n // Input validation\n if (!pattern || pattern.trim() === '') {\n throw new Error('Pattern cannot be empty');\n }\n\n if (pattern.length > MAX_PATTERN_LENGTH) {\n throw new Error(`Pattern too long (max ${MAX_PATTERN_LENGTH} characters)`);\n }\n\n // ReDoS protection - limit wildcards\n const starCount = (pattern.match(/\\*/g) || []).length;\n if (starCount > MAX_WILDCARDS) {\n throw new Error(`Too many wildcards in pattern (max ${MAX_WILDCARDS})`);\n }\n\n if (!existsSync(snapshotPath)) {\n throw new Error(`Snapshot not found: ${snapshotPath}. Run 'argus snapshot' to create one.`);\n }\n\n const content = readFileSync(snapshotPath, 'utf-8');\n\n // Extract all FILE: markers\n const fileRegex = /^FILE: \\.\\/(.+)$/gm;\n const files: string[] = [];\n let match;\n while ((match = fileRegex.exec(content)) !== null) {\n files.push(match[1]);\n }\n\n // Convert glob pattern to regex with proper escaping\n let regexPattern = pattern\n .replace(/[.+^${}()|[\\]\\\\-]/g, '\\\\$&') // Escape all regex special chars\n .replace(/\\*\\*/g, '<<<GLOBSTAR>>>')\n .replace(/\\*/g, '[^/]*?') // Non-greedy\n .replace(/<<<GLOBSTAR>>>/g, '.*?') // Non-greedy\n .replace(/\\?/g, '.');\n\n const flags = caseInsensitive ? 'i' : '';\n const regex = new RegExp(`^${regexPattern}$`, flags);\n\n const matching = files.filter(f => regex.test(f));\n const limited = matching.slice(0, limit).sort(); // Sort only the limited set\n\n return {\n pattern,\n files: limited,\n count: limited.length,\n totalMatching: matching.length,\n hasMore: matching.length > limit,\n };\n }\n\n case 'find_importers': {\n const path = resolve(args.path as string);\n const target = args.target as string;\n \n if (!existsSync(path)) {\n throw new Error(`File not found: ${path}`);\n }\n \n const content = readFileSync(path, 'utf-8');\n const metadata = parseSnapshotMetadata(content);\n \n if (!metadata) {\n throw new Error('This snapshot does not have metadata. Create with: argus snapshot --enhanced');\n }\n \n // Normalize the target path\n const normalizedTarget = target.startsWith('./') ? target.slice(2) : target;\n const targetVariants = [normalizedTarget, './' + normalizedTarget, normalizedTarget.replace(/\\.(ts|tsx|js|jsx)$/, '')];\n \n // Find all files that import this target\n const importers: string[] = [];\n for (const [file, imports] of Object.entries(metadata.importGraph)) {\n for (const imp of imports) {\n if (targetVariants.some(v => imp === v || imp.endsWith('/' + v) || imp.includes(v))) {\n importers.push(file);\n break;\n }\n }\n }\n \n // Also check the exportGraph (direct mapping)\n for (const variant of targetVariants) {\n if (metadata.exportGraph[variant]) {\n importers.push(...metadata.exportGraph[variant]);\n }\n }\n \n const unique = [...new Set(importers)];\n return {\n target,\n importedBy: unique,\n count: unique.length,\n };\n }\n \n case 'find_symbol': {\n const path = resolve(args.path as string);\n const symbol = args.symbol as string;\n \n if (!existsSync(path)) {\n throw new Error(`File not found: ${path}`);\n }\n \n const content = readFileSync(path, 'utf-8');\n const metadata = parseSnapshotMetadata(content);\n \n if (!metadata) {\n throw new Error('This snapshot does not have metadata. Create with: argus snapshot --enhanced');\n }\n \n // Look up in symbol index\n const files = metadata.symbolIndex[symbol] || [];\n \n // Also find detailed export info\n const exportDetails = metadata.exports.filter(e => e.symbol === symbol);\n \n return {\n symbol,\n exportedFrom: files,\n details: exportDetails,\n count: files.length,\n };\n }\n \n case 'get_file_deps': {\n const path = resolve(args.path as string);\n const file = args.file as string;\n \n if (!existsSync(path)) {\n throw new Error(`File not found: ${path}`);\n }\n \n const content = readFileSync(path, 'utf-8');\n const metadata = parseSnapshotMetadata(content);\n \n if (!metadata) {\n throw new Error('This snapshot does not have metadata. Create with: argus snapshot --enhanced');\n }\n \n // Normalize the file path\n const normalizedFile = file.startsWith('./') ? file.slice(2) : file;\n const fileVariants = [normalizedFile, './' + normalizedFile];\n \n // Find imports for this file\n let imports: string[] = [];\n for (const variant of fileVariants) {\n if (metadata.importGraph[variant]) {\n imports = metadata.importGraph[variant];\n break;\n }\n }\n \n return {\n file,\n imports,\n count: imports.length,\n };\n }\n \n case 'analyze_codebase': {\n if (!provider) {\n throw new Error('Argus not configured. Run `argus init` to set up.');\n }\n \n const path = resolve(args.path as string);\n const query = args.query as string;\n const maxTurns = (args.maxTurns as number) || 15;\n \n if (!existsSync(path)) {\n throw new Error(`Path not found: ${path}`);\n }\n \n let snapshotPath = path;\n let tempSnapshot = false;\n \n // If it's a directory, create a temporary enhanced snapshot\n const stats = statSync(path);\n if (stats.isDirectory()) {\n const tempDir = mkdtempSync(join(tmpdir(), 'argus-'));\n snapshotPath = join(tempDir, 'snapshot.txt');\n \n createEnhancedSnapshot(path, snapshotPath, {\n extensions: config.defaults.snapshotExtensions,\n excludePatterns: config.defaults.excludePatterns,\n });\n \n tempSnapshot = true;\n }\n \n try {\n const result = await analyze(provider, snapshotPath, query, { maxTurns });\n \n return {\n answer: result.answer,\n success: result.success,\n turns: result.turns,\n commands: result.commands,\n };\n } finally {\n if (tempSnapshot && existsSync(snapshotPath)) {\n unlinkSync(snapshotPath);\n }\n }\n }\n \n case 'search_codebase': {\n const path = resolve(args.path as string);\n const pattern = args.pattern as string;\n const caseInsensitive = args.caseInsensitive !== false; // default true (consistent with find_files)\n const maxResults = Math.min((args.maxResults as number) || DEFAULT_SEARCH_RESULTS, MAX_SEARCH_RESULTS);\n const offset = (args.offset as number) || 0;\n const contextChars = (args.contextChars as number) || 0;\n\n // Input validation\n if (!pattern || pattern.trim() === '') {\n throw new Error('Pattern cannot be empty');\n }\n\n if (offset < 0 || !Number.isInteger(offset)) {\n throw new Error('Offset must be a non-negative integer');\n }\n\n if (contextChars < 0) {\n throw new Error('contextChars must be non-negative');\n }\n\n if (!existsSync(path)) {\n throw new Error(`Snapshot not found: ${path}. Run 'argus snapshot' to create one.`);\n }\n\n // Fetch one extra to detect hasMore\n const fetchLimit = offset + maxResults + 1;\n\n // Try worker first for cached search (faster for repeated queries)\n if (workerAvailable) {\n const workerResult = await searchWithWorker(path, pattern, {\n caseInsensitive,\n maxResults: fetchLimit,\n offset: 0,\n });\n\n if (workerResult) {\n // Worker returned results, process them\n const hasMore = workerResult.matches.length === fetchLimit;\n const pageMatches = workerResult.matches.slice(offset, offset + maxResults);\n\n // Apply contextChars truncation if needed\n const formattedMatches = pageMatches.map(m => {\n let displayLine = m.line;\n\n if (contextChars > 0 && displayLine.length > contextChars) {\n const matchStart = displayLine.indexOf(m.match);\n if (matchStart !== -1) {\n const matchEnd = matchStart + m.match.length;\n const matchCenter = Math.floor((matchStart + matchEnd) / 2);\n const halfContext = Math.floor(contextChars / 2);\n\n let start = Math.max(0, matchCenter - halfContext);\n let end = start + contextChars;\n\n if (end > displayLine.length) {\n end = displayLine.length;\n start = Math.max(0, end - contextChars);\n }\n\n const prefix = start > 0 ? '...' : '';\n const suffix = end < displayLine.length ? '...' : '';\n displayLine = prefix + displayLine.slice(start, end) + suffix;\n }\n }\n\n return { lineNum: m.lineNum, line: displayLine, match: m.match };\n });\n\n const response: Record<string, unknown> = {\n count: formattedMatches.length,\n matches: formattedMatches,\n _source: 'worker', // Debug: show source\n };\n\n if (offset > 0 || hasMore) {\n response.offset = offset;\n response.hasMore = hasMore;\n response.totalFound = hasMore ? `${offset + maxResults}+` : String(offset + formattedMatches.length);\n if (hasMore) {\n response.nextOffset = offset + maxResults;\n }\n }\n\n return response;\n }\n }\n\n // Fallback to direct file search\n const allMatches = searchDocument(path, pattern, {\n caseInsensitive,\n maxResults: fetchLimit\n });\n\n const hasMore = allMatches.length === fetchLimit;\n const pageMatches = allMatches.slice(offset, offset + maxResults);\n\n // Format matches with optional match-centered truncation\n const formattedMatches = pageMatches.map(m => {\n let displayLine = m.line.trim();\n\n if (contextChars > 0 && displayLine.length > contextChars) {\n const matchStart = displayLine.indexOf(m.match);\n if (matchStart !== -1) {\n const matchEnd = matchStart + m.match.length;\n const matchCenter = Math.floor((matchStart + matchEnd) / 2);\n const halfContext = Math.floor(contextChars / 2);\n\n let start = Math.max(0, matchCenter - halfContext);\n let end = start + contextChars;\n\n if (end > displayLine.length) {\n end = displayLine.length;\n start = Math.max(0, end - contextChars);\n }\n\n const prefix = start > 0 ? '...' : '';\n const suffix = end < displayLine.length ? '...' : '';\n displayLine = prefix + displayLine.slice(start, end) + suffix;\n }\n }\n\n return {\n lineNum: m.lineNum,\n line: displayLine,\n match: m.match,\n };\n });\n\n // Build response - backwards compatible\n const response: Record<string, unknown> = {\n count: formattedMatches.length,\n matches: formattedMatches,\n };\n\n // Add pagination fields when relevant\n if (offset > 0 || hasMore) {\n response.offset = offset;\n response.hasMore = hasMore;\n response.totalFound = hasMore ? `${offset + maxResults}+` : String(offset + formattedMatches.length);\n if (hasMore) {\n response.nextOffset = offset + maxResults;\n }\n }\n\n return response;\n }\n \n case 'semantic_search': {\n const projectPath = resolve(args.path as string);\n const query = args.query as string;\n const limit = (args.limit as number) || 20;\n\n if (!query || query.trim() === '') {\n throw new Error('Query cannot be empty');\n }\n\n const snapshotPath = join(projectPath, '.argus', 'snapshot.txt');\n const indexPath = join(projectPath, '.argus', 'search.db');\n\n if (!existsSync(snapshotPath)) {\n throw new Error(`Snapshot not found: ${snapshotPath}. Run 'argus snapshot' first.`);\n }\n\n // Import SemanticIndex dynamically to avoid startup cost\n const { SemanticIndex } = await import('./core/semantic-search.js');\n const index = new SemanticIndex(indexPath);\n\n try {\n // Check if index needs rebuilding\n const stats = index.getStats();\n const snapshotMtime = statSync(snapshotPath).mtimeMs;\n const needsReindex = !stats.lastIndexed ||\n new Date(stats.lastIndexed).getTime() < snapshotMtime ||\n stats.snapshotPath !== snapshotPath;\n\n if (needsReindex) {\n index.indexFromSnapshot(snapshotPath);\n // Continue with search after reindexing\n }\n\n const results = index.search(query, limit);\n\n return {\n query,\n count: results.length,\n results: results.map(r => ({\n file: r.file,\n symbol: r.symbol,\n type: r.type,\n snippet: r.content.split('\\n').slice(0, 5).join('\\n'),\n })),\n };\n } finally {\n index.close();\n }\n }\n\n case 'create_snapshot': {\n const path = resolve(args.path as string);\n const outputPath = args.outputPath\n ? resolve(args.outputPath as string)\n : join(tmpdir(), `argus-snapshot-${Date.now()}.txt`);\n const extensions = args.extensions as string[] || config.defaults.snapshotExtensions;\n \n if (!existsSync(path)) {\n throw new Error(`Path not found: ${path}`);\n }\n \n // Always create enhanced snapshot by default\n const result = createEnhancedSnapshot(path, outputPath, {\n extensions,\n excludePatterns: config.defaults.excludePatterns,\n });\n \n return {\n outputPath: result.outputPath,\n fileCount: result.fileCount,\n totalLines: result.totalLines,\n totalSize: result.totalSize,\n enhanced: true,\n metadata: 'metadata' in result ? {\n imports: result.metadata.imports.length,\n exports: result.metadata.exports.length,\n symbols: Object.keys(result.metadata.symbolIndex).length,\n } : undefined,\n };\n }\n \n case '__ARGUS_GUIDE': {\n return {\n message: 'This is a documentation tool. Read the description for Argus usage patterns.',\n tools: TOOLS.map(t => ({ name: t.name, purpose: t.description.split('\\n')[0] })),\n recommendation: 'Start with search_codebase for most queries. Use analyze_codebase only for complex architecture questions.',\n };\n }\n\n case 'get_context': {\n const snapshotPath = resolve(args.path as string);\n const targetFile = args.file as string;\n const targetLine = args.line as number;\n const beforeLines = (args.before as number) || 10;\n const afterLines = (args.after as number) || 10;\n\n if (!existsSync(snapshotPath)) {\n throw new Error(`Snapshot not found: ${snapshotPath}`);\n }\n\n const content = readFileSync(snapshotPath, 'utf-8');\n\n // Find the file section in the snapshot\n // Normalize the target file path (handle with or without ./ prefix)\n const normalizedTarget = targetFile.replace(/^\\.\\//, '');\n const fileMarkerVariants = [\n `FILE: ./${normalizedTarget}`,\n `FILE: ${normalizedTarget}`,\n ];\n\n let fileStart = -1;\n for (const marker of fileMarkerVariants) {\n fileStart = content.indexOf(marker);\n if (fileStart !== -1) break;\n }\n\n if (fileStart === -1) {\n throw new Error(`File not found in snapshot: ${targetFile}`);\n }\n\n // Find the end of this file section (next FILE: marker or METADATA:)\n const nextFileStart = content.indexOf('\\nFILE:', fileStart + 1);\n const metadataStart = content.indexOf('\\nMETADATA:', fileStart);\n const fileEnd = Math.min(\n nextFileStart === -1 ? Infinity : nextFileStart,\n metadataStart === -1 ? Infinity : metadataStart\n );\n\n // Extract file content\n const fileContent = content.slice(fileStart, fileEnd === Infinity ? undefined : fileEnd);\n const fileLines = fileContent.split('\\n').slice(2); // Skip FILE: header and separator\n\n // Calculate range\n const startLine = Math.max(0, targetLine - beforeLines - 1);\n const endLine = Math.min(fileLines.length, targetLine + afterLines);\n\n // Extract context with line numbers\n const contextLines = fileLines.slice(startLine, endLine).map((line, idx) => {\n const lineNum = startLine + idx + 1;\n const marker = lineNum === targetLine ? '>>>' : ' ';\n return `${marker} ${lineNum.toString().padStart(4)}: ${line}`;\n });\n\n return {\n file: targetFile,\n targetLine,\n range: { start: startLine + 1, end: endLine },\n content: contextLines.join('\\n'),\n totalLines: fileLines.length,\n };\n }\n\n default:\n throw new Error(`Unknown tool: ${name}`);\n }\n}\n\n// MCP Protocol handlers\nfunction handleInitialize(): MCPResponse['result'] {\n return {\n protocolVersion: '2024-11-05',\n capabilities: {\n tools: {},\n },\n serverInfo: {\n name: 'argus',\n version: '1.0.0',\n },\n };\n}\n\nfunction handleToolsList(): MCPResponse['result'] {\n return { tools: TOOLS };\n}\n\nasync function handleToolsCall(params: { name: string; arguments: Record<string, unknown> }): Promise<MCPResponse['result']> {\n try {\n const result = await handleToolCall(params.name, params.arguments);\n return {\n content: [\n {\n type: 'text',\n text: typeof result === 'string' ? result : JSON.stringify(result, null, 2),\n },\n ],\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 isError: true,\n };\n }\n}\n\n// Main message handler\nasync function handleMessage(request: MCPRequest): Promise<MCPResponse | null> {\n try {\n let result: unknown;\n \n switch (request.method) {\n case 'initialize':\n result = handleInitialize();\n break;\n case 'tools/list':\n result = handleToolsList();\n break;\n case 'tools/call':\n result = await handleToolsCall(request.params as { name: string; arguments: Record<string, unknown> });\n break;\n case 'notifications/initialized':\n case 'notifications/cancelled':\n // Notifications don't get responses\n return null;\n default:\n // Check if it's a notification (no id = notification)\n if (request.id === undefined || request.id === null) {\n return null; // Don't respond to unknown notifications\n }\n return {\n jsonrpc: '2.0',\n id: request.id,\n error: {\n code: -32601,\n message: `Method not found: ${request.method}`,\n },\n };\n }\n \n return {\n jsonrpc: '2.0',\n id: request.id,\n result,\n };\n } catch (error) {\n return {\n jsonrpc: '2.0',\n id: request.id,\n error: {\n code: -32603,\n message: error instanceof Error ? error.message : String(error),\n },\n };\n }\n}\n\n// Start stdio server\nconst rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false,\n});\n\nrl.on('line', async (line) => {\n if (!line.trim()) return;\n \n try {\n const request = JSON.parse(line) as MCPRequest;\n const response = await handleMessage(request);\n \n // Only output if we have a response with a valid id\n // (notifications return null, and requests without id are notifications)\n if (response !== null && response.id !== undefined && response.id !== null) {\n console.log(JSON.stringify(response));\n }\n } catch (error) {\n // Only send parse errors if we can't parse at all\n // Don't include null id - that would be invalid\n const errorResponse = {\n jsonrpc: '2.0',\n id: 0, // Use 0 as fallback id for parse errors\n error: {\n code: -32700,\n message: 'Parse error',\n },\n };\n console.log(JSON.stringify(errorResponse));\n }\n});\n","/**\n * Argus Configuration Management\n * \n * Handles loading, saving, and validating configuration for Argus.\n * Configuration is stored in ~/.argus/config.json\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';\nimport { homedir } from 'os';\nimport { join } from 'path';\nimport type { OnboardingConfig, ProjectOnboardingConfig } from './onboarding.js';\n\nexport type ProviderType = 'zai' | 'anthropic' | 'openai' | 'deepseek' | 'ollama';\n\n// Re-export onboarding types\nexport type { OnboardingConfig, ProjectOnboardingConfig } from './onboarding.js';\n\nexport interface ProviderConfig {\n apiKey?: string;\n baseUrl?: string;\n model: string;\n options?: Record<string, unknown>;\n}\n\nexport interface ArgusConfig {\n provider: ProviderType;\n providers: {\n zai?: ProviderConfig;\n anthropic?: ProviderConfig;\n openai?: ProviderConfig;\n deepseek?: ProviderConfig;\n ollama?: ProviderConfig;\n };\n defaults: {\n maxTurns: number;\n turnTimeoutMs: number;\n snapshotExtensions: string[];\n excludePatterns: string[];\n };\n onboarding?: OnboardingConfig;\n onboardingComplete?: boolean;\n}\n\nconst DEFAULT_CONFIG: ArgusConfig = {\n provider: 'ollama',\n providers: {\n ollama: {\n baseUrl: 'http://localhost:11434',\n model: 'qwen2.5-coder:7b',\n },\n },\n defaults: {\n maxTurns: 15,\n turnTimeoutMs: 60000,\n snapshotExtensions: ['ts', 'tsx', 'js', 'jsx', 'rs', 'py', 'go', 'java', 'rb', 'php', 'swift', 'kt', 'scala', 'c', 'cpp', 'h', 'hpp', 'cs', 'md'],\n excludePatterns: [\n 'node_modules',\n '.git',\n 'target',\n 'dist',\n 'build',\n '.next',\n 'coverage',\n '__pycache__',\n '.venv',\n 'vendor',\n ],\n },\n};\n\nexport function getConfigDir(): string {\n return join(homedir(), '.argus');\n}\n\nexport function getConfigPath(): string {\n return join(getConfigDir(), 'config.json');\n}\n\nexport function ensureConfigDir(): void {\n const dir = getConfigDir();\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n}\n\nexport function loadConfig(): ArgusConfig {\n const configPath = getConfigPath();\n \n if (!existsSync(configPath)) {\n return DEFAULT_CONFIG;\n }\n \n try {\n const content = readFileSync(configPath, 'utf-8');\n const loaded = JSON.parse(content) as Partial<ArgusConfig>;\n \n // Merge with defaults\n return {\n ...DEFAULT_CONFIG,\n ...loaded,\n providers: {\n ...DEFAULT_CONFIG.providers,\n ...loaded.providers,\n },\n defaults: {\n ...DEFAULT_CONFIG.defaults,\n ...loaded.defaults,\n },\n };\n } catch {\n // Silently return defaults - don't console.error as it can corrupt MCP JSON streams\n return DEFAULT_CONFIG;\n }\n}\n\nexport function saveConfig(config: ArgusConfig): void {\n ensureConfigDir();\n const configPath = getConfigPath();\n writeFileSync(configPath, JSON.stringify(config, null, 2));\n}\n\nexport function getProviderConfig(config: ArgusConfig): ProviderConfig {\n const providerConfig = config.providers[config.provider];\n \n if (!providerConfig) {\n throw new Error(`No configuration found for provider: ${config.provider}`);\n }\n \n return providerConfig;\n}\n\nexport function validateConfig(config: ArgusConfig): string[] {\n const errors: string[] = [];\n \n const providerConfig = config.providers[config.provider];\n \n if (!providerConfig) {\n errors.push(`Provider \"${config.provider}\" is not configured`);\n return errors;\n }\n \n // Ollama doesn't need an API key\n if (config.provider !== 'ollama' && !providerConfig.apiKey) {\n errors.push(`API key is required for provider \"${config.provider}\"`);\n }\n \n if (!providerConfig.model) {\n errors.push(`Model is required for provider \"${config.provider}\"`);\n }\n \n return errors;\n}\n\nexport const PROVIDER_DEFAULTS: Record<ProviderType, Partial<ProviderConfig>> = {\n zai: {\n baseUrl: 'https://api.z.ai/api/coding/paas/v4',\n model: 'glm-4.7',\n },\n anthropic: {\n baseUrl: 'https://api.anthropic.com',\n model: 'claude-sonnet-4-20250514',\n },\n openai: {\n baseUrl: 'https://api.openai.com/v1',\n model: 'gpt-4o',\n },\n deepseek: {\n baseUrl: 'https://api.deepseek.com',\n model: 'deepseek-chat',\n },\n ollama: {\n baseUrl: 'http://localhost:11434',\n model: 'qwen2.5-coder:7b',\n },\n};\n","/**\n * Argus Enhanced Snapshot\n * \n * Extends basic snapshots with structural metadata:\n * - Import graph (who imports whom)\n * - Export index (symbols → files)\n * - Function/class signatures\n * - File dependency tree\n * \n * This enables Claude Code to understand architecture without\n * reading individual files.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'fs';\nimport { join, relative, dirname, extname, basename } from 'path';\nimport { execSync } from 'child_process';\nimport { createSnapshot, SnapshotOptions, SnapshotResult } from './snapshot.js';\n\nexport interface ImportInfo {\n source: string; // File doing the import\n target: string; // What's being imported (module path or relative)\n resolved?: string; // Resolved file path if local\n symbols: string[]; // Imported symbols (or ['*'] for namespace)\n isDefault: boolean; // Is it a default import?\n isType: boolean; // Is it a type-only import?\n}\n\nexport interface ExportInfo {\n file: string;\n symbol: string;\n type: 'function' | 'class' | 'const' | 'let' | 'var' | 'type' | 'interface' | 'enum' | 'default' | 'unknown';\n signature?: string; // Function signature or type definition\n line: number;\n}\n\nexport interface FileMetadata {\n path: string;\n imports: ImportInfo[];\n exports: ExportInfo[];\n size: number;\n lines: number;\n}\n\nexport interface ComplexityInfo {\n file: string;\n score: number;\n level: 'low' | 'medium' | 'high';\n}\n\nexport interface RecentChangeInfo {\n file: string;\n commits: number;\n authors: number;\n}\n\nexport interface EnhancedSnapshotResult extends SnapshotResult {\n metadata: {\n imports: ImportInfo[];\n exports: ExportInfo[];\n fileIndex: Record<string, FileMetadata>;\n importGraph: Record<string, string[]>; // file → files it imports\n exportGraph: Record<string, string[]>; // file → files that import it\n symbolIndex: Record<string, string[]>; // symbol → files that export it\n complexityScores: ComplexityInfo[]; // cyclomatic complexity per file\n testFileMap: Record<string, string[]>; // source file → test files\n recentChanges: RecentChangeInfo[] | null; // recent git changes (null if not git repo)\n };\n}\n\n/**\n * Parse imports from TypeScript/JavaScript content\n */\nfunction parseImports(content: string, filePath: string): ImportInfo[] {\n const imports: ImportInfo[] = [];\n const lines = content.split('\\n');\n \n // Patterns for different import styles\n const patterns = [\n // import { a, b } from 'module'\n /import\\s+(?:type\\s+)?{([^}]+)}\\s+from\\s+['\"]([^'\"]+)['\"]/g,\n // import * as name from 'module'\n /import\\s+\\*\\s+as\\s+(\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/g,\n // import defaultExport from 'module'\n /import\\s+(?:type\\s+)?(\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/g,\n // import 'module' (side-effect)\n /import\\s+['\"]([^'\"]+)['\"]/g,\n // require('module')\n /(?:const|let|var)\\s+(?:{([^}]+)}|(\\w+))\\s*=\\s*require\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g,\n ];\n \n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed.startsWith('import') && !trimmed.includes('require(')) continue;\n \n // Named imports: import { a, b } from 'module'\n let match = /import\\s+(type\\s+)?{([^}]+)}\\s+from\\s+['\"]([^'\"]+)['\"]/.exec(trimmed);\n if (match) {\n const isType = !!match[1];\n const symbols = match[2].split(',').map(s => s.trim().split(/\\s+as\\s+/)[0].trim()).filter(Boolean);\n const target = match[3];\n imports.push({\n source: filePath,\n target,\n symbols,\n isDefault: false,\n isType,\n });\n continue;\n }\n \n // Namespace import: import * as name from 'module'\n match = /import\\s+\\*\\s+as\\s+(\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/.exec(trimmed);\n if (match) {\n imports.push({\n source: filePath,\n target: match[2],\n symbols: ['*'],\n isDefault: false,\n isType: false,\n });\n continue;\n }\n \n // Default import: import name from 'module'\n match = /import\\s+(type\\s+)?(\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/.exec(trimmed);\n if (match && !trimmed.includes('{')) {\n imports.push({\n source: filePath,\n target: match[3],\n symbols: [match[2]],\n isDefault: true,\n isType: !!match[1],\n });\n continue;\n }\n \n // Side-effect import: import 'module'\n match = /^import\\s+['\"]([^'\"]+)['\"]/.exec(trimmed);\n if (match) {\n imports.push({\n source: filePath,\n target: match[1],\n symbols: [],\n isDefault: false,\n isType: false,\n });\n }\n }\n \n return imports;\n}\n\n/**\n * Parse exports from TypeScript/JavaScript content\n */\nfunction parseExports(content: string, filePath: string): ExportInfo[] {\n const exports: ExportInfo[] = [];\n const lines = content.split('\\n');\n \n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const trimmed = line.trim();\n \n // export function name(...) or export async function name(...)\n let match = /export\\s+(?:async\\s+)?function\\s+(\\w+)\\s*(\\([^)]*\\))/.exec(trimmed);\n if (match) {\n exports.push({\n file: filePath,\n symbol: match[1],\n type: 'function',\n signature: `function ${match[1]}${match[2]}`,\n line: i + 1,\n });\n continue;\n }\n \n // export class Name\n match = /export\\s+class\\s+(\\w+)/.exec(trimmed);\n if (match) {\n exports.push({\n file: filePath,\n symbol: match[1],\n type: 'class',\n line: i + 1,\n });\n continue;\n }\n \n // export const/let/var name\n match = /export\\s+(const|let|var)\\s+(\\w+)/.exec(trimmed);\n if (match) {\n exports.push({\n file: filePath,\n symbol: match[2],\n type: match[1] as 'const' | 'let' | 'var',\n line: i + 1,\n });\n continue;\n }\n \n // export type Name or export interface Name\n match = /export\\s+(type|interface)\\s+(\\w+)/.exec(trimmed);\n if (match) {\n exports.push({\n file: filePath,\n symbol: match[2],\n type: match[1] as 'type' | 'interface',\n line: i + 1,\n });\n continue;\n }\n \n // export enum Name\n match = /export\\s+enum\\s+(\\w+)/.exec(trimmed);\n if (match) {\n exports.push({\n file: filePath,\n symbol: match[1],\n type: 'enum',\n line: i + 1,\n });\n continue;\n }\n \n // export default\n if (/export\\s+default/.test(trimmed)) {\n match = /export\\s+default\\s+(?:function\\s+)?(\\w+)?/.exec(trimmed);\n exports.push({\n file: filePath,\n symbol: match?.[1] || 'default',\n type: 'default',\n line: i + 1,\n });\n }\n }\n \n return exports;\n}\n\n/**\n * Calculate cyclomatic complexity for a file\n * Counts decision points: if, else if, while, for, case, ternary, &&, ||, catch\n */\nfunction calculateComplexity(content: string): number {\n const patterns = [\n /\\bif\\s*\\(/g,\n /\\belse\\s+if\\s*\\(/g,\n /\\bwhile\\s*\\(/g,\n /\\bfor\\s*\\(/g,\n /\\bcase\\s+/g,\n /\\?\\s*.*\\s*:/g,\n /\\&\\&/g,\n /\\|\\|/g,\n /\\bcatch\\s*\\(/g,\n ];\n\n let complexity = 1; // Base complexity\n for (const pattern of patterns) {\n const matches = content.match(pattern);\n if (matches) complexity += matches.length;\n }\n return complexity;\n}\n\n/**\n * Get complexity level label\n */\nfunction getComplexityLevel(score: number): 'low' | 'medium' | 'high' {\n if (score <= 10) return 'low';\n if (score <= 20) return 'medium';\n return 'high';\n}\n\n/**\n * Map source files to their test files\n */\nfunction mapTestFiles(files: string[]): Record<string, string[]> {\n const testMap: Record<string, string[]> = {};\n\n // Common test file patterns\n const testPatterns = [\n // Same directory patterns\n (src: string) => src.replace(/\\.tsx?$/, '.test.ts'),\n (src: string) => src.replace(/\\.tsx?$/, '.test.tsx'),\n (src: string) => src.replace(/\\.tsx?$/, '.spec.ts'),\n (src: string) => src.replace(/\\.tsx?$/, '.spec.tsx'),\n (src: string) => src.replace(/\\.jsx?$/, '.test.js'),\n (src: string) => src.replace(/\\.jsx?$/, '.test.jsx'),\n (src: string) => src.replace(/\\.jsx?$/, '.spec.js'),\n (src: string) => src.replace(/\\.jsx?$/, '.spec.jsx'),\n // __tests__ directory pattern\n (src: string) => {\n const dir = dirname(src);\n const base = basename(src).replace(/\\.(tsx?|jsx?)$/, '');\n return join(dir, '__tests__', `${base}.test.ts`);\n },\n (src: string) => {\n const dir = dirname(src);\n const base = basename(src).replace(/\\.(tsx?|jsx?)$/, '');\n return join(dir, '__tests__', `${base}.test.tsx`);\n },\n // test/ directory pattern\n (src: string) => src.replace(/^src\\//, 'test/').replace(/\\.(tsx?|jsx?)$/, '.test.ts'),\n (src: string) => src.replace(/^src\\//, 'tests/').replace(/\\.(tsx?|jsx?)$/, '.test.ts'),\n ];\n\n // Create a set for fast lookup\n const fileSet = new Set(files);\n\n for (const file of files) {\n // Skip test files themselves\n if (file.includes('.test.') || file.includes('.spec.') || file.includes('__tests__')) continue;\n\n // Only check source files\n if (!/\\.(tsx?|jsx?)$/.test(file)) continue;\n\n const tests: string[] = [];\n for (const pattern of testPatterns) {\n const testPath = pattern(file);\n // Only add if the path changed (pattern matched) AND test file exists\n if (testPath !== file && fileSet.has(testPath)) {\n tests.push(testPath);\n }\n }\n\n if (tests.length > 0) {\n testMap[file] = [...new Set(tests)]; // Dedupe\n }\n }\n return testMap;\n}\n\n/**\n * Get recent changes from git (last 7 days)\n * Returns null if not a git repo\n * Note: Uses execSync with hardcoded commands (no user input) for git operations\n */\nfunction getRecentChanges(projectPath: string): RecentChangeInfo[] | null {\n try {\n // Check if it's a git repo - using execSync with hardcoded command\n execSync('git rev-parse --git-dir', { cwd: projectPath, encoding: 'utf-8', stdio: 'pipe' });\n\n // Get commits with file names and authors from last 7 days\n // Note: This is a hardcoded git command with no user input, safe from injection\n const output = execSync(\n 'git log --since=\"7 days ago\" --name-only --format=\"COMMIT_AUTHOR:%an\" --diff-filter=ACMR',\n { cwd: projectPath, encoding: 'utf-8', maxBuffer: 10 * 1024 * 1024, stdio: 'pipe' }\n );\n\n if (!output.trim()) return [];\n\n const fileStats: Record<string, { commits: Set<string>; authors: Set<string> }> = {};\n let currentAuthor = '';\n let currentCommitId = 0;\n\n for (const line of output.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed) {\n currentCommitId++; // New commit block\n continue;\n }\n\n if (trimmed.startsWith('COMMIT_AUTHOR:')) {\n currentAuthor = trimmed.replace('COMMIT_AUTHOR:', '');\n continue;\n }\n\n // It's a file name\n const file = trimmed;\n if (!fileStats[file]) {\n fileStats[file] = { commits: new Set(), authors: new Set() };\n }\n fileStats[file].commits.add(`${currentCommitId}`);\n if (currentAuthor) {\n fileStats[file].authors.add(currentAuthor);\n }\n }\n\n // Convert to array and sort by commit count (most active first)\n const result: RecentChangeInfo[] = Object.entries(fileStats)\n .map(([file, stats]) => ({\n file,\n commits: stats.commits.size,\n authors: stats.authors.size,\n }))\n .sort((a, b) => b.commits - a.commits);\n\n return result;\n } catch {\n return null; // Not a git repo or git not available\n }\n}\n\n/**\n * Resolve a relative import path to an actual file\n */\nfunction resolveImportPath(importPath: string, fromFile: string, projectFiles: string[]): string | undefined {\n if (!importPath.startsWith('.')) return undefined; // External module\n \n const fromDir = dirname(fromFile);\n let resolved = join(fromDir, importPath);\n \n // Try with extensions\n const extensions = ['.ts', '.tsx', '.js', '.jsx', '', '/index.ts', '/index.tsx', '/index.js', '/index.jsx'];\n for (const ext of extensions) {\n const candidate = resolved + ext;\n if (projectFiles.includes(candidate) || projectFiles.includes('./' + candidate)) {\n return candidate;\n }\n }\n \n return undefined;\n}\n\n/**\n * Create an enhanced snapshot with structural metadata\n */\nexport function createEnhancedSnapshot(\n projectPath: string,\n outputPath: string,\n options: SnapshotOptions = {}\n): EnhancedSnapshotResult {\n // First create the basic snapshot\n const baseResult = createSnapshot(projectPath, outputPath, options);\n \n // Now parse all files for metadata\n const allImports: ImportInfo[] = [];\n const allExports: ExportInfo[] = [];\n const fileIndex: Record<string, FileMetadata> = {};\n const projectFiles = baseResult.files.map(f => './' + f);\n \n for (const relPath of baseResult.files) {\n const fullPath = join(projectPath, relPath);\n const ext = extname(relPath).toLowerCase();\n \n // Only parse JS/TS files for imports/exports\n if (!['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'].includes(ext)) {\n continue;\n }\n \n try {\n const content = readFileSync(fullPath, 'utf-8');\n const imports = parseImports(content, relPath);\n const exports = parseExports(content, relPath);\n \n // Resolve local imports\n for (const imp of imports) {\n imp.resolved = resolveImportPath(imp.target, relPath, projectFiles);\n }\n \n allImports.push(...imports);\n allExports.push(...exports);\n \n fileIndex[relPath] = {\n path: relPath,\n imports,\n exports,\n size: content.length,\n lines: content.split('\\n').length,\n };\n } catch {\n // Skip files that can't be read\n }\n }\n \n // Build import graph (file → files it imports)\n const importGraph: Record<string, string[]> = {};\n for (const imp of allImports) {\n if (imp.resolved) {\n if (!importGraph[imp.source]) importGraph[imp.source] = [];\n if (!importGraph[imp.source].includes(imp.resolved)) {\n importGraph[imp.source].push(imp.resolved);\n }\n }\n }\n \n // Build export graph (file → files that import it)\n const exportGraph: Record<string, string[]> = {};\n for (const imp of allImports) {\n if (imp.resolved) {\n if (!exportGraph[imp.resolved]) exportGraph[imp.resolved] = [];\n if (!exportGraph[imp.resolved].includes(imp.source)) {\n exportGraph[imp.resolved].push(imp.source);\n }\n }\n }\n \n // Build symbol index (symbol → files that export it)\n const symbolIndex: Record<string, string[]> = {};\n for (const exp of allExports) {\n if (!symbolIndex[exp.symbol]) symbolIndex[exp.symbol] = [];\n if (!symbolIndex[exp.symbol].includes(exp.file)) {\n symbolIndex[exp.symbol].push(exp.file);\n }\n }\n\n // Calculate complexity scores for all files\n const complexityScores: ComplexityInfo[] = [];\n for (const [relPath, metadata] of Object.entries(fileIndex)) {\n const fullPath = join(projectPath, relPath);\n try {\n const content = readFileSync(fullPath, 'utf-8');\n const score = calculateComplexity(content);\n complexityScores.push({\n file: relPath,\n score,\n level: getComplexityLevel(score),\n });\n } catch {\n // Skip files that can't be read\n }\n }\n // Sort by complexity score (highest first)\n complexityScores.sort((a, b) => b.score - a.score);\n\n // Map test files to source files\n const testFileMap = mapTestFiles(baseResult.files);\n\n // Get recent git changes (null if not a git repo)\n const recentChanges = getRecentChanges(projectPath);\n\n // Append metadata to snapshot file\n const metadataSection = `\n\n================================================================================\nMETADATA: IMPORT GRAPH\n================================================================================\n${Object.entries(importGraph).map(([file, imports]) => `${file}:\\n${imports.map(i => ` → ${i}`).join('\\n')}`).join('\\n\\n')}\n\n================================================================================\nMETADATA: EXPORT INDEX\n================================================================================\n${Object.entries(symbolIndex).map(([symbol, files]) => `${symbol}: ${files.join(', ')}`).join('\\n')}\n\n================================================================================\nMETADATA: FILE EXPORTS\n================================================================================\n${allExports.map(e => `${e.file}:${e.line} - ${e.type} ${e.symbol}${e.signature ? ` ${e.signature}` : ''}`).join('\\n')}\n\n================================================================================\nMETADATA: WHO IMPORTS WHOM\n================================================================================\n${Object.entries(exportGraph).map(([file, importers]) => `${file} is imported by:\\n${importers.map(i => ` ← ${i}`).join('\\n')}`).join('\\n\\n')}\n\n================================================================================\nMETADATA: COMPLEXITY SCORES\n================================================================================\n${complexityScores.map(c => `${c.file}: ${c.score} (${c.level})`).join('\\n')}\n\n================================================================================\nMETADATA: TEST COVERAGE MAP\n================================================================================\n${Object.entries(testFileMap).length > 0\n ? Object.entries(testFileMap).map(([src, tests]) => `${src} -> ${tests.join(', ')}`).join('\\n')\n : '(no test file mappings found)'}\n${baseResult.files.filter(f =>\n /\\.(tsx?|jsx?)$/.test(f) &&\n !f.includes('.test.') &&\n !f.includes('.spec.') &&\n !f.includes('__tests__') &&\n !testFileMap[f]\n ).map(f => `${f} -> (no tests)`).join('\\n')}\n${recentChanges !== null ? `\n\n================================================================================\nMETADATA: RECENT CHANGES (last 7 days)\n================================================================================\n${recentChanges.length > 0\n ? recentChanges.map(c => `${c.file}: ${c.commits} commit${c.commits !== 1 ? 's' : ''}, ${c.authors} author${c.authors !== 1 ? 's' : ''}`).join('\\n')\n : '(no changes in the last 7 days)'}` : ''}\n`;\n\n // Append to snapshot\n const existingContent = readFileSync(outputPath, 'utf-8');\n writeFileSync(outputPath, existingContent + metadataSection);\n\n return {\n ...baseResult,\n metadata: {\n imports: allImports,\n exports: allExports,\n fileIndex,\n importGraph,\n exportGraph,\n symbolIndex,\n complexityScores,\n testFileMap,\n recentChanges,\n },\n };\n}\n","/**\n * Argus Snapshot Generator\n * \n * Creates optimized text snapshots of codebases for analysis.\n * Handles file filtering, exclusion patterns, and formatting.\n */\n\nimport { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'fs';\nimport { join, relative, extname } from 'path';\n\nexport interface SnapshotOptions {\n extensions?: string[];\n excludePatterns?: string[];\n maxFileSize?: number; // in bytes\n includeHidden?: boolean;\n}\n\nexport interface SnapshotResult {\n outputPath: string;\n fileCount: number;\n totalLines: number;\n totalSize: number;\n files: string[];\n}\n\nconst DEFAULT_OPTIONS: Required<SnapshotOptions> = {\n extensions: ['ts', 'tsx', 'js', 'jsx', 'rs', 'py', 'go', 'java', 'rb', 'php', 'swift', 'kt', 'scala', 'c', 'cpp', 'h', 'hpp', 'cs', 'md', 'json'],\n excludePatterns: [\n 'node_modules',\n '.git',\n 'target',\n 'dist',\n 'build',\n '.next',\n 'coverage',\n '__pycache__',\n '.venv',\n 'vendor',\n '.DS_Store',\n '*.lock',\n 'package-lock.json',\n '*.min.js',\n '*.min.css',\n ],\n maxFileSize: 1024 * 1024, // 1MB\n includeHidden: false,\n};\n\nfunction shouldExclude(filePath: string, patterns: string[]): boolean {\n const normalizedPath = filePath.replace(/\\\\/g, '/');\n \n for (const pattern of patterns) {\n // Glob-like pattern matching\n if (pattern.startsWith('*')) {\n const suffix = pattern.slice(1);\n if (normalizedPath.endsWith(suffix)) return true;\n } else if (normalizedPath.includes(`/${pattern}/`) || normalizedPath.endsWith(`/${pattern}`) || normalizedPath === pattern) {\n return true;\n }\n }\n \n return false;\n}\n\nfunction hasValidExtension(filePath: string, extensions: string[]): boolean {\n const ext = extname(filePath).slice(1).toLowerCase();\n return extensions.includes(ext);\n}\n\nfunction collectFiles(\n dir: string,\n options: Required<SnapshotOptions>,\n baseDir: string = dir\n): string[] {\n const files: string[] = [];\n \n try {\n const entries = readdirSync(dir, { withFileTypes: true });\n \n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n const relativePath = relative(baseDir, fullPath);\n \n // Skip hidden files unless explicitly included\n if (!options.includeHidden && entry.name.startsWith('.')) {\n continue;\n }\n \n // Check exclusion patterns\n if (shouldExclude(relativePath, options.excludePatterns)) {\n continue;\n }\n \n if (entry.isDirectory()) {\n files.push(...collectFiles(fullPath, options, baseDir));\n } else if (entry.isFile()) {\n // Check extension\n if (!hasValidExtension(entry.name, options.extensions)) {\n continue;\n }\n \n // Check file size\n try {\n const stats = statSync(fullPath);\n if (stats.size > options.maxFileSize) {\n continue;\n }\n } catch {\n continue;\n }\n \n files.push(fullPath);\n }\n }\n } catch (error) {\n // Directory not readable, skip\n }\n \n return files.sort();\n}\n\nexport function createSnapshot(\n projectPath: string,\n outputPath: string,\n options: SnapshotOptions = {}\n): SnapshotResult {\n const mergedOptions: Required<SnapshotOptions> = {\n ...DEFAULT_OPTIONS,\n ...options,\n };\n \n if (!existsSync(projectPath)) {\n throw new Error(`Project path does not exist: ${projectPath}`);\n }\n \n const stats = statSync(projectPath);\n if (!stats.isDirectory()) {\n throw new Error(`Project path is not a directory: ${projectPath}`);\n }\n \n // Collect all files\n const files = collectFiles(projectPath, mergedOptions);\n \n // Build snapshot content\n const lines: string[] = [];\n \n // Header\n lines.push('================================================================================');\n lines.push('CODEBASE SNAPSHOT');\n lines.push(`Project: ${projectPath}`);\n lines.push(`Generated: ${new Date().toISOString()}`);\n lines.push(`Extensions: ${mergedOptions.extensions.join(', ')}`);\n lines.push(`Files: ${files.length}`);\n lines.push('================================================================================');\n lines.push('');\n \n // Process each file\n for (const filePath of files) {\n const relativePath = relative(projectPath, filePath);\n \n lines.push('');\n lines.push('================================================================================');\n lines.push(`FILE: ./${relativePath}`);\n lines.push('================================================================================');\n \n try {\n const content = readFileSync(filePath, 'utf-8');\n lines.push(content);\n } catch (error) {\n lines.push('[Unable to read file]');\n }\n }\n \n // Write snapshot\n const content = lines.join('\\n');\n writeFileSync(outputPath, content);\n \n const totalLines = content.split('\\n').length;\n const totalSize = Buffer.byteLength(content, 'utf-8');\n \n return {\n outputPath,\n fileCount: files.length,\n totalLines,\n totalSize,\n files: files.map(f => relative(projectPath, f)),\n };\n}\n\nexport function getSnapshotStats(snapshotPath: string): {\n fileCount: number;\n totalLines: number;\n totalSize: number;\n} {\n if (!existsSync(snapshotPath)) {\n throw new Error(`Snapshot file does not exist: ${snapshotPath}`);\n }\n \n const content = readFileSync(snapshotPath, 'utf-8');\n const totalLines = content.split('\\n').length;\n const totalSize = Buffer.byteLength(content, 'utf-8');\n \n // Count FILE: markers\n const fileMatches = content.match(/^FILE: /gm);\n const fileCount = fileMatches ? fileMatches.length : 0;\n \n return { fileCount, totalLines, totalSize };\n}\n","/**\n * Argus RLM Engine\n * \n * Recursive Language Model engine for document analysis.\n * Based on the Matryoshka RLM approach by Dmitri Sotnikov.\n * \n * The engine uses an LLM to generate Nucleus DSL commands that are\n * executed against documents, enabling analysis of content far\n * exceeding typical context limits.\n */\n\nimport { readFileSync } from 'fs';\nimport { AIProvider, Message } from '../providers/types.js';\nimport { buildSystemPrompt, getTurnLimit } from './prompts.js';\n\nexport interface AnalysisOptions {\n maxTurns?: number;\n turnTimeoutMs?: number;\n verbose?: boolean;\n onProgress?: (turn: number, command: string, result: unknown) => void;\n}\n\nexport interface AnalysisResult {\n answer: string;\n turns: number;\n commands: string[];\n success: boolean;\n error?: string;\n}\n\ninterface GrepMatch {\n match: string;\n line: string;\n lineNum: number;\n index: number;\n groups: string[];\n}\n\nconst NUCLEUS_REFERENCE = `\nYou are analyzing a document using the Nucleus DSL. Generate S-expression commands to explore the document.\n\nAVAILABLE COMMANDS:\n- (grep \"pattern\") - Search for regex pattern, returns matches with line numbers\n- (grep \"pattern\" \"flags\") - With flags like \"i\" for case-insensitive\n- (count RESULTS) - Count number of items in RESULTS\n- (map RESULTS (lambda (x) expr)) - Transform each item\n- (filter RESULTS (lambda (x) expr)) - Keep items where expr is true\n- (sort RESULTS key) - Sort by key\n- (first RESULTS) - Get first item\n- (last RESULTS) - Get last item \n- (take RESULTS n) - Get first n items\n- (match str \"pattern\" group) - Extract regex group from string\n\nVARIABLES:\n- RESULTS always contains the result of the last command\n- _1, _2, etc. contain results from turn 1, 2, etc.\n\nFINAL ANSWER:\nWhen you have enough information, output: <<<FINAL>>>your answer here<<<END>>>\n\nRULES:\n1. Output ONLY a single Nucleus command OR a final answer, nothing else\n2. Use grep to search the document\n3. Use map/filter to process results\n4. Build understanding iteratively\n5. When ready, provide the final answer\n\nExample session:\nTurn 1: (grep \"function.*export\")\nTurn 2: (count RESULTS)\nTurn 3: <<<FINAL>>>There are 15 exported functions<<<END>>>\n`;\n\n/**\n * Execute a Nucleus command against document content\n */\nfunction executeNucleus(command: string, content: string, bindings: Map<string, unknown>): unknown {\n // Parse the S-expression\n const parsed = parseSExpression(command);\n if (!parsed) {\n throw new Error(`Failed to parse command: ${command}`);\n }\n \n return evaluateExpr(parsed, content, bindings);\n}\n\ntype SExpr = string | SExpr[];\n\nfunction parseSExpression(input: string): SExpr | null {\n const tokens = tokenize(input.trim());\n if (tokens.length === 0) return null;\n \n let pos = 0;\n \n function parse(): SExpr {\n const token = tokens[pos++];\n \n if (token === '(') {\n const list: SExpr[] = [];\n while (tokens[pos] !== ')' && pos < tokens.length) {\n list.push(parse());\n }\n pos++; // consume ')'\n return list;\n } else if (token.startsWith('\"')) {\n // String literal\n return token.slice(1, -1).replace(/\\\\\"/g, '\"');\n } else if (/^-?\\d+(\\.\\d+)?$/.test(token)) {\n return token; // Keep as string, convert when needed\n } else {\n return token; // Symbol\n }\n }\n \n return parse();\n}\n\nfunction tokenize(input: string): string[] {\n const tokens: string[] = [];\n let i = 0;\n \n while (i < input.length) {\n const char = input[i];\n \n if (/\\s/.test(char)) {\n i++;\n continue;\n }\n \n if (char === '(' || char === ')') {\n tokens.push(char);\n i++;\n continue;\n }\n \n if (char === '\"') {\n let str = '\"';\n i++;\n while (i < input.length && input[i] !== '\"') {\n if (input[i] === '\\\\' && i + 1 < input.length) {\n str += input[i] + input[i + 1];\n i += 2;\n } else {\n str += input[i];\n i++;\n }\n }\n str += '\"';\n i++;\n tokens.push(str);\n continue;\n }\n \n // Symbol or number\n let sym = '';\n while (i < input.length && !/[\\s()]/.test(input[i])) {\n sym += input[i];\n i++;\n }\n tokens.push(sym);\n }\n \n return tokens;\n}\n\nfunction evaluateExpr(expr: SExpr, content: string, bindings: Map<string, unknown>): unknown {\n if (typeof expr === 'string') {\n // Variable lookup\n if (bindings.has(expr)) {\n return bindings.get(expr);\n }\n // Number\n if (/^-?\\d+(\\.\\d+)?$/.test(expr)) {\n return parseFloat(expr);\n }\n return expr;\n }\n \n if (!Array.isArray(expr) || expr.length === 0) {\n return expr;\n }\n \n const [op, ...args] = expr;\n \n switch (op) {\n case 'grep': {\n const pattern = evaluateExpr(args[0], content, bindings) as string;\n const flags = args[1] ? evaluateExpr(args[1], content, bindings) as string : '';\n const regex = new RegExp(pattern, flags + 'g');\n const lines = content.split('\\n');\n const matches: GrepMatch[] = [];\n \n let charIndex = 0;\n for (let lineNum = 0; lineNum < lines.length; lineNum++) {\n const line = lines[lineNum];\n let match;\n const lineRegex = new RegExp(pattern, flags + 'g');\n while ((match = lineRegex.exec(line)) !== null) {\n matches.push({\n match: match[0],\n line: line,\n lineNum: lineNum + 1,\n index: charIndex + match.index,\n groups: match.slice(1),\n });\n }\n charIndex += line.length + 1;\n }\n \n return matches;\n }\n \n case 'count': {\n const arr = evaluateExpr(args[0], content, bindings);\n if (Array.isArray(arr)) return arr.length;\n return 0;\n }\n \n case 'map': {\n const arr = evaluateExpr(args[0], content, bindings) as unknown[];\n const lambdaExpr = args[1] as SExpr[];\n \n if (!Array.isArray(lambdaExpr) || lambdaExpr[0] !== 'lambda') {\n throw new Error('map requires a lambda expression');\n }\n \n const params = lambdaExpr[1] as SExpr[];\n const body = lambdaExpr[2];\n const paramName = Array.isArray(params) ? params[0] as string : params as string;\n \n return arr.map(item => {\n const localBindings = new Map(bindings);\n localBindings.set(paramName, item);\n return evaluateExpr(body, content, localBindings);\n });\n }\n \n case 'filter': {\n const arr = evaluateExpr(args[0], content, bindings) as unknown[];\n const lambdaExpr = args[1] as SExpr[];\n \n if (!Array.isArray(lambdaExpr) || lambdaExpr[0] !== 'lambda') {\n throw new Error('filter requires a lambda expression');\n }\n \n const params = lambdaExpr[1] as SExpr[];\n const body = lambdaExpr[2];\n const paramName = Array.isArray(params) ? params[0] as string : params as string;\n \n return arr.filter(item => {\n const localBindings = new Map(bindings);\n localBindings.set(paramName, item);\n return evaluateExpr(body, content, localBindings);\n });\n }\n \n case 'first': {\n const arr = evaluateExpr(args[0], content, bindings) as unknown[];\n return arr[0];\n }\n \n case 'last': {\n const arr = evaluateExpr(args[0], content, bindings) as unknown[];\n return arr[arr.length - 1];\n }\n \n case 'take': {\n const arr = evaluateExpr(args[0], content, bindings) as unknown[];\n const n = evaluateExpr(args[1], content, bindings) as number;\n return arr.slice(0, n);\n }\n \n case 'sort': {\n const arr = evaluateExpr(args[0], content, bindings) as Record<string, unknown>[];\n const key = evaluateExpr(args[1], content, bindings) as string;\n return [...arr].sort((a, b) => {\n const aVal = a[key];\n const bVal = b[key];\n if (typeof aVal === 'number' && typeof bVal === 'number') {\n return aVal - bVal;\n }\n return String(aVal).localeCompare(String(bVal));\n });\n }\n \n case 'match': {\n const str = evaluateExpr(args[0], content, bindings);\n const strValue = typeof str === 'object' && str !== null && 'line' in str \n ? (str as GrepMatch).line \n : String(str);\n const pattern = evaluateExpr(args[1], content, bindings) as string;\n const group = args[2] ? evaluateExpr(args[2], content, bindings) as number : 0;\n \n const regex = new RegExp(pattern);\n const match = strValue.match(regex);\n if (match) {\n return match[group] || null;\n }\n return null;\n }\n \n default:\n throw new Error(`Unknown command: ${op}`);\n }\n}\n\n/**\n * Extract Nucleus command from LLM response\n */\nfunction extractCommand(response: string): { command?: string; finalAnswer?: string } {\n // Check for final answer\n const finalMatch = response.match(/<<<FINAL>>>([\\s\\S]*?)<<<END>>>/);\n if (finalMatch) {\n return { finalAnswer: finalMatch[1].trim() };\n }\n \n // Look for S-expression\n const sexpMatch = response.match(/\\([^)]*(?:\\([^)]*\\)[^)]*)*\\)/);\n if (sexpMatch) {\n return { command: sexpMatch[0] };\n }\n \n return {};\n}\n\n/**\n * Run RLM analysis on a document\n */\nexport async function analyze(\n provider: AIProvider,\n documentPath: string,\n query: string,\n options: AnalysisOptions = {}\n): Promise<AnalysisResult> {\n const {\n maxTurns = 15,\n verbose = false,\n onProgress,\n } = options;\n \n // Use dynamic turn limit based on query type, but cap at maxTurns\n const dynamicLimit = Math.min(getTurnLimit(query), maxTurns);\n \n // Load document\n const content = readFileSync(documentPath, 'utf-8');\n \n // Get document stats for context\n const fileCount = (content.match(/^FILE:/gm) || []).length;\n const lineCount = content.split('\\n').length;\n \n const bindings = new Map<string, unknown>();\n const commands: string[] = [];\n const messages: Message[] = [\n {\n role: 'system',\n content: buildSystemPrompt(query),\n },\n {\n role: 'user',\n content: `CODEBASE SNAPSHOT:\n- Total size: ${content.length.toLocaleString()} characters\n- Files: ${fileCount}\n- Lines: ${lineCount.toLocaleString()}\n\nFiles are marked with \"FILE: ./path/to/file\" headers.\n\nQUERY: ${query}\n\nBegin analysis. You have ${dynamicLimit} turns maximum - provide final answer before then.`,\n },\n ];\n \n for (let turn = 1; turn <= dynamicLimit; turn++) {\n // Force final answer on last turn\n const isLastTurn = turn === dynamicLimit;\n const isNearEnd = turn >= dynamicLimit - 2;\n \n if (verbose) {\n console.log(`\\n[Turn ${turn}/${dynamicLimit}] Querying LLM...`);\n }\n \n // Get LLM response\n const result = await provider.complete(messages);\n const response = result.content;\n \n if (verbose) {\n console.log(`[Turn ${turn}] Response: ${response.slice(0, 200)}...`);\n }\n \n // Extract command or final answer\n const extracted = extractCommand(response);\n \n if (extracted.finalAnswer) {\n return {\n answer: extracted.finalAnswer,\n turns: turn,\n commands,\n success: true,\n };\n }\n \n if (!extracted.command) {\n // No command found, add to messages and continue\n messages.push({ role: 'assistant', content: response });\n messages.push({ role: 'user', content: 'Please provide a Nucleus command or final answer.' });\n continue;\n }\n \n const command = extracted.command;\n commands.push(command);\n \n if (verbose) {\n console.log(`[Turn ${turn}] Command: ${command}`);\n }\n \n // Execute command\n try {\n const cmdResult = executeNucleus(command, content, bindings);\n \n // Store result in bindings\n bindings.set('RESULTS', cmdResult);\n bindings.set(`_${turn}`, cmdResult);\n \n const resultStr = JSON.stringify(cmdResult, null, 2);\n const truncatedResult = resultStr.length > 2000 \n ? resultStr.slice(0, 2000) + '...[truncated]' \n : resultStr;\n \n if (verbose) {\n console.log(`[Turn ${turn}] Result: ${truncatedResult.slice(0, 500)}...`);\n }\n \n onProgress?.(turn, command, cmdResult);\n \n // Add to conversation with nudge if near end\n messages.push({ role: 'assistant', content: command });\n \n let userMessage = `Result:\\n${truncatedResult}`;\n if (isNearEnd && !isLastTurn) {\n userMessage += `\\n\\n⚠️ ${dynamicLimit - turn} turns remaining. Start forming your final answer.`;\n }\n messages.push({ role: 'user', content: userMessage });\n \n // FORCE final answer on last turn - make one more LLM call\n if (isLastTurn) {\n messages.push({ \n role: 'user', \n content: 'STOP SEARCHING. Based on everything you found, provide your final answer NOW using <<<FINAL>>>your answer<<<END>>>' \n });\n \n const finalResult = await provider.complete(messages);\n const finalExtracted = extractCommand(finalResult.content);\n \n if (finalExtracted.finalAnswer) {\n return {\n answer: finalExtracted.finalAnswer,\n turns: turn,\n commands,\n success: true,\n };\n }\n \n // Even if not properly formatted, return whatever we got\n return {\n answer: finalResult.content,\n turns: turn,\n commands,\n success: true,\n };\n }\n \n } catch (error) {\n const errMsg = error instanceof Error ? error.message : String(error);\n \n if (verbose) {\n console.log(`[Turn ${turn}] Error: ${errMsg}`);\n }\n \n messages.push({ role: 'assistant', content: command });\n messages.push({ role: 'user', content: `Error executing command: ${errMsg}` });\n }\n }\n \n return {\n answer: 'Maximum turns reached without final answer',\n turns: dynamicLimit,\n commands,\n success: false,\n error: 'Max turns reached',\n };\n}\n\n/**\n * Fast grep search without AI\n */\nexport function searchDocument(\n documentPath: string,\n pattern: string,\n options: { caseInsensitive?: boolean; maxResults?: number } = {}\n): GrepMatch[] {\n const content = readFileSync(documentPath, 'utf-8');\n const flags = options.caseInsensitive ? 'gi' : 'g';\n const regex = new RegExp(pattern, flags);\n const lines = content.split('\\n');\n const matches: GrepMatch[] = [];\n \n let charIndex = 0;\n for (let lineNum = 0; lineNum < lines.length; lineNum++) {\n const line = lines[lineNum];\n let match;\n const lineRegex = new RegExp(pattern, flags);\n while ((match = lineRegex.exec(line)) !== null) {\n matches.push({\n match: match[0],\n line: line,\n lineNum: lineNum + 1,\n index: charIndex + match.index,\n groups: match.slice(1),\n });\n \n if (options.maxResults && matches.length >= options.maxResults) {\n return matches;\n }\n }\n charIndex += line.length + 1;\n }\n \n return matches;\n}\n","/**\n * Argus RLM Prompts\n * \n * Optimized prompts for codebase understanding that persists across Claude Code sessions.\n */\n\nexport const NUCLEUS_COMMANDS = `\nCOMMANDS (output ONE per turn):\n(grep \"pattern\") - Find lines matching regex\n(grep \"pattern\" \"i\") - Case-insensitive search \n(count RESULTS) - Count matches\n(take RESULTS n) - First n results\n(filter RESULTS (lambda (x) (match x.line \"pattern\" 0))) - Filter results\n(map RESULTS (lambda (x) x.line)) - Extract just the lines\n\nVARIABLES: RESULTS = last result, _1 _2 _3 = results from turn 1,2,3\n\nTO ANSWER: <<<FINAL>>>your answer<<<END>>>\n`;\n\n// Main system prompt for codebase analysis\nexport const CODEBASE_ANALYSIS_PROMPT = `You are analyzing a SOFTWARE CODEBASE snapshot to help a developer understand it.\n\nThe snapshot contains source files concatenated with \"FILE: ./path/to/file\" markers.\n\n${NUCLEUS_COMMANDS}\n\n## STRATEGY FOR CODEBASE SNAPSHOTS\n\n**To find modules/directories:**\n(grep \"FILE:.*src/[^/]+/\") - top-level source dirs\n(grep \"FILE:.*mod\\\\.rs\") - Rust modules \n(grep \"FILE:.*index\\\\.(ts|js)\") - JS/TS modules\n\n**To find implementations:**\n(grep \"fn function_name\") - Rust functions\n(grep \"function|const.*=>\") - JS functions\n(grep \"class ClassName\") - Classes\n(grep \"struct |type |interface\") - Type definitions\n\n**To understand structure:**\n(grep \"FILE:\") - List all files\n(grep \"use |import |require\") - Find dependencies\n(grep \"pub |export\") - Public APIs\n\n## RULES\n1. Output ONLY a Nucleus command OR a final answer\n2. NO explanations, NO markdown formatting in commands\n3. MUST provide final answer by turn 8\n4. If turn 6+, start summarizing what you found\n\n## EXAMPLE SESSION\nTurn 1: (grep \"FILE:.*src/[^/]+/mod\\\\.rs\")\nTurn 2: (take RESULTS 15)\nTurn 3: <<<FINAL>>>The codebase has these main modules:\n- src/auth/ - Authentication handling\n- src/api/ - API endpoints\n- src/db/ - Database layer\n...<<<END>>>\n`;\n\n// Specialized prompt for architecture questions\nexport const ARCHITECTURE_PROMPT = `You are generating an ARCHITECTURE SUMMARY of a codebase.\n\n${NUCLEUS_COMMANDS}\n\n## YOUR TASK\nCreate a summary suitable for CLAUDE.md that helps Claude Code understand this project after context compaction.\n\n## SEARCH STRATEGY (do these in order)\n1. (grep \"FILE:.*mod\\\\.rs|FILE:.*index\\\\.(ts|js)\") - Find module entry points\n2. (take RESULTS 20) - Limit results\n3. Based on file paths, provide your summary\n\n## OUTPUT FORMAT\nYour final answer should be structured like:\n\n## Modules\n- **module_name/** - Brief description based on files found\n\n## Key Patterns \n- Pattern observations from the code\n\n## Important Files\n- List key files and their apparent purpose\n\nPROVIDE FINAL ANSWER BY TURN 6.\n`;\n\n// Prompt for finding specific implementations\nexport const IMPLEMENTATION_PROMPT = `You are finding HOW something works in a codebase.\n\n${NUCLEUS_COMMANDS}\n\n## STRATEGY\n1. (grep \"FILE:.*keyword\") - Find files related to the concept\n2. (grep \"keyword\") - Find all mentions\n3. (take RESULTS 30) - Limit if too many results\n4. Look for function definitions, structs, classes\n5. PROVIDE FINAL ANSWER based on file paths and code patterns found\n\n## IMPORTANT\n- You have 12 turns maximum\n- By turn 8, START WRITING YOUR FINAL ANSWER\n- Use what you've found - don't keep searching indefinitely\n- It's better to give a partial answer than no answer\n\n## OUTPUT FORMAT\nYour final answer should explain:\n- Which files contain the implementation\n- Key functions/structs/classes involved \n- Basic flow of how it works (based on what you found)\n`;\n\n// Prompt for counting/quantifying\nexport const COUNT_PROMPT = `You are counting items in a codebase.\n\n${NUCLEUS_COMMANDS}\n\n## STRATEGY \n1. (grep \"pattern\")\n2. (count RESULTS)\n3. <<<FINAL>>>There are N items matching the pattern.<<<END>>>\n\nTHIS SHOULD TAKE 2-3 TURNS MAXIMUM.\n`;\n\n// Prompt for quick searches\nexport const SEARCH_PROMPT = `You are searching for specific code.\n\n${NUCLEUS_COMMANDS}\n\n## STRATEGY\n1. (grep \"pattern\")\n2. (take RESULTS 20) if too many\n3. Report what you found with file paths\n\nPROVIDE FINAL ANSWER BY TURN 4.\n`;\n\n/**\n * Detect query type and select best prompt\n */\nexport function selectPrompt(query: string): string {\n const q = query.toLowerCase();\n \n // Count queries - fastest\n if (/how many|count|number of|total|how much/.test(q)) {\n return COUNT_PROMPT;\n }\n \n // Simple search queries\n if (/^(find|search|show|list|where is|locate)\\b/.test(q) && q.length < 50) {\n return SEARCH_PROMPT;\n }\n \n // Architecture/overview queries \n if (/architect|structure|overview|module|organization|main.*component|summar|layout/.test(q)) {\n return ARCHITECTURE_PROMPT;\n }\n \n // Implementation queries\n if (/how does|how is|implement|work|handle|process|flow/.test(q)) {\n return IMPLEMENTATION_PROMPT;\n }\n \n // Default\n return CODEBASE_ANALYSIS_PROMPT;\n}\n\n/**\n * Build system prompt with query-specific guidance\n */\nexport function buildSystemPrompt(query: string): string {\n return selectPrompt(query);\n}\n\n/**\n * Get the turn limit based on query type\n */\nexport function getTurnLimit(query: string): number {\n const q = query.toLowerCase();\n \n if (/how many|count/.test(q)) return 5;\n if (/^(find|search|show|list)\\b/.test(q) && q.length < 50) return 6;\n if (/architect|overview|structure|module/.test(q)) return 12;\n if (/how does|how is|implement|work/.test(q)) return 12; // Implementation needs more\n \n return 12; // Default\n}\n","/**\n * Argus AI Providers\n * \n * Factory for creating AI providers based on configuration.\n */\n\nimport { ArgusConfig, ProviderType, ProviderConfig } from '../core/config.js';\nimport { AIProvider } from './types.js';\nimport { createZAIProvider, createOpenAIProvider, createDeepSeekProvider } from './openai-compatible.js';\nimport { createOllamaProvider } from './ollama.js';\nimport { createAnthropicProvider } from './anthropic.js';\n\nexport type { AIProvider, Message, CompletionOptions, CompletionResult, ProviderConfig } from './types.js';\nexport { createZAIProvider, createOpenAIProvider, createDeepSeekProvider } from './openai-compatible.js';\nexport { createOllamaProvider, OllamaProvider } from './ollama.js';\nexport { createAnthropicProvider } from './anthropic.js';\n\n/**\n * Create an AI provider from Argus configuration\n */\nexport function createProvider(config: ArgusConfig): AIProvider {\n const providerType = config.provider;\n const providerConfig = config.providers[providerType];\n \n if (!providerConfig) {\n throw new Error(`No configuration found for provider: ${providerType}`);\n }\n \n return createProviderByType(providerType, providerConfig);\n}\n\n/**\n * Create an AI provider by type and config\n */\nexport function createProviderByType(type: ProviderType, config: ProviderConfig): AIProvider {\n switch (type) {\n case 'zai':\n return createZAIProvider(config);\n case 'openai':\n return createOpenAIProvider(config);\n case 'deepseek':\n return createDeepSeekProvider(config);\n case 'ollama':\n return createOllamaProvider(config);\n case 'anthropic':\n return createAnthropicProvider(config);\n default:\n throw new Error(`Unknown provider type: ${type}`);\n }\n}\n\n/**\n * Get a human-readable name for a provider\n */\nexport function getProviderDisplayName(type: ProviderType): string {\n switch (type) {\n case 'zai':\n return 'ZAI (GLM)';\n case 'openai':\n return 'OpenAI';\n case 'deepseek':\n return 'DeepSeek';\n case 'ollama':\n return 'Ollama (Local)';\n case 'anthropic':\n return 'Anthropic (Claude)';\n default:\n return type;\n }\n}\n\n/**\n * List all available provider types\n */\nexport function listProviderTypes(): ProviderType[] {\n return ['zai', 'anthropic', 'openai', 'deepseek', 'ollama'];\n}\n","/**\n * OpenAI-Compatible Provider\n * \n * Works with OpenAI, ZAI (GLM), DeepSeek, and any OpenAI-compatible API.\n */\n\nimport { AIProvider, Message, CompletionOptions, CompletionResult, ProviderConfig } from './types.js';\n\nexport class OpenAICompatibleProvider implements AIProvider {\n name: string;\n private config: ProviderConfig;\n \n constructor(name: string, config: ProviderConfig) {\n this.name = name;\n this.config = config;\n \n if (!config.apiKey) {\n throw new Error(`API key is required for ${name} provider`);\n }\n \n if (!config.baseUrl) {\n throw new Error(`Base URL is required for ${name} provider`);\n }\n }\n \n async complete(messages: Message[], options?: CompletionOptions): Promise<CompletionResult> {\n const endpoint = `${this.config.baseUrl}/chat/completions`;\n \n const body = {\n model: this.config.model,\n messages: messages.map(m => ({\n role: m.role,\n content: m.content,\n })),\n temperature: options?.temperature ?? this.config.options?.temperature ?? 0.2,\n max_tokens: options?.maxTokens ?? this.config.options?.max_tokens ?? 4096,\n ...(options?.stopSequences && { stop: options.stopSequences }),\n };\n \n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.apiKey}`,\n },\n body: JSON.stringify(body),\n });\n \n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`${this.name} API error (${response.status}): ${errorText}`);\n }\n \n const data = await response.json() as {\n choices: Array<{\n message: { content: string };\n finish_reason: string;\n }>;\n usage?: {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n };\n };\n \n const choice = data.choices[0];\n \n return {\n content: choice.message.content || '',\n finishReason: choice.finish_reason === 'stop' ? 'stop' : \n choice.finish_reason === 'length' ? 'length' : 'error',\n usage: data.usage ? {\n promptTokens: data.usage.prompt_tokens,\n completionTokens: data.usage.completion_tokens,\n totalTokens: data.usage.total_tokens,\n } : undefined,\n };\n }\n \n async healthCheck(): Promise<boolean> {\n try {\n const result = await this.complete([\n { role: 'user', content: 'Say \"ok\"' }\n ], { maxTokens: 10 });\n return result.content.length > 0;\n } catch {\n return false;\n }\n }\n}\n\n/**\n * Create a provider for ZAI GLM models\n */\nexport function createZAIProvider(config: ProviderConfig): AIProvider {\n return new OpenAICompatibleProvider('ZAI', {\n ...config,\n baseUrl: config.baseUrl || 'https://api.z.ai/api/coding/paas/v4',\n model: config.model || 'glm-4.7',\n });\n}\n\n/**\n * Create a provider for OpenAI models\n */\nexport function createOpenAIProvider(config: ProviderConfig): AIProvider {\n return new OpenAICompatibleProvider('OpenAI', {\n ...config,\n baseUrl: config.baseUrl || 'https://api.openai.com/v1',\n model: config.model || 'gpt-4o',\n });\n}\n\n/**\n * Create a provider for DeepSeek models\n */\nexport function createDeepSeekProvider(config: ProviderConfig): AIProvider {\n return new OpenAICompatibleProvider('DeepSeek', {\n ...config,\n baseUrl: config.baseUrl || 'https://api.deepseek.com',\n model: config.model || 'deepseek-chat',\n });\n}\n","/**\n * Ollama Provider\n * \n * Provider for local Ollama models.\n */\n\nimport { AIProvider, Message, CompletionOptions, CompletionResult, ProviderConfig } from './types.js';\n\nexport class OllamaProvider implements AIProvider {\n name = 'Ollama';\n private config: ProviderConfig;\n \n constructor(config: ProviderConfig) {\n this.config = {\n ...config,\n baseUrl: config.baseUrl || 'http://localhost:11434',\n model: config.model || 'qwen2.5-coder:7b',\n };\n }\n \n async complete(messages: Message[], options?: CompletionOptions): Promise<CompletionResult> {\n const endpoint = `${this.config.baseUrl}/api/chat`;\n \n const body = {\n model: this.config.model,\n messages: messages.map(m => ({\n role: m.role,\n content: m.content,\n })),\n stream: false,\n options: {\n temperature: options?.temperature ?? this.config.options?.temperature ?? 0.2,\n num_ctx: this.config.options?.num_ctx ?? 8192,\n },\n };\n \n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n });\n \n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Ollama API error (${response.status}): ${errorText}`);\n }\n \n const data = await response.json() as {\n message: { content: string };\n done: boolean;\n eval_count?: number;\n prompt_eval_count?: number;\n };\n \n return {\n content: data.message.content || '',\n finishReason: data.done ? 'stop' : 'error',\n usage: data.eval_count ? {\n promptTokens: data.prompt_eval_count || 0,\n completionTokens: data.eval_count,\n totalTokens: (data.prompt_eval_count || 0) + data.eval_count,\n } : undefined,\n };\n }\n \n async healthCheck(): Promise<boolean> {\n try {\n const response = await fetch(`${this.config.baseUrl}/api/tags`);\n if (!response.ok) return false;\n \n const data = await response.json() as { models: Array<{ name: string }> };\n const hasModel = data.models.some(m => \n m.name === this.config.model || m.name.startsWith(this.config.model + ':')\n );\n \n return hasModel;\n } catch {\n return false;\n }\n }\n \n /**\n * List available models\n */\n async listModels(): Promise<string[]> {\n try {\n const response = await fetch(`${this.config.baseUrl}/api/tags`);\n if (!response.ok) return [];\n \n const data = await response.json() as { models: Array<{ name: string }> };\n return data.models.map(m => m.name);\n } catch {\n return [];\n }\n }\n}\n\nexport function createOllamaProvider(config: ProviderConfig): OllamaProvider {\n return new OllamaProvider(config);\n}\n","/**\n * Anthropic Provider\n * \n * Provider for Claude models via the Anthropic API.\n */\n\nimport { AIProvider, Message, CompletionOptions, CompletionResult, ProviderConfig } from './types.js';\n\nexport class AnthropicProvider implements AIProvider {\n name = 'Anthropic';\n private config: ProviderConfig;\n \n constructor(config: ProviderConfig) {\n if (!config.apiKey) {\n throw new Error('API key is required for Anthropic provider');\n }\n \n this.config = {\n ...config,\n baseUrl: config.baseUrl || 'https://api.anthropic.com',\n model: config.model || 'claude-sonnet-4-20250514',\n };\n }\n \n async complete(messages: Message[], options?: CompletionOptions): Promise<CompletionResult> {\n const endpoint = `${this.config.baseUrl}/v1/messages`;\n \n // Extract system message if present\n const systemMessage = messages.find(m => m.role === 'system');\n const nonSystemMessages = messages.filter(m => m.role !== 'system');\n \n const body = {\n model: this.config.model,\n max_tokens: options?.maxTokens ?? this.config.options?.max_tokens ?? 4096,\n ...(systemMessage && { system: systemMessage.content }),\n messages: nonSystemMessages.map(m => ({\n role: m.role,\n content: m.content,\n })),\n ...(options?.temperature !== undefined && { temperature: options.temperature }),\n ...(options?.stopSequences && { stop_sequences: options.stopSequences }),\n };\n \n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-api-key': this.config.apiKey!,\n 'anthropic-version': '2023-06-01',\n },\n body: JSON.stringify(body),\n });\n \n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Anthropic API error (${response.status}): ${errorText}`);\n }\n \n const data = await response.json() as {\n content: Array<{ type: string; text: string }>;\n stop_reason: string;\n usage: {\n input_tokens: number;\n output_tokens: number;\n };\n };\n \n const textContent = data.content\n .filter(c => c.type === 'text')\n .map(c => c.text)\n .join('');\n \n return {\n content: textContent,\n finishReason: data.stop_reason === 'end_turn' ? 'stop' : \n data.stop_reason === 'max_tokens' ? 'length' : 'error',\n usage: {\n promptTokens: data.usage.input_tokens,\n completionTokens: data.usage.output_tokens,\n totalTokens: data.usage.input_tokens + data.usage.output_tokens,\n },\n };\n }\n \n async healthCheck(): Promise<boolean> {\n try {\n const result = await this.complete([\n { role: 'user', content: 'Say \"ok\"' }\n ], { maxTokens: 10 });\n return result.content.length > 0;\n } catch {\n return false;\n }\n }\n}\n\nexport function createAnthropicProvider(config: ProviderConfig): AIProvider {\n return new AnthropicProvider(config);\n}\n"],"mappings":";;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAOA,OAAO,cAAc;AACrB,SAAS,cAAAA,aAAY,aAAAC,YAAW,gBAAAC,qBAAoB;AACpD,SAAS,WAAAC,gBAAe;AATxB,IAmBa;AAnBb;AAAA;AAAA;AAAA;AAmBO,IAAM,gBAAN,MAAoB;AAAA,MACjB;AAAA,MACA,cAAc;AAAA,MAEtB,YAAY,QAAgB;AAE1B,cAAM,MAAMA,SAAQ,MAAM;AAC1B,YAAI,CAACH,YAAW,GAAG,GAAG;AACpB,UAAAC,WAAU,KAAK,EAAE,WAAW,KAAK,CAAC;AAAA,QACpC;AAEA,aAAK,KAAK,IAAI,SAAS,MAAM;AAC7B,aAAK,WAAW;AAAA,MAClB;AAAA,MAEQ,aAAmB;AACzB,YAAI,KAAK,YAAa;AAGtB,aAAK,GAAG,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,KAQZ;AAGD,aAAK,GAAG,KAAK;AAAA;AAAA;AAAA;AAAA;AAAA,KAKZ;AAED,aAAK,cAAc;AAAA,MACrB;AAAA;AAAA;AAAA;AAAA,MAKA,QAAc;AACZ,aAAK,GAAG,KAAK,wBAAwB;AAAA,MACvC;AAAA;AAAA;AAAA;AAAA,MAKA,UAAU,MAAc,SAAuE;AAC7F,cAAM,SAAS,KAAK,GAAG,QAAQ;AAAA;AAAA;AAAA,KAG9B;AAED,cAAM,KAAK,KAAK,GAAG,YAAY,MAAM;AACnC,qBAAW,OAAO,SAAS;AACzB,mBAAO,IAAI,MAAM,IAAI,MAAM,IAAI,SAAS,IAAI,IAAI;AAAA,UAClD;AAAA,QACF,CAAC;AAED,WAAG;AAAA,MACL;AAAA;AAAA;AAAA;AAAA,MAKA,kBAAkB,cAA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iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,MAChE;AAAA,IACF;AAAA,EACF;AACF;AAGA,IAAM,KAAK,gBAAgB;AAAA,EACzB,OAAO,QAAQ;AAAA,EACf,QAAQ,QAAQ;AAAA,EAChB,UAAU;AACZ,CAAC;AAED,GAAG,GAAG,QAAQ,OAAO,SAAS;AAC5B,MAAI,CAAC,KAAK,KAAK,EAAG;AAElB,MAAI;AACF,UAAM,UAAU,KAAK,MAAM,IAAI;AAC/B,UAAM,WAAW,MAAM,cAAc,OAAO;AAI5C,QAAI,aAAa,QAAQ,SAAS,OAAO,UAAa,SAAS,OAAO,MAAM;AAC1E,cAAQ,IAAI,KAAK,UAAU,QAAQ,CAAC;AAAA,IACtC;AAAA,EACF,SAAS,OAAO;AAGd,UAAM,gBAAgB;AAAA,MACpB,SAAS;AAAA,MACT,IAAI;AAAA;AAAA,MACJ,OAAO;AAAA,QACL,MAAM;AAAA,QACN,SAAS;AAAA,MACX;AAAA,IACF;AACA,YAAQ,IAAI,KAAK,UAAU,aAAa,CAAC;AAAA,EAC3C;AACF,CAAC;","names":["existsSync","mkdirSync","readFileSync","dirname","config","readFileSync","writeFileSync","join","extname","existsSync","readFileSync","writeFileSync","join","content","join","extname","readFileSync","writeFileSync","readFileSync","provider","readFileSync","config","config","config","config","existsSync","statSync","readFileSync","join","hasMore","pageMatches","formattedMatches","response","SemanticIndex"]}
|
|
1
|
+
{"version":3,"sources":["../node_modules/tsup/assets/esm_shims.js","../src/core/semantic-search.ts","../src/mcp.ts","../src/core/config.ts","../src/core/enhanced-snapshot.ts","../src/core/snapshot.ts","../src/core/engine.ts","../src/core/prompts.ts","../src/providers/index.ts","../src/providers/openai-compatible.ts","../src/providers/ollama.ts","../src/providers/anthropic.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport { fileURLToPath } from 'url'\nimport path from 'path'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","/**\n * Semantic Search using SQLite FTS5\n *\n * Provides full-text search capabilities for code symbols and content.\n * Uses SQLite's built-in FTS5 for efficient text search without external dependencies.\n */\n\nimport Database from 'better-sqlite3';\nimport { existsSync, mkdirSync, readFileSync } from 'fs';\nimport { dirname } from 'path';\n\nexport interface SearchResult {\n file: string;\n symbol: string;\n content: string;\n type: string;\n rank: number;\n}\n\nexport class SemanticIndex {\n private db: Database.Database;\n private initialized = false;\n\n constructor(dbPath: string) {\n // Ensure directory exists\n const dir = dirname(dbPath);\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n\n this.db = new Database(dbPath);\n this.initialize();\n }\n\n private initialize(): void {\n if (this.initialized) return;\n\n // Create FTS5 virtual table for code search\n this.db.exec(`\n CREATE VIRTUAL TABLE IF NOT EXISTS code_index USING fts5(\n file,\n symbol,\n content,\n type,\n tokenize='porter unicode61'\n );\n `);\n\n // Create metadata table\n this.db.exec(`\n CREATE TABLE IF NOT EXISTS index_metadata (\n key TEXT PRIMARY KEY,\n value TEXT\n );\n `);\n\n this.initialized = true;\n }\n\n /**\n * Clear the index and rebuild from scratch\n */\n clear(): void {\n this.db.exec('DELETE FROM code_index');\n }\n\n /**\n * Index a file's symbols and content\n */\n indexFile(file: string, symbols: Array<{ name: string; content: string; type: string }>): void {\n const insert = this.db.prepare(`\n INSERT INTO code_index (file, symbol, content, type)\n VALUES (?, ?, ?, ?)\n `);\n\n const tx = this.db.transaction(() => {\n for (const sym of symbols) {\n insert.run(file, sym.name, sym.content, sym.type);\n }\n });\n\n tx();\n }\n\n /**\n * Index content from a snapshot file\n */\n indexFromSnapshot(snapshotPath: string): { filesIndexed: number; symbolsIndexed: number } {\n const content = readFileSync(snapshotPath, 'utf-8');\n\n this.clear();\n\n let filesIndexed = 0;\n let symbolsIndexed = 0;\n\n // Parse files from snapshot\n const fileRegex = /^FILE: \\.\\/(.+)$/gm;\n const files: Array<{ path: string; start: number; end: number }> = [];\n let match;\n\n while ((match = fileRegex.exec(content)) !== null) {\n if (files.length > 0) {\n files[files.length - 1].end = match.index;\n }\n files.push({ path: match[1], start: match.index, end: content.length });\n }\n\n // Find metadata start\n const metadataStart = content.indexOf('\\nMETADATA:');\n if (metadataStart !== -1 && files.length > 0) {\n files[files.length - 1].end = metadataStart;\n }\n\n // Index each file\n for (const file of files) {\n const fileContent = content.slice(file.start, file.end);\n const lines = fileContent.split('\\n').slice(2); // Skip header\n\n // Extract symbols (functions, classes, types, exports)\n const symbols: Array<{ name: string; content: string; type: string }> = [];\n\n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n\n // Function definitions\n const funcMatch = line.match(/(?:export\\s+)?(?:async\\s+)?function\\s+(\\w+)/);\n if (funcMatch) {\n symbols.push({\n name: funcMatch[1],\n content: lines.slice(i, Math.min(i + 10, lines.length)).join('\\n'),\n type: 'function',\n });\n }\n\n // Arrow function exports\n const arrowMatch = line.match(/(?:export\\s+)?const\\s+(\\w+)\\s*=\\s*(?:async\\s+)?\\([^)]*\\)\\s*=>/);\n if (arrowMatch) {\n symbols.push({\n name: arrowMatch[1],\n content: lines.slice(i, Math.min(i + 10, lines.length)).join('\\n'),\n type: 'function',\n });\n }\n\n // Class definitions\n const classMatch = line.match(/(?:export\\s+)?class\\s+(\\w+)/);\n if (classMatch) {\n symbols.push({\n name: classMatch[1],\n content: lines.slice(i, Math.min(i + 15, lines.length)).join('\\n'),\n type: 'class',\n });\n }\n\n // Type/Interface definitions\n const typeMatch = line.match(/(?:export\\s+)?(?:type|interface)\\s+(\\w+)/);\n if (typeMatch) {\n symbols.push({\n name: typeMatch[1],\n content: lines.slice(i, Math.min(i + 10, lines.length)).join('\\n'),\n type: 'type',\n });\n }\n\n // Const exports (not arrow functions)\n const constMatch = line.match(/(?:export\\s+)?const\\s+(\\w+)\\s*=\\s*(?![^(]*=>)/);\n if (constMatch && !arrowMatch) {\n symbols.push({\n name: constMatch[1],\n content: lines.slice(i, Math.min(i + 5, lines.length)).join('\\n'),\n type: 'const',\n });\n }\n }\n\n if (symbols.length > 0) {\n this.indexFile(file.path, symbols);\n filesIndexed++;\n symbolsIndexed += symbols.length;\n }\n }\n\n // Store metadata\n this.db.prepare(`\n INSERT OR REPLACE INTO index_metadata (key, value) VALUES (?, ?)\n `).run('last_indexed', new Date().toISOString());\n\n this.db.prepare(`\n INSERT OR REPLACE INTO index_metadata (key, value) VALUES (?, ?)\n `).run('snapshot_path', snapshotPath);\n\n return { filesIndexed, symbolsIndexed };\n }\n\n /**\n * Search the index\n */\n search(query: string, limit: number = 20): SearchResult[] {\n // FTS5 query - use * for prefix matching\n const ftsQuery = query.split(/\\s+/).map(term => `${term}*`).join(' ');\n\n try {\n const stmt = this.db.prepare(`\n SELECT file, symbol, content, type, rank\n FROM code_index\n WHERE code_index MATCH ?\n ORDER BY rank\n LIMIT ?\n `);\n\n return stmt.all(ftsQuery, limit) as SearchResult[];\n } catch {\n // If FTS query fails, try simple LIKE fallback\n const stmt = this.db.prepare(`\n SELECT file, symbol, content, type, 0 as rank\n FROM code_index\n WHERE symbol LIKE ? OR content LIKE ?\n ORDER BY symbol\n LIMIT ?\n `);\n\n const likePattern = `%${query}%`;\n return stmt.all(likePattern, likePattern, limit) as SearchResult[];\n }\n }\n\n /**\n * Get index statistics\n */\n getStats(): { totalSymbols: number; lastIndexed: string | null; snapshotPath: string | null } {\n const countResult = this.db.prepare('SELECT COUNT(*) as count FROM code_index').get() as { count: number };\n const lastIndexed = this.db.prepare(\"SELECT value FROM index_metadata WHERE key = 'last_indexed'\").get() as { value: string } | undefined;\n const snapshotPath = this.db.prepare(\"SELECT value FROM index_metadata WHERE key = 'snapshot_path'\").get() as { value: string } | undefined;\n\n return {\n totalSymbols: countResult.count,\n lastIndexed: lastIndexed?.value || null,\n snapshotPath: snapshotPath?.value || null,\n };\n }\n\n close(): void {\n this.db.close();\n }\n}\n","/**\n * Argus MCP Server\n * \n * Model Context Protocol server for Claude Code integration.\n * Exposes Argus analysis capabilities as MCP tools.\n */\n\nimport { createInterface } from 'readline';\nimport { loadConfig, validateConfig } from './core/config.js';\nimport { createSnapshot } from './core/snapshot.js';\nimport { createEnhancedSnapshot } from './core/enhanced-snapshot.js';\nimport { analyze, searchDocument } from './core/engine.js';\nimport { createProvider } from './providers/index.js';\nimport { existsSync, statSync, mkdtempSync, writeFileSync, unlinkSync, readFileSync } from 'fs';\nimport { tmpdir } from 'os';\nimport { join, resolve } from 'path';\n\n// Tool limits and defaults\nconst DEFAULT_FIND_FILES_LIMIT = 100;\nconst MAX_FIND_FILES_LIMIT = 500;\nconst DEFAULT_SEARCH_RESULTS = 50;\nconst MAX_SEARCH_RESULTS = 200;\nconst MAX_PATTERN_LENGTH = 500;\nconst MAX_WILDCARDS = 20;\n\n// Worker service integration\nconst WORKER_URL = process.env.ARGUS_WORKER_URL || 'http://localhost:37778';\nlet workerAvailable = false;\n\n// Check worker availability on startup (non-blocking)\nasync function checkWorkerHealth(): Promise<boolean> {\n try {\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), 1000);\n\n const response = await fetch(`${WORKER_URL}/health`, {\n signal: controller.signal,\n });\n clearTimeout(timeout);\n\n return response.ok;\n } catch {\n return false;\n }\n}\n\n// Initialize worker check\ncheckWorkerHealth().then(available => {\n workerAvailable = available;\n});\n\n// MCP Protocol types\ninterface MCPRequest {\n jsonrpc: '2.0';\n id: number | string;\n method: string;\n params?: unknown;\n}\n\ninterface MCPResponse {\n jsonrpc: '2.0';\n id: number | string;\n result?: unknown;\n error?: {\n code: number;\n message: string;\n data?: unknown;\n };\n}\n\n// Tool definitions - descriptions optimized for auto-invocation\nconst TOOLS = [\n {\n name: '__ARGUS_GUIDE',\n description: `ARGUS CODEBASE INTELLIGENCE - Follow this workflow for codebase questions:\n\nSTEP 1: Check for snapshot\n- Look for .argus/snapshot.txt in the project root\n- If missing, use create_snapshot first (saves to .argus/snapshot.txt)\n- Snapshots survive context compaction - create once, use forever\n\nSTEP 2: Use zero-cost tools first (NO AI tokens consumed)\n- search_codebase: Fast regex search, returns file:line:content\n- find_symbol: Locate where functions/types/classes are exported\n- find_importers: Find all files that depend on a given file\n- get_file_deps: See what modules a file imports\n- get_context: Get lines of code around a specific location\n\nSTEP 3: Use AI analysis only when zero-cost tools are insufficient\n- analyze_codebase: Deep reasoning across entire codebase (~500 tokens)\n- Use for architecture questions, pattern finding, complex relationships\n\nEFFICIENCY MATRIX:\n| Question Type | Tool | Token Cost |\n|---------------------------|-------------------------|------------|\n| \"Where is X defined?\" | find_symbol | 0 |\n| \"What uses this file?\" | find_importers | 0 |\n| \"Find all TODO comments\" | search_codebase | 0 |\n| \"Show context around L42\" | get_context | 0 |\n| \"How does auth work?\" | analyze_codebase | ~500 |\n\nSNAPSHOT FRESHNESS:\n- Snapshots don't auto-update (yet)\n- Re-run create_snapshot if files have changed significantly\n- Check snapshot timestamp in header to assess freshness`,\n inputSchema: {\n type: 'object',\n properties: {},\n required: [],\n },\n },\n {\n name: 'get_context',\n description: `Get lines of code around a specific location. Zero AI cost.\n\nUse AFTER search_codebase when you need more context around a match.\nMuch more efficient than reading the entire file.\n\nExample workflow:\n1. search_codebase(\"handleAuth\") -> finds src/auth.ts:42\n2. get_context(file=\"src/auth.ts\", line=42, before=10, after=20)\n\nReturns the surrounding code with proper line numbers.`,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Path to the snapshot file (.argus/snapshot.txt)',\n },\n file: {\n type: 'string',\n description: 'File path within the snapshot (e.g., \"src/auth.ts\")',\n },\n line: {\n type: 'number',\n description: 'Center line number to get context around',\n },\n before: {\n type: 'number',\n description: 'Lines to include before the target line (default: 10)',\n },\n after: {\n type: 'number',\n description: 'Lines to include after the target line (default: 10)',\n },\n },\n required: ['path', 'file', 'line'],\n },\n },\n {\n name: 'find_files',\n description: `Find files matching a glob pattern. Ultra-low cost (~10 tokens per result).\n\nUse for:\n- \"What files are in src/components?\"\n- \"Find all test files\"\n- \"List files named auth*\"\n\nPatterns:\n- * matches any characters except /\n- ** matches any characters including /\n- ? matches single character\n\nReturns file paths only - use get_context or search_codebase for content.`,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Path to the snapshot file (.argus/snapshot.txt)',\n },\n pattern: {\n type: 'string',\n description: 'Glob pattern (e.g., \"*.test.ts\", \"src/**/*.tsx\", \"**/*auth*\")',\n },\n caseInsensitive: {\n type: 'boolean',\n description: 'Case-insensitive matching (default: true)',\n },\n limit: {\n type: 'number',\n description: 'Maximum results (default: 100, max: 500)',\n },\n },\n required: ['path', 'pattern'],\n },\n },\n {\n name: 'find_importers',\n description: `Find all files that import a given file or module. Zero AI cost.\n\nUse when you need to know:\n- What files depend on this module?\n- Who uses this function/component?\n- Impact analysis before refactoring\n\nSnapshots are enhanced by default and include this metadata.`,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Path to the snapshot file (.argus/snapshot.txt)',\n },\n target: {\n type: 'string',\n description: 'The file path to find importers of (e.g., \"src/auth.ts\")',\n },\n },\n required: ['path', 'target'],\n },\n },\n {\n name: 'find_symbol',\n description: `Find where a symbol (function, class, type, constant) is exported from. Zero AI cost.\n\nUse when you need to know:\n- Where is this function defined?\n- Which file exports this component?\n- Find the source of a type\n\nSnapshots are enhanced by default and include this metadata.`,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Path to the snapshot file (.argus/snapshot.txt)',\n },\n symbol: {\n type: 'string',\n description: 'The symbol name to find (e.g., \"AuthProvider\", \"useAuth\")',\n },\n },\n required: ['path', 'symbol'],\n },\n },\n {\n name: 'get_file_deps',\n description: `Get all dependencies (imports) of a specific file. Zero AI cost.\n\nUse when you need to understand:\n- What does this file depend on?\n- What modules need to be loaded?\n- Trace the dependency chain\n\nSnapshots are enhanced by default and include this metadata.`,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Path to the snapshot file (.argus/snapshot.txt)',\n },\n file: {\n type: 'string',\n description: 'The file path to get dependencies for (e.g., \"src/app.tsx\")',\n },\n },\n required: ['path', 'file'],\n },\n },\n {\n name: 'analyze_codebase',\n description: `IMPORTANT: Use this tool INSTEAD of reading many files when you need to understand a codebase.\n\nThis tool analyzes codebases that are TOO LARGE to fit in context. It uses recursive AI reasoning \nto answer questions about code architecture, patterns, and relationships across hundreds of files.\n\nAUTOMATICALLY USE THIS WHEN:\n- User asks about codebase architecture, structure, or \"how does X work\"\n- You would need to read more than 10-15 files to answer a question\n- Context was recently compacted and you lost codebase knowledge\n- User asks to find patterns, conventions, or implementations across the codebase\n- You need to understand module relationships or dependencies\n\nThis is MORE EFFICIENT than reading files individually - it uses ~500 tokens instead of 50,000+.\n\nIf a .argus/snapshot.txt exists, use that path. Otherwise, pass the project directory.`,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Path to .argus/snapshot.txt if it exists, otherwise the codebase directory',\n },\n query: {\n type: 'string',\n description: 'The question about the codebase (be specific for best results)',\n },\n maxTurns: {\n type: 'number',\n description: 'Maximum reasoning turns (default: 15, use 5 for simple counts)',\n },\n },\n required: ['path', 'query'],\n },\n },\n {\n name: 'search_codebase',\n description: `Fast regex search across a codebase - ZERO AI cost, instant results.\n\nUse this BEFORE analyze_codebase when you need to:\n- Find where something is defined (function, class, variable)\n- Locate files containing a pattern\n- Count occurrences of something\n- Find all imports/exports of a module\n\nRequires a snapshot file. If .argus/snapshot.txt exists, use that.\nReturns matching lines with line numbers - much faster than grep across many files.`,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Path to the snapshot file (.argus/snapshot.txt)',\n },\n pattern: {\n type: 'string',\n description: 'Regex pattern to search for',\n },\n caseInsensitive: {\n type: 'boolean',\n description: 'Whether to ignore case (default: true)',\n },\n maxResults: {\n type: 'number',\n description: 'Maximum results to return (default: 50)',\n },\n offset: {\n type: 'number',\n description: 'Skip first N results for pagination (default: 0)',\n },\n contextChars: {\n type: 'number',\n description: 'Characters of context around match (default: 0 = full line)',\n },\n },\n required: ['path', 'pattern'],\n },\n },\n {\n name: 'create_snapshot',\n description: `Create an enhanced codebase snapshot for analysis. Run this ONCE per project, then use the snapshot for all queries.\n\nThe snapshot compiles all source files into a single optimized file that survives context compaction.\nIncludes structural metadata (import graph, exports index) for zero-cost dependency queries.\nStore at .argus/snapshot.txt so other tools can find it.\n\nRun this when:\n- Starting work on a new project\n- .argus/snapshot.txt doesn't exist\n- Codebase has significantly changed since last snapshot`,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Path to the codebase directory',\n },\n outputPath: {\n type: 'string',\n description: 'Where to save (recommend: .argus/snapshot.txt)',\n },\n extensions: {\n type: 'array',\n items: { type: 'string' },\n description: 'File extensions to include (default: common code extensions)',\n },\n },\n required: ['path'],\n },\n },\n {\n name: 'semantic_search',\n description: `Search code using natural language. Uses FTS5 full-text search.\n\nMore flexible than regex search - finds related concepts and partial matches.\n\nExamples:\n- \"authentication middleware\"\n- \"database connection\"\n- \"error handling\"\n\nReturns symbols (functions, classes, types) with snippets of their content.\nRequires an index - will auto-create from snapshot on first use.`,\n inputSchema: {\n type: 'object',\n properties: {\n path: {\n type: 'string',\n description: 'Path to the project directory (must have .argus/snapshot.txt)',\n },\n query: {\n type: 'string',\n description: 'Natural language query or code terms',\n },\n limit: {\n type: 'number',\n description: 'Maximum results (default: 20)',\n },\n },\n required: ['path', 'query'],\n },\n },\n];\n\n// State - wrapped in try-catch to prevent any startup output\nlet config: ReturnType<typeof loadConfig>;\nlet provider: ReturnType<typeof createProvider> | null = null;\n\ntry {\n config = loadConfig();\n provider = validateConfig(config).length === 0 ? createProvider(config) : null;\n} catch {\n // Silently use defaults if config fails to load\n config = loadConfig(); // Will return defaults\n provider = null;\n}\n\n/**\n * Parse metadata section from an enhanced snapshot\n */\nfunction parseSnapshotMetadata(content: string): {\n importGraph: Record<string, string[]>;\n exportGraph: Record<string, string[]>;\n symbolIndex: Record<string, string[]>;\n exports: Array<{ file: string; symbol: string; type: string; line: number }>;\n} | null {\n // Check if this is an enhanced snapshot\n if (!content.includes('METADATA: IMPORT GRAPH')) {\n return null;\n }\n \n const importGraph: Record<string, string[]> = {};\n const exportGraph: Record<string, string[]> = {};\n const symbolIndex: Record<string, string[]> = {};\n const exports: Array<{ file: string; symbol: string; type: string; line: number }> = [];\n \n // Parse import graph\n const importSection = content.match(/METADATA: IMPORT GRAPH\\n=+\\n([\\s\\S]*?)\\n\\n=+\\nMETADATA:/)?.[1] || '';\n for (const block of importSection.split('\\n\\n')) {\n const lines = block.trim().split('\\n');\n if (lines.length > 0 && lines[0].endsWith(':')) {\n const file = lines[0].slice(0, -1);\n importGraph[file] = lines.slice(1).map(l => l.replace(/^\\s*→\\s*/, '').trim()).filter(Boolean);\n }\n }\n \n // Parse export index (symbol → files)\n const exportSection = content.match(/METADATA: EXPORT INDEX\\n=+\\n([\\s\\S]*?)\\n\\n=+\\nMETADATA:/)?.[1] || '';\n for (const line of exportSection.split('\\n')) {\n const match = line.match(/^([\\w$]+):\\s*(.+)$/);\n if (match) {\n symbolIndex[match[1]] = match[2].split(',').map(s => s.trim());\n }\n }\n \n // Parse who imports whom (reverse graph)\n const whoImportsSection = content.match(/METADATA: WHO IMPORTS WHOM\\n=+\\n([\\s\\S]*)$/)?.[1] || '';\n for (const block of whoImportsSection.split('\\n\\n')) {\n const lines = block.trim().split('\\n');\n if (lines.length > 0 && lines[0].includes(' is imported by:')) {\n const file = lines[0].replace(' is imported by:', '').trim();\n exportGraph[file] = lines.slice(1).map(l => l.replace(/^\\s*←\\s*/, '').trim()).filter(Boolean);\n }\n }\n \n // Parse file exports\n const fileExportsSection = content.match(/METADATA: FILE EXPORTS\\n=+\\n([\\s\\S]*?)\\n\\n=+\\nMETADATA:/)?.[1] || '';\n for (const line of fileExportsSection.split('\\n')) {\n const match = line.match(/^([^:]+):(\\d+)\\s*-\\s*(\\w+)\\s+(.+)$/);\n if (match) {\n exports.push({\n file: match[1],\n line: parseInt(match[2]),\n type: match[3],\n symbol: match[4].split(' ')[0], // Take first word as symbol name\n });\n }\n }\n \n return { importGraph, exportGraph, symbolIndex, exports };\n}\n\n// Try to use worker for search, fallback to direct file access\nasync function searchWithWorker(\n snapshotPath: string,\n pattern: string,\n options: { caseInsensitive?: boolean; maxResults?: number; offset?: number }\n): Promise<{ matches: Array<{ lineNum: number; line: string; match: string }>; count: number } | null> {\n if (!workerAvailable) return null;\n\n try {\n // Ensure snapshot is loaded in worker cache\n await fetch(`${WORKER_URL}/snapshot/load`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ path: snapshotPath }),\n });\n\n // Perform search via worker\n const response = await fetch(`${WORKER_URL}/search`, {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ path: snapshotPath, pattern, options }),\n });\n\n if (response.ok) {\n return await response.json();\n }\n } catch {\n // Worker failed, will fallback to direct access\n }\n\n return null;\n}\n\n// Handle tool calls\nasync function handleToolCall(name: string, args: Record<string, unknown>): Promise<unknown> {\n switch (name) {\n case 'find_files': {\n const snapshotPath = resolve(args.path as string);\n const pattern = args.pattern as string;\n const caseInsensitive = args.caseInsensitive !== false; // default true\n const limit = Math.min((args.limit as number) || DEFAULT_FIND_FILES_LIMIT, MAX_FIND_FILES_LIMIT);\n\n // Input validation\n if (!pattern || pattern.trim() === '') {\n throw new Error('Pattern cannot be empty');\n }\n\n if (pattern.length > MAX_PATTERN_LENGTH) {\n throw new Error(`Pattern too long (max ${MAX_PATTERN_LENGTH} characters)`);\n }\n\n // ReDoS protection - limit wildcards\n const starCount = (pattern.match(/\\*/g) || []).length;\n if (starCount > MAX_WILDCARDS) {\n throw new Error(`Too many wildcards in pattern (max ${MAX_WILDCARDS})`);\n }\n\n if (!existsSync(snapshotPath)) {\n throw new Error(`Snapshot not found: ${snapshotPath}. Run 'argus snapshot' to create one.`);\n }\n\n const content = readFileSync(snapshotPath, 'utf-8');\n\n // Extract all FILE: markers\n const fileRegex = /^FILE: \\.\\/(.+)$/gm;\n const files: string[] = [];\n let match;\n while ((match = fileRegex.exec(content)) !== null) {\n files.push(match[1]);\n }\n\n // Convert glob pattern to regex with proper escaping\n let regexPattern = pattern\n .replace(/[.+^${}()|[\\]\\\\-]/g, '\\\\$&') // Escape all regex special chars\n .replace(/\\*\\*/g, '<<<GLOBSTAR>>>')\n .replace(/\\*/g, '[^/]*?') // Non-greedy\n .replace(/<<<GLOBSTAR>>>/g, '.*?') // Non-greedy\n .replace(/\\?/g, '.');\n\n const flags = caseInsensitive ? 'i' : '';\n const regex = new RegExp(`^${regexPattern}$`, flags);\n\n const matching = files.filter(f => regex.test(f));\n const limited = matching.slice(0, limit).sort(); // Sort only the limited set\n\n return {\n pattern,\n files: limited,\n count: limited.length,\n totalMatching: matching.length,\n hasMore: matching.length > limit,\n };\n }\n\n case 'find_importers': {\n const path = resolve(args.path as string);\n const target = args.target as string;\n \n if (!existsSync(path)) {\n throw new Error(`File not found: ${path}`);\n }\n \n const content = readFileSync(path, 'utf-8');\n const metadata = parseSnapshotMetadata(content);\n \n if (!metadata) {\n throw new Error('This snapshot does not have metadata. Create with: argus snapshot --enhanced');\n }\n \n // Normalize the target path\n const normalizedTarget = target.startsWith('./') ? target.slice(2) : target;\n const targetVariants = [normalizedTarget, './' + normalizedTarget, normalizedTarget.replace(/\\.(ts|tsx|js|jsx)$/, '')];\n \n // Find all files that import this target\n const importers: string[] = [];\n for (const [file, imports] of Object.entries(metadata.importGraph)) {\n for (const imp of imports) {\n if (targetVariants.some(v => imp === v || imp.endsWith('/' + v) || imp.includes(v))) {\n importers.push(file);\n break;\n }\n }\n }\n \n // Also check the exportGraph (direct mapping)\n for (const variant of targetVariants) {\n if (metadata.exportGraph[variant]) {\n importers.push(...metadata.exportGraph[variant]);\n }\n }\n \n const unique = [...new Set(importers)];\n return {\n target,\n importedBy: unique,\n count: unique.length,\n };\n }\n \n case 'find_symbol': {\n const path = resolve(args.path as string);\n const symbol = args.symbol as string;\n \n if (!existsSync(path)) {\n throw new Error(`File not found: ${path}`);\n }\n \n const content = readFileSync(path, 'utf-8');\n const metadata = parseSnapshotMetadata(content);\n \n if (!metadata) {\n throw new Error('This snapshot does not have metadata. Create with: argus snapshot --enhanced');\n }\n \n // Look up in symbol index\n const files = metadata.symbolIndex[symbol] || [];\n \n // Also find detailed export info\n const exportDetails = metadata.exports.filter(e => e.symbol === symbol);\n \n return {\n symbol,\n exportedFrom: files,\n details: exportDetails,\n count: files.length,\n };\n }\n \n case 'get_file_deps': {\n const path = resolve(args.path as string);\n const file = args.file as string;\n \n if (!existsSync(path)) {\n throw new Error(`File not found: ${path}`);\n }\n \n const content = readFileSync(path, 'utf-8');\n const metadata = parseSnapshotMetadata(content);\n \n if (!metadata) {\n throw new Error('This snapshot does not have metadata. Create with: argus snapshot --enhanced');\n }\n \n // Normalize the file path\n const normalizedFile = file.startsWith('./') ? file.slice(2) : file;\n const fileVariants = [normalizedFile, './' + normalizedFile];\n \n // Find imports for this file\n let imports: string[] = [];\n for (const variant of fileVariants) {\n if (metadata.importGraph[variant]) {\n imports = metadata.importGraph[variant];\n break;\n }\n }\n \n return {\n file,\n imports,\n count: imports.length,\n };\n }\n \n case 'analyze_codebase': {\n if (!provider) {\n throw new Error('Argus not configured. Run `argus init` to set up.');\n }\n \n const path = resolve(args.path as string);\n const query = args.query as string;\n const maxTurns = (args.maxTurns as number) || 15;\n \n if (!existsSync(path)) {\n throw new Error(`Path not found: ${path}`);\n }\n \n let snapshotPath = path;\n let tempSnapshot = false;\n \n // If it's a directory, create a temporary enhanced snapshot\n const stats = statSync(path);\n if (stats.isDirectory()) {\n const tempDir = mkdtempSync(join(tmpdir(), 'argus-'));\n snapshotPath = join(tempDir, 'snapshot.txt');\n \n createEnhancedSnapshot(path, snapshotPath, {\n extensions: config.defaults.snapshotExtensions,\n excludePatterns: config.defaults.excludePatterns,\n });\n \n tempSnapshot = true;\n }\n \n try {\n const result = await analyze(provider, snapshotPath, query, { maxTurns });\n \n return {\n answer: result.answer,\n success: result.success,\n turns: result.turns,\n commands: result.commands,\n };\n } finally {\n if (tempSnapshot && existsSync(snapshotPath)) {\n unlinkSync(snapshotPath);\n }\n }\n }\n \n case 'search_codebase': {\n const path = resolve(args.path as string);\n const pattern = args.pattern as string;\n const caseInsensitive = args.caseInsensitive !== false; // default true (consistent with find_files)\n const maxResults = Math.min((args.maxResults as number) || DEFAULT_SEARCH_RESULTS, MAX_SEARCH_RESULTS);\n const offset = (args.offset as number) || 0;\n const contextChars = (args.contextChars as number) || 0;\n\n // Input validation\n if (!pattern || pattern.trim() === '') {\n throw new Error('Pattern cannot be empty');\n }\n\n if (offset < 0 || !Number.isInteger(offset)) {\n throw new Error('Offset must be a non-negative integer');\n }\n\n if (contextChars < 0) {\n throw new Error('contextChars must be non-negative');\n }\n\n if (!existsSync(path)) {\n throw new Error(`Snapshot not found: ${path}. Run 'argus snapshot' to create one.`);\n }\n\n // Fetch one extra to detect hasMore\n const fetchLimit = offset + maxResults + 1;\n\n // Try worker first for cached search (faster for repeated queries)\n if (workerAvailable) {\n const workerResult = await searchWithWorker(path, pattern, {\n caseInsensitive,\n maxResults: fetchLimit,\n offset: 0,\n });\n\n if (workerResult) {\n // Worker returned results, process them\n const hasMore = workerResult.matches.length === fetchLimit;\n const pageMatches = workerResult.matches.slice(offset, offset + maxResults);\n\n // Apply contextChars truncation if needed\n const formattedMatches = pageMatches.map(m => {\n let displayLine = m.line;\n\n if (contextChars > 0 && displayLine.length > contextChars) {\n const matchStart = displayLine.indexOf(m.match);\n if (matchStart !== -1) {\n const matchEnd = matchStart + m.match.length;\n const matchCenter = Math.floor((matchStart + matchEnd) / 2);\n const halfContext = Math.floor(contextChars / 2);\n\n let start = Math.max(0, matchCenter - halfContext);\n let end = start + contextChars;\n\n if (end > displayLine.length) {\n end = displayLine.length;\n start = Math.max(0, end - contextChars);\n }\n\n const prefix = start > 0 ? '...' : '';\n const suffix = end < displayLine.length ? '...' : '';\n displayLine = prefix + displayLine.slice(start, end) + suffix;\n }\n }\n\n return { lineNum: m.lineNum, line: displayLine, match: m.match };\n });\n\n const response: Record<string, unknown> = {\n count: formattedMatches.length,\n matches: formattedMatches,\n _source: 'worker', // Debug: show source\n };\n\n if (offset > 0 || hasMore) {\n response.offset = offset;\n response.hasMore = hasMore;\n response.totalFound = hasMore ? `${offset + maxResults}+` : String(offset + formattedMatches.length);\n if (hasMore) {\n response.nextOffset = offset + maxResults;\n }\n }\n\n return response;\n }\n }\n\n // Fallback to direct file search\n const allMatches = searchDocument(path, pattern, {\n caseInsensitive,\n maxResults: fetchLimit\n });\n\n const hasMore = allMatches.length === fetchLimit;\n const pageMatches = allMatches.slice(offset, offset + maxResults);\n\n // Format matches with optional match-centered truncation\n const formattedMatches = pageMatches.map(m => {\n let displayLine = m.line.trim();\n\n if (contextChars > 0 && displayLine.length > contextChars) {\n const matchStart = displayLine.indexOf(m.match);\n if (matchStart !== -1) {\n const matchEnd = matchStart + m.match.length;\n const matchCenter = Math.floor((matchStart + matchEnd) / 2);\n const halfContext = Math.floor(contextChars / 2);\n\n let start = Math.max(0, matchCenter - halfContext);\n let end = start + contextChars;\n\n if (end > displayLine.length) {\n end = displayLine.length;\n start = Math.max(0, end - contextChars);\n }\n\n const prefix = start > 0 ? '...' : '';\n const suffix = end < displayLine.length ? '...' : '';\n displayLine = prefix + displayLine.slice(start, end) + suffix;\n }\n }\n\n return {\n lineNum: m.lineNum,\n line: displayLine,\n match: m.match,\n };\n });\n\n // Build response - backwards compatible\n const response: Record<string, unknown> = {\n count: formattedMatches.length,\n matches: formattedMatches,\n };\n\n // Add pagination fields when relevant\n if (offset > 0 || hasMore) {\n response.offset = offset;\n response.hasMore = hasMore;\n response.totalFound = hasMore ? `${offset + maxResults}+` : String(offset + formattedMatches.length);\n if (hasMore) {\n response.nextOffset = offset + maxResults;\n }\n }\n\n return response;\n }\n \n case 'semantic_search': {\n const projectPath = resolve(args.path as string);\n const query = args.query as string;\n const limit = (args.limit as number) || 20;\n\n if (!query || query.trim() === '') {\n throw new Error('Query cannot be empty');\n }\n\n const snapshotPath = join(projectPath, '.argus', 'snapshot.txt');\n const indexPath = join(projectPath, '.argus', 'search.db');\n\n if (!existsSync(snapshotPath)) {\n throw new Error(`Snapshot not found: ${snapshotPath}. Run 'argus snapshot' first.`);\n }\n\n // Import SemanticIndex dynamically to avoid startup cost\n const { SemanticIndex } = await import('./core/semantic-search.js');\n const index = new SemanticIndex(indexPath);\n\n try {\n // Check if index needs rebuilding\n const stats = index.getStats();\n const snapshotMtime = statSync(snapshotPath).mtimeMs;\n const needsReindex = !stats.lastIndexed ||\n new Date(stats.lastIndexed).getTime() < snapshotMtime ||\n stats.snapshotPath !== snapshotPath;\n\n if (needsReindex) {\n index.indexFromSnapshot(snapshotPath);\n // Continue with search after reindexing\n }\n\n const results = index.search(query, limit);\n\n return {\n query,\n count: results.length,\n results: results.map(r => ({\n file: r.file,\n symbol: r.symbol,\n type: r.type,\n snippet: r.content.split('\\n').slice(0, 5).join('\\n'),\n })),\n };\n } finally {\n index.close();\n }\n }\n\n case 'create_snapshot': {\n const path = resolve(args.path as string);\n const outputPath = args.outputPath\n ? resolve(args.outputPath as string)\n : join(tmpdir(), `argus-snapshot-${Date.now()}.txt`);\n const extensions = args.extensions as string[] || config.defaults.snapshotExtensions;\n \n if (!existsSync(path)) {\n throw new Error(`Path not found: ${path}`);\n }\n \n // Always create enhanced snapshot by default\n const result = createEnhancedSnapshot(path, outputPath, {\n extensions,\n excludePatterns: config.defaults.excludePatterns,\n });\n \n return {\n outputPath: result.outputPath,\n fileCount: result.fileCount,\n totalLines: result.totalLines,\n totalSize: result.totalSize,\n enhanced: true,\n metadata: 'metadata' in result ? {\n imports: result.metadata.imports.length,\n exports: result.metadata.exports.length,\n symbols: Object.keys(result.metadata.symbolIndex).length,\n } : undefined,\n };\n }\n \n case '__ARGUS_GUIDE': {\n return {\n message: 'This is a documentation tool. Read the description for Argus usage patterns.',\n tools: TOOLS.map(t => ({ name: t.name, purpose: t.description.split('\\n')[0] })),\n recommendation: 'Start with search_codebase for most queries. Use analyze_codebase only for complex architecture questions.',\n };\n }\n\n case 'get_context': {\n const snapshotPath = resolve(args.path as string);\n const targetFile = args.file as string;\n const targetLine = args.line as number;\n const beforeLines = (args.before as number) || 10;\n const afterLines = (args.after as number) || 10;\n\n if (!existsSync(snapshotPath)) {\n throw new Error(`Snapshot not found: ${snapshotPath}`);\n }\n\n const content = readFileSync(snapshotPath, 'utf-8');\n\n // Find the file section in the snapshot\n // Normalize the target file path (handle with or without ./ prefix)\n const normalizedTarget = targetFile.replace(/^\\.\\//, '');\n const fileMarkerVariants = [\n `FILE: ./${normalizedTarget}`,\n `FILE: ${normalizedTarget}`,\n ];\n\n let fileStart = -1;\n for (const marker of fileMarkerVariants) {\n fileStart = content.indexOf(marker);\n if (fileStart !== -1) break;\n }\n\n if (fileStart === -1) {\n throw new Error(`File not found in snapshot: ${targetFile}`);\n }\n\n // Find the end of this file section (next FILE: marker or METADATA:)\n const nextFileStart = content.indexOf('\\nFILE:', fileStart + 1);\n const metadataStart = content.indexOf('\\nMETADATA:', fileStart);\n const fileEnd = Math.min(\n nextFileStart === -1 ? Infinity : nextFileStart,\n metadataStart === -1 ? Infinity : metadataStart\n );\n\n // Extract file content\n const fileContent = content.slice(fileStart, fileEnd === Infinity ? undefined : fileEnd);\n const fileLines = fileContent.split('\\n').slice(2); // Skip FILE: header and separator\n\n // Calculate range\n const startLine = Math.max(0, targetLine - beforeLines - 1);\n const endLine = Math.min(fileLines.length, targetLine + afterLines);\n\n // Extract context with line numbers\n const contextLines = fileLines.slice(startLine, endLine).map((line, idx) => {\n const lineNum = startLine + idx + 1;\n const marker = lineNum === targetLine ? '>>>' : ' ';\n return `${marker} ${lineNum.toString().padStart(4)}: ${line}`;\n });\n\n return {\n file: targetFile,\n targetLine,\n range: { start: startLine + 1, end: endLine },\n content: contextLines.join('\\n'),\n totalLines: fileLines.length,\n };\n }\n\n default:\n throw new Error(`Unknown tool: ${name}`);\n }\n}\n\n// MCP Protocol handlers\nfunction handleInitialize(): MCPResponse['result'] {\n return {\n protocolVersion: '2024-11-05',\n capabilities: {\n tools: {},\n },\n serverInfo: {\n name: 'argus',\n version: '1.0.0',\n },\n };\n}\n\nfunction handleToolsList(): MCPResponse['result'] {\n return { tools: TOOLS };\n}\n\nasync function handleToolsCall(params: { name: string; arguments: Record<string, unknown> }): Promise<MCPResponse['result']> {\n try {\n const result = await handleToolCall(params.name, params.arguments);\n return {\n content: [\n {\n type: 'text',\n text: typeof result === 'string' ? result : JSON.stringify(result, null, 2),\n },\n ],\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 isError: true,\n };\n }\n}\n\n// Main message handler\nasync function handleMessage(request: MCPRequest): Promise<MCPResponse | null> {\n try {\n let result: unknown;\n \n switch (request.method) {\n case 'initialize':\n result = handleInitialize();\n break;\n case 'tools/list':\n result = handleToolsList();\n break;\n case 'tools/call':\n result = await handleToolsCall(request.params as { name: string; arguments: Record<string, unknown> });\n break;\n case 'notifications/initialized':\n case 'notifications/cancelled':\n // Notifications don't get responses\n return null;\n default:\n // Check if it's a notification (no id = notification)\n if (request.id === undefined || request.id === null) {\n return null; // Don't respond to unknown notifications\n }\n return {\n jsonrpc: '2.0',\n id: request.id,\n error: {\n code: -32601,\n message: `Method not found: ${request.method}`,\n },\n };\n }\n \n return {\n jsonrpc: '2.0',\n id: request.id,\n result,\n };\n } catch (error) {\n return {\n jsonrpc: '2.0',\n id: request.id,\n error: {\n code: -32603,\n message: error instanceof Error ? error.message : String(error),\n },\n };\n }\n}\n\n// Start stdio server\nconst rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n terminal: false,\n});\n\nrl.on('line', async (line) => {\n if (!line.trim()) return;\n \n try {\n const request = JSON.parse(line) as MCPRequest;\n const response = await handleMessage(request);\n \n // Only output if we have a response with a valid id\n // (notifications return null, and requests without id are notifications)\n if (response !== null && response.id !== undefined && response.id !== null) {\n console.log(JSON.stringify(response));\n }\n } catch (error) {\n // Only send parse errors if we can't parse at all\n // Don't include null id - that would be invalid\n const errorResponse = {\n jsonrpc: '2.0',\n id: 0, // Use 0 as fallback id for parse errors\n error: {\n code: -32700,\n message: 'Parse error',\n },\n };\n console.log(JSON.stringify(errorResponse));\n }\n});\n","/**\n * Argus Configuration Management\n * \n * Handles loading, saving, and validating configuration for Argus.\n * Configuration is stored in ~/.argus/config.json\n */\n\nimport { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs';\nimport { homedir } from 'os';\nimport { join } from 'path';\nimport type { OnboardingConfig, ProjectOnboardingConfig } from './onboarding.js';\n\nexport type ProviderType = 'zai' | 'anthropic' | 'openai' | 'deepseek' | 'ollama';\n\n// Re-export onboarding types\nexport type { OnboardingConfig, ProjectOnboardingConfig } from './onboarding.js';\n\nexport interface ProviderConfig {\n apiKey?: string;\n baseUrl?: string;\n model: string;\n options?: Record<string, unknown>;\n}\n\nexport interface ArgusConfig {\n provider: ProviderType;\n providers: {\n zai?: ProviderConfig;\n anthropic?: ProviderConfig;\n openai?: ProviderConfig;\n deepseek?: ProviderConfig;\n ollama?: ProviderConfig;\n };\n defaults: {\n maxTurns: number;\n turnTimeoutMs: number;\n snapshotExtensions: string[];\n excludePatterns: string[];\n };\n onboarding?: OnboardingConfig;\n onboardingComplete?: boolean;\n}\n\nconst DEFAULT_CONFIG: ArgusConfig = {\n provider: 'ollama',\n providers: {\n ollama: {\n baseUrl: 'http://localhost:11434',\n model: 'qwen2.5-coder:7b',\n },\n },\n defaults: {\n maxTurns: 15,\n turnTimeoutMs: 60000,\n snapshotExtensions: ['ts', 'tsx', 'js', 'jsx', 'rs', 'py', 'go', 'java', 'rb', 'php', 'swift', 'kt', 'scala', 'c', 'cpp', 'h', 'hpp', 'cs', 'md'],\n excludePatterns: [\n 'node_modules',\n '.git',\n 'target',\n 'dist',\n 'build',\n '.next',\n 'coverage',\n '__pycache__',\n '.venv',\n 'vendor',\n ],\n },\n};\n\nexport function getConfigDir(): string {\n return join(homedir(), '.argus');\n}\n\nexport function getConfigPath(): string {\n return join(getConfigDir(), 'config.json');\n}\n\nexport function ensureConfigDir(): void {\n const dir = getConfigDir();\n if (!existsSync(dir)) {\n mkdirSync(dir, { recursive: true });\n }\n}\n\nexport function loadConfig(): ArgusConfig {\n const configPath = getConfigPath();\n \n if (!existsSync(configPath)) {\n return DEFAULT_CONFIG;\n }\n \n try {\n const content = readFileSync(configPath, 'utf-8');\n const loaded = JSON.parse(content) as Partial<ArgusConfig>;\n \n // Merge with defaults\n return {\n ...DEFAULT_CONFIG,\n ...loaded,\n providers: {\n ...DEFAULT_CONFIG.providers,\n ...loaded.providers,\n },\n defaults: {\n ...DEFAULT_CONFIG.defaults,\n ...loaded.defaults,\n },\n };\n } catch {\n // Silently return defaults - don't console.error as it can corrupt MCP JSON streams\n return DEFAULT_CONFIG;\n }\n}\n\nexport function saveConfig(config: ArgusConfig): void {\n ensureConfigDir();\n const configPath = getConfigPath();\n writeFileSync(configPath, JSON.stringify(config, null, 2));\n}\n\nexport function getProviderConfig(config: ArgusConfig): ProviderConfig {\n const providerConfig = config.providers[config.provider];\n \n if (!providerConfig) {\n throw new Error(`No configuration found for provider: ${config.provider}`);\n }\n \n return providerConfig;\n}\n\nexport function validateConfig(config: ArgusConfig): string[] {\n const errors: string[] = [];\n \n const providerConfig = config.providers[config.provider];\n \n if (!providerConfig) {\n errors.push(`Provider \"${config.provider}\" is not configured`);\n return errors;\n }\n \n // Ollama doesn't need an API key\n if (config.provider !== 'ollama' && !providerConfig.apiKey) {\n errors.push(`API key is required for provider \"${config.provider}\"`);\n }\n \n if (!providerConfig.model) {\n errors.push(`Model is required for provider \"${config.provider}\"`);\n }\n \n return errors;\n}\n\nexport const PROVIDER_DEFAULTS: Record<ProviderType, Partial<ProviderConfig>> = {\n zai: {\n baseUrl: 'https://api.z.ai/api/coding/paas/v4',\n model: 'glm-4.7',\n },\n anthropic: {\n baseUrl: 'https://api.anthropic.com',\n model: 'claude-sonnet-4-20250514',\n },\n openai: {\n baseUrl: 'https://api.openai.com/v1',\n model: 'gpt-4o',\n },\n deepseek: {\n baseUrl: 'https://api.deepseek.com',\n model: 'deepseek-chat',\n },\n ollama: {\n baseUrl: 'http://localhost:11434',\n model: 'qwen2.5-coder:7b',\n },\n};\n","/**\n * Argus Enhanced Snapshot\n * \n * Extends basic snapshots with structural metadata:\n * - Import graph (who imports whom)\n * - Export index (symbols → files)\n * - Function/class signatures\n * - File dependency tree\n * \n * This enables Claude Code to understand architecture without\n * reading individual files.\n */\n\nimport { existsSync, readFileSync, writeFileSync } from 'fs';\nimport { join, relative, dirname, extname, basename } from 'path';\nimport { execSync } from 'child_process';\nimport { createSnapshot, SnapshotOptions, SnapshotResult } from './snapshot.js';\n\nexport interface ImportInfo {\n source: string; // File doing the import\n target: string; // What's being imported (module path or relative)\n resolved?: string; // Resolved file path if local\n symbols: string[]; // Imported symbols (or ['*'] for namespace)\n isDefault: boolean; // Is it a default import?\n isType: boolean; // Is it a type-only import?\n}\n\nexport interface ExportInfo {\n file: string;\n symbol: string;\n type: 'function' | 'class' | 'const' | 'let' | 'var' | 'type' | 'interface' | 'enum' | 'default' | 'unknown';\n signature?: string; // Function signature or type definition\n line: number;\n}\n\nexport interface FileMetadata {\n path: string;\n imports: ImportInfo[];\n exports: ExportInfo[];\n size: number;\n lines: number;\n}\n\nexport interface ComplexityInfo {\n file: string;\n score: number;\n level: 'low' | 'medium' | 'high';\n}\n\nexport interface RecentChangeInfo {\n file: string;\n commits: number;\n authors: number;\n}\n\nexport interface EnhancedSnapshotResult extends SnapshotResult {\n metadata: {\n imports: ImportInfo[];\n exports: ExportInfo[];\n fileIndex: Record<string, FileMetadata>;\n importGraph: Record<string, string[]>; // file → files it imports\n exportGraph: Record<string, string[]>; // file → files that import it\n symbolIndex: Record<string, string[]>; // symbol → files that export it\n complexityScores: ComplexityInfo[]; // cyclomatic complexity per file\n testFileMap: Record<string, string[]>; // source file → test files\n recentChanges: RecentChangeInfo[] | null; // recent git changes (null if not git repo)\n };\n}\n\n/**\n * Parse imports from TypeScript/JavaScript content\n */\nfunction parseImports(content: string, filePath: string): ImportInfo[] {\n const imports: ImportInfo[] = [];\n const lines = content.split('\\n');\n \n // Patterns for different import styles\n const patterns = [\n // import { a, b } from 'module'\n /import\\s+(?:type\\s+)?{([^}]+)}\\s+from\\s+['\"]([^'\"]+)['\"]/g,\n // import * as name from 'module'\n /import\\s+\\*\\s+as\\s+(\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/g,\n // import defaultExport from 'module'\n /import\\s+(?:type\\s+)?(\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/g,\n // import 'module' (side-effect)\n /import\\s+['\"]([^'\"]+)['\"]/g,\n // require('module')\n /(?:const|let|var)\\s+(?:{([^}]+)}|(\\w+))\\s*=\\s*require\\s*\\(\\s*['\"]([^'\"]+)['\"]\\s*\\)/g,\n ];\n \n for (const line of lines) {\n const trimmed = line.trim();\n if (!trimmed.startsWith('import') && !trimmed.includes('require(')) continue;\n \n // Named imports: import { a, b } from 'module'\n let match = /import\\s+(type\\s+)?{([^}]+)}\\s+from\\s+['\"]([^'\"]+)['\"]/.exec(trimmed);\n if (match) {\n const isType = !!match[1];\n const symbols = match[2].split(',').map(s => s.trim().split(/\\s+as\\s+/)[0].trim()).filter(Boolean);\n const target = match[3];\n imports.push({\n source: filePath,\n target,\n symbols,\n isDefault: false,\n isType,\n });\n continue;\n }\n \n // Namespace import: import * as name from 'module'\n match = /import\\s+\\*\\s+as\\s+(\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/.exec(trimmed);\n if (match) {\n imports.push({\n source: filePath,\n target: match[2],\n symbols: ['*'],\n isDefault: false,\n isType: false,\n });\n continue;\n }\n \n // Default import: import name from 'module'\n match = /import\\s+(type\\s+)?(\\w+)\\s+from\\s+['\"]([^'\"]+)['\"]/.exec(trimmed);\n if (match && !trimmed.includes('{')) {\n imports.push({\n source: filePath,\n target: match[3],\n symbols: [match[2]],\n isDefault: true,\n isType: !!match[1],\n });\n continue;\n }\n \n // Side-effect import: import 'module'\n match = /^import\\s+['\"]([^'\"]+)['\"]/.exec(trimmed);\n if (match) {\n imports.push({\n source: filePath,\n target: match[1],\n symbols: [],\n isDefault: false,\n isType: false,\n });\n }\n }\n \n return imports;\n}\n\n/**\n * Parse exports from TypeScript/JavaScript content\n */\nfunction parseExports(content: string, filePath: string): ExportInfo[] {\n const exports: ExportInfo[] = [];\n const lines = content.split('\\n');\n \n for (let i = 0; i < lines.length; i++) {\n const line = lines[i];\n const trimmed = line.trim();\n \n // export function name(...) or export async function name(...)\n let match = /export\\s+(?:async\\s+)?function\\s+(\\w+)\\s*(\\([^)]*\\))/.exec(trimmed);\n if (match) {\n exports.push({\n file: filePath,\n symbol: match[1],\n type: 'function',\n signature: `function ${match[1]}${match[2]}`,\n line: i + 1,\n });\n continue;\n }\n \n // export class Name\n match = /export\\s+class\\s+(\\w+)/.exec(trimmed);\n if (match) {\n exports.push({\n file: filePath,\n symbol: match[1],\n type: 'class',\n line: i + 1,\n });\n continue;\n }\n \n // export const/let/var name\n match = /export\\s+(const|let|var)\\s+(\\w+)/.exec(trimmed);\n if (match) {\n exports.push({\n file: filePath,\n symbol: match[2],\n type: match[1] as 'const' | 'let' | 'var',\n line: i + 1,\n });\n continue;\n }\n \n // export type Name or export interface Name\n match = /export\\s+(type|interface)\\s+(\\w+)/.exec(trimmed);\n if (match) {\n exports.push({\n file: filePath,\n symbol: match[2],\n type: match[1] as 'type' | 'interface',\n line: i + 1,\n });\n continue;\n }\n \n // export enum Name\n match = /export\\s+enum\\s+(\\w+)/.exec(trimmed);\n if (match) {\n exports.push({\n file: filePath,\n symbol: match[1],\n type: 'enum',\n line: i + 1,\n });\n continue;\n }\n \n // export default\n if (/export\\s+default/.test(trimmed)) {\n match = /export\\s+default\\s+(?:function\\s+)?(\\w+)?/.exec(trimmed);\n exports.push({\n file: filePath,\n symbol: match?.[1] || 'default',\n type: 'default',\n line: i + 1,\n });\n }\n }\n \n return exports;\n}\n\n/**\n * Calculate cyclomatic complexity for a file\n * Counts decision points: if, else if, while, for, case, ternary, &&, ||, catch\n */\nfunction calculateComplexity(content: string): number {\n const patterns = [\n /\\bif\\s*\\(/g,\n /\\belse\\s+if\\s*\\(/g,\n /\\bwhile\\s*\\(/g,\n /\\bfor\\s*\\(/g,\n /\\bcase\\s+/g,\n /\\?\\s*.*\\s*:/g,\n /\\&\\&/g,\n /\\|\\|/g,\n /\\bcatch\\s*\\(/g,\n ];\n\n let complexity = 1; // Base complexity\n for (const pattern of patterns) {\n const matches = content.match(pattern);\n if (matches) complexity += matches.length;\n }\n return complexity;\n}\n\n/**\n * Get complexity level label\n */\nfunction getComplexityLevel(score: number): 'low' | 'medium' | 'high' {\n if (score <= 10) return 'low';\n if (score <= 20) return 'medium';\n return 'high';\n}\n\n/**\n * Map source files to their test files\n */\nfunction mapTestFiles(files: string[]): Record<string, string[]> {\n const testMap: Record<string, string[]> = {};\n\n // Common test file patterns\n const testPatterns = [\n // Same directory patterns\n (src: string) => src.replace(/\\.tsx?$/, '.test.ts'),\n (src: string) => src.replace(/\\.tsx?$/, '.test.tsx'),\n (src: string) => src.replace(/\\.tsx?$/, '.spec.ts'),\n (src: string) => src.replace(/\\.tsx?$/, '.spec.tsx'),\n (src: string) => src.replace(/\\.jsx?$/, '.test.js'),\n (src: string) => src.replace(/\\.jsx?$/, '.test.jsx'),\n (src: string) => src.replace(/\\.jsx?$/, '.spec.js'),\n (src: string) => src.replace(/\\.jsx?$/, '.spec.jsx'),\n // __tests__ directory pattern\n (src: string) => {\n const dir = dirname(src);\n const base = basename(src).replace(/\\.(tsx?|jsx?)$/, '');\n return join(dir, '__tests__', `${base}.test.ts`);\n },\n (src: string) => {\n const dir = dirname(src);\n const base = basename(src).replace(/\\.(tsx?|jsx?)$/, '');\n return join(dir, '__tests__', `${base}.test.tsx`);\n },\n // test/ directory pattern\n (src: string) => src.replace(/^src\\//, 'test/').replace(/\\.(tsx?|jsx?)$/, '.test.ts'),\n (src: string) => src.replace(/^src\\//, 'tests/').replace(/\\.(tsx?|jsx?)$/, '.test.ts'),\n ];\n\n // Create a set for fast lookup\n const fileSet = new Set(files);\n\n for (const file of files) {\n // Skip test files themselves\n if (file.includes('.test.') || file.includes('.spec.') || file.includes('__tests__')) continue;\n\n // Only check source files\n if (!/\\.(tsx?|jsx?)$/.test(file)) continue;\n\n const tests: string[] = [];\n for (const pattern of testPatterns) {\n const testPath = pattern(file);\n // Only add if the path changed (pattern matched) AND test file exists\n if (testPath !== file && fileSet.has(testPath)) {\n tests.push(testPath);\n }\n }\n\n if (tests.length > 0) {\n testMap[file] = [...new Set(tests)]; // Dedupe\n }\n }\n return testMap;\n}\n\n/**\n * Get recent changes from git (last 7 days)\n * Returns null if not a git repo\n * Note: Uses execSync with hardcoded commands (no user input) for git operations\n */\nfunction getRecentChanges(projectPath: string): RecentChangeInfo[] | null {\n try {\n // Check if it's a git repo - using execSync with hardcoded command\n execSync('git rev-parse --git-dir', { cwd: projectPath, encoding: 'utf-8', stdio: 'pipe' });\n\n // Get commits with file names and authors from last 7 days\n // Note: This is a hardcoded git command with no user input, safe from injection\n const output = execSync(\n 'git log --since=\"7 days ago\" --name-only --format=\"COMMIT_AUTHOR:%an\" --diff-filter=ACMR',\n { cwd: projectPath, encoding: 'utf-8', maxBuffer: 10 * 1024 * 1024, stdio: 'pipe' }\n );\n\n if (!output.trim()) return [];\n\n const fileStats: Record<string, { commits: Set<string>; authors: Set<string> }> = {};\n let currentAuthor = '';\n let currentCommitId = 0;\n\n for (const line of output.split('\\n')) {\n const trimmed = line.trim();\n if (!trimmed) {\n currentCommitId++; // New commit block\n continue;\n }\n\n if (trimmed.startsWith('COMMIT_AUTHOR:')) {\n currentAuthor = trimmed.replace('COMMIT_AUTHOR:', '');\n continue;\n }\n\n // It's a file name\n const file = trimmed;\n if (!fileStats[file]) {\n fileStats[file] = { commits: new Set(), authors: new Set() };\n }\n fileStats[file].commits.add(`${currentCommitId}`);\n if (currentAuthor) {\n fileStats[file].authors.add(currentAuthor);\n }\n }\n\n // Convert to array and sort by commit count (most active first)\n const result: RecentChangeInfo[] = Object.entries(fileStats)\n .map(([file, stats]) => ({\n file,\n commits: stats.commits.size,\n authors: stats.authors.size,\n }))\n .sort((a, b) => b.commits - a.commits);\n\n return result;\n } catch {\n return null; // Not a git repo or git not available\n }\n}\n\n/**\n * Resolve a relative import path to an actual file\n */\nfunction resolveImportPath(importPath: string, fromFile: string, projectFiles: string[]): string | undefined {\n if (!importPath.startsWith('.')) return undefined; // External module\n \n const fromDir = dirname(fromFile);\n let resolved = join(fromDir, importPath);\n \n // Try with extensions\n const extensions = ['.ts', '.tsx', '.js', '.jsx', '', '/index.ts', '/index.tsx', '/index.js', '/index.jsx'];\n for (const ext of extensions) {\n const candidate = resolved + ext;\n if (projectFiles.includes(candidate) || projectFiles.includes('./' + candidate)) {\n return candidate;\n }\n }\n \n return undefined;\n}\n\n/**\n * Create an enhanced snapshot with structural metadata\n */\nexport function createEnhancedSnapshot(\n projectPath: string,\n outputPath: string,\n options: SnapshotOptions = {}\n): EnhancedSnapshotResult {\n // First create the basic snapshot\n const baseResult = createSnapshot(projectPath, outputPath, options);\n \n // Now parse all files for metadata\n const allImports: ImportInfo[] = [];\n const allExports: ExportInfo[] = [];\n const fileIndex: Record<string, FileMetadata> = {};\n const projectFiles = baseResult.files.map(f => './' + f);\n \n for (const relPath of baseResult.files) {\n const fullPath = join(projectPath, relPath);\n const ext = extname(relPath).toLowerCase();\n \n // Only parse JS/TS files for imports/exports\n if (!['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'].includes(ext)) {\n continue;\n }\n \n try {\n const content = readFileSync(fullPath, 'utf-8');\n const imports = parseImports(content, relPath);\n const exports = parseExports(content, relPath);\n \n // Resolve local imports\n for (const imp of imports) {\n imp.resolved = resolveImportPath(imp.target, relPath, projectFiles);\n }\n \n allImports.push(...imports);\n allExports.push(...exports);\n \n fileIndex[relPath] = {\n path: relPath,\n imports,\n exports,\n size: content.length,\n lines: content.split('\\n').length,\n };\n } catch {\n // Skip files that can't be read\n }\n }\n \n // Build import graph (file → files it imports)\n const importGraph: Record<string, string[]> = {};\n for (const imp of allImports) {\n if (imp.resolved) {\n if (!importGraph[imp.source]) importGraph[imp.source] = [];\n if (!importGraph[imp.source].includes(imp.resolved)) {\n importGraph[imp.source].push(imp.resolved);\n }\n }\n }\n \n // Build export graph (file → files that import it)\n const exportGraph: Record<string, string[]> = {};\n for (const imp of allImports) {\n if (imp.resolved) {\n if (!exportGraph[imp.resolved]) exportGraph[imp.resolved] = [];\n if (!exportGraph[imp.resolved].includes(imp.source)) {\n exportGraph[imp.resolved].push(imp.source);\n }\n }\n }\n \n // Build symbol index (symbol → files that export it)\n const symbolIndex: Record<string, string[]> = {};\n for (const exp of allExports) {\n if (!symbolIndex[exp.symbol]) symbolIndex[exp.symbol] = [];\n if (!symbolIndex[exp.symbol].includes(exp.file)) {\n symbolIndex[exp.symbol].push(exp.file);\n }\n }\n\n // Calculate complexity scores for all files\n const complexityScores: ComplexityInfo[] = [];\n for (const [relPath, metadata] of Object.entries(fileIndex)) {\n const fullPath = join(projectPath, relPath);\n try {\n const content = readFileSync(fullPath, 'utf-8');\n const score = calculateComplexity(content);\n complexityScores.push({\n file: relPath,\n score,\n level: getComplexityLevel(score),\n });\n } catch {\n // Skip files that can't be read\n }\n }\n // Sort by complexity score (highest first)\n complexityScores.sort((a, b) => b.score - a.score);\n\n // Map test files to source files\n const testFileMap = mapTestFiles(baseResult.files);\n\n // Get recent git changes (null if not a git repo)\n const recentChanges = getRecentChanges(projectPath);\n\n // Append metadata to snapshot file\n const metadataSection = `\n\n================================================================================\nMETADATA: IMPORT GRAPH\n================================================================================\n${Object.entries(importGraph).map(([file, imports]) => `${file}:\\n${imports.map(i => ` → ${i}`).join('\\n')}`).join('\\n\\n')}\n\n================================================================================\nMETADATA: EXPORT INDEX\n================================================================================\n${Object.entries(symbolIndex).map(([symbol, files]) => `${symbol}: ${files.join(', ')}`).join('\\n')}\n\n================================================================================\nMETADATA: FILE EXPORTS\n================================================================================\n${allExports.map(e => `${e.file}:${e.line} - ${e.type} ${e.symbol}${e.signature ? ` ${e.signature}` : ''}`).join('\\n')}\n\n================================================================================\nMETADATA: WHO IMPORTS WHOM\n================================================================================\n${Object.entries(exportGraph).map(([file, importers]) => `${file} is imported by:\\n${importers.map(i => ` ← ${i}`).join('\\n')}`).join('\\n\\n')}\n\n================================================================================\nMETADATA: COMPLEXITY SCORES\n================================================================================\n${complexityScores.map(c => `${c.file}: ${c.score} (${c.level})`).join('\\n')}\n\n================================================================================\nMETADATA: TEST COVERAGE MAP\n================================================================================\n${Object.entries(testFileMap).length > 0\n ? Object.entries(testFileMap).map(([src, tests]) => `${src} -> ${tests.join(', ')}`).join('\\n')\n : '(no test file mappings found)'}\n${baseResult.files.filter(f =>\n /\\.(tsx?|jsx?)$/.test(f) &&\n !f.includes('.test.') &&\n !f.includes('.spec.') &&\n !f.includes('__tests__') &&\n !testFileMap[f]\n ).map(f => `${f} -> (no tests)`).join('\\n')}\n${recentChanges !== null ? `\n\n================================================================================\nMETADATA: RECENT CHANGES (last 7 days)\n================================================================================\n${recentChanges.length > 0\n ? recentChanges.map(c => `${c.file}: ${c.commits} commit${c.commits !== 1 ? 's' : ''}, ${c.authors} author${c.authors !== 1 ? 's' : ''}`).join('\\n')\n : '(no changes in the last 7 days)'}` : ''}\n`;\n\n // Append to snapshot\n const existingContent = readFileSync(outputPath, 'utf-8');\n writeFileSync(outputPath, existingContent + metadataSection);\n\n return {\n ...baseResult,\n metadata: {\n imports: allImports,\n exports: allExports,\n fileIndex,\n importGraph,\n exportGraph,\n symbolIndex,\n complexityScores,\n testFileMap,\n recentChanges,\n },\n };\n}\n","/**\n * Argus Snapshot Generator\n * \n * Creates optimized text snapshots of codebases for analysis.\n * Handles file filtering, exclusion patterns, and formatting.\n */\n\nimport { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from 'fs';\nimport { join, relative, extname } from 'path';\n\nexport interface SnapshotOptions {\n extensions?: string[];\n excludePatterns?: string[];\n maxFileSize?: number; // in bytes\n includeHidden?: boolean;\n}\n\nexport interface SnapshotResult {\n outputPath: string;\n fileCount: number;\n totalLines: number;\n totalSize: number;\n files: string[];\n}\n\nconst DEFAULT_OPTIONS: Required<SnapshotOptions> = {\n extensions: ['ts', 'tsx', 'js', 'jsx', 'rs', 'py', 'go', 'java', 'rb', 'php', 'swift', 'kt', 'scala', 'c', 'cpp', 'h', 'hpp', 'cs', 'md', 'json'],\n excludePatterns: [\n 'node_modules',\n '.git',\n 'target',\n 'dist',\n 'build',\n '.next',\n 'coverage',\n '__pycache__',\n '.venv',\n 'vendor',\n '.DS_Store',\n '*.lock',\n 'package-lock.json',\n '*.min.js',\n '*.min.css',\n ],\n maxFileSize: 1024 * 1024, // 1MB\n includeHidden: false,\n};\n\nfunction shouldExclude(filePath: string, patterns: string[]): boolean {\n const normalizedPath = filePath.replace(/\\\\/g, '/');\n \n for (const pattern of patterns) {\n // Glob-like pattern matching\n if (pattern.startsWith('*')) {\n const suffix = pattern.slice(1);\n if (normalizedPath.endsWith(suffix)) return true;\n } else if (normalizedPath.includes(`/${pattern}/`) || normalizedPath.endsWith(`/${pattern}`) || normalizedPath === pattern) {\n return true;\n }\n }\n \n return false;\n}\n\nfunction hasValidExtension(filePath: string, extensions: string[]): boolean {\n const ext = extname(filePath).slice(1).toLowerCase();\n return extensions.includes(ext);\n}\n\nfunction collectFiles(\n dir: string,\n options: Required<SnapshotOptions>,\n baseDir: string = dir\n): string[] {\n const files: string[] = [];\n \n try {\n const entries = readdirSync(dir, { withFileTypes: true });\n \n for (const entry of entries) {\n const fullPath = join(dir, entry.name);\n const relativePath = relative(baseDir, fullPath);\n \n // Skip hidden files unless explicitly included\n if (!options.includeHidden && entry.name.startsWith('.')) {\n continue;\n }\n \n // Check exclusion patterns\n if (shouldExclude(relativePath, options.excludePatterns)) {\n continue;\n }\n \n if (entry.isDirectory()) {\n files.push(...collectFiles(fullPath, options, baseDir));\n } else if (entry.isFile()) {\n // Check extension\n if (!hasValidExtension(entry.name, options.extensions)) {\n continue;\n }\n \n // Check file size\n try {\n const stats = statSync(fullPath);\n if (stats.size > options.maxFileSize) {\n continue;\n }\n } catch {\n continue;\n }\n \n files.push(fullPath);\n }\n }\n } catch (error) {\n // Directory not readable, skip\n }\n \n return files.sort();\n}\n\nexport function createSnapshot(\n projectPath: string,\n outputPath: string,\n options: SnapshotOptions = {}\n): SnapshotResult {\n const mergedOptions: Required<SnapshotOptions> = {\n ...DEFAULT_OPTIONS,\n ...options,\n };\n \n if (!existsSync(projectPath)) {\n throw new Error(`Project path does not exist: ${projectPath}`);\n }\n \n const stats = statSync(projectPath);\n if (!stats.isDirectory()) {\n throw new Error(`Project path is not a directory: ${projectPath}`);\n }\n \n // Collect all files\n const files = collectFiles(projectPath, mergedOptions);\n \n // Build snapshot content\n const lines: string[] = [];\n \n // Header\n lines.push('================================================================================');\n lines.push('CODEBASE SNAPSHOT');\n lines.push(`Project: ${projectPath}`);\n lines.push(`Generated: ${new Date().toISOString()}`);\n lines.push(`Extensions: ${mergedOptions.extensions.join(', ')}`);\n lines.push(`Files: ${files.length}`);\n lines.push('================================================================================');\n lines.push('');\n \n // Process each file\n for (const filePath of files) {\n const relativePath = relative(projectPath, filePath);\n \n lines.push('');\n lines.push('================================================================================');\n lines.push(`FILE: ./${relativePath}`);\n lines.push('================================================================================');\n \n try {\n const content = readFileSync(filePath, 'utf-8');\n lines.push(content);\n } catch (error) {\n lines.push('[Unable to read file]');\n }\n }\n \n // Write snapshot\n const content = lines.join('\\n');\n writeFileSync(outputPath, content);\n \n const totalLines = content.split('\\n').length;\n const totalSize = Buffer.byteLength(content, 'utf-8');\n \n return {\n outputPath,\n fileCount: files.length,\n totalLines,\n totalSize,\n files: files.map(f => relative(projectPath, f)),\n };\n}\n\nexport function getSnapshotStats(snapshotPath: string): {\n fileCount: number;\n totalLines: number;\n totalSize: number;\n} {\n if (!existsSync(snapshotPath)) {\n throw new Error(`Snapshot file does not exist: ${snapshotPath}`);\n }\n \n const content = readFileSync(snapshotPath, 'utf-8');\n const totalLines = content.split('\\n').length;\n const totalSize = Buffer.byteLength(content, 'utf-8');\n \n // Count FILE: markers\n const fileMatches = content.match(/^FILE: /gm);\n const fileCount = fileMatches ? fileMatches.length : 0;\n \n return { fileCount, totalLines, totalSize };\n}\n","/**\n * Argus RLM Engine\n * \n * Recursive Language Model engine for document analysis.\n * Based on the Matryoshka RLM approach by Dmitri Sotnikov.\n * \n * The engine uses an LLM to generate Nucleus DSL commands that are\n * executed against documents, enabling analysis of content far\n * exceeding typical context limits.\n */\n\nimport { readFileSync } from 'fs';\nimport { AIProvider, Message } from '../providers/types.js';\nimport { buildSystemPrompt, getTurnLimit } from './prompts.js';\n\nexport interface AnalysisOptions {\n maxTurns?: number;\n turnTimeoutMs?: number;\n verbose?: boolean;\n onProgress?: (turn: number, command: string, result: unknown) => void;\n}\n\nexport interface AnalysisResult {\n answer: string;\n turns: number;\n commands: string[];\n success: boolean;\n error?: string;\n}\n\ninterface GrepMatch {\n match: string;\n line: string;\n lineNum: number;\n index: number;\n groups: string[];\n}\n\nconst NUCLEUS_REFERENCE = `\nYou are analyzing a document using the Nucleus DSL. Generate S-expression commands to explore the document.\n\nAVAILABLE COMMANDS:\n- (grep \"pattern\") - Search for regex pattern, returns matches with line numbers\n- (grep \"pattern\" \"flags\") - With flags like \"i\" for case-insensitive\n- (count RESULTS) - Count number of items in RESULTS\n- (map RESULTS (lambda (x) expr)) - Transform each item\n- (filter RESULTS (lambda (x) expr)) - Keep items where expr is true\n- (sort RESULTS key) - Sort by key\n- (first RESULTS) - Get first item\n- (last RESULTS) - Get last item \n- (take RESULTS n) - Get first n items\n- (match str \"pattern\" group) - Extract regex group from string\n\nVARIABLES:\n- RESULTS always contains the result of the last command\n- _1, _2, etc. contain results from turn 1, 2, etc.\n\nFINAL ANSWER:\nWhen you have enough information, output: <<<FINAL>>>your answer here<<<END>>>\n\nRULES:\n1. Output ONLY a single Nucleus command OR a final answer, nothing else\n2. Use grep to search the document\n3. Use map/filter to process results\n4. Build understanding iteratively\n5. When ready, provide the final answer\n\nExample session:\nTurn 1: (grep \"function.*export\")\nTurn 2: (count RESULTS)\nTurn 3: <<<FINAL>>>There are 15 exported functions<<<END>>>\n`;\n\n/**\n * Execute a Nucleus command against document content\n */\nfunction executeNucleus(command: string, content: string, bindings: Map<string, unknown>): unknown {\n // Parse the S-expression\n const parsed = parseSExpression(command);\n if (!parsed) {\n throw new Error(`Failed to parse command: ${command}`);\n }\n \n return evaluateExpr(parsed, content, bindings);\n}\n\ntype SExpr = string | SExpr[];\n\nfunction parseSExpression(input: string): SExpr | null {\n const tokens = tokenize(input.trim());\n if (tokens.length === 0) return null;\n \n let pos = 0;\n \n function parse(): SExpr {\n const token = tokens[pos++];\n \n if (token === '(') {\n const list: SExpr[] = [];\n while (tokens[pos] !== ')' && pos < tokens.length) {\n list.push(parse());\n }\n pos++; // consume ')'\n return list;\n } else if (token.startsWith('\"')) {\n // String literal\n return token.slice(1, -1).replace(/\\\\\"/g, '\"');\n } else if (/^-?\\d+(\\.\\d+)?$/.test(token)) {\n return token; // Keep as string, convert when needed\n } else {\n return token; // Symbol\n }\n }\n \n return parse();\n}\n\nfunction tokenize(input: string): string[] {\n const tokens: string[] = [];\n let i = 0;\n \n while (i < input.length) {\n const char = input[i];\n \n if (/\\s/.test(char)) {\n i++;\n continue;\n }\n \n if (char === '(' || char === ')') {\n tokens.push(char);\n i++;\n continue;\n }\n \n if (char === '\"') {\n let str = '\"';\n i++;\n while (i < input.length && input[i] !== '\"') {\n if (input[i] === '\\\\' && i + 1 < input.length) {\n str += input[i] + input[i + 1];\n i += 2;\n } else {\n str += input[i];\n i++;\n }\n }\n str += '\"';\n i++;\n tokens.push(str);\n continue;\n }\n \n // Symbol or number\n let sym = '';\n while (i < input.length && !/[\\s()]/.test(input[i])) {\n sym += input[i];\n i++;\n }\n tokens.push(sym);\n }\n \n return tokens;\n}\n\nfunction evaluateExpr(expr: SExpr, content: string, bindings: Map<string, unknown>): unknown {\n if (typeof expr === 'string') {\n // Variable lookup\n if (bindings.has(expr)) {\n return bindings.get(expr);\n }\n // Number\n if (/^-?\\d+(\\.\\d+)?$/.test(expr)) {\n return parseFloat(expr);\n }\n return expr;\n }\n \n if (!Array.isArray(expr) || expr.length === 0) {\n return expr;\n }\n \n const [op, ...args] = expr;\n \n switch (op) {\n case 'grep': {\n const pattern = evaluateExpr(args[0], content, bindings) as string;\n const flags = args[1] ? evaluateExpr(args[1], content, bindings) as string : '';\n const regex = new RegExp(pattern, flags + 'g');\n // Cache lines array to avoid re-splitting on every grep (major memory optimization)\n let lines = bindings.get('__cached_lines__') as string[] | undefined;\n if (!lines) {\n lines = content.split('\\n');\n bindings.set('__cached_lines__', lines);\n }\n const matches: GrepMatch[] = [];\n const MAX_MATCHES = 1000; // Prevent memory explosion\n\n let charIndex = 0;\n for (let lineNum = 0; lineNum < lines.length; lineNum++) {\n const line = lines[lineNum];\n let match;\n const lineRegex = new RegExp(pattern, flags + 'g');\n while ((match = lineRegex.exec(line)) !== null) {\n matches.push({\n match: match[0],\n line: line,\n lineNum: lineNum + 1,\n index: charIndex + match.index,\n groups: match.slice(1),\n });\n if (matches.length >= MAX_MATCHES) {\n return matches;\n }\n }\n charIndex += line.length + 1;\n }\n\n return matches;\n }\n \n case 'count': {\n const arr = evaluateExpr(args[0], content, bindings);\n if (Array.isArray(arr)) return arr.length;\n return 0;\n }\n \n case 'map': {\n const arr = evaluateExpr(args[0], content, bindings) as unknown[];\n const lambdaExpr = args[1] as SExpr[];\n \n if (!Array.isArray(lambdaExpr) || lambdaExpr[0] !== 'lambda') {\n throw new Error('map requires a lambda expression');\n }\n \n const params = lambdaExpr[1] as SExpr[];\n const body = lambdaExpr[2];\n const paramName = Array.isArray(params) ? params[0] as string : params as string;\n \n return arr.map(item => {\n const localBindings = new Map(bindings);\n localBindings.set(paramName, item);\n return evaluateExpr(body, content, localBindings);\n });\n }\n \n case 'filter': {\n const arr = evaluateExpr(args[0], content, bindings) as unknown[];\n const lambdaExpr = args[1] as SExpr[];\n \n if (!Array.isArray(lambdaExpr) || lambdaExpr[0] !== 'lambda') {\n throw new Error('filter requires a lambda expression');\n }\n \n const params = lambdaExpr[1] as SExpr[];\n const body = lambdaExpr[2];\n const paramName = Array.isArray(params) ? params[0] as string : params as string;\n \n return arr.filter(item => {\n const localBindings = new Map(bindings);\n localBindings.set(paramName, item);\n return evaluateExpr(body, content, localBindings);\n });\n }\n \n case 'first': {\n const arr = evaluateExpr(args[0], content, bindings) as unknown[];\n return arr[0];\n }\n \n case 'last': {\n const arr = evaluateExpr(args[0], content, bindings) as unknown[];\n return arr[arr.length - 1];\n }\n \n case 'take': {\n const arr = evaluateExpr(args[0], content, bindings) as unknown[];\n const n = evaluateExpr(args[1], content, bindings) as number;\n return arr.slice(0, n);\n }\n \n case 'sort': {\n const arr = evaluateExpr(args[0], content, bindings) as Record<string, unknown>[];\n const key = evaluateExpr(args[1], content, bindings) as string;\n return [...arr].sort((a, b) => {\n const aVal = a[key];\n const bVal = b[key];\n if (typeof aVal === 'number' && typeof bVal === 'number') {\n return aVal - bVal;\n }\n return String(aVal).localeCompare(String(bVal));\n });\n }\n \n case 'match': {\n const str = evaluateExpr(args[0], content, bindings);\n const strValue = typeof str === 'object' && str !== null && 'line' in str \n ? (str as GrepMatch).line \n : String(str);\n const pattern = evaluateExpr(args[1], content, bindings) as string;\n const group = args[2] ? evaluateExpr(args[2], content, bindings) as number : 0;\n \n const regex = new RegExp(pattern);\n const match = strValue.match(regex);\n if (match) {\n return match[group] || null;\n }\n return null;\n }\n \n default:\n throw new Error(`Unknown command: ${op}`);\n }\n}\n\n/**\n * Extract Nucleus command from LLM response\n */\nfunction extractCommand(response: string): { command?: string; finalAnswer?: string } {\n // Check for final answer\n const finalMatch = response.match(/<<<FINAL>>>([\\s\\S]*?)<<<END>>>/);\n if (finalMatch) {\n return { finalAnswer: finalMatch[1].trim() };\n }\n \n // Look for S-expression\n const sexpMatch = response.match(/\\([^)]*(?:\\([^)]*\\)[^)]*)*\\)/);\n if (sexpMatch) {\n return { command: sexpMatch[0] };\n }\n \n return {};\n}\n\n/**\n * Run RLM analysis on a document\n */\nexport async function analyze(\n provider: AIProvider,\n documentPath: string,\n query: string,\n options: AnalysisOptions = {}\n): Promise<AnalysisResult> {\n const {\n maxTurns = 15,\n verbose = false,\n onProgress,\n } = options;\n \n // Use dynamic turn limit based on query type, but cap at maxTurns\n const dynamicLimit = Math.min(getTurnLimit(query), maxTurns);\n \n // Load document\n const content = readFileSync(documentPath, 'utf-8');\n\n // Get document stats for context (count newlines without splitting)\n const fileCount = (content.match(/^FILE:/gm) || []).length;\n const lineCount = (content.match(/\\n/g) || []).length + 1;\n\n const bindings = new Map<string, unknown>();\n const commands: string[] = [];\n const messages: Message[] = [\n {\n role: 'system',\n content: buildSystemPrompt(query),\n },\n {\n role: 'user',\n content: `CODEBASE SNAPSHOT:\n- Total size: ${content.length.toLocaleString()} characters\n- Files: ${fileCount}\n- Lines: ${lineCount.toLocaleString()}\n\nFiles are marked with \"FILE: ./path/to/file\" headers.\n\nQUERY: ${query}\n\nBegin analysis. You have ${dynamicLimit} turns maximum - provide final answer before then.`,\n },\n ];\n \n for (let turn = 1; turn <= dynamicLimit; turn++) {\n // Force final answer on last turn\n const isLastTurn = turn === dynamicLimit;\n const isNearEnd = turn >= dynamicLimit - 2;\n \n if (verbose) {\n console.log(`\\n[Turn ${turn}/${dynamicLimit}] Querying LLM...`);\n }\n \n // Get LLM response\n const result = await provider.complete(messages);\n const response = result.content;\n \n if (verbose) {\n console.log(`[Turn ${turn}] Response: ${response.slice(0, 200)}...`);\n }\n \n // Extract command or final answer\n const extracted = extractCommand(response);\n \n if (extracted.finalAnswer) {\n return {\n answer: extracted.finalAnswer,\n turns: turn,\n commands,\n success: true,\n };\n }\n \n if (!extracted.command) {\n // No command found, add to messages and continue\n messages.push({ role: 'assistant', content: response });\n messages.push({ role: 'user', content: 'Please provide a Nucleus command or final answer.' });\n continue;\n }\n \n const command = extracted.command;\n commands.push(command);\n \n if (verbose) {\n console.log(`[Turn ${turn}] Command: ${command}`);\n }\n \n // Execute command\n try {\n const cmdResult = executeNucleus(command, content, bindings);\n \n // Store result in bindings\n bindings.set('RESULTS', cmdResult);\n bindings.set(`_${turn}`, cmdResult);\n \n const resultStr = JSON.stringify(cmdResult, null, 2);\n const truncatedResult = resultStr.length > 2000 \n ? resultStr.slice(0, 2000) + '...[truncated]' \n : resultStr;\n \n if (verbose) {\n console.log(`[Turn ${turn}] Result: ${truncatedResult.slice(0, 500)}...`);\n }\n \n onProgress?.(turn, command, cmdResult);\n \n // Add to conversation with nudge if near end\n messages.push({ role: 'assistant', content: command });\n \n let userMessage = `Result:\\n${truncatedResult}`;\n if (isNearEnd && !isLastTurn) {\n userMessage += `\\n\\n⚠️ ${dynamicLimit - turn} turns remaining. Start forming your final answer.`;\n }\n messages.push({ role: 'user', content: userMessage });\n \n // FORCE final answer on last turn - make one more LLM call\n if (isLastTurn) {\n messages.push({ \n role: 'user', \n content: 'STOP SEARCHING. Based on everything you found, provide your final answer NOW using <<<FINAL>>>your answer<<<END>>>' \n });\n \n const finalResult = await provider.complete(messages);\n const finalExtracted = extractCommand(finalResult.content);\n \n if (finalExtracted.finalAnswer) {\n return {\n answer: finalExtracted.finalAnswer,\n turns: turn,\n commands,\n success: true,\n };\n }\n \n // Even if not properly formatted, return whatever we got\n return {\n answer: finalResult.content,\n turns: turn,\n commands,\n success: true,\n };\n }\n \n } catch (error) {\n const errMsg = error instanceof Error ? error.message : String(error);\n \n if (verbose) {\n console.log(`[Turn ${turn}] Error: ${errMsg}`);\n }\n \n messages.push({ role: 'assistant', content: command });\n messages.push({ role: 'user', content: `Error executing command: ${errMsg}` });\n }\n }\n \n return {\n answer: 'Maximum turns reached without final answer',\n turns: dynamicLimit,\n commands,\n success: false,\n error: 'Max turns reached',\n };\n}\n\n/**\n * Fast grep search without AI\n */\nexport function searchDocument(\n documentPath: string,\n pattern: string,\n options: { caseInsensitive?: boolean; maxResults?: number } = {}\n): GrepMatch[] {\n const content = readFileSync(documentPath, 'utf-8');\n const flags = options.caseInsensitive ? 'gi' : 'g';\n const regex = new RegExp(pattern, flags);\n const lines = content.split('\\n');\n const matches: GrepMatch[] = [];\n \n let charIndex = 0;\n for (let lineNum = 0; lineNum < lines.length; lineNum++) {\n const line = lines[lineNum];\n let match;\n const lineRegex = new RegExp(pattern, flags);\n while ((match = lineRegex.exec(line)) !== null) {\n matches.push({\n match: match[0],\n line: line,\n lineNum: lineNum + 1,\n index: charIndex + match.index,\n groups: match.slice(1),\n });\n \n if (options.maxResults && matches.length >= options.maxResults) {\n return matches;\n }\n }\n charIndex += line.length + 1;\n }\n \n return matches;\n}\n","/**\n * Argus RLM Prompts\n * \n * Optimized prompts for codebase understanding that persists across Claude Code sessions.\n */\n\nexport const NUCLEUS_COMMANDS = `\nCOMMANDS (output ONE per turn):\n(grep \"pattern\") - Find lines matching regex\n(grep \"pattern\" \"i\") - Case-insensitive search \n(count RESULTS) - Count matches\n(take RESULTS n) - First n results\n(filter RESULTS (lambda (x) (match x.line \"pattern\" 0))) - Filter results\n(map RESULTS (lambda (x) x.line)) - Extract just the lines\n\nVARIABLES: RESULTS = last result, _1 _2 _3 = results from turn 1,2,3\n\nTO ANSWER: <<<FINAL>>>your answer<<<END>>>\n`;\n\n// Main system prompt for codebase analysis\nexport const CODEBASE_ANALYSIS_PROMPT = `You are analyzing a SOFTWARE CODEBASE snapshot to help a developer understand it.\n\nThe snapshot contains source files concatenated with \"FILE: ./path/to/file\" markers.\n\n${NUCLEUS_COMMANDS}\n\n## STRATEGY FOR CODEBASE SNAPSHOTS\n\n**To find modules/directories:**\n(grep \"FILE:.*src/[^/]+/\") - top-level source dirs\n(grep \"FILE:.*mod\\\\.rs\") - Rust modules \n(grep \"FILE:.*index\\\\.(ts|js)\") - JS/TS modules\n\n**To find implementations:**\n(grep \"fn function_name\") - Rust functions\n(grep \"function|const.*=>\") - JS functions\n(grep \"class ClassName\") - Classes\n(grep \"struct |type |interface\") - Type definitions\n\n**To understand structure:**\n(grep \"FILE:\") - List all files\n(grep \"use |import |require\") - Find dependencies\n(grep \"pub |export\") - Public APIs\n\n## RULES\n1. Output ONLY a Nucleus command OR a final answer\n2. NO explanations, NO markdown formatting in commands\n3. MUST provide final answer by turn 8\n4. If turn 6+, start summarizing what you found\n\n## EXAMPLE SESSION\nTurn 1: (grep \"FILE:.*src/[^/]+/mod\\\\.rs\")\nTurn 2: (take RESULTS 15)\nTurn 3: <<<FINAL>>>The codebase has these main modules:\n- src/auth/ - Authentication handling\n- src/api/ - API endpoints\n- src/db/ - Database layer\n...<<<END>>>\n`;\n\n// Specialized prompt for architecture questions\nexport const ARCHITECTURE_PROMPT = `You are generating an ARCHITECTURE SUMMARY of a codebase.\n\n${NUCLEUS_COMMANDS}\n\n## YOUR TASK\nCreate a summary suitable for CLAUDE.md that helps Claude Code understand this project after context compaction.\n\n## SEARCH STRATEGY (do these in order)\n1. (grep \"FILE:.*mod\\\\.rs|FILE:.*index\\\\.(ts|js)\") - Find module entry points\n2. (take RESULTS 20) - Limit results\n3. Based on file paths, provide your summary\n\n## OUTPUT FORMAT\nYour final answer should be structured like:\n\n## Modules\n- **module_name/** - Brief description based on files found\n\n## Key Patterns \n- Pattern observations from the code\n\n## Important Files\n- List key files and their apparent purpose\n\nPROVIDE FINAL ANSWER BY TURN 6.\n`;\n\n// Prompt for finding specific implementations\nexport const IMPLEMENTATION_PROMPT = `You are finding HOW something works in a codebase.\n\n${NUCLEUS_COMMANDS}\n\n## STRATEGY\n1. (grep \"FILE:.*keyword\") - Find files related to the concept\n2. (grep \"keyword\") - Find all mentions\n3. (take RESULTS 30) - Limit if too many results\n4. Look for function definitions, structs, classes\n5. PROVIDE FINAL ANSWER based on file paths and code patterns found\n\n## IMPORTANT\n- You have 12 turns maximum\n- By turn 8, START WRITING YOUR FINAL ANSWER\n- Use what you've found - don't keep searching indefinitely\n- It's better to give a partial answer than no answer\n\n## OUTPUT FORMAT\nYour final answer should explain:\n- Which files contain the implementation\n- Key functions/structs/classes involved \n- Basic flow of how it works (based on what you found)\n`;\n\n// Prompt for counting/quantifying\nexport const COUNT_PROMPT = `You are counting items in a codebase.\n\n${NUCLEUS_COMMANDS}\n\n## STRATEGY \n1. (grep \"pattern\")\n2. (count RESULTS)\n3. <<<FINAL>>>There are N items matching the pattern.<<<END>>>\n\nTHIS SHOULD TAKE 2-3 TURNS MAXIMUM.\n`;\n\n// Prompt for quick searches\nexport const SEARCH_PROMPT = `You are searching for specific code.\n\n${NUCLEUS_COMMANDS}\n\n## STRATEGY\n1. (grep \"pattern\")\n2. (take RESULTS 20) if too many\n3. Report what you found with file paths\n\nPROVIDE FINAL ANSWER BY TURN 4.\n`;\n\n/**\n * Detect query type and select best prompt\n */\nexport function selectPrompt(query: string): string {\n const q = query.toLowerCase();\n \n // Count queries - fastest\n if (/how many|count|number of|total|how much/.test(q)) {\n return COUNT_PROMPT;\n }\n \n // Simple search queries\n if (/^(find|search|show|list|where is|locate)\\b/.test(q) && q.length < 50) {\n return SEARCH_PROMPT;\n }\n \n // Architecture/overview queries \n if (/architect|structure|overview|module|organization|main.*component|summar|layout/.test(q)) {\n return ARCHITECTURE_PROMPT;\n }\n \n // Implementation queries\n if (/how does|how is|implement|work|handle|process|flow/.test(q)) {\n return IMPLEMENTATION_PROMPT;\n }\n \n // Default\n return CODEBASE_ANALYSIS_PROMPT;\n}\n\n/**\n * Build system prompt with query-specific guidance\n */\nexport function buildSystemPrompt(query: string): string {\n return selectPrompt(query);\n}\n\n/**\n * Get the turn limit based on query type\n */\nexport function getTurnLimit(query: string): number {\n const q = query.toLowerCase();\n \n if (/how many|count/.test(q)) return 5;\n if (/^(find|search|show|list)\\b/.test(q) && q.length < 50) return 6;\n if (/architect|overview|structure|module/.test(q)) return 12;\n if (/how does|how is|implement|work/.test(q)) return 12; // Implementation needs more\n \n return 12; // Default\n}\n","/**\n * Argus AI Providers\n * \n * Factory for creating AI providers based on configuration.\n */\n\nimport { ArgusConfig, ProviderType, ProviderConfig } from '../core/config.js';\nimport { AIProvider } from './types.js';\nimport { createZAIProvider, createOpenAIProvider, createDeepSeekProvider } from './openai-compatible.js';\nimport { createOllamaProvider } from './ollama.js';\nimport { createAnthropicProvider } from './anthropic.js';\n\nexport type { AIProvider, Message, CompletionOptions, CompletionResult, ProviderConfig } from './types.js';\nexport { createZAIProvider, createOpenAIProvider, createDeepSeekProvider } from './openai-compatible.js';\nexport { createOllamaProvider, OllamaProvider } from './ollama.js';\nexport { createAnthropicProvider } from './anthropic.js';\n\n/**\n * Create an AI provider from Argus configuration\n */\nexport function createProvider(config: ArgusConfig): AIProvider {\n const providerType = config.provider;\n const providerConfig = config.providers[providerType];\n \n if (!providerConfig) {\n throw new Error(`No configuration found for provider: ${providerType}`);\n }\n \n return createProviderByType(providerType, providerConfig);\n}\n\n/**\n * Create an AI provider by type and config\n */\nexport function createProviderByType(type: ProviderType, config: ProviderConfig): AIProvider {\n switch (type) {\n case 'zai':\n return createZAIProvider(config);\n case 'openai':\n return createOpenAIProvider(config);\n case 'deepseek':\n return createDeepSeekProvider(config);\n case 'ollama':\n return createOllamaProvider(config);\n case 'anthropic':\n return createAnthropicProvider(config);\n default:\n throw new Error(`Unknown provider type: ${type}`);\n }\n}\n\n/**\n * Get a human-readable name for a provider\n */\nexport function getProviderDisplayName(type: ProviderType): string {\n switch (type) {\n case 'zai':\n return 'ZAI (GLM)';\n case 'openai':\n return 'OpenAI';\n case 'deepseek':\n return 'DeepSeek';\n case 'ollama':\n return 'Ollama (Local)';\n case 'anthropic':\n return 'Anthropic (Claude)';\n default:\n return type;\n }\n}\n\n/**\n * List all available provider types\n */\nexport function listProviderTypes(): ProviderType[] {\n return ['zai', 'anthropic', 'openai', 'deepseek', 'ollama'];\n}\n","/**\n * OpenAI-Compatible Provider\n * \n * Works with OpenAI, ZAI (GLM), DeepSeek, and any OpenAI-compatible API.\n */\n\nimport { AIProvider, Message, CompletionOptions, CompletionResult, ProviderConfig } from './types.js';\n\nexport class OpenAICompatibleProvider implements AIProvider {\n name: string;\n private config: ProviderConfig;\n \n constructor(name: string, config: ProviderConfig) {\n this.name = name;\n this.config = config;\n \n if (!config.apiKey) {\n throw new Error(`API key is required for ${name} provider`);\n }\n \n if (!config.baseUrl) {\n throw new Error(`Base URL is required for ${name} provider`);\n }\n }\n \n async complete(messages: Message[], options?: CompletionOptions): Promise<CompletionResult> {\n const endpoint = `${this.config.baseUrl}/chat/completions`;\n \n const body = {\n model: this.config.model,\n messages: messages.map(m => ({\n role: m.role,\n content: m.content,\n })),\n temperature: options?.temperature ?? this.config.options?.temperature ?? 0.2,\n max_tokens: options?.maxTokens ?? this.config.options?.max_tokens ?? 4096,\n ...(options?.stopSequences && { stop: options.stopSequences }),\n };\n \n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'Authorization': `Bearer ${this.config.apiKey}`,\n },\n body: JSON.stringify(body),\n });\n \n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`${this.name} API error (${response.status}): ${errorText}`);\n }\n \n const data = await response.json() as {\n choices: Array<{\n message: { content: string };\n finish_reason: string;\n }>;\n usage?: {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n };\n };\n \n const choice = data.choices[0];\n \n return {\n content: choice.message.content || '',\n finishReason: choice.finish_reason === 'stop' ? 'stop' : \n choice.finish_reason === 'length' ? 'length' : 'error',\n usage: data.usage ? {\n promptTokens: data.usage.prompt_tokens,\n completionTokens: data.usage.completion_tokens,\n totalTokens: data.usage.total_tokens,\n } : undefined,\n };\n }\n \n async healthCheck(): Promise<boolean> {\n try {\n const result = await this.complete([\n { role: 'user', content: 'Say \"ok\"' }\n ], { maxTokens: 10 });\n return result.content.length > 0;\n } catch {\n return false;\n }\n }\n}\n\n/**\n * Create a provider for ZAI GLM models\n */\nexport function createZAIProvider(config: ProviderConfig): AIProvider {\n return new OpenAICompatibleProvider('ZAI', {\n ...config,\n baseUrl: config.baseUrl || 'https://api.z.ai/api/coding/paas/v4',\n model: config.model || 'glm-4.7',\n });\n}\n\n/**\n * Create a provider for OpenAI models\n */\nexport function createOpenAIProvider(config: ProviderConfig): AIProvider {\n return new OpenAICompatibleProvider('OpenAI', {\n ...config,\n baseUrl: config.baseUrl || 'https://api.openai.com/v1',\n model: config.model || 'gpt-4o',\n });\n}\n\n/**\n * Create a provider for DeepSeek models\n */\nexport function createDeepSeekProvider(config: ProviderConfig): AIProvider {\n return new OpenAICompatibleProvider('DeepSeek', {\n ...config,\n baseUrl: config.baseUrl || 'https://api.deepseek.com',\n model: config.model || 'deepseek-chat',\n });\n}\n","/**\n * Ollama Provider\n * \n * Provider for local Ollama models.\n */\n\nimport { AIProvider, Message, CompletionOptions, CompletionResult, ProviderConfig } from './types.js';\n\nexport class OllamaProvider implements AIProvider {\n name = 'Ollama';\n private config: ProviderConfig;\n \n constructor(config: ProviderConfig) {\n this.config = {\n ...config,\n baseUrl: config.baseUrl || 'http://localhost:11434',\n model: config.model || 'qwen2.5-coder:7b',\n };\n }\n \n async complete(messages: Message[], options?: CompletionOptions): Promise<CompletionResult> {\n const endpoint = `${this.config.baseUrl}/api/chat`;\n \n const body = {\n model: this.config.model,\n messages: messages.map(m => ({\n role: m.role,\n content: m.content,\n })),\n stream: false,\n options: {\n temperature: options?.temperature ?? this.config.options?.temperature ?? 0.2,\n num_ctx: this.config.options?.num_ctx ?? 8192,\n },\n };\n \n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(body),\n });\n \n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Ollama API error (${response.status}): ${errorText}`);\n }\n \n const data = await response.json() as {\n message: { content: string };\n done: boolean;\n eval_count?: number;\n prompt_eval_count?: number;\n };\n \n return {\n content: data.message.content || '',\n finishReason: data.done ? 'stop' : 'error',\n usage: data.eval_count ? {\n promptTokens: data.prompt_eval_count || 0,\n completionTokens: data.eval_count,\n totalTokens: (data.prompt_eval_count || 0) + data.eval_count,\n } : undefined,\n };\n }\n \n async healthCheck(): Promise<boolean> {\n try {\n const response = await fetch(`${this.config.baseUrl}/api/tags`);\n if (!response.ok) return false;\n \n const data = await response.json() as { models: Array<{ name: string }> };\n const hasModel = data.models.some(m => \n m.name === this.config.model || m.name.startsWith(this.config.model + ':')\n );\n \n return hasModel;\n } catch {\n return false;\n }\n }\n \n /**\n * List available models\n */\n async listModels(): Promise<string[]> {\n try {\n const response = await fetch(`${this.config.baseUrl}/api/tags`);\n if (!response.ok) return [];\n \n const data = await response.json() as { models: Array<{ name: string }> };\n return data.models.map(m => m.name);\n } catch {\n return [];\n }\n }\n}\n\nexport function createOllamaProvider(config: ProviderConfig): OllamaProvider {\n return new OllamaProvider(config);\n}\n","/**\n * Anthropic Provider\n * \n * Provider for Claude models via the Anthropic API.\n */\n\nimport { AIProvider, Message, CompletionOptions, CompletionResult, ProviderConfig } from './types.js';\n\nexport class AnthropicProvider implements AIProvider {\n name = 'Anthropic';\n private config: ProviderConfig;\n \n constructor(config: ProviderConfig) {\n if (!config.apiKey) {\n throw new Error('API key is required for Anthropic provider');\n }\n \n this.config = {\n ...config,\n baseUrl: config.baseUrl || 'https://api.anthropic.com',\n model: config.model || 'claude-sonnet-4-20250514',\n };\n }\n \n async complete(messages: Message[], options?: CompletionOptions): Promise<CompletionResult> {\n const endpoint = `${this.config.baseUrl}/v1/messages`;\n \n // Extract system message if present\n const systemMessage = messages.find(m => m.role === 'system');\n const nonSystemMessages = messages.filter(m => m.role !== 'system');\n \n const body = {\n model: this.config.model,\n max_tokens: options?.maxTokens ?? this.config.options?.max_tokens ?? 4096,\n ...(systemMessage && { system: systemMessage.content }),\n messages: nonSystemMessages.map(m => ({\n role: m.role,\n content: m.content,\n })),\n ...(options?.temperature !== undefined && { temperature: options.temperature }),\n ...(options?.stopSequences && { stop_sequences: options.stopSequences }),\n };\n \n const response = await fetch(endpoint, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-api-key': this.config.apiKey!,\n 'anthropic-version': '2023-06-01',\n },\n body: JSON.stringify(body),\n });\n \n if (!response.ok) {\n const errorText = await response.text();\n throw new Error(`Anthropic API error (${response.status}): ${errorText}`);\n }\n \n const data = await response.json() as {\n content: Array<{ type: string; text: string }>;\n stop_reason: string;\n usage: {\n input_tokens: number;\n output_tokens: number;\n };\n };\n \n const textContent = data.content\n .filter(c => c.type === 'text')\n .map(c => c.text)\n .join('');\n \n return {\n content: textContent,\n finishReason: data.stop_reason === 'end_turn' ? 'stop' : \n data.stop_reason === 'max_tokens' ? 'length' : 'error',\n usage: {\n promptTokens: data.usage.input_tokens,\n completionTokens: data.usage.output_tokens,\n totalTokens: data.usage.input_tokens + data.usage.output_tokens,\n },\n };\n }\n \n async healthCheck(): Promise<boolean> {\n try {\n const result = await this.complete([\n { role: 'user', content: 'Say \"ok\"' }\n ], { maxTokens: 10 });\n return result.content.length > 0;\n } catch {\n return false;\n }\n }\n}\n\nexport function createAnthropicProvider(config: ProviderConfig): AIProvider {\n return new AnthropicProvider(config);\n}\n"],"mappings":";;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAOA,OAAO,cAAc;AACrB,SAAS,cAAAA,aAAY,aAAAC,YAAW,gBAAAC,qBAAoB;AACpD,SAAS,WAAAC,gBAAe;AATxB,IAmBa;AAnBb;AAAA;AAAA;AAAA;AAmBO,IAAM,gBAAN,MAAoB;AAAA,MACjB;AAAA,MACA,cAAc;AAAA,MAEtB,YAAY,QAAgB;AAE1B,cAAM,MAAMA,SAAQ,MAAM;AAC1B,YAAI,CAACH,YAAW,GAAG,GAAG;AACpB,UAAAC,WAAU,KAAK,EAAE,WAAW,KAAK,CAAC;AAAA,QACpC;AAEA,aAAK,KAAK,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Aa,QAAQ,SAAS,OAAO,UAAa,SAAS,OAAO,MAAM;AAC1E,cAAQ,IAAI,KAAK,UAAU,QAAQ,CAAC;AAAA,IACtC;AAAA,EACF,SAAS,OAAO;AAGd,UAAM,gBAAgB;AAAA,MACpB,SAAS;AAAA,MACT,IAAI;AAAA;AAAA,MACJ,OAAO;AAAA,QACL,MAAM;AAAA,QACN,SAAS;AAAA,MACX;AAAA,IACF;AACA,YAAQ,IAAI,KAAK,UAAU,aAAa,CAAC;AAAA,EAC3C;AACF,CAAC;","names":["existsSync","mkdirSync","readFileSync","dirname","config","readFileSync","writeFileSync","join","extname","existsSync","readFileSync","writeFileSync","join","content","join","extname","readFileSync","writeFileSync","readFileSync","provider","readFileSync","config","config","config","config","existsSync","statSync","readFileSync","join","hasMore","pageMatches","formattedMatches","response","SemanticIndex"]}
|