graph-indexer 2.1.0 โ†’ 3.0.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 (129) hide show
  1. package/CHANGELOG.md +260 -1
  2. package/README.md +232 -312
  3. package/SECURITY.md +37 -59
  4. package/bin/graph-indexer.mjs +251 -0
  5. package/integrations/claude-code/.claude-plugin/plugin.json +8 -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 +99 -0
  9. package/integrations/claude-code/hooks/hooks.json +16 -0
  10. package/integrations/opencode/graph-indexer.js +124 -0
  11. package/package.json +31 -105
  12. package/src/cli/helper.mjs +67 -0
  13. package/src/cli/hook.mjs +356 -0
  14. package/src/cli/init.mjs +255 -0
  15. package/src/cli/resident.mjs +175 -0
  16. package/src/index/discover.mjs +130 -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 +331 -0
  21. package/src/index/resolver.mjs +954 -0
  22. package/src/mcp/render.mjs +60 -0
  23. package/src/mcp/server.mjs +147 -0
  24. package/src/mcp/tools.mjs +973 -0
  25. package/src/parse/arity.mjs +152 -0
  26. package/src/parse/extract.mjs +1031 -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 +343 -0
  40. package/src/query/facts.mjs +323 -0
  41. package/src/query/intel.mjs +680 -0
  42. package/src/query/read.mjs +81 -0
  43. package/src/query/testcmd.mjs +119 -0
  44. package/src/query/textsearch.mjs +160 -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/paths.mjs +24 -0
  49. package/vendor/grammars/bash.wasm.gz +0 -0
  50. package/vendor/grammars/c.wasm.gz +0 -0
  51. package/vendor/grammars/c_sharp.wasm.gz +0 -0
  52. package/vendor/grammars/cpp.wasm.gz +0 -0
  53. package/vendor/grammars/css.wasm.gz +0 -0
  54. package/vendor/grammars/go.wasm.gz +0 -0
  55. package/vendor/grammars/java.wasm.gz +0 -0
  56. package/vendor/grammars/javascript.wasm.gz +0 -0
  57. package/vendor/grammars/kotlin.wasm.gz +0 -0
  58. package/vendor/grammars/manifest.json +148 -0
  59. package/vendor/grammars/php.wasm.gz +0 -0
  60. package/vendor/grammars/python.wasm.gz +0 -0
  61. package/vendor/grammars/ruby.wasm.gz +0 -0
  62. package/vendor/grammars/rust.wasm.gz +0 -0
  63. package/vendor/grammars/scala.wasm.gz +0 -0
  64. package/vendor/grammars/tsx.wasm.gz +0 -0
  65. package/vendor/grammars/typescript.wasm.gz +0 -0
  66. package/vendor/web-tree-sitter/web-tree-sitter.js +3980 -0
  67. package/vendor/web-tree-sitter/web-tree-sitter.wasm +0 -0
  68. package/cli-ui.mjs +0 -78
  69. package/colbert.mjs +0 -168
  70. package/config.mjs +0 -494
  71. package/daemon-ctl.mjs +0 -175
  72. package/daemon-lock.mjs +0 -69
  73. package/embedders/python/mlx_embed_server.py +0 -61
  74. package/embedders/python/requirements-mlx.txt +0 -5
  75. package/embedders/setup-mlx.mjs +0 -110
  76. package/embeddings.mjs +0 -571
  77. package/engine/binary.mjs +0 -437
  78. package/engine/memory.mjs +0 -1003
  79. package/engine/sqlite.mjs +0 -1136
  80. package/enrichment.mjs +0 -521
  81. package/git-signals.mjs +0 -248
  82. package/indexer.mjs +0 -546
  83. package/init.mjs +0 -1809
  84. package/layout.mjs +0 -123
  85. package/mcp/centrality.mjs +0 -117
  86. package/mcp/format.mjs +0 -61
  87. package/mcp/resolver.mjs +0 -116
  88. package/mcp/symbolgraph.mjs +0 -137
  89. package/mcp/taint.mjs +0 -225
  90. package/mcp/tools.mjs +0 -1582
  91. package/mcp/topology.mjs +0 -676
  92. package/mcp-server.mjs +0 -197
  93. package/parse/extractor.mjs +0 -628
  94. package/parse/imports.mjs +0 -365
  95. package/parse/interprocedural.mjs +0 -134
  96. package/parse/languages.mjs +0 -253
  97. package/parse/metadata.mjs +0 -701
  98. package/parse/routes.mjs +0 -327
  99. package/parse/scip.mjs +0 -391
  100. package/parse/taint-patterns.mjs +0 -119
  101. package/prompts/CORE.md +0 -91
  102. package/prompts/DOMAIN_TEMPLATE.md +0 -46
  103. package/prompts/INTEGRATION.md +0 -123
  104. package/prompts/frameworks/ANDROID.md +0 -17
  105. package/prompts/frameworks/ASPNET_CORE.md +0 -19
  106. package/prompts/frameworks/FASTAPI_DJANGO.md +0 -20
  107. package/prompts/frameworks/LARAVEL_SYMFONY.md +0 -22
  108. package/prompts/frameworks/NODE_EXPRESS_NESTJS.md +0 -19
  109. package/prompts/frameworks/RAILS.md +0 -20
  110. package/prompts/frameworks/REACT.md +0 -20
  111. package/prompts/frameworks/SPRING_BOOT.md +0 -20
  112. package/prompts/languages/BASH.md +0 -22
  113. package/prompts/languages/C.md +0 -21
  114. package/prompts/languages/CSHARP.md +0 -24
  115. package/prompts/languages/CSS_SCSS.md +0 -22
  116. package/prompts/languages/GO.md +0 -24
  117. package/prompts/languages/JAVA.md +0 -23
  118. package/prompts/languages/JAVASCRIPT_TYPESCRIPT.md +0 -24
  119. package/prompts/languages/KOTLIN.md +0 -24
  120. package/prompts/languages/PHP.md +0 -23
  121. package/prompts/languages/PYTHON.md +0 -23
  122. package/prompts/languages/RUBY.md +0 -23
  123. package/prompts/languages/RUST.md +0 -21
  124. package/prompts/languages/SWIFT.md +0 -21
  125. package/seal.mjs +0 -400
  126. package/search-core.mjs +0 -777
  127. package/search-sparse.mjs +0 -183
  128. package/storage.mjs +0 -73
  129. package/watch-daemon.mjs +0 -289
package/indexer.mjs DELETED
@@ -1,546 +0,0 @@
1
- #!/usr/bin/env node
2
- /**
3
- * @file indexer.mjs
4
- * @description Bootstrap indexer. Walks a repository, extracts Tree-sitter AST
5
- * chunks + cross-file topology, generates local embeddings (Ollama),
6
- * optionally enriches the most central chunks with an LLM, and writes
7
- * the index to the configured backend โ€” the default in-memory JSON
8
- * artifacts, or a disk-backed SQLite database (--use-sqlite).
9
- * @author MaquinaTech <https://github.com/MaquinaTech>
10
- * @copyright (c) 2026 MaquinaTech. All rights reserved.
11
- * @license MIT
12
- */
13
- import fs from 'fs';
14
- import path from 'path';
15
- import { MAX_FILE_SIZE_BYTES, buildIgnoreFilter, extractImportsFromAST, extractSemanticChunks } from './parse/extractor.mjs';
16
- import { EXTENSIONS, getParserForFile, ensureLanguagesReady } from './parse/languages.mjs';
17
- import { extractRoutes } from './parse/routes.mjs';
18
- import { resolveLocalImports, buildEmbeddingPayload, fullBodyForEmbedding } from './parse/imports.mjs';
19
- import { readEmbeddingBinary, writeEmbeddingBinary } from './engine/binary.mjs';
20
- import { embeddingKeyFor, summaryEmbeddingText, SUMMARY_VEC_SUFFIX, WINDOW_VEC_SUFFIX, embeddingWindows } from './search-core.mjs';
21
- import { createEmbedder, describeEmbedder, readEmbedMeta, writeEmbedMeta, embedModelChanged, _resetSubprocesses } from './embeddings.mjs';
22
- import { resolveConfig, describeConfig, configNotices } from './config.mjs';
23
- import { AUTO_SQLITE_CHUNK_THRESHOLD } from './storage.mjs';
24
- import { ensureDataDir, migrateLegacyLayout } from './layout.mjs';
25
- import { enrichCoreChunks } from './enrichment.mjs';
26
- import { collectGitSignals, writeGitSignals } from './git-signals.mjs';
27
- import {
28
- installEgressGuard, sealManifest, signManifest, verifySignedManifest,
29
- generateAttestationKeyPair, canonicalJson, SealViolation,
30
- } from './seal.mjs';
31
-
32
- /** Value following `--flag` in argv, or undefined. */
33
- function argVal(flag) {
34
- const i = process.argv.indexOf(flag);
35
- return i >= 0 && i + 1 < process.argv.length ? process.argv[i + 1] : undefined;
36
- }
37
-
38
- // resolveConfig fail-closes on a sealed-incompatible config (throws SealViolation); surface it
39
- // as a clean exit rather than an unhandled rejection.
40
- let config;
41
- try {
42
- config = resolveConfig();
43
- } catch (err) {
44
- if (err && err.name === 'SealViolation') { console.error(`๐Ÿ”’ ${err.message}`); process.exit(2); }
45
- throw err;
46
- }
47
-
48
- // `idx-index --gen-attestation-key <prefix>`: write an Ed25519 keypair (<prefix>.key / <prefix>.pub)
49
- // and exit. The private key is the signing key (keep safe); the public key is shared for verification.
50
- {
51
- const prefix = argVal('--gen-attestation-key');
52
- if (prefix) {
53
- const { publicKey, privateKey } = generateAttestationKeyPair();
54
- fs.writeFileSync(`${prefix}.key`, privateKey, { mode: 0o600 });
55
- fs.writeFileSync(`${prefix}.pub`, publicKey);
56
- console.log(`๐Ÿ”‘ Attestation keypair written: ${prefix}.key (private โ€” keep safe) + ${prefix}.pub (share to verify).`);
57
- process.exit(0);
58
- }
59
- }
60
-
61
- // `idx-index --verify-attestation <file> --pub-key <path>`: verify a signed manifest's signature and,
62
- // if authentic, report whether it MATCHES the current effective config. Exit 0 = valid + matching.
63
- {
64
- const verifyFile = argVal('--verify-attestation');
65
- if (verifyFile) {
66
- let envelope;
67
- try { envelope = JSON.parse(fs.readFileSync(verifyFile, 'utf8')); }
68
- catch (e) { console.error(`โŒ cannot read attestation ${verifyFile}: ${e.message}`); process.exit(3); }
69
- const pubPath = argVal('--pub-key');
70
- if (!pubPath) { console.error('โŒ --verify-attestation requires --pub-key <path>'); process.exit(3); }
71
- let pubPem;
72
- try { pubPem = fs.readFileSync(pubPath, 'utf8'); }
73
- catch (e) { console.error(`โŒ cannot read public key ${pubPath}: ${e.message}`); process.exit(3); }
74
- const res = verifySignedManifest(envelope, pubPem);
75
- if (!res.valid) { console.error(`โŒ attestation INVALID: ${res.reason}`); process.exit(3); }
76
- console.log(`โœ… attestation signature VALID (key ${res.publicKeyFingerprint}).`);
77
- const matches = canonicalJson(sealManifest(config)) === canonicalJson(envelope.manifest);
78
- if (matches) { console.log('โœ… attested manifest MATCHES the current effective config.'); process.exit(0); }
79
- console.log('โš ๏ธ attested manifest DIFFERS from the current effective config (policy drift):');
80
- console.log(` attested: ${canonicalJson(envelope.manifest)}`);
81
- console.log(` current : ${canonicalJson(sealManifest(config))}`);
82
- process.exit(3);
83
- }
84
- }
85
-
86
- // `idx-index --attest [--sign-key <path>]`: print the deterministic seal manifest (signed if a key
87
- // is given) and exit (no indexing).
88
- if (process.argv.includes('--attest')) {
89
- const manifest = sealManifest(config);
90
- const signKey = argVal('--sign-key');
91
- if (signKey) {
92
- let keyPem;
93
- try { keyPem = fs.readFileSync(signKey, 'utf8'); }
94
- catch (e) { console.error(`โŒ cannot read signing key ${signKey}: ${e.message}`); process.exit(2); }
95
- try { console.log(JSON.stringify(signManifest(manifest, keyPem), null, 2)); }
96
- catch (e) { console.error(`โŒ signing failed: ${e.message}`); process.exit(2); }
97
- } else {
98
- console.log(JSON.stringify(manifest, null, 2));
99
- }
100
- process.exit(0);
101
- }
102
-
103
- // F1: install the deny-by-default egress guard BEFORE any provider (embedder/enricher) loads, so
104
- // even provider initialisation cannot reach the network under a sealed tier.
105
- if (config.sealed !== 'off') {
106
- installEgressGuard({ allow: config.sealed === 'local' ? ['loopback'] : [] });
107
- }
108
-
109
- const PROJECT_ROOT = config.projectRoot;
110
- const INDEX_PATH = config.indexPath;
111
- const EMBEDDINGS_PATH = config.embeddingPath;
112
-
113
- // Artifacts are written under <root>/.graph-indexer/ โ€” make sure it exists and
114
- // relocate any artifacts left at the root by a pre-v1.4 install.
115
- ensureDataDir(PROJECT_ROOT);
116
- migrateLegacyLayout(PROJECT_ROOT);
117
-
118
- function walkRepo(dir, root, ig, files = []) {
119
- for (const entry of fs.readdirSync(dir)) {
120
- if (entry.startsWith('.')) continue;
121
- const fullPath = path.join(dir, entry);
122
- const relPath = path.relative(root, fullPath).replace(/\\/g, '/');
123
- if (ig.ignores(relPath)) continue;
124
- if (fs.statSync(fullPath).isDirectory()) {
125
- walkRepo(fullPath, root, ig, files);
126
- } else if (EXTENSIONS.has(path.extname(fullPath))) {
127
- files.push(fullPath);
128
- }
129
- }
130
- return files;
131
- }
132
-
133
- async function main() {
134
- console.log(`\n๐Ÿš€ Starting Optimized Indexer\n๐Ÿ“‚ Directory: ${PROJECT_ROOT}`);
135
- console.log('โš™๏ธ Effective configuration:');
136
- for (const line of describeConfig(config)) console.log(` ${line}`);
137
- for (const notice of configNotices(config)) console.log(`โš ๏ธ ${notice}`);
138
- console.log('');
139
-
140
- // Grammar packages are installed on demand (not bundled) โ€” resolve/install
141
- // whatever the configured languages need BEFORE walking the repo. Sealed mode
142
- // never reaches the network for this: installEgressGuard can't stop a child
143
- // `npm install` process, so autoInstall is explicitly off rather than relying
144
- // on the guard โ€” and, matching the fail-closed egress checks elsewhere in
145
- // sealed mode, an unresolvable grammar refuses the run instead of silently
146
- // shipping a partial index.
147
- const { missing: missingGrammars } = await ensureLanguagesReady({
148
- projectRoot: PROJECT_ROOT,
149
- enabledLangs: config.languages,
150
- autoInstall: config.sealed === 'off',
151
- log: (msg) => console.log(msg),
152
- });
153
- if (config.sealed !== 'off' && missingGrammars.length > 0) {
154
- const detail = missingGrammars.map(m => ` โ€ข ${m.key} (${m.pkg}@${m.version})`).join('\n');
155
- throw new SealViolation(
156
- `--sealed ${config.sealed} refuses to start โ€” ${missingGrammars.length} language grammar(s) `
157
- + `are not installed and sealed mode won't fetch them:\n${detail}\n`
158
- + ` remedy: pre-install before sealing, e.g. npm install --prefix ${path.join(PROJECT_ROOT, '.graph-indexer')} `
159
- + `${missingGrammars.map(m => `${m.pkg}@${m.version}`).join(' ')}`
160
- + ` โ€” or drop the language from your .graph-indexer.json "languages" selection`
161
- );
162
- }
163
-
164
- const ig = buildIgnoreFilter(PROJECT_ROOT);
165
- const files = walkRepo(PROJECT_ROOT, PROJECT_ROOT, ig);
166
- console.log(`Found ${files.length} files to analyse.\n`);
167
-
168
- // Resolve the embedding provider for this run (Ollama โ†’ in-process local โ†’
169
- // lexical, unless forced). Index time and query time must share the model.
170
- const embedder = await createEmbedder(config);
171
- console.log(`๐Ÿ”Ž Embeddings: ${describeEmbedder(embedder)}`);
172
- // Make the `auto` fallback ladder observable โ€” never silently lexical-only.
173
- if (config.embedProvider === 'auto') {
174
- if (embedder.provider === 'local') {
175
- console.log(` โ†ช Ollama not reachable at ${config.ollamaHost}; using the bundled in-process model (no daemon required).`);
176
- } else if (embedder.provider === 'off') {
177
- console.log(` โ†ช No Ollama and no in-process model installed (\`npm run embed:setup:local\`) โ€” indexing lexical-only.`);
178
- }
179
- }
180
- console.log('');
181
-
182
- let existingCache = readEmbeddingBinary(EMBEDDINGS_PATH);
183
- // A model switch invalidates the cached vectors โ€” vectors of different models
184
- // (and dims) must never be mixed in one bin. Re-embed from scratch. (e.g. switching
185
- // `--embed-provider local` โ†’ `code-local`: 384-dim MiniLM โ†’ 768-dim jina-code.)
186
- const prevMeta = readEmbedMeta(EMBEDDINGS_PATH);
187
- if (embedModelChanged(prevMeta, embedder.model)) {
188
- console.log(`โš ๏ธ Embedding model changed (${prevMeta.model} โ†’ ${embedder.model}); re-embedding from scratch.`);
189
- existingCache = new Map();
190
- }
191
- console.log(`๐Ÿ“ฆ Loaded ${existingCache.size} cached embeddings from previous runs.\n`);
192
-
193
- const indexData = { chunks: [], graph: { dependencies: {}, importedBy: {}, routes: [] }, embeddingCache: {} };
194
- const pendingChunks = [];
195
- // Full bodies of oversized chunks (snippet was truncated by the 3000-char cap),
196
- // captured here while we still hold the source so the dense channel can window the
197
- // WHOLE definition. Kept out of the chunk/JSON โ€” transient, dropped after embedding.
198
- const fullBodies = new Map();
199
- let totalCheckedFiles = 0;
200
-
201
- for (const absolutePath of files) {
202
- totalCheckedFiles++;
203
- const relPath = path.relative(PROJECT_ROOT, absolutePath).replace(/\\/g, '/');
204
- process.stdout.write(`\rโšก Parsing AST: [${totalCheckedFiles}/${files.length}] Processing: ${relPath.slice(-40)} `);
205
-
206
- if (relPath.includes('.bundle.') || relPath.includes('.min.')) continue;
207
-
208
- try {
209
- const stats = await fs.promises.stat(absolutePath);
210
- if (stats.size > MAX_FILE_SIZE_BYTES) continue;
211
-
212
- const content = await fs.promises.readFile(absolutePath, 'utf-8');
213
- if (!content.trim()) continue;
214
-
215
- const ext = path.extname(absolutePath);
216
- const parser = getParserForFile(ext);
217
- if (!parser) continue;
218
-
219
- const tree = parser.parse((offset) => offset < content.length ? content.slice(offset, offset + 4096) : null);
220
- const rawImports = extractImportsFromAST(tree.rootNode, ext);
221
- const imports = resolveLocalImports(rawImports, relPath, PROJECT_ROOT);
222
- indexData.graph.dependencies[relPath] = imports;
223
-
224
- const fileChunks = extractSemanticChunks(tree.rootNode, relPath, content, ext, { interprocedural: config.interprocedural });
225
- for (const chunk of fileChunks) {
226
- const fullBody = fullBodyForEmbedding(chunk, content);
227
- if (fullBody) fullBodies.set(chunk.id, fullBody);
228
- pendingChunks.push(chunk);
229
- }
230
-
231
- for (const route of extractRoutes(tree.rootNode, relPath, fileChunks, ext)) {
232
- indexData.graph.routes.push(route);
233
- }
234
- } catch (err) {
235
- console.error(`\n๐Ÿ’ฅ Error in ${relPath}: ${err.message}`);
236
- }
237
- }
238
-
239
- // Opt-in inter-procedural receiver-type fixpoint (--interprocedural): propagate return
240
- // types along factory call chains so multi-hop receivers resolve. Runs ONCE over the whole
241
- // program here, while every chunk's return_via / call_sites are known, and writes
242
- // recv_resolved_type into call_sites (serialized identically by both backends). Strips the
243
- // transient _return_via. Off by default โ†’ chunks/index byte-identical.
244
- if (config.interprocedural) {
245
- const { applyInterprocedural } = await import('./parse/interprocedural.mjs');
246
- applyInterprocedural(pendingChunks);
247
- console.log('๐Ÿ”— Inter-procedural receiver types resolved (factory return-type propagation).');
248
- }
249
-
250
- // Enrichment runs before embedding so hypothetical questions share the same vector space.
251
- if (config.enrichment.enabled) {
252
- await enrichCoreChunks(pendingChunks, indexData.graph, config);
253
- }
254
-
255
- // โ”€โ”€ Embedding generation (cache-aware) โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€
256
- // Vectors are keyed by embeddingKeyFor(chunk), which includes an enrichment
257
- // digest so enriched chunks hit the cache on re-runs (previously they were
258
- // re-embedded on every run).
259
- const toEmbed = [];
260
- for (const chunk of pendingChunks) {
261
- const vecKey = embeddingKeyFor(chunk);
262
- const sKey = vecKey + SUMMARY_VEC_SUFFIX;
263
- // Compute the payload once here and reuse it in the worker to avoid a second build.
264
- const payload = buildEmbeddingPayload(chunk, indexData.graph.dependencies[chunk.file_path] || [], fullBodies.get(chunk.id) || null);
265
- const windows = embeddingWindows(payload);
266
- // Indexes built before dual/window vectors only have the base key, so we must
267
- // check that summary and window keys are also cached before skipping embedding.
268
- const summaryMissing = summaryEmbeddingText(chunk) && !existingCache.has(sKey);
269
- let windowsMissing = false;
270
- for (let i = 1; i < windows.length; i++) if (!existingCache.has(vecKey + WINDOW_VEC_SUFFIX + i)) { windowsMissing = true; break; }
271
- if (existingCache.has(vecKey) && !summaryMissing && !windowsMissing) {
272
- indexData.embeddingCache[vecKey] = Array.from(existingCache.get(vecKey));
273
- if (existingCache.has(sKey)) indexData.embeddingCache[sKey] = Array.from(existingCache.get(sKey));
274
- for (let i = 1; i < windows.length; i++) {
275
- const wk = vecKey + WINDOW_VEC_SUFFIX + i;
276
- if (existingCache.has(wk)) indexData.embeddingCache[wk] = Array.from(existingCache.get(wk));
277
- }
278
- indexData.chunks.push(chunk);
279
- } else {
280
- toEmbed.push({ chunk, payload, windows });
281
- }
282
- }
283
-
284
- console.log(`\n\n๐Ÿง  Embedding Generation โ€” ${describeEmbedder(embedder)}`);
285
- console.log(`Chunks reused from cache: ${indexData.chunks.length}`);
286
- console.log(`New chunks to process: ${toEmbed.length}`);
287
-
288
- if (toEmbed.length > 0) {
289
- const BATCH_SIZE = 64;
290
- // Embedding concurrency. A single local Ollama model serves requests
291
- // serially, so a high fan-out just queues batches and risks per-request
292
- // timeouts (a large model like qwen3-embedding:4b made every queued batch
293
- // breach the old cap). Default 4 (fast on small models / when
294
- // OLLAMA_NUM_PARALLEL is set); lower it (e.g. 1) for big models on modest
295
- // hardware via INDEXER_EMBED_CONCURRENCY.
296
- const CONCURRENCY = Number(process.env.INDEXER_EMBED_CONCURRENCY) > 0
297
- ? Number(process.env.INDEXER_EMBED_CONCURRENCY) : 4;
298
- const batches = [];
299
- for (let i = 0; i < toEmbed.length; i += BATCH_SIZE) batches.push(toEmbed.slice(i, i + BATCH_SIZE));
300
-
301
- let completed = 0, vectorBatches = 0, failedBatches = 0;
302
- console.time('Embedding Generation Duration');
303
- const worker = async (batch) => {
304
- // Oversized chunks need window vectors so semantic search can reach
305
- // their tail (the embedder truncates the base text to window 0 only).
306
- // Enriched chunks also get a compact summary vector whose vocabulary
307
- // matches natural-language queries.
308
- const entries = [];
309
- for (const { chunk: c, payload, windows } of batch) {
310
- const baseKey = embeddingKeyFor(c);
311
- entries.push({ key: baseKey, text: payload });
312
- for (let i = 1; i < windows.length; i++) entries.push({ key: baseKey + WINDOW_VEC_SUFFIX + i, text: windows[i] });
313
- const sText = summaryEmbeddingText(c);
314
- if (sText) entries.push({ key: baseKey + SUMMARY_VEC_SUFFIX, text: sText });
315
- }
316
- // Per-batch graceful degradation: a slow/failed embedding batch (e.g. a
317
- // timeout on a big model) must NOT abort the whole index. Those chunks
318
- // are still indexed lexically โ€” they just miss their vector until the
319
- // next run re-tries them (the cache only stores what succeeded).
320
- let matrix = null;
321
- try { matrix = await embedder.embedDocuments(entries.map(e => e.text)); }
322
- catch (e) { failedBatches++; process.stderr.write(`\nโš ๏ธ embedding batch failed (${e.message}); indexing ${batch.length} chunks lexical-only this run.\n`); }
323
- if (matrix && matrix.length === entries.length) {
324
- for (let j = 0; j < entries.length; j++) {
325
- indexData.embeddingCache[entries[j].key] = matrix[j];
326
- }
327
- vectorBatches++;
328
- }
329
- for (const { chunk } of batch) indexData.chunks.push(chunk);
330
- completed += batch.length;
331
- process.stdout.write(`\r๐Ÿค– Embedding Progress: [${completed}/${toEmbed.length}] Chunks processed...`);
332
- };
333
- for (let i = 0; i < batches.length; i += CONCURRENCY) {
334
- await Promise.all(batches.slice(i, i + CONCURRENCY).map(worker));
335
- }
336
- console.timeEnd('Embedding Generation Duration');
337
- if (failedBatches > 0) {
338
- console.log(`โš ๏ธ ${failedBatches}/${batches.length} embedding batches failed (lexical-only for those chunks); re-run to fill them in. `
339
- + `Tip: a large embed model on modest hardware wants INDEXER_EMBED_CONCURRENCY=1 and/or a higher INDEXER_EMBED_TIMEOUT_MS.`);
340
- }
341
- }
342
-
343
- for (const [filePath, imports] of Object.entries(indexData.graph.dependencies)) {
344
- for (const dep of imports) {
345
- if (!indexData.graph.importedBy[dep]) indexData.graph.importedBy[dep] = [];
346
- if (!indexData.graph.importedBy[dep].includes(filePath)) indexData.graph.importedBy[dep].push(filePath);
347
- }
348
- }
349
-
350
- // Opt-in resolved symbol graph (--symbol-graph): build the chunkโ†’chunk edge set ONCE
351
- // over the finalized chunks (reusing the query-time resolvers, so confidence matches
352
- // get_call_graph). Serialized into the index for both backends โ†’ getEdges. Built via a
353
- // throwaway in-memory store so it sees the same resolution the MCP server will.
354
- let symbolEdges = null;
355
- let centrality = null;
356
- let scipReferers = null; // A2 v2: SCIP precise cross-file references for find_references
357
- if (config.symbolGraph) {
358
- const tmpSg = path.join(config.dataDir, '_symbolgraph-build.json');
359
- try {
360
- fs.writeFileSync(tmpSg, JSON.stringify({ chunks: indexData.chunks, graph: indexData.graph }));
361
- const { MemoryGraphIndex } = await import('./engine/memory.mjs');
362
- const { buildSymbolGraph } = await import('./mcp/symbolgraph.mjs');
363
- const { getResolver, createScipResolver } = await import('./mcp/resolver.mjs');
364
- const { computeSymbolCentrality } = await import('./mcp/centrality.mjs');
365
- const sgIdx = new MemoryGraphIndex(tmpSg, { cacheEmbeddings: false });
366
- sgIdx.load();
367
- // A2: a 'scip' resolver ingests a locally-generated SCIP index and resolves edges by
368
- // real cross-file bindings (promote confirmed โ†’ `resolved`, suppress wrong-target
369
- // fan-out). Missing/unreadable index โ†’ fall back to heuristic (never worse, loud).
370
- let resolver = getResolver(config.resolver);
371
- let scipStats = null;
372
- if (config.resolver === 'scip') {
373
- if (!config.scipIndex) {
374
- console.warn('โš ๏ธ --resolver scip without --scip-index โ€” no SCIP index to read; '
375
- + 'falling back to heuristic resolver.');
376
- resolver = getResolver('heuristic');
377
- } else {
378
- try {
379
- const { loadScip, buildScipBindings, buildScipReferers } = await import('./parse/scip.mjs');
380
- const aligned = buildScipBindings(sgIdx, loadScip(config.scipIndex));
381
- scipStats = aligned.stats;
382
- resolver = createScipResolver(aligned.bindings, aligned.definedChunks);
383
- // A2 v2: invert the same bindings into the precise cross-file "referenced-by"
384
- // map find_references consumes (kind-agnostic, sound, isolated artifact).
385
- const refs = buildScipReferers(aligned.bindings);
386
- if (Object.keys(refs).length) scipReferers = refs;
387
- if (scipStats.matchedDocs === 0) {
388
- console.warn(`โš ๏ธ SCIP index matched 0 of ${scipStats.docs} document(s) to indexed `
389
- + `files (${config.scipIndex}) โ€” check the path / project_root. Resolver is `
390
- + 'effectively inert (edges stay heuristic { high, name_only }).');
391
- }
392
- } catch (e) {
393
- console.warn(`โš ๏ธ SCIP load failed (${e.message}); falling back to heuristic resolver.`);
394
- resolver = getResolver('heuristic');
395
- }
396
- }
397
- }
398
- const res = buildSymbolGraph(sgIdx, { resolver });
399
- symbolEdges = res.edges;
400
- sgIdx.close?.();
401
- const isPreciseTier = config.resolver === 'precise' || (config.resolver === 'scip' && scipStats);
402
- const resolvedCount = isPreciseTier
403
- ? symbolEdges.filter(e => e.confidence === 'resolved').length : 0;
404
- console.log(`๐Ÿ•ธ Symbol graph: ${symbolEdges.length} resolved edges`
405
- + `${config.resolver === 'precise' ? ` ยท resolver=precise (${resolvedCount} resolved-tier)` : ''}`
406
- + `${(config.resolver === 'scip' && scipStats) ? ` ยท resolver=scip (${resolvedCount} resolved-tier; `
407
- + `${scipStats.matchedDocs}/${scipStats.docs} docs matched, ${scipStats.bindingPairs} bindings)` : ''}`
408
- + `${res.cappedNames.length ? ` (โš ๏ธ ${res.cappedNames.length} high-degree name(s) capped: ${res.cappedNames.slice(0, 5).join(', ')})` : ''}.`);
409
- // A5: confidence-weighted PageRank over those edges (computed once โ†’ serialized โ†’
410
- // parity-free). Surfaced by explain_symbol / get_repo_map; does not touch ranking.
411
- const cen = computeSymbolCentrality(symbolEdges);
412
- centrality = cen.total ? cen.centrality : null;
413
- if (centrality) console.log(`๐Ÿ“Š Centrality: ranked ${cen.total} connected symbols (PageRank, ${cen.iters} iters).`);
414
- // A2 v2: precise cross-file references (find_references `resolved` tier), serialized
415
- // as an isolated artifact alongside the graph.
416
- if (scipReferers) {
417
- const pairs = Object.values(scipReferers).reduce((s, a) => s + a.length, 0);
418
- console.log(`๐ŸŽฏ SCIP references: ${Object.keys(scipReferers).length} definitions referenced (${pairs} precise referer pairs).`);
419
- }
420
- } finally {
421
- try { fs.unlinkSync(tmpSg); } catch { /* none */ }
422
- }
423
- }
424
-
425
- // C2: opt-in index-time taint serialization. Compute the full flow set once โ€” against the
426
- // symbol-graph edges when present (cross-function precision), else chunk.calls โ€” and serialize
427
- // it so trace_taint / find_tainted_sinks answer instantly. Like edges/centrality: computed once
428
- // โ†’ both backends serve byte-identical flows (parity-free).
429
- let taintPayload = null;
430
- if (config.taint) {
431
- const tmpT = path.join(config.dataDir, '_taint-build.json');
432
- try {
433
- fs.writeFileSync(tmpT, JSON.stringify({
434
- chunks: indexData.chunks, graph: indexData.graph,
435
- ...(symbolEdges ? { edges: symbolEdges } : {}),
436
- }));
437
- const { MemoryGraphIndex } = await import('./engine/memory.mjs');
438
- const { computeTaintCache } = await import('./mcp/taint.mjs');
439
- const tIdx = new MemoryGraphIndex(tmpT, { cacheEmbeddings: false });
440
- tIdx.load();
441
- taintPayload = computeTaintCache(tIdx, { maxDepth: 4 });
442
- tIdx.close?.();
443
- console.log(`๐Ÿงช Taint: ${taintPayload.flows.length} flows precomputed `
444
- + `(${taintPayload.meta.sources} sources, ${taintPayload.meta.sinks} sinks, depth ${taintPayload.meta.maxDepth}).`);
445
- } finally {
446
- try { fs.unlinkSync(tmpT); } catch { /* none */ }
447
- }
448
- }
449
-
450
- // B3: opt-in learned-sparse model. Learn the corpus co-occurrence (PMI) association model once
451
- // and serialize it (isolated artifact, like centrality/taint); searchHybrid then adds an NL-only
452
- // vocabulary-expansion channel. Zero new dependency, fully air-gapped; default index
453
- // byte-identical (no model unless --learned-sparse).
454
- let sparseModel = null;
455
- if (config.learnedSparse) {
456
- const { buildSparseModel } = await import('./search-sparse.mjs');
457
- sparseModel = buildSparseModel(indexData.chunks);
458
- if (sparseModel) {
459
- console.log(`๐Ÿงฉ Learned-sparse: ${sparseModel.meta.terms} terms ยท ${sparseModel.meta.pairs} associations `
460
- + `(PMI over ${sparseModel.meta.docs} chunks).`);
461
- } else {
462
- console.log('๐Ÿงฉ Learned-sparse: no association signal in this corpus โ€” model omitted (channel inert).');
463
- }
464
- }
465
-
466
- // Resolve 'auto' now that the true chunk count is known โ€” the threshold is only
467
- // meaningful after all chunks have been extracted.
468
- const backend = config.storage === 'auto'
469
- ? (indexData.chunks.length >= AUTO_SQLITE_CHUNK_THRESHOLD ? 'sqlite' : 'memory')
470
- : config.storage;
471
- if (config.storage === 'auto') {
472
- console.log(`๐Ÿ—„ Storage: auto โ†’ ${backend} (${indexData.chunks.length} chunks, threshold ${AUTO_SQLITE_CHUNK_THRESHOLD}).`);
473
- }
474
-
475
- if (backend === 'sqlite') {
476
- const { SqliteGraphStore } = await import('./engine/sqlite.mjs');
477
- const store = new SqliteGraphStore(config.sqlitePath, { embeddingPath: EMBEDDINGS_PATH });
478
- const res = store.buildFrom({
479
- chunks: indexData.chunks, graph: indexData.graph, embeddingCache: indexData.embeddingCache,
480
- edges: symbolEdges, centrality, taint: taintPayload, scipRefs: scipReferers,
481
- sparseModel,
482
- });
483
- store.close?.();
484
- for (const p of [INDEX_PATH, `${INDEX_PATH}.tmp`]) { try { fs.unlinkSync(p); } catch { /* none */ } }
485
- console.log(`\n๐ŸŽ‰ SQLite index built: ${res.chunks} chunks ยท ${res.terms} terms ยท dim ${res.dim}`);
486
- console.log(` โ†’ ${config.sqlitePath}\n`);
487
- } else {
488
- const tmpPath = `${INDEX_PATH}.tmp`;
489
- const tmpBinPath = `${EMBEDDINGS_PATH}.tmp`;
490
- await Promise.all([
491
- fs.promises.writeFile(tmpPath, JSON.stringify({
492
- chunks: indexData.chunks, graph: indexData.graph,
493
- ...(symbolEdges ? { edges: symbolEdges } : {}),
494
- ...(centrality ? { centrality } : {}),
495
- ...(taintPayload ? { taint: taintPayload } : {}),
496
- ...(scipReferers ? { scip_refs: scipReferers } : {}),
497
- ...(sparseModel ? { sparse_model: sparseModel } : {}),
498
- })),
499
- fs.promises.writeFile(tmpBinPath, writeEmbeddingBinary(indexData.embeddingCache)),
500
- ]);
501
- await Promise.all([
502
- fs.promises.rename(tmpPath, INDEX_PATH),
503
- fs.promises.rename(tmpBinPath, EMBEDDINGS_PATH),
504
- ]);
505
- for (const p of [config.sqlitePath, `${config.sqlitePath}-wal`, `${config.sqlitePath}-shm`]) {
506
- try { fs.unlinkSync(p); } catch { /* none */ }
507
- }
508
- if (indexData.chunks.length === 0) {
509
- console.log(`\nโš ๏ธ Indexing finished but produced 0 chunks โ€” no indexable definitions found under ${PROJECT_ROOT}.`);
510
- console.log(` Check the --repo path is correct and contains supported languages (see README), and note that trivial one-line definitions are intentionally skipped.\n`);
511
- } else {
512
- console.log(`\n๐ŸŽ‰ Indexing complete. Total fragments: ${indexData.chunks.length}\n`);
513
- }
514
- }
515
-
516
- // Stamp which model produced the shared embeddings bin, so the server queries
517
- // with the same provider and the next index run detects a model switch.
518
- writeEmbedMeta(EMBEDDINGS_PATH, {
519
- provider: embedder.provider,
520
- model: embedder.model,
521
- dim: embedder.dim ?? prevMeta?.dim ?? null,
522
- });
523
-
524
- // Git signals are a sidecar kept out of the main index so they don't affect
525
- // measured retrieval ranking โ€” only opt-in tools consume them.
526
- if (config.gitSignals) {
527
- const signals = collectGitSignals(PROJECT_ROOT);
528
- if (signals) {
529
- writeGitSignals(config.gitSignalsPath, signals);
530
- console.log(`๐Ÿ”„ Git signals: ${signals.commits} commits ยท ${Object.keys(signals.churn).length} files (churn/recency/co-change).\n`);
531
- } else {
532
- // Drop any stale sidecar so signals from a previous run don't linger.
533
- try { fs.unlinkSync(config.gitSignalsPath); } catch { /* none to remove */ }
534
- }
535
- }
536
-
537
- // Kill any subprocess-based embedder (MLX) so the event loop can drain.
538
- // Without this the readline interface on proc.stdout keeps Node alive indefinitely.
539
- _resetSubprocesses();
540
- }
541
-
542
- main().catch((err) => {
543
- if (err && err.name === 'SealViolation') { console.error(`๐Ÿ”’ ${err.message}`); process.exit(2); }
544
- console.error(err);
545
- process.exit(1);
546
- });