graph-indexer 2.1.1 → 3.0.1

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 (131) hide show
  1. package/CHANGELOG.md +312 -1
  2. package/README.md +236 -312
  3. package/SECURITY.md +53 -58
  4. package/bin/graph-indexer.mjs +251 -0
  5. package/integrations/claude-code/.claude-plugin/plugin.json +9 -0
  6. package/integrations/claude-code/.mcp.json +8 -0
  7. package/integrations/claude-code/agents/code-structure.md +22 -0
  8. package/integrations/claude-code/hooks/gi-hook.mjs +103 -0
  9. package/integrations/claude-code/hooks/hooks.json +16 -0
  10. package/integrations/opencode/graph-indexer.js +129 -0
  11. package/package.json +32 -109
  12. package/src/cli/helper.mjs +67 -0
  13. package/src/cli/hook.mjs +366 -0
  14. package/src/cli/init.mjs +272 -0
  15. package/src/cli/resident.mjs +185 -0
  16. package/src/index/discover.mjs +128 -0
  17. package/src/index/fingerprint.mjs +30 -0
  18. package/src/index/graph.mjs +61 -0
  19. package/src/index/indexer.mjs +476 -0
  20. package/src/index/modules.mjs +332 -0
  21. package/src/index/resolver.mjs +961 -0
  22. package/src/mcp/render.mjs +60 -0
  23. package/src/mcp/server.mjs +147 -0
  24. package/src/mcp/tools.mjs +974 -0
  25. package/src/parse/arity.mjs +153 -0
  26. package/src/parse/extract.mjs +1038 -0
  27. package/src/parse/lang/csharp.mjs +106 -0
  28. package/src/parse/lang/ecma.mjs +438 -0
  29. package/src/parse/lang/go.mjs +194 -0
  30. package/src/parse/lang/jvm.mjs +118 -0
  31. package/src/parse/lang/kotlin.mjs +97 -0
  32. package/src/parse/lang/misc.mjs +115 -0
  33. package/src/parse/lang/native.mjs +126 -0
  34. package/src/parse/lang/python.mjs +153 -0
  35. package/src/parse/lang/rust.mjs +157 -0
  36. package/src/parse/lang/scripting.mjs +219 -0
  37. package/src/parse/languages.mjs +48 -0
  38. package/src/parse/runtime.mjs +56 -0
  39. package/src/query/check.mjs +345 -0
  40. package/src/query/facts.mjs +323 -0
  41. package/src/query/intel.mjs +683 -0
  42. package/src/query/read.mjs +81 -0
  43. package/src/query/testcmd.mjs +130 -0
  44. package/src/query/textsearch.mjs +178 -0
  45. package/src/search/search.mjs +210 -0
  46. package/src/search/tokenize.mjs +188 -0
  47. package/src/store/db.mjs +169 -0
  48. package/src/util/git.mjs +30 -0
  49. package/src/util/paths.mjs +63 -0
  50. package/src/util/regex.mjs +2 -0
  51. package/vendor/grammars/bash.wasm.gz +0 -0
  52. package/vendor/grammars/c.wasm.gz +0 -0
  53. package/vendor/grammars/c_sharp.wasm.gz +0 -0
  54. package/vendor/grammars/cpp.wasm.gz +0 -0
  55. package/vendor/grammars/css.wasm.gz +0 -0
  56. package/vendor/grammars/go.wasm.gz +0 -0
  57. package/vendor/grammars/java.wasm.gz +0 -0
  58. package/vendor/grammars/javascript.wasm.gz +0 -0
  59. package/vendor/grammars/kotlin.wasm.gz +0 -0
  60. package/vendor/grammars/manifest.json +148 -0
  61. package/vendor/grammars/php.wasm.gz +0 -0
  62. package/vendor/grammars/python.wasm.gz +0 -0
  63. package/vendor/grammars/ruby.wasm.gz +0 -0
  64. package/vendor/grammars/rust.wasm.gz +0 -0
  65. package/vendor/grammars/scala.wasm.gz +0 -0
  66. package/vendor/grammars/tsx.wasm.gz +0 -0
  67. package/vendor/grammars/typescript.wasm.gz +0 -0
  68. package/vendor/web-tree-sitter/web-tree-sitter.js +3980 -0
  69. package/vendor/web-tree-sitter/web-tree-sitter.wasm +0 -0
  70. package/cli-ui.mjs +0 -78
  71. package/colbert.mjs +0 -168
  72. package/config.mjs +0 -494
  73. package/daemon-ctl.mjs +0 -175
  74. package/daemon-lock.mjs +0 -69
  75. package/embedders/python/mlx_embed_server.py +0 -61
  76. package/embedders/python/requirements-mlx.txt +0 -5
  77. package/embedders/setup-mlx.mjs +0 -110
  78. package/embeddings.mjs +0 -571
  79. package/engine/binary.mjs +0 -437
  80. package/engine/memory.mjs +0 -1003
  81. package/engine/sqlite.mjs +0 -1136
  82. package/enrichment.mjs +0 -521
  83. package/git-signals.mjs +0 -248
  84. package/indexer.mjs +0 -546
  85. package/init.mjs +0 -1809
  86. package/layout.mjs +0 -123
  87. package/mcp/centrality.mjs +0 -117
  88. package/mcp/format.mjs +0 -61
  89. package/mcp/resolver.mjs +0 -116
  90. package/mcp/symbolgraph.mjs +0 -137
  91. package/mcp/taint.mjs +0 -225
  92. package/mcp/tools.mjs +0 -1582
  93. package/mcp/topology.mjs +0 -676
  94. package/mcp-server.mjs +0 -197
  95. package/parse/extractor.mjs +0 -628
  96. package/parse/imports.mjs +0 -365
  97. package/parse/interprocedural.mjs +0 -134
  98. package/parse/languages.mjs +0 -253
  99. package/parse/metadata.mjs +0 -701
  100. package/parse/routes.mjs +0 -327
  101. package/parse/scip.mjs +0 -391
  102. package/parse/taint-patterns.mjs +0 -119
  103. package/prompts/CORE.md +0 -91
  104. package/prompts/DOMAIN_TEMPLATE.md +0 -46
  105. package/prompts/INTEGRATION.md +0 -123
  106. package/prompts/frameworks/ANDROID.md +0 -17
  107. package/prompts/frameworks/ASPNET_CORE.md +0 -19
  108. package/prompts/frameworks/FASTAPI_DJANGO.md +0 -20
  109. package/prompts/frameworks/LARAVEL_SYMFONY.md +0 -22
  110. package/prompts/frameworks/NODE_EXPRESS_NESTJS.md +0 -19
  111. package/prompts/frameworks/RAILS.md +0 -20
  112. package/prompts/frameworks/REACT.md +0 -20
  113. package/prompts/frameworks/SPRING_BOOT.md +0 -20
  114. package/prompts/languages/BASH.md +0 -22
  115. package/prompts/languages/C.md +0 -21
  116. package/prompts/languages/CSHARP.md +0 -24
  117. package/prompts/languages/CSS_SCSS.md +0 -22
  118. package/prompts/languages/GO.md +0 -24
  119. package/prompts/languages/JAVA.md +0 -23
  120. package/prompts/languages/JAVASCRIPT_TYPESCRIPT.md +0 -24
  121. package/prompts/languages/KOTLIN.md +0 -24
  122. package/prompts/languages/PHP.md +0 -23
  123. package/prompts/languages/PYTHON.md +0 -23
  124. package/prompts/languages/RUBY.md +0 -23
  125. package/prompts/languages/RUST.md +0 -21
  126. package/prompts/languages/SWIFT.md +0 -21
  127. package/seal.mjs +0 -400
  128. package/search-core.mjs +0 -777
  129. package/search-sparse.mjs +0 -183
  130. package/storage.mjs +0 -73
  131. package/watch-daemon.mjs +0 -289
@@ -1,628 +0,0 @@
1
- /**
2
- * @file parse/extractor.mjs
3
- * @description File-level AST extraction: ignore filter, chunk hashing,
4
- * file skeleton, import extraction, and semantic chunking.
5
- * @author MaquinaTech <https://github.com/MaquinaTech>
6
- * @copyright (c) 2026 MaquinaTech. All rights reserved.
7
- * @license MIT
8
- */
9
- import fs from 'fs';
10
- import path from 'path';
11
- import { createHash } from 'crypto';
12
- import ignore from 'ignore';
13
- import Parser from 'tree-sitter';
14
- const { Query } = Parser;
15
-
16
- import { getParserForFile, LANGUAGE_MAP, EXTENSIONS } from './languages.mjs';
17
- import {
18
- extractParams, extractReturnType, extractClassContext,
19
- extractDecorators, extractHeritage, extractTypeAnnotations, extractCallSites, extractReturnVia,
20
- } from './metadata.mjs';
21
-
22
- export const MAX_FILE_SIZE_BYTES = 500000;
23
-
24
- // Evaluated lazily (not at module load) — LANGUAGE_MAP populates asynchronously
25
- // via ensureLanguagesReady(), which callers await before extractSemanticChunks runs.
26
- function _hasSCSS() { return Boolean(LANGUAGE_MAP['.scss']) && LANGUAGE_MAP['.scss'] !== LANGUAGE_MAP['.css']; }
27
-
28
- const LANGUAGE_QUERIES = {
29
- ts: `
30
- (class_declaration) @chunk
31
- (function_declaration) @chunk
32
- (method_definition) @chunk
33
- (lexical_declaration) @chunk
34
- (expression_statement) @chunk
35
- (export_statement) @chunk
36
- `,
37
- css: `(rule_set) @chunk`,
38
- scss: `
39
- (rule_set) @chunk
40
- (mixin_statement) @chunk
41
- (function_statement) @chunk
42
- `,
43
- py: `
44
- (function_definition) @chunk
45
- (class_definition) @chunk
46
- (expression_statement) @chunk
47
- `,
48
- rs: `
49
- (function_item) @chunk
50
- (struct_item) @chunk
51
- (enum_item) @chunk
52
- (trait_item) @chunk
53
- (impl_item) @chunk
54
- `,
55
- go: `
56
- (function_declaration) @chunk
57
- (method_declaration) @chunk
58
- (type_declaration) @chunk
59
- `,
60
- php: `
61
- (function_definition) @chunk
62
- (method_declaration) @chunk
63
- (class_declaration) @chunk
64
- (expression_statement) @chunk
65
- `,
66
- java: `
67
- (method_declaration) @chunk
68
- (class_declaration) @chunk
69
- (interface_declaration) @chunk
70
- (constructor_declaration) @chunk
71
- (enum_declaration) @chunk
72
- `,
73
- kotlin: `
74
- (function_declaration) @chunk
75
- (class_declaration) @chunk
76
- (object_declaration) @chunk
77
- (companion_object) @chunk
78
- (secondary_constructor) @chunk
79
- `,
80
- cs: `
81
- (method_declaration) @chunk
82
- (class_declaration) @chunk
83
- (interface_declaration) @chunk
84
- (constructor_declaration) @chunk
85
- (enum_declaration) @chunk
86
- (property_declaration) @chunk
87
- `,
88
- rb: `
89
- (method) @chunk
90
- (singleton_method) @chunk
91
- (class) @chunk
92
- (module) @chunk
93
- `,
94
- // C: functions + record/typedef definitions. Bare prototypes (declaration) and
95
- // object macros (preproc_def) are intentionally excluded — too noisy / sub-chunk.
96
- c: `
97
- (function_definition) @chunk
98
- (struct_specifier) @chunk
99
- (union_specifier) @chunk
100
- (enum_specifier) @chunk
101
- (type_definition) @chunk
102
- (preproc_function_def) @chunk
103
- `,
104
- // Bash: the function is the only meaningful indexable unit. Top-level command
105
- // sequences are script glue, not symbols, so they are not chunked.
106
- bash: `
107
- (function_definition) @chunk
108
- `,
109
- // Swift: struct/class/enum/extension all parse as class_declaration (the grammar
110
- // distinguishes them by an inner keyword); protocols and free funcs are separate.
111
- swift: `
112
- (class_declaration) @chunk
113
- (protocol_declaration) @chunk
114
- (function_declaration) @chunk
115
- `
116
- };
117
-
118
- const CONTAINERS = new Set([
119
- 'class_declaration', 'function_declaration', 'method_definition',
120
- 'lexical_declaration', 'expression_statement', 'export_statement',
121
- 'function_definition', 'class_definition', 'rule_set',
122
- // SCSS
123
- 'mixin_statement', 'function_statement',
124
- 'function_item', 'struct_item', 'enum_item', 'trait_item', 'impl_item',
125
- 'method_declaration', 'type_declaration',
126
- // Java / C#
127
- 'interface_declaration', 'constructor_declaration', 'enum_declaration',
128
- // Kotlin
129
- 'object_declaration', 'companion_object', 'secondary_constructor',
130
- // C#
131
- 'property_declaration',
132
- // Ruby
133
- 'method', 'singleton_method', 'module',
134
- // C (records + typedef so nested/anonymous specifiers dedupe to one chunk)
135
- 'struct_specifier', 'union_specifier', 'enum_specifier', 'type_definition',
136
- 'preproc_function_def',
137
- // Swift (class_declaration + function_declaration already listed above)
138
- 'protocol_declaration'
139
- ]);
140
-
141
- export function buildIgnoreFilter(rootPath) {
142
- const ig = ignore();
143
- ig.add(['node_modules', '.git', 'dist', 'build', '.next', 'coverage', '*.tmp', 'vendor', '.venv']);
144
- const gitignorePath = path.join(rootPath, '.gitignore');
145
- if (fs.existsSync(gitignorePath)) ig.add(fs.readFileSync(gitignorePath, 'utf-8'));
146
- return ig;
147
- }
148
-
149
- export function generateChunkHash(text) {
150
- return createHash('sha256').update(text).digest('hex');
151
- }
152
-
153
- export function extractFileSkeleton(rootNode, content) {
154
- const signatures = [];
155
- function walk(node) {
156
- if (node.type.includes('declaration') || node.type.includes('definition')) {
157
- let name = node.childForFieldName?.("name")?.text || "anonymous";
158
- signatures.push(`- [${node.type}] ${name} (lines ${node.startPosition.row + 1}-${node.endPosition.row + 1})`);
159
- }
160
- node.children.forEach(walk);
161
- }
162
- walk(rootNode);
163
- return signatures.join('\n');
164
- }
165
-
166
- export function extractImportsFromAST(rootNode, ext) {
167
- const imports = new Set();
168
- function walk(node) {
169
- if (['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'].includes(ext)) {
170
- if (node.type === 'import_statement') {
171
- const source = node.children.find(c => c.type === 'string');
172
- if (source) imports.add(source.text.replace(/['"]/g, ''));
173
- } else if (node.type === 'call_expression' && node.children[0]?.text === 'require') {
174
- const arg = node.children[1]?.children?.find(c => c.type === 'string');
175
- if (arg) imports.add(arg.text.replace(/['"]/g, ''));
176
- }
177
- }
178
- else if (ext === '.py') {
179
- if (node.type === 'import_statement') {
180
- // import foo.bar.baz → store as foo/bar/baz
181
- for (const child of node.children) {
182
- if (child.type === 'dotted_name') imports.add(child.text.replace(/\./g, '/'));
183
- }
184
- } else if (node.type === 'import_from_statement') {
185
- // from .sibling import X → relative: emit as ./sibling
186
- // from ..pkg import Y → relative: emit as ../pkg
187
- // from foo.bar import Z → absolute: store foo/bar
188
- const relNode = node.children.find(c => c.type === 'relative_import');
189
- if (relNode) {
190
- // dots count = depth; remainder is the module path after dots
191
- const raw = relNode.text; // e.g. '.' or '..utils'
192
- const dots = raw.match(/^\.+/)?.[0] ?? '.';
193
- const mod = raw.slice(dots.length);
194
- const prefix = dots.length === 1 ? './' : '../'.repeat(dots.length - 1);
195
- imports.add(mod ? prefix + mod.replace(/\./g, '/') : prefix.slice(0, -1) || '.');
196
- } else {
197
- const mod = node.children.find(c => c.type === 'dotted_name');
198
- if (mod) imports.add(mod.text.replace(/\./g, '/'));
199
- }
200
- }
201
- }
202
- else if (ext === '.rs') {
203
- if (node.type === 'use_declaration') {
204
- // Collect the first path text from the argument subtree
205
- const arg = node.childForFieldName?.('argument') ||
206
- node.children.find(c => !['use', ';', 'pub'].includes(c.type));
207
- if (arg) imports.add(arg.text.split('::').slice(0, 3).join('::'));
208
- }
209
- }
210
- else if (ext === '.go') {
211
- if (node.type === 'import_spec') {
212
- const pathNode = node.children.find(c =>
213
- c.type === 'interpreted_string_literal' || c.type === 'raw_string_literal');
214
- if (pathNode) imports.add(pathNode.text.replace(/['"`]/g, ''));
215
- }
216
- }
217
- else if (ext === '.php') {
218
- if (node.type === 'include_expression' || node.type === 'require_expression' ||
219
- node.type === 'include_once_expression' || node.type === 'require_once_expression') {
220
- const strNode = node.children.find(c =>
221
- c.type === 'string' || c.type === 'encapsed_string');
222
- if (strNode) imports.add(strNode.text.replace(/['"]/g, ''));
223
- }
224
- } else if (ext === '.java') {
225
- if (node.type === 'import_declaration') {
226
- const scopedId = node.children.find(c => c.type === 'scoped_identifier' || c.type === 'identifier');
227
- if (scopedId) imports.add(scopedId.text.replace(/\./g, '/'));
228
- }
229
- }
230
- else if (ext === '.kt' || ext === '.kts') {
231
- if (node.type === 'import_header') {
232
- const path = node.children.find(c => c.type === 'identifier' || c.type === 'user_type' || c.isNamed);
233
- const raw = node.text.replace(/^import\s+/, '').replace(/\s*\.\*\s*$/, '').trim();
234
- if (raw) imports.add(raw.replace(/\./g, '/'));
235
- }
236
- }
237
- else if (ext === '.cs') {
238
- if (node.type === 'using_directive') {
239
- const ns = node.children.find(c => c.type === 'qualified_name' || c.type === 'identifier' || c.type === 'name_equals');
240
- if (ns) {
241
- const raw = ns.text.replace(/\s*=\s*.*$/, '').trim();
242
- if (raw) imports.add(raw.replace(/\./g, '/'));
243
- }
244
- }
245
- }
246
- else if (ext === '.rb') {
247
- if (node.type === 'call' || node.type === 'method_call') {
248
- const method = node.childForFieldName?.('method') || node.children[0];
249
- if (method && (method.text === 'require' || method.text === 'require_relative')) {
250
- const args = node.childForFieldName?.('arguments') || node.children.find(c => c.type === 'argument_list');
251
- const strArg = args?.children?.find(c => c.type === 'string' || c.type === 'simple_string');
252
- if (strArg) imports.add(strArg.text.replace(/['"]/g, ''));
253
- }
254
- }
255
- }
256
- else if (ext === '.c' || ext === '.h') {
257
- // Only quoted local includes (`#include "foo.h"`) carry intra-project
258
- // edges; angle-bracket system includes (<stdio.h>) are stdlib noise.
259
- if (node.type === 'preproc_include') {
260
- const str = node.children.find(c => c.type === 'string_literal');
261
- if (str) imports.add(str.text.replace(/^[<"]|[>"]$/g, ''));
262
- }
263
- }
264
- else if (ext === '.sh' || ext === '.bash') {
265
- // `source path` / `. path` pull another script into scope.
266
- if (node.type === 'command') {
267
- const cmd = node.childForFieldName?.('name')?.text;
268
- if (cmd === 'source' || cmd === '.') {
269
- const arg = node.namedChildren.find(c => c.type !== 'command_name');
270
- if (arg) imports.add(arg.text.replace(/['"]/g, ''));
271
- }
272
- }
273
- }
274
- else if (ext === '.swift') {
275
- // `import Foundation` / `import MyModule.Submodule` — module-level, rarely
276
- // file-resolvable, but tracked so the dependency list is non-empty.
277
- if (node.type === 'import_declaration') {
278
- const raw = node.text.replace(/^@?\w*\s*import\s+/, '').trim();
279
- if (raw) imports.add(raw.replace(/\./g, '/'));
280
- }
281
- }
282
- node.children.forEach(walk);
283
- }
284
- walk(rootNode);
285
- return Array.from(imports);
286
- }
287
-
288
- // ─── God-class defence ────────────────────────────────────────────────────────
289
-
290
- /**
291
- * Token-safe skeleton for a class that exceeds GOD_CLASS_LINES.
292
- *
293
- * The agent prompt (prompts/CORE.md) promises get_chunk() costs ~300 tokens. A 2 000-line
294
- * "god class" stored as one chunk violates that contract. This skeleton keeps
295
- * only the first HEADER_LINES of the class (signature + opening brace) and
296
- * appends a one-line summary — enough for name resolution and embeddings, while
297
- * the real bodies are reachable via the individual method chunks that the
298
- * god-class split produces.
299
- */
300
- function buildGodClassSkeleton(classNode) {
301
- const allLines = classNode.text.split('\n');
302
- const HEADER_LINES = 15;
303
- const header = allLines.slice(0, HEADER_LINES).join('\n');
304
- return (
305
- `${header}\n` +
306
- ` // ⚠ [Large class: ${allLines.length} lines — ` +
307
- `methods are indexed as individual searchable chunks. ` +
308
- `Use search_code() to find specific methods.]\n}`
309
- );
310
- }
311
-
312
- /**
313
- * Resolve the declared name out of a C declarator chain.
314
- * C nests the identifier under layers of pointer_declarator / array_declarator /
315
- * function_declarator (`int *make_node(void)` → pointer_declarator → function_declarator
316
- * → identifier), so we descend the `declarator` field until we hit the identifier.
317
- */
318
- function _cDeclaratorName(node) {
319
- let d = node, guard = 0;
320
- while (d && guard++ < 16) {
321
- if (d.type === 'identifier' || d.type === 'type_identifier' || d.type === 'field_identifier') return d.text;
322
- // Descend the declarator field, or — for wrappers without that field, e.g. a
323
- // function-pointer typedef's parenthesized_declarator — the inner *_declarator.
324
- const next = d.childForFieldName?.('declarator')
325
- || d.namedChildren?.find(c => /_declarator$/.test(c.type));
326
- if (next && next !== d) { d = next; continue; }
327
- const id = d.namedChildren?.find(c =>
328
- c.type === 'identifier' || c.type === 'type_identifier' || c.type === 'field_identifier');
329
- if (id) return id.text;
330
- break;
331
- }
332
- return null;
333
- }
334
-
335
- export function extractSemanticChunks(rootNode, relPath, sourceCode, ext, { interprocedural = false } = {}) {
336
- const chunks = [];
337
- const parser = getParserForFile(ext);
338
- if (!parser) return chunks;
339
-
340
- const JS_LIKE = ['.ts', '.tsx', '.js', '.jsx', '.mjs', '.cjs'];
341
- const EXT_TO_LANG = {
342
- '.java': 'java', '.kt': 'kotlin', '.kts': 'kotlin', '.cs': 'cs',
343
- '.rb': 'rb',
344
- // .scss uses the SCSS grammar+query when installed; otherwise it parses
345
- // with the CSS grammar, so it MUST use the css query (the scss query
346
- // references node types the CSS grammar doesn't have).
347
- '.scss': _hasSCSS() ? 'scss' : 'css',
348
- // C headers share the C grammar/query; .sh and .bash share the bash query.
349
- // (.c and .swift resolve via the ext.slice(1) fallback below.)
350
- '.h': 'c', '.sh': 'bash', '.bash': 'bash',
351
- };
352
- const langKey = JS_LIKE.includes(ext) ? 'ts'
353
- : (EXT_TO_LANG[ext] || (LANGUAGE_QUERIES[ext.slice(1)] ? ext.slice(1) : null));
354
- if (!langKey || !LANGUAGE_QUERIES[langKey]) return chunks;
355
-
356
- // Extract top-of-file comments for module context (header inheritance).
357
- let fileDocstring = "";
358
- let cursorNode = rootNode.children[0];
359
- while (cursorNode) {
360
- if (cursorNode.type === 'comment') fileDocstring += cursorNode.text + "\n";
361
- else if (cursorNode.type !== 'import_statement' && cursorNode.type !== 'expression_statement') break;
362
- cursorNode = cursorNode.nextSibling;
363
- }
364
- fileDocstring = fileDocstring.trim();
365
-
366
- try {
367
- const query = new Query(parser.getLanguage(), LANGUAGE_QUERIES[langKey]);
368
- const matches = query.matches(rootNode);
369
- const processedNodes = new Set();
370
-
371
- // ── God-class pre-pass ─────────────────────────────────────────────────
372
- // TS exported classes live inside export_statement — mark the inner
373
- // class_declaration so the method-isNested check resolves the correct ancestor.
374
- const GOD_CLASS_LINES = 200;
375
- const GOD_CLASS_NODE_TYPES = new Set([
376
- 'class_declaration', 'class_definition',
377
- 'impl_item', // Rust impl blocks
378
- 'class', // Ruby
379
- 'object_declaration', // Kotlin
380
- ]);
381
- const oversizedClassIds = new Set(); // node IDs whose direct methods are un-nested
382
-
383
- for (const match of matches) {
384
- for (const capture of match.captures) {
385
- if (capture.name !== 'chunk') continue;
386
- const n = capture.node;
387
- const nLines = n.endPosition.row - n.startPosition.row + 1;
388
- if (nLines <= GOD_CLASS_LINES) continue;
389
- if (GOD_CLASS_NODE_TYPES.has(n.type)) {
390
- oversizedClassIds.add(n.id);
391
- }
392
- // TS: large export_statement wrapping a class — mark the inner class_declaration
393
- // so method_definition.parent chain finds the oversized class node, not the
394
- // export_statement (which isn't what the isNested walk stops at).
395
- if (n.type === 'export_statement') {
396
- for (let ci = 0; ci < n.namedChildCount; ci++) {
397
- const c = n.namedChild(ci);
398
- if (GOD_CLASS_NODE_TYPES.has(c.type)) {
399
- oversizedClassIds.add(c.id);
400
- break;
401
- }
402
- }
403
- }
404
- }
405
- }
406
-
407
- for (const match of matches) {
408
- let chunkNode = null;
409
- for (const capture of match.captures) {
410
- if (capture.name === 'chunk') chunkNode = capture.node;
411
- }
412
-
413
- if (!chunkNode || processedNodes.has(chunkNode.id)) continue;
414
- processedNodes.add(chunkNode.id);
415
-
416
- // Skip trivial definitions spanning fewer than 3 lines (one-line getters,
417
- // re-export forwarders, stubs): they add symbol noise and rarely carry
418
- // behaviour worth its own chunk. A file of ONLY one-liners thus yields no
419
- // chunks — the indexer surfaces a warning when the whole repo comes back empty.
420
- if (chunkNode.endPosition.row - chunkNode.startPosition.row < 2) continue;
421
-
422
- // Walk to parent === null (tree root) rather than stopping at a named root type:
423
- // Ruby's `module` keyword is in CONTAINERS but also the name of Python's root node,
424
- // so stopping at 'program' alone falsely marked top-level Python classes as nested.
425
- // God-class exception: if the first CONTAINERS ancestor is oversized, the node is a
426
- // direct method — allow it through as its own chunk.
427
- let isNested = false;
428
- let currentParent = chunkNode.parent;
429
- while (currentParent && currentParent.parent !== null) {
430
- if (CONTAINERS.has(currentParent.type)) {
431
- if (!oversizedClassIds.has(currentParent.id)) {
432
- isNested = true;
433
- }
434
- break;
435
- }
436
- currentParent = currentParent.parent;
437
- }
438
- if (isNested) continue;
439
-
440
- let nameText = "anonymous";
441
- const nameNode = chunkNode.childForFieldName?.("name");
442
-
443
- if (nameNode) {
444
- nameText = nameNode.text;
445
- } else if (chunkNode.type === "export_statement") {
446
- const decl = chunkNode.children.find(c => ['lexical_declaration', 'function_declaration', 'class_declaration'].includes(c.type));
447
- if (decl) {
448
- if (decl.type === "lexical_declaration") {
449
- const varDecl = decl.children.find(c => c.type === "variable_declarator");
450
- nameText = varDecl?.children.find(c => c.type === "identifier")?.text || "anonymous";
451
- } else {
452
- nameText = decl.childForFieldName?.("name")?.text || "anonymous";
453
- }
454
- } else {
455
- const defaultChild = chunkNode.children.find(c => c.type === 'identifier' || c.type === 'call_expression');
456
- if (defaultChild) {
457
- if (defaultChild.type === 'identifier') {
458
- nameText = `default_${defaultChild.text}`;
459
- } else if (defaultChild.type === 'call_expression') {
460
- const funcName = defaultChild.childForFieldName?.("function")?.text || defaultChild.children[0]?.text;
461
- const argNode = defaultChild.childForFieldName?.("arguments")?.children?.find(c => c.type === 'identifier');
462
- nameText = argNode ? `default_${funcName}_${argNode.text}` : `default_${funcName}`;
463
- }
464
- } else {
465
- nameText = "default_export";
466
- }
467
- }
468
- } else if (chunkNode.type === "lexical_declaration") {
469
- const decl = chunkNode.children.find(c => c.type === "variable_declarator");
470
- nameText = decl?.children.find(c => c.type === "identifier")?.text || "anonymous";
471
- } else if (chunkNode.type === "expression_statement") {
472
- const callExp = chunkNode.children.find(c => c.type === "call_expression");
473
- const assignExp = chunkNode.children.find(c => c.type === "assignment_expression");
474
- if (callExp) {
475
- const funcName = callExp.childForFieldName?.("function")?.text || callExp.children[0]?.text;
476
- const argsNode = callExp.childForFieldName?.("arguments");
477
- const stringArg = argsNode?.children?.find(c => c.type === "string" || c.type === "template_string");
478
- nameText = stringArg ? `${funcName}_${stringArg.text.replace(/['"`]/g, '')}` : (funcName || "anonymous");
479
- } else if (assignExp) {
480
- nameText = assignExp.childForFieldName?.("left")?.text || "anonymous";
481
- }
482
- } else if (chunkNode.type === "type_declaration") {
483
- // Go: `type X struct {…}` / `type X interface {…}` / `type X = Y`.
484
- // The identifier lives on the nested type_spec / type_alias node, not on
485
- // the type_declaration itself, so childForFieldName("name") above is null.
486
- // Without this branch every Go struct/interface collapses to the useless
487
- // synthetic name `<file>_type_declaration`, making core types (e.g. Gin's
488
- // RouterGroup, Engine, Context) unsearchable by name and invisible to the
489
- // 2.0× name-boost in searchHybrid.
490
- const spec = chunkNode.namedChildren?.find(c => c.type === "type_spec" || c.type === "type_alias");
491
- nameText = spec?.childForFieldName?.("name")?.text
492
- || spec?.children?.find(c => c.type === "type_identifier")?.text
493
- || "anonymous";
494
- } else if (chunkNode.type === "function_definition" || chunkNode.type === "type_definition"
495
- || chunkNode.type === "preproc_function_def") {
496
- // C: the name is not a direct `name` field. For a function it is buried in
497
- // declarator → … → identifier (e.g. `int *make()` nests through a
498
- // pointer_declarator); for a typedef the `declarator` field is the new type
499
- // name; a function-like macro carries an `identifier` child. Without this the
500
- // chunk collapses to the useless synthetic `<file>_function_definition`, making
501
- // every C function unsearchable by name and invisible to the 2.0× name boost.
502
- nameText = _cDeclaratorName(chunkNode.childForFieldName?.("declarator"))
503
- || chunkNode.children.find(c => c.type === "identifier")?.text
504
- || "anonymous";
505
- } else {
506
- // Generic fallback: search direct children for an identifier-like node.
507
- // Includes type_identifier (Go/TS), constant (Ruby class/module names) and
508
- // field_identifier so nested-name grammars don't fall through to anonymous.
509
- const idNode = chunkNode.children.find(c =>
510
- c.type === "identifier" || c.type === "name" || c.type === "property_identifier"
511
- || c.type === "type_identifier" || c.type === "constant" || c.type === "field_identifier");
512
- nameText = idNode?.text || "anonymous";
513
- }
514
-
515
- if (nameText === "anonymous" || nameText === "default_export") {
516
- nameText = `${path.basename(relPath, path.extname(relPath))}_${chunkNode.type}`;
517
- }
518
-
519
- let docstring = "";
520
- let prev = chunkNode.previousSibling;
521
- while (prev && (prev.type === 'comment' || !prev.isNamed)) {
522
- if (prev.type === 'comment') docstring = prev.text + "\n" + docstring;
523
- prev = prev.previousSibling;
524
- }
525
- docstring = docstring.trim();
526
-
527
- if (!docstring && fileDocstring) {
528
- docstring = `[File Context]: ${fileDocstring}`;
529
- }
530
-
531
- // For oversized class containers — or TS export_statements wrapping one —
532
- // store a compact skeleton so get_chunk() returns a bounded token count.
533
- // All metadata fields (calls, params, type_refs, decorators, extends) are
534
- // still extracted from the FULL AST node, so ranking and topology are intact.
535
- const isOversizedClass = oversizedClassIds.has(chunkNode.id);
536
- const wrapsOversizedClass = !isOversizedClass && chunkNode.type === 'export_statement' && (() => {
537
- for (let ci = 0; ci < chunkNode.namedChildCount; ci++) {
538
- if (oversizedClassIds.has(chunkNode.namedChild(ci).id)) return true;
539
- }
540
- return false;
541
- })();
542
- const snippet = (isOversizedClass || wrapsOversizedClass)
543
- ? buildGodClassSkeleton(isOversizedClass ? chunkNode : (() => {
544
- for (let ci = 0; ci < chunkNode.namedChildCount; ci++) {
545
- const c = chunkNode.namedChild(ci);
546
- if (oversizedClassIds.has(c.id)) return c;
547
- }
548
- return chunkNode;
549
- })())
550
- : chunkNode.text.slice(0, 3000);
551
- // Hash the FULL node text (not the 3000-char snippet) so the content key
552
- // reflects a definition's whole body. This keeps the dense channel's window
553
- // vectors (which embed the full body — see buildEmbeddingPayload/embeddingWindows)
554
- // correctly invalidated when a tail-only edit changes code past the snippet
555
- // cap. For chunks whose body fits the cap, node text == snippet, so the hash
556
- // is unchanged (no needless re-embed); BM25 and code_snippet are untouched.
557
- const hash = generateChunkHash(docstring + chunkNode.text);
558
- const callSites = extractCallSites(chunkNode).slice(0, 256);
559
- const outgoingCalls = Array.from(new Set(callSites.map(s => s.name)));
560
-
561
- const params = extractParams(chunkNode, ext);
562
- const returnType = extractReturnType(chunkNode, ext);
563
- const classContext = extractClassContext(chunkNode);
564
- const typeRefs = extractTypeAnnotations(chunkNode, ext);
565
- const decorators = extractDecorators(chunkNode);
566
- const heritage = extractHeritage(chunkNode, ext);
567
-
568
- const id = createHash('sha256')
569
- .update(`${relPath}::${chunkNode.startPosition.row}::${chunkNode.startPosition.column}`)
570
- .digest('hex').slice(0, 24);
571
-
572
- const chunk = {
573
- id, file_path: relPath, node_type: chunkNode.type, name: nameText,
574
- docstring: docstring, code_snippet: snippet, content_hash: hash,
575
- start_line: chunkNode.startPosition.row + 1, end_line: chunkNode.endPosition.row + 1,
576
- calls: outgoingCalls, call_sites: callSites,
577
- params, return_type: returnType, class_context: classContext,
578
- type_refs: typeRefs, decorators, extends: heritage,
579
- };
580
- // Opt-in inter-procedural fixpoint: capture what this function returns so the
581
- // indexer can propagate return types along factory chains. Transient — stripped
582
- // before serialization (parse/interprocedural.mjs::applyInterprocedural). Off by
583
- // default → the chunk is byte-identical to before.
584
- if (interprocedural) {
585
- const rv = extractReturnVia(chunkNode);
586
- if (rv) chunk._return_via = rv;
587
- }
588
- chunks.push(chunk);
589
- }
590
- } catch (e) {
591
- process.stderr.write(`\n[parse/extractor] 💥 Query Error in ${relPath}: ${e.message}\n`);
592
- }
593
-
594
- // ── Python public re-exports ────────────────────────────────────────────────
595
- // PEP 484 convention: `from starlette.background import BackgroundTasks as
596
- // BackgroundTasks` re-exports a symbol as public API. Files like
597
- // fastapi/background.py consist ONLY of such lines and previously produced
598
- // zero chunks — resolve_symbol('BackgroundTasks') found nothing and agents
599
- // hit a dead end. Each explicit re-export becomes a small chunk that names
600
- // the symbol and points at its source module. (JS/TS barrels already chunk
601
- // via the export_statement capture.)
602
- if (ext === '.py') {
603
- for (const node of rootNode.children) {
604
- if (node.type !== 'import_from_statement') continue;
605
- const moduleName = node.childForFieldName?.('module_name')?.text || '';
606
- for (const child of node.children) {
607
- if (child.type !== 'aliased_import') continue;
608
- const orig = child.childForFieldName?.('name')?.text || '';
609
- const alias = child.childForFieldName?.('alias')?.text || '';
610
- if (!alias || orig.split('.').pop() !== alias) continue; // only `import X as X`
611
- const snippet = node.text.slice(0, 300);
612
- const docstring = `Public re-export of ${alias} from ${moduleName}.`;
613
- const id = createHash('sha256')
614
- .update(`${relPath}::${node.startPosition.row}::${child.startPosition.column}`)
615
- .digest('hex').slice(0, 24);
616
- chunks.push({
617
- id, file_path: relPath, node_type: 're_export', name: alias,
618
- docstring, code_snippet: snippet,
619
- content_hash: generateChunkHash(docstring + snippet),
620
- start_line: node.startPosition.row + 1, end_line: node.endPosition.row + 1,
621
- calls: [], call_sites: [], params: [], return_type: '', class_context: '',
622
- type_refs: [], decorators: [], extends: [],
623
- });
624
- }
625
- }
626
- }
627
- return chunks;
628
- }