@blackbelt-technology/pi-dashboard-kb 0.8.0 → 0.10.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 (124) hide show
  1. package/README.md +46 -0
  2. package/bin/kb.mjs +89 -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 +53 -5
  10. package/dist/cli.js +140 -37
  11. package/dist/config.d.ts +80 -0
  12. package/dist/config.js +157 -6
  13. package/dist/dox-row.d.ts +9 -0
  14. package/dist/dox-row.js +32 -0
  15. package/dist/dox-triage.d.ts +3 -3
  16. package/dist/dox-triage.js +22 -15
  17. package/dist/dox.d.ts +45 -6
  18. package/dist/dox.js +236 -94
  19. package/dist/eval.d.ts +24 -0
  20. package/dist/eval.js +106 -13
  21. package/dist/git-scope/commits.d.ts +26 -0
  22. package/dist/git-scope/commits.js +243 -0
  23. package/dist/git-scope/deps.d.ts +41 -0
  24. package/dist/git-scope/deps.js +78 -0
  25. package/dist/git-scope/forge/cli.d.ts +16 -0
  26. package/dist/git-scope/forge/cli.js +66 -0
  27. package/dist/git-scope/forge/gitea.d.ts +15 -0
  28. package/dist/git-scope/forge/gitea.js +98 -0
  29. package/dist/git-scope/forge/github.d.ts +8 -0
  30. package/dist/git-scope/forge/github.js +50 -0
  31. package/dist/git-scope/forge/gitlab.d.ts +8 -0
  32. package/dist/git-scope/forge/gitlab.js +49 -0
  33. package/dist/git-scope/forge/index.d.ts +7 -0
  34. package/dist/git-scope/forge/index.js +13 -0
  35. package/dist/git-scope/forge/types.d.ts +70 -0
  36. package/dist/git-scope/forge/types.js +21 -0
  37. package/dist/git-scope/index.d.ts +4 -0
  38. package/dist/git-scope/index.js +2 -0
  39. package/dist/git-scope/lease.d.ts +24 -0
  40. package/dist/git-scope/lease.js +80 -0
  41. package/dist/git-scope/links.d.ts +23 -0
  42. package/dist/git-scope/links.js +61 -0
  43. package/dist/git-scope/repo.d.ts +36 -0
  44. package/dist/git-scope/repo.js +99 -0
  45. package/dist/git-scope/scope.d.ts +78 -0
  46. package/dist/git-scope/scope.js +406 -0
  47. package/dist/git-scope/store.d.ts +16 -0
  48. package/dist/git-scope/store.js +71 -0
  49. package/dist/git-scope/sync.d.ts +44 -0
  50. package/dist/git-scope/sync.js +215 -0
  51. package/dist/gitignore.d.ts +37 -0
  52. package/dist/gitignore.js +267 -0
  53. package/dist/index-gate.d.ts +27 -0
  54. package/dist/index-gate.js +71 -0
  55. package/dist/index-run.d.ts +66 -5
  56. package/dist/index-run.js +317 -60
  57. package/dist/index.d.ts +33 -18
  58. package/dist/index.js +22 -9
  59. package/dist/indexer.d.ts +29 -0
  60. package/dist/indexer.js +100 -15
  61. package/dist/migrate-file-index.js +4 -4
  62. package/dist/migrate-runner.js +7 -5
  63. package/dist/net-guard.d.ts +35 -0
  64. package/dist/net-guard.js +285 -0
  65. package/dist/render.js +18 -0
  66. package/dist/search-opts.d.ts +22 -0
  67. package/dist/search-opts.js +21 -0
  68. package/dist/seed.d.ts +59 -0
  69. package/dist/seed.js +235 -0
  70. package/dist/sources.d.ts +29 -0
  71. package/dist/sources.js +230 -32
  72. package/dist/sqlite-store.d.ts +111 -8
  73. package/dist/sqlite-store.js +412 -56
  74. package/dist/staleness.d.ts +25 -0
  75. package/dist/staleness.js +69 -0
  76. package/dist/trust.d.ts +33 -1
  77. package/dist/trust.js +72 -5
  78. package/dist/types.d.ts +81 -0
  79. package/dist/verdict.d.ts +53 -0
  80. package/dist/verdict.js +377 -0
  81. package/engine-fingerprint.json +5 -0
  82. package/package.json +6 -4
  83. package/src/adoc-chunker.ts +308 -0
  84. package/src/archive-guard.ts +144 -0
  85. package/src/chunker.ts +51 -5
  86. package/src/cli.ts +137 -37
  87. package/src/config.ts +199 -6
  88. package/src/dox-row.ts +35 -0
  89. package/src/dox-triage.ts +24 -16
  90. package/src/dox.ts +259 -68
  91. package/src/eval.ts +117 -14
  92. package/src/git-scope/commits.ts +267 -0
  93. package/src/git-scope/deps.ts +111 -0
  94. package/src/git-scope/forge/cli.ts +76 -0
  95. package/src/git-scope/forge/gitea.ts +124 -0
  96. package/src/git-scope/forge/github.ts +73 -0
  97. package/src/git-scope/forge/gitlab.ts +71 -0
  98. package/src/git-scope/forge/index.ts +17 -0
  99. package/src/git-scope/forge/types.ts +88 -0
  100. package/src/git-scope/index.ts +6 -0
  101. package/src/git-scope/lease.ts +80 -0
  102. package/src/git-scope/links.ts +73 -0
  103. package/src/git-scope/repo.ts +108 -0
  104. package/src/git-scope/scope.ts +424 -0
  105. package/src/git-scope/store.ts +73 -0
  106. package/src/git-scope/sync.ts +240 -0
  107. package/src/gitignore.ts +282 -0
  108. package/src/index-gate.ts +73 -0
  109. package/src/index-run.ts +362 -58
  110. package/src/index.ts +52 -20
  111. package/src/indexer.ts +120 -14
  112. package/src/migrate-file-index.ts +4 -4
  113. package/src/migrate-runner.ts +6 -4
  114. package/src/net-guard.ts +288 -0
  115. package/src/node-sqlite.d.ts +9 -0
  116. package/src/render.ts +17 -1
  117. package/src/search-opts.ts +52 -0
  118. package/src/seed.ts +249 -0
  119. package/src/sources.ts +235 -28
  120. package/src/sqlite-store.ts +404 -55
  121. package/src/staleness.ts +76 -0
  122. package/src/trust.ts +81 -8
  123. package/src/types.ts +86 -1
  124. package/src/verdict.ts +426 -0
@@ -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,57 @@
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");
11
+ /**
12
+ * `[[x]]` scanner. Linear: `close` (next `]`) only moves forward, so unclosed
13
+ * openers never rescan (the old `/\[\[([^\]]+)\]\]/g` was quadratic).
14
+ */
15
+ function scanWikilinks(text) {
16
+ const out = [];
17
+ let close = -1;
18
+ let i = text.indexOf("[[");
19
+ while (i !== -1) {
20
+ if (close < i + 2) {
21
+ close = text.indexOf("]", i + 2);
22
+ if (close === -1)
23
+ break;
24
+ }
25
+ if (close > i + 2 && text[close + 1] === "]") {
26
+ out.push(text.slice(i + 2, close).trim());
27
+ i = text.indexOf("[[", close + 2);
28
+ }
29
+ else {
30
+ i = text.indexOf("[[", i + 1);
31
+ }
32
+ }
33
+ return out;
34
+ }
35
+ /** `](x.md)` / `](x.mdx)` scanner; same forward-only `close` pointer (next `)`). */
36
+ function scanMdLinks(text) {
37
+ const out = [];
38
+ let close = -1;
39
+ let i = text.indexOf("](");
40
+ while (i !== -1) {
41
+ if (close < i + 2) {
42
+ close = text.indexOf(")", i + 2);
43
+ if (close === -1)
44
+ break;
45
+ }
46
+ const len = close - (i + 2);
47
+ if ((len >= 4 && text.endsWith(".md", close)) || (len >= 5 && text.endsWith(".mdx", close))) {
48
+ out.push(text.slice(i + 2, close).trim());
49
+ i = text.indexOf("](", close + 1);
50
+ }
51
+ else {
52
+ i = text.indexOf("](", i + 1);
53
+ }
54
+ }
55
+ return out;
56
+ }
9
57
  export function chunkMarkdown(input) {
10
58
  const docType = input.docType ?? "doc";
11
59
  const { body: text, fm, parseFailed } = parseFrontmatter(input.text);
@@ -104,7 +152,7 @@ export function chunkMarkdown(input) {
104
152
  body: c.body.trimEnd(),
105
153
  bodyHash: sha(c.body.trim()),
106
154
  }));
107
- const wikilinks = [...input.text.matchAll(/\[\[([^\]]+)\]\]/g)].map((m) => m[1].trim());
108
- const mdLinks = [...input.text.matchAll(/\]\(([^)]+\.mdx?)\)/g)].map((m) => m[1].trim());
155
+ const wikilinks = scanWikilinks(input.text);
156
+ const mdLinks = scanMdLinks(input.text);
109
157
  return { chunks, frontmatter: fm, wikilinks, mdLinks, parseFailed };
110
158
  }
package/dist/cli.js CHANGED
@@ -3,18 +3,23 @@
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 { existsSync, readFileSync } from "node:fs";
6
- import { join, resolve } from "node:path";
7
- import { frontmatterConfigHash, loadConfig } from "./config.js";
8
- import { agentsChain, doxInit, doxLint } from "./dox.js";
6
+ import { join, relative, resolve } from "node:path";
7
+ import { indexOptionsFromConfig, loadConfig } from "./config.js";
8
+ import { agentsChain, doxInit, doxLint, listEmptyPurposeRows } from "./dox.js";
9
9
  import { ackTargets, applyDecisions, buildWorkItems } from "./dox-triage.js";
10
- import { evaluate } from "./eval.js";
11
- import { runIndexAtomic } from "./index-run.js";
10
+ import { evaluate, loadGolden } from "./eval.js";
11
+ import { beginForcedSource, sourceGateIsStale, stampPass, stampSource } from "./index-gate.js";
12
+ import { BUILDING_LINE, isFirstIndexLive, runIndexAtomic } from "./index-run.js";
12
13
  import { indexSource } from "./indexer.js";
13
14
  import { kbInit } from "./init.js";
14
15
  import { renderHits } from "./render.js";
16
+ import { searchOptsFromConfig } from "./search-opts.js";
17
+ import { seedOptionsFromConfig } from "./seed.js";
15
18
  import { resolveAll } from "./sources.js";
16
- import { SCHEMA_VERSION, SqliteFtsStore } from "./sqlite-store.js";
19
+ import { SqliteFtsStore } from "./sqlite-store.js";
20
+ import { readStaleness } from "./staleness.js";
17
21
  import { defaultPromptTrust } from "./trust.js";
22
+ import { enrichHits } from "./verdict.js";
18
23
  function parse(argv) {
19
24
  const f = { _: [] };
20
25
  for (let i = 0; i < argv.length; i++) {
@@ -77,24 +82,52 @@ function openStore(cfg) {
77
82
  return store;
78
83
  }
79
84
  async function runIndex(cfg, store, sources, force = false) {
80
- // Apply the same schema-version / facet-config gate as runIndexAtomic so the
81
- // auto-index-on-search path also picks up new structures after an upgrade or a
85
+ // Apply the same per-source schema-version / options-hash gate as runIndexAtomic so
86
+ // the auto-index-on-search path also picks up new structures after an upgrade or a
82
87
  // frontmatter-config change (else the DB stays stale until an explicit `index`).
83
- const hash = frontmatterConfigHash(cfg.frontmatter);
84
- const stale = (store.getUserVersion?.() ?? 0) < SCHEMA_VERSION || (store.getMeta?.("facetConfigHash") ?? null) !== hash;
85
- const eff = force || stale;
88
+ // A source is stamped only after it was walked; skipped/failed ones stay due.
86
89
  let scanned = 0, changed = 0, deleted = 0, chunks = 0;
87
90
  for (const s of sources) {
88
- 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 eff = force || sourceGateIsStale(store, cfg, s.id);
92
+ const st = await indexSource(store, { root: s.id, dir: s.dir }, indexOptionsFromConfig(cfg, { force: eff, onFirstBatch: eff ? beginForcedSource(store, s.id) : undefined }));
93
+ if (!st.missing)
94
+ stampSource(store, cfg, s.id);
89
95
  scanned += st.scanned;
90
96
  changed += st.changed;
91
97
  deleted += st.deleted;
92
98
  chunks += st.chunks;
93
99
  }
94
- store.setUserVersion?.(SCHEMA_VERSION);
95
- store.setMeta?.("facetConfigHash", hash);
100
+ stampPass(store, cfg);
96
101
  return { scanned, changed, deleted, chunks };
97
102
  }
103
+ /** Open the docs store for a non-index command WITHOUT ever creating `dbPath` in place:
104
+ * an absent DB is built through the atomic first-index path (temp file → no-clobber
105
+ * install), or — while another process is building it — reported as still being built
106
+ * (exit 75, EX_TEMPFAIL). With no indexable source nothing is built and an empty
107
+ * in-memory store answers. See change: fix-kb-index-integrity (D2). */
108
+ async function openStoreForQuery(cfg, sources, flags) {
109
+ if (!existsSync(cfg.dbAbsPath)) {
110
+ if (isFirstIndexLive(cfg.dbAbsPath)) {
111
+ console.log(BUILDING_LINE);
112
+ process.exit(75);
113
+ }
114
+ if (!flags["no-reindex"] && sources.some((s) => existsSync(s.dir))) {
115
+ await runIndexAtomic({
116
+ dbPath: cfg.dbAbsPath,
117
+ sources: sources.map((x) => ({ id: x.id, dir: x.dir })),
118
+ indexOpts: indexOptionsFromConfig(cfg),
119
+ gate: cfg,
120
+ seed: seedOptionsFromConfig(cfg, { noSeed: !!flags["no-seed"], explicitSources: !!flags.source?.length, customDb: !!flags.db }),
121
+ });
122
+ }
123
+ else {
124
+ const mem = new SqliteFtsStore(":memory:");
125
+ mem.init();
126
+ return mem;
127
+ }
128
+ }
129
+ return openStore(cfg);
130
+ }
98
131
  /** Resolve sources for a run. --source overrides (filesystem, sync); otherwise
99
132
  * resolve all configured specs (filesystem sync + remote async + TOFU trust). */
100
133
  async function sourcesForRun(cfg, flags) {
@@ -112,12 +145,13 @@ async function sourcesForRun(cfg, flags) {
112
145
  const HELP = `kb — markdown knowledge base
113
146
  Usage:
114
147
  kb init [--global] [--source <ref>]... [--dry-run] [--force] [--cwd <dir>]
115
- kb index [--source <dir>...] [--db <path>] [--force] [--refresh]
148
+ kb index [--source <dir>...] [--db <path>] [--force] [--refresh] [--no-seed]
149
+ (--no-seed: skip seeding a linked worktree's first index from the main checkout)
116
150
  kb search "<query>" [--limit N] [--root id] [--doc-type doc|agents|source-md]
117
151
  [--expand-parent|--no-expand-parent] [--expand-graph] [--rerank]
118
152
  [--expand-query] [--json] [--no-reindex] [--source <dir>...] [--db <path>]
119
- [--no-source-dedup] [--no-lane-quota] [--no-coverage-rerank]
120
- (--limit bounds distinct SOURCES, not chunks)
153
+ [--no-source-dedup] [--no-lane-quota] [--no-coverage-rerank] [--verdicts]
154
+ (--limit bounds distinct SOURCES, not chunks; --verdicts = opt-in trust labels)
121
155
  kb neighbors "<node>" [--depth N] [--rel child_of|links_to|references|has_tag]
122
156
  kb backlinks "<node>"
123
157
  kb get <path> [--section "<heading_path>"]
@@ -127,7 +161,12 @@ Usage:
127
161
  (--source-rows also reports undocumented .ts/.tsx)
128
162
  kb dox triage [--json] [--limit N] triage STALE rows vs the git diff since ack
129
163
  [--apply <d.json> [--write]] [--ack <targets.json>]
164
+ kb dox describe --list [--json] [--dir <path>] list rows with an empty Purpose cell
130
165
  kb eval --golden <file.json> [--limit N] [--doc-type ...] [--no-reindex]
166
+ [--allow-zero] [--verbose] [--json]
167
+ (--golden accepts a bare array of {q, expect} or an {"items": [...]} object;
168
+ items outside the configured roots are reported as unreachable;
169
+ a run with 0 scored items or 0 recall exits non-zero unless --allow-zero)
131
170
  kb config show resolved config
132
171
  Global: --cwd <dir> --config <file>`;
133
172
  function main() {
@@ -188,9 +227,13 @@ function main() {
188
227
  const r = doxLint({ cwd, json: !!flags.json, fix: !!flags.fix, sourceFileRows: !!flags["source-rows"] });
189
228
  if (flags.json)
190
229
  console.log(JSON.stringify(r, null, 2));
191
- else
230
+ else {
231
+ // Coverage line (design D4, fix-dox-lint-blind-rows): a clean verdict
232
+ // must be distinguishable from an unread file.
233
+ console.log(`${r.filesScanned} files, ${r.rowsScanned} rows scanned, ${r.issues.length} findings`);
192
234
  for (const i of r.issues)
193
235
  console.log(`${i.kind}\t${i.agentsFile}${i.path ? "\t" + i.path : ""}\t${i.detail}`);
236
+ }
194
237
  if (r.issues.length)
195
238
  process.exit(1);
196
239
  return;
@@ -212,7 +255,7 @@ function main() {
212
255
  console.log(`re-acked ${ackTargets({ cwd, targets, stalenessFile })} entries`);
213
256
  return;
214
257
  }
215
- const staleness = existsSync(stalenessFile) ? JSON.parse(readFileSync(stalenessFile, "utf8")) : {};
258
+ const staleness = readStaleness(stalenessFile);
216
259
  const items = buildWorkItems({ cwd, issues: doxLint({ cwd }).issues, staleness, limit: flags.limit ? Number(flags.limit) : undefined });
217
260
  if (flags.json) {
218
261
  console.log(JSON.stringify(items, null, 2));
@@ -226,6 +269,25 @@ function main() {
226
269
  console.log(` ${i.baselineFound ? "diff" : "????"}\t${i.agentsFile}\t${i.row}`);
227
270
  return;
228
271
  }
272
+ if (sub === "describe") {
273
+ // --list is the only v1 op; accept it (and its absence) uniformly.
274
+ const r = listEmptyPurposeRows({ cwd, dir: typeof flags.dir === "string" ? flags.dir : undefined });
275
+ if (flags.json) {
276
+ console.log(JSON.stringify(r, null, 2));
277
+ return;
278
+ }
279
+ if (r.total === 0) {
280
+ console.log("no empty-purpose rows");
281
+ return;
282
+ }
283
+ console.log(`${r.total} empty-purpose row(s) across ${r.groups.length} AGENTS.md file(s)`);
284
+ for (const g of r.groups) {
285
+ console.log(g.agentsPath);
286
+ for (const s of g.subjects)
287
+ console.log(` ${s}`);
288
+ }
289
+ return;
290
+ }
229
291
  console.error(`unknown dox subcommand: ${sub}`);
230
292
  process.exit(2);
231
293
  }
@@ -253,15 +315,16 @@ async function runCmd(cmd, flags) {
253
315
  const s = await runIndexAtomic({
254
316
  dbPath: cfg.dbAbsPath,
255
317
  sources: sources.map((x) => ({ id: x.id, dir: x.dir })),
256
- indexOpts: { force: !!flags.force, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions, frontmatter: cfg.frontmatter },
257
- facetConfigHash: frontmatterConfigHash(cfg.frontmatter),
318
+ indexOpts: indexOptionsFromConfig(cfg, { force: !!flags.force }),
319
+ gate: cfg,
258
320
  explicit,
321
+ seed: seedOptionsFromConfig(cfg, { noSeed: !!flags["no-seed"], explicitSources: explicit, customDb: !!flags.db }),
259
322
  });
260
323
  console.log(`indexed ${s.scanned} files (${s.changed} changed, ${s.deleted} deleted, ${s.chunks} chunks) in ${(performance.now() - t).toFixed(0)}ms`);
261
324
  console.log(JSON.stringify(s.counts));
262
325
  return;
263
326
  }
264
- const store = openStore(cfg);
327
+ const store = await openStoreForQuery(cfg, sources, flags);
265
328
  try {
266
329
  if (cmd === "search") {
267
330
  const q = flags._[1];
@@ -273,25 +336,31 @@ async function runCmd(cmd, flags) {
273
336
  const docType = enumFlag(flags["doc-type"], ["doc", "agents", "source-md"], "--doc-type");
274
337
  if (!flags["no-reindex"])
275
338
  await runIndex(cfg, store, sources); // auto incremental freshness
339
+ // One shared mapping (design D2, fix-kb-eval-measurement-integrity): the
340
+ // CLI's flag-derived overrides are the ONLY difference from the tool.
276
341
  const so = {
277
342
  limit: limit ?? 10,
278
343
  root: flags.root,
279
344
  docType: docType,
280
- fieldWeights: cfg.ranking.fieldWeights,
281
- proximityBoost: cfg.ranking.proximityBoost,
282
- diversity: cfg.ranking.diversity,
283
- // `limit` bounds distinct SOURCES, not chunks. See change: fix-kb-search-retrieval-quality.
284
- sourceDedup: flags["no-source-dedup"] ? false : cfg.ranking.sourceDedup,
285
- laneQuota: flags["no-lane-quota"] ? 0 : cfg.ranking.laneQuota,
286
- coverageRerank: flags["no-coverage-rerank"] ? false : cfg.ranking.coverageRerank,
287
- prf: cfg.queryExpansion.prf,
288
- expandParent: flags["no-expand-parent"] ? false : (cfg.expand.parent || !!flags["expand-parent"]),
289
- expandGraph: cfg.expand.graph || !!flags["expand-graph"],
290
- rerank: cfg.rerank.enabled || !!flags.rerank,
291
- queryExpansion: flags["expand-query"] ? (cfg.queryExpansion.mode === "off" ? "synonym" : cfg.queryExpansion.mode) : cfg.queryExpansion.mode,
292
- rootPriority: Object.fromEntries(sources.map((s) => [s.id, s.priority])),
345
+ ...searchOptsFromConfig(cfg, {
346
+ sources,
347
+ overrides: {
348
+ sourceDedup: flags["no-source-dedup"] ? false : undefined,
349
+ laneQuota: flags["no-lane-quota"] ? 0 : undefined,
350
+ coverageRerank: flags["no-coverage-rerank"] ? false : undefined,
351
+ expandParent: flags["no-expand-parent"] ? false : flags["expand-parent"] ? true : undefined,
352
+ expandGraph: flags["expand-graph"] ? true : undefined,
353
+ rerank: flags.rerank ? true : undefined,
354
+ queryExpansion: flags["expand-query"] && cfg.queryExpansion.mode === "off" ? "synonym" : undefined,
355
+ },
356
+ }),
293
357
  };
294
358
  const hits = store.search(q, so);
359
+ // Opt-in trust verdicts (arm A): post-search enrichment OUTSIDE the store
360
+ // (design D10) — labels only, ordering untouched (D1); bodies from disk.
361
+ // See change: add-kb-trust-verdicts-and-search-guard.
362
+ if (flags.verdicts)
363
+ await enrichHits(hits, { cwd: cfg.cwd });
295
364
  if (flags.json)
296
365
  console.log(JSON.stringify(hits, null, 2));
297
366
  else if (hits.length)
@@ -328,9 +397,43 @@ async function runCmd(cmd, flags) {
328
397
  }
329
398
  if (!flags["no-reindex"])
330
399
  await runIndex(cfg, store, sources);
331
- const golden = JSON.parse(readFileSync(resolve(cfg.cwd, gf), "utf8"));
332
- const m = evaluate(store, golden, { k: flags.limit ? Number(flags.limit) : 10, docType: flags["doc-type"] });
400
+ // Fixture contract (design D3): bare array | {items}, item shapes validated.
401
+ const golden = loadGolden(JSON.parse(readFileSync(resolve(cfg.cwd, gf), "utf8")), gf);
402
+ // Eval measures the TOOL path (spec R1): the extension's option set. Roots
403
+ // enable repo-relative expect normalization + reachability (design D4).
404
+ const roots = sources.map((s) => ({ id: s.id, relPrefix: relative(cfg.cwd, s.dir), dir: s.dir }));
405
+ // Same validation contract as `search`: reject garbage instead of
406
+ // passing an invalid limit to the backend or an unknown doc-type as an
407
+ // empty filter (CodeRabbit round, fix-kb-eval-measurement-integrity).
408
+ const limit = posInt(flags.limit, "--limit") ?? 10;
409
+ const docType = enumFlag(flags["doc-type"], ["doc", "agents", "source-md"], "--doc-type");
410
+ const m = evaluate(store, golden, {
411
+ k: limit,
412
+ docType: docType,
413
+ verbose: !!flags.verbose,
414
+ roots,
415
+ ...searchOptsFromConfig(cfg, { sources, overrides: { expandGraph: false, rerank: false } }),
416
+ });
333
417
  console.log(JSON.stringify(m, null, flags.json ? 2 : 0));
418
+ if (flags.verbose && m.unreachablePaths?.length) {
419
+ for (const p of m.unreachablePaths)
420
+ console.error(`[kb eval] unreachable: ${p}`);
421
+ }
422
+ // Vacuous-run guard (design D5): an all-zero score is a harness fault far
423
+ // more often than a retrieval fault. Metrics stay on stdout; the failure
424
+ // signal is the exit code. --allow-zero measures anyway.
425
+ const why = m.n === 0
426
+ ? golden.length === 0
427
+ ? "the golden fixture has no items"
428
+ : `all ${m.unreachable} of ${golden.length} golden items are unreachable under the configured roots (${roots.map((r) => r.relPrefix || ".").join(", ")}) — check root normalization`
429
+ : m["Recall@K"] === 0
430
+ ? `recall is 0 across all ${m.n} scored items — check the fixture shape and root normalization`
431
+ : null;
432
+ if (why) {
433
+ console.error(`[kb eval] VACUOUS RUN: ${why}. Re-run with --allow-zero to measure anyway.`);
434
+ if (!flags["allow-zero"])
435
+ process.exit(1);
436
+ }
334
437
  }
335
438
  else {
336
439
  console.error(`unknown command: ${cmd}\n\n${HELP}`);
package/dist/config.d.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { type FacetKeyConfig } from "./frontmatter.js";
2
+ import type { IndexOptions } from "./indexer.js";
2
3
  export interface SourceConfig {
3
4
  kind?: "filesystem" | "npm" | "git" | "https";
4
5
  ref: string;
@@ -26,6 +27,15 @@ export interface RankingConfig {
26
27
  * 0 disables the quota. SWEPT over the bundled fixtures — see
27
28
  * openspec/changes/fix-kb-search-retrieval-quality/measurements.md. */
28
29
  laneQuota: number;
30
+ /** Relative score margin that lets the reserved `agents` lane take result
31
+ * slot 1, 0..1 (change fix-kb-search-lane-composition, design D2/D3).
32
+ * `0` disables the rule and restores the pre-change interleaving exactly.
33
+ * The running-share quota is structurally incapable of taking slot 1
34
+ * (`(0+1)/(0+1) <= share` is false for every share < 1), so rank 1 needs
35
+ * its own knob. Inert whenever there is no reserved lane: an explicit
36
+ * `doc_type` or `laneQuota: 0` zeroes `laneShare` at the call site, so
37
+ * `interleaveLanes` — and this rule inside it — is never reached. */
38
+ laneLeadMargin: number;
29
39
  /** IDF-weighted coverage rerank over the candidate pool (design D4).
30
40
  * Implemented, DEFAULT OFF: on the bundled fixtures it costs markdown-intent
31
41
  * R@10 0.620 → 0.472 to buy source-intent 0.423 → 0.462, a net regression. */
@@ -59,6 +69,52 @@ export interface FrontmatterConfig {
59
69
  searchableKeys: string[];
60
70
  facetKeys: FacetKeyConfig[];
61
71
  }
72
+ /** kb search-guard enforcement mode (arm B). Shipped default `warn` (resolved
73
+ * at planning): a guard that is off does nothing about the measured 10:1
74
+ * under-use; `block` can refuse tool calls and is therefore NEVER a default —
75
+ * reachable only by explicit config. The KB_GUARD_MODE env override may
76
+ * select `off`/`warn` only (it can weaken, never enable blocking — D14). */
77
+ export type GuardMode = "off" | "warn" | "block";
78
+ export interface ReadDisciplineConfig {
79
+ guard: {
80
+ mode: GuardMode;
81
+ };
82
+ }
83
+ /** Per-turn DOX doctrine delivery (change: inject-dox-doctrine-and-describe).
84
+ * `inject: "kb"` appends the READ doctrine to the system prompt; `write`
85
+ * additionally appends the WRITE discipline. `inject: "off"` suppresses both
86
+ * and makes `write` inert. */
87
+ export interface DoctrineConfig {
88
+ inject: "kb" | "off";
89
+ write: boolean;
90
+ }
91
+ /** Forge flavours the git scope can talk to. */
92
+ export type ForgeKind = "github" | "gitlab" | "gitea";
93
+ /** `git` scope group (change: add-kb-git-forge-scope, design G8). `forge.hosts`
94
+ * and `forge.gitea.tokenEnv` are honoured from the GLOBAL layer only. */
95
+ export interface GitConfig {
96
+ enabled: boolean;
97
+ remote: string;
98
+ searchWaitMs: number;
99
+ commits: {
100
+ maxInitial: number;
101
+ maxPathsPerCommit: number;
102
+ };
103
+ forge: {
104
+ enabled: boolean;
105
+ minSyncIntervalSeconds: number;
106
+ hintedMinSyncIntervalSeconds: number;
107
+ rateFloorPercent: number;
108
+ firstSyncWindowDays: number;
109
+ firstSyncMaxItems: number;
110
+ pagesPerSync: number;
111
+ leaseSeconds: number;
112
+ hosts: Record<string, ForgeKind>;
113
+ gitea: {
114
+ tokenEnv: string;
115
+ };
116
+ };
117
+ }
62
118
  export interface KbConfig {
63
119
  sources: SourceConfig[];
64
120
  roots?: Array<{
@@ -94,10 +150,15 @@ export interface KbConfig {
94
150
  directoryLevelAgents: DirectoryLevelAgentsConfig;
95
151
  frontmatter: FrontmatterConfig;
96
152
  doxEnforcement: boolean;
153
+ readDiscipline: ReadDisciplineConfig;
154
+ doctrine: DoctrineConfig;
97
155
  ranking: RankingConfig;
98
156
  expand: ExpandConfig;
99
157
  rerank: RerankConfig;
100
158
  queryExpansion: QueryExpansionConfig;
159
+ git: GitConfig;
160
+ /** Seed a linked worktree's first index from the main checkout's index (default true). */
161
+ seedFromMainWorktree: boolean;
101
162
  dbPath: string;
102
163
  }
103
164
  export interface ResolvedSource {
@@ -112,11 +173,30 @@ export interface ResolvedConfig extends KbConfig {
112
173
  allSourceSpecs: SourceConfig[];
113
174
  resolvedSources: ResolvedSource[];
114
175
  origin: "project" | "global" | "defaults";
176
+ /** Highest layer that supplied a `doctrine` KEY (`{}` counts) — distinct from
177
+ * `origin`, which is file-presence. Callers use it to detect first contact. */
178
+ doctrineSource: "project" | "global" | "none";
115
179
  }
116
180
  export declare const DEFAULTS: KbConfig;
117
181
  /** Stable hash of the frontmatter routing config. A change forces a full reindex
118
182
  * (design D6) since existing property rows/meta chunks reflect the old routing. */
119
183
  export declare function frontmatterConfigHash(fm: FrontmatterConfig): string;
184
+ /** The slice of a resolved config the index gate hashes. */
185
+ export interface IndexGateConfig {
186
+ frontmatter: FrontmatterConfig;
187
+ includeSourceMarkdown?: boolean;
188
+ }
189
+ /** Hash of every option that changes what an UNCHANGED file indexes to: the
190
+ * frontmatter routing config and `includeSourceMarkdown` (it flips a file's
191
+ * `doc_type`; unset normalizes to `true`, as the indexer reads it). Selection-only
192
+ * options (include/exclude/extensions/gitignore/agents) are deliberately NOT in it:
193
+ * an unchanged file keeps its rows and the next walk adds/prunes the rest.
194
+ * See change: fix-kb-index-integrity (D6). */
195
+ export declare function indexOptionsHash(cfg: IndexGateConfig): string;
196
+ /** The ONE derivation of indexer options from a resolved config — every docs writer
197
+ * (`kb index`, CLI auto-index, kb-extension reindex, dashboard reindex job) uses it,
198
+ * so none can silently drop `frontmatter` (custom facet keys). */
199
+ export declare function indexOptionsFromConfig(cfg: ResolvedConfig, overrides?: Partial<IndexOptions>): IndexOptions;
120
200
  /** Layer configs left→right, deep-merging the known nested object keys. */
121
201
  export declare function mergeConfig(...layers: Array<Partial<KbConfig> | null | undefined>): Partial<KbConfig>;
122
202
  /** Validate a parsed config shape; throw with a precise message on violation. */