@blackbelt-technology/pi-dashboard-kb 0.7.0 → 0.9.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 (63) hide show
  1. package/README.md +69 -0
  2. package/bin/kb.mjs +84 -0
  3. package/bin/lib/engine-fingerprint.mjs +183 -0
  4. package/dist/adoc-chunker.d.ts +29 -0
  5. package/dist/adoc-chunker.js +274 -0
  6. package/dist/archive-guard.d.ts +12 -0
  7. package/dist/archive-guard.js +154 -0
  8. package/dist/chunker.d.ts +3 -0
  9. package/dist/chunker.js +5 -3
  10. package/dist/cli.js +137 -19
  11. package/dist/config.d.ts +49 -0
  12. package/dist/config.js +43 -6
  13. package/dist/dox-triage.d.ts +67 -0
  14. package/dist/dox-triage.js +183 -0
  15. package/dist/dox.d.ts +68 -7
  16. package/dist/dox.js +370 -94
  17. package/dist/eval.d.ts +30 -0
  18. package/dist/eval.js +120 -13
  19. package/dist/gitignore.d.ts +24 -0
  20. package/dist/gitignore.js +205 -0
  21. package/dist/index.d.ts +25 -17
  22. package/dist/index.js +17 -8
  23. package/dist/indexer.d.ts +9 -1
  24. package/dist/indexer.js +40 -11
  25. package/dist/net-guard.d.ts +35 -0
  26. package/dist/net-guard.js +285 -0
  27. package/dist/render.js +37 -2
  28. package/dist/search-opts.d.ts +22 -0
  29. package/dist/search-opts.js +21 -0
  30. package/dist/sources.d.ts +29 -0
  31. package/dist/sources.js +230 -32
  32. package/dist/sqlite-store.d.ts +72 -2
  33. package/dist/sqlite-store.js +482 -78
  34. package/dist/staleness.d.ts +25 -0
  35. package/dist/staleness.js +69 -0
  36. package/dist/trust.d.ts +33 -1
  37. package/dist/trust.js +72 -5
  38. package/dist/types.d.ts +59 -0
  39. package/dist/verdict.d.ts +45 -0
  40. package/dist/verdict.js +368 -0
  41. package/engine-fingerprint.json +5 -0
  42. package/package.json +8 -4
  43. package/src/adoc-chunker.ts +308 -0
  44. package/src/archive-guard.ts +144 -0
  45. package/src/chunker.ts +5 -3
  46. package/src/cli.ts +130 -20
  47. package/src/config.ts +81 -6
  48. package/src/dox-triage.ts +231 -0
  49. package/src/dox.ts +390 -70
  50. package/src/eval.ts +136 -14
  51. package/src/gitignore.ts +215 -0
  52. package/src/index.ts +45 -20
  53. package/src/indexer.ts +46 -10
  54. package/src/net-guard.ts +288 -0
  55. package/src/render.ts +35 -3
  56. package/src/search-opts.ts +52 -0
  57. package/src/sources.ts +232 -28
  58. package/src/sqlite-store.ts +448 -67
  59. package/src/staleness.ts +76 -0
  60. package/src/trust.ts +81 -8
  61. package/src/types.ts +58 -0
  62. package/src/verdict.ts +412 -0
  63. package/src/AGENTS.md +0 -23
@@ -1,17 +1,21 @@
1
1
  // Default KbStore backend over node:sqlite (Node built-in; FTS5 verified).
2
2
  // Zero runtime deps. Requires --experimental-sqlite on current Node.
3
3
  // better-sqlite3 is a drop-in fallback behind the same KbStore interface.
4
- import { mkdirSync, renameSync, unlinkSync } from "node:fs";
4
+ import { mkdirSync, renameSync, statSync, unlinkSync } from "node:fs";
5
5
  import { dirname } from "node:path";
6
6
  import { DatabaseSync } from "node:sqlite";
7
7
  /** Bump when the frontmatter structural schema/behavior changes so an existing
8
8
  * DB force-reindexes once on open (design D6). */
9
- export const SCHEMA_VERSION = 2;
9
+ export const SCHEMA_VERSION = 3;
10
10
  const DDL = `
11
11
  CREATE VIRTUAL TABLE IF NOT EXISTS chunks USING fts5(
12
12
  root UNINDEXED, path UNINDEXED, chunk_id UNINDEXED, doc_type UNINDEXED,
13
13
  parent_chunk_id UNINDEXED, level UNINDEXED, body_hash UNINDEXED,
14
14
  heading_path, heading, body,
15
+ -- Line anchors appended AFTER body so the body column keeps index 9 (bm25 and
16
+ -- snippet are positional). FTS5 has no ALTER TABLE ADD COLUMN, so adding
17
+ -- them is a SCHEMA_VERSION bump + one-time full reindex (design D3a).
18
+ start_line UNINDEXED, end_line UNINDEXED,
15
19
  tokenize='porter unicode61'
16
20
  );
17
21
  CREATE TABLE IF NOT EXISTS files (
@@ -80,6 +84,10 @@ function toMatch(q) {
80
84
  export class SqliteFtsStore {
81
85
  db;
82
86
  dbPath;
87
+ /** Opened via `openExisting`: SELECT-only handle, must never issue DDL against the saved file. */
88
+ existingOnly;
89
+ /** fts5vocab view used for document frequencies (persistent in a writer, connection-local TEMP when `existingOnly`). */
90
+ vocabTable = "chunks_vocab";
83
91
  // Prepared-statement cache: re-preparing per row on a hot insert path (chunks
84
92
  // + properties, many per file) is a measurable reindex cost. Cache by SQL.
85
93
  stmts = new Map();
@@ -91,25 +99,98 @@ export class SqliteFtsStore {
91
99
  }
92
100
  return s;
93
101
  }
94
- constructor(dbPath) {
102
+ /**
103
+ * `existingOnly` opens a side-effect-free handle for read-only callers: no
104
+ * `mkdir`, no `journal_mode=WAL` (a mode change rewrites a DELETE-mode file
105
+ * header), and the caller must NOT call `init()` (no DDL / schema migration).
106
+ * Prefer {@link SqliteFtsStore.openExisting}.
107
+ */
108
+ constructor(dbPath, opts = {}) {
95
109
  this.dbPath = dbPath;
96
- if (dbPath !== ":memory:")
110
+ this.existingOnly = opts.existingOnly === true;
111
+ if (!opts.existingOnly && dbPath !== ":memory:")
97
112
  mkdirSync(dirname(dbPath), { recursive: true });
98
113
  this.db = new DatabaseSync(dbPath);
99
- this.db.exec("PRAGMA journal_mode=WAL");
114
+ if (!opts.existingOnly)
115
+ this.db.exec("PRAGMA journal_mode=WAL");
100
116
  // Let a concurrent reader (e.g. `/stats` during a reindex) wait briefly for a
101
117
  // batch's write lock instead of failing with SQLITE_BUSY. See change:
102
118
  // fix-kb-index-feedback.
103
119
  this.db.exec("PRAGMA busy_timeout=5000");
104
120
  }
121
+ /**
122
+ * Open an EXISTING db without creating, migrating or re-moding it. Returns
123
+ * null for a missing or 0-byte file (callers treat that as an empty index).
124
+ * A read-write handle is used on purpose: a `readOnly` connection cannot
125
+ * create the WAL `-shm` sidecar once the writer checkpointed and removed it
126
+ * (SQLITE_CANTOPEN). Callers must only issue SELECTs.
127
+ */
128
+ static openExisting(dbPath) {
129
+ try {
130
+ if (statSync(dbPath).size === 0)
131
+ return null;
132
+ }
133
+ catch {
134
+ return null;
135
+ }
136
+ return new SqliteFtsStore(dbPath, { existingOnly: true });
137
+ }
138
+ /** True when `chunks` exists with the current column set (`start_line`). Read-only probe. */
139
+ hasCurrentSchema() {
140
+ const cols = this.db.prepare("PRAGMA table_info(chunks)").all().map((c) => c.name);
141
+ return { table: cols.length > 0, current: cols.includes("start_line") };
142
+ }
143
+ /** Indexed file count per root. `files` has a (root,path) PK, so this is cheap (no FTS scan). */
144
+ filesByRoot() {
145
+ const out = {};
146
+ for (const r of this.db.prepare("SELECT root, COUNT(*) AS n FROM files GROUP BY root").all())
147
+ out[r.root] = Number(r.n);
148
+ return out;
149
+ }
105
150
  init() {
151
+ this.migrateChunksSchema();
106
152
  this.db.exec(DDL);
107
153
  }
154
+ /** Rebuild the `chunks` FTS5 table when its column set predates the current
155
+ * DDL. `CREATE VIRTUAL TABLE IF NOT EXISTS` is a NO-OP on an existing table
156
+ * and FTS5 has no `ALTER TABLE ADD COLUMN`, so without this an older store
157
+ * keeps its 10-column table and every `insertChunk` throws "table chunks has
158
+ * no column named start_line" — permanently un-reindexable. Chunks are
159
+ * derived data, so dropping is safe; `files` (the mtime/sha256 state) is
160
+ * cleared with them, or the next INCREMENTAL walk would skip every unchanged
161
+ * file and leave the rebuilt table empty. Runs for every opener, not just the
162
+ * `runIndexAtomic` version gate. See change: asciidoc-support (design D3a). */
163
+ migrateChunksSchema() {
164
+ let cols;
165
+ try {
166
+ cols = this.db.prepare("PRAGMA table_info(chunks)").all().map((r) => String(r.name));
167
+ }
168
+ catch {
169
+ return; // no table yet → the DDL below creates it at the current shape
170
+ }
171
+ if (cols.length === 0)
172
+ return;
173
+ if (cols.includes("start_line") && cols.includes("end_line"))
174
+ return;
175
+ this.db.exec("DROP TABLE IF EXISTS chunks");
176
+ // Everything below is derived from the same walk; clearing it keeps the
177
+ // rebuilt index free of rows the deletion sweep can no longer reach (that
178
+ // sweep reads `listPaths`, which now returns nothing).
179
+ for (const t of ["files", "nodes", "edges", "properties"]) {
180
+ try {
181
+ this.db.exec(`DELETE FROM ${t}`);
182
+ }
183
+ catch { /* table absent in a pre-DDL store — nothing to clear */ }
184
+ }
185
+ }
108
186
  begin() {
109
187
  this.db.exec("BEGIN");
110
188
  }
111
189
  commit() {
112
190
  this.db.exec("COMMIT");
191
+ // An index batch just changed the corpus; cached document frequencies (and
192
+ // therefore IDF) are stale. The fts5vocab view itself is live.
193
+ this.dfCache.clear();
113
194
  }
114
195
  rollback() {
115
196
  try {
@@ -163,6 +244,7 @@ export class SqliteFtsStore {
163
244
  return this.db.prepare("SELECT path FROM files WHERE root=?").all(root).map((r) => r.path);
164
245
  }
165
246
  deleteByPath(root, path) {
247
+ this.dfCache.clear();
166
248
  // chunks includes the file's synthetic `:meta` chunk (same path) — removed here.
167
249
  this.db.prepare("DELETE FROM chunks WHERE root=? AND path=?").run(root, path);
168
250
  // outbound edges originate from this file's nodes; prune nodes owned by path then dangling edges
@@ -217,8 +299,8 @@ export class SqliteFtsStore {
217
299
  this.db.prepare("INSERT INTO kb_meta(k,v) VALUES(?,?) ON CONFLICT(k) DO UPDATE SET v=excluded.v").run(k, v);
218
300
  }
219
301
  insertChunk(c) {
220
- this.prep("INSERT INTO chunks(root,path,chunk_id,doc_type,parent_chunk_id,level,body_hash,heading_path,heading,body) VALUES(?,?,?,?,?,?,?,?,?,?)")
221
- .run(c.root, c.path, c.chunkId, c.docType, c.parentChunkId, c.level, c.bodyHash, c.headingPath, c.heading, c.body);
302
+ this.prep("INSERT INTO chunks(root,path,chunk_id,doc_type,parent_chunk_id,level,body_hash,heading_path,heading,body,start_line,end_line) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)")
303
+ .run(c.root, c.path, c.chunkId, c.docType, c.parentChunkId, c.level, c.bodyHash, c.headingPath, c.heading, c.body, c.startLine ?? null, c.endLine ?? null);
222
304
  }
223
305
  addNode(n) {
224
306
  this.db.prepare("INSERT INTO nodes(type,name,path) VALUES(?,?,?) ON CONFLICT(type,name) DO UPDATE SET path=COALESCE(excluded.path, nodes.path)").run(n.type, n.name, n.path);
@@ -230,11 +312,103 @@ export class SqliteFtsStore {
230
312
  return;
231
313
  this.db.prepare("INSERT OR IGNORE INTO edges(src,dst,rel,weight) VALUES(?,?,?,?)").run(src.id, dst.id, e.rel, e.weight ?? 1);
232
314
  }
315
+ /** Porter stems for raw tokens, computed by SQLite's OWN tokenizer so they
316
+ * match what FTS5 actually indexed. A raw token is NOT a usable key into the
317
+ * vocab table: FTS5 stores `collaps`, and no prefix range anchored at
318
+ * `collapsed` can reach a key that sorts BEFORE it. The helper tables live in
319
+ * `temp.`, so this works against a read-only main DB. */
320
+ stemReady = null;
321
+ stemCache = new Map();
322
+ stems(tokens) {
323
+ const out = new Map();
324
+ const missing = [...new Set(tokens.filter((t) => !this.stemCache.has(t)))];
325
+ if (this.stemReady === null) {
326
+ try {
327
+ this.db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS temp.kb_stem USING fts5(t, tokenize='porter unicode61')");
328
+ this.db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS temp.kb_stem_vocab USING fts5vocab(kb_stem, 'instance')");
329
+ this.stemReady = true;
330
+ }
331
+ catch {
332
+ this.stemReady = false;
333
+ }
334
+ }
335
+ if (this.stemReady && missing.length) {
336
+ try {
337
+ this.db.exec("DELETE FROM temp.kb_stem");
338
+ const ins = this.db.prepare("INSERT INTO temp.kb_stem(rowid, t) VALUES(?,?)");
339
+ missing.forEach((t, i) => ins.run(i + 1, t));
340
+ // 'instance' carries the source rowid, so each stem maps back to its token.
341
+ for (const r of this.db.prepare("SELECT term, doc FROM temp.kb_stem_vocab").all()) {
342
+ const tok = missing[(Number(r.doc) || 0) - 1];
343
+ if (tok !== undefined)
344
+ this.stemCache.set(tok, String(r.term));
345
+ }
346
+ }
347
+ catch { /* stemming unavailable → fall back to the raw token below */ }
348
+ }
349
+ for (const t of tokens)
350
+ out.set(t, this.stemCache.get(t) ?? t);
351
+ return out;
352
+ }
353
+ /** Corpus document frequency for raw tokens, via the fts5vocab shadow table.
354
+ * Keys are exact porter stems (see `stems()`), so df is exact rather than a
355
+ * prefix over-estimate. `fts5vocab` is a live view over the FTS index, but
356
+ * `dfCache` is not — it is dropped on `commit()`/`deleteByPath`, the points at
357
+ * which an index batch can have moved the counts. Falls back to df=0 when the
358
+ * vocab table cannot be created (e.g. a read-only DB). */
359
+ dfCache = new Map();
360
+ vocabReady = null;
361
+ documentFrequencies(tokens) {
362
+ const out = new Map();
363
+ const stem = this.stems(tokens);
364
+ const keys = [...new Set(tokens.map((t) => stem.get(t)))];
365
+ const missing = keys.filter((k) => !this.dfCache.has(k));
366
+ if (this.vocabReady === null) {
367
+ try {
368
+ if (this.existingOnly) {
369
+ // A read-only handle must not write DDL into the saved index. Reuse the
370
+ // persistent view if a writer already made one; otherwise a TEMP view
371
+ // (connection-local; lives in the temp database, never in the saved file).
372
+ const persisted = this.db.prepare("SELECT 1 FROM sqlite_master WHERE type='table' AND name='chunks_vocab'").get();
373
+ if (!persisted) {
374
+ this.db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS temp.chunks_vocab_ro USING fts5vocab(main, chunks, 'row')");
375
+ this.vocabTable = "temp.chunks_vocab_ro";
376
+ }
377
+ }
378
+ else {
379
+ this.db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS chunks_vocab USING fts5vocab(chunks, 'row')");
380
+ }
381
+ this.vocabReady = true;
382
+ }
383
+ catch {
384
+ this.vocabReady = false;
385
+ }
386
+ }
387
+ if (this.vocabReady && missing.length) {
388
+ const ph = missing.map(() => "?").join(",");
389
+ try {
390
+ const rows = this.db.prepare(`SELECT term, doc FROM ${this.vocabTable} WHERE term IN (${ph})`).all(...missing);
391
+ for (const k of missing)
392
+ this.dfCache.set(k, 0); // absent term = df 0
393
+ for (const r of rows)
394
+ this.dfCache.set(String(r.term), Number(r.doc) || 0);
395
+ }
396
+ catch { /* vocab unusable → leave uncached, treated as df 0 below */ }
397
+ }
398
+ for (const t of tokens)
399
+ out.set(t, this.dfCache.get(stem.get(t)) ?? 0);
400
+ return out;
401
+ }
402
+ /** IDF weights for the given tokens over the current corpus. */
403
+ idf(tokens) {
404
+ const n = Math.max(1, this.counts().chunks);
405
+ const df = this.documentFrequencies(tokens);
406
+ const out = new Map();
407
+ for (const t of tokens)
408
+ out.set(t, Math.log(1 + n / (1 + (df.get(t) ?? 0))));
409
+ return out;
410
+ }
233
411
  search(query, opts = {}) {
234
- const expanded = expandQuery(query, opts);
235
- const m = toMatch(expanded);
236
- if (!m)
237
- return [];
238
412
  // Coerce numerics that get interpolated into SQL (bm25 weights, LIMIT) to
239
413
  // finite, bounded numbers — never trust raw config/flag values in a SQL string.
240
414
  const num = (v, dflt, min, max) => {
@@ -249,60 +423,157 @@ export class SqliteFtsStore {
249
423
  };
250
424
  const limit = num(opts.limit, 10, 1, 1000);
251
425
  const wantDedup = opts.dedup !== false;
252
- const fetch = Math.min(4000, wantDedup ? limit * 4 : limit);
253
- const where = ["chunks MATCH ?"];
254
- const args = [m];
255
- if (opts.root) {
256
- where.push("root = ?");
257
- args.push(opts.root);
258
- }
259
- if (opts.docType) {
260
- where.push("doc_type = ?");
261
- args.push(opts.docType);
262
- }
263
- // structured facet filters (opt-in; absent → no clause → identical query)
264
- const ff = buildFilterClauses(opts.filters, "chunks");
265
- where.push(...ff.clauses);
266
- args.push(...ff.args);
267
- const sql = `SELECT root, path, chunk_id chunkId, doc_type docType, body_hash bodyHash,
426
+ const wantSourceDedup = opts.sourceDedup !== false;
427
+ // Coverage rerank is opt-IN: measured a net regression on the bundled
428
+ // fixtures. See openspec/changes/fix-kb-search-retrieval-quality/measurements.md.
429
+ const wantCoverage = opts.coverageRerank === true;
430
+ // Source dedup collapses many sections of one file into one slot, so a pool
431
+ // sized at `limit` would starve the page — fetch a multiple of `limit`
432
+ // (design D2), still bounded by the pre-existing 4000 ceiling.
433
+ const fetch = Math.min(4000, wantSourceDedup ? limit * 6 : wantDedup ? limit * 4 : limit);
434
+ const qterms = tokenize(query);
435
+ // --- one BM25 pass, optionally restricted to a doc-type lane -------------
436
+ const pass = (match, docType, depth = fetch) => {
437
+ const where = ["chunks MATCH ?"];
438
+ const args = [match];
439
+ if (opts.root) {
440
+ where.push("root = ?");
441
+ args.push(opts.root);
442
+ }
443
+ if (docType) {
444
+ where.push("doc_type = ?");
445
+ args.push(docType);
446
+ }
447
+ // structured facet filters (opt-in; absent → no clause → identical query)
448
+ const ff = buildFilterClauses(opts.filters, "chunks");
449
+ where.push(...ff.clauses);
450
+ args.push(...ff.args);
451
+ const sql = `SELECT root, path, chunk_id chunkId, doc_type docType, body_hash bodyHash,
268
452
  parent_chunk_id parentChunkId, heading_path headingPath, heading, body,
269
- bm25(chunks, 0,0,0,0,0,0,0, ${w.headingPath}, ${w.heading}, ${w.body}) score,
453
+ bm25(chunks, 0,0,0,0,0,0,0, ${w.headingPath}, ${w.heading}, ${w.body}, 0,0) score,
270
454
  snippet(chunks, 9, '[', ']', ' … ', 12) snippet
271
- FROM chunks WHERE ${where.join(" AND ")} ORDER BY score LIMIT ${fetch}`;
272
- const rows = this.db.prepare(sql).all(...args);
273
- // bodies for proximity + MMR (dropped before returning)
455
+ FROM chunks WHERE ${where.join(" AND ")} ORDER BY score LIMIT ${depth}`;
456
+ return this.db.prepare(sql).all(...args);
457
+ };
458
+ // --- query expansion ------------------------------------------------------
459
+ // PRF is engine-side (design D4) and is applied ONLY with coverage rerank on:
460
+ // expanding an OR-query deepens the very dilution the rerank exists to cure
461
+ // (measured: PRF alone P@5 0.366 → 0.297).
462
+ const mode = opts.queryExpansion ?? "off";
463
+ let match = toMatch(expandQuery(query, opts));
464
+ if (!match)
465
+ return [];
466
+ let extraTerms = [];
467
+ if (mode === "prf" && wantCoverage) {
468
+ extraTerms = this.prfTerms(query, qterms, pass(match, opts.docType), opts);
469
+ if (extraTerms.length)
470
+ match = toMatch(`${query} ${extraTerms.join(" ")}`);
471
+ }
472
+ // --- lanes ----------------------------------------------------------------
473
+ // An `agents` chunk is 3.2% of the index and ~3x longer than a `doc` chunk,
474
+ // so BM25 length normalisation buries the per-file record layer ~30:1. The
475
+ // fix is engine-side: rank an `agents` lane separately and interleave a
476
+ // reserved share of the page (design D3). An explicit docType bypasses it.
477
+ const laneShare = opts.docType ? 0 : Math.min(1, Math.max(0, Number(opts.laneQuota ?? 0.5) || 0));
478
+ const mainRows = pass(match, opts.docType);
479
+ // Same depth as the main lane. A shallower pool would be cheaper only in
480
+ // theory: `doc_type` is an UNINDEXED FTS5 column, so this pass scans the
481
+ // whole match set regardless of LIMIT. It would, however, make
482
+ // `suppressedSections` depend on WHICH lane surfaced a source — an `agents`
483
+ // file with more matching sections than the shallow pool would under-report.
484
+ const agentsRows = laneShare > 0 ? pass(match, "agents") : [];
485
+ // The lead rule (design D2) compares each lane's best RAW BM25(+proximity)
486
+ // score. Neither MMR nor `coverageRerank` mutates `score` — they only
487
+ // reorder — and the capture below is a MIN over the lane, so it is
488
+ // reorder-invariant by construction. Reading `hits[0].score` instead would
489
+ // NOT be: `coverageRerank` fully re-sorts, so its head is not the
490
+ // best-scoring candidate. The min is what makes the position moot.
274
491
  const bodies = new Map();
275
- const qterms = tokenize(query);
276
- let hits = rows.map((r) => {
277
- bodies.set(r.chunkId, r.body);
278
- let score = r.score;
279
- if (opts.proximityBoost)
280
- score += proximityDelta(qterms, r.body);
281
- return { root: r.root, path: r.path, headingPath: r.headingPath, chunkId: r.chunkId, docType: r.docType, score, snippet: r.snippet, parentChunkId: r.parentChunkId };
282
- });
283
- if (wantDedup) {
284
- // exact-content collapse; prefer higher-priority root, then best score
285
- const prio = opts.rootPriority ?? {};
286
- const groups = new Map();
287
- for (const h of hits) {
288
- const key = rows.find((r) => r.chunkId === h.chunkId).bodyHash;
289
- (groups.get(key) ?? groups.set(key, []).get(key)).push(h);
492
+ const lane = (rows, captureRawBest) => {
493
+ let hits = rows.map((r) => {
494
+ bodies.set(r.chunkId, r.body);
495
+ let score = r.score;
496
+ if (opts.proximityBoost)
497
+ score += proximityDelta(qterms, r.body);
498
+ return { root: r.root, path: r.path, headingPath: r.headingPath, chunkId: r.chunkId, docType: r.docType, score, snippet: r.snippet, parentChunkId: r.parentChunkId };
499
+ });
500
+ if (wantDedup) {
501
+ // exact-content collapse; prefer higher-priority root, then best score.
502
+ // Runs FIRST so `akaPaths` is computed against the full candidate set —
503
+ // source dedup then operates over already-collapsed hits (design D1).
504
+ const prio = opts.rootPriority ?? {};
505
+ const byChunk = new Map(rows.map((r) => [r.chunkId, r]));
506
+ const groups = new Map();
507
+ for (const h of hits) {
508
+ const key = byChunk.get(h.chunkId).bodyHash;
509
+ (groups.get(key) ?? groups.set(key, []).get(key)).push(h);
510
+ }
511
+ hits = [];
512
+ for (const g of groups.values()) {
513
+ g.sort((a, b) => (prio[b.root] ?? 0) - (prio[a.root] ?? 0) || a.score - b.score);
514
+ const head = g[0];
515
+ if (g.length > 1)
516
+ head.akaPaths = g.slice(1).map((x) => x.path);
517
+ hits.push(head);
518
+ }
519
+ hits.sort((a, b) => a.score - b.score);
290
520
  }
291
- hits = [];
292
- for (const g of groups.values()) {
293
- g.sort((a, b) => (prio[b.root] ?? 0) - (prio[a.root] ?? 0) || a.score - b.score);
294
- const head = g[0];
295
- if (g.length > 1)
296
- head.akaPaths = g.slice(1).map((x) => x.path);
297
- hits.push(head);
521
+ if (wantSourceDedup) {
522
+ // One slot per (root, path); representative = best (lowest) BM25 score;
523
+ // the rest become a per-source count the render surfaces.
524
+ const groups = new Map();
525
+ for (const h of hits) {
526
+ const key = `${h.root}\u001f${h.path}`;
527
+ (groups.get(key) ?? groups.set(key, []).get(key)).push(h);
528
+ }
529
+ hits = [];
530
+ for (const g of groups.values()) {
531
+ g.sort((a, b) => a.score - b.score);
532
+ const head = g[0];
533
+ head.suppressedSections = g.length - 1;
534
+ hits.push(head);
535
+ }
536
+ hits.sort((a, b) => a.score - b.score);
298
537
  }
299
- hits.sort((a, b) => a.score - b.score);
538
+ if (captureRawBest && hits.length)
539
+ captureRawBest(hits.reduce((b, h) => Math.min(b, h.score), Number.POSITIVE_INFINITY));
540
+ // lexical MMR diversity (Tier A)
541
+ const div = opts.diversity;
542
+ if (div?.enabled)
543
+ hits = mmr(hits, bodies, div.lambda, fetch);
544
+ if (wantCoverage)
545
+ hits = this.coverageRerank(hits, bodies, qterms, extraTerms);
546
+ return hits;
547
+ };
548
+ // Lead-slot rule (change fix-kb-search-lane-composition, design D1/D2). The
549
+ // running-share quota cannot ever take slot 1 — `(0+1)/(0+1) <= share` is
550
+ // false for every share < 1 — so rank 1 gets its own knob. `0` = off.
551
+ const leadMargin = Math.min(1, Math.max(0, Number(opts.laneLeadMargin ?? 0) || 0));
552
+ let mainBest = Number.NaN;
553
+ let reservedBest = Number.NaN;
554
+ const main = lane(mainRows, (b) => { mainBest = b; });
555
+ let hits;
556
+ if (laneShare > 0 && agentsRows.length) {
557
+ const reserved = lane(agentsRows, (b) => { reservedBest = b; });
558
+ // Sign-safe relative margin: scores are negative and ascending-better, so
559
+ // a ratio test would invert across the sign boundary. At margin 1 this
560
+ // reduces to `r0 <= 0` — an unconditional lead, the documented degenerate
561
+ // endpoint.
562
+ // NOTE the decision/pick asymmetry under `coverageRerank` (default OFF):
563
+ // the decision reads the lane's raw BEST, while the pick is
564
+ // `reserved[0]` — the lane's own head, which a coverage re-sort may have
565
+ // moved off that best. Deliberate: the lane's internal ordering is the
566
+ // lane's business, and the rule only decides WHICH lane leads. Both
567
+ // knobs are opt-in, so the interaction is spot-checked (D6), not shipped.
568
+ const leadFirst = leadMargin > 0 &&
569
+ Number.isFinite(mainBest) &&
570
+ Number.isFinite(reservedBest) &&
571
+ reservedBest - mainBest <= leadMargin * Math.abs(mainBest);
572
+ hits = interleaveLanes(main, reserved, laneShare, limit, wantSourceDedup, leadFirst);
573
+ }
574
+ else {
575
+ hits = main.slice(0, limit);
300
576
  }
301
- // lexical MMR diversity (Tier A)
302
- const div = opts.diversity;
303
- if (div?.enabled)
304
- hits = mmr(hits, bodies, div.lambda, fetch);
305
- hits = hits.slice(0, limit);
306
577
  // optional cross-encoder rerank (Tier C): no-op without an injected reranker
307
578
  if (opts.rerank) {
308
579
  const rer = opts.reranker;
@@ -353,12 +624,81 @@ export class SqliteFtsStore {
353
624
  JOIN nodes t ON e.dst = t.id JOIN nodes n ON e.src = n.id WHERE t.name = ?`;
354
625
  return this.db.prepare(sql).all(node).map((r) => ({ type: r.type, name: r.name, path: r.path }));
355
626
  }
627
+ /** Fetch a chunk by path (+ optional section). A path-only fetch of a
628
+ * multi-chunk file returns the FIRST chunk plus a `suppressedSections` count
629
+ * — it must never silently hand back one arbitrary slice of N (design D7). */
356
630
  getChunk(root, path, headingPath) {
357
- const sql = headingPath
358
- ? "SELECT * FROM chunks WHERE root=? AND path=? AND heading_path=? LIMIT 1"
359
- : "SELECT * FROM chunks WHERE root=? AND path=? ORDER BY rowid LIMIT 1";
360
- const r = (headingPath ? this.db.prepare(sql).get(root, path, headingPath) : this.db.prepare(sql).get(root, path));
361
- return r ? rowToChunk(r) : null;
631
+ if (headingPath) {
632
+ const r = this.db.prepare("SELECT * FROM chunks WHERE root=? AND path=? AND heading_path=? LIMIT 1").get(root, path, headingPath);
633
+ return r ? rowToChunk(r) : null;
634
+ }
635
+ const r = this.db.prepare("SELECT * FROM chunks WHERE root=? AND path=? ORDER BY rowid LIMIT 1").get(root, path);
636
+ if (!r)
637
+ return null;
638
+ const n = this.db.prepare("SELECT COUNT(*) n FROM chunks WHERE root=? AND path=?").get(root, path).n;
639
+ return { ...rowToChunk(r), suppressedSections: Math.max(0, n - 1) };
640
+ }
641
+ /** All chunks of a file in document order — the non-truncating companion to a
642
+ * path-only `getChunk`. */
643
+ getChunks(root, path) {
644
+ return this.db.prepare("SELECT * FROM chunks WHERE root=? AND path=? ORDER BY rowid").all(root, path).map(rowToChunk);
645
+ }
646
+ /** Rerank by IDF-weighted coverage of the ORIGINAL query terms, BM25 as the
647
+ * tiebreak. PRF-appended terms count at half weight so expansion can never
648
+ * dominate the sort (design D4). */
649
+ coverageRerank(hits, bodies, qterms, extraTerms) {
650
+ if (!qterms.length || hits.length < 2)
651
+ return hits;
652
+ const all = [...qterms, ...extraTerms];
653
+ const idf = this.idf(all);
654
+ const cov = new Map();
655
+ for (const h of hits) {
656
+ const toks = new Set(tokenize(`${h.headingPath} ${bodies.get(h.chunkId) ?? ""}`));
657
+ let c = 0;
658
+ for (const t of qterms)
659
+ if (hasStem(toks, t))
660
+ c += idf.get(t) ?? 0;
661
+ for (const t of extraTerms)
662
+ if (hasStem(toks, t))
663
+ c += 0.5 * (idf.get(t) ?? 0);
664
+ cov.set(h.chunkId, c);
665
+ }
666
+ return [...hits].sort((a, b) => (cov.get(b.chunkId) - cov.get(a.chunkId)) || a.score - b.score);
667
+ }
668
+ /** RM3-style pseudo-relevance feedback: mine the top candidates of a first
669
+ * pass for terms absent from the query and below the corpus-frequency
670
+ * ceiling, rank by freq × IDF, return the top `terms` (design D4). */
671
+ prfTerms(query, qterms, firstPass, opts) {
672
+ const cfg = opts.prf ?? {};
673
+ const want = Math.max(0, Math.trunc(cfg.terms ?? 6));
674
+ const topK = Math.max(1, Math.trunc(cfg.topK ?? 10));
675
+ const ceiling = Math.min(1, Math.max(0, cfg.dfCeiling ?? 0.1));
676
+ // RM3 needs a feedback SET. When the first pass returns only a handful of
677
+ // candidates the "top-k relevant" docs are simply the whole corpus, so the
678
+ // mined terms carry no discriminating signal and only dilute the OR-query.
679
+ if (!want || firstPass.length < MIN_FEEDBACK_DOCS)
680
+ return [];
681
+ const seen = new Set(qterms);
682
+ const freq = new Map();
683
+ for (const r of firstPass.slice(0, topK)) {
684
+ for (const t of tokenize(`${r.headingPath} ${r.body}`)) {
685
+ if (seen.has(t))
686
+ continue;
687
+ freq.set(t, (freq.get(t) ?? 0) + 1);
688
+ }
689
+ }
690
+ // Bound the df round trip: only the most frequent feedback candidates.
691
+ const cands = [...freq.entries()].sort((a, b) => b[1] - a[1]).slice(0, 40).map(([t]) => t);
692
+ if (!cands.length)
693
+ return [];
694
+ const n = Math.max(1, this.counts().chunks);
695
+ const df = this.documentFrequencies(cands);
696
+ return cands
697
+ .filter((t) => (df.get(t) ?? 0) / n <= ceiling)
698
+ .map((t) => [t, (freq.get(t) ?? 0) * Math.log(1 + n / (1 + (df.get(t) ?? 0)))])
699
+ .sort((a, b) => b[1] - a[1])
700
+ .slice(0, want)
701
+ .map(([t]) => t);
362
702
  }
363
703
  getChunkById(root, chunkId) {
364
704
  const r = this.db.prepare("SELECT * FROM chunks WHERE root=? AND chunk_id=? LIMIT 1").get(root, chunkId);
@@ -374,29 +714,93 @@ export class SqliteFtsStore {
374
714
  };
375
715
  }
376
716
  }
717
+ /** Minimum first-pass candidates before PRF mining is meaningful (design D4). */
718
+ const MIN_FEEDBACK_DOCS = 5;
377
719
  const STOP = new Set("the for and how what with you your does can from that this are into use using get set all a an of to in on is be as it or by at do".split(" "));
378
720
  function tokenize(s) {
379
721
  return (s.toLowerCase().match(/[a-z0-9]{2,}/g) ?? []).filter((t) => !STOP.has(t));
380
722
  }
381
723
  function rowToChunk(r) {
382
- return { root: r.root, path: r.path, chunkId: r.chunk_id, headingPath: r.heading_path, heading: r.heading, level: r.level, parentChunkId: r.parent_chunk_id, docType: r.doc_type, body: r.body, bodyHash: r.body_hash };
724
+ const c = { root: r.root, path: r.path, chunkId: r.chunk_id, headingPath: r.heading_path, heading: r.heading, level: r.level, parentChunkId: r.parent_chunk_id, docType: r.doc_type, body: r.body, bodyHash: r.body_hash };
725
+ // Optional line anchors: absent (NULL) for markdown chunks — keep them off the
726
+ // object entirely so a markdown chunk round-trips byte-identically.
727
+ if (r.start_line != null)
728
+ c.startLine = Number(r.start_line);
729
+ if (r.end_line != null)
730
+ c.endLine = Number(r.end_line);
731
+ return c;
383
732
  }
384
- /** Query expansion (Tier C, default off). synonym = curated glossary;
385
- * agent = pass-through (caller reformulates); prf = lightweight lexical RM3.
733
+ /** Query expansion (Tier C). synonym = curated glossary; off/agent =
734
+ * pass-through (the caller already reformulated). `prf` is NOT handled here:
735
+ * it needs a first retrieval pass, so `search()` owns it (design D4).
386
736
  * No model dependency. */
387
737
  function expandQuery(query, opts) {
388
738
  const mode = opts.queryExpansion ?? "off";
389
- if (mode === "off" || mode === "agent")
390
- return query; // agent: caller already reformulated
391
- const terms = tokenize(query);
392
- if (mode === "synonym" && opts.synonyms) {
393
- const extra = [];
394
- for (const t of terms)
395
- for (const syn of opts.synonyms[t] ?? [])
396
- extra.push(syn);
397
- return extra.length ? query + " " + extra.join(" ") : query;
398
- }
399
- return query; // prf handled by callers via a second pass; engine no-ops here
739
+ if (mode !== "synonym" || !opts.synonyms)
740
+ return query;
741
+ const extra = [];
742
+ for (const t of tokenize(query))
743
+ for (const syn of opts.synonyms[t] ?? [])
744
+ extra.push(syn);
745
+ return extra.length ? `${query} ${extra.join(" ")}` : query;
746
+ }
747
+ /** Stem-tolerant membership: FTS5 indexes porter stems while `tokenize()`
748
+ * yields raw tokens, so `collapsed` must count as covering `collapse`.
749
+ * The prefix arm is bounded to a shared stem of at least STEM_MIN characters —
750
+ * an unbounded prefix test saturates coverage (every candidate "covers" every
751
+ * short term) and collapses the rerank into noise. */
752
+ const STEM_MIN = 4;
753
+ function hasStem(tokens, term) {
754
+ if (tokens.has(term))
755
+ return true;
756
+ if (term.length < STEM_MIN)
757
+ return false;
758
+ for (const t of tokens) {
759
+ if (t.length < STEM_MIN)
760
+ continue;
761
+ if (t.startsWith(term) || term.startsWith(t))
762
+ return true;
763
+ }
764
+ return false;
765
+ }
766
+ /** Interleave a reserved-share lane with the unrestricted lane (design D3).
767
+ * A source already emitted by either lane is never repeated, and a lane that
768
+ * runs dry yields its remaining slots to the other. */
769
+ function interleaveLanes(main, reserved, share, limit, dedupSources, leadFirst = false) {
770
+ const out = [];
771
+ const seen = new Set();
772
+ let mi = 0;
773
+ let ri = 0;
774
+ let taken = 0;
775
+ // The lanes overlap (the unrestricted lane also sees `agents` chunks), so a
776
+ // source taken by one lane is skipped in the other — but only when the caller
777
+ // asked for source dedup at all.
778
+ const next = (arr, i) => {
779
+ if (!dedupSources)
780
+ return i;
781
+ while (i < arr.length && seen.has(`${arr[i].root}\u001f${arr[i].path}`))
782
+ i++;
783
+ return i;
784
+ };
785
+ while (out.length < limit) {
786
+ mi = next(main, mi);
787
+ ri = next(reserved, ri);
788
+ const mHas = mi < main.length;
789
+ const rHas = ri < reserved.length;
790
+ if (!mHas && !rHas)
791
+ break;
792
+ // Slot 1 is decided by the lead rule; slots 2..N by the running share.
793
+ // The lead pick is an ordinary reserved take — it increments `taken` and
794
+ // populates `seen`, so slot 2 then reads `2/2 = 1 > share` and yields.
795
+ const wantReserved = rHas && (!mHas || (out.length === 0 && leadFirst) || (taken + 1) / (out.length + 1) <= share);
796
+ const pick = wantReserved ? reserved[ri++] : main[mi++];
797
+ if (wantReserved)
798
+ taken++;
799
+ if (dedupSources)
800
+ seen.add(`${pick.root}\u001f${pick.path}`);
801
+ out.push(pick);
802
+ }
803
+ return out;
400
804
  }
401
805
  /** Proximity/in-order boost: reward hits whose query terms appear close and in
402
806
  * query order in the body. Returns a delta to ADD to the bm25 score (negative