@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/src/sources.ts
ADDED
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
// Pluggable source resolvers (design §6b). A `SourceResolver` turns any source
|
|
2
|
+
// spec into a local directory; the indexer always operates on local dirs.
|
|
3
|
+
// Filesystem = trivial; npm/git/https = network + cache + TOFU trust.
|
|
4
|
+
// KB only reads markdown; it never executes source code.
|
|
5
|
+
//
|
|
6
|
+
// Source classification mirrors `packages/server/src/package-source-helpers.ts`
|
|
7
|
+
// (`parseSourceKind`/`computeIdentity`) — reimplemented here to keep this
|
|
8
|
+
// publishable package self-contained (no kb→server dependency).
|
|
9
|
+
import { createHash } from "node:crypto";
|
|
10
|
+
import { execFileSync } from "node:child_process"; // ban:child_process-ok (kb package is self-contained; owns git clone/pull + tar/zip extract for remote resolvers, no pi-dashboard-shared dep)
|
|
11
|
+
import { existsSync, mkdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
12
|
+
import { homedir } from "node:os";
|
|
13
|
+
import { isAbsolute, join, resolve } from "node:path";
|
|
14
|
+
import type { SourceConfig } from "./config.js";
|
|
15
|
+
import { isTrusted, recordTrust } from "./trust.js";
|
|
16
|
+
|
|
17
|
+
export type KbSourceKind = "filesystem" | "npm" | "git" | "https";
|
|
18
|
+
|
|
19
|
+
export interface ResolvedSource {
|
|
20
|
+
id: string; // stored on chunks.root (the spec ref)
|
|
21
|
+
dir: string; // absolute local directory to index
|
|
22
|
+
priority: number;
|
|
23
|
+
identity: string; // dedup identity
|
|
24
|
+
revision?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface ResolveCtx {
|
|
28
|
+
cwd: string;
|
|
29
|
+
cacheDir: string; // absolute, for remote clones/fetches
|
|
30
|
+
refresh?: boolean; // --refresh: re-pull refreshable remote sources
|
|
31
|
+
promptTrust?: (s: SourceConfig) => Promise<boolean>;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface SourceResolver {
|
|
35
|
+
kind: KbSourceKind;
|
|
36
|
+
resolve(spec: SourceConfig, ctx: ResolveCtx): Promise<ResolvedSource>;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Classify a ref string (mirrors parseSourceKind). */
|
|
40
|
+
export function classifyRef(ref: string): KbSourceKind {
|
|
41
|
+
if (ref.startsWith("npm:")) return "npm";
|
|
42
|
+
if (ref.startsWith("git:") || ref.startsWith("git@")) return "git";
|
|
43
|
+
if (/^(https?|ssh):\/\//.test(ref)) return "https";
|
|
44
|
+
return "filesystem";
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Bare npm package name from a ref (`npm:@scope/pkg@1.2.3` → `@scope/pkg`). */
|
|
48
|
+
function npmBareName(ref: string): string {
|
|
49
|
+
const rest = ref.startsWith("npm:") ? ref.slice(4) : ref;
|
|
50
|
+
if (rest.startsWith("@")) {
|
|
51
|
+
const at = rest.indexOf("@", 1);
|
|
52
|
+
return at >= 0 ? rest.slice(0, at) : rest;
|
|
53
|
+
}
|
|
54
|
+
const at = rest.indexOf("@");
|
|
55
|
+
return at >= 0 ? rest.slice(0, at) : rest;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Dedup identity (mirrors computeIdentity). cwd resolves relative paths. */
|
|
59
|
+
export function sourceIdentity(spec: SourceConfig, cwd = "."): string {
|
|
60
|
+
const ref = spec.ref;
|
|
61
|
+
const k = spec.kind ?? classifyRef(ref);
|
|
62
|
+
if (k === "npm") return `npm:${npmBareName(ref)}`;
|
|
63
|
+
if (k === "git" || k === "https") {
|
|
64
|
+
const lastAt = ref.lastIndexOf("@");
|
|
65
|
+
if (lastAt > 0) {
|
|
66
|
+
const tail = ref.slice(lastAt + 1);
|
|
67
|
+
if (!tail.includes(":") && !tail.includes("/")) return ref.slice(0, lastAt);
|
|
68
|
+
}
|
|
69
|
+
return ref;
|
|
70
|
+
}
|
|
71
|
+
return isAbsolute(ref) ? ref : resolve(cwd, ref);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function shortHash(s: string): string {
|
|
75
|
+
return createHash("sha256").update(s).digest("hex").slice(0, 16);
|
|
76
|
+
}
|
|
77
|
+
function cacheKey(spec: SourceConfig): string {
|
|
78
|
+
return shortHash(`${spec.kind ?? classifyRef(spec.ref)}:${spec.ref}:${spec.pin ?? ""}`);
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async function ensureTrusted(spec: SourceConfig, ctx: ResolveCtx): Promise<void> {
|
|
82
|
+
if (isTrusted(spec)) return;
|
|
83
|
+
const prompt = ctx.promptTrust ?? (async () => false);
|
|
84
|
+
const ok = await prompt(spec);
|
|
85
|
+
if (!ok) throw new Error(`remote source ${spec.kind}:${spec.ref} not trusted — run interactively or pre-approve`);
|
|
86
|
+
recordTrust(spec);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function isStale(spec: SourceConfig, markerPath: string): boolean {
|
|
90
|
+
if (!existsSync(markerPath)) return true;
|
|
91
|
+
const ttlMs = typeof spec.refresh === "object" ? spec.refresh.ttlMs : undefined;
|
|
92
|
+
if (!ttlMs) return false;
|
|
93
|
+
return Date.now() - Number(statSync(markerPath).mtimeMs) > ttlMs;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// --- filesystem ---
|
|
97
|
+
|
|
98
|
+
export const filesystemResolver: SourceResolver = {
|
|
99
|
+
kind: "filesystem",
|
|
100
|
+
async resolve(spec, ctx) {
|
|
101
|
+
const base = isAbsolute(spec.ref) ? spec.ref : resolve(ctx.cwd, spec.ref);
|
|
102
|
+
const dir = spec.subdir ? join(base, spec.subdir) : base;
|
|
103
|
+
return { id: spec.ref, dir, priority: spec.priority ?? 0, identity: sourceIdentity(spec, ctx.cwd) };
|
|
104
|
+
},
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
// --- npm ---
|
|
108
|
+
|
|
109
|
+
export const npmResolver: SourceResolver = {
|
|
110
|
+
kind: "npm",
|
|
111
|
+
async resolve(spec, ctx) {
|
|
112
|
+
await ensureTrusted(spec, ctx);
|
|
113
|
+
const bare = npmBareName(spec.ref);
|
|
114
|
+
const candidates = [
|
|
115
|
+
join(homedir(), ".pi", "agent", "npm", "node_modules", bare),
|
|
116
|
+
join(ctx.cwd, ".pi", "npm", "node_modules", bare),
|
|
117
|
+
join(ctx.cwd, "node_modules", bare),
|
|
118
|
+
];
|
|
119
|
+
const pkgDir = candidates.find((p) => existsSync(p));
|
|
120
|
+
if (!pkgDir) throw new Error(`npm source ${spec.ref} not found (looked in ${candidates.join(", ")}). Install it first.`);
|
|
121
|
+
const dir = spec.subdir ? join(pkgDir, spec.subdir) : pkgDir;
|
|
122
|
+
return { id: spec.ref, dir, priority: spec.priority ?? 0, identity: sourceIdentity(spec, ctx.cwd) };
|
|
123
|
+
},
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
// --- git ---
|
|
127
|
+
|
|
128
|
+
function gitUrlOf(spec: SourceConfig): string {
|
|
129
|
+
const ref = spec.ref.startsWith("git:") ? spec.ref.slice(4) : spec.ref;
|
|
130
|
+
if (ref.startsWith("git@")) return ref;
|
|
131
|
+
if (/^github\.com\//.test(ref)) return `https://${ref}`;
|
|
132
|
+
if (!/^[a-z]+:\/\//.test(ref)) return `https://${ref}`;
|
|
133
|
+
return ref;
|
|
134
|
+
}
|
|
135
|
+
function gitRefOf(spec: SourceConfig): string | undefined {
|
|
136
|
+
if (spec.pin) return spec.pin;
|
|
137
|
+
const ref = spec.ref;
|
|
138
|
+
if (!ref.startsWith("git@")) {
|
|
139
|
+
const lastAt = ref.lastIndexOf("@");
|
|
140
|
+
if (lastAt > 0) {
|
|
141
|
+
const tail = ref.slice(lastAt + 1);
|
|
142
|
+
if (!tail.includes(":") && !tail.includes("/")) return tail;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return undefined;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export const gitResolver: SourceResolver = {
|
|
149
|
+
kind: "git",
|
|
150
|
+
async resolve(spec, ctx) {
|
|
151
|
+
await ensureTrusted(spec, ctx);
|
|
152
|
+
const cloneDir = join(ctx.cacheDir, cacheKey(spec));
|
|
153
|
+
const url = gitUrlOf(spec);
|
|
154
|
+
const ref = gitRefOf(spec);
|
|
155
|
+
const hasGit = existsSync(join(cloneDir, ".git"));
|
|
156
|
+
const shouldPull = ctx.refresh || spec.refresh === "on-index" || (!hasGit);
|
|
157
|
+
// execFileSync (argv array, no shell) — never interpolate url/ref/pin into a
|
|
158
|
+
// shell string (command-injection-safe even with hostile refs).
|
|
159
|
+
const git = (args: string[]) => execFileSync("git", args, { stdio: "pipe" });
|
|
160
|
+
if (!hasGit) {
|
|
161
|
+
mkdirSync(ctx.cacheDir, { recursive: true });
|
|
162
|
+
git(["clone", "--depth", "1", ...(ref ? ["--branch", ref] : []), "--", url, cloneDir]);
|
|
163
|
+
} else if (shouldPull) {
|
|
164
|
+
if (ref) { git(["-C", cloneDir, "fetch", "--depth", "1", "origin", ref]); git(["-C", cloneDir, "checkout", ref]); }
|
|
165
|
+
else git(["-C", cloneDir, "pull", "--ff-only"]);
|
|
166
|
+
}
|
|
167
|
+
const rev = execFileSync("git", ["-C", cloneDir, "rev-parse", "--short", "HEAD"], { encoding: "utf8" }).trim();
|
|
168
|
+
const dir = spec.subdir ? join(cloneDir, spec.subdir) : cloneDir;
|
|
169
|
+
return { id: spec.ref, dir, priority: spec.priority ?? 0, identity: sourceIdentity(spec, ctx.cwd), revision: rev };
|
|
170
|
+
},
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
// --- https ---
|
|
174
|
+
|
|
175
|
+
export const httpsResolver: SourceResolver = {
|
|
176
|
+
kind: "https",
|
|
177
|
+
async resolve(spec, ctx) {
|
|
178
|
+
await ensureTrusted(spec, ctx);
|
|
179
|
+
const dest = join(ctx.cacheDir, cacheKey(spec));
|
|
180
|
+
const url = spec.ref;
|
|
181
|
+
const marker = join(dest, ".fetched");
|
|
182
|
+
const isArchive = /\.(tar\.gz|tgz|tar\.bz2|zip)$/.test(url);
|
|
183
|
+
const shouldFetch = ctx.refresh || spec.refresh === "on-index" || isStale(spec, marker);
|
|
184
|
+
if (shouldFetch) {
|
|
185
|
+
if (existsSync(dest)) rmSync(dest, { recursive: true, force: true });
|
|
186
|
+
mkdirSync(dest, { recursive: true });
|
|
187
|
+
if (isArchive) {
|
|
188
|
+
const buf = Buffer.from(await (await fetch(url)).arrayBuffer());
|
|
189
|
+
const archivePath = join(dest, "archive" + (url.endsWith(".zip") ? ".zip" : ".tar.gz"));
|
|
190
|
+
writeFileSync(archivePath, buf);
|
|
191
|
+
if (url.endsWith(".zip")) execFileSync("unzip", ["-o", archivePath, "-d", dest], { stdio: "pipe" });
|
|
192
|
+
else execFileSync("tar", ["xzf", archivePath, "-C", dest], { stdio: "pipe" });
|
|
193
|
+
} else {
|
|
194
|
+
const text = await (await fetch(url)).text();
|
|
195
|
+
writeFileSync(join(dest, url.split("/").pop() || "index.md"), text);
|
|
196
|
+
}
|
|
197
|
+
writeFileSync(marker, String(Date.now()));
|
|
198
|
+
}
|
|
199
|
+
return { id: spec.ref, dir: dest, priority: spec.priority ?? 0, identity: sourceIdentity(spec, ctx.cwd) };
|
|
200
|
+
},
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
const RESOLVERS: Record<KbSourceKind, SourceResolver> = {
|
|
204
|
+
filesystem: filesystemResolver,
|
|
205
|
+
npm: npmResolver,
|
|
206
|
+
git: gitResolver,
|
|
207
|
+
https: httpsResolver,
|
|
208
|
+
};
|
|
209
|
+
|
|
210
|
+
export function resolverFor(kind: KbSourceKind): SourceResolver {
|
|
211
|
+
return RESOLVERS[kind];
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Resolve all configured sources to local dirs. Filesystem sources are sync
|
|
215
|
+
* and need no trust; remote sources prompt TOFU and may hit the network. */
|
|
216
|
+
export async function resolveAll(specs: SourceConfig[], ctx: ResolveCtx): Promise<ResolvedSource[]> {
|
|
217
|
+
const out: ResolvedSource[] = [];
|
|
218
|
+
for (const spec of specs) {
|
|
219
|
+
const kind = (spec.kind ?? classifyRef(spec.ref)) as KbSourceKind;
|
|
220
|
+
out.push(await resolverFor(kind).resolve(spec, ctx));
|
|
221
|
+
}
|
|
222
|
+
return out;
|
|
223
|
+
}
|
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
// Default KbStore backend over node:sqlite (Node built-in; FTS5 verified).
|
|
2
|
+
// Zero runtime deps. Requires --experimental-sqlite on current Node.
|
|
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";
|
|
6
|
+
import { dirname } from "node:path";
|
|
7
|
+
import type { Chunk, FileState, GraphEdge, GraphNode, KbHit, KbStore, SearchOpts } from "./types.js";
|
|
8
|
+
|
|
9
|
+
const DDL = `
|
|
10
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS chunks USING fts5(
|
|
11
|
+
root UNINDEXED, path UNINDEXED, chunk_id UNINDEXED, doc_type UNINDEXED,
|
|
12
|
+
parent_chunk_id UNINDEXED, level UNINDEXED, body_hash UNINDEXED,
|
|
13
|
+
heading_path, heading, body,
|
|
14
|
+
tokenize='porter unicode61'
|
|
15
|
+
);
|
|
16
|
+
CREATE TABLE IF NOT EXISTS files (
|
|
17
|
+
root TEXT, path TEXT, mtime_ms REAL, sha256 TEXT,
|
|
18
|
+
PRIMARY KEY (root, path)
|
|
19
|
+
);
|
|
20
|
+
CREATE TABLE IF NOT EXISTS nodes (
|
|
21
|
+
id INTEGER PRIMARY KEY, type TEXT, name TEXT, path TEXT,
|
|
22
|
+
UNIQUE(type, name)
|
|
23
|
+
);
|
|
24
|
+
CREATE TABLE IF NOT EXISTS edges (
|
|
25
|
+
src INTEGER, dst INTEGER, rel TEXT, weight REAL DEFAULT 1,
|
|
26
|
+
PRIMARY KEY (src, dst, rel)
|
|
27
|
+
);
|
|
28
|
+
CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src);
|
|
29
|
+
CREATE INDEX IF NOT EXISTS idx_edges_dst ON edges(dst);
|
|
30
|
+
`;
|
|
31
|
+
|
|
32
|
+
// FTS5 query builder: OR the alphanumeric terms (recall + BM25 ranks).
|
|
33
|
+
function toMatch(q: string): string {
|
|
34
|
+
const terms = tokenize(q);
|
|
35
|
+
const kept = terms.length ? terms : (q.toLowerCase().match(/[a-z0-9]{2,}/g) ?? []);
|
|
36
|
+
return kept.map((t) => `"${t}"`).join(" OR ");
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export class SqliteFtsStore implements KbStore {
|
|
40
|
+
private db: DatabaseSync;
|
|
41
|
+
constructor(dbPath: string) {
|
|
42
|
+
if (dbPath !== ":memory:") mkdirSync(dirname(dbPath), { recursive: true });
|
|
43
|
+
this.db = new DatabaseSync(dbPath);
|
|
44
|
+
this.db.exec("PRAGMA journal_mode=WAL");
|
|
45
|
+
}
|
|
46
|
+
init() {
|
|
47
|
+
this.db.exec(DDL);
|
|
48
|
+
}
|
|
49
|
+
begin() {
|
|
50
|
+
this.db.exec("BEGIN");
|
|
51
|
+
}
|
|
52
|
+
commit() {
|
|
53
|
+
this.db.exec("COMMIT");
|
|
54
|
+
}
|
|
55
|
+
rollback() {
|
|
56
|
+
try {
|
|
57
|
+
this.db.exec("ROLLBACK");
|
|
58
|
+
} catch {}
|
|
59
|
+
}
|
|
60
|
+
close() {
|
|
61
|
+
this.db.close();
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
getFileState(root: string, path: string): FileState | null {
|
|
65
|
+
const r = this.db.prepare("SELECT mtime_ms, sha256 FROM files WHERE root=? AND path=?").get(root, path) as any;
|
|
66
|
+
return r ? { mtimeMs: r.mtime_ms, sha256: r.sha256 } : null;
|
|
67
|
+
}
|
|
68
|
+
setFileState(root: string, path: string, s: FileState) {
|
|
69
|
+
this.db.prepare("INSERT INTO files(root,path,mtime_ms,sha256) VALUES(?,?,?,?) ON CONFLICT(root,path) DO UPDATE SET mtime_ms=excluded.mtime_ms, sha256=excluded.sha256").run(root, path, s.mtimeMs, s.sha256);
|
|
70
|
+
}
|
|
71
|
+
listPaths(root: string): string[] {
|
|
72
|
+
return (this.db.prepare("SELECT path FROM files WHERE root=?").all(root) as any[]).map((r) => r.path);
|
|
73
|
+
}
|
|
74
|
+
deleteByPath(root: string, path: string) {
|
|
75
|
+
this.db.prepare("DELETE FROM chunks WHERE root=? AND path=?").run(root, path);
|
|
76
|
+
// outbound edges originate from this file's nodes; prune nodes owned by path then dangling edges
|
|
77
|
+
const owned = this.db.prepare("SELECT id FROM nodes WHERE path=?").all(path) as any[];
|
|
78
|
+
for (const n of owned) this.db.prepare("DELETE FROM edges WHERE src=? OR dst=?").run(n.id, n.id);
|
|
79
|
+
this.db.prepare("DELETE FROM nodes WHERE path=?").run(path);
|
|
80
|
+
this.db.prepare("DELETE FROM files WHERE root=? AND path=?").run(root, path);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
insertChunk(c: Chunk) {
|
|
84
|
+
this.db
|
|
85
|
+
.prepare("INSERT INTO chunks(root,path,chunk_id,doc_type,parent_chunk_id,level,body_hash,heading_path,heading,body) VALUES(?,?,?,?,?,?,?,?,?,?)")
|
|
86
|
+
.run(c.root, c.path, c.chunkId, c.docType, c.parentChunkId, c.level, c.bodyHash, c.headingPath, c.heading, c.body);
|
|
87
|
+
}
|
|
88
|
+
addNode(n: GraphNode) {
|
|
89
|
+
this.db.prepare("INSERT INTO nodes(type,name,path) VALUES(?,?,?) ON CONFLICT(type,name) DO UPDATE SET path=COALESCE(excluded.path, nodes.path)").run(n.type, n.name, n.path);
|
|
90
|
+
}
|
|
91
|
+
addEdge(e: GraphEdge) {
|
|
92
|
+
const src = this.db.prepare("SELECT id FROM nodes WHERE name=? LIMIT 1").get(e.src) as any;
|
|
93
|
+
const dst = this.db.prepare("SELECT id FROM nodes WHERE name=? LIMIT 1").get(e.dst) as any;
|
|
94
|
+
if (!src || !dst) return;
|
|
95
|
+
this.db.prepare("INSERT OR IGNORE INTO edges(src,dst,rel,weight) VALUES(?,?,?,?)").run(src.id, dst.id, e.rel, e.weight ?? 1);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
search(query: string, opts: SearchOpts = {}): KbHit[] {
|
|
99
|
+
const expanded = expandQuery(query, opts);
|
|
100
|
+
const m = toMatch(expanded);
|
|
101
|
+
if (!m) return [];
|
|
102
|
+
// Coerce numerics that get interpolated into SQL (bm25 weights, LIMIT) to
|
|
103
|
+
// finite, bounded numbers — never trust raw config/flag values in a SQL string.
|
|
104
|
+
const num = (v: unknown, dflt: number, min: number, max: number): number => {
|
|
105
|
+
const n = Number(v);
|
|
106
|
+
return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : dflt;
|
|
107
|
+
};
|
|
108
|
+
const fw = opts.fieldWeights;
|
|
109
|
+
const w = {
|
|
110
|
+
headingPath: num(fw?.headingPath, 8, 0, 1000),
|
|
111
|
+
heading: num(fw?.heading, 4, 0, 1000),
|
|
112
|
+
body: num(fw?.body, 1, 0, 1000),
|
|
113
|
+
};
|
|
114
|
+
const limit = num(opts.limit, 10, 1, 1000);
|
|
115
|
+
const wantDedup = opts.dedup !== false;
|
|
116
|
+
const fetch = Math.min(4000, wantDedup ? limit * 4 : limit);
|
|
117
|
+
const where: string[] = ["chunks MATCH ?"];
|
|
118
|
+
const args: any[] = [m];
|
|
119
|
+
if (opts.root) { where.push("root = ?"); args.push(opts.root); }
|
|
120
|
+
if (opts.docType) { where.push("doc_type = ?"); args.push(opts.docType); }
|
|
121
|
+
const sql = `SELECT root, path, chunk_id chunkId, doc_type docType, body_hash bodyHash,
|
|
122
|
+
parent_chunk_id parentChunkId, heading_path headingPath, heading, body,
|
|
123
|
+
bm25(chunks, 0,0,0,0,0,0,0, ${w.headingPath}, ${w.heading}, ${w.body}) score,
|
|
124
|
+
snippet(chunks, 9, '[', ']', ' … ', 12) snippet
|
|
125
|
+
FROM chunks WHERE ${where.join(" AND ")} ORDER BY score LIMIT ${fetch}`;
|
|
126
|
+
const rows = this.db.prepare(sql).all(...args) as any[];
|
|
127
|
+
|
|
128
|
+
// bodies for proximity + MMR (dropped before returning)
|
|
129
|
+
const bodies = new Map<string, string>();
|
|
130
|
+
const qterms = tokenize(query);
|
|
131
|
+
let hits: KbHit[] = rows.map((r) => {
|
|
132
|
+
bodies.set(r.chunkId, r.body);
|
|
133
|
+
let score = r.score;
|
|
134
|
+
if (opts.proximityBoost) score += proximityDelta(qterms, r.body);
|
|
135
|
+
return { root: r.root, path: r.path, headingPath: r.headingPath, chunkId: r.chunkId, docType: r.docType, score, snippet: r.snippet, parentChunkId: r.parentChunkId } as KbHit & { parentChunkId: string | null };
|
|
136
|
+
});
|
|
137
|
+
|
|
138
|
+
if (wantDedup) {
|
|
139
|
+
// exact-content collapse; prefer higher-priority root, then best score
|
|
140
|
+
const prio = opts.rootPriority ?? {};
|
|
141
|
+
const groups = new Map<string, KbHit[]>();
|
|
142
|
+
for (const h of hits) {
|
|
143
|
+
const key = (rows.find((r) => r.chunkId === h.chunkId) as any).bodyHash;
|
|
144
|
+
(groups.get(key) ?? groups.set(key, []).get(key)!).push(h);
|
|
145
|
+
}
|
|
146
|
+
hits = [];
|
|
147
|
+
for (const g of groups.values()) {
|
|
148
|
+
g.sort((a, b) => (prio[b.root] ?? 0) - (prio[a.root] ?? 0) || a.score - b.score);
|
|
149
|
+
const head = g[0];
|
|
150
|
+
if (g.length > 1) head.akaPaths = g.slice(1).map((x) => x.path);
|
|
151
|
+
hits.push(head);
|
|
152
|
+
}
|
|
153
|
+
hits.sort((a, b) => a.score - b.score);
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// lexical MMR diversity (Tier A)
|
|
157
|
+
const div = opts.diversity;
|
|
158
|
+
if (div?.enabled) hits = mmr(hits, bodies, div.lambda, fetch);
|
|
159
|
+
hits = hits.slice(0, limit);
|
|
160
|
+
|
|
161
|
+
// optional cross-encoder rerank (Tier C): no-op without an injected reranker
|
|
162
|
+
if (opts.rerank) {
|
|
163
|
+
const rer = opts.reranker;
|
|
164
|
+
if (rer) {
|
|
165
|
+
const reranked = rer(query, hits);
|
|
166
|
+
// search() is sync; only a sync reranker can reorder here. An async
|
|
167
|
+
// reranker (Promise) is ignored — keep BM25 order rather than wipe hits.
|
|
168
|
+
if (!(reranked instanceof Promise)) hits = reranked;
|
|
169
|
+
}
|
|
170
|
+
// no reranker present → clean no-op, BM25 order preserved
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// parent small-to-big (Tier B, on by default)
|
|
174
|
+
if (opts.expandParent) {
|
|
175
|
+
for (const h of hits) {
|
|
176
|
+
const pc = (h as any).parentChunkId as string | null;
|
|
177
|
+
if (!pc) continue;
|
|
178
|
+
const parent = this.getChunkById(h.root, pc);
|
|
179
|
+
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 };
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
// drop internal parentChunkId from hits
|
|
185
|
+
return hits.map(({ ...h }) => { delete (h as any).parentChunkId; return h; });
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
neighbors(node: string, depth: number, rel?: GraphEdge["rel"]): GraphNode[] {
|
|
189
|
+
const relClause = rel ? "AND e.rel = :rel" : "";
|
|
190
|
+
const sql = `
|
|
191
|
+
WITH RECURSIVE reach(id, d) AS (
|
|
192
|
+
SELECT id, 0 FROM nodes WHERE name = :name
|
|
193
|
+
UNION
|
|
194
|
+
SELECT e.dst, r.d+1 FROM edges e JOIN reach r ON e.src = r.id
|
|
195
|
+
WHERE r.d < :depth ${relClause}
|
|
196
|
+
)
|
|
197
|
+
SELECT DISTINCT n.type, n.name, n.path FROM reach JOIN nodes n USING(id) WHERE n.name != :name`;
|
|
198
|
+
const params: any = { name: node, depth };
|
|
199
|
+
if (rel) params.rel = rel;
|
|
200
|
+
return (this.db.prepare(sql).all(params) as any[]).map((r) => ({ type: r.type, name: r.name, path: r.path }));
|
|
201
|
+
}
|
|
202
|
+
backlinks(node: string): GraphNode[] {
|
|
203
|
+
const sql = `SELECT DISTINCT n.type, n.name, n.path FROM edges e
|
|
204
|
+
JOIN nodes t ON e.dst = t.id JOIN nodes n ON e.src = n.id WHERE t.name = ?`;
|
|
205
|
+
return (this.db.prepare(sql).all(node) as any[]).map((r) => ({ type: r.type, name: r.name, path: r.path }));
|
|
206
|
+
}
|
|
207
|
+
getChunk(root: string, path: string, headingPath?: string): Chunk | null {
|
|
208
|
+
const sql = headingPath
|
|
209
|
+
? "SELECT * FROM chunks WHERE root=? AND path=? AND heading_path=? LIMIT 1"
|
|
210
|
+
: "SELECT * FROM chunks WHERE root=? AND path=? ORDER BY rowid LIMIT 1";
|
|
211
|
+
const r = (headingPath ? this.db.prepare(sql).get(root, path, headingPath) : this.db.prepare(sql).get(root, path)) as any;
|
|
212
|
+
return r ? rowToChunk(r) : null;
|
|
213
|
+
}
|
|
214
|
+
getChunkById(root: string, chunkId: string): Chunk | null {
|
|
215
|
+
const r = this.db.prepare("SELECT * FROM chunks WHERE root=? AND chunk_id=? LIMIT 1").get(root, chunkId) as any;
|
|
216
|
+
return r ? rowToChunk(r) : null;
|
|
217
|
+
}
|
|
218
|
+
counts() {
|
|
219
|
+
const c = (q: string) => (this.db.prepare(q).get() as any).n as number;
|
|
220
|
+
return {
|
|
221
|
+
files: c("SELECT COUNT(*) n FROM files"),
|
|
222
|
+
chunks: c("SELECT COUNT(*) n FROM chunks"),
|
|
223
|
+
nodes: c("SELECT COUNT(*) n FROM nodes"),
|
|
224
|
+
edges: c("SELECT COUNT(*) n FROM edges"),
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const STOP = new Set("the for and how what with you your does can from that this are into use using get set all a an of to in on is be as it or by at do".split(" "));
|
|
230
|
+
function tokenize(s: string): string[] {
|
|
231
|
+
return (s.toLowerCase().match(/[a-z0-9]{2,}/g) ?? []).filter((t) => !STOP.has(t));
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function rowToChunk(r: any): Chunk {
|
|
235
|
+
return { root: r.root, path: r.path, chunkId: r.chunk_id, headingPath: r.heading_path, heading: r.heading, level: r.level, parentChunkId: r.parent_chunk_id, docType: r.doc_type, body: r.body, bodyHash: r.body_hash };
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Query expansion (Tier C, default off). synonym = curated glossary;
|
|
239
|
+
* agent = pass-through (caller reformulates); prf = lightweight lexical RM3.
|
|
240
|
+
* No model dependency. */
|
|
241
|
+
function expandQuery(query: string, opts: SearchOpts): string {
|
|
242
|
+
const mode = opts.queryExpansion ?? "off";
|
|
243
|
+
if (mode === "off" || mode === "agent") return query; // agent: caller already reformulated
|
|
244
|
+
const terms = tokenize(query);
|
|
245
|
+
if (mode === "synonym" && opts.synonyms) {
|
|
246
|
+
const extra: string[] = [];
|
|
247
|
+
for (const t of terms) for (const syn of opts.synonyms[t] ?? []) extra.push(syn);
|
|
248
|
+
return extra.length ? query + " " + extra.join(" ") : query;
|
|
249
|
+
}
|
|
250
|
+
return query; // prf handled by callers via a second pass; engine no-ops here
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/** Proximity/in-order boost: reward hits whose query terms appear close and in
|
|
254
|
+
* query order in the body. Returns a delta to ADD to the bm25 score (negative
|
|
255
|
+
* = better). bm25 is asc (lower=better), so a good proximity lowers the score. */
|
|
256
|
+
function proximityDelta(queryTerms: string[], body: string): number {
|
|
257
|
+
if (queryTerms.length < 2) return 0;
|
|
258
|
+
const tokens = body.toLowerCase().match(/[a-z0-9]{2,}/g) ?? [];
|
|
259
|
+
const pos: Record<string, number[]> = Object.create(null);
|
|
260
|
+
tokens.forEach((t, i) => { (pos[t] ??= []).push(i); });
|
|
261
|
+
// smallest window containing all query terms in order
|
|
262
|
+
let best = Infinity;
|
|
263
|
+
const qt = queryTerms;
|
|
264
|
+
const walk = (idx: number, start: number, span: number): void => {
|
|
265
|
+
if (idx === qt.length) { best = Math.min(best, span); return; }
|
|
266
|
+
const arr = pos[qt[idx]];
|
|
267
|
+
if (!arr) return;
|
|
268
|
+
for (const p of arr) {
|
|
269
|
+
if (p < start) continue;
|
|
270
|
+
walk(idx + 1, p, idx === 0 ? 0 : span + (p - start));
|
|
271
|
+
if (best === 1) return;
|
|
272
|
+
}
|
|
273
|
+
};
|
|
274
|
+
walk(0, -1, 0);
|
|
275
|
+
if (!isFinite(best)) return 0;
|
|
276
|
+
// window 1..~40 → delta 0..-2 (closer = bigger boost)
|
|
277
|
+
return -Math.max(0, 2 - best / 20);
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/** Lexical MMR diversification over an already-ranked list. */
|
|
281
|
+
function mmr(ranked: KbHit[], bodies: Map<string, string>, lambda: number, limit: number): KbHit[] {
|
|
282
|
+
if (ranked.length <= limit) return ranked;
|
|
283
|
+
const tok = (h: KbHit) => new Set(tokenize(bodies.get(h.chunkId) ?? h.headingPath));
|
|
284
|
+
const sets = new Map<string, Set<string>>();
|
|
285
|
+
ranked.forEach((h) => sets.set(h.chunkId, tok(h)));
|
|
286
|
+
const jaccard = (a: Set<string>, b: Set<string>) => {
|
|
287
|
+
let inter = 0;
|
|
288
|
+
for (const t of a) if (b.has(t)) inter++;
|
|
289
|
+
const uni = a.size + b.size - inter;
|
|
290
|
+
return uni ? inter / uni : 0;
|
|
291
|
+
};
|
|
292
|
+
const out: KbHit[] = [ranked[0]];
|
|
293
|
+
const remaining = ranked.slice(1);
|
|
294
|
+
while (out.length < limit && remaining.length) {
|
|
295
|
+
let bestI = 0;
|
|
296
|
+
let bestScore = -Infinity;
|
|
297
|
+
for (let i = 0; i < remaining.length; i++) {
|
|
298
|
+
const h = remaining[i];
|
|
299
|
+
const rel = -h.score; // higher bm25-relevance = better
|
|
300
|
+
let maxSim = 0;
|
|
301
|
+
for (const o of out) maxSim = Math.max(maxSim, jaccard(sets.get(h.chunkId)!, sets.get(o.chunkId)!));
|
|
302
|
+
const score = lambda * rel - (1 - lambda) * maxSim;
|
|
303
|
+
if (score > bestScore) { bestScore = score; bestI = i; }
|
|
304
|
+
}
|
|
305
|
+
out.push(remaining.splice(bestI, 1)[0]);
|
|
306
|
+
}
|
|
307
|
+
return out;
|
|
308
|
+
}
|
package/src/trust.ts
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// TOFU trust store for remote KB sources (design §6b, mirrors
|
|
2
|
+
// `packages/server/src/worktree-init-trust.ts`). Filesystem sources skip trust;
|
|
3
|
+
// npm/git/https require confirmation on first fetch. Keyed by
|
|
4
|
+
// `sha256(canonical(SourceSpec))` so editing the spec re-prompts.
|
|
5
|
+
// Persisted at `~/.pi/dashboard/kb-source-trust.json`.
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
8
|
+
import { dirname, join } from "node:path";
|
|
9
|
+
import { homedir } from "node:os";
|
|
10
|
+
import type { SourceConfig } from "./config.js";
|
|
11
|
+
|
|
12
|
+
function storePath(): string {
|
|
13
|
+
return process.env.KB_SOURCE_TRUST_PATH ?? join(homedir(), ".pi", "dashboard", "kb-source-trust.json");
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** Canonical string for a source spec → stable hash key. */
|
|
17
|
+
export function canonicalSource(s: SourceConfig): string {
|
|
18
|
+
const k = s.kind ?? "filesystem";
|
|
19
|
+
return `${k}\u0000${s.ref}\u0000${s.subdir ?? ""}\u0000${s.pin ?? ""}`;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function sourceHash(s: SourceConfig): string {
|
|
23
|
+
return createHash("sha256").update(canonicalSource(s)).digest("hex");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
type TrustMap = Record<string, true>;
|
|
27
|
+
|
|
28
|
+
function load(): TrustMap {
|
|
29
|
+
try {
|
|
30
|
+
const raw = readFileSync(storePath(), "utf8");
|
|
31
|
+
const parsed = JSON.parse(raw);
|
|
32
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) return parsed as TrustMap;
|
|
33
|
+
} catch { /* missing/malformed → empty */ }
|
|
34
|
+
return {};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function save(map: TrustMap): void {
|
|
38
|
+
const p = storePath();
|
|
39
|
+
try {
|
|
40
|
+
mkdirSync(dirname(p), { recursive: true });
|
|
41
|
+
writeFileSync(p, JSON.stringify(map, null, 2), "utf8");
|
|
42
|
+
} catch (err) {
|
|
43
|
+
console.warn(`[kb-source-trust] failed to persist: ${(err as Error)?.message}`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function isTrusted(s: SourceConfig): boolean {
|
|
48
|
+
return load()[sourceHash(s)] === true;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function recordTrust(s: SourceConfig): void {
|
|
52
|
+
const map = load();
|
|
53
|
+
map[sourceHash(s)] = true;
|
|
54
|
+
save(map);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** Default CLI prompt: reads y/N from stdin. Returns true only on explicit yes. */
|
|
58
|
+
export async function defaultPromptTrust(s: SourceConfig): Promise<boolean> {
|
|
59
|
+
const { createInterface } = await import("node:readline");
|
|
60
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
61
|
+
return new Promise((resolve) => {
|
|
62
|
+
rl.question(`KB wants to fetch remote source ${s.kind}:${s.ref}${s.pin ? `@${s.pin}` : ""}. Allow? [y/N] `, (ans) => {
|
|
63
|
+
rl.close();
|
|
64
|
+
resolve(/^y/i.test(ans.trim()));
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
}
|