@esankhan3/anvil-knowledge-core 0.1.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.
Files changed (126) hide show
  1. package/README.md +194 -0
  2. package/dist/__tests__/chunker.test.d.ts +10 -0
  3. package/dist/__tests__/chunker.test.d.ts.map +1 -0
  4. package/dist/__tests__/chunker.test.js +161 -0
  5. package/dist/__tests__/chunker.test.js.map +1 -0
  6. package/dist/__tests__/query-classifier.test.d.ts +5 -0
  7. package/dist/__tests__/query-classifier.test.d.ts.map +1 -0
  8. package/dist/__tests__/query-classifier.test.js +158 -0
  9. package/dist/__tests__/query-classifier.test.js.map +1 -0
  10. package/dist/__tests__/retriever-defaults.test.d.ts +12 -0
  11. package/dist/__tests__/retriever-defaults.test.d.ts.map +1 -0
  12. package/dist/__tests__/retriever-defaults.test.js +37 -0
  13. package/dist/__tests__/retriever-defaults.test.js.map +1 -0
  14. package/dist/__tests__/structural-hasher.test.d.ts +5 -0
  15. package/dist/__tests__/structural-hasher.test.d.ts.map +1 -0
  16. package/dist/__tests__/structural-hasher.test.js +185 -0
  17. package/dist/__tests__/structural-hasher.test.js.map +1 -0
  18. package/dist/ast-graph-builder.d.ts +38 -0
  19. package/dist/ast-graph-builder.d.ts.map +1 -0
  20. package/dist/ast-graph-builder.js +1041 -0
  21. package/dist/ast-graph-builder.js.map +1 -0
  22. package/dist/chunker.d.ts +47 -0
  23. package/dist/chunker.d.ts.map +1 -0
  24. package/dist/chunker.js +428 -0
  25. package/dist/chunker.js.map +1 -0
  26. package/dist/claude-runner.d.ts +10 -0
  27. package/dist/claude-runner.d.ts.map +1 -0
  28. package/dist/claude-runner.js +10 -0
  29. package/dist/claude-runner.js.map +1 -0
  30. package/dist/config.d.ts +36 -0
  31. package/dist/config.d.ts.map +1 -0
  32. package/dist/config.js +83 -0
  33. package/dist/config.js.map +1 -0
  34. package/dist/cross-repo-detector.d.ts +7 -0
  35. package/dist/cross-repo-detector.d.ts.map +1 -0
  36. package/dist/cross-repo-detector.js +990 -0
  37. package/dist/cross-repo-detector.js.map +1 -0
  38. package/dist/embedder.d.ts +84 -0
  39. package/dist/embedder.d.ts.map +1 -0
  40. package/dist/embedder.js +378 -0
  41. package/dist/embedder.js.map +1 -0
  42. package/dist/file-walker.d.ts +18 -0
  43. package/dist/file-walker.d.ts.map +1 -0
  44. package/dist/file-walker.js +221 -0
  45. package/dist/file-walker.js.map +1 -0
  46. package/dist/git-diff.d.ts +32 -0
  47. package/dist/git-diff.d.ts.map +1 -0
  48. package/dist/git-diff.js +145 -0
  49. package/dist/git-diff.js.map +1 -0
  50. package/dist/graph-metrics.d.ts +31 -0
  51. package/dist/graph-metrics.d.ts.map +1 -0
  52. package/dist/graph-metrics.js +277 -0
  53. package/dist/graph-metrics.js.map +1 -0
  54. package/dist/graph-query.d.ts +8 -0
  55. package/dist/graph-query.d.ts.map +1 -0
  56. package/dist/graph-query.js +79 -0
  57. package/dist/graph-query.js.map +1 -0
  58. package/dist/index.d.ts +27 -0
  59. package/dist/index.d.ts.map +1 -0
  60. package/dist/index.js +43 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/indexer.d.ts +98 -0
  63. package/dist/indexer.d.ts.map +1 -0
  64. package/dist/indexer.js +635 -0
  65. package/dist/indexer.js.map +1 -0
  66. package/dist/project-graph-builder-core.d.ts +48 -0
  67. package/dist/project-graph-builder-core.d.ts.map +1 -0
  68. package/dist/project-graph-builder-core.js +213 -0
  69. package/dist/project-graph-builder-core.js.map +1 -0
  70. package/dist/project-graph-builder.d.ts +39 -0
  71. package/dist/project-graph-builder.d.ts.map +1 -0
  72. package/dist/project-graph-builder.js +640 -0
  73. package/dist/project-graph-builder.js.map +1 -0
  74. package/dist/query-classifier.d.ts +38 -0
  75. package/dist/query-classifier.d.ts.map +1 -0
  76. package/dist/query-classifier.js +199 -0
  77. package/dist/query-classifier.js.map +1 -0
  78. package/dist/query-router.d.ts +82 -0
  79. package/dist/query-router.d.ts.map +1 -0
  80. package/dist/query-router.js +278 -0
  81. package/dist/query-router.js.map +1 -0
  82. package/dist/rag-evaluator.d.ts +53 -0
  83. package/dist/rag-evaluator.d.ts.map +1 -0
  84. package/dist/rag-evaluator.js +217 -0
  85. package/dist/rag-evaluator.js.map +1 -0
  86. package/dist/repo-profiler.d.ts +62 -0
  87. package/dist/repo-profiler.d.ts.map +1 -0
  88. package/dist/repo-profiler.js +488 -0
  89. package/dist/repo-profiler.js.map +1 -0
  90. package/dist/reranker.d.ts +8 -0
  91. package/dist/reranker.d.ts.map +1 -0
  92. package/dist/reranker.js +250 -0
  93. package/dist/reranker.js.map +1 -0
  94. package/dist/retriever.d.ts +42 -0
  95. package/dist/retriever.d.ts.map +1 -0
  96. package/dist/retriever.js +320 -0
  97. package/dist/retriever.js.map +1 -0
  98. package/dist/semantic-edge-detector.d.ts +28 -0
  99. package/dist/semantic-edge-detector.d.ts.map +1 -0
  100. package/dist/semantic-edge-detector.js +191 -0
  101. package/dist/semantic-edge-detector.js.map +1 -0
  102. package/dist/service-mesh-inferrer.d.ts +57 -0
  103. package/dist/service-mesh-inferrer.d.ts.map +1 -0
  104. package/dist/service-mesh-inferrer.js +322 -0
  105. package/dist/service-mesh-inferrer.js.map +1 -0
  106. package/dist/structural-hasher.d.ts +57 -0
  107. package/dist/structural-hasher.d.ts.map +1 -0
  108. package/dist/structural-hasher.js +350 -0
  109. package/dist/structural-hasher.js.map +1 -0
  110. package/dist/tree-sitter-parser.d.ts +71 -0
  111. package/dist/tree-sitter-parser.d.ts.map +1 -0
  112. package/dist/tree-sitter-parser.js +633 -0
  113. package/dist/tree-sitter-parser.js.map +1 -0
  114. package/dist/types.d.ts +179 -0
  115. package/dist/types.d.ts.map +1 -0
  116. package/dist/types.js +2 -0
  117. package/dist/types.js.map +1 -0
  118. package/dist/vector-store.d.ts +56 -0
  119. package/dist/vector-store.d.ts.map +1 -0
  120. package/dist/vector-store.js +299 -0
  121. package/dist/vector-store.js.map +1 -0
  122. package/dist/workspace-detector.d.ts +11 -0
  123. package/dist/workspace-detector.d.ts.map +1 -0
  124. package/dist/workspace-detector.js +587 -0
  125. package/dist/workspace-detector.js.map +1 -0
  126. package/package.json +41 -0
@@ -0,0 +1,1041 @@
1
+ /**
2
+ * AST graph builder — Graphify-level quality for RAG retrieval.
3
+ *
4
+ * Builds a knowledge graph from source code with:
5
+ * Phase 0: Workspace package nodes
6
+ * Phase 1: File walking + entity extraction (regex-based, multi-language)
7
+ * Phase 2: Import resolution (relative + module-path + workspace + named imports)
8
+ * Phase 3: Type reference edges from entity bodies
9
+ * Phase 4: Import-aware call disambiguation (deferred cross-file resolution)
10
+ * Phase 5: Inheritance resolution
11
+ * Phase 6: Package→file contains edges
12
+ *
13
+ * Key improvements over previous version:
14
+ * - symbolToIds (multi-candidate) replaces symbolToId (first-writer-wins)
15
+ * - Import graph used to disambiguate calls (eliminates false edges)
16
+ * - Entity-level 'uses' edges from named imports (not just file→file)
17
+ * - Type reference edges from function signatures
18
+ * - Confidence scoring on every edge (for weighted BFS in retriever)
19
+ */
20
+ import { readFileSync } from 'node:fs';
21
+ import { relative, extname, dirname, resolve, basename, join } from 'node:path';
22
+ import { walkDir, langFromExt, extractImports, extractNamedImports } from '@esankhan3/anvil-knowledge-core';
23
+ import { initTreeSitter, parseFile as tsParseFile, supportedLanguages } from '@esankhan3/anvil-knowledge-core';
24
+ // ---------------------------------------------------------------------------
25
+ // Tree-sitter integration — use AST parsing when available, regex fallback
26
+ // ---------------------------------------------------------------------------
27
+ let treeSitterReady = false;
28
+ let treeSitterSupported = new Set();
29
+ async function ensureTreeSitter() {
30
+ if (treeSitterReady)
31
+ return true;
32
+ try {
33
+ await initTreeSitter();
34
+ treeSitterSupported = new Set(supportedLanguages());
35
+ treeSitterReady = true;
36
+ return true;
37
+ }
38
+ catch {
39
+ // Tree-sitter not available — fall back to regex
40
+ return false;
41
+ }
42
+ }
43
+ async function tryTreeSitterParse(filePath, content, lang) {
44
+ if (!treeSitterReady || !treeSitterSupported.has(lang))
45
+ return null;
46
+ try {
47
+ return await tsParseFile(filePath, content, lang);
48
+ }
49
+ catch {
50
+ return null;
51
+ }
52
+ }
53
+ function tsEntityPatterns() {
54
+ return [
55
+ { regex: /^export\s+function\s+/, type: 'function', nameExtractor: (l) => l.match(/^export\s+function\s+(\w+)/)?.[1] },
56
+ { regex: /^export\s+async\s+function\s+/, type: 'function', nameExtractor: (l) => l.match(/^export\s+async\s+function\s+(\w+)/)?.[1] },
57
+ { regex: /^function\s+/, type: 'function', nameExtractor: (l) => l.match(/^function\s+(\w+)/)?.[1] },
58
+ { regex: /^async\s+function\s+/, type: 'function', nameExtractor: (l) => l.match(/^async\s+function\s+(\w+)/)?.[1] },
59
+ { regex: /^export\s+class\s+/, type: 'class', nameExtractor: (l) => l.match(/^export\s+class\s+(\w+)/)?.[1] },
60
+ { regex: /^class\s+/, type: 'class', nameExtractor: (l) => l.match(/^class\s+(\w+)/)?.[1] },
61
+ { regex: /^export\s+interface\s+/, type: 'interface', nameExtractor: (l) => l.match(/^export\s+interface\s+(\w+)/)?.[1] },
62
+ { regex: /^interface\s+/, type: 'interface', nameExtractor: (l) => l.match(/^interface\s+(\w+)/)?.[1] },
63
+ { regex: /^export\s+type\s+/, type: 'type', nameExtractor: (l) => l.match(/^export\s+type\s+(\w+)/)?.[1] },
64
+ { regex: /^type\s+/, type: 'type', nameExtractor: (l) => l.match(/^type\s+(\w+)/)?.[1] },
65
+ { regex: /^export\s+const\s+/, type: 'const', nameExtractor: (l) => l.match(/^export\s+const\s+(\w+)/)?.[1] },
66
+ ];
67
+ }
68
+ function pyEntityPatterns() {
69
+ return [
70
+ { regex: /^def\s+/, type: 'function', nameExtractor: (l) => l.match(/^def\s+(\w+)/)?.[1] },
71
+ { regex: /^async\s+def\s+/, type: 'function', nameExtractor: (l) => l.match(/^async\s+def\s+(\w+)/)?.[1] },
72
+ { regex: /^class\s+/, type: 'class', nameExtractor: (l) => l.match(/^class\s+(\w+)/)?.[1] },
73
+ ];
74
+ }
75
+ function goEntityPatterns() {
76
+ return [
77
+ { regex: /^func\s+/, type: 'function', nameExtractor: (l) => l.match(/^func\s+(?:\([^)]*\)\s+)?(\w+)/)?.[1] },
78
+ { regex: /^type\s+\w+\s+struct/, type: 'struct', nameExtractor: (l) => l.match(/^type\s+(\w+)\s+struct/)?.[1] },
79
+ { regex: /^type\s+\w+\s+interface/, type: 'interface', nameExtractor: (l) => l.match(/^type\s+(\w+)\s+interface/)?.[1] },
80
+ ];
81
+ }
82
+ function rsEntityPatterns() {
83
+ return [
84
+ { regex: /^(?:pub\s+)?fn\s+/, type: 'function', nameExtractor: (l) => l.match(/fn\s+(\w+)/)?.[1] },
85
+ { regex: /^(?:pub\s+)?struct\s+/, type: 'struct', nameExtractor: (l) => l.match(/struct\s+(\w+)/)?.[1] },
86
+ { regex: /^impl\s+/, type: 'impl', nameExtractor: (l) => l.match(/^impl\s+(?:<[^>]+>\s+)?(\w+)/)?.[1] },
87
+ { regex: /^(?:pub\s+)?trait\s+/, type: 'trait', nameExtractor: (l) => l.match(/trait\s+(\w+)/)?.[1] },
88
+ { regex: /^(?:pub\s+)?enum\s+/, type: 'enum', nameExtractor: (l) => l.match(/enum\s+(\w+)/)?.[1] },
89
+ ];
90
+ }
91
+ function javaEntityPatterns() {
92
+ return [
93
+ { regex: /(?:public|private|protected)\s+class\s+/, type: 'class', nameExtractor: (l) => l.match(/class\s+(\w+)/)?.[1] },
94
+ { regex: /(?:public|private|protected)\s+interface\s+/, type: 'interface', nameExtractor: (l) => l.match(/interface\s+(\w+)/)?.[1] },
95
+ { regex: /(?:public|private|protected)\s+(?:static\s+)?(?:void|int|long|boolean|String|[A-Z]\w*)\s+\w+\s*\(/, type: 'method', nameExtractor: (l) => l.match(/(?:void|int|long|boolean|String|[A-Z]\w*)\s+(\w+)\s*\(/)?.[1] },
96
+ ];
97
+ }
98
+ function phpEntityPatterns() {
99
+ return [
100
+ { regex: /^(?:abstract\s+)?class\s+/, type: 'class', nameExtractor: (l) => l.match(/class\s+(\w+)/)?.[1] },
101
+ { regex: /^interface\s+/, type: 'interface', nameExtractor: (l) => l.match(/interface\s+(\w+)/)?.[1] },
102
+ { regex: /^trait\s+/, type: 'trait', nameExtractor: (l) => l.match(/trait\s+(\w+)/)?.[1] },
103
+ { regex: /^(?:public|private|protected)\s+(?:static\s+)?function\s+/, type: 'method', nameExtractor: (l) => l.match(/function\s+(\w+)/)?.[1] },
104
+ { regex: /^function\s+/, type: 'function', nameExtractor: (l) => l.match(/^function\s+(\w+)/)?.[1] },
105
+ ];
106
+ }
107
+ function entityPatternsForLang(lang) {
108
+ switch (lang) {
109
+ case 'typescript':
110
+ case 'javascript':
111
+ return tsEntityPatterns();
112
+ case 'python':
113
+ return pyEntityPatterns();
114
+ case 'go':
115
+ return goEntityPatterns();
116
+ case 'rust':
117
+ return rsEntityPatterns();
118
+ case 'java':
119
+ return javaEntityPatterns();
120
+ case 'php':
121
+ return phpEntityPatterns();
122
+ default:
123
+ return tsEntityPatterns();
124
+ }
125
+ }
126
+ // ---------------------------------------------------------------------------
127
+ // Inheritance extraction
128
+ // ---------------------------------------------------------------------------
129
+ function extractInheritance(line, lang) {
130
+ const parents = [];
131
+ if (lang === 'typescript' || lang === 'javascript') {
132
+ const ext = line.match(/class\s+\w+\s+extends\s+(\w+)/);
133
+ if (ext)
134
+ parents.push(ext[1]);
135
+ const impl = line.match(/class\s+\w+(?:\s+extends\s+\w+)?\s+implements\s+([\w,\s]+)/);
136
+ if (impl)
137
+ parents.push(...impl[1].split(',').map((s) => s.trim()).filter(Boolean));
138
+ }
139
+ else if (lang === 'python') {
140
+ const m = line.match(/^class\s+\w+\(([^)]+)\)/);
141
+ if (m)
142
+ parents.push(...m[1].split(',').map((s) => s.trim()).filter((s) => s && s !== 'object'));
143
+ }
144
+ else if (lang === 'rust') {
145
+ const m = line.match(/^impl\s+(\w+)\s+for\s+(\w+)/);
146
+ if (m)
147
+ parents.push(m[1]); // trait name
148
+ }
149
+ else if (lang === 'java' || lang === 'php') {
150
+ const ext = line.match(/class\s+\w+\s+extends\s+(\w+)/);
151
+ if (ext)
152
+ parents.push(ext[1]);
153
+ const impl = line.match(/class\s+\w+(?:\s+extends\s+\w+)?\s+implements\s+([\w,\s]+)/);
154
+ if (impl)
155
+ parents.push(...impl[1].split(',').map((s) => s.trim()).filter(Boolean));
156
+ }
157
+ return parents;
158
+ }
159
+ // ---------------------------------------------------------------------------
160
+ // Type reference extraction (Phase 3)
161
+ // ---------------------------------------------------------------------------
162
+ /**
163
+ * Extract type references from an entity body.
164
+ * These create 'type-ref' edges so BFS from a function reaches its parameter/return types.
165
+ */
166
+ function extractTypeReferences(body, lang) {
167
+ const refs = new Set();
168
+ if (lang === 'typescript' || lang === 'javascript') {
169
+ // Parameter types: (param: TypeName), return types: ): TypeName
170
+ for (const m of body.matchAll(/:\s*([A-Z][A-Za-z0-9_]*)/g))
171
+ refs.add(m[1]);
172
+ // Generic type params: <TypeName>
173
+ for (const m of body.matchAll(/<([A-Z][A-Za-z0-9_]*)/g))
174
+ refs.add(m[1]);
175
+ // Type assertions: as TypeName
176
+ for (const m of body.matchAll(/\bas\s+([A-Z][A-Za-z0-9_]*)/g))
177
+ refs.add(m[1]);
178
+ // new ClassName(
179
+ for (const m of body.matchAll(/\bnew\s+([A-Z][A-Za-z0-9_]*)/g))
180
+ refs.add(m[1]);
181
+ }
182
+ else if (lang === 'python') {
183
+ // Type hints: param: TypeName, -> TypeName
184
+ for (const m of body.matchAll(/:\s*([A-Z][A-Za-z0-9_]*)/g))
185
+ refs.add(m[1]);
186
+ for (const m of body.matchAll(/->\s*([A-Z][A-Za-z0-9_]*)/g))
187
+ refs.add(m[1]);
188
+ }
189
+ else if (lang === 'go') {
190
+ // Go types: *TypeName, []TypeName, map[Key]Value, TypeName{ in signatures and bodies
191
+ for (const m of body.matchAll(/[*\[\]]\s*([A-Z][A-Za-z0-9_]*)/g))
192
+ refs.add(m[1]);
193
+ // Function parameters: name TypeName
194
+ for (const m of body.matchAll(/\w+\s+([A-Z][A-Za-z0-9_]*)[,)\s]/g))
195
+ refs.add(m[1]);
196
+ // Return types
197
+ for (const m of body.matchAll(/\)\s*(?:\()?([A-Z][A-Za-z0-9_]*)/g))
198
+ refs.add(m[1]);
199
+ }
200
+ else if (lang === 'java' || lang === 'php') {
201
+ // Type parameters: TypeName varName, return TypeName
202
+ for (const m of body.matchAll(/\b([A-Z][A-Za-z0-9_]*)\s+\$?\w+/g))
203
+ refs.add(m[1]);
204
+ // new ClassName(
205
+ for (const m of body.matchAll(/\bnew\s+([A-Z][A-Za-z0-9_]*)/g))
206
+ refs.add(m[1]);
207
+ }
208
+ else if (lang === 'rust') {
209
+ // Type annotations: -> TypeName, : TypeName
210
+ for (const m of body.matchAll(/[-:]\s*(?:&\s*(?:mut\s+)?)?([A-Z][A-Za-z0-9_]*)/g))
211
+ refs.add(m[1]);
212
+ }
213
+ // Filter out common false positives (built-in types, too-short names)
214
+ const builtins = new Set([
215
+ 'String', 'Number', 'Boolean', 'Object', 'Array', 'Map', 'Set', 'Promise',
216
+ 'Error', 'Date', 'RegExp', 'Function', 'Symbol', 'Buffer', 'Console',
217
+ 'JSON', 'Math', 'Uint8Array', 'Int32Array', 'Float64Array',
218
+ 'None', 'True', 'False', 'Self', 'Vec', 'Box', 'Option', 'Result',
219
+ 'HashMap', 'HashSet', 'Iterator', 'Exception', 'Throwable',
220
+ ]);
221
+ return [...refs].filter(r => r.length >= 3 && !builtins.has(r));
222
+ }
223
+ // ---------------------------------------------------------------------------
224
+ // Import resolution
225
+ // ---------------------------------------------------------------------------
226
+ const RESOLVE_EXTENSIONS = ['.ts', '.tsx', '.js', '.jsx', '/index.ts', '/index.js'];
227
+ function extractPackageName(importPath) {
228
+ if (importPath.startsWith('@')) {
229
+ const parts = importPath.split('/');
230
+ return parts.length >= 2 ? `${parts[0]}/${parts[1]}` : importPath;
231
+ }
232
+ const slashIdx = importPath.indexOf('/');
233
+ return slashIdx > 0 ? importPath.slice(0, slashIdx) : importPath;
234
+ }
235
+ function findOwningPackage(relPath, workspaceMap) {
236
+ let best = null;
237
+ let bestLen = -1;
238
+ for (const pkg of workspaceMap.packages) {
239
+ if (pkg.relativePath === '.')
240
+ continue;
241
+ const prefix = pkg.relativePath + '/';
242
+ if (relPath.startsWith(prefix) && prefix.length > bestLen) {
243
+ best = pkg;
244
+ bestLen = prefix.length;
245
+ }
246
+ }
247
+ return best;
248
+ }
249
+ function resolveImportPath(importPath, currentFile, knownFiles, workspaceMap) {
250
+ // 1. Relative imports
251
+ if (importPath.startsWith('.')) {
252
+ const currentDir = dirname(currentFile);
253
+ const base = resolve('/', currentDir, importPath).slice(1);
254
+ for (const ext of ['', ...RESOLVE_EXTENSIONS]) {
255
+ const candidate = base + ext;
256
+ if (knownFiles.has(candidate))
257
+ return candidate;
258
+ }
259
+ return null;
260
+ }
261
+ if (!workspaceMap)
262
+ return null;
263
+ // 2. Workspace package resolution
264
+ const pkgName = extractPackageName(importPath);
265
+ const pkg = workspaceMap.nameToPackage.get(pkgName);
266
+ if (pkg) {
267
+ if (importPath !== pkgName) {
268
+ const subPath = importPath.slice(pkgName.length + 1);
269
+ const fullSub = join(pkg.relativePath, subPath);
270
+ for (const ext of ['', ...RESOLVE_EXTENSIONS]) {
271
+ if (knownFiles.has(fullSub + ext))
272
+ return fullSub + ext;
273
+ }
274
+ const srcSub = join(pkg.relativePath, 'src', subPath);
275
+ for (const ext of ['', ...RESOLVE_EXTENSIONS]) {
276
+ if (knownFiles.has(srcSub + ext))
277
+ return srcSub + ext;
278
+ }
279
+ }
280
+ return `pkg::${pkg.name}`;
281
+ }
282
+ // 3. tsconfig path alias resolution
283
+ for (const [alias, resolvedBase] of workspaceMap.pathAliases) {
284
+ if (importPath === alias || importPath.startsWith(alias + '/')) {
285
+ const subPath = importPath === alias ? '' : importPath.slice(alias.length + 1);
286
+ const mapped = subPath ? join(resolvedBase, subPath) : resolvedBase;
287
+ for (const ext of ['', ...RESOLVE_EXTENSIONS]) {
288
+ if (knownFiles.has(mapped + ext))
289
+ return mapped + ext;
290
+ }
291
+ for (const wsPkg of workspaceMap.packages) {
292
+ if (resolvedBase.startsWith(wsPkg.relativePath)) {
293
+ return `pkg::${wsPkg.name}`;
294
+ }
295
+ }
296
+ }
297
+ }
298
+ return null;
299
+ }
300
+ // ---------------------------------------------------------------------------
301
+ // Go module path resolution
302
+ // ---------------------------------------------------------------------------
303
+ function parseGoModulePath(repoPath) {
304
+ try {
305
+ const gomod = readFileSync(join(repoPath, 'go.mod'), 'utf-8');
306
+ const m = gomod.match(/^module\s+(\S+)/m);
307
+ return m?.[1] ?? null;
308
+ }
309
+ catch {
310
+ return null;
311
+ }
312
+ }
313
+ function buildGoPackageMap(repoPath, goModulePath, knownFiles) {
314
+ // Map full Go import path → directory relative path
315
+ const pkgMap = new Map();
316
+ const goDirs = new Set();
317
+ for (const f of knownFiles) {
318
+ if (f.endsWith('.go')) {
319
+ goDirs.add(dirname(f));
320
+ }
321
+ }
322
+ for (const dir of goDirs) {
323
+ const importPath = dir === '.' ? goModulePath : `${goModulePath}/${dir}`;
324
+ pkgMap.set(importPath, dir);
325
+ }
326
+ return pkgMap;
327
+ }
328
+ function resolveGoImport(importPath, goModulePath, goPackageMap, knownFiles) {
329
+ if (!goModulePath || !importPath.startsWith(goModulePath))
330
+ return null;
331
+ const dir = goPackageMap.get(importPath);
332
+ if (!dir)
333
+ return null;
334
+ // Return the directory — Go imports are package-level
335
+ // Find any .go file in that directory to use as the target
336
+ for (const f of knownFiles) {
337
+ if (f.startsWith(dir + '/') && f.endsWith('.go') && !f.endsWith('_test.go')) {
338
+ return dir; // return the directory path as a module node
339
+ }
340
+ }
341
+ return dir;
342
+ }
343
+ // ---------------------------------------------------------------------------
344
+ // PHP namespace resolution
345
+ // ---------------------------------------------------------------------------
346
+ function parseComposerAutoload(repoPath) {
347
+ const nsMap = new Map();
348
+ try {
349
+ const composer = JSON.parse(readFileSync(join(repoPath, 'composer.json'), 'utf-8'));
350
+ const psr4 = composer?.autoload?.['psr-4'] ?? {};
351
+ for (const [ns, path] of Object.entries(psr4)) {
352
+ nsMap.set(ns, path.replace(/\/+$/, ''));
353
+ }
354
+ // Also dev autoload
355
+ const devPsr4 = composer?.['autoload-dev']?.['psr-4'] ?? {};
356
+ for (const [ns, path] of Object.entries(devPsr4)) {
357
+ nsMap.set(ns, path.replace(/\/+$/, ''));
358
+ }
359
+ }
360
+ catch { /* no composer.json */ }
361
+ return nsMap;
362
+ }
363
+ function resolvePhpImport(importPath, phpNamespaceMap, knownFiles) {
364
+ for (const [prefix, basePath] of phpNamespaceMap) {
365
+ if (importPath.startsWith(prefix)) {
366
+ const relPart = importPath.slice(prefix.length).replace(/\\/g, '/');
367
+ const candidate = basePath + '/' + relPart + '.php';
368
+ if (knownFiles.has(candidate))
369
+ return candidate;
370
+ }
371
+ }
372
+ return null;
373
+ }
374
+ // ---------------------------------------------------------------------------
375
+ // Python import resolution
376
+ // ---------------------------------------------------------------------------
377
+ function resolvePythonImport(importPath, currentFile, knownFiles) {
378
+ // Relative: from .module import ... (starts with .)
379
+ if (importPath.startsWith('.')) {
380
+ const dots = importPath.match(/^(\.+)/)?.[1].length ?? 1;
381
+ let baseDir = dirname(currentFile);
382
+ for (let i = 1; i < dots; i++)
383
+ baseDir = dirname(baseDir);
384
+ const modulePart = importPath.slice(dots);
385
+ if (!modulePart)
386
+ return null;
387
+ const candidate = join(baseDir, modulePart.replace(/\./g, '/'));
388
+ for (const ext of ['.py', '/__init__.py']) {
389
+ if (knownFiles.has(candidate + ext))
390
+ return candidate + ext;
391
+ }
392
+ return null;
393
+ }
394
+ // Absolute: from package.module import ...
395
+ const pathParts = importPath.split('.');
396
+ const candidate = pathParts.join('/');
397
+ for (const ext of ['.py', '/__init__.py']) {
398
+ if (knownFiles.has(candidate + ext))
399
+ return candidate + ext;
400
+ }
401
+ // Try stripping first segment (package name)
402
+ if (pathParts.length > 1) {
403
+ const withoutPkg = pathParts.slice(1).join('/');
404
+ for (const ext of ['.py', '/__init__.py']) {
405
+ if (knownFiles.has(withoutPkg + ext))
406
+ return withoutPkg + ext;
407
+ }
408
+ }
409
+ return null;
410
+ }
411
+ // ---------------------------------------------------------------------------
412
+ // Rust crate resolution
413
+ // ---------------------------------------------------------------------------
414
+ function resolveRustImport(importPath, knownFiles) {
415
+ // crate::module::item → src/module.rs or src/module/mod.rs
416
+ if (!importPath.startsWith('crate::'))
417
+ return null;
418
+ const parts = importPath.slice(7).split('::');
419
+ // Try progressively shorter paths (last parts might be items, not modules)
420
+ for (let len = parts.length; len > 0; len--) {
421
+ const candidate = 'src/' + parts.slice(0, len).join('/');
422
+ if (knownFiles.has(candidate + '.rs'))
423
+ return candidate + '.rs';
424
+ if (knownFiles.has(candidate + '/mod.rs'))
425
+ return candidate + '/mod.rs';
426
+ }
427
+ return null;
428
+ }
429
+ // ---------------------------------------------------------------------------
430
+ // Java import resolution
431
+ // ---------------------------------------------------------------------------
432
+ function resolveJavaImport(importPath, knownFiles) {
433
+ const filePath = importPath.replace(/\./g, '/') + '.java';
434
+ for (const prefix of ['src/main/java/', 'src/', '']) {
435
+ if (knownFiles.has(prefix + filePath))
436
+ return prefix + filePath;
437
+ }
438
+ return null;
439
+ }
440
+ // ---------------------------------------------------------------------------
441
+ // Call disambiguation (Phase 1 — import-aware)
442
+ // ---------------------------------------------------------------------------
443
+ const SKIP_CALL_NAMES = new Set([
444
+ 'if', 'else', 'for', 'while', 'switch', 'case', 'return', 'new', 'throw',
445
+ 'catch', 'try', 'await', 'yield', 'import', 'export', 'from', 'const',
446
+ 'let', 'var', 'function', 'class', 'interface', 'type', 'enum', 'struct',
447
+ 'impl', 'trait', 'fn', 'pub', 'use', 'mod', 'def', 'self', 'super',
448
+ 'this', 'true', 'false', 'null', 'undefined', 'void', 'async', 'static',
449
+ 'print', 'println', 'console', 'log', 'warn', 'error', 'info', 'debug',
450
+ 'require', 'module', 'exports', 'default', 'extends', 'implements',
451
+ 'package', 'public', 'private', 'protected', 'abstract', 'final',
452
+ 'override', 'virtual', 'delete', 'typeof', 'instanceof',
453
+ 'len', 'str', 'int', 'float', 'bool', 'list', 'dict', 'set', 'tuple',
454
+ 'range', 'map', 'filter', 'reduce', 'append', 'push', 'pop', 'shift',
455
+ 'fmt', 'err', 'nil', 'make', 'close', 'open', 'read', 'write',
456
+ ]);
457
+ /**
458
+ * Disambiguate a call target using the import graph.
459
+ * Returns the best candidate node ID or null if ambiguous/unknown.
460
+ */
461
+ function resolveCallTarget(calledName, callerFile, callerEntityId, symbolToIds, fileImportTargets) {
462
+ const candidates = symbolToIds.get(calledName);
463
+ if (!candidates || candidates.length === 0)
464
+ return null;
465
+ // Single candidate — high confidence
466
+ if (candidates.length === 1) {
467
+ if (candidates[0] === callerEntityId)
468
+ return null; // self-call
469
+ // Same file = EXTRACTED, cross-file = INFERRED
470
+ const targetFile = candidates[0].split('::')[0];
471
+ const confidence = targetFile === callerFile ? 0.9 : 0.8;
472
+ return { targetId: candidates[0], confidence };
473
+ }
474
+ // Multiple candidates — disambiguate
475
+ // 1. Same file first
476
+ const sameFile = candidates.find(c => c.startsWith(callerFile + '::') && c !== callerEntityId);
477
+ if (sameFile)
478
+ return { targetId: sameFile, confidence: 0.9 };
479
+ // 2. Imported file candidate
480
+ const callerImports = fileImportTargets.get(callerFile);
481
+ if (callerImports) {
482
+ const importedCandidate = candidates.find(c => {
483
+ const candidateFile = c.split('::')[0];
484
+ return callerImports.has(candidateFile);
485
+ });
486
+ if (importedCandidate)
487
+ return { targetId: importedCandidate, confidence: 0.85 };
488
+ }
489
+ // 3. Same directory heuristic
490
+ const callerDir = dirname(callerFile);
491
+ const sameDirCandidates = candidates.filter(c => {
492
+ const candidateFile = c.split('::')[0];
493
+ return dirname(candidateFile) === callerDir && c !== callerEntityId;
494
+ });
495
+ if (sameDirCandidates.length === 1)
496
+ return { targetId: sameDirCandidates[0], confidence: 0.65 };
497
+ // No disambiguation — drop the edge entirely (better no edge than wrong edge)
498
+ return null;
499
+ }
500
+ // ---------------------------------------------------------------------------
501
+ // Extended import resolution (uses language-specific resolvers)
502
+ // ---------------------------------------------------------------------------
503
+ function resolveImportFull(importPath, currentFile, lang, knownFiles, workspaceMap, goModulePath, goPackageMap, phpNamespaceMap) {
504
+ // 1. Try the standard resolver (relative + workspace + tsconfig)
505
+ const standard = resolveImportPath(importPath, currentFile, knownFiles, workspaceMap);
506
+ if (standard)
507
+ return standard;
508
+ // 2. Language-specific module path resolution
509
+ if (lang === 'go') {
510
+ return resolveGoImport(importPath, goModulePath, goPackageMap, knownFiles);
511
+ }
512
+ if (lang === 'php') {
513
+ return resolvePhpImport(importPath, phpNamespaceMap, knownFiles);
514
+ }
515
+ if (lang === 'python') {
516
+ return resolvePythonImport(importPath, currentFile, knownFiles);
517
+ }
518
+ if (lang === 'rust') {
519
+ return resolveRustImport(importPath, knownFiles);
520
+ }
521
+ if (lang === 'java') {
522
+ return resolveJavaImport(importPath, knownFiles);
523
+ }
524
+ return null;
525
+ }
526
+ /** Find the entity whose line range contains the given line number. */
527
+ function findEntityAtLine(entities, line) {
528
+ // Entities are sorted by line. Find the last entity that starts at or before this line.
529
+ let best = null;
530
+ for (const e of entities) {
531
+ if (e.line <= line)
532
+ best = e;
533
+ else
534
+ break;
535
+ }
536
+ return best;
537
+ }
538
+ export async function buildAstGraph(repoPath, opts) {
539
+ // Phase 0 — Walk: collect all source files
540
+ const files = [];
541
+ walkDir(repoPath, files);
542
+ const maxFiles = opts?.maxFiles ?? 5000;
543
+ const sourceFiles = files.slice(0, maxFiles);
544
+ const relPaths = new Set(sourceFiles.map((f) => relative(repoPath, f)));
545
+ const nodes = [];
546
+ const edges = [];
547
+ const entities = [];
548
+ // Store tree-sitter results per file for use in Phase 3 & 4
549
+ const tsResultByFile = new Map();
550
+ // Multi-candidate symbol map (Phase 1: replaces first-writer-wins)
551
+ const symbolToIds = new Map();
552
+ function registerSymbol(name, entityId) {
553
+ const existing = symbolToIds.get(name);
554
+ if (existing) {
555
+ existing.push(entityId);
556
+ }
557
+ else {
558
+ symbolToIds.set(name, [entityId]);
559
+ }
560
+ }
561
+ // Phase 0b — Package nodes (workspace-aware)
562
+ const wsMap = opts?.workspaceMap;
563
+ if (wsMap) {
564
+ for (const pkg of wsMap.packages) {
565
+ nodes.push({
566
+ id: `pkg::${pkg.name}`,
567
+ label: pkg.name,
568
+ type: 'package',
569
+ file: pkg.relativePath,
570
+ });
571
+ }
572
+ }
573
+ // Phase 0c — Language-specific resolvers (built once per repo)
574
+ const goModulePath = parseGoModulePath(repoPath);
575
+ const goPackageMap = goModulePath ? buildGoPackageMap(repoPath, goModulePath, relPaths) : new Map();
576
+ const phpNamespaceMap = parseComposerAutoload(repoPath);
577
+ // Per-file import targets (for call disambiguation)
578
+ const fileImportTargets = new Map();
579
+ // Initialize tree-sitter (best-effort — falls back to regex if unavailable)
580
+ await ensureTreeSitter();
581
+ // Phase 1 — Extract entities + imports (tree-sitter with regex fallback)
582
+ for (const filePath of sourceFiles) {
583
+ let content;
584
+ try {
585
+ content = readFileSync(filePath, 'utf-8');
586
+ }
587
+ catch {
588
+ continue;
589
+ }
590
+ const relPath = relative(repoPath, filePath);
591
+ const ext = extname(filePath);
592
+ const lang = langFromExt(ext);
593
+ const lines = content.split('\n');
594
+ // Module node
595
+ nodes.push({ id: relPath, label: basename(relPath), type: 'module', file: relPath });
596
+ // Try tree-sitter first, fall back to regex
597
+ const tsResult = await tryTreeSitterParse(filePath, content, lang);
598
+ if (tsResult && tsResult.entities.length > 0) {
599
+ // ── Tree-sitter path: compiler-accurate entity extraction ──
600
+ tsResultByFile.set(relPath, tsResult);
601
+ let currentClassId = null;
602
+ for (const tsEntity of tsResult.entities) {
603
+ const entityId = `${relPath}::${tsEntity.name}`;
604
+ const entityType = tsEntity.type === 'struct' ? 'struct'
605
+ : tsEntity.type === 'trait' ? 'trait'
606
+ : tsEntity.type === 'enum' ? 'enum'
607
+ : tsEntity.type === 'method' ? 'method'
608
+ : tsEntity.type;
609
+ nodes.push({ id: entityId, label: tsEntity.name, type: entityType, file: relPath });
610
+ // Extract inheritance from the entity body's first line
611
+ const firstLine = tsEntity.body.split('\n')[0] || '';
612
+ const parentNames = extractInheritance(firstLine, lang);
613
+ const entity = {
614
+ id: entityId,
615
+ label: tsEntity.name,
616
+ type: entityType,
617
+ file: relPath,
618
+ line: tsEntity.startLine,
619
+ indent: 0,
620
+ parents: parentNames,
621
+ };
622
+ entities.push(entity);
623
+ registerSymbol(tsEntity.name, entityId);
624
+ // Contains edge — methods belong to their parent class
625
+ if (tsEntity.parent) {
626
+ const parentId = `${relPath}::${tsEntity.parent}`;
627
+ edges.push({ source: parentId, target: entityId, type: 'contains', confidence: 1.0 });
628
+ registerSymbol(`${tsEntity.parent}.${tsEntity.name}`, entityId);
629
+ }
630
+ else {
631
+ edges.push({ source: relPath, target: entityId, type: 'contains', confidence: 1.0 });
632
+ }
633
+ if (entityType === 'class' || entityType === 'struct' || entityType === 'interface' || entityType === 'trait') {
634
+ currentClassId = entityId;
635
+ }
636
+ }
637
+ }
638
+ else {
639
+ // ── Regex fallback path ──
640
+ const patterns = entityPatternsForLang(lang);
641
+ let currentClassId = null;
642
+ let currentClassIndent = -1;
643
+ for (let i = 0; i < lines.length; i++) {
644
+ const line = lines[i];
645
+ const trimmed = line.trimStart();
646
+ const indent = line.length - trimmed.length;
647
+ if (currentClassId && indent <= currentClassIndent) {
648
+ currentClassId = null;
649
+ currentClassIndent = -1;
650
+ }
651
+ for (const pat of patterns) {
652
+ if (!pat.regex.test(trimmed))
653
+ continue;
654
+ const name = pat.nameExtractor(trimmed);
655
+ if (!name)
656
+ break;
657
+ const entityId = `${relPath}::${name}`;
658
+ const parentNames = extractInheritance(trimmed, lang);
659
+ nodes.push({ id: entityId, label: name, type: pat.type, file: relPath });
660
+ const entity = {
661
+ id: entityId,
662
+ label: name,
663
+ type: pat.type,
664
+ file: relPath,
665
+ line: i,
666
+ indent,
667
+ parents: parentNames,
668
+ };
669
+ entities.push(entity);
670
+ registerSymbol(name, entityId);
671
+ if (currentClassId && indent > currentClassIndent && (pat.type === 'function' || pat.type === 'method')) {
672
+ edges.push({ source: currentClassId, target: entityId, type: 'contains', confidence: 1.0 });
673
+ const className = currentClassId.split('::').pop();
674
+ if (className)
675
+ registerSymbol(`${className}.${name}`, entityId);
676
+ }
677
+ else {
678
+ edges.push({ source: relPath, target: entityId, type: 'contains', confidence: 1.0 });
679
+ }
680
+ if (pat.type === 'class' || pat.type === 'struct' || pat.type === 'interface' || pat.type === 'trait') {
681
+ currentClassId = entityId;
682
+ currentClassIndent = indent;
683
+ }
684
+ break;
685
+ }
686
+ }
687
+ }
688
+ // Phase 2a — Import edges (file-level + entity-level 'uses')
689
+ const importSpecs = extractImports(lines, lang);
690
+ const importTargetSet = new Set();
691
+ for (const spec of importSpecs) {
692
+ const resolved = resolveImportFull(spec, relPath, lang, relPaths, wsMap, goModulePath, goPackageMap, phpNamespaceMap);
693
+ if (resolved) {
694
+ edges.push({ source: relPath, target: resolved, type: 'imports', confidence: 1.0 });
695
+ importTargetSet.add(resolved);
696
+ }
697
+ }
698
+ // Phase 2b — Entity-level 'uses' edges from named imports
699
+ const namedImports = extractNamedImports(lines, lang);
700
+ for (const ni of namedImports) {
701
+ const resolved = resolveImportFull(ni.specifier, relPath, lang, relPaths, wsMap, goModulePath, goPackageMap, phpNamespaceMap);
702
+ if (!resolved)
703
+ continue;
704
+ importTargetSet.add(resolved);
705
+ for (const name of ni.names) {
706
+ // Look for the specific entity in the target file
707
+ const targetEntityId = `${resolved}::${name}`;
708
+ const candidates = symbolToIds.get(name);
709
+ if (candidates?.includes(targetEntityId)) {
710
+ edges.push({ source: relPath, target: targetEntityId, type: 'uses', confidence: 0.95 });
711
+ }
712
+ else if (candidates && candidates.length === 1) {
713
+ // Single candidate with the imported name — likely correct
714
+ edges.push({ source: relPath, target: candidates[0], type: 'uses', confidence: 0.85 });
715
+ }
716
+ }
717
+ }
718
+ fileImportTargets.set(relPath, importTargetSet);
719
+ }
720
+ // Phase 3 — Type reference edges
721
+ const entityByFile = new Map();
722
+ for (const e of entities) {
723
+ const list = entityByFile.get(e.file) || [];
724
+ list.push(e);
725
+ entityByFile.set(e.file, list);
726
+ }
727
+ for (const filePath of sourceFiles) {
728
+ const relPath = relative(repoPath, filePath);
729
+ const fileEntities = entityByFile.get(relPath);
730
+ if (!fileEntities || fileEntities.length === 0)
731
+ continue;
732
+ // Use tree-sitter type references when available (file-level, more complete)
733
+ const tsResult = tsResultByFile.get(relPath);
734
+ if (tsResult && tsResult.typeReferences.length > 0) {
735
+ // Tree-sitter extracted all type references from the file — resolve each
736
+ const seenTypeRefs = new Set();
737
+ for (const typeName of tsResult.typeReferences) {
738
+ if (seenTypeRefs.has(typeName))
739
+ continue;
740
+ seenTypeRefs.add(typeName);
741
+ // Attribute to the first entity in the file or the file itself
742
+ const sourceId = fileEntities[0]?.id ?? relPath;
743
+ const resolved = resolveCallTarget(typeName, relPath, sourceId, symbolToIds, fileImportTargets);
744
+ if (resolved) {
745
+ edges.push({ source: sourceId, target: resolved.targetId, type: 'type-ref', confidence: Math.min(resolved.confidence, 0.85) });
746
+ }
747
+ }
748
+ }
749
+ else {
750
+ // Regex fallback — scan entity bodies (limited to 30 lines each)
751
+ let content;
752
+ try {
753
+ content = readFileSync(filePath, 'utf-8');
754
+ }
755
+ catch {
756
+ continue;
757
+ }
758
+ const lines = content.split('\n');
759
+ const lang = langFromExt(extname(filePath));
760
+ for (let ei = 0; ei < fileEntities.length; ei++) {
761
+ const entity = fileEntities[ei];
762
+ const startLine = entity.line;
763
+ const endLine = ei + 1 < fileEntities.length ? fileEntities[ei + 1].line : lines.length;
764
+ const body = lines.slice(startLine, Math.min(startLine + 30, endLine)).join('\n');
765
+ const typeRefs = extractTypeReferences(body, lang);
766
+ for (const typeName of typeRefs) {
767
+ const resolved = resolveCallTarget(typeName, entity.file, entity.id, symbolToIds, fileImportTargets);
768
+ if (resolved) {
769
+ edges.push({ source: entity.id, target: resolved.targetId, type: 'type-ref', confidence: Math.min(resolved.confidence, 0.85) });
770
+ }
771
+ }
772
+ }
773
+ }
774
+ }
775
+ // Phase 4 — Import-aware call disambiguation (deferred cross-file resolution)
776
+ // Uses tree-sitter call sites when available for precise caller→callee attribution,
777
+ // falls back to regex scanning for files without tree-sitter support.
778
+ for (const filePath of sourceFiles) {
779
+ const relPath = relative(repoPath, filePath);
780
+ const fileEntities = entityByFile.get(relPath);
781
+ if (!fileEntities || fileEntities.length === 0)
782
+ continue;
783
+ const tsResult = tsResultByFile.get(relPath);
784
+ if (tsResult && tsResult.callSites.length > 0) {
785
+ // ── Tree-sitter path: precise call sites with containing entity ──
786
+ const seenEdges = new Set();
787
+ for (const callSite of tsResult.callSites) {
788
+ const calledName = callSite.callee;
789
+ if (calledName.length < 3)
790
+ continue;
791
+ if (SKIP_CALL_NAMES.has(calledName))
792
+ continue;
793
+ // Determine the calling entity — tree-sitter provides containingEntity
794
+ let sourceEntityId;
795
+ if (callSite.containingEntity) {
796
+ sourceEntityId = `${relPath}::${callSite.containingEntity}`;
797
+ // Verify this entity exists (might be a nested name)
798
+ if (!fileEntities.some(e => e.id === sourceEntityId)) {
799
+ // Fall back to line-based entity lookup
800
+ sourceEntityId = findEntityAtLine(fileEntities, callSite.startLine)?.id ?? relPath;
801
+ }
802
+ }
803
+ else {
804
+ // Module-level call — attribute to file or nearest entity
805
+ sourceEntityId = findEntityAtLine(fileEntities, callSite.startLine)?.id ?? relPath;
806
+ }
807
+ // Deduplicate: same source→callee pair
808
+ const edgeKey = `${sourceEntityId}→${calledName}`;
809
+ if (seenEdges.has(edgeKey))
810
+ continue;
811
+ seenEdges.add(edgeKey);
812
+ const resolved = resolveCallTarget(calledName, relPath, sourceEntityId, symbolToIds, fileImportTargets);
813
+ if (resolved) {
814
+ // Tree-sitter call sites are more reliable — boost confidence slightly
815
+ const confidence = Math.min(resolved.confidence + 0.05, 1.0);
816
+ edges.push({ source: sourceEntityId, target: resolved.targetId, type: 'calls', confidence });
817
+ }
818
+ }
819
+ }
820
+ else {
821
+ // ── Regex fallback path ──
822
+ let content;
823
+ try {
824
+ content = readFileSync(filePath, 'utf-8');
825
+ }
826
+ catch {
827
+ continue;
828
+ }
829
+ const lines = content.split('\n');
830
+ for (let ei = 0; ei < fileEntities.length; ei++) {
831
+ const entity = fileEntities[ei];
832
+ const startLine = entity.line;
833
+ const endLine = ei + 1 < fileEntities.length ? fileEntities[ei + 1].line : lines.length;
834
+ const body = lines.slice(startLine, endLine).join('\n');
835
+ const callRegex = /\b([a-zA-Z_]\w*)\s*\(/g;
836
+ let match;
837
+ const seenCalls = new Set();
838
+ while ((match = callRegex.exec(body)) !== null) {
839
+ const calledName = match[1];
840
+ if (calledName.length < 3)
841
+ continue;
842
+ if (SKIP_CALL_NAMES.has(calledName))
843
+ continue;
844
+ if (seenCalls.has(calledName))
845
+ continue;
846
+ seenCalls.add(calledName);
847
+ const resolved = resolveCallTarget(calledName, entity.file, entity.id, symbolToIds, fileImportTargets);
848
+ if (resolved) {
849
+ edges.push({ source: entity.id, target: resolved.targetId, type: 'calls', confidence: resolved.confidence });
850
+ }
851
+ }
852
+ }
853
+ }
854
+ }
855
+ // Phase 5 — Inheritance edges (deferred, resolved against multi-candidate map)
856
+ for (const entity of entities) {
857
+ for (const parent of entity.parents) {
858
+ const candidates = symbolToIds.get(parent);
859
+ if (!candidates || candidates.length === 0)
860
+ continue;
861
+ if (candidates.length === 1) {
862
+ edges.push({ source: entity.id, target: candidates[0], type: 'inherits', confidence: 0.95 });
863
+ }
864
+ else {
865
+ // Prefer same-file or imported candidate
866
+ const resolved = resolveCallTarget(parent, entity.file, entity.id, symbolToIds, fileImportTargets);
867
+ if (resolved) {
868
+ edges.push({ source: entity.id, target: resolved.targetId, type: 'inherits', confidence: resolved.confidence });
869
+ }
870
+ }
871
+ }
872
+ }
873
+ // Phase 6 — Package→file contains edges (workspace-aware)
874
+ if (wsMap) {
875
+ for (const relPath of relPaths) {
876
+ const owning = findOwningPackage(relPath, wsMap);
877
+ if (owning) {
878
+ edges.push({ source: `pkg::${owning.name}`, target: relPath, type: 'contains', confidence: 1.0 });
879
+ }
880
+ }
881
+ }
882
+ return { nodes, links: edges };
883
+ }
884
+ // ---------------------------------------------------------------------------
885
+ // Report generation
886
+ // ---------------------------------------------------------------------------
887
+ export function generateGraphReport(repoName, graph) {
888
+ const sections = [];
889
+ sections.push(`# Knowledge Graph Report: ${repoName}`);
890
+ sections.push(`\n> Auto-generated by Anvil AST graph builder.\n`);
891
+ const nodeCount = graph.nodes.length;
892
+ const edgeCount = graph.links.length;
893
+ const fileNodes = graph.nodes.filter((n) => n.type === 'module');
894
+ sections.push(`## Overview\n`);
895
+ sections.push(`- **Files:** ${fileNodes.length}`);
896
+ sections.push(`- **Entities:** ${nodeCount - fileNodes.length}`);
897
+ sections.push(`- **Total nodes:** ${nodeCount}`);
898
+ sections.push(`- **Total edges:** ${edgeCount}`);
899
+ // Edge type distribution
900
+ const edgeTypeCounts = new Map();
901
+ for (const e of graph.links) {
902
+ const t = e.type || 'unknown';
903
+ edgeTypeCounts.set(t, (edgeTypeCounts.get(t) || 0) + 1);
904
+ }
905
+ sections.push(`\n### Edge Types\n`);
906
+ sections.push('| Type | Count | Avg Confidence |');
907
+ sections.push('|------|-------|----------------|');
908
+ for (const [type, count] of [...edgeTypeCounts.entries()].sort((a, b) => b[1] - a[1])) {
909
+ const edgesOfType = graph.links.filter(e => e.type === type);
910
+ const avgConf = edgesOfType.reduce((sum, e) => sum + (e.confidence ?? 0), 0) / edgesOfType.length;
911
+ sections.push(`| ${type} | ${count} | ${avgConf.toFixed(2)} |`);
912
+ }
913
+ // Entity type distribution
914
+ const entityTypeCounts = new Map();
915
+ for (const n of graph.nodes) {
916
+ const t = n.type || 'unknown';
917
+ entityTypeCounts.set(t, (entityTypeCounts.get(t) || 0) + 1);
918
+ }
919
+ sections.push(`\n### Entity Types\n`);
920
+ sections.push('| Type | Count |');
921
+ sections.push('|------|-------|');
922
+ for (const [type, count] of [...entityTypeCounts.entries()].sort((a, b) => b[1] - a[1])) {
923
+ sections.push(`| ${type} | ${count} |`);
924
+ }
925
+ // Top 10 hotspots by edge degree
926
+ const degreeMap = new Map();
927
+ for (const e of graph.links) {
928
+ degreeMap.set(e.source, (degreeMap.get(e.source) || 0) + 1);
929
+ degreeMap.set(e.target, (degreeMap.get(e.target) || 0) + 1);
930
+ }
931
+ const topNodes = [...degreeMap.entries()]
932
+ .sort((a, b) => b[1] - a[1])
933
+ .slice(0, 10);
934
+ if (topNodes.length > 0) {
935
+ sections.push(`\n### Hotspots (Top 10 by edge degree)\n`);
936
+ sections.push('| Node | Degree | Type |');
937
+ sections.push('|------|--------|------|');
938
+ for (const [nodeId, degree] of topNodes) {
939
+ const node = graph.nodes.find((n) => n.id === nodeId);
940
+ sections.push(`| ${nodeId} | ${degree} | ${node?.type || '-'} |`);
941
+ }
942
+ }
943
+ // Import dependency summary
944
+ const importEdges = graph.links.filter((e) => e.type === 'imports' || e.type === 'uses');
945
+ const importCounts = new Map();
946
+ for (const e of importEdges) {
947
+ importCounts.set(e.source, (importCounts.get(e.source) || 0) + 1);
948
+ }
949
+ const topImporters = [...importCounts.entries()]
950
+ .sort((a, b) => b[1] - a[1])
951
+ .slice(0, 10);
952
+ if (topImporters.length > 0) {
953
+ sections.push(`\n### Top Importers\n`);
954
+ sections.push('| File | Import Count |');
955
+ sections.push('|------|-------------|');
956
+ for (const [file, count] of topImporters) {
957
+ sections.push(`| ${file} | ${count} |`);
958
+ }
959
+ }
960
+ return sections.join('\n');
961
+ }
962
+ // ---------------------------------------------------------------------------
963
+ // Incremental graph update
964
+ // ---------------------------------------------------------------------------
965
+ /**
966
+ * Incrementally update an AST graph when only some files changed.
967
+ * Instead of rebuilding the entire graph, this:
968
+ * 1. Removes nodes/edges for changed + deleted files
969
+ * 2. Re-parses only the changed files
970
+ * 3. Re-resolves edges affected by the changes
971
+ *
972
+ * Falls back to full rebuild if incremental update fails.
973
+ */
974
+ export async function incrementalGraphUpdate(existingGraph, changedFiles, deletedFiles, repoPath, opts) {
975
+ // If more than 30% of files changed, full rebuild is faster
976
+ const totalFiles = new Set(existingGraph.nodes.filter(n => n.file).map(n => n.file)).size;
977
+ const changedCount = changedFiles.length + deletedFiles.length;
978
+ if (totalFiles === 0 || changedCount / totalFiles > 0.3) {
979
+ return buildAstGraph(repoPath, opts);
980
+ }
981
+ try {
982
+ // 1. Identify nodes to remove (from changed + deleted files)
983
+ const filesToRemove = new Set([...changedFiles, ...deletedFiles]);
984
+ const removedNodeIds = new Set();
985
+ for (const node of existingGraph.nodes) {
986
+ if (node.file && filesToRemove.has(node.file)) {
987
+ removedNodeIds.add(node.id);
988
+ }
989
+ }
990
+ // Also remove module nodes for these files
991
+ for (const node of existingGraph.nodes) {
992
+ if (node.type === 'module' && node.file && filesToRemove.has(node.file)) {
993
+ removedNodeIds.add(node.id);
994
+ }
995
+ }
996
+ // 2. Keep nodes and edges NOT connected to removed nodes
997
+ const keptNodes = existingGraph.nodes.filter(n => !removedNodeIds.has(n.id));
998
+ const keptEdges = existingGraph.links.filter(e => !removedNodeIds.has(e.source) && !removedNodeIds.has(e.target));
999
+ // 3. Re-parse only changed files using the full builder
1000
+ // Build a mini-graph for just the changed files, then merge
1001
+ if (changedFiles.length === 0) {
1002
+ // Only deletions — return the pruned graph
1003
+ return { nodes: keptNodes, links: keptEdges };
1004
+ }
1005
+ // Build fresh graph for the whole repo (only way to get correct cross-file resolution)
1006
+ // but this is the fallback — for true surgical update we'd need per-file parsing
1007
+ // For now, rebuild full and it will be fast since graph building is already fast (~seconds)
1008
+ const freshGraph = await buildAstGraph(repoPath, opts);
1009
+ // Extract only nodes/edges from changed files in the fresh graph
1010
+ const changedFileSet = new Set(changedFiles);
1011
+ const newNodes = freshGraph.nodes.filter(n => n.file && changedFileSet.has(n.file));
1012
+ const newNodeIds = new Set(newNodes.map(n => n.id));
1013
+ // Edges: keep edges from fresh graph that touch new nodes OR connect to kept nodes
1014
+ const keptNodeIds = new Set(keptNodes.map(n => n.id));
1015
+ const newEdges = freshGraph.links.filter(e => {
1016
+ const sourceIsNew = newNodeIds.has(e.source);
1017
+ const targetIsNew = newNodeIds.has(e.target);
1018
+ const sourceExists = keptNodeIds.has(e.source) || newNodeIds.has(e.source);
1019
+ const targetExists = keptNodeIds.has(e.target) || newNodeIds.has(e.target);
1020
+ // Keep edge if both endpoints exist and at least one is from changed files
1021
+ return sourceExists && targetExists && (sourceIsNew || targetIsNew);
1022
+ });
1023
+ // Also keep edges between existing nodes that reference entities from changed files
1024
+ // (e.g., if file B imports from changed file A, B's import edge should be updated)
1025
+ const updatedEdges = freshGraph.links.filter(e => {
1026
+ const sourceKept = keptNodeIds.has(e.source);
1027
+ const targetNew = newNodeIds.has(e.target);
1028
+ return sourceKept && targetNew;
1029
+ });
1030
+ return {
1031
+ nodes: [...keptNodes, ...newNodes],
1032
+ links: [...keptEdges, ...newEdges, ...updatedEdges],
1033
+ };
1034
+ }
1035
+ catch (err) {
1036
+ // Incremental update failed — fall back to full rebuild
1037
+ console.warn(`[ast-graph] Incremental update failed, falling back to full rebuild: ${err}`);
1038
+ return buildAstGraph(repoPath, opts);
1039
+ }
1040
+ }
1041
+ //# sourceMappingURL=ast-graph-builder.js.map