codeorbit 0.9.4 → 0.10.0

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/adapters/mcp/server.ts","../src/adapters/mcp/tools.ts","../src/infrastructure/SqliteGraphRepository.ts","../src/infrastructure/TreeSitterParser.ts","../src/infrastructure/SqliteEmbeddingStore.ts","../src/infrastructure/LocalEmbeddingProvider.ts","../src/infrastructure/GoogleEmbeddingProvider.ts","../src/infrastructure/FileSystemHelper.ts","../src/infrastructure/GitRunner.ts","../src/usecases/buildGraph.ts","../src/usecases/getImpactRadius.ts","../src/usecases/queryGraph.ts","../src/usecases/getReviewContext.ts","../src/usecases/semanticSearch.ts","../src/usecases/listStats.ts","../src/usecases/embedGraph.ts","../src/usecases/getDocsSection.ts","../src/usecases/findLargeFunctions.ts"],"sourcesContent":["/**\n * MCP server entry point for codeorbit.\n *\n * Run as: codeorbit serve\n * Communicates via stdio (standard MCP transport).\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { z } from 'zod'\nimport {\n buildOrUpdateGraph,\n embedGraph,\n findLargeFunctions,\n getDocsSection,\n getImpactRadius,\n getReviewContext,\n listGraphStats,\n queryGraph,\n semanticSearchNodes,\n} from './tools.js'\n\n// ---------------------------------------------------------------------------\n// Server setup\n// ---------------------------------------------------------------------------\n\nconst server = new McpServer(\n { name: 'codeorbit', version: '0.1.0' },\n {\n instructions:\n 'Persistent incremental knowledge graph for token-efficient, ' +\n 'context-aware code reviews. Parses your codebase with Tree-sitter, ' +\n 'builds a structural graph, and provides smart impact analysis.',\n },\n)\n\n// ---------------------------------------------------------------------------\n// Tool registrations\n// ---------------------------------------------------------------------------\n\nserver.tool(\n 'build_or_update_graph_tool',\n 'Build or incrementally update the code knowledge graph.\\n\\n' +\n 'Call this first to initialize the graph, or after making changes.\\n' +\n 'By default performs an incremental update (only changed files).\\n' +\n 'Set full_rebuild=True to re-parse every file.\\n\\n' +\n 'Args:\\n' +\n ' full_rebuild: If True, re-parse all files. Default: False (incremental).\\n' +\n ' repo_root: Repository root path. Auto-detected from current directory if omitted.\\n' +\n ' base: Git ref to diff against for incremental updates. Default: HEAD~1.',\n {\n full_rebuild: z.boolean().default(false),\n repo_root: z.string().nullable().default(null),\n base: z.string().default('HEAD~1'),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n buildOrUpdateGraph({\n fullRebuild: args.full_rebuild,\n repoRoot: args.repo_root,\n base: args.base,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'get_impact_radius_tool',\n 'Analyze the blast radius of changed files in the codebase.\\n\\n' +\n 'Shows which functions, classes, and files are impacted by changes.\\n' +\n 'Auto-detects changed files from git if not specified.\\n\\n' +\n 'Args:\\n' +\n ' changed_files: List of changed file paths (relative to repo root). Auto-detected if omitted.\\n' +\n ' max_depth: Number of hops to traverse in the dependency graph. Default: 2.\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.\\n' +\n ' base: Git ref for auto-detecting changes. Default: HEAD~1.',\n {\n changed_files: z.array(z.string()).nullable().default(null),\n max_depth: z.number().int().default(2),\n repo_root: z.string().nullable().default(null),\n base: z.string().default('HEAD~1'),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n getImpactRadius({\n changedFiles: args.changed_files,\n maxDepth: args.max_depth,\n repoRoot: args.repo_root,\n base: args.base,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'query_graph_tool',\n 'Run a predefined graph query to explore code relationships.\\n\\n' +\n 'Available patterns:\\n' +\n '- callers_of: Find functions that call the target\\n' +\n '- callees_of: Find functions called by the target\\n' +\n '- imports_of: Find what the target imports\\n' +\n '- importers_of: Find files that import the target\\n' +\n '- children_of: Find nodes contained in a file or class\\n' +\n '- tests_for: Find tests for the target\\n' +\n '- inheritors_of: Find classes inheriting from the target\\n' +\n '- file_summary: Get all nodes in a file\\n\\n' +\n 'Args:\\n' +\n ' pattern: Query pattern name (see above).\\n' +\n ' target: Node name, qualified name, or file path to query.\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.',\n {\n pattern: z.string(),\n target: z.string(),\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n queryGraph({\n pattern: args.pattern,\n target: args.target,\n repoRoot: args.repo_root,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'get_review_context_tool',\n 'Generate a focused, token-efficient review context for code changes.\\n\\n' +\n 'Combines impact analysis with source snippets and review guidance.\\n' +\n 'Use this for comprehensive code reviews.\\n\\n' +\n 'Args:\\n' +\n ' changed_files: Files to review. Auto-detected from git diff if omitted.\\n' +\n ' max_depth: Impact radius depth. Default: 2.\\n' +\n ' include_source: Include source code snippets. Default: True.\\n' +\n ' max_lines_per_file: Max source lines per file. Default: 200.\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.\\n' +\n ' base: Git ref for change detection. Default: HEAD~1.',\n {\n changed_files: z.array(z.string()).nullable().default(null),\n max_depth: z.number().int().default(2),\n include_source: z.boolean().default(true),\n max_lines_per_file: z.number().int().default(200),\n repo_root: z.string().nullable().default(null),\n base: z.string().default('HEAD~1'),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n getReviewContext({\n changedFiles: args.changed_files,\n maxDepth: args.max_depth,\n includeSource: args.include_source,\n maxLinesPerFile: args.max_lines_per_file,\n repoRoot: args.repo_root,\n base: args.base,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'semantic_search_nodes_tool',\n 'Search for code entities by name, keyword, or semantic similarity.\\n\\n' +\n 'Uses vector embeddings for semantic search when available (run embed_graph_tool\\n' +\n 'first, requires @huggingface/transformers). Falls back to keyword matching otherwise.\\n\\n' +\n 'Args:\\n' +\n ' query: Search string to match against node names.\\n' +\n ' kind: Optional filter: File, Class, Function, Type, or Test.\\n' +\n ' limit: Maximum results. Default: 20.\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.',\n {\n query: z.string(),\n kind: z.string().nullable().default(null),\n limit: z.number().int().default(20),\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n await semanticSearchNodes({\n query: args.query,\n kind: args.kind,\n limit: args.limit,\n repoRoot: args.repo_root,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'embed_graph_tool',\n 'Compute vector embeddings for all graph nodes to enable semantic search.\\n\\n' +\n 'Requires: npm install @huggingface/transformers\\n' +\n 'Only computes embeddings for nodes that do not already have them.\\n\\n' +\n 'Args:\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.',\n {\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(await embedGraph({ repoRoot: args.repo_root })),\n },\n ],\n }),\n)\n\nserver.tool(\n 'list_graph_stats_tool',\n 'Get aggregate statistics about the code knowledge graph.\\n\\n' +\n 'Shows total nodes, edges, languages, files, and last update time.\\n' +\n 'Useful for checking if the graph is built and up to date.\\n\\n' +\n 'Args:\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.',\n {\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(listGraphStats({ repoRoot: args.repo_root })),\n },\n ],\n }),\n)\n\nserver.tool(\n 'get_docs_section_tool',\n 'Get a specific section from the LLM-optimized documentation reference.\\n\\n' +\n 'Returns only the requested section content for minimal token usage.\\n\\n' +\n 'Available sections: usage, review-delta, review-pr, commands, legal,\\n' +\n 'watch, embeddings, languages, troubleshooting.\\n\\n' +\n 'Args:\\n' +\n ' section_name: The section to retrieve (e.g. \"review-delta\", \"usage\").',\n {\n section_name: z.string(),\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n getDocsSection({\n sectionName: args.section_name,\n repoRoot: args.repo_root,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'find_large_functions_tool',\n 'Find functions, classes, or files exceeding a line-count threshold.\\n\\n' +\n 'Useful for decomposition audits, code quality checks, and enforcing\\n' +\n 'size limits during code review. Results are ordered by line count.\\n\\n' +\n 'Args:\\n' +\n ' min_lines: Minimum line count to flag. Default: 50.\\n' +\n ' kind: Optional filter: Function, Class, File, or Test.\\n' +\n ' file_path_pattern: Filter by file path substring (e.g. \"components/\").\\n' +\n ' limit: Maximum results. Default: 50.\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.',\n {\n min_lines: z.number().int().default(50),\n kind: z.string().nullable().default(null),\n file_path_pattern: z.string().nullable().default(null),\n limit: z.number().int().default(50),\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n findLargeFunctions({\n minLines: args.min_lines,\n kind: args.kind,\n filePathPattern: args.file_path_pattern,\n limit: args.limit,\n repoRoot: args.repo_root,\n }),\n ),\n },\n ],\n }),\n)\n\n// ---------------------------------------------------------------------------\n// Server entry point\n// ---------------------------------------------------------------------------\n\nexport async function runMcpServer(): Promise<void> {\n const transport = new StdioServerTransport()\n await server.connect(transport)\n}\n","/**\n * MCP tool adapter layer.\n *\n * Each function: validate args → create infrastructure → call use case → return result.\n * No business logic lives here — all logic is in src/usecases/.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { SqliteGraphRepository, nodeToDict, edgeToDict } from '../../infrastructure/SqliteGraphRepository.js'\nimport { TreeSitterParser } from '../../infrastructure/TreeSitterParser.js'\nimport { SqliteEmbeddingStore } from '../../infrastructure/SqliteEmbeddingStore.js'\nimport { findProjectRoot, getDbPath } from '../../infrastructure/FileSystemHelper.js'\nimport { getChangedFiles, getStagedAndUnstaged } from '../../infrastructure/GitRunner.js'\nimport { fullBuild, incrementalUpdate } from '../../usecases/buildGraph.js'\nimport { computeImpactRadius } from '../../usecases/getImpactRadius.js'\nimport { queryGraph as queryGraphUseCase } from '../../usecases/queryGraph.js'\nimport { getReviewContext as getReviewContextUseCase } from '../../usecases/getReviewContext.js'\nimport { semanticSearchNodes as semanticSearchUseCase } from '../../usecases/semanticSearch.js'\nimport { listStats } from '../../usecases/listStats.js'\nimport { embedGraph as embedGraphUseCase } from '../../usecases/embedGraph.js'\nimport { getDocsSection as getDocsSectionUseCase } from '../../usecases/getDocsSection.js'\nimport { findLargeFunctions as findLargeFunctionsUseCase } from '../../usecases/findLargeFunctions.js'\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction validateRepoRoot(repoRoot: string): string {\n const resolved = path.resolve(repoRoot)\n if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) {\n throw new Error(`repo_root is not an existing directory: ${resolved}`)\n }\n if (\n !fs.existsSync(path.join(resolved, '.git')) &&\n !fs.existsSync(path.join(resolved, '.codeorbit'))\n ) {\n throw new Error(\n `repo_root does not look like a project root (no .git or .codeorbit): ${resolved}`,\n )\n }\n return resolved\n}\n\nfunction resolveRoot(repoRoot?: string | null): string {\n return repoRoot ? validateRepoRoot(repoRoot) : findProjectRoot()\n}\n\n// ---------------------------------------------------------------------------\n// Tool 1: buildOrUpdateGraph\n// ---------------------------------------------------------------------------\n\nexport function buildOrUpdateGraph(args: {\n fullRebuild?: boolean\n repoRoot?: string | null\n base?: string\n}): Record<string, unknown> {\n const { fullRebuild = false, repoRoot = null, base = 'HEAD~1' } = args\n const root = resolveRoot(repoRoot)\n const repo = new SqliteGraphRepository(getDbPath(root))\n const parser = new TreeSitterParser()\n try {\n if (fullRebuild) {\n const result = fullBuild(root, repo, parser)\n return {\n status: 'ok',\n build_type: 'full',\n summary:\n `Full build complete: parsed ${result.filesUpdated} files, ` +\n `created ${result.totalNodes} nodes and ${result.totalEdges} edges.`,\n files_updated: result.filesUpdated,\n total_nodes: result.totalNodes,\n total_edges: result.totalEdges,\n errors: result.errors,\n }\n } else {\n const result = incrementalUpdate(root, repo, parser, base)\n if (result.filesUpdated === 0) {\n return {\n status: 'ok',\n build_type: 'incremental',\n summary: 'No changes detected. Graph is up to date.',\n files_updated: 0,\n total_nodes: 0,\n total_edges: 0,\n changed_files: [],\n dependent_files: [],\n errors: [],\n }\n }\n return {\n status: 'ok',\n build_type: 'incremental',\n summary:\n `Incremental update: ${result.filesUpdated} files re-parsed, ` +\n `${result.totalNodes} nodes and ${result.totalEdges} edges updated. ` +\n `Changed: ${JSON.stringify(result.changedFiles)}. ` +\n `Dependents also updated: ${JSON.stringify(result.dependentFiles)}.`,\n files_updated: result.filesUpdated,\n total_nodes: result.totalNodes,\n total_edges: result.totalEdges,\n changed_files: result.changedFiles,\n dependent_files: result.dependentFiles,\n errors: result.errors,\n }\n }\n } finally {\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 2: getImpactRadius\n// ---------------------------------------------------------------------------\n\nexport function getImpactRadius(args: {\n changedFiles?: string[] | null\n maxDepth?: number\n maxResults?: number\n repoRoot?: string | null\n base?: string\n}): Record<string, unknown> {\n const {\n changedFiles = null,\n maxDepth = 2,\n maxResults = 500,\n repoRoot = null,\n base = 'HEAD~1',\n } = args\n const root = resolveRoot(repoRoot)\n const repo = new SqliteGraphRepository(getDbPath(root))\n try {\n let changed = changedFiles\n if (!changed) {\n changed = getChangedFiles(root, base)\n if (changed.length === 0) {\n changed = getStagedAndUnstaged(root)\n }\n }\n\n if (changed.length === 0) {\n return {\n status: 'ok',\n summary: 'No changed files detected.',\n changed_nodes: [],\n impacted_nodes: [],\n impacted_files: [],\n truncated: false,\n total_impacted: 0,\n }\n }\n\n const absFiles = changed.map((f) => path.join(root, f))\n const result = computeImpactRadius(absFiles, repo, maxDepth, maxResults)\n\n const summaryParts = [\n `Blast radius for ${changed.length} changed file(s):`,\n ` - ${result.changedNodes.length} nodes directly changed`,\n ` - ${result.impactedNodes.length} nodes impacted (within ${maxDepth} hops)`,\n ` - ${result.impactedFiles.length} additional files affected`,\n ]\n if (result.truncated) {\n summaryParts.push(\n ` - Results truncated: showing ${result.impactedNodes.length} of ${result.totalImpacted} impacted nodes`,\n )\n }\n\n return {\n status: 'ok',\n summary: summaryParts.join('\\n'),\n changed_files: changed,\n changed_nodes: result.changedNodes.map(nodeToDict),\n impacted_nodes: result.impactedNodes.map(nodeToDict),\n impacted_files: result.impactedFiles,\n edges: result.edges.map(edgeToDict),\n truncated: result.truncated,\n total_impacted: result.totalImpacted,\n }\n } finally {\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 3: queryGraph\n// ---------------------------------------------------------------------------\n\nexport function queryGraph(args: {\n pattern: string\n target: string\n repoRoot?: string | null\n}): Record<string, unknown> {\n const { pattern, target, repoRoot = null } = args\n const root = resolveRoot(repoRoot)\n const repo = new SqliteGraphRepository(getDbPath(root))\n try {\n return queryGraphUseCase({ pattern, target, repo, repoRoot: root })\n } finally {\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 4: getReviewContext\n// ---------------------------------------------------------------------------\n\nexport function getReviewContext(args: {\n changedFiles?: string[] | null\n maxDepth?: number\n includeSource?: boolean\n maxLinesPerFile?: number\n repoRoot?: string | null\n base?: string\n}): Record<string, unknown> {\n const {\n changedFiles = null,\n maxDepth = 2,\n includeSource = true,\n maxLinesPerFile = 200,\n repoRoot = null,\n base = 'HEAD~1',\n } = args\n const root = resolveRoot(repoRoot)\n const repo = new SqliteGraphRepository(getDbPath(root))\n try {\n let changed = changedFiles\n if (!changed) {\n changed = getChangedFiles(root, base)\n if (changed.length === 0) {\n changed = getStagedAndUnstaged(root)\n }\n }\n\n if (changed.length === 0) {\n return {\n status: 'ok',\n summary: 'No changes detected. Nothing to review.',\n context: {},\n }\n }\n\n return getReviewContextUseCase({\n changedFiles: changed,\n repo,\n repoRoot: root,\n maxDepth,\n includeSource,\n maxLinesPerFile,\n })\n } finally {\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 5: semanticSearchNodes\n// ---------------------------------------------------------------------------\n\nexport async function semanticSearchNodes(args: {\n query: string\n kind?: string | null\n limit?: number\n repoRoot?: string | null\n}): Promise<Record<string, unknown>> {\n const { query, kind = null, limit = 20, repoRoot = null } = args\n const root = resolveRoot(repoRoot)\n const dbPath = getDbPath(root)\n const repo = new SqliteGraphRepository(dbPath)\n const embStore = new SqliteEmbeddingStore(dbPath)\n try {\n return await semanticSearchUseCase({ query, kind, limit, repo, embStore })\n } finally {\n embStore.close()\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 6: listGraphStats\n// ---------------------------------------------------------------------------\n\nexport function listGraphStats(args: {\n repoRoot?: string | null\n}): Record<string, unknown> {\n const { repoRoot = null } = args\n const root = resolveRoot(repoRoot)\n const dbPath = getDbPath(root)\n const repo = new SqliteGraphRepository(dbPath)\n const embStore = new SqliteEmbeddingStore(dbPath)\n try {\n return listStats({ repo, embStore, repoRoot: root })\n } finally {\n embStore.close()\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 7: embedGraph\n// ---------------------------------------------------------------------------\n\nexport async function embedGraph(args: {\n repoRoot?: string | null\n}): Promise<Record<string, unknown>> {\n const { repoRoot = null } = args\n const root = resolveRoot(repoRoot)\n const dbPath = getDbPath(root)\n const repo = new SqliteGraphRepository(dbPath)\n const embStore = new SqliteEmbeddingStore(dbPath)\n try {\n return await embedGraphUseCase({ repo, embStore })\n } finally {\n embStore.close()\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 8: getDocsSection\n// ---------------------------------------------------------------------------\n\nexport function getDocsSection(args: {\n sectionName: string\n repoRoot?: string | null\n}): Record<string, unknown> {\n const { sectionName, repoRoot = null } = args\n const searchRoots: string[] = []\n\n if (repoRoot) {\n searchRoots.push(path.resolve(repoRoot))\n }\n\n try {\n const root = resolveRoot(repoRoot)\n if (!searchRoots.includes(root)) {\n searchRoots.push(root)\n }\n } catch {\n // ignore — repo root not required for docs lookup\n }\n\n return getDocsSectionUseCase({ sectionName, searchRoots })\n}\n\n// ---------------------------------------------------------------------------\n// Tool 9: findLargeFunctions\n// ---------------------------------------------------------------------------\n\nexport function findLargeFunctions(args: {\n minLines?: number\n kind?: string | null\n filePathPattern?: string | null\n limit?: number\n repoRoot?: string | null\n}): Record<string, unknown> {\n const {\n minLines = 50,\n kind = null,\n filePathPattern = null,\n limit = 50,\n repoRoot = null,\n } = args\n const root = resolveRoot(repoRoot)\n const repo = new SqliteGraphRepository(getDbPath(root))\n try {\n return findLargeFunctionsUseCase({ minLines, kind, filePathPattern, limit, repo, repoRoot: root })\n } finally {\n repo.close()\n }\n}\n","/**\n * SQLite-backed knowledge graph storage — infrastructure implementation.\n *\n * Implements IGraphRepository. Pure CRUD + adjacency — no business logic.\n * BFS impact-radius computation was extracted to usecases/getImpactRadius.ts.\n *\n * Direct port of code_review_graph/graph.py.\n */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport Database from 'better-sqlite3';\nimport type {\n NodeInfo,\n EdgeInfo,\n GraphNode,\n GraphEdge,\n GraphStats,\n NodeRow,\n EdgeRow,\n CountRow,\n KindCountRow,\n LanguageRow,\n FilePathRow,\n MetadataRow,\n EdgeKind,\n} from '../domain/types.js';\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js';\n\n// ---------------------------------------------------------------------------\n// Schema DDL — must match Python's _SCHEMA_SQL exactly (schema_version = 1)\n// ---------------------------------------------------------------------------\n\nconst SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS nodes (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n kind TEXT NOT NULL,\n name TEXT NOT NULL,\n qualified_name TEXT NOT NULL UNIQUE,\n file_path TEXT NOT NULL,\n line_start INTEGER,\n line_end INTEGER,\n language TEXT,\n parent_name TEXT,\n params TEXT,\n return_type TEXT,\n modifiers TEXT,\n is_test INTEGER DEFAULT 0,\n file_hash TEXT,\n extra TEXT DEFAULT '{}',\n updated_at REAL NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS edges (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n kind TEXT NOT NULL,\n source_qualified TEXT NOT NULL,\n target_qualified TEXT NOT NULL,\n file_path TEXT NOT NULL,\n line INTEGER DEFAULT 0,\n extra TEXT DEFAULT '{}',\n updated_at REAL NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS metadata (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS idx_nodes_file ON nodes(file_path);\nCREATE INDEX IF NOT EXISTS idx_nodes_kind ON nodes(kind);\nCREATE INDEX IF NOT EXISTS idx_nodes_qualified ON nodes(qualified_name);\nCREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source_qualified);\nCREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target_qualified);\nCREATE INDEX IF NOT EXISTS idx_edges_kind ON edges(kind);\nCREATE INDEX IF NOT EXISTS idx_edges_file ON edges(file_path);\n`;\n\n// ---------------------------------------------------------------------------\n// In-memory adjacency cache (replaces networkx.DiGraph)\n// ---------------------------------------------------------------------------\n\ninterface AdjacencyCache {\n out: Map<string, Set<string>>;\n in: Map<string, Set<string>>;\n}\n\n// ---------------------------------------------------------------------------\n// SqliteGraphRepository\n// ---------------------------------------------------------------------------\n\nexport class SqliteGraphRepository implements IGraphRepository {\n private db: Database.Database;\n private adjCache: AdjacencyCache | null = null;\n readonly dbPath: string;\n\n constructor(dbPath: string) {\n this.dbPath = dbPath;\n const dir = path.dirname(dbPath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n this.db = new Database(dbPath);\n this.db.pragma('journal_mode = WAL');\n this.db.pragma('busy_timeout = 5000');\n\n try {\n this.db.pragma('wal_checkpoint(TRUNCATE)');\n } catch {\n // ignore — safe to skip if another writer holds it\n }\n\n this._initSchema();\n }\n\n close(): void {\n try {\n this.db.pragma('wal_checkpoint(TRUNCATE)');\n } catch {\n // ignore\n }\n this.db.close();\n for (const suffix of ['-wal', '-shm']) {\n const side = this.dbPath + suffix;\n try {\n if (fs.existsSync(side)) { fs.unlinkSync(side); }\n } catch {\n // locked by another process — leave it alone\n }\n }\n }\n\n // ---------------------------------------------------------------------------\n // Write operations\n // ---------------------------------------------------------------------------\n\n upsertNode(node: NodeInfo, fileHash = ''): number {\n const now = Date.now() / 1000;\n const qualified = this._makeQualified(node);\n const extra = node.extra ? JSON.stringify(node.extra) : '{}';\n\n this.db.prepare(`\n INSERT INTO nodes\n (kind, name, qualified_name, file_path, line_start, line_end,\n language, parent_name, params, return_type, modifiers, is_test,\n file_hash, extra, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(qualified_name) DO UPDATE SET\n kind=excluded.kind, name=excluded.name,\n file_path=excluded.file_path, line_start=excluded.line_start,\n line_end=excluded.line_end, language=excluded.language,\n parent_name=excluded.parent_name, params=excluded.params,\n return_type=excluded.return_type, modifiers=excluded.modifiers,\n is_test=excluded.is_test, file_hash=excluded.file_hash,\n extra=excluded.extra, updated_at=excluded.updated_at\n `).run(\n node.kind, node.name, qualified, node.filePath,\n node.lineStart, node.lineEnd, node.language ?? null,\n node.parentName ?? null, node.params ?? null, node.returnType ?? null,\n node.modifiers ?? null, node.isTest ? 1 : 0, fileHash,\n extra, now,\n );\n\n const row = this.db.prepare(\n 'SELECT id FROM nodes WHERE qualified_name = ?'\n ).get(qualified) as { id: number };\n return row.id;\n }\n\n upsertEdge(edge: EdgeInfo): number {\n const now = Date.now() / 1000;\n const extra = edge.extra ? JSON.stringify(edge.extra) : '{}';\n const line = edge.line ?? 0;\n\n const existing = this.db.prepare(`\n SELECT id FROM edges\n WHERE kind=? AND source_qualified=? AND target_qualified=?\n AND file_path=? AND line=?\n `).get(edge.kind, edge.source, edge.target, edge.filePath, line) as\n { id: number } | undefined;\n\n if (existing) {\n this.db.prepare(\n 'UPDATE edges SET line=?, extra=?, updated_at=? WHERE id=?'\n ).run(line, extra, now, existing.id);\n return existing.id;\n }\n\n const result = this.db.prepare(`\n INSERT INTO edges\n (kind, source_qualified, target_qualified, file_path, line, extra, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n `).run(edge.kind, edge.source, edge.target, edge.filePath, line, extra, now);\n return Number(result.lastInsertRowid);\n }\n\n removeFileData(filePath: string): void {\n this.db.prepare('DELETE FROM nodes WHERE file_path = ?').run(filePath);\n this.db.prepare('DELETE FROM edges WHERE file_path = ?').run(filePath);\n this._invalidateCache();\n }\n\n storeFileNodesEdges(\n filePath: string,\n nodes: NodeInfo[],\n edges: EdgeInfo[],\n fileHash = '',\n ): void {\n const txn = this.db.transaction(() => {\n this.removeFileData(filePath);\n for (const node of nodes) { this.upsertNode(node, fileHash); }\n for (const edge of edges) { this.upsertEdge(edge); }\n });\n txn();\n this._invalidateCache();\n }\n\n setMetadata(key: string, value: string): void {\n this.db.prepare(\n 'INSERT OR REPLACE INTO metadata (key, value) VALUES (?, ?)'\n ).run(key, value);\n }\n\n getMetadata(key: string): string | undefined {\n const row = this.db.prepare(\n 'SELECT value FROM metadata WHERE key = ?'\n ).get(key) as MetadataRow | undefined;\n return row?.value;\n }\n\n // ---------------------------------------------------------------------------\n // Read operations\n // ---------------------------------------------------------------------------\n\n getNode(qualifiedName: string): GraphNode | undefined {\n const row = this.db.prepare(\n 'SELECT * FROM nodes WHERE qualified_name = ?'\n ).get(qualifiedName) as NodeRow | undefined;\n return row ? this._rowToNode(row) : undefined;\n }\n\n getNodesByFile(filePath: string): GraphNode[] {\n const rows = this.db.prepare(\n 'SELECT * FROM nodes WHERE file_path = ? ORDER BY line_start'\n ).all(filePath) as NodeRow[];\n return rows.map((r) => this._rowToNode(r));\n }\n\n getEdgesBySource(qualifiedName: string): GraphEdge[] {\n const rows = this.db.prepare(\n 'SELECT * FROM edges WHERE source_qualified = ?'\n ).all(qualifiedName) as EdgeRow[];\n return rows.map((r) => this._rowToEdge(r));\n }\n\n getEdgesByTarget(qualifiedName: string): GraphEdge[] {\n const rows = this.db.prepare(\n 'SELECT * FROM edges WHERE target_qualified = ?'\n ).all(qualifiedName) as EdgeRow[];\n return rows.map((r) => this._rowToEdge(r));\n }\n\n searchEdgesByTargetName(name: string, kind: EdgeKind = 'CALLS'): GraphEdge[] {\n const rows = this.db.prepare(\n 'SELECT * FROM edges WHERE target_qualified = ? AND kind = ?'\n ).all(name, kind) as EdgeRow[];\n return rows.map((r) => this._rowToEdge(r));\n }\n\n getAllFiles(): string[] {\n const rows = this.db.prepare(\n \"SELECT DISTINCT file_path FROM nodes WHERE kind = 'File' ORDER BY file_path\"\n ).all() as FilePathRow[];\n return rows.map((r) => r.file_path);\n }\n\n searchNodes(query: string, limit = 20): GraphNode[] {\n const words = query.toLowerCase().split(/\\s+/).filter(Boolean);\n if (words.length === 0) { return []; }\n\n const conditions = words.map(\n () => '(LOWER(name) LIKE ? OR LOWER(qualified_name) LIKE ?)'\n );\n const params: Array<string | number> = [];\n for (const word of words) {\n params.push(`%${word}%`, `%${word}%`);\n }\n params.push(limit);\n\n const where = conditions.join(' AND ');\n // nosec: all values are parameterised\n const rows = this.db.prepare(\n `SELECT * FROM nodes WHERE ${where} LIMIT ?`\n ).all(...params) as NodeRow[];\n return rows.map((r) => this._rowToNode(r));\n }\n\n getSubgraph(qualifiedNames: string[]): { nodes: GraphNode[]; edges: GraphEdge[] } {\n const nodes: GraphNode[] = [];\n for (const qn of qualifiedNames) {\n const n = this.getNode(qn);\n if (n) { nodes.push(n); }\n }\n const qnSet = new Set(qualifiedNames);\n const edges: GraphEdge[] = [];\n for (const qn of qualifiedNames) {\n for (const e of this.getEdgesBySource(qn)) {\n if (qnSet.has(e.targetQualified)) { edges.push(e); }\n }\n }\n return { nodes, edges };\n }\n\n getStats(): GraphStats {\n const totalNodes = (\n this.db.prepare('SELECT COUNT(*) AS cnt FROM nodes').get() as CountRow\n ).cnt;\n const totalEdges = (\n this.db.prepare('SELECT COUNT(*) AS cnt FROM edges').get() as CountRow\n ).cnt;\n\n const nodesByKind: Record<string, number> = {};\n for (const r of this.db.prepare(\n 'SELECT kind, COUNT(*) AS cnt FROM nodes GROUP BY kind'\n ).all() as KindCountRow[]) {\n nodesByKind[r.kind] = r.cnt;\n }\n\n const edgesByKind: Record<string, number> = {};\n for (const r of this.db.prepare(\n 'SELECT kind, COUNT(*) AS cnt FROM edges GROUP BY kind'\n ).all() as KindCountRow[]) {\n edgesByKind[r.kind] = r.cnt;\n }\n\n const languages = (this.db.prepare(\n \"SELECT DISTINCT language FROM nodes WHERE language IS NOT NULL AND language != ''\"\n ).all() as LanguageRow[]).map((r) => r.language);\n\n const filesCount = (this.db.prepare(\n \"SELECT COUNT(*) AS cnt FROM nodes WHERE kind = 'File'\"\n ).get() as CountRow).cnt;\n\n const lastUpdated = this.getMetadata('last_updated') ?? null;\n\n let embeddingsCount = 0;\n try {\n embeddingsCount = (\n this.db.prepare('SELECT COUNT(*) AS cnt FROM embeddings').get() as CountRow\n ).cnt;\n } catch {\n // embeddings table may not exist — that is fine\n }\n\n return {\n totalNodes, totalEdges, nodesByKind, edgesByKind,\n languages, filesCount, lastUpdated, embeddingsCount,\n };\n }\n\n getNodesBySize(\n minLines = 50,\n maxLines?: number,\n kind?: string,\n filePathPattern?: string,\n limit = 50,\n ): Array<GraphNode & { lineCount: number }> {\n const conditions = [\n 'line_start IS NOT NULL',\n 'line_end IS NOT NULL',\n '(line_end - line_start + 1) >= ?',\n ];\n const params: Array<string | number> = [minLines];\n\n if (maxLines !== undefined) {\n conditions.push('(line_end - line_start + 1) <= ?');\n params.push(maxLines);\n }\n if (kind) { conditions.push('kind = ?'); params.push(kind); }\n if (filePathPattern) {\n conditions.push('file_path LIKE ?');\n params.push(`%${filePathPattern}%`);\n }\n params.push(limit);\n const where = conditions.join(' AND ');\n // nosec: all values are parameterised\n const rows = this.db.prepare(\n `SELECT * FROM nodes WHERE ${where} ORDER BY (line_end - line_start + 1) DESC LIMIT ?`\n ).all(...params) as NodeRow[];\n return rows.map((r) => ({\n ...this._rowToNode(r),\n lineCount:\n r.line_start != null && r.line_end != null\n ? r.line_end - r.line_start + 1\n : 0,\n }));\n }\n\n getAllEdges(): GraphEdge[] {\n const rows = this.db.prepare('SELECT * FROM edges').all() as EdgeRow[];\n return rows.map((r) => this._rowToEdge(r));\n }\n\n getEdgesAmong(qualifiedNames: Set<string>): GraphEdge[] {\n if (qualifiedNames.size === 0) { return []; }\n const qns = [...qualifiedNames];\n const results: GraphEdge[] = [];\n const batchSize = 450;\n\n for (let i = 0; i < qns.length; i += batchSize) {\n const batch = qns.slice(i, i + batchSize);\n const placeholders = batch.map(() => '?').join(',');\n // nosec: placeholders are parameterised\n const rows = this.db.prepare(\n `SELECT * FROM edges WHERE source_qualified IN (${placeholders})`\n ).all(...batch) as EdgeRow[];\n for (const r of rows) {\n const edge = this._rowToEdge(r);\n if (qualifiedNames.has(edge.targetQualified)) { results.push(edge); }\n }\n }\n return results;\n }\n\n // ---------------------------------------------------------------------------\n // Adjacency (BFS support for use cases)\n // ---------------------------------------------------------------------------\n\n getAdjacency(): { outgoing: Map<string, Set<string>>; incoming: Map<string, Set<string>> } {\n const cache = this._buildAdjacency();\n return { outgoing: cache.out, incoming: cache.in };\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n private _initSchema(): void {\n this.db.exec(SCHEMA_SQL);\n this.setMetadata('schema_version', '1');\n }\n\n private _invalidateCache(): void {\n this.adjCache = null;\n }\n\n private _buildAdjacency(): AdjacencyCache {\n if (this.adjCache) { return this.adjCache; }\n const out = new Map<string, Set<string>>();\n const inMap = new Map<string, Set<string>>();\n\n const rows = this.db.prepare('SELECT source_qualified, target_qualified FROM edges').all() as\n Array<{ source_qualified: string; target_qualified: string }>;\n\n for (const r of rows) {\n if (!out.has(r.source_qualified)) { out.set(r.source_qualified, new Set()); }\n out.get(r.source_qualified)!.add(r.target_qualified);\n\n if (!inMap.has(r.target_qualified)) { inMap.set(r.target_qualified, new Set()); }\n inMap.get(r.target_qualified)!.add(r.source_qualified);\n }\n\n this.adjCache = { out, in: inMap };\n return this.adjCache;\n }\n\n private _makeQualified(node: NodeInfo): string {\n if (node.kind === 'File') { return node.filePath; }\n if (node.parentName) {\n return `${node.filePath}::${node.parentName}.${node.name}`;\n }\n return `${node.filePath}::${node.name}`;\n }\n\n private _rowToNode(row: NodeRow): GraphNode {\n return {\n id: row.id,\n kind: row.kind as GraphNode['kind'],\n name: row.name,\n qualifiedName: row.qualified_name,\n filePath: row.file_path,\n lineStart: row.line_start,\n lineEnd: row.line_end,\n language: row.language ?? null,\n parentName: row.parent_name ?? null,\n params: row.params ?? null,\n returnType: row.return_type ?? null,\n modifiers: row.modifiers ?? null,\n isTest: row.is_test === 1,\n fileHash: row.file_hash ?? null,\n };\n }\n\n private _rowToEdge(row: EdgeRow): GraphEdge {\n return {\n id: row.id,\n kind: row.kind as GraphEdge['kind'],\n sourceQualified: row.source_qualified,\n targetQualified: row.target_qualified,\n filePath: row.file_path,\n line: row.line ?? 0,\n };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Utility exports (mirrors Python module-level helpers)\n// ---------------------------------------------------------------------------\n\nexport function sanitizeName(s: string, maxLen = 256): string {\n let cleaned = '';\n for (const ch of s) {\n const code = ch.codePointAt(0) ?? 0;\n if (ch === '\\t' || ch === '\\n' || code >= 0x20) { cleaned += ch; }\n }\n return cleaned.slice(0, maxLen);\n}\n\nexport function nodeToDict(n: GraphNode): Record<string, unknown> {\n return {\n id: n.id,\n kind: n.kind,\n name: sanitizeName(n.name),\n qualified_name: sanitizeName(n.qualifiedName),\n file_path: n.filePath,\n line_start: n.lineStart,\n line_end: n.lineEnd,\n language: n.language,\n parent_name: n.parentName ? sanitizeName(n.parentName) : n.parentName,\n is_test: n.isTest,\n };\n}\n\nexport function edgeToDict(e: GraphEdge): Record<string, unknown> {\n return {\n id: e.id,\n kind: e.kind,\n source: sanitizeName(e.sourceQualified),\n target: sanitizeName(e.targetQualified),\n file_path: e.filePath,\n line: e.line,\n };\n}\n\n// Backward-compat alias (used by tests + public index.ts)\nexport { SqliteGraphRepository as GraphStore };\n","/**\n * Tree-sitter based multi-language code parser.\n *\n * Extracts structural nodes (classes, functions, imports, types) and edges\n * (calls, inheritance, contains) from source files.\n *\n * Direct port of code_review_graph/parser.py.\n * Supports 14 languages: Python, JS/TS/TSX, Go, Rust, Java, C, C++, C#,\n * Ruby, Kotlin, Swift, PHP, Solidity, Vue SFC.\n */\n\nimport crypto from 'node:crypto';\nimport fs from 'node:fs';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport Parser from 'tree-sitter';\n\nconst _require = createRequire(import.meta.url);\nimport type { NodeInfo, EdgeInfo } from '../domain/types.js';\nimport type { IParser } from '../domain/ports/IParser.js';\n\n// ---------------------------------------------------------------------------\n// Language loading — individual npm grammar packages\n// ---------------------------------------------------------------------------\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Language = any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype SyntaxNode = any;\n\nfunction loadLanguage(pkg: string): Language | null {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const mod = _require(pkg);\n return mod.default ?? mod;\n } catch {\n return null;\n }\n}\n\n// Lazy-loaded grammar map. Languages are loaded on first use.\nconst _languageCache = new Map<string, Language | null>();\n\nfunction getLanguage(name: string): Language | null {\n if (_languageCache.has(name)) { return _languageCache.get(name) ?? null; }\n\n const pkgMap: Record<string, string> = {\n python: 'tree-sitter-python',\n javascript: 'tree-sitter-javascript',\n typescript: 'tree-sitter-typescript/bindings/node/typescript',\n tsx: 'tree-sitter-typescript/bindings/node/tsx',\n go: 'tree-sitter-go',\n rust: 'tree-sitter-rust',\n java: 'tree-sitter-java',\n c: 'tree-sitter-c',\n cpp: 'tree-sitter-cpp',\n csharp: 'tree-sitter-c-sharp',\n ruby: 'tree-sitter-ruby',\n kotlin: 'tree-sitter-kotlin',\n swift: 'tree-sitter-swift',\n php: 'tree-sitter-php/php',\n solidity: 'tree-sitter-solidity',\n vue: 'tree-sitter-vue',\n };\n\n const pkg = pkgMap[name];\n const lang = pkg ? loadLanguage(pkg) : null;\n _languageCache.set(name, lang);\n return lang;\n}\n\n// ---------------------------------------------------------------------------\n// Extension → language mapping\n// ---------------------------------------------------------------------------\n\nexport const EXTENSION_TO_LANGUAGE: Record<string, string> = {\n '.py': 'python',\n '.js': 'javascript',\n '.jsx': 'javascript',\n '.ts': 'typescript',\n '.tsx': 'tsx',\n '.go': 'go',\n '.rs': 'rust',\n '.java': 'java',\n '.cs': 'csharp',\n '.rb': 'ruby',\n '.cpp': 'cpp',\n '.cc': 'cpp',\n '.cxx': 'cpp',\n '.c': 'c',\n '.h': 'c',\n '.hpp': 'cpp',\n '.kt': 'kotlin',\n '.swift': 'swift',\n '.php': 'php',\n '.sol': 'solidity',\n '.vue': 'vue',\n};\n\n// ---------------------------------------------------------------------------\n// AST node type sets per language\n// ---------------------------------------------------------------------------\n\nconst CLASS_TYPES: Record<string, string[]> = {\n python: ['class_definition'],\n javascript: ['class_declaration', 'class'],\n typescript: ['class_declaration', 'class'],\n tsx: ['class_declaration', 'class'],\n go: ['type_declaration'],\n rust: ['struct_item', 'enum_item', 'impl_item'],\n java: ['class_declaration', 'interface_declaration', 'enum_declaration'],\n c: ['struct_specifier', 'type_definition'],\n cpp: ['class_specifier', 'struct_specifier'],\n csharp: ['class_declaration', 'interface_declaration', 'enum_declaration', 'struct_declaration'],\n ruby: ['class', 'module'],\n kotlin: ['class_declaration', 'object_declaration'],\n swift: ['class_declaration', 'struct_declaration', 'protocol_declaration'],\n php: ['class_declaration', 'interface_declaration'],\n solidity: [\n 'contract_declaration', 'interface_declaration', 'library_declaration',\n 'struct_declaration', 'enum_declaration', 'error_declaration',\n 'user_defined_type_definition',\n ],\n};\n\nconst FUNCTION_TYPES: Record<string, string[]> = {\n python: ['function_definition'],\n javascript: ['function_declaration', 'method_definition', 'arrow_function'],\n typescript: ['function_declaration', 'method_definition', 'arrow_function'],\n tsx: ['function_declaration', 'method_definition', 'arrow_function'],\n go: ['function_declaration', 'method_declaration'],\n rust: ['function_item'],\n java: ['method_declaration', 'constructor_declaration'],\n c: ['function_definition'],\n cpp: ['function_definition'],\n csharp: ['method_declaration', 'constructor_declaration'],\n ruby: ['method', 'singleton_method'],\n kotlin: ['function_declaration'],\n swift: ['function_declaration'],\n php: ['function_definition', 'method_declaration'],\n solidity: [\n 'function_definition', 'constructor_definition', 'modifier_definition',\n 'event_definition', 'fallback_receive_definition',\n ],\n};\n\nconst IMPORT_TYPES: Record<string, string[]> = {\n python: ['import_statement', 'import_from_statement'],\n javascript: ['import_statement'],\n typescript: ['import_statement'],\n tsx: ['import_statement'],\n go: ['import_declaration'],\n rust: ['use_declaration'],\n java: ['import_declaration'],\n c: ['preproc_include'],\n cpp: ['preproc_include'],\n csharp: ['using_directive'],\n ruby: ['call'], // require / require_relative\n kotlin: ['import_header'],\n swift: ['import_declaration'],\n php: ['namespace_use_declaration'],\n solidity: ['import_directive'],\n};\n\nconst CALL_TYPES: Record<string, string[]> = {\n python: ['call'],\n javascript: ['call_expression', 'new_expression'],\n typescript: ['call_expression', 'new_expression'],\n tsx: ['call_expression', 'new_expression'],\n go: ['call_expression'],\n rust: ['call_expression', 'macro_invocation'],\n java: ['method_invocation', 'object_creation_expression'],\n c: ['call_expression'],\n cpp: ['call_expression'],\n csharp: ['invocation_expression', 'object_creation_expression'],\n ruby: ['call', 'method_call'],\n kotlin: ['call_expression'],\n swift: ['call_expression'],\n php: ['function_call_expression', 'member_call_expression'],\n solidity: ['call_expression'],\n};\n\n// ---------------------------------------------------------------------------\n// Test detection patterns\n// ---------------------------------------------------------------------------\n\nconst TEST_PATTERNS = [\n /^test_/,\n /^Test/,\n /_test$/,\n /\\.test\\./,\n /\\.spec\\./,\n /_spec$/,\n];\n\nconst TEST_FILE_PATTERNS = [\n /test_.*\\.py$/,\n /.*_test\\.py$/,\n /.*\\.test\\.[jt]sx?$/,\n /.*\\.spec\\.[jt]sx?$/,\n /.*_test\\.go$/,\n /tests?\\//,\n];\n\nfunction isTestFile(filePath: string): boolean {\n return TEST_FILE_PATTERNS.some((p) => p.test(filePath));\n}\n\n// Test-runner framework names that indicate a function IS a test even\n// if its name doesn't start with \"test\".\nconst TEST_RUNNER_NAMES = new Set([\n 'describe', 'it', 'test', 'beforeEach', 'afterEach', 'beforeAll', 'afterAll',\n]);\n\nfunction isTestFunction(name: string, filePath: string): boolean {\n // Name-pattern match always wins\n if (TEST_PATTERNS.some((p) => p.test(name))) { return true; }\n // In a test file, only test-runner functions count (not every helper)\n if (isTestFile(filePath) && TEST_RUNNER_NAMES.has(name)) { return true; }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Public utility\n// ---------------------------------------------------------------------------\n\nexport function fileHash(filePath: string): string {\n const buf = fs.readFileSync(filePath);\n return crypto.createHash('sha256').update(buf).digest('hex');\n}\n\n// ---------------------------------------------------------------------------\n// CodeParser\n// ---------------------------------------------------------------------------\n\nconst MAX_AST_DEPTH = 180;\nconst MODULE_CACHE_MAX = 15_000;\n\nexport class CodeParser implements IParser {\n private parsers = new Map<string, Parser>();\n private moduleFileCache = new Map<string, string | null>();\n\n private getParser(language: string): Parser | null {\n if (this.parsers.has(language)) { return this.parsers.get(language) ?? null; }\n try {\n const lang = getLanguage(language);\n if (!lang) { return null; }\n const p = new Parser();\n p.setLanguage(lang);\n this.parsers.set(language, p);\n return p;\n } catch {\n return null;\n }\n }\n\n detectLanguage(filePath: string): string | null {\n const ext = path.extname(filePath).toLowerCase();\n return EXTENSION_TO_LANGUAGE[ext] ?? null;\n }\n\n parseFile(filePath: string): [NodeInfo[], EdgeInfo[]] {\n let source: Buffer;\n try {\n source = fs.readFileSync(filePath);\n } catch {\n return [[], []];\n }\n return this.parseBytes(filePath, source);\n }\n\n parseBytes(filePath: string, source: Buffer): [NodeInfo[], EdgeInfo[]] {\n const language = this.detectLanguage(filePath);\n if (!language) { return [[], []]; }\n\n if (language === 'vue') {\n return this._parseVue(filePath, source);\n }\n\n const parser = this.getParser(language);\n if (!parser) { return [[], []]; }\n\n const tree = parser.parse(source.toString('utf-8'));\n const nodes: NodeInfo[] = [];\n const edges: EdgeInfo[] = [];\n const testFile = isTestFile(filePath);\n\n // File node\n const lineCount = source.toString('utf-8').split('\\n').length;\n nodes.push({\n kind: 'File',\n name: filePath,\n filePath,\n lineStart: 1,\n lineEnd: lineCount,\n language,\n isTest: testFile,\n });\n\n const [importMap, definedNames] = this._collectFileScope(\n tree.rootNode, language, source,\n );\n\n this._extractFromTree(\n tree.rootNode, source, language, filePath, nodes, edges,\n undefined, undefined, importMap, definedNames,\n );\n\n const resolvedEdges = this._resolveCallTargets(nodes, edges, filePath);\n\n // Generate TESTED_BY edges\n if (testFile) {\n const testQNames = new Set<string>();\n for (const n of nodes) {\n if (n.isTest) {\n testQNames.add(this._qualify(n.name, filePath, n.parentName ?? null));\n }\n }\n const testedBy: EdgeInfo[] = [];\n for (const edge of resolvedEdges) {\n if (edge.kind === 'CALLS' && testQNames.has(edge.source)) {\n testedBy.push({\n kind: 'TESTED_BY',\n source: edge.target,\n target: edge.source,\n filePath: edge.filePath,\n line: edge.line,\n });\n }\n }\n resolvedEdges.push(...testedBy);\n }\n\n return [nodes, resolvedEdges];\n }\n\n private _parseVue(filePath: string, source: Buffer): [NodeInfo[], EdgeInfo[]] {\n const vueParser = this.getParser('vue');\n if (!vueParser) { return [[], []]; }\n\n const tree = vueParser.parse(source.toString('utf-8'));\n const testFile = isTestFile(filePath);\n const lineCount = source.toString('utf-8').split('\\n').length;\n\n const allNodes: NodeInfo[] = [{\n kind: 'File',\n name: filePath,\n filePath,\n lineStart: 1,\n lineEnd: lineCount,\n language: 'vue',\n isTest: testFile,\n }];\n const allEdges: EdgeInfo[] = [];\n\n for (const child of tree.rootNode.children) {\n if (child.type !== 'script_element') { continue; }\n\n let scriptLang = 'javascript';\n let startTag: SyntaxNode | null = null;\n let rawTextNode: SyntaxNode | null = null;\n\n for (const sub of child.children) {\n if (sub.type === 'start_tag') { startTag = sub; }\n else if (sub.type === 'raw_text') { rawTextNode = sub; }\n }\n\n if (startTag) {\n for (const attr of startTag.children) {\n if (attr.type === 'attribute') {\n let attrName: string | null = null;\n let attrValue: string | null = null;\n for (const a of attr.children) {\n if (a.type === 'attribute_name') { attrName = a.text; }\n else if (a.type === 'quoted_attribute_value') {\n for (const v of a.children) {\n if (v.type === 'attribute_value') { attrValue = v.text; }\n }\n }\n }\n if (attrName === 'lang' && (attrValue === 'ts' || attrValue === 'typescript')) {\n scriptLang = 'typescript';\n }\n }\n }\n }\n\n if (!rawTextNode) { continue; }\n\n const scriptSource = Buffer.from(rawTextNode.text, 'utf-8');\n const lineOffset: number = rawTextNode.startPosition.row;\n\n const scriptParser = this.getParser(scriptLang);\n if (!scriptParser) { continue; }\n\n const scriptTree = scriptParser.parse(scriptSource.toString('utf-8'));\n const [importMap, definedNames] = this._collectFileScope(\n scriptTree.rootNode, scriptLang, scriptSource,\n );\n\n const nodes: NodeInfo[] = [];\n const edges: EdgeInfo[] = [];\n this._extractFromTree(\n scriptTree.rootNode, scriptSource, scriptLang, filePath,\n nodes, edges, undefined, undefined, importMap, definedNames,\n );\n\n // Adjust line numbers and language for position within .vue file\n for (const n of nodes) {\n n.lineStart += lineOffset;\n n.lineEnd += lineOffset;\n n.language = 'vue';\n }\n for (const e of edges) {\n e.line = (e.line ?? 0) + lineOffset;\n }\n\n allNodes.push(...nodes);\n allEdges.push(...edges);\n }\n\n // Generate TESTED_BY edges\n if (testFile) {\n const testQNames = new Set<string>();\n for (const n of allNodes) {\n if (n.isTest) {\n testQNames.add(this._qualify(n.name, filePath, n.parentName ?? null));\n }\n }\n const testedBy: EdgeInfo[] = [];\n for (const edge of allEdges) {\n if (edge.kind === 'CALLS' && testQNames.has(edge.source)) {\n testedBy.push({\n kind: 'TESTED_BY',\n source: edge.target,\n target: edge.source,\n filePath: edge.filePath,\n line: edge.line,\n });\n }\n }\n allEdges.push(...testedBy);\n }\n\n return [allNodes, allEdges];\n }\n\n private _resolveCallTargets(\n nodes: NodeInfo[],\n edges: EdgeInfo[],\n filePath: string,\n ): EdgeInfo[] {\n const symbols = new Map<string, string>();\n for (const node of nodes) {\n if (['Function', 'Class', 'Type', 'Test'].includes(node.kind)) {\n const bare = node.name;\n if (!symbols.has(bare)) {\n symbols.set(bare, this._qualify(bare, filePath, node.parentName ?? null));\n }\n }\n }\n\n return edges.map((edge) => {\n if (edge.kind === 'CALLS' && !edge.target.includes('::')) {\n const qualified = symbols.get(edge.target);\n if (qualified) {\n return { ...edge, target: qualified };\n }\n }\n return edge;\n });\n }\n\n private _extractFromTree(\n root: SyntaxNode,\n source: Buffer,\n language: string,\n filePath: string,\n nodes: NodeInfo[],\n edges: EdgeInfo[],\n enclosingClass?: string | null,\n enclosingFunc?: string | null,\n importMap?: Map<string, string>,\n definedNames?: Set<string>,\n depth = 0,\n ): void {\n if (depth > MAX_AST_DEPTH) { return; }\n\n const classTypes = new Set(CLASS_TYPES[language] ?? []);\n const funcTypes = new Set(FUNCTION_TYPES[language] ?? []);\n const importTypes = new Set(IMPORT_TYPES[language] ?? []);\n const callTypes = new Set(CALL_TYPES[language] ?? []);\n\n for (const child of root.children) {\n const nodeType: string = child.type;\n\n // --- Classes ---\n if (classTypes.has(nodeType)) {\n const name = this._getName(child, language, 'class');\n if (name) {\n nodes.push({\n kind: 'Class',\n name,\n filePath,\n lineStart: child.startPosition.row + 1,\n lineEnd: child.endPosition.row + 1,\n language,\n parentName: enclosingClass ?? null,\n });\n\n edges.push({\n kind: 'CONTAINS',\n source: filePath,\n target: this._qualify(name, filePath, enclosingClass ?? null),\n filePath,\n line: child.startPosition.row + 1,\n });\n\n const bases = this._getBases(child, language);\n for (const base of bases) {\n edges.push({\n kind: 'INHERITS',\n source: this._qualify(name, filePath, enclosingClass ?? null),\n target: base,\n filePath,\n line: child.startPosition.row + 1,\n });\n }\n\n this._extractFromTree(\n child, source, language, filePath, nodes, edges,\n name, null, importMap, definedNames, depth + 1,\n );\n continue;\n }\n }\n\n // --- Functions ---\n if (funcTypes.has(nodeType)) {\n const name = this._getName(child, language, 'function');\n if (name) {\n const isTest = isTestFunction(name, filePath);\n const kind = isTest ? 'Test' : 'Function';\n const qualified = this._qualify(name, filePath, enclosingClass ?? null);\n const params = this._getParams(child, language);\n const retType = this._getReturnType(child, language);\n\n nodes.push({\n kind,\n name,\n filePath,\n lineStart: child.startPosition.row + 1,\n lineEnd: child.endPosition.row + 1,\n language,\n parentName: enclosingClass ?? null,\n params,\n returnType: retType,\n isTest,\n });\n\n const container = enclosingClass\n ? this._qualify(enclosingClass, filePath, null)\n : filePath;\n edges.push({\n kind: 'CONTAINS',\n source: container,\n target: qualified,\n filePath,\n line: child.startPosition.row + 1,\n });\n\n // Solidity: modifier invocations → CALLS edges\n if (language === 'solidity') {\n for (const sub of child.children) {\n if (sub.type === 'modifier_invocation') {\n for (const ident of sub.children) {\n if (ident.type === 'identifier') {\n edges.push({\n kind: 'CALLS',\n source: qualified,\n target: ident.text,\n filePath,\n line: sub.startPosition.row + 1,\n });\n break;\n }\n }\n }\n }\n }\n\n this._extractFromTree(\n child, source, language, filePath, nodes, edges,\n enclosingClass, name, importMap, definedNames, depth + 1,\n );\n continue;\n }\n }\n\n // --- Imports ---\n if (importTypes.has(nodeType)) {\n const imports = this._extractImport(child, language);\n for (const impTarget of imports) {\n edges.push({\n kind: 'IMPORTS_FROM',\n source: filePath,\n target: impTarget,\n filePath,\n line: child.startPosition.row + 1,\n });\n }\n continue;\n }\n\n // --- Calls ---\n if (callTypes.has(nodeType)) {\n const callName = this._getCallName(child, language);\n if (callName && enclosingFunc) {\n const caller = this._qualify(enclosingFunc, filePath, enclosingClass ?? null);\n const target = this._resolveCallTarget(\n callName, filePath, language,\n importMap ?? new Map(), definedNames ?? new Set(),\n );\n edges.push({\n kind: 'CALLS',\n source: caller,\n target,\n filePath,\n line: child.startPosition.row + 1,\n });\n }\n }\n\n // --- Solidity-specific constructs ---\n if (language === 'solidity') {\n // emit statements → CALLS edges\n if (nodeType === 'emit_statement' && enclosingFunc) {\n for (const sub of child.children) {\n if (sub.type === 'expression') {\n for (const ident of sub.children) {\n if (ident.type === 'identifier') {\n const caller = this._qualify(\n enclosingFunc, filePath, enclosingClass ?? null,\n );\n edges.push({\n kind: 'CALLS',\n source: caller,\n target: ident.text,\n filePath,\n line: child.startPosition.row + 1,\n });\n }\n }\n }\n }\n }\n\n // State variable declarations → Function nodes\n if (nodeType === 'state_variable_declaration' && enclosingClass) {\n let varName: string | null = null;\n let varVisibility: string | null = null;\n let varType: string | null = null;\n let varMutability: string | null = null;\n\n for (const sub of child.children) {\n if (sub.type === 'identifier') { varName = sub.text; }\n else if (sub.type === 'visibility') { varVisibility = sub.text; }\n else if (sub.type === 'type_name') { varType = sub.text; }\n else if (sub.type === 'constant' || sub.type === 'immutable') {\n varMutability = sub.type;\n }\n }\n if (varName) {\n const qualified = this._qualify(varName, filePath, enclosingClass);\n nodes.push({\n kind: 'Function',\n name: varName,\n filePath,\n lineStart: child.startPosition.row + 1,\n lineEnd: child.endPosition.row + 1,\n language,\n parentName: enclosingClass,\n returnType: varType,\n modifiers: varVisibility,\n extra: { solidity_kind: 'state_variable', mutability: varMutability },\n });\n edges.push({\n kind: 'CONTAINS',\n source: this._qualify(enclosingClass, filePath, null),\n target: qualified,\n filePath,\n line: child.startPosition.row + 1,\n });\n continue;\n }\n }\n\n // Constant variable declarations\n if (nodeType === 'constant_variable_declaration') {\n let varName: string | null = null;\n let varType: string | null = null;\n for (const sub of child.children) {\n if (sub.type === 'identifier') { varName = sub.text; }\n else if (sub.type === 'type_name') { varType = sub.text; }\n }\n if (varName) {\n const qualified = this._qualify(varName, filePath, enclosingClass ?? null);\n nodes.push({\n kind: 'Function',\n name: varName,\n filePath,\n lineStart: child.startPosition.row + 1,\n lineEnd: child.endPosition.row + 1,\n language,\n parentName: enclosingClass ?? null,\n returnType: varType,\n extra: { solidity_kind: 'constant' },\n });\n const container = enclosingClass\n ? this._qualify(enclosingClass, filePath, null)\n : filePath;\n edges.push({\n kind: 'CONTAINS',\n source: container,\n target: qualified,\n filePath,\n line: child.startPosition.row + 1,\n });\n continue;\n }\n }\n\n // Using directives → DEPENDS_ON edge\n if (nodeType === 'using_directive') {\n let libName: string | null = null;\n for (const sub of child.children) {\n if (sub.type === 'type_alias') {\n for (const ident of sub.children) {\n if (ident.type === 'identifier') { libName = ident.text; break; }\n }\n }\n }\n if (libName) {\n const sourceName = enclosingClass\n ? this._qualify(enclosingClass, filePath, null)\n : filePath;\n edges.push({\n kind: 'DEPENDS_ON',\n source: sourceName,\n target: libName,\n filePath,\n line: child.startPosition.row + 1,\n });\n }\n continue;\n }\n }\n\n // Recurse for other node types\n this._extractFromTree(\n child, source, language, filePath, nodes, edges,\n enclosingClass, enclosingFunc, importMap, definedNames, depth + 1,\n );\n }\n }\n\n private _collectFileScope(\n root: SyntaxNode,\n language: string,\n source: Buffer,\n ): [Map<string, string>, Set<string>] {\n const importMap = new Map<string, string>();\n const definedNames = new Set<string>();\n\n const classTypes = new Set(CLASS_TYPES[language] ?? []);\n const funcTypes = new Set(FUNCTION_TYPES[language] ?? []);\n const importTypes = new Set(IMPORT_TYPES[language] ?? []);\n const decoratorWrappers = new Set(['decorated_definition', 'decorator']);\n\n for (const child of root.children) {\n const nodeType: string = child.type;\n\n // Unwrap decorator wrappers\n let target = child;\n if (decoratorWrappers.has(nodeType)) {\n for (const inner of child.children) {\n if (funcTypes.has(inner.type) || classTypes.has(inner.type)) {\n target = inner;\n break;\n }\n }\n }\n\n const targetType: string = target.type;\n\n if (funcTypes.has(targetType) || classTypes.has(targetType)) {\n const name = this._getName(\n target, language, classTypes.has(targetType) ? 'class' : 'function',\n );\n if (name) { definedNames.add(name); }\n }\n\n if (importTypes.has(nodeType)) {\n this._collectImportNames(child, language, source, importMap);\n }\n }\n\n return [importMap, definedNames];\n }\n\n private _collectImportNames(\n node: SyntaxNode,\n language: string,\n _source: Buffer,\n importMap: Map<string, string>,\n ): void {\n if (language === 'python') {\n if (node.type === 'import_from_statement') {\n let module: string | null = null;\n let seenImport = false;\n for (const child of node.children) {\n if (child.type === 'dotted_name' && !seenImport) {\n module = child.text;\n } else if (child.type === 'import') {\n seenImport = true;\n } else if (seenImport && module) {\n if (child.type === 'identifier' || child.type === 'dotted_name') {\n importMap.set(child.text, module);\n } else if (child.type === 'aliased_import') {\n const names = child.children\n .filter((c: SyntaxNode) =>\n c.type === 'identifier' || c.type === 'dotted_name'\n )\n .map((c: SyntaxNode) => c.text as string);\n if (names.length > 0) { importMap.set(names[names.length - 1]!, module); }\n }\n }\n }\n }\n } else if (language === 'javascript' || language === 'typescript' || language === 'tsx') {\n let module: string | null = null;\n for (const child of node.children) {\n if (child.type === 'string') {\n module = (child.text as string).replace(/^['\"]|['\"]$/g, '');\n }\n }\n if (module) {\n for (const child of node.children) {\n if (child.type === 'import_clause') {\n this._collectJsImportNames(child, module, importMap);\n }\n }\n }\n }\n }\n\n private _collectJsImportNames(\n clauseNode: SyntaxNode,\n module: string,\n importMap: Map<string, string>,\n ): void {\n for (const child of clauseNode.children) {\n if (child.type === 'identifier') {\n importMap.set(child.text, module);\n } else if (child.type === 'named_imports') {\n for (const spec of child.children) {\n if (spec.type === 'import_specifier') {\n const names = spec.children\n .filter((s: SyntaxNode) =>\n s.type === 'identifier' || s.type === 'property_identifier'\n )\n .map((s: SyntaxNode) => s.text as string);\n if (names.length > 0) { importMap.set(names[names.length - 1]!, module); }\n }\n }\n }\n }\n }\n\n private _resolveModuleToFile(\n module: string,\n filePath: string,\n language: string,\n ): string | null {\n const callerDir = path.dirname(filePath);\n const cacheKey = `${language}:${callerDir}:${module}`;\n if (this.moduleFileCache.has(cacheKey)) {\n return this.moduleFileCache.get(cacheKey) ?? null;\n }\n\n const resolved = this._doResolveModule(module, filePath, language);\n if (this.moduleFileCache.size >= MODULE_CACHE_MAX) {\n this.moduleFileCache.clear();\n }\n this.moduleFileCache.set(cacheKey, resolved);\n return resolved;\n }\n\n private _doResolveModule(\n module: string,\n filePath: string,\n language: string,\n ): string | null {\n const callerDir = path.dirname(filePath);\n\n if (language === 'python') {\n const relPath = module.replace(/\\./g, '/');\n const candidates = [`${relPath}.py`, `${relPath}/__init__.py`];\n let current = callerDir;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n for (const candidate of candidates) {\n const target = path.join(current, candidate);\n if (fs.existsSync(target)) { return path.resolve(target); }\n }\n const parent = path.dirname(current);\n if (parent === current) { break; }\n current = parent;\n }\n } else if (\n language === 'javascript' || language === 'typescript' ||\n language === 'tsx' || language === 'vue'\n ) {\n if (module.startsWith('.')) {\n const base = path.join(callerDir, module);\n const extensions = ['.ts', '.tsx', '.js', '.jsx', '.vue'];\n if (fs.existsSync(base) && fs.statSync(base).isFile()) {\n return path.resolve(base);\n }\n for (const ext of extensions) {\n const target = base + ext;\n if (fs.existsSync(target)) { return path.resolve(target); }\n }\n // Try index file in directory\n if (fs.existsSync(base) && fs.statSync(base).isDirectory()) {\n for (const ext of extensions) {\n const target = path.join(base, `index${ext}`);\n if (fs.existsSync(target)) { return path.resolve(target); }\n }\n }\n }\n }\n\n return null;\n }\n\n private _resolveCallTarget(\n callName: string,\n filePath: string,\n language: string,\n importMap: Map<string, string>,\n definedNames: Set<string>,\n ): string {\n if (definedNames.has(callName)) {\n return this._qualify(callName, filePath, null);\n }\n const importedFrom = importMap.get(callName);\n if (importedFrom) {\n const resolved = this._resolveModuleToFile(importedFrom, filePath, language);\n if (resolved) { return this._qualify(callName, resolved, null); }\n }\n return callName;\n }\n\n private _qualify(name: string, filePath: string, enclosingClass: string | null): string {\n if (enclosingClass) { return `${filePath}::${enclosingClass}.${name}`; }\n return `${filePath}::${name}`;\n }\n\n private _getName(node: SyntaxNode, language: string, kind: string): string | null {\n // Solidity: constructor and receive/fallback have no identifier child\n if (language === 'solidity') {\n if (node.type === 'constructor_definition') { return 'constructor'; }\n if (node.type === 'fallback_receive_definition') {\n for (const child of node.children) {\n if (child.type === 'receive' || child.type === 'fallback') {\n return child.text;\n }\n }\n }\n }\n\n // C/C++: function names are inside function_declarator/pointer_declarator\n if ((language === 'c' || language === 'cpp') && kind === 'function') {\n for (const child of node.children) {\n if (child.type === 'function_declarator' || child.type === 'pointer_declarator') {\n const result = this._getName(child, language, kind);\n if (result) { return result; }\n }\n }\n }\n\n // Most languages: look for identifier child\n for (const child of node.children) {\n if ([\n 'identifier', 'name', 'type_identifier', 'property_identifier',\n 'simple_identifier', 'constant',\n ].includes(child.type)) {\n return child.text;\n }\n }\n\n // Go type declarations: look for type_spec\n if (language === 'go' && node.type === 'type_declaration') {\n for (const child of node.children) {\n if (child.type === 'type_spec') {\n return this._getName(child, language, kind);\n }\n }\n }\n\n return null;\n }\n\n private _getParams(node: SyntaxNode, language: string): string | null {\n for (const child of node.children) {\n if (['parameters', 'formal_parameters', 'parameter_list'].includes(child.type)) {\n return child.text;\n }\n }\n if (language === 'solidity') {\n const params = node.children\n .filter((c: SyntaxNode) => c.type === 'parameter')\n .map((c: SyntaxNode) => c.text as string);\n if (params.length > 0) { return `(${params.join(', ')})`; }\n }\n return null;\n }\n\n private _getReturnType(node: SyntaxNode, language: string): string | null {\n for (const child of node.children) {\n if ([\n 'type', 'return_type', 'type_annotation', 'return_type_definition',\n ].includes(child.type)) {\n return child.text;\n }\n }\n if (language === 'python') {\n for (let i = 0; i < node.children.length - 1; i++) {\n if (node.children[i].type === '->') {\n return node.children[i + 1].text;\n }\n }\n }\n return null;\n }\n\n private _getBases(node: SyntaxNode, language: string): string[] {\n const bases: string[] = [];\n\n if (language === 'python') {\n for (const child of node.children) {\n if (child.type === 'argument_list') {\n for (const arg of child.children) {\n if (arg.type === 'identifier' || arg.type === 'attribute') {\n bases.push(arg.text);\n }\n }\n }\n }\n } else if (\n language === 'java' || language === 'csharp' || language === 'kotlin'\n ) {\n for (const child of node.children) {\n if ([\n 'superclass', 'super_interfaces', 'extends_type', 'implements_type',\n 'type_identifier', 'supertype', 'delegation_specifier',\n ].includes(child.type)) {\n bases.push(child.text);\n }\n }\n } else if (language === 'cpp') {\n for (const child of node.children) {\n if (child.type === 'base_class_clause') {\n for (const sub of child.children) {\n if (sub.type === 'type_identifier') { bases.push(sub.text); }\n }\n }\n }\n } else if (\n language === 'typescript' || language === 'javascript' || language === 'tsx'\n ) {\n for (const child of node.children) {\n if (child.type === 'extends_clause' || child.type === 'implements_clause') {\n for (const sub of child.children) {\n if ([\n 'identifier', 'type_identifier', 'nested_identifier',\n ].includes(sub.type)) {\n bases.push(sub.text);\n }\n }\n }\n }\n } else if (language === 'solidity') {\n for (const child of node.children) {\n if (child.type === 'inheritance_specifier') {\n for (const sub of child.children) {\n if (sub.type === 'user_defined_type') {\n for (const ident of sub.children) {\n if (ident.type === 'identifier') { bases.push(ident.text); }\n }\n }\n }\n }\n }\n } else if (language === 'go') {\n for (const child of node.children) {\n if (child.type === 'type_spec') {\n for (const sub of child.children) {\n if (sub.type === 'struct_type' || sub.type === 'interface_type') {\n for (const fieldNode of sub.children) {\n if (fieldNode.type === 'field_declaration_list') {\n for (const f of fieldNode.children) {\n if (f.type === 'type_identifier') { bases.push(f.text); }\n }\n }\n }\n }\n }\n }\n }\n }\n\n return bases;\n }\n\n private _extractImport(node: SyntaxNode, language: string): string[] {\n const imports: string[] = [];\n const text: string = node.text.trim();\n\n if (language === 'python') {\n if (node.type === 'import_from_statement') {\n for (const child of node.children) {\n if (child.type === 'dotted_name') {\n imports.push(child.text);\n break;\n }\n }\n } else {\n for (const child of node.children) {\n if (child.type === 'dotted_name') { imports.push(child.text); }\n }\n }\n } else if (\n language === 'javascript' || language === 'typescript' || language === 'tsx'\n ) {\n for (const child of node.children) {\n if (child.type === 'string') {\n imports.push((child.text as string).replace(/^['\"]|['\"]$/g, ''));\n }\n }\n } else if (language === 'go') {\n for (const child of node.children) {\n if (child.type === 'import_spec_list') {\n for (const spec of child.children) {\n if (spec.type === 'import_spec') {\n for (const s of spec.children) {\n if (s.type === 'interpreted_string_literal') {\n imports.push((s.text as string).replace(/^\"|\"$/g, ''));\n }\n }\n }\n }\n } else if (child.type === 'import_spec') {\n for (const s of child.children) {\n if (s.type === 'interpreted_string_literal') {\n imports.push((s.text as string).replace(/^\"|\"$/g, ''));\n }\n }\n }\n }\n } else if (language === 'rust') {\n imports.push(text.replace(/^use\\s+/, '').replace(/;$/, '').trim());\n } else if (language === 'c' || language === 'cpp') {\n for (const child of node.children) {\n if (child.type === 'system_lib_string' || child.type === 'string_literal') {\n imports.push((child.text as string).replace(/^[<\"\"]|[>\"\"]$/g, ''));\n }\n }\n } else if (language === 'java' || language === 'csharp') {\n const parts = text.split(/\\s+/);\n if (parts.length >= 2) {\n imports.push(parts[parts.length - 1]!.replace(/;$/, ''));\n }\n } else if (language === 'solidity') {\n for (const child of node.children) {\n if (child.type === 'string') {\n const val = (child.text as string).replace(/^\"|\"$/g, '');\n if (val) { imports.push(val); }\n }\n }\n } else if (language === 'ruby') {\n if (text.includes('require')) {\n const match = /['\"]([^'\"]+)['\"]/u.exec(text);\n if (match) { imports.push(match[1]!); }\n }\n } else {\n imports.push(text);\n }\n\n return imports;\n }\n\n private _getCallName(node: SyntaxNode, language: string): string | null {\n if (!node.children || node.children.length === 0) { return null; }\n\n let first: SyntaxNode = node.children[0];\n\n // Solidity wraps call targets in 'expression' — unwrap\n if (\n language === 'solidity' &&\n first.type === 'expression' &&\n first.children.length > 0\n ) {\n first = first.children[0];\n }\n\n if (first.type === 'identifier') { return first.text; }\n\n const memberTypes = [\n 'attribute', 'member_expression', 'field_expression', 'selector_expression',\n ];\n if (memberTypes.includes(first.type)) {\n for (let i = first.children.length - 1; i >= 0; i--) {\n const child: SyntaxNode = first.children[i];\n if ([\n 'identifier', 'property_identifier', 'field_identifier', 'field_name',\n ].includes(child.type)) {\n return child.text;\n }\n }\n return first.text;\n }\n\n if (first.type === 'scoped_identifier' || first.type === 'qualified_name') {\n return first.text;\n }\n\n return null;\n }\n}\n\n// Canonical export alias matching the file name\nexport { CodeParser as TreeSitterParser }\n","/**\n * SQLite-backed embedding store.\n *\n * Extracted from embeddings.ts::EmbeddingStore + helper functions.\n * Implements IEmbeddingStore.\n */\n\nimport crypto from 'node:crypto'\nimport Database from 'better-sqlite3'\nimport type { GraphNode } from '../domain/types.js'\nimport type { IEmbeddingStore } from '../domain/ports/IEmbeddingStore.js'\nimport type { IEmbeddingProvider } from '../domain/ports/IEmbeddingProvider.js'\nimport { LocalEmbeddingProvider } from './LocalEmbeddingProvider.js'\nimport { GoogleEmbeddingProvider } from './GoogleEmbeddingProvider.js'\n\n// ---------------------------------------------------------------------------\n// Schema\n// ---------------------------------------------------------------------------\n\nconst EMBEDDINGS_SCHEMA = `\nCREATE TABLE IF NOT EXISTS embeddings (\n qualified_name TEXT PRIMARY KEY,\n vector BLOB NOT NULL,\n text_hash TEXT NOT NULL,\n provider TEXT NOT NULL DEFAULT 'unknown'\n);\n`\n\n// ---------------------------------------------------------------------------\n// Vector helpers\n// ---------------------------------------------------------------------------\n\nfunction encodeVector(vec: number[]): Buffer {\n const buf = Buffer.allocUnsafe(vec.length * 4)\n for (let i = 0; i < vec.length; i++) buf.writeFloatLE(vec[i]!, i * 4)\n return buf\n}\n\nfunction decodeVector(blob: Buffer): number[] {\n const n = blob.length / 4\n const result: number[] = new Array(n)\n for (let i = 0; i < n; i++) result[i] = blob.readFloatLE(i * 4)\n return result\n}\n\nfunction cosineSimilarity(a: number[], b: number[]): number {\n if (a.length !== b.length) return 0\n let dot = 0, normA = 0, normB = 0\n for (let i = 0; i < a.length; i++) {\n dot += a[i]! * b[i]!\n normA += a[i]! * a[i]!\n normB += b[i]! * b[i]!\n }\n if (normA === 0 || normB === 0) return 0\n return dot / (Math.sqrt(normA) * Math.sqrt(normB))\n}\n\nexport function nodeToText(node: GraphNode): string {\n const parts = [node.name]\n if (node.kind !== 'File') parts.push(node.kind.toLowerCase())\n if (node.parentName) parts.push(`in ${node.parentName}`)\n if (node.params) parts.push(node.params)\n if (node.returnType) parts.push(`returns ${node.returnType}`)\n if (node.language) parts.push(node.language)\n return parts.join(' ')\n}\n\n// ---------------------------------------------------------------------------\n// Provider factory\n// ---------------------------------------------------------------------------\n\nexport function getProvider(provider?: string | null): IEmbeddingProvider | null {\n if (provider === 'google') {\n const apiKey = process.env['GOOGLE_API_KEY']\n if (!apiKey) return null\n try { return new GoogleEmbeddingProvider(apiKey) } catch { return null }\n }\n return new LocalEmbeddingProvider()\n}\n\n// ---------------------------------------------------------------------------\n// SqliteEmbeddingStore\n// ---------------------------------------------------------------------------\n\nexport class SqliteEmbeddingStore implements IEmbeddingStore {\n private _db: Database.Database\n readonly available: boolean\n private _provider: IEmbeddingProvider | null\n\n constructor(dbPath: string, provider?: string | null) {\n this._db = new Database(dbPath)\n this._db.exec(EMBEDDINGS_SCHEMA)\n\n try {\n this._db.prepare('SELECT provider FROM embeddings LIMIT 1').get()\n } catch {\n this._db.exec(\n \"ALTER TABLE embeddings ADD COLUMN provider TEXT NOT NULL DEFAULT 'unknown'\",\n )\n }\n\n this._provider = getProvider(provider)\n this.available = this._provider !== null\n }\n\n count(): number {\n const row = this._db\n .prepare('SELECT COUNT(*) AS cnt FROM embeddings')\n .get() as { cnt: number }\n return row.cnt\n }\n\n async embedNodes(nodes: GraphNode[], batchSize = 64): Promise<number> {\n if (!this._provider) return 0\n const providerName = this._provider.name\n\n const toEmbed: Array<{ node: GraphNode; text: string; textHash: string }> = []\n for (const node of nodes) {\n if (node.kind === 'File') continue\n const text = nodeToText(node)\n const textHash = crypto.createHash('sha256').update(text).digest('hex')\n const existing = this._db\n .prepare('SELECT text_hash, provider FROM embeddings WHERE qualified_name = ?')\n .get(node.qualifiedName) as { text_hash: string; provider: string } | undefined\n if (existing && existing.text_hash === textHash && existing.provider === providerName) {\n continue\n }\n toEmbed.push({ node, text, textHash })\n }\n\n if (toEmbed.length === 0) return 0\n\n const insert = this._db.prepare(\n 'INSERT OR REPLACE INTO embeddings (qualified_name, vector, text_hash, provider) VALUES (?, ?, ?, ?)',\n )\n\n for (let i = 0; i < toEmbed.length; i += batchSize) {\n const batch = toEmbed.slice(i, i + batchSize)\n const vectors = await this._provider.embed(batch.map((b) => b.text))\n this._db.transaction(() => {\n for (let j = 0; j < batch.length; j++) {\n const { node, textHash } = batch[j]!\n insert.run(node.qualifiedName, encodeVector(vectors[j]!), textHash, providerName)\n }\n })()\n }\n\n return toEmbed.length\n }\n\n async search(\n query: string,\n limit = 20,\n ): Promise<Array<{ qualifiedName: string; score: number }>> {\n if (!this._provider) return []\n const providerName = this._provider.name\n const queryVec = await this._provider.embedQuery(query)\n\n const rows = this._db\n .prepare('SELECT qualified_name, vector FROM embeddings WHERE provider = ?')\n .all(providerName) as Array<{ qualified_name: string; vector: Buffer }>\n\n const scored = rows.map((row) => ({\n qualifiedName: row.qualified_name,\n score: cosineSimilarity(queryVec, decodeVector(row.vector)),\n }))\n\n scored.sort((a, b) => b.score - a.score)\n return scored.slice(0, limit)\n }\n\n removeNode(qualifiedName: string): void {\n this._db\n .prepare('DELETE FROM embeddings WHERE qualified_name = ?')\n .run(qualifiedName)\n }\n\n close(): void {\n this._db.close()\n }\n}\n\n// Backward-compat alias\nexport { SqliteEmbeddingStore as EmbeddingStore }\n","/**\n * Local HuggingFace embedding provider.\n *\n * Extracted from embeddings.ts::LocalEmbeddingProvider.\n */\n\nimport type { IEmbeddingProvider } from '../domain/ports/IEmbeddingProvider.js'\n\nconst NOMIC_MODEL = 'Xenova/nomic-embed-text-v1.5'\nconst MINILM_MODEL = 'Xenova/all-MiniLM-L6-v2'\n\nexport class LocalEmbeddingProvider implements IEmbeddingProvider {\n private _pipelinePromise: Promise<unknown> | null = null\n private readonly _model: string\n private readonly _dim: number\n\n constructor() {\n const hasToken = !!(process.env['HF_TOKEN'] ?? process.env['CODEORBIT_HF_TOKEN'])\n this._model = hasToken ? NOMIC_MODEL : MINILM_MODEL\n this._dim = hasToken ? 768 : 384\n }\n\n private _getPipeline(): Promise<unknown> {\n if (!this._pipelinePromise) {\n const model = this._model\n this._pipelinePromise = import('@huggingface/transformers').then((mod) => {\n const { pipeline, env } = mod as Record<string, unknown> & {\n env: Record<string, unknown>\n pipeline: (task: string, model: string) => Promise<unknown>\n }\n const hfToken = process.env['HF_TOKEN'] ?? process.env['CODEORBIT_HF_TOKEN']\n if (hfToken) env['token'] = hfToken\n return pipeline('feature-extraction', model)\n })\n }\n return this._pipelinePromise\n }\n\n async embed(texts: string[]): Promise<number[][]> {\n const pipe = (await this._getPipeline()) as (\n inputs: string[],\n opts: Record<string, unknown>,\n ) => Promise<{ data: Float32Array; dims: number[] }>\n const inputs =\n this._model === NOMIC_MODEL ? texts.map((t) => `search_document: ${t}`) : texts\n const output = await pipe(inputs, { pooling: 'mean', normalize: true })\n const dim = this._dim\n return Array.from({ length: texts.length }, (_, i) =>\n Array.from(output.data.subarray(i * dim, (i + 1) * dim)),\n )\n }\n\n async embedQuery(text: string): Promise<number[]> {\n const pipe = (await this._getPipeline()) as (\n inputs: string[],\n opts: Record<string, unknown>,\n ) => Promise<{ data: Float32Array }>\n const input = this._model === NOMIC_MODEL ? `search_query: ${text}` : text\n const output = await pipe([input], { pooling: 'mean', normalize: true })\n return Array.from(output.data)\n }\n\n get dimension(): number { return this._dim }\n\n get name(): string { return `local:${this._model.split('/')[1]}` }\n}\n","/**\n * Google Gemini embedding provider.\n *\n * Extracted from embeddings.ts::GoogleEmbeddingProvider.\n */\n\nimport { createRequire } from 'node:module'\nimport type { IEmbeddingProvider } from '../domain/ports/IEmbeddingProvider.js'\n\nconst _require = createRequire(import.meta.url)\n\nexport class GoogleEmbeddingProvider implements IEmbeddingProvider {\n private _model: {\n embedContent(req: unknown): Promise<{ embedding: { values: number[] } }>\n batchEmbedContents(req: unknown): Promise<{ embeddings: Array<{ values: number[] }> }>\n }\n private _dimension: number | null = null\n readonly modelName: string\n\n constructor(apiKey: string, model = 'gemini-embedding-001') {\n this.modelName = model\n const { GoogleGenerativeAI } = _require('@google/generative-ai') as {\n GoogleGenerativeAI: new (key: string) => {\n getGenerativeModel(opts: { model: string }): unknown\n }\n }\n const genAI = new GoogleGenerativeAI(apiKey)\n this._model = genAI.getGenerativeModel({ model }) as typeof this._model\n }\n\n private async _withRetry<T>(fn: () => Promise<T>, maxRetries = 3): Promise<T> {\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n try {\n return await fn()\n } catch (e) {\n const msg = String(e)\n const retryable = msg.includes('429') || msg.includes('500') || msg.includes('503')\n if (!retryable || attempt === maxRetries - 1) throw e\n await new Promise((r) => setTimeout(r, 2 ** attempt * 1000))\n }\n }\n throw new Error('unreachable')\n }\n\n async embed(texts: string[]): Promise<number[][]> {\n const batchSize = 100\n const results: number[][] = []\n for (let i = 0; i < texts.length; i += batchSize) {\n const batch = texts.slice(i, i + batchSize)\n const response = await this._withRetry(() =>\n this._model.batchEmbedContents({\n requests: batch.map((t) => ({\n content: { parts: [{ text: t }], role: 'user' },\n taskType: 'RETRIEVAL_DOCUMENT',\n })),\n }),\n )\n results.push(...response.embeddings.map((e) => e.values))\n }\n if (this._dimension === null && results.length > 0) {\n this._dimension = results[0]!.length\n }\n return results\n }\n\n async embedQuery(text: string): Promise<number[]> {\n const response = await this._withRetry(() =>\n this._model.embedContent({\n content: { parts: [{ text }], role: 'user' },\n taskType: 'RETRIEVAL_QUERY',\n }),\n )\n const vec = response.embedding.values\n if (this._dimension === null) this._dimension = vec.length\n return vec\n }\n\n get dimension(): number { return this._dimension ?? 768 }\n\n get name(): string { return `google:${this.modelName}` }\n}\n","/**\n * File-system infrastructure helpers.\n *\n * Extracted from incremental.ts: findRepoRoot, findProjectRoot, getDbPath,\n * loadIgnorePatterns, shouldIgnore, isBinary, walkDir, collectAllFiles.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport micromatch from 'micromatch'\nimport { CodeParser } from './TreeSitterParser.js'\nimport { getAllTrackedFiles } from './GitRunner.js'\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nexport const DEFAULT_IGNORE_PATTERNS = [\n '.codeorbit/**',\n 'node_modules/**',\n '.git/**',\n '__pycache__/**',\n '*.pyc',\n '.venv/**',\n 'venv/**',\n 'dist/**',\n 'build/**',\n '.next/**',\n 'target/**',\n '*.min.js',\n '*.min.css',\n '*.map',\n '*.lock',\n 'package-lock.json',\n 'yarn.lock',\n '*.db',\n '*.sqlite',\n '*.db-journal',\n '*.db-wal',\n]\n\nexport const PRUNE_DIRS = new Set([\n 'node_modules', '.git', '__pycache__', '.next', '.nuxt', '.svelte-kit',\n 'dist', 'build', '.venv', 'venv', 'env', 'target', '.mypy_cache',\n '.pytest_cache', 'coverage', '.tox', '.cache', '.tmp', 'tmp', 'temp',\n 'vendor', 'Pods', 'DerivedData', '.gradle', '.idea', '.vs',\n])\n\nexport const DEBOUNCE_MS = 300\n\n// ---------------------------------------------------------------------------\n// Repo / DB path discovery\n// ---------------------------------------------------------------------------\n\nexport function findRepoRoot(start?: string): string | undefined {\n let current = start ?? process.cwd()\n while (true) {\n if (fs.existsSync(path.join(current, '.git'))) {\n return current\n }\n const parent = path.dirname(current)\n if (parent === current) { break }\n current = parent\n }\n return undefined\n}\n\nexport function findProjectRoot(start?: string): string {\n return findRepoRoot(start) ?? start ?? process.cwd()\n}\n\nexport function getDbPath(repoRoot: string): string {\n const crgDir = path.join(repoRoot, '.codeorbit')\n const newDb = path.join(crgDir, 'graph.db')\n\n if (!fs.existsSync(crgDir)) {\n fs.mkdirSync(crgDir, { recursive: true })\n }\n\n const innerGitignore = path.join(crgDir, '.gitignore')\n if (!fs.existsSync(innerGitignore)) {\n fs.writeFileSync(\n innerGitignore,\n '# Auto-generated by codeorbit — do not commit database files.\\n' +\n '# The graph.db contains absolute paths and code structure metadata.\\n' +\n '*\\n',\n )\n }\n\n const legacyDb = path.join(repoRoot, '.codeorbit.db')\n if (fs.existsSync(legacyDb) && !fs.existsSync(newDb)) {\n fs.renameSync(legacyDb, newDb)\n }\n for (const suffix of ['-wal', '-shm', '-journal']) {\n const side = legacyDb + suffix\n if (fs.existsSync(side)) {\n try { fs.unlinkSync(side) } catch { /* ignore */ }\n }\n }\n\n return newDb\n}\n\n// ---------------------------------------------------------------------------\n// Ignore patterns\n// ---------------------------------------------------------------------------\n\nexport function loadIgnorePatterns(repoRoot: string): string[] {\n const patterns = [...DEFAULT_IGNORE_PATTERNS]\n const ignoreFile = path.join(repoRoot, '.codeorbitignore')\n if (fs.existsSync(ignoreFile)) {\n for (const line of fs.readFileSync(ignoreFile, 'utf-8').split('\\n')) {\n const trimmed = line.trim()\n if (trimmed && !trimmed.startsWith('#')) {\n patterns.push(trimmed)\n }\n }\n }\n return patterns\n}\n\nexport function shouldIgnore(filePath: string, patterns: string[]): boolean {\n return micromatch.isMatch(filePath, patterns)\n}\n\nexport function isBinary(filePath: string): boolean {\n try {\n const chunk = Buffer.alloc(8192)\n const fd = fs.openSync(filePath, 'r')\n const bytesRead = fs.readSync(fd, chunk, 0, 8192, 0)\n fs.closeSync(fd)\n return chunk.slice(0, bytesRead).includes(0)\n } catch {\n return true\n }\n}\n\n// ---------------------------------------------------------------------------\n// File collection\n// ---------------------------------------------------------------------------\n\nfunction walkDir(dir: string, repoRoot: string): string[] {\n const files: string[] = []\n const entries = fs.readdirSync(dir, { withFileTypes: true })\n for (const entry of entries) {\n if (entry.isDirectory()) {\n if (PRUNE_DIRS.has(entry.name)) { continue }\n files.push(...walkDir(path.join(dir, entry.name), repoRoot))\n } else if (entry.isFile()) {\n const rel = path.relative(repoRoot, path.join(dir, entry.name))\n files.push(rel)\n }\n }\n return files\n}\n\nexport function collectAllFiles(repoRoot: string): string[] {\n const ignorePatterns = loadIgnorePatterns(repoRoot)\n const parser = new CodeParser()\n const files: string[] = []\n\n const tracked = getAllTrackedFiles(repoRoot)\n const candidates = tracked.length > 0 ? tracked : walkDir(repoRoot, repoRoot)\n\n for (const relPath of candidates) {\n if (shouldIgnore(relPath, ignorePatterns)) { continue }\n const fullPath = path.join(repoRoot, relPath)\n\n let stat: fs.Stats\n try {\n stat = fs.lstatSync(fullPath)\n } catch {\n continue\n }\n\n if (!stat.isFile() || stat.isSymbolicLink()) { continue }\n if (!parser.detectLanguage(fullPath)) { continue }\n if (isBinary(fullPath)) { continue }\n files.push(relPath)\n }\n\n return files\n}\n","/**\n * Git operations infrastructure.\n *\n * Extracted from incremental.ts: gitRun, getChangedFiles, getStagedAndUnstaged,\n * getAllTrackedFiles.\n */\n\nimport { spawnSync } from 'node:child_process'\n\nexport const GIT_TIMEOUT_MS = Number(process.env['CRG_GIT_TIMEOUT'] ?? 30) * 1000\n\nfunction gitRun(args: string[], cwd: string): string {\n const result = spawnSync('git', args, {\n cwd,\n encoding: 'utf-8',\n timeout: GIT_TIMEOUT_MS,\n stdio: ['ignore', 'pipe', 'ignore'],\n })\n if (result.error || result.status !== 0) {\n return ''\n }\n return result.stdout ?? ''\n}\n\nexport function getChangedFiles(repoRoot: string, base = 'HEAD~1'): string[] {\n let output = gitRun(['diff', '--name-only', base], repoRoot)\n if (!output.trim()) {\n output = gitRun(['diff', '--name-only', '--cached'], repoRoot)\n }\n return output\n .split('\\n')\n .map((f) => f.trim())\n .filter(Boolean)\n}\n\nexport function getStagedAndUnstaged(repoRoot: string): string[] {\n const output = gitRun(['status', '--porcelain'], repoRoot)\n const files: string[] = []\n for (const line of output.split('\\n')) {\n if (line.length > 3) {\n let entry = line.slice(3).trim()\n if (entry.includes(' -> ')) {\n entry = entry.split(' -> ')[1]!\n }\n files.push(entry)\n }\n }\n return files\n}\n\nexport function getAllTrackedFiles(repoRoot: string): string[] {\n const output = gitRun(['ls-files'], repoRoot)\n return output\n .split('\\n')\n .map((f) => f.trim())\n .filter(Boolean)\n}\n","/**\n * Use cases: full build and incremental update of the knowledge graph.\n *\n * Extracted from incremental.ts (fullBuild, incrementalUpdate, findDependents)\n * + tools.ts (buildOrUpdateGraph).\n *\n * Accepts IParser and IGraphRepository as parameters for testability.\n * Imports file-system and git utilities from infrastructure.\n */\n\nimport crypto from 'node:crypto'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport type { BuildResult } from '../domain/types.js'\nimport type { IParser } from '../domain/ports/IParser.js'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport {\n collectAllFiles,\n loadIgnorePatterns,\n shouldIgnore,\n} from '../infrastructure/FileSystemHelper.js'\nimport { getChangedFiles } from '../infrastructure/GitRunner.js'\n\n// ---------------------------------------------------------------------------\n// Full build\n// ---------------------------------------------------------------------------\n\nexport function fullBuild(\n repoRoot: string,\n repo: IGraphRepository,\n parser: IParser,\n): BuildResult {\n const files = collectAllFiles(repoRoot)\n\n // Purge stale data\n const existingFiles = new Set(repo.getAllFiles())\n const currentAbs = new Set(files.map((f) => path.join(repoRoot, f)))\n for (const stale of existingFiles) {\n if (!currentAbs.has(stale)) {\n repo.removeFileData(stale)\n }\n }\n\n let totalNodes = 0\n let totalEdges = 0\n const errors: string[] = []\n\n for (let i = 0; i < files.length; i++) {\n const relPath = files[i]!\n const fullPath = path.join(repoRoot, relPath)\n try {\n const source = fs.readFileSync(fullPath)\n const fhash = crypto.createHash('sha256').update(source).digest('hex')\n const [nodes, edges] = parser.parseBytes(fullPath, source)\n repo.storeFileNodesEdges(fullPath, nodes, edges, fhash)\n totalNodes += nodes.length\n totalEdges += edges.length\n } catch (err) {\n errors.push(`${relPath}: ${String(err)}`)\n }\n if ((i + 1) % 50 === 0 || i + 1 === files.length) {\n process.stderr.write(`Progress: ${i + 1}/${files.length} files parsed\\n`)\n }\n }\n\n repo.setMetadata('last_updated', new Date().toISOString().replace(/\\..+$/, ''))\n repo.setMetadata('last_build_type', 'full')\n\n return {\n buildType: 'full',\n filesUpdated: files.length,\n totalNodes,\n totalEdges,\n changedFiles: files,\n dependentFiles: [],\n errors,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Incremental update\n// ---------------------------------------------------------------------------\n\nexport function incrementalUpdate(\n repoRoot: string,\n repo: IGraphRepository,\n parser: IParser,\n base = 'HEAD~1',\n changedFiles?: string[],\n): BuildResult {\n const ignorePatterns = loadIgnorePatterns(repoRoot)\n const changed = changedFiles ?? getChangedFiles(repoRoot, base)\n\n if (changed.length === 0) {\n return {\n buildType: 'incremental',\n filesUpdated: 0,\n totalNodes: 0,\n totalEdges: 0,\n changedFiles: [],\n dependentFiles: [],\n errors: [],\n }\n }\n\n const dependentFiles = new Set<string>()\n for (const relPath of changed) {\n const fullPath = path.join(repoRoot, relPath)\n const deps = findDependents(repo, fullPath)\n for (const d of deps) {\n try {\n dependentFiles.add(path.relative(repoRoot, d))\n } catch {\n dependentFiles.add(d)\n }\n }\n }\n\n const allFiles = new Set([...changed, ...dependentFiles])\n let totalNodes = 0\n let totalEdges = 0\n const errors: string[] = []\n\n for (const relPath of allFiles) {\n if (shouldIgnore(relPath, ignorePatterns)) { continue }\n const absPath = path.join(repoRoot, relPath)\n\n if (!fs.existsSync(absPath)) {\n repo.removeFileData(absPath)\n continue\n }\n if (!parser.detectLanguage(absPath)) { continue }\n\n try {\n const source = fs.readFileSync(absPath)\n const fhash = crypto.createHash('sha256').update(source).digest('hex')\n const existingNodes = repo.getNodesByFile(absPath)\n if (existingNodes.length > 0 && existingNodes[0]!.fileHash === fhash) {\n continue\n }\n const [nodes, edges] = parser.parseBytes(absPath, source)\n repo.storeFileNodesEdges(absPath, nodes, edges, fhash)\n totalNodes += nodes.length\n totalEdges += edges.length\n } catch (err) {\n errors.push(`${relPath}: ${String(err)}`)\n }\n }\n\n repo.setMetadata('last_updated', new Date().toISOString().replace(/\\..+$/, ''))\n repo.setMetadata('last_build_type', 'incremental')\n\n return {\n buildType: 'incremental',\n filesUpdated: allFiles.size,\n totalNodes,\n totalEdges,\n changedFiles: changed,\n dependentFiles: [...dependentFiles],\n errors,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Private helper\n// ---------------------------------------------------------------------------\n\nfunction findDependents(repo: IGraphRepository, filePath: string): string[] {\n const dependents = new Set<string>()\n\n for (const e of repo.getEdgesByTarget(filePath)) {\n if (e.kind === 'IMPORTS_FROM') {\n dependents.add(e.filePath)\n }\n }\n\n for (const node of repo.getNodesByFile(filePath)) {\n for (const e of repo.getEdgesByTarget(node.qualifiedName)) {\n if (['CALLS', 'IMPORTS_FROM', 'INHERITS', 'IMPLEMENTS'].includes(e.kind)) {\n dependents.add(e.filePath)\n }\n }\n }\n\n dependents.delete(filePath)\n return [...dependents]\n}\n","/**\n * Use case: compute impact radius via BFS.\n *\n * Extracted from GraphStore.getImpactRadius() so the BFS algorithm lives in\n * the application layer, independent of the SQLite infrastructure.\n */\n\nimport type { ImpactRadius } from '../domain/types.js'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\n\nexport function computeImpactRadius(\n changedFiles: string[],\n repo: IGraphRepository,\n maxDepth = 2,\n maxNodes = 500,\n): ImpactRadius {\n const adj = repo.getAdjacency()\n\n // Seed: all qualified names in changed files\n const seeds = new Set<string>()\n for (const f of changedFiles) {\n for (const node of repo.getNodesByFile(f)) {\n seeds.add(node.qualifiedName)\n }\n }\n\n const visited = new Set<string>()\n let frontier = new Set(seeds)\n const impacted = new Set<string>()\n let depth = 0\n\n while (frontier.size > 0 && depth < maxDepth) {\n const nextFrontier = new Set<string>()\n for (const qn of frontier) {\n visited.add(qn)\n const outNeighbors = adj.outgoing.get(qn)\n if (outNeighbors) {\n for (const nb of outNeighbors) {\n if (!visited.has(nb)) { nextFrontier.add(nb); impacted.add(nb) }\n }\n }\n const inNeighbors = adj.incoming.get(qn)\n if (inNeighbors) {\n for (const nb of inNeighbors) {\n if (!visited.has(nb)) { nextFrontier.add(nb); impacted.add(nb) }\n }\n }\n }\n if (visited.size + nextFrontier.size > maxNodes) { break }\n frontier = nextFrontier\n depth++\n }\n\n const changedNodes = []\n for (const qn of seeds) {\n const n = repo.getNode(qn)\n if (n) { changedNodes.push(n) }\n }\n\n let impactedNodes = []\n for (const qn of impacted) {\n if (seeds.has(qn)) { continue }\n const n = repo.getNode(qn)\n if (n) { impactedNodes.push(n) }\n }\n\n const totalImpacted = impactedNodes.length\n const truncated = totalImpacted > maxNodes\n if (truncated) { impactedNodes = impactedNodes.slice(0, maxNodes) }\n\n const impactedFiles = [...new Set(impactedNodes.map((n) => n.filePath))]\n\n const allQns = new Set([...seeds, ...impactedNodes.map((n) => n.qualifiedName)])\n const edges = allQns.size > 0 ? repo.getEdgesAmong(allQns) : []\n\n return { changedNodes, impactedNodes, impactedFiles, edges, truncated, totalImpacted }\n}\n","/**\n * Use case: predefined graph queries (callers_of, callees_of, etc.).\n *\n * Extracted from tools.ts::queryGraph.\n */\n\nimport path from 'node:path'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport { nodeToDict, edgeToDict } from '../infrastructure/SqliteGraphRepository.js'\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nexport const BUILTIN_CALL_NAMES = new Set([\n 'map', 'filter', 'reduce', 'reduceRight', 'forEach', 'find', 'findIndex',\n 'some', 'every', 'includes', 'indexOf', 'lastIndexOf', 'push', 'pop',\n 'shift', 'unshift', 'splice', 'slice', 'concat', 'join', 'flat', 'flatMap',\n 'sort', 'reverse', 'fill', 'keys', 'values', 'entries', 'from', 'isArray',\n 'of', 'at', 'trim', 'trimStart', 'trimEnd', 'split', 'replace', 'replaceAll',\n 'match', 'matchAll', 'search', 'substring', 'substr', 'toLowerCase',\n 'toUpperCase', 'startsWith', 'endsWith', 'padStart', 'padEnd', 'repeat',\n 'charAt', 'charCodeAt', 'assign', 'freeze', 'defineProperty',\n 'getOwnPropertyNames', 'hasOwnProperty', 'create', 'is', 'fromEntries',\n 'log', 'warn', 'error', 'info', 'debug', 'trace', 'dir', 'table', 'time',\n 'timeEnd', 'assert', 'clear', 'count', 'then', 'catch', 'finally',\n 'resolve', 'reject', 'all', 'allSettled', 'race', 'any', 'parse',\n 'stringify', 'floor', 'ceil', 'round', 'random', 'max', 'min', 'abs',\n 'pow', 'sqrt', 'addEventListener', 'removeEventListener', 'querySelector',\n 'querySelectorAll', 'getElementById', 'createElement', 'appendChild',\n 'removeChild', 'setAttribute', 'getAttribute', 'preventDefault',\n 'stopPropagation', 'setTimeout', 'clearTimeout', 'setInterval',\n 'clearInterval', 'toString', 'valueOf', 'toJSON', 'toISOString', 'getTime',\n 'getFullYear', 'now', 'isNaN', 'parseInt', 'parseFloat', 'toFixed',\n 'encodeURIComponent', 'decodeURIComponent', 'call', 'apply', 'bind',\n 'next', 'emit', 'on', 'off', 'once', 'pipe', 'write', 'read', 'end',\n 'close', 'destroy', 'send', 'status', 'json', 'redirect', 'set', 'get',\n 'delete', 'has', 'findUnique', 'findFirst', 'findMany', 'createMany',\n 'update', 'updateMany', 'deleteMany', 'upsert', 'aggregate', 'groupBy',\n 'transaction', 'describe', 'it', 'test', 'expect', 'beforeEach',\n 'afterEach', 'beforeAll', 'afterAll', 'mock', 'spyOn', 'require', 'fetch',\n])\n\nexport const QUERY_PATTERNS: Record<string, string> = {\n callers_of: 'Find all functions that call a given function',\n callees_of: 'Find all functions called by a given function',\n imports_of: 'Find all imports of a given file or module',\n importers_of: 'Find all files that import a given file or module',\n children_of: 'Find all nodes contained in a file or class',\n tests_for: 'Find all tests for a given function or class',\n inheritors_of: 'Find all classes that inherit from a given class',\n file_summary: 'Get a summary of all nodes in a file',\n}\n\n// ---------------------------------------------------------------------------\n// Use case\n// ---------------------------------------------------------------------------\n\nexport function queryGraph(args: {\n pattern: string\n target: string\n repo: IGraphRepository\n repoRoot: string\n}): Record<string, unknown> {\n const { pattern, target, repo, repoRoot } = args\n\n if (!QUERY_PATTERNS[pattern]) {\n return {\n status: 'error',\n error: `Unknown pattern '${pattern}'. Available: ${Object.keys(QUERY_PATTERNS).join(', ')}`,\n }\n }\n\n const results: Array<Record<string, unknown>> = []\n const edgesOut: Array<Record<string, unknown>> = []\n\n if (\n pattern === 'callers_of' &&\n BUILTIN_CALL_NAMES.has(target) &&\n !target.includes('::')\n ) {\n return {\n status: 'ok',\n pattern,\n target,\n description: QUERY_PATTERNS[pattern],\n summary: `'${target}' is a common builtin — callers_of skipped to avoid noise.`,\n results: [],\n edges: [],\n }\n }\n\n let node = repo.getNode(target)\n let resolvedTarget = target\n\n if (!node) {\n const absTarget = path.join(repoRoot, target)\n node = repo.getNode(absTarget)\n if (node) { resolvedTarget = absTarget }\n }\n if (!node) {\n const candidates = repo.searchNodes(target, 5)\n if (candidates.length === 1) {\n node = candidates[0]!\n resolvedTarget = node.qualifiedName\n } else if (candidates.length > 1) {\n return {\n status: 'ambiguous',\n summary: `Multiple matches for '${target}'. Please use a qualified name.`,\n candidates: candidates.map(nodeToDict),\n }\n }\n }\n\n if (!node && pattern !== 'file_summary') {\n return { status: 'not_found', summary: `No node found matching '${target}'.` }\n }\n\n const qn = node?.qualifiedName ?? resolvedTarget\n\n if (pattern === 'callers_of') {\n for (const e of repo.getEdgesByTarget(qn)) {\n if (e.kind === 'CALLS') {\n const caller = repo.getNode(e.sourceQualified)\n if (caller) { results.push(nodeToDict(caller)) }\n edgesOut.push(edgeToDict(e))\n }\n }\n if (results.length === 0 && node) {\n for (const e of repo.searchEdgesByTargetName(node.name)) {\n const caller = repo.getNode(e.sourceQualified)\n if (caller) { results.push(nodeToDict(caller)) }\n edgesOut.push(edgeToDict(e))\n }\n }\n } else if (pattern === 'callees_of') {\n for (const e of repo.getEdgesBySource(qn)) {\n if (e.kind === 'CALLS') {\n const callee = repo.getNode(e.targetQualified)\n if (callee) { results.push(nodeToDict(callee)) }\n edgesOut.push(edgeToDict(e))\n }\n }\n } else if (pattern === 'imports_of') {\n for (const e of repo.getEdgesBySource(qn)) {\n if (e.kind === 'IMPORTS_FROM') {\n results.push({ import_target: e.targetQualified })\n edgesOut.push(edgeToDict(e))\n }\n }\n } else if (pattern === 'importers_of') {\n const absTarget = node ? node.filePath : path.join(repoRoot, target)\n for (const e of repo.getEdgesByTarget(absTarget)) {\n if (e.kind === 'IMPORTS_FROM') {\n results.push({ importer: e.sourceQualified, file: e.filePath })\n edgesOut.push(edgeToDict(e))\n }\n }\n } else if (pattern === 'children_of') {\n for (const e of repo.getEdgesBySource(qn)) {\n if (e.kind === 'CONTAINS') {\n const child = repo.getNode(e.targetQualified)\n if (child) { results.push(nodeToDict(child)) }\n }\n }\n } else if (pattern === 'tests_for') {\n for (const e of repo.getEdgesByTarget(qn)) {\n if (e.kind === 'TESTED_BY') {\n const testNode = repo.getNode(e.sourceQualified)\n if (testNode) { results.push(nodeToDict(testNode)) }\n }\n }\n const name = node?.name ?? target\n const seenQns = new Set(results.map((r) => r['qualified_name']))\n for (const t of [\n ...repo.searchNodes(`test_${name}`, 10),\n ...repo.searchNodes(`Test${name}`, 10),\n ]) {\n if (!seenQns.has(t.qualifiedName) && t.isTest) {\n results.push(nodeToDict(t))\n }\n }\n } else if (pattern === 'inheritors_of') {\n for (const e of repo.getEdgesByTarget(qn)) {\n if (e.kind === 'INHERITS' || e.kind === 'IMPLEMENTS') {\n const child = repo.getNode(e.sourceQualified)\n if (child) { results.push(nodeToDict(child)) }\n edgesOut.push(edgeToDict(e))\n }\n }\n } else if (pattern === 'file_summary') {\n const absPath = path.join(repoRoot, target)\n for (const n of repo.getNodesByFile(absPath)) {\n results.push(nodeToDict(n))\n }\n }\n\n return {\n status: 'ok',\n pattern,\n target: resolvedTarget,\n description: QUERY_PATTERNS[pattern],\n summary: `Found ${results.length} result(s) for ${pattern}('${resolvedTarget}')`,\n results,\n edges: edgesOut,\n }\n}\n","/**\n * Use case: generate focused review context for changed files.\n *\n * Extracted from tools.ts::getReviewContext + extractRelevantLines + generateReviewGuidance.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport type { ImpactRadius, GraphNode } from '../domain/types.js'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport { nodeToDict, edgeToDict } from '../infrastructure/SqliteGraphRepository.js'\nimport { computeImpactRadius } from './getImpactRadius.js'\n\nexport function getReviewContext(args: {\n changedFiles: string[]\n repo: IGraphRepository\n repoRoot: string\n maxDepth?: number\n includeSource?: boolean\n maxLinesPerFile?: number\n}): Record<string, unknown> {\n const {\n changedFiles,\n repo,\n repoRoot,\n maxDepth = 2,\n includeSource = true,\n maxLinesPerFile = 200,\n } = args\n\n if (changedFiles.length === 0) {\n return { status: 'ok', summary: 'No changes detected. Nothing to review.', context: {} }\n }\n\n const absFiles = changedFiles.map((f) => path.join(repoRoot, f))\n const impact = computeImpactRadius(absFiles, repo, maxDepth)\n\n const context: Record<string, unknown> = {\n changed_files: changedFiles,\n impacted_files: impact.impactedFiles,\n graph: {\n changed_nodes: impact.changedNodes.map(nodeToDict),\n impacted_nodes: impact.impactedNodes.map(nodeToDict),\n edges: impact.edges.map(edgeToDict),\n },\n }\n\n if (includeSource) {\n const snippets: Record<string, string> = {}\n for (const relPath of changedFiles) {\n const fullPath = path.join(repoRoot, relPath)\n if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {\n try {\n const content = fs.readFileSync(fullPath, 'utf-8')\n const lines = content.split('\\n')\n if (lines.length > maxLinesPerFile) {\n snippets[relPath] = extractRelevantLines(lines, impact.changedNodes, fullPath)\n } else {\n snippets[relPath] = lines.map((l, i) => `${i + 1}: ${l}`).join('\\n')\n }\n } catch {\n snippets[relPath] = '(could not read file)'\n }\n }\n }\n context['source_snippets'] = snippets\n }\n\n const guidance = generateReviewGuidance(impact, changedFiles)\n context['review_guidance'] = guidance\n\n const summaryParts = [\n `Review context for ${changedFiles.length} changed file(s):`,\n ` - ${impact.changedNodes.length} directly changed nodes`,\n ` - ${impact.impactedNodes.length} impacted nodes in ${impact.impactedFiles.length} files`,\n '',\n 'Review guidance:',\n guidance,\n ]\n\n return { status: 'ok', summary: summaryParts.join('\\n'), context }\n}\n\n// ---------------------------------------------------------------------------\n// Private helpers\n// ---------------------------------------------------------------------------\n\nfunction extractRelevantLines(\n lines: string[],\n nodes: GraphNode[],\n filePath: string,\n): string {\n const ranges: Array<[number, number]> = []\n for (const n of nodes) {\n if (n.filePath === filePath) {\n const start = Math.max(0, (n.lineStart ?? 1) - 3)\n const end = Math.min(lines.length, (n.lineEnd ?? lines.length) + 2)\n ranges.push([start, end])\n }\n }\n\n if (ranges.length === 0) {\n return lines.slice(0, 50).map((l, i) => `${i + 1}: ${l}`).join('\\n')\n }\n\n ranges.sort((a, b) => a[0] - b[0])\n const merged: Array<[number, number]> = [ranges[0]!]\n for (const [start, end] of ranges.slice(1)) {\n const last = merged[merged.length - 1]!\n if (start <= last[1] + 1) {\n merged[merged.length - 1] = [last[0], Math.max(last[1], end)]\n } else {\n merged.push([start, end])\n }\n }\n\n const parts: string[] = []\n for (const [start, end] of merged) {\n if (parts.length > 0) { parts.push('...') }\n for (let i = start; i < end; i++) {\n parts.push(`${i + 1}: ${lines[i] ?? ''}`)\n }\n }\n return parts.join('\\n')\n}\n\nfunction generateReviewGuidance(impact: ImpactRadius, _changedFiles: string[]): string {\n const guidanceParts: string[] = []\n\n const changedFuncs = impact.changedNodes.filter((n) => n.kind === 'Function')\n const testedFuncQns = new Set(\n impact.edges\n .filter((e) => e.kind === 'TESTED_BY')\n .map((e) => e.sourceQualified),\n )\n const untested = changedFuncs.filter(\n (f) => !testedFuncQns.has(f.qualifiedName) && !f.isTest,\n )\n if (untested.length > 0) {\n guidanceParts.push(\n `- ${untested.length} changed function(s) lack test coverage: ` +\n untested.slice(0, 5).map((n) => n.name).join(', '),\n )\n }\n\n if (impact.impactedNodes.length > 20) {\n guidanceParts.push(\n `- Wide blast radius: ${impact.impactedNodes.length} nodes impacted. ` +\n 'Review callers and dependents carefully.',\n )\n }\n\n const inheritanceEdges = impact.edges.filter(\n (e) => e.kind === 'INHERITS' || e.kind === 'IMPLEMENTS',\n )\n if (inheritanceEdges.length > 0) {\n guidanceParts.push(\n `- ${inheritanceEdges.length} inheritance/implementation relationship(s) affected. ` +\n 'Check for Liskov substitution violations.',\n )\n }\n\n if (impact.impactedFiles.length > 3) {\n guidanceParts.push(\n `- Changes impact ${impact.impactedFiles.length} other files. ` +\n 'Consider splitting into smaller PRs.',\n )\n }\n\n if (guidanceParts.length === 0) {\n guidanceParts.push('- Changes appear well-contained with minimal blast radius.')\n }\n\n return guidanceParts.join('\\n')\n}\n","/**\n * Use case: semantic or keyword search across graph nodes.\n *\n * Extracted from tools.ts::semanticSearchNodes.\n */\n\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport type { IEmbeddingStore } from '../domain/ports/IEmbeddingStore.js'\nimport { nodeToDict } from '../infrastructure/SqliteGraphRepository.js'\n\nexport async function semanticSearchNodes(args: {\n query: string\n kind?: string | null\n limit?: number\n repo: IGraphRepository\n embStore: IEmbeddingStore\n}): Promise<Record<string, unknown>> {\n const { query, kind = null, limit = 20, repo, embStore } = args\n let searchMode = 'keyword'\n\n try {\n if (embStore.available && embStore.count() > 0) {\n searchMode = 'semantic'\n let raw = await semanticSearch(query, repo, embStore, limit * 2)\n if (kind) { raw = raw.filter((r) => r['kind'] === kind) }\n raw = raw.slice(0, limit)\n return {\n status: 'ok',\n query,\n search_mode: searchMode,\n summary:\n `Found ${raw.length} node(s) matching '${query}' via semantic search` +\n (kind ? ` (kind=${kind})` : ''),\n results: raw,\n }\n }\n } catch {\n searchMode = 'keyword'\n }\n\n let results = repo.searchNodes(query, limit * 2)\n if (kind) { results = results.filter((r) => r.kind === kind) }\n\n const qLower = query.toLowerCase()\n results.sort((a, b) => {\n const aLower = a.name.toLowerCase()\n const bLower = b.name.toLowerCase()\n const aScore = aLower === qLower ? 0 : aLower.startsWith(qLower) ? 1 : 2\n const bScore = bLower === qLower ? 0 : bLower.startsWith(qLower) ? 1 : 2\n return aScore - bScore\n })\n results = results.slice(0, limit)\n\n return {\n status: 'ok',\n query,\n search_mode: searchMode,\n summary:\n `Found ${results.length} node(s) matching '${query}'` +\n (kind ? ` (kind=${kind})` : ''),\n results: results.map(nodeToDict),\n }\n}\n\nasync function semanticSearch(\n query: string,\n repo: IGraphRepository,\n embStore: IEmbeddingStore,\n limit = 20,\n): Promise<Array<Record<string, unknown>>> {\n if (embStore.available && embStore.count() > 0) {\n const results = await embStore.search(query, limit)\n const output: Array<Record<string, unknown>> = []\n for (const { qualifiedName, score } of results) {\n const node = repo.getNode(qualifiedName)\n if (node) {\n const d = nodeToDict(node)\n d['similarity_score'] = Math.round(score * 10000) / 10000\n output.push(d)\n }\n }\n return output\n }\n return repo.searchNodes(query, limit).map((n) => nodeToDict(n))\n}\n","/**\n * Use case: list aggregate graph statistics.\n *\n * Extracted from tools.ts::listGraphStats.\n */\n\nimport path from 'node:path'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport type { IEmbeddingStore } from '../domain/ports/IEmbeddingStore.js'\n\nexport function listStats(args: {\n repo: IGraphRepository\n embStore: IEmbeddingStore\n repoRoot: string\n}): Record<string, unknown> {\n const { repo, embStore, repoRoot } = args\n const stats = repo.getStats()\n const rootName = path.basename(repoRoot)\n\n const summaryParts = [\n `Graph statistics for ${rootName}:`,\n ` Files: ${stats.filesCount}`,\n ` Total nodes: ${stats.totalNodes}`,\n ` Total edges: ${stats.totalEdges}`,\n ` Languages: ${stats.languages.length > 0 ? stats.languages.join(', ') : 'none'}`,\n ` Last updated: ${stats.lastUpdated ?? 'never'}`,\n '',\n 'Nodes by kind:',\n ...Object.entries(stats.nodesByKind).sort().map(([k, c]) => ` ${k}: ${c}`),\n '',\n 'Edges by kind:',\n ...Object.entries(stats.edgesByKind).sort().map(([k, c]) => ` ${k}: ${c}`),\n ]\n\n let embCount = 0\n try {\n embCount = embStore.count()\n summaryParts.push('', `Embeddings: ${embCount} nodes embedded`)\n if (!embStore.available) {\n summaryParts.push(' (install @huggingface/transformers for semantic search)')\n }\n } catch {\n // embeddings unavailable\n }\n\n return {\n status: 'ok',\n summary: summaryParts.join('\\n'),\n total_nodes: stats.totalNodes,\n total_edges: stats.totalEdges,\n nodes_by_kind: stats.nodesByKind,\n edges_by_kind: stats.edgesByKind,\n languages: stats.languages,\n files_count: stats.filesCount,\n last_updated: stats.lastUpdated,\n embeddings_count: embCount,\n }\n}\n","/**\n * Use case: embed all graph nodes for semantic search.\n *\n * Extracted from tools.ts::embedGraph + embeddings.ts::embedAllNodes.\n */\n\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport type { IEmbeddingStore } from '../domain/ports/IEmbeddingStore.js'\n\nexport async function embedAllNodes(\n repo: IGraphRepository,\n embStore: IEmbeddingStore,\n): Promise<number> {\n if (!embStore.available) return 0\n const allNodes = []\n for (const f of repo.getAllFiles()) {\n allNodes.push(...repo.getNodesByFile(f))\n }\n return embStore.embedNodes(allNodes)\n}\n\nexport async function embedGraph(args: {\n repo: IGraphRepository\n embStore: IEmbeddingStore\n}): Promise<Record<string, unknown>> {\n const { repo, embStore } = args\n\n if (!embStore.available) {\n return {\n status: 'error',\n error:\n '@huggingface/transformers is not installed. ' +\n 'Install with: npm install codeorbit (with optional deps)',\n }\n }\n\n const newlyEmbedded = await embedAllNodes(repo, embStore)\n const total = embStore.count()\n return {\n status: 'ok',\n summary:\n `Embedded ${newlyEmbedded} new node(s). Total embeddings: ${total}. ` +\n 'Semantic search is now active.',\n newly_embedded: newlyEmbedded,\n total_embeddings: total,\n }\n}\n","/**\n * Use case: retrieve a named section from the LLM-optimized docs reference.\n *\n * Extracted from tools.ts::getDocsSection.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nconst AVAILABLE_SECTIONS = [\n 'usage',\n 'review-delta',\n 'review-pr',\n 'commands',\n 'legal',\n 'watch',\n 'embeddings',\n 'languages',\n 'troubleshooting',\n]\n\nexport function getDocsSection(args: {\n sectionName: string\n searchRoots: string[]\n}): Record<string, unknown> {\n const { sectionName, searchRoots } = args\n\n for (const searchRoot of searchRoots) {\n const candidate = path.join(searchRoot, 'docs', 'LLM-OPTIMIZED-REFERENCE.md')\n if (fs.existsSync(candidate)) {\n const content = fs.readFileSync(candidate, 'utf-8')\n const escapedName = sectionName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n const match = new RegExp(\n `<section name=\"${escapedName}\">(.*?)</section>`,\n 'si',\n ).exec(content)\n if (match) {\n return { status: 'ok', section: sectionName, content: match[1]!.trim() }\n }\n }\n }\n\n return {\n status: 'not_found',\n error: `Section '${sectionName}' not found. Available: ${AVAILABLE_SECTIONS.join(', ')}`,\n }\n}\n","/**\n * Use case: find functions/classes exceeding a line-count threshold.\n *\n * Extracted from tools.ts::findLargeFunctions.\n */\n\nimport path from 'node:path'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport { nodeToDict } from '../infrastructure/SqliteGraphRepository.js'\n\nexport function findLargeFunctions(args: {\n minLines?: number\n kind?: string | null\n filePathPattern?: string | null\n limit?: number\n repo: IGraphRepository\n repoRoot: string\n}): Record<string, unknown> {\n const { minLines = 50, kind = null, filePathPattern = null, limit = 50, repo, repoRoot } = args\n\n const nodes = repo.getNodesBySize(\n minLines,\n undefined,\n kind ?? undefined,\n filePathPattern ?? undefined,\n limit,\n )\n\n const results = nodes.map((n) => {\n const d = nodeToDict(n) as Record<string, unknown>\n d['line_count'] =\n n.lineStart != null && n.lineEnd != null ? n.lineEnd - n.lineStart + 1 : 0\n try {\n d['relative_path'] = path.relative(repoRoot, n.filePath)\n } catch {\n d['relative_path'] = n.filePath\n }\n return d\n })\n\n const summaryParts = [\n `Found ${results.length} node(s) with >= ${minLines} lines` +\n (kind ? ` (kind=${kind})` : '') +\n (filePathPattern ? ` matching '${filePathPattern}'` : '') +\n ':',\n ]\n for (const r of results.slice(0, 10)) {\n summaryParts.push(\n ` ${String(r['line_count']).padStart(4)} lines | ${String(r['kind']).padStart(8)} | ` +\n `${r['name']} (${r['relative_path']}:${r['line_start']})`,\n )\n }\n if (results.length > 10) {\n summaryParts.push(` ... and ${results.length - 10} more`)\n }\n\n return {\n status: 'ok',\n summary: summaryParts.join('\\n'),\n total_found: results.length,\n min_lines: minLines,\n results,\n }\n}\n"],"mappings":";AAOA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;AACrC,SAAS,SAAS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AAA,IACvB,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,IAAI;AAAA,EAC/C;AAAA,EACA,OAAO,UAAU;AAAA,IACf,SAAS;AAAA,MACP;AAAA,QACE,MAAM;AAAA,QACN,MAAM,KAAK;AAAA,UACTC,gBAAe;AAAA,YACb,aAAa,KAAK;AAAA,YAClB,UAAU,KAAK;AAAA,UACjB,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAEA,OAAO;AAAA,EACL;AAAA,EACA;AAAA,EASA;AAAA,IACE,WAAW,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE;AAAA,IACtC,MAAM,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,IAAI;AAAA,IACxC,mBAAmB,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,IAAI;AAAA,IACrD,OAAO,EAAE,OAAO,EAAE,IAAI,EAAE,QAAQ,EAAE;AAAA,IAClC,WAAW,EAAE,OAAO,EAAE,SAAS,EAAE,QAAQ,IAAI;AAAA,EAC/C;AAAA,EACA,OAAO,UAAU;AAAA,IACf,SAAS;AAAA,MACP;AAAA,QACE,MAAM;AAAA,QACN,MAAM,KAAK;AAAA,UACTC,oBAAmB;AAAA,YACjB,UAAU,KAAK;AAAA,YACf,MAAM,KAAK;AAAA,YACX,iBAAiB,KAAK;AAAA,YACtB,OAAO,KAAK;AAAA,YACZ,UAAU,KAAK;AAAA,UACjB,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAMA,eAAsB,eAA8B;AAClD,QAAM,YAAY,IAAI,qBAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAChC;","names":["fs","path","fs","path","path","fs","crypto","Database","createRequire","_require","Database","crypto","fs","path","fs","path","crypto","fs","path","path","fs","crypto","path","path","fs","path","path","fs","path","fs","path","path","path","path","fs","queryGraph","getReviewContext","semanticSearchNodes","embedGraph","getDocsSection","findLargeFunctions","queryGraph","getReviewContext","semanticSearchNodes","embedGraph","getDocsSection","findLargeFunctions"]}
1
+ {"version":3,"sources":["../src/adapters/mcp/server.ts","../src/adapters/mcp/tools.ts","../src/infrastructure/SqliteGraphRepository.ts","../src/infrastructure/TreeSitterParser.ts","../src/infrastructure/SqliteEmbeddingStore.ts","../src/infrastructure/LocalEmbeddingProvider.ts","../src/infrastructure/GoogleEmbeddingProvider.ts","../src/infrastructure/FileSystemHelper.ts","../src/infrastructure/GitRunner.ts","../src/usecases/buildGraph.ts","../src/usecases/getImpactRadius.ts","../src/usecases/queryGraph.ts","../src/usecases/getReviewContext.ts","../src/usecases/semanticSearch.ts","../src/usecases/listStats.ts","../src/usecases/embedGraph.ts","../src/usecases/getDocsSection.ts","../src/usecases/findLargeFunctions.ts"],"sourcesContent":["/**\n * MCP server entry point for codeorbit.\n *\n * Run as: codeorbit serve\n * Communicates via stdio (standard MCP transport).\n */\n\nimport { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { z } from 'zod'\nimport {\n buildOrUpdateGraph,\n embedGraph,\n findLargeFunctions,\n getDocsSection,\n getImpactRadius,\n getReviewContext,\n listGraphStats,\n queryGraph,\n semanticSearchNodes,\n} from './tools.js'\n\n// ---------------------------------------------------------------------------\n// Server setup\n// ---------------------------------------------------------------------------\n\nconst server = new McpServer(\n { name: 'codeorbit', version: '0.1.0' },\n {\n instructions:\n 'Persistent incremental knowledge graph for token-efficient, ' +\n 'context-aware code reviews. Parses your codebase with Tree-sitter, ' +\n 'builds a structural graph, and provides smart impact analysis.',\n },\n)\n\n// ---------------------------------------------------------------------------\n// Tool registrations\n// ---------------------------------------------------------------------------\n\nserver.tool(\n 'build_or_update_graph_tool',\n 'Build or incrementally update the code knowledge graph.\\n\\n' +\n 'Call this first to initialize the graph, or after making changes.\\n' +\n 'By default performs an incremental update (only changed files).\\n' +\n 'Set full_rebuild=True to re-parse every file.\\n\\n' +\n 'Args:\\n' +\n ' full_rebuild: If True, re-parse all files. Default: False (incremental).\\n' +\n ' repo_root: Repository root path. Auto-detected from current directory if omitted.\\n' +\n ' base: Git ref to diff against for incremental updates. Default: HEAD~1.',\n {\n full_rebuild: z.boolean().default(false),\n repo_root: z.string().nullable().default(null),\n base: z.string().default('HEAD~1'),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n buildOrUpdateGraph({\n fullRebuild: args.full_rebuild,\n repoRoot: args.repo_root,\n base: args.base,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'get_impact_radius_tool',\n 'Analyze the blast radius of changed files in the codebase.\\n\\n' +\n 'Shows which functions, classes, and files are impacted by changes.\\n' +\n 'Auto-detects changed files from git if not specified.\\n\\n' +\n 'Args:\\n' +\n ' changed_files: List of changed file paths (relative to repo root). Auto-detected if omitted.\\n' +\n ' max_depth: Number of hops to traverse in the dependency graph. Default: 2.\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.\\n' +\n ' base: Git ref for auto-detecting changes. Default: HEAD~1.',\n {\n changed_files: z.array(z.string()).nullable().default(null),\n max_depth: z.number().int().default(2),\n repo_root: z.string().nullable().default(null),\n base: z.string().default('HEAD~1'),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n getImpactRadius({\n changedFiles: args.changed_files,\n maxDepth: args.max_depth,\n repoRoot: args.repo_root,\n base: args.base,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'query_graph_tool',\n 'Run a predefined graph query to explore code relationships.\\n\\n' +\n 'Available patterns:\\n' +\n '- callers_of: Find functions that call the target\\n' +\n '- callees_of: Find functions called by the target\\n' +\n '- imports_of: Find what the target imports\\n' +\n '- importers_of: Find files that import the target\\n' +\n '- children_of: Find nodes contained in a file or class\\n' +\n '- tests_for: Find tests for the target\\n' +\n '- inheritors_of: Find classes inheriting from the target\\n' +\n '- file_summary: Get all nodes in a file\\n\\n' +\n 'Args:\\n' +\n ' pattern: Query pattern name (see above).\\n' +\n ' target: Node name, qualified name, or file path to query.\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.',\n {\n pattern: z.string(),\n target: z.string(),\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n queryGraph({\n pattern: args.pattern,\n target: args.target,\n repoRoot: args.repo_root,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'get_review_context_tool',\n 'Generate a focused, token-efficient review context for code changes.\\n\\n' +\n 'Combines impact analysis with source snippets and review guidance.\\n' +\n 'Use this for comprehensive code reviews.\\n\\n' +\n 'Args:\\n' +\n ' changed_files: Files to review. Auto-detected from git diff if omitted.\\n' +\n ' max_depth: Impact radius depth. Default: 2.\\n' +\n ' include_source: Include source code snippets. Default: True.\\n' +\n ' max_lines_per_file: Max source lines per file. Default: 200.\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.\\n' +\n ' base: Git ref for change detection. Default: HEAD~1.',\n {\n changed_files: z.array(z.string()).nullable().default(null),\n max_depth: z.number().int().default(2),\n include_source: z.boolean().default(true),\n max_lines_per_file: z.number().int().default(200),\n repo_root: z.string().nullable().default(null),\n base: z.string().default('HEAD~1'),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n getReviewContext({\n changedFiles: args.changed_files,\n maxDepth: args.max_depth,\n includeSource: args.include_source,\n maxLinesPerFile: args.max_lines_per_file,\n repoRoot: args.repo_root,\n base: args.base,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'semantic_search_nodes_tool',\n 'Search for code entities by name, keyword, or semantic similarity.\\n\\n' +\n 'Uses vector embeddings for semantic search when available (run embed_graph_tool\\n' +\n 'first, requires @huggingface/transformers). Falls back to keyword matching otherwise.\\n\\n' +\n 'Args:\\n' +\n ' query: Search string to match against node names.\\n' +\n ' kind: Optional filter: File, Class, Function, Type, or Test.\\n' +\n ' limit: Maximum results. Default: 20.\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.',\n {\n query: z.string(),\n kind: z.string().nullable().default(null),\n limit: z.number().int().default(20),\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n await semanticSearchNodes({\n query: args.query,\n kind: args.kind,\n limit: args.limit,\n repoRoot: args.repo_root,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'embed_graph_tool',\n 'Compute vector embeddings for all graph nodes to enable semantic search.\\n\\n' +\n 'Requires: npm install @huggingface/transformers\\n' +\n 'Only computes embeddings for nodes that do not already have them.\\n\\n' +\n 'Args:\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.',\n {\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(await embedGraph({ repoRoot: args.repo_root })),\n },\n ],\n }),\n)\n\nserver.tool(\n 'list_graph_stats_tool',\n 'Get aggregate statistics about the code knowledge graph.\\n\\n' +\n 'Shows total nodes, edges, languages, files, and last update time.\\n' +\n 'Useful for checking if the graph is built and up to date.\\n\\n' +\n 'Args:\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.',\n {\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(listGraphStats({ repoRoot: args.repo_root })),\n },\n ],\n }),\n)\n\nserver.tool(\n 'get_docs_section_tool',\n 'Get a specific section from the LLM-optimized documentation reference.\\n\\n' +\n 'Returns only the requested section content for minimal token usage.\\n\\n' +\n 'Available sections: usage, review-delta, review-pr, commands, legal,\\n' +\n 'watch, embeddings, languages, troubleshooting.\\n\\n' +\n 'Args:\\n' +\n ' section_name: The section to retrieve (e.g. \"review-delta\", \"usage\").',\n {\n section_name: z.string(),\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n getDocsSection({\n sectionName: args.section_name,\n repoRoot: args.repo_root,\n }),\n ),\n },\n ],\n }),\n)\n\nserver.tool(\n 'find_large_functions_tool',\n 'Find functions, classes, or files exceeding a line-count threshold.\\n\\n' +\n 'Useful for decomposition audits, code quality checks, and enforcing\\n' +\n 'size limits during code review. Results are ordered by line count.\\n\\n' +\n 'Args:\\n' +\n ' min_lines: Minimum line count to flag. Default: 50.\\n' +\n ' kind: Optional filter: Function, Class, File, or Test.\\n' +\n ' file_path_pattern: Filter by file path substring (e.g. \"components/\").\\n' +\n ' limit: Maximum results. Default: 50.\\n' +\n ' repo_root: Repository root path. Auto-detected if omitted.',\n {\n min_lines: z.number().int().default(50),\n kind: z.string().nullable().default(null),\n file_path_pattern: z.string().nullable().default(null),\n limit: z.number().int().default(50),\n repo_root: z.string().nullable().default(null),\n },\n async (args) => ({\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(\n findLargeFunctions({\n minLines: args.min_lines,\n kind: args.kind,\n filePathPattern: args.file_path_pattern,\n limit: args.limit,\n repoRoot: args.repo_root,\n }),\n ),\n },\n ],\n }),\n)\n\n// ---------------------------------------------------------------------------\n// Server entry point\n// ---------------------------------------------------------------------------\n\nexport async function runMcpServer(): Promise<void> {\n const transport = new StdioServerTransport()\n await server.connect(transport)\n}\n","/**\n * MCP tool adapter layer.\n *\n * Each function: validate args → create infrastructure → call use case → return result.\n * No business logic lives here — all logic is in src/usecases/.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { SqliteGraphRepository, nodeToDict, edgeToDict } from '../../infrastructure/SqliteGraphRepository.js'\nimport { TreeSitterParser } from '../../infrastructure/TreeSitterParser.js'\nimport { SqliteEmbeddingStore } from '../../infrastructure/SqliteEmbeddingStore.js'\nimport { findProjectRoot, getDbPath } from '../../infrastructure/FileSystemHelper.js'\nimport { getChangedFiles, getStagedAndUnstaged } from '../../infrastructure/GitRunner.js'\nimport { fullBuild, incrementalUpdate } from '../../usecases/buildGraph.js'\nimport { computeImpactRadius } from '../../usecases/getImpactRadius.js'\nimport { queryGraph as queryGraphUseCase } from '../../usecases/queryGraph.js'\nimport { getReviewContext as getReviewContextUseCase } from '../../usecases/getReviewContext.js'\nimport { semanticSearchNodes as semanticSearchUseCase } from '../../usecases/semanticSearch.js'\nimport { listStats } from '../../usecases/listStats.js'\nimport { embedGraph as embedGraphUseCase } from '../../usecases/embedGraph.js'\nimport { getDocsSection as getDocsSectionUseCase } from '../../usecases/getDocsSection.js'\nimport { findLargeFunctions as findLargeFunctionsUseCase } from '../../usecases/findLargeFunctions.js'\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\nfunction validateRepoRoot(repoRoot: string): string {\n const resolved = path.resolve(repoRoot)\n if (!fs.existsSync(resolved) || !fs.statSync(resolved).isDirectory()) {\n throw new Error(`repo_root is not an existing directory: ${resolved}`)\n }\n if (\n !fs.existsSync(path.join(resolved, '.git')) &&\n !fs.existsSync(path.join(resolved, '.codeorbit'))\n ) {\n throw new Error(\n `repo_root does not look like a project root (no .git or .codeorbit): ${resolved}`,\n )\n }\n return resolved\n}\n\nfunction resolveRoot(repoRoot?: string | null): string {\n return repoRoot ? validateRepoRoot(repoRoot) : findProjectRoot()\n}\n\n// ---------------------------------------------------------------------------\n// Tool 1: buildOrUpdateGraph\n// ---------------------------------------------------------------------------\n\nexport function buildOrUpdateGraph(args: {\n fullRebuild?: boolean\n repoRoot?: string | null\n base?: string\n}): Record<string, unknown> {\n const { fullRebuild = false, repoRoot = null, base = 'HEAD~1' } = args\n const root = resolveRoot(repoRoot)\n const repo = new SqliteGraphRepository(getDbPath(root))\n const parser = new TreeSitterParser()\n try {\n if (fullRebuild) {\n const result = fullBuild(root, repo, parser)\n return {\n status: 'ok',\n build_type: 'full',\n summary:\n `Full build complete: parsed ${result.filesUpdated} files, ` +\n `created ${result.totalNodes} nodes and ${result.totalEdges} edges.`,\n files_updated: result.filesUpdated,\n total_nodes: result.totalNodes,\n total_edges: result.totalEdges,\n errors: result.errors,\n }\n } else {\n const result = incrementalUpdate(root, repo, parser, base)\n if (result.filesUpdated === 0) {\n return {\n status: 'ok',\n build_type: 'incremental',\n summary: 'No changes detected. Graph is up to date.',\n files_updated: 0,\n total_nodes: 0,\n total_edges: 0,\n changed_files: [],\n dependent_files: [],\n errors: [],\n }\n }\n return {\n status: 'ok',\n build_type: 'incremental',\n summary:\n `Incremental update: ${result.filesUpdated} files re-parsed, ` +\n `${result.totalNodes} nodes and ${result.totalEdges} edges updated. ` +\n `Changed: ${JSON.stringify(result.changedFiles)}. ` +\n `Dependents also updated: ${JSON.stringify(result.dependentFiles)}.`,\n files_updated: result.filesUpdated,\n total_nodes: result.totalNodes,\n total_edges: result.totalEdges,\n changed_files: result.changedFiles,\n dependent_files: result.dependentFiles,\n errors: result.errors,\n }\n }\n } finally {\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 2: getImpactRadius\n// ---------------------------------------------------------------------------\n\nexport function getImpactRadius(args: {\n changedFiles?: string[] | null\n maxDepth?: number\n maxResults?: number\n repoRoot?: string | null\n base?: string\n}): Record<string, unknown> {\n const {\n changedFiles = null,\n maxDepth = 2,\n maxResults = 500,\n repoRoot = null,\n base = 'HEAD~1',\n } = args\n const root = resolveRoot(repoRoot)\n const repo = new SqliteGraphRepository(getDbPath(root))\n try {\n let changed = changedFiles\n if (!changed) {\n changed = getChangedFiles(root, base)\n if (changed.length === 0) {\n changed = getStagedAndUnstaged(root)\n }\n }\n\n if (changed.length === 0) {\n return {\n status: 'ok',\n summary: 'No changed files detected.',\n changed_nodes: [],\n impacted_nodes: [],\n impacted_files: [],\n truncated: false,\n total_impacted: 0,\n }\n }\n\n const absFiles = changed.map((f) => path.join(root, f))\n const result = computeImpactRadius(absFiles, repo, maxDepth, maxResults)\n\n const summaryParts = [\n `Blast radius for ${changed.length} changed file(s):`,\n ` - ${result.changedNodes.length} nodes directly changed`,\n ` - ${result.impactedNodes.length} nodes impacted (within ${maxDepth} hops)`,\n ` - ${result.impactedFiles.length} additional files affected`,\n ]\n if (result.truncated) {\n summaryParts.push(\n ` - Results truncated: showing ${result.impactedNodes.length} of ${result.totalImpacted} impacted nodes`,\n )\n }\n\n return {\n status: 'ok',\n summary: summaryParts.join('\\n'),\n changed_files: changed,\n changed_nodes: result.changedNodes.map(nodeToDict),\n impacted_nodes: result.impactedNodes.map(nodeToDict),\n impacted_files: result.impactedFiles,\n edges: result.edges.map(edgeToDict),\n truncated: result.truncated,\n total_impacted: result.totalImpacted,\n }\n } finally {\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 3: queryGraph\n// ---------------------------------------------------------------------------\n\nexport function queryGraph(args: {\n pattern: string\n target: string\n repoRoot?: string | null\n}): Record<string, unknown> {\n const { pattern, target, repoRoot = null } = args\n const root = resolveRoot(repoRoot)\n const repo = new SqliteGraphRepository(getDbPath(root))\n try {\n return queryGraphUseCase({ pattern, target, repo, repoRoot: root })\n } finally {\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 4: getReviewContext\n// ---------------------------------------------------------------------------\n\nexport function getReviewContext(args: {\n changedFiles?: string[] | null\n maxDepth?: number\n includeSource?: boolean\n maxLinesPerFile?: number\n repoRoot?: string | null\n base?: string\n}): Record<string, unknown> {\n const {\n changedFiles = null,\n maxDepth = 2,\n includeSource = true,\n maxLinesPerFile = 200,\n repoRoot = null,\n base = 'HEAD~1',\n } = args\n const root = resolveRoot(repoRoot)\n const repo = new SqliteGraphRepository(getDbPath(root))\n try {\n let changed = changedFiles\n if (!changed) {\n changed = getChangedFiles(root, base)\n if (changed.length === 0) {\n changed = getStagedAndUnstaged(root)\n }\n }\n\n if (changed.length === 0) {\n return {\n status: 'ok',\n summary: 'No changes detected. Nothing to review.',\n context: {},\n }\n }\n\n return getReviewContextUseCase({\n changedFiles: changed,\n repo,\n repoRoot: root,\n maxDepth,\n includeSource,\n maxLinesPerFile,\n })\n } finally {\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 5: semanticSearchNodes\n// ---------------------------------------------------------------------------\n\nexport async function semanticSearchNodes(args: {\n query: string\n kind?: string | null\n limit?: number\n repoRoot?: string | null\n}): Promise<Record<string, unknown>> {\n const { query, kind = null, limit = 20, repoRoot = null } = args\n const root = resolveRoot(repoRoot)\n const dbPath = getDbPath(root)\n const repo = new SqliteGraphRepository(dbPath)\n const embStore = new SqliteEmbeddingStore(dbPath)\n try {\n return await semanticSearchUseCase({ query, kind, limit, repo, embStore })\n } finally {\n embStore.close()\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 6: listGraphStats\n// ---------------------------------------------------------------------------\n\nexport function listGraphStats(args: {\n repoRoot?: string | null\n}): Record<string, unknown> {\n const { repoRoot = null } = args\n const root = resolveRoot(repoRoot)\n const dbPath = getDbPath(root)\n const repo = new SqliteGraphRepository(dbPath)\n const embStore = new SqliteEmbeddingStore(dbPath)\n try {\n return listStats({ repo, embStore, repoRoot: root })\n } finally {\n embStore.close()\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 7: embedGraph\n// ---------------------------------------------------------------------------\n\nexport async function embedGraph(args: {\n repoRoot?: string | null\n}): Promise<Record<string, unknown>> {\n const { repoRoot = null } = args\n const root = resolveRoot(repoRoot)\n const dbPath = getDbPath(root)\n const repo = new SqliteGraphRepository(dbPath)\n const embStore = new SqliteEmbeddingStore(dbPath)\n try {\n return await embedGraphUseCase({ repo, embStore })\n } finally {\n embStore.close()\n repo.close()\n }\n}\n\n// ---------------------------------------------------------------------------\n// Tool 8: getDocsSection\n// ---------------------------------------------------------------------------\n\nexport function getDocsSection(args: {\n sectionName: string\n repoRoot?: string | null\n}): Record<string, unknown> {\n const { sectionName, repoRoot = null } = args\n const searchRoots: string[] = []\n\n if (repoRoot) {\n searchRoots.push(path.resolve(repoRoot))\n }\n\n try {\n const root = resolveRoot(repoRoot)\n if (!searchRoots.includes(root)) {\n searchRoots.push(root)\n }\n } catch {\n // ignore — repo root not required for docs lookup\n }\n\n return getDocsSectionUseCase({ sectionName, searchRoots })\n}\n\n// ---------------------------------------------------------------------------\n// Tool 9: findLargeFunctions\n// ---------------------------------------------------------------------------\n\nexport function findLargeFunctions(args: {\n minLines?: number\n kind?: string | null\n filePathPattern?: string | null\n limit?: number\n repoRoot?: string | null\n}): Record<string, unknown> {\n const {\n minLines = 50,\n kind = null,\n filePathPattern = null,\n limit = 50,\n repoRoot = null,\n } = args\n const root = resolveRoot(repoRoot)\n const repo = new SqliteGraphRepository(getDbPath(root))\n try {\n return findLargeFunctionsUseCase({ minLines, kind, filePathPattern, limit, repo, repoRoot: root })\n } finally {\n repo.close()\n }\n}\n","/**\n * SQLite-backed knowledge graph storage — infrastructure implementation.\n *\n * Implements IGraphRepository. Pure CRUD + adjacency — no business logic.\n * BFS impact-radius computation was extracted to usecases/getImpactRadius.ts.\n *\n * Direct port of code_review_graph/graph.py.\n */\n\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport Database from 'better-sqlite3';\nimport type {\n NodeInfo,\n EdgeInfo,\n GraphNode,\n GraphEdge,\n GraphStats,\n NodeRow,\n EdgeRow,\n CountRow,\n KindCountRow,\n LanguageRow,\n FilePathRow,\n MetadataRow,\n EdgeKind,\n} from '../domain/types.js';\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js';\n\n// ---------------------------------------------------------------------------\n// Schema DDL — must match Python's _SCHEMA_SQL exactly (schema_version = 1)\n// ---------------------------------------------------------------------------\n\nconst SCHEMA_SQL = `\nCREATE TABLE IF NOT EXISTS nodes (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n kind TEXT NOT NULL,\n name TEXT NOT NULL,\n qualified_name TEXT NOT NULL UNIQUE,\n file_path TEXT NOT NULL,\n line_start INTEGER,\n line_end INTEGER,\n language TEXT,\n parent_name TEXT,\n params TEXT,\n return_type TEXT,\n modifiers TEXT,\n is_test INTEGER DEFAULT 0,\n file_hash TEXT,\n extra TEXT DEFAULT '{}',\n updated_at REAL NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS edges (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n kind TEXT NOT NULL,\n source_qualified TEXT NOT NULL,\n target_qualified TEXT NOT NULL,\n file_path TEXT NOT NULL,\n line INTEGER DEFAULT 0,\n extra TEXT DEFAULT '{}',\n updated_at REAL NOT NULL\n);\n\nCREATE TABLE IF NOT EXISTS metadata (\n key TEXT PRIMARY KEY,\n value TEXT NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS idx_nodes_file ON nodes(file_path);\nCREATE INDEX IF NOT EXISTS idx_nodes_kind ON nodes(kind);\nCREATE INDEX IF NOT EXISTS idx_nodes_qualified ON nodes(qualified_name);\nCREATE INDEX IF NOT EXISTS idx_edges_source ON edges(source_qualified);\nCREATE INDEX IF NOT EXISTS idx_edges_target ON edges(target_qualified);\nCREATE INDEX IF NOT EXISTS idx_edges_kind ON edges(kind);\nCREATE INDEX IF NOT EXISTS idx_edges_file ON edges(file_path);\n`;\n\n// ---------------------------------------------------------------------------\n// In-memory adjacency cache (replaces networkx.DiGraph)\n// ---------------------------------------------------------------------------\n\ninterface AdjacencyCache {\n out: Map<string, Set<string>>;\n in: Map<string, Set<string>>;\n}\n\n// ---------------------------------------------------------------------------\n// SqliteGraphRepository\n// ---------------------------------------------------------------------------\n\nexport class SqliteGraphRepository implements IGraphRepository {\n private db: Database.Database;\n private adjCache: AdjacencyCache | null = null;\n readonly dbPath: string;\n\n constructor(dbPath: string) {\n this.dbPath = dbPath;\n const dir = path.dirname(dbPath);\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n\n this.db = new Database(dbPath);\n this.db.pragma('journal_mode = WAL');\n this.db.pragma('busy_timeout = 5000');\n\n try {\n this.db.pragma('wal_checkpoint(TRUNCATE)');\n } catch {\n // ignore — safe to skip if another writer holds it\n }\n\n this._initSchema();\n }\n\n close(): void {\n try {\n this.db.pragma('wal_checkpoint(TRUNCATE)');\n } catch {\n // ignore\n }\n this.db.close();\n for (const suffix of ['-wal', '-shm']) {\n const side = this.dbPath + suffix;\n try {\n if (fs.existsSync(side)) { fs.unlinkSync(side); }\n } catch {\n // locked by another process — leave it alone\n }\n }\n }\n\n // ---------------------------------------------------------------------------\n // Write operations\n // ---------------------------------------------------------------------------\n\n upsertNode(node: NodeInfo, fileHash = ''): number {\n const now = Date.now() / 1000;\n const qualified = this._makeQualified(node);\n const extra = node.extra ? JSON.stringify(node.extra) : '{}';\n\n this.db.prepare(`\n INSERT INTO nodes\n (kind, name, qualified_name, file_path, line_start, line_end,\n language, parent_name, params, return_type, modifiers, is_test,\n file_hash, extra, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n ON CONFLICT(qualified_name) DO UPDATE SET\n kind=excluded.kind, name=excluded.name,\n file_path=excluded.file_path, line_start=excluded.line_start,\n line_end=excluded.line_end, language=excluded.language,\n parent_name=excluded.parent_name, params=excluded.params,\n return_type=excluded.return_type, modifiers=excluded.modifiers,\n is_test=excluded.is_test, file_hash=excluded.file_hash,\n extra=excluded.extra, updated_at=excluded.updated_at\n `).run(\n node.kind, node.name, qualified, node.filePath,\n node.lineStart, node.lineEnd, node.language ?? null,\n node.parentName ?? null, node.params ?? null, node.returnType ?? null,\n node.modifiers ?? null, node.isTest ? 1 : 0, fileHash,\n extra, now,\n );\n\n const row = this.db.prepare(\n 'SELECT id FROM nodes WHERE qualified_name = ?'\n ).get(qualified) as { id: number };\n return row.id;\n }\n\n upsertEdge(edge: EdgeInfo): number {\n const now = Date.now() / 1000;\n const extra = edge.extra ? JSON.stringify(edge.extra) : '{}';\n const line = edge.line ?? 0;\n\n const existing = this.db.prepare(`\n SELECT id FROM edges\n WHERE kind=? AND source_qualified=? AND target_qualified=?\n AND file_path=? AND line=?\n `).get(edge.kind, edge.source, edge.target, edge.filePath, line) as\n { id: number } | undefined;\n\n if (existing) {\n this.db.prepare(\n 'UPDATE edges SET line=?, extra=?, updated_at=? WHERE id=?'\n ).run(line, extra, now, existing.id);\n return existing.id;\n }\n\n const result = this.db.prepare(`\n INSERT INTO edges\n (kind, source_qualified, target_qualified, file_path, line, extra, updated_at)\n VALUES (?, ?, ?, ?, ?, ?, ?)\n `).run(edge.kind, edge.source, edge.target, edge.filePath, line, extra, now);\n return Number(result.lastInsertRowid);\n }\n\n removeFileData(filePath: string): void {\n this.db.prepare('DELETE FROM nodes WHERE file_path = ?').run(filePath);\n this.db.prepare('DELETE FROM edges WHERE file_path = ?').run(filePath);\n this._invalidateCache();\n }\n\n storeFileNodesEdges(\n filePath: string,\n nodes: NodeInfo[],\n edges: EdgeInfo[],\n fileHash = '',\n ): void {\n const txn = this.db.transaction(() => {\n this.removeFileData(filePath);\n for (const node of nodes) { this.upsertNode(node, fileHash); }\n for (const edge of edges) { this.upsertEdge(edge); }\n });\n txn();\n this._invalidateCache();\n }\n\n setMetadata(key: string, value: string): void {\n this.db.prepare(\n 'INSERT OR REPLACE INTO metadata (key, value) VALUES (?, ?)'\n ).run(key, value);\n }\n\n getMetadata(key: string): string | undefined {\n const row = this.db.prepare(\n 'SELECT value FROM metadata WHERE key = ?'\n ).get(key) as MetadataRow | undefined;\n return row?.value;\n }\n\n // ---------------------------------------------------------------------------\n // Read operations\n // ---------------------------------------------------------------------------\n\n getNode(qualifiedName: string): GraphNode | undefined {\n const row = this.db.prepare(\n 'SELECT * FROM nodes WHERE qualified_name = ?'\n ).get(qualifiedName) as NodeRow | undefined;\n return row ? this._rowToNode(row) : undefined;\n }\n\n getNodesByFile(filePath: string): GraphNode[] {\n const rows = this.db.prepare(\n 'SELECT * FROM nodes WHERE file_path = ? ORDER BY line_start'\n ).all(filePath) as NodeRow[];\n return rows.map((r) => this._rowToNode(r));\n }\n\n getEdgesBySource(qualifiedName: string): GraphEdge[] {\n const rows = this.db.prepare(\n 'SELECT * FROM edges WHERE source_qualified = ?'\n ).all(qualifiedName) as EdgeRow[];\n return rows.map((r) => this._rowToEdge(r));\n }\n\n getEdgesByTarget(qualifiedName: string): GraphEdge[] {\n const rows = this.db.prepare(\n 'SELECT * FROM edges WHERE target_qualified = ?'\n ).all(qualifiedName) as EdgeRow[];\n return rows.map((r) => this._rowToEdge(r));\n }\n\n searchEdgesByTargetName(name: string, kind: EdgeKind = 'CALLS'): GraphEdge[] {\n const rows = this.db.prepare(\n 'SELECT * FROM edges WHERE target_qualified = ? AND kind = ?'\n ).all(name, kind) as EdgeRow[];\n return rows.map((r) => this._rowToEdge(r));\n }\n\n getAllFiles(): string[] {\n const rows = this.db.prepare(\n \"SELECT DISTINCT file_path FROM nodes WHERE kind = 'File' ORDER BY file_path\"\n ).all() as FilePathRow[];\n return rows.map((r) => r.file_path);\n }\n\n searchNodes(query: string, limit = 20): GraphNode[] {\n const words = query.toLowerCase().split(/\\s+/).filter(Boolean);\n if (words.length === 0) { return []; }\n\n const conditions = words.map(\n () => '(LOWER(name) LIKE ? OR LOWER(qualified_name) LIKE ?)'\n );\n const params: Array<string | number> = [];\n for (const word of words) {\n params.push(`%${word}%`, `%${word}%`);\n }\n params.push(limit);\n\n const where = conditions.join(' AND ');\n // nosec: all values are parameterised\n const rows = this.db.prepare(\n `SELECT * FROM nodes WHERE ${where} LIMIT ?`\n ).all(...params) as NodeRow[];\n return rows.map((r) => this._rowToNode(r));\n }\n\n getSubgraph(qualifiedNames: string[]): { nodes: GraphNode[]; edges: GraphEdge[] } {\n const nodes: GraphNode[] = [];\n for (const qn of qualifiedNames) {\n const n = this.getNode(qn);\n if (n) { nodes.push(n); }\n }\n const qnSet = new Set(qualifiedNames);\n const edges: GraphEdge[] = [];\n for (const qn of qualifiedNames) {\n for (const e of this.getEdgesBySource(qn)) {\n if (qnSet.has(e.targetQualified)) { edges.push(e); }\n }\n }\n return { nodes, edges };\n }\n\n getStats(): GraphStats {\n const totalNodes = (\n this.db.prepare('SELECT COUNT(*) AS cnt FROM nodes').get() as CountRow\n ).cnt;\n const totalEdges = (\n this.db.prepare('SELECT COUNT(*) AS cnt FROM edges').get() as CountRow\n ).cnt;\n\n const nodesByKind: Record<string, number> = {};\n for (const r of this.db.prepare(\n 'SELECT kind, COUNT(*) AS cnt FROM nodes GROUP BY kind'\n ).all() as KindCountRow[]) {\n nodesByKind[r.kind] = r.cnt;\n }\n\n const edgesByKind: Record<string, number> = {};\n for (const r of this.db.prepare(\n 'SELECT kind, COUNT(*) AS cnt FROM edges GROUP BY kind'\n ).all() as KindCountRow[]) {\n edgesByKind[r.kind] = r.cnt;\n }\n\n const languages = (this.db.prepare(\n \"SELECT DISTINCT language FROM nodes WHERE language IS NOT NULL AND language != ''\"\n ).all() as LanguageRow[]).map((r) => r.language);\n\n const filesCount = (this.db.prepare(\n \"SELECT COUNT(*) AS cnt FROM nodes WHERE kind = 'File'\"\n ).get() as CountRow).cnt;\n\n const lastUpdated = this.getMetadata('last_updated') ?? null;\n\n let embeddingsCount = 0;\n try {\n embeddingsCount = (\n this.db.prepare('SELECT COUNT(*) AS cnt FROM embeddings').get() as CountRow\n ).cnt;\n } catch {\n // embeddings table may not exist — that is fine\n }\n\n return {\n totalNodes, totalEdges, nodesByKind, edgesByKind,\n languages, filesCount, lastUpdated, embeddingsCount,\n };\n }\n\n getNodesBySize(\n minLines = 50,\n maxLines?: number,\n kind?: string,\n filePathPattern?: string,\n limit = 50,\n ): Array<GraphNode & { lineCount: number }> {\n const conditions = [\n 'line_start IS NOT NULL',\n 'line_end IS NOT NULL',\n '(line_end - line_start + 1) >= ?',\n ];\n const params: Array<string | number> = [minLines];\n\n if (maxLines !== undefined) {\n conditions.push('(line_end - line_start + 1) <= ?');\n params.push(maxLines);\n }\n if (kind) { conditions.push('kind = ?'); params.push(kind); }\n if (filePathPattern) {\n conditions.push('file_path LIKE ?');\n params.push(`%${filePathPattern}%`);\n }\n params.push(limit);\n const where = conditions.join(' AND ');\n // nosec: all values are parameterised\n const rows = this.db.prepare(\n `SELECT * FROM nodes WHERE ${where} ORDER BY (line_end - line_start + 1) DESC LIMIT ?`\n ).all(...params) as NodeRow[];\n return rows.map((r) => ({\n ...this._rowToNode(r),\n lineCount:\n r.line_start != null && r.line_end != null\n ? r.line_end - r.line_start + 1\n : 0,\n }));\n }\n\n getAllEdges(): GraphEdge[] {\n const rows = this.db.prepare('SELECT * FROM edges').all() as EdgeRow[];\n return rows.map((r) => this._rowToEdge(r));\n }\n\n getEdgesAmong(qualifiedNames: Set<string>): GraphEdge[] {\n if (qualifiedNames.size === 0) { return []; }\n const qns = [...qualifiedNames];\n const results: GraphEdge[] = [];\n const batchSize = 450;\n\n for (let i = 0; i < qns.length; i += batchSize) {\n const batch = qns.slice(i, i + batchSize);\n const placeholders = batch.map(() => '?').join(',');\n // nosec: placeholders are parameterised\n const rows = this.db.prepare(\n `SELECT * FROM edges WHERE source_qualified IN (${placeholders})`\n ).all(...batch) as EdgeRow[];\n for (const r of rows) {\n const edge = this._rowToEdge(r);\n if (qualifiedNames.has(edge.targetQualified)) { results.push(edge); }\n }\n }\n return results;\n }\n\n // ---------------------------------------------------------------------------\n // Adjacency (BFS support for use cases)\n // ---------------------------------------------------------------------------\n\n getAdjacency(): { outgoing: Map<string, Set<string>>; incoming: Map<string, Set<string>> } {\n const cache = this._buildAdjacency();\n return { outgoing: cache.out, incoming: cache.in };\n }\n\n // ---------------------------------------------------------------------------\n // Private helpers\n // ---------------------------------------------------------------------------\n\n private _initSchema(): void {\n this.db.exec(SCHEMA_SQL);\n this.setMetadata('schema_version', '1');\n }\n\n private _invalidateCache(): void {\n this.adjCache = null;\n }\n\n private _buildAdjacency(): AdjacencyCache {\n if (this.adjCache) { return this.adjCache; }\n const out = new Map<string, Set<string>>();\n const inMap = new Map<string, Set<string>>();\n\n const rows = this.db.prepare('SELECT source_qualified, target_qualified FROM edges').all() as\n Array<{ source_qualified: string; target_qualified: string }>;\n\n for (const r of rows) {\n if (!out.has(r.source_qualified)) { out.set(r.source_qualified, new Set()); }\n out.get(r.source_qualified)!.add(r.target_qualified);\n\n if (!inMap.has(r.target_qualified)) { inMap.set(r.target_qualified, new Set()); }\n inMap.get(r.target_qualified)!.add(r.source_qualified);\n }\n\n this.adjCache = { out, in: inMap };\n return this.adjCache;\n }\n\n private _makeQualified(node: NodeInfo): string {\n if (node.kind === 'File') { return node.filePath; }\n if (node.parentName) {\n return `${node.filePath}::${node.parentName}.${node.name}`;\n }\n return `${node.filePath}::${node.name}`;\n }\n\n private _rowToNode(row: NodeRow): GraphNode {\n return {\n id: row.id,\n kind: row.kind as GraphNode['kind'],\n name: row.name,\n qualifiedName: row.qualified_name,\n filePath: row.file_path,\n lineStart: row.line_start,\n lineEnd: row.line_end,\n language: row.language ?? null,\n parentName: row.parent_name ?? null,\n params: row.params ?? null,\n returnType: row.return_type ?? null,\n modifiers: row.modifiers ?? null,\n isTest: row.is_test === 1,\n fileHash: row.file_hash ?? null,\n };\n }\n\n private _rowToEdge(row: EdgeRow): GraphEdge {\n return {\n id: row.id,\n kind: row.kind as GraphEdge['kind'],\n sourceQualified: row.source_qualified,\n targetQualified: row.target_qualified,\n filePath: row.file_path,\n line: row.line ?? 0,\n };\n }\n}\n\n// ---------------------------------------------------------------------------\n// Utility exports (mirrors Python module-level helpers)\n// ---------------------------------------------------------------------------\n\nexport function sanitizeName(s: string, maxLen = 256): string {\n let cleaned = '';\n for (const ch of s) {\n const code = ch.codePointAt(0) ?? 0;\n if (ch === '\\t' || ch === '\\n' || code >= 0x20) { cleaned += ch; }\n }\n return cleaned.slice(0, maxLen);\n}\n\nexport function nodeToDict(n: GraphNode): Record<string, unknown> {\n return {\n id: n.id,\n kind: n.kind,\n name: sanitizeName(n.name),\n qualified_name: sanitizeName(n.qualifiedName),\n file_path: n.filePath,\n line_start: n.lineStart,\n line_end: n.lineEnd,\n language: n.language,\n parent_name: n.parentName ? sanitizeName(n.parentName) : n.parentName,\n is_test: n.isTest,\n };\n}\n\nexport function edgeToDict(e: GraphEdge): Record<string, unknown> {\n return {\n id: e.id,\n kind: e.kind,\n source: sanitizeName(e.sourceQualified),\n target: sanitizeName(e.targetQualified),\n file_path: e.filePath,\n line: e.line,\n };\n}\n\n// Backward-compat alias (used by tests + public index.ts)\nexport { SqliteGraphRepository as GraphStore };\n","/**\n * Tree-sitter based multi-language code parser.\n *\n * Extracts structural nodes (classes, functions, imports, types) and edges\n * (calls, inheritance, contains) from source files.\n *\n * Direct port of code_review_graph/parser.py.\n * Supports 14 languages: Python, JS/TS/TSX, Go, Rust, Java, C, C++, C#,\n * Ruby, Kotlin, Swift, PHP, Solidity, Vue SFC.\n */\n\nimport crypto from 'node:crypto';\nimport fs from 'node:fs';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nconst _require = createRequire(import.meta.url);\n\n// Lazy-load tree-sitter so the require() doesn't execute at bundle load time.\n// This prevents VS Code from crashing the extension host when the native\n// tree-sitter binary was compiled for a different Node.js ABI than Electron uses.\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nlet _ParserClass: any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nfunction getParserClass(): any {\n if (!_ParserClass) { _ParserClass = _require('tree-sitter'); }\n return _ParserClass;\n}\nimport type { NodeInfo, EdgeInfo } from '../domain/types.js';\nimport type { IParser } from '../domain/ports/IParser.js';\n\n// ---------------------------------------------------------------------------\n// Language loading — individual npm grammar packages\n// ---------------------------------------------------------------------------\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype Language = any;\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype SyntaxNode = any;\n\nfunction loadLanguage(pkg: string): Language | null {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const mod = _require(pkg);\n return mod.default ?? mod;\n } catch {\n return null;\n }\n}\n\n// Lazy-loaded grammar map. Languages are loaded on first use.\nconst _languageCache = new Map<string, Language | null>();\n\nfunction getLanguage(name: string): Language | null {\n if (_languageCache.has(name)) { return _languageCache.get(name) ?? null; }\n\n const pkgMap: Record<string, string> = {\n python: 'tree-sitter-python',\n javascript: 'tree-sitter-javascript',\n typescript: 'tree-sitter-typescript/bindings/node/typescript',\n tsx: 'tree-sitter-typescript/bindings/node/tsx',\n go: 'tree-sitter-go',\n rust: 'tree-sitter-rust',\n java: 'tree-sitter-java',\n c: 'tree-sitter-c',\n cpp: 'tree-sitter-cpp',\n csharp: 'tree-sitter-c-sharp',\n ruby: 'tree-sitter-ruby',\n kotlin: 'tree-sitter-kotlin',\n swift: 'tree-sitter-swift',\n php: 'tree-sitter-php/php',\n solidity: 'tree-sitter-solidity',\n vue: 'tree-sitter-vue',\n };\n\n const pkg = pkgMap[name];\n const lang = pkg ? loadLanguage(pkg) : null;\n _languageCache.set(name, lang);\n return lang;\n}\n\n// ---------------------------------------------------------------------------\n// Extension → language mapping\n// ---------------------------------------------------------------------------\n\nexport const EXTENSION_TO_LANGUAGE: Record<string, string> = {\n '.py': 'python',\n '.js': 'javascript',\n '.jsx': 'javascript',\n '.ts': 'typescript',\n '.tsx': 'tsx',\n '.go': 'go',\n '.rs': 'rust',\n '.java': 'java',\n '.cs': 'csharp',\n '.rb': 'ruby',\n '.cpp': 'cpp',\n '.cc': 'cpp',\n '.cxx': 'cpp',\n '.c': 'c',\n '.h': 'c',\n '.hpp': 'cpp',\n '.kt': 'kotlin',\n '.swift': 'swift',\n '.php': 'php',\n '.sol': 'solidity',\n '.vue': 'vue',\n};\n\n// ---------------------------------------------------------------------------\n// AST node type sets per language\n// ---------------------------------------------------------------------------\n\nconst CLASS_TYPES: Record<string, string[]> = {\n python: ['class_definition'],\n javascript: ['class_declaration', 'class'],\n typescript: ['class_declaration', 'class'],\n tsx: ['class_declaration', 'class'],\n go: ['type_declaration'],\n rust: ['struct_item', 'enum_item', 'impl_item'],\n java: ['class_declaration', 'interface_declaration', 'enum_declaration'],\n c: ['struct_specifier', 'type_definition'],\n cpp: ['class_specifier', 'struct_specifier'],\n csharp: ['class_declaration', 'interface_declaration', 'enum_declaration', 'struct_declaration'],\n ruby: ['class', 'module'],\n kotlin: ['class_declaration', 'object_declaration'],\n swift: ['class_declaration', 'struct_declaration', 'protocol_declaration'],\n php: ['class_declaration', 'interface_declaration'],\n solidity: [\n 'contract_declaration', 'interface_declaration', 'library_declaration',\n 'struct_declaration', 'enum_declaration', 'error_declaration',\n 'user_defined_type_definition',\n ],\n};\n\nconst FUNCTION_TYPES: Record<string, string[]> = {\n python: ['function_definition'],\n javascript: ['function_declaration', 'method_definition', 'arrow_function'],\n typescript: ['function_declaration', 'method_definition', 'arrow_function'],\n tsx: ['function_declaration', 'method_definition', 'arrow_function'],\n go: ['function_declaration', 'method_declaration'],\n rust: ['function_item'],\n java: ['method_declaration', 'constructor_declaration'],\n c: ['function_definition'],\n cpp: ['function_definition'],\n csharp: ['method_declaration', 'constructor_declaration'],\n ruby: ['method', 'singleton_method'],\n kotlin: ['function_declaration'],\n swift: ['function_declaration'],\n php: ['function_definition', 'method_declaration'],\n solidity: [\n 'function_definition', 'constructor_definition', 'modifier_definition',\n 'event_definition', 'fallback_receive_definition',\n ],\n};\n\nconst IMPORT_TYPES: Record<string, string[]> = {\n python: ['import_statement', 'import_from_statement'],\n javascript: ['import_statement'],\n typescript: ['import_statement'],\n tsx: ['import_statement'],\n go: ['import_declaration'],\n rust: ['use_declaration'],\n java: ['import_declaration'],\n c: ['preproc_include'],\n cpp: ['preproc_include'],\n csharp: ['using_directive'],\n ruby: ['call'], // require / require_relative\n kotlin: ['import_header'],\n swift: ['import_declaration'],\n php: ['namespace_use_declaration'],\n solidity: ['import_directive'],\n};\n\nconst CALL_TYPES: Record<string, string[]> = {\n python: ['call'],\n javascript: ['call_expression', 'new_expression'],\n typescript: ['call_expression', 'new_expression'],\n tsx: ['call_expression', 'new_expression'],\n go: ['call_expression'],\n rust: ['call_expression', 'macro_invocation'],\n java: ['method_invocation', 'object_creation_expression'],\n c: ['call_expression'],\n cpp: ['call_expression'],\n csharp: ['invocation_expression', 'object_creation_expression'],\n ruby: ['call', 'method_call'],\n kotlin: ['call_expression'],\n swift: ['call_expression'],\n php: ['function_call_expression', 'member_call_expression'],\n solidity: ['call_expression'],\n};\n\n// ---------------------------------------------------------------------------\n// Test detection patterns\n// ---------------------------------------------------------------------------\n\nconst TEST_PATTERNS = [\n /^test_/,\n /^Test/,\n /_test$/,\n /\\.test\\./,\n /\\.spec\\./,\n /_spec$/,\n];\n\nconst TEST_FILE_PATTERNS = [\n /test_.*\\.py$/,\n /.*_test\\.py$/,\n /.*\\.test\\.[jt]sx?$/,\n /.*\\.spec\\.[jt]sx?$/,\n /.*_test\\.go$/,\n /tests?\\//,\n];\n\nfunction isTestFile(filePath: string): boolean {\n return TEST_FILE_PATTERNS.some((p) => p.test(filePath));\n}\n\n// Test-runner framework names that indicate a function IS a test even\n// if its name doesn't start with \"test\".\nconst TEST_RUNNER_NAMES = new Set([\n 'describe', 'it', 'test', 'beforeEach', 'afterEach', 'beforeAll', 'afterAll',\n]);\n\nfunction isTestFunction(name: string, filePath: string): boolean {\n // Name-pattern match always wins\n if (TEST_PATTERNS.some((p) => p.test(name))) { return true; }\n // In a test file, only test-runner functions count (not every helper)\n if (isTestFile(filePath) && TEST_RUNNER_NAMES.has(name)) { return true; }\n return false;\n}\n\n// ---------------------------------------------------------------------------\n// Public utility\n// ---------------------------------------------------------------------------\n\nexport function fileHash(filePath: string): string {\n const buf = fs.readFileSync(filePath);\n return crypto.createHash('sha256').update(buf).digest('hex');\n}\n\n// ---------------------------------------------------------------------------\n// CodeParser\n// ---------------------------------------------------------------------------\n\nconst MAX_AST_DEPTH = 180;\nconst MODULE_CACHE_MAX = 15_000;\n\nexport class CodeParser implements IParser {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private parsers = new Map<string, any>();\n private moduleFileCache = new Map<string, string | null>();\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n private getParser(language: string): any {\n if (this.parsers.has(language)) { return this.parsers.get(language) ?? null; }\n try {\n const lang = getLanguage(language);\n if (!lang) { return null; }\n const p = new (getParserClass())();\n p.setLanguage(lang);\n this.parsers.set(language, p);\n return p;\n } catch {\n return null;\n }\n }\n\n detectLanguage(filePath: string): string | null {\n const ext = path.extname(filePath).toLowerCase();\n return EXTENSION_TO_LANGUAGE[ext] ?? null;\n }\n\n parseFile(filePath: string): [NodeInfo[], EdgeInfo[]] {\n let source: Buffer;\n try {\n source = fs.readFileSync(filePath);\n } catch {\n return [[], []];\n }\n return this.parseBytes(filePath, source);\n }\n\n parseBytes(filePath: string, source: Buffer): [NodeInfo[], EdgeInfo[]] {\n const language = this.detectLanguage(filePath);\n if (!language) { return [[], []]; }\n\n if (language === 'vue') {\n return this._parseVue(filePath, source);\n }\n\n const parser = this.getParser(language);\n if (!parser) { return [[], []]; }\n\n const tree = parser.parse(source.toString('utf-8'));\n const nodes: NodeInfo[] = [];\n const edges: EdgeInfo[] = [];\n const testFile = isTestFile(filePath);\n\n // File node\n const lineCount = source.toString('utf-8').split('\\n').length;\n nodes.push({\n kind: 'File',\n name: filePath,\n filePath,\n lineStart: 1,\n lineEnd: lineCount,\n language,\n isTest: testFile,\n });\n\n const [importMap, definedNames] = this._collectFileScope(\n tree.rootNode, language, source,\n );\n\n this._extractFromTree(\n tree.rootNode, source, language, filePath, nodes, edges,\n undefined, undefined, importMap, definedNames,\n );\n\n const resolvedEdges = this._resolveCallTargets(nodes, edges, filePath);\n\n // Generate TESTED_BY edges\n if (testFile) {\n const testQNames = new Set<string>();\n for (const n of nodes) {\n if (n.isTest) {\n testQNames.add(this._qualify(n.name, filePath, n.parentName ?? null));\n }\n }\n const testedBy: EdgeInfo[] = [];\n for (const edge of resolvedEdges) {\n if (edge.kind === 'CALLS' && testQNames.has(edge.source)) {\n testedBy.push({\n kind: 'TESTED_BY',\n source: edge.target,\n target: edge.source,\n filePath: edge.filePath,\n line: edge.line,\n });\n }\n }\n resolvedEdges.push(...testedBy);\n }\n\n return [nodes, resolvedEdges];\n }\n\n private _parseVue(filePath: string, source: Buffer): [NodeInfo[], EdgeInfo[]] {\n const vueParser = this.getParser('vue');\n if (!vueParser) { return [[], []]; }\n\n const tree = vueParser.parse(source.toString('utf-8'));\n const testFile = isTestFile(filePath);\n const lineCount = source.toString('utf-8').split('\\n').length;\n\n const allNodes: NodeInfo[] = [{\n kind: 'File',\n name: filePath,\n filePath,\n lineStart: 1,\n lineEnd: lineCount,\n language: 'vue',\n isTest: testFile,\n }];\n const allEdges: EdgeInfo[] = [];\n\n for (const child of tree.rootNode.children) {\n if (child.type !== 'script_element') { continue; }\n\n let scriptLang = 'javascript';\n let startTag: SyntaxNode | null = null;\n let rawTextNode: SyntaxNode | null = null;\n\n for (const sub of child.children) {\n if (sub.type === 'start_tag') { startTag = sub; }\n else if (sub.type === 'raw_text') { rawTextNode = sub; }\n }\n\n if (startTag) {\n for (const attr of startTag.children) {\n if (attr.type === 'attribute') {\n let attrName: string | null = null;\n let attrValue: string | null = null;\n for (const a of attr.children) {\n if (a.type === 'attribute_name') { attrName = a.text; }\n else if (a.type === 'quoted_attribute_value') {\n for (const v of a.children) {\n if (v.type === 'attribute_value') { attrValue = v.text; }\n }\n }\n }\n if (attrName === 'lang' && (attrValue === 'ts' || attrValue === 'typescript')) {\n scriptLang = 'typescript';\n }\n }\n }\n }\n\n if (!rawTextNode) { continue; }\n\n const scriptSource = Buffer.from(rawTextNode.text, 'utf-8');\n const lineOffset: number = rawTextNode.startPosition.row;\n\n const scriptParser = this.getParser(scriptLang);\n if (!scriptParser) { continue; }\n\n const scriptTree = scriptParser.parse(scriptSource.toString('utf-8'));\n const [importMap, definedNames] = this._collectFileScope(\n scriptTree.rootNode, scriptLang, scriptSource,\n );\n\n const nodes: NodeInfo[] = [];\n const edges: EdgeInfo[] = [];\n this._extractFromTree(\n scriptTree.rootNode, scriptSource, scriptLang, filePath,\n nodes, edges, undefined, undefined, importMap, definedNames,\n );\n\n // Adjust line numbers and language for position within .vue file\n for (const n of nodes) {\n n.lineStart += lineOffset;\n n.lineEnd += lineOffset;\n n.language = 'vue';\n }\n for (const e of edges) {\n e.line = (e.line ?? 0) + lineOffset;\n }\n\n allNodes.push(...nodes);\n allEdges.push(...edges);\n }\n\n // Generate TESTED_BY edges\n if (testFile) {\n const testQNames = new Set<string>();\n for (const n of allNodes) {\n if (n.isTest) {\n testQNames.add(this._qualify(n.name, filePath, n.parentName ?? null));\n }\n }\n const testedBy: EdgeInfo[] = [];\n for (const edge of allEdges) {\n if (edge.kind === 'CALLS' && testQNames.has(edge.source)) {\n testedBy.push({\n kind: 'TESTED_BY',\n source: edge.target,\n target: edge.source,\n filePath: edge.filePath,\n line: edge.line,\n });\n }\n }\n allEdges.push(...testedBy);\n }\n\n return [allNodes, allEdges];\n }\n\n private _resolveCallTargets(\n nodes: NodeInfo[],\n edges: EdgeInfo[],\n filePath: string,\n ): EdgeInfo[] {\n const symbols = new Map<string, string>();\n for (const node of nodes) {\n if (['Function', 'Class', 'Type', 'Test'].includes(node.kind)) {\n const bare = node.name;\n if (!symbols.has(bare)) {\n symbols.set(bare, this._qualify(bare, filePath, node.parentName ?? null));\n }\n }\n }\n\n return edges.map((edge) => {\n if (edge.kind === 'CALLS' && !edge.target.includes('::')) {\n const qualified = symbols.get(edge.target);\n if (qualified) {\n return { ...edge, target: qualified };\n }\n }\n return edge;\n });\n }\n\n private _extractFromTree(\n root: SyntaxNode,\n source: Buffer,\n language: string,\n filePath: string,\n nodes: NodeInfo[],\n edges: EdgeInfo[],\n enclosingClass?: string | null,\n enclosingFunc?: string | null,\n importMap?: Map<string, string>,\n definedNames?: Set<string>,\n depth = 0,\n ): void {\n if (depth > MAX_AST_DEPTH) { return; }\n\n const classTypes = new Set(CLASS_TYPES[language] ?? []);\n const funcTypes = new Set(FUNCTION_TYPES[language] ?? []);\n const importTypes = new Set(IMPORT_TYPES[language] ?? []);\n const callTypes = new Set(CALL_TYPES[language] ?? []);\n\n for (const child of root.children) {\n const nodeType: string = child.type;\n\n // --- Classes ---\n if (classTypes.has(nodeType)) {\n const name = this._getName(child, language, 'class');\n if (name) {\n nodes.push({\n kind: 'Class',\n name,\n filePath,\n lineStart: child.startPosition.row + 1,\n lineEnd: child.endPosition.row + 1,\n language,\n parentName: enclosingClass ?? null,\n });\n\n edges.push({\n kind: 'CONTAINS',\n source: filePath,\n target: this._qualify(name, filePath, enclosingClass ?? null),\n filePath,\n line: child.startPosition.row + 1,\n });\n\n const bases = this._getBases(child, language);\n for (const base of bases) {\n edges.push({\n kind: 'INHERITS',\n source: this._qualify(name, filePath, enclosingClass ?? null),\n target: base,\n filePath,\n line: child.startPosition.row + 1,\n });\n }\n\n this._extractFromTree(\n child, source, language, filePath, nodes, edges,\n name, null, importMap, definedNames, depth + 1,\n );\n continue;\n }\n }\n\n // --- Functions ---\n if (funcTypes.has(nodeType)) {\n const name = this._getName(child, language, 'function');\n if (name) {\n const isTest = isTestFunction(name, filePath);\n const kind = isTest ? 'Test' : 'Function';\n const qualified = this._qualify(name, filePath, enclosingClass ?? null);\n const params = this._getParams(child, language);\n const retType = this._getReturnType(child, language);\n\n nodes.push({\n kind,\n name,\n filePath,\n lineStart: child.startPosition.row + 1,\n lineEnd: child.endPosition.row + 1,\n language,\n parentName: enclosingClass ?? null,\n params,\n returnType: retType,\n isTest,\n });\n\n const container = enclosingClass\n ? this._qualify(enclosingClass, filePath, null)\n : filePath;\n edges.push({\n kind: 'CONTAINS',\n source: container,\n target: qualified,\n filePath,\n line: child.startPosition.row + 1,\n });\n\n // Solidity: modifier invocations → CALLS edges\n if (language === 'solidity') {\n for (const sub of child.children) {\n if (sub.type === 'modifier_invocation') {\n for (const ident of sub.children) {\n if (ident.type === 'identifier') {\n edges.push({\n kind: 'CALLS',\n source: qualified,\n target: ident.text,\n filePath,\n line: sub.startPosition.row + 1,\n });\n break;\n }\n }\n }\n }\n }\n\n this._extractFromTree(\n child, source, language, filePath, nodes, edges,\n enclosingClass, name, importMap, definedNames, depth + 1,\n );\n continue;\n }\n }\n\n // --- Imports ---\n if (importTypes.has(nodeType)) {\n const imports = this._extractImport(child, language);\n for (const impTarget of imports) {\n edges.push({\n kind: 'IMPORTS_FROM',\n source: filePath,\n target: impTarget,\n filePath,\n line: child.startPosition.row + 1,\n });\n }\n continue;\n }\n\n // --- Calls ---\n if (callTypes.has(nodeType)) {\n const callName = this._getCallName(child, language);\n if (callName && enclosingFunc) {\n const caller = this._qualify(enclosingFunc, filePath, enclosingClass ?? null);\n const target = this._resolveCallTarget(\n callName, filePath, language,\n importMap ?? new Map(), definedNames ?? new Set(),\n );\n edges.push({\n kind: 'CALLS',\n source: caller,\n target,\n filePath,\n line: child.startPosition.row + 1,\n });\n }\n }\n\n // --- Solidity-specific constructs ---\n if (language === 'solidity') {\n // emit statements → CALLS edges\n if (nodeType === 'emit_statement' && enclosingFunc) {\n for (const sub of child.children) {\n if (sub.type === 'expression') {\n for (const ident of sub.children) {\n if (ident.type === 'identifier') {\n const caller = this._qualify(\n enclosingFunc, filePath, enclosingClass ?? null,\n );\n edges.push({\n kind: 'CALLS',\n source: caller,\n target: ident.text,\n filePath,\n line: child.startPosition.row + 1,\n });\n }\n }\n }\n }\n }\n\n // State variable declarations → Function nodes\n if (nodeType === 'state_variable_declaration' && enclosingClass) {\n let varName: string | null = null;\n let varVisibility: string | null = null;\n let varType: string | null = null;\n let varMutability: string | null = null;\n\n for (const sub of child.children) {\n if (sub.type === 'identifier') { varName = sub.text; }\n else if (sub.type === 'visibility') { varVisibility = sub.text; }\n else if (sub.type === 'type_name') { varType = sub.text; }\n else if (sub.type === 'constant' || sub.type === 'immutable') {\n varMutability = sub.type;\n }\n }\n if (varName) {\n const qualified = this._qualify(varName, filePath, enclosingClass);\n nodes.push({\n kind: 'Function',\n name: varName,\n filePath,\n lineStart: child.startPosition.row + 1,\n lineEnd: child.endPosition.row + 1,\n language,\n parentName: enclosingClass,\n returnType: varType,\n modifiers: varVisibility,\n extra: { solidity_kind: 'state_variable', mutability: varMutability },\n });\n edges.push({\n kind: 'CONTAINS',\n source: this._qualify(enclosingClass, filePath, null),\n target: qualified,\n filePath,\n line: child.startPosition.row + 1,\n });\n continue;\n }\n }\n\n // Constant variable declarations\n if (nodeType === 'constant_variable_declaration') {\n let varName: string | null = null;\n let varType: string | null = null;\n for (const sub of child.children) {\n if (sub.type === 'identifier') { varName = sub.text; }\n else if (sub.type === 'type_name') { varType = sub.text; }\n }\n if (varName) {\n const qualified = this._qualify(varName, filePath, enclosingClass ?? null);\n nodes.push({\n kind: 'Function',\n name: varName,\n filePath,\n lineStart: child.startPosition.row + 1,\n lineEnd: child.endPosition.row + 1,\n language,\n parentName: enclosingClass ?? null,\n returnType: varType,\n extra: { solidity_kind: 'constant' },\n });\n const container = enclosingClass\n ? this._qualify(enclosingClass, filePath, null)\n : filePath;\n edges.push({\n kind: 'CONTAINS',\n source: container,\n target: qualified,\n filePath,\n line: child.startPosition.row + 1,\n });\n continue;\n }\n }\n\n // Using directives → DEPENDS_ON edge\n if (nodeType === 'using_directive') {\n let libName: string | null = null;\n for (const sub of child.children) {\n if (sub.type === 'type_alias') {\n for (const ident of sub.children) {\n if (ident.type === 'identifier') { libName = ident.text; break; }\n }\n }\n }\n if (libName) {\n const sourceName = enclosingClass\n ? this._qualify(enclosingClass, filePath, null)\n : filePath;\n edges.push({\n kind: 'DEPENDS_ON',\n source: sourceName,\n target: libName,\n filePath,\n line: child.startPosition.row + 1,\n });\n }\n continue;\n }\n }\n\n // Recurse for other node types\n this._extractFromTree(\n child, source, language, filePath, nodes, edges,\n enclosingClass, enclosingFunc, importMap, definedNames, depth + 1,\n );\n }\n }\n\n private _collectFileScope(\n root: SyntaxNode,\n language: string,\n source: Buffer,\n ): [Map<string, string>, Set<string>] {\n const importMap = new Map<string, string>();\n const definedNames = new Set<string>();\n\n const classTypes = new Set(CLASS_TYPES[language] ?? []);\n const funcTypes = new Set(FUNCTION_TYPES[language] ?? []);\n const importTypes = new Set(IMPORT_TYPES[language] ?? []);\n const decoratorWrappers = new Set(['decorated_definition', 'decorator']);\n\n for (const child of root.children) {\n const nodeType: string = child.type;\n\n // Unwrap decorator wrappers\n let target = child;\n if (decoratorWrappers.has(nodeType)) {\n for (const inner of child.children) {\n if (funcTypes.has(inner.type) || classTypes.has(inner.type)) {\n target = inner;\n break;\n }\n }\n }\n\n const targetType: string = target.type;\n\n if (funcTypes.has(targetType) || classTypes.has(targetType)) {\n const name = this._getName(\n target, language, classTypes.has(targetType) ? 'class' : 'function',\n );\n if (name) { definedNames.add(name); }\n }\n\n if (importTypes.has(nodeType)) {\n this._collectImportNames(child, language, source, importMap);\n }\n }\n\n return [importMap, definedNames];\n }\n\n private _collectImportNames(\n node: SyntaxNode,\n language: string,\n _source: Buffer,\n importMap: Map<string, string>,\n ): void {\n if (language === 'python') {\n if (node.type === 'import_from_statement') {\n let module: string | null = null;\n let seenImport = false;\n for (const child of node.children) {\n if (child.type === 'dotted_name' && !seenImport) {\n module = child.text;\n } else if (child.type === 'import') {\n seenImport = true;\n } else if (seenImport && module) {\n if (child.type === 'identifier' || child.type === 'dotted_name') {\n importMap.set(child.text, module);\n } else if (child.type === 'aliased_import') {\n const names = child.children\n .filter((c: SyntaxNode) =>\n c.type === 'identifier' || c.type === 'dotted_name'\n )\n .map((c: SyntaxNode) => c.text as string);\n if (names.length > 0) { importMap.set(names[names.length - 1]!, module); }\n }\n }\n }\n }\n } else if (language === 'javascript' || language === 'typescript' || language === 'tsx') {\n let module: string | null = null;\n for (const child of node.children) {\n if (child.type === 'string') {\n module = (child.text as string).replace(/^['\"]|['\"]$/g, '');\n }\n }\n if (module) {\n for (const child of node.children) {\n if (child.type === 'import_clause') {\n this._collectJsImportNames(child, module, importMap);\n }\n }\n }\n }\n }\n\n private _collectJsImportNames(\n clauseNode: SyntaxNode,\n module: string,\n importMap: Map<string, string>,\n ): void {\n for (const child of clauseNode.children) {\n if (child.type === 'identifier') {\n importMap.set(child.text, module);\n } else if (child.type === 'named_imports') {\n for (const spec of child.children) {\n if (spec.type === 'import_specifier') {\n const names = spec.children\n .filter((s: SyntaxNode) =>\n s.type === 'identifier' || s.type === 'property_identifier'\n )\n .map((s: SyntaxNode) => s.text as string);\n if (names.length > 0) { importMap.set(names[names.length - 1]!, module); }\n }\n }\n }\n }\n }\n\n private _resolveModuleToFile(\n module: string,\n filePath: string,\n language: string,\n ): string | null {\n const callerDir = path.dirname(filePath);\n const cacheKey = `${language}:${callerDir}:${module}`;\n if (this.moduleFileCache.has(cacheKey)) {\n return this.moduleFileCache.get(cacheKey) ?? null;\n }\n\n const resolved = this._doResolveModule(module, filePath, language);\n if (this.moduleFileCache.size >= MODULE_CACHE_MAX) {\n this.moduleFileCache.clear();\n }\n this.moduleFileCache.set(cacheKey, resolved);\n return resolved;\n }\n\n private _doResolveModule(\n module: string,\n filePath: string,\n language: string,\n ): string | null {\n const callerDir = path.dirname(filePath);\n\n if (language === 'python') {\n const relPath = module.replace(/\\./g, '/');\n const candidates = [`${relPath}.py`, `${relPath}/__init__.py`];\n let current = callerDir;\n // eslint-disable-next-line no-constant-condition\n while (true) {\n for (const candidate of candidates) {\n const target = path.join(current, candidate);\n if (fs.existsSync(target)) { return path.resolve(target); }\n }\n const parent = path.dirname(current);\n if (parent === current) { break; }\n current = parent;\n }\n } else if (\n language === 'javascript' || language === 'typescript' ||\n language === 'tsx' || language === 'vue'\n ) {\n if (module.startsWith('.')) {\n const base = path.join(callerDir, module);\n const extensions = ['.ts', '.tsx', '.js', '.jsx', '.vue'];\n if (fs.existsSync(base) && fs.statSync(base).isFile()) {\n return path.resolve(base);\n }\n for (const ext of extensions) {\n const target = base + ext;\n if (fs.existsSync(target)) { return path.resolve(target); }\n }\n // Try index file in directory\n if (fs.existsSync(base) && fs.statSync(base).isDirectory()) {\n for (const ext of extensions) {\n const target = path.join(base, `index${ext}`);\n if (fs.existsSync(target)) { return path.resolve(target); }\n }\n }\n }\n }\n\n return null;\n }\n\n private _resolveCallTarget(\n callName: string,\n filePath: string,\n language: string,\n importMap: Map<string, string>,\n definedNames: Set<string>,\n ): string {\n if (definedNames.has(callName)) {\n return this._qualify(callName, filePath, null);\n }\n const importedFrom = importMap.get(callName);\n if (importedFrom) {\n const resolved = this._resolveModuleToFile(importedFrom, filePath, language);\n if (resolved) { return this._qualify(callName, resolved, null); }\n }\n return callName;\n }\n\n private _qualify(name: string, filePath: string, enclosingClass: string | null): string {\n if (enclosingClass) { return `${filePath}::${enclosingClass}.${name}`; }\n return `${filePath}::${name}`;\n }\n\n private _getName(node: SyntaxNode, language: string, kind: string): string | null {\n // Solidity: constructor and receive/fallback have no identifier child\n if (language === 'solidity') {\n if (node.type === 'constructor_definition') { return 'constructor'; }\n if (node.type === 'fallback_receive_definition') {\n for (const child of node.children) {\n if (child.type === 'receive' || child.type === 'fallback') {\n return child.text;\n }\n }\n }\n }\n\n // C/C++: function names are inside function_declarator/pointer_declarator\n if ((language === 'c' || language === 'cpp') && kind === 'function') {\n for (const child of node.children) {\n if (child.type === 'function_declarator' || child.type === 'pointer_declarator') {\n const result = this._getName(child, language, kind);\n if (result) { return result; }\n }\n }\n }\n\n // Most languages: look for identifier child\n for (const child of node.children) {\n if ([\n 'identifier', 'name', 'type_identifier', 'property_identifier',\n 'simple_identifier', 'constant',\n ].includes(child.type)) {\n return child.text;\n }\n }\n\n // Go type declarations: look for type_spec\n if (language === 'go' && node.type === 'type_declaration') {\n for (const child of node.children) {\n if (child.type === 'type_spec') {\n return this._getName(child, language, kind);\n }\n }\n }\n\n return null;\n }\n\n private _getParams(node: SyntaxNode, language: string): string | null {\n for (const child of node.children) {\n if (['parameters', 'formal_parameters', 'parameter_list'].includes(child.type)) {\n return child.text;\n }\n }\n if (language === 'solidity') {\n const params = node.children\n .filter((c: SyntaxNode) => c.type === 'parameter')\n .map((c: SyntaxNode) => c.text as string);\n if (params.length > 0) { return `(${params.join(', ')})`; }\n }\n return null;\n }\n\n private _getReturnType(node: SyntaxNode, language: string): string | null {\n for (const child of node.children) {\n if ([\n 'type', 'return_type', 'type_annotation', 'return_type_definition',\n ].includes(child.type)) {\n return child.text;\n }\n }\n if (language === 'python') {\n for (let i = 0; i < node.children.length - 1; i++) {\n if (node.children[i].type === '->') {\n return node.children[i + 1].text;\n }\n }\n }\n return null;\n }\n\n private _getBases(node: SyntaxNode, language: string): string[] {\n const bases: string[] = [];\n\n if (language === 'python') {\n for (const child of node.children) {\n if (child.type === 'argument_list') {\n for (const arg of child.children) {\n if (arg.type === 'identifier' || arg.type === 'attribute') {\n bases.push(arg.text);\n }\n }\n }\n }\n } else if (\n language === 'java' || language === 'csharp' || language === 'kotlin'\n ) {\n for (const child of node.children) {\n if ([\n 'superclass', 'super_interfaces', 'extends_type', 'implements_type',\n 'type_identifier', 'supertype', 'delegation_specifier',\n ].includes(child.type)) {\n bases.push(child.text);\n }\n }\n } else if (language === 'cpp') {\n for (const child of node.children) {\n if (child.type === 'base_class_clause') {\n for (const sub of child.children) {\n if (sub.type === 'type_identifier') { bases.push(sub.text); }\n }\n }\n }\n } else if (\n language === 'typescript' || language === 'javascript' || language === 'tsx'\n ) {\n for (const child of node.children) {\n if (child.type === 'extends_clause' || child.type === 'implements_clause') {\n for (const sub of child.children) {\n if ([\n 'identifier', 'type_identifier', 'nested_identifier',\n ].includes(sub.type)) {\n bases.push(sub.text);\n }\n }\n }\n }\n } else if (language === 'solidity') {\n for (const child of node.children) {\n if (child.type === 'inheritance_specifier') {\n for (const sub of child.children) {\n if (sub.type === 'user_defined_type') {\n for (const ident of sub.children) {\n if (ident.type === 'identifier') { bases.push(ident.text); }\n }\n }\n }\n }\n }\n } else if (language === 'go') {\n for (const child of node.children) {\n if (child.type === 'type_spec') {\n for (const sub of child.children) {\n if (sub.type === 'struct_type' || sub.type === 'interface_type') {\n for (const fieldNode of sub.children) {\n if (fieldNode.type === 'field_declaration_list') {\n for (const f of fieldNode.children) {\n if (f.type === 'type_identifier') { bases.push(f.text); }\n }\n }\n }\n }\n }\n }\n }\n }\n\n return bases;\n }\n\n private _extractImport(node: SyntaxNode, language: string): string[] {\n const imports: string[] = [];\n const text: string = node.text.trim();\n\n if (language === 'python') {\n if (node.type === 'import_from_statement') {\n for (const child of node.children) {\n if (child.type === 'dotted_name') {\n imports.push(child.text);\n break;\n }\n }\n } else {\n for (const child of node.children) {\n if (child.type === 'dotted_name') { imports.push(child.text); }\n }\n }\n } else if (\n language === 'javascript' || language === 'typescript' || language === 'tsx'\n ) {\n for (const child of node.children) {\n if (child.type === 'string') {\n imports.push((child.text as string).replace(/^['\"]|['\"]$/g, ''));\n }\n }\n } else if (language === 'go') {\n for (const child of node.children) {\n if (child.type === 'import_spec_list') {\n for (const spec of child.children) {\n if (spec.type === 'import_spec') {\n for (const s of spec.children) {\n if (s.type === 'interpreted_string_literal') {\n imports.push((s.text as string).replace(/^\"|\"$/g, ''));\n }\n }\n }\n }\n } else if (child.type === 'import_spec') {\n for (const s of child.children) {\n if (s.type === 'interpreted_string_literal') {\n imports.push((s.text as string).replace(/^\"|\"$/g, ''));\n }\n }\n }\n }\n } else if (language === 'rust') {\n imports.push(text.replace(/^use\\s+/, '').replace(/;$/, '').trim());\n } else if (language === 'c' || language === 'cpp') {\n for (const child of node.children) {\n if (child.type === 'system_lib_string' || child.type === 'string_literal') {\n imports.push((child.text as string).replace(/^[<\"\"]|[>\"\"]$/g, ''));\n }\n }\n } else if (language === 'java' || language === 'csharp') {\n const parts = text.split(/\\s+/);\n if (parts.length >= 2) {\n imports.push(parts[parts.length - 1]!.replace(/;$/, ''));\n }\n } else if (language === 'solidity') {\n for (const child of node.children) {\n if (child.type === 'string') {\n const val = (child.text as string).replace(/^\"|\"$/g, '');\n if (val) { imports.push(val); }\n }\n }\n } else if (language === 'ruby') {\n if (text.includes('require')) {\n const match = /['\"]([^'\"]+)['\"]/u.exec(text);\n if (match) { imports.push(match[1]!); }\n }\n } else {\n imports.push(text);\n }\n\n return imports;\n }\n\n private _getCallName(node: SyntaxNode, language: string): string | null {\n if (!node.children || node.children.length === 0) { return null; }\n\n let first: SyntaxNode = node.children[0];\n\n // Solidity wraps call targets in 'expression' — unwrap\n if (\n language === 'solidity' &&\n first.type === 'expression' &&\n first.children.length > 0\n ) {\n first = first.children[0];\n }\n\n if (first.type === 'identifier') { return first.text; }\n\n const memberTypes = [\n 'attribute', 'member_expression', 'field_expression', 'selector_expression',\n ];\n if (memberTypes.includes(first.type)) {\n for (let i = first.children.length - 1; i >= 0; i--) {\n const child: SyntaxNode = first.children[i];\n if ([\n 'identifier', 'property_identifier', 'field_identifier', 'field_name',\n ].includes(child.type)) {\n return child.text;\n }\n }\n return first.text;\n }\n\n if (first.type === 'scoped_identifier' || first.type === 'qualified_name') {\n return first.text;\n }\n\n return null;\n }\n}\n\n// Canonical export alias matching the file name\nexport { CodeParser as TreeSitterParser }\n","/**\n * SQLite-backed embedding store.\n *\n * Extracted from embeddings.ts::EmbeddingStore + helper functions.\n * Implements IEmbeddingStore.\n */\n\nimport crypto from 'node:crypto'\nimport Database from 'better-sqlite3'\nimport type { GraphNode } from '../domain/types.js'\nimport type { IEmbeddingStore } from '../domain/ports/IEmbeddingStore.js'\nimport type { IEmbeddingProvider } from '../domain/ports/IEmbeddingProvider.js'\nimport { LocalEmbeddingProvider } from './LocalEmbeddingProvider.js'\nimport { GoogleEmbeddingProvider } from './GoogleEmbeddingProvider.js'\n\n// ---------------------------------------------------------------------------\n// Schema\n// ---------------------------------------------------------------------------\n\nconst EMBEDDINGS_SCHEMA = `\nCREATE TABLE IF NOT EXISTS embeddings (\n qualified_name TEXT PRIMARY KEY,\n vector BLOB NOT NULL,\n text_hash TEXT NOT NULL,\n provider TEXT NOT NULL DEFAULT 'unknown'\n);\n`\n\n// ---------------------------------------------------------------------------\n// Vector helpers\n// ---------------------------------------------------------------------------\n\nfunction encodeVector(vec: number[]): Buffer {\n const buf = Buffer.allocUnsafe(vec.length * 4)\n for (let i = 0; i < vec.length; i++) buf.writeFloatLE(vec[i]!, i * 4)\n return buf\n}\n\nfunction decodeVector(blob: Buffer): number[] {\n const n = blob.length / 4\n const result: number[] = new Array(n)\n for (let i = 0; i < n; i++) result[i] = blob.readFloatLE(i * 4)\n return result\n}\n\nfunction cosineSimilarity(a: number[], b: number[]): number {\n if (a.length !== b.length) return 0\n let dot = 0, normA = 0, normB = 0\n for (let i = 0; i < a.length; i++) {\n dot += a[i]! * b[i]!\n normA += a[i]! * a[i]!\n normB += b[i]! * b[i]!\n }\n if (normA === 0 || normB === 0) return 0\n return dot / (Math.sqrt(normA) * Math.sqrt(normB))\n}\n\nexport function nodeToText(node: GraphNode): string {\n const parts = [node.name]\n if (node.kind !== 'File') parts.push(node.kind.toLowerCase())\n if (node.parentName) parts.push(`in ${node.parentName}`)\n if (node.params) parts.push(node.params)\n if (node.returnType) parts.push(`returns ${node.returnType}`)\n if (node.language) parts.push(node.language)\n return parts.join(' ')\n}\n\n// ---------------------------------------------------------------------------\n// Provider factory\n// ---------------------------------------------------------------------------\n\nexport function getProvider(provider?: string | null): IEmbeddingProvider | null {\n if (provider === 'google') {\n const apiKey = process.env['GOOGLE_API_KEY']\n if (!apiKey) return null\n try { return new GoogleEmbeddingProvider(apiKey) } catch { return null }\n }\n return new LocalEmbeddingProvider()\n}\n\n// ---------------------------------------------------------------------------\n// SqliteEmbeddingStore\n// ---------------------------------------------------------------------------\n\nexport class SqliteEmbeddingStore implements IEmbeddingStore {\n private _db: Database.Database\n readonly available: boolean\n private _provider: IEmbeddingProvider | null\n\n constructor(dbPath: string, provider?: string | null) {\n this._db = new Database(dbPath)\n this._db.exec(EMBEDDINGS_SCHEMA)\n\n try {\n this._db.prepare('SELECT provider FROM embeddings LIMIT 1').get()\n } catch {\n this._db.exec(\n \"ALTER TABLE embeddings ADD COLUMN provider TEXT NOT NULL DEFAULT 'unknown'\",\n )\n }\n\n this._provider = getProvider(provider)\n this.available = this._provider !== null\n }\n\n count(): number {\n const row = this._db\n .prepare('SELECT COUNT(*) AS cnt FROM embeddings')\n .get() as { cnt: number }\n return row.cnt\n }\n\n async embedNodes(nodes: GraphNode[], batchSize = 64): Promise<number> {\n if (!this._provider) return 0\n const providerName = this._provider.name\n\n const toEmbed: Array<{ node: GraphNode; text: string; textHash: string }> = []\n for (const node of nodes) {\n if (node.kind === 'File') continue\n const text = nodeToText(node)\n const textHash = crypto.createHash('sha256').update(text).digest('hex')\n const existing = this._db\n .prepare('SELECT text_hash, provider FROM embeddings WHERE qualified_name = ?')\n .get(node.qualifiedName) as { text_hash: string; provider: string } | undefined\n if (existing && existing.text_hash === textHash && existing.provider === providerName) {\n continue\n }\n toEmbed.push({ node, text, textHash })\n }\n\n if (toEmbed.length === 0) return 0\n\n const insert = this._db.prepare(\n 'INSERT OR REPLACE INTO embeddings (qualified_name, vector, text_hash, provider) VALUES (?, ?, ?, ?)',\n )\n\n for (let i = 0; i < toEmbed.length; i += batchSize) {\n const batch = toEmbed.slice(i, i + batchSize)\n const vectors = await this._provider.embed(batch.map((b) => b.text))\n this._db.transaction(() => {\n for (let j = 0; j < batch.length; j++) {\n const { node, textHash } = batch[j]!\n insert.run(node.qualifiedName, encodeVector(vectors[j]!), textHash, providerName)\n }\n })()\n }\n\n return toEmbed.length\n }\n\n async search(\n query: string,\n limit = 20,\n ): Promise<Array<{ qualifiedName: string; score: number }>> {\n if (!this._provider) return []\n const providerName = this._provider.name\n const queryVec = await this._provider.embedQuery(query)\n\n const rows = this._db\n .prepare('SELECT qualified_name, vector FROM embeddings WHERE provider = ?')\n .all(providerName) as Array<{ qualified_name: string; vector: Buffer }>\n\n const scored = rows.map((row) => ({\n qualifiedName: row.qualified_name,\n score: cosineSimilarity(queryVec, decodeVector(row.vector)),\n }))\n\n scored.sort((a, b) => b.score - a.score)\n return scored.slice(0, limit)\n }\n\n removeNode(qualifiedName: string): void {\n this._db\n .prepare('DELETE FROM embeddings WHERE qualified_name = ?')\n .run(qualifiedName)\n }\n\n close(): void {\n this._db.close()\n }\n}\n\n// Backward-compat alias\nexport { SqliteEmbeddingStore as EmbeddingStore }\n","/**\n * Local HuggingFace embedding provider.\n *\n * Extracted from embeddings.ts::LocalEmbeddingProvider.\n */\n\nimport type { IEmbeddingProvider } from '../domain/ports/IEmbeddingProvider.js'\n\nconst NOMIC_MODEL = 'Xenova/nomic-embed-text-v1.5'\nconst MINILM_MODEL = 'Xenova/all-MiniLM-L6-v2'\n\nexport class LocalEmbeddingProvider implements IEmbeddingProvider {\n private _pipelinePromise: Promise<unknown> | null = null\n private readonly _model: string\n private readonly _dim: number\n\n constructor() {\n const hasToken = !!(process.env['HF_TOKEN'] ?? process.env['CODEORBIT_HF_TOKEN'])\n this._model = hasToken ? NOMIC_MODEL : MINILM_MODEL\n this._dim = hasToken ? 768 : 384\n }\n\n private _getPipeline(): Promise<unknown> {\n if (!this._pipelinePromise) {\n const model = this._model\n this._pipelinePromise = import('@huggingface/transformers').then((mod) => {\n const { pipeline, env } = mod as Record<string, unknown> & {\n env: Record<string, unknown>\n pipeline: (task: string, model: string) => Promise<unknown>\n }\n const hfToken = process.env['HF_TOKEN'] ?? process.env['CODEORBIT_HF_TOKEN']\n if (hfToken) env['token'] = hfToken\n return pipeline('feature-extraction', model)\n })\n }\n return this._pipelinePromise\n }\n\n async embed(texts: string[]): Promise<number[][]> {\n const pipe = (await this._getPipeline()) as (\n inputs: string[],\n opts: Record<string, unknown>,\n ) => Promise<{ data: Float32Array; dims: number[] }>\n const inputs =\n this._model === NOMIC_MODEL ? texts.map((t) => `search_document: ${t}`) : texts\n const output = await pipe(inputs, { pooling: 'mean', normalize: true })\n const dim = this._dim\n return Array.from({ length: texts.length }, (_, i) =>\n Array.from(output.data.subarray(i * dim, (i + 1) * dim)),\n )\n }\n\n async embedQuery(text: string): Promise<number[]> {\n const pipe = (await this._getPipeline()) as (\n inputs: string[],\n opts: Record<string, unknown>,\n ) => Promise<{ data: Float32Array }>\n const input = this._model === NOMIC_MODEL ? `search_query: ${text}` : text\n const output = await pipe([input], { pooling: 'mean', normalize: true })\n return Array.from(output.data)\n }\n\n get dimension(): number { return this._dim }\n\n get name(): string { return `local:${this._model.split('/')[1]}` }\n}\n","/**\n * Google Gemini embedding provider.\n *\n * Extracted from embeddings.ts::GoogleEmbeddingProvider.\n */\n\nimport { createRequire } from 'node:module'\nimport type { IEmbeddingProvider } from '../domain/ports/IEmbeddingProvider.js'\n\nconst _require = createRequire(import.meta.url)\n\nexport class GoogleEmbeddingProvider implements IEmbeddingProvider {\n private _model: {\n embedContent(req: unknown): Promise<{ embedding: { values: number[] } }>\n batchEmbedContents(req: unknown): Promise<{ embeddings: Array<{ values: number[] }> }>\n }\n private _dimension: number | null = null\n readonly modelName: string\n\n constructor(apiKey: string, model = 'gemini-embedding-001') {\n this.modelName = model\n const { GoogleGenerativeAI } = _require('@google/generative-ai') as {\n GoogleGenerativeAI: new (key: string) => {\n getGenerativeModel(opts: { model: string }): unknown\n }\n }\n const genAI = new GoogleGenerativeAI(apiKey)\n this._model = genAI.getGenerativeModel({ model }) as typeof this._model\n }\n\n private async _withRetry<T>(fn: () => Promise<T>, maxRetries = 3): Promise<T> {\n for (let attempt = 0; attempt < maxRetries; attempt++) {\n try {\n return await fn()\n } catch (e) {\n const msg = String(e)\n const retryable = msg.includes('429') || msg.includes('500') || msg.includes('503')\n if (!retryable || attempt === maxRetries - 1) throw e\n await new Promise((r) => setTimeout(r, 2 ** attempt * 1000))\n }\n }\n throw new Error('unreachable')\n }\n\n async embed(texts: string[]): Promise<number[][]> {\n const batchSize = 100\n const results: number[][] = []\n for (let i = 0; i < texts.length; i += batchSize) {\n const batch = texts.slice(i, i + batchSize)\n const response = await this._withRetry(() =>\n this._model.batchEmbedContents({\n requests: batch.map((t) => ({\n content: { parts: [{ text: t }], role: 'user' },\n taskType: 'RETRIEVAL_DOCUMENT',\n })),\n }),\n )\n results.push(...response.embeddings.map((e) => e.values))\n }\n if (this._dimension === null && results.length > 0) {\n this._dimension = results[0]!.length\n }\n return results\n }\n\n async embedQuery(text: string): Promise<number[]> {\n const response = await this._withRetry(() =>\n this._model.embedContent({\n content: { parts: [{ text }], role: 'user' },\n taskType: 'RETRIEVAL_QUERY',\n }),\n )\n const vec = response.embedding.values\n if (this._dimension === null) this._dimension = vec.length\n return vec\n }\n\n get dimension(): number { return this._dimension ?? 768 }\n\n get name(): string { return `google:${this.modelName}` }\n}\n","/**\n * File-system infrastructure helpers.\n *\n * Extracted from incremental.ts: findRepoRoot, findProjectRoot, getDbPath,\n * loadIgnorePatterns, shouldIgnore, isBinary, walkDir, collectAllFiles.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport micromatch from 'micromatch'\nimport { CodeParser } from './TreeSitterParser.js'\nimport { getAllTrackedFiles } from './GitRunner.js'\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nexport const DEFAULT_IGNORE_PATTERNS = [\n '.codeorbit/**',\n 'node_modules/**',\n '.git/**',\n '__pycache__/**',\n '*.pyc',\n '.venv/**',\n 'venv/**',\n 'dist/**',\n 'build/**',\n '.next/**',\n 'target/**',\n '*.min.js',\n '*.min.css',\n '*.map',\n '*.lock',\n 'package-lock.json',\n 'yarn.lock',\n '*.db',\n '*.sqlite',\n '*.db-journal',\n '*.db-wal',\n]\n\nexport const PRUNE_DIRS = new Set([\n 'node_modules', '.git', '__pycache__', '.next', '.nuxt', '.svelte-kit',\n 'dist', 'build', '.venv', 'venv', 'env', 'target', '.mypy_cache',\n '.pytest_cache', 'coverage', '.tox', '.cache', '.tmp', 'tmp', 'temp',\n 'vendor', 'Pods', 'DerivedData', '.gradle', '.idea', '.vs',\n])\n\nexport const DEBOUNCE_MS = 300\n\n// ---------------------------------------------------------------------------\n// Repo / DB path discovery\n// ---------------------------------------------------------------------------\n\nexport function findRepoRoot(start?: string): string | undefined {\n let current = start ?? process.cwd()\n while (true) {\n if (fs.existsSync(path.join(current, '.git'))) {\n return current\n }\n const parent = path.dirname(current)\n if (parent === current) { break }\n current = parent\n }\n return undefined\n}\n\nexport function findProjectRoot(start?: string): string {\n return findRepoRoot(start) ?? start ?? process.cwd()\n}\n\nexport function getDbPath(repoRoot: string): string {\n const crgDir = path.join(repoRoot, '.codeorbit')\n const newDb = path.join(crgDir, 'graph.db')\n\n if (!fs.existsSync(crgDir)) {\n fs.mkdirSync(crgDir, { recursive: true })\n }\n\n const innerGitignore = path.join(crgDir, '.gitignore')\n if (!fs.existsSync(innerGitignore)) {\n fs.writeFileSync(\n innerGitignore,\n '# Auto-generated by codeorbit — do not commit database files.\\n' +\n '# The graph.db contains absolute paths and code structure metadata.\\n' +\n '*\\n',\n )\n }\n\n const legacyDb = path.join(repoRoot, '.codeorbit.db')\n if (fs.existsSync(legacyDb) && !fs.existsSync(newDb)) {\n fs.renameSync(legacyDb, newDb)\n }\n for (const suffix of ['-wal', '-shm', '-journal']) {\n const side = legacyDb + suffix\n if (fs.existsSync(side)) {\n try { fs.unlinkSync(side) } catch { /* ignore */ }\n }\n }\n\n return newDb\n}\n\n// ---------------------------------------------------------------------------\n// Ignore patterns\n// ---------------------------------------------------------------------------\n\nexport function loadIgnorePatterns(repoRoot: string): string[] {\n const patterns = [...DEFAULT_IGNORE_PATTERNS]\n const ignoreFile = path.join(repoRoot, '.codeorbitignore')\n if (fs.existsSync(ignoreFile)) {\n for (const line of fs.readFileSync(ignoreFile, 'utf-8').split('\\n')) {\n const trimmed = line.trim()\n if (trimmed && !trimmed.startsWith('#')) {\n patterns.push(trimmed)\n }\n }\n }\n return patterns\n}\n\nexport function shouldIgnore(filePath: string, patterns: string[]): boolean {\n return micromatch.isMatch(filePath, patterns)\n}\n\nexport function isBinary(filePath: string): boolean {\n try {\n const chunk = Buffer.alloc(8192)\n const fd = fs.openSync(filePath, 'r')\n const bytesRead = fs.readSync(fd, chunk, 0, 8192, 0)\n fs.closeSync(fd)\n return chunk.slice(0, bytesRead).includes(0)\n } catch {\n return true\n }\n}\n\n// ---------------------------------------------------------------------------\n// File collection\n// ---------------------------------------------------------------------------\n\nfunction walkDir(dir: string, repoRoot: string): string[] {\n const files: string[] = []\n const entries = fs.readdirSync(dir, { withFileTypes: true })\n for (const entry of entries) {\n if (entry.isDirectory()) {\n if (PRUNE_DIRS.has(entry.name)) { continue }\n files.push(...walkDir(path.join(dir, entry.name), repoRoot))\n } else if (entry.isFile()) {\n const rel = path.relative(repoRoot, path.join(dir, entry.name))\n files.push(rel)\n }\n }\n return files\n}\n\nexport function collectAllFiles(repoRoot: string): string[] {\n const ignorePatterns = loadIgnorePatterns(repoRoot)\n const parser = new CodeParser()\n const files: string[] = []\n\n const tracked = getAllTrackedFiles(repoRoot)\n const candidates = tracked.length > 0 ? tracked : walkDir(repoRoot, repoRoot)\n\n for (const relPath of candidates) {\n if (shouldIgnore(relPath, ignorePatterns)) { continue }\n const fullPath = path.join(repoRoot, relPath)\n\n let stat: fs.Stats\n try {\n stat = fs.lstatSync(fullPath)\n } catch {\n continue\n }\n\n if (!stat.isFile() || stat.isSymbolicLink()) { continue }\n if (!parser.detectLanguage(fullPath)) { continue }\n if (isBinary(fullPath)) { continue }\n files.push(relPath)\n }\n\n return files\n}\n","/**\n * Git operations infrastructure.\n *\n * Extracted from incremental.ts: gitRun, getChangedFiles, getStagedAndUnstaged,\n * getAllTrackedFiles.\n */\n\nimport { spawnSync } from 'node:child_process'\n\nexport const GIT_TIMEOUT_MS = Number(process.env['CRG_GIT_TIMEOUT'] ?? 30) * 1000\n\nfunction gitRun(args: string[], cwd: string): string {\n const result = spawnSync('git', args, {\n cwd,\n encoding: 'utf-8',\n timeout: GIT_TIMEOUT_MS,\n stdio: ['ignore', 'pipe', 'ignore'],\n })\n if (result.error || result.status !== 0) {\n return ''\n }\n return result.stdout ?? ''\n}\n\nexport function getChangedFiles(repoRoot: string, base = 'HEAD~1'): string[] {\n let output = gitRun(['diff', '--name-only', base], repoRoot)\n if (!output.trim()) {\n output = gitRun(['diff', '--name-only', '--cached'], repoRoot)\n }\n return output\n .split('\\n')\n .map((f) => f.trim())\n .filter(Boolean)\n}\n\nexport function getStagedAndUnstaged(repoRoot: string): string[] {\n const output = gitRun(['status', '--porcelain'], repoRoot)\n const files: string[] = []\n for (const line of output.split('\\n')) {\n if (line.length > 3) {\n let entry = line.slice(3).trim()\n if (entry.includes(' -> ')) {\n entry = entry.split(' -> ')[1]!\n }\n files.push(entry)\n }\n }\n return files\n}\n\nexport function getAllTrackedFiles(repoRoot: string): string[] {\n const output = gitRun(['ls-files'], repoRoot)\n return output\n .split('\\n')\n .map((f) => f.trim())\n .filter(Boolean)\n}\n","/**\n * Use cases: full build and incremental update of the knowledge graph.\n *\n * Extracted from incremental.ts (fullBuild, incrementalUpdate, findDependents)\n * + tools.ts (buildOrUpdateGraph).\n *\n * Accepts IParser and IGraphRepository as parameters for testability.\n * Imports file-system and git utilities from infrastructure.\n */\n\nimport crypto from 'node:crypto'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport type { BuildResult } from '../domain/types.js'\nimport type { IParser } from '../domain/ports/IParser.js'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport {\n collectAllFiles,\n loadIgnorePatterns,\n shouldIgnore,\n} from '../infrastructure/FileSystemHelper.js'\nimport { getChangedFiles } from '../infrastructure/GitRunner.js'\n\n// ---------------------------------------------------------------------------\n// Full build\n// ---------------------------------------------------------------------------\n\nexport function fullBuild(\n repoRoot: string,\n repo: IGraphRepository,\n parser: IParser,\n): BuildResult {\n const files = collectAllFiles(repoRoot)\n\n // Purge stale data\n const existingFiles = new Set(repo.getAllFiles())\n const currentAbs = new Set(files.map((f) => path.join(repoRoot, f)))\n for (const stale of existingFiles) {\n if (!currentAbs.has(stale)) {\n repo.removeFileData(stale)\n }\n }\n\n let totalNodes = 0\n let totalEdges = 0\n const errors: string[] = []\n\n for (let i = 0; i < files.length; i++) {\n const relPath = files[i]!\n const fullPath = path.join(repoRoot, relPath)\n try {\n const source = fs.readFileSync(fullPath)\n const fhash = crypto.createHash('sha256').update(source).digest('hex')\n const [nodes, edges] = parser.parseBytes(fullPath, source)\n repo.storeFileNodesEdges(fullPath, nodes, edges, fhash)\n totalNodes += nodes.length\n totalEdges += edges.length\n } catch (err) {\n errors.push(`${relPath}: ${String(err)}`)\n }\n if ((i + 1) % 50 === 0 || i + 1 === files.length) {\n process.stderr.write(`Progress: ${i + 1}/${files.length} files parsed\\n`)\n }\n }\n\n repo.setMetadata('last_updated', new Date().toISOString().replace(/\\..+$/, ''))\n repo.setMetadata('last_build_type', 'full')\n\n return {\n buildType: 'full',\n filesUpdated: files.length,\n totalNodes,\n totalEdges,\n changedFiles: files,\n dependentFiles: [],\n errors,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Incremental update\n// ---------------------------------------------------------------------------\n\nexport function incrementalUpdate(\n repoRoot: string,\n repo: IGraphRepository,\n parser: IParser,\n base = 'HEAD~1',\n changedFiles?: string[],\n): BuildResult {\n const ignorePatterns = loadIgnorePatterns(repoRoot)\n const changed = changedFiles ?? getChangedFiles(repoRoot, base)\n\n if (changed.length === 0) {\n return {\n buildType: 'incremental',\n filesUpdated: 0,\n totalNodes: 0,\n totalEdges: 0,\n changedFiles: [],\n dependentFiles: [],\n errors: [],\n }\n }\n\n const dependentFiles = new Set<string>()\n for (const relPath of changed) {\n const fullPath = path.join(repoRoot, relPath)\n const deps = findDependents(repo, fullPath)\n for (const d of deps) {\n try {\n dependentFiles.add(path.relative(repoRoot, d))\n } catch {\n dependentFiles.add(d)\n }\n }\n }\n\n const allFiles = new Set([...changed, ...dependentFiles])\n let totalNodes = 0\n let totalEdges = 0\n const errors: string[] = []\n\n for (const relPath of allFiles) {\n if (shouldIgnore(relPath, ignorePatterns)) { continue }\n const absPath = path.join(repoRoot, relPath)\n\n if (!fs.existsSync(absPath)) {\n repo.removeFileData(absPath)\n continue\n }\n if (!parser.detectLanguage(absPath)) { continue }\n\n try {\n const source = fs.readFileSync(absPath)\n const fhash = crypto.createHash('sha256').update(source).digest('hex')\n const existingNodes = repo.getNodesByFile(absPath)\n if (existingNodes.length > 0 && existingNodes[0]!.fileHash === fhash) {\n continue\n }\n const [nodes, edges] = parser.parseBytes(absPath, source)\n repo.storeFileNodesEdges(absPath, nodes, edges, fhash)\n totalNodes += nodes.length\n totalEdges += edges.length\n } catch (err) {\n errors.push(`${relPath}: ${String(err)}`)\n }\n }\n\n repo.setMetadata('last_updated', new Date().toISOString().replace(/\\..+$/, ''))\n repo.setMetadata('last_build_type', 'incremental')\n\n return {\n buildType: 'incremental',\n filesUpdated: allFiles.size,\n totalNodes,\n totalEdges,\n changedFiles: changed,\n dependentFiles: [...dependentFiles],\n errors,\n }\n}\n\n// ---------------------------------------------------------------------------\n// Private helper\n// ---------------------------------------------------------------------------\n\nfunction findDependents(repo: IGraphRepository, filePath: string): string[] {\n const dependents = new Set<string>()\n\n for (const e of repo.getEdgesByTarget(filePath)) {\n if (e.kind === 'IMPORTS_FROM') {\n dependents.add(e.filePath)\n }\n }\n\n for (const node of repo.getNodesByFile(filePath)) {\n for (const e of repo.getEdgesByTarget(node.qualifiedName)) {\n if (['CALLS', 'IMPORTS_FROM', 'INHERITS', 'IMPLEMENTS'].includes(e.kind)) {\n dependents.add(e.filePath)\n }\n }\n }\n\n dependents.delete(filePath)\n return [...dependents]\n}\n","/**\n * Use case: compute impact radius via BFS.\n *\n * Extracted from GraphStore.getImpactRadius() so the BFS algorithm lives in\n * the application layer, independent of the SQLite infrastructure.\n */\n\nimport type { ImpactRadius } from '../domain/types.js'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\n\nexport function computeImpactRadius(\n changedFiles: string[],\n repo: IGraphRepository,\n maxDepth = 2,\n maxNodes = 500,\n): ImpactRadius {\n const adj = repo.getAdjacency()\n\n // Seed: all qualified names in changed files\n const seeds = new Set<string>()\n for (const f of changedFiles) {\n for (const node of repo.getNodesByFile(f)) {\n seeds.add(node.qualifiedName)\n }\n }\n\n const visited = new Set<string>()\n let frontier = new Set(seeds)\n const impacted = new Set<string>()\n let depth = 0\n\n while (frontier.size > 0 && depth < maxDepth) {\n const nextFrontier = new Set<string>()\n for (const qn of frontier) {\n visited.add(qn)\n const outNeighbors = adj.outgoing.get(qn)\n if (outNeighbors) {\n for (const nb of outNeighbors) {\n if (!visited.has(nb)) { nextFrontier.add(nb); impacted.add(nb) }\n }\n }\n const inNeighbors = adj.incoming.get(qn)\n if (inNeighbors) {\n for (const nb of inNeighbors) {\n if (!visited.has(nb)) { nextFrontier.add(nb); impacted.add(nb) }\n }\n }\n }\n if (visited.size + nextFrontier.size > maxNodes) { break }\n frontier = nextFrontier\n depth++\n }\n\n const changedNodes = []\n for (const qn of seeds) {\n const n = repo.getNode(qn)\n if (n) { changedNodes.push(n) }\n }\n\n let impactedNodes = []\n for (const qn of impacted) {\n if (seeds.has(qn)) { continue }\n const n = repo.getNode(qn)\n if (n) { impactedNodes.push(n) }\n }\n\n const totalImpacted = impactedNodes.length\n const truncated = totalImpacted > maxNodes\n if (truncated) { impactedNodes = impactedNodes.slice(0, maxNodes) }\n\n const impactedFiles = [...new Set(impactedNodes.map((n) => n.filePath))]\n\n const allQns = new Set([...seeds, ...impactedNodes.map((n) => n.qualifiedName)])\n const edges = allQns.size > 0 ? repo.getEdgesAmong(allQns) : []\n\n return { changedNodes, impactedNodes, impactedFiles, edges, truncated, totalImpacted }\n}\n","/**\n * Use case: predefined graph queries (callers_of, callees_of, etc.).\n *\n * Extracted from tools.ts::queryGraph.\n */\n\nimport path from 'node:path'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport { nodeToDict, edgeToDict } from '../infrastructure/SqliteGraphRepository.js'\n\n// ---------------------------------------------------------------------------\n// Constants\n// ---------------------------------------------------------------------------\n\nexport const BUILTIN_CALL_NAMES = new Set([\n 'map', 'filter', 'reduce', 'reduceRight', 'forEach', 'find', 'findIndex',\n 'some', 'every', 'includes', 'indexOf', 'lastIndexOf', 'push', 'pop',\n 'shift', 'unshift', 'splice', 'slice', 'concat', 'join', 'flat', 'flatMap',\n 'sort', 'reverse', 'fill', 'keys', 'values', 'entries', 'from', 'isArray',\n 'of', 'at', 'trim', 'trimStart', 'trimEnd', 'split', 'replace', 'replaceAll',\n 'match', 'matchAll', 'search', 'substring', 'substr', 'toLowerCase',\n 'toUpperCase', 'startsWith', 'endsWith', 'padStart', 'padEnd', 'repeat',\n 'charAt', 'charCodeAt', 'assign', 'freeze', 'defineProperty',\n 'getOwnPropertyNames', 'hasOwnProperty', 'create', 'is', 'fromEntries',\n 'log', 'warn', 'error', 'info', 'debug', 'trace', 'dir', 'table', 'time',\n 'timeEnd', 'assert', 'clear', 'count', 'then', 'catch', 'finally',\n 'resolve', 'reject', 'all', 'allSettled', 'race', 'any', 'parse',\n 'stringify', 'floor', 'ceil', 'round', 'random', 'max', 'min', 'abs',\n 'pow', 'sqrt', 'addEventListener', 'removeEventListener', 'querySelector',\n 'querySelectorAll', 'getElementById', 'createElement', 'appendChild',\n 'removeChild', 'setAttribute', 'getAttribute', 'preventDefault',\n 'stopPropagation', 'setTimeout', 'clearTimeout', 'setInterval',\n 'clearInterval', 'toString', 'valueOf', 'toJSON', 'toISOString', 'getTime',\n 'getFullYear', 'now', 'isNaN', 'parseInt', 'parseFloat', 'toFixed',\n 'encodeURIComponent', 'decodeURIComponent', 'call', 'apply', 'bind',\n 'next', 'emit', 'on', 'off', 'once', 'pipe', 'write', 'read', 'end',\n 'close', 'destroy', 'send', 'status', 'json', 'redirect', 'set', 'get',\n 'delete', 'has', 'findUnique', 'findFirst', 'findMany', 'createMany',\n 'update', 'updateMany', 'deleteMany', 'upsert', 'aggregate', 'groupBy',\n 'transaction', 'describe', 'it', 'test', 'expect', 'beforeEach',\n 'afterEach', 'beforeAll', 'afterAll', 'mock', 'spyOn', 'require', 'fetch',\n])\n\nexport const QUERY_PATTERNS: Record<string, string> = {\n callers_of: 'Find all functions that call a given function',\n callees_of: 'Find all functions called by a given function',\n imports_of: 'Find all imports of a given file or module',\n importers_of: 'Find all files that import a given file or module',\n children_of: 'Find all nodes contained in a file or class',\n tests_for: 'Find all tests for a given function or class',\n inheritors_of: 'Find all classes that inherit from a given class',\n file_summary: 'Get a summary of all nodes in a file',\n}\n\n// ---------------------------------------------------------------------------\n// Use case\n// ---------------------------------------------------------------------------\n\nexport function queryGraph(args: {\n pattern: string\n target: string\n repo: IGraphRepository\n repoRoot: string\n}): Record<string, unknown> {\n const { pattern, target, repo, repoRoot } = args\n\n if (!QUERY_PATTERNS[pattern]) {\n return {\n status: 'error',\n error: `Unknown pattern '${pattern}'. Available: ${Object.keys(QUERY_PATTERNS).join(', ')}`,\n }\n }\n\n const results: Array<Record<string, unknown>> = []\n const edgesOut: Array<Record<string, unknown>> = []\n\n if (\n pattern === 'callers_of' &&\n BUILTIN_CALL_NAMES.has(target) &&\n !target.includes('::')\n ) {\n return {\n status: 'ok',\n pattern,\n target,\n description: QUERY_PATTERNS[pattern],\n summary: `'${target}' is a common builtin — callers_of skipped to avoid noise.`,\n results: [],\n edges: [],\n }\n }\n\n let node = repo.getNode(target)\n let resolvedTarget = target\n\n if (!node) {\n const absTarget = path.join(repoRoot, target)\n node = repo.getNode(absTarget)\n if (node) { resolvedTarget = absTarget }\n }\n if (!node) {\n const candidates = repo.searchNodes(target, 5)\n if (candidates.length === 1) {\n node = candidates[0]!\n resolvedTarget = node.qualifiedName\n } else if (candidates.length > 1) {\n return {\n status: 'ambiguous',\n summary: `Multiple matches for '${target}'. Please use a qualified name.`,\n candidates: candidates.map(nodeToDict),\n }\n }\n }\n\n if (!node && pattern !== 'file_summary') {\n return { status: 'not_found', summary: `No node found matching '${target}'.` }\n }\n\n const qn = node?.qualifiedName ?? resolvedTarget\n\n if (pattern === 'callers_of') {\n for (const e of repo.getEdgesByTarget(qn)) {\n if (e.kind === 'CALLS') {\n const caller = repo.getNode(e.sourceQualified)\n if (caller) { results.push(nodeToDict(caller)) }\n edgesOut.push(edgeToDict(e))\n }\n }\n if (results.length === 0 && node) {\n for (const e of repo.searchEdgesByTargetName(node.name)) {\n const caller = repo.getNode(e.sourceQualified)\n if (caller) { results.push(nodeToDict(caller)) }\n edgesOut.push(edgeToDict(e))\n }\n }\n } else if (pattern === 'callees_of') {\n for (const e of repo.getEdgesBySource(qn)) {\n if (e.kind === 'CALLS') {\n const callee = repo.getNode(e.targetQualified)\n if (callee) { results.push(nodeToDict(callee)) }\n edgesOut.push(edgeToDict(e))\n }\n }\n } else if (pattern === 'imports_of') {\n for (const e of repo.getEdgesBySource(qn)) {\n if (e.kind === 'IMPORTS_FROM') {\n results.push({ import_target: e.targetQualified })\n edgesOut.push(edgeToDict(e))\n }\n }\n } else if (pattern === 'importers_of') {\n const absTarget = node ? node.filePath : path.join(repoRoot, target)\n for (const e of repo.getEdgesByTarget(absTarget)) {\n if (e.kind === 'IMPORTS_FROM') {\n results.push({ importer: e.sourceQualified, file: e.filePath })\n edgesOut.push(edgeToDict(e))\n }\n }\n } else if (pattern === 'children_of') {\n for (const e of repo.getEdgesBySource(qn)) {\n if (e.kind === 'CONTAINS') {\n const child = repo.getNode(e.targetQualified)\n if (child) { results.push(nodeToDict(child)) }\n }\n }\n } else if (pattern === 'tests_for') {\n for (const e of repo.getEdgesByTarget(qn)) {\n if (e.kind === 'TESTED_BY') {\n const testNode = repo.getNode(e.sourceQualified)\n if (testNode) { results.push(nodeToDict(testNode)) }\n }\n }\n const name = node?.name ?? target\n const seenQns = new Set(results.map((r) => r['qualified_name']))\n for (const t of [\n ...repo.searchNodes(`test_${name}`, 10),\n ...repo.searchNodes(`Test${name}`, 10),\n ]) {\n if (!seenQns.has(t.qualifiedName) && t.isTest) {\n results.push(nodeToDict(t))\n }\n }\n } else if (pattern === 'inheritors_of') {\n for (const e of repo.getEdgesByTarget(qn)) {\n if (e.kind === 'INHERITS' || e.kind === 'IMPLEMENTS') {\n const child = repo.getNode(e.sourceQualified)\n if (child) { results.push(nodeToDict(child)) }\n edgesOut.push(edgeToDict(e))\n }\n }\n } else if (pattern === 'file_summary') {\n const absPath = path.join(repoRoot, target)\n for (const n of repo.getNodesByFile(absPath)) {\n results.push(nodeToDict(n))\n }\n }\n\n return {\n status: 'ok',\n pattern,\n target: resolvedTarget,\n description: QUERY_PATTERNS[pattern],\n summary: `Found ${results.length} result(s) for ${pattern}('${resolvedTarget}')`,\n results,\n edges: edgesOut,\n }\n}\n","/**\n * Use case: generate focused review context for changed files.\n *\n * Extracted from tools.ts::getReviewContext + extractRelevantLines + generateReviewGuidance.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport type { ImpactRadius, GraphNode } from '../domain/types.js'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport { nodeToDict, edgeToDict } from '../infrastructure/SqliteGraphRepository.js'\nimport { computeImpactRadius } from './getImpactRadius.js'\n\nexport function getReviewContext(args: {\n changedFiles: string[]\n repo: IGraphRepository\n repoRoot: string\n maxDepth?: number\n includeSource?: boolean\n maxLinesPerFile?: number\n}): Record<string, unknown> {\n const {\n changedFiles,\n repo,\n repoRoot,\n maxDepth = 2,\n includeSource = true,\n maxLinesPerFile = 200,\n } = args\n\n if (changedFiles.length === 0) {\n return { status: 'ok', summary: 'No changes detected. Nothing to review.', context: {} }\n }\n\n const absFiles = changedFiles.map((f) => path.join(repoRoot, f))\n const impact = computeImpactRadius(absFiles, repo, maxDepth)\n\n const context: Record<string, unknown> = {\n changed_files: changedFiles,\n impacted_files: impact.impactedFiles,\n graph: {\n changed_nodes: impact.changedNodes.map(nodeToDict),\n impacted_nodes: impact.impactedNodes.map(nodeToDict),\n edges: impact.edges.map(edgeToDict),\n },\n }\n\n if (includeSource) {\n const snippets: Record<string, string> = {}\n for (const relPath of changedFiles) {\n const fullPath = path.join(repoRoot, relPath)\n if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {\n try {\n const content = fs.readFileSync(fullPath, 'utf-8')\n const lines = content.split('\\n')\n if (lines.length > maxLinesPerFile) {\n snippets[relPath] = extractRelevantLines(lines, impact.changedNodes, fullPath)\n } else {\n snippets[relPath] = lines.map((l, i) => `${i + 1}: ${l}`).join('\\n')\n }\n } catch {\n snippets[relPath] = '(could not read file)'\n }\n }\n }\n context['source_snippets'] = snippets\n }\n\n const guidance = generateReviewGuidance(impact, changedFiles)\n context['review_guidance'] = guidance\n\n const summaryParts = [\n `Review context for ${changedFiles.length} changed file(s):`,\n ` - ${impact.changedNodes.length} directly changed nodes`,\n ` - ${impact.impactedNodes.length} impacted nodes in ${impact.impactedFiles.length} files`,\n '',\n 'Review guidance:',\n guidance,\n ]\n\n return { status: 'ok', summary: summaryParts.join('\\n'), context }\n}\n\n// ---------------------------------------------------------------------------\n// Private helpers\n// ---------------------------------------------------------------------------\n\nfunction extractRelevantLines(\n lines: string[],\n nodes: GraphNode[],\n filePath: string,\n): string {\n const ranges: Array<[number, number]> = []\n for (const n of nodes) {\n if (n.filePath === filePath) {\n const start = Math.max(0, (n.lineStart ?? 1) - 3)\n const end = Math.min(lines.length, (n.lineEnd ?? lines.length) + 2)\n ranges.push([start, end])\n }\n }\n\n if (ranges.length === 0) {\n return lines.slice(0, 50).map((l, i) => `${i + 1}: ${l}`).join('\\n')\n }\n\n ranges.sort((a, b) => a[0] - b[0])\n const merged: Array<[number, number]> = [ranges[0]!]\n for (const [start, end] of ranges.slice(1)) {\n const last = merged[merged.length - 1]!\n if (start <= last[1] + 1) {\n merged[merged.length - 1] = [last[0], Math.max(last[1], end)]\n } else {\n merged.push([start, end])\n }\n }\n\n const parts: string[] = []\n for (const [start, end] of merged) {\n if (parts.length > 0) { parts.push('...') }\n for (let i = start; i < end; i++) {\n parts.push(`${i + 1}: ${lines[i] ?? ''}`)\n }\n }\n return parts.join('\\n')\n}\n\nfunction generateReviewGuidance(impact: ImpactRadius, _changedFiles: string[]): string {\n const guidanceParts: string[] = []\n\n const changedFuncs = impact.changedNodes.filter((n) => n.kind === 'Function')\n const testedFuncQns = new Set(\n impact.edges\n .filter((e) => e.kind === 'TESTED_BY')\n .map((e) => e.sourceQualified),\n )\n const untested = changedFuncs.filter(\n (f) => !testedFuncQns.has(f.qualifiedName) && !f.isTest,\n )\n if (untested.length > 0) {\n guidanceParts.push(\n `- ${untested.length} changed function(s) lack test coverage: ` +\n untested.slice(0, 5).map((n) => n.name).join(', '),\n )\n }\n\n if (impact.impactedNodes.length > 20) {\n guidanceParts.push(\n `- Wide blast radius: ${impact.impactedNodes.length} nodes impacted. ` +\n 'Review callers and dependents carefully.',\n )\n }\n\n const inheritanceEdges = impact.edges.filter(\n (e) => e.kind === 'INHERITS' || e.kind === 'IMPLEMENTS',\n )\n if (inheritanceEdges.length > 0) {\n guidanceParts.push(\n `- ${inheritanceEdges.length} inheritance/implementation relationship(s) affected. ` +\n 'Check for Liskov substitution violations.',\n )\n }\n\n if (impact.impactedFiles.length > 3) {\n guidanceParts.push(\n `- Changes impact ${impact.impactedFiles.length} other files. ` +\n 'Consider splitting into smaller PRs.',\n )\n }\n\n if (guidanceParts.length === 0) {\n guidanceParts.push('- Changes appear well-contained with minimal blast radius.')\n }\n\n return guidanceParts.join('\\n')\n}\n","/**\n * Use case: semantic or keyword search across graph nodes.\n *\n * Extracted from tools.ts::semanticSearchNodes.\n */\n\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport type { IEmbeddingStore } from '../domain/ports/IEmbeddingStore.js'\nimport { nodeToDict } from '../infrastructure/SqliteGraphRepository.js'\n\nexport async function semanticSearchNodes(args: {\n query: string\n kind?: string | null\n limit?: number\n repo: IGraphRepository\n embStore: IEmbeddingStore\n}): Promise<Record<string, unknown>> {\n const { query, kind = null, limit = 20, repo, embStore } = args\n let searchMode = 'keyword'\n\n try {\n if (embStore.available && embStore.count() > 0) {\n searchMode = 'semantic'\n let raw = await semanticSearch(query, repo, embStore, limit * 2)\n if (kind) { raw = raw.filter((r) => r['kind'] === kind) }\n raw = raw.slice(0, limit)\n return {\n status: 'ok',\n query,\n search_mode: searchMode,\n summary:\n `Found ${raw.length} node(s) matching '${query}' via semantic search` +\n (kind ? ` (kind=${kind})` : ''),\n results: raw,\n }\n }\n } catch {\n searchMode = 'keyword'\n }\n\n let results = repo.searchNodes(query, limit * 2)\n if (kind) { results = results.filter((r) => r.kind === kind) }\n\n const qLower = query.toLowerCase()\n results.sort((a, b) => {\n const aLower = a.name.toLowerCase()\n const bLower = b.name.toLowerCase()\n const aScore = aLower === qLower ? 0 : aLower.startsWith(qLower) ? 1 : 2\n const bScore = bLower === qLower ? 0 : bLower.startsWith(qLower) ? 1 : 2\n return aScore - bScore\n })\n results = results.slice(0, limit)\n\n return {\n status: 'ok',\n query,\n search_mode: searchMode,\n summary:\n `Found ${results.length} node(s) matching '${query}'` +\n (kind ? ` (kind=${kind})` : ''),\n results: results.map(nodeToDict),\n }\n}\n\nasync function semanticSearch(\n query: string,\n repo: IGraphRepository,\n embStore: IEmbeddingStore,\n limit = 20,\n): Promise<Array<Record<string, unknown>>> {\n if (embStore.available && embStore.count() > 0) {\n const results = await embStore.search(query, limit)\n const output: Array<Record<string, unknown>> = []\n for (const { qualifiedName, score } of results) {\n const node = repo.getNode(qualifiedName)\n if (node) {\n const d = nodeToDict(node)\n d['similarity_score'] = Math.round(score * 10000) / 10000\n output.push(d)\n }\n }\n return output\n }\n return repo.searchNodes(query, limit).map((n) => nodeToDict(n))\n}\n","/**\n * Use case: list aggregate graph statistics.\n *\n * Extracted from tools.ts::listGraphStats.\n */\n\nimport path from 'node:path'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport type { IEmbeddingStore } from '../domain/ports/IEmbeddingStore.js'\n\nexport function listStats(args: {\n repo: IGraphRepository\n embStore: IEmbeddingStore\n repoRoot: string\n}): Record<string, unknown> {\n const { repo, embStore, repoRoot } = args\n const stats = repo.getStats()\n const rootName = path.basename(repoRoot)\n\n const summaryParts = [\n `Graph statistics for ${rootName}:`,\n ` Files: ${stats.filesCount}`,\n ` Total nodes: ${stats.totalNodes}`,\n ` Total edges: ${stats.totalEdges}`,\n ` Languages: ${stats.languages.length > 0 ? stats.languages.join(', ') : 'none'}`,\n ` Last updated: ${stats.lastUpdated ?? 'never'}`,\n '',\n 'Nodes by kind:',\n ...Object.entries(stats.nodesByKind).sort().map(([k, c]) => ` ${k}: ${c}`),\n '',\n 'Edges by kind:',\n ...Object.entries(stats.edgesByKind).sort().map(([k, c]) => ` ${k}: ${c}`),\n ]\n\n let embCount = 0\n try {\n embCount = embStore.count()\n summaryParts.push('', `Embeddings: ${embCount} nodes embedded`)\n if (!embStore.available) {\n summaryParts.push(' (install @huggingface/transformers for semantic search)')\n }\n } catch {\n // embeddings unavailable\n }\n\n return {\n status: 'ok',\n summary: summaryParts.join('\\n'),\n total_nodes: stats.totalNodes,\n total_edges: stats.totalEdges,\n nodes_by_kind: stats.nodesByKind,\n edges_by_kind: stats.edgesByKind,\n languages: stats.languages,\n files_count: stats.filesCount,\n last_updated: stats.lastUpdated,\n embeddings_count: embCount,\n }\n}\n","/**\n * Use case: embed all graph nodes for semantic search.\n *\n * Extracted from tools.ts::embedGraph + embeddings.ts::embedAllNodes.\n */\n\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport type { IEmbeddingStore } from '../domain/ports/IEmbeddingStore.js'\n\nexport async function embedAllNodes(\n repo: IGraphRepository,\n embStore: IEmbeddingStore,\n): Promise<number> {\n if (!embStore.available) return 0\n const allNodes = []\n for (const f of repo.getAllFiles()) {\n allNodes.push(...repo.getNodesByFile(f))\n }\n return embStore.embedNodes(allNodes)\n}\n\nexport async function embedGraph(args: {\n repo: IGraphRepository\n embStore: IEmbeddingStore\n}): Promise<Record<string, unknown>> {\n const { repo, embStore } = args\n\n if (!embStore.available) {\n return {\n status: 'error',\n error:\n '@huggingface/transformers is not installed. ' +\n 'Install with: npm install codeorbit (with optional deps)',\n }\n }\n\n const newlyEmbedded = await embedAllNodes(repo, embStore)\n const total = embStore.count()\n return {\n status: 'ok',\n summary:\n `Embedded ${newlyEmbedded} new node(s). Total embeddings: ${total}. ` +\n 'Semantic search is now active.',\n newly_embedded: newlyEmbedded,\n total_embeddings: total,\n }\n}\n","/**\n * Use case: retrieve a named section from the LLM-optimized docs reference.\n *\n * Extracted from tools.ts::getDocsSection.\n */\n\nimport fs from 'node:fs'\nimport path from 'node:path'\n\nconst AVAILABLE_SECTIONS = [\n 'usage',\n 'review-delta',\n 'review-pr',\n 'commands',\n 'legal',\n 'watch',\n 'embeddings',\n 'languages',\n 'troubleshooting',\n]\n\nexport function getDocsSection(args: {\n sectionName: string\n searchRoots: string[]\n}): Record<string, unknown> {\n const { sectionName, searchRoots } = args\n\n for (const searchRoot of searchRoots) {\n const candidate = path.join(searchRoot, 'docs', 'LLM-OPTIMIZED-REFERENCE.md')\n if (fs.existsSync(candidate)) {\n const content = fs.readFileSync(candidate, 'utf-8')\n const escapedName = sectionName.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n const match = new RegExp(\n `<section name=\"${escapedName}\">(.*?)</section>`,\n 'si',\n ).exec(content)\n if (match) {\n return { status: 'ok', section: sectionName, content: match[1]!.trim() }\n }\n }\n }\n\n return {\n status: 'not_found',\n error: `Section '${sectionName}' not found. Available: ${AVAILABLE_SECTIONS.join(', ')}`,\n }\n}\n","/**\n * Use case: find functions/classes exceeding a line-count threshold.\n *\n * Extracted from tools.ts::findLargeFunctions.\n */\n\nimport path from 'node:path'\nimport type { IGraphRepository } from '../domain/ports/IGraphRepository.js'\nimport { nodeToDict } from '../infrastructure/SqliteGraphRepository.js'\n\nexport function findLargeFunctions(args: {\n minLines?: number\n kind?: string | null\n filePathPattern?: string | null\n limit?: number\n repo: IGraphRepository\n repoRoot: string\n}): Record<string, unknown> {\n const { minLines = 50, kind = null, filePathPattern = null, limit = 50, repo, repoRoot } = args\n\n const nodes = repo.getNodesBySize(\n minLines,\n undefined,\n kind ?? undefined,\n filePathPattern ?? undefined,\n limit,\n )\n\n const results = nodes.map((n) => {\n const d = nodeToDict(n) as Record<string, unknown>\n d['line_count'] =\n n.lineStart != null && n.lineEnd != null ? n.lineEnd - n.lineStart + 1 : 0\n try {\n d['relative_path'] = path.relative(repoRoot, n.filePath)\n } catch {\n d['relative_path'] = n.filePath\n }\n return d\n })\n\n const summaryParts = [\n `Found ${results.length} node(s) with >= ${minLines} lines` +\n (kind ? ` (kind=${kind})` : '') +\n (filePathPattern ? ` matching '${filePathPattern}'` : '') +\n ':',\n ]\n for (const r of results.slice(0, 10)) {\n summaryParts.push(\n ` ${String(r['line_count']).padStart(4)} lines | ${String(r['kind']).padStart(8)} | ` +\n `${r['name']} (${r['relative_path']}:${r['line_start']})`,\n )\n }\n if (results.length > 10) {\n summaryParts.push(` ... and ${results.length - 10} more`)\n }\n\n return {\n status: 'ok',\n summary: summaryParts.join('\\n'),\n total_found: results.length,\n min_lines: minLines,\n results,\n }\n}\n"],"mappings":";AAOA,SAAS,iBAAiB;AAC1B,SAAS,4BAA4B;AACrC,SAAS,SAAS;;;ACFlB,OAAOA,SAAQ;AACf,OAAOC,YAAU;;;ACCjB,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,OAAO,cAAc;AAsBrB,IAAM,aAAa;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA0DZ,IAAM,wBAAN,MAAwD;AAAA,EACrD;AAAA,EACA,WAAkC;AAAA,EACjC;AAAA,EAET,YAAY,QAAgB;AAC1B,SAAK,SAAS;AACd,UAAM,MAAM,KAAK,QAAQ,MAAM;AAC/B,QAAI,CAAC,GAAG,WAAW,GAAG,GAAG;AACvB,SAAG,UAAU,KAAK,EAAE,WAAW,KAAK,CAAC;AAAA,IACvC;AAEA,SAAK,KAAK,IAAI,SAAS,MAAM;AAC7B,SAAK,GAAG,OAAO,oBAAoB;AACnC,SAAK,GAAG,OAAO,qBAAqB;AAEpC,QAAI;AACF,WAAK,GAAG,OAAO,0BAA0B;AAAA,IAC3C,QAAQ;AAAA,IAER;AAEA,SAAK,YAAY;AAAA,EACnB;AAAA,EAEA,QAAc;AACZ,QAAI;AACF,WAAK,GAAG,OAAO,0BAA0B;AAAA,IAC3C,QAAQ;AAAA,IAER;AACA,SAAK,GAAG,MAAM;AACd,eAAW,UAAU,CAAC,QAAQ,MAAM,GA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UAAU,KAAK;AAAA,UACjB,CAAC;AAAA,QACH;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;AAMA,eAAsB,eAA8B;AAClD,QAAM,YAAY,IAAI,qBAAqB;AAC3C,QAAM,OAAO,QAAQ,SAAS;AAChC;","names":["fs","path","fs","path","path","fs","crypto","Database","createRequire","_require","Database","crypto","fs","path","fs","path","crypto","fs","path","path","fs","crypto","path","path","fs","path","path","fs","path","fs","path","path","path","path","fs","queryGraph","getReviewContext","semanticSearchNodes","embedGraph","getDocsSection","findLargeFunctions","queryGraph","getReviewContext","semanticSearchNodes","embedGraph","getDocsSection","findLargeFunctions"]}