graph-indexer 1.1.0 → 2.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 (59) hide show
  1. package/CHANGELOG.md +412 -0
  2. package/README.md +228 -350
  3. package/SECURITY.md +68 -0
  4. package/TRADEMARK.md +31 -0
  5. package/cli-ui.mjs +78 -0
  6. package/config.mjs +269 -0
  7. package/daemon-ctl.mjs +175 -0
  8. package/daemon-lock.mjs +69 -0
  9. package/embedders/python/mlx_embed_server.py +61 -0
  10. package/embedders/python/requirements-mlx.txt +5 -0
  11. package/embedders/setup-mlx.mjs +110 -0
  12. package/embeddings.mjs +489 -0
  13. package/engine/binary.mjs +399 -0
  14. package/{core-engine.mjs → engine/memory.mjs} +359 -249
  15. package/engine/sqlite.mjs +863 -0
  16. package/enrichment.mjs +426 -0
  17. package/git-signals.mjs +248 -0
  18. package/indexer.mjs +216 -77
  19. package/init.mjs +1604 -170
  20. package/layout.mjs +123 -0
  21. package/mcp/format.mjs +61 -0
  22. package/mcp/tools.mjs +1157 -0
  23. package/mcp/topology.mjs +551 -0
  24. package/mcp-server.mjs +118 -573
  25. package/package.json +56 -16
  26. package/parse/extractor.mjs +617 -0
  27. package/parse/imports.mjs +365 -0
  28. package/parse/languages.mjs +89 -0
  29. package/parse/metadata.mjs +655 -0
  30. package/parse/routes.mjs +327 -0
  31. package/prompts/CORE.md +86 -0
  32. package/prompts/DOMAIN_TEMPLATE.md +46 -0
  33. package/prompts/INTEGRATION.md +123 -0
  34. package/prompts/frameworks/ANDROID.md +17 -0
  35. package/prompts/frameworks/ASPNET_CORE.md +19 -0
  36. package/prompts/frameworks/FASTAPI_DJANGO.md +19 -0
  37. package/prompts/frameworks/LARAVEL_SYMFONY.md +22 -0
  38. package/prompts/frameworks/NODE_EXPRESS_NESTJS.md +18 -0
  39. package/prompts/frameworks/RAILS.md +20 -0
  40. package/prompts/frameworks/REACT.md +20 -0
  41. package/prompts/frameworks/SPRING_BOOT.md +19 -0
  42. package/prompts/languages/BASH.md +22 -0
  43. package/prompts/languages/C.md +21 -0
  44. package/prompts/languages/CSHARP.md +24 -0
  45. package/prompts/languages/CSS_SCSS.md +22 -0
  46. package/prompts/languages/GO.md +23 -0
  47. package/prompts/languages/JAVA.md +23 -0
  48. package/prompts/languages/JAVASCRIPT_TYPESCRIPT.md +24 -0
  49. package/prompts/languages/KOTLIN.md +24 -0
  50. package/prompts/languages/PHP.md +23 -0
  51. package/prompts/languages/PYTHON.md +23 -0
  52. package/prompts/languages/RUBY.md +23 -0
  53. package/prompts/languages/RUST.md +21 -0
  54. package/prompts/languages/SWIFT.md +21 -0
  55. package/search-core.mjs +627 -0
  56. package/storage.mjs +68 -0
  57. package/watch-daemon.mjs +204 -69
  58. package/PROMPT.md +0 -143
  59. package/parser-utils.mjs +0 -861
@@ -0,0 +1,627 @@
1
+ /**
2
+ * @file search-core.mjs
3
+ * @description Storage-agnostic retrieval primitives shared by every backend:
4
+ * tokenisation, cosine similarity, BM25 scoring, the RRF fusion +
5
+ * boost ladder, and PageRank centrality. Keeping this math in one
6
+ * place is what lets the in-memory engine and the SQLite store
7
+ * return identical rankings — the numbers are measured once and
8
+ * reused, never re-derived per backend.
9
+ * @author MaquinaTech <https://github.com/MaquinaTech>
10
+ * @copyright (c) 2026 MaquinaTech. All rights reserved.
11
+ * @license MIT
12
+ */
13
+
14
+ import { createHash } from 'crypto';
15
+
16
+ // Max embedding-input length in chars. ~8000 chars ≈ the usable context of the
17
+ // default embedders (nomic-embed-text / MiniLM) once a query/document prefix is
18
+ // added; longer inputs are silently truncated by the backend, so this is also the
19
+ // per-window size for oversized definitions (see embeddingWindows).
20
+ export const EMBEDDING_CONTEXT_LIMIT = 8000;
21
+
22
+ /**
23
+ * Cache key for a chunk's embedding vector.
24
+ *
25
+ * The embedding payload includes the LLM enrichment summary when present, so a
26
+ * vector computed for an enriched chunk is NOT interchangeable with one computed
27
+ * for the same code without enrichment. Keying by content_hash alone caused two
28
+ * defects: enriched chunks were re-embedded on every index run (cache never hit),
29
+ * and a stale un-enriched vector could be silently reused for an enriched chunk.
30
+ *
31
+ * The key is content_hash for plain chunks, and content_hash + a digest of the
32
+ * enrichment text for enriched ones — deterministic as long as the enrichment
33
+ * cache returns the same summary for the same code.
34
+ *
35
+ * @param {object} chunk
36
+ * @returns {string}
37
+ */
38
+ export function embeddingKeyFor(chunk) {
39
+ const hasEnrichment = Boolean(chunk.summary) || (chunk.concepts?.length > 0);
40
+ if (!hasEnrichment) return chunk.content_hash;
41
+ const enrichText = `${chunk.summary || ''}|${(chunk.concepts || []).join(',')}`;
42
+ const suffix = createHash('sha256').update(enrichText).digest('hex').slice(0, 12);
43
+ return `${chunk.content_hash}|e:${suffix}`;
44
+ }
45
+
46
+ export function truncateForEmbedding(text) {
47
+ return text.length > EMBEDDING_CONTEXT_LIMIT ? text.slice(0, EMBEDDING_CONTEXT_LIMIT) : text;
48
+ }
49
+
50
+ // Window-and-pool sub-chunking for the dense channel. A large definition (e.g. a
51
+ // ~600-line free function) used to be embedded as a single vector over only its
52
+ // first EMBEDDING_CONTEXT_LIMIT chars — its tail was invisible to semantic search
53
+ // (BM25 still indexed the whole text, so this gap is dense-only). Instead we embed
54
+ // a few overlapping windows and retrieve the chunk by the MAX cosine over its
55
+ // windows (max-sim), which preserves tail recall where mean-pooling would dilute it.
56
+ //
57
+ // 12% overlap: a definition that straddles a boundary still lands wholly inside an
58
+ // adjacent window (EMBEDDING_CONTEXT_LIMIT*0.12 ≈ 960 chars of shared context).
59
+ export const EMBEDDING_WINDOW_OVERLAP = 0.12;
60
+ // Hard cap on windows per chunk. Bounds embed cost and .bin growth at ~MAX× a
61
+ // single vector. 4 windows at the 7040-char stride cover ~29k chars (~700 lines);
62
+ // beyond that the god-class split already shards classes into method chunks, and a
63
+ // non-class definition that large is rare enough to accept head-only coverage.
64
+ export const EMBEDDING_MAX_WINDOWS = 4;
65
+ // Suffix for a chunk's window vectors past the first: <key>|w1, <key>|w2, … Window 0
66
+ // is the base key itself (identical to the single-vector path), so small chunks and
67
+ // the head of large chunks are byte-identical to before windowing existed.
68
+ export const WINDOW_VEC_SUFFIX = '|w';
69
+
70
+ const _VEC_SUFFIX_RE = /\|(?:s|w\d+)$/;
71
+ /** Strip a vector-key suffix (summary `|s` or window `|wN`) back to the base key, so
72
+ * every per-chunk vector folds onto one fusion candidate. Both backends use this. */
73
+ export function baseEmbeddingKey(key) {
74
+ return key.replace(_VEC_SUFFIX_RE, '');
75
+ }
76
+
77
+ /**
78
+ * Split an oversized embedding payload into overlapping windows of
79
+ * ≤EMBEDDING_CONTEXT_LIMIT chars, capped at EMBEDDING_MAX_WINDOWS. Returns [] when
80
+ * the payload fits in a single window (the default path — the caller embeds it under
81
+ * the base key unchanged). Window 0 is the same first-EMBEDDING_CONTEXT_LIMIT slice
82
+ * the single-vector path produced, so the base vector is unchanged; windows 1..N
83
+ * cover the tail and are stored under WINDOW_VEC_SUFFIX keys.
84
+ *
85
+ * @param {string} payload
86
+ * @returns {string[]} [] or [window0, window1, …] (length ≥ 2 when it splits).
87
+ */
88
+ export function embeddingWindows(payload) {
89
+ if (!payload || payload.length <= EMBEDDING_CONTEXT_LIMIT) return [];
90
+ const stride = Math.max(1, Math.round(EMBEDDING_CONTEXT_LIMIT * (1 - EMBEDDING_WINDOW_OVERLAP)));
91
+ const windows = [];
92
+ for (let i = 0; i < EMBEDDING_MAX_WINDOWS; i++) {
93
+ const start = i * stride;
94
+ if (start >= payload.length) break;
95
+ windows.push(payload.slice(start, start + EMBEDDING_CONTEXT_LIMIT));
96
+ if (start + EMBEDDING_CONTEXT_LIMIT >= payload.length) break; // tail covered
97
+ }
98
+ return windows;
99
+ }
100
+
101
+ export function cosineSimilarity(vecA, vecB) {
102
+ let dot = 0, nA = 0, nB = 0;
103
+ for (let i = 0; i < vecA.length; i++) {
104
+ dot += vecA[i] * vecB[i];
105
+ nA += vecA[i] * vecA[i];
106
+ nB += vecB[i] * vecB[i];
107
+ }
108
+ return nA === 0 || nB === 0 ? 0 : dot / (Math.sqrt(nA) * Math.sqrt(nB));
109
+ }
110
+
111
+ // ─── Light Porter stemmer (additive recall bridge) ─────────────────────────────
112
+ // Collapses English morphological variants to a shared root so behavioural queries
113
+ // reach code identifiers across the inflection gap that lexical match otherwise
114
+ // misses: "intercepting"↔"Interceptor", "injection"↔"Injectable",
115
+ // "bootstrapping"↔"bootstrap", "managing"↔"Manager". Classic Porter (1980) steps
116
+ // 1–5 plus an agent-noun "-or" rule for code (Interceptor→intercept,
117
+ // Constructor→construct). Used ADDITIVELY in tokenize(): the raw token is always
118
+ // emitted and the stem only when it differs — so exact matches, df statistics and
119
+ // the name/path boosts are byte-for-byte unchanged; only recall is added.
120
+ // Deterministic and pure → both backends produce identical postings (parity-safe).
121
+ const _isVowel = (s, i) => {
122
+ const c = s.charCodeAt(i);
123
+ // a e i o u
124
+ if (c === 97 || c === 101 || c === 105 || c === 111 || c === 117) return true;
125
+ if (s[i] === 'y') return i === 0 ? true : !_isVowel(s, i - 1);
126
+ return false;
127
+ };
128
+ const _measure = (s) => {
129
+ let n = 0, prevV = false;
130
+ for (let i = 0; i < s.length; i++) { const v = _isVowel(s, i); if (prevV && !v) n++; prevV = v; }
131
+ return n;
132
+ };
133
+ const _hasVowel = (s) => { for (let i = 0; i < s.length; i++) if (_isVowel(s, i)) return true; return false; };
134
+ const _endsDoubleCons = (s) => s.length >= 2 && s[s.length - 1] === s[s.length - 2] && !_isVowel(s, s.length - 1);
135
+ const _cvc = (s) => {
136
+ const n = s.length; if (n < 3) return false;
137
+ if (_isVowel(s, n - 1) || !_isVowel(s, n - 2) || _isVowel(s, n - 3)) return false;
138
+ const c = s[n - 1]; return c !== 'w' && c !== 'x' && c !== 'y';
139
+ };
140
+ const _STEP2 = [['ational', 'ate'], ['tional', 'tion'], ['enci', 'ence'], ['anci', 'ance'], ['izer', 'ize'], ['abli', 'able'], ['alli', 'al'], ['entli', 'ent'], ['eli', 'e'], ['ousli', 'ous'], ['ization', 'ize'], ['ation', 'ate'], ['ator', 'ate'], ['alism', 'al'], ['iveness', 'ive'], ['fulness', 'ful'], ['ousness', 'ous'], ['aliti', 'al'], ['iviti', 'ive'], ['biliti', 'ble'], ['logi', 'log']];
141
+ const _STEP3 = [['icate', 'ic'], ['ative', ''], ['alize', 'al'], ['iciti', 'ic'], ['ical', 'ic'], ['ful', ''], ['ness', '']];
142
+ // Longest-first; 'or' added to Porter's set so agent nouns reduce like '-er'.
143
+ const _STEP4 = ['ement', 'ance', 'ence', 'able', 'ible', 'ment', 'ant', 'ent', 'ion', 'ism', 'ate', 'iti', 'ous', 'ive', 'ize', 'al', 'er', 'or', 'ic', 'ou'];
144
+
145
+ /** Porter stem of a single lowercase word. Returns the input unchanged for short
146
+ * tokens (≤3 chars: acronyms, short API names) so precise symbols never blur. */
147
+ export function stemToken(word) {
148
+ let w = word;
149
+ if (w.length <= 3) return w;
150
+
151
+ if (w.endsWith('sses')) w = w.slice(0, -2);
152
+ else if (w.endsWith('ies')) w = w.slice(0, -2);
153
+ else if (!w.endsWith('ss') && w.endsWith('s')) w = w.slice(0, -1);
154
+
155
+ let fix = false;
156
+ if (w.endsWith('eed')) { if (_measure(w.slice(0, -3)) > 0) w = w.slice(0, -1); }
157
+ else if (w.endsWith('ed') && _hasVowel(w.slice(0, -2))) { w = w.slice(0, -2); fix = true; }
158
+ else if (w.endsWith('ing') && _hasVowel(w.slice(0, -3))) { w = w.slice(0, -3); fix = true; }
159
+ if (fix) {
160
+ if (w.endsWith('at') || w.endsWith('bl') || w.endsWith('iz')) w += 'e';
161
+ else if (_endsDoubleCons(w) && !/[lsz]$/.test(w)) w = w.slice(0, -1);
162
+ else if (_measure(w) === 1 && _cvc(w)) w += 'e';
163
+ }
164
+
165
+ if (w.length > 2 && w.endsWith('y') && _hasVowel(w.slice(0, -1))) w = w.slice(0, -1) + 'i';
166
+
167
+ for (const [suf, rep] of _STEP2) { if (w.endsWith(suf)) { const st = w.slice(0, -suf.length); if (_measure(st) > 0) w = st + rep; break; } }
168
+ for (const [suf, rep] of _STEP3) { if (w.endsWith(suf)) { const st = w.slice(0, -suf.length); if (_measure(st) > 0) w = st + rep; break; } }
169
+
170
+ for (const suf of _STEP4) {
171
+ if (w.endsWith(suf)) {
172
+ const st = w.slice(0, -suf.length);
173
+ if (suf === 'ion') { if (_measure(st) > 1 && /[st]$/.test(st)) w = st; }
174
+ else if (_measure(st) > 1) w = st;
175
+ break;
176
+ }
177
+ }
178
+
179
+ if (w.endsWith('e')) { const st = w.slice(0, -1); const m = _measure(st); if (m > 1 || (m === 1 && !_cvc(st))) w = st; }
180
+ if (_measure(w) > 1 && w.endsWith('l') && _endsDoubleCons(w)) w = w.slice(0, -1);
181
+
182
+ return w;
183
+ }
184
+
185
+ /**
186
+ * Tokenise code/identifiers: lowercase words plus camelCase sub-parts, so
187
+ * `dispatchRequest` indexes as `dispatchrequest`, `dispatch`, `request`. Each
188
+ * emitted token also contributes its Porter stem (when different) so behavioural
189
+ * queries bridge the inflection gap to code names — see stemToken. Additive: the
190
+ * raw token is never dropped, so exact match and the boost ladder are unaffected.
191
+ */
192
+ // Stem postings live in a separate term namespace (sentinel-prefixed) so a raw
193
+ // query token can NEVER match a stem posting: symbolic/exact lookups stay precisely
194
+ // what they were before stemming existed, and only a query that opts in (emits the
195
+ // prefixed stem) reaches the morphological bridges. Index always emits both; the
196
+ // query emits the prefixed stem only for natural-language queries.
197
+ export const STEM_PREFIX = '~stem~'; // sentinel namespace: raw tokens are [A-Za-z0-9]+, so '~' can never collide
198
+
199
+ export function tokenize(text, stem = true) {
200
+ if (!text) return [];
201
+ const rawTokens = text.split(/[\s\W_]+/);
202
+ const tokens = [];
203
+ const emit = (t) => {
204
+ const lo = t.toLowerCase();
205
+ tokens.push(lo);
206
+ if (!stem) return;
207
+ const s = stemToken(lo);
208
+ if (s !== lo && s.length >= 3) tokens.push(STEM_PREFIX + s);
209
+ };
210
+ for (const word of rawTokens) {
211
+ if (word.length < 2) continue;
212
+ emit(word);
213
+ const camelParts = word.replace(/([a-z])([A-Z])/g, '$1 $2').split(' ');
214
+ if (camelParts.length > 1) {
215
+ for (const part of camelParts) {
216
+ if (part.length >= 2) emit(part);
217
+ }
218
+ }
219
+ }
220
+ return tokens;
221
+ }
222
+
223
+ /**
224
+ * Suffix appended to an embedding key for a chunk's summary-only vector.
225
+ * Enriched chunks carry TWO vectors in the bin: the full code payload (base key)
226
+ * and this compact summary+concepts text. A one-line natural-language query is
227
+ * far closer in embedding space to a one-line summary than to 700 chars of code,
228
+ * so the summary vector is what lets behavioural queries hit code that shares
229
+ * none of their words. Scan hits on `<key>|s` map back to the same chunk.
230
+ */
231
+ export const SUMMARY_VEC_SUFFIX = '|s';
232
+
233
+ /** The text embedded as the summary-only vector, or null when not enriched.
234
+ * The leading LLM summary carries the behavioural signal; the concept tags add
235
+ * domain vocabulary; the qualified name (class_context.name when present) anchors
236
+ * the vector to the symbol so a method is disambiguated from same-named peers. */
237
+ export function summaryEmbeddingText(chunk) {
238
+ if (!chunk.summary && !(chunk.concepts?.length > 0)) return null;
239
+ const qualifiedName = chunk.class_context ? `${chunk.class_context}.${chunk.name}` : chunk.name;
240
+ return [chunk.summary, (chunk.concepts || []).join(', '), qualifiedName]
241
+ .filter(Boolean).join('. ');
242
+ }
243
+
244
+ /**
245
+ * Build the lexical document indexed for BM25. Concatenates the discriminative
246
+ * fields of a chunk (name, docstring, neighbour basenames, calls, params, return
247
+ * type, qualified name, type refs, LLM concept tags, body).
248
+ *
249
+ * Single source of truth shared by the in-memory engine, the watch daemon and the
250
+ * SQLite writer so every backend indexes identical text. Decorators are
251
+ * deliberately excluded — measured to regress framework repos (see engine/memory.mjs).
252
+ * When enrichment ran, chunk.concepts contains domain keyword strings that bridge
253
+ * lexical gaps (e.g. "authentication JWT middleware"); chunk.hyde is concepts.join(' ')
254
+ * and serves as the backward-compatible field for existing serialized indexes.
255
+ *
256
+ * @param {object} chunk
257
+ * @param {string[]} depRelPaths Resolved local imports of the chunk's file.
258
+ * @returns {string}
259
+ */
260
+ export function buildLexicalDocument(chunk, depRelPaths = []) {
261
+ const cleanDeps = depRelPaths.map(d => d.split('/').pop().split('.')[0]);
262
+ // Prefer the structured concepts array (new); fall back to the joined hyde string
263
+ // (old serialized indexes) so both formats index identical terms.
264
+ const conceptTokens = chunk.concepts?.length
265
+ ? chunk.concepts.join(' ')
266
+ : (chunk.hyde || '');
267
+ return [
268
+ chunk.name,
269
+ chunk.docstring || '',
270
+ cleanDeps.join(' '),
271
+ (chunk.calls || []).join(' '),
272
+ (chunk.params || []).join(' '),
273
+ chunk.return_type || '',
274
+ chunk.class_context ? `${chunk.class_context}.${chunk.name}` : '',
275
+ (chunk.type_refs || []).join(' '),
276
+ conceptTokens, // domain concept keywords from LLM enrichment (opt-in)
277
+ chunk.code_snippet,
278
+ ].join(' ');
279
+ }
280
+
281
+ // ─── BM25 (tuned for code) ─────────────────────────────────────────────────────
282
+ // b lowered from 0.75 → 0.3: code chunks have purposeful length variation unlike
283
+ // prose, so heavy length normalisation wrongly penalises long implementations vs
284
+ // short export stubs.
285
+ export const BM25_K1 = 1.5;
286
+ export const BM25_B = 0.3;
287
+
288
+ /** Okapi IDF — always positive, avoids negative IDF for very common terms. */
289
+ export function okapiIdf(docCount, docFreq) {
290
+ return Math.log((docCount - docFreq + 0.5) / (docFreq + 0.5) + 1);
291
+ }
292
+
293
+ /** BM25 term contribution: diminishing TF returns + document-length normalisation. */
294
+ export function bm25Score(idf, tf, docLen, avgdl, k1 = BM25_K1, b = BM25_B) {
295
+ return idf * (tf * (k1 + 1)) / (tf + k1 * (1 - b + b * docLen / avgdl));
296
+ }
297
+
298
+ // ─── Hybrid fusion (RRF + boost ladder) ────────────────────────────────────────
299
+
300
+ // Lexical candidates handed to fusion — shared by BOTH backends. An asymmetric
301
+ // cap would let deep-ranked chunks earn RRF contributions on one backend only,
302
+ // silently breaking rank parity.
303
+ export const LEXICAL_FUSION_CAP = 2000;
304
+
305
+ // Unique vector candidates handed to fusion (after summary-vector dedupe).
306
+ export const VECTOR_FUSION_CAP = 200;
307
+ // Raw bin entries to collect before dedupe: each chunk owns at most TWO entries
308
+ // (code vector + summary vector), so 2× the cap guarantees the full unique set.
309
+ export const VECTOR_SCAN_RAW_N = VECTOR_FUSION_CAP * 2;
310
+
311
+ /**
312
+ * Normalize a store's raw vector hits into the fusion-ready candidate list:
313
+ * best score per chunk id, deterministic (score desc, id asc) order, capped.
314
+ * EVERY backend path (eager matrix, streaming scan, binary sketch) must funnel
315
+ * through this so the vector channel is rank-identical across stores — dedupe
316
+ * scope and tie order were measured to silently diverge otherwise.
317
+ *
318
+ * @param {Array<{id:string, score:number}>} entries May contain duplicate ids.
319
+ * @returns {Array<{id:string, score:number, rank:number}>}
320
+ */
321
+ export function finalizeVectorCandidates(entries, cap = VECTOR_FUSION_CAP) {
322
+ const best = new Map();
323
+ for (const e of entries) {
324
+ const prev = best.get(e.id);
325
+ if (prev === undefined || e.score > prev) best.set(e.id, e.score);
326
+ }
327
+ return Array.from(best.entries())
328
+ .sort((a, b) => (b[1] - a[1]) || (a[0] < b[0] ? -1 : 1))
329
+ .slice(0, cap)
330
+ .map(([id, score], i) => ({ id, score, rank: i + 1 }));
331
+ }
332
+
333
+ // Non-natural-language channel weights (keyword / symbol-lookup queries). The
334
+ // vector weight was lowered 1.0 → 0.7 after the 15-fixture search-eval was fixed
335
+ // to actually exercise embeddings (its "semantic" pass had been silently lexical,
336
+ // because the test bridge forced embeddings off — so the prior 1.0 was tuned
337
+ // against a vector-less harness). With honest measurement, a full-strength vector
338
+ // channel slightly OVER-contributes on keyword queries (BM25's home turf): it
339
+ // displaces a confident exact-name lexical rank-1 with a same-prefixed sibling
340
+ // (`Map`→`key`, `GardenPlantingRepository`→`…Dao`). 0.7 is the top of the winning
341
+ // plateau — it restores those rank-1s (broad kw MRR 0.569 → 0.588, +1 hit@1) while
342
+ // keeping the vector channel's recall lift, and leaves the 5-suite repo-eval
343
+ // byte-identical (symbolic 0.78/0.83). Below 0.7 the repo-eval symbolic starts to
344
+ // erode; the NL path keeps its own (higher) vector weight below.
345
+ const LEXICAL_WEIGHT = 1.5;
346
+ const VECTOR_WEIGHT = 0.7;
347
+
348
+ // Natural-language queries keep the lexical channel at full strength (exact-name and
349
+ // keyword matches are the most reliable signal); the vector channel's weight depends on
350
+ // whether the corpus carries LLM enrichment:
351
+ //
352
+ // • PLAIN corpus (no enrichment) — the only vectors are raw-code embeddings, a weak
353
+ // conceptual signal that DISPLACES correct lexical hits at any real weight. It acts
354
+ // as a low-weight rescue (0.4). This was the historical "joint optimum" finding.
355
+ // • ENRICHED corpus — every central chunk also owns a summary vector that speaks the
356
+ // vocabulary of behavioural queries, so the vector channel becomes a strong semantic
357
+ // signal and earns more weight. The value is the JOINT optimum of two independent
358
+ // suites that DISAGREE: the repo-eval behavioural channel keeps climbing to ~1.0,
359
+ // while the broader 15-fixture search-eval (mixed nl/kw/xc) peaks at 0.4 and decays
360
+ // above it (a high weight lets a confident-but-wrong summary vector displace a good
361
+ // lexical hit on cross-cutting queries). 0.6 improves BOTH over baseline and avoids
362
+ // overfitting either; the opt-in LLM reranker recovers the top-rank precision that a
363
+ // lower weight gives up. (Plain stays 0.4 — raw-code vectors are a weak rescue.)
364
+ //
365
+ // The engine selects the regime per index via `corpusEnriched` (see engine/memory.mjs /
366
+ // engine/sqlite.mjs), so a repo indexed without --enrich is never hurt by the strong weight.
367
+ const NL_LEXICAL_WEIGHT = 1.5;
368
+ const NL_VECTOR_WEIGHT_PLAIN = 0.4;
369
+ const NL_VECTOR_WEIGHT_ENRICHED = 0.6;
370
+
371
+ const QUERY_STOPWORDS = new Set([
372
+ 'the', 'a', 'an', 'and', 'or', 'of', 'to', 'in', 'for', 'on', 'with', 'at',
373
+ 'by', 'from', 'that', 'this', 'is', 'are', 'was', 'were', 'be', 'how', 'what',
374
+ 'when', 'where', 'which', 'who', 'why', 'does', 'do', 'it', 'its', 'into',
375
+ 'back', 'if', 'then', 'their', 'there', 'all', 'any',
376
+ ]);
377
+
378
+ /**
379
+ * Heuristic: is this an agent-style natural-language query (a behavioural
380
+ * description / question) rather than a keyword or symbol lookup? NL queries are
381
+ * long and contain English function words; symbol queries ("ShouldBindJSON bind
382
+ * request body") contain none.
383
+ */
384
+ export function isNaturalLanguageQuery(queryText) {
385
+ const words = String(queryText).toLowerCase().split(/[\s\W_]+/).filter(Boolean);
386
+ if (words.length < 5) return false;
387
+ const stops = words.filter(w => QUERY_STOPWORDS.has(w)).length;
388
+ return stops >= 2 && stops / words.length >= 0.2;
389
+ }
390
+
391
+ export const TEST_FILE_RE = /\.(test|spec)\.|[/\\]__tests__[/\\]|_test\.|^tests?[/\\]|[/\\]tests?[/\\]|[/\\]spec[/\\]/i;
392
+ // Example/sample/demo/sandbox/etc. trees are a top-level project convention
393
+ // (examples/, samples/, demo/, docs_src/, …). The keyword is matched ONLY as the
394
+ // FIRST or SECOND path segment. Matching it at ANY depth (the previous behaviour)
395
+ // false-positived on PACKAGE PATHS that merely contain the word — e.g. Spring's
396
+ // `src/main/java/org/springframework/samples/petclinic/…` and Google's
397
+ // `com/google/samples/apps/…` — silently excluding real application code from LLM
398
+ // enrichment and demoting it in search. The fixtures' legitimate example/sample
399
+ // dirs all sit at depth ≤1, so this only stops the deep package-path false hits.
400
+ export const EXAMPLE_DIR_RE = /^(?:[^/\\]+[/\\])?(?:examples?|samples?|demos?|tutorials?|docs_src|sandbox|benchmarks?|scripts?)[/\\]/;
401
+
402
+ /**
403
+ * Reciprocal-Rank-Fusion of lexical + vector candidate lists, with the measured
404
+ * boost ladder (test/example demotion, expression demotion, TS barrel demotion,
405
+ * file-path boost, exact/snake name boost, optional exact-symbol boost).
406
+ *
407
+ * All backend-specific data is reached through accessors so the identical math
408
+ * serves both the in-memory Maps and SQLite row lookups.
409
+ *
410
+ * @param {object} p
411
+ * @param {Array<{id:string,rank:number}>} p.lexicalResults
412
+ * @param {Array<{id:string,rank:number}>} p.vectorResults
413
+ * @param {(id:string)=>object|undefined} p.getChunk
414
+ * @param {(id:string)=>Set<string>|undefined} p.getPathTokens
415
+ * @param {(token:string)=>number} p.getDf Document frequency of a token.
416
+ * @param {number} p.docCount
417
+ * @param {number} p.rrfK
418
+ * @param {number} p.topK
419
+ * @param {string} p.queryText
420
+ * @param {string|null} [p.exactBoostName]
421
+ * @param {(termLower:string)=>Iterable<string>} [p.resolveExact] Ids whose name === term.
422
+ * @returns {Array<{score:number, chunk:object}>}
423
+ */
424
+ export function fuseAndRank({
425
+ lexicalResults, vectorResults, getChunk, getPathTokens, getDf,
426
+ docCount, rrfK, topK, queryText, exactBoostName = null, resolveExact = null,
427
+ corpusEnriched = false,
428
+ }) {
429
+ const rrfScores = new Map();
430
+ const K = rrfK;
431
+ const queryLower = queryText.toLowerCase();
432
+
433
+ const _queryPathTokens = queryLower.split(/[\s\W_]+/).filter(t => t.length >= 3);
434
+
435
+ // File-path boost discriminativeness gate (natural-language queries only).
436
+ // The file-path boost (further down) fires when a query token matches a
437
+ // filename segment — but a common low-IDF word ("path", "url", "config",
438
+ // "index") that merely appears in a filename then over-promotes EVERY chunk in
439
+ // that file (an NL query mentioning "path" boosts all of path.go, burying the
440
+ // real answer that lives elsewhere). Restrict the boost to query terms
441
+ // discriminative enough to be a genuine filename signal: IDF ≥ ln(docCount/2),
442
+ // a per-corpus structural threshold (not tuned to any query). Symbolic/keyword
443
+ // queries are excluded by the NL gate and keep the original token set
444
+ // byte-for-byte. Measured: lifts agent-style recall@5 (overall s@5 0.77→0.81;
445
+ // tuning-semantic s@5 0.52→0.61) with symbolic rankings unchanged, no regression.
446
+ const _pathBoostIsNL = isNaturalLanguageQuery(queryText);
447
+ const _pathBoostMinIdf = Math.log(Math.max(docCount, 2) / 2);
448
+ const _queryPathTokensBoost = _pathBoostIsNL
449
+ ? _queryPathTokens.filter(t => okapiIdf(docCount, getDf(t)) >= _pathBoostMinIdf)
450
+ : _queryPathTokens;
451
+
452
+ // Name-boost eligibility: long tokens, or short-but-discriminative ones whose
453
+ // document frequency is ≤15% of the corpus (self-tunes per repo/language,
454
+ // surfacing exact matches on short API names without re-introducing stopwords).
455
+ const _docN = docCount || 1;
456
+ const _queryNameTokens = queryLower.split(/[\s\W_]+/).filter(t =>
457
+ t.length >= 5 || (t.length >= 3 && (getDf(t) || 0) <= 0.15 * _docN)
458
+ );
459
+
460
+ // Query-adaptive channel weights: lexical-led for keyword/symbol lookups,
461
+ // vector-led for natural-language behavioural queries (only when a vector
462
+ // channel actually produced candidates — lexical-only mode is unaffected).
463
+ const nlQuery = vectorResults.length > 0 && isNaturalLanguageQuery(queryText);
464
+ const nlVecWeight = corpusEnriched ? NL_VECTOR_WEIGHT_ENRICHED : NL_VECTOR_WEIGHT_PLAIN;
465
+ const wLex = nlQuery ? NL_LEXICAL_WEIGHT : LEXICAL_WEIGHT;
466
+ const wVec = nlQuery ? nlVecWeight : VECTOR_WEIGHT;
467
+
468
+ // Re-rank the vector channel with test/example demotion applied to the cosine
469
+ // scores BEFORE ranks are assigned: a test helper that out-scores the real
470
+ // implementation in raw cosine otherwise occupies the top RRF positions and
471
+ // pushes the right answer's reciprocal rank down, even though the boost
472
+ // ladder demotes the helper later.
473
+ if (vectorResults.length > 0) {
474
+ const adjusted = vectorResults.map(r => {
475
+ const c = getChunk(r.id);
476
+ let f = 1;
477
+ if (c) {
478
+ if (TEST_FILE_RE.test(c.file_path) && !queryLower.includes('test') && !queryLower.includes('spec')) f = 0.25;
479
+ else if (EXAMPLE_DIR_RE.test(c.file_path)) f = 0.5;
480
+ }
481
+ return { id: r.id, score: (r.score ?? 0) * f };
482
+ });
483
+ adjusted.sort((a, b) => (b.score - a.score) || (a.id < b.id ? -1 : 1));
484
+ vectorResults = adjusted.map((r, i) => ({ ...r, rank: i + 1 }));
485
+ }
486
+
487
+ // Boosts are NOT gated on vector-candidate membership. Gating was intended to
488
+ // stop generic-word name collisions on NL queries, but because the code-embedding
489
+ // channel is weak it mostly suppressed the EXACT-name boost on the correct hit
490
+ // (which then sank below a noisy vector candidate). Removing the gate measured
491
+ // strictly better on both retrieval suites; the exact-name boost is the single
492
+ // most reliable signal and must always apply.
493
+ const boostEligible = null;
494
+
495
+ // Style-intent detection: a stylesheet bundle vendored into a source tree
496
+ // (e.g. a bundled bootstrap.css) produces hundreds of synthetic-named
497
+ // `*_rule_set` chunks that pollute CODE searches in mixed repos. Demote those
498
+ // synthetic rule_sets UNLESS the query is actually about styling (a selector
499
+ // char, an exact_tokens pin, or a style keyword). Named SCSS @mixin/@function
500
+ // chunks are unaffected — only nameless rule_sets are noise for code queries.
501
+ const queryIsStyle = exactBoostName != null ||
502
+ /[.#]|css|scss|stylesheet|selector|\bstyle\b|\bclass\b|color|margin|padding|font|border|background|hover|keyframe|animation|mixin|breakpoint|responsive|\bwidth\b|\bheight\b/.test(queryLower);
503
+
504
+ const allResults = [
505
+ ...vectorResults.map(r => ({ ...r, _w: wVec })),
506
+ ...lexicalResults.map(r => ({ ...r, _w: wLex })),
507
+ ];
508
+
509
+ for (const { id, rank, _w } of allResults) {
510
+ let baseScore = (_w ?? 1.0) / (K + rank);
511
+ const chunk = getChunk(id);
512
+ if (!chunk) continue;
513
+
514
+ if (TEST_FILE_RE.test(chunk.file_path)) {
515
+ if (!queryLower.includes('test') && !queryLower.includes('spec')) baseScore *= 0.25;
516
+ }
517
+ // Demotion: synthetic-named stylesheet rule_sets on non-style queries
518
+ // (vendored CSS bundle noise in mixed repos). Named mixins/functions exempt.
519
+ if (!queryIsStyle && chunk.name && chunk.name.endsWith('_rule_set')) baseScore *= 0.2;
520
+ if (EXAMPLE_DIR_RE.test(chunk.file_path)) baseScore *= 0.5;
521
+ if (chunk.node_type === 'expression_statement' || chunk.node_type === 'call_expression') {
522
+ baseScore *= 0.8;
523
+ }
524
+ // Demotion: TypeScript barrel re-exports (`export { X } from 'y'`) — no
525
+ // implementation. JS exports are excluded since those often ARE the module.
526
+ if (chunk.name && chunk.name.endsWith('_export_statement') && chunk.file_path?.endsWith('.ts')) {
527
+ baseScore *= 0.7;
528
+ }
529
+ // Demotion: Python public re-exports (`from x import Y as Y`) — but only
530
+ // when a REAL definition of the same name exists in the index. When the
531
+ // re-export is the only in-repo occurrence (the implementation lives in a
532
+ // dependency, e.g. fastapi re-exporting starlette's BackgroundTasks), the
533
+ // alias IS the best available answer and must not be demoted.
534
+ if (chunk.node_type === 're_export' && resolveExact && chunk.name) {
535
+ for (const rid of resolveExact(String(chunk.name).toLowerCase())) {
536
+ const rc = getChunk(rid);
537
+ if (rc && rc.node_type !== 're_export') { baseScore *= 0.7; break; }
538
+ }
539
+ }
540
+
541
+ // File-path boost via the separate path-token set (not the BM25 index), so
542
+ // length normalisation never penalises long implementations sharing a path.
543
+ const canBoost = !boostEligible || boostEligible.has(id);
544
+ if (canBoost && _queryPathTokensBoost.length > 0) {
545
+ const pathToks = getPathTokens(id);
546
+ if (pathToks) {
547
+ const hasExact = _queryPathTokensBoost.some(t => pathToks.has(t));
548
+ const hasPrefix = !hasExact && _queryPathTokensBoost.some(t =>
549
+ t.length >= 4 && Array.from(pathToks).some(pt => pt.startsWith(t.slice(0, 5)))
550
+ );
551
+ if (hasExact) baseScore *= 1.4;
552
+ else if (hasPrefix) baseScore *= 1.2;
553
+ }
554
+ }
555
+
556
+ // Name boost: 2.0× exact (token IS the name), 1.4× snake_case suffix match.
557
+ // Only [._] splitting keeps camelCase names atomic (no generic-suffix bleed).
558
+ // Plural equivalence (`BackgroundTask` ↔ `BackgroundTasks`) is included —
559
+ // API names pluralize and a strict equality check missed them.
560
+ if (canBoost && chunk.name && chunk.name !== 'anonymous') {
561
+ const nameLower = chunk.name.toLowerCase();
562
+ const lastDotted = nameLower.split('.').pop() ?? nameLower;
563
+ const queryTokensAll = _queryNameTokens;
564
+ const eq = (a, b) => a === b || a === b + 's' || b === a + 's';
565
+ if (queryTokensAll.some(t => eq(nameLower, t) || eq(lastDotted, t))) {
566
+ // NOTE: a PageRank multiplier was trialled here (tie-break duplicate
567
+ // names toward central files) and measured NEGATIVE — hub files win
568
+ // exact-name matches on common words and the semantic channel drops.
569
+ baseScore *= 2.0;
570
+ } else {
571
+ const snakeParts = nameLower.split(/[._]+/);
572
+ const lastSnake = snakeParts[snakeParts.length - 1] ?? '';
573
+ if (snakeParts.length >= 2 && lastSnake.length >= 3 && queryTokensAll.includes(lastSnake)) {
574
+ baseScore *= 1.4;
575
+ }
576
+ }
577
+ }
578
+
579
+ rrfScores.set(id, (rrfScores.get(id) || 0) + baseScore);
580
+ }
581
+
582
+ if (exactBoostName && resolveExact) {
583
+ const boostTerm = String(exactBoostName).toLowerCase().trim();
584
+ for (const id of resolveExact(boostTerm)) {
585
+ rrfScores.set(id, (rrfScores.get(id) || 0) + 1 / (K + 1));
586
+ }
587
+ }
588
+
589
+ return Array.from(rrfScores.entries())
590
+ .sort((a, b) => (b[1] - a[1]) || (a[0] < b[0] ? -1 : 1))
591
+ .slice(0, topK)
592
+ .map(([id, rrfScore]) => ({ score: rrfScore, chunk: getChunk(id) }))
593
+ .filter(r => r.chunk !== undefined);
594
+ }
595
+
596
+ // ─── Graph centrality ──────────────────────────────────────────────────────────
597
+
598
+ /**
599
+ * Simplified PageRank over the file dependency graph. Files imported by many
600
+ * others receive higher rank (= more important). Used by get_repo_map ordering
601
+ * and by LLM enrichment to pick the "core" files worth summarising.
602
+ *
603
+ * @param {{dependencies:Object<string,string[]>}} graph
604
+ * @returns {Map<string, number>} file → rank
605
+ */
606
+ export function computePageRank(graph, iters = 30, damping = 0.85) {
607
+ const files = Object.keys(graph?.dependencies || {});
608
+ const N = files.length;
609
+ if (N === 0) return new Map();
610
+
611
+ const idx = new Map(files.map((f, i) => [f, i]));
612
+ const ranks = new Float64Array(N).fill(1.0 / N);
613
+ const outDeg = files.map(f => Math.max((graph.dependencies[f] || []).length, 1));
614
+
615
+ for (let iter = 0; iter < iters; iter++) {
616
+ const next = new Float64Array(N).fill((1 - damping) / N);
617
+ for (let i = 0; i < N; i++) {
618
+ const contrib = damping * ranks[i] / outDeg[i];
619
+ for (const dep of (graph.dependencies[files[i]] || [])) {
620
+ const j = idx.get(dep);
621
+ if (j !== undefined) next[j] += contrib;
622
+ }
623
+ }
624
+ ranks.set(next);
625
+ }
626
+ return new Map(files.map((f, i) => [f, ranks[i]]));
627
+ }