@blackbelt-technology/pi-dashboard-kb 0.5.4 → 0.6.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/dist/indexer.js CHANGED
@@ -1,11 +1,18 @@
1
1
  // Indexer: walk a filesystem source, layered mtime→sha256 change detection,
2
2
  // structural chunking, Tier-1 graph extraction, transactional upsert (design §5).
3
3
  import { createHash } from "node:crypto";
4
- import { readFileSync, readdirSync, statSync } from "node:fs";
4
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
5
5
  import { join, relative } from "node:path";
6
6
  import { chunkMarkdown } from "./chunker.js";
7
7
  const sha = (s) => createHash("sha256").update(s).digest("hex");
8
8
  const DEFAULT_EXCLUDE = /(^|\/)(node_modules|\.git|dist|build|\.next|coverage|\.kb)(\/|$)/;
9
+ /** Files processed between event-loop yields + batch commits. A long synchronous
10
+ * walk would otherwise pin the single Node thread for its whole duration, so a
11
+ * concurrent `/stats` reader could never observe `indexing:true` (no spinner)
12
+ * and would see no live progress. Committing per batch also releases the WAL
13
+ * write lock so the reader is served. See change: fix-kb-index-feedback. */
14
+ const YIELD_EVERY = 100;
15
+ const yieldToEventLoop = () => new Promise((r) => setImmediate(r));
9
16
  /** Minimal glob → RegExp (supports **, *, ?). Good enough for include/exclude. */
10
17
  function globToRe(g) {
11
18
  const body = g
@@ -36,13 +43,23 @@ function walk(dir, base, out = []) {
36
43
  }
37
44
  function docTypeOf(rel, includeSourceMarkdown) {
38
45
  const base = rel.split("/").pop() ?? "";
39
- if (base === "AGENTS.md" || base === "CLAUDE.md")
46
+ // `<File>.AGENTS.md` = per-file index sidecar (large-row promotion). Classified
47
+ // `agents` so it is searchable, but its name != "AGENTS.md" so pi's native
48
+ // up-walk never auto-injects it (pull-only via kb search).
49
+ if (base === "AGENTS.md" || base === "CLAUDE.md" || base.endsWith(".AGENTS.md"))
40
50
  return "agents";
41
51
  if (includeSourceMarkdown && /(^|\/)(src|lib|app|packages)\//.test(rel))
42
52
  return "source-md";
43
53
  return "doc";
44
54
  }
45
- export function indexSource(store, src, opts = {}) {
55
+ export async function indexSource(store, src, opts = {}) {
56
+ // A configured source whose dir is absent degrades to skip-with-warning rather
57
+ // than throwing ENOENT mid-walk. A partial source set still indexes what exists.
58
+ // See change: harden-kb-index-failure-atomicity.
59
+ if (!existsSync(src.dir)) {
60
+ console.warn(`kb index: source directory does not exist, skipping: ${src.dir}`);
61
+ return { scanned: 0, changed: 0, deleted: 0, chunks: 0, missing: true };
62
+ }
46
63
  const extRe = opts.extensions?.length ? new RegExp("(" + opts.extensions.map((e) => e.replace(/\./g, "\\.")).join("|") + ")$", "i") : /\.(md|mdx|markdown)$/i;
47
64
  const inc = opts.include?.map(globToRe);
48
65
  const exc = opts.exclude?.map(globToRe);
@@ -61,9 +78,22 @@ export function indexSource(store, src, opts = {}) {
61
78
  });
62
79
  const stats = { scanned: files.length, changed: 0, deleted: 0, chunks: 0 };
63
80
  const live = new Set();
81
+ // Batched transaction: commit + yield every YIELD_EVERY files so the walk does
82
+ // not block the event loop and a concurrent `/stats` read sees live progress.
83
+ // NOTE: this trades whole-walk atomicity for responsiveness — a mid-walk throw
84
+ // leaves earlier batches committed; a reindex is idempotent so a re-run
85
+ // completes it. See change: fix-kb-index-feedback.
86
+ let sinceYield = 0;
64
87
  store.begin();
65
88
  try {
66
89
  for (const abs of files) {
90
+ if (sinceYield >= YIELD_EVERY) {
91
+ store.commit();
92
+ await yieldToEventLoop();
93
+ store.begin();
94
+ sinceYield = 0;
95
+ }
96
+ sinceYield++;
67
97
  const rel = relative(src.dir, abs);
68
98
  live.add(rel);
69
99
  const st = statSync(abs);
@@ -0,0 +1,39 @@
1
+ export interface IndexRow {
2
+ purpose: string;
3
+ seeChange: string[];
4
+ }
5
+ /** Parse a single file-index split's markdown into path → {purpose, seeChange}. */
6
+ export declare function parseFileIndex(text: string): Map<string, IndexRow>;
7
+ /** Merge many split files (already read to text) into one index. */
8
+ export declare function mergeIndex(texts: string[]): Map<string, IndexRow>;
9
+ export type FileStatus = "hit" | "miss";
10
+ export interface FileEntry {
11
+ rel: string;
12
+ base: string;
13
+ status: FileStatus;
14
+ purpose?: string;
15
+ }
16
+ export interface DirPlan {
17
+ dir: string;
18
+ tier: 0 | 1;
19
+ files: FileEntry[];
20
+ }
21
+ /** Join enumerated source groups against the parsed index; classify tier. */
22
+ export declare function planDirs(groups: Map<string, string[]>, index: Map<string, IndexRow>): DirPlan[];
23
+ /** Deterministic Tier-0 rows: verbatim index purposes, path-alphabetical. */
24
+ export declare function tier0Rows(plan: DirPlan): string[];
25
+ /** Render a directory AGENTS.md body from its rows. */
26
+ export declare function renderAgentsMd(dir: string, rows: string[]): string;
27
+ export interface AuthoredRow {
28
+ base: string;
29
+ purpose: string;
30
+ }
31
+ export interface ValidationResult {
32
+ ok: boolean;
33
+ errors: string[];
34
+ }
35
+ /** Structural gate (design §4c): exactly one non-empty row per input file;
36
+ * hit purposes byte-identical to the index. Semantic review is separate. */
37
+ export declare function validateAuthored(plan: DirPlan, authored: AuthoredRow[]): ValidationResult;
38
+ /** Build final rows for a plan given authored purposes (used after validation). */
39
+ export declare function finalRows(plan: DirPlan, authored: AuthoredRow[]): string[];
@@ -0,0 +1,92 @@
1
+ // One-time migration core: re-home docs/file-index-<area>.md purposes into a
2
+ // per-directory AGENTS.md tree, and mark files with no covering row as `miss`
3
+ // (authored from source by @fast subagents). PURE + testable; the actual
4
+ // subagent fan-out is driven by the orchestrating agent, which calls these
5
+ // helpers for parse / plan / tier-0 rows / validation / render.
6
+ import { basename } from "node:path";
7
+ const ROW_RE = /^\|\s*`([^`]+)`\s*\|\s*(.*?)\s*\|\s*$/;
8
+ const SEE_CHANGE_RE = /See change:\s*([A-Za-z0-9_-]+)/g;
9
+ /** Parse a single file-index split's markdown into path → {purpose, seeChange}. */
10
+ export function parseFileIndex(text) {
11
+ const out = new Map();
12
+ for (const line of text.split("\n")) {
13
+ const m = line.match(ROW_RE);
14
+ if (!m)
15
+ continue;
16
+ const path = m[1].trim();
17
+ const purpose = m[2].trim();
18
+ // skip the header separator / pointer rows that aren't source paths
19
+ if (!purpose || path === "File")
20
+ continue;
21
+ const seeChange = [...purpose.matchAll(SEE_CHANGE_RE)].map((mm) => mm[1]);
22
+ out.set(path, { purpose, seeChange });
23
+ }
24
+ return out;
25
+ }
26
+ /** Merge many split files (already read to text) into one index. */
27
+ export function mergeIndex(texts) {
28
+ const merged = new Map();
29
+ for (const t of texts)
30
+ for (const [k, v] of parseFileIndex(t))
31
+ merged.set(k, v);
32
+ return merged;
33
+ }
34
+ /** Join enumerated source groups against the parsed index; classify tier. */
35
+ export function planDirs(groups, index) {
36
+ const plans = [];
37
+ for (const [dir, rels] of groups) {
38
+ const files = rels.map((rel) => {
39
+ const row = index.get(rel);
40
+ return row
41
+ ? { rel, base: basename(rel), status: "hit", purpose: row.purpose }
42
+ : { rel, base: basename(rel), status: "miss" };
43
+ });
44
+ files.sort((a, b) => a.base.localeCompare(b.base));
45
+ const tier = files.every((f) => f.status === "hit") ? 0 : 1;
46
+ plans.push({ dir, tier, files });
47
+ }
48
+ plans.sort((a, b) => a.dir.localeCompare(b.dir));
49
+ return plans;
50
+ }
51
+ const rowFor = (base, purpose) => `| \`${base}\` | ${purpose} |`;
52
+ const byBaseAlpha = (files) => [...files].sort((a, b) => a.base.localeCompare(b.base));
53
+ /** Deterministic Tier-0 rows: verbatim index purposes, path-alphabetical. */
54
+ export function tier0Rows(plan) {
55
+ return byBaseAlpha(plan.files).map((f) => rowFor(f.base, f.purpose ?? ""));
56
+ }
57
+ /** Render a directory AGENTS.md body from its rows. */
58
+ export function renderAgentsMd(dir, rows) {
59
+ return `# DOX — ${dir}\n\nFiles in this directory. One row per source file.\n\n| File | Purpose |\n|------|---------|\n${rows.join("\n")}\n`;
60
+ }
61
+ /** Structural gate (design §4c): exactly one non-empty row per input file;
62
+ * hit purposes byte-identical to the index. Semantic review is separate. */
63
+ export function validateAuthored(plan, authored) {
64
+ const errors = [];
65
+ const byBase = new Map();
66
+ for (const a of authored) {
67
+ if (byBase.has(a.base))
68
+ errors.push(`duplicate row for ${a.base}`);
69
+ byBase.set(a.base, a.purpose);
70
+ }
71
+ for (const f of plan.files) {
72
+ const p = byBase.get(f.base);
73
+ if (p === undefined) {
74
+ errors.push(`missing row for ${f.base}`);
75
+ continue;
76
+ }
77
+ if (!p.trim())
78
+ errors.push(`empty purpose for ${f.base}`);
79
+ if (f.status === "hit" && p !== f.purpose)
80
+ errors.push(`hit purpose drifted for ${f.base}`);
81
+ }
82
+ for (const base of byBase.keys()) {
83
+ if (!plan.files.some((f) => f.base === base))
84
+ errors.push(`unexpected row for ${base}`);
85
+ }
86
+ return { ok: errors.length === 0, errors };
87
+ }
88
+ /** Build final rows for a plan given authored purposes (used after validation). */
89
+ export function finalRows(plan, authored) {
90
+ const byBase = new Map(authored.map((a) => [a.base, a.purpose]));
91
+ return byBaseAlpha(plan.files).map((f) => rowFor(f.base, byBase.get(f.base) ?? f.purpose ?? ""));
92
+ }
@@ -0,0 +1,57 @@
1
+ import { type DirPlan } from "./migrate-file-index.js";
2
+ export declare const PACKAGES_ROOT_RE: RegExp;
3
+ /** Read every docs/file-index-*.md split as raw text. */
4
+ export declare function loadSplitTexts(cwd: string): string[];
5
+ /** Build all dir plans for the migration scope (packages/ source tree). */
6
+ export declare function buildDirPlans(cwd: string): DirPlan[];
7
+ export declare function groundingCheck(purpose: string, sourceText: string, known?: Set<string>): {
8
+ ok: boolean;
9
+ ungrounded: string[];
10
+ };
11
+ /** All source-file stems (basename without extension) across the plans — the
12
+ * cross-reference allowlist for grounding. */
13
+ export declare function knownStems(plans: DirPlan[]): Set<string>;
14
+ export interface MissRef {
15
+ dir: string;
16
+ base: string;
17
+ rel: string;
18
+ }
19
+ export interface Batch {
20
+ dirs: string[];
21
+ miss: MissRef[];
22
+ }
23
+ /** Group tier-1 miss files into batches: ≤maxMiss files and ≤maxDirs dirs per
24
+ * batch; a dir with >maxMiss misses splits into sequential same-dir batches. */
25
+ export declare function makeBatches(plans: DirPlan[], opts?: {
26
+ maxMiss?: number;
27
+ maxDirs?: number;
28
+ }): Batch[];
29
+ /** The exact @fast subagent prompt for one batch (read-only authoring). */
30
+ export declare function subagentPrompt(cwd: string, batch: Batch): string;
31
+ /** Parse a subagent batch reply into rel-path → purpose. */
32
+ export declare function parseAuthoredBatch(text: string): Map<string, string>;
33
+ /** Fold a parsed batch reply into migration state (state.authored[dir][base]). */
34
+ export declare function recordAuthored(state: MigrationState, batch: Batch, byRel: Map<string, string>): {
35
+ recorded: number;
36
+ missing: string[];
37
+ };
38
+ /** Assemble one dir's AGENTS.md from its plan + authored miss rows, validate,
39
+ * ground-check, and write. Returns {ok, errors, ungrounded}. Idempotent. */
40
+ export declare function writeDir(cwd: string, plan: DirPlan, authoredMiss: Map<string, string>, opts?: {
41
+ dryRun?: boolean;
42
+ known?: Set<string>;
43
+ }): {
44
+ ok: boolean;
45
+ errors: string[];
46
+ ungrounded: {
47
+ base: string;
48
+ ids: string[];
49
+ }[];
50
+ };
51
+ export interface MigrationState {
52
+ authored: Record<string, Record<string, string>>;
53
+ doneDirs: string[];
54
+ gaps: Record<string, string[]>;
55
+ }
56
+ export declare function loadState(cwd: string): MigrationState;
57
+ export declare function saveState(cwd: string, s: MigrationState): void;
@@ -0,0 +1,172 @@
1
+ // One-off big-bang runner for the file-index → AGENTS.md tree migration.
2
+ // Deterministic + resumable. The orchestrating agent drives Tier-1 authoring by
3
+ // spawning @fast subagents; this module owns everything else: plan, batch,
4
+ // grounding gate, idempotent per-dir write, checkpoint/gaps persistence.
5
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { dirname, join } from "node:path";
7
+ import { areaFiles } from "./dox.js";
8
+ import { finalRows, mergeIndex, planDirs, renderAgentsMd, validateAuthored } from "./migrate-file-index.js";
9
+ export const PACKAGES_ROOT_RE = /^packages\//;
10
+ /** Read every docs/file-index-*.md split as raw text. */
11
+ export function loadSplitTexts(cwd) {
12
+ const docs = join(cwd, "docs");
13
+ return readdirSync(docs)
14
+ .filter((f) => /^file-index-.*\.md$/.test(f))
15
+ .map((f) => readFileSync(join(docs, f), "utf8"));
16
+ }
17
+ /** Build all dir plans for the migration scope (packages/ source tree). */
18
+ export function buildDirPlans(cwd) {
19
+ const index = mergeIndex(loadSplitTexts(cwd));
20
+ const groups = new Map([...areaFiles(cwd)].filter(([dir]) => PACKAGES_ROOT_RE.test(dir)));
21
+ return planDirs(groups, index);
22
+ }
23
+ // --- grounding gate (deterministic semantic check) ---
24
+ // Every backticked identifier in an authored purpose must appear in the source
25
+ // file. Catches hallucinated exports/symbols — the dominant Tier-1 failure mode.
26
+ const STOP = new Set(["React", "DOM", "JSON", "HTML", "URL", "API", "HTTP", "CSS", "UI", "TODO"]);
27
+ function significantIds(span) {
28
+ const ids = span.match(/[A-Za-z_$][A-Za-z0-9_$]*/g) ?? [];
29
+ // only mixed-case (camel/Pascal) or underscore identifiers — the export-name shapes
30
+ return ids.filter((id) => id.length >= 3 && !STOP.has(id) && (/[a-z]/.test(id) && /[A-Z]/.test(id) || id.includes("_")));
31
+ }
32
+ export function groundingCheck(purpose, sourceText, known) {
33
+ const spans = [...purpose.matchAll(/`([^`]+)`/g)].map((m) => m[1]);
34
+ const ungrounded = [];
35
+ for (const span of spans) {
36
+ for (const id of significantIds(span)) {
37
+ // grounded if the identifier appears in this file OR is another source
38
+ // file's stem (a legitimate cross-reference to a consumer/related module).
39
+ if (known?.has(id))
40
+ continue;
41
+ if (!new RegExp(`\\b${id.replace(/\$/g, "\\$")}\\b`).test(sourceText))
42
+ ungrounded.push(id);
43
+ }
44
+ }
45
+ return { ok: ungrounded.length === 0, ungrounded: [...new Set(ungrounded)] };
46
+ }
47
+ /** All source-file stems (basename without extension) across the plans — the
48
+ * cross-reference allowlist for grounding. */
49
+ export function knownStems(plans) {
50
+ const s = new Set();
51
+ for (const p of plans)
52
+ for (const f of p.files)
53
+ s.add(f.base.replace(/\.[^.]+$/, ""));
54
+ return s;
55
+ }
56
+ /** Group tier-1 miss files into batches: ≤maxMiss files and ≤maxDirs dirs per
57
+ * batch; a dir with >maxMiss misses splits into sequential same-dir batches. */
58
+ export function makeBatches(plans, opts = {}) {
59
+ const maxMiss = opts.maxMiss ?? 20;
60
+ const maxDirs = opts.maxDirs ?? 8;
61
+ const batches = [];
62
+ let cur = { dirs: [], miss: [] };
63
+ const flush = () => {
64
+ if (cur.miss.length)
65
+ batches.push(cur);
66
+ cur = { dirs: [], miss: [] };
67
+ };
68
+ for (const plan of plans.filter((p) => p.tier === 1)) {
69
+ const misses = plan.files.filter((f) => f.status === "miss").map((f) => ({ dir: plan.dir, base: f.base, rel: f.rel }));
70
+ if (misses.length > maxMiss) {
71
+ flush();
72
+ for (let i = 0; i < misses.length; i += maxMiss)
73
+ batches.push({ dirs: [plan.dir], miss: misses.slice(i, i + maxMiss) });
74
+ continue;
75
+ }
76
+ if (cur.miss.length + misses.length > maxMiss || cur.dirs.length + 1 > maxDirs)
77
+ flush();
78
+ cur.dirs.push(plan.dir);
79
+ cur.miss.push(...misses);
80
+ }
81
+ flush();
82
+ return batches;
83
+ }
84
+ /** The exact @fast subagent prompt for one batch (read-only authoring). */
85
+ export function subagentPrompt(cwd, batch) {
86
+ const lines = batch.miss.map((m) => `- ${m.rel}`).join("\n");
87
+ return `You author one-line "purpose" table rows for a per-directory AGENTS.md file index. READ-ONLY: you may Read source files; you MUST NOT write or edit anything. Output ONLY the table rows, one per file, nothing else.
88
+
89
+ Repo root: ${cwd}
90
+ Author a row for EACH of these ${batch.miss.length} files (Read each fully first):
91
+ ${lines}
92
+
93
+ Row schema (path column = the EXACT repo-relative path from the list above, one line per file):
94
+ | \`<repo-relative-path>\` | <purpose> |
95
+
96
+ CAVEMAN STYLE for the purpose column (mandatory):
97
+ - Short declarative fragments. Drop articles (a/an/the) and copulas when meaning survives.
98
+ - Subject → verb → object, present tense. No hedging, no "we"/"you", no marketing.
99
+ - One fact per clause. Prefer concrete tokens (exported symbols, types, function names, paths) over prose.
100
+ - Keep identifiers verbatim inside backticks. Name the key exports + the file's role.
101
+ - Do NOT invent a "See change:" annotation. Only real source facts.
102
+
103
+ Output exactly ${batch.miss.length} lines (the rows), each starting with the file's repo-relative path in backticks, nothing before or after.`;
104
+ }
105
+ /** Parse a subagent batch reply into rel-path → purpose. */
106
+ export function parseAuthoredBatch(text) {
107
+ const out = new Map();
108
+ for (const line of text.split("\n")) {
109
+ // tolerate LLM output that drops the trailing pipe: `| path | purpose` or `| path | purpose |`
110
+ const m = line.match(/^\|\s*`([^`]+)`\s*\|\s*(.*?)\s*$/);
111
+ if (!m)
112
+ continue;
113
+ const purpose = m[2].replace(/\s*\|\s*$/, "").trim();
114
+ if (purpose)
115
+ out.set(m[1].trim(), purpose);
116
+ }
117
+ return out;
118
+ }
119
+ /** Fold a parsed batch reply into migration state (state.authored[dir][base]). */
120
+ export function recordAuthored(state, batch, byRel) {
121
+ let recorded = 0;
122
+ const missing = [];
123
+ for (const m of batch.miss) {
124
+ const purpose = byRel.get(m.rel);
125
+ if (!purpose) {
126
+ missing.push(m.rel);
127
+ continue;
128
+ }
129
+ (state.authored[m.dir] ??= {})[m.base] = purpose;
130
+ recorded++;
131
+ }
132
+ return { recorded, missing };
133
+ }
134
+ // --- per-dir assembly + idempotent write ---
135
+ /** Assemble one dir's AGENTS.md from its plan + authored miss rows, validate,
136
+ * ground-check, and write. Returns {ok, errors, ungrounded}. Idempotent. */
137
+ export function writeDir(cwd, plan, authoredMiss, opts = {}) {
138
+ const authored = plan.files.map((f) => f.status === "hit" ? { base: f.base, purpose: f.purpose } : { base: f.base, purpose: authoredMiss.get(f.base) ?? "" });
139
+ const v = validateAuthored(plan, authored);
140
+ const ungrounded = [];
141
+ for (const f of plan.files) {
142
+ if (f.status !== "miss")
143
+ continue;
144
+ const purpose = authoredMiss.get(f.base) ?? "";
145
+ const src = readFileSync(join(cwd, f.rel), "utf8");
146
+ const g = groundingCheck(purpose, src, opts.known);
147
+ if (!g.ok)
148
+ ungrounded.push({ base: f.base, ids: g.ungrounded });
149
+ }
150
+ if (!v.ok)
151
+ return { ok: false, errors: v.errors, ungrounded };
152
+ if (!opts.dryRun) {
153
+ const md = renderAgentsMd(plan.dir, finalRows(plan, authored));
154
+ const file = join(cwd, plan.dir, "AGENTS.md");
155
+ mkdirSync(dirname(file), { recursive: true });
156
+ writeFileSync(file, md, "utf8");
157
+ }
158
+ return { ok: v.ok, errors: v.errors, ungrounded };
159
+ }
160
+ // --- checkpoint / gaps persistence (resumability) ---
161
+ const stateDir = (cwd) => join(cwd, ".pi", "dashboard", "kb");
162
+ export function loadState(cwd) {
163
+ const f = join(stateDir(cwd), "migration-state.json");
164
+ if (existsSync(f))
165
+ return JSON.parse(readFileSync(f, "utf8"));
166
+ return { authored: {}, doneDirs: [], gaps: {} };
167
+ }
168
+ export function saveState(cwd, s) {
169
+ const dir = stateDir(cwd);
170
+ mkdirSync(dir, { recursive: true });
171
+ writeFileSync(join(dir, "migration-state.json"), JSON.stringify(s, null, 2), "utf8");
172
+ }
@@ -0,0 +1,11 @@
1
+ import type { KbHit } from "./types.js";
2
+ export interface RenderOpts {
3
+ /** Leading token per hit: raw BM25 `score` (CLI) or 1-based `rank` (tool). */
4
+ leading: "score" | "rank";
5
+ /** Prefix for the parent-heading continuation (CLI "[parent: ", tool "⤷ "). */
6
+ parentGlyph: string;
7
+ /** Multi-line block per hit (tool) vs single header line + indented snippet (CLI). */
8
+ multiline: boolean;
9
+ }
10
+ /** Render hits to text. `rank` is a 1-based ordinal over the given (post-limit) list. */
11
+ export declare function renderHits(hits: KbHit[], opts: RenderOpts): string;
package/dist/render.js ADDED
@@ -0,0 +1,27 @@
1
+ const SNIPPET_MAX = 160;
2
+ /** Render hits to text. `rank` is a 1-based ordinal over the given (post-limit) list. */
3
+ export function renderHits(hits, opts) {
4
+ const { leading, parentGlyph, multiline } = opts;
5
+ return hits
6
+ .map((h, i) => {
7
+ const lead = leading === "rank" ? String(i + 1) : h.score.toFixed(2);
8
+ const head = `${lead} ${h.path} :: ${h.headingPath}`;
9
+ const dup = h.akaPaths && h.akaPaths.length ? `(+${h.akaPaths.length} dup)` : "";
10
+ const snippet = h.snippet.replace(/\s+/g, " ").slice(0, SNIPPET_MAX);
11
+ if (multiline) {
12
+ const lines = [head];
13
+ if (dup)
14
+ lines.push(` ${dup}`);
15
+ if (h.parent)
16
+ lines.push(` ${parentGlyph}${h.parent.headingPath}`);
17
+ lines.push(` ${snippet}`);
18
+ return lines.join("\n");
19
+ }
20
+ // Single-line CLI form — byte-identical to the legacy inline render. The
21
+ // bracketed parent glyph carries its own closing "]".
22
+ const dupInline = dup ? ` ${dup}` : "";
23
+ const parentInline = h.parent ? ` ${parentGlyph}${h.parent.headingPath}]` : "";
24
+ return `${head}${dupInline}${parentInline}\n ${snippet}`;
25
+ })
26
+ .join("\n");
27
+ }
@@ -1,12 +1,21 @@
1
1
  import type { Chunk, FileState, GraphEdge, GraphNode, KbHit, KbStore, SearchOpts } from "./types.js";
2
2
  export declare class SqliteFtsStore implements KbStore {
3
3
  private db;
4
+ readonly dbPath: string;
4
5
  constructor(dbPath: string);
5
6
  init(): void;
6
7
  begin(): void;
7
8
  commit(): void;
8
9
  rollback(): void;
9
10
  close(): void;
11
+ /** Finalize a temp-path build onto `dest`. WAL ordering is load-bearing:
12
+ * TRUNCATE-checkpoint + close BEFORE the rename so the single main file holds
13
+ * every committed page; then rename atomically and drop stale sidecars.
14
+ * See change: harden-kb-index-failure-atomicity. */
15
+ finalizeRename(dest: string): void;
16
+ /** Close and remove this DB file + WAL sidecars — cleanup for a failed run
17
+ * that itself created the file (never touches a pre-existing valid DB). */
18
+ closeAndUnlink(): void;
10
19
  getFileState(root: string, path: string): FileState | null;
11
20
  setFileState(root: string, path: string, s: FileState): void;
12
21
  listPaths(root: string): string[];
@@ -1,9 +1,9 @@
1
1
  // Default KbStore backend over node:sqlite (Node built-in; FTS5 verified).
2
2
  // Zero runtime deps. Requires --experimental-sqlite on current Node.
3
3
  // better-sqlite3 is a drop-in fallback behind the same KbStore interface.
4
- import { DatabaseSync } from "node:sqlite";
5
- import { mkdirSync } from "node:fs";
4
+ import { mkdirSync, renameSync, unlinkSync } from "node:fs";
6
5
  import { dirname } from "node:path";
6
+ import { DatabaseSync } from "node:sqlite";
7
7
  const DDL = `
8
8
  CREATE VIRTUAL TABLE IF NOT EXISTS chunks USING fts5(
9
9
  root UNINDEXED, path UNINDEXED, chunk_id UNINDEXED, doc_type UNINDEXED,
@@ -34,11 +34,17 @@ function toMatch(q) {
34
34
  }
35
35
  export class SqliteFtsStore {
36
36
  db;
37
+ dbPath;
37
38
  constructor(dbPath) {
39
+ this.dbPath = dbPath;
38
40
  if (dbPath !== ":memory:")
39
41
  mkdirSync(dirname(dbPath), { recursive: true });
40
42
  this.db = new DatabaseSync(dbPath);
41
43
  this.db.exec("PRAGMA journal_mode=WAL");
44
+ // Let a concurrent reader (e.g. `/stats` during a reindex) wait briefly for a
45
+ // batch's write lock instead of failing with SQLITE_BUSY. See change:
46
+ // fix-kb-index-feedback.
47
+ this.db.exec("PRAGMA busy_timeout=5000");
42
48
  }
43
49
  init() {
44
50
  this.db.exec(DDL);
@@ -58,6 +64,38 @@ export class SqliteFtsStore {
58
64
  close() {
59
65
  this.db.close();
60
66
  }
67
+ /** Finalize a temp-path build onto `dest`. WAL ordering is load-bearing:
68
+ * TRUNCATE-checkpoint + close BEFORE the rename so the single main file holds
69
+ * every committed page; then rename atomically and drop stale sidecars.
70
+ * See change: harden-kb-index-failure-atomicity. */
71
+ finalizeRename(dest) {
72
+ try {
73
+ this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
74
+ }
75
+ catch { }
76
+ this.db.close();
77
+ renameSync(this.dbPath, dest);
78
+ for (const ext of ["-wal", "-shm"]) {
79
+ try {
80
+ unlinkSync(this.dbPath + ext);
81
+ }
82
+ catch { }
83
+ }
84
+ }
85
+ /** Close and remove this DB file + WAL sidecars — cleanup for a failed run
86
+ * that itself created the file (never touches a pre-existing valid DB). */
87
+ closeAndUnlink() {
88
+ try {
89
+ this.db.close();
90
+ }
91
+ catch { }
92
+ for (const ext of ["", "-wal", "-shm"]) {
93
+ try {
94
+ unlinkSync(this.dbPath + ext);
95
+ }
96
+ catch { }
97
+ }
98
+ }
61
99
  getFileState(root, path) {
62
100
  const r = this.db.prepare("SELECT mtime_ms, sha256 FROM files WHERE root=? AND path=?").get(root, path);
63
101
  return r ? { mtimeMs: r.mtime_ms, sha256: r.sha256 } : null;
@@ -181,7 +219,10 @@ export class SqliteFtsStore {
181
219
  continue;
182
220
  const parent = this.getChunkById(h.root, pc);
183
221
  if (parent && parent.chunkId !== h.chunkId) {
184
- h.parent = { root: parent.root, path: parent.path, headingPath: parent.headingPath, chunkId: parent.chunkId, docType: parent.docType, score: 0, snippet: parent.headingPath };
222
+ // Collapse to headingPath only: root/path/docType dup the child (same
223
+ // file by construction), score is a constant 0, snippet repeats
224
+ // headingPath, chunkId is not a tool refetch key. See change: slim-kb-search-output.
225
+ h.parent = { headingPath: parent.headingPath };
185
226
  }
186
227
  }
187
228
  }
package/dist/types.d.ts CHANGED
@@ -32,7 +32,9 @@ export interface KbHit {
32
32
  score: number;
33
33
  snippet: string;
34
34
  akaPaths?: string[];
35
- parent?: KbHit | null;
35
+ parent?: {
36
+ headingPath: string;
37
+ } | null;
36
38
  }
37
39
  /** A pluggable reranker: rescoring BM25 top-k. Default = none (no-op). */
38
40
  export type Reranker = (query: string, candidates: KbHit[]) => Promise<KbHit[]> | KbHit[];
package/package.json CHANGED
@@ -1,7 +1,14 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-dashboard-kb",
3
- "version": "0.5.4",
4
- "publishConfig": { "access": "public" },
3
+ "version": "0.6.0",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "https://github.com/BlackBeltTechnology/pi-agent-dashboard",
7
+ "directory": "packages/kb"
8
+ },
9
+ "publishConfig": {
10
+ "access": "public"
11
+ },
5
12
  "description": "Directory-based SQLite/FTS5 knowledge base over markdown, queryable by LLM agents. Structural heading chunking, Tier-1 graph, content-hash incremental indexing, near-duplicate dedup, BM25F ranking. Zero runtime deps (node:sqlite).",
6
13
  "type": "module",
7
14
  "license": "MIT",
@@ -20,6 +27,18 @@
20
27
  "verify": "NODE_OPTIONS=--experimental-sqlite tsx verify.ts",
21
28
  "test": "NODE_OPTIONS=--experimental-sqlite vitest run"
22
29
  },
23
- "files": ["dist", "src", "!src/__tests__"],
24
- "keywords": ["knowledge-base", "fts5", "sqlite", "markdown", "bm25", "rag", "pi"]
30
+ "files": [
31
+ "dist",
32
+ "src",
33
+ "!src/__tests__"
34
+ ],
35
+ "keywords": [
36
+ "knowledge-base",
37
+ "fts5",
38
+ "sqlite",
39
+ "markdown",
40
+ "bm25",
41
+ "rag",
42
+ "pi"
43
+ ]
25
44
  }
package/src/AGENTS.md ADDED
@@ -0,0 +1,23 @@
1
+ # DOX — packages/kb/src
2
+
3
+ Files in this directory. One row per source file.
4
+
5
+ | File | Purpose |
6
+ |------|---------|
7
+ | `chunker.ts` | Structural heading chunker. Fence-safe, breadcrumb-aware. Line-based fenced-code state machine. |
8
+ | `cli.ts` | kb CLI. Commands init\|index\|search\|neighbors\|backlinks\|get\|agents\|dox\|eval\|config. Dev run NODE_OPTIONS=--experimental-sqlite tsx src/cli.ts. `index` routes through `runIndexAtomic` (index-run.ts) and does NOT `openStore` — opening pre-creates the DB husk. `search`/`eval` still `openStore` + auto-reindex. `search` non-json branch calls shared `renderHits(leading:"score")`. See change: harden-kb-index-failure-atomicity; slim-kb-search-output. |
9
+ | `config.ts` | Config layering. project .pi/dashboard/knowledge_base.json → global ~/.pi/dashboard/knowledge_base.json → defaults. No file-count cap default. |
10
+ | `dox.ts` | DOX tree. Directory-level AGENTS.md scaffold + audit. kb agents <path> nearest-applicable chain. Detect-don't-write: dox init/--fix fill PATH columns + prune orphans only. `over-threshold` lint splits two arms: `arm:"bytes"` (actionable — bytes > `AGENTS_BYTE_CAP` 30 KB, auto-injected per turn, remedy sidecar split) + `arm:"rows"` (informational — inline count > `ROW_CAP` 40, no per-turn cost, optional foldering). `countInlineRows(af)` counts INLINE rows only (excludes sidecar-pointer rows matching `/→ see \`<File>.AGENTS.md\`/`) — sibling to `parseRowPaths` (public export consumed by kb-extension; signature untouched, stays complete path list). Splitting a heavy row to its sidecar drops both byte + counted-row totals. `ROW_CAP`/`AGENTS_BYTE_CAP` numeric values unchanged. `isMdFile` excludes `*.AGENTS.md` sidecars + `*.agent.md` companions (both DOX index artifacts, not documentable source). `DEFAULT_EXCLUDE` skips build output (`out`) + electron bundled/vendored trees (`bundled-extensions`, `electron/resources/server`) — all gitignored, fs-walk-only, else bogus missing/companion rows; `server` scoped to `electron/resources/server` so real `server` source dirs stay indexed. `resolveRowPath(agentsDir,cwd,rp)` resolves rows relative to their OWN AGENTS.md dir, repo-root `cwd` fallback (nested AGENTS.md may document a file living at project root) before orphan. `parseRowPaths` + `doxLint` scan only rows under a `# DOX —` heading (prose tables like Subagent Routing ignored). `doxLint` `walkAgents` tests `DEFAULT_EXCLUDE` on the cwd-RELATIVE path (mirrors `walkFiles`) so running inside `.worktrees/` does not exclude the whole tree. `rowPaths`/staleness keyed cwd-relative. See change: split-components-agents-dedup-rollup. See change: fix-dox-lint-false-positives. See change: fold-oversized-agents-directories. |
11
+ | `eval.ts` | Retrieval-quality eval. Scores search against golden set. Gates ranking changes. |
12
+ | `index-run.ts` | Atomic `kb index` orchestration. `runIndexAtomic({dbPath,sources,indexOpts,explicit})` returns `IndexStats & {counts}` (counts read from the still-open store so `index` never re-`openStore`s). First index (no dbPath) builds into `<dbPath>.tmp-<pid>` + `rename()` on success (survives OOM/SIGKILL — real path only on success); incremental (dbPath exists) indexes in place (mid-run failure leaves prior DB valid & queryable). All-sources-missing + explicit-`--source`-missing throw BEFORE any store opens (no husk). `sweepOrphanTemps` unlinks stale `.tmp-*` but SKIPS a temp whose PID is a live process (concurrent peer's active build). See change: harden-kb-index-failure-atomicity. |
13
+ | `index.ts` | Public API barrel for @blackbelt-technology/pi-dashboard-kb. Exports `renderHits` + `RenderOpts`. |
14
+ | `indexer.ts` | Indexer. `indexSource` is ASYNC: walks source, mtime→sha256 change detection, structural chunking, Tier-1 graph extraction, BATCHED transactional upsert — commits + `await setImmediate` every `YIELD_EVERY`=100 files so the walk yields the event loop (a concurrent `/stats` reader observes `indexing`+live counts) and releases the WAL write lock; trades whole-walk atomicity for responsiveness (mid-walk throw leaves earlier batches committed; reindex idempotent). All callers must `await`. A source whose `dir` does not exist is skipped with `console.warn` (returns `missing:true`), not a thrown ENOENT — partial source set still indexes what exists. `docTypeOf` classifies `*.AGENTS.md` per-file index sidecars as `agents` doc_type (searchable; name != `AGENTS.md` so pi never auto-injects them). See change: split-components-agents-dedup-rollup; fix-kb-index-feedback; harden-kb-index-failure-atomicity. |
15
+ | `init.ts` | kb init. Scaffolds + validates knowledge_base.json. --global writes global file. --force, --dry-run flags. gitignores dbPath. |
16
+ | `migrate-file-index.ts` | One-time migration core. Re-homes `docs/file-index-<area>.md` purposes into per-dir `AGENTS.md` tree. Pure + testable. Exports `parseFileIndex`, `mergeIndex`, `planDirs`, `tier0Rows`, `renderAgentsMd`, `validateAuthored`, `finalRows`, types `IndexRow`, `FileEntry`, `DirPlan`, `AuthoredRow`. Classifies dirs tier 0 (all hits, deterministic) vs tier 1 (≥1 miss, needs subagent). |
17
+ | `migrate-runner.ts` | Big-bang resumable runner for file-index → AGENTS.md migration (one-time; source splits since deleted). Owns plan, batching, grounding gate, idempotent per-dir write, checkpoint persistence. Exports `loadSplitTexts`, `buildDirPlans`, `groundingCheck`, `knownStems`, `makeBatches`, `subagentPrompt`, `parseAuthoredBatch`, `recordAuthored`, `writeDir`, `loadState`, `saveState`, `PACKAGES_ROOT_RE`. Drives `@fast` subagent fan-out for Tier-1 authoring. Rollup export (`exportRollup`/`treeRows`/`SPLIT_AREAS`) REMOVED — `docs/file-index*.md` retired, per-directory `AGENTS.md` tree is sole per-file record. See change: split-components-agents-dedup-rollup. See change: migrate-file-index-to-agents-tree. |
18
+ | `node-sqlite.d.ts` | Ambient shim `declare module "node:sqlite"` (DatabaseSync + StatementSync surface used by `sqlite-store.ts`). Pins @types/node 20.x lacks `node:sqlite` typings (ship in >= 22.5) so root `tsc`/kb build fail TS2307; shim resolves without a dep bump. Delete when @types/node >= 22.5. See change: adopt-pi-074-080-features. |
19
+ | `render.ts` | Shared hit renderer for CLI + kb_search tool. `renderHits(hits, { leading:"score"\|"rank", parentGlyph, multiline })`. Same fields/order both callers; differ on leading token (BM25 score vs 1-based rank ordinal), parent glyph, line structure. CLI opts byte-identical to legacy inline render. See change: slim-kb-search-output. |
20
+ | `sources.ts` | Pluggable source resolvers. fs/npm/git/https → local dir. KB reads markdown only, never executes source. |
21
+ | `sqlite-store.ts` | Default KbStore backend over node:sqlite. FTS5. WAL + `PRAGMA busy_timeout=5000` (concurrent reader waits for a batch commit, not `SQLITE_BUSY`). Zero runtime deps. Requires --experimental-sqlite. better-sqlite3 drop-in fallback. `readonly dbPath`. `finalizeRename(dest)`: TRUNCATE-checkpoint + close BEFORE `rename` (WAL ordering load-bearing), then drop stale sidecars. `closeAndUnlink()`: close + unlink db + `-wal`/`-shm` (failed first-index cleanup). `expandParent` collapses `h.parent` to `{ headingPath }` (dropped root/path/docType/chunkId/score/snippet — same-file dups/constants). See change: fix-kb-index-feedback; harden-kb-index-failure-atomicity; slim-kb-search-output. |
22
+ | `trust.ts` | TOFU trust store for remote sources. fs sources skip trust. npm/git/https confirm on first fetch. Keyed by sha256(canonical(SourceSpec)). |
23
+ | `types.ts` | KbStore interface + chunk types. Storage accessed only through KbStore. `KbHit.parent` narrowed to `{ headingPath } \| null` — display-only, non-recursive, NOT a refetch key. BREAKING public-type change. See change: slim-kb-search-output. |