@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
@@ -15,7 +15,7 @@
15
15
  /** The two primitives the gate needs — structural, so it doesn't widen the
16
16
  * VectorStorePort (the exact/bypass baseline is LanceDB-specific). */
17
17
  export interface RecallProbe {
18
- vectorSearchIds(queryEmbedding: number[], k: number): Promise<string[]>;
18
+ vectorSearchIds(queryEmbedding: number[], k: number, nprobes?: number): Promise<string[]>;
19
19
  vectorSearchExactIds(queryEmbedding: number[], k: number): Promise<string[]>;
20
20
  }
21
21
  export interface RecallReport {
@@ -27,4 +27,16 @@ export interface RecallReport {
27
27
  /** Mean (and worst-case) recall@k of the approximate index vs the exact flat
28
28
  * baseline over `queries`. */
29
29
  export declare function measureRecallAtK(store: RecallProbe, queries: number[][], k: number): Promise<RecallReport>;
30
+ /** The fewest IVF probes whose mean recall@k over `queries` reaches `target`
31
+ * (recall rises with probes, so a binary search over 1..maxNprobes). The
32
+ * exact baseline is computed once per query. When even `maxNprobes` misses
33
+ * the target (quantization loss), returns `maxNprobes` with its recall. */
34
+ export declare function calibrateNprobes(store: RecallProbe, queries: number[][], opts: {
35
+ k: number;
36
+ target: number;
37
+ maxNprobes: number;
38
+ }): Promise<{
39
+ nprobes: number;
40
+ recall: number;
41
+ }>;
30
42
  //# sourceMappingURL=vector-recall.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"vector-recall.d.ts","sourceRoot":"","sources":["../src/vector-recall.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH;uEACuE;AACvE,MAAM,WAAW,WAAW;IAC1B,eAAe,CAAC,cAAc,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IACxE,oBAAoB,CAAC,cAAc,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;CAC9E;AAED,MAAM,WAAW,YAAY;IAC3B,CAAC,EAAE,MAAM,CAAC;IACV,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;+BAC+B;AAC/B,wBAAsB,gBAAgB,CACpC,KAAK,EAAE,WAAW,EAClB,OAAO,EAAE,MAAM,EAAE,EAAE,EACnB,CAAC,EAAE,MAAM,GACR,OAAO,CAAC,YAAY,CAAC,CAavB"}
1
+ {"version":3,"file":"vector-recall.d.ts","sourceRoot":"","sources":["../src/vector-recall.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH;uEACuE;AACvE,MAAM,WAAW,WAAW;IAC1B,eAAe,CAAC,cAAc,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;IAC1F,oBAAoB,CAAC,cAAc,EAAE,MAAM,EAAE,EAAE,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;CAC9E;AAED,MAAM,WAAW,YAAY;IAC3B,CAAC,EAAE,MAAM,CAAC;IACV,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED;+BAC+B;AAC/B,wBAAsB,gBAAgB,CACpC,KAAK,EAAE,WAAW,EAClB,OAAO,EAAE,MAAM,EAAE,EAAE,EACnB,CAAC,EAAE,MAAM,GACR,OAAO,CAAC,YAAY,CAAC,CAavB;AAED;;;4EAG4E;AAC5E,wBAAsB,gBAAgB,CACpC,KAAK,EAAE,WAAW,EAClB,OAAO,EAAE,MAAM,EAAE,EAAE,EACnB,IAAI,EAAE;IAAE,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,UAAU,EAAE,MAAM,CAAA;CAAE,GACtD,OAAO,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAA;CAAE,CAAC,CAqB9C"}
@@ -29,4 +29,37 @@ export async function measureRecallAtK(store, queries, k) {
29
29
  const n = queries.length;
30
30
  return { k, queries: n, meanRecall: n > 0 ? sum / n : 1, minRecall: n > 0 ? min : 1 };
31
31
  }
32
+ /** The fewest IVF probes whose mean recall@k over `queries` reaches `target`
33
+ * (recall rises with probes, so a binary search over 1..maxNprobes). The
34
+ * exact baseline is computed once per query. When even `maxNprobes` misses
35
+ * the target (quantization loss), returns `maxNprobes` with its recall. */
36
+ export async function calibrateNprobes(store, queries, opts) {
37
+ const exact = [];
38
+ for (const q of queries)
39
+ exact.push(await store.vectorSearchExactIds(q, opts.k));
40
+ const recallAt = async (nprobes) => {
41
+ let sum = 0;
42
+ for (let i = 0; i < queries.length; i++) {
43
+ const approx = new Set(await store.vectorSearchIds(queries[i], opts.k, nprobes));
44
+ sum += exact[i].length > 0 ? exact[i].filter((id) => approx.has(id)).length / exact[i].length : 1;
45
+ }
46
+ return queries.length > 0 ? sum / queries.length : 1;
47
+ };
48
+ let best = { nprobes: opts.maxNprobes, recall: await recallAt(opts.maxNprobes) };
49
+ if (best.recall < opts.target)
50
+ return best;
51
+ let lo = 1;
52
+ let hi = opts.maxNprobes;
53
+ while (lo < hi) {
54
+ const mid = Math.floor((lo + hi) / 2);
55
+ const recall = await recallAt(mid);
56
+ if (recall >= opts.target) {
57
+ hi = mid;
58
+ best = { nprobes: mid, recall };
59
+ }
60
+ else
61
+ lo = mid + 1;
62
+ }
63
+ return best;
64
+ }
32
65
  //# sourceMappingURL=vector-recall.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"vector-recall.js","sourceRoot":"","sources":["../src/vector-recall.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAgBH;+BAC+B;AAC/B,MAAM,CAAC,KAAK,UAAU,gBAAgB,CACpC,KAAkB,EAClB,OAAmB,EACnB,CAAS;IAET,IAAI,GAAG,GAAG,CAAC,CAAC;IACZ,IAAI,GAAG,GAAG,CAAC,CAAC;IACZ,KAAK,MAAM,CAAC,IAAI,OAAO,EAAE,CAAC;QACxB,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,MAAM,KAAK,CAAC,eAAe,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QAC1D,MAAM,KAAK,GAAG,MAAM,KAAK,CAAC,oBAAoB,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QACr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k, ScoredChunk } from '@esankhan3/anvil-knowledge-core';
2
2
  import type { VectorStorePort, IvfPqIndexConfig, VectorIndexBuildResult, VectorIndexState, VectorIndexType } from './storage/ports.js';
3
+ /** Insert a space at camelCase / PascalCase / acronym boundaries
4
+ * (`parseHTTPResponse` → `parse HTTP Response`) so identifier parts become
5
+ * BM25 terms. snake_case needs nothing: `_` already breaks tokens. */
6
+ export declare function splitIdentifiers(text: string): string;
7
+ /** The parts of a text's compound identifiers only (`return
8
+ * verifyExpectedBacklogCount(q)` → `verify Expected Backlog Count`). The
9
+ * contentSplit column holds this rather than the whole split text, so a
10
+ * plain word counts once — in contextualizedContent — not once per column. */
11
+ export declare function identifierParts(text: string): string;
12
+ /** SHA-256 (hex) of the text a chunk is embedded from — the key embedding
13
+ * reuse looks vectors up by. */
14
+ export declare function contentHash(contextualizedContent: string): string;
3
15
  export declare class VectorStore implements VectorStorePort {
4
16
  private db;
5
17
  private table;
@@ -8,6 +20,11 @@ export declare class VectorStore implements VectorStorePort {
8
20
  private cacheBudget?;
9
21
  private indexConfig?;
10
22
  private initialized;
23
+ private columnsEnsured;
24
+ private calibratedNprobes?;
25
+ /** Whether the table has the identifier-split FTS index (absent on tables
26
+ * no upgraded writer has touched yet); resolved on first search. */
27
+ private splitFts?;
11
28
  /** `dbPath` is a local directory (default) or an object-store URI
12
29
  * (`s3://bucket/prefix`). `storageOptions` carries the LanceDB/object_store
13
30
  * S3 connection knobs (endpoint, region, path-style, …) for MinIO; omit for
@@ -35,17 +52,26 @@ export declare class VectorStore implements VectorStorePort {
35
52
  init(opts?: {
36
53
  healCorrupt?: boolean;
37
54
  }): Promise<void>;
38
- /** Create or rebuild the full-text search index on contextualizedContent */
39
- /** (Re)build the full-text index. Public so a streamed batch insert can
40
- * defer it to a single call after the final batch instead of paying the
41
- * rebuild on every addChunks. */
55
+ /** Build each full-text index (FTS_INDEXES) that is missing or was built
56
+ * with an older config, after adding any derived column the table lacks.
57
+ * An existing current index is left alone: rows appended since are still
58
+ * searched (unindexed rows are scanned) and optimizeIndexes() folds them
59
+ * in, so a cycle's cost tracks what changed, not the corpus size. Write
60
+ * path only. */
42
61
  ensureFtsIndex(): Promise<void>;
62
+ /** Add the DERIVED_COLUMNS an older writer's table lacks, computed in SQL
63
+ * from existing columns — a column add writes only the new column's files,
64
+ * never rewrites rows. Must run before this writer's first add (rows carry
65
+ * every column), so addChunks / upsertChunks / ensureFtsIndex call it.
66
+ * Write path only. */
67
+ private ensureColumns;
43
68
  /** Build scalar indexes on every column that `.filter()` / `.where()` touches,
44
69
  * so graph-expansion + filtered search do indexed lookups instead of full
45
70
  * table scans — the dominant per-query cost at org scale (a 383k-row scan of
46
71
  * text-heavy rows, repeated per graph-expansion batch). `bitmap` for
47
72
  * low-cardinality equality columns (repoName, project), `btree` for
48
- * high-cardinality ones (filePath, entityName, id).
73
+ * high-cardinality ones (filePath, entityName, id, and contentHash for the
74
+ * writer's embedding-reuse lookups).
49
75
  *
50
76
  * Write path only; idempotent (build-if-absent — a new table, e.g. after a
51
77
  * corrupt-store heal, gets them on its first run; incremental adds are folded
@@ -102,16 +128,21 @@ export declare class VectorStore implements VectorStorePort {
102
128
  vectorSearch(queryEmbedding: number[], opts?: {
103
129
  limit?: number;
104
130
  filter?: string;
131
+ /** Probe count for this query only (calibration). */
132
+ nprobes?: number;
105
133
  }): Promise<ScoredChunk[]>;
106
134
  /** Approximate (IVF_PQ, index-backed) nearest-neighbor ids — applies the
107
135
  * configured nprobes/refineFactor via vectorSearch. Used by the recall gate. */
108
- vectorSearchIds(queryEmbedding: number[], k: number): Promise<string[]>;
136
+ vectorSearchIds(queryEmbedding: number[], k: number, nprobes?: number): Promise<string[]>;
109
137
  /** EXACT nearest-neighbor ids via `bypassVectorIndex()` — forces a flat scan
110
138
  * on the same table, ignoring the IVF_PQ index. This is the ground-truth
111
139
  * baseline the P1d recall gate compares the approximate search against. */
112
140
  vectorSearchExactIds(queryEmbedding: number[], k: number): Promise<string[]>;
113
141
  /** Full-text BM25 search (LanceDB built-in FTS) */
114
142
  fullTextSearch(queryText: string, limit?: number, filter?: string): Promise<ScoredChunk[]>;
143
+ /** Use the writer-calibrated probe count (vector_index.json) for queries. */
144
+ setCalibratedNprobes(nprobes: number | undefined): void;
145
+ private hasSplitFts;
115
146
  /** Exact-symbol lookup: chunks whose entityName equals one of `names`.
116
147
  * BTREE-indexed equality (see ensureScalarIndexes) — a definition becomes a
117
148
  * retrieval candidate even when vector and BM25 both rank it outside their
@@ -157,9 +188,24 @@ export declare class VectorStore implements VectorStorePort {
157
188
  hasData(): Promise<boolean>;
158
189
  /** Delete chunks for specific files within a repo (for incremental re-indexing) */
159
190
  deleteFileChunks(project: string, repoName: string, filePaths: string[]): Promise<void>;
191
+ /** (id, contentHash) of every row of the given files. Write path only. */
192
+ getFileRowHashes(project: string, repoName: string, filePaths: string[]): Promise<Array<{
193
+ id: string;
194
+ contentHash: string;
195
+ }>>;
196
+ /** A vector for each of `hashes` that some row's contentHash equals — the
197
+ * embedding of that exact text, for reuse instead of a provider call.
198
+ * BTREE-indexed (ensureScalarIndexes). Write path only. */
199
+ getVectorsByContentHash(hashes: string[]): Promise<Map<string, number[]>>;
200
+ /** Delete exactly these rows — each matched on id AND contentHash, so a new
201
+ * row that took over an id (chunk ids are position-keyed) survives. */
202
+ deleteRows(rows: Array<{
203
+ id: string;
204
+ contentHash: string;
205
+ }>): Promise<void>;
160
206
  /** Add chunks without deleting existing project data (for incremental updates).
161
- * Pass { skipIndex: true } to defer the FTS rebuild; the caller must then
162
- * call ensureFtsIndex() once after the final batch. */
207
+ * Pass { skipIndex: true } to skip the ensureFtsIndex() check; the caller
208
+ * must then call it once after the final batch. */
163
209
  addChunks(chunks: Array<CodeChunk & {
164
210
  embedding: number[];
165
211
  }>, opts?: {
@@ -1 +1 @@
1
- {"version":3,"file":"vector-store.d.ts","sourceRoot":"","sources":["../src/vector-store.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,SAAS,EAAE,WAAW,EAAE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C;QAAC,WAAW,EAAE,MAAM,CAAA;KAAE,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC;IAajF;;wDAEoD;IAC9C,SAAS,CAAC,MAAM,EAAE,KAAK,CAAC,SAAS,GAAG;QAAE,SAAS,EAAE,MAAM,EAAE,CAAA;KAAE,CAAC,EAAE,IAAI,CAAC,EAAE;QAAE,SAAS,CAAC,EAAE,OAAO,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;CAgCnH;AAED;wEACwE;AACxE,OAAO,EAAE,WAAW,IAAI,gBAAgB,EAAE,CAAC"}
@@ -1,4 +1,5 @@
1
1
  import { rmSync } from 'node:fs';
2
+ import { createHash } from 'node:crypto';
2
3
  /** A LanceDB store left 0-byte/truncated by a prior killed-mid-write (OOM /
3
4
  * SIGKILL / ENOSPC). Surfaces as a lance IO / "Invalid range" / generic
4
5
  * memory error on open or first read. Distinct from "table not found"
@@ -7,10 +8,57 @@ function isCorruptVectorStore(err) {
7
8
  const msg = err instanceof Error ? err.message : String(err);
8
9
  return /Invalid range|Generic memory error|LanceError\(IO\)|corrupt|unexpected end of file|failed to (read|open)/i.test(msg);
9
10
  }
10
- /** IVF partitions probed per vector query (recall/latency dial; env-tunable so
11
- * it can be adjusted on the VM without a redeploy). No effect until the IVF
12
- * index exists (ensureVectorIndex). */
13
- const VECTOR_NPROBES = Math.max(1, parseInt(process.env.CODE_SEARCH_VECTOR_NPROBES ?? '', 10) || 40);
11
+ /** IVF partitions probed per vector query. The writer calibrates it per index
12
+ * (vector_index.json: the fewest probes reaching the target recall on
13
+ * query-like probes) and readers apply it via setCalibratedNprobes.
14
+ * CODE_SEARCH_VECTOR_NPROBES overrides it — e.g. to trade recall for latency
15
+ * on a VM without a redeploy; DEFAULT_NPROBES applies when there is neither.
16
+ * No effect until the IVF index exists (ensureVectorIndex). */
17
+ const ENV_NPROBES = parseInt(process.env.CODE_SEARCH_VECTOR_NPROBES ?? '', 10) > 0
18
+ ? parseInt(process.env.CODE_SEARCH_VECTOR_NPROBES ?? '', 10)
19
+ : undefined;
20
+ const DEFAULT_NPROBES = 40;
21
+ /** Insert a space at camelCase / PascalCase / acronym boundaries
22
+ * (`parseHTTPResponse` → `parse HTTP Response`) so identifier parts become
23
+ * BM25 terms. snake_case needs nothing: `_` already breaks tokens. */
24
+ export function splitIdentifiers(text) {
25
+ return text.replace(/([a-z0-9])([A-Z])/g, '$1 $2').replace(/([A-Z]+)([A-Z][a-z])/g, '$1 $2');
26
+ }
27
+ /** Words with no case boundary inside: lowercase, ALL_CAPS, Capitalized. */
28
+ const PLAIN_WORD = /\b(?:[a-z0-9_]+|[A-Z0-9_]+|[A-Z][a-z0-9_]+)\b/g;
29
+ /** The parts of a text's compound identifiers only (`return
30
+ * verifyExpectedBacklogCount(q)` → `verify Expected Backlog Count`). The
31
+ * contentSplit column holds this rather than the whole split text, so a
32
+ * plain word counts once — in contextualizedContent — not once per column. */
33
+ export function identifierParts(text) {
34
+ return splitIdentifiers(text.replace(PLAIN_WORD, ' ').replace(/[^A-Za-z0-9_]+/g, ' '));
35
+ }
36
+ /** SHA-256 (hex) of the text a chunk is embedded from — the key embedding
37
+ * reuse looks vectors up by. */
38
+ export function contentHash(contextualizedContent) {
39
+ return createHash('sha256').update(contextualizedContent).digest('hex');
40
+ }
41
+ /** Columns derived from others, with the SQL that fills them in for rows
42
+ * written before the column existed (ensureColumns). Each SQL must match the
43
+ * JS that addChunks uses for new rows (`(?-u:\b)` = JS's ASCII `\b`). */
44
+ const DERIVED_COLUMNS = [
45
+ { name: 'contentHash', valueSql: "encode(sha256(contextualizedContent), 'hex')" },
46
+ {
47
+ name: 'contentSplit',
48
+ valueSql: "regexp_replace(regexp_replace(regexp_replace(regexp_replace(contextualizedContent, " +
49
+ "'(?-u:\\b)(?:[a-z0-9_]+|[A-Z0-9_]+|[A-Z][a-z0-9_]+)(?-u:\\b)', ' ', 'g'), '[^A-Za-z0-9_]+', ' ', 'g'), " +
50
+ "'([a-z0-9])([A-Z])', '${1} ${2}', 'g'), '([A-Z]+)([A-Z][a-z])', '${1} ${2}', 'g')",
51
+ },
52
+ ];
53
+ /** Full-text indexes. Each name stands for its config in ensureFtsIndex:
54
+ * change a config → change its name, and the next write cycle builds the new
55
+ * index and drops the old one. */
56
+ const FTS_INDEXES = [
57
+ // Positions enable PhraseQuery (multi-token literal matching).
58
+ { column: 'contextualizedContent', name: 'contextualizedContent_idx', withPosition: true },
59
+ // Compound-identifier parts for term search; phrases stay on the original column.
60
+ { column: 'contentSplit', name: 'contentSplit_idx', withPosition: false },
61
+ ];
14
62
  export class VectorStore {
15
63
  db; // lancedb.Connection
16
64
  table; // lancedb.Table
@@ -19,6 +67,11 @@ export class VectorStore {
19
67
  cacheBudget;
20
68
  indexConfig;
21
69
  initialized = false;
70
+ columnsEnsured = false;
71
+ calibratedNprobes;
72
+ /** Whether the table has the identifier-split FTS index (absent on tables
73
+ * no upgraded writer has touched yet); resolved on first search. */
74
+ splitFts;
22
75
  /** `dbPath` is a local directory (default) or an object-store URI
23
76
  * (`s3://bucket/prefix`). `storageOptions` carries the LanceDB/object_store
24
77
  * S3 connection knobs (endpoint, region, path-style, …) for MinIO; omit for
@@ -101,36 +154,63 @@ export class VectorStore {
101
154
  }
102
155
  this.initialized = true;
103
156
  }
104
- /** Create or rebuild the full-text search index on contextualizedContent */
105
- /** (Re)build the full-text index. Public so a streamed batch insert can
106
- * defer it to a single call after the final batch instead of paying the
107
- * rebuild on every addChunks. */
157
+ /** Build each full-text index (FTS_INDEXES) that is missing or was built
158
+ * with an older config, after adding any derived column the table lacks.
159
+ * An existing current index is left alone: rows appended since are still
160
+ * searched (unindexed rows are scanned) and optimizeIndexes() folds them
161
+ * in, so a cycle's cost tracks what changed, not the corpus size. Write
162
+ * path only. */
108
163
  async ensureFtsIndex() {
109
164
  if (!this.table)
110
165
  return;
111
- try {
112
- const lancedb = await import('@lancedb/lancedb');
113
- // withPosition: term positions enable PhraseQuery (multi-token literal
114
- // matching). removeStopWords: the default drops 'to'/'if'/'in' etc.,
115
- // which silently breaks phrases containing them — and stop words are
116
- // meaningful tokens in code and error strings. The index is rebuilt
117
- // every embed cycle, so this takes effect at the next reindex without
118
- // a migration.
119
- await this.table.createIndex('contextualizedContent', {
120
- config: lancedb.Index.fts({ withPosition: true, removeStopWords: false }),
121
- replace: true,
122
- });
123
- }
124
- catch {
125
- // Index creation can fail on empty tables or unsupported configs — non-fatal
166
+ await this.ensureColumns();
167
+ const lancedb = await import('@lancedb/lancedb');
168
+ for (const spec of FTS_INDEXES) {
169
+ try {
170
+ const indexes = await this.table.listIndices();
171
+ const fts = indexes.filter((i) => i.indexType === 'FTS' && i.columns.includes(spec.column));
172
+ if (fts.some((i) => i.name === spec.name))
173
+ continue;
174
+ // removeStopWords: the default drops 'to'/'if'/'in' etc., which
175
+ // silently breaks phrases containing them — and stop words are
176
+ // meaningful tokens in code and error strings.
177
+ await this.table.createIndex(spec.column, {
178
+ config: lancedb.Index.fts({ withPosition: spec.withPosition, removeStopWords: false }),
179
+ name: spec.name,
180
+ replace: true,
181
+ });
182
+ // Indexes built under another name carry an older config. Drop them
183
+ // only after the current one exists, so search never lacks an index.
184
+ for (const old of fts)
185
+ await this.table.dropIndex(old.name);
186
+ }
187
+ catch {
188
+ // Index creation can fail on empty tables or unsupported configs — non-fatal
189
+ }
126
190
  }
127
191
  }
192
+ /** Add the DERIVED_COLUMNS an older writer's table lacks, computed in SQL
193
+ * from existing columns — a column add writes only the new column's files,
194
+ * never rewrites rows. Must run before this writer's first add (rows carry
195
+ * every column), so addChunks / upsertChunks / ensureFtsIndex call it.
196
+ * Write path only. */
197
+ async ensureColumns() {
198
+ if (!this.table || this.columnsEnsured)
199
+ return;
200
+ const schema = await this.table.schema();
201
+ const have = new Set(schema.fields.map((f) => f.name));
202
+ const missing = DERIVED_COLUMNS.filter((c) => !have.has(c.name));
203
+ if (missing.length > 0)
204
+ await this.table.addColumns(missing);
205
+ this.columnsEnsured = true;
206
+ }
128
207
  /** Build scalar indexes on every column that `.filter()` / `.where()` touches,
129
208
  * so graph-expansion + filtered search do indexed lookups instead of full
130
209
  * table scans — the dominant per-query cost at org scale (a 383k-row scan of
131
210
  * text-heavy rows, repeated per graph-expansion batch). `bitmap` for
132
211
  * low-cardinality equality columns (repoName, project), `btree` for
133
- * high-cardinality ones (filePath, entityName, id).
212
+ * high-cardinality ones (filePath, entityName, id, and contentHash for the
213
+ * writer's embedding-reuse lookups).
134
214
  *
135
215
  * Write path only; idempotent (build-if-absent — a new table, e.g. after a
136
216
  * corrupt-store heal, gets them on its first run; incremental adds are folded
@@ -146,8 +226,10 @@ export class VectorStore {
146
226
  { col: 'filePath', kind: 'btree' },
147
227
  { col: 'entityName', kind: 'btree' },
148
228
  { col: 'id', kind: 'btree' },
229
+ { col: 'contentHash', kind: 'btree' },
149
230
  ];
150
231
  try {
232
+ await this.ensureColumns();
151
233
  const existing = await this.table.listIndices();
152
234
  const indexed = new Set(existing.flatMap((i) => i.columns ?? []));
153
235
  const lancedb = await import('@lancedb/lancedb');
@@ -294,6 +376,8 @@ export class VectorStore {
294
376
  vector: c.embedding, // LanceDB uses 'vector' field for embeddings
295
377
  content: c.content,
296
378
  contextualizedContent: c.contextualizedContent,
379
+ contentSplit: identifierParts(c.contextualizedContent),
380
+ contentHash: contentHash(c.contextualizedContent),
297
381
  contextPrefix: c.contextPrefix,
298
382
  filePath: c.filePath,
299
383
  repoName: c.repoName,
@@ -310,20 +394,11 @@ export class VectorStore {
310
394
  this.table = await this.db.createTable('chunks', rows, { mode: 'overwrite' });
311
395
  }
312
396
  else {
313
- // Delete existing chunks for the same project, then add new ones
314
- // This handles re-indexing
315
- const project = chunks[0]?.project;
316
- if (project) {
317
- try {
318
- await this.table.delete(`project = '${project.replace(/'/g, "''")}'`);
319
- }
320
- catch {
321
- /* ok if empty */
322
- }
323
- }
397
+ await this.ensureColumns();
398
+ // Replace rows with the given ids, keep everything else.
399
+ await this.deleteChunksByIds(rows.map((r) => r.id));
324
400
  await this.table.add(rows);
325
401
  }
326
- // Rebuild FTS index after data changes
327
402
  await this.ensureFtsIndex();
328
403
  }
329
404
  /** Semantic vector search */
@@ -331,14 +406,15 @@ export class VectorStore {
331
406
  if (!this.table)
332
407
  return [];
333
408
  // nprobes = IVF partitions scanned per query (no-op on a flat/un-indexed
334
- // table). Higher = better recall, more work. `indexConfig` (IVF_PQ / S3
335
- // deployments) wins when set; otherwise the env-tunable VECTOR_NPROBES.
409
+ // table). Higher = better recall, more work. Precedence: this call's
410
+ // value, `indexConfig` (IVF_PQ / S3 deployments), the env override, the
411
+ // writer-calibrated value, the default.
336
412
  // refineFactor (IVF_PQ only) re-ranks the top nprobes·refine candidates
337
413
  // with exact distance against the retained raw vectors (ADR §5.5).
338
414
  let query = this.table
339
415
  .search(queryEmbedding)
340
416
  .limit(opts?.limit ?? 20)
341
- .nprobes(this.indexConfig?.nprobes ?? VECTOR_NPROBES);
417
+ .nprobes(opts?.nprobes ?? this.indexConfig?.nprobes ?? ENV_NPROBES ?? this.calibratedNprobes ?? DEFAULT_NPROBES);
342
418
  if (this.indexConfig?.refineFactor)
343
419
  query = query.refineFactor(this.indexConfig.refineFactor);
344
420
  if (opts?.filter)
@@ -352,8 +428,8 @@ export class VectorStore {
352
428
  }
353
429
  /** Approximate (IVF_PQ, index-backed) nearest-neighbor ids — applies the
354
430
  * configured nprobes/refineFactor via vectorSearch. Used by the recall gate. */
355
- async vectorSearchIds(queryEmbedding, k) {
356
- const results = await this.vectorSearch(queryEmbedding, { limit: k });
431
+ async vectorSearchIds(queryEmbedding, k, nprobes) {
432
+ const results = await this.vectorSearch(queryEmbedding, { limit: k, nprobes });
357
433
  return results.map((s) => s.chunk.id);
358
434
  }
359
435
  /** EXACT nearest-neighbor ids via `bypassVectorIndex()` — forces a flat scan
@@ -370,7 +446,26 @@ export class VectorStore {
370
446
  if (!this.table)
371
447
  return [];
372
448
  try {
373
- let q = this.table.search(queryText, 'fts', 'contextualizedContent').limit(limit);
449
+ let q;
450
+ // Words containing '_' are already split into terms on the original
451
+ // column; sending them to the split column too would count them again
452
+ // for camelCase spellings of the same words (TRIGGER_TO_WEB_TYPE vs
453
+ // triggerToWebType) and outrank the definition.
454
+ const splitQuery = splitIdentifiers(queryText.replace(/[A-Za-z0-9]*_[A-Za-z0-9_]*/g, ' '));
455
+ if (/[A-Za-z0-9]/.test(splitQuery) && (await this.hasSplitFts())) {
456
+ // Original tokens on the original column, identifier parts on the
457
+ // split column; a row's score is the sum. An exact identifier keeps
458
+ // its rare full token, and "expected backlog count" also reaches
459
+ // `verifyExpectedBacklogCount`.
460
+ const { BooleanQuery, MatchQuery, Occur } = await import('@lancedb/lancedb');
461
+ q = this.table.query().fullTextSearch(new BooleanQuery([
462
+ [Occur.Should, new MatchQuery(queryText, 'contextualizedContent')],
463
+ [Occur.Should, new MatchQuery(splitQuery, 'contentSplit')],
464
+ ])).limit(limit);
465
+ }
466
+ else {
467
+ q = this.table.search(queryText, 'fts', 'contextualizedContent').limit(limit);
468
+ }
374
469
  // Apply the same repo filter as vectorSearch — without it, BM25 results
375
470
  // leak across repos even when the caller scoped to specific repos.
376
471
  if (filter)
@@ -390,6 +485,17 @@ export class VectorStore {
390
485
  return [];
391
486
  }
392
487
  }
488
+ /** Use the writer-calibrated probe count (vector_index.json) for queries. */
489
+ setCalibratedNprobes(nprobes) {
490
+ this.calibratedNprobes = nprobes && nprobes > 0 ? nprobes : undefined;
491
+ }
492
+ hasSplitFts() {
493
+ this.splitFts ??= (async () => {
494
+ const indexes = await this.table.listIndices();
495
+ return indexes.some((i) => i.name === 'contentSplit_idx');
496
+ })().catch(() => false);
497
+ return this.splitFts;
498
+ }
393
499
  /** Exact-symbol lookup: chunks whose entityName equals one of `names`.
394
500
  * BTREE-indexed equality (see ensureScalarIndexes) — a definition becomes a
395
501
  * retrieval candidate even when vector and BM25 both rank it outside their
@@ -500,9 +606,14 @@ export class VectorStore {
500
606
  const esc = (s) => s.replace(/'/g, "''");
501
607
  const conditions = lookups.map((l) => {
502
608
  const base = `repoName = '${esc(l.repoName)}' AND filePath = '${esc(l.filePath)}'`;
503
- return l.entityName
504
- ? `(${base} AND entityName = '${esc(l.entityName)}')`
505
- : `(${base})`;
609
+ if (!l.entityName)
610
+ return `(${base})`;
611
+ // `Class.member` (graph node ids) → that class's member chunk.
612
+ const dot = l.entityName.lastIndexOf('.');
613
+ const member = dot > 0
614
+ ? ` OR (entityName = '${esc(l.entityName.slice(dot + 1))}' AND parentEntity = '${esc(l.entityName.slice(0, dot))}')`
615
+ : '';
616
+ return `(${base} AND (entityName = '${esc(l.entityName)}'${member}))`;
506
617
  });
507
618
  try {
508
619
  // Split into batches (avoid overly long filter strings) and run them
@@ -555,11 +666,13 @@ export class VectorStore {
555
666
  async deleteChunksByIds(ids) {
556
667
  if (!this.table || ids.length === 0)
557
668
  return;
558
- // Batch deletes to avoid overly long filter strings
559
- const batchSize = 50;
669
+ // Batched IN-lists: each delete is one table commit, so the batch bounds
670
+ // both the filter length and the commit count (a full id sweep can be
671
+ // hundreds of thousands of ids).
672
+ const batchSize = 1000;
560
673
  for (let i = 0; i < ids.length; i += batchSize) {
561
674
  const batch = ids.slice(i, i + batchSize);
562
- const filter = batch.map((id) => `id = '${id.replace(/'/g, "''")}'`).join(' OR ');
675
+ const filter = `id IN (${batch.map((id) => `'${id.replace(/'/g, "''")}'`).join(', ')})`;
563
676
  try {
564
677
  await this.table.delete(filter);
565
678
  }
@@ -604,19 +717,65 @@ export class VectorStore {
604
717
  async deleteFileChunks(project, repoName, filePaths) {
605
718
  if (!this.table || filePaths.length === 0)
606
719
  return;
607
- const escapedProject = project.replace(/'/g, "''");
608
- const escapedRepo = repoName.replace(/'/g, "''");
609
- const fileFilter = filePaths.map((f) => `'${f.replace(/'/g, "''")}'`).join(', ');
610
720
  try {
611
- await this.table.delete(`project = '${escapedProject}' AND repoName = '${escapedRepo}' AND filePath IN (${fileFilter})`);
721
+ await this.table.delete(fileRowsFilter(project, repoName, filePaths));
612
722
  }
613
723
  catch {
614
724
  /* ok if empty */
615
725
  }
616
726
  }
727
+ /** (id, contentHash) of every row of the given files. Write path only. */
728
+ async getFileRowHashes(project, repoName, filePaths) {
729
+ if (!this.table || filePaths.length === 0)
730
+ return [];
731
+ await this.ensureColumns();
732
+ const rows = await this.table.query()
733
+ .where(fileRowsFilter(project, repoName, filePaths))
734
+ .select(['id', 'contentHash'])
735
+ .toArray();
736
+ return rows.map((r) => ({ id: r.id, contentHash: r.contentHash }));
737
+ }
738
+ /** A vector for each of `hashes` that some row's contentHash equals — the
739
+ * embedding of that exact text, for reuse instead of a provider call.
740
+ * BTREE-indexed (ensureScalarIndexes). Write path only. */
741
+ async getVectorsByContentHash(hashes) {
742
+ const found = new Map();
743
+ if (!this.table || hashes.length === 0)
744
+ return found;
745
+ await this.ensureColumns();
746
+ const batchSize = 1000;
747
+ for (let i = 0; i < hashes.length; i += batchSize) {
748
+ const batch = hashes.slice(i, i + batchSize).filter((h) => /^[0-9a-f]{64}$/.test(h));
749
+ if (batch.length === 0)
750
+ continue;
751
+ const rows = await this.table.query()
752
+ .where(`contentHash IN (${batch.map((h) => `'${h}'`).join(', ')})`)
753
+ .select(['contentHash', 'vector'])
754
+ .toArray();
755
+ for (const r of rows)
756
+ if (!found.has(r.contentHash))
757
+ found.set(r.contentHash, Array.from(r.vector));
758
+ }
759
+ return found;
760
+ }
761
+ /** Delete exactly these rows — each matched on id AND contentHash, so a new
762
+ * row that took over an id (chunk ids are position-keyed) survives. */
763
+ async deleteRows(rows) {
764
+ if (!this.table || rows.length === 0)
765
+ return;
766
+ const esc = (s) => s.replace(/'/g, "''");
767
+ // Each pair is two conditions; Lance rejects a filter with more than 500.
768
+ const batchSize = 200;
769
+ for (let i = 0; i < rows.length; i += batchSize) {
770
+ const filter = rows.slice(i, i + batchSize)
771
+ .map((r) => `(id = '${esc(r.id)}' AND contentHash = '${esc(r.contentHash)}')`)
772
+ .join(' OR ');
773
+ await this.table.delete(filter);
774
+ }
775
+ }
617
776
  /** Add chunks without deleting existing project data (for incremental updates).
618
- * Pass { skipIndex: true } to defer the FTS rebuild; the caller must then
619
- * call ensureFtsIndex() once after the final batch. */
777
+ * Pass { skipIndex: true } to skip the ensureFtsIndex() check; the caller
778
+ * must then call it once after the final batch. */
620
779
  async addChunks(chunks, opts) {
621
780
  if (chunks.length === 0)
622
781
  return;
@@ -625,6 +784,8 @@ export class VectorStore {
625
784
  vector: c.embedding,
626
785
  content: c.content,
627
786
  contextualizedContent: c.contextualizedContent,
787
+ contentSplit: identifierParts(c.contextualizedContent),
788
+ contentHash: contentHash(c.contextualizedContent),
628
789
  contextPrefix: c.contextPrefix,
629
790
  filePath: c.filePath,
630
791
  repoName: c.repoName,
@@ -641,10 +802,9 @@ export class VectorStore {
641
802
  this.table = await this.db.createTable('chunks', rows, { mode: 'overwrite' });
642
803
  }
643
804
  else {
805
+ await this.ensureColumns();
644
806
  await this.table.add(rows);
645
807
  }
646
- // Rebuild FTS index after data changes — unless the caller is streaming
647
- // batches and will call ensureFtsIndex() once at the end.
648
808
  if (!opts?.skipIndex) {
649
809
  await this.ensureFtsIndex();
650
810
  }
@@ -653,6 +813,12 @@ export class VectorStore {
653
813
  /** ADR §3 canonical name for the default LanceDB-backed `VectorStorePort`
654
814
  * adapter. Alias for now; a later phase renames the class outright. */
655
815
  export { VectorStore as LanceVectorStore };
816
+ /** Predicate for every row of the given files of one repo. */
817
+ function fileRowsFilter(project, repoName, filePaths) {
818
+ const esc = (s) => s.replace(/'/g, "''");
819
+ const files = filePaths.map((f) => `'${esc(f)}'`).join(', ');
820
+ return `project = '${esc(project)}' AND repoName = '${esc(repoName)}' AND filePath IN (${files})`;
821
+ }
656
822
  function rowToChunk(row) {
657
823
  return {
658
824
  id: row.id,