@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
package/dist/dox.js CHANGED
@@ -2,9 +2,11 @@
2
2
  // `kb agents <path>` nearest-applicable chain (design §6d). Pure-local,
3
3
  // deterministic, no LLM/embedding. The detect-don't-write rule: `dox init`
4
4
  // and `--fix` only fill PATH columns / prune orphans; the LLM authors purposes.
5
- import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync, appendFileSync } from "node:fs";
6
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
5
  import { createHash } from "node:crypto";
6
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
7
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
8
+ import { loadGitignoreMatcher } from "./gitignore.js";
9
+ import { readStaleness } from "./staleness.js";
8
10
  // delta ②: exclude worktree checkouts, archived openspec proposals, and doc-example noise.
9
11
  // Also exclude build output (`out`) and the electron bundled/vendored trees
10
12
  // (`bundled-extensions`, `electron/resources/server`) — all gitignored, zero
@@ -16,8 +18,20 @@ import { createHash } from "node:crypto";
16
18
  // navigable source) and self-evident top-level docs (`CHANGELOG.md`, `CLAUDE.md`,
17
19
  // repo-root `README.md`) with no per-file DOX value; `README` anchored to root so
18
20
  // package READMEs stay documented.
19
- const DEFAULT_EXCLUDE = /(^|\/)(node_modules|\.git|\.github|dist|build|out|\.next|coverage|\.kb|\.pi|\.worktrees|\.reverse-spec-scratch|openspec|doc-example|bundled-extensions|mockups|research|site|Prompt stories)(\/|$)|(^|\/)electron\/resources\/server(\/|$)|(^|\/)(CHANGELOG|CLAUDE)\.md$|^README\.md$/;
20
- const AGENTS_FILES = ["AGENTS.md"];
21
+ // `.pi` is NOT excluded wholesale: `.pi/skills/`, `.pi/agents/` and `.pi/prompts/`
22
+ // carry per-file DOX rows per the Documentation Update Protocol, and excluding the
23
+ // whole tree blinded the orphan check there. Only the non-source `.pi` subdirs
24
+ // (caches, kb index, npm/git mirrors, flow run state) are skipped.
25
+ const DEFAULT_EXCLUDE = /(^|\/)(node_modules|\.git|\.github|dist|build|out|\.next|coverage|\.kb|\.worktrees|\.reverse-spec-scratch|openspec|doc-example|bundled-extensions|mockups|research|site|Prompt stories)(\/|$)|(^|\/)\.pi\/(dashboard|npm|git|flows)(\/|$)|(^|\/)electron\/resources\/server(\/|$)|(^|\/)(CHANGELOG|CLAUDE)\.md$|^README\.md$/;
26
+ /**
27
+ * `AGENTS.override.md` (pi 0.84.0) REPLACES a directory's context rather than
28
+ * adding to it, so it is listed first and shadows the other candidates in the
29
+ * SAME directory. Mirrors pi's own first-match-wins candidate list in
30
+ * `dist/core/resource-loader.js`. Ancestor inheritance is unaffected.
31
+ * See change: update-pi-core-0-84-adopt-apis.
32
+ */
33
+ const AGENTS_OVERRIDE_FILE = "AGENTS.override.md";
34
+ const AGENTS_FILES = [AGENTS_OVERRIDE_FILE, "AGENTS.md"];
21
35
  // delta ①: dox init now maps SOURCE, not docs. Source globs, minus type decls and tests.
22
36
  const SOURCE_EXT = /\.(ts|tsx|js|jsx)$/;
23
37
  const MD_EXT = /\.(md|mdx)$/i;
@@ -34,8 +48,8 @@ function isMdFile(name) {
34
48
  !name.endsWith(".AGENTS.md") &&
35
49
  !name.endsWith(".agent.md"));
36
50
  }
37
- export const AREA_FILE_THRESHOLD = 8; // ≥ this many md files in a subdir → own AGENTS.md
38
- export const ROW_CAP = 40;
51
+ const AREA_FILE_THRESHOLD = 8; // ≥ this many md files in a subdir → own AGENTS.md
52
+ const ROW_CAP = 40;
39
53
  // pi auto-injects a dir AGENTS.md on every turn when cwd sits at/below it. Past
40
54
  // this byte cap it is "too large" → split file-based: promote the heaviest rows
41
55
  // to `<File>.AGENTS.md` sidecars (pull-only) + cap remaining rows to one line.
@@ -63,7 +77,16 @@ export function agentsChain(cwd, targetPath, opts = {}) {
63
77
  const ordered = dirs.reverse();
64
78
  const chain = [];
65
79
  ordered.forEach((dir, depth) => {
80
+ // An override replaces this directory's context: take it alone and skip the
81
+ // siblings, otherwise the same logical scope is injected twice.
82
+ const override = join(dir, AGENTS_OVERRIDE_FILE);
83
+ if (existsSync(override)) {
84
+ chain.push({ path: override, rel: relative(cwd, override) || AGENTS_OVERRIDE_FILE, depth });
85
+ return;
86
+ }
66
87
  for (const name of names) {
88
+ if (name === AGENTS_OVERRIDE_FILE)
89
+ continue;
67
90
  const p = join(dir, name);
68
91
  if (existsSync(p))
69
92
  chain.push({ path: p, rel: relative(cwd, p) || name, depth });
@@ -94,12 +117,109 @@ export function fallbackManifest(cwd, targetPath, store) {
94
117
  }
95
118
  return lines.join("\n");
96
119
  }
120
+ // --- row recognition (design D1/D2, fix-dox-lint-blind-rows) ---
121
+ // A row counts iff it sits in a table whose header matches EXACTLY this shape
122
+ // (whitespace-flexible, exact cell names, case-sensitive — all walked tables
123
+ // match exactly). Recognition is keyed on the TABLE, never on heading state:
124
+ // a heading-state gate silently skips rows under subheadings and in files
125
+ // without a `# DOX` heading, while reporting the file as clean.
126
+ const FILE_TABLE_HEADER = /^\|\s*File\s*\|\s*Purpose\s*\|\s*$/;
127
+ // A delimiter row: pipes + dash cells only. The FIRST delimiter after the
128
+ // header belongs to the table; a SECOND one closes it — a directly-adjacent
129
+ // prose table brings its own delimiter, which ends the file table before the
130
+ // prose body cells can be read as rows (the adjacency hazard).
131
+ const TABLE_DELIMITER = /^\|(?:\s*:?-+:?\s*\|)+$/;
132
+ const ROW_PATH = /^\|\s*`([^`]+)`\s*\|/;
133
+ /** Recognize DOX file rows by table header (design D1). One state machine,
134
+ * three consumers (parseRowPaths, countInlineRows, doxLint). Opens on the
135
+ * header line; stays open while lines start with `|` and are not a second
136
+ * delimiter; closes on the first non-`|` line or the second delimiter. */
137
+ export function scanDoxRows(text) {
138
+ const rows = [];
139
+ const emptyFileTables = [];
140
+ const lines = text.split("\n");
141
+ let open = false;
142
+ let seenDelimiter = false;
143
+ let rowsInTable = 0;
144
+ let headerLine = -1;
145
+ const closeTable = () => {
146
+ if (open && rowsInTable === 0)
147
+ emptyFileTables.push({ line: headerLine });
148
+ open = false;
149
+ };
150
+ for (let i = 0; i < lines.length; i++) {
151
+ const line = lines[i];
152
+ if (FILE_TABLE_HEADER.test(line)) {
153
+ closeTable();
154
+ open = true;
155
+ seenDelimiter = false;
156
+ rowsInTable = 0;
157
+ headerLine = i;
158
+ continue;
159
+ }
160
+ if (!open)
161
+ continue;
162
+ if (!line.startsWith("|") || !line.slice(1).includes("|")) {
163
+ closeTable();
164
+ continue;
165
+ }
166
+ if (TABLE_DELIMITER.test(line)) {
167
+ if (seenDelimiter)
168
+ closeTable();
169
+ else
170
+ seenDelimiter = true;
171
+ continue;
172
+ }
173
+ const m = line.match(ROW_PATH);
174
+ if (m) {
175
+ rows.push({ path: m[1], line, lineIndex: i });
176
+ rowsInTable++;
177
+ }
178
+ }
179
+ closeTable();
180
+ return { rows, emptyFileTables };
181
+ }
182
+ const FILE_TABLE_TEMPLATE = "| File | Purpose |\n|---|---|\n";
183
+ /** Table-aware row insertion (design D2). Appends after the file table's last
184
+ * row (never a leading blank line — that would close the table); creates the
185
+ * header + delimiter at EOF when the file has no file table. Shared by
186
+ * --fix's missing arm AND doxInit, so appended rows are recognized on the
187
+ * next run and duplicates never accumulate. */
188
+ function insertRows(text, newRows) {
189
+ const scan = scanDoxRows(text);
190
+ const lines = text.split("\n");
191
+ if (scan.rows.length > 0) {
192
+ const at = scan.rows[scan.rows.length - 1].lineIndex + 1;
193
+ lines.splice(at, 0, ...newRows);
194
+ return lines.join("\n");
195
+ }
196
+ if (scan.emptyFileTables.length > 0) {
197
+ const h = scan.emptyFileTables[scan.emptyFileTables.length - 1].line;
198
+ const at = h + 1 < lines.length && TABLE_DELIMITER.test(lines[h + 1]) ? h + 2 : h + 1;
199
+ lines.splice(at, 0, ...newRows);
200
+ return lines.join("\n");
201
+ }
202
+ const prefix = text === "" ? "" : text.endsWith("\n") ? text : `${text}\n`;
203
+ return `${prefix}\n${FILE_TABLE_TEMPLATE}${newRows.join("\n")}\n`;
204
+ }
205
+ function appendRowsToAgentsFile(agentsFile, rows) {
206
+ if (rows.length === 0)
207
+ return;
208
+ let text = "";
209
+ try {
210
+ text = readFileSync(agentsFile, "utf8");
211
+ }
212
+ catch {
213
+ /* new file — insertRows creates the table from scratch */
214
+ }
215
+ writeFileSync(agentsFile, insertRows(text, rows), "utf8");
216
+ }
97
217
  // delta ①: parameterized walker. `dox init` walks source (walkSource); fallbackManifest
98
218
  // + doxLint keep walking md (walkMd). __tests__ dirs are always skipped.
99
219
  // DEFAULT_EXCLUDE is tested against the path RELATIVE to the walk root, so an
100
220
  // ancestor dir named like an excluded token (e.g. running inside .worktrees)
101
221
  // does not nuke the whole walk.
102
- function walkFiles(dir, match, out = [], root = dir) {
222
+ function walkFiles(dir, match, out = [], root = dir, ignore) {
103
223
  if (!existsSync(dir))
104
224
  return out;
105
225
  for (const e of readdirSync(dir, { withFileTypes: true })) {
@@ -109,18 +229,24 @@ function walkFiles(dir, match, out = [], root = dir) {
109
229
  if (e.isDirectory()) {
110
230
  if (e.name === "__tests__")
111
231
  continue;
112
- walkFiles(abs, match, out, root);
232
+ const rel = relative(root, abs);
233
+ // Conservative dir-pruning (design D3): hard-prune only when the dir
234
+ // matches AND no deeper .gitignore could negate it; otherwise descend
235
+ // and filter files at match time so deep negations survive.
236
+ if (ignore?.isIgnoredDir(rel) && !ignore.hasDeeperGitignore(rel))
237
+ continue;
238
+ walkFiles(abs, match, out, root, ignore);
113
239
  }
114
- else if (match(e.name))
240
+ else if (match(e.name) && !ignore?.isIgnored(relative(root, abs)))
115
241
  out.push(abs);
116
242
  }
117
243
  return out;
118
244
  }
119
- function walkMd(dir, out = []) {
120
- return walkFiles(dir, isMdFile, out);
245
+ function walkMd(dir, out = [], ignore) {
246
+ return walkFiles(dir, isMdFile, out, dir, ignore);
121
247
  }
122
- function walkSource(dir, out = []) {
123
- return walkFiles(dir, isSourceFile, out);
248
+ function walkSource(dir, out = [], ignore) {
249
+ return walkFiles(dir, isSourceFile, out, dir, ignore);
124
250
  }
125
251
  /** Resolve a DOX row path. Rows document paths RELATIVE TO THEIR OWN AGENTS.md
126
252
  * dir. A directory may also document a file that lives OUTSIDE its own dir (a
@@ -148,58 +274,81 @@ const SIDECAR_POINTER = /→ see `[^`]+\.AGENTS\.md`/;
148
274
  export function countInlineRows(agentsFile) {
149
275
  if (!existsSync(agentsFile))
150
276
  return 0;
151
- const text = readFileSync(agentsFile, "utf8");
152
- let inDox = false;
153
- let count = 0;
154
- for (const line of text.split("\n")) {
155
- const h = line.match(/^#{1,6}\s+(.*)$/);
156
- if (h) {
157
- inDox = /^DOX\b/.test(h[1].trim());
158
- continue;
159
- }
160
- if (!inDox)
161
- continue;
162
- const m = line.match(/^\|\s*`([^`]+)`\s*\|/);
163
- if (!m)
164
- continue;
165
- if (SIDECAR_POINTER.test(line))
166
- continue; // sidecar-pointer row, pull-only
167
- count++;
168
- }
169
- return count;
277
+ return scanDoxRows(readFileSync(agentsFile, "utf8")).rows.filter((r) => !SIDECAR_POINTER.test(r.line)).length;
170
278
  }
171
- /** Parse existing row paths from an AGENTS.md file. */
279
+ /** Parse existing row paths from an AGENTS.md file. Rows are recognized by
280
+ * their table's `| File | Purpose |` header (design D1) — independent of
281
+ * heading structure. */
172
282
  export function parseRowPaths(agentsFile) {
173
283
  if (!existsSync(agentsFile))
174
284
  return [];
175
- const text = readFileSync(agentsFile, "utf8");
176
- const paths = [];
177
- // Only rows under a `# DOX —` heading are file-index rows. Prose tables
178
- // (Subagent Routing, QA globs, …) under other headings are NOT DOX rows.
179
- let inDox = false;
180
- for (const line of text.split("\n")) {
181
- const h = line.match(/^#{1,6}\s+(.*)$/);
182
- if (h) {
183
- inDox = /^DOX\b/.test(h[1].trim());
184
- continue;
285
+ return scanDoxRows(readFileSync(agentsFile, "utf8")).rows.map((r) => r.path);
286
+ }
287
+ // --- dox describe --list (change: inject-dox-doctrine-and-describe) ---
288
+ const ROW_PURPOSE = /^\|\s*`([^`]+)`\s*\|\s*(.*?)\s*\|\s*$/;
289
+ /** Enumerate every `| File | Purpose |` row whose Purpose is empty or
290
+ * whitespace-only, grouped by owning `AGENTS.md`. `dir` restricts the walk to
291
+ * one subtree. Read-only: no model, no writes (design D8). Rows are recognized
292
+ * by the table header (`scanDoxRows`), so a prose-only file is skipped. */
293
+ export function listEmptyPurposeRows(opts) {
294
+ const cwd = opts.cwd;
295
+ const dir = typeof opts.dir === "string" && opts.dir.length > 0 ? opts.dir : undefined;
296
+ const start = dir ? resolve(cwd, dir) : cwd;
297
+ // A `--dir` outside cwd, or one naming an excluded / `__tests__` directory,
298
+ // is rejected: the descent skips those dirs, so the START dir needs the same
299
+ // gate (else `--dir a/__tests__` enumerates what the walk would skip).
300
+ if (start !== cwd && !start.startsWith(cwd + sep))
301
+ return { groups: [], total: 0 };
302
+ if (basename(start) === "__tests__" || DEFAULT_EXCLUDE.test(relative(cwd, start)))
303
+ return { groups: [], total: 0 };
304
+ const gi = loadGitignoreMatcher(cwd, { cwd, prune: (rel) => DEFAULT_EXCLUDE.test(rel) });
305
+ const agentsFiles = [];
306
+ const walk = (dir) => {
307
+ if (!existsSync(dir))
308
+ return;
309
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
310
+ const abs = join(dir, e.name);
311
+ if (DEFAULT_EXCLUDE.test(relative(cwd, abs)))
312
+ continue;
313
+ if (e.isDirectory()) {
314
+ if (e.name === "__tests__")
315
+ continue; // skipped during descent, as in the `dox init` source walk
316
+ const rel = relative(cwd, abs);
317
+ if (gi.isIgnoredDir(rel) && !gi.hasDeeperGitignore(rel))
318
+ continue;
319
+ walk(abs);
320
+ }
321
+ else if (e.name === "AGENTS.md" && !gi.isIgnored(relative(cwd, abs))) {
322
+ agentsFiles.push(abs);
323
+ }
324
+ }
325
+ };
326
+ walk(start);
327
+ const groups = [];
328
+ let total = 0;
329
+ for (const af of agentsFiles.sort()) {
330
+ const subjects = [];
331
+ for (const row of scanDoxRows(readFileSync(af, "utf8")).rows) {
332
+ const m = row.line.match(ROW_PURPOSE);
333
+ if (m && m[2].trim() === "")
334
+ subjects.push(row.path);
335
+ }
336
+ if (subjects.length > 0) {
337
+ groups.push({ agentsPath: relative(cwd, af), subjects });
338
+ total += subjects.length;
185
339
  }
186
- if (!inDox)
187
- continue;
188
- const m = line.match(/^\|\s*`([^`]+)`\s*\|/);
189
- if (m)
190
- paths.push(m[1]);
191
340
  }
192
- return paths;
341
+ return { groups, total };
193
342
  }
194
343
  /** Source-file walk (delta ①②), exported for the file-index migration. */
195
- export function sourceFiles(cwd) {
196
- return walkSource(cwd);
344
+ export function sourceFiles(cwd, ignore) {
345
+ return walkSource(cwd, [], ignore);
197
346
  }
198
347
  // delta ③: group source files by FULL parent dir (dirname), not the top-level
199
348
  // segment — this is what makes the tree directory-level.
200
- export function areaFiles(cwd) {
349
+ export function areaFiles(cwd, ignore) {
201
350
  const groups = new Map();
202
- for (const f of walkSource(cwd)) {
351
+ for (const f of walkSource(cwd, [], ignore)) {
203
352
  const rel = relative(cwd, f);
204
353
  const dir = rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : ".";
205
354
  (groups.get(dir) ?? groups.set(dir, []).get(dir)).push(rel);
@@ -210,8 +359,9 @@ export function areaFiles(cwd) {
210
359
  * AGENTS.md; only adds missing files + missing path rows. */
211
360
  export function doxInit(opts) {
212
361
  const cwd = opts.cwd;
362
+ const gi = loadGitignoreMatcher(cwd, { cwd, prune: (rel) => DEFAULT_EXCLUDE.test(rel) });
213
363
  const plan = { created: [], appended: [] };
214
- const groups = areaFiles(cwd);
364
+ const groups = areaFiles(cwd, gi);
215
365
  const ensure = (agentsFile, rows) => {
216
366
  if (existsSync(agentsFile)) {
217
367
  const existing = new Set(parseRowPaths(agentsFile));
@@ -221,14 +371,17 @@ export function doxInit(opts) {
221
371
  });
222
372
  if (missRows.length)
223
373
  plan.appended.push({ file: agentsFile, rows: missRows });
374
+ // Table-aware append (design D2): rows land inside the file table, so a
375
+ // rerun recognizes them and stays idempotent (an EOF-append outside any
376
+ // table would re-fire as missing forever).
224
377
  if (!opts.dryRun && missRows.length)
225
- appendFileSync(agentsFile, "\n" + missRows.join("\n") + "\n");
378
+ appendRowsToAgentsFile(agentsFile, missRows);
226
379
  }
227
380
  else {
228
381
  plan.created.push(agentsFile);
229
382
  if (!opts.dryRun) {
230
383
  mkdirSync(dirname(agentsFile), { recursive: true });
231
- writeFileSync(agentsFile, `# DOX — ${relative(cwd, dirname(agentsFile)) || "root"}\n\nFiles in this area. Purposes left for the agent to author.\n\n${rows.join("\n")}\n`, "utf8");
384
+ writeFileSync(agentsFile, `# DOX — ${relative(cwd, dirname(agentsFile)) || "root"}\n\nFiles in this area. Purposes left for the agent to author.\n\n${FILE_TABLE_TEMPLATE}${rows.join("\n")}\n`, "utf8");
232
385
  }
233
386
  }
234
387
  };
@@ -245,6 +398,84 @@ export function doxInit(opts) {
245
398
  }
246
399
  return plan;
247
400
  }
401
+ // --- dox lint ---
402
+ /**
403
+ * Pull repo-path REFERENCES out of a row's purpose cell.
404
+ *
405
+ * The lint hashes the file behind each row but never validates paths written
406
+ * inside the prose, so a directory move silently rots cross-references (this is
407
+ * how a routing rule kept pointing at two deleted dirs). The hard part is not
408
+ * finding candidates — it is rejecting the ~99% that are not repo paths at all:
409
+ * URL routes, MIME types, npm specifiers, `~`/absolute paths, model ids, code
410
+ * fragments like `get/list/remove`, and descriptions of OTHER projects' layouts.
411
+ *
412
+ * Discriminators, in order of how much noise each removes:
413
+ * 1. first segment must be a real top-level entry of THIS repo — kills
414
+ * `lib/validations.ts` (consumer-project prose) and `provider/model`
415
+ * 2. must carry a source-file extension or be a glob — kills bare route paths
416
+ * 3. structural rejects: leading `~` or `/`, `@` scopes, and any char that
417
+ * cannot appear in a path we would write (`:?="'()[]{}<>` , whitespace…)
418
+ */
419
+ export function extractRefPaths(cell, topLevel) {
420
+ const out = [];
421
+ for (const m of cell.matchAll(/`([^`]+)`/g)) {
422
+ const raw = m[1].trim();
423
+ if (!raw.includes("/"))
424
+ continue;
425
+ if (/^[~/@]/.test(raw))
426
+ continue; // home, absolute, npm scope
427
+ if (/[:?="'()[\]{}<>|,;!#\s]/.test(raw))
428
+ continue; // routes, code, prose, placeholders
429
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional non-ASCII guard
430
+ if (/[^\x20-\x7e]/.test(raw))
431
+ continue;
432
+ const p = raw.replace(/^\.\//, "").replace(/\/$/, "");
433
+ if (!p.includes("/"))
434
+ continue;
435
+ if (!topLevel.has(p.split("/")[0]))
436
+ continue;
437
+ if (!/\.[a-z0-9]{1,5}$/i.test(p) && !p.includes("*"))
438
+ continue;
439
+ // Build output and excluded trees (`packages/electron/out/*`, `.worktrees/*`)
440
+ // are legitimately absent until built/created — flagging them is noise, and a
441
+ // check that cries wolf gets ignored.
442
+ if (DEFAULT_EXCLUDE.test(p))
443
+ continue;
444
+ out.push(p);
445
+ }
446
+ return out;
447
+ }
448
+ /** Cheap glob test for `*` / `**` reference paths (no dependency on a matcher). */
449
+ function globHit(pattern, cwd) {
450
+ const rx = new RegExp(`^${pattern
451
+ .split("/")
452
+ .map((s) => s
453
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
454
+ .replace(/\*\*/g, "\u0001")
455
+ .replace(/\*/g, "[^/]*")
456
+ .replace(/\u0001/g, ".*"))
457
+ .join("/")}$`);
458
+ const walk = (dir, rel) => {
459
+ let entries = [];
460
+ try {
461
+ entries = readdirSync(dir, { withFileTypes: true });
462
+ }
463
+ catch {
464
+ return false;
465
+ }
466
+ for (const e of entries) {
467
+ const r = rel ? `${rel}/${e.name}` : e.name;
468
+ if (DEFAULT_EXCLUDE.test(r))
469
+ continue;
470
+ if (rx.test(r))
471
+ return true;
472
+ if (e.isDirectory() && walk(join(dir, e.name), r))
473
+ return true;
474
+ }
475
+ return false;
476
+ };
477
+ return walk(cwd, "");
478
+ }
248
479
  function fileSha(p) {
249
480
  try {
250
481
  return createHash("sha256").update(readFileSync(p)).digest("hex");
@@ -265,6 +496,22 @@ export function doxLint(opts) {
265
496
  const cwd = opts.cwd;
266
497
  const issues = [];
267
498
  let fixed = 0;
499
+ let filesScanned = 0;
500
+ let rowsScanned = 0;
501
+ // Gitignore-aware walk predicate (design D3), seeded from the repo root so
502
+ // root-anchored patterns apply even though the walk starts at cwd.
503
+ const gi = loadGitignoreMatcher(cwd, { cwd, prune: (rel) => DEFAULT_EXCLUDE.test(rel) });
504
+ // Top-level entries of THIS repo — the primary discriminator that stops
505
+ // broken-ref from firing on prose that merely looks path-shaped.
506
+ const topLevelEntries = new Set();
507
+ try {
508
+ for (const e of readdirSync(cwd, { withFileTypes: true }))
509
+ topLevelEntries.add(e.name);
510
+ }
511
+ catch {
512
+ /* empty cwd — leave the set empty, which disables broken-ref entirely */
513
+ }
514
+ const seenRefs = new Set();
268
515
  // find all AGENTS.md
269
516
  const agentsFiles = [];
270
517
  // Test the path RELATIVE to cwd (mirrors walkFiles) so an ancestor dir named
@@ -277,23 +524,22 @@ export function doxLint(opts) {
277
524
  const abs = join(dir, e.name);
278
525
  if (DEFAULT_EXCLUDE.test(relative(cwd, abs)))
279
526
  continue;
280
- if (e.isDirectory())
527
+ if (e.isDirectory()) {
528
+ const rel = relative(cwd, abs);
529
+ if (gi.isIgnoredDir(rel) && !gi.hasDeeperGitignore(rel))
530
+ continue;
281
531
  walkAgents(abs);
282
- else if (e.name === "AGENTS.md")
532
+ }
533
+ else if (e.name === "AGENTS.md" && !gi.isIgnored(relative(cwd, abs)))
283
534
  agentsFiles.push(abs);
284
535
  }
285
536
  };
286
537
  walkAgents(cwd);
287
- // staleness sidecar
288
- let staleness = {};
538
+ // staleness sidecar — v1 (sha strings) / v2 (records with stat baseline)
539
+ // tolerant reader shared with triage, ack-on-edit, and query-time verdicts.
289
540
  const sf = opts.stalenessFile ?? join(cwd, ".pi", "dashboard", "kb", "dox-staleness.json");
290
- if (existsSync(sf)) {
291
- try {
292
- staleness = JSON.parse(readFileSync(sf, "utf8"));
293
- }
294
- catch { /* */ }
295
- }
296
- const allMd = new Set(walkMd(cwd).map((f) => relative(cwd, f)));
541
+ const staleness = readStaleness(sf);
542
+ const allMd = new Set(walkMd(cwd, [], gi).map((f) => relative(cwd, f)));
297
543
  const rowPaths = new Set();
298
544
  for (const af of agentsFiles) {
299
545
  const afRel = relative(cwd, af);
@@ -310,25 +556,32 @@ export function doxLint(opts) {
310
556
  const inlineCount = countInlineRows(af);
311
557
  if (inlineCount > ROW_CAP)
312
558
  issues.push({ kind: "over-threshold", agentsFile: afRel, arm: "rows", detail: `${inlineCount} inline rows > cap ${ROW_CAP}; informational (advisory; no per-turn injection cost) — optional: folder into cohesive subdirectories` });
313
- const survivingRows = [];
314
- const text = readFileSync(af, "utf8").split("\n");
559
+ filesScanned++;
560
+ const text = readFileSync(af, "utf8");
561
+ const scan = scanDoxRows(text);
562
+ rowsScanned += scan.rows.length;
563
+ // A file-row table nobody filled is a finding, not silence (design D4).
564
+ for (const t of scan.emptyFileTables) {
565
+ issues.push({ kind: "zero-row-table", agentsFile: afRel, detail: `file-row table header at line ${t.line + 1} has zero recognized rows` });
566
+ }
567
+ const pruneIdx = new Set();
315
568
  const afDir = dirname(af);
316
- let inDox = false;
317
- for (const line of text) {
318
- const h = line.match(/^#{1,6}\s+(.*)$/);
319
- if (h) {
320
- inDox = /^DOX\b/.test(h[1].trim());
321
- if (opts.fix)
322
- survivingRows.push(line);
323
- continue;
324
- }
325
- const m = inDox ? line.match(/^\|\s*`([^`]+)`\s*\|/) : null;
326
- if (!m) {
327
- if (opts.fix)
328
- survivingRows.push(line);
329
- continue;
569
+ for (const row of scan.rows) {
570
+ const rp = row.path;
571
+ const line = row.line;
572
+ // Cross-references inside the PURPOSE cell. Rot here is invisible to the
573
+ // hash check, because the row's own file is untouched by the move.
574
+ const purposeCell = line.slice(line.indexOf("|", line.indexOf("`" + rp + "`")) + 1);
575
+ for (const ref of extractRefPaths(purposeCell, topLevelEntries)) {
576
+ if (seenRefs.has(ref))
577
+ continue;
578
+ seenRefs.add(ref);
579
+ const hit = ref.includes("*")
580
+ ? globHit(ref, cwd)
581
+ : existsSync(join(cwd, ref)) || existsSync(join(afDir, ref));
582
+ if (!hit)
583
+ issues.push({ kind: "broken-ref", agentsFile: afRel, path: ref, detail: `broken-ref: row prose cites ${ref}, which does not exist` });
330
584
  }
331
- const rp = m[1];
332
585
  const abs = resolveRowPath(afDir, cwd, rp);
333
586
  const rel = relative(cwd, abs);
334
587
  rowPaths.add(rel);
@@ -338,17 +591,20 @@ export function doxLint(opts) {
338
591
  issues.push({ kind, agentsFile: afRel, path: rp, detail: `${kind}: ${rp} does not exist` });
339
592
  if (opts.fix && kind === "orphan") {
340
593
  fixed++;
341
- continue;
342
- } // prune orphan row
594
+ pruneIdx.add(row.lineIndex); // prune the orphan line, keep every other line byte-identical
595
+ }
343
596
  }
344
- else if (staleness[rel] && fileSha(abs) && staleness[rel] !== fileSha(abs)) {
345
- issues.push({ kind: "stale", agentsFile: afRel, path: rp, detail: `tracked source-hash drifted` });
597
+ else if (staleness[rel]?.sha256) {
598
+ const diskSha = fileSha(abs);
599
+ if (diskSha && staleness[rel].sha256 !== diskSha) {
600
+ issues.push({ kind: "stale", agentsFile: afRel, path: rp, detail: `tracked source-hash drifted` });
601
+ }
346
602
  }
347
- if (opts.fix)
348
- survivingRows.push(line);
349
603
  }
350
- if (opts.fix)
351
- writeFileSync(af, survivingRows.join("\n") + "\n", "utf8");
604
+ if (opts.fix && pruneIdx.size > 0) {
605
+ const out = text.split("\n").filter((_, idx) => !pruneIdx.has(idx));
606
+ writeFileSync(af, out.join("\n"), "utf8");
607
+ }
352
608
  }
353
609
  // missing rows: md files in an area (dir containing an AGENTS.md) with no row.
354
610
  // Owner = nearest ancestor AGENTS.md (deepest dir prefix of the file's dir).
@@ -376,12 +632,32 @@ export function doxLint(opts) {
376
632
  if (owner) {
377
633
  const ownerRel = relative(cwd, owner) || "AGENTS.md";
378
634
  issues.push({ kind: "missing", agentsFile: ownerRel, path: md, detail: `no row for ${md}` });
635
+ // Table-aware append (design D2): an EOF-append outside the table would
636
+ // never be recognized again — the finding would re-fire forever.
379
637
  if (opts.fix) {
380
- appendFileSync(owner, `| \`${md}\` | |\n`);
638
+ appendRowsToAgentsFile(owner, [`| \`${md}\` | |`]);
381
639
  fixed++;
382
640
  }
383
641
  }
384
642
  }
643
+ // missing rows, SOURCE arm (design D9): a .ts/.tsx in a covered area with no
644
+ // row in ANY ancestor AGENTS.md and no <file>.AGENTS.md sidecar is unreachable
645
+ // through the `agents` doc-type lane that retrieval depends on. Opt-in, and
646
+ // never auto-fixed: a blank purpose row is worse than an honest finding.
647
+ if (opts.sourceFileRows) {
648
+ for (const abs of sourceFiles(cwd, gi)) {
649
+ const rel = relative(cwd, abs);
650
+ if (rowPaths.has(rel))
651
+ continue;
652
+ if (existsSync(join(cwd, `${rel}.AGENTS.md`)))
653
+ continue;
654
+ const dir = rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : ".";
655
+ const owner = ownerOf(dir);
656
+ if (!owner)
657
+ continue;
658
+ issues.push({ kind: "missing", arm: "source", agentsFile: relative(cwd, owner) || "AGENTS.md", path: rel, detail: `no row for source file ${rel}` });
659
+ }
660
+ }
385
661
  // missing companions: large source/md files with no <file>.agent.md
386
662
  for (const md of allMd) {
387
663
  const abs = join(cwd, md);
@@ -391,5 +667,5 @@ export function doxLint(opts) {
391
667
  issues.push({ kind: "missing-companion", agentsFile: comp, path: md, detail: `${md} past threshold, no ${comp}` });
392
668
  }
393
669
  }
394
- return { issues, fixed };
670
+ return { issues, fixed, filesScanned, rowsScanned };
395
671
  }
package/dist/eval.d.ts CHANGED
@@ -3,6 +3,14 @@ export interface GoldenItem {
3
3
  q: string;
4
4
  expect: string;
5
5
  }
6
+ /** A configured root, for expect normalization + reachability (design D4).
7
+ * `relPrefix` is the source dir relative to cwd; `dir` (absolute) is used only
8
+ * to resolve the root's top-level entries for the reachability rule (b). */
9
+ export interface RootRef {
10
+ id: string;
11
+ relPrefix: string;
12
+ dir?: string;
13
+ }
6
14
  export interface EvalMetrics {
7
15
  n: number;
8
16
  "P@1": number;
@@ -10,8 +18,30 @@ export interface EvalMetrics {
10
18
  "Recall@K": number;
11
19
  MRR: number;
12
20
  "nDCG@K": number;
21
+ /** Mean count of distinct `(root, path)` sources per top-K page (D8). */
22
+ distinctSourcesAtK: number;
23
+ /** Mean fraction of slots whose source already appeared earlier on the page. */
24
+ duplicateSlotShare: number;
25
+ /** Fraction of queries whose whole top-K page comes from one source. */
26
+ singleSourcePageRate: number;
13
27
  avgLatencyMs: number;
28
+ /** Items whose `expect` sits outside every configured root — reported, never
29
+ * searched, excluded from every metric above (design D4). `n + unreachable`
30
+ * always sums to the fixture size. */
31
+ unreachable: number;
32
+ /** The unreachable expect paths, only when the caller passes `verbose`. */
33
+ unreachablePaths?: string[];
14
34
  }
35
+ /** Load + validate a golden fixture (design D3). Accepts a bare array or an
36
+ * object with an `items` array (the mined sets' bundled shape); anything else
37
+ * throws naming BOTH accepted shapes + the file. Every item must carry a
38
+ * string `q` and a string `expect` — today a non-string expect is a SILENT
39
+ * zero (`includes(undefined)`); rejected items name file + array index.
40
+ * Provenance (`intent`/`minedAt` on the object shape) prints a stderr header
41
+ * and never affects scoring; stdout stays byte-clean for `--json` pipes. */
42
+ export declare function loadGolden(raw: unknown, file: string): GoldenItem[];
15
43
  export declare function evaluate(store: KbStore, golden: GoldenItem[], opts?: SearchOpts & {
16
44
  k?: number;
45
+ roots?: RootRef[];
46
+ verbose?: boolean;
17
47
  }): EvalMetrics;