@blackbelt-technology/pi-dashboard-kb 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -0
- package/bin/kb.mjs +84 -0
- package/bin/lib/engine-fingerprint.mjs +183 -0
- package/dist/adoc-chunker.d.ts +29 -0
- package/dist/adoc-chunker.js +274 -0
- package/dist/archive-guard.d.ts +12 -0
- package/dist/archive-guard.js +154 -0
- package/dist/chunker.d.ts +3 -0
- package/dist/chunker.js +5 -3
- package/dist/cli.js +137 -19
- package/dist/config.d.ts +49 -0
- package/dist/config.js +43 -6
- package/dist/dox-triage.d.ts +67 -0
- package/dist/dox-triage.js +183 -0
- package/dist/dox.d.ts +68 -7
- package/dist/dox.js +370 -94
- package/dist/eval.d.ts +30 -0
- package/dist/eval.js +120 -13
- package/dist/gitignore.d.ts +24 -0
- package/dist/gitignore.js +205 -0
- package/dist/index.d.ts +25 -17
- package/dist/index.js +17 -8
- package/dist/indexer.d.ts +9 -1
- package/dist/indexer.js +40 -11
- package/dist/net-guard.d.ts +35 -0
- package/dist/net-guard.js +285 -0
- package/dist/render.js +37 -2
- package/dist/search-opts.d.ts +22 -0
- package/dist/search-opts.js +21 -0
- package/dist/sources.d.ts +29 -0
- package/dist/sources.js +230 -32
- package/dist/sqlite-store.d.ts +72 -2
- package/dist/sqlite-store.js +482 -78
- package/dist/staleness.d.ts +25 -0
- package/dist/staleness.js +69 -0
- package/dist/trust.d.ts +33 -1
- package/dist/trust.js +72 -5
- package/dist/types.d.ts +59 -0
- package/dist/verdict.d.ts +45 -0
- package/dist/verdict.js +368 -0
- package/engine-fingerprint.json +5 -0
- package/package.json +8 -4
- package/src/adoc-chunker.ts +308 -0
- package/src/archive-guard.ts +144 -0
- package/src/chunker.ts +5 -3
- package/src/cli.ts +130 -20
- package/src/config.ts +81 -6
- package/src/dox-triage.ts +231 -0
- package/src/dox.ts +390 -70
- package/src/eval.ts +136 -14
- package/src/gitignore.ts +215 -0
- package/src/index.ts +45 -20
- package/src/indexer.ts +46 -10
- package/src/net-guard.ts +288 -0
- package/src/render.ts +35 -3
- package/src/search-opts.ts +52 -0
- package/src/sources.ts +232 -28
- package/src/sqlite-store.ts +448 -67
- package/src/staleness.ts +76 -0
- package/src/trust.ts +81 -8
- package/src/types.ts +58 -0
- package/src/verdict.ts +412 -0
- package/src/AGENTS.md +0 -23
package/dist/sources.js
CHANGED
|
@@ -6,12 +6,29 @@
|
|
|
6
6
|
// Source classification mirrors `packages/server/src/package-source-helpers.ts`
|
|
7
7
|
// (`parseSourceKind`/`computeIdentity`) — reimplemented here to keep this
|
|
8
8
|
// publishable package self-contained (no kb→server dependency).
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import { existsSync, mkdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
9
|
+
import { execFile } 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)
|
|
10
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
11
|
+
import { existsSync, mkdirSync, mkdtempSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
12
|
+
import { isIP } from "node:net";
|
|
12
13
|
import { homedir } from "node:os";
|
|
13
|
-
import { isAbsolute, join, resolve } from "node:path";
|
|
14
|
+
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
15
|
+
import { promisify } from "node:util";
|
|
16
|
+
import { extractArchiveSafely } from "./archive-guard.js";
|
|
17
|
+
import { assertPublicHost, guardedFetch } from "./net-guard.js";
|
|
14
18
|
import { isTrusted, recordTrust } from "./trust.js";
|
|
19
|
+
const execFileAsync = promisify(execFile);
|
|
20
|
+
/** Per-git-call bound: a hung clone must not pin a job forever. */
|
|
21
|
+
const GIT_TIMEOUT_MS = 120_000;
|
|
22
|
+
const GIT_MAX_BUFFER = 16 * 1024 * 1024;
|
|
23
|
+
/** Thrown when a remote source has no trust record (and none was granted). Classifiable by callers. */
|
|
24
|
+
export class KbUntrustedSourceError extends Error {
|
|
25
|
+
spec;
|
|
26
|
+
constructor(spec) {
|
|
27
|
+
super(`remote source ${spec.kind ?? classifyRef(spec.ref)}:${spec.ref} not trusted — run interactively or pre-approve`);
|
|
28
|
+
this.spec = spec;
|
|
29
|
+
this.name = "KbUntrustedSourceError";
|
|
30
|
+
}
|
|
31
|
+
}
|
|
15
32
|
/** Classify a ref string (mirrors parseSourceKind). */
|
|
16
33
|
export function classifyRef(ref) {
|
|
17
34
|
if (ref.startsWith("npm:"))
|
|
@@ -52,7 +69,7 @@ export function sourceIdentity(spec, cwd = ".") {
|
|
|
52
69
|
function shortHash(s) {
|
|
53
70
|
return createHash("sha256").update(s).digest("hex").slice(0, 16);
|
|
54
71
|
}
|
|
55
|
-
function cacheKey(spec) {
|
|
72
|
+
export function cacheKey(spec) {
|
|
56
73
|
return shortHash(`${spec.kind ?? classifyRef(spec.ref)}:${spec.ref}:${spec.pin ?? ""}`);
|
|
57
74
|
}
|
|
58
75
|
async function ensureTrusted(spec, ctx) {
|
|
@@ -61,7 +78,7 @@ async function ensureTrusted(spec, ctx) {
|
|
|
61
78
|
const prompt = ctx.promptTrust ?? (async () => false);
|
|
62
79
|
const ok = await prompt(spec);
|
|
63
80
|
if (!ok)
|
|
64
|
-
throw new
|
|
81
|
+
throw new KbUntrustedSourceError(spec);
|
|
65
82
|
recordTrust(spec);
|
|
66
83
|
}
|
|
67
84
|
function isStale(spec, markerPath) {
|
|
@@ -124,63 +141,244 @@ function gitRefOf(spec) {
|
|
|
124
141
|
}
|
|
125
142
|
return undefined;
|
|
126
143
|
}
|
|
144
|
+
// Option-like refs/pins are passed positionally to fetch/checkout — reject `-` prefixes.
|
|
145
|
+
function assertSafeGitRef(label, v) {
|
|
146
|
+
if (v !== undefined && (v.startsWith("-") || /[\x00-\x1f]/.test(v)))
|
|
147
|
+
throw new Error(`git ${label} ${JSON.stringify(v)} is not allowed (option-like)`);
|
|
148
|
+
}
|
|
149
|
+
/** Allowlist https / ssh / scp-style git@host:path on the URL git actually receives. */
|
|
150
|
+
function parseGitTarget(url) {
|
|
151
|
+
const scp = /^git@([^:/]+):/.exec(url);
|
|
152
|
+
if (scp)
|
|
153
|
+
return { scheme: "ssh", host: scp[1], port: "" };
|
|
154
|
+
let u;
|
|
155
|
+
try {
|
|
156
|
+
u = new URL(url);
|
|
157
|
+
}
|
|
158
|
+
catch {
|
|
159
|
+
throw new Error(`git source URL is not valid: ${url}`);
|
|
160
|
+
}
|
|
161
|
+
if (u.protocol !== "https:" && u.protocol !== "ssh:") {
|
|
162
|
+
throw new Error(`git source scheme ${u.protocol}// is not allowed (only https, ssh, git@host:path)`);
|
|
163
|
+
}
|
|
164
|
+
return { scheme: u.protocol === "https:" ? "https" : "ssh", host: u.hostname, port: u.port };
|
|
165
|
+
}
|
|
166
|
+
let warnedOldGit = false;
|
|
127
167
|
export const gitResolver = {
|
|
128
168
|
kind: "git",
|
|
129
169
|
async resolve(spec, ctx) {
|
|
130
170
|
await ensureTrusted(spec, ctx);
|
|
131
|
-
const
|
|
171
|
+
const hooks = ctx.testHooks ?? {};
|
|
172
|
+
// execFile (argv array, no shell) — never interpolate url/ref/pin into a
|
|
173
|
+
// shell string (command-injection-safe even with hostile refs).
|
|
174
|
+
const git = hooks.git ?? (async (args) => (await execFileAsync("git", args, { encoding: "utf8", timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER })).stdout);
|
|
175
|
+
const rawRef = spec.ref.startsWith("git:") ? spec.ref.slice(4) : spec.ref;
|
|
176
|
+
if (/^[a-z][a-z0-9+.-]*::/i.test(rawRef))
|
|
177
|
+
throw new Error(`git transport helper refs are not allowed: ${rawRef}`);
|
|
132
178
|
const url = gitUrlOf(spec);
|
|
133
179
|
const ref = gitRefOf(spec);
|
|
180
|
+
assertSafeGitRef("pin", spec.pin);
|
|
181
|
+
assertSafeGitRef("ref", ref);
|
|
182
|
+
const target = parseGitTarget(url);
|
|
183
|
+
const cloneDir = join(ctx.cacheDir, cacheKey(spec));
|
|
134
184
|
const hasGit = existsSync(join(cloneDir, ".git"));
|
|
135
185
|
const shouldPull = ctx.refresh || spec.refresh === "on-index" || (!hasGit);
|
|
136
|
-
|
|
137
|
-
//
|
|
138
|
-
|
|
186
|
+
const hardening = [];
|
|
187
|
+
// Only networked operations need the host check / pin; a cached clone with no refresh works offline.
|
|
188
|
+
if (shouldPull) {
|
|
189
|
+
const addrs = await assertPublicHost(target.host, { lookup: hooks.lookup });
|
|
190
|
+
// Hardening as GLOBAL options before the subcommand (`git clone -c` would only
|
|
191
|
+
// write the new repo's config). Pin curl to the address we just checked (git >= 2.37).
|
|
192
|
+
hardening.push("-c", "protocol.allow=never", "-c", "protocol.https.allow=always", "-c", "protocol.ssh.allow=always", "-c", "http.followRedirects=false", "-c", "submodule.recurse=false", "-c", "fetch.recurseSubmodules=false");
|
|
193
|
+
if (target.scheme === "https" && !isIPLiteral(target.host)) {
|
|
194
|
+
const m = /git version (\d+)\.(\d+)/.exec(await git(["version"]));
|
|
195
|
+
if (m && (Number(m[1]) > 2 || (Number(m[1]) === 2 && Number(m[2]) >= 37))) {
|
|
196
|
+
const ip = addrs[0].family === 6 ? `[${addrs[0].address}]` : addrs[0].address;
|
|
197
|
+
hardening.push("-c", `http.curloptResolve=${target.host}:${target.port || "443"}:${ip}`);
|
|
198
|
+
}
|
|
199
|
+
else if (!warnedOldGit) {
|
|
200
|
+
warnedOldGit = true;
|
|
201
|
+
console.warn("[kb] git < 2.37: http.curloptResolve unavailable — host is checked but not pinned");
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
if (hasGit && shouldPull) {
|
|
206
|
+
// A poisoned/stale `origin` must never be contacted. Compare the RAW config value(s)
|
|
207
|
+
// (`remote get-url` applies the user's url.*.insteadOf rewriting — their config is trusted,
|
|
208
|
+
// so a rewrite is not a mismatch). Read ALL values: `--get` reports only the LAST one while
|
|
209
|
+
// fetch uses the FIRST URL of a multi-URL remote, so require exactly one, equal to the checked
|
|
210
|
+
// URL. On a mismatch refuse WITHOUT mutating the cache: nothing is deleted or replaced, so a
|
|
211
|
+
// concurrent resolver using this clone can never lose it.
|
|
212
|
+
let origins = [];
|
|
213
|
+
try {
|
|
214
|
+
origins = (await git(["-C", cloneDir, "config", "--get-all", "remote.origin.url"])).split("\n").map((l) => l.trim()).filter(Boolean);
|
|
215
|
+
}
|
|
216
|
+
catch { /* treated as a mismatch */ }
|
|
217
|
+
if (origins.length !== 1) {
|
|
218
|
+
throw new Error(`git cache entry ${cloneDir} has ${origins.length} configured origin URLs (expected exactly 1: ${url}); remove it and retry`);
|
|
219
|
+
}
|
|
220
|
+
if (origins[0] !== url) {
|
|
221
|
+
throw new Error(`git cache entry ${cloneDir} was cloned from a different origin (${origins[0]}) than the checked URL (${url}); remove it and retry`);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
139
224
|
if (!hasGit) {
|
|
140
225
|
mkdirSync(ctx.cacheDir, { recursive: true });
|
|
141
|
-
git(["clone", "--depth", "1", ...(ref ? ["--branch", ref] : []), "--", url, cloneDir]);
|
|
226
|
+
await git([...hardening, "clone", "--depth", "1", ...(ref ? ["--branch", ref] : []), "--", url, cloneDir]);
|
|
142
227
|
}
|
|
143
228
|
else if (shouldPull) {
|
|
144
229
|
if (ref) {
|
|
145
|
-
git(["-C", cloneDir, "fetch", "--depth", "1", "origin", ref]);
|
|
146
|
-
git(["-C", cloneDir, "checkout", ref]);
|
|
230
|
+
await git([...hardening, "-C", cloneDir, "fetch", "--no-recurse-submodules", "--depth", "1", "origin", ref]);
|
|
231
|
+
await git([...hardening, "-C", cloneDir, "checkout", "--no-recurse-submodules", ref]);
|
|
147
232
|
}
|
|
148
233
|
else
|
|
149
|
-
git(["-C", cloneDir, "pull", "--ff-only"]);
|
|
234
|
+
await git([...hardening, "-C", cloneDir, "pull", "--no-recurse-submodules", "--ff-only"]);
|
|
150
235
|
}
|
|
151
|
-
const rev =
|
|
236
|
+
const rev = (await git(["-C", cloneDir, "rev-parse", "--short", "HEAD"])).trim();
|
|
152
237
|
const dir = spec.subdir ? join(cloneDir, spec.subdir) : cloneDir;
|
|
153
238
|
return { id: spec.ref, dir, priority: spec.priority ?? 0, identity: sourceIdentity(spec, ctx.cwd), revision: rev };
|
|
154
239
|
},
|
|
155
240
|
};
|
|
241
|
+
function isIPLiteral(host) {
|
|
242
|
+
return isIP(host.startsWith("[") ? host.slice(1, -1) : host) !== 0;
|
|
243
|
+
}
|
|
156
244
|
// --- https ---
|
|
245
|
+
/** Archive kind from the URL *path* (query strings must not defeat detection). */
|
|
246
|
+
function archiveKindOf(pathname) {
|
|
247
|
+
if (/\.zip$/i.test(pathname))
|
|
248
|
+
return "zip";
|
|
249
|
+
if (/\.(tar\.gz|tgz|tar\.bz2)$/i.test(pathname))
|
|
250
|
+
return "tar";
|
|
251
|
+
return undefined;
|
|
252
|
+
}
|
|
253
|
+
/** Plain-file name: `basename(pathname)`, sanitised, falling back to `index.md`. */
|
|
254
|
+
function plainFileName(pathname) {
|
|
255
|
+
let name = pathname.endsWith("/") ? "" : basename(pathname);
|
|
256
|
+
try {
|
|
257
|
+
name = decodeURIComponent(name);
|
|
258
|
+
}
|
|
259
|
+
catch { /* keep raw */ }
|
|
260
|
+
// eslint-disable-next-line no-control-regex
|
|
261
|
+
name = name.replace(/[\x00-\x1f\x7f\\/:]/g, "_");
|
|
262
|
+
return name === "" || name === "." || name === ".." ? "index.md" : name;
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Lock-free, single-winner cache swap (review: concurrent refreshes).
|
|
266
|
+
*
|
|
267
|
+
* Every writer backs the previous cache up under a UNIQUE name
|
|
268
|
+
* (`<dest>.old-<epochMs>-<uuid>`) and only ever deletes ITS OWN backup, so one
|
|
269
|
+
* writer can never destroy another's rollback copy. Concurrent writers are
|
|
270
|
+
* last-writer-wins: a loser errors out (rename onto a populated dest fails) but
|
|
271
|
+
* `dest` always holds one writer's complete, valid content — never a mix, never
|
|
272
|
+
* nothing. No lock, so no lock-ownership/stale-steal class of bugs.
|
|
273
|
+
*/
|
|
274
|
+
function swapInto(dest, fresh, rename) {
|
|
275
|
+
const backup = `${dest}.old-${Date.now()}-${randomUUID()}`;
|
|
276
|
+
const hadDest = existsSync(dest);
|
|
277
|
+
if (hadDest)
|
|
278
|
+
rename(dest, backup);
|
|
279
|
+
try {
|
|
280
|
+
rename(fresh, dest);
|
|
281
|
+
}
|
|
282
|
+
catch (e) {
|
|
283
|
+
if (hadDest) {
|
|
284
|
+
try {
|
|
285
|
+
rename(backup, dest);
|
|
286
|
+
}
|
|
287
|
+
catch {
|
|
288
|
+
// dest was repopulated by a concurrent writer: it is valid, keep it; the backup ages out
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
throw e;
|
|
292
|
+
}
|
|
293
|
+
if (hadDest)
|
|
294
|
+
rmSync(backup, { recursive: true, force: true });
|
|
295
|
+
}
|
|
296
|
+
/**
|
|
297
|
+
* A backup younger than this may be ANOTHER writer's in-flight rollback copy (its
|
|
298
|
+
* two renames are ms apart): while one exists nothing is restored, and it is never
|
|
299
|
+
* pruned. Older ones are abandoned (the writer crashed between its renames).
|
|
300
|
+
*/
|
|
301
|
+
const BACKUP_GRACE_MS = 60_000;
|
|
302
|
+
/** Backups older than this are debris and pruned. */
|
|
303
|
+
const BACKUP_MAX_AGE_MS = 60 * 60_000;
|
|
304
|
+
const backupStamp = (name) => Number(/\.old-(\d+)-/.exec(name)?.[1] ?? 0);
|
|
305
|
+
/**
|
|
306
|
+
* Crash recovery: restore the newest ABANDONED backup (past the grace window) when
|
|
307
|
+
* `dest` is gone — a crash between the two swap renames — then prune only
|
|
308
|
+
* backups old enough to be debris. Exported for the interleaving test.
|
|
309
|
+
*/
|
|
310
|
+
export function recoverBackups(dest) {
|
|
311
|
+
const dir = dirname(dest);
|
|
312
|
+
const prefix = `${basename(dest)}.old-`;
|
|
313
|
+
let names;
|
|
314
|
+
try {
|
|
315
|
+
names = readdirSync(dir).filter((n) => n.startsWith(prefix));
|
|
316
|
+
}
|
|
317
|
+
catch {
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
const age = (n) => Date.now() - backupStamp(n);
|
|
321
|
+
names.sort((x, y) => backupStamp(y) - backupStamp(x)); // newest first
|
|
322
|
+
// Restore only when EVERY backup is abandoned: a single young one may be a live writer's
|
|
323
|
+
// rollback copy, and restoring an older backup under it would make that writer's publish fail.
|
|
324
|
+
if (!existsSync(dest) && !names.some((n) => age(n) <= BACKUP_GRACE_MS)) {
|
|
325
|
+
const abandoned = names[0];
|
|
326
|
+
if (abandoned) {
|
|
327
|
+
try {
|
|
328
|
+
renameSync(join(dir, abandoned), dest);
|
|
329
|
+
names.splice(names.indexOf(abandoned), 1);
|
|
330
|
+
}
|
|
331
|
+
catch {
|
|
332
|
+
// a concurrent writer restored/populated dest first — fine
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
for (const n of names) {
|
|
337
|
+
if (age(n) > BACKUP_MAX_AGE_MS)
|
|
338
|
+
rmSync(join(dir, n), { recursive: true, force: true });
|
|
339
|
+
}
|
|
340
|
+
}
|
|
157
341
|
export const httpsResolver = {
|
|
158
342
|
kind: "https",
|
|
159
343
|
async resolve(spec, ctx) {
|
|
160
344
|
await ensureTrusted(spec, ctx);
|
|
345
|
+
const hooks = ctx.testHooks ?? {};
|
|
161
346
|
const dest = join(ctx.cacheDir, cacheKey(spec));
|
|
162
|
-
const url = spec.ref;
|
|
163
347
|
const marker = join(dest, ".fetched");
|
|
164
|
-
|
|
348
|
+
let url;
|
|
349
|
+
try {
|
|
350
|
+
url = new URL(spec.ref);
|
|
351
|
+
}
|
|
352
|
+
catch {
|
|
353
|
+
throw new Error(`invalid source URL: ${spec.ref}`);
|
|
354
|
+
}
|
|
355
|
+
if (url.protocol !== "https:")
|
|
356
|
+
throw new Error(`only https:// sources are allowed (got ${url.protocol}//): ${spec.ref}`);
|
|
357
|
+
// Crash recovery from a previous interrupted swap.
|
|
358
|
+
recoverBackups(dest);
|
|
165
359
|
const shouldFetch = ctx.refresh || spec.refresh === "on-index" || isStale(spec, marker);
|
|
166
360
|
if (shouldFetch) {
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
const
|
|
173
|
-
|
|
174
|
-
if (
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
361
|
+
mkdirSync(ctx.cacheDir, { recursive: true });
|
|
362
|
+
const stage = mkdtempSync(join(ctx.cacheDir, ".stage-"));
|
|
363
|
+
try {
|
|
364
|
+
const out = join(stage, "out");
|
|
365
|
+
mkdirSync(out);
|
|
366
|
+
const body = await (hooks.fetch ?? ((u) => guardedFetch(u)))(spec.ref);
|
|
367
|
+
const kind = archiveKindOf(url.pathname);
|
|
368
|
+
if (kind) {
|
|
369
|
+
const archive = join(stage, kind === "zip" ? "archive.zip" : "archive.tar");
|
|
370
|
+
writeFileSync(archive, body);
|
|
371
|
+
await extractArchiveSafely(kind, archive, out, hooks.archiveLimits);
|
|
372
|
+
}
|
|
373
|
+
else {
|
|
374
|
+
writeFileSync(join(out, plainFileName(url.pathname)), body);
|
|
375
|
+
}
|
|
376
|
+
writeFileSync(join(out, ".fetched"), String(Date.now()));
|
|
377
|
+
swapInto(dest, out, hooks.rename ?? renameSync);
|
|
178
378
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
writeFileSync(join(dest, url.split("/").pop() || "index.md"), text);
|
|
379
|
+
finally {
|
|
380
|
+
rmSync(stage, { recursive: true, force: true });
|
|
182
381
|
}
|
|
183
|
-
writeFileSync(marker, String(Date.now()));
|
|
184
382
|
}
|
|
185
383
|
return { id: spec.ref, dir: dest, priority: spec.priority ?? 0, identity: sourceIdentity(spec, ctx.cwd) };
|
|
186
384
|
},
|
package/dist/sqlite-store.d.ts
CHANGED
|
@@ -1,14 +1,51 @@
|
|
|
1
1
|
import type { Chunk, FileState, Filter, GraphEdge, GraphNode, KbHit, KbStore, SearchOpts, StorePropertyRow } from "./types.js";
|
|
2
2
|
/** Bump when the frontmatter structural schema/behavior changes so an existing
|
|
3
3
|
* DB force-reindexes once on open (design D6). */
|
|
4
|
-
export declare const SCHEMA_VERSION =
|
|
4
|
+
export declare const SCHEMA_VERSION = 3;
|
|
5
5
|
export declare class SqliteFtsStore implements KbStore {
|
|
6
6
|
private db;
|
|
7
7
|
readonly dbPath: string;
|
|
8
|
+
/** Opened via `openExisting`: SELECT-only handle, must never issue DDL against the saved file. */
|
|
9
|
+
private readonly existingOnly;
|
|
10
|
+
/** fts5vocab view used for document frequencies (persistent in a writer, connection-local TEMP when `existingOnly`). */
|
|
11
|
+
private vocabTable;
|
|
8
12
|
private stmts;
|
|
9
13
|
private prep;
|
|
10
|
-
|
|
14
|
+
/**
|
|
15
|
+
* `existingOnly` opens a side-effect-free handle for read-only callers: no
|
|
16
|
+
* `mkdir`, no `journal_mode=WAL` (a mode change rewrites a DELETE-mode file
|
|
17
|
+
* header), and the caller must NOT call `init()` (no DDL / schema migration).
|
|
18
|
+
* Prefer {@link SqliteFtsStore.openExisting}.
|
|
19
|
+
*/
|
|
20
|
+
constructor(dbPath: string, opts?: {
|
|
21
|
+
existingOnly?: boolean;
|
|
22
|
+
});
|
|
23
|
+
/**
|
|
24
|
+
* Open an EXISTING db without creating, migrating or re-moding it. Returns
|
|
25
|
+
* null for a missing or 0-byte file (callers treat that as an empty index).
|
|
26
|
+
* A read-write handle is used on purpose: a `readOnly` connection cannot
|
|
27
|
+
* create the WAL `-shm` sidecar once the writer checkpointed and removed it
|
|
28
|
+
* (SQLITE_CANTOPEN). Callers must only issue SELECTs.
|
|
29
|
+
*/
|
|
30
|
+
static openExisting(dbPath: string): SqliteFtsStore | null;
|
|
31
|
+
/** True when `chunks` exists with the current column set (`start_line`). Read-only probe. */
|
|
32
|
+
hasCurrentSchema(): {
|
|
33
|
+
table: boolean;
|
|
34
|
+
current: boolean;
|
|
35
|
+
};
|
|
36
|
+
/** Indexed file count per root. `files` has a (root,path) PK, so this is cheap (no FTS scan). */
|
|
37
|
+
filesByRoot(): Record<string, number>;
|
|
11
38
|
init(): void;
|
|
39
|
+
/** Rebuild the `chunks` FTS5 table when its column set predates the current
|
|
40
|
+
* DDL. `CREATE VIRTUAL TABLE IF NOT EXISTS` is a NO-OP on an existing table
|
|
41
|
+
* and FTS5 has no `ALTER TABLE ADD COLUMN`, so without this an older store
|
|
42
|
+
* keeps its 10-column table and every `insertChunk` throws "table chunks has
|
|
43
|
+
* no column named start_line" — permanently un-reindexable. Chunks are
|
|
44
|
+
* derived data, so dropping is safe; `files` (the mtime/sha256 state) is
|
|
45
|
+
* cleared with them, or the next INCREMENTAL walk would skip every unchanged
|
|
46
|
+
* file and leave the rebuilt table empty. Runs for every opener, not just the
|
|
47
|
+
* `runIndexAtomic` version gate. See change: asciidoc-support (design D3a). */
|
|
48
|
+
private migrateChunksSchema;
|
|
12
49
|
begin(): void;
|
|
13
50
|
commit(): void;
|
|
14
51
|
rollback(): void;
|
|
@@ -38,10 +75,43 @@ export declare class SqliteFtsStore implements KbStore {
|
|
|
38
75
|
insertChunk(c: Chunk): void;
|
|
39
76
|
addNode(n: GraphNode): void;
|
|
40
77
|
addEdge(e: GraphEdge): void;
|
|
78
|
+
/** Porter stems for raw tokens, computed by SQLite's OWN tokenizer so they
|
|
79
|
+
* match what FTS5 actually indexed. A raw token is NOT a usable key into the
|
|
80
|
+
* vocab table: FTS5 stores `collaps`, and no prefix range anchored at
|
|
81
|
+
* `collapsed` can reach a key that sorts BEFORE it. The helper tables live in
|
|
82
|
+
* `temp.`, so this works against a read-only main DB. */
|
|
83
|
+
private stemReady;
|
|
84
|
+
private stemCache;
|
|
85
|
+
private stems;
|
|
86
|
+
/** Corpus document frequency for raw tokens, via the fts5vocab shadow table.
|
|
87
|
+
* Keys are exact porter stems (see `stems()`), so df is exact rather than a
|
|
88
|
+
* prefix over-estimate. `fts5vocab` is a live view over the FTS index, but
|
|
89
|
+
* `dfCache` is not — it is dropped on `commit()`/`deleteByPath`, the points at
|
|
90
|
+
* which an index batch can have moved the counts. Falls back to df=0 when the
|
|
91
|
+
* vocab table cannot be created (e.g. a read-only DB). */
|
|
92
|
+
private dfCache;
|
|
93
|
+
private vocabReady;
|
|
94
|
+
private documentFrequencies;
|
|
95
|
+
/** IDF weights for the given tokens over the current corpus. */
|
|
96
|
+
private idf;
|
|
41
97
|
search(query: string, opts?: SearchOpts): KbHit[];
|
|
42
98
|
neighbors(node: string, depth: number, rel?: GraphEdge["rel"]): GraphNode[];
|
|
43
99
|
backlinks(node: string): GraphNode[];
|
|
100
|
+
/** Fetch a chunk by path (+ optional section). A path-only fetch of a
|
|
101
|
+
* multi-chunk file returns the FIRST chunk plus a `suppressedSections` count
|
|
102
|
+
* — it must never silently hand back one arbitrary slice of N (design D7). */
|
|
44
103
|
getChunk(root: string, path: string, headingPath?: string): Chunk | null;
|
|
104
|
+
/** All chunks of a file in document order — the non-truncating companion to a
|
|
105
|
+
* path-only `getChunk`. */
|
|
106
|
+
getChunks(root: string, path: string): Chunk[];
|
|
107
|
+
/** Rerank by IDF-weighted coverage of the ORIGINAL query terms, BM25 as the
|
|
108
|
+
* tiebreak. PRF-appended terms count at half weight so expansion can never
|
|
109
|
+
* dominate the sort (design D4). */
|
|
110
|
+
private coverageRerank;
|
|
111
|
+
/** RM3-style pseudo-relevance feedback: mine the top candidates of a first
|
|
112
|
+
* pass for terms absent from the query and below the corpus-frequency
|
|
113
|
+
* ceiling, rank by freq × IDF, return the top `terms` (design D4). */
|
|
114
|
+
private prfTerms;
|
|
45
115
|
getChunkById(root: string, chunkId: string): Chunk | null;
|
|
46
116
|
counts(): {
|
|
47
117
|
files: number;
|