@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
@@ -0,0 +1,154 @@
1
+ // Traversal-safe archive extraction (change: harden-untrusted-content-ingestion,
2
+ // design D4 / B13). The archive is LISTED and validated first; any absolute, `..`,
3
+ // control-char or non-file (link/device/fifo) entry rejects the whole archive.
4
+ // Names and types come from two listings matched by line index — names are never
5
+ // parsed out of a verbose line, so ` -> ` and spaces in names are harmless.
6
+ // Fail closed: an unparseable listing, a count mismatch or a non-zero exit rejects.
7
+ import { execFile } from "node:child_process"; // ban:child_process-ok (kb package is self-contained; owns tar/zip listing + extract for the https resolver)
8
+ import { lstatSync, readdirSync, realpathSync } from "node:fs";
9
+ import { join, sep } from "node:path";
10
+ import { promisify } from "node:util";
11
+ export const DEFAULT_MAX_ENTRIES = 50_000;
12
+ export const DEFAULT_MAX_EXPANDED_BYTES = 256 * 1024 * 1024;
13
+ const execFileAsync = promisify(execFile);
14
+ /** Per-call bound: a hung tar/unzip must not pin a reindex job forever. */
15
+ const RUN_TIMEOUT_MS = 120_000;
16
+ const MAX_LISTING_BYTES = 256 * 1024 * 1024;
17
+ // Async on purpose (change: improve-kb-settings-sources-and-search, D6): a large archive must
18
+ // never stall the dashboard server's event loop. Env is read per call, not at import.
19
+ const env = () => ({ ...process.env, LC_ALL: "C" });
20
+ const run = async (cmd, args) => (await execFileAsync(cmd, args, { encoding: "latin1", env: env(), timeout: RUN_TIMEOUT_MS, maxBuffer: MAX_LISTING_BYTES })).stdout;
21
+ /** Decode tar's C-locale escapes (`\NNN`, `\t`, `\n`, `\\` …) to a latin1 byte string. */
22
+ function decodeTarName(raw) {
23
+ const simple = { a: "\x07", b: "\b", f: "\f", n: "\n", r: "\r", t: "\t", v: "\v", "\\": "\\", "'": "'", '"': '"' };
24
+ return raw.replace(/\\([0-7]{1,3}|.)/gs, (_m, c) => (/^[0-7]+$/.test(c) ? String.fromCharCode(parseInt(c, 8) & 0xff) : (simple[c] ?? `\\${c}`)));
25
+ }
26
+ function checkName(name, display) {
27
+ if (name.length === 0)
28
+ throw new Error(`unsafe archive entry: empty name`);
29
+ // eslint-disable-next-line no-control-regex
30
+ if (/[\x00-\x1f\x7f]/.test(name))
31
+ throw new Error(`unsafe archive entry (control character): ${JSON.stringify(display)}`);
32
+ if (name.startsWith("/") || name.startsWith("\\") || /^[A-Za-z]:/.test(name))
33
+ throw new Error(`unsafe archive entry (absolute path): ${display}`);
34
+ if (name.split(/[\\/]/).includes(".."))
35
+ throw new Error(`unsafe archive entry (.. segment): ${display}`);
36
+ }
37
+ const lines = (s) => {
38
+ const l = s.split("\n");
39
+ if (l.length && l[l.length - 1] === "")
40
+ l.pop();
41
+ return l;
42
+ };
43
+ /** Validate a tar archive (any compression the host tar auto-detects). Throws on any unsafe entry. */
44
+ async function validateTar(archive, maxEntries) {
45
+ const names = lines(await run("tar", ["-tf", archive]));
46
+ const verbose = lines(await run("tar", ["-tvf", archive]));
47
+ if (names.length > maxEntries)
48
+ throw new Error(`archive has too many entries (${names.length} > ${maxEntries})`);
49
+ if (names.length !== verbose.length)
50
+ throw new Error(`cannot validate archive: listing mismatch (${names.length} names vs ${verbose.length} entries)`);
51
+ for (let i = 0; i < names.length; i++) {
52
+ const v = verbose[i];
53
+ const type = v[0];
54
+ if (type !== "-" && type !== "d")
55
+ throw new Error(`unsafe archive entry (type '${type}'): ${names[i]}`);
56
+ // bsdtar renders a hardlink as `-… name link to target`; reject fail-closed.
57
+ if (v.includes(" link to ") || v.includes(" ==> "))
58
+ throw new Error(`unsafe archive entry (link): ${names[i]}`);
59
+ checkName(decodeTarName(names[i]), names[i]);
60
+ }
61
+ }
62
+ /** Validate a zip archive. Throws on any unsafe entry; returns `true` when it is empty. */
63
+ async function validateZip(archive, maxEntries) {
64
+ let header;
65
+ try {
66
+ header = await run("unzip", ["-Z", archive]);
67
+ }
68
+ catch (e) {
69
+ // `Empty zipfile.` exits 1 — recover its stdout and look at the entry count.
70
+ header = String(e.stdout ?? "");
71
+ if (!/number of entries: 0\b/.test(header))
72
+ throw e;
73
+ }
74
+ const hl = lines(header);
75
+ const sizeIdx = hl.findIndex((l) => l.startsWith("Zip file size:"));
76
+ const count = Number(/number of entries: (\d+)/.exec(hl[sizeIdx] ?? "")?.[1]);
77
+ if (sizeIdx < 0 || !Number.isInteger(count))
78
+ throw new Error("cannot validate archive: unparseable zip listing");
79
+ if (count > maxEntries)
80
+ throw new Error(`archive has too many entries (${count} > ${maxEntries})`);
81
+ if (count === 0)
82
+ return true; // `unzip -Z1` prints `Empty zipfile.` and exits 1
83
+ const names = lines(await run("unzip", ["-Z1", archive]));
84
+ const typeLines = hl.slice(sizeIdx + 1, sizeIdx + 1 + count);
85
+ if (names.length !== count || typeLines.length !== count)
86
+ throw new Error(`cannot validate archive: zip listing mismatch (${names.length} names, ${typeLines.length} types, ${count} entries)`);
87
+ for (let i = 0; i < count; i++) {
88
+ const type = typeLines[i][0];
89
+ if (type !== "-" && type !== "d")
90
+ throw new Error(`unsafe archive entry (type '${type}'): ${names[i]}`);
91
+ // Info-ZIP renders control characters as ^X (fail-closed for a literal `^A`).
92
+ if (/\^[@-_]/.test(names[i]))
93
+ throw new Error(`unsafe archive entry (control character): ${JSON.stringify(names[i])}`);
94
+ checkName(names[i], names[i]);
95
+ }
96
+ return false;
97
+ }
98
+ /**
99
+ * Stream the archive's decompressed content to a bounded buffer BEFORE extracting to disk:
100
+ * a decompression bomb (tiny download, huge expansion) aborts once `maxBytes` is exceeded.
101
+ */
102
+ async function assertExpandedWithin(cmd, args, maxBytes) {
103
+ try {
104
+ await execFileAsync(cmd, args, { encoding: "buffer", env: env(), timeout: RUN_TIMEOUT_MS, maxBuffer: maxBytes });
105
+ }
106
+ catch (e) {
107
+ // sync execFile reports ENOBUFS; the async one reports ERR_CHILD_PROCESS_STDIO_MAXBUFFER.
108
+ const code = e.code;
109
+ if (code === "ENOBUFS" || code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER")
110
+ throw new Error(`archive expands beyond the ${maxBytes}-byte limit`);
111
+ throw e;
112
+ }
113
+ }
114
+ /** Walk `out` and reject any symlink, escaping realpath or multiply-linked file (backstop, not the control). */
115
+ function backstopWalk(out) {
116
+ const root = realpathSync(out);
117
+ const walk = (dir) => {
118
+ for (const name of readdirSync(dir)) {
119
+ const p = join(dir, name);
120
+ const st = lstatSync(p);
121
+ if (st.isSymbolicLink())
122
+ throw new Error(`extracted symlink rejected: ${p}`);
123
+ const real = realpathSync(p);
124
+ if (real !== root && !real.startsWith(root + sep))
125
+ throw new Error(`extracted entry escapes destination: ${p}`);
126
+ if (st.isDirectory())
127
+ walk(p);
128
+ else if (st.isFile() && st.nlink > 1)
129
+ throw new Error(`extracted hardlink rejected: ${p}`);
130
+ }
131
+ };
132
+ walk(root);
133
+ }
134
+ /**
135
+ * Validate `archive`, then extract it into the (fresh, empty) `outDir`, then run
136
+ * the post-extraction backstop. Throws before extracting on any unsafe entry.
137
+ */
138
+ export async function extractArchiveSafely(kind, archive, outDir, limits = {}) {
139
+ const maxEntries = limits.maxEntries ?? DEFAULT_MAX_ENTRIES;
140
+ const maxBytes = limits.maxExpandedBytes ?? DEFAULT_MAX_EXPANDED_BYTES;
141
+ if (kind === "zip") {
142
+ const empty = await validateZip(archive, maxEntries);
143
+ if (!empty) {
144
+ await assertExpandedWithin("unzip", ["-p", archive], maxBytes);
145
+ await run("unzip", ["-o", "-q", archive, "-d", outDir]);
146
+ }
147
+ }
148
+ else {
149
+ await validateTar(archive, maxEntries);
150
+ await assertExpandedWithin("tar", ["-xOf", archive], maxBytes);
151
+ await run("tar", ["-xf", archive, "-C", outDir, "--no-same-owner"]);
152
+ }
153
+ backstopWalk(outDir);
154
+ }
package/dist/chunker.d.ts CHANGED
@@ -1,5 +1,8 @@
1
1
  import { type FmValue } from "./frontmatter.js";
2
2
  import type { Chunk, DocType } from "./types.js";
3
+ export declare const MIN_CHUNK_CHARS = 100;
4
+ export declare const MAX_CHUNK_CHARS = 4000;
5
+ export declare const sha: (s: string) => string;
3
6
  export interface ChunkInput {
4
7
  root: string;
5
8
  path: string;
package/dist/chunker.js CHANGED
@@ -3,9 +3,11 @@
3
3
  // (research §2.5). mdast (unified/remark) is the documented refinement.
4
4
  import { createHash } from "node:crypto";
5
5
  import { parseFrontmatter } from "./frontmatter.js";
6
- const MIN_CHUNK_CHARS = 100;
7
- const MAX_CHUNK_CHARS = 4000;
8
- const sha = (s) => createHash("sha256").update(s).digest("hex");
6
+ // Shared with the AsciiDoc chunker (adoc-chunker.ts) so both normalize with the
7
+ // SAME thresholds and id/hash scheme (chunk-contract parity, design D3).
8
+ export const MIN_CHUNK_CHARS = 100;
9
+ export const MAX_CHUNK_CHARS = 4000;
10
+ export const sha = (s) => createHash("sha256").update(s).digest("hex");
9
11
  export function chunkMarkdown(input) {
10
12
  const docType = input.docType ?? "doc";
11
13
  const { body: text, fm, parseFailed } = parseFrontmatter(input.text);
package/dist/cli.js CHANGED
@@ -3,17 +3,21 @@
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
5
  import { readFileSync } from "node:fs";
6
- import { resolve } from "node:path";
6
+ import { join, relative, resolve } from "node:path";
7
7
  import { frontmatterConfigHash, loadConfig } from "./config.js";
8
- import { agentsChain, doxInit, doxLint } from "./dox.js";
9
- import { evaluate } from "./eval.js";
8
+ import { agentsChain, doxInit, doxLint, listEmptyPurposeRows } from "./dox.js";
9
+ import { ackTargets, applyDecisions, buildWorkItems } from "./dox-triage.js";
10
+ import { evaluate, loadGolden } from "./eval.js";
10
11
  import { runIndexAtomic } from "./index-run.js";
11
12
  import { indexSource } from "./indexer.js";
12
13
  import { kbInit } from "./init.js";
13
14
  import { renderHits } from "./render.js";
15
+ import { searchOptsFromConfig } from "./search-opts.js";
14
16
  import { resolveAll } from "./sources.js";
15
17
  import { SCHEMA_VERSION, SqliteFtsStore } from "./sqlite-store.js";
18
+ import { readStaleness } from "./staleness.js";
16
19
  import { defaultPromptTrust } from "./trust.js";
20
+ import { enrichHits } from "./verdict.js";
17
21
  function parse(argv) {
18
22
  const f = { _: [] };
19
23
  for (let i = 0; i < argv.length; i++) {
@@ -84,7 +88,7 @@ async function runIndex(cfg, store, sources, force = false) {
84
88
  const eff = force || stale;
85
89
  let scanned = 0, changed = 0, deleted = 0, chunks = 0;
86
90
  for (const s of sources) {
87
- const st = await indexSource(store, { root: s.id, dir: s.dir }, { force: eff, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions, frontmatter: cfg.frontmatter });
91
+ const st = await indexSource(store, { root: s.id, dir: s.dir }, { force: eff, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions, frontmatter: cfg.frontmatter, respectGitignore: cfg.respectGitignore, cwd: cfg.cwd });
88
92
  scanned += st.scanned;
89
93
  changed += st.changed;
90
94
  deleted += st.deleted;
@@ -115,13 +119,23 @@ Usage:
115
119
  kb search "<query>" [--limit N] [--root id] [--doc-type doc|agents|source-md]
116
120
  [--expand-parent|--no-expand-parent] [--expand-graph] [--rerank]
117
121
  [--expand-query] [--json] [--no-reindex] [--source <dir>...] [--db <path>]
122
+ [--no-source-dedup] [--no-lane-quota] [--no-coverage-rerank] [--verdicts]
123
+ (--limit bounds distinct SOURCES, not chunks; --verdicts = opt-in trust labels)
118
124
  kb neighbors "<node>" [--depth N] [--rel child_of|links_to|references|has_tag]
119
125
  kb backlinks "<node>"
120
126
  kb get <path> [--section "<heading_path>"]
121
127
  kb agents <path> nearest AGENTS.md chain (root→nearest); --fallback-manifest
122
128
  kb dox init [--dry-run] scaffold a DOX AGENTS.md tree (path rows only)
123
- kb dox lint [--json] [--fix] audit DOX tree drift
129
+ kb dox lint [--json] [--fix] [--source-rows] audit DOX tree drift
130
+ (--source-rows also reports undocumented .ts/.tsx)
131
+ kb dox triage [--json] [--limit N] triage STALE rows vs the git diff since ack
132
+ [--apply <d.json> [--write]] [--ack <targets.json>]
133
+ kb dox describe --list [--json] [--dir <path>] list rows with an empty Purpose cell
124
134
  kb eval --golden <file.json> [--limit N] [--doc-type ...] [--no-reindex]
135
+ [--allow-zero] [--verbose] [--json]
136
+ (--golden accepts a bare array of {q, expect} or an {"items": [...]} object;
137
+ items outside the configured roots are reported as unreachable;
138
+ a run with 0 scored items or 0 recall exits non-zero unless --allow-zero)
125
139
  kb config show resolved config
126
140
  Global: --cwd <dir> --config <file>`;
127
141
  function main() {
@@ -177,16 +191,72 @@ function main() {
177
191
  return;
178
192
  }
179
193
  if (sub === "lint") {
180
- const r = doxLint({ cwd, json: !!flags.json, fix: !!flags.fix });
194
+ // --source-rows opts into the D9 source-file `missing` arm (off by default
195
+ // so an existing tree adopts it incrementally). See change: fix-kb-search-retrieval-quality.
196
+ const r = doxLint({ cwd, json: !!flags.json, fix: !!flags.fix, sourceFileRows: !!flags["source-rows"] });
181
197
  if (flags.json)
182
198
  console.log(JSON.stringify(r, null, 2));
183
- else
199
+ else {
200
+ // Coverage line (design D4, fix-dox-lint-blind-rows): a clean verdict
201
+ // must be distinguishable from an unread file.
202
+ console.log(`${r.filesScanned} files, ${r.rowsScanned} rows scanned, ${r.issues.length} findings`);
184
203
  for (const i of r.issues)
185
204
  console.log(`${i.kind}\t${i.agentsFile}${i.path ? "\t" + i.path : ""}\t${i.detail}`);
205
+ }
186
206
  if (r.issues.length)
187
207
  process.exit(1);
188
208
  return;
189
209
  }
210
+ if (sub === "triage") {
211
+ const stalenessFile = flags["staleness-file"] ?? join(cwd, ".pi/dashboard/kb/dox-staleness.json");
212
+ if (flags.apply) {
213
+ const decisions = JSON.parse(readFileSync(flags.apply, "utf8"));
214
+ const r = applyDecisions({ cwd, decisions, write: !!flags.write });
215
+ for (const s of r.skipped)
216
+ console.error(`skipped: ${s}`);
217
+ console.log(`${flags.write ? "applied" : "dry-run"}: ${r.rewritten} rewritten, ${r.kept} kept`);
218
+ if (!flags.write)
219
+ console.log("re-run with --write to apply");
220
+ return;
221
+ }
222
+ if (flags.ack) {
223
+ const targets = JSON.parse(readFileSync(flags.ack, "utf8"));
224
+ console.log(`re-acked ${ackTargets({ cwd, targets, stalenessFile })} entries`);
225
+ return;
226
+ }
227
+ const staleness = readStaleness(stalenessFile);
228
+ const items = buildWorkItems({ cwd, issues: doxLint({ cwd }).issues, staleness, limit: flags.limit ? Number(flags.limit) : undefined });
229
+ if (flags.json) {
230
+ console.log(JSON.stringify(items, null, 2));
231
+ return;
232
+ }
233
+ const noBase = items.filter((i) => !i.baselineFound);
234
+ console.log(`stale rows: ${items.length}`);
235
+ console.log(` with a recoverable diff : ${items.length - noBase.length}`);
236
+ console.log(` no baseline (needs eyes): ${noBase.length}`);
237
+ for (const i of items)
238
+ console.log(` ${i.baselineFound ? "diff" : "????"}\t${i.agentsFile}\t${i.row}`);
239
+ return;
240
+ }
241
+ if (sub === "describe") {
242
+ // --list is the only v1 op; accept it (and its absence) uniformly.
243
+ const r = listEmptyPurposeRows({ cwd, dir: typeof flags.dir === "string" ? flags.dir : undefined });
244
+ if (flags.json) {
245
+ console.log(JSON.stringify(r, null, 2));
246
+ return;
247
+ }
248
+ if (r.total === 0) {
249
+ console.log("no empty-purpose rows");
250
+ return;
251
+ }
252
+ console.log(`${r.total} empty-purpose row(s) across ${r.groups.length} AGENTS.md file(s)`);
253
+ for (const g of r.groups) {
254
+ console.log(g.agentsPath);
255
+ for (const s of g.subjects)
256
+ console.log(` ${s}`);
257
+ }
258
+ return;
259
+ }
190
260
  console.error(`unknown dox subcommand: ${sub}`);
191
261
  process.exit(2);
192
262
  }
@@ -214,7 +284,7 @@ async function runCmd(cmd, flags) {
214
284
  const s = await runIndexAtomic({
215
285
  dbPath: cfg.dbAbsPath,
216
286
  sources: sources.map((x) => ({ id: x.id, dir: x.dir })),
217
- indexOpts: { force: !!flags.force, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions, frontmatter: cfg.frontmatter },
287
+ indexOpts: { force: !!flags.force, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions, frontmatter: cfg.frontmatter, respectGitignore: cfg.respectGitignore, cwd: cfg.cwd },
218
288
  facetConfigHash: frontmatterConfigHash(cfg.frontmatter),
219
289
  explicit,
220
290
  });
@@ -234,20 +304,31 @@ async function runCmd(cmd, flags) {
234
304
  const docType = enumFlag(flags["doc-type"], ["doc", "agents", "source-md"], "--doc-type");
235
305
  if (!flags["no-reindex"])
236
306
  await runIndex(cfg, store, sources); // auto incremental freshness
307
+ // One shared mapping (design D2, fix-kb-eval-measurement-integrity): the
308
+ // CLI's flag-derived overrides are the ONLY difference from the tool.
237
309
  const so = {
238
310
  limit: limit ?? 10,
239
311
  root: flags.root,
240
312
  docType: docType,
241
- fieldWeights: cfg.ranking.fieldWeights,
242
- proximityBoost: cfg.ranking.proximityBoost,
243
- diversity: cfg.ranking.diversity,
244
- expandParent: flags["no-expand-parent"] ? false : (cfg.expand.parent || !!flags["expand-parent"]),
245
- expandGraph: cfg.expand.graph || !!flags["expand-graph"],
246
- rerank: cfg.rerank.enabled || !!flags.rerank,
247
- queryExpansion: flags["expand-query"] ? (cfg.queryExpansion.mode === "off" ? "synonym" : cfg.queryExpansion.mode) : cfg.queryExpansion.mode,
248
- rootPriority: Object.fromEntries(sources.map((s) => [s.id, s.priority])),
313
+ ...searchOptsFromConfig(cfg, {
314
+ sources,
315
+ overrides: {
316
+ sourceDedup: flags["no-source-dedup"] ? false : undefined,
317
+ laneQuota: flags["no-lane-quota"] ? 0 : undefined,
318
+ coverageRerank: flags["no-coverage-rerank"] ? false : undefined,
319
+ expandParent: flags["no-expand-parent"] ? false : flags["expand-parent"] ? true : undefined,
320
+ expandGraph: flags["expand-graph"] ? true : undefined,
321
+ rerank: flags.rerank ? true : undefined,
322
+ queryExpansion: flags["expand-query"] && cfg.queryExpansion.mode === "off" ? "synonym" : undefined,
323
+ },
324
+ }),
249
325
  };
250
326
  const hits = store.search(q, so);
327
+ // Opt-in trust verdicts (arm A): post-search enrichment OUTSIDE the store
328
+ // (design D10) — labels only, ordering untouched (D1); bodies from disk.
329
+ // See change: add-kb-trust-verdicts-and-search-guard.
330
+ if (flags.verdicts)
331
+ await enrichHits(hits, { cwd: cfg.cwd });
251
332
  if (flags.json)
252
333
  console.log(JSON.stringify(hits, null, 2));
253
334
  else if (hits.length)
@@ -271,7 +352,10 @@ async function runCmd(cmd, flags) {
271
352
  if (c)
272
353
  break;
273
354
  }
274
- console.log(c ? c.body : `(not found: ${flags._[1]})`);
355
+ // A path-only fetch of a multi-chunk file must never look like the whole
356
+ // file. See change: fix-kb-search-retrieval-quality (design D7).
357
+ const more = c?.suppressedSections ?? 0;
358
+ 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]})`);
275
359
  }
276
360
  else if (cmd === "eval") {
277
361
  const gf = flags.golden;
@@ -281,9 +365,43 @@ async function runCmd(cmd, flags) {
281
365
  }
282
366
  if (!flags["no-reindex"])
283
367
  await runIndex(cfg, store, sources);
284
- const golden = JSON.parse(readFileSync(resolve(cfg.cwd, gf), "utf8"));
285
- const m = evaluate(store, golden, { k: flags.limit ? Number(flags.limit) : 10, docType: flags["doc-type"] });
368
+ // Fixture contract (design D3): bare array | {items}, item shapes validated.
369
+ const golden = loadGolden(JSON.parse(readFileSync(resolve(cfg.cwd, gf), "utf8")), gf);
370
+ // Eval measures the TOOL path (spec R1): the extension's option set. Roots
371
+ // enable repo-relative expect normalization + reachability (design D4).
372
+ const roots = sources.map((s) => ({ id: s.id, relPrefix: relative(cfg.cwd, s.dir), dir: s.dir }));
373
+ // Same validation contract as `search`: reject garbage instead of
374
+ // passing an invalid limit to the backend or an unknown doc-type as an
375
+ // empty filter (CodeRabbit round, fix-kb-eval-measurement-integrity).
376
+ const limit = posInt(flags.limit, "--limit") ?? 10;
377
+ const docType = enumFlag(flags["doc-type"], ["doc", "agents", "source-md"], "--doc-type");
378
+ const m = evaluate(store, golden, {
379
+ k: limit,
380
+ docType: docType,
381
+ verbose: !!flags.verbose,
382
+ roots,
383
+ ...searchOptsFromConfig(cfg, { sources, overrides: { expandGraph: false, rerank: false } }),
384
+ });
286
385
  console.log(JSON.stringify(m, null, flags.json ? 2 : 0));
386
+ if (flags.verbose && m.unreachablePaths?.length) {
387
+ for (const p of m.unreachablePaths)
388
+ console.error(`[kb eval] unreachable: ${p}`);
389
+ }
390
+ // Vacuous-run guard (design D5): an all-zero score is a harness fault far
391
+ // more often than a retrieval fault. Metrics stay on stdout; the failure
392
+ // signal is the exit code. --allow-zero measures anyway.
393
+ const why = m.n === 0
394
+ ? golden.length === 0
395
+ ? "the golden fixture has no items"
396
+ : `all ${m.unreachable} of ${golden.length} golden items are unreachable under the configured roots (${roots.map((r) => r.relPrefix || ".").join(", ")}) — check root normalization`
397
+ : m["Recall@K"] === 0
398
+ ? `recall is 0 across all ${m.n} scored items — check the fixture shape and root normalization`
399
+ : null;
400
+ if (why) {
401
+ console.error(`[kb eval] VACUOUS RUN: ${why}. Re-run with --allow-zero to measure anyway.`);
402
+ if (!flags["allow-zero"])
403
+ process.exit(1);
404
+ }
287
405
  }
288
406
  else {
289
407
  console.error(`unknown command: ${cmd}\n\n${HELP}`);
package/dist/config.d.ts CHANGED
@@ -20,6 +20,25 @@ export interface RankingConfig {
20
20
  enabled: boolean;
21
21
  lambda: number;
22
22
  };
23
+ /** Collapse hits to one per `(root, path)` (design D1). */
24
+ sourceDedup: boolean;
25
+ /** Share of the page reserved for the `agents` doc-type lane, 0..1 (design D3).
26
+ * 0 disables the quota. SWEPT over the bundled fixtures — see
27
+ * openspec/changes/fix-kb-search-retrieval-quality/measurements.md. */
28
+ laneQuota: number;
29
+ /** Relative score margin that lets the reserved `agents` lane take result
30
+ * slot 1, 0..1 (change fix-kb-search-lane-composition, design D2/D3).
31
+ * `0` disables the rule and restores the pre-change interleaving exactly.
32
+ * The running-share quota is structurally incapable of taking slot 1
33
+ * (`(0+1)/(0+1) <= share` is false for every share < 1), so rank 1 needs
34
+ * its own knob. Inert whenever there is no reserved lane: an explicit
35
+ * `doc_type` or `laneQuota: 0` zeroes `laneShare` at the call site, so
36
+ * `interleaveLanes` — and this rule inside it — is never reached. */
37
+ laneLeadMargin: number;
38
+ /** IDF-weighted coverage rerank over the candidate pool (design D4).
39
+ * Implemented, DEFAULT OFF: on the bundled fixtures it costs markdown-intent
40
+ * R@10 0.620 → 0.472 to buy source-intent 0.423 → 0.462, a net regression. */
41
+ coverageRerank: boolean;
23
42
  }
24
43
  export interface ExpandConfig {
25
44
  parent: boolean;
@@ -32,6 +51,12 @@ export interface RerankConfig {
32
51
  }
33
52
  export interface QueryExpansionConfig {
34
53
  mode: "off" | "prf" | "synonym" | "agent";
54
+ /** RM3-style pseudo-relevance-feedback tuning (design D4). */
55
+ prf: {
56
+ terms: number;
57
+ topK: number;
58
+ dfCeiling: number;
59
+ };
35
60
  }
36
61
  export interface DirectoryLevelAgentsConfig {
37
62
  enabled: boolean;
@@ -43,6 +68,25 @@ export interface FrontmatterConfig {
43
68
  searchableKeys: string[];
44
69
  facetKeys: FacetKeyConfig[];
45
70
  }
71
+ /** kb search-guard enforcement mode (arm B). Shipped default `warn` (resolved
72
+ * at planning): a guard that is off does nothing about the measured 10:1
73
+ * under-use; `block` can refuse tool calls and is therefore NEVER a default —
74
+ * reachable only by explicit config. The KB_GUARD_MODE env override may
75
+ * select `off`/`warn` only (it can weaken, never enable blocking — D14). */
76
+ export type GuardMode = "off" | "warn" | "block";
77
+ export interface ReadDisciplineConfig {
78
+ guard: {
79
+ mode: GuardMode;
80
+ };
81
+ }
82
+ /** Per-turn DOX doctrine delivery (change: inject-dox-doctrine-and-describe).
83
+ * `inject: "kb"` appends the READ doctrine to the system prompt; `write`
84
+ * additionally appends the WRITE discipline. `inject: "off"` suppresses both
85
+ * and makes `write` inert. */
86
+ export interface DoctrineConfig {
87
+ inject: "kb" | "off";
88
+ write: boolean;
89
+ }
46
90
  export interface KbConfig {
47
91
  sources: SourceConfig[];
48
92
  roots?: Array<{
@@ -78,6 +122,8 @@ export interface KbConfig {
78
122
  directoryLevelAgents: DirectoryLevelAgentsConfig;
79
123
  frontmatter: FrontmatterConfig;
80
124
  doxEnforcement: boolean;
125
+ readDiscipline: ReadDisciplineConfig;
126
+ doctrine: DoctrineConfig;
81
127
  ranking: RankingConfig;
82
128
  expand: ExpandConfig;
83
129
  rerank: RerankConfig;
@@ -96,6 +142,9 @@ export interface ResolvedConfig extends KbConfig {
96
142
  allSourceSpecs: SourceConfig[];
97
143
  resolvedSources: ResolvedSource[];
98
144
  origin: "project" | "global" | "defaults";
145
+ /** Highest layer that supplied a `doctrine` KEY (`{}` counts) — distinct from
146
+ * `origin`, which is file-presence. Callers use it to detect first contact. */
147
+ doctrineSource: "project" | "global" | "none";
99
148
  }
100
149
  export declare const DEFAULTS: KbConfig;
101
150
  /** Stable hash of the frontmatter routing config. A change forces a full reindex
package/dist/config.js CHANGED
@@ -13,9 +13,11 @@ function expandTilde(p) {
13
13
  export const DEFAULTS = {
14
14
  sources: [],
15
15
  sourceCacheDir: "~/.pi/dashboard/kb/sources",
16
- include: ["**/*.md"],
16
+ // Widened for AsciiDoc together with the indexer walk regex + chunker dispatch
17
+ // (design D4) — widening one gate alone indexes zero extra files.
18
+ include: ["**/*.md", "**/*.adoc", "**/*.asciidoc"],
17
19
  exclude: ["**/node_modules/**", "**/archive/**"],
18
- extensions: [".md"],
20
+ extensions: [".md", ".adoc", ".asciidoc"],
19
21
  maxFileCount: null, // no cap
20
22
  maxDepth: null,
21
23
  respectGitignore: true,
@@ -32,15 +34,31 @@ export const DEFAULTS = {
32
34
  directoryLevelAgents: { enabled: true, claudeMd: true, mode: "pull", fallbackManifest: true },
33
35
  frontmatter: { searchableKeys: DEFAULT_SEARCHABLE_KEYS, facetKeys: DEFAULT_FACET_KEYS },
34
36
  doxEnforcement: false,
35
- ranking: { fieldWeights: { headingPath: 10, heading: 3, body: 1 }, proximityBoost: true, diversity: { enabled: true, lambda: 0.7 } },
37
+ readDiscipline: { guard: { mode: "warn" } },
38
+ doctrine: { inject: "kb", write: false },
39
+ ranking: {
40
+ fieldWeights: { headingPath: 10, heading: 3, body: 1 },
41
+ proximityBoost: true,
42
+ diversity: { enabled: true, lambda: 0.7 },
43
+ sourceDedup: true,
44
+ // 0.5 = the largest reserved share with NO markdown-intent regression
45
+ // (R@10 0.630 vs 0.611 unquota'd) while source-intent rises 0.317 → 0.500.
46
+ laneQuota: 0.5,
47
+ coverageRerank: false,
48
+ // Chosen by measurement over both golden sets — see
49
+ // openspec/changes/fix-kb-search-lane-composition/measurements.md.
50
+ laneLeadMargin: 0,
51
+ },
36
52
  expand: { parent: true, graph: false },
37
53
  rerank: { enabled: false, model: "ms-marco-MiniLM-L-6-v2", candidateK: 50 },
38
- queryExpansion: { mode: "off" },
54
+ // PRF is implemented engine-side but DEFAULT OFF: it is gated on coverage
55
+ // rerank (which measures as a net regression), and adds ~3x search latency.
56
+ queryExpansion: { mode: "off", prf: { terms: 6, topK: 10, dfCeiling: 0.1 } },
39
57
  dbPath: ".pi/dashboard/kb/index.db",
40
58
  };
41
59
  // Nested object keys that need one-level field fill-in (not wholesale replace),
42
60
  // so a partial `{ranking:{proximityBoost:false}}` keeps default fieldWeights/diversity.
43
- const NESTED_KEYS = ["chunking", "dedup", "graph", "directoryLevelAgents", "frontmatter", "ranking", "expand", "rerank", "queryExpansion"];
61
+ const NESTED_KEYS = ["chunking", "dedup", "graph", "directoryLevelAgents", "frontmatter", "readDiscipline", "doctrine", "ranking", "expand", "rerank", "queryExpansion"];
44
62
  /** Stable hash of the frontmatter routing config. A change forces a full reindex
45
63
  * (design D6) since existing property rows/meta chunks reflect the old routing. */
46
64
  export function frontmatterConfigHash(fm) {
@@ -86,6 +104,22 @@ export function validateConfig(c, origin = "config") {
86
104
  throw err("dbPath must be a non-empty string");
87
105
  if (!/^(off|prf|synonym|agent)$/.test(merged.queryExpansion.mode))
88
106
  throw err(`queryExpansion.mode "${merged.queryExpansion.mode}" unknown`);
107
+ const gm = merged.readDiscipline?.guard?.mode;
108
+ if (gm !== undefined && !/^(off|warn|block)$/.test(gm))
109
+ throw err(`readDiscipline.guard.mode "${gm}" unknown (off | warn | block)`);
110
+ const doc = merged.doctrine;
111
+ if (!doc || typeof doc !== "object" || Array.isArray(doc))
112
+ throw err("doctrine must be an object ({ inject, write })");
113
+ if (doc.inject !== undefined && !/^(kb|off)$/.test(doc.inject))
114
+ throw err(`doctrine.inject "${doc.inject}" unknown (kb | off)`);
115
+ if (doc.write !== undefined && typeof doc.write !== "boolean")
116
+ throw err("doctrine.write must be a boolean");
117
+ const lq = merged.ranking.laneQuota;
118
+ if (typeof lq !== "number" || !Number.isFinite(lq) || lq < 0 || lq > 1)
119
+ throw err("ranking.laneQuota must be a number in [0,1]");
120
+ const llm = merged.ranking.laneLeadMargin;
121
+ if (typeof llm !== "number" || !Number.isFinite(llm) || llm < 0 || llm > 1)
122
+ throw err("ranking.laneLeadMargin must be a number in [0,1]");
89
123
  const fm = merged.frontmatter;
90
124
  if (!fm || !Array.isArray(fm.searchableKeys) || fm.searchableKeys.some((k) => typeof k !== "string"))
91
125
  throw err("frontmatter.searchableKeys must be a string array");
@@ -120,6 +154,9 @@ export function loadConfig(cwd, opts = {}) {
120
154
  const project = opts.configPath ? readJson(opts.configPath) : readJson(projectConfigPath(cwd));
121
155
  const global = readJson(globalConfigPath());
122
156
  const origin = project ? "project" : global ? "global" : "defaults";
157
+ // KEY-presence (a non-null object, `{}` included) — NOT file-presence. A
158
+ // project file holding only `readDiscipline` has recorded no doctrine choice.
159
+ const doctrineSource = project?.doctrine !== undefined ? "project" : global?.doctrine !== undefined ? "global" : "none";
123
160
  const merged = validateConfig(mergeConfig(DEFAULTS, global, project), origin);
124
161
  // legacy roots[] → filesystem sources
125
162
  const fromRoots = (merged.roots ?? []).map((r) => ({ kind: "filesystem", ref: r.path, priority: r.priority }));
@@ -132,5 +169,5 @@ export function loadConfig(cwd, opts = {}) {
132
169
  });
133
170
  const dbAbsPath = isAbsolute(merged.dbPath) ? merged.dbPath : resolve(cwd, merged.dbPath);
134
171
  const cacheDirAbs = expandTilde(merged.sourceCacheDir);
135
- return { ...merged, cwd, dbAbsPath, cacheDirAbs, allSourceSpecs, resolvedSources, origin };
172
+ return { ...merged, cwd, dbAbsPath, cacheDirAbs, allSourceSpecs, resolvedSources, origin, doctrineSource };
136
173
  }
@@ -0,0 +1,67 @@
1
+ import { type AckRecord } from "./staleness.js";
2
+ import { type DoxIssue } from "./dox.js";
3
+ export declare const ROW_RE: RegExp;
4
+ /** History window scanned for a blob matching the acked hash. */
5
+ export declare const DEFAULT_DEPTH = 60;
6
+ /** Per-item diff budget. Keeps a @fast subagent's context small and cheap. */
7
+ export declare const DIFF_CAP = 6000;
8
+ export interface DoxRow {
9
+ line: number;
10
+ path: string;
11
+ purpose: string;
12
+ }
13
+ export declare function parseRows(md: string): DoxRow[];
14
+ /** Replace one row's purpose cell. Byte-identical elsewhere; no-op if absent. */
15
+ export declare function replaceRowPurpose(md: string, rowPath: string, newPurpose: string): string;
16
+ export interface Baseline {
17
+ found: boolean;
18
+ commit: string | null;
19
+ diff: string;
20
+ reason: string | null;
21
+ }
22
+ export declare function resolveBaseline(opts: {
23
+ cwd: string;
24
+ file: string;
25
+ ackedSha: string;
26
+ depth?: number;
27
+ }): Baseline;
28
+ export interface WorkItem {
29
+ agentsFile: string;
30
+ row: string;
31
+ target: string;
32
+ purpose: string;
33
+ baseline: string | null;
34
+ baselineFound: boolean;
35
+ reason: string | null;
36
+ diff: string;
37
+ }
38
+ export declare function buildWorkItems(opts: {
39
+ cwd: string;
40
+ issues: DoxIssue[];
41
+ staleness: Record<string, AckRecord>;
42
+ depth?: number;
43
+ limit?: number;
44
+ }): WorkItem[];
45
+ export interface Decision {
46
+ agentsFile: string;
47
+ row: string;
48
+ verdict: "KEEP" | "REWRITE";
49
+ purpose?: string;
50
+ note?: string;
51
+ }
52
+ export interface ApplyResult {
53
+ rewritten: number;
54
+ kept: number;
55
+ skipped: string[];
56
+ }
57
+ export declare function applyDecisions(opts: {
58
+ cwd: string;
59
+ decisions: Decision[];
60
+ write?: boolean;
61
+ }): ApplyResult;
62
+ /** Re-acknowledge rows: record each target's sha256 + stat baseline (v2). */
63
+ export declare function ackTargets(opts: {
64
+ cwd: string;
65
+ targets: string[];
66
+ stalenessFile: string;
67
+ }): number;