@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.
- package/README.md +23 -0
- package/dist/cli.js +52 -5
- package/dist/config.d.ts +16 -0
- package/dist/config.js +16 -2
- package/dist/dox-triage.d.ts +66 -0
- package/dist/dox-triage.js +176 -0
- package/dist/dox.d.ts +24 -2
- package/dist/dox.js +145 -4
- package/dist/eval.d.ts +6 -0
- package/dist/eval.js +14 -0
- package/dist/indexer.d.ts +2 -1
- package/dist/indexer.js +2 -2
- package/dist/render.js +19 -2
- package/dist/sqlite-store.d.ts +33 -0
- package/dist/sqlite-store.js +345 -69
- package/dist/types.d.ts +19 -0
- package/package.json +3 -1
- package/src/cli.ts +46 -5
- package/src/config.ts +27 -2
- package/src/dox-triage.ts +223 -0
- package/src/dox.ts +141 -6
- package/src/eval.ts +19 -0
- package/src/indexer.ts +2 -2
- package/src/render.ts +18 -2
- package/src/sqlite-store.ts +317 -58
- package/src/types.ts +15 -0
- package/src/AGENTS.md +0 -23
package/dist/sqlite-store.js
CHANGED
|
@@ -110,6 +110,9 @@ export class SqliteFtsStore {
|
|
|
110
110
|
}
|
|
111
111
|
commit() {
|
|
112
112
|
this.db.exec("COMMIT");
|
|
113
|
+
// An index batch just changed the corpus; cached document frequencies (and
|
|
114
|
+
// therefore IDF) are stale. The fts5vocab view itself is live.
|
|
115
|
+
this.dfCache.clear();
|
|
113
116
|
}
|
|
114
117
|
rollback() {
|
|
115
118
|
try {
|
|
@@ -163,6 +166,7 @@ export class SqliteFtsStore {
|
|
|
163
166
|
return this.db.prepare("SELECT path FROM files WHERE root=?").all(root).map((r) => r.path);
|
|
164
167
|
}
|
|
165
168
|
deleteByPath(root, path) {
|
|
169
|
+
this.dfCache.clear();
|
|
166
170
|
// chunks includes the file's synthetic `:meta` chunk (same path) — removed here.
|
|
167
171
|
this.db.prepare("DELETE FROM chunks WHERE root=? AND path=?").run(root, path);
|
|
168
172
|
// outbound edges originate from this file's nodes; prune nodes owned by path then dangling edges
|
|
@@ -230,11 +234,91 @@ export class SqliteFtsStore {
|
|
|
230
234
|
return;
|
|
231
235
|
this.db.prepare("INSERT OR IGNORE INTO edges(src,dst,rel,weight) VALUES(?,?,?,?)").run(src.id, dst.id, e.rel, e.weight ?? 1);
|
|
232
236
|
}
|
|
237
|
+
/** Porter stems for raw tokens, computed by SQLite's OWN tokenizer so they
|
|
238
|
+
* match what FTS5 actually indexed. A raw token is NOT a usable key into the
|
|
239
|
+
* vocab table: FTS5 stores `collaps`, and no prefix range anchored at
|
|
240
|
+
* `collapsed` can reach a key that sorts BEFORE it. The helper tables live in
|
|
241
|
+
* `temp.`, so this works against a read-only main DB. */
|
|
242
|
+
stemReady = null;
|
|
243
|
+
stemCache = new Map();
|
|
244
|
+
stems(tokens) {
|
|
245
|
+
const out = new Map();
|
|
246
|
+
const missing = [...new Set(tokens.filter((t) => !this.stemCache.has(t)))];
|
|
247
|
+
if (this.stemReady === null) {
|
|
248
|
+
try {
|
|
249
|
+
this.db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS temp.kb_stem USING fts5(t, tokenize='porter unicode61')");
|
|
250
|
+
this.db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS temp.kb_stem_vocab USING fts5vocab(kb_stem, 'instance')");
|
|
251
|
+
this.stemReady = true;
|
|
252
|
+
}
|
|
253
|
+
catch {
|
|
254
|
+
this.stemReady = false;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
if (this.stemReady && missing.length) {
|
|
258
|
+
try {
|
|
259
|
+
this.db.exec("DELETE FROM temp.kb_stem");
|
|
260
|
+
const ins = this.db.prepare("INSERT INTO temp.kb_stem(rowid, t) VALUES(?,?)");
|
|
261
|
+
missing.forEach((t, i) => ins.run(i + 1, t));
|
|
262
|
+
// 'instance' carries the source rowid, so each stem maps back to its token.
|
|
263
|
+
for (const r of this.db.prepare("SELECT term, doc FROM temp.kb_stem_vocab").all()) {
|
|
264
|
+
const tok = missing[(Number(r.doc) || 0) - 1];
|
|
265
|
+
if (tok !== undefined)
|
|
266
|
+
this.stemCache.set(tok, String(r.term));
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
catch { /* stemming unavailable → fall back to the raw token below */ }
|
|
270
|
+
}
|
|
271
|
+
for (const t of tokens)
|
|
272
|
+
out.set(t, this.stemCache.get(t) ?? t);
|
|
273
|
+
return out;
|
|
274
|
+
}
|
|
275
|
+
/** Corpus document frequency for raw tokens, via the fts5vocab shadow table.
|
|
276
|
+
* Keys are exact porter stems (see `stems()`), so df is exact rather than a
|
|
277
|
+
* prefix over-estimate. `fts5vocab` is a live view over the FTS index, but
|
|
278
|
+
* `dfCache` is not — it is dropped on `commit()`/`deleteByPath`, the points at
|
|
279
|
+
* which an index batch can have moved the counts. Falls back to df=0 when the
|
|
280
|
+
* vocab table cannot be created (e.g. a read-only DB). */
|
|
281
|
+
dfCache = new Map();
|
|
282
|
+
vocabReady = null;
|
|
283
|
+
documentFrequencies(tokens) {
|
|
284
|
+
const out = new Map();
|
|
285
|
+
const stem = this.stems(tokens);
|
|
286
|
+
const keys = [...new Set(tokens.map((t) => stem.get(t)))];
|
|
287
|
+
const missing = keys.filter((k) => !this.dfCache.has(k));
|
|
288
|
+
if (this.vocabReady === null) {
|
|
289
|
+
try {
|
|
290
|
+
this.db.exec("CREATE VIRTUAL TABLE IF NOT EXISTS chunks_vocab USING fts5vocab(chunks, 'row')");
|
|
291
|
+
this.vocabReady = true;
|
|
292
|
+
}
|
|
293
|
+
catch {
|
|
294
|
+
this.vocabReady = false;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
if (this.vocabReady && missing.length) {
|
|
298
|
+
const ph = missing.map(() => "?").join(",");
|
|
299
|
+
try {
|
|
300
|
+
const rows = this.db.prepare(`SELECT term, doc FROM chunks_vocab WHERE term IN (${ph})`).all(...missing);
|
|
301
|
+
for (const k of missing)
|
|
302
|
+
this.dfCache.set(k, 0); // absent term = df 0
|
|
303
|
+
for (const r of rows)
|
|
304
|
+
this.dfCache.set(String(r.term), Number(r.doc) || 0);
|
|
305
|
+
}
|
|
306
|
+
catch { /* vocab unusable → leave uncached, treated as df 0 below */ }
|
|
307
|
+
}
|
|
308
|
+
for (const t of tokens)
|
|
309
|
+
out.set(t, this.dfCache.get(stem.get(t)) ?? 0);
|
|
310
|
+
return out;
|
|
311
|
+
}
|
|
312
|
+
/** IDF weights for the given tokens over the current corpus. */
|
|
313
|
+
idf(tokens) {
|
|
314
|
+
const n = Math.max(1, this.counts().chunks);
|
|
315
|
+
const df = this.documentFrequencies(tokens);
|
|
316
|
+
const out = new Map();
|
|
317
|
+
for (const t of tokens)
|
|
318
|
+
out.set(t, Math.log(1 + n / (1 + (df.get(t) ?? 0))));
|
|
319
|
+
return out;
|
|
320
|
+
}
|
|
233
321
|
search(query, opts = {}) {
|
|
234
|
-
const expanded = expandQuery(query, opts);
|
|
235
|
-
const m = toMatch(expanded);
|
|
236
|
-
if (!m)
|
|
237
|
-
return [];
|
|
238
322
|
// Coerce numerics that get interpolated into SQL (bm25 weights, LIMIT) to
|
|
239
323
|
// finite, bounded numbers — never trust raw config/flag values in a SQL string.
|
|
240
324
|
const num = (v, dflt, min, max) => {
|
|
@@ -249,60 +333,128 @@ export class SqliteFtsStore {
|
|
|
249
333
|
};
|
|
250
334
|
const limit = num(opts.limit, 10, 1, 1000);
|
|
251
335
|
const wantDedup = opts.dedup !== false;
|
|
252
|
-
const
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
336
|
+
const wantSourceDedup = opts.sourceDedup !== false;
|
|
337
|
+
// Coverage rerank is opt-IN: measured a net regression on the bundled
|
|
338
|
+
// fixtures. See openspec/changes/fix-kb-search-retrieval-quality/measurements.md.
|
|
339
|
+
const wantCoverage = opts.coverageRerank === true;
|
|
340
|
+
// Source dedup collapses many sections of one file into one slot, so a pool
|
|
341
|
+
// sized at `limit` would starve the page — fetch a multiple of `limit`
|
|
342
|
+
// (design D2), still bounded by the pre-existing 4000 ceiling.
|
|
343
|
+
const fetch = Math.min(4000, wantSourceDedup ? limit * 6 : wantDedup ? limit * 4 : limit);
|
|
344
|
+
const qterms = tokenize(query);
|
|
345
|
+
// --- one BM25 pass, optionally restricted to a doc-type lane -------------
|
|
346
|
+
const pass = (match, docType, depth = fetch) => {
|
|
347
|
+
const where = ["chunks MATCH ?"];
|
|
348
|
+
const args = [match];
|
|
349
|
+
if (opts.root) {
|
|
350
|
+
where.push("root = ?");
|
|
351
|
+
args.push(opts.root);
|
|
352
|
+
}
|
|
353
|
+
if (docType) {
|
|
354
|
+
where.push("doc_type = ?");
|
|
355
|
+
args.push(docType);
|
|
356
|
+
}
|
|
357
|
+
// structured facet filters (opt-in; absent → no clause → identical query)
|
|
358
|
+
const ff = buildFilterClauses(opts.filters, "chunks");
|
|
359
|
+
where.push(...ff.clauses);
|
|
360
|
+
args.push(...ff.args);
|
|
361
|
+
const sql = `SELECT root, path, chunk_id chunkId, doc_type docType, body_hash bodyHash,
|
|
268
362
|
parent_chunk_id parentChunkId, heading_path headingPath, heading, body,
|
|
269
363
|
bm25(chunks, 0,0,0,0,0,0,0, ${w.headingPath}, ${w.heading}, ${w.body}) score,
|
|
270
364
|
snippet(chunks, 9, '[', ']', ' … ', 12) snippet
|
|
271
|
-
FROM chunks WHERE ${where.join(" AND ")} ORDER BY score LIMIT ${
|
|
272
|
-
|
|
273
|
-
|
|
365
|
+
FROM chunks WHERE ${where.join(" AND ")} ORDER BY score LIMIT ${depth}`;
|
|
366
|
+
return this.db.prepare(sql).all(...args);
|
|
367
|
+
};
|
|
368
|
+
// --- query expansion ------------------------------------------------------
|
|
369
|
+
// PRF is engine-side (design D4) and is applied ONLY with coverage rerank on:
|
|
370
|
+
// expanding an OR-query deepens the very dilution the rerank exists to cure
|
|
371
|
+
// (measured: PRF alone P@5 0.366 → 0.297).
|
|
372
|
+
const mode = opts.queryExpansion ?? "off";
|
|
373
|
+
let match = toMatch(expandQuery(query, opts));
|
|
374
|
+
if (!match)
|
|
375
|
+
return [];
|
|
376
|
+
let extraTerms = [];
|
|
377
|
+
if (mode === "prf" && wantCoverage) {
|
|
378
|
+
extraTerms = this.prfTerms(query, qterms, pass(match, opts.docType), opts);
|
|
379
|
+
if (extraTerms.length)
|
|
380
|
+
match = toMatch(`${query} ${extraTerms.join(" ")}`);
|
|
381
|
+
}
|
|
382
|
+
// --- lanes ----------------------------------------------------------------
|
|
383
|
+
// An `agents` chunk is 3.2% of the index and ~3x longer than a `doc` chunk,
|
|
384
|
+
// so BM25 length normalisation buries the per-file record layer ~30:1. The
|
|
385
|
+
// fix is engine-side: rank an `agents` lane separately and interleave a
|
|
386
|
+
// reserved share of the page (design D3). An explicit docType bypasses it.
|
|
387
|
+
const laneShare = opts.docType ? 0 : Math.min(1, Math.max(0, Number(opts.laneQuota ?? 0.5) || 0));
|
|
388
|
+
const mainRows = pass(match, opts.docType);
|
|
389
|
+
// Same depth as the main lane. A shallower pool would be cheaper only in
|
|
390
|
+
// theory: `doc_type` is an UNINDEXED FTS5 column, so this pass scans the
|
|
391
|
+
// whole match set regardless of LIMIT. It would, however, make
|
|
392
|
+
// `suppressedSections` depend on WHICH lane surfaced a source — an `agents`
|
|
393
|
+
// file with more matching sections than the shallow pool would under-report.
|
|
394
|
+
const agentsRows = laneShare > 0 ? pass(match, "agents") : [];
|
|
274
395
|
const bodies = new Map();
|
|
275
|
-
const
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
const
|
|
289
|
-
|
|
396
|
+
const lane = (rows) => {
|
|
397
|
+
let hits = rows.map((r) => {
|
|
398
|
+
bodies.set(r.chunkId, r.body);
|
|
399
|
+
let score = r.score;
|
|
400
|
+
if (opts.proximityBoost)
|
|
401
|
+
score += proximityDelta(qterms, r.body);
|
|
402
|
+
return { root: r.root, path: r.path, headingPath: r.headingPath, chunkId: r.chunkId, docType: r.docType, score, snippet: r.snippet, parentChunkId: r.parentChunkId };
|
|
403
|
+
});
|
|
404
|
+
if (wantDedup) {
|
|
405
|
+
// exact-content collapse; prefer higher-priority root, then best score.
|
|
406
|
+
// Runs FIRST so `akaPaths` is computed against the full candidate set —
|
|
407
|
+
// source dedup then operates over already-collapsed hits (design D1).
|
|
408
|
+
const prio = opts.rootPriority ?? {};
|
|
409
|
+
const byChunk = new Map(rows.map((r) => [r.chunkId, r]));
|
|
410
|
+
const groups = new Map();
|
|
411
|
+
for (const h of hits) {
|
|
412
|
+
const key = byChunk.get(h.chunkId).bodyHash;
|
|
413
|
+
(groups.get(key) ?? groups.set(key, []).get(key)).push(h);
|
|
414
|
+
}
|
|
415
|
+
hits = [];
|
|
416
|
+
for (const g of groups.values()) {
|
|
417
|
+
g.sort((a, b) => (prio[b.root] ?? 0) - (prio[a.root] ?? 0) || a.score - b.score);
|
|
418
|
+
const head = g[0];
|
|
419
|
+
if (g.length > 1)
|
|
420
|
+
head.akaPaths = g.slice(1).map((x) => x.path);
|
|
421
|
+
hits.push(head);
|
|
422
|
+
}
|
|
423
|
+
hits.sort((a, b) => a.score - b.score);
|
|
290
424
|
}
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
const
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
425
|
+
if (wantSourceDedup) {
|
|
426
|
+
// One slot per (root, path); representative = best (lowest) BM25 score;
|
|
427
|
+
// the rest become a per-source count the render surfaces.
|
|
428
|
+
const groups = new Map();
|
|
429
|
+
for (const h of hits) {
|
|
430
|
+
const key = `${h.root}\u001f${h.path}`;
|
|
431
|
+
(groups.get(key) ?? groups.set(key, []).get(key)).push(h);
|
|
432
|
+
}
|
|
433
|
+
hits = [];
|
|
434
|
+
for (const g of groups.values()) {
|
|
435
|
+
g.sort((a, b) => a.score - b.score);
|
|
436
|
+
const head = g[0];
|
|
437
|
+
head.suppressedSections = g.length - 1;
|
|
438
|
+
hits.push(head);
|
|
439
|
+
}
|
|
440
|
+
hits.sort((a, b) => a.score - b.score);
|
|
298
441
|
}
|
|
299
|
-
|
|
442
|
+
// lexical MMR diversity (Tier A)
|
|
443
|
+
const div = opts.diversity;
|
|
444
|
+
if (div?.enabled)
|
|
445
|
+
hits = mmr(hits, bodies, div.lambda, fetch);
|
|
446
|
+
if (wantCoverage)
|
|
447
|
+
hits = this.coverageRerank(hits, bodies, qterms, extraTerms);
|
|
448
|
+
return hits;
|
|
449
|
+
};
|
|
450
|
+
const main = lane(mainRows);
|
|
451
|
+
let hits;
|
|
452
|
+
if (laneShare > 0 && agentsRows.length) {
|
|
453
|
+
hits = interleaveLanes(main, lane(agentsRows), laneShare, limit, wantSourceDedup);
|
|
454
|
+
}
|
|
455
|
+
else {
|
|
456
|
+
hits = main.slice(0, limit);
|
|
300
457
|
}
|
|
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
458
|
// optional cross-encoder rerank (Tier C): no-op without an injected reranker
|
|
307
459
|
if (opts.rerank) {
|
|
308
460
|
const rer = opts.reranker;
|
|
@@ -353,12 +505,81 @@ export class SqliteFtsStore {
|
|
|
353
505
|
JOIN nodes t ON e.dst = t.id JOIN nodes n ON e.src = n.id WHERE t.name = ?`;
|
|
354
506
|
return this.db.prepare(sql).all(node).map((r) => ({ type: r.type, name: r.name, path: r.path }));
|
|
355
507
|
}
|
|
508
|
+
/** Fetch a chunk by path (+ optional section). A path-only fetch of a
|
|
509
|
+
* multi-chunk file returns the FIRST chunk plus a `suppressedSections` count
|
|
510
|
+
* — it must never silently hand back one arbitrary slice of N (design D7). */
|
|
356
511
|
getChunk(root, path, headingPath) {
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
512
|
+
if (headingPath) {
|
|
513
|
+
const r = this.db.prepare("SELECT * FROM chunks WHERE root=? AND path=? AND heading_path=? LIMIT 1").get(root, path, headingPath);
|
|
514
|
+
return r ? rowToChunk(r) : null;
|
|
515
|
+
}
|
|
516
|
+
const r = this.db.prepare("SELECT * FROM chunks WHERE root=? AND path=? ORDER BY rowid LIMIT 1").get(root, path);
|
|
517
|
+
if (!r)
|
|
518
|
+
return null;
|
|
519
|
+
const n = this.db.prepare("SELECT COUNT(*) n FROM chunks WHERE root=? AND path=?").get(root, path).n;
|
|
520
|
+
return { ...rowToChunk(r), suppressedSections: Math.max(0, n - 1) };
|
|
521
|
+
}
|
|
522
|
+
/** All chunks of a file in document order — the non-truncating companion to a
|
|
523
|
+
* path-only `getChunk`. */
|
|
524
|
+
getChunks(root, path) {
|
|
525
|
+
return this.db.prepare("SELECT * FROM chunks WHERE root=? AND path=? ORDER BY rowid").all(root, path).map(rowToChunk);
|
|
526
|
+
}
|
|
527
|
+
/** Rerank by IDF-weighted coverage of the ORIGINAL query terms, BM25 as the
|
|
528
|
+
* tiebreak. PRF-appended terms count at half weight so expansion can never
|
|
529
|
+
* dominate the sort (design D4). */
|
|
530
|
+
coverageRerank(hits, bodies, qterms, extraTerms) {
|
|
531
|
+
if (!qterms.length || hits.length < 2)
|
|
532
|
+
return hits;
|
|
533
|
+
const all = [...qterms, ...extraTerms];
|
|
534
|
+
const idf = this.idf(all);
|
|
535
|
+
const cov = new Map();
|
|
536
|
+
for (const h of hits) {
|
|
537
|
+
const toks = new Set(tokenize(`${h.headingPath} ${bodies.get(h.chunkId) ?? ""}`));
|
|
538
|
+
let c = 0;
|
|
539
|
+
for (const t of qterms)
|
|
540
|
+
if (hasStem(toks, t))
|
|
541
|
+
c += idf.get(t) ?? 0;
|
|
542
|
+
for (const t of extraTerms)
|
|
543
|
+
if (hasStem(toks, t))
|
|
544
|
+
c += 0.5 * (idf.get(t) ?? 0);
|
|
545
|
+
cov.set(h.chunkId, c);
|
|
546
|
+
}
|
|
547
|
+
return [...hits].sort((a, b) => (cov.get(b.chunkId) - cov.get(a.chunkId)) || a.score - b.score);
|
|
548
|
+
}
|
|
549
|
+
/** RM3-style pseudo-relevance feedback: mine the top candidates of a first
|
|
550
|
+
* pass for terms absent from the query and below the corpus-frequency
|
|
551
|
+
* ceiling, rank by freq × IDF, return the top `terms` (design D4). */
|
|
552
|
+
prfTerms(query, qterms, firstPass, opts) {
|
|
553
|
+
const cfg = opts.prf ?? {};
|
|
554
|
+
const want = Math.max(0, Math.trunc(cfg.terms ?? 6));
|
|
555
|
+
const topK = Math.max(1, Math.trunc(cfg.topK ?? 10));
|
|
556
|
+
const ceiling = Math.min(1, Math.max(0, cfg.dfCeiling ?? 0.1));
|
|
557
|
+
// RM3 needs a feedback SET. When the first pass returns only a handful of
|
|
558
|
+
// candidates the "top-k relevant" docs are simply the whole corpus, so the
|
|
559
|
+
// mined terms carry no discriminating signal and only dilute the OR-query.
|
|
560
|
+
if (!want || firstPass.length < MIN_FEEDBACK_DOCS)
|
|
561
|
+
return [];
|
|
562
|
+
const seen = new Set(qterms);
|
|
563
|
+
const freq = new Map();
|
|
564
|
+
for (const r of firstPass.slice(0, topK)) {
|
|
565
|
+
for (const t of tokenize(`${r.headingPath} ${r.body}`)) {
|
|
566
|
+
if (seen.has(t))
|
|
567
|
+
continue;
|
|
568
|
+
freq.set(t, (freq.get(t) ?? 0) + 1);
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
// Bound the df round trip: only the most frequent feedback candidates.
|
|
572
|
+
const cands = [...freq.entries()].sort((a, b) => b[1] - a[1]).slice(0, 40).map(([t]) => t);
|
|
573
|
+
if (!cands.length)
|
|
574
|
+
return [];
|
|
575
|
+
const n = Math.max(1, this.counts().chunks);
|
|
576
|
+
const df = this.documentFrequencies(cands);
|
|
577
|
+
return cands
|
|
578
|
+
.filter((t) => (df.get(t) ?? 0) / n <= ceiling)
|
|
579
|
+
.map((t) => [t, (freq.get(t) ?? 0) * Math.log(1 + n / (1 + (df.get(t) ?? 0)))])
|
|
580
|
+
.sort((a, b) => b[1] - a[1])
|
|
581
|
+
.slice(0, want)
|
|
582
|
+
.map(([t]) => t);
|
|
362
583
|
}
|
|
363
584
|
getChunkById(root, chunkId) {
|
|
364
585
|
const r = this.db.prepare("SELECT * FROM chunks WHERE root=? AND chunk_id=? LIMIT 1").get(root, chunkId);
|
|
@@ -374,6 +595,8 @@ export class SqliteFtsStore {
|
|
|
374
595
|
};
|
|
375
596
|
}
|
|
376
597
|
}
|
|
598
|
+
/** Minimum first-pass candidates before PRF mining is meaningful (design D4). */
|
|
599
|
+
const MIN_FEEDBACK_DOCS = 5;
|
|
377
600
|
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
601
|
function tokenize(s) {
|
|
379
602
|
return (s.toLowerCase().match(/[a-z0-9]{2,}/g) ?? []).filter((t) => !STOP.has(t));
|
|
@@ -381,22 +604,75 @@ function tokenize(s) {
|
|
|
381
604
|
function rowToChunk(r) {
|
|
382
605
|
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 };
|
|
383
606
|
}
|
|
384
|
-
/** Query expansion (Tier C
|
|
385
|
-
*
|
|
607
|
+
/** Query expansion (Tier C). synonym = curated glossary; off/agent =
|
|
608
|
+
* pass-through (the caller already reformulated). `prf` is NOT handled here:
|
|
609
|
+
* it needs a first retrieval pass, so `search()` owns it (design D4).
|
|
386
610
|
* No model dependency. */
|
|
387
611
|
function expandQuery(query, opts) {
|
|
388
612
|
const mode = opts.queryExpansion ?? "off";
|
|
389
|
-
if (mode
|
|
390
|
-
return query;
|
|
391
|
-
const
|
|
392
|
-
|
|
393
|
-
const
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
613
|
+
if (mode !== "synonym" || !opts.synonyms)
|
|
614
|
+
return query;
|
|
615
|
+
const extra = [];
|
|
616
|
+
for (const t of tokenize(query))
|
|
617
|
+
for (const syn of opts.synonyms[t] ?? [])
|
|
618
|
+
extra.push(syn);
|
|
619
|
+
return extra.length ? `${query} ${extra.join(" ")}` : query;
|
|
620
|
+
}
|
|
621
|
+
/** Stem-tolerant membership: FTS5 indexes porter stems while `tokenize()`
|
|
622
|
+
* yields raw tokens, so `collapsed` must count as covering `collapse`.
|
|
623
|
+
* The prefix arm is bounded to a shared stem of at least STEM_MIN characters —
|
|
624
|
+
* an unbounded prefix test saturates coverage (every candidate "covers" every
|
|
625
|
+
* short term) and collapses the rerank into noise. */
|
|
626
|
+
const STEM_MIN = 4;
|
|
627
|
+
function hasStem(tokens, term) {
|
|
628
|
+
if (tokens.has(term))
|
|
629
|
+
return true;
|
|
630
|
+
if (term.length < STEM_MIN)
|
|
631
|
+
return false;
|
|
632
|
+
for (const t of tokens) {
|
|
633
|
+
if (t.length < STEM_MIN)
|
|
634
|
+
continue;
|
|
635
|
+
if (t.startsWith(term) || term.startsWith(t))
|
|
636
|
+
return true;
|
|
637
|
+
}
|
|
638
|
+
return false;
|
|
639
|
+
}
|
|
640
|
+
/** Interleave a reserved-share lane with the unrestricted lane (design D3).
|
|
641
|
+
* A source already emitted by either lane is never repeated, and a lane that
|
|
642
|
+
* runs dry yields its remaining slots to the other. */
|
|
643
|
+
function interleaveLanes(main, reserved, share, limit, dedupSources) {
|
|
644
|
+
const out = [];
|
|
645
|
+
const seen = new Set();
|
|
646
|
+
let mi = 0;
|
|
647
|
+
let ri = 0;
|
|
648
|
+
let taken = 0;
|
|
649
|
+
// The lanes overlap (the unrestricted lane also sees `agents` chunks), so a
|
|
650
|
+
// source taken by one lane is skipped in the other — but only when the caller
|
|
651
|
+
// asked for source dedup at all.
|
|
652
|
+
const next = (arr, i) => {
|
|
653
|
+
if (!dedupSources)
|
|
654
|
+
return i;
|
|
655
|
+
while (i < arr.length && seen.has(`${arr[i].root}\u001f${arr[i].path}`))
|
|
656
|
+
i++;
|
|
657
|
+
return i;
|
|
658
|
+
};
|
|
659
|
+
while (out.length < limit) {
|
|
660
|
+
mi = next(main, mi);
|
|
661
|
+
ri = next(reserved, ri);
|
|
662
|
+
const mHas = mi < main.length;
|
|
663
|
+
const rHas = ri < reserved.length;
|
|
664
|
+
if (!mHas && !rHas)
|
|
665
|
+
break;
|
|
666
|
+
// Take from the reserved lane while it is under its share of the page so far.
|
|
667
|
+
const wantReserved = rHas && (!mHas || (taken + 1) / (out.length + 1) <= share);
|
|
668
|
+
const pick = wantReserved ? reserved[ri++] : main[mi++];
|
|
669
|
+
if (wantReserved)
|
|
670
|
+
taken++;
|
|
671
|
+
if (dedupSources)
|
|
672
|
+
seen.add(`${pick.root}\u001f${pick.path}`);
|
|
673
|
+
out.push(pick);
|
|
674
|
+
}
|
|
675
|
+
return out;
|
|
400
676
|
}
|
|
401
677
|
/** Proximity/in-order boost: reward hits whose query terms appear close and in
|
|
402
678
|
* query order in the body. Returns a delta to ADD to the bm25 score (negative
|
package/dist/types.d.ts
CHANGED
|
@@ -11,6 +11,10 @@ export interface Chunk {
|
|
|
11
11
|
docType: DocType;
|
|
12
12
|
body: string;
|
|
13
13
|
bodyHash: string;
|
|
14
|
+
/** Further sections of this file NOT returned by this fetch. Set by a
|
|
15
|
+
* path-only `getChunk` so it can never silently truncate a multi-chunk file
|
|
16
|
+
* (design D7). Absent/0 = this is the whole story. */
|
|
17
|
+
suppressedSections?: number;
|
|
14
18
|
}
|
|
15
19
|
export interface GraphNode {
|
|
16
20
|
type: "file" | "heading" | "tag" | "entity";
|
|
@@ -32,6 +36,9 @@ export interface KbHit {
|
|
|
32
36
|
score: number;
|
|
33
37
|
snippet: string;
|
|
34
38
|
akaPaths?: string[];
|
|
39
|
+
/** Further matching sections of this same source collapsed by source-level
|
|
40
|
+
* dedup (design D1). 0 = this source matched exactly once. */
|
|
41
|
+
suppressedSections?: number;
|
|
35
42
|
parent?: {
|
|
36
43
|
headingPath: string;
|
|
37
44
|
} | null;
|
|
@@ -63,6 +70,18 @@ export interface SearchOpts {
|
|
|
63
70
|
root?: string;
|
|
64
71
|
docType?: DocType;
|
|
65
72
|
dedup?: boolean;
|
|
73
|
+
sourceDedup?: boolean;
|
|
74
|
+
/** Share of the result page reserved for `doc_type='agents'` (0..1). 0 disables
|
|
75
|
+
* the lane quota. Ignored when the caller passes an explicit `docType`. */
|
|
76
|
+
laneQuota?: number;
|
|
77
|
+
/** IDF-weighted coverage rerank (design D4). Opt-IN: default OFF, because it
|
|
78
|
+
* measured a net regression on the bundled fixtures. Gates PRF expansion. */
|
|
79
|
+
coverageRerank?: boolean;
|
|
80
|
+
prf?: {
|
|
81
|
+
terms?: number;
|
|
82
|
+
topK?: number;
|
|
83
|
+
dfCeiling?: number;
|
|
84
|
+
};
|
|
66
85
|
fieldWeights?: {
|
|
67
86
|
headingPath: number;
|
|
68
87
|
heading: number;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blackbelt-technology/pi-dashboard-kb",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"repository": {
|
|
5
5
|
"type": "git",
|
|
6
6
|
"url": "https://github.com/BlackBeltTechnology/pi-agent-dashboard",
|
|
@@ -30,6 +30,8 @@
|
|
|
30
30
|
"files": [
|
|
31
31
|
"dist",
|
|
32
32
|
"src",
|
|
33
|
+
"!**/AGENTS.md",
|
|
34
|
+
"!**/*.AGENTS.md",
|
|
33
35
|
"!src/__tests__"
|
|
34
36
|
],
|
|
35
37
|
"keywords": [
|
package/src/cli.ts
CHANGED
|
@@ -2,10 +2,11 @@
|
|
|
2
2
|
// kb CLI (Phase 1): index | search | neighbors | backlinks | get | config
|
|
3
3
|
// Run (dev): NODE_OPTIONS=--experimental-sqlite tsx src/cli.ts <cmd> ...
|
|
4
4
|
// Shipped bin builds to dist/cli.js (build step deferred).
|
|
5
|
-
import { readFileSync } from "node:fs";
|
|
6
|
-
import { resolve } from "node:path";
|
|
5
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
6
|
+
import { join, resolve } from "node:path";
|
|
7
7
|
import { frontmatterConfigHash, loadConfig, type ResolvedConfig, type ResolvedSource } from "./config.js";
|
|
8
8
|
import { agentsChain, doxInit, doxLint } from "./dox.js";
|
|
9
|
+
import { ackTargets, applyDecisions, buildWorkItems } from "./dox-triage.js";
|
|
9
10
|
import { evaluate, type GoldenItem } from "./eval.js";
|
|
10
11
|
import { runIndexAtomic } from "./index-run.js";
|
|
11
12
|
import { indexSource } from "./indexer.js";
|
|
@@ -108,12 +109,17 @@ Usage:
|
|
|
108
109
|
kb search "<query>" [--limit N] [--root id] [--doc-type doc|agents|source-md]
|
|
109
110
|
[--expand-parent|--no-expand-parent] [--expand-graph] [--rerank]
|
|
110
111
|
[--expand-query] [--json] [--no-reindex] [--source <dir>...] [--db <path>]
|
|
112
|
+
[--no-source-dedup] [--no-lane-quota] [--no-coverage-rerank]
|
|
113
|
+
(--limit bounds distinct SOURCES, not chunks)
|
|
111
114
|
kb neighbors "<node>" [--depth N] [--rel child_of|links_to|references|has_tag]
|
|
112
115
|
kb backlinks "<node>"
|
|
113
116
|
kb get <path> [--section "<heading_path>"]
|
|
114
117
|
kb agents <path> nearest AGENTS.md chain (root→nearest); --fallback-manifest
|
|
115
118
|
kb dox init [--dry-run] scaffold a DOX AGENTS.md tree (path rows only)
|
|
116
|
-
kb dox lint [--json] [--fix]
|
|
119
|
+
kb dox lint [--json] [--fix] [--source-rows] audit DOX tree drift
|
|
120
|
+
(--source-rows also reports undocumented .ts/.tsx)
|
|
121
|
+
kb dox triage [--json] [--limit N] triage STALE rows vs the git diff since ack
|
|
122
|
+
[--apply <d.json> [--write]] [--ack <targets.json>]
|
|
117
123
|
kb eval --golden <file.json> [--limit N] [--doc-type ...] [--no-reindex]
|
|
118
124
|
kb config show resolved config
|
|
119
125
|
Global: --cwd <dir> --config <file>`;
|
|
@@ -164,12 +170,39 @@ function main() {
|
|
|
164
170
|
return;
|
|
165
171
|
}
|
|
166
172
|
if (sub === "lint") {
|
|
167
|
-
|
|
173
|
+
// --source-rows opts into the D9 source-file `missing` arm (off by default
|
|
174
|
+
// so an existing tree adopts it incrementally). See change: fix-kb-search-retrieval-quality.
|
|
175
|
+
const r = doxLint({ cwd, json: !!flags.json, fix: !!flags.fix, sourceFileRows: !!flags["source-rows"] });
|
|
168
176
|
if (flags.json) console.log(JSON.stringify(r, null, 2));
|
|
169
177
|
else for (const i of r.issues) console.log(`${i.kind}\t${i.agentsFile}${i.path ? "\t" + i.path : ""}\t${i.detail}`);
|
|
170
178
|
if (r.issues.length) process.exit(1);
|
|
171
179
|
return;
|
|
172
180
|
}
|
|
181
|
+
if (sub === "triage") {
|
|
182
|
+
const stalenessFile = (flags["staleness-file"] as string) ?? join(cwd, ".pi/dashboard/kb/dox-staleness.json");
|
|
183
|
+
if (flags.apply) {
|
|
184
|
+
const decisions = JSON.parse(readFileSync(flags.apply as string, "utf8"));
|
|
185
|
+
const r = applyDecisions({ cwd, decisions, write: !!flags.write });
|
|
186
|
+
for (const s of r.skipped) console.error(`skipped: ${s}`);
|
|
187
|
+
console.log(`${flags.write ? "applied" : "dry-run"}: ${r.rewritten} rewritten, ${r.kept} kept`);
|
|
188
|
+
if (!flags.write) console.log("re-run with --write to apply");
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
if (flags.ack) {
|
|
192
|
+
const targets = JSON.parse(readFileSync(flags.ack as string, "utf8"));
|
|
193
|
+
console.log(`re-acked ${ackTargets({ cwd, targets, stalenessFile })} entries`);
|
|
194
|
+
return;
|
|
195
|
+
}
|
|
196
|
+
const staleness = existsSync(stalenessFile) ? JSON.parse(readFileSync(stalenessFile, "utf8")) : {};
|
|
197
|
+
const items = buildWorkItems({ cwd, issues: doxLint({ cwd }).issues, staleness, limit: flags.limit ? Number(flags.limit) : undefined });
|
|
198
|
+
if (flags.json) { console.log(JSON.stringify(items, null, 2)); return; }
|
|
199
|
+
const noBase = items.filter((i) => !i.baselineFound);
|
|
200
|
+
console.log(`stale rows: ${items.length}`);
|
|
201
|
+
console.log(` with a recoverable diff : ${items.length - noBase.length}`);
|
|
202
|
+
console.log(` no baseline (needs eyes): ${noBase.length}`);
|
|
203
|
+
for (const i of items) console.log(` ${i.baselineFound ? "diff" : "????"}\t${i.agentsFile}\t${i.row}`);
|
|
204
|
+
return;
|
|
205
|
+
}
|
|
173
206
|
console.error(`unknown dox subcommand: ${sub}`); process.exit(2);
|
|
174
207
|
}
|
|
175
208
|
|
|
@@ -220,6 +253,11 @@ async function runCmd(cmd: string, flags: Flags): Promise<void> {
|
|
|
220
253
|
fieldWeights: cfg.ranking.fieldWeights,
|
|
221
254
|
proximityBoost: cfg.ranking.proximityBoost,
|
|
222
255
|
diversity: cfg.ranking.diversity,
|
|
256
|
+
// `limit` bounds distinct SOURCES, not chunks. See change: fix-kb-search-retrieval-quality.
|
|
257
|
+
sourceDedup: flags["no-source-dedup"] ? false : cfg.ranking.sourceDedup,
|
|
258
|
+
laneQuota: flags["no-lane-quota"] ? 0 : cfg.ranking.laneQuota,
|
|
259
|
+
coverageRerank: flags["no-coverage-rerank"] ? false : cfg.ranking.coverageRerank,
|
|
260
|
+
prf: cfg.queryExpansion.prf,
|
|
223
261
|
expandParent: flags["no-expand-parent"] ? false : (cfg.expand.parent || !!flags["expand-parent"]),
|
|
224
262
|
expandGraph: cfg.expand.graph || !!flags["expand-graph"],
|
|
225
263
|
rerank: cfg.rerank.enabled || !!flags.rerank,
|
|
@@ -244,7 +282,10 @@ async function runCmd(cmd: string, flags: Flags): Promise<void> {
|
|
|
244
282
|
c = store.getChunk(s.id, flags._[1], flags.section as string | undefined);
|
|
245
283
|
if (c) break;
|
|
246
284
|
}
|
|
247
|
-
|
|
285
|
+
// A path-only fetch of a multi-chunk file must never look like the whole
|
|
286
|
+
// file. See change: fix-kb-search-retrieval-quality (design D7).
|
|
287
|
+
const more = c?.suppressedSections ?? 0;
|
|
288
|
+
console.log(c ? (more > 0 ? `${c.body}\n\n(+${more} more section${more === 1 ? "" : "s"} in this file — pass --section <headingPath> to fetch one)` : c.body) : `(not found: ${flags._[1]})`);
|
|
248
289
|
} else if (cmd === "eval") {
|
|
249
290
|
const gf = flags.golden as string | undefined;
|
|
250
291
|
if (!gf) { console.error("eval needs --golden <file.json>"); process.exit(2); }
|