@blackbelt-technology/pi-dashboard-kb 0.6.1 → 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/README.md ADDED
@@ -0,0 +1,23 @@
1
+ # Pi Dashboard KB
2
+
3
+ Directory-based SQLite/FTS5 knowledge base over markdown, queryable by LLM agents.
4
+
5
+ Structural heading chunking, a Tier-1 heading graph, content-hash incremental
6
+ indexing, near-duplicate dedup, and BM25F ranking. Zero runtime dependencies —
7
+ built on `node:sqlite`.
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ npm install -g @blackbelt-technology/pi-dashboard-kb
13
+ kb search "how does pairing work"
14
+ kb agents packages/server/src/index.ts
15
+ kb dox lint
16
+ ```
17
+
18
+ Pair it with `@blackbelt-technology/pi-dashboard-kb-extension` to expose `kb_search`,
19
+ `kb_get` and `kb_neighbors` as pi tools.
20
+
21
+ ## License
22
+
23
+ MIT — part of [pi-agent-dashboard](https://github.com/BlackBeltTechnology/pi-agent-dashboard).
package/dist/chunker.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type FmValue } from "./frontmatter.js";
1
2
  import type { Chunk, DocType } from "./types.js";
2
3
  export interface ChunkInput {
3
4
  root: string;
@@ -7,8 +8,9 @@ export interface ChunkInput {
7
8
  }
8
9
  export interface ParseResult {
9
10
  chunks: Chunk[];
10
- frontmatter: Record<string, unknown> | null;
11
+ frontmatter: Record<string, FmValue> | null;
11
12
  wikilinks: string[];
12
13
  mdLinks: string[];
14
+ parseFailed: boolean;
13
15
  }
14
16
  export declare function chunkMarkdown(input: ChunkInput): ParseResult;
package/dist/chunker.js CHANGED
@@ -2,29 +2,13 @@
2
2
  // Line-based with a fenced-code state machine; validated in the prototype
3
3
  // (research §2.5). mdast (unified/remark) is the documented refinement.
4
4
  import { createHash } from "node:crypto";
5
+ import { parseFrontmatter } from "./frontmatter.js";
5
6
  const MIN_CHUNK_CHARS = 100;
6
7
  const MAX_CHUNK_CHARS = 4000;
7
8
  const sha = (s) => createHash("sha256").update(s).digest("hex");
8
- function parseFrontmatter(text) {
9
- if (!text.startsWith("---\n"))
10
- return { body: text, fm: null };
11
- const end = text.indexOf("\n---", 4);
12
- if (end === -1)
13
- return { body: text, fm: null };
14
- const raw = text.slice(4, end);
15
- const fm = {};
16
- for (const line of raw.split("\n")) {
17
- const m = line.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);
18
- if (!m)
19
- continue;
20
- const [, k, v] = m;
21
- fm[k] = v.startsWith("[") ? v.replace(/^\[|\]$/g, "").split(",").map((s) => s.trim().replace(/^["']|["']$/g, "")).filter(Boolean) : v.replace(/^["']|["']$/g, "");
22
- }
23
- return { body: text.slice(end + 4), fm };
24
- }
25
9
  export function chunkMarkdown(input) {
26
10
  const docType = input.docType ?? "doc";
27
- const { body: text, fm } = parseFrontmatter(input.text);
11
+ const { body: text, fm, parseFailed } = parseFrontmatter(input.text);
28
12
  const lines = text.split("\n");
29
13
  const fileTitle = input.path.split("/").pop().replace(/\.(md|mdx|markdown)$/i, "");
30
14
  const raw = [];
@@ -122,5 +106,5 @@ export function chunkMarkdown(input) {
122
106
  }));
123
107
  const wikilinks = [...input.text.matchAll(/\[\[([^\]]+)\]\]/g)].map((m) => m[1].trim());
124
108
  const mdLinks = [...input.text.matchAll(/\]\(([^)]+\.mdx?)\)/g)].map((m) => m[1].trim());
125
- return { chunks, frontmatter: fm, wikilinks, mdLinks };
109
+ return { chunks, frontmatter: fm, wikilinks, mdLinks, parseFailed };
126
110
  }
package/dist/cli.js CHANGED
@@ -2,17 +2,18 @@
2
2
  // kb CLI (Phase 1): index | search | neighbors | backlinks | get | config
3
3
  // Run (dev): NODE_OPTIONS=--experimental-sqlite tsx src/cli.ts <cmd> ...
4
4
  // Shipped bin builds to dist/cli.js (build step deferred).
5
- import { readFileSync } from "node:fs";
6
- import { resolve } from "node:path";
7
- import { loadConfig } from "./config.js";
5
+ import { existsSync, readFileSync } from "node:fs";
6
+ import { join, resolve } from "node:path";
7
+ import { frontmatterConfigHash, loadConfig } from "./config.js";
8
8
  import { agentsChain, doxInit, doxLint } from "./dox.js";
9
+ import { ackTargets, applyDecisions, buildWorkItems } from "./dox-triage.js";
9
10
  import { evaluate } from "./eval.js";
10
11
  import { runIndexAtomic } from "./index-run.js";
11
12
  import { indexSource } from "./indexer.js";
12
13
  import { kbInit } from "./init.js";
13
14
  import { renderHits } from "./render.js";
14
15
  import { resolveAll } from "./sources.js";
15
- import { SqliteFtsStore } from "./sqlite-store.js";
16
+ import { SCHEMA_VERSION, SqliteFtsStore } from "./sqlite-store.js";
16
17
  import { defaultPromptTrust } from "./trust.js";
17
18
  function parse(argv) {
18
19
  const f = { _: [] };
@@ -76,14 +77,22 @@ function openStore(cfg) {
76
77
  return store;
77
78
  }
78
79
  async function runIndex(cfg, store, sources, force = false) {
80
+ // Apply the same schema-version / facet-config gate as runIndexAtomic so the
81
+ // auto-index-on-search path also picks up new structures after an upgrade or a
82
+ // frontmatter-config change (else the DB stays stale until an explicit `index`).
83
+ const hash = frontmatterConfigHash(cfg.frontmatter);
84
+ const stale = (store.getUserVersion?.() ?? 0) < SCHEMA_VERSION || (store.getMeta?.("facetConfigHash") ?? null) !== hash;
85
+ const eff = force || stale;
79
86
  let scanned = 0, changed = 0, deleted = 0, chunks = 0;
80
87
  for (const s of sources) {
81
- const st = await indexSource(store, { root: s.id, dir: s.dir }, { force, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions });
88
+ const st = await indexSource(store, { root: s.id, dir: s.dir }, { force: eff, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions, frontmatter: cfg.frontmatter });
82
89
  scanned += st.scanned;
83
90
  changed += st.changed;
84
91
  deleted += st.deleted;
85
92
  chunks += st.chunks;
86
93
  }
94
+ store.setUserVersion?.(SCHEMA_VERSION);
95
+ store.setMeta?.("facetConfigHash", hash);
87
96
  return { scanned, changed, deleted, chunks };
88
97
  }
89
98
  /** Resolve sources for a run. --source overrides (filesystem, sync); otherwise
@@ -107,12 +116,17 @@ Usage:
107
116
  kb search "<query>" [--limit N] [--root id] [--doc-type doc|agents|source-md]
108
117
  [--expand-parent|--no-expand-parent] [--expand-graph] [--rerank]
109
118
  [--expand-query] [--json] [--no-reindex] [--source <dir>...] [--db <path>]
119
+ [--no-source-dedup] [--no-lane-quota] [--no-coverage-rerank]
120
+ (--limit bounds distinct SOURCES, not chunks)
110
121
  kb neighbors "<node>" [--depth N] [--rel child_of|links_to|references|has_tag]
111
122
  kb backlinks "<node>"
112
123
  kb get <path> [--section "<heading_path>"]
113
124
  kb agents <path> nearest AGENTS.md chain (root→nearest); --fallback-manifest
114
125
  kb dox init [--dry-run] scaffold a DOX AGENTS.md tree (path rows only)
115
- kb dox lint [--json] [--fix] audit DOX tree drift
126
+ kb dox lint [--json] [--fix] [--source-rows] audit DOX tree drift
127
+ (--source-rows also reports undocumented .ts/.tsx)
128
+ kb dox triage [--json] [--limit N] triage STALE rows vs the git diff since ack
129
+ [--apply <d.json> [--write]] [--ack <targets.json>]
116
130
  kb eval --golden <file.json> [--limit N] [--doc-type ...] [--no-reindex]
117
131
  kb config show resolved config
118
132
  Global: --cwd <dir> --config <file>`;
@@ -169,7 +183,9 @@ function main() {
169
183
  return;
170
184
  }
171
185
  if (sub === "lint") {
172
- const r = doxLint({ cwd, json: !!flags.json, fix: !!flags.fix });
186
+ // --source-rows opts into the D9 source-file `missing` arm (off by default
187
+ // so an existing tree adopts it incrementally). See change: fix-kb-search-retrieval-quality.
188
+ const r = doxLint({ cwd, json: !!flags.json, fix: !!flags.fix, sourceFileRows: !!flags["source-rows"] });
173
189
  if (flags.json)
174
190
  console.log(JSON.stringify(r, null, 2));
175
191
  else
@@ -179,6 +195,37 @@ function main() {
179
195
  process.exit(1);
180
196
  return;
181
197
  }
198
+ if (sub === "triage") {
199
+ const stalenessFile = flags["staleness-file"] ?? join(cwd, ".pi/dashboard/kb/dox-staleness.json");
200
+ if (flags.apply) {
201
+ const decisions = JSON.parse(readFileSync(flags.apply, "utf8"));
202
+ const r = applyDecisions({ cwd, decisions, write: !!flags.write });
203
+ for (const s of r.skipped)
204
+ console.error(`skipped: ${s}`);
205
+ console.log(`${flags.write ? "applied" : "dry-run"}: ${r.rewritten} rewritten, ${r.kept} kept`);
206
+ if (!flags.write)
207
+ console.log("re-run with --write to apply");
208
+ return;
209
+ }
210
+ if (flags.ack) {
211
+ const targets = JSON.parse(readFileSync(flags.ack, "utf8"));
212
+ console.log(`re-acked ${ackTargets({ cwd, targets, stalenessFile })} entries`);
213
+ return;
214
+ }
215
+ const staleness = existsSync(stalenessFile) ? JSON.parse(readFileSync(stalenessFile, "utf8")) : {};
216
+ const items = buildWorkItems({ cwd, issues: doxLint({ cwd }).issues, staleness, limit: flags.limit ? Number(flags.limit) : undefined });
217
+ if (flags.json) {
218
+ console.log(JSON.stringify(items, null, 2));
219
+ return;
220
+ }
221
+ const noBase = items.filter((i) => !i.baselineFound);
222
+ console.log(`stale rows: ${items.length}`);
223
+ console.log(` with a recoverable diff : ${items.length - noBase.length}`);
224
+ console.log(` no baseline (needs eyes): ${noBase.length}`);
225
+ for (const i of items)
226
+ console.log(` ${i.baselineFound ? "diff" : "????"}\t${i.agentsFile}\t${i.row}`);
227
+ return;
228
+ }
182
229
  console.error(`unknown dox subcommand: ${sub}`);
183
230
  process.exit(2);
184
231
  }
@@ -206,7 +253,8 @@ async function runCmd(cmd, flags) {
206
253
  const s = await runIndexAtomic({
207
254
  dbPath: cfg.dbAbsPath,
208
255
  sources: sources.map((x) => ({ id: x.id, dir: x.dir })),
209
- indexOpts: { force: !!flags.force, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions },
256
+ indexOpts: { force: !!flags.force, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions, frontmatter: cfg.frontmatter },
257
+ facetConfigHash: frontmatterConfigHash(cfg.frontmatter),
210
258
  explicit,
211
259
  });
212
260
  console.log(`indexed ${s.scanned} files (${s.changed} changed, ${s.deleted} deleted, ${s.chunks} chunks) in ${(performance.now() - t).toFixed(0)}ms`);
@@ -232,6 +280,11 @@ async function runCmd(cmd, flags) {
232
280
  fieldWeights: cfg.ranking.fieldWeights,
233
281
  proximityBoost: cfg.ranking.proximityBoost,
234
282
  diversity: cfg.ranking.diversity,
283
+ // `limit` bounds distinct SOURCES, not chunks. See change: fix-kb-search-retrieval-quality.
284
+ sourceDedup: flags["no-source-dedup"] ? false : cfg.ranking.sourceDedup,
285
+ laneQuota: flags["no-lane-quota"] ? 0 : cfg.ranking.laneQuota,
286
+ coverageRerank: flags["no-coverage-rerank"] ? false : cfg.ranking.coverageRerank,
287
+ prf: cfg.queryExpansion.prf,
235
288
  expandParent: flags["no-expand-parent"] ? false : (cfg.expand.parent || !!flags["expand-parent"]),
236
289
  expandGraph: cfg.expand.graph || !!flags["expand-graph"],
237
290
  rerank: cfg.rerank.enabled || !!flags.rerank,
@@ -262,7 +315,10 @@ async function runCmd(cmd, flags) {
262
315
  if (c)
263
316
  break;
264
317
  }
265
- console.log(c ? c.body : `(not found: ${flags._[1]})`);
318
+ // A path-only fetch of a multi-chunk file must never look like the whole
319
+ // file. See change: fix-kb-search-retrieval-quality (design D7).
320
+ const more = c?.suppressedSections ?? 0;
321
+ console.log(c ? (more > 0 ? `${c.body}\n\n(+${more} more section${more === 1 ? "" : "s"} in this file — pass --section <headingPath> to fetch one)` : c.body) : `(not found: ${flags._[1]})`);
266
322
  }
267
323
  else if (cmd === "eval") {
268
324
  const gf = flags.golden;
package/dist/config.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type FacetKeyConfig } from "./frontmatter.js";
1
2
  export interface SourceConfig {
2
3
  kind?: "filesystem" | "npm" | "git" | "https";
3
4
  ref: string;
@@ -19,6 +20,16 @@ export interface RankingConfig {
19
20
  enabled: boolean;
20
21
  lambda: number;
21
22
  };
23
+ /** Collapse hits to one per `(root, path)` (design D1). */
24
+ sourceDedup: boolean;
25
+ /** Share of the page reserved for the `agents` doc-type lane, 0..1 (design D3).
26
+ * 0 disables the quota. SWEPT over the bundled fixtures — see
27
+ * openspec/changes/fix-kb-search-retrieval-quality/measurements.md. */
28
+ laneQuota: number;
29
+ /** IDF-weighted coverage rerank over the candidate pool (design D4).
30
+ * Implemented, DEFAULT OFF: on the bundled fixtures it costs markdown-intent
31
+ * R@10 0.620 → 0.472 to buy source-intent 0.423 → 0.462, a net regression. */
32
+ coverageRerank: boolean;
22
33
  }
23
34
  export interface ExpandConfig {
24
35
  parent: boolean;
@@ -31,6 +42,12 @@ export interface RerankConfig {
31
42
  }
32
43
  export interface QueryExpansionConfig {
33
44
  mode: "off" | "prf" | "synonym" | "agent";
45
+ /** RM3-style pseudo-relevance-feedback tuning (design D4). */
46
+ prf: {
47
+ terms: number;
48
+ topK: number;
49
+ dfCeiling: number;
50
+ };
34
51
  }
35
52
  export interface DirectoryLevelAgentsConfig {
36
53
  enabled: boolean;
@@ -38,6 +55,10 @@ export interface DirectoryLevelAgentsConfig {
38
55
  mode: "pull" | "push";
39
56
  fallbackManifest: boolean;
40
57
  }
58
+ export interface FrontmatterConfig {
59
+ searchableKeys: string[];
60
+ facetKeys: FacetKeyConfig[];
61
+ }
41
62
  export interface KbConfig {
42
63
  sources: SourceConfig[];
43
64
  roots?: Array<{
@@ -71,6 +92,7 @@ export interface KbConfig {
71
92
  frontmatter: boolean;
72
93
  };
73
94
  directoryLevelAgents: DirectoryLevelAgentsConfig;
95
+ frontmatter: FrontmatterConfig;
74
96
  doxEnforcement: boolean;
75
97
  ranking: RankingConfig;
76
98
  expand: ExpandConfig;
@@ -92,6 +114,9 @@ export interface ResolvedConfig extends KbConfig {
92
114
  origin: "project" | "global" | "defaults";
93
115
  }
94
116
  export declare const DEFAULTS: KbConfig;
117
+ /** Stable hash of the frontmatter routing config. A change forces a full reindex
118
+ * (design D6) since existing property rows/meta chunks reflect the old routing. */
119
+ export declare function frontmatterConfigHash(fm: FrontmatterConfig): string;
95
120
  /** Layer configs left→right, deep-merging the known nested object keys. */
96
121
  export declare function mergeConfig(...layers: Array<Partial<KbConfig> | null | undefined>): Partial<KbConfig>;
97
122
  /** Validate a parsed config shape; throw with a precise message on violation. */
package/dist/config.js CHANGED
@@ -2,9 +2,11 @@
2
2
  // → global `~/.pi/dashboard/knowledge_base.json` → built-in defaults.
3
3
  // Project file is used whole; absent fields fall back to global, then defaults.
4
4
  // No file-count cap by default (requirement #1).
5
+ import { createHash } from "node:crypto";
5
6
  import { existsSync, readFileSync } from "node:fs";
6
7
  import { homedir } from "node:os";
7
8
  import { isAbsolute, join, resolve } from "node:path";
9
+ import { DEFAULT_FACET_KEYS, DEFAULT_SEARCHABLE_KEYS } from "./frontmatter.js";
8
10
  function expandTilde(p) {
9
11
  return p.startsWith("~/") ? join(homedir(), p.slice(2)) : p;
10
12
  }
@@ -28,16 +30,37 @@ export const DEFAULTS = {
28
30
  // no per-turn injection. Push mode stays gated behind the context-cost spike
29
31
  // (see change migrate-file-index-to-agents-tree design §5).
30
32
  directoryLevelAgents: { enabled: true, claudeMd: true, mode: "pull", fallbackManifest: true },
33
+ frontmatter: { searchableKeys: DEFAULT_SEARCHABLE_KEYS, facetKeys: DEFAULT_FACET_KEYS },
31
34
  doxEnforcement: false,
32
- ranking: { fieldWeights: { headingPath: 10, heading: 3, body: 1 }, proximityBoost: true, diversity: { enabled: true, lambda: 0.7 } },
35
+ ranking: {
36
+ fieldWeights: { headingPath: 10, heading: 3, body: 1 },
37
+ proximityBoost: true,
38
+ diversity: { enabled: true, lambda: 0.7 },
39
+ sourceDedup: true,
40
+ // 0.5 = the largest reserved share with NO markdown-intent regression
41
+ // (R@10 0.630 vs 0.611 unquota'd) while source-intent rises 0.317 → 0.500.
42
+ laneQuota: 0.5,
43
+ coverageRerank: false,
44
+ },
33
45
  expand: { parent: true, graph: false },
34
46
  rerank: { enabled: false, model: "ms-marco-MiniLM-L-6-v2", candidateK: 50 },
35
- queryExpansion: { mode: "off" },
47
+ // PRF is implemented engine-side but DEFAULT OFF: it is gated on coverage
48
+ // rerank (which measures as a net regression), and adds ~3x search latency.
49
+ queryExpansion: { mode: "off", prf: { terms: 6, topK: 10, dfCeiling: 0.1 } },
36
50
  dbPath: ".pi/dashboard/kb/index.db",
37
51
  };
38
52
  // Nested object keys that need one-level field fill-in (not wholesale replace),
39
53
  // so a partial `{ranking:{proximityBoost:false}}` keeps default fieldWeights/diversity.
40
- const NESTED_KEYS = ["chunking", "dedup", "graph", "directoryLevelAgents", "ranking", "expand", "rerank", "queryExpansion"];
54
+ const NESTED_KEYS = ["chunking", "dedup", "graph", "directoryLevelAgents", "frontmatter", "ranking", "expand", "rerank", "queryExpansion"];
55
+ /** Stable hash of the frontmatter routing config. A change forces a full reindex
56
+ * (design D6) since existing property rows/meta chunks reflect the old routing. */
57
+ export function frontmatterConfigHash(fm) {
58
+ const norm = {
59
+ searchableKeys: [...fm.searchableKeys].sort(),
60
+ facetKeys: [...fm.facetKeys].map((f) => ({ key: f.key, type: f.type ?? "string" })).sort((a, b) => a.key.localeCompare(b.key)),
61
+ };
62
+ return createHash("sha256").update(JSON.stringify(norm)).digest("hex").slice(0, 16);
63
+ }
41
64
  /** Layer configs left→right, deep-merging the known nested object keys. */
42
65
  export function mergeConfig(...layers) {
43
66
  const out = {};
@@ -74,6 +97,20 @@ export function validateConfig(c, origin = "config") {
74
97
  throw err("dbPath must be a non-empty string");
75
98
  if (!/^(off|prf|synonym|agent)$/.test(merged.queryExpansion.mode))
76
99
  throw err(`queryExpansion.mode "${merged.queryExpansion.mode}" unknown`);
100
+ const lq = merged.ranking.laneQuota;
101
+ if (typeof lq !== "number" || !Number.isFinite(lq) || lq < 0 || lq > 1)
102
+ throw err("ranking.laneQuota must be a number in [0,1]");
103
+ const fm = merged.frontmatter;
104
+ if (!fm || !Array.isArray(fm.searchableKeys) || fm.searchableKeys.some((k) => typeof k !== "string"))
105
+ throw err("frontmatter.searchableKeys must be a string array");
106
+ if (!Array.isArray(fm.facetKeys))
107
+ throw err("frontmatter.facetKeys must be an array");
108
+ for (const f of fm.facetKeys) {
109
+ if (typeof f !== "object" || f === null || typeof f.key !== "string")
110
+ throw err("each frontmatter.facetKeys entry needs a string `key`");
111
+ if (f.type != null && !/^(string|number|date)$/.test(f.type))
112
+ throw err(`frontmatter facet key "${f.key}" has unknown type "${f.type}"`);
113
+ }
77
114
  return merged;
78
115
  }
79
116
  export function projectConfigPath(cwd) {
@@ -0,0 +1,66 @@
1
+ import { type DoxIssue } from "./dox.js";
2
+ export declare const ROW_RE: RegExp;
3
+ /** History window scanned for a blob matching the acked hash. */
4
+ export declare const DEFAULT_DEPTH = 60;
5
+ /** Per-item diff budget. Keeps a @fast subagent's context small and cheap. */
6
+ export declare const DIFF_CAP = 6000;
7
+ export interface DoxRow {
8
+ line: number;
9
+ path: string;
10
+ purpose: string;
11
+ }
12
+ export declare function parseRows(md: string): DoxRow[];
13
+ /** Replace one row's purpose cell. Byte-identical elsewhere; no-op if absent. */
14
+ export declare function replaceRowPurpose(md: string, rowPath: string, newPurpose: string): string;
15
+ export interface Baseline {
16
+ found: boolean;
17
+ commit: string | null;
18
+ diff: string;
19
+ reason: string | null;
20
+ }
21
+ export declare function resolveBaseline(opts: {
22
+ cwd: string;
23
+ file: string;
24
+ ackedSha: string;
25
+ depth?: number;
26
+ }): Baseline;
27
+ export interface WorkItem {
28
+ agentsFile: string;
29
+ row: string;
30
+ target: string;
31
+ purpose: string;
32
+ baseline: string | null;
33
+ baselineFound: boolean;
34
+ reason: string | null;
35
+ diff: string;
36
+ }
37
+ export declare function buildWorkItems(opts: {
38
+ cwd: string;
39
+ issues: DoxIssue[];
40
+ staleness: Record<string, string>;
41
+ depth?: number;
42
+ limit?: number;
43
+ }): WorkItem[];
44
+ export interface Decision {
45
+ agentsFile: string;
46
+ row: string;
47
+ verdict: "KEEP" | "REWRITE";
48
+ purpose?: string;
49
+ note?: string;
50
+ }
51
+ export interface ApplyResult {
52
+ rewritten: number;
53
+ kept: number;
54
+ skipped: string[];
55
+ }
56
+ export declare function applyDecisions(opts: {
57
+ cwd: string;
58
+ decisions: Decision[];
59
+ write?: boolean;
60
+ }): ApplyResult;
61
+ /** Re-acknowledge rows: record each target's current sha256. */
62
+ export declare function ackTargets(opts: {
63
+ cwd: string;
64
+ targets: string[];
65
+ stalenessFile: string;
66
+ }): number;
@@ -0,0 +1,176 @@
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 { resolveRowPath } from "./dox.js";
20
+ export const ROW_RE = /^\|\s*`([^`]+)`\s*\|\s*(.*?)\s*\|\s*$/;
21
+ /** History window scanned for a blob matching the acked hash. */
22
+ export const DEFAULT_DEPTH = 60;
23
+ /** Per-item diff budget. Keeps a @fast subagent's context small and cheap. */
24
+ export const DIFF_CAP = 6000;
25
+ export function parseRows(md) {
26
+ const rows = [];
27
+ md.split("\n").forEach((line, i) => {
28
+ const m = line.match(ROW_RE);
29
+ if (!m)
30
+ return;
31
+ if (/^-+$/.test(m[1]))
32
+ return;
33
+ rows.push({ line: i, path: m[1], purpose: m[2] });
34
+ });
35
+ return rows;
36
+ }
37
+ /** Replace one row's purpose cell. Byte-identical elsewhere; no-op if absent. */
38
+ export function replaceRowPurpose(md, rowPath, newPurpose) {
39
+ let hit = false;
40
+ const out = md.split("\n").map((line) => {
41
+ if (hit)
42
+ return line;
43
+ const m = line.match(ROW_RE);
44
+ if (!m || m[1] !== rowPath)
45
+ return line;
46
+ hit = true;
47
+ return `| \`${m[1]}\` | ${newPurpose} |`;
48
+ });
49
+ return hit ? out.join("\n") : md;
50
+ }
51
+ const sha256 = (buf) => createHash("sha256").update(buf).digest("hex");
52
+ function git(cwd, args) {
53
+ return execFileSync("git", args, { cwd, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
54
+ }
55
+ export function resolveBaseline(opts) {
56
+ const { cwd, file, ackedSha, depth = DEFAULT_DEPTH } = opts;
57
+ let commits = [];
58
+ try {
59
+ commits = git(cwd, ["rev-list", `-n${depth}`, "HEAD", "--", file]).trim().split("\n").filter(Boolean);
60
+ }
61
+ catch {
62
+ return { found: false, commit: null, diff: "", reason: "no-history" };
63
+ }
64
+ if (!commits.length)
65
+ return { found: false, commit: null, diff: "", reason: "untracked" };
66
+ for (const c of commits) {
67
+ let blob;
68
+ try {
69
+ blob = execFileSync("git", ["show", `${c}:${file}`], { cwd, maxBuffer: 64 * 1024 * 1024 });
70
+ }
71
+ catch {
72
+ continue;
73
+ }
74
+ if (sha256(blob) !== ackedSha)
75
+ continue;
76
+ let diff = "";
77
+ try {
78
+ // `<commit> --` (NOT `<commit>..HEAD`): staleness is hashed from the WORKING
79
+ // TREE, so the diff must span uncommitted edits too. Using ..HEAD reports an
80
+ // empty diff for a row made stale purely by unstaged work, which would then
81
+ // be judged "unchanged" on no evidence at all.
82
+ diff = git(cwd, ["diff", c, "--", file]);
83
+ }
84
+ catch {
85
+ diff = "";
86
+ }
87
+ return {
88
+ found: true,
89
+ commit: c,
90
+ diff: diff.length > DIFF_CAP ? `${diff.slice(0, DIFF_CAP)}\n…[diff truncated]` : diff,
91
+ reason: null,
92
+ };
93
+ }
94
+ // Acked state predates the window, or was acked from an uncommitted tree.
95
+ // Say so rather than diffing against an arbitrary commit.
96
+ return { found: false, commit: null, diff: "", reason: `no-match-in-last-${depth}` };
97
+ }
98
+ export function buildWorkItems(opts) {
99
+ const { cwd, issues, staleness, depth = DEFAULT_DEPTH, limit = Number.POSITIVE_INFINITY } = opts;
100
+ const items = [];
101
+ for (const iss of issues) {
102
+ if (iss.kind !== "stale" || !iss.path)
103
+ continue;
104
+ if (items.length >= limit)
105
+ break;
106
+ const agentsAbs = join(cwd, iss.agentsFile);
107
+ if (!existsSync(agentsAbs))
108
+ continue;
109
+ // Reuse the lint's own resolver so triage and lint never disagree about
110
+ // which file a row points at (incl. the repo-root fallback for config rows).
111
+ const abs = resolveRowPath(dirname(agentsAbs), cwd, iss.path);
112
+ if (!existsSync(abs) || !statSync(abs).isFile())
113
+ continue;
114
+ const target = relative(cwd, abs);
115
+ const row = parseRows(readFileSync(agentsAbs, "utf8")).find((r) => r.path === iss.path);
116
+ if (!row)
117
+ continue;
118
+ const acked = staleness[target] ?? staleness[iss.path];
119
+ const base = acked
120
+ ? resolveBaseline({ cwd, file: target, ackedSha: acked, depth })
121
+ : { found: false, commit: null, diff: "", reason: "not-acked" };
122
+ items.push({
123
+ agentsFile: iss.agentsFile,
124
+ row: iss.path,
125
+ target,
126
+ purpose: row.purpose,
127
+ baseline: base.commit,
128
+ baselineFound: base.found,
129
+ reason: base.reason,
130
+ diff: base.diff,
131
+ });
132
+ }
133
+ return items;
134
+ }
135
+ export function applyDecisions(opts) {
136
+ const { cwd, decisions, write = false } = opts;
137
+ const res = { rewritten: 0, kept: 0, skipped: [] };
138
+ for (const d of decisions) {
139
+ if (d.verdict !== "REWRITE" || !d.purpose) {
140
+ res.kept++;
141
+ continue;
142
+ }
143
+ const p = join(cwd, d.agentsFile);
144
+ if (!existsSync(p)) {
145
+ res.skipped.push(`${d.agentsFile} (missing)`);
146
+ continue;
147
+ }
148
+ const before = readFileSync(p, "utf8");
149
+ const after = replaceRowPurpose(before, d.row, d.purpose);
150
+ if (after === before) {
151
+ res.skipped.push(`${d.agentsFile} :: ${d.row} (row not found)`);
152
+ continue;
153
+ }
154
+ if (write)
155
+ writeFileSync(p, after, "utf8");
156
+ res.rewritten++;
157
+ }
158
+ return res;
159
+ }
160
+ /** Re-acknowledge rows: record each target's current sha256. */
161
+ export function ackTargets(opts) {
162
+ const { cwd, targets, stalenessFile } = opts;
163
+ const map = existsSync(stalenessFile)
164
+ ? JSON.parse(readFileSync(stalenessFile, "utf8"))
165
+ : {};
166
+ let n = 0;
167
+ for (const t of targets) {
168
+ const p = join(cwd, t);
169
+ if (!existsSync(p) || !statSync(p).isFile())
170
+ continue;
171
+ map[t] = sha256(readFileSync(p));
172
+ n++;
173
+ }
174
+ writeFileSync(stalenessFile, `${JSON.stringify(map, null, 2)}\n`, "utf8");
175
+ return n;
176
+ }
package/dist/dox.d.ts CHANGED
@@ -51,18 +51,40 @@ export declare function areaFiles(cwd: string): Map<string, string[]>;
51
51
  /** Plan (and optionally write) a DOX tree. Idempotent: never clobbers existing
52
52
  * AGENTS.md; only adds missing files + missing path rows. */
53
53
  export declare function doxInit(opts: DoxInitOptions): DoxInitPlan;
54
+ /**
55
+ * Pull repo-path REFERENCES out of a row's purpose cell.
56
+ *
57
+ * The lint hashes the file behind each row but never validates paths written
58
+ * inside the prose, so a directory move silently rots cross-references (this is
59
+ * how a routing rule kept pointing at two deleted dirs). The hard part is not
60
+ * finding candidates — it is rejecting the ~99% that are not repo paths at all:
61
+ * URL routes, MIME types, npm specifiers, `~`/absolute paths, model ids, code
62
+ * fragments like `get/list/remove`, and descriptions of OTHER projects' layouts.
63
+ *
64
+ * Discriminators, in order of how much noise each removes:
65
+ * 1. first segment must be a real top-level entry of THIS repo — kills
66
+ * `lib/validations.ts` (consumer-project prose) and `provider/model`
67
+ * 2. must carry a source-file extension or be a glob — kills bare route paths
68
+ * 3. structural rejects: leading `~` or `/`, `@` scopes, and any char that
69
+ * cannot appear in a path we would write (`:?="'()[]{}<>` , whitespace…)
70
+ */
71
+ export declare function extractRefPaths(cell: string, topLevel: Set<string>): string[];
54
72
  export interface DoxIssue {
55
- kind: "stale" | "orphan" | "missing" | "missing-companion" | "broken-pointer" | "over-threshold";
73
+ kind: "stale" | "orphan" | "missing" | "missing-companion" | "broken-pointer" | "broken-ref" | "over-threshold";
56
74
  agentsFile: string;
57
75
  path?: string;
58
76
  detail: string;
59
- arm?: "bytes" | "rows";
77
+ arm?: "bytes" | "rows" | "source";
60
78
  }
61
79
  export interface DoxLintOptions {
62
80
  json?: boolean;
63
81
  fix?: boolean;
64
82
  cwd: string;
65
83
  stalenessFile?: string;
84
+ /** Opt-in: report undocumented SOURCE files as `missing` (design D9). OFF by
85
+ * default so an existing tree can adopt the arm incrementally instead of
86
+ * red-walling CI with a large one-time finding count. */
87
+ sourceFileRows?: boolean;
66
88
  }
67
89
  export interface DoxLintResult {
68
90
  issues: DoxIssue[];