@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.
@@ -0,0 +1,14 @@
1
+ import type { Chunk, DocType } from "./types.js";
2
+ export interface ChunkInput {
3
+ root: string;
4
+ path: string;
5
+ text: string;
6
+ docType?: DocType;
7
+ }
8
+ export interface ParseResult {
9
+ chunks: Chunk[];
10
+ frontmatter: Record<string, unknown> | null;
11
+ wikilinks: string[];
12
+ mdLinks: string[];
13
+ }
14
+ export declare function chunkMarkdown(input: ChunkInput): ParseResult;
@@ -0,0 +1,126 @@
1
+ // Structural (heading) chunker — fence-safe, breadcrumb-aware (design §3).
2
+ // Line-based with a fenced-code state machine; validated in the prototype
3
+ // (research §2.5). mdast (unified/remark) is the documented refinement.
4
+ import { createHash } from "node:crypto";
5
+ const MIN_CHUNK_CHARS = 100;
6
+ const MAX_CHUNK_CHARS = 4000;
7
+ 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
+ export function chunkMarkdown(input) {
26
+ const docType = input.docType ?? "doc";
27
+ const { body: text, fm } = parseFrontmatter(input.text);
28
+ const lines = text.split("\n");
29
+ const fileTitle = input.path.split("/").pop().replace(/\.(md|mdx|markdown)$/i, "");
30
+ const raw = [];
31
+ const stack = [];
32
+ let cur = null;
33
+ let inFence = false;
34
+ let fenceCh = "";
35
+ let ordinal = 0;
36
+ const flush = () => {
37
+ if (cur && cur.body.trim())
38
+ raw.push(cur);
39
+ };
40
+ for (const line of lines) {
41
+ const t = line.trimStart();
42
+ const fm2 = t.match(/^(```+|~~~+)/);
43
+ if (fm2) {
44
+ if (!inFence) {
45
+ inFence = true;
46
+ fenceCh = fm2[1][0];
47
+ }
48
+ else if (t.startsWith(fenceCh)) {
49
+ inFence = false;
50
+ }
51
+ if (cur)
52
+ cur.body += line + "\n";
53
+ continue;
54
+ }
55
+ const hm = !inFence && line.match(/^(#{1,6})\s+(.*)$/);
56
+ if (hm) {
57
+ flush();
58
+ const level = hm[1].length;
59
+ const title = hm[2].trim();
60
+ while (stack.length && stack[stack.length - 1].level >= level)
61
+ stack.pop();
62
+ const parentOrdinal = stack.length ? stack[stack.length - 1].chunkOrdinal : -1;
63
+ stack.push({ level, title, chunkOrdinal: ordinal });
64
+ cur = {
65
+ headingPath: stack.map((s) => s.title).join(" > "),
66
+ heading: title,
67
+ level,
68
+ parentChunkId: parentOrdinal >= 0 ? String(parentOrdinal) : null,
69
+ body: "",
70
+ };
71
+ ordinal++;
72
+ }
73
+ else {
74
+ if (!cur) {
75
+ cur = { headingPath: fileTitle, heading: fileTitle, level: 0, parentChunkId: null, body: "" };
76
+ ordinal++;
77
+ }
78
+ cur.body += line + "\n";
79
+ }
80
+ }
81
+ flush();
82
+ // merge tiny chunks up into the previous (design §3 step 5)
83
+ const merged = [];
84
+ for (const c of raw) {
85
+ if (c.body.trim().length < MIN_CHUNK_CHARS && merged.length) {
86
+ merged[merged.length - 1].body += "\n" + c.heading + "\n" + c.body;
87
+ }
88
+ else
89
+ merged.push(c);
90
+ }
91
+ // split oversized leaf sections by paragraph (design §3 step 6)
92
+ const sized = [];
93
+ for (const c of merged) {
94
+ if (c.body.length <= MAX_CHUNK_CHARS) {
95
+ sized.push(c);
96
+ continue;
97
+ }
98
+ const paras = c.body.split(/\n\s*\n/);
99
+ let buf = "";
100
+ for (const p of paras) {
101
+ if ((buf + p).length > MAX_CHUNK_CHARS && buf) {
102
+ sized.push({ ...c, body: buf });
103
+ buf = "";
104
+ }
105
+ buf += p + "\n\n";
106
+ }
107
+ if (buf.trim())
108
+ sized.push({ ...c, body: buf });
109
+ }
110
+ const fileSha = sha(input.path);
111
+ const chunks = sized.map((c, i) => ({
112
+ root: input.root,
113
+ path: input.path,
114
+ chunkId: `${fileSha.slice(0, 8)}:${i}`,
115
+ headingPath: c.headingPath,
116
+ heading: c.heading,
117
+ level: c.level,
118
+ parentChunkId: c.parentChunkId ? `${fileSha.slice(0, 8)}:${c.parentChunkId}` : null,
119
+ docType,
120
+ body: c.body.trimEnd(),
121
+ bodyHash: sha(c.body.trim()),
122
+ }));
123
+ const wikilinks = [...input.text.matchAll(/\[\[([^\]]+)\]\]/g)].map((m) => m[1].trim());
124
+ const mdLinks = [...input.text.matchAll(/\]\(([^)]+\.mdx?)\)/g)].map((m) => m[1].trim());
125
+ return { chunks, frontmatter: fm, wikilinks, mdLinks };
126
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,277 @@
1
+ #!/usr/bin/env node
2
+ // kb CLI (Phase 1): index | search | neighbors | backlinks | get | config
3
+ // Run (dev): NODE_OPTIONS=--experimental-sqlite tsx src/cli.ts <cmd> ...
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";
8
+ import { kbInit } from "./init.js";
9
+ import { SqliteFtsStore } from "./sqlite-store.js";
10
+ import { indexSource } from "./indexer.js";
11
+ import { evaluate } from "./eval.js";
12
+ import { resolveAll } from "./sources.js";
13
+ import { defaultPromptTrust } from "./trust.js";
14
+ import { agentsChain, doxInit, doxLint } from "./dox.js";
15
+ function parse(argv) {
16
+ const f = { _: [] };
17
+ for (let i = 0; i < argv.length; i++) {
18
+ const a = argv[i];
19
+ if (a.startsWith("--")) {
20
+ const key = a.slice(2);
21
+ const next = argv[i + 1];
22
+ if (next === undefined || next.startsWith("--"))
23
+ f[key] = true;
24
+ else {
25
+ // collect repeatable --source
26
+ if (key === "source")
27
+ (f.source = [].concat(f.source ?? [], next));
28
+ else
29
+ f[key] = next;
30
+ i++;
31
+ }
32
+ }
33
+ else
34
+ f._.push(a);
35
+ }
36
+ return f;
37
+ }
38
+ /** Validate a positive-integer flag; exit 2 with a clear message on garbage. */
39
+ function posInt(v, name) {
40
+ if (v === undefined)
41
+ return undefined;
42
+ const n = Number(v);
43
+ if (!Number.isInteger(n) || n < 1) {
44
+ console.error(`${name} must be a positive integer (got ${String(v)})`);
45
+ process.exit(2);
46
+ }
47
+ return n;
48
+ }
49
+ /** Validate an enum flag against an allowlist; exit 2 on unknown value. */
50
+ function enumFlag(v, allowed, name) {
51
+ if (v === undefined || v === true)
52
+ return undefined;
53
+ if (!allowed.includes(v)) {
54
+ console.error(`${name} must be one of ${allowed.join("|")} (got ${String(v)})`);
55
+ process.exit(2);
56
+ }
57
+ return v;
58
+ }
59
+ function cfgFrom(flags) {
60
+ const cwd = flags.cwd ?? process.cwd();
61
+ const cfg = loadConfig(cwd, { configPath: flags.config });
62
+ // --source <dir> (repeatable) overrides sources for ad-hoc use
63
+ const srcs = flags.source;
64
+ if (srcs?.length) {
65
+ cfg.resolvedSources = srcs.map((s, i) => ({ id: s, dir: resolve(cwd, s), priority: srcs.length - i }));
66
+ }
67
+ if (flags.db)
68
+ cfg.dbAbsPath = resolve(cwd, flags.db);
69
+ return cfg;
70
+ }
71
+ function openStore(cfg) {
72
+ const store = new SqliteFtsStore(cfg.dbAbsPath);
73
+ store.init();
74
+ return store;
75
+ }
76
+ function runIndex(cfg, store, sources, force = false) {
77
+ let scanned = 0, changed = 0, deleted = 0, chunks = 0;
78
+ for (const s of sources) {
79
+ const st = indexSource(store, { root: s.id, dir: s.dir }, { force, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions });
80
+ scanned += st.scanned;
81
+ changed += st.changed;
82
+ deleted += st.deleted;
83
+ chunks += st.chunks;
84
+ }
85
+ return { scanned, changed, deleted, chunks };
86
+ }
87
+ /** Resolve sources for a run. --source overrides (filesystem, sync); otherwise
88
+ * resolve all configured specs (filesystem sync + remote async + TOFU trust). */
89
+ async function sourcesForRun(cfg, flags) {
90
+ const srcs = flags.source;
91
+ if (srcs?.length)
92
+ return srcs.map((s, i) => ({ id: s, dir: resolve(cfg.cwd, s), priority: srcs.length - i, identity: s }));
93
+ const interactive = process.stdin.isTTY ?? false;
94
+ return resolveAll(cfg.allSourceSpecs, {
95
+ cwd: cfg.cwd,
96
+ cacheDir: cfg.cacheDirAbs,
97
+ refresh: !!flags.refresh,
98
+ promptTrust: interactive ? defaultPromptTrust : undefined,
99
+ });
100
+ }
101
+ const HELP = `kb — markdown knowledge base
102
+ Usage:
103
+ kb init [--global] [--source <ref>]... [--dry-run] [--force] [--cwd <dir>]
104
+ kb index [--source <dir>...] [--db <path>] [--force] [--refresh]
105
+ kb search "<query>" [--limit N] [--root id] [--doc-type doc|agents|source-md]
106
+ [--expand-parent|--no-expand-parent] [--expand-graph] [--rerank]
107
+ [--expand-query] [--json] [--no-reindex] [--source <dir>...] [--db <path>]
108
+ kb neighbors "<node>" [--depth N] [--rel child_of|links_to|references|has_tag]
109
+ kb backlinks "<node>"
110
+ kb get <path> [--section "<heading_path>"]
111
+ kb agents <path> nearest AGENTS.md chain (root→nearest); --fallback-manifest
112
+ kb dox init [--dry-run] scaffold a DOX AGENTS.md tree (path rows only)
113
+ kb dox lint [--json] [--fix] audit DOX tree drift
114
+ kb eval --golden <file.json> [--limit N] [--doc-type ...] [--no-reindex]
115
+ kb config show resolved config
116
+ Global: --cwd <dir> --config <file>`;
117
+ function main() {
118
+ const flags = parse(process.argv.slice(2));
119
+ const cmd = flags._[0];
120
+ if (!cmd || cmd === "help" || flags.help) {
121
+ console.log(HELP);
122
+ return;
123
+ }
124
+ if (cmd === "config") {
125
+ const cfg = cfgFrom(flags);
126
+ console.log(JSON.stringify({ origin: cfg.origin, dbAbsPath: cfg.dbAbsPath, cacheDirAbs: cfg.cacheDirAbs, sources: cfg.resolvedSources, allSourceSpecs: cfg.allSourceSpecs, maxFileCount: cfg.maxFileCount, indexAgentsFiles: cfg.indexAgentsFiles }, null, 2));
127
+ return;
128
+ }
129
+ if (cmd === "init") {
130
+ const r = kbInit({
131
+ global: !!flags.global,
132
+ force: !!flags.force,
133
+ dryRun: !!flags["dry-run"],
134
+ sources: flags.source,
135
+ cwd: flags.cwd ?? process.cwd(),
136
+ });
137
+ if (!flags["dry-run"] && r.wrote) {
138
+ console.log(`wrote ${r.configPath}`);
139
+ if (r.gitignoreAdded)
140
+ console.log(`gitignored ${r.gitignoreAdded} in ${r.gitignorePath}`);
141
+ }
142
+ return;
143
+ }
144
+ if (cmd === "agents") {
145
+ const cwd = flags.cwd ?? process.cwd();
146
+ const { chain, manifest } = agentsChain(cwd, flags._[1] ?? cwd, { claudeMd: true, fallbackManifest: flags["no-fallback-manifest"] ? false : true });
147
+ if (flags.json)
148
+ console.log(JSON.stringify({ chain: chain.map((c) => c.rel), manifest }, null, 2));
149
+ else if (chain.length)
150
+ for (const c of chain)
151
+ console.log(c.rel);
152
+ else if (manifest)
153
+ console.log(manifest);
154
+ else
155
+ console.log("(no AGENTS.md on path and no manifest)");
156
+ return;
157
+ }
158
+ if (cmd === "dox") {
159
+ const sub = flags._[1];
160
+ const cwd = flags.cwd ?? process.cwd();
161
+ if (sub === "init") {
162
+ const plan = doxInit({ cwd, dryRun: !!flags["dry-run"] });
163
+ if (flags["dry-run"])
164
+ console.log(`# dry-run dox init\ncreate: ${plan.created.join(", ") || "(none)"}\nappend: ${plan.appended.map((a) => a.file + " +" + a.rows.length).join(", ") || "(none)"}`);
165
+ else
166
+ console.log(`created ${plan.created.length} AGENTS.md, appended rows to ${plan.appended.length} files`);
167
+ return;
168
+ }
169
+ if (sub === "lint") {
170
+ const r = doxLint({ cwd, json: !!flags.json, fix: !!flags.fix });
171
+ if (flags.json)
172
+ console.log(JSON.stringify(r, null, 2));
173
+ else
174
+ for (const i of r.issues)
175
+ console.log(`${i.kind}\t${i.agentsFile}${i.path ? "\t" + i.path : ""}\t${i.detail}`);
176
+ if (r.issues.length)
177
+ process.exit(1);
178
+ return;
179
+ }
180
+ console.error(`unknown dox subcommand: ${sub}`);
181
+ process.exit(2);
182
+ }
183
+ // index/search/neighbors/backlinks/get/eval need sources + store
184
+ void runCmd(cmd, flags).catch((e) => { console.error(String(e?.message ?? e)); process.exit(1); });
185
+ }
186
+ async function runCmd(cmd, flags) {
187
+ const cfg = cfgFrom(flags);
188
+ const isIndex = cmd === "index";
189
+ if (!cfg.allSourceSpecs.length && isIndex && !flags.source?.length) {
190
+ console.error("no sources configured. add sources[] to .pi/dashboard/knowledge_base.json or pass --source <dir>");
191
+ process.exit(2);
192
+ }
193
+ const sources = await sourcesForRun(cfg, flags);
194
+ if (!sources.length && isIndex) {
195
+ console.error("no sources resolved");
196
+ process.exit(2);
197
+ }
198
+ const store = openStore(cfg);
199
+ try {
200
+ if (cmd === "index") {
201
+ const t = performance.now();
202
+ const s = runIndex(cfg, store, sources, !!flags.force);
203
+ console.log(`indexed ${s.scanned} files (${s.changed} changed, ${s.deleted} deleted, ${s.chunks} chunks) in ${(performance.now() - t).toFixed(0)}ms`);
204
+ console.log(JSON.stringify(store.counts()));
205
+ }
206
+ else if (cmd === "search") {
207
+ const q = flags._[1];
208
+ if (!q) {
209
+ console.error("search needs a query");
210
+ process.exit(2);
211
+ }
212
+ const limit = posInt(flags.limit, "--limit");
213
+ const docType = enumFlag(flags["doc-type"], ["doc", "agents", "source-md"], "--doc-type");
214
+ if (!flags["no-reindex"])
215
+ runIndex(cfg, store, sources); // auto incremental freshness
216
+ const so = {
217
+ limit: limit ?? 10,
218
+ root: flags.root,
219
+ docType: docType,
220
+ fieldWeights: cfg.ranking.fieldWeights,
221
+ proximityBoost: cfg.ranking.proximityBoost,
222
+ diversity: cfg.ranking.diversity,
223
+ expandParent: flags["no-expand-parent"] ? false : (cfg.expand.parent || !!flags["expand-parent"]),
224
+ expandGraph: cfg.expand.graph || !!flags["expand-graph"],
225
+ rerank: cfg.rerank.enabled || !!flags.rerank,
226
+ queryExpansion: flags["expand-query"] ? (cfg.queryExpansion.mode === "off" ? "synonym" : cfg.queryExpansion.mode) : cfg.queryExpansion.mode,
227
+ rootPriority: Object.fromEntries(sources.map((s) => [s.id, s.priority])),
228
+ };
229
+ const hits = store.search(q, so);
230
+ if (flags.json)
231
+ console.log(JSON.stringify(hits, null, 2));
232
+ else
233
+ for (const h of hits)
234
+ console.log(`${h.score.toFixed(2)} ${h.path} :: ${h.headingPath}${h.akaPaths ? ` (+${h.akaPaths.length} dup)` : ""}${h.parent ? ` [parent: ${h.parent.headingPath}]` : ""}\n ${h.snippet.replace(/\s+/g, " ").slice(0, 160)}`);
235
+ }
236
+ else if (cmd === "neighbors") {
237
+ const depth = posInt(flags.depth, "--depth") ?? 2;
238
+ const rel = enumFlag(flags.rel, ["child_of", "links_to", "references", "has_tag"], "--rel");
239
+ const n = store.neighbors(flags._[1], depth, rel);
240
+ console.log(flags.json ? JSON.stringify(n, null, 2) : n.map((x) => `${x.type}\t${x.name}`).join("\n"));
241
+ }
242
+ else if (cmd === "backlinks") {
243
+ const n = store.backlinks(flags._[1]);
244
+ console.log(flags.json ? JSON.stringify(n, null, 2) : n.map((x) => `${x.type}\t${x.name}`).join("\n"));
245
+ }
246
+ else if (cmd === "get") {
247
+ // search every resolved root (not just the first) for the path
248
+ let c = null;
249
+ for (const s of sources) {
250
+ c = store.getChunk(s.id, flags._[1], flags.section);
251
+ if (c)
252
+ break;
253
+ }
254
+ console.log(c ? c.body : `(not found: ${flags._[1]})`);
255
+ }
256
+ else if (cmd === "eval") {
257
+ const gf = flags.golden;
258
+ if (!gf) {
259
+ console.error("eval needs --golden <file.json>");
260
+ process.exit(2);
261
+ }
262
+ if (!flags["no-reindex"])
263
+ runIndex(cfg, store, sources);
264
+ const golden = JSON.parse(readFileSync(resolve(cfg.cwd, gf), "utf8"));
265
+ const m = evaluate(store, golden, { k: flags.limit ? Number(flags.limit) : 10, docType: flags["doc-type"] });
266
+ console.log(JSON.stringify(m, null, flags.json ? 2 : 0));
267
+ }
268
+ else {
269
+ console.error(`unknown command: ${cmd}\n\n${HELP}`);
270
+ process.exit(2);
271
+ }
272
+ }
273
+ finally {
274
+ store.close();
275
+ }
276
+ }
277
+ main();
@@ -0,0 +1,104 @@
1
+ export interface SourceConfig {
2
+ kind?: "filesystem" | "npm" | "git" | "https";
3
+ ref: string;
4
+ priority?: number;
5
+ subdir?: string;
6
+ pin?: string;
7
+ refresh?: "on-index" | "manual" | {
8
+ ttlMs: number;
9
+ };
10
+ }
11
+ export interface RankingConfig {
12
+ fieldWeights: {
13
+ headingPath: number;
14
+ heading: number;
15
+ body: number;
16
+ };
17
+ proximityBoost: boolean;
18
+ diversity: {
19
+ enabled: boolean;
20
+ lambda: number;
21
+ };
22
+ }
23
+ export interface ExpandConfig {
24
+ parent: boolean;
25
+ graph: boolean;
26
+ }
27
+ export interface RerankConfig {
28
+ enabled: boolean;
29
+ model: string;
30
+ candidateK: number;
31
+ }
32
+ export interface QueryExpansionConfig {
33
+ mode: "off" | "prf" | "synonym" | "agent";
34
+ }
35
+ export interface DirectoryLevelAgentsConfig {
36
+ enabled: boolean;
37
+ claudeMd: boolean;
38
+ mode: "pull" | "push";
39
+ fallbackManifest: boolean;
40
+ }
41
+ export interface KbConfig {
42
+ sources: SourceConfig[];
43
+ roots?: Array<{
44
+ path: string;
45
+ priority?: number;
46
+ }>;
47
+ sourceCacheDir: string;
48
+ include: string[];
49
+ exclude: string[];
50
+ extensions: string[];
51
+ maxFileCount: number | null;
52
+ maxDepth: number | null;
53
+ respectGitignore: boolean;
54
+ tokenizer: string;
55
+ trigram: boolean;
56
+ indexAgentsFiles: boolean;
57
+ includeSourceMarkdown: boolean;
58
+ chunking: {
59
+ minHeadingsForStructural: number;
60
+ minChunkChars: number;
61
+ maxChunkChars: number;
62
+ breadcrumbInBody: boolean;
63
+ };
64
+ dedup: {
65
+ exactContentCollapse: boolean;
66
+ preferHigherPriorityRoot: boolean;
67
+ };
68
+ graph: {
69
+ wikilinks: boolean;
70
+ headingTree: boolean;
71
+ frontmatter: boolean;
72
+ };
73
+ directoryLevelAgents: DirectoryLevelAgentsConfig;
74
+ doxEnforcement: boolean;
75
+ ranking: RankingConfig;
76
+ expand: ExpandConfig;
77
+ rerank: RerankConfig;
78
+ queryExpansion: QueryExpansionConfig;
79
+ dbPath: string;
80
+ }
81
+ export interface ResolvedSource {
82
+ id: string;
83
+ dir: string;
84
+ priority: number;
85
+ }
86
+ export interface ResolvedConfig extends KbConfig {
87
+ cwd: string;
88
+ dbAbsPath: string;
89
+ cacheDirAbs: string;
90
+ allSourceSpecs: SourceConfig[];
91
+ resolvedSources: ResolvedSource[];
92
+ origin: "project" | "global" | "defaults";
93
+ }
94
+ export declare const DEFAULTS: KbConfig;
95
+ /** Layer configs left→right, deep-merging the known nested object keys. */
96
+ export declare function mergeConfig(...layers: Array<Partial<KbConfig> | null | undefined>): Partial<KbConfig>;
97
+ /** Validate a parsed config shape; throw with a precise message on violation. */
98
+ export declare function validateConfig(c: Partial<KbConfig>, origin?: string): KbConfig;
99
+ export declare function projectConfigPath(cwd: string): string;
100
+ export declare function globalConfigPath(): string;
101
+ /** Merge: defaults < global < project (field-level fill-in). */
102
+ export declare function loadConfig(cwd: string, opts?: {
103
+ configPath?: string;
104
+ }): ResolvedConfig;
package/dist/config.js ADDED
@@ -0,0 +1,110 @@
1
+ // Config layering (design §7): project `.pi/dashboard/knowledge_base.json`
2
+ // → global `~/.pi/dashboard/knowledge_base.json` → built-in defaults.
3
+ // Project file is used whole; absent fields fall back to global, then defaults.
4
+ // No file-count cap by default (requirement #1).
5
+ import { existsSync, readFileSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { isAbsolute, join, resolve } from "node:path";
8
+ function expandTilde(p) {
9
+ return p.startsWith("~/") ? join(homedir(), p.slice(2)) : p;
10
+ }
11
+ export const DEFAULTS = {
12
+ sources: [],
13
+ sourceCacheDir: "~/.pi/dashboard/kb/sources",
14
+ include: ["**/*.md"],
15
+ exclude: ["**/node_modules/**", "**/archive/**"],
16
+ extensions: [".md"],
17
+ maxFileCount: null, // no cap
18
+ maxDepth: null,
19
+ respectGitignore: true,
20
+ tokenizer: "porter unicode61",
21
+ trigram: false,
22
+ indexAgentsFiles: true,
23
+ includeSourceMarkdown: true,
24
+ chunking: { minHeadingsForStructural: 1, minChunkChars: 120, maxChunkChars: 4000, breadcrumbInBody: true },
25
+ dedup: { exactContentCollapse: true, preferHigherPriorityRoot: true },
26
+ graph: { wikilinks: true, headingTree: true, frontmatter: true },
27
+ directoryLevelAgents: { enabled: false, claudeMd: true, mode: "pull", fallbackManifest: true },
28
+ doxEnforcement: false,
29
+ ranking: { fieldWeights: { headingPath: 10, heading: 3, body: 1 }, proximityBoost: true, diversity: { enabled: true, lambda: 0.7 } },
30
+ expand: { parent: true, graph: false },
31
+ rerank: { enabled: false, model: "ms-marco-MiniLM-L-6-v2", candidateK: 50 },
32
+ queryExpansion: { mode: "off" },
33
+ dbPath: ".pi/dashboard/kb/index.db",
34
+ };
35
+ // Nested object keys that need one-level field fill-in (not wholesale replace),
36
+ // so a partial `{ranking:{proximityBoost:false}}` keeps default fieldWeights/diversity.
37
+ const NESTED_KEYS = ["chunking", "dedup", "graph", "directoryLevelAgents", "ranking", "expand", "rerank", "queryExpansion"];
38
+ /** Layer configs left→right, deep-merging the known nested object keys. */
39
+ export function mergeConfig(...layers) {
40
+ const out = {};
41
+ for (const layer of layers) {
42
+ if (!layer)
43
+ continue;
44
+ for (const [k, v] of Object.entries(layer)) {
45
+ if (NESTED_KEYS.includes(k) && v && typeof v === "object" && !Array.isArray(v) && out[k] && typeof out[k] === "object") {
46
+ out[k] = { ...out[k], ...v };
47
+ }
48
+ else {
49
+ out[k] = v;
50
+ }
51
+ }
52
+ }
53
+ return out;
54
+ }
55
+ /** Validate a parsed config shape; throw with a precise message on violation. */
56
+ export function validateConfig(c, origin = "config") {
57
+ const merged = mergeConfig(DEFAULTS, c);
58
+ const err = (msg) => new Error(`invalid KB ${origin}: ${msg}`);
59
+ if (!Array.isArray(merged.sources))
60
+ throw err("sources must be an array");
61
+ for (const s of merged.sources) {
62
+ if (typeof s !== "object" || s === null || typeof s.ref !== "string")
63
+ throw err("each source needs a string `ref`");
64
+ const k = s.kind ?? "filesystem";
65
+ if (!/^(filesystem|npm|git|https)$/.test(k))
66
+ throw err(`source kind "${k}" unknown`);
67
+ }
68
+ if (typeof merged.maxFileCount !== "number" && merged.maxFileCount !== null)
69
+ throw err("maxFileCount must be a number or null");
70
+ if (typeof merged.dbPath !== "string" || !merged.dbPath)
71
+ throw err("dbPath must be a non-empty string");
72
+ if (!/^(off|prf|synonym|agent)$/.test(merged.queryExpansion.mode))
73
+ throw err(`queryExpansion.mode "${merged.queryExpansion.mode}" unknown`);
74
+ return merged;
75
+ }
76
+ export function projectConfigPath(cwd) {
77
+ return join(cwd, ".pi", "dashboard", "knowledge_base.json");
78
+ }
79
+ export function globalConfigPath() {
80
+ return join(homedir(), ".pi", "dashboard", "knowledge_base.json");
81
+ }
82
+ function readJson(path) {
83
+ if (!existsSync(path))
84
+ return null;
85
+ try {
86
+ return JSON.parse(readFileSync(path, "utf8"));
87
+ }
88
+ catch (e) {
89
+ throw new Error(`invalid KB config at ${path}: ${e.message}`);
90
+ }
91
+ }
92
+ /** Merge: defaults < global < project (field-level fill-in). */
93
+ export function loadConfig(cwd, opts = {}) {
94
+ const project = opts.configPath ? readJson(opts.configPath) : readJson(projectConfigPath(cwd));
95
+ const global = readJson(globalConfigPath());
96
+ const origin = project ? "project" : global ? "global" : "defaults";
97
+ const merged = validateConfig(mergeConfig(DEFAULTS, global, project), origin);
98
+ // legacy roots[] → filesystem sources
99
+ const fromRoots = (merged.roots ?? []).map((r) => ({ kind: "filesystem", ref: r.path, priority: r.priority }));
100
+ const allSourceSpecs = [...fromRoots, ...merged.sources];
101
+ const resolvedSources = allSourceSpecs
102
+ .filter((s) => (s.kind ?? "filesystem") === "filesystem")
103
+ .map((s) => {
104
+ const base = isAbsolute(s.ref) ? s.ref : resolve(cwd, s.ref);
105
+ return { id: s.ref, dir: s.subdir ? join(base, s.subdir) : base, priority: s.priority ?? 0 };
106
+ });
107
+ const dbAbsPath = isAbsolute(merged.dbPath) ? merged.dbPath : resolve(cwd, merged.dbPath);
108
+ const cacheDirAbs = expandTilde(merged.sourceCacheDir);
109
+ return { ...merged, cwd, dbAbsPath, cacheDirAbs, allSourceSpecs, resolvedSources, origin };
110
+ }