@sashabogi/argus-mcp 1.2.2 → 1.2.3

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/mcp.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/mcp.ts","../src/core/config.ts","../src/core/snapshot.ts","../src/core/engine.ts","../src/core/prompts.ts","../src/providers/openai-compatible.ts","../src/providers/ollama.ts","../src/providers/anthropic.ts","../src/providers/index.ts"],"sourcesContent":["/**\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 { 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// 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: '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\nRequires an enhanced snapshot with metadata (created with --enhanced flag).`,\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\nRequires an enhanced snapshot with metadata (created with --enhanced flag).`,\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\nRequires an enhanced snapshot with metadata (created with --enhanced flag).`,\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: false)',\n },\n maxResults: {\n type: 'number',\n description: 'Maximum results to return (default: 50)',\n },\n },\n required: ['path', 'pattern'],\n },\n },\n {\n name: 'create_snapshot',\n description: `Create a 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.\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\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// Handle tool calls\nasync function handleToolCall(name: string, args: Record<string, unknown>): Promise<unknown> {\n switch (name) {\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 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 const result = createSnapshot(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 as boolean || false;\n const maxResults = (args.maxResults as number) || 50;\n \n if (!existsSync(path)) {\n throw new Error(`File not found: ${path}`);\n }\n \n const matches = searchDocument(path, pattern, { caseInsensitive, maxResults });\n \n return {\n count: matches.length,\n matches: matches.map(m => ({\n lineNum: m.lineNum,\n line: m.line.trim(),\n match: m.match,\n })),\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 const result = createSnapshot(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 };\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 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 * 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","/**\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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AAA,MACL,KAAK;AAEH,eAAO;AAAA,MACT;AAEE,YAAI,QAAQ,OAAO,UAAa,QAAQ,OAAO,MAAM;AACnD,iBAAO;AAAA,QACT;AACA,eAAO;AAAA,UACL,SAAS;AAAA,UACT,IAAI,QAAQ;AAAA,UACZ,OAAO;AAAA,YACL,MAAM;AAAA,YACN,SAAS,qBAAqB,QAAQ,MAAM;AAAA,UAC9C;AAAA,QACF;AAAA,IACJ;AAEA,WAAO;AAAA,MACL,SAAS;AAAA,MACT,IAAI,QAAQ;AAAA,MACZ;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AACd,WAAO;AAAA,MACL,SAAS;AAAA,MACT,IAAI,QAAQ;AAAA,MACZ,OAAO;AAAA,QACL,MAAM;AAAA,QACN,SAAS,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":["config","existsSync","readFileSync","writeFileSync","join","content","readFileSync","provider","readFileSync","config","config","config","config","existsSync","statSync","readFileSync","join"]}
1
+ {"version":3,"sources":["../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/openai-compatible.ts","../src/providers/ollama.ts","../src/providers/anthropic.ts","../src/providers/index.ts"],"sourcesContent":["/**\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// 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: '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: false)',\n },\n maxResults: {\n type: 'number',\n description: 'Maximum results to return (default: 50)',\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\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// Handle tool calls\nasync function handleToolCall(name: string, args: Record<string, unknown>): Promise<unknown> {\n switch (name) {\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 as boolean || false;\n const maxResults = (args.maxResults as number) || 50;\n \n if (!existsSync(path)) {\n throw new Error(`File not found: ${path}`);\n }\n \n const matches = searchDocument(path, pattern, { caseInsensitive, maxResults });\n \n return {\n count: matches.length,\n matches: matches.map(m => ({\n lineNum: m.lineNum,\n line: m.line.trim(),\n match: m.match,\n })),\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 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 } from 'path';\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 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 };\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 * 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 // 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 \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 },\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 * 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","/**\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"],"mappings":";;;AAOA,SAAS,uBAAuB;;;ACAhC,SAAS,YAAY,WAAW,cAAc,qBAAqB;AACnE,SAAS,eAAe;AACxB,SAAS,YAAY;AAkCrB,IAAM,iBAA8B;AAAA,EAClC,UAAU;AAAA,EACV,WAAW;AAAA,IACT,QAAQ;AAAA,MACN,SAAS;AAAA,MACT,OAAO;AAAA,IACT;AAAA,EACF;AAAA,EACA,UAAU;AAAA,IACR,UAAU;AAAA,IACV,eAAe;AAAA,IACf,oBAAoB,CAAC,MAAM,OAAO,MAAM,OAAO,MAAM,MAAM,MAAM,QAAQ,MAAM,OAAO,SAAS,MAAM,SAAS,KAAK,OAAO,KAAK,OAAO,MAAM,IAA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eAAO;AAAA,UACL,SAAS;AAAA,UACT,IAAI,QAAQ;AAAA,UACZ,OAAO;AAAA,YACL,MAAM;AAAA,YACN,SAAS,qBAAqB,QAAQ,MAAM;AAAA,UAC9C;AAAA,QACF;AAAA,IACJ;AAEA,WAAO;AAAA,MACL,SAAS;AAAA,MACT,IAAI,QAAQ;AAAA,MACZ;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AACd,WAAO;AAAA,MACL,SAAS;AAAA,MACT,IAAI,QAAQ;AAAA,MACZ,OAAO;AAAA,QACL,MAAM;AAAA,QACN,SAAS,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":["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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sashabogi/argus-mcp",
3
- "version": "1.2.2",
3
+ "version": "1.2.3",
4
4
  "description": "Codebase Intelligence Beyond Context Limits - AI-powered analysis for entire projects",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",