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