@blackbelt-technology/pi-dashboard-kb 0.8.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 (62) hide show
  1. package/README.md +46 -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 +96 -25
  11. package/dist/config.d.ts +33 -0
  12. package/dist/config.js +27 -4
  13. package/dist/dox-triage.d.ts +3 -2
  14. package/dist/dox-triage.js +15 -8
  15. package/dist/dox.d.ts +45 -6
  16. package/dist/dox.js +228 -93
  17. package/dist/eval.d.ts +24 -0
  18. package/dist/eval.js +106 -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 +7 -0
  24. package/dist/indexer.js +38 -9
  25. package/dist/net-guard.d.ts +35 -0
  26. package/dist/net-guard.js +285 -0
  27. package/dist/render.js +18 -0
  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 +39 -2
  33. package/dist/sqlite-store.js +145 -17
  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 +40 -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 +6 -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 +93 -24
  47. package/src/config.ts +54 -4
  48. package/src/dox-triage.ts +17 -9
  49. package/src/dox.ts +252 -67
  50. package/src/eval.ts +117 -14
  51. package/src/gitignore.ts +215 -0
  52. package/src/index.ts +45 -20
  53. package/src/indexer.ts +44 -8
  54. package/src/net-guard.ts +288 -0
  55. package/src/render.ts +17 -1
  56. package/src/search-opts.ts +52 -0
  57. package/src/sources.ts +232 -28
  58. package/src/sqlite-store.ts +139 -17
  59. package/src/staleness.ts +76 -0
  60. package/src/trust.ts +81 -8
  61. package/src/types.ts +43 -0
  62. package/src/verdict.ts +412 -0
package/dist/dox.d.ts CHANGED
@@ -1,6 +1,5 @@
1
+ import { type GitignoreMatcher } from "./gitignore.js";
1
2
  import type { KbStore } from "./types.js";
2
- export declare const AREA_FILE_THRESHOLD = 8;
3
- export declare const ROW_CAP = 40;
4
3
  export declare const AGENTS_BYTE_CAP = 30000;
5
4
  export interface AgentsChainOpts {
6
5
  claudeMd?: boolean;
@@ -20,6 +19,24 @@ export declare function agentsChain(cwd: string, targetPath: string, opts?: Agen
20
19
  /** KB-generated routing manifest when no AGENTS.md exists on the path: lists
21
20
  * markdown files under the target subtree as a path → heading map. */
22
21
  export declare function fallbackManifest(cwd: string, targetPath: string, store?: KbStore): string;
22
+ export interface DoxRow {
23
+ path: string;
24
+ line: string;
25
+ lineIndex: number;
26
+ }
27
+ export interface DoxScan {
28
+ rows: DoxRow[];
29
+ /** File-row tables from which zero rows were recognized (header line
30
+ * indexes). A header nobody filled is a finding, not silence. */
31
+ emptyFileTables: {
32
+ line: number;
33
+ }[];
34
+ }
35
+ /** Recognize DOX file rows by table header (design D1). One state machine,
36
+ * three consumers (parseRowPaths, countInlineRows, doxLint). Opens on the
37
+ * header line; stays open while lines start with `|` and are not a second
38
+ * delimiter; closes on the first non-`|` line or the second delimiter. */
39
+ export declare function scanDoxRows(text: string): DoxScan;
23
40
  export interface DoxInitOptions {
24
41
  dryRun?: boolean;
25
42
  cwd: string;
@@ -43,11 +60,28 @@ export declare function resolveRowPath(agentsDir: string, cwd: string, rp: strin
43
60
  * string[] (consumed cross-package by kb-extension acknowledgeRows/decideNudge
44
61
  * + the missing/orphan/staleness checks); the exclusion is count-only. */
45
62
  export declare function countInlineRows(agentsFile: string): number;
46
- /** Parse existing row paths from an AGENTS.md file. */
63
+ /** Parse existing row paths from an AGENTS.md file. Rows are recognized by
64
+ * their table's `| File | Purpose |` header (design D1) — independent of
65
+ * heading structure. */
47
66
  export declare function parseRowPaths(agentsFile: string): string[];
67
+ export interface EmptyPurposeList {
68
+ groups: Array<{
69
+ agentsPath: string;
70
+ subjects: string[];
71
+ }>;
72
+ total: number;
73
+ }
74
+ /** Enumerate every `| File | Purpose |` row whose Purpose is empty or
75
+ * whitespace-only, grouped by owning `AGENTS.md`. `dir` restricts the walk to
76
+ * one subtree. Read-only: no model, no writes (design D8). Rows are recognized
77
+ * by the table header (`scanDoxRows`), so a prose-only file is skipped. */
78
+ export declare function listEmptyPurposeRows(opts: {
79
+ cwd: string;
80
+ dir?: string;
81
+ }): EmptyPurposeList;
48
82
  /** Source-file walk (delta ①②), exported for the file-index migration. */
49
- export declare function sourceFiles(cwd: string): string[];
50
- export declare function areaFiles(cwd: string): Map<string, string[]>;
83
+ export declare function sourceFiles(cwd: string, ignore?: GitignoreMatcher): string[];
84
+ export declare function areaFiles(cwd: string, ignore?: GitignoreMatcher): Map<string, string[]>;
51
85
  /** Plan (and optionally write) a DOX tree. Idempotent: never clobbers existing
52
86
  * AGENTS.md; only adds missing files + missing path rows. */
53
87
  export declare function doxInit(opts: DoxInitOptions): DoxInitPlan;
@@ -70,7 +104,7 @@ export declare function doxInit(opts: DoxInitOptions): DoxInitPlan;
70
104
  */
71
105
  export declare function extractRefPaths(cell: string, topLevel: Set<string>): string[];
72
106
  export interface DoxIssue {
73
- kind: "stale" | "orphan" | "missing" | "missing-companion" | "broken-pointer" | "broken-ref" | "over-threshold";
107
+ kind: "stale" | "orphan" | "missing" | "missing-companion" | "broken-pointer" | "broken-ref" | "zero-row-table" | "over-threshold";
74
108
  agentsFile: string;
75
109
  path?: string;
76
110
  detail: string;
@@ -89,5 +123,10 @@ export interface DoxLintOptions {
89
123
  export interface DoxLintResult {
90
124
  issues: DoxIssue[];
91
125
  fixed: number;
126
+ /** Coverage (design D4): AGENTS.md files row-parsed, so a clean verdict can
127
+ * be distinguished from an unread file. */
128
+ filesScanned: number;
129
+ /** Recognized rows across all scanned files. */
130
+ rowsScanned: number;
92
131
  }
93
132
  export declare function doxLint(opts: DoxLintOptions): DoxLintResult;
package/dist/dox.js CHANGED
@@ -3,8 +3,10 @@
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
5
  import { createHash } from "node:crypto";
6
- import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
6
+ import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
7
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
@@ -46,8 +48,8 @@ function isMdFile(name) {
46
48
  !name.endsWith(".AGENTS.md") &&
47
49
  !name.endsWith(".agent.md"));
48
50
  }
49
- export const AREA_FILE_THRESHOLD = 8; // ≥ this many md files in a subdir → own AGENTS.md
50
- 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;
51
53
  // pi auto-injects a dir AGENTS.md on every turn when cwd sits at/below it. Past
52
54
  // this byte cap it is "too large" → split file-based: promote the heaviest rows
53
55
  // to `<File>.AGENTS.md` sidecars (pull-only) + cap remaining rows to one line.
@@ -115,12 +117,109 @@ export function fallbackManifest(cwd, targetPath, store) {
115
117
  }
116
118
  return lines.join("\n");
117
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
+ }
118
217
  // delta ①: parameterized walker. `dox init` walks source (walkSource); fallbackManifest
119
218
  // + doxLint keep walking md (walkMd). __tests__ dirs are always skipped.
120
219
  // DEFAULT_EXCLUDE is tested against the path RELATIVE to the walk root, so an
121
220
  // ancestor dir named like an excluded token (e.g. running inside .worktrees)
122
221
  // does not nuke the whole walk.
123
- function walkFiles(dir, match, out = [], root = dir) {
222
+ function walkFiles(dir, match, out = [], root = dir, ignore) {
124
223
  if (!existsSync(dir))
125
224
  return out;
126
225
  for (const e of readdirSync(dir, { withFileTypes: true })) {
@@ -130,18 +229,24 @@ function walkFiles(dir, match, out = [], root = dir) {
130
229
  if (e.isDirectory()) {
131
230
  if (e.name === "__tests__")
132
231
  continue;
133
- 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);
134
239
  }
135
- else if (match(e.name))
240
+ else if (match(e.name) && !ignore?.isIgnored(relative(root, abs)))
136
241
  out.push(abs);
137
242
  }
138
243
  return out;
139
244
  }
140
- function walkMd(dir, out = []) {
141
- return walkFiles(dir, isMdFile, out);
245
+ function walkMd(dir, out = [], ignore) {
246
+ return walkFiles(dir, isMdFile, out, dir, ignore);
142
247
  }
143
- function walkSource(dir, out = []) {
144
- return walkFiles(dir, isSourceFile, out);
248
+ function walkSource(dir, out = [], ignore) {
249
+ return walkFiles(dir, isSourceFile, out, dir, ignore);
145
250
  }
146
251
  /** Resolve a DOX row path. Rows document paths RELATIVE TO THEIR OWN AGENTS.md
147
252
  * dir. A directory may also document a file that lives OUTSIDE its own dir (a
@@ -169,58 +274,81 @@ const SIDECAR_POINTER = /→ see `[^`]+\.AGENTS\.md`/;
169
274
  export function countInlineRows(agentsFile) {
170
275
  if (!existsSync(agentsFile))
171
276
  return 0;
172
- const text = readFileSync(agentsFile, "utf8");
173
- let inDox = false;
174
- let count = 0;
175
- for (const line of text.split("\n")) {
176
- const h = line.match(/^#{1,6}\s+(.*)$/);
177
- if (h) {
178
- inDox = /^DOX\b/.test(h[1].trim());
179
- continue;
180
- }
181
- if (!inDox)
182
- continue;
183
- const m = line.match(/^\|\s*`([^`]+)`\s*\|/);
184
- if (!m)
185
- continue;
186
- if (SIDECAR_POINTER.test(line))
187
- continue; // sidecar-pointer row, pull-only
188
- count++;
189
- }
190
- return count;
277
+ return scanDoxRows(readFileSync(agentsFile, "utf8")).rows.filter((r) => !SIDECAR_POINTER.test(r.line)).length;
191
278
  }
192
- /** 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. */
193
282
  export function parseRowPaths(agentsFile) {
194
283
  if (!existsSync(agentsFile))
195
284
  return [];
196
- const text = readFileSync(agentsFile, "utf8");
197
- const paths = [];
198
- // Only rows under a `# DOX —` heading are file-index rows. Prose tables
199
- // (Subagent Routing, QA globs, …) under other headings are NOT DOX rows.
200
- let inDox = false;
201
- for (const line of text.split("\n")) {
202
- const h = line.match(/^#{1,6}\s+(.*)$/);
203
- if (h) {
204
- inDox = /^DOX\b/.test(h[1].trim());
205
- 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;
206
339
  }
207
- if (!inDox)
208
- continue;
209
- const m = line.match(/^\|\s*`([^`]+)`\s*\|/);
210
- if (m)
211
- paths.push(m[1]);
212
340
  }
213
- return paths;
341
+ return { groups, total };
214
342
  }
215
343
  /** Source-file walk (delta ①②), exported for the file-index migration. */
216
- export function sourceFiles(cwd) {
217
- return walkSource(cwd);
344
+ export function sourceFiles(cwd, ignore) {
345
+ return walkSource(cwd, [], ignore);
218
346
  }
219
347
  // delta ③: group source files by FULL parent dir (dirname), not the top-level
220
348
  // segment — this is what makes the tree directory-level.
221
- export function areaFiles(cwd) {
349
+ export function areaFiles(cwd, ignore) {
222
350
  const groups = new Map();
223
- for (const f of walkSource(cwd)) {
351
+ for (const f of walkSource(cwd, [], ignore)) {
224
352
  const rel = relative(cwd, f);
225
353
  const dir = rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : ".";
226
354
  (groups.get(dir) ?? groups.set(dir, []).get(dir)).push(rel);
@@ -231,8 +359,9 @@ export function areaFiles(cwd) {
231
359
  * AGENTS.md; only adds missing files + missing path rows. */
232
360
  export function doxInit(opts) {
233
361
  const cwd = opts.cwd;
362
+ const gi = loadGitignoreMatcher(cwd, { cwd, prune: (rel) => DEFAULT_EXCLUDE.test(rel) });
234
363
  const plan = { created: [], appended: [] };
235
- const groups = areaFiles(cwd);
364
+ const groups = areaFiles(cwd, gi);
236
365
  const ensure = (agentsFile, rows) => {
237
366
  if (existsSync(agentsFile)) {
238
367
  const existing = new Set(parseRowPaths(agentsFile));
@@ -242,14 +371,17 @@ export function doxInit(opts) {
242
371
  });
243
372
  if (missRows.length)
244
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).
245
377
  if (!opts.dryRun && missRows.length)
246
- appendFileSync(agentsFile, "\n" + missRows.join("\n") + "\n");
378
+ appendRowsToAgentsFile(agentsFile, missRows);
247
379
  }
248
380
  else {
249
381
  plan.created.push(agentsFile);
250
382
  if (!opts.dryRun) {
251
383
  mkdirSync(dirname(agentsFile), { recursive: true });
252
- 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");
253
385
  }
254
386
  }
255
387
  };
@@ -364,6 +496,11 @@ export function doxLint(opts) {
364
496
  const cwd = opts.cwd;
365
497
  const issues = [];
366
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) });
367
504
  // Top-level entries of THIS repo — the primary discriminator that stops
368
505
  // broken-ref from firing on prose that merely looks path-shaped.
369
506
  const topLevelEntries = new Set();
@@ -387,23 +524,22 @@ export function doxLint(opts) {
387
524
  const abs = join(dir, e.name);
388
525
  if (DEFAULT_EXCLUDE.test(relative(cwd, abs)))
389
526
  continue;
390
- if (e.isDirectory())
527
+ if (e.isDirectory()) {
528
+ const rel = relative(cwd, abs);
529
+ if (gi.isIgnoredDir(rel) && !gi.hasDeeperGitignore(rel))
530
+ continue;
391
531
  walkAgents(abs);
392
- else if (e.name === "AGENTS.md")
532
+ }
533
+ else if (e.name === "AGENTS.md" && !gi.isIgnored(relative(cwd, abs)))
393
534
  agentsFiles.push(abs);
394
535
  }
395
536
  };
396
537
  walkAgents(cwd);
397
- // staleness sidecar
398
- 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.
399
540
  const sf = opts.stalenessFile ?? join(cwd, ".pi", "dashboard", "kb", "dox-staleness.json");
400
- if (existsSync(sf)) {
401
- try {
402
- staleness = JSON.parse(readFileSync(sf, "utf8"));
403
- }
404
- catch { /* */ }
405
- }
406
- 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)));
407
543
  const rowPaths = new Set();
408
544
  for (const af of agentsFiles) {
409
545
  const afRel = relative(cwd, af);
@@ -420,25 +556,19 @@ export function doxLint(opts) {
420
556
  const inlineCount = countInlineRows(af);
421
557
  if (inlineCount > ROW_CAP)
422
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` });
423
- const survivingRows = [];
424
- 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();
425
568
  const afDir = dirname(af);
426
- let inDox = false;
427
- for (const line of text) {
428
- const h = line.match(/^#{1,6}\s+(.*)$/);
429
- if (h) {
430
- inDox = /^DOX\b/.test(h[1].trim());
431
- if (opts.fix)
432
- survivingRows.push(line);
433
- continue;
434
- }
435
- const m = inDox ? line.match(/^\|\s*`([^`]+)`\s*\|/) : null;
436
- if (!m) {
437
- if (opts.fix)
438
- survivingRows.push(line);
439
- continue;
440
- }
441
- const rp = m[1];
569
+ for (const row of scan.rows) {
570
+ const rp = row.path;
571
+ const line = row.line;
442
572
  // Cross-references inside the PURPOSE cell. Rot here is invisible to the
443
573
  // hash check, because the row's own file is untouched by the move.
444
574
  const purposeCell = line.slice(line.indexOf("|", line.indexOf("`" + rp + "`")) + 1);
@@ -461,17 +591,20 @@ export function doxLint(opts) {
461
591
  issues.push({ kind, agentsFile: afRel, path: rp, detail: `${kind}: ${rp} does not exist` });
462
592
  if (opts.fix && kind === "orphan") {
463
593
  fixed++;
464
- continue;
465
- } // prune orphan row
594
+ pruneIdx.add(row.lineIndex); // prune the orphan line, keep every other line byte-identical
595
+ }
466
596
  }
467
- else if (staleness[rel] && fileSha(abs) && staleness[rel] !== fileSha(abs)) {
468
- 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
+ }
469
602
  }
470
- if (opts.fix)
471
- survivingRows.push(line);
472
603
  }
473
- if (opts.fix)
474
- 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
+ }
475
608
  }
476
609
  // missing rows: md files in an area (dir containing an AGENTS.md) with no row.
477
610
  // Owner = nearest ancestor AGENTS.md (deepest dir prefix of the file's dir).
@@ -499,8 +632,10 @@ export function doxLint(opts) {
499
632
  if (owner) {
500
633
  const ownerRel = relative(cwd, owner) || "AGENTS.md";
501
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.
502
637
  if (opts.fix) {
503
- appendFileSync(owner, `| \`${md}\` | |\n`);
638
+ appendRowsToAgentsFile(owner, [`| \`${md}\` | |`]);
504
639
  fixed++;
505
640
  }
506
641
  }
@@ -510,7 +645,7 @@ export function doxLint(opts) {
510
645
  // through the `agents` doc-type lane that retrieval depends on. Opt-in, and
511
646
  // never auto-fixed: a blank purpose row is worse than an honest finding.
512
647
  if (opts.sourceFileRows) {
513
- for (const abs of sourceFiles(cwd)) {
648
+ for (const abs of sourceFiles(cwd, gi)) {
514
649
  const rel = relative(cwd, abs);
515
650
  if (rowPaths.has(rel))
516
651
  continue;
@@ -532,5 +667,5 @@ export function doxLint(opts) {
532
667
  issues.push({ kind: "missing-companion", agentsFile: comp, path: md, detail: `${md} past threshold, no ${comp}` });
533
668
  }
534
669
  }
535
- return { issues, fixed };
670
+ return { issues, fixed, filesScanned, rowsScanned };
536
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;
@@ -17,7 +25,23 @@ export interface EvalMetrics {
17
25
  /** Fraction of queries whose whole top-K page comes from one source. */
18
26
  singleSourcePageRate: number;
19
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[];
20
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[];
21
43
  export declare function evaluate(store: KbStore, golden: GoldenItem[], opts?: SearchOpts & {
22
44
  k?: number;
45
+ roots?: RootRef[];
46
+ verbose?: boolean;
23
47
  }): EvalMetrics;