@blackbelt-technology/pi-dashboard-kb 0.7.0 → 0.8.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.
@@ -111,6 +111,9 @@ export class SqliteFtsStore implements KbStore {
111
111
  }
112
112
  commit() {
113
113
  this.db.exec("COMMIT");
114
+ // An index batch just changed the corpus; cached document frequencies (and
115
+ // therefore IDF) are stale. The fts5vocab view itself is live.
116
+ this.dfCache.clear();
114
117
  }
115
118
  rollback() {
116
119
  try {
@@ -160,6 +163,7 @@ export class SqliteFtsStore implements KbStore {
160
163
  return (this.db.prepare("SELECT path FROM files WHERE root=?").all(root) as any[]).map((r) => r.path);
161
164
  }
162
165
  deleteByPath(root: string, path: string) {
166
+ this.dfCache.clear();
163
167
  // chunks includes the file's synthetic `:meta` chunk (same path) — removed here.
164
168
  this.db.prepare("DELETE FROM chunks WHERE root=? AND path=?").run(root, path);
165
169
  // outbound edges originate from this file's nodes; prune nodes owned by path then dangling edges
@@ -224,10 +228,84 @@ export class SqliteFtsStore implements KbStore {
224
228
  this.db.prepare("INSERT OR IGNORE INTO edges(src,dst,rel,weight) VALUES(?,?,?,?)").run(src.id, dst.id, e.rel, e.weight ?? 1);
225
229
  }
226
230
 
231
+ /** Porter stems for raw tokens, computed by SQLite's OWN tokenizer so they
232
+ * match what FTS5 actually indexed. A raw token is NOT a usable key into the
233
+ * vocab table: FTS5 stores `collaps`, and no prefix range anchored at
234
+ * `collapsed` can reach a key that sorts BEFORE it. The helper tables live in
235
+ * `temp.`, so this works against a read-only main DB. */
236
+ private stemReady: boolean | null = null;
237
+ private stemCache = new Map<string, string>();
238
+ private stems(tokens: string[]): Map<string, string> {
239
+ const out = new Map<string, string>();
240
+ const missing = [...new Set(tokens.filter((t) => !this.stemCache.has(t)))];
241
+ if (this.stemReady === null) {
242
+ try {
243
+ this.db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS temp.kb_stem USING fts5(t, tokenize='porter unicode61')");
244
+ this.db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS temp.kb_stem_vocab USING fts5vocab(kb_stem, 'instance')");
245
+ this.stemReady = true;
246
+ } catch {
247
+ this.stemReady = false;
248
+ }
249
+ }
250
+ if (this.stemReady && missing.length) {
251
+ try {
252
+ this.db.exec("DELETE FROM temp.kb_stem");
253
+ const ins = this.db.prepare("INSERT INTO temp.kb_stem(rowid, t) VALUES(?,?)");
254
+ missing.forEach((t, i) => ins.run(i + 1, t));
255
+ // 'instance' carries the source rowid, so each stem maps back to its token.
256
+ for (const r of this.db.prepare("SELECT term, doc FROM temp.kb_stem_vocab").all() as any[]) {
257
+ const tok = missing[(Number(r.doc) || 0) - 1];
258
+ if (tok !== undefined) this.stemCache.set(tok, String(r.term));
259
+ }
260
+ } catch { /* stemming unavailable → fall back to the raw token below */ }
261
+ }
262
+ for (const t of tokens) out.set(t, this.stemCache.get(t) ?? t);
263
+ return out;
264
+ }
265
+
266
+ /** Corpus document frequency for raw tokens, via the fts5vocab shadow table.
267
+ * Keys are exact porter stems (see `stems()`), so df is exact rather than a
268
+ * prefix over-estimate. `fts5vocab` is a live view over the FTS index, but
269
+ * `dfCache` is not — it is dropped on `commit()`/`deleteByPath`, the points at
270
+ * which an index batch can have moved the counts. Falls back to df=0 when the
271
+ * vocab table cannot be created (e.g. a read-only DB). */
272
+ private dfCache = new Map<string, number>();
273
+ private vocabReady: boolean | null = null;
274
+ private documentFrequencies(tokens: string[]): Map<string, number> {
275
+ const out = new Map<string, number>();
276
+ const stem = this.stems(tokens);
277
+ const keys = [...new Set(tokens.map((t) => stem.get(t) as string))];
278
+ const missing = keys.filter((k) => !this.dfCache.has(k));
279
+ if (this.vocabReady === null) {
280
+ try {
281
+ this.db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS chunks_vocab USING fts5vocab(chunks, 'row')");
282
+ this.vocabReady = true;
283
+ } catch {
284
+ this.vocabReady = false;
285
+ }
286
+ }
287
+ if (this.vocabReady && missing.length) {
288
+ const ph = missing.map(() => "?").join(",");
289
+ try {
290
+ const rows = this.db.prepare(`SELECT term, doc FROM chunks_vocab WHERE term IN (${ph})`).all(...missing) as any[];
291
+ for (const k of missing) this.dfCache.set(k, 0); // absent term = df 0
292
+ for (const r of rows) this.dfCache.set(String(r.term), Number(r.doc) || 0);
293
+ } catch { /* vocab unusable → leave uncached, treated as df 0 below */ }
294
+ }
295
+ for (const t of tokens) out.set(t, this.dfCache.get(stem.get(t) as string) ?? 0);
296
+ return out;
297
+ }
298
+
299
+ /** IDF weights for the given tokens over the current corpus. */
300
+ private idf(tokens: string[]): Map<string, number> {
301
+ const n = Math.max(1, this.counts().chunks);
302
+ const df = this.documentFrequencies(tokens);
303
+ const out = new Map<string, number>();
304
+ for (const t of tokens) out.set(t, Math.log(1 + n / (1 + (df.get(t) ?? 0))));
305
+ return out;
306
+ }
307
+
227
308
  search(query: string, opts: SearchOpts = {}): KbHit[] {
228
- const expanded = expandQuery(query, opts);
229
- const m = toMatch(expanded);
230
- if (!m) return [];
231
309
  // Coerce numerics that get interpolated into SQL (bm25 weights, LIMIT) to
232
310
  // finite, bounded numbers — never trust raw config/flag values in a SQL string.
233
311
  const num = (v: unknown, dflt: number, min: number, max: number): number => {
@@ -242,54 +320,123 @@ export class SqliteFtsStore implements KbStore {
242
320
  };
243
321
  const limit = num(opts.limit, 10, 1, 1000);
244
322
  const wantDedup = opts.dedup !== false;
245
- const fetch = Math.min(4000, wantDedup ? limit * 4 : limit);
246
- const where: string[] = ["chunks MATCH ?"];
247
- const args: any[] = [m];
248
- if (opts.root) { where.push("root = ?"); args.push(opts.root); }
249
- if (opts.docType) { where.push("doc_type = ?"); args.push(opts.docType); }
250
- // structured facet filters (opt-in; absent → no clause → identical query)
251
- const ff = buildFilterClauses(opts.filters, "chunks");
252
- where.push(...ff.clauses);
253
- args.push(...ff.args);
254
- const sql = `SELECT root, path, chunk_id chunkId, doc_type docType, body_hash bodyHash,
323
+ const wantSourceDedup = opts.sourceDedup !== false;
324
+ // Coverage rerank is opt-IN: measured a net regression on the bundled
325
+ // fixtures. See openspec/changes/fix-kb-search-retrieval-quality/measurements.md.
326
+ const wantCoverage = opts.coverageRerank === true;
327
+ // Source dedup collapses many sections of one file into one slot, so a pool
328
+ // sized at `limit` would starve the page — fetch a multiple of `limit`
329
+ // (design D2), still bounded by the pre-existing 4000 ceiling.
330
+ const fetch = Math.min(4000, wantSourceDedup ? limit * 6 : wantDedup ? limit * 4 : limit);
331
+ const qterms = tokenize(query);
332
+
333
+ // --- one BM25 pass, optionally restricted to a doc-type lane -------------
334
+ const pass = (match: string, docType?: string, depth = fetch): any[] => {
335
+ const where: string[] = ["chunks MATCH ?"];
336
+ const args: any[] = [match];
337
+ if (opts.root) { where.push("root = ?"); args.push(opts.root); }
338
+ if (docType) { where.push("doc_type = ?"); args.push(docType); }
339
+ // structured facet filters (opt-in; absent → no clause → identical query)
340
+ const ff = buildFilterClauses(opts.filters, "chunks");
341
+ where.push(...ff.clauses);
342
+ args.push(...ff.args);
343
+ const sql = `SELECT root, path, chunk_id chunkId, doc_type docType, body_hash bodyHash,
255
344
  parent_chunk_id parentChunkId, heading_path headingPath, heading, body,
256
345
  bm25(chunks, 0,0,0,0,0,0,0, ${w.headingPath}, ${w.heading}, ${w.body}) score,
257
346
  snippet(chunks, 9, '[', ']', ' … ', 12) snippet
258
- FROM chunks WHERE ${where.join(" AND ")} ORDER BY score LIMIT ${fetch}`;
259
- const rows = this.db.prepare(sql).all(...args) as any[];
347
+ FROM chunks WHERE ${where.join(" AND ")} ORDER BY score LIMIT ${depth}`;
348
+ return this.db.prepare(sql).all(...args) as any[];
349
+ };
350
+
351
+ // --- query expansion ------------------------------------------------------
352
+ // PRF is engine-side (design D4) and is applied ONLY with coverage rerank on:
353
+ // expanding an OR-query deepens the very dilution the rerank exists to cure
354
+ // (measured: PRF alone P@5 0.366 → 0.297).
355
+ const mode = opts.queryExpansion ?? "off";
356
+ let match = toMatch(expandQuery(query, opts));
357
+ if (!match) return [];
358
+ let extraTerms: string[] = [];
359
+ if (mode === "prf" && wantCoverage) {
360
+ extraTerms = this.prfTerms(query, qterms, pass(match, opts.docType), opts);
361
+ if (extraTerms.length) match = toMatch(`${query} ${extraTerms.join(" ")}`);
362
+ }
363
+
364
+ // --- lanes ----------------------------------------------------------------
365
+ // An `agents` chunk is 3.2% of the index and ~3x longer than a `doc` chunk,
366
+ // so BM25 length normalisation buries the per-file record layer ~30:1. The
367
+ // fix is engine-side: rank an `agents` lane separately and interleave a
368
+ // reserved share of the page (design D3). An explicit docType bypasses it.
369
+ const laneShare = opts.docType ? 0 : Math.min(1, Math.max(0, Number(opts.laneQuota ?? 0.5) || 0));
370
+ const mainRows = pass(match, opts.docType);
371
+ // Same depth as the main lane. A shallower pool would be cheaper only in
372
+ // theory: `doc_type` is an UNINDEXED FTS5 column, so this pass scans the
373
+ // whole match set regardless of LIMIT. It would, however, make
374
+ // `suppressedSections` depend on WHICH lane surfaced a source — an `agents`
375
+ // file with more matching sections than the shallow pool would under-report.
376
+ const agentsRows = laneShare > 0 ? pass(match, "agents") : [];
260
377
 
261
- // bodies for proximity + MMR (dropped before returning)
262
378
  const bodies = new Map<string, string>();
263
- const qterms = tokenize(query);
264
- let hits: KbHit[] = rows.map((r) => {
265
- bodies.set(r.chunkId, r.body);
266
- let score = r.score;
267
- if (opts.proximityBoost) score += proximityDelta(qterms, r.body);
268
- return { root: r.root, path: r.path, headingPath: r.headingPath, chunkId: r.chunkId, docType: r.docType, score, snippet: r.snippet, parentChunkId: r.parentChunkId } as KbHit & { parentChunkId: string | null };
269
- });
270
-
271
- if (wantDedup) {
272
- // exact-content collapse; prefer higher-priority root, then best score
273
- const prio = opts.rootPriority ?? {};
274
- const groups = new Map<string, KbHit[]>();
275
- for (const h of hits) {
276
- const key = (rows.find((r) => r.chunkId === h.chunkId) as any).bodyHash;
277
- (groups.get(key) ?? groups.set(key, []).get(key)!).push(h);
379
+ const lane = (rows: any[]): KbHit[] => {
380
+ let hits: KbHit[] = rows.map((r) => {
381
+ bodies.set(r.chunkId, r.body);
382
+ let score = r.score;
383
+ if (opts.proximityBoost) score += proximityDelta(qterms, r.body);
384
+ return { root: r.root, path: r.path, headingPath: r.headingPath, chunkId: r.chunkId, docType: r.docType, score, snippet: r.snippet, parentChunkId: r.parentChunkId } as KbHit & { parentChunkId: string | null };
385
+ });
386
+
387
+ if (wantDedup) {
388
+ // exact-content collapse; prefer higher-priority root, then best score.
389
+ // Runs FIRST so `akaPaths` is computed against the full candidate set —
390
+ // source dedup then operates over already-collapsed hits (design D1).
391
+ const prio = opts.rootPriority ?? {};
392
+ const byChunk = new Map<string, any>(rows.map((r) => [r.chunkId, r]));
393
+ const groups = new Map<string, KbHit[]>();
394
+ for (const h of hits) {
395
+ const key = byChunk.get(h.chunkId).bodyHash;
396
+ (groups.get(key) ?? groups.set(key, []).get(key)!).push(h);
397
+ }
398
+ hits = [];
399
+ for (const g of groups.values()) {
400
+ g.sort((a, b) => (prio[b.root] ?? 0) - (prio[a.root] ?? 0) || a.score - b.score);
401
+ const head = g[0];
402
+ if (g.length > 1) head.akaPaths = g.slice(1).map((x) => x.path);
403
+ hits.push(head);
404
+ }
405
+ hits.sort((a, b) => a.score - b.score);
278
406
  }
279
- hits = [];
280
- for (const g of groups.values()) {
281
- g.sort((a, b) => (prio[b.root] ?? 0) - (prio[a.root] ?? 0) || a.score - b.score);
282
- const head = g[0];
283
- if (g.length > 1) head.akaPaths = g.slice(1).map((x) => x.path);
284
- hits.push(head);
407
+
408
+ if (wantSourceDedup) {
409
+ // One slot per (root, path); representative = best (lowest) BM25 score;
410
+ // the rest become a per-source count the render surfaces.
411
+ const groups = new Map<string, KbHit[]>();
412
+ for (const h of hits) {
413
+ const key = `${h.root}\u001f${h.path}`;
414
+ (groups.get(key) ?? groups.set(key, []).get(key)!).push(h);
415
+ }
416
+ hits = [];
417
+ for (const g of groups.values()) {
418
+ g.sort((a, b) => a.score - b.score);
419
+ const head = g[0];
420
+ head.suppressedSections = g.length - 1;
421
+ hits.push(head);
422
+ }
423
+ hits.sort((a, b) => a.score - b.score);
285
424
  }
286
- hits.sort((a, b) => a.score - b.score);
287
- }
288
425
 
289
- // lexical MMR diversity (Tier A)
290
- const div = opts.diversity;
291
- if (div?.enabled) hits = mmr(hits, bodies, div.lambda, fetch);
292
- hits = hits.slice(0, limit);
426
+ // lexical MMR diversity (Tier A)
427
+ const div = opts.diversity;
428
+ if (div?.enabled) hits = mmr(hits, bodies, div.lambda, fetch);
429
+ if (wantCoverage) hits = this.coverageRerank(hits, bodies, qterms, extraTerms);
430
+ return hits;
431
+ };
432
+
433
+ const main = lane(mainRows);
434
+ let hits: KbHit[];
435
+ if (laneShare > 0 && agentsRows.length) {
436
+ hits = interleaveLanes(main, lane(agentsRows), laneShare, limit, wantSourceDedup);
437
+ } else {
438
+ hits = main.slice(0, limit);
439
+ }
293
440
 
294
441
  // optional cross-encoder rerank (Tier C): no-op without an injected reranker
295
442
  if (opts.rerank) {
@@ -340,12 +487,75 @@ export class SqliteFtsStore implements KbStore {
340
487
  JOIN nodes t ON e.dst = t.id JOIN nodes n ON e.src = n.id WHERE t.name = ?`;
341
488
  return (this.db.prepare(sql).all(node) as any[]).map((r) => ({ type: r.type, name: r.name, path: r.path }));
342
489
  }
490
+ /** Fetch a chunk by path (+ optional section). A path-only fetch of a
491
+ * multi-chunk file returns the FIRST chunk plus a `suppressedSections` count
492
+ * — it must never silently hand back one arbitrary slice of N (design D7). */
343
493
  getChunk(root: string, path: string, headingPath?: string): Chunk | null {
344
- const sql = headingPath
345
- ? "SELECT * FROM chunks WHERE root=? AND path=? AND heading_path=? LIMIT 1"
346
- : "SELECT * FROM chunks WHERE root=? AND path=? ORDER BY rowid LIMIT 1";
347
- const r = (headingPath ? this.db.prepare(sql).get(root, path, headingPath) : this.db.prepare(sql).get(root, path)) as any;
348
- return r ? rowToChunk(r) : null;
494
+ if (headingPath) {
495
+ const r = this.db.prepare("SELECT * FROM chunks WHERE root=? AND path=? AND heading_path=? LIMIT 1").get(root, path, headingPath) as any;
496
+ return r ? rowToChunk(r) : null;
497
+ }
498
+ const r = this.db.prepare("SELECT * FROM chunks WHERE root=? AND path=? ORDER BY rowid LIMIT 1").get(root, path) as any;
499
+ if (!r) return null;
500
+ const n = (this.db.prepare("SELECT COUNT(*) n FROM chunks WHERE root=? AND path=?").get(root, path) as any).n as number;
501
+ return { ...rowToChunk(r), suppressedSections: Math.max(0, n - 1) };
502
+ }
503
+
504
+ /** All chunks of a file in document order — the non-truncating companion to a
505
+ * path-only `getChunk`. */
506
+ getChunks(root: string, path: string): Chunk[] {
507
+ return (this.db.prepare("SELECT * FROM chunks WHERE root=? AND path=? ORDER BY rowid").all(root, path) as any[]).map(rowToChunk);
508
+ }
509
+
510
+ /** Rerank by IDF-weighted coverage of the ORIGINAL query terms, BM25 as the
511
+ * tiebreak. PRF-appended terms count at half weight so expansion can never
512
+ * dominate the sort (design D4). */
513
+ private coverageRerank(hits: KbHit[], bodies: Map<string, string>, qterms: string[], extraTerms: string[]): KbHit[] {
514
+ if (!qterms.length || hits.length < 2) return hits;
515
+ const all = [...qterms, ...extraTerms];
516
+ const idf = this.idf(all);
517
+ const cov = new Map<string, number>();
518
+ for (const h of hits) {
519
+ const toks = new Set(tokenize(`${h.headingPath} ${bodies.get(h.chunkId) ?? ""}`));
520
+ let c = 0;
521
+ for (const t of qterms) if (hasStem(toks, t)) c += idf.get(t) ?? 0;
522
+ for (const t of extraTerms) if (hasStem(toks, t)) c += 0.5 * (idf.get(t) ?? 0);
523
+ cov.set(h.chunkId, c);
524
+ }
525
+ return [...hits].sort((a, b) => (cov.get(b.chunkId)! - cov.get(a.chunkId)!) || a.score - b.score);
526
+ }
527
+
528
+ /** RM3-style pseudo-relevance feedback: mine the top candidates of a first
529
+ * pass for terms absent from the query and below the corpus-frequency
530
+ * ceiling, rank by freq × IDF, return the top `terms` (design D4). */
531
+ private prfTerms(query: string, qterms: string[], firstPass: any[], opts: SearchOpts): string[] {
532
+ const cfg = opts.prf ?? {};
533
+ const want = Math.max(0, Math.trunc(cfg.terms ?? 6));
534
+ const topK = Math.max(1, Math.trunc(cfg.topK ?? 10));
535
+ const ceiling = Math.min(1, Math.max(0, cfg.dfCeiling ?? 0.1));
536
+ // RM3 needs a feedback SET. When the first pass returns only a handful of
537
+ // candidates the "top-k relevant" docs are simply the whole corpus, so the
538
+ // mined terms carry no discriminating signal and only dilute the OR-query.
539
+ if (!want || firstPass.length < MIN_FEEDBACK_DOCS) return [];
540
+ const seen = new Set(qterms);
541
+ const freq = new Map<string, number>();
542
+ for (const r of firstPass.slice(0, topK)) {
543
+ for (const t of tokenize(`${r.headingPath} ${r.body}`)) {
544
+ if (seen.has(t)) continue;
545
+ freq.set(t, (freq.get(t) ?? 0) + 1);
546
+ }
547
+ }
548
+ // Bound the df round trip: only the most frequent feedback candidates.
549
+ const cands = [...freq.entries()].sort((a, b) => b[1] - a[1]).slice(0, 40).map(([t]) => t);
550
+ if (!cands.length) return [];
551
+ const n = Math.max(1, this.counts().chunks);
552
+ const df = this.documentFrequencies(cands);
553
+ return cands
554
+ .filter((t) => (df.get(t) ?? 0) / n <= ceiling)
555
+ .map((t) => [t, (freq.get(t) ?? 0) * Math.log(1 + n / (1 + (df.get(t) ?? 0)))] as const)
556
+ .sort((a, b) => b[1] - a[1])
557
+ .slice(0, want)
558
+ .map(([t]) => t);
349
559
  }
350
560
  getChunkById(root: string, chunkId: string): Chunk | null {
351
561
  const r = this.db.prepare("SELECT * FROM chunks WHERE root=? AND chunk_id=? LIMIT 1").get(root, chunkId) as any;
@@ -362,6 +572,9 @@ export class SqliteFtsStore implements KbStore {
362
572
  }
363
573
  }
364
574
 
575
+ /** Minimum first-pass candidates before PRF mining is meaningful (design D4). */
576
+ const MIN_FEEDBACK_DOCS = 5;
577
+
365
578
  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(" "));
366
579
  function tokenize(s: string): string[] {
367
580
  return (s.toLowerCase().match(/[a-z0-9]{2,}/g) ?? []).filter((t) => !STOP.has(t));
@@ -371,19 +584,65 @@ function rowToChunk(r: any): Chunk {
371
584
  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 };
372
585
  }
373
586
 
374
- /** Query expansion (Tier C, default off). synonym = curated glossary;
375
- * agent = pass-through (caller reformulates); prf = lightweight lexical RM3.
587
+ /** Query expansion (Tier C). synonym = curated glossary; off/agent =
588
+ * pass-through (the caller already reformulated). `prf` is NOT handled here:
589
+ * it needs a first retrieval pass, so `search()` owns it (design D4).
376
590
  * No model dependency. */
377
591
  function expandQuery(query: string, opts: SearchOpts): string {
378
592
  const mode = opts.queryExpansion ?? "off";
379
- if (mode === "off" || mode === "agent") return query; // agent: caller already reformulated
380
- const terms = tokenize(query);
381
- if (mode === "synonym" && opts.synonyms) {
382
- const extra: string[] = [];
383
- for (const t of terms) for (const syn of opts.synonyms[t] ?? []) extra.push(syn);
384
- return extra.length ? query + " " + extra.join(" ") : query;
385
- }
386
- return query; // prf handled by callers via a second pass; engine no-ops here
593
+ if (mode !== "synonym" || !opts.synonyms) return query;
594
+ const extra: string[] = [];
595
+ for (const t of tokenize(query)) for (const syn of opts.synonyms[t] ?? []) extra.push(syn);
596
+ return extra.length ? `${query} ${extra.join(" ")}` : query;
597
+ }
598
+
599
+ /** Stem-tolerant membership: FTS5 indexes porter stems while `tokenize()`
600
+ * yields raw tokens, so `collapsed` must count as covering `collapse`.
601
+ * The prefix arm is bounded to a shared stem of at least STEM_MIN characters —
602
+ * an unbounded prefix test saturates coverage (every candidate "covers" every
603
+ * short term) and collapses the rerank into noise. */
604
+ const STEM_MIN = 4;
605
+ function hasStem(tokens: Set<string>, term: string): boolean {
606
+ if (tokens.has(term)) return true;
607
+ if (term.length < STEM_MIN) return false;
608
+ for (const t of tokens) {
609
+ if (t.length < STEM_MIN) continue;
610
+ if (t.startsWith(term) || term.startsWith(t)) return true;
611
+ }
612
+ return false;
613
+ }
614
+
615
+ /** Interleave a reserved-share lane with the unrestricted lane (design D3).
616
+ * A source already emitted by either lane is never repeated, and a lane that
617
+ * runs dry yields its remaining slots to the other. */
618
+ function interleaveLanes(main: KbHit[], reserved: KbHit[], share: number, limit: number, dedupSources: boolean): KbHit[] {
619
+ const out: KbHit[] = [];
620
+ const seen = new Set<string>();
621
+ let mi = 0;
622
+ let ri = 0;
623
+ let taken = 0;
624
+ // The lanes overlap (the unrestricted lane also sees `agents` chunks), so a
625
+ // source taken by one lane is skipped in the other — but only when the caller
626
+ // asked for source dedup at all.
627
+ const next = (arr: KbHit[], i: number): number => {
628
+ if (!dedupSources) return i;
629
+ while (i < arr.length && seen.has(`${arr[i].root}\u001f${arr[i].path}`)) i++;
630
+ return i;
631
+ };
632
+ while (out.length < limit) {
633
+ mi = next(main, mi);
634
+ ri = next(reserved, ri);
635
+ const mHas = mi < main.length;
636
+ const rHas = ri < reserved.length;
637
+ if (!mHas && !rHas) break;
638
+ // Take from the reserved lane while it is under its share of the page so far.
639
+ const wantReserved = rHas && (!mHas || (taken + 1) / (out.length + 1) <= share);
640
+ const pick = wantReserved ? reserved[ri++] : main[mi++];
641
+ if (wantReserved) taken++;
642
+ if (dedupSources) seen.add(`${pick.root}\u001f${pick.path}`);
643
+ out.push(pick);
644
+ }
645
+ return out;
387
646
  }
388
647
 
389
648
  /** Proximity/in-order boost: reward hits whose query terms appear close and in
package/src/types.ts CHANGED
@@ -17,6 +17,10 @@ export interface Chunk {
17
17
  docType: DocType;
18
18
  body: string; // section text (breadcrumb is indexed via columns, not prepended)
19
19
  bodyHash: string; // sha256 of trimmed body (exact-content dedup)
20
+ /** Further sections of this file NOT returned by this fetch. Set by a
21
+ * path-only `getChunk` so it can never silently truncate a multi-chunk file
22
+ * (design D7). Absent/0 = this is the whole story. */
23
+ suppressedSections?: number;
20
24
  }
21
25
 
22
26
  export interface GraphNode {
@@ -40,6 +44,9 @@ export interface KbHit {
40
44
  score: number; // lower = more relevant (BM25 convention)
41
45
  snippet: string;
42
46
  akaPaths?: string[]; // duplicate copies collapsed by dedup
47
+ /** Further matching sections of this same source collapsed by source-level
48
+ * dedup (design D1). 0 = this source matched exactly once. */
49
+ suppressedSections?: number;
43
50
  parent?: { headingPath: string } | null; // small-to-big parent context (expand.parent); display-only, NOT a refetch key; non-recursive
44
51
  }
45
52
 
@@ -73,6 +80,14 @@ export interface SearchOpts {
73
80
  root?: string;
74
81
  docType?: DocType;
75
82
  dedup?: boolean; // exact-content collapse (default true)
83
+ sourceDedup?: boolean; // collapse to one hit per (root, path) (default true; design D1)
84
+ /** Share of the result page reserved for `doc_type='agents'` (0..1). 0 disables
85
+ * the lane quota. Ignored when the caller passes an explicit `docType`. */
86
+ laneQuota?: number;
87
+ /** IDF-weighted coverage rerank (design D4). Opt-IN: default OFF, because it
88
+ * measured a net regression on the bundled fixtures. Gates PRF expansion. */
89
+ coverageRerank?: boolean;
90
+ prf?: { terms?: number; topK?: number; dfCeiling?: number }; // PRF tuning (design D4)
76
91
  fieldWeights?: { headingPath: number; heading: number; body: number };
77
92
  rootPriority?: Record<string, number>; // root id → priority (higher = preferred on dedup)
78
93
  proximityBoost?: boolean; // Tier A: in-order/proximity aux ranker
package/src/AGENTS.md DELETED
@@ -1,23 +0,0 @@
1
- # DOX — packages/kb/src
2
-
3
- Files in this directory. One row per source file.
4
-
5
- | File | Purpose |
6
- |------|---------|
7
- | `chunker.ts` | Structural heading chunker. Fence-safe, breadcrumb-aware. Line-based fenced-code state machine. |
8
- | `cli.ts` | kb CLI. Commands init\|index\|search\|neighbors\|backlinks\|get\|agents\|dox\|eval\|config. Dev run NODE_OPTIONS=--experimental-sqlite tsx src/cli.ts. `index` routes through `runIndexAtomic` (index-run.ts) and does NOT `openStore` — opening pre-creates the DB husk. `search`/`eval` still `openStore` + auto-reindex. `search` non-json branch calls shared `renderHits(leading:"score")`. See change: harden-kb-index-failure-atomicity; slim-kb-search-output. |
9
- | `config.ts` | Config layering. project .pi/dashboard/knowledge_base.json → global ~/.pi/dashboard/knowledge_base.json → defaults. No file-count cap default. |
10
- | `dox.ts` | DOX tree. Directory-level AGENTS.md scaffold + audit. kb agents <path> nearest-applicable chain. Detect-don't-write: dox init/--fix fill PATH columns + prune orphans only. `over-threshold` lint splits two arms: `arm:"bytes"` (actionable — bytes > `AGENTS_BYTE_CAP` 30 KB, auto-injected per turn, remedy sidecar split) + `arm:"rows"` (informational — inline count > `ROW_CAP` 40, no per-turn cost, optional foldering). `countInlineRows(af)` counts INLINE rows only (excludes sidecar-pointer rows matching `/→ see \`<File>.AGENTS.md\`/`) — sibling to `parseRowPaths` (public export consumed by kb-extension; signature untouched, stays complete path list). Splitting a heavy row to its sidecar drops both byte + counted-row totals. `ROW_CAP`/`AGENTS_BYTE_CAP` numeric values unchanged. `isMdFile` excludes `*.AGENTS.md` sidecars + `*.agent.md` companions (both DOX index artifacts, not documentable source). `DEFAULT_EXCLUDE` skips build output (`out`) + electron bundled/vendored trees (`bundled-extensions`, `electron/resources/server`) + `.reverse-spec-scratch` (transient reverse-spec experiment output) — all gitignored, fs-walk-only, else bogus missing/companion rows; `server` scoped to `electron/resources/server` so real `server` source dirs stay indexed. `resolveRowPath(agentsDir,cwd,rp)` resolves rows relative to their OWN AGENTS.md dir, repo-root `cwd` fallback (nested AGENTS.md may document a file living at project root) before orphan. `parseRowPaths` + `doxLint` scan only rows under a `# DOX —` heading (prose tables like Subagent Routing ignored). `doxLint` `walkAgents` tests `DEFAULT_EXCLUDE` on the cwd-RELATIVE path (mirrors `walkFiles`) so running inside `.worktrees/` does not exclude the whole tree. `rowPaths`/staleness keyed cwd-relative. See change: split-components-agents-dedup-rollup. See change: fix-dox-lint-false-positives. See change: fold-oversized-agents-directories. |
11
- | `eval.ts` | Retrieval-quality eval. Scores search against golden set. Gates ranking changes. |
12
- | `index-run.ts` | Atomic `kb index` orchestration. `runIndexAtomic({dbPath,sources,indexOpts,explicit})` returns `IndexStats & {counts}` (counts read from the still-open store so `index` never re-`openStore`s). First index (no dbPath) builds into `<dbPath>.tmp-<pid>` + `rename()` on success (survives OOM/SIGKILL — real path only on success); incremental (dbPath exists) indexes in place (mid-run failure leaves prior DB valid & queryable). All-sources-missing + explicit-`--source`-missing throw BEFORE any store opens (no husk). `sweepOrphanTemps` unlinks stale `.tmp-*` but SKIPS a temp whose PID is a live process (concurrent peer's active build). See change: harden-kb-index-failure-atomicity. |
13
- | `index.ts` | Public API barrel for @blackbelt-technology/pi-dashboard-kb. Exports `renderHits` + `RenderOpts`. |
14
- | `indexer.ts` | Indexer. `indexSource` is ASYNC: walks source, mtime→sha256 change detection, structural chunking, Tier-1 graph extraction, BATCHED transactional upsert — commits + `await setImmediate` every `YIELD_EVERY`=100 files so the walk yields the event loop (a concurrent `/stats` reader observes `indexing`+live counts) and releases the WAL write lock; trades whole-walk atomicity for responsiveness (mid-walk throw leaves earlier batches committed; reindex idempotent). All callers must `await`. A source whose `dir` does not exist is skipped with `console.warn` (returns `missing:true`), not a thrown ENOENT — partial source set still indexes what exists. `docTypeOf` classifies `*.AGENTS.md` per-file index sidecars as `agents` doc_type (searchable; name != `AGENTS.md` so pi never auto-injects them). See change: split-components-agents-dedup-rollup; fix-kb-index-feedback; harden-kb-index-failure-atomicity. |
15
- | `init.ts` | kb init. Scaffolds + validates knowledge_base.json. --global writes global file. --force, --dry-run flags. gitignores dbPath. |
16
- | `migrate-file-index.ts` | One-time migration core. Re-homes `docs/file-index-<area>.md` purposes into per-dir `AGENTS.md` tree. Pure + testable. Exports `parseFileIndex`, `mergeIndex`, `planDirs`, `tier0Rows`, `renderAgentsMd`, `validateAuthored`, `finalRows`, types `IndexRow`, `FileEntry`, `DirPlan`, `AuthoredRow`. Classifies dirs tier 0 (all hits, deterministic) vs tier 1 (≥1 miss, needs subagent). |
17
- | `migrate-runner.ts` | Big-bang resumable runner for file-index → AGENTS.md migration (one-time; source splits since deleted). Owns plan, batching, grounding gate, idempotent per-dir write, checkpoint persistence. Exports `loadSplitTexts`, `buildDirPlans`, `groundingCheck`, `knownStems`, `makeBatches`, `subagentPrompt`, `parseAuthoredBatch`, `recordAuthored`, `writeDir`, `loadState`, `saveState`, `PACKAGES_ROOT_RE`. Drives `@fast` subagent fan-out for Tier-1 authoring. Rollup export (`exportRollup`/`treeRows`/`SPLIT_AREAS`) REMOVED — `docs/file-index*.md` retired, per-directory `AGENTS.md` tree is sole per-file record. See change: split-components-agents-dedup-rollup. See change: migrate-file-index-to-agents-tree. |
18
- | `node-sqlite.d.ts` | Ambient shim `declare module "node:sqlite"` (DatabaseSync + StatementSync surface used by `sqlite-store.ts`). Pins @types/node 20.x lacks `node:sqlite` typings (ship in >= 22.5) so root `tsc`/kb build fail TS2307; shim resolves without a dep bump. Delete when @types/node >= 22.5. See change: adopt-pi-074-080-features. |
19
- | `render.ts` | Shared hit renderer for CLI + kb_search tool. `renderHits(hits, { leading:"score"\|"rank", parentGlyph, multiline })`. Same fields/order both callers; differ on leading token (BM25 score vs 1-based rank ordinal), parent glyph, line structure. CLI opts byte-identical to legacy inline render. See change: slim-kb-search-output. |
20
- | `sources.ts` | Pluggable source resolvers. fs/npm/git/https → local dir. KB reads markdown only, never executes source. |
21
- | `sqlite-store.ts` | Default KbStore backend over node:sqlite. FTS5. WAL + `PRAGMA busy_timeout=5000` (concurrent reader waits for a batch commit, not `SQLITE_BUSY`). Zero runtime deps. Requires --experimental-sqlite. better-sqlite3 drop-in fallback. `readonly dbPath`. `finalizeRename(dest)`: TRUNCATE-checkpoint + close BEFORE `rename` (WAL ordering load-bearing), then drop stale sidecars. `closeAndUnlink()`: close + unlink db + `-wal`/`-shm` (failed first-index cleanup). `expandParent` collapses `h.parent` to `{ headingPath }` (dropped root/path/docType/chunkId/score/snippet — same-file dups/constants). See change: fix-kb-index-feedback; harden-kb-index-failure-atomicity; slim-kb-search-output. |
22
- | `trust.ts` | TOFU trust store for remote sources. fs sources skip trust. npm/git/https confirm on first fetch. Keyed by sha256(canonical(SourceSpec)). |
23
- | `types.ts` | KbStore interface + chunk types. Storage accessed only through KbStore. `KbHit.parent` narrowed to `{ headingPath } \| null` — display-only, non-recursive, NOT a refetch key. BREAKING public-type change. See change: slim-kb-search-output. |