@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.
@@ -0,0 +1,121 @@
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, relative } from "node:path";
7
+
8
+ export interface IndexRow {
9
+ purpose: string; // verbatim purpose column (incl. inline "See change:")
10
+ seeChange: string[]; // extracted change ids
11
+ }
12
+
13
+ const ROW_RE = /^\|\s*`([^`]+)`\s*\|\s*(.*?)\s*\|\s*$/;
14
+ const SEE_CHANGE_RE = /See change:\s*([A-Za-z0-9_-]+)/g;
15
+
16
+ /** Parse a single file-index split's markdown into path → {purpose, seeChange}. */
17
+ export function parseFileIndex(text: string): Map<string, IndexRow> {
18
+ const out = new Map<string, IndexRow>();
19
+ for (const line of text.split("\n")) {
20
+ const m = line.match(ROW_RE);
21
+ if (!m) continue;
22
+ const path = m[1].trim();
23
+ const purpose = m[2].trim();
24
+ // skip the header separator / pointer rows that aren't source paths
25
+ if (!purpose || path === "File") continue;
26
+ const seeChange = [...purpose.matchAll(SEE_CHANGE_RE)].map((mm) => mm[1]);
27
+ out.set(path, { purpose, seeChange });
28
+ }
29
+ return out;
30
+ }
31
+
32
+ /** Merge many split files (already read to text) into one index. */
33
+ export function mergeIndex(texts: string[]): Map<string, IndexRow> {
34
+ const merged = new Map<string, IndexRow>();
35
+ for (const t of texts) for (const [k, v] of parseFileIndex(t)) merged.set(k, v);
36
+ return merged;
37
+ }
38
+
39
+ export type FileStatus = "hit" | "miss";
40
+ export interface FileEntry {
41
+ rel: string; // repo-relative source path
42
+ base: string; // basename (row key in its AGENTS.md)
43
+ status: FileStatus;
44
+ purpose?: string; // present for hits (verbatim from index)
45
+ }
46
+ export interface DirPlan {
47
+ dir: string; // repo-relative directory
48
+ tier: 0 | 1; // 0 = all hits (deterministic), 1 = ≥1 miss (needs subagent)
49
+ files: FileEntry[];
50
+ }
51
+
52
+ /** Join enumerated source groups against the parsed index; classify tier. */
53
+ export function planDirs(groups: Map<string, string[]>, index: Map<string, IndexRow>): DirPlan[] {
54
+ const plans: DirPlan[] = [];
55
+ for (const [dir, rels] of groups) {
56
+ const files: FileEntry[] = rels.map((rel) => {
57
+ const row = index.get(rel);
58
+ return row
59
+ ? { rel, base: basename(rel), status: "hit" as const, purpose: row.purpose }
60
+ : { rel, base: basename(rel), status: "miss" as const };
61
+ });
62
+ files.sort((a, b) => a.base.localeCompare(b.base));
63
+ const tier = files.every((f) => f.status === "hit") ? 0 : 1;
64
+ plans.push({ dir, tier, files });
65
+ }
66
+ plans.sort((a, b) => a.dir.localeCompare(b.dir));
67
+ return plans;
68
+ }
69
+
70
+ const rowFor = (base: string, purpose: string) => `| \`${base}\` | ${purpose} |`;
71
+
72
+ const byBaseAlpha = (files: FileEntry[]) => [...files].sort((a, b) => a.base.localeCompare(b.base));
73
+
74
+ /** Deterministic Tier-0 rows: verbatim index purposes, path-alphabetical. */
75
+ export function tier0Rows(plan: DirPlan): string[] {
76
+ return byBaseAlpha(plan.files).map((f) => rowFor(f.base, f.purpose ?? ""));
77
+ }
78
+
79
+ /** Render a directory AGENTS.md body from its rows. */
80
+ export function renderAgentsMd(dir: string, rows: string[]): string {
81
+ return `# DOX — ${dir}\n\nFiles in this directory. One row per source file.\n\n| File | Purpose |\n|------|---------|\n${rows.join("\n")}\n`;
82
+ }
83
+
84
+ export interface AuthoredRow {
85
+ base: string;
86
+ purpose: string;
87
+ }
88
+ export interface ValidationResult {
89
+ ok: boolean;
90
+ errors: string[];
91
+ }
92
+
93
+ /** Structural gate (design §4c): exactly one non-empty row per input file;
94
+ * hit purposes byte-identical to the index. Semantic review is separate. */
95
+ export function validateAuthored(plan: DirPlan, authored: AuthoredRow[]): ValidationResult {
96
+ const errors: string[] = [];
97
+ const byBase = new Map<string, string>();
98
+ for (const a of authored) {
99
+ if (byBase.has(a.base)) errors.push(`duplicate row for ${a.base}`);
100
+ byBase.set(a.base, a.purpose);
101
+ }
102
+ for (const f of plan.files) {
103
+ const p = byBase.get(f.base);
104
+ if (p === undefined) {
105
+ errors.push(`missing row for ${f.base}`);
106
+ continue;
107
+ }
108
+ if (!p.trim()) errors.push(`empty purpose for ${f.base}`);
109
+ if (f.status === "hit" && p !== f.purpose) errors.push(`hit purpose drifted for ${f.base}`);
110
+ }
111
+ for (const base of byBase.keys()) {
112
+ if (!plan.files.some((f) => f.base === base)) errors.push(`unexpected row for ${base}`);
113
+ }
114
+ return { ok: errors.length === 0, errors };
115
+ }
116
+
117
+ /** Build final rows for a plan given authored purposes (used after validation). */
118
+ export function finalRows(plan: DirPlan, authored: AuthoredRow[]): string[] {
119
+ const byBase = new Map(authored.map((a) => [a.base, a.purpose]));
120
+ return byBaseAlpha(plan.files).map((f) => rowFor(f.base, byBase.get(f.base) ?? f.purpose ?? ""));
121
+ }
@@ -0,0 +1,191 @@
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 { type AuthoredRow, type DirPlan, finalRows, mergeIndex, planDirs, renderAgentsMd, validateAuthored } from "./migrate-file-index.js";
9
+
10
+ export const PACKAGES_ROOT_RE = /^packages\//;
11
+
12
+ /** Read every docs/file-index-*.md split as raw text. */
13
+ export function loadSplitTexts(cwd: string): string[] {
14
+ const docs = join(cwd, "docs");
15
+ return readdirSync(docs)
16
+ .filter((f) => /^file-index-.*\.md$/.test(f))
17
+ .map((f) => readFileSync(join(docs, f), "utf8"));
18
+ }
19
+
20
+ /** Build all dir plans for the migration scope (packages/ source tree). */
21
+ export function buildDirPlans(cwd: string): DirPlan[] {
22
+ const index = mergeIndex(loadSplitTexts(cwd));
23
+ const groups = new Map([...areaFiles(cwd)].filter(([dir]) => PACKAGES_ROOT_RE.test(dir)));
24
+ return planDirs(groups, index);
25
+ }
26
+
27
+ // --- grounding gate (deterministic semantic check) ---
28
+ // Every backticked identifier in an authored purpose must appear in the source
29
+ // file. Catches hallucinated exports/symbols — the dominant Tier-1 failure mode.
30
+ const STOP = new Set(["React", "DOM", "JSON", "HTML", "URL", "API", "HTTP", "CSS", "UI", "TODO"]);
31
+ function significantIds(span: string): string[] {
32
+ const ids = span.match(/[A-Za-z_$][A-Za-z0-9_$]*/g) ?? [];
33
+ // only mixed-case (camel/Pascal) or underscore identifiers — the export-name shapes
34
+ return ids.filter((id) => id.length >= 3 && !STOP.has(id) && (/[a-z]/.test(id) && /[A-Z]/.test(id) || id.includes("_")));
35
+ }
36
+ export function groundingCheck(purpose: string, sourceText: string, known?: Set<string>): { ok: boolean; ungrounded: string[] } {
37
+ const spans = [...purpose.matchAll(/`([^`]+)`/g)].map((m) => m[1]);
38
+ const ungrounded: string[] = [];
39
+ for (const span of spans) {
40
+ for (const id of significantIds(span)) {
41
+ // grounded if the identifier appears in this file OR is another source
42
+ // file's stem (a legitimate cross-reference to a consumer/related module).
43
+ if (known?.has(id)) continue;
44
+ if (!new RegExp(`\\b${id.replace(/\$/g, "\\$")}\\b`).test(sourceText)) ungrounded.push(id);
45
+ }
46
+ }
47
+ return { ok: ungrounded.length === 0, ungrounded: [...new Set(ungrounded)] };
48
+ }
49
+
50
+ /** All source-file stems (basename without extension) across the plans — the
51
+ * cross-reference allowlist for grounding. */
52
+ export function knownStems(plans: DirPlan[]): Set<string> {
53
+ const s = new Set<string>();
54
+ for (const p of plans) for (const f of p.files) s.add(f.base.replace(/\.[^.]+$/, ""));
55
+ return s;
56
+ }
57
+
58
+ // --- batching (design §4b) ---
59
+ export interface MissRef {
60
+ dir: string;
61
+ base: string;
62
+ rel: string;
63
+ }
64
+ export interface Batch {
65
+ dirs: string[];
66
+ miss: MissRef[];
67
+ }
68
+ /** Group tier-1 miss files into batches: ≤maxMiss files and ≤maxDirs dirs per
69
+ * batch; a dir with >maxMiss misses splits into sequential same-dir batches. */
70
+ export function makeBatches(plans: DirPlan[], opts: { maxMiss?: number; maxDirs?: number } = {}): Batch[] {
71
+ const maxMiss = opts.maxMiss ?? 20;
72
+ const maxDirs = opts.maxDirs ?? 8;
73
+ const batches: Batch[] = [];
74
+ let cur: Batch = { dirs: [], miss: [] };
75
+ const flush = () => {
76
+ if (cur.miss.length) batches.push(cur);
77
+ cur = { dirs: [], miss: [] };
78
+ };
79
+ for (const plan of plans.filter((p) => p.tier === 1)) {
80
+ const misses = plan.files.filter((f) => f.status === "miss").map((f) => ({ dir: plan.dir, base: f.base, rel: f.rel }));
81
+ if (misses.length > maxMiss) {
82
+ flush();
83
+ for (let i = 0; i < misses.length; i += maxMiss) batches.push({ dirs: [plan.dir], miss: misses.slice(i, i + maxMiss) });
84
+ continue;
85
+ }
86
+ if (cur.miss.length + misses.length > maxMiss || cur.dirs.length + 1 > maxDirs) flush();
87
+ cur.dirs.push(plan.dir);
88
+ cur.miss.push(...misses);
89
+ }
90
+ flush();
91
+ return batches;
92
+ }
93
+
94
+ /** The exact @fast subagent prompt for one batch (read-only authoring). */
95
+ export function subagentPrompt(cwd: string, batch: Batch): string {
96
+ const lines = batch.miss.map((m) => `- ${m.rel}`).join("\n");
97
+ 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.
98
+
99
+ Repo root: ${cwd}
100
+ Author a row for EACH of these ${batch.miss.length} files (Read each fully first):
101
+ ${lines}
102
+
103
+ Row schema (path column = the EXACT repo-relative path from the list above, one line per file):
104
+ | \`<repo-relative-path>\` | <purpose> |
105
+
106
+ CAVEMAN STYLE for the purpose column (mandatory):
107
+ - Short declarative fragments. Drop articles (a/an/the) and copulas when meaning survives.
108
+ - Subject → verb → object, present tense. No hedging, no "we"/"you", no marketing.
109
+ - One fact per clause. Prefer concrete tokens (exported symbols, types, function names, paths) over prose.
110
+ - Keep identifiers verbatim inside backticks. Name the key exports + the file's role.
111
+ - Do NOT invent a "See change:" annotation. Only real source facts.
112
+
113
+ Output exactly ${batch.miss.length} lines (the rows), each starting with the file's repo-relative path in backticks, nothing before or after.`;
114
+ }
115
+
116
+ /** Parse a subagent batch reply into rel-path → purpose. */
117
+ export function parseAuthoredBatch(text: string): Map<string, string> {
118
+ const out = new Map<string, string>();
119
+ for (const line of text.split("\n")) {
120
+ // tolerate LLM output that drops the trailing pipe: `| path | purpose` or `| path | purpose |`
121
+ const m = line.match(/^\|\s*`([^`]+)`\s*\|\s*(.*?)\s*$/);
122
+ if (!m) continue;
123
+ const purpose = m[2].replace(/\s*\|\s*$/, "").trim();
124
+ if (purpose) out.set(m[1].trim(), purpose);
125
+ }
126
+ return out;
127
+ }
128
+
129
+ /** Fold a parsed batch reply into migration state (state.authored[dir][base]). */
130
+ export function recordAuthored(state: MigrationState, batch: Batch, byRel: Map<string, string>): { recorded: number; missing: string[] } {
131
+ let recorded = 0;
132
+ const missing: string[] = [];
133
+ for (const m of batch.miss) {
134
+ const purpose = byRel.get(m.rel);
135
+ if (!purpose) {
136
+ missing.push(m.rel);
137
+ continue;
138
+ }
139
+ (state.authored[m.dir] ??= {})[m.base] = purpose;
140
+ recorded++;
141
+ }
142
+ return { recorded, missing };
143
+ }
144
+
145
+ // --- per-dir assembly + idempotent write ---
146
+ /** Assemble one dir's AGENTS.md from its plan + authored miss rows, validate,
147
+ * ground-check, and write. Returns {ok, errors, ungrounded}. Idempotent. */
148
+ export function writeDir(cwd: string, plan: DirPlan, authoredMiss: Map<string, string>, opts: { dryRun?: boolean; known?: Set<string> } = {}): {
149
+ ok: boolean;
150
+ errors: string[];
151
+ ungrounded: { base: string; ids: string[] }[];
152
+ } {
153
+ const authored: AuthoredRow[] = plan.files.map((f) =>
154
+ f.status === "hit" ? { base: f.base, purpose: f.purpose! } : { base: f.base, purpose: authoredMiss.get(f.base) ?? "" },
155
+ );
156
+ const v = validateAuthored(plan, authored);
157
+ const ungrounded: { base: string; ids: string[] }[] = [];
158
+ for (const f of plan.files) {
159
+ if (f.status !== "miss") continue;
160
+ const purpose = authoredMiss.get(f.base) ?? "";
161
+ const src = readFileSync(join(cwd, f.rel), "utf8");
162
+ const g = groundingCheck(purpose, src, opts.known);
163
+ if (!g.ok) ungrounded.push({ base: f.base, ids: g.ungrounded });
164
+ }
165
+ if (!v.ok) return { ok: false, errors: v.errors, ungrounded };
166
+ if (!opts.dryRun) {
167
+ const md = renderAgentsMd(plan.dir, finalRows(plan, authored));
168
+ const file = join(cwd, plan.dir, "AGENTS.md");
169
+ mkdirSync(dirname(file), { recursive: true });
170
+ writeFileSync(file, md, "utf8");
171
+ }
172
+ return { ok: v.ok, errors: v.errors, ungrounded };
173
+ }
174
+
175
+ // --- checkpoint / gaps persistence (resumability) ---
176
+ const stateDir = (cwd: string) => join(cwd, ".pi", "dashboard", "kb");
177
+ export interface MigrationState {
178
+ authored: Record<string, Record<string, string>>; // dir → base → purpose
179
+ doneDirs: string[];
180
+ gaps: Record<string, string[]>; // dir → messages
181
+ }
182
+ export function loadState(cwd: string): MigrationState {
183
+ const f = join(stateDir(cwd), "migration-state.json");
184
+ if (existsSync(f)) return JSON.parse(readFileSync(f, "utf8"));
185
+ return { authored: {}, doneDirs: [], gaps: {} };
186
+ }
187
+ export function saveState(cwd: string, s: MigrationState): void {
188
+ const dir = stateDir(cwd);
189
+ mkdirSync(dir, { recursive: true });
190
+ writeFileSync(join(dir, "migration-state.json"), JSON.stringify(s, null, 2), "utf8");
191
+ }
@@ -0,0 +1,33 @@
1
+ // Ambient shim for the Node built-in `node:sqlite` module.
2
+ //
3
+ // `node:sqlite` is experimental; its typings (`sqlite.d.ts`) ship in
4
+ // `@types/node` >= 22.5. This repo pins `@types/node` 20.x, which has no such
5
+ // declaration, so `tsc` (the root `npm run lint` AND `packages/kb`'s own build)
6
+ // fails `TS2307: Cannot find module 'node:sqlite'`. This declares ONLY the
7
+ // surface `sqlite-store.ts` uses so the module resolves without a dependency
8
+ // bump. Delete this file when `@types/node` is bumped to >= 22.5.
9
+ //
10
+ // See change: adopt-pi-074-080-features (CI-unblock for the pre-existing
11
+ // develop `node:sqlite` lint failure).
12
+ declare module "node:sqlite" {
13
+ export interface StatementSync {
14
+ get(...params: unknown[]): unknown;
15
+ all(...params: unknown[]): unknown[];
16
+ run(...params: unknown[]): { changes: number | bigint; lastInsertRowid: number | bigint };
17
+ iterate(...params: unknown[]): IterableIterator<unknown>;
18
+ }
19
+ export interface DatabaseSyncOptions {
20
+ open?: boolean;
21
+ readOnly?: boolean;
22
+ enableForeignKeyConstraints?: boolean;
23
+ enableDoubleQuotedStringLiterals?: boolean;
24
+ allowExtension?: boolean;
25
+ }
26
+ export class DatabaseSync {
27
+ constructor(path: string, options?: DatabaseSyncOptions);
28
+ exec(sql: string): void;
29
+ prepare(sql: string): StatementSync;
30
+ open(): void;
31
+ close(): void;
32
+ }
33
+ }
package/src/render.ts ADDED
@@ -0,0 +1,46 @@
1
+ // One parameterized hit renderer shared by the CLI and the kb_search tool.
2
+ // See change: slim-kb-search-output.
3
+ //
4
+ // The CLI and the tool's condensed output carry the SAME fields in the SAME
5
+ // order (path :: headingPath, (+N dup), parent heading, snippet) and differ only
6
+ // on three axes, captured by RenderOpts:
7
+ // - leading token: raw BM25 score (CLI) vs 1-based rank ordinal (tool)
8
+ // - parent glyph: "[parent: " (CLI, bracketed inline) vs "⤷ " (tool)
9
+ // - line structure: single-line + indented snippet (CLI) vs multi-line (tool)
10
+ import type { KbHit } from "./types.js";
11
+
12
+ export interface RenderOpts {
13
+ /** Leading token per hit: raw BM25 `score` (CLI) or 1-based `rank` (tool). */
14
+ leading: "score" | "rank";
15
+ /** Prefix for the parent-heading continuation (CLI "[parent: ", tool "⤷ "). */
16
+ parentGlyph: string;
17
+ /** Multi-line block per hit (tool) vs single header line + indented snippet (CLI). */
18
+ multiline: boolean;
19
+ }
20
+
21
+ const SNIPPET_MAX = 160;
22
+
23
+ /** Render hits to text. `rank` is a 1-based ordinal over the given (post-limit) list. */
24
+ export function renderHits(hits: KbHit[], opts: RenderOpts): string {
25
+ const { leading, parentGlyph, multiline } = opts;
26
+ return hits
27
+ .map((h, i) => {
28
+ 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)` : "";
31
+ const snippet = h.snippet.replace(/\s+/g, " ").slice(0, SNIPPET_MAX);
32
+ if (multiline) {
33
+ const lines = [head];
34
+ if (dup) lines.push(` ${dup}`);
35
+ if (h.parent) lines.push(` ${parentGlyph}${h.parent.headingPath}`);
36
+ lines.push(` ${snippet}`);
37
+ return lines.join("\n");
38
+ }
39
+ // Single-line CLI form — byte-identical to the legacy inline render. The
40
+ // bracketed parent glyph carries its own closing "]".
41
+ const dupInline = dup ? ` ${dup}` : "";
42
+ const parentInline = h.parent ? ` ${parentGlyph}${h.parent.headingPath}]` : "";
43
+ return `${head}${dupInline}${parentInline}\n ${snippet}`;
44
+ })
45
+ .join("\n");
46
+ }
@@ -1,9 +1,10 @@
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
+
5
+ import { mkdirSync, renameSync, unlinkSync } from "node:fs";
6
6
  import { dirname } from "node:path";
7
+ import { DatabaseSync } from "node:sqlite";
7
8
  import type { Chunk, FileState, GraphEdge, GraphNode, KbHit, KbStore, SearchOpts } from "./types.js";
8
9
 
9
10
  const DDL = `
@@ -38,10 +39,16 @@ function toMatch(q: string): string {
38
39
 
39
40
  export class SqliteFtsStore implements KbStore {
40
41
  private db: DatabaseSync;
42
+ readonly dbPath: string;
41
43
  constructor(dbPath: string) {
44
+ this.dbPath = dbPath;
42
45
  if (dbPath !== ":memory:") mkdirSync(dirname(dbPath), { recursive: true });
43
46
  this.db = new DatabaseSync(dbPath);
44
47
  this.db.exec("PRAGMA journal_mode=WAL");
48
+ // Let a concurrent reader (e.g. `/stats` during a reindex) wait briefly for a
49
+ // batch's write lock instead of failing with SQLITE_BUSY. See change:
50
+ // fix-kb-index-feedback.
51
+ this.db.exec("PRAGMA busy_timeout=5000");
45
52
  }
46
53
  init() {
47
54
  this.db.exec(DDL);
@@ -60,6 +67,34 @@ export class SqliteFtsStore implements KbStore {
60
67
  close() {
61
68
  this.db.close();
62
69
  }
70
+ /** Finalize a temp-path build onto `dest`. WAL ordering is load-bearing:
71
+ * TRUNCATE-checkpoint + close BEFORE the rename so the single main file holds
72
+ * every committed page; then rename atomically and drop stale sidecars.
73
+ * See change: harden-kb-index-failure-atomicity. */
74
+ finalizeRename(dest: string) {
75
+ try {
76
+ this.db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
77
+ } catch {}
78
+ this.db.close();
79
+ renameSync(this.dbPath, dest);
80
+ for (const ext of ["-wal", "-shm"]) {
81
+ try {
82
+ unlinkSync(this.dbPath + ext);
83
+ } catch {}
84
+ }
85
+ }
86
+ /** Close and remove this DB file + WAL sidecars — cleanup for a failed run
87
+ * that itself created the file (never touches a pre-existing valid DB). */
88
+ closeAndUnlink() {
89
+ try {
90
+ this.db.close();
91
+ } catch {}
92
+ for (const ext of ["", "-wal", "-shm"]) {
93
+ try {
94
+ unlinkSync(this.dbPath + ext);
95
+ } catch {}
96
+ }
97
+ }
63
98
 
64
99
  getFileState(root: string, path: string): FileState | null {
65
100
  const r = this.db.prepare("SELECT mtime_ms, sha256 FROM files WHERE root=? AND path=?").get(root, path) as any;
@@ -177,7 +212,10 @@ export class SqliteFtsStore implements KbStore {
177
212
  if (!pc) continue;
178
213
  const parent = this.getChunkById(h.root, pc);
179
214
  if (parent && parent.chunkId !== h.chunkId) {
180
- h.parent = { root: parent.root, path: parent.path, headingPath: parent.headingPath, chunkId: parent.chunkId, docType: parent.docType, score: 0, snippet: parent.headingPath };
215
+ // Collapse to headingPath only: root/path/docType dup the child (same
216
+ // file by construction), score is a constant 0, snippet repeats
217
+ // headingPath, chunkId is not a tool refetch key. See change: slim-kb-search-output.
218
+ h.parent = { headingPath: parent.headingPath };
181
219
  }
182
220
  }
183
221
  }
package/src/types.ts CHANGED
@@ -40,7 +40,7 @@ export interface KbHit {
40
40
  score: number; // lower = more relevant (BM25 convention)
41
41
  snippet: string;
42
42
  akaPaths?: string[]; // duplicate copies collapsed by dedup
43
- parent?: KbHit | null; // small-to-big: parent section/file context (expand.parent)
43
+ parent?: { headingPath: string } | null; // small-to-big parent context (expand.parent); display-only, NOT a refetch key; non-recursive
44
44
  }
45
45
 
46
46
  /** A pluggable reranker: rescoring BM25 top-k. Default = none (no-op). */