@blackbelt-technology/pi-dashboard-kb 0.7.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/config.ts CHANGED
@@ -24,6 +24,16 @@ export interface RankingConfig {
24
24
  fieldWeights: { headingPath: number; heading: number; body: number };
25
25
  proximityBoost: boolean;
26
26
  diversity: { enabled: boolean; lambda: number };
27
+ /** Collapse hits to one per `(root, path)` (design D1). */
28
+ sourceDedup: boolean;
29
+ /** Share of the page reserved for the `agents` doc-type lane, 0..1 (design D3).
30
+ * 0 disables the quota. SWEPT over the bundled fixtures — see
31
+ * openspec/changes/fix-kb-search-retrieval-quality/measurements.md. */
32
+ laneQuota: number;
33
+ /** IDF-weighted coverage rerank over the candidate pool (design D4).
34
+ * Implemented, DEFAULT OFF: on the bundled fixtures it costs markdown-intent
35
+ * R@10 0.620 → 0.472 to buy source-intent 0.423 → 0.462, a net regression. */
36
+ coverageRerank: boolean;
27
37
  }
28
38
  export interface ExpandConfig {
29
39
  parent: boolean;
@@ -36,6 +46,8 @@ export interface RerankConfig {
36
46
  }
37
47
  export interface QueryExpansionConfig {
38
48
  mode: "off" | "prf" | "synonym" | "agent";
49
+ /** RM3-style pseudo-relevance-feedback tuning (design D4). */
50
+ prf: { terms: number; topK: number; dfCeiling: number };
39
51
  }
40
52
  export interface DirectoryLevelAgentsConfig {
41
53
  enabled: boolean;
@@ -110,10 +122,21 @@ export const DEFAULTS: KbConfig = {
110
122
  directoryLevelAgents: { enabled: true, claudeMd: true, mode: "pull", fallbackManifest: true },
111
123
  frontmatter: { searchableKeys: DEFAULT_SEARCHABLE_KEYS, facetKeys: DEFAULT_FACET_KEYS },
112
124
  doxEnforcement: false,
113
- ranking: { fieldWeights: { headingPath: 10, heading: 3, body: 1 }, proximityBoost: true, diversity: { enabled: true, lambda: 0.7 } },
125
+ ranking: {
126
+ fieldWeights: { headingPath: 10, heading: 3, body: 1 },
127
+ proximityBoost: true,
128
+ diversity: { enabled: true, lambda: 0.7 },
129
+ sourceDedup: true,
130
+ // 0.5 = the largest reserved share with NO markdown-intent regression
131
+ // (R@10 0.630 vs 0.611 unquota'd) while source-intent rises 0.317 → 0.500.
132
+ laneQuota: 0.5,
133
+ coverageRerank: false,
134
+ },
114
135
  expand: { parent: true, graph: false },
115
136
  rerank: { enabled: false, model: "ms-marco-MiniLM-L-6-v2", candidateK: 50 },
116
- queryExpansion: { mode: "off" },
137
+ // PRF is implemented engine-side but DEFAULT OFF: it is gated on coverage
138
+ // rerank (which measures as a net regression), and adds ~3x search latency.
139
+ queryExpansion: { mode: "off", prf: { terms: 6, topK: 10, dfCeiling: 0.1 } },
117
140
  dbPath: ".pi/dashboard/kb/index.db",
118
141
  };
119
142
 
@@ -160,6 +183,8 @@ export function validateConfig(c: Partial<KbConfig>, origin = "config"): KbConfi
160
183
  if (typeof merged.maxFileCount !== "number" && merged.maxFileCount !== null) throw err("maxFileCount must be a number or null");
161
184
  if (typeof merged.dbPath !== "string" || !merged.dbPath) throw err("dbPath must be a non-empty string");
162
185
  if (!/^(off|prf|synonym|agent)$/.test(merged.queryExpansion.mode)) throw err(`queryExpansion.mode "${merged.queryExpansion.mode}" unknown`);
186
+ const lq = merged.ranking.laneQuota;
187
+ if (typeof lq !== "number" || !Number.isFinite(lq) || lq < 0 || lq > 1) throw err("ranking.laneQuota must be a number in [0,1]");
163
188
  const fm = merged.frontmatter;
164
189
  if (!fm || !Array.isArray(fm.searchableKeys) || fm.searchableKeys.some((k) => typeof k !== "string")) throw err("frontmatter.searchableKeys must be a string array");
165
190
  if (!Array.isArray(fm.facetKeys)) throw err("frontmatter.facetKeys must be an array");
@@ -0,0 +1,223 @@
1
+ // Stale-row triage: judge a DOX row against the REAL git diff since it was
2
+ // last acknowledged, instead of guessing.
3
+ //
4
+ // `kb dox lint` marks a row "stale" when the sha256 of its file differs from the
5
+ // acknowledged hash. That only means BYTES CHANGED — it is not evidence the row
6
+ // text is wrong. The two obvious responses are both bad: bulk re-acking launders
7
+ // genuine drift, and a symbol-presence heuristic produces false positives (it
8
+ // will flag a row that correctly documents a symbol as *removed*).
9
+ //
10
+ // This module recovers real evidence. The acknowledged hash identifies a past
11
+ // state of the file, so walking the file's history for the commit whose blob
12
+ // hashes to that value pinpoints what a human last signed off on. `git diff`
13
+ // from there is exactly what the row has never been reconciled against — small
14
+ // enough to hand to a cheap model, specific enough to judge.
15
+ import { execFileSync } from "node:child_process"; // ban:child_process-ok (kb package is self-contained; owns the git history walk, no pi-dashboard-shared dep)
16
+ import { createHash } from "node:crypto";
17
+ import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
18
+ import { dirname, join, relative } from "node:path";
19
+ import { type DoxIssue, resolveRowPath } from "./dox.js";
20
+
21
+ export const ROW_RE = /^\|\s*`([^`]+)`\s*\|\s*(.*?)\s*\|\s*$/;
22
+ /** History window scanned for a blob matching the acked hash. */
23
+ export const DEFAULT_DEPTH = 60;
24
+ /** Per-item diff budget. Keeps a @fast subagent's context small and cheap. */
25
+ export const DIFF_CAP = 6000;
26
+
27
+ export interface DoxRow {
28
+ line: number;
29
+ path: string;
30
+ purpose: string;
31
+ }
32
+
33
+ export function parseRows(md: string): DoxRow[] {
34
+ const rows: DoxRow[] = [];
35
+ md.split("\n").forEach((line, i) => {
36
+ const m = line.match(ROW_RE);
37
+ if (!m) return;
38
+ if (/^-+$/.test(m[1])) return;
39
+ rows.push({ line: i, path: m[1], purpose: m[2] });
40
+ });
41
+ return rows;
42
+ }
43
+
44
+ /** Replace one row's purpose cell. Byte-identical elsewhere; no-op if absent. */
45
+ export function replaceRowPurpose(md: string, rowPath: string, newPurpose: string): string {
46
+ let hit = false;
47
+ const out = md.split("\n").map((line) => {
48
+ if (hit) return line;
49
+ const m = line.match(ROW_RE);
50
+ if (!m || m[1] !== rowPath) return line;
51
+ hit = true;
52
+ return `| \`${m[1]}\` | ${newPurpose} |`;
53
+ });
54
+ return hit ? out.join("\n") : md;
55
+ }
56
+
57
+ const sha256 = (buf: Buffer | string) => createHash("sha256").update(buf).digest("hex");
58
+
59
+ function git(cwd: string, args: string[]): string {
60
+ return execFileSync("git", args, { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
61
+ }
62
+
63
+ export interface Baseline {
64
+ found: boolean;
65
+ commit: string | null;
66
+ diff: string;
67
+ reason: string | null;
68
+ }
69
+
70
+ export function resolveBaseline(opts: {
71
+ cwd: string;
72
+ file: string;
73
+ ackedSha: string;
74
+ depth?: number;
75
+ }): Baseline {
76
+ const { cwd, file, ackedSha, depth = DEFAULT_DEPTH } = opts;
77
+ let commits: string[] = [];
78
+ try {
79
+ commits = git(cwd, ["rev-list", `-n${depth}`, "HEAD", "--", file]).trim().split("\n").filter(Boolean);
80
+ } catch {
81
+ return { found: false, commit: null, diff: "", reason: "no-history" };
82
+ }
83
+ if (!commits.length) return { found: false, commit: null, diff: "", reason: "untracked" };
84
+
85
+ for (const c of commits) {
86
+ let blob: Buffer;
87
+ try {
88
+ blob = execFileSync("git", ["show", `${c}:${file}`], { cwd, maxBuffer: 64 * 1024 * 1024 });
89
+ } catch {
90
+ continue;
91
+ }
92
+ if (sha256(blob) !== ackedSha) continue;
93
+ let diff = "";
94
+ try {
95
+ // `<commit> --` (NOT `<commit>..HEAD`): staleness is hashed from the WORKING
96
+ // TREE, so the diff must span uncommitted edits too. Using ..HEAD reports an
97
+ // empty diff for a row made stale purely by unstaged work, which would then
98
+ // be judged "unchanged" on no evidence at all.
99
+ diff = git(cwd, ["diff", c, "--", file]);
100
+ } catch {
101
+ diff = "";
102
+ }
103
+ return {
104
+ found: true,
105
+ commit: c,
106
+ diff: diff.length > DIFF_CAP ? `${diff.slice(0, DIFF_CAP)}\n…[diff truncated]` : diff,
107
+ reason: null,
108
+ };
109
+ }
110
+ // Acked state predates the window, or was acked from an uncommitted tree.
111
+ // Say so rather than diffing against an arbitrary commit.
112
+ return { found: false, commit: null, diff: "", reason: `no-match-in-last-${depth}` };
113
+ }
114
+
115
+ export interface WorkItem {
116
+ agentsFile: string;
117
+ row: string;
118
+ target: string;
119
+ purpose: string;
120
+ baseline: string | null;
121
+ baselineFound: boolean;
122
+ reason: string | null;
123
+ diff: string;
124
+ }
125
+
126
+ export function buildWorkItems(opts: {
127
+ cwd: string;
128
+ issues: DoxIssue[];
129
+ staleness: Record<string, string>;
130
+ depth?: number;
131
+ limit?: number;
132
+ }): WorkItem[] {
133
+ const { cwd, issues, staleness, depth = DEFAULT_DEPTH, limit = Number.POSITIVE_INFINITY } = opts;
134
+ const items: WorkItem[] = [];
135
+ for (const iss of issues) {
136
+ if (iss.kind !== "stale" || !iss.path) continue;
137
+ if (items.length >= limit) break;
138
+ const agentsAbs = join(cwd, iss.agentsFile);
139
+ if (!existsSync(agentsAbs)) continue;
140
+ // Reuse the lint's own resolver so triage and lint never disagree about
141
+ // which file a row points at (incl. the repo-root fallback for config rows).
142
+ const abs = resolveRowPath(dirname(agentsAbs), cwd, iss.path);
143
+ if (!existsSync(abs) || !statSync(abs).isFile()) continue;
144
+ const target = relative(cwd, abs);
145
+ const row = parseRows(readFileSync(agentsAbs, "utf8")).find((r) => r.path === iss.path);
146
+ if (!row) continue;
147
+ const acked = staleness[target] ?? staleness[iss.path];
148
+ const base = acked
149
+ ? resolveBaseline({ cwd, file: target, ackedSha: acked, depth })
150
+ : { found: false, commit: null, diff: "", reason: "not-acked" };
151
+ items.push({
152
+ agentsFile: iss.agentsFile,
153
+ row: iss.path,
154
+ target,
155
+ purpose: row.purpose,
156
+ baseline: base.commit,
157
+ baselineFound: base.found,
158
+ reason: base.reason,
159
+ diff: base.diff,
160
+ });
161
+ }
162
+ return items;
163
+ }
164
+
165
+ export interface Decision {
166
+ agentsFile: string;
167
+ row: string;
168
+ verdict: "KEEP" | "REWRITE";
169
+ purpose?: string;
170
+ note?: string;
171
+ }
172
+
173
+ export interface ApplyResult {
174
+ rewritten: number;
175
+ kept: number;
176
+ skipped: string[];
177
+ }
178
+
179
+ export function applyDecisions(opts: {
180
+ cwd: string;
181
+ decisions: Decision[];
182
+ write?: boolean;
183
+ }): ApplyResult {
184
+ const { cwd, decisions, write = false } = opts;
185
+ const res: ApplyResult = { rewritten: 0, kept: 0, skipped: [] };
186
+ for (const d of decisions) {
187
+ if (d.verdict !== "REWRITE" || !d.purpose) {
188
+ res.kept++;
189
+ continue;
190
+ }
191
+ const p = join(cwd, d.agentsFile);
192
+ if (!existsSync(p)) {
193
+ res.skipped.push(`${d.agentsFile} (missing)`);
194
+ continue;
195
+ }
196
+ const before = readFileSync(p, "utf8");
197
+ const after = replaceRowPurpose(before, d.row, d.purpose);
198
+ if (after === before) {
199
+ res.skipped.push(`${d.agentsFile} :: ${d.row} (row not found)`);
200
+ continue;
201
+ }
202
+ if (write) writeFileSync(p, after, "utf8");
203
+ res.rewritten++;
204
+ }
205
+ return res;
206
+ }
207
+
208
+ /** Re-acknowledge rows: record each target's current sha256. */
209
+ export function ackTargets(opts: { cwd: string; targets: string[]; stalenessFile: string }): number {
210
+ const { cwd, targets, stalenessFile } = opts;
211
+ const map: Record<string, string> = existsSync(stalenessFile)
212
+ ? JSON.parse(readFileSync(stalenessFile, "utf8"))
213
+ : {};
214
+ let n = 0;
215
+ for (const t of targets) {
216
+ const p = join(cwd, t);
217
+ if (!existsSync(p) || !statSync(p).isFile()) continue;
218
+ map[t] = sha256(readFileSync(p));
219
+ n++;
220
+ }
221
+ writeFileSync(stalenessFile, `${JSON.stringify(map, null, 2)}\n`, "utf8");
222
+ return n;
223
+ }
package/src/dox.ts CHANGED
@@ -2,9 +2,10 @@
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, rmSync, statSync, writeFileSync, appendFileSync } from "node:fs";
6
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
+
7
6
  import { createHash } from "node:crypto";
7
+ import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
8
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
8
9
  import type { KbStore } from "./types.js";
9
10
 
10
11
  // delta ②: exclude worktree checkouts, archived openspec proposals, and doc-example noise.
@@ -18,8 +19,20 @@ import type { KbStore } from "./types.js";
18
19
  // navigable source) and self-evident top-level docs (`CHANGELOG.md`, `CLAUDE.md`,
19
20
  // repo-root `README.md`) with no per-file DOX value; `README` anchored to root so
20
21
  // package READMEs stay documented.
21
- 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$/;
22
- const AGENTS_FILES = ["AGENTS.md"];
22
+ // `.pi` is NOT excluded wholesale: `.pi/skills/`, `.pi/agents/` and `.pi/prompts/`
23
+ // carry per-file DOX rows per the Documentation Update Protocol, and excluding the
24
+ // whole tree blinded the orphan check there. Only the non-source `.pi` subdirs
25
+ // (caches, kb index, npm/git mirrors, flow run state) are skipped.
26
+ 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$/;
27
+ /**
28
+ * `AGENTS.override.md` (pi 0.84.0) REPLACES a directory's context rather than
29
+ * adding to it, so it is listed first and shadows the other candidates in the
30
+ * SAME directory. Mirrors pi's own first-match-wins candidate list in
31
+ * `dist/core/resource-loader.js`. Ancestor inheritance is unaffected.
32
+ * See change: update-pi-core-0-84-adopt-apis.
33
+ */
34
+ const AGENTS_OVERRIDE_FILE = "AGENTS.override.md";
35
+ const AGENTS_FILES = [AGENTS_OVERRIDE_FILE, "AGENTS.md"];
23
36
  // delta ①: dox init now maps SOURCE, not docs. Source globs, minus type decls and tests.
24
37
  const SOURCE_EXT = /\.(ts|tsx|js|jsx)$/;
25
38
  const MD_EXT = /\.(md|mdx)$/i;
@@ -76,7 +89,15 @@ export function agentsChain(cwd: string, targetPath: string, opts: AgentsChainOp
76
89
  const ordered = dirs.reverse();
77
90
  const chain: AgentsEntry[] = [];
78
91
  ordered.forEach((dir, depth) => {
92
+ // An override replaces this directory's context: take it alone and skip the
93
+ // siblings, otherwise the same logical scope is injected twice.
94
+ const override = join(dir, AGENTS_OVERRIDE_FILE);
95
+ if (existsSync(override)) {
96
+ chain.push({ path: override, rel: relative(cwd, override) || AGENTS_OVERRIDE_FILE, depth });
97
+ return;
98
+ }
79
99
  for (const name of names) {
100
+ if (name === AGENTS_OVERRIDE_FILE) continue;
80
101
  const p = join(dir, name);
81
102
  if (existsSync(p)) chain.push({ path: p, rel: relative(cwd, p) || name, depth });
82
103
  }
@@ -258,20 +279,97 @@ export function doxInit(opts: DoxInitOptions): DoxInitPlan {
258
279
 
259
280
  // --- dox lint ---
260
281
 
282
+ /**
283
+ * Pull repo-path REFERENCES out of a row's purpose cell.
284
+ *
285
+ * The lint hashes the file behind each row but never validates paths written
286
+ * inside the prose, so a directory move silently rots cross-references (this is
287
+ * how a routing rule kept pointing at two deleted dirs). The hard part is not
288
+ * finding candidates — it is rejecting the ~99% that are not repo paths at all:
289
+ * URL routes, MIME types, npm specifiers, `~`/absolute paths, model ids, code
290
+ * fragments like `get/list/remove`, and descriptions of OTHER projects' layouts.
291
+ *
292
+ * Discriminators, in order of how much noise each removes:
293
+ * 1. first segment must be a real top-level entry of THIS repo — kills
294
+ * `lib/validations.ts` (consumer-project prose) and `provider/model`
295
+ * 2. must carry a source-file extension or be a glob — kills bare route paths
296
+ * 3. structural rejects: leading `~` or `/`, `@` scopes, and any char that
297
+ * cannot appear in a path we would write (`:?="'()[]{}<>` , whitespace…)
298
+ */
299
+ export function extractRefPaths(cell: string, topLevel: Set<string>): string[] {
300
+ const out: string[] = [];
301
+ for (const m of cell.matchAll(/`([^`]+)`/g)) {
302
+ const raw = m[1].trim();
303
+ if (!raw.includes("/")) continue;
304
+ if (/^[~/@]/.test(raw)) continue; // home, absolute, npm scope
305
+ if (/[:?="'()[\]{}<>|,;!#\s]/.test(raw)) continue; // routes, code, prose, placeholders
306
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: intentional non-ASCII guard
307
+ if (/[^\x20-\x7e]/.test(raw)) continue;
308
+ const p = raw.replace(/^\.\//, "").replace(/\/$/, "");
309
+ if (!p.includes("/")) continue;
310
+ if (!topLevel.has(p.split("/")[0])) continue;
311
+ if (!/\.[a-z0-9]{1,5}$/i.test(p) && !p.includes("*")) continue;
312
+ // Build output and excluded trees (`packages/electron/out/*`, `.worktrees/*`)
313
+ // are legitimately absent until built/created — flagging them is noise, and a
314
+ // check that cries wolf gets ignored.
315
+ if (DEFAULT_EXCLUDE.test(p)) continue;
316
+ out.push(p);
317
+ }
318
+ return out;
319
+ }
320
+
321
+ /** Cheap glob test for `*` / `**` reference paths (no dependency on a matcher). */
322
+ function globHit(pattern: string, cwd: string): boolean {
323
+ const rx = new RegExp(
324
+ `^${pattern
325
+ .split("/")
326
+ .map((s) =>
327
+ s
328
+ .replace(/[.+^${}()|[\]\\]/g, "\\$&")
329
+ .replace(/\*\*/g, "\u0001")
330
+ .replace(/\*/g, "[^/]*")
331
+ .replace(/\u0001/g, ".*"),
332
+ )
333
+ .join("/")}$`,
334
+ );
335
+ const walk = (dir: string, rel: string): boolean => {
336
+ let entries: import("node:fs").Dirent[] = [];
337
+ try {
338
+ entries = readdirSync(dir, { withFileTypes: true });
339
+ } catch {
340
+ return false;
341
+ }
342
+ for (const e of entries) {
343
+ const r = rel ? `${rel}/${e.name}` : e.name;
344
+ if (DEFAULT_EXCLUDE.test(r)) continue;
345
+ if (rx.test(r)) return true;
346
+ if (e.isDirectory() && walk(join(dir, e.name), r)) return true;
347
+ }
348
+ return false;
349
+ };
350
+ return walk(cwd, "");
351
+ }
352
+
261
353
  export interface DoxIssue {
262
- kind: "stale" | "orphan" | "missing" | "missing-companion" | "broken-pointer" | "over-threshold";
354
+ kind: "stale" | "orphan" | "missing" | "missing-companion" | "broken-pointer" | "broken-ref" | "over-threshold";
263
355
  agentsFile: string;
264
356
  path?: string;
265
357
  detail: string;
266
358
  // over-threshold discriminator: "bytes" = actionable (auto-injected per turn,
267
359
  // remedy = sidecar split); "rows" = informational (advisory, no injection cost).
268
- arm?: "bytes" | "rows";
360
+ // missing discriminator: "source" = an undocumented .ts/.tsx (design D9), which
361
+ // is opt-in and never auto-fixed; markdown `missing` findings carry no arm.
362
+ arm?: "bytes" | "rows" | "source";
269
363
  }
270
364
  export interface DoxLintOptions {
271
365
  json?: boolean;
272
366
  fix?: boolean;
273
367
  cwd: string;
274
368
  stalenessFile?: string; // sidecar path (source-path → ack-hash)
369
+ /** Opt-in: report undocumented SOURCE files as `missing` (design D9). OFF by
370
+ * default so an existing tree can adopt the arm incrementally instead of
371
+ * red-walling CI with a large one-time finding count. */
372
+ sourceFileRows?: boolean;
275
373
  }
276
374
  export interface DoxLintResult {
277
375
  issues: DoxIssue[];
@@ -290,6 +388,16 @@ export function doxLint(opts: DoxLintOptions): DoxLintResult {
290
388
  const issues: DoxIssue[] = [];
291
389
  let fixed = 0;
292
390
 
391
+ // Top-level entries of THIS repo — the primary discriminator that stops
392
+ // broken-ref from firing on prose that merely looks path-shaped.
393
+ const topLevelEntries = new Set<string>();
394
+ try {
395
+ for (const e of readdirSync(cwd, { withFileTypes: true })) topLevelEntries.add(e.name);
396
+ } catch {
397
+ /* empty cwd — leave the set empty, which disables broken-ref entirely */
398
+ }
399
+ const seenRefs = new Set<string>();
400
+
293
401
  // find all AGENTS.md
294
402
  const agentsFiles: string[] = [];
295
403
  // Test the path RELATIVE to cwd (mirrors walkFiles) so an ancestor dir named
@@ -337,6 +445,17 @@ export function doxLint(opts: DoxLintOptions): DoxLintResult {
337
445
  const m = inDox ? line.match(/^\|\s*`([^`]+)`\s*\|/) : null;
338
446
  if (!m) { if (opts.fix) survivingRows.push(line); continue; }
339
447
  const rp = m[1];
448
+ // Cross-references inside the PURPOSE cell. Rot here is invisible to the
449
+ // hash check, because the row's own file is untouched by the move.
450
+ const purposeCell = line.slice(line.indexOf("|", line.indexOf("`" + rp + "`")) + 1);
451
+ for (const ref of extractRefPaths(purposeCell, topLevelEntries)) {
452
+ if (seenRefs.has(ref)) continue;
453
+ seenRefs.add(ref);
454
+ const hit = ref.includes("*")
455
+ ? globHit(ref, cwd)
456
+ : existsSync(join(cwd, ref)) || existsSync(join(afDir, ref));
457
+ if (!hit) issues.push({ kind: "broken-ref", agentsFile: afRel, path: ref, detail: `broken-ref: row prose cites ${ref}, which does not exist` });
458
+ }
340
459
  const abs = resolveRowPath(afDir, cwd, rp);
341
460
  const rel = relative(cwd, abs);
342
461
  rowPaths.add(rel);
@@ -379,6 +498,22 @@ export function doxLint(opts: DoxLintOptions): DoxLintResult {
379
498
  }
380
499
  }
381
500
 
501
+ // missing rows, SOURCE arm (design D9): a .ts/.tsx in a covered area with no
502
+ // row in ANY ancestor AGENTS.md and no <file>.AGENTS.md sidecar is unreachable
503
+ // through the `agents` doc-type lane that retrieval depends on. Opt-in, and
504
+ // never auto-fixed: a blank purpose row is worse than an honest finding.
505
+ if (opts.sourceFileRows) {
506
+ for (const abs of sourceFiles(cwd)) {
507
+ const rel = relative(cwd, abs);
508
+ if (rowPaths.has(rel)) continue;
509
+ if (existsSync(join(cwd, `${rel}.AGENTS.md`))) continue;
510
+ const dir = rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : ".";
511
+ const owner = ownerOf(dir);
512
+ if (!owner) continue;
513
+ issues.push({ kind: "missing", arm: "source", agentsFile: relative(cwd, owner) || "AGENTS.md", path: rel, detail: `no row for source file ${rel}` });
514
+ }
515
+ }
516
+
382
517
  // missing companions: large source/md files with no <file>.agent.md
383
518
  for (const md of allMd) {
384
519
  const abs = join(cwd, md);
package/src/eval.ts CHANGED
@@ -14,12 +14,21 @@ export interface EvalMetrics {
14
14
  "Recall@K": number;
15
15
  MRR: number;
16
16
  "nDCG@K": number;
17
+ /** Mean count of distinct `(root, path)` sources per top-K page (D8). */
18
+ distinctSourcesAtK: number;
19
+ /** Mean fraction of slots whose source already appeared earlier on the page. */
20
+ duplicateSlotShare: number;
21
+ /** Fraction of queries whose whole top-K page comes from one source. */
22
+ singleSourcePageRate: number;
17
23
  avgLatencyMs: number;
18
24
  }
19
25
 
20
26
  export function evaluate(store: KbStore, golden: GoldenItem[], opts: SearchOpts & { k?: number } = {}): EvalMetrics {
21
27
  const k = opts.k ?? 10;
22
28
  let p1 = 0, p5 = 0, recall = 0, mrr = 0, ndcg = 0, lat = 0;
29
+ // Redundancy accumulators (D8). Precision/recall are blind to page composition
30
+ // by construction, so redundancy is tracked as its own first-class metric.
31
+ let distinct = 0, dupShare = 0, singleSource = 0, pages = 0;
23
32
  for (const g of golden) {
24
33
  const t = performance.now();
25
34
  const res = store.search(g.q, { ...opts, limit: k });
@@ -35,6 +44,13 @@ export function evaluate(store: KbStore, golden: GoldenItem[], opts: SearchOpts
35
44
  mrr += 1 / first;
36
45
  ndcg += 1 / Math.log2(first + 1); // IDCG=1 (single relevant target)
37
46
  }
47
+ if (res.length) {
48
+ const sources = new Set(res.map((r) => `${r.root}\u001f${r.path}`));
49
+ distinct += sources.size;
50
+ dupShare += (res.length - sources.size) / res.length;
51
+ if (sources.size === 1) singleSource++;
52
+ pages++;
53
+ }
38
54
  }
39
55
  const n = golden.length || 1;
40
56
  return {
@@ -44,6 +60,9 @@ export function evaluate(store: KbStore, golden: GoldenItem[], opts: SearchOpts
44
60
  "Recall@K": +(recall / n).toFixed(3),
45
61
  MRR: +(mrr / n).toFixed(3),
46
62
  "nDCG@K": +(ndcg / n).toFixed(3),
63
+ distinctSourcesAtK: +(distinct / (pages || 1)).toFixed(3),
64
+ duplicateSlotShare: +(dupShare / (pages || 1)).toFixed(3),
65
+ singleSourcePageRate: +(singleSource / (pages || 1)).toFixed(3),
47
66
  avgLatencyMs: +(lat / n).toFixed(2),
48
67
  };
49
68
  }
package/src/indexer.ts CHANGED
@@ -68,12 +68,12 @@ function walk(dir: string, base: string, out: string[] = []): string[] {
68
68
  return out;
69
69
  }
70
70
 
71
- function docTypeOf(rel: string, includeSourceMarkdown: boolean): DocType {
71
+ export function docTypeOf(rel: string, includeSourceMarkdown: boolean): DocType {
72
72
  const base = rel.split("/").pop() ?? "";
73
73
  // `<File>.AGENTS.md` = per-file index sidecar (large-row promotion). Classified
74
74
  // `agents` so it is searchable, but its name != "AGENTS.md" so pi's native
75
75
  // up-walk never auto-injects it (pull-only via kb search).
76
- if (base === "AGENTS.md" || base === "CLAUDE.md" || base.endsWith(".AGENTS.md")) return "agents";
76
+ if (base === "AGENTS.override.md" || base === "AGENTS.md" || base === "CLAUDE.md" || base.endsWith(".AGENTS.md")) return "agents";
77
77
  if (includeSourceMarkdown && /(^|\/)(src|lib|app|packages)\//.test(rel)) return "source-md";
78
78
  return "doc";
79
79
  }
package/src/render.ts CHANGED
@@ -20,14 +20,30 @@ export interface RenderOpts {
20
20
 
21
21
  const SNIPPET_MAX = 160;
22
22
 
23
+ /** Leaf of a `A > B > C` breadcrumb. 47% of a rendered page was breadcrumb text
24
+ * and 38% of that was a prefix repeated inside one file group, while the leaf
25
+ * carries the discriminating token. Full `headingPath` stays in `KbHit` and in
26
+ * the JSON format so `kb_get(path, section)` addressing still works.
27
+ * See change: fix-kb-search-retrieval-quality (design D5). */
28
+ function leafHeading(headingPath: string): string {
29
+ const parts = headingPath.split(" > ");
30
+ return parts[parts.length - 1] || headingPath;
31
+ }
32
+
23
33
  /** Render hits to text. `rank` is a 1-based ordinal over the given (post-limit) list. */
24
34
  export function renderHits(hits: KbHit[], opts: RenderOpts): string {
25
35
  const { leading, parentGlyph, multiline } = opts;
26
36
  return hits
27
37
  .map((h, i) => {
28
38
  const lead = leading === "rank" ? String(i + 1) : h.score.toFixed(2);
29
- const head = `${lead} ${h.path} :: ${h.headingPath}`;
30
- const dup = h.akaPaths && h.akaPaths.length ? `(+${h.akaPaths.length} dup)` : "";
39
+ const head = `${lead} ${h.path} :: ${leafHeading(h.headingPath)}`;
40
+ const marks: string[] = [];
41
+ if (h.akaPaths?.length) marks.push(`(+${h.akaPaths.length} dup)`);
42
+ // Per-source match count from source-level dedup: a free relevance signal
43
+ // ("this file is the topic authority") in five tokens.
44
+ const sup = h.suppressedSections ?? 0;
45
+ if (sup > 0) marks.push(`(+${sup} more section${sup === 1 ? "" : "s"})`);
46
+ const dup = marks.join(" ");
31
47
  const snippet = h.snippet.replace(/\s+/g, " ").slice(0, SNIPPET_MAX);
32
48
  if (multiline) {
33
49
  const lines = [head];