@blackbelt-technology/pi-dashboard-kb 0.5.4

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/dox.ts ADDED
@@ -0,0 +1,289 @@
1
+ // DOX tree: directory-level AGENTS.md scaffolding + audit, and the
2
+ // `kb agents <path>` nearest-applicable chain (design §6d). Pure-local,
3
+ // deterministic, no LLM/embedding. The detect-don't-write rule: `dox init`
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";
7
+ import { createHash } from "node:crypto";
8
+ import type { KbStore } from "./types.js";
9
+
10
+ const DEFAULT_EXCLUDE = /(^|\/)(node_modules|\.git|dist|build|\.next|coverage|\.kb|\.pi)(\/|$)/;
11
+ const AGENTS_FILES = ["AGENTS.md"];
12
+ export const AREA_FILE_THRESHOLD = 8; // ≥ this many md files in a subdir → own AGENTS.md
13
+ export const ROW_CAP = 40;
14
+ const COMPANION_LOC = 300;
15
+ const COMPANION_BYTES = 15000;
16
+
17
+ export interface AgentsChainOpts {
18
+ claudeMd?: boolean;
19
+ fallbackManifest?: boolean;
20
+ }
21
+ export interface AgentsEntry {
22
+ path: string; // absolute AGENTS.md path
23
+ rel: string; // relative to cwd
24
+ depth: number; // 0 = root
25
+ }
26
+
27
+ /** Walk from cwd down to targetPath's dir, collecting AGENTS.md (CLAUDE.md if
28
+ * claudeMd) on the ancestor chain. Returns root→nearest order. */
29
+ export function agentsChain(cwd: string, targetPath: string, opts: AgentsChainOpts = {}): { chain: AgentsEntry[]; manifest: string | null } {
30
+ const names = opts.claudeMd ? [...AGENTS_FILES, "CLAUDE.md"] : AGENTS_FILES;
31
+ const target = isAbsolute(targetPath) ? targetPath : resolve(cwd, targetPath);
32
+ // collect ancestor dirs from target up to cwd. Use a path-boundary check
33
+ // (sep-aware) so a sibling like `/foo-bar` is not treated as inside `/foo`.
34
+ const withinCwd = (p: string) => p === cwd || p.startsWith(cwd + sep);
35
+ const dirs: string[] = [];
36
+ const d = existsSync(target) && statSync(target).isDirectory() ? target : dirname(target);
37
+ for (let cur = d; withinCwd(cur); cur = dirname(cur)) {
38
+ dirs.push(cur);
39
+ if (cur === cwd) break;
40
+ }
41
+ if (!dirs.includes(cwd)) dirs.push(cwd);
42
+ // root→nearest = cwd first → target
43
+ const ordered = dirs.reverse();
44
+ const chain: AgentsEntry[] = [];
45
+ ordered.forEach((dir, depth) => {
46
+ for (const name of names) {
47
+ const p = join(dir, name);
48
+ if (existsSync(p)) chain.push({ path: p, rel: relative(cwd, p) || name, depth });
49
+ }
50
+ });
51
+ let manifest: string | null = null;
52
+ if (chain.length === 0 && opts.fallbackManifest) {
53
+ manifest = fallbackManifest(cwd, target);
54
+ }
55
+ return { chain, manifest };
56
+ }
57
+
58
+ /** KB-generated routing manifest when no AGENTS.md exists on the path: lists
59
+ * markdown files under the target subtree as a path → heading map. */
60
+ export function fallbackManifest(cwd: string, targetPath: string, store?: KbStore): string {
61
+ const target = isAbsolute(targetPath) ? targetPath : resolve(cwd, targetPath);
62
+ const walkRoot = existsSync(target) && statSync(target).isDirectory() ? target : dirname(target);
63
+ const files = walkMd(walkRoot);
64
+ const lines = [`# KB routing manifest for ${relative(cwd, target) || target}`, "", "No AGENTS.md on this path. Generated map of nearby markdown:", ""];
65
+ for (const f of files.slice(0, 50)) {
66
+ const rel = relative(cwd, f) || basename(f);
67
+ lines.push(`- \`${rel}\``);
68
+ }
69
+ if (store) {
70
+ lines.push("", "## Top sections in this subtree");
71
+ const hits = store.search(relative(cwd, target) || basename(target), { limit: 10 });
72
+ for (const h of hits) lines.push(`- \`${h.path}\` :: ${h.headingPath}`);
73
+ }
74
+ return lines.join("\n");
75
+ }
76
+
77
+ // --- dox init ---
78
+
79
+ export interface DoxInitOptions {
80
+ dryRun?: boolean;
81
+ cwd: string;
82
+ }
83
+ export interface DoxInitPlan {
84
+ created: string[]; // AGENTS.md paths to create
85
+ appended: { file: string; rows: string[] }[]; // existing files getting new rows
86
+ }
87
+
88
+ function walkMd(dir: string, out: string[] = []): string[] {
89
+ if (!existsSync(dir)) return out;
90
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
91
+ const abs = join(dir, e.name);
92
+ const rel = abs; // for DEFAULT_EXCLUDE we test the abs-ish path
93
+ if (DEFAULT_EXCLUDE.test(rel)) continue;
94
+ if (e.isDirectory()) walkMd(abs, out);
95
+ else if (/\.(md|mdx)$/i.test(e.name) && !AGENTS_FILES.includes(e.name)) out.push(abs);
96
+ }
97
+ return out;
98
+ }
99
+
100
+ /** Parse existing row paths from an AGENTS.md file. */
101
+ export function parseRowPaths(agentsFile: string): string[] {
102
+ if (!existsSync(agentsFile)) return [];
103
+ const text = readFileSync(agentsFile, "utf8");
104
+ const paths: string[] = [];
105
+ for (const line of text.split("\n")) {
106
+ const m = line.match(/^\|\s*`([^`]+)`\s*\|/);
107
+ if (m) paths.push(m[1]);
108
+ }
109
+ return paths;
110
+ }
111
+
112
+ function areaFiles(cwd: string): Map<string, string[]> {
113
+ // group md files by immediate subdir
114
+ const groups = new Map<string, string[]>();
115
+ for (const f of walkMd(cwd)) {
116
+ const rel = relative(cwd, f);
117
+ const top = rel.includes("/") ? rel.slice(0, rel.indexOf("/")) : ".";
118
+ (groups.get(top) ?? groups.set(top, []).get(top)!).push(rel);
119
+ }
120
+ return groups;
121
+ }
122
+
123
+ /** Plan (and optionally write) a DOX tree. Idempotent: never clobbers existing
124
+ * AGENTS.md; only adds missing files + missing path rows. */
125
+ export function doxInit(opts: DoxInitOptions): DoxInitPlan {
126
+ const cwd = opts.cwd;
127
+ const plan: DoxInitPlan = { created: [], appended: [] };
128
+ const groups = areaFiles(cwd);
129
+
130
+ const buildRows = (rels: string[], areaDir: string): string[] =>
131
+ rels
132
+ .filter((r) => !AGENTS_FILES.includes(basename(r)))
133
+ .map((r) => `| \`${r}\` | |`);
134
+
135
+ const ensure = (agentsFile: string, rows: string[]) => {
136
+ if (existsSync(agentsFile)) {
137
+ const existing = new Set(parseRowPaths(agentsFile));
138
+ const missRows = rows.filter((row) => {
139
+ const m = row.match(/`([^`]+)`/);
140
+ return m && !existing.has(m[1]);
141
+ });
142
+ if (missRows.length) plan.appended.push({ file: agentsFile, rows: missRows });
143
+ if (!opts.dryRun && missRows.length) appendFileSync(agentsFile, "\n" + missRows.join("\n") + "\n");
144
+ } else {
145
+ plan.created.push(agentsFile);
146
+ if (!opts.dryRun) {
147
+ mkdirSync(dirname(agentsFile), { recursive: true });
148
+ writeFileSync(agentsFile, `# DOX — ${relative(cwd, dirname(agentsFile)) || "root"}\n\nFiles in this area. Purposes left for the agent to author.\n\n${rows.join("\n")}\n`, "utf8");
149
+ }
150
+ }
151
+ };
152
+
153
+ // root AGENTS.md: rows for root-level files + pointers to area AGENTS.md
154
+ const rootRels = groups.get(".") ?? [];
155
+ const areaDirs = [...groups.keys()].filter((k) => k !== "." && groups.get(k)!.length >= AREA_FILE_THRESHOLD);
156
+ const rootRows = buildRows(rootRels, cwd);
157
+ for (const a of areaDirs) rootRows.push(`| \`${a}/AGENTS.md\` | |`);
158
+ ensure(join(cwd, "AGENTS.md"), rootRows);
159
+
160
+ // one AGENTS.md per over-threshold area
161
+ for (const a of areaDirs) {
162
+ const rels = groups.get(a)!;
163
+ const areaRows = buildRows(rels, join(cwd, a));
164
+ // split into chunks of ROW_CAP
165
+ for (let i = 0; i < areaRows.length; i += ROW_CAP) {
166
+ const chunk = areaRows.slice(i, i + ROW_CAP);
167
+ const subArea = i === 0 ? join(cwd, a) : join(cwd, a, `part-${Math.floor(i / ROW_CAP) + 1}`);
168
+ ensure(join(subArea, "AGENTS.md"), chunk);
169
+ }
170
+ }
171
+
172
+ return plan;
173
+ }
174
+
175
+ // --- dox lint ---
176
+
177
+ export interface DoxIssue {
178
+ kind: "stale" | "orphan" | "missing" | "missing-companion" | "broken-pointer" | "over-threshold";
179
+ agentsFile: string;
180
+ path?: string;
181
+ detail: string;
182
+ }
183
+ export interface DoxLintOptions {
184
+ json?: boolean;
185
+ fix?: boolean;
186
+ cwd: string;
187
+ stalenessFile?: string; // sidecar path (source-path → ack-hash)
188
+ }
189
+ export interface DoxLintResult {
190
+ issues: DoxIssue[];
191
+ fixed: number;
192
+ }
193
+
194
+ function fileSha(p: string): string {
195
+ try { return createHash("sha256").update(readFileSync(p)).digest("hex"); } catch { return ""; }
196
+ }
197
+ function loc(p: string): number {
198
+ try { return readFileSync(p, "utf8").split("\n").length; } catch { return 0; }
199
+ }
200
+
201
+ export function doxLint(opts: DoxLintOptions): DoxLintResult {
202
+ const cwd = opts.cwd;
203
+ const issues: DoxIssue[] = [];
204
+ let fixed = 0;
205
+
206
+ // find all AGENTS.md
207
+ const agentsFiles: string[] = [];
208
+ const walkAgents = (dir: string) => {
209
+ if (!existsSync(dir)) return;
210
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
211
+ const abs = join(dir, e.name);
212
+ if (DEFAULT_EXCLUDE.test(abs)) continue;
213
+ if (e.isDirectory()) walkAgents(abs);
214
+ else if (e.name === "AGENTS.md") agentsFiles.push(abs);
215
+ }
216
+ };
217
+ walkAgents(cwd);
218
+
219
+ // staleness sidecar
220
+ let staleness: Record<string, string> = {};
221
+ const sf = opts.stalenessFile ?? join(cwd, ".pi", "dashboard", "kb", "dox-staleness.json");
222
+ if (existsSync(sf)) { try { staleness = JSON.parse(readFileSync(sf, "utf8")); } catch { /* */ } }
223
+
224
+ const allMd = new Set(walkMd(cwd).map((f) => relative(cwd, f)));
225
+ const rowPaths = new Set<string>();
226
+
227
+ for (const af of agentsFiles) {
228
+ const rows = parseRowPaths(af);
229
+ const afRel = relative(cwd, af);
230
+ // over-threshold
231
+ if (rows.length > ROW_CAP) issues.push({ kind: "over-threshold", agentsFile: afRel, detail: `${rows.length} rows > cap ${ROW_CAP}` });
232
+ const survivingRows: string[] = [];
233
+ const text = readFileSync(af, "utf8").split("\n");
234
+ for (const line of text) {
235
+ const m = line.match(/^\|\s*`([^`]+)`\s*\|/);
236
+ if (!m) { if (opts.fix) survivingRows.push(line); continue; }
237
+ const rp = m[1];
238
+ rowPaths.add(rp);
239
+ const abs = isAbsolute(rp) ? rp : resolve(cwd, rp);
240
+ if (!existsSync(abs)) {
241
+ // could be a broken pointer to an area AGENTS.md, or an orphan source row
242
+ const kind = rp.endsWith("AGENTS.md") ? "broken-pointer" : "orphan";
243
+ issues.push({ kind, agentsFile: afRel, path: rp, detail: `${kind}: ${rp} does not exist` });
244
+ if (opts.fix && kind === "orphan") { fixed++; continue; } // prune orphan row
245
+ } else if (staleness[rp] && fileSha(abs) && staleness[rp] !== fileSha(abs)) {
246
+ issues.push({ kind: "stale", agentsFile: afRel, path: rp, detail: `tracked source-hash drifted` });
247
+ }
248
+ if (opts.fix) survivingRows.push(line);
249
+ }
250
+ if (opts.fix) writeFileSync(af, survivingRows.join("\n") + "\n", "utf8");
251
+ }
252
+
253
+ // missing rows: md files in an area (dir containing an AGENTS.md) with no row.
254
+ // Owner = nearest ancestor AGENTS.md (deepest dir prefix of the file's dir).
255
+ const ownerOf = (mdDir: string): string | null => {
256
+ let best: string | null = null;
257
+ let bestDepth = -1;
258
+ for (const af of agentsFiles) {
259
+ const aDir = relative(cwd, dirname(af)) || ".";
260
+ const prefix = aDir === "." ? "" : aDir + "/";
261
+ if (mdDir === aDir || mdDir.startsWith(prefix)) {
262
+ const depth = aDir.split("/").filter(Boolean).length;
263
+ if (depth > bestDepth) { best = af; bestDepth = depth; }
264
+ }
265
+ }
266
+ return best;
267
+ };
268
+ for (const md of allMd) {
269
+ if (rowPaths.has(md)) continue;
270
+ const dir = md.includes("/") ? md.slice(0, md.lastIndexOf("/")) : ".";
271
+ const owner = ownerOf(dir);
272
+ if (owner) {
273
+ const ownerRel = relative(cwd, owner) || "AGENTS.md";
274
+ issues.push({ kind: "missing", agentsFile: ownerRel, path: md, detail: `no row for ${md}` });
275
+ if (opts.fix) { appendFileSync(owner, `| \`${md}\` | |\n`); fixed++; }
276
+ }
277
+ }
278
+
279
+ // missing companions: large source/md files with no <file>.agent.md
280
+ for (const md of allMd) {
281
+ const abs = join(cwd, md);
282
+ if (loc(abs) > COMPANION_LOC || statSync(abs).size > COMPANION_BYTES) {
283
+ const comp = md.replace(/\.mdx?$/i, ".agent.md");
284
+ if (!existsSync(join(cwd, comp))) issues.push({ kind: "missing-companion", agentsFile: comp, path: md, detail: `${md} past threshold, no ${comp}` });
285
+ }
286
+ }
287
+
288
+ return { issues, fixed };
289
+ }
package/src/eval.ts ADDED
@@ -0,0 +1,49 @@
1
+ // Retrieval-quality evaluation (design §6c Tier E, research §2.5).
2
+ // Scores search against a golden `query -> expected path-substring` set.
3
+ // Gate ranking changes on these metrics; track normal + paraphrase sets.
4
+ import type { KbStore, SearchOpts } from "./types.js";
5
+
6
+ export interface GoldenItem {
7
+ q: string;
8
+ expect: string; // path substring the correct result should match (root-agnostic)
9
+ }
10
+ export interface EvalMetrics {
11
+ n: number;
12
+ "P@1": number;
13
+ "P@5": number;
14
+ "Recall@K": number;
15
+ MRR: number;
16
+ "nDCG@K": number;
17
+ avgLatencyMs: number;
18
+ }
19
+
20
+ export function evaluate(store: KbStore, golden: GoldenItem[], opts: SearchOpts & { k?: number } = {}): EvalMetrics {
21
+ const k = opts.k ?? 10;
22
+ let p1 = 0, p5 = 0, recall = 0, mrr = 0, ndcg = 0, lat = 0;
23
+ for (const g of golden) {
24
+ const t = performance.now();
25
+ const res = store.search(g.q, { ...opts, limit: k });
26
+ lat += performance.now() - t;
27
+ let first = 0;
28
+ res.forEach((r, i) => {
29
+ if (!first && r.path.includes(g.expect)) first = i + 1;
30
+ });
31
+ if (first === 1) p1++;
32
+ if (first >= 1 && first <= 5) p5++;
33
+ if (first >= 1) {
34
+ recall++;
35
+ mrr += 1 / first;
36
+ ndcg += 1 / Math.log2(first + 1); // IDCG=1 (single relevant target)
37
+ }
38
+ }
39
+ const n = golden.length || 1;
40
+ return {
41
+ n: golden.length,
42
+ "P@1": +(p1 / n).toFixed(3),
43
+ "P@5": +(p5 / n).toFixed(3),
44
+ "Recall@K": +(recall / n).toFixed(3),
45
+ MRR: +(mrr / n).toFixed(3),
46
+ "nDCG@K": +(ndcg / n).toFixed(3),
47
+ avgLatencyMs: +(lat / n).toFixed(2),
48
+ };
49
+ }
package/src/index.ts ADDED
@@ -0,0 +1,25 @@
1
+ // Public API barrel for @blackbelt-technology/pi-dashboard-kb (Phase 1 slice).
2
+ export type {
3
+ Chunk,
4
+ DocType,
5
+ FileState,
6
+ GraphEdge,
7
+ GraphNode,
8
+ KbHit,
9
+ KbStore,
10
+ SearchOpts,
11
+ } from "./types.js";
12
+ export { chunkMarkdown } from "./chunker.js";
13
+ export type { ChunkInput, ParseResult } from "./chunker.js";
14
+ export { SqliteFtsStore } from "./sqlite-store.js";
15
+ export { indexSource } from "./indexer.js";
16
+ export type { IndexSource, IndexOptions, IndexStats } from "./indexer.js";
17
+ export { kbInit } from "./init.js";
18
+ export type { InitOptions, InitResult } from "./init.js";
19
+ export { loadConfig, validateConfig, DEFAULTS } from "./config.js";
20
+ export type { KbConfig, SourceConfig, RankingConfig, ResolvedConfig } from "./config.js";
21
+ export { resolveAll, classifyRef, sourceIdentity, resolverFor } from "./sources.js";
22
+ export type { KbSourceKind, ResolvedSource, ResolveCtx, SourceResolver } from "./sources.js";
23
+ export { isTrusted, recordTrust, canonicalSource, sourceHash } from "./trust.js";
24
+ export { agentsChain, doxInit, doxLint, fallbackManifest, parseRowPaths } from "./dox.js";
25
+ export type { AgentsEntry, DoxInitPlan, DoxIssue, DoxLintResult } from "./dox.js";
package/src/indexer.ts ADDED
@@ -0,0 +1,159 @@
1
+ // Indexer: walk a filesystem source, layered mtime→sha256 change detection,
2
+ // structural chunking, Tier-1 graph extraction, transactional upsert (design §5).
3
+ import { createHash } from "node:crypto";
4
+ import { readFileSync, readdirSync, statSync } from "node:fs";
5
+ import { join, relative } from "node:path";
6
+ import { chunkMarkdown } from "./chunker.js";
7
+ import type { DocType, KbStore } from "./types.js";
8
+
9
+ export interface IndexSource {
10
+ root: string; // label/id stored on chunks
11
+ dir: string; // absolute directory to walk
12
+ include?: (rel: string) => boolean;
13
+ }
14
+ export interface IndexOptions {
15
+ force?: boolean;
16
+ indexAgentsFiles?: boolean; // AGENTS.md / CLAUDE.md
17
+ includeSourceMarkdown?: boolean; // *.md in source dirs → doc_type 'source-md'
18
+ include?: string[]; // glob patterns to include
19
+ exclude?: string[]; // glob patterns to exclude
20
+ extensions?: string[]; // e.g. [".md"]
21
+ }
22
+ export interface IndexStats {
23
+ scanned: number;
24
+ changed: number;
25
+ deleted: number;
26
+ chunks: number;
27
+ }
28
+
29
+ const sha = (s: string | Buffer) => createHash("sha256").update(s).digest("hex");
30
+ const DEFAULT_EXCLUDE = /(^|\/)(node_modules|\.git|dist|build|\.next|coverage|\.kb)(\/|$)/;
31
+
32
+ /** Minimal glob → RegExp (supports **, *, ?). Good enough for include/exclude. */
33
+ function globToRe(g: string): RegExp {
34
+ const body = g
35
+ .replace(/[.+^$(){}|\\]/g, "\\$&")
36
+ .replace(/\*\*\//g, "«GS»")
37
+ .replace(/\*\*/g, "«G»")
38
+ .replace(/\*/g, "[^/]*")
39
+ .replace(/\?/g, "[^/]")
40
+ .replace(/«GS»/g, "(.*/)?")
41
+ .replace(/«G»/g, ".*");
42
+ return new RegExp("(^|/)" + body + "$");
43
+ }
44
+ function matchAny(pats: RegExp[], rel: string): boolean {
45
+ return pats.some((re) => re.test(rel));
46
+ }
47
+
48
+ function walk(dir: string, base: string, out: string[] = []): string[] {
49
+ for (const e of readdirSync(dir, { withFileTypes: true })) {
50
+ const abs = join(dir, e.name);
51
+ const rel = relative(base, abs);
52
+ if (DEFAULT_EXCLUDE.test(rel)) continue;
53
+ if (e.isDirectory()) walk(abs, base, out);
54
+ else if (/\.(md|mdx|markdown)$/i.test(e.name)) out.push(abs);
55
+ }
56
+ return out;
57
+ }
58
+
59
+ function docTypeOf(rel: string, includeSourceMarkdown: boolean): DocType {
60
+ const base = rel.split("/").pop() ?? "";
61
+ if (base === "AGENTS.md" || base === "CLAUDE.md") return "agents";
62
+ if (includeSourceMarkdown && /(^|\/)(src|lib|app|packages)\//.test(rel)) return "source-md";
63
+ return "doc";
64
+ }
65
+
66
+ export function indexSource(store: KbStore, src: IndexSource, opts: IndexOptions = {}): IndexStats {
67
+ const extRe = opts.extensions?.length ? new RegExp("(" + opts.extensions.map((e) => e.replace(/\./g, "\\.")).join("|") + ")$", "i") : /\.(md|mdx|markdown)$/i;
68
+ const inc = opts.include?.map(globToRe);
69
+ const exc = opts.exclude?.map(globToRe);
70
+ const includeSourceMd = opts.includeSourceMarkdown !== false;
71
+ const files = walk(src.dir, src.dir).filter((abs) => {
72
+ const rel = relative(src.dir, abs);
73
+ if (src.include && !src.include(rel)) return false;
74
+ if (inc && !matchAny(inc, rel)) return false;
75
+ if (exc && matchAny(exc, rel)) return false;
76
+ if (docTypeOf(rel, includeSourceMd) === "agents" && opts.indexAgentsFiles === false) return false;
77
+ return true;
78
+ });
79
+
80
+ const stats: IndexStats = { scanned: files.length, changed: 0, deleted: 0, chunks: 0 };
81
+ const live = new Set<string>();
82
+
83
+ store.begin();
84
+ try {
85
+ for (const abs of files) {
86
+ const rel = relative(src.dir, abs);
87
+ live.add(rel);
88
+ const st = statSync(abs);
89
+ const prev = store.getFileState(src.root, rel);
90
+ if (!opts.force && prev && prev.mtimeMs === st.mtimeMs) continue; // mtime cheap-check
91
+ const buf = readFileSync(abs);
92
+ const hash = sha(buf);
93
+ if (!opts.force && prev && prev.sha256 === hash) {
94
+ store.setFileState(src.root, rel, { mtimeMs: st.mtimeMs, sha256: hash });
95
+ continue; // content unchanged
96
+ }
97
+ // changed → replace
98
+ store.deleteByPath(src.root, rel);
99
+ const { chunks, wikilinks, mdLinks, frontmatter } = chunkMarkdown({ root: src.root, path: rel, text: buf.toString("utf8"), docType: docTypeOf(rel, includeSourceMd) });
100
+ // file node
101
+ store.addNode({ type: "file", name: rel, path: rel });
102
+ for (const c of chunks) {
103
+ store.insertChunk(c);
104
+ if (c.level > 0) {
105
+ store.addNode({ type: "heading", name: c.headingPath, path: rel });
106
+ const parentName = c.parentChunkId ? chunks.find((x) => x.chunkId === c.parentChunkId)?.headingPath : rel;
107
+ store.addEdge({ src: c.headingPath, dst: parentName ?? rel, rel: "child_of" });
108
+ }
109
+ }
110
+ // tier-1 graph: wikilinks + md links + frontmatter tags
111
+ for (const w of wikilinks) {
112
+ store.addNode({ type: "file", name: normalizeLink(w), path: null });
113
+ store.addEdge({ src: rel, dst: normalizeLink(w), rel: "links_to" });
114
+ }
115
+ for (const l of mdLinks) {
116
+ const target = normalizeRel(rel, l);
117
+ store.addNode({ type: "file", name: target, path: null });
118
+ store.addEdge({ src: rel, dst: target, rel: "references" });
119
+ }
120
+ const tags = frontmatter?.tags;
121
+ if (Array.isArray(tags)) for (const tag of tags) {
122
+ store.addNode({ type: "tag", name: `tag:${tag}`, path: null });
123
+ store.addEdge({ src: rel, dst: `tag:${tag}`, rel: "has_tag" });
124
+ }
125
+ store.setFileState(src.root, rel, { mtimeMs: st.mtimeMs, sha256: hash }); // persist for incremental
126
+ stats.changed++;
127
+ stats.chunks += chunks.length;
128
+ }
129
+ // deletions: paths in store but not on disk
130
+ for (const p of store.listPaths(src.root)) {
131
+ if (!live.has(p)) {
132
+ store.deleteByPath(src.root, p);
133
+ stats.deleted++;
134
+ }
135
+ }
136
+ store.commit();
137
+ } catch (err) {
138
+ store.rollback();
139
+ throw err;
140
+ }
141
+ return stats;
142
+ }
143
+
144
+ // [[name]] → basename match (design §9.6 simplified): resolve to "<name>.md" leaf
145
+ function normalizeLink(w: string): string {
146
+ const name = w.split("|")[0].split("#")[0].trim();
147
+ return name.endsWith(".md") ? name : `${name}.md`;
148
+ }
149
+ function normalizeRel(from: string, link: string): string {
150
+ const dir = from.includes("/") ? from.slice(0, from.lastIndexOf("/")) : "";
151
+ const parts = (dir ? dir + "/" : "") + link;
152
+ const stack: string[] = [];
153
+ for (const seg of parts.split("/")) {
154
+ if (seg === "." || seg === "") continue;
155
+ if (seg === "..") stack.pop();
156
+ else stack.push(seg);
157
+ }
158
+ return stack.join("/");
159
+ }
package/src/init.ts ADDED
@@ -0,0 +1,85 @@
1
+ // `kb init` — scaffold + validate knowledge_base.json (design §7, §8.1).
2
+ // Project file by default; --global writes ~/.pi/dashboard/knowledge_base.json.
3
+ // Seeds documented defaults + sources[]; gitignores dbPath; never clobbers
4
+ // without --force; --dry-run prints and writes nothing.
5
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, appendFileSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { dirname, isAbsolute, join, resolve } from "node:path";
8
+ import { DEFAULTS, globalConfigPath, projectConfigPath, validateConfig, type KbConfig, type SourceConfig } from "./config.js";
9
+
10
+ export interface InitOptions {
11
+ global?: boolean;
12
+ force?: boolean;
13
+ dryRun?: boolean;
14
+ sources?: string[]; // raw <ref> strings → filesystem sources
15
+ cwd?: string;
16
+ }
17
+
18
+ export interface InitResult {
19
+ configPath: string;
20
+ dbPath: string;
21
+ gitignorePath: string | null;
22
+ gitignoreAdded: string | null;
23
+ sources: SourceConfig[];
24
+ wrote: boolean;
25
+ }
26
+
27
+ /** Build the config object to be written, with documented defaults. */
28
+ export function buildInitConfig(sources: SourceConfig[] = []): KbConfig {
29
+ return { ...DEFAULTS, sources };
30
+ }
31
+
32
+ /** Render a human-readable, commented JSON-ish config. JSON has no comments,
33
+ * so we emit valid JSON with defaults and return a separate doc string. */
34
+ export function renderConfig(c: KbConfig): string {
35
+ return JSON.stringify(c, null, 2);
36
+ }
37
+
38
+ function ensureGitignore(dbPath: string, cwd: string): { path: string; added: string } | null {
39
+ // Resolve dbPath relative to cwd; gitignore the project-local DB dir.
40
+ const abs = isAbsolute(dbPath) ? dbPath : resolve(cwd, dbPath);
41
+ if (!abs.startsWith(cwd)) return null; // DB outside project → no project gitignore entry
42
+ const rel = abs.slice(cwd.length + 1);
43
+ const entry = `/${rel}`;
44
+ const giPath = join(cwd, ".gitignore");
45
+ let existing = "";
46
+ if (existsSync(giPath)) existing = readFileSync(giPath, "utf8");
47
+ if (existing.includes(entry)) return { path: giPath, added: "" };
48
+ appendFileSync(giPath, (existing && !existing.endsWith("\n") ? "\n" : "") + `\n# kb knowledge base index\n${entry}\n`);
49
+ return { path: giPath, added: entry };
50
+ }
51
+
52
+ export function kbInit(opts: InitOptions): InitResult {
53
+ const cwd = opts.cwd ?? process.cwd();
54
+ const configPath = opts.global ? globalConfigPath() : projectConfigPath(cwd);
55
+ const sources: SourceConfig[] = (opts.sources ?? []).map((ref) => ({ kind: "filesystem", ref }));
56
+ const cfg = buildInitConfig(sources);
57
+ validateConfig(cfg, opts.global ? "global" : "project");
58
+
59
+ const dbPath = cfg.dbPath;
60
+ const gitignorePath = opts.global ? null : join(cwd, ".gitignore");
61
+
62
+ if (existsSync(configPath) && !opts.force) {
63
+ if (opts.dryRun) {
64
+ return { configPath, dbPath, gitignorePath, gitignoreAdded: null, sources, wrote: false };
65
+ }
66
+ throw new Error(`${configPath} already exists — pass --force to overwrite`);
67
+ }
68
+
69
+ if (opts.dryRun) {
70
+ // print planned config, write nothing
71
+ console.log(`# dry-run: would write ${configPath}`);
72
+ console.log(renderConfig(cfg));
73
+ return { configPath, dbPath, gitignorePath, gitignoreAdded: null, sources, wrote: false };
74
+ }
75
+
76
+ mkdirSync(dirname(configPath), { recursive: true });
77
+ writeFileSync(configPath, renderConfig(cfg) + "\n", "utf8");
78
+
79
+ let gitignoreAdded: string | null = null;
80
+ if (!opts.global) {
81
+ const gi = ensureGitignore(dbPath, cwd);
82
+ if (gi) gitignoreAdded = gi.added || null;
83
+ }
84
+ return { configPath, dbPath, gitignorePath, gitignoreAdded, sources, wrote: true };
85
+ }