@esankhan3/anvil-knowledge-core 0.4.5 → 0.4.7

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 (138) hide show
  1. package/dist/__tests__/ast-graph.test.d.ts +9 -0
  2. package/dist/__tests__/ast-graph.test.d.ts.map +1 -0
  3. package/dist/__tests__/ast-graph.test.js +93 -0
  4. package/dist/__tests__/ast-graph.test.js.map +1 -0
  5. package/dist/__tests__/chunker-boundaries.test.d.ts +10 -0
  6. package/dist/__tests__/chunker-boundaries.test.d.ts.map +1 -0
  7. package/dist/__tests__/chunker-boundaries.test.js +218 -0
  8. package/dist/__tests__/chunker-boundaries.test.js.map +1 -0
  9. package/dist/__tests__/content-hash-reuse.test.d.ts +8 -0
  10. package/dist/__tests__/content-hash-reuse.test.d.ts.map +1 -0
  11. package/dist/__tests__/content-hash-reuse.test.js +110 -0
  12. package/dist/__tests__/content-hash-reuse.test.js.map +1 -0
  13. package/dist/__tests__/cross-repo-detector.test.js +5 -0
  14. package/dist/__tests__/cross-repo-detector.test.js.map +1 -1
  15. package/dist/__tests__/env-overrides.test.js +29 -0
  16. package/dist/__tests__/env-overrides.test.js.map +1 -1
  17. package/dist/__tests__/graph-store-queries.test.d.ts +14 -0
  18. package/dist/__tests__/graph-store-queries.test.d.ts.map +1 -0
  19. package/dist/__tests__/graph-store-queries.test.js +246 -0
  20. package/dist/__tests__/graph-store-queries.test.js.map +1 -0
  21. package/dist/__tests__/identifier-bm25.test.d.ts +7 -0
  22. package/dist/__tests__/identifier-bm25.test.d.ts.map +1 -0
  23. package/dist/__tests__/identifier-bm25.test.js +107 -0
  24. package/dist/__tests__/identifier-bm25.test.js.map +1 -0
  25. package/dist/__tests__/index-cycle-cost.test.d.ts +8 -0
  26. package/dist/__tests__/index-cycle-cost.test.d.ts.map +1 -0
  27. package/dist/__tests__/index-cycle-cost.test.js +122 -0
  28. package/dist/__tests__/index-cycle-cost.test.js.map +1 -0
  29. package/dist/__tests__/index-integrity.test.d.ts +10 -0
  30. package/dist/__tests__/index-integrity.test.d.ts.map +1 -0
  31. package/dist/__tests__/index-integrity.test.js +151 -0
  32. package/dist/__tests__/index-integrity.test.js.map +1 -0
  33. package/dist/__tests__/kb-fixture.d.ts +32 -0
  34. package/dist/__tests__/kb-fixture.d.ts.map +1 -0
  35. package/dist/__tests__/kb-fixture.js +116 -0
  36. package/dist/__tests__/kb-fixture.js.map +1 -0
  37. package/dist/__tests__/nprobes-calibration.test.d.ts +10 -0
  38. package/dist/__tests__/nprobes-calibration.test.d.ts.map +1 -0
  39. package/dist/__tests__/nprobes-calibration.test.js +107 -0
  40. package/dist/__tests__/nprobes-calibration.test.js.map +1 -0
  41. package/dist/__tests__/project-graph-cross-edges.test.d.ts +7 -0
  42. package/dist/__tests__/project-graph-cross-edges.test.d.ts.map +1 -0
  43. package/dist/__tests__/project-graph-cross-edges.test.js +45 -0
  44. package/dist/__tests__/project-graph-cross-edges.test.js.map +1 -0
  45. package/dist/__tests__/query-caches.test.d.ts +7 -0
  46. package/dist/__tests__/query-caches.test.d.ts.map +1 -0
  47. package/dist/__tests__/query-caches.test.js +86 -0
  48. package/dist/__tests__/query-caches.test.js.map +1 -0
  49. package/dist/__tests__/retriever-config.test.d.ts +8 -0
  50. package/dist/__tests__/retriever-config.test.d.ts.map +1 -0
  51. package/dist/__tests__/retriever-config.test.js +77 -0
  52. package/dist/__tests__/retriever-config.test.js.map +1 -0
  53. package/dist/__tests__/retriever-graph-expansion.test.d.ts +8 -0
  54. package/dist/__tests__/retriever-graph-expansion.test.d.ts.map +1 -0
  55. package/dist/__tests__/retriever-graph-expansion.test.js +79 -0
  56. package/dist/__tests__/retriever-graph-expansion.test.js.map +1 -0
  57. package/dist/__tests__/tree-sitter-parse.test.d.ts +8 -0
  58. package/dist/__tests__/tree-sitter-parse.test.d.ts.map +1 -0
  59. package/dist/__tests__/tree-sitter-parse.test.js +124 -0
  60. package/dist/__tests__/tree-sitter-parse.test.js.map +1 -0
  61. package/dist/ast-graph-builder.d.ts +4 -2
  62. package/dist/ast-graph-builder.d.ts.map +1 -1
  63. package/dist/ast-graph-builder.js +60 -35
  64. package/dist/ast-graph-builder.js.map +1 -1
  65. package/dist/chunker.d.ts +16 -6
  66. package/dist/chunker.d.ts.map +1 -1
  67. package/dist/chunker.js +130 -42
  68. package/dist/chunker.js.map +1 -1
  69. package/dist/config.d.ts +3 -0
  70. package/dist/config.d.ts.map +1 -1
  71. package/dist/config.js +6 -6
  72. package/dist/config.js.map +1 -1
  73. package/dist/cross-repo-detector.d.ts +5 -2
  74. package/dist/cross-repo-detector.d.ts.map +1 -1
  75. package/dist/cross-repo-detector.js +31 -3
  76. package/dist/cross-repo-detector.js.map +1 -1
  77. package/dist/embedder.d.ts +5 -5
  78. package/dist/embedder.d.ts.map +1 -1
  79. package/dist/embedder.js.map +1 -1
  80. package/dist/file-walker.d.ts +3 -1
  81. package/dist/file-walker.d.ts.map +1 -1
  82. package/dist/file-walker.js +9 -3
  83. package/dist/file-walker.js.map +1 -1
  84. package/dist/git-diff.d.ts.map +1 -1
  85. package/dist/git-diff.js +5 -11
  86. package/dist/git-diff.js.map +1 -1
  87. package/dist/graph-store.d.ts +34 -6
  88. package/dist/graph-store.d.ts.map +1 -1
  89. package/dist/graph-store.js +263 -101
  90. package/dist/graph-store.js.map +1 -1
  91. package/dist/index.d.ts +1 -1
  92. package/dist/index.d.ts.map +1 -1
  93. package/dist/indexer.d.ts +8 -0
  94. package/dist/indexer.d.ts.map +1 -1
  95. package/dist/indexer.js +293 -122
  96. package/dist/indexer.js.map +1 -1
  97. package/dist/project-graph-builder.d.ts.map +1 -1
  98. package/dist/project-graph-builder.js +12 -11
  99. package/dist/project-graph-builder.js.map +1 -1
  100. package/dist/query-expander.d.ts.map +1 -1
  101. package/dist/query-expander.js +12 -8
  102. package/dist/query-expander.js.map +1 -1
  103. package/dist/query-router.d.ts +5 -0
  104. package/dist/query-router.d.ts.map +1 -1
  105. package/dist/query-router.js +1 -1
  106. package/dist/query-router.js.map +1 -1
  107. package/dist/repo-pipeline.d.ts +8 -0
  108. package/dist/repo-pipeline.d.ts.map +1 -1
  109. package/dist/repo-pipeline.js +9 -6
  110. package/dist/repo-pipeline.js.map +1 -1
  111. package/dist/retriever.d.ts.map +1 -1
  112. package/dist/retriever.js +36 -21
  113. package/dist/retriever.js.map +1 -1
  114. package/dist/storage/fs-blob-store.d.ts +3 -4
  115. package/dist/storage/fs-blob-store.d.ts.map +1 -1
  116. package/dist/storage/fs-blob-store.js +14 -7
  117. package/dist/storage/fs-blob-store.js.map +1 -1
  118. package/dist/storage/ports.d.ts +15 -0
  119. package/dist/storage/ports.d.ts.map +1 -1
  120. package/dist/tree-sitter-parser.d.ts +10 -2
  121. package/dist/tree-sitter-parser.d.ts.map +1 -1
  122. package/dist/tree-sitter-parser.js +169 -43
  123. package/dist/tree-sitter-parser.js.map +1 -1
  124. package/dist/types.d.ts +12 -1
  125. package/dist/types.d.ts.map +1 -1
  126. package/dist/vector-index-maintenance.d.ts +4 -1
  127. package/dist/vector-index-maintenance.d.ts.map +1 -1
  128. package/dist/vector-index-maintenance.js +26 -1
  129. package/dist/vector-index-maintenance.js.map +1 -1
  130. package/dist/vector-recall.d.ts +13 -1
  131. package/dist/vector-recall.d.ts.map +1 -1
  132. package/dist/vector-recall.js +33 -0
  133. package/dist/vector-recall.js.map +1 -1
  134. package/dist/vector-store.d.ts +54 -8
  135. package/dist/vector-store.d.ts.map +1 -1
  136. package/dist/vector-store.js +222 -56
  137. package/dist/vector-store.js.map +1 -1
  138. package/package.json +3 -3
package/dist/indexer.js CHANGED
@@ -4,6 +4,8 @@ import { tmpdir } from 'node:os';
4
4
  import { createEmbeddingProvider } from '@esankhan3/anvil-knowledge-core';
5
5
  import { resolveStorage, invalidateGraphStores } from './storage/resolve.js';
6
6
  import { maintainVectorIndex, readVectorIndexHealth } from './vector-index-maintenance.js';
7
+ import { contentHash, splitIdentifiers } from './vector-store.js';
8
+ import { cosineSimilarity } from './query-router.js';
7
9
  import { FsBlobStore } from './storage/fs-blob-store.js';
8
10
  import { ProjectGraphBuilder } from '@esankhan3/anvil-knowledge-core';
9
11
  import { correlateCrossRepoEdges, CROSS_REPO_SIGNALS_VERSION } from './cross-repo-detector.js';
@@ -12,7 +14,7 @@ import { HybridRetriever } from './retriever.js';
12
14
  import { loadKnowledgeConfig, getKnowledgeBasePath } from '@esankhan3/anvil-knowledge-core';
13
15
  import { profileProject, loadAllProfiles } from '@esankhan3/anvil-knowledge-core';
14
16
  import { inferServiceMesh } from '@esankhan3/anvil-knowledge-core';
15
- import { computeStructuralHash } from '@esankhan3/anvil-knowledge-core';
17
+ import { CHUNK_ID_VERSION } from './chunker.js';
16
18
  import { createQueryRouter } from '@esankhan3/anvil-knowledge-core';
17
19
  import { iterateChunksFile } from './chunks-io.js';
18
20
  import { writeSystemGraphSqlite, createSystemGraphSqliteWriter } from './graph-store.js';
@@ -29,59 +31,39 @@ async function writeRepoIndexMeta(blobs, repoName, meta) {
29
31
  await blobs.putJson(`${repoName}/index_meta.json`, meta);
30
32
  }
31
33
  /**
32
- * Structural dedup, streaming: read each per-repo shard line-by-line, keep the
33
- * first chunk per structural hash, write survivors to chunks.json. Bounded
34
- * memory — a Set of hashes + one chunk at a time, never the whole corpus (this
35
- * replaces the in-RAM deduplicateByStructure(allChunks) that OOM'd at org scale).
36
- * Keeps first-seen per hash (repo order) rather than smallest-id, but the
37
- * survivors are structurally identical, so dedup is functionally equivalent.
34
+ * Merge the per-repo shards (+ chunks carried forward from the previous
35
+ * corpus) into chunks.json, streaming: one chunk at a time plus a Set of ids,
36
+ * never the whole corpus. Every repo keeps its own copy of shared code —
37
+ * identical code in two repos is two searchable, separately-scoped chunks.
38
38
  */
39
- async function dedupShardsToChunks(shardPaths, blobs, chunksKey,
39
+ async function mergeShardsToChunks(shardPaths, blobs, chunksKey,
40
40
  /** Local NDJSON copy of the PREVIOUS chunks.json + which of its chunks to
41
41
  * keep. Absent on a full rebuild (every repo re-chunked) — the shards are
42
- * then the complete corpus, today's behavior. */
42
+ * then the complete corpus. */
43
43
  carryForward) {
44
- // Shards are transient local scratch — read raw. Survivors stream straight
45
- // into the durable chunks blob via putNdjson (byte-identical NDJSON to the
46
- // prior createChunkWriter); counts are tallied inside the generator and read
47
- // back after putNdjson drains it. Fresh shards stream FIRST so a re-chunked
48
- // file's new chunk wins the structural-hash dedup over a stale twin.
44
+ // Shards are transient local scratch — read raw. Chunks stream straight into
45
+ // the durable chunks blob via putNdjson; counts are tallied inside the
46
+ // generator and read back after putNdjson drains it. Fresh shards stream
47
+ // FIRST so a re-chunked chunk wins over a carried-forward one with its id.
49
48
  const seen = new Set();
50
- let kept = 0, dropped = 0, tokens = 0;
51
- async function* survivors() {
52
- for (const sp of shardPaths) {
53
- if (!existsSync(sp))
54
- continue;
55
- for await (const c of iterateChunksFile(sp)) {
56
- const h = computeStructuralHash(c.content, c.language).hash;
57
- if (seen.has(h)) {
58
- dropped++;
49
+ let kept = 0, tokens = 0;
50
+ async function* merged() {
51
+ const sources = shardPaths.filter((sp) => existsSync(sp)).map((sp) => ({ path: sp, keep: () => true }));
52
+ if (carryForward && existsSync(carryForward.prevPath))
53
+ sources.push({ path: carryForward.prevPath, keep: carryForward.keep });
54
+ for (const { path, keep } of sources) {
55
+ for await (const c of iterateChunksFile(path)) {
56
+ if (!keep(c) || seen.has(c.id))
59
57
  continue;
60
- }
61
- seen.add(h);
62
- kept++;
63
- tokens += c.tokens;
64
- yield c;
65
- }
66
- }
67
- if (carryForward && existsSync(carryForward.prevPath)) {
68
- for await (const c of iterateChunksFile(carryForward.prevPath)) {
69
- if (!carryForward.keep(c))
70
- continue;
71
- const h = computeStructuralHash(c.content, c.language).hash;
72
- if (seen.has(h)) {
73
- dropped++;
74
- continue;
75
- }
76
- seen.add(h);
58
+ seen.add(c.id);
77
59
  kept++;
78
60
  tokens += c.tokens;
79
61
  yield c;
80
62
  }
81
63
  }
82
64
  }
83
- await blobs.putNdjson(chunksKey, survivors());
84
- return { kept, dropped, tokens };
65
+ await blobs.putNdjson(chunksKey, merged());
66
+ return { kept, tokens };
85
67
  }
86
68
  export class KnowledgeIndexer {
87
69
  // ---------------------------------------------------------------------------
@@ -113,13 +95,14 @@ export class KnowledgeIndexer {
113
95
  : sameWorkingTreeState(meta?.workingTree ?? {}, getWorkingTreeState(repo.path));
114
96
  if (meta && currentSha && meta.lastIndexedSha === currentSha && treeUnchanged) {
115
97
  // A skipped repo is served entirely from its stored artifacts (graph +
116
- // cross-repo signals) — no clone, no AST re-parse. An index whose
117
- // signals are missing or in an older format must be re-indexed once
118
- // to (re)extract them.
98
+ // cross-repo signals + chunks carried forward) — no clone, no AST
99
+ // re-parse. An index whose signals are missing or in an older format,
100
+ // or whose chunks use an older id scheme, must be re-indexed once.
119
101
  const signals = await storage.blobs
120
102
  .getJson(`${repo.name}/signals.json`)
121
103
  .catch(() => null);
122
- const hasArtifacts = (await storage.blobs.exists(`${repo.name}/graph.json`)) &&
104
+ const hasArtifacts = meta.chunkIdVersion === CHUNK_ID_VERSION &&
105
+ (await storage.blobs.exists(`${repo.name}/graph.json`)) &&
123
106
  signals?.version === CROSS_REPO_SIGNALS_VERSION;
124
107
  if (hasArtifacts) {
125
108
  skippedRepos.push(repo.name);
@@ -135,10 +118,20 @@ export class KnowledgeIndexer {
135
118
  reposToIndex.push(repo);
136
119
  }
137
120
  }
138
- if (reposToIndex.length === 0) {
121
+ // Repos the last cycle indexed that are no longer in the workspace: their
122
+ // chunks drop out of chunks.json below (embedChunks then sweeps their rows)
123
+ // and their per-repo artifacts are deleted — so this cycle isn't a no-op.
124
+ const currentRepoNames = new Set(repos.map((r) => r.name));
125
+ const prevStats = await storage.blobs
126
+ .getJson('index_stats.json')
127
+ .catch(() => null);
128
+ const removedRepos = (prevStats?.repos ?? [])
129
+ .map((r) => r.name)
130
+ .filter((n) => n && n !== '.' && n !== '..' && !/[\\/]/.test(n) && !currentRepoNames.has(n));
131
+ if (reposToIndex.length === 0 && removedRepos.length === 0) {
139
132
  log('All repos up to date — nothing to build.');
140
133
  report({ phase: 'done', message: 'All repos up to date', percent: 100, etaSeconds: 0, skippedRepos });
141
- return { project, repos: [], totalChunks: 0, totalTokens: 0, crossRepoEdges: 0, durationMs: 0, chunksPath: join(basePath, 'chunks.json') };
134
+ return { project, repos: [], totalChunks: 0, totalTokens: 0, crossRepoEdges: prevStats?.crossRepoEdges ?? 0, durationMs: 0, chunksPath: join(basePath, 'chunks.json') };
142
135
  }
143
136
  // 2. LLM Repo Profiling (WS-1) — skipped if LLM_MODE=none
144
137
  const { isLlmAvailable } = await import('./claude-runner.js');
@@ -267,13 +260,12 @@ export class KnowledgeIndexer {
267
260
  });
268
261
  }
269
262
  }
270
- // Structural dedup — streaming over the per-repo shards into chunks.json
271
- // (bounded memory; replaces the in-RAM dedup that OOM'd at org scale).
263
+ // Merge the per-repo shards into chunks.json, streaming (bounded memory).
272
264
  // PARTIAL CYCLES: the shards only cover repos re-chunked THIS cycle —
273
265
  // skipped repos' chunks and an incrementally-chunked repo's untouched
274
266
  // files must be carried forward from the previous chunks.json, or every
275
267
  // scheduled reindex silently shrinks the corpus to the changed set.
276
- report({ phase: 'dedup', message: 'Deduplicating chunks (streaming)...', percent: 68, etaSeconds: -1 });
268
+ report({ phase: 'dedup', message: 'Merging chunks (streaming)...', percent: 68, etaSeconds: -1 });
277
269
  const chunksPath = join(basePath, 'chunks.json');
278
270
  const anyPartialShard = [...repoChunkResults.values()].some((r) => !r.shardComplete);
279
271
  const needCarry = (skippedRepos.length > 0 || anyPartialShard) && (await storage.blobs.exists('chunks.json'));
@@ -286,28 +278,33 @@ export class KnowledgeIndexer {
286
278
  await storage.blobs.getBytes('chunks.json', { toFile: prevPath });
287
279
  const currentRepos = new Set(repos.map((r) => r.name));
288
280
  const fullyRechunked = new Set([...repoChunkResults.entries()].filter(([, r]) => r.shardComplete).map(([name]) => name));
289
- const removedFiles = new Map([...repoChunkResults.entries()]
281
+ // A partial shard's fileIndex lists every file the repo still has: carry
282
+ // forward only those, minus the ones re-chunked this cycle.
283
+ const partial = new Map([...repoChunkResults.entries()]
290
284
  .filter(([, r]) => !r.shardComplete)
291
- .map(([name, r]) => [name, new Set([...r.changedFiles, ...r.deletedFiles])]));
285
+ .map(([name, r]) => [name, { files: r.fileIndex, changed: new Set(r.changedFiles) }]));
292
286
  carryForward = {
293
287
  prevPath,
294
- keep: (c) => currentRepos.has(c.repoName) && // repos removed from the org drop out
295
- !fullyRechunked.has(c.repoName) && // complete shard = replaces the repo wholesale
296
- !removedFiles.get(c.repoName)?.has(c.filePath), // partial shard: only its changed/deleted files are replaced
288
+ keep: (c) => {
289
+ if (!currentRepos.has(c.repoName))
290
+ return false; // repos removed from the org drop out
291
+ if (fullyRechunked.has(c.repoName))
292
+ return false; // complete shard = replaces the repo wholesale
293
+ const p = partial.get(c.repoName);
294
+ return !p || (c.filePath in p.files && !p.changed.has(c.filePath));
295
+ },
297
296
  };
298
297
  }
299
- const dedup = await dedupShardsToChunks(shardPaths, storage.blobs, 'chunks.json', carryForward);
298
+ const merged = await mergeShardsToChunks(shardPaths, storage.blobs, 'chunks.json', carryForward);
300
299
  if (carryForward) {
301
300
  try {
302
301
  rmSync(carryForward.prevPath, { force: true });
303
302
  }
304
303
  catch { /* scratch */ }
305
304
  }
306
- const dedupedChunkCount = dedup.kept;
307
- const dedupedTokenSum = dedup.tokens;
308
- if (dedup.dropped > 0)
309
- log(`Structural dedup: ${dedup.dropped} duplicates removed`);
310
- log(`Saved ${dedupedChunkCount} chunks to ${chunksPath}`);
305
+ const mergedChunkCount = merged.kept;
306
+ const mergedTokenSum = merged.tokens;
307
+ log(`Saved ${mergedChunkCount} chunks to ${chunksPath}`);
311
308
  for (const sp of shardPaths) {
312
309
  try {
313
310
  rmSync(sp, { force: true });
@@ -409,18 +406,19 @@ export class KnowledgeIndexer {
409
406
  console.error(`[knowledge-core] Could not persist system graph (${graphBuilder.nodeCount} nodes, ${graphBuilder.edgeCount} edges): ${msg}. Cross-repo graph tools will be unavailable; search and embeddings are unaffected.`);
410
407
  }
411
408
  }
412
- // 11. (chunks.json was written + the chunk arrays freed right after dedup,
409
+ // 11. (chunks.json was written + the chunk arrays freed right after merging,
413
410
  // above — so ~810k chunk objects don't sit in memory through the graph build.)
414
411
  // 11b. Save stale files list (for incremental embedding cleanup).
415
- // Includes both deleted AND modified files: chunk.id is position-keyed
416
- // (chunker.ts:179), so an in-place edit at the same line range produces
412
+ // Includes both deleted AND modified files: chunk ids are position-keyed
413
+ // (chunker.ts chunkId), so an in-place edit at the same line range produces
417
414
  // an identical id and the embedder's id-set filter would otherwise leave
418
415
  // the old vector in LanceDB unchanged. Listing modified files here lets
419
416
  // embedChunks() wipe their old chunks before re-embedding.
420
417
  const allStaleFiles = [];
421
418
  for (const repo of reposToIndex) {
422
419
  const result = repoChunkResults.get(repo.name);
423
- if (!result)
420
+ // A repo indexed for the first time has no rows to wipe.
421
+ if (!result || !(await readRepoIndexMeta(basePath, repo.name, storage.blobs)))
424
422
  continue;
425
423
  for (const f of result.deletedFiles ?? []) {
426
424
  allStaleFiles.push({ repoName: repo.name, filePath: f });
@@ -446,26 +444,41 @@ export class KnowledgeIndexer {
446
444
  const sha = result?.sha ?? getRepoSha(repo.path);
447
445
  const totalChunkCount = result ? Object.values(result.fileIndex).reduce((sum, f) => sum + f.chunkCount, 0) : 0;
448
446
  if (sha) {
447
+ // The repo's unchanged rows keep the vector space they were embedded in
448
+ // until the embed step records the next one.
449
+ const prev = await readRepoIndexMeta(basePath, repo.name, storage.blobs);
449
450
  await writeRepoIndexMeta(storage.blobs, repo.name, {
450
451
  lastIndexedSha: sha,
451
452
  lastIndexedAt: new Date().toISOString(),
452
453
  chunkCount: totalChunkCount,
453
454
  embeddingProvider: 'pending',
455
+ embeddingModel: prev?.embeddingModel,
456
+ embeddingDimensions: prev?.embeddingDimensions,
454
457
  files: result?.fileIndex,
455
458
  workingTree: result?.workingTree,
459
+ chunkIdVersion: CHUNK_ID_VERSION,
456
460
  // Serializable form (WorkspaceMap holds Maps) — rehydrated when this
457
461
  // repo is later skipped, for cross-repo workspace-dep correlation.
458
462
  workspacePackages: workspaceMaps.get(repo.name)?.packages,
459
463
  });
460
464
  }
461
465
  }
466
+ for (const name of removedRepos) {
467
+ try {
468
+ await storage.blobs.deletePrefix(`${name}/`);
469
+ log(`Removed ${name} — no longer in the workspace`);
470
+ }
471
+ catch (e) {
472
+ log(`Warning: could not remove stored artifacts of ${name}: ${e}`);
473
+ }
474
+ }
462
475
  // Rolled-up stats: index_status / GET /status read ONE small blob instead
463
476
  // of walking every repo's index_meta (800 reads per call at org scale).
464
477
  try {
465
478
  await storage.blobs.putJson('index_stats.json', {
466
479
  repos: repoStats,
467
- totalChunks: dedupedChunkCount,
468
- totalTokens: dedupedTokenSum,
480
+ totalChunks: mergedChunkCount,
481
+ totalTokens: mergedTokenSum,
469
482
  crossRepoEdges: crossRepoEdgeCount,
470
483
  embeddingProvider: 'pending',
471
484
  lastIndexed: new Date().toISOString(),
@@ -475,12 +488,12 @@ export class KnowledgeIndexer {
475
488
  // Signal read replicas: chunks + graph + metas for this cycle are visible.
476
489
  await bumpIndexGeneration(storage.blobs);
477
490
  const durationMs = Date.now() - startTime;
478
- report({ phase: 'done', message: `KB built: ${dedupedChunkCount} chunks, ${crossRepoEdgeCount} edges in ${formatEta(Math.ceil(durationMs / 1000))}`, percent: 100, etaSeconds: 0, skippedRepos });
491
+ report({ phase: 'done', message: `KB built: ${mergedChunkCount} chunks, ${crossRepoEdgeCount} edges in ${formatEta(Math.ceil(durationMs / 1000))}`, percent: 100, etaSeconds: 0, skippedRepos });
479
492
  return {
480
493
  project,
481
494
  repos: repoStats,
482
- totalChunks: dedupedChunkCount,
483
- totalTokens: dedupedTokenSum,
495
+ totalChunks: mergedChunkCount,
496
+ totalTokens: mergedTokenSum,
484
497
  crossRepoEdges: crossRepoEdgeCount,
485
498
  durationMs,
486
499
  chunksPath,
@@ -504,14 +517,20 @@ export class KnowledgeIndexer {
504
517
  // drop it and rebuild from chunks.json rather than failing every reindex.
505
518
  const vectorStore = storage.vectors;
506
519
  await vectorStore.init({ healCorrupt: true });
507
- // Wipe the rows of changed/deleted files (listed by buildKB) BEFORE taking
508
- // the id snapshot below: chunk ids are hash(filePath, startLine, endLine),
509
- // so a changed file's unmoved chunks keep their ids — wiped after the
510
- // snapshot they would be skipped as "already embedded" and lost. Wiped
511
- // first, the file is re-embedded whole from chunks.json.
520
+ // Cross-repo edges are counted by buildKB (stats rollup), not here.
521
+ const crossRepoEdges = (await storage.blobs
522
+ .getJson('index_stats.json')
523
+ .catch(() => null))?.crossRepoEdges ?? 0;
524
+ // Rows of changed/deleted files (listed by buildKB) are stale. Chunk ids are
525
+ // hash(repoName, filePath, startLine, endLine), so a changed file's new
526
+ // chunks can take ids its old rows hold: note each stale row's
527
+ // (id, contentHash), treat those ids as not embedded in the diff below, and
528
+ // delete exactly those rows after the embed loop. Until then their vectors
529
+ // stay in the table for reuse by content. A stale row whose id and text
530
+ // both come back is simply kept.
512
531
  const deletedFiles = await this.getDeletedFiles(storage.blobs);
532
+ const staleRows = new Map(); // id → contentHashes
513
533
  if (deletedFiles.length > 0) {
514
- // Group by repo for efficient deletion (file path matching, not chunk ids)
515
534
  const byRepo = new Map();
516
535
  for (const d of deletedFiles) {
517
536
  const list = byRepo.get(d.repoName) ?? [];
@@ -519,8 +538,12 @@ export class KnowledgeIndexer {
519
538
  byRepo.set(d.repoName, list);
520
539
  }
521
540
  for (const [repoName, filePaths] of byRepo) {
522
- log(`Removing stale chunks for ${filePaths.length} changed/deleted files from ${repoName}...`);
523
- await vectorStore.deleteFileChunks(project, repoName, filePaths);
541
+ log(`Re-planning ${filePaths.length} changed/deleted files from ${repoName}...`);
542
+ for (const r of await vectorStore.getFileRowHashes(project, repoName, filePaths)) {
543
+ const hashes = staleRows.get(r.id) ?? new Set();
544
+ hashes.add(r.contentHash);
545
+ staleRows.set(r.id, hashes);
546
+ }
524
547
  }
525
548
  }
526
549
  // Which chunks are already embedded (id-set diff). Bounded: holds only the
@@ -535,6 +558,8 @@ export class KnowledgeIndexer {
535
558
  }
536
559
  }
537
560
  catch { /* first run — no existing data */ }
561
+ for (const id of staleRows.keys())
562
+ existingIds.delete(id);
538
563
  // Pass 1 — stream chunks.json to tally totals + how many need embedding,
539
564
  // WITHOUT ever holding all chunks in memory. At org scale (~810k chunks,
540
565
  // each carrying full source + contextualized text) the old
@@ -546,21 +571,67 @@ export class KnowledgeIndexer {
546
571
  let totalTokens = 0;
547
572
  let newChunkCount = 0;
548
573
  const repoChunkCounts = new Map();
574
+ const listedIds = new Set();
575
+ // A reservoir sample of named chunks: the source of the query-like probes
576
+ // that calibrate the vector index's nprobes (maintainVectorIndex).
577
+ const probeChunks = [];
578
+ let named = 0;
579
+ let seed = 0x2545f491;
580
+ const rand = () => (seed = (Math.imul(seed, 1664525) + 1013904223) >>> 0) / 2 ** 32;
549
581
  for await (const c of storage.blobs.iterateNdjson('chunks.json')) {
550
582
  totalChunks++;
551
583
  totalTokens += c.tokens;
552
584
  repoChunkCounts.set(c.repoName, (repoChunkCounts.get(c.repoName) ?? 0) + 1);
553
- if (!existingIds.has(c.id))
554
- newChunkCount++;
585
+ listedIds.add(c.id);
586
+ if (c.entityName && c.entityName.length >= 4) {
587
+ named++;
588
+ if (probeChunks.length < CALIBRATION_PROBES)
589
+ probeChunks.push(c);
590
+ else {
591
+ const j = Math.floor(rand() * named);
592
+ if (j < CALIBRATION_PROBES)
593
+ probeChunks[j] = c;
594
+ }
595
+ }
596
+ if (existingIds.has(c.id))
597
+ continue;
598
+ // Same id, same text as a stale row: keep that row as it is.
599
+ const stale = staleRows.get(c.id);
600
+ if (stale?.delete(contentHash(c.contextualizedContent))) {
601
+ existingIds.add(c.id);
602
+ continue;
603
+ }
604
+ newChunkCount++;
555
605
  }
556
606
  log(`Loaded ${totalChunks} chunks from ${chunksPath}`);
607
+ // chunks.json is the corpus: rows it no longer lists — a removed repo, a
608
+ // file deletion a fallback re-chunk caught, chunks from an older id scheme
609
+ // — are swept, after the embed loop so their vectors can be reused first
610
+ // (their ids can't collide with a listed chunk). An empty chunks.json is
611
+ // treated as a failed build, not as "delete everything".
612
+ const orphanIds = totalChunks > 0 ? [...existingIds].filter((id) => !listedIds.has(id)) : [];
613
+ const staleLeft = [...staleRows].flatMap(([id, hashes]) => [...hashes].map((h) => ({ id, contentHash: h })));
614
+ const sweep = async () => {
615
+ // A stale row whose id no listed chunk took can go by id (cheap IN-list
616
+ // deletes); only ids a new chunk now holds need the exact pair.
617
+ const takenIds = staleLeft.filter((r) => listedIds.has(r.id));
618
+ const byId = [...staleLeft.filter((r) => !listedIds.has(r.id)).map((r) => r.id), ...orphanIds];
619
+ if (staleLeft.length > 0)
620
+ log(`Removing ${staleLeft.length} stale rows of changed/deleted files...`);
621
+ if (orphanIds.length > 0)
622
+ log(`Removing ${orphanIds.length} rows no longer in ${chunksPath}...`);
623
+ await vectorStore.deleteRows(takenIds);
624
+ await vectorStore.deleteChunksByIds(byId);
625
+ };
557
626
  const repoNames = [...repoChunkCounts.keys()];
627
+ const probes = async () => probeChunks.length > 0 ? createEmbeddingProvider(config.embedding).embed(calibrationProbeTexts(probeChunks)) : [];
558
628
  if (newChunkCount === 0 && deletedFiles.length === 0) {
559
- // All vectors already present, so DON'T re-embed. But still (re)build the
560
- // full-text (BM25) index over the existing rows: a prior run that wrote
561
- // vectors then aborted before the post-loop FTS build (e.g. killed/aborted
562
- // mid-run) leaves BM25 permanently degraded, and this "nothing new" path is
563
- // the only one a re-run reaches. Cheap relative to embedding; idempotent.
629
+ await sweep();
630
+ // All vectors already present, so DON'T re-embed. But build the full-text
631
+ // (BM25) index if it is missing: a prior run that wrote vectors then
632
+ // aborted before the post-loop FTS build leaves none, and this "nothing
633
+ // new" path is the only one a re-run reaches. An existing index is kept;
634
+ // maintainVectorIndex's optimize() folds in rows it doesn't cover yet.
564
635
  log('All chunks already embedded — ensuring full-text index is built (no re-embed).');
565
636
  await vectorStore.ensureFtsIndex();
566
637
  // Heal missing scalar + vector indexes too (a prior run could have aborted
@@ -569,7 +640,7 @@ export class KnowledgeIndexer {
569
640
  // (build / due retrain / optimize — a prior run may also have died before
570
641
  // folding its appends in).
571
642
  await vectorStore.ensureScalarIndexes();
572
- const vectorIndex = await maintainVectorIndex(vectorStore, storage.blobs, { rowsWritten: 0 });
643
+ const vectorIndex = await maintainVectorIndex(vectorStore, storage.blobs, { rowsWritten: 0, probes });
573
644
  // optimize() prunes dataset versions past the retention window; readers
574
645
  // only reopen on a generation bump, so signal them or a reader pinned to
575
646
  // a pruned version would lose its files.
@@ -582,7 +653,7 @@ export class KnowledgeIndexer {
582
653
  totalTokens,
583
654
  embeddingProvider: 'cached',
584
655
  embeddingDimensions: 0,
585
- crossRepoEdges: 0,
656
+ crossRepoEdges,
586
657
  lastIndexed: new Date().toISOString(),
587
658
  indexDurationMs: Date.now() - startTime,
588
659
  ...(vectorIndex ? { vectorIndex } : {}),
@@ -605,23 +676,82 @@ export class KnowledgeIndexer {
605
676
  const batchSize = envInt('CODE_SEARCH_EMBEDDING_BATCH_SIZE', isOllama ? 10 : 128);
606
677
  const concurrency = isOllama ? 1 : envInt('CODE_SEARCH_EMBEDDING_CONCURRENCY', 8);
607
678
  log(`Embedding ${newChunkCount} new chunks with ${embedder.name} (${totalChunks - newChunkCount} cached, batch ${batchSize} × concurrency ${concurrency})...`);
679
+ // The contentHash index must exist before the reuse lookups below (an
680
+ // upgraded table gets the column and its index here, not after the loop).
681
+ await vectorStore.ensureScalarIndexes();
682
+ // Embedding reuse: a chunk whose exact text a row already holds takes that
683
+ // row's vector instead of a provider call. Only within one embedding space:
684
+ // the first batch with reusable vectors embeds one of those texts and
685
+ // compares (every batch waits on that one answer), so a provider / model /
686
+ // dimension change never reuses a vector.
687
+ let reused = 0;
688
+ let sameSpace;
689
+ const embedBatch = async (chunks) => {
690
+ const texts = chunks.map((c) => c.contextualizedContent);
691
+ const hashes = texts.map(contentHash);
692
+ const known = await vectorStore.getVectorsByContentHash([...new Set(hashes)]);
693
+ const vectors = hashes.map((h) => known.get(h));
694
+ let fromStore = vectors.filter(Boolean).length;
695
+ const hit = vectors.findIndex(Boolean);
696
+ if (hit >= 0) {
697
+ let probe;
698
+ const stored = vectors[hit];
699
+ sameSpace ??= embedder.embed([texts[hit]]).then(([v]) => {
700
+ probe = v;
701
+ return v.length === stored.length && cosineSimilarity(v, stored) > 0.99;
702
+ });
703
+ if (!(await sameSpace)) {
704
+ vectors.fill(undefined);
705
+ fromStore = 0;
706
+ }
707
+ if (probe) {
708
+ if (vectors[hit])
709
+ fromStore--;
710
+ vectors[hit] = probe;
711
+ }
712
+ }
713
+ const missing = vectors.flatMap((v, i) => (v ? [] : [i]));
714
+ if (missing.length > 0) {
715
+ const fresh = await embedder.embed(missing.map((i) => texts[i]));
716
+ missing.forEach((i, k) => { vectors[i] = fresh[k]; });
717
+ }
718
+ reused += fromStore;
719
+ return vectors;
720
+ };
608
721
  // Stream chunks.json a second time and embed only the new ones, in batches.
609
- // Up to `concurrency` batches are in flight at once; each is written to
610
- // LanceDB the instant its embeddings return (writes serialized via
611
- // writeChain — LanceDB's add must not run concurrently on one table).
612
- // Crucially we NEVER materialize the full chunk set nor a pre-sliced
613
- // `batches[][]`: the producer reads one chunk at a time, fills a batch,
614
- // dispatches it, then blocks until an in-flight slot frees. Memory stays
615
- // bounded to the id-set + ~concurrency batches regardless of corpus size.
616
- // The run stays resumable: new chunks are diffed against ids already in the
617
- // store, so a crash loses only the few in-flight batches and a re-run
618
- // continues from there. FTS is built once after the loop (skipIndex defers
619
- // the per-batch rebuild).
722
+ // Up to `concurrency` batches are in flight at once. Embedded rows go into
723
+ // a buffer that is appended to LanceDB once it holds WRITE_ROWS rows (and
724
+ // once more at the end): every append is a LanceDB commit — a new version
725
+ // plus a data file — so appending per embedding batch would make commits,
726
+ // files and version-cleanup work scale with chunks / batchSize. Appends are
727
+ // serialized via writeChain (LanceDB's add must not run concurrently on
728
+ // one table). Crucially we NEVER materialize the full chunk set nor a
729
+ // pre-sliced `batches[][]`: the producer reads one chunk at a time, fills a
730
+ // batch, dispatches it, then blocks until an in-flight slot frees. Memory
731
+ // stays bounded to the id-set + ~concurrency batches + one write buffer
732
+ // regardless of corpus size. The run stays resumable: new chunks are
733
+ // diffed against ids already in the store, so a crash loses at most the
734
+ // unwritten buffer and a re-run continues from there. FTS is checked once
735
+ // after the loop (skipIndex).
736
+ const WRITE_ROWS = 4096;
620
737
  const totalBatches = Math.max(1, Math.ceil(newChunkCount / batchSize));
621
738
  let batchesDone = 0;
739
+ let embedded = 0;
622
740
  let stored = 0;
623
741
  const embedStartTime = Date.now();
624
742
  let writeChain = Promise.resolve();
743
+ let pending = [];
744
+ // Append the buffered rows after any earlier append; resolves once written.
745
+ const flush = () => {
746
+ const rows = pending;
747
+ pending = [];
748
+ if (rows.length === 0)
749
+ return writeChain;
750
+ return (writeChain = writeChain.then(async () => {
751
+ await vectorStore.addChunks(rows, { skipIndex: true });
752
+ stored += rows.length;
753
+ }));
754
+ };
625
755
  // When any batch fails, signal the producer + siblings to stop and surface
626
756
  // the error after all in-flight batches settle — otherwise a failed batch
627
757
  // rejects while its siblings keep embedding + mutating progress in the
@@ -634,28 +764,28 @@ export class KnowledgeIndexer {
634
764
  if (aborted)
635
765
  return;
636
766
  try {
637
- const batchEmbeddings = await embedder.embed(batchChunks.map((c) => c.contextualizedContent));
638
- const batchRows = batchChunks.map((chunk, j) => ({ ...chunk, embedding: batchEmbeddings[j] }));
639
- // Serialize the LanceDB write by chaining onto the previous one, and
640
- // await only the promise we just appended.
641
- const myWrite = (writeChain = writeChain.then(() => vectorStore.addChunks(batchRows, { skipIndex: true })));
642
- await myWrite;
767
+ const batchEmbeddings = await embedBatch(batchChunks);
643
768
  if (aborted)
644
769
  return;
645
- stored += batchRows.length;
770
+ pending.push(...batchChunks.map((chunk, j) => ({ ...chunk, embedding: batchEmbeddings[j] })));
771
+ embedded += batchChunks.length;
646
772
  batchesDone++;
773
+ if (pending.length >= WRITE_ROWS)
774
+ await flush();
775
+ if (aborted)
776
+ return;
647
777
  const elapsed = Date.now() - embedStartTime;
648
778
  const msPerBatch = elapsed / batchesDone;
649
779
  const etaSeconds = Math.ceil((msPerBatch * (totalBatches - batchesDone)) / 1000);
650
780
  const percent = Math.round(5 + (batchesDone / totalBatches) * 85);
651
781
  report({
652
782
  phase: 'embedding',
653
- message: `Embedding: ${stored}/${newChunkCount} new (~${etaSeconds}s remaining)`,
783
+ message: `Embedding: ${embedded}/${newChunkCount} new (~${etaSeconds}s remaining)`,
654
784
  percent, etaSeconds,
655
- chunksTotal: newChunkCount, chunksProcessed: stored,
785
+ chunksTotal: newChunkCount, chunksProcessed: embedded,
656
786
  });
657
787
  if (batchesDone % 10 === 0 || batchesDone === totalBatches) {
658
- log(` Embedded ${stored}/${newChunkCount} (ETA: ${formatEta(etaSeconds)})`);
788
+ log(` Embedded ${embedded}/${newChunkCount} (ETA: ${formatEta(etaSeconds)})`);
659
789
  }
660
790
  }
661
791
  catch (err) {
@@ -683,9 +813,19 @@ export class KnowledgeIndexer {
683
813
  if (batch.length > 0 && !aborted)
684
814
  dispatch(batch);
685
815
  await Promise.all(inFlight);
816
+ if (!aborted) {
817
+ try {
818
+ await flush();
819
+ }
820
+ catch (err) {
821
+ aborted = err;
822
+ }
823
+ }
686
824
  if (aborted)
687
825
  throw aborted; // no zombies left running; fail the run cleanly
688
- // Build the full-text + scalar indexes once, after all batches are inserted.
826
+ await sweep();
827
+ // Build the full-text + scalar indexes if missing, after all batches are
828
+ // inserted; existing ones are kept and optimize() below folds the appends in.
689
829
  report({ phase: 'storing', message: 'Building search indexes...', percent: 92, etaSeconds: -1 });
690
830
  if (newChunkCount > 0) {
691
831
  await vectorStore.ensureFtsIndex();
@@ -699,8 +839,8 @@ export class KnowledgeIndexer {
699
839
  // last training reach the retrain ratio, and optimizes (folds this run's
700
840
  // appends into every index, compacts, prunes).
701
841
  await vectorStore.ensureScalarIndexes();
702
- const vectorIndex = await maintainVectorIndex(vectorStore, storage.blobs, { rowsWritten: stored });
703
- log(`Stored ${newChunkCount} new chunks in LanceDB (${deletedFiles.length} removed)`);
842
+ const vectorIndex = await maintainVectorIndex(vectorStore, storage.blobs, { rowsWritten: stored, probes });
843
+ log(`Stored ${newChunkCount} new chunks in LanceDB (${reused} reused by content, ${deletedFiles.length} files re-planned)`);
704
844
  // The stale-file list is applied — clear it, or a later no-change cycle
705
845
  // (buildKB returns early without rewriting it) would wipe those files again
706
846
  // with nothing left to re-embed them.
@@ -713,6 +853,8 @@ export class KnowledgeIndexer {
713
853
  const meta = await storage.blobs.getJson(metaKey);
714
854
  if (meta) {
715
855
  meta.embeddingProvider = embedder.name;
856
+ meta.embeddingModel = embedder.model;
857
+ meta.embeddingDimensions = embedder.dimensions;
716
858
  meta.lastIndexedAt = new Date().toISOString();
717
859
  await storage.blobs.putJson(metaKey, meta);
718
860
  }
@@ -742,7 +884,7 @@ export class KnowledgeIndexer {
742
884
  totalTokens,
743
885
  embeddingProvider: embedder.name,
744
886
  embeddingDimensions: embedder.dimensions,
745
- crossRepoEdges: 0,
887
+ crossRepoEdges,
746
888
  lastIndexed: new Date().toISOString(),
747
889
  indexDurationMs: durationMs,
748
890
  ...(vectorIndex ? { vectorIndex } : {}),
@@ -966,10 +1108,14 @@ const retrieverCache = new Map();
966
1108
  * invalidated that way, so it relies on this TTL check to notice the writer's
967
1109
  * reindex and rebuild. 0 disables. env: CODE_SEARCH_RETRIEVER_TTL_MS.
968
1110
  */
969
- const RETRIEVER_FRESHNESS_MS = Math.max(0, parseInt(process.env.CODE_SEARCH_RETRIEVER_TTL_MS ?? '', 10) || 30_000);
1111
+ export function retrieverFreshnessMs() {
1112
+ const ms = parseInt(process.env.CODE_SEARCH_RETRIEVER_TTL_MS ?? '', 10);
1113
+ return Number.isFinite(ms) && ms >= 0 ? ms : 30_000;
1114
+ }
1115
+ const RETRIEVER_FRESHNESS_MS = retrieverFreshnessMs();
970
1116
  function retrieverCacheKey(project, config) {
971
1117
  const e = config.embedding;
972
- return `${project}::${e.provider}:${e.model ?? ''}:${e.dimensions ?? ''}`;
1118
+ return `${project}::${e.provider}:${e.model ?? ''}:${e.dimensions ?? ''}::${JSON.stringify(config.retrieval)}`;
973
1119
  }
974
1120
  /** Cheap change-signal for a project's index. Primary: the `index_generation`
975
1121
  * blob the writer bumps after every cycle — works on EVERY backend (a Mongo
@@ -992,6 +1138,26 @@ async function indexFingerprint(basePath, blobs) {
992
1138
  } };
993
1139
  return `${mt(join(basePath, 'lancedb'))}:${mt(join(basePath, 'system_graph.sqlite'))}`;
994
1140
  }
1141
+ /** Chunks sampled per embed run for nprobes calibration probes. */
1142
+ const CALIBRATION_PROBES = 100;
1143
+ /** Query-like texts for nprobes calibration, from sampled chunks: the entity
1144
+ * name as typed (identifier queries), split into lowercase words, or the
1145
+ * first line of a comment in the chunk (natural-language queries). Short
1146
+ * texts like these embed away from code chunks, as real queries do. */
1147
+ function calibrationProbeTexts(chunks) {
1148
+ return chunks.map((c, i) => {
1149
+ const name = c.entityName;
1150
+ const words = splitIdentifiers(name).replace(/_/g, ' ').toLowerCase();
1151
+ if (i % 3 === 0)
1152
+ return name;
1153
+ if (i % 3 === 1)
1154
+ return words;
1155
+ const comment = c.content.split('\n')
1156
+ .map((l) => l.trim().match(/^(?:\/\/+|#+|\/\*+|\*+)\s*(.{12,})/)?.[1])
1157
+ .find(Boolean);
1158
+ return comment?.replace(/\*\/\s*$/, '').trim() || words;
1159
+ });
1160
+ }
995
1161
  /** Bump the change-signal read replicas poll on their freshness TTL. Written
996
1162
  * after every completed write phase (buildKB, embedChunks) — non-fatal, the
997
1163
  * in-process invalidate still covers the writer's own cache. */
@@ -1111,6 +1277,8 @@ async function buildRetriever(project, config) {
1111
1277
  // Load vector store
1112
1278
  const vectorStore = storage.vectors;
1113
1279
  await vectorStore.init();
1280
+ // The probe count the writer calibrated for this index (vector_index.json).
1281
+ vectorStore.setCalibratedNprobes((await readVectorIndexHealth(storage.blobs))?.nprobes);
1114
1282
  // Open the system-graph store for graph-augmented retrieval. It prefers
1115
1283
  // system_graph.sqlite (org scale, bounded slice queries) and falls back to
1116
1284
  // the legacy JSON for small/old indexes; null if neither exists → retrieval
@@ -1121,18 +1289,21 @@ async function buildRetriever(project, config) {
1121
1289
  // Create embedding provider for query-time embedding
1122
1290
  const embedder = createEmbeddingProvider(config.embedding);
1123
1291
  // Vector-space safety: refuse to run if the index was embedded with a
1124
- // different provider/dimension than what the current config resolves to.
1125
- // Garbage results from silent space mismatch are worse than a hard error.
1292
+ // different provider, model or dimension than the current config resolves
1293
+ // to. Garbage results from silent space mismatch are worse than a hard error.
1126
1294
  try {
1127
1295
  for (const entry of await listRepoNames(storage)) {
1128
1296
  const meta = await readRepoIndexMeta(basePath, entry, storage.blobs);
1129
- if (!meta || !meta.embeddingProvider || meta.embeddingProvider === 'pending')
1297
+ if (!meta)
1130
1298
  continue;
1131
- if (meta.embeddingProvider !== embedder.name) {
1299
+ const built = (meta.embeddingProvider && meta.embeddingProvider !== 'pending' && meta.embeddingProvider !== embedder.name && `provider "${meta.embeddingProvider}"`) ||
1300
+ (meta.embeddingModel !== undefined && embedder.model !== undefined && meta.embeddingModel !== embedder.model && `model "${meta.embeddingModel}"`) ||
1301
+ (meta.embeddingDimensions !== undefined && meta.embeddingDimensions !== embedder.dimensions && `${meta.embeddingDimensions} dimensions`);
1302
+ if (built) {
1132
1303
  throw new Error(`[knowledge-core] Vector-space mismatch for repo "${entry}": ` +
1133
- `index built with "${meta.embeddingProvider}" but retrieval is using "${embedder.name}". ` +
1134
- `Reindex with consistent embedding provider, or revert the config change. ` +
1135
- `(set CODE_SEARCH_EMBEDDING_PROVIDER or config.embedding.provider to match the index.)`);
1304
+ `index built with ${built} but retrieval is using "${embedder.name}" model "${embedder.model ?? ''}" (${embedder.dimensions} dimensions). ` +
1305
+ `Reindex with force, or revert the config change ` +
1306
+ `(CODE_SEARCH_EMBEDDING_PROVIDER / _MODEL / _DIMENSIONS or config.embedding).`);
1136
1307
  }
1137
1308
  }
1138
1309
  }