@blackbelt-technology/pi-dashboard-kb 0.10.0 → 0.12.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 +31 -0
- package/bin/lib/engine-fingerprint.mjs +25 -1
- package/dist/chunker.js +21 -3
- package/dist/cli.js +9 -11
- package/dist/fetch-resolve.d.ts +48 -0
- package/dist/fetch-resolve.js +87 -0
- package/dist/index-gate.d.ts +5 -4
- package/dist/index-gate.js +6 -5
- package/dist/index.d.ts +3 -1
- package/dist/index.js +2 -1
- package/dist/indexer.d.ts +22 -0
- package/dist/indexer.js +34 -1
- package/dist/sources.d.ts +7 -2
- package/dist/sources.js +57 -5
- package/dist/sqlite-store.d.ts +21 -2
- package/dist/sqlite-store.js +102 -28
- package/dist/types.d.ts +9 -0
- package/engine-fingerprint.json +3 -2
- package/package.json +1 -1
- package/src/chunker.ts +20 -4
- package/src/cli.ts +9 -10
- package/src/fetch-resolve.ts +115 -0
- package/src/index-gate.ts +7 -6
- package/src/index.ts +3 -1
- package/src/indexer.ts +40 -1
- package/src/sources.ts +57 -6
- package/src/sqlite-store.ts +98 -20
- package/src/types.ts +9 -0
package/README.md
CHANGED
|
@@ -18,6 +18,37 @@ kb dox lint
|
|
|
18
18
|
Pair it with `@blackbelt-technology/pi-dashboard-kb-extension` to expose `kb_search`,
|
|
19
19
|
`kb_get` and `kb_neighbors` as pi tools.
|
|
20
20
|
|
|
21
|
+
## Sources
|
|
22
|
+
|
|
23
|
+
`.pi/dashboard/knowledge_base.json` lists `sources[]`. The kind comes from an
|
|
24
|
+
explicit `kind` or is inferred from `ref`:
|
|
25
|
+
|
|
26
|
+
```json
|
|
27
|
+
{ "sources": [
|
|
28
|
+
{ "ref": "docs" },
|
|
29
|
+
{ "ref": "https://github.com/owner/repo" },
|
|
30
|
+
{ "ref": "https://github.com/owner/repo/tree/dev", "subdir": "docs" },
|
|
31
|
+
{ "ref": "ssh://git@github.com/owner/private" },
|
|
32
|
+
{ "ref": "https://raw.githubusercontent.com/owner/repo/main/README.md" }
|
|
33
|
+
] }
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
A GitHub repository URL (optionally `.git`, `@<ref>` or `/tree/<ref>`) and an
|
|
37
|
+
`ssh://` URL are cloned as `git` sources. Raw file and archive URLs are fetched
|
|
38
|
+
as `https`; an https fetch that yields an HTML page or a file without an
|
|
39
|
+
indexable extension fails with a hint instead of indexing nothing. Remote
|
|
40
|
+
sources are indexed by `kb index` (they prompt for trust once); the live
|
|
41
|
+
extension auto-reindexes filesystem sources only.
|
|
42
|
+
|
|
43
|
+
`kb get <path>` / `kb_get` look in every indexed source. A path indexed in more
|
|
44
|
+
than one source returns a candidate list (`<source-id>:<path>`) instead of a
|
|
45
|
+
body; pass a candidate back, or qualify the path by its source directory.
|
|
46
|
+
`--section` / `section` accepts a full heading path or a unique last heading.
|
|
47
|
+
An unknown section in a found file prints
|
|
48
|
+
`(section not found: <section> in <path> — sections:)` followed by up to 50 of
|
|
49
|
+
the file's heading paths (then `(+K more sections)`); `(not found: <path>)`
|
|
50
|
+
means the path itself is not indexed.
|
|
51
|
+
|
|
21
52
|
## Evaluate retrieval (kb eval)
|
|
22
53
|
|
|
23
54
|
```bash
|
|
@@ -5,7 +5,14 @@
|
|
|
5
5
|
// gate (scripts/check-kb-dist-fresh.mjs) recomputes with it — no three-way
|
|
6
6
|
// reimplementation.
|
|
7
7
|
//
|
|
8
|
-
//
|
|
8
|
+
// Four hashes:
|
|
9
|
+
// rowsHash — LF-normalized contents of ROW_PRODUCING_FILES only (the files whose
|
|
10
|
+
// edits can change the rows an index pass writes). THE engine value the
|
|
11
|
+
// staleness gate and the worktree-seed gate compare, so an edit to
|
|
12
|
+
// render.ts / cli.ts / … no longer forces a corpus-wide reindex.
|
|
13
|
+
// Completeness is mechanical: engine-row-closure.test.ts asserts the
|
|
14
|
+
// indexer.ts import closure ⊆ this list ∪ a declared non-row list.
|
|
15
|
+
// (change: throttle-kb-reindex, D1)
|
|
9
16
|
// srcHash — LF-normalized contents of src/**/*.ts minus src/__tests__,
|
|
10
17
|
// sorted relative paths (a src edit without a rebuild forks
|
|
11
18
|
// the hash → observable in CI).
|
|
@@ -56,6 +63,22 @@ export function computeSrcHash(pkgRoot) {
|
|
|
56
63
|
return hashFiles(pkgRoot, rels);
|
|
57
64
|
}
|
|
58
65
|
|
|
66
|
+
/** The files whose content determines the rows `indexSource` writes (chunkers, indexer,
|
|
67
|
+
* frontmatter extraction, gitignore filter). `sqlite-store.ts` is deliberately absent: it also
|
|
68
|
+
* holds search code, so its row-affecting part (DDL) is governed by SCHEMA_VERSION + the DDL
|
|
69
|
+
* golden test instead. Package-relative posix paths. */
|
|
70
|
+
export const ROW_PRODUCING_FILES = Object.freeze(["src/adoc-chunker.ts", "src/chunker.ts", "src/frontmatter.ts", "src/gitignore.ts", "src/indexer.ts"]);
|
|
71
|
+
|
|
72
|
+
/** Digest of ROW_PRODUCING_FILES (fixed sorted order ⇒ path/mtime/creation-order independent).
|
|
73
|
+
* A file absent from `pkgRoot` hashes as empty (stub sandboxes); the real package's files are
|
|
74
|
+
* asserted present by engine-fingerprint.test.ts. */
|
|
75
|
+
export function computeRowsHash(pkgRoot) {
|
|
76
|
+
return hashFiles(
|
|
77
|
+
pkgRoot,
|
|
78
|
+
[...ROW_PRODUCING_FILES].sort().filter((rel) => existsSync(join(pkgRoot, rel))),
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
59
82
|
/** The tsconfig extends chain (root first, then each resolved extends target).
|
|
60
83
|
* Only relative extends targets are followed — a package-spec extends target
|
|
61
84
|
* cannot resolve reliably without a module resolver and this package has none. */
|
|
@@ -137,6 +160,7 @@ export function computeDistHash(pkgRoot) {
|
|
|
137
160
|
|
|
138
161
|
export function fingerprintPackage(pkgRoot) {
|
|
139
162
|
return {
|
|
163
|
+
rowsHash: computeRowsHash(pkgRoot),
|
|
140
164
|
srcHash: computeSrcHash(pkgRoot),
|
|
141
165
|
tsconfigHash: computeTsconfigHash(pkgRoot),
|
|
142
166
|
distHash: computeDistHash(pkgRoot),
|
package/dist/chunker.js
CHANGED
|
@@ -59,6 +59,9 @@ export function chunkMarkdown(input) {
|
|
|
59
59
|
const { body: text, fm, parseFailed } = parseFrontmatter(input.text);
|
|
60
60
|
const lines = text.split("\n");
|
|
61
61
|
const fileTitle = input.path.split("/").pop().replace(/\.(md|mdx|markdown)$/i, "");
|
|
62
|
+
// `ordinal` is the parse-time section number; `parentOrdinal` (-1 = none) names
|
|
63
|
+
// the direct enclosing section. Both survive tiny-merge and oversize-split and
|
|
64
|
+
// are resolved to final chunk indices at the end (as adoc-chunker.ts does).
|
|
62
65
|
const raw = [];
|
|
63
66
|
const stack = [];
|
|
64
67
|
let cur = null;
|
|
@@ -97,14 +100,15 @@ export function chunkMarkdown(input) {
|
|
|
97
100
|
headingPath: stack.map((s) => s.title).join(" > "),
|
|
98
101
|
heading: title,
|
|
99
102
|
level,
|
|
100
|
-
|
|
103
|
+
ordinal,
|
|
104
|
+
parentOrdinal,
|
|
101
105
|
body: "",
|
|
102
106
|
};
|
|
103
107
|
ordinal++;
|
|
104
108
|
}
|
|
105
109
|
else {
|
|
106
110
|
if (!cur) {
|
|
107
|
-
cur = { headingPath: fileTitle, heading: fileTitle, level: 0,
|
|
111
|
+
cur = { headingPath: fileTitle, heading: fileTitle, level: 0, ordinal, parentOrdinal: -1, body: "" };
|
|
108
112
|
ordinal++;
|
|
109
113
|
}
|
|
110
114
|
cur.body += line + "\n";
|
|
@@ -130,6 +134,8 @@ export function chunkMarkdown(input) {
|
|
|
130
134
|
const paras = c.body.split(/\n\s*\n/);
|
|
131
135
|
let buf = "";
|
|
132
136
|
for (const p of paras) {
|
|
137
|
+
if (!p.trim())
|
|
138
|
+
continue; // never emit (or lead a piece with) a whitespace-only paragraph
|
|
133
139
|
if ((buf + p).length > MAX_CHUNK_CHARS && buf) {
|
|
134
140
|
sized.push({ ...c, body: buf });
|
|
135
141
|
buf = "";
|
|
@@ -140,6 +146,18 @@ export function chunkMarkdown(input) {
|
|
|
140
146
|
sized.push({ ...c, body: buf });
|
|
141
147
|
}
|
|
142
148
|
const fileSha = sha(input.path);
|
|
149
|
+
// ordinal → first final index (a split section's children point at its first
|
|
150
|
+
// piece). An absent ordinal was dropped (empty) or merged away (tiny): its
|
|
151
|
+
// children get a null parent, never a sibling or themselves.
|
|
152
|
+
const indexByOrdinal = new Map();
|
|
153
|
+
sized.forEach((c, i) => {
|
|
154
|
+
if (!indexByOrdinal.has(c.ordinal))
|
|
155
|
+
indexByOrdinal.set(c.ordinal, i);
|
|
156
|
+
});
|
|
157
|
+
const parentIdOf = (c) => {
|
|
158
|
+
const idx = indexByOrdinal.get(c.parentOrdinal);
|
|
159
|
+
return idx === undefined ? null : `${fileSha.slice(0, 8)}:${idx}`;
|
|
160
|
+
};
|
|
143
161
|
const chunks = sized.map((c, i) => ({
|
|
144
162
|
root: input.root,
|
|
145
163
|
path: input.path,
|
|
@@ -147,7 +165,7 @@ export function chunkMarkdown(input) {
|
|
|
147
165
|
headingPath: c.headingPath,
|
|
148
166
|
heading: c.heading,
|
|
149
167
|
level: c.level,
|
|
150
|
-
parentChunkId: c
|
|
168
|
+
parentChunkId: parentIdOf(c),
|
|
151
169
|
docType,
|
|
152
170
|
body: c.body.trimEnd(),
|
|
153
171
|
bodyHash: sha(c.body.trim()),
|
package/dist/cli.js
CHANGED
|
@@ -8,6 +8,7 @@ import { indexOptionsFromConfig, loadConfig } from "./config.js";
|
|
|
8
8
|
import { agentsChain, doxInit, doxLint, listEmptyPurposeRows } from "./dox.js";
|
|
9
9
|
import { ackTargets, applyDecisions, buildWorkItems } from "./dox-triage.js";
|
|
10
10
|
import { evaluate, loadGolden } from "./eval.js";
|
|
11
|
+
import { buildFetchRoots, renderFetch, resolveFetch } from "./fetch-resolve.js";
|
|
11
12
|
import { beginForcedSource, sourceGateIsStale, stampPass, stampSource } from "./index-gate.js";
|
|
12
13
|
import { BUILDING_LINE, isFirstIndexLive, runIndexAtomic } from "./index-run.js";
|
|
13
14
|
import { indexSource } from "./indexer.js";
|
|
@@ -139,6 +140,7 @@ async function sourcesForRun(cfg, flags) {
|
|
|
139
140
|
cwd: cfg.cwd,
|
|
140
141
|
cacheDir: cfg.cacheDirAbs,
|
|
141
142
|
refresh: !!flags.refresh,
|
|
143
|
+
extensions: cfg.extensions,
|
|
142
144
|
promptTrust: interactive ? defaultPromptTrust : undefined,
|
|
143
145
|
});
|
|
144
146
|
}
|
|
@@ -377,17 +379,13 @@ async function runCmd(cmd, flags) {
|
|
|
377
379
|
console.log(flags.json ? JSON.stringify(n, null, 2) : n.map((x) => `${x.type}\t${x.name}`).join("\n"));
|
|
378
380
|
}
|
|
379
381
|
else if (cmd === "get") {
|
|
380
|
-
//
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
// A path-only fetch of a multi-chunk file must never look like the whole
|
|
388
|
-
// file. See change: fix-kb-search-retrieval-quality (design D7).
|
|
389
|
-
const more = c?.suppressedSections ?? 0;
|
|
390
|
-
console.log(c ? (more > 0 ? `${c.body}\n\n(+${more} more section${more === 1 ? "" : "s"} in this file — pass --section <headingPath> to fetch one)` : c.body) : `(not found: ${flags._[1]})`);
|
|
382
|
+
// Every indexed root via the shared resolver (same rules as the kb_get
|
|
383
|
+
// tool): qualified paths, candidate list on collision, last-heading
|
|
384
|
+
// section fallback. See change: fix-kb-get-roots-and-guard.
|
|
385
|
+
const section = flags.section;
|
|
386
|
+
const roots = buildFetchRoots(store.listRoots(), cfg.resolvedSources, cfg.cwd);
|
|
387
|
+
const r = resolveFetch(store, roots, flags._[1], section);
|
|
388
|
+
console.log(renderFetch(r, flags._[1], section, "pass --section <headingPath>").text);
|
|
391
389
|
}
|
|
392
390
|
else if (cmd === "eval") {
|
|
393
391
|
const gf = flags.golden;
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { Chunk } from "./types.js";
|
|
2
|
+
/** A fetchable root. `relDir` (repo-relative, `/`-separated) exists only for
|
|
3
|
+
* filesystem roots; remote roots resolve by literal or id-qualified path. */
|
|
4
|
+
export interface FetchRoot {
|
|
5
|
+
id: string;
|
|
6
|
+
relDir?: string;
|
|
7
|
+
}
|
|
8
|
+
/** The store surface `resolveFetch` needs. */
|
|
9
|
+
export interface FetchStore {
|
|
10
|
+
getChunk(root: string, path: string, headingPath?: string): Chunk | null;
|
|
11
|
+
getChunkBySection?(root: string, path: string, section: string): Chunk[];
|
|
12
|
+
/** All chunks of one file in document order (lists sections on a miss). */
|
|
13
|
+
getChunks(root: string, path: string): Chunk[];
|
|
14
|
+
}
|
|
15
|
+
export type FetchResult = {
|
|
16
|
+
kind: "hit";
|
|
17
|
+
root: string;
|
|
18
|
+
path: string;
|
|
19
|
+
chunk: Chunk;
|
|
20
|
+
} | {
|
|
21
|
+
kind: "ambiguous";
|
|
22
|
+
on: "path" | "section";
|
|
23
|
+
candidates: string[];
|
|
24
|
+
}
|
|
25
|
+
/** The path resolved, the section did not; `sections` = the file's distinct
|
|
26
|
+
* body heading paths in document order (frontmatter `:meta` excluded). */
|
|
27
|
+
| {
|
|
28
|
+
kind: "section-missing";
|
|
29
|
+
sections: string[];
|
|
30
|
+
} | {
|
|
31
|
+
kind: "missing";
|
|
32
|
+
};
|
|
33
|
+
/** Build fetch roots from the store's distinct roots; `relDir` comes from the
|
|
34
|
+
* matching filesystem source (`relative(cwd, dir)`, normalized to `/`). */
|
|
35
|
+
export declare function buildFetchRoots(rootIds: string[], fsSources: Array<{
|
|
36
|
+
id: string;
|
|
37
|
+
dir: string;
|
|
38
|
+
}>, cwd: string): FetchRoot[];
|
|
39
|
+
export declare function resolveFetch(store: FetchStore, roots: FetchRoot[], arg: string, section?: string): FetchResult;
|
|
40
|
+
export interface RenderedFetch {
|
|
41
|
+
text: string;
|
|
42
|
+
found: boolean;
|
|
43
|
+
suppressedSections: number;
|
|
44
|
+
candidates?: number;
|
|
45
|
+
}
|
|
46
|
+
/** Render a fetch result. `sectionHint` names how the caller passes a section
|
|
47
|
+
* (tool: "pass `section`", CLI: "pass --section <headingPath>"). */
|
|
48
|
+
export declare function renderFetch(r: FetchResult, arg: string, section: string | undefined, sectionHint: string): RenderedFetch;
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
// Shared section-fetch resolver for the `kb_get` tool and the `kb get` CLI, so
|
|
2
|
+
// the two surfaces cannot diverge again. Resolves a path argument across EVERY
|
|
3
|
+
// indexed root (store-derived, remote included), accepts source-qualified
|
|
4
|
+
// paths, never silently picks one of several matches, and falls back from an
|
|
5
|
+
// exact heading path to a unique last heading.
|
|
6
|
+
// See change: fix-kb-get-roots-and-guard (design D1–D4).
|
|
7
|
+
import { relative } from "node:path";
|
|
8
|
+
/** Most heading paths listed after a section-not-found marker. */
|
|
9
|
+
const SECTION_LIST_CAP = 50;
|
|
10
|
+
/** Build fetch roots from the store's distinct roots; `relDir` comes from the
|
|
11
|
+
* matching filesystem source (`relative(cwd, dir)`, normalized to `/`). */
|
|
12
|
+
export function buildFetchRoots(rootIds, fsSources, cwd) {
|
|
13
|
+
const dirs = new Map(fsSources.map((s) => [s.id, relative(cwd, s.dir).replace(/\\/g, "/")]));
|
|
14
|
+
return rootIds.map((id) => (dirs.has(id) ? { id, relDir: dirs.get(id) } : { id }));
|
|
15
|
+
}
|
|
16
|
+
/** Every (root, path) reading of `arg` that exists in the store (design D2). */
|
|
17
|
+
function pathReadings(store, roots, arg) {
|
|
18
|
+
const readings = new Map();
|
|
19
|
+
const add = (root, path) => {
|
|
20
|
+
const key = `${root}\0${path}`;
|
|
21
|
+
if (path && !readings.has(key) && store.getChunk(root, path))
|
|
22
|
+
readings.set(key, { root, path });
|
|
23
|
+
};
|
|
24
|
+
// 1. literal
|
|
25
|
+
for (const r of roots)
|
|
26
|
+
add(r.id, arg);
|
|
27
|
+
// 2. id-qualified — the LONGEST matching id wins, so ids containing `:` round-trip
|
|
28
|
+
const byId = roots.filter((r) => arg.startsWith(`${r.id}:`)).sort((a, b) => b.id.length - a.id.length)[0];
|
|
29
|
+
if (byId)
|
|
30
|
+
add(byId.id, arg.slice(byId.id.length + 1));
|
|
31
|
+
// 3. dir-qualified
|
|
32
|
+
for (const r of roots) {
|
|
33
|
+
if (r.relDir && r.relDir !== "." && arg.startsWith(`${r.relDir}/`))
|
|
34
|
+
add(r.id, arg.slice(r.relDir.length + 1));
|
|
35
|
+
}
|
|
36
|
+
return [...readings.values()];
|
|
37
|
+
}
|
|
38
|
+
/** Section lookup inside one resolved file (design D3). */
|
|
39
|
+
function resolveSection(store, root, path, section) {
|
|
40
|
+
const matches = store.getChunkBySection ? store.getChunkBySection(root, path, section) : [store.getChunk(root, path, section)].filter((c) => !!c);
|
|
41
|
+
// A long section split into several chunks shares one heading path — one section.
|
|
42
|
+
const headings = [...new Set(matches.map((c) => c.headingPath))];
|
|
43
|
+
if (!headings.length) {
|
|
44
|
+
const body = store.getChunks(root, path).filter((c) => !c.chunkId.endsWith(":meta"));
|
|
45
|
+
return { kind: "section-missing", sections: [...new Set(body.map((c) => c.headingPath))] };
|
|
46
|
+
}
|
|
47
|
+
if (headings.length > 1)
|
|
48
|
+
return { kind: "ambiguous", on: "section", candidates: headings };
|
|
49
|
+
return { kind: "hit", root, path, chunk: matches[0] };
|
|
50
|
+
}
|
|
51
|
+
export function resolveFetch(store, roots, arg, section) {
|
|
52
|
+
const found = pathReadings(store, roots, arg);
|
|
53
|
+
if (!found.length)
|
|
54
|
+
return { kind: "missing" };
|
|
55
|
+
if (found.length > 1)
|
|
56
|
+
return { kind: "ambiguous", on: "path", candidates: found.map((f) => `${f.root}:${f.path}`).sort() };
|
|
57
|
+
const { root, path } = found[0];
|
|
58
|
+
// Section disambiguation only after the path resolved to exactly one root.
|
|
59
|
+
if (section)
|
|
60
|
+
return resolveSection(store, root, path, section);
|
|
61
|
+
const chunk = store.getChunk(root, path);
|
|
62
|
+
return chunk ? { kind: "hit", root, path, chunk } : { kind: "missing" };
|
|
63
|
+
}
|
|
64
|
+
/** Render a fetch result. `sectionHint` names how the caller passes a section
|
|
65
|
+
* (tool: "pass `section`", CLI: "pass --section <headingPath>"). */
|
|
66
|
+
export function renderFetch(r, arg, section, sectionHint) {
|
|
67
|
+
if (r.kind === "missing")
|
|
68
|
+
return { text: `(not found: ${arg})`, found: false, suppressedSections: 0 };
|
|
69
|
+
if (r.kind === "section-missing") {
|
|
70
|
+
if (!r.sections.length)
|
|
71
|
+
return { text: `(section not found: ${section} in ${arg} — no sections)`, found: false, suppressedSections: 0 };
|
|
72
|
+
const extra = r.sections.length - SECTION_LIST_CAP;
|
|
73
|
+
const lines = [`(section not found: ${section} in ${arg} — sections:)`, ...r.sections.slice(0, SECTION_LIST_CAP)];
|
|
74
|
+
if (extra > 0)
|
|
75
|
+
lines.push(`(+${extra} more section${extra === 1 ? "" : "s"})`);
|
|
76
|
+
return { text: lines.join("\n"), found: false, suppressedSections: 0 };
|
|
77
|
+
}
|
|
78
|
+
if (r.kind === "ambiguous") {
|
|
79
|
+
const head = r.on === "path"
|
|
80
|
+
? `(ambiguous: ${arg} is indexed in ${r.candidates.length} sources — pass one of:)`
|
|
81
|
+
: `(ambiguous: section ${section} matches ${r.candidates.length} sections in ${arg} — pass one of as section:)`;
|
|
82
|
+
return { text: [head, ...r.candidates].join("\n"), found: false, suppressedSections: 0, candidates: r.candidates.length };
|
|
83
|
+
}
|
|
84
|
+
const more = r.chunk.suppressedSections ?? 0;
|
|
85
|
+
const text = more > 0 ? `${r.chunk.body}\n\n(+${more} more section${more === 1 ? "" : "s"} in this file — ${sectionHint} to fetch one)` : r.chunk.body;
|
|
86
|
+
return { text, found: true, suppressedSections: more };
|
|
87
|
+
}
|
package/dist/index-gate.d.ts
CHANGED
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { type IndexGateConfig } from "./config.js";
|
|
2
2
|
import type { KbStore } from "./types.js";
|
|
3
|
-
/** The running kb engine: `
|
|
4
|
-
*
|
|
5
|
-
*
|
|
6
|
-
*
|
|
3
|
+
/** The running kb engine: `rowsHash` of the shipped `engine-fingerprint.json` (a digest of the
|
|
4
|
+
* row-producing sources only, so non-row edits do not force a reindex), read once per
|
|
5
|
+
* process; `null` when it cannot be read or lacks `rowsHash` (then no engine record is kept or
|
|
6
|
+
* required and no seed is accepted). `KB_ENGINE_FINGERPRINT` overrides it (test seam for child
|
|
7
|
+
* processes). See changes: add-kb-worktree-seed (D6), throttle-kb-reindex (D1). */
|
|
7
8
|
export declare function runningEngine(): string | null;
|
|
8
9
|
/** Test seam: pin the running engine (`undefined` re-reads the fingerprint file). */
|
|
9
10
|
export declare function setRunningEngineForTest(v: string | null | undefined): void;
|
package/dist/index-gate.js
CHANGED
|
@@ -11,10 +11,11 @@ const gateKey = (root) => `gate:${root}`;
|
|
|
11
11
|
const engineKey = (root) => `engine:${root}`;
|
|
12
12
|
const gateValue = (cfg) => `${SCHEMA_VERSION}:${indexOptionsHash(cfg)}`;
|
|
13
13
|
let engineCache;
|
|
14
|
-
/** The running kb engine: `
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
14
|
+
/** The running kb engine: `rowsHash` of the shipped `engine-fingerprint.json` (a digest of the
|
|
15
|
+
* row-producing sources only, so non-row edits do not force a reindex), read once per
|
|
16
|
+
* process; `null` when it cannot be read or lacks `rowsHash` (then no engine record is kept or
|
|
17
|
+
* required and no seed is accepted). `KB_ENGINE_FINGERPRINT` overrides it (test seam for child
|
|
18
|
+
* processes). See changes: add-kb-worktree-seed (D6), throttle-kb-reindex (D1). */
|
|
18
19
|
export function runningEngine() {
|
|
19
20
|
if (engineCache !== undefined)
|
|
20
21
|
return engineCache;
|
|
@@ -23,7 +24,7 @@ export function runningEngine() {
|
|
|
23
24
|
return (engineCache = env);
|
|
24
25
|
try {
|
|
25
26
|
const raw = JSON.parse(readFileSync(new URL("../engine-fingerprint.json", import.meta.url), "utf8"));
|
|
26
|
-
engineCache = typeof raw.
|
|
27
|
+
engineCache = typeof raw.rowsHash === "string" && raw.rowsHash ? raw.rowsHash : null;
|
|
27
28
|
}
|
|
28
29
|
catch {
|
|
29
30
|
engineCache = null;
|
package/dist/index.d.ts
CHANGED
|
@@ -14,8 +14,10 @@ export { createGitScope, GitScope } from "./git-scope/index.js";
|
|
|
14
14
|
export { beginForcedSource, runningEngine, sourceGateIsStale, stampPass, stampSource } from "./index-gate.js";
|
|
15
15
|
export type { AtomicIndexSource, InstallDeps, InstallResult, RunIndexAtomicOpts } from "./index-run.js";
|
|
16
16
|
export { BUILDING_LINE, installIndex, isFirstIndexLive, makeHeartbeat, runIndexAtomic, sweepOrphanTemps } from "./index-run.js";
|
|
17
|
+
export type { FetchResult, FetchRoot, FetchStore, RenderedFetch } from "./fetch-resolve.js";
|
|
18
|
+
export { buildFetchRoots, renderFetch, resolveFetch } from "./fetch-resolve.js";
|
|
17
19
|
export type { IndexOptions, IndexSource, IndexStats } from "./indexer.js";
|
|
18
|
-
export { headingNodeName, indexSource } from "./indexer.js";
|
|
20
|
+
export { headingNodeName, indexSource, KbIndexAborted } from "./indexer.js";
|
|
19
21
|
export type { InitOptions, InitResult } from "./init.js";
|
|
20
22
|
export { kbInit } from "./init.js";
|
|
21
23
|
export type { RenderOpts } from "./render.js";
|
package/dist/index.js
CHANGED
|
@@ -8,7 +8,8 @@ export { buildMeta, buildProperties, DEFAULT_FACET_KEYS, DEFAULT_SEARCHABLE_KEYS
|
|
|
8
8
|
export { createGitScope, GitScope } from "./git-scope/index.js";
|
|
9
9
|
export { beginForcedSource, runningEngine, sourceGateIsStale, stampPass, stampSource } from "./index-gate.js";
|
|
10
10
|
export { BUILDING_LINE, installIndex, isFirstIndexLive, makeHeartbeat, runIndexAtomic, sweepOrphanTemps } from "./index-run.js";
|
|
11
|
-
export {
|
|
11
|
+
export { buildFetchRoots, renderFetch, resolveFetch } from "./fetch-resolve.js";
|
|
12
|
+
export { headingNodeName, indexSource, KbIndexAborted } from "./indexer.js";
|
|
12
13
|
export { kbInit } from "./init.js";
|
|
13
14
|
export { renderHits } from "./render.js";
|
|
14
15
|
export { searchOptsFromConfig } from "./search-opts.js";
|
package/dist/indexer.d.ts
CHANGED
|
@@ -32,6 +32,21 @@ export interface IndexOptions {
|
|
|
32
32
|
* `beginForcedSource` uses it to clear the source's engine record atomically with the first
|
|
33
33
|
* rewritten rows. See change: add-kb-worktree-seed (D6). */
|
|
34
34
|
onFirstBatch?: () => void;
|
|
35
|
+
/** Stops the pass at the next file boundary by throwing `KbIndexAborted`; the open batch is
|
|
36
|
+
* rolled back, already-committed batches stay (a re-run is idempotent). Optional, additive.
|
|
37
|
+
* See change: throttle-kb-reindex (D3). */
|
|
38
|
+
signal?: AbortSignal;
|
|
39
|
+
/** Called once per committed batch (after the commit) with the source root and files done / walked
|
|
40
|
+
* total. Never fires for an empty source. Optional, additive. See change: throttle-kb-reindex (D3). */
|
|
41
|
+
onProgress?: (p: {
|
|
42
|
+
root: string;
|
|
43
|
+
done: number;
|
|
44
|
+
total: number;
|
|
45
|
+
}) => void;
|
|
46
|
+
}
|
|
47
|
+
/** Thrown by `indexSource` when `IndexOptions.signal` aborts the pass. Not a data error. */
|
|
48
|
+
export declare class KbIndexAborted extends Error {
|
|
49
|
+
constructor();
|
|
35
50
|
}
|
|
36
51
|
export interface IndexStats {
|
|
37
52
|
scanned: number;
|
|
@@ -41,6 +56,13 @@ export interface IndexStats {
|
|
|
41
56
|
parseFailures?: number;
|
|
42
57
|
missing?: boolean;
|
|
43
58
|
}
|
|
59
|
+
/** Wall-clock bound on one batch: also commit + yield once this many ms passed since the last
|
|
60
|
+
* yield, whichever of the count / time bound hits first. Per-file cost varies by orders of
|
|
61
|
+
* magnitude (a 100-file batch of large files pinned the loop for seconds), so the count alone
|
|
62
|
+
* cannot bound a blocked turn. One file's chunk + write stays the minimum unit — the check runs
|
|
63
|
+
* between files, never inside one. Same idiom as `WALK_YIELD_MAX_MS`.
|
|
64
|
+
* See change: throttle-kb-reindex (D2). */
|
|
65
|
+
export declare const INDEX_BATCH_MAX_MS = 50;
|
|
44
66
|
/** Directory entries (walk) / directories (gitignore pre-scan) processed between
|
|
45
67
|
* event-loop yields. One constant for both traversals. Bounds deep and broad
|
|
46
68
|
* trees, not a single huge directory (one `readdirSync` call).
|
package/dist/indexer.js
CHANGED
|
@@ -7,6 +7,13 @@ import { chunkAsciiDoc } from "./adoc-chunker.js";
|
|
|
7
7
|
import { chunkMarkdown } from "./chunker.js";
|
|
8
8
|
import { buildMeta, buildProperties, DEFAULT_FACET_KEYS, DEFAULT_SEARCHABLE_KEYS } from "./frontmatter.js";
|
|
9
9
|
import { loadGitignoreMatcherYielding } from "./gitignore.js";
|
|
10
|
+
/** Thrown by `indexSource` when `IndexOptions.signal` aborts the pass. Not a data error. */
|
|
11
|
+
export class KbIndexAborted extends Error {
|
|
12
|
+
constructor() {
|
|
13
|
+
super("kb index aborted");
|
|
14
|
+
this.name = "KbIndexAborted";
|
|
15
|
+
}
|
|
16
|
+
}
|
|
10
17
|
const sha = (s) => createHash("sha256").update(s).digest("hex");
|
|
11
18
|
const DEFAULT_EXCLUDE = /(^|\/)(node_modules|\.git|\.worktrees|dist|build|\.next|coverage|\.kb)(\/|$)/;
|
|
12
19
|
/** Selectable source extensions. Widened together with `config.ts` defaults and
|
|
@@ -25,6 +32,13 @@ const TITLE_EXT_RE = /\.(md|mdx|markdown|adoc|asciidoc)$/i;
|
|
|
25
32
|
* and would see no live progress. Committing per batch also releases the WAL
|
|
26
33
|
* write lock so the reader is served. See change: fix-kb-index-feedback. */
|
|
27
34
|
const YIELD_EVERY = 100;
|
|
35
|
+
/** Wall-clock bound on one batch: also commit + yield once this many ms passed since the last
|
|
36
|
+
* yield, whichever of the count / time bound hits first. Per-file cost varies by orders of
|
|
37
|
+
* magnitude (a 100-file batch of large files pinned the loop for seconds), so the count alone
|
|
38
|
+
* cannot bound a blocked turn. One file's chunk + write stays the minimum unit — the check runs
|
|
39
|
+
* between files, never inside one. Same idiom as `WALK_YIELD_MAX_MS`.
|
|
40
|
+
* See change: throttle-kb-reindex (D2). */
|
|
41
|
+
export const INDEX_BATCH_MAX_MS = 50;
|
|
28
42
|
const yieldToEventLoop = () => new Promise((r) => setImmediate(r));
|
|
29
43
|
/** Directory entries (walk) / directories (gitignore pre-scan) processed between
|
|
30
44
|
* event-loop yields. One constant for both traversals. Bounds deep and broad
|
|
@@ -124,6 +138,10 @@ export async function indexSource(store, src, opts = {}) {
|
|
|
124
138
|
return false;
|
|
125
139
|
return true;
|
|
126
140
|
});
|
|
141
|
+
// The walk awaits: a cancel that landed during it must stop the pass here — an empty file list never
|
|
142
|
+
// reaches the per-file check, so the deletion sweep below would otherwise run and report success.
|
|
143
|
+
if (opts.signal?.aborted)
|
|
144
|
+
throw new KbIndexAborted();
|
|
127
145
|
const stats = { scanned: files.length, changed: 0, deleted: 0, chunks: 0 };
|
|
128
146
|
const live = new Set();
|
|
129
147
|
// Batched transaction: commit + yield every YIELD_EVERY files so the walk does
|
|
@@ -132,6 +150,15 @@ export async function indexSource(store, src, opts = {}) {
|
|
|
132
150
|
// leaves earlier batches committed; a reindex is idempotent so a re-run
|
|
133
151
|
// completes it. See change: fix-kb-index-feedback.
|
|
134
152
|
let sinceYield = 0;
|
|
153
|
+
let lastYield = performance.now();
|
|
154
|
+
let done = 0; // files whose work started; reported to onProgress at each commit
|
|
155
|
+
let reported = 0;
|
|
156
|
+
const report = () => {
|
|
157
|
+
if (done > reported) {
|
|
158
|
+
reported = done;
|
|
159
|
+
opts.onProgress?.({ root: src.root, done, total: files.length });
|
|
160
|
+
}
|
|
161
|
+
};
|
|
135
162
|
// Rebuild the per-file chunk-rowid record when it may be stale (first pass of a
|
|
136
163
|
// connection, or another connection committed since); throws BEFORE any per-file
|
|
137
164
|
// delete. See change: fix-kb-index-integrity (D5).
|
|
@@ -142,14 +169,19 @@ export async function indexSource(store, src, opts = {}) {
|
|
|
142
169
|
// prior (consistent) state, a kill after leaves the hook's effect. See change: add-kb-worktree-seed (D6).
|
|
143
170
|
opts.onFirstBatch?.();
|
|
144
171
|
for (const abs of files) {
|
|
145
|
-
if (sinceYield >= YIELD_EVERY) {
|
|
172
|
+
if (sinceYield >= YIELD_EVERY || performance.now() - lastYield >= INDEX_BATCH_MAX_MS) {
|
|
146
173
|
store.commit();
|
|
174
|
+
report();
|
|
147
175
|
await yieldToEventLoop();
|
|
148
176
|
store.begin();
|
|
149
177
|
sinceYield = 0;
|
|
178
|
+
lastYield = performance.now();
|
|
150
179
|
}
|
|
151
180
|
sinceYield++;
|
|
181
|
+
done++;
|
|
152
182
|
opts.heartbeat?.();
|
|
183
|
+
if (opts.signal?.aborted)
|
|
184
|
+
throw new KbIndexAborted();
|
|
153
185
|
const rel = relative(src.dir, abs);
|
|
154
186
|
// A file that vanishes between the walk and its read is a deleted file, not a
|
|
155
187
|
// pass-aborting error: it stays out of the live set so the deletion sweep below
|
|
@@ -255,6 +287,7 @@ export async function indexSource(store, src, opts = {}) {
|
|
|
255
287
|
// Path-less nodes (placeholders, tags) that no edge references any more.
|
|
256
288
|
store.sweepPlaceholders?.();
|
|
257
289
|
store.commit();
|
|
290
|
+
report();
|
|
258
291
|
}
|
|
259
292
|
catch (err) {
|
|
260
293
|
store.rollback();
|
package/dist/sources.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type SourceConfig } from "./config.js";
|
|
2
2
|
import { type LookupAll } from "./net-guard.js";
|
|
3
3
|
/** Thrown when a remote source has no trust record (and none was granted). Classifiable by callers. */
|
|
4
4
|
export declare class KbUntrustedSourceError extends Error {
|
|
@@ -18,6 +18,9 @@ export interface ResolveCtx {
|
|
|
18
18
|
cacheDir: string;
|
|
19
19
|
refresh?: boolean;
|
|
20
20
|
promptTrust?: (s: SourceConfig) => Promise<boolean>;
|
|
21
|
+
/** Indexable extensions for the https plain-file content check (default:
|
|
22
|
+
* `DEFAULTS.extensions`). Matched case-insensitively. */
|
|
23
|
+
extensions?: string[];
|
|
21
24
|
/** Test seams only (change: harden-untrusted-content-ingestion). Never set in production. */
|
|
22
25
|
testHooks?: {
|
|
23
26
|
/** Replaces `guardedFetch` for the https resolver. */
|
|
@@ -39,7 +42,9 @@ export interface SourceResolver {
|
|
|
39
42
|
kind: KbSourceKind;
|
|
40
43
|
resolve(spec: SourceConfig, ctx: ResolveCtx): Promise<ResolvedSource>;
|
|
41
44
|
}
|
|
42
|
-
/** Classify a ref string (mirrors parseSourceKind).
|
|
45
|
+
/** Classify a ref string (mirrors parseSourceKind). GitHub repo refs and
|
|
46
|
+
* `ssh://` URLs clone (`git`); direct file / archive / other GitHub URLs stay
|
|
47
|
+
* `https` and are content-checked there. */
|
|
43
48
|
export declare function classifyRef(ref: string): KbSourceKind;
|
|
44
49
|
/** Dedup identity (mirrors computeIdentity). cwd resolves relative paths. */
|
|
45
50
|
export declare function sourceIdentity(spec: SourceConfig, cwd?: string): string;
|
package/dist/sources.js
CHANGED
|
@@ -11,9 +11,10 @@ import { createHash, randomUUID } from "node:crypto";
|
|
|
11
11
|
import { existsSync, mkdirSync, mkdtempSync, readdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
12
12
|
import { isIP } from "node:net";
|
|
13
13
|
import { homedir } from "node:os";
|
|
14
|
-
import { basename, dirname, isAbsolute, join, resolve } from "node:path";
|
|
14
|
+
import { basename, dirname, extname, isAbsolute, join, resolve } from "node:path";
|
|
15
15
|
import { promisify } from "node:util";
|
|
16
16
|
import { extractArchiveSafely } from "./archive-guard.js";
|
|
17
|
+
import { DEFAULTS } from "./config.js";
|
|
17
18
|
import { assertPublicHost, guardedFetch } from "./net-guard.js";
|
|
18
19
|
import { isTrusted, recordTrust } from "./trust.js";
|
|
19
20
|
const execFileAsync = promisify(execFile);
|
|
@@ -29,13 +30,23 @@ export class KbUntrustedSourceError extends Error {
|
|
|
29
30
|
this.name = "KbUntrustedSourceError";
|
|
30
31
|
}
|
|
31
32
|
}
|
|
32
|
-
/**
|
|
33
|
+
/** A GitHub REPOSITORY ref: `[https://]github.com/<o>/<r>` with an optional
|
|
34
|
+
* `.git`, `@<ref>`, or `/tree/<ref>[/…]` suffix. Any other github.com path
|
|
35
|
+
* (blob/raw/archive/issues/pull/wiki/…) is not a repo. Groups: owner, repo,
|
|
36
|
+
* `.git`, `@ref`, tree ref. See change: fix-kb-get-roots-and-guard (D7). */
|
|
37
|
+
const GITHUB_REPO = /^(?:https:\/\/)?(?:www\.)?github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(\.git)?(?:@([^/@:\s]+)|\/tree\/([^/\s]+)(?:\/.*)?)?\/?$/;
|
|
38
|
+
const GITHUB_ANY = /^(?:https?:\/\/)?(?:www\.)?github\.com\//;
|
|
39
|
+
/** Classify a ref string (mirrors parseSourceKind). GitHub repo refs and
|
|
40
|
+
* `ssh://` URLs clone (`git`); direct file / archive / other GitHub URLs stay
|
|
41
|
+
* `https` and are content-checked there. */
|
|
33
42
|
export function classifyRef(ref) {
|
|
34
43
|
if (ref.startsWith("npm:"))
|
|
35
44
|
return "npm";
|
|
36
|
-
if (ref.startsWith("git:") || ref.startsWith("git@"))
|
|
45
|
+
if (ref.startsWith("git:") || ref.startsWith("git@") || ref.startsWith("ssh://"))
|
|
37
46
|
return "git";
|
|
38
|
-
if (
|
|
47
|
+
if (GITHUB_REPO.test(ref))
|
|
48
|
+
return "git";
|
|
49
|
+
if (GITHUB_ANY.test(ref) || /^https?:\/\//.test(ref))
|
|
39
50
|
return "https";
|
|
40
51
|
return "filesystem";
|
|
41
52
|
}
|
|
@@ -121,6 +132,11 @@ function gitUrlOf(spec) {
|
|
|
121
132
|
const ref = spec.ref.startsWith("git:") ? spec.ref.slice(4) : spec.ref;
|
|
122
133
|
if (ref.startsWith("git@"))
|
|
123
134
|
return ref;
|
|
135
|
+
// GitHub repo: clone the bare repo URL (revision suffixes are not part of it;
|
|
136
|
+
// an existing `.git` spelling is kept so cached clones' origins still match).
|
|
137
|
+
const gh = GITHUB_REPO.exec(ref);
|
|
138
|
+
if (gh)
|
|
139
|
+
return `https://github.com/${gh[1]}/${gh[2]}${gh[3] ?? ""}`;
|
|
124
140
|
if (/^github\.com\//.test(ref))
|
|
125
141
|
return `https://${ref}`;
|
|
126
142
|
if (!/^[a-z]+:\/\//.test(ref))
|
|
@@ -130,6 +146,9 @@ function gitUrlOf(spec) {
|
|
|
130
146
|
function gitRefOf(spec) {
|
|
131
147
|
if (spec.pin)
|
|
132
148
|
return spec.pin;
|
|
149
|
+
const gh = GITHUB_REPO.exec(spec.ref.startsWith("git:") ? spec.ref.slice(4) : spec.ref);
|
|
150
|
+
if (gh)
|
|
151
|
+
return gh[4] ?? gh[5];
|
|
133
152
|
const ref = spec.ref;
|
|
134
153
|
if (!ref.startsWith("git@")) {
|
|
135
154
|
const lastAt = ref.lastIndexOf("@");
|
|
@@ -261,6 +280,37 @@ function plainFileName(pathname) {
|
|
|
261
280
|
name = name.replace(/[\x00-\x1f\x7f\\/:]/g, "_");
|
|
262
281
|
return name === "" || name === "." || name === ".." ? "index.md" : name;
|
|
263
282
|
}
|
|
283
|
+
/** Body sniffs as an HTML document (after BOM / whitespace / HTML comments). */
|
|
284
|
+
function looksLikeHtml(body) {
|
|
285
|
+
let head = body.subarray(0, 4096).toString("utf8").replace(/^\uFEFF/, "");
|
|
286
|
+
for (;;) {
|
|
287
|
+
head = head.trimStart();
|
|
288
|
+
if (!head.startsWith("<!--"))
|
|
289
|
+
break;
|
|
290
|
+
const end = head.indexOf("-->");
|
|
291
|
+
if (end < 0)
|
|
292
|
+
return false;
|
|
293
|
+
head = head.slice(end + 3);
|
|
294
|
+
}
|
|
295
|
+
return /^<(!doctype\s+html|html[\s>])/i.test(head);
|
|
296
|
+
}
|
|
297
|
+
/** Reject a plain https fetch that would index nothing (HTML page or no
|
|
298
|
+
* indexable extension). Throws BEFORE the cache swap, so `dest` and its fetch
|
|
299
|
+
* marker survive. See change: fix-kb-get-roots-and-guard (D8). */
|
|
300
|
+
function assertIndexableBody(ref, url, name, body, extensions) {
|
|
301
|
+
const ext = extname(name).toLowerCase();
|
|
302
|
+
const indexable = extensions.some((e) => e.toLowerCase() === ext);
|
|
303
|
+
const html = looksLikeHtml(body);
|
|
304
|
+
if (indexable && !html)
|
|
305
|
+
return;
|
|
306
|
+
const gh = /^(?:www\.)?github\.com$/i.test(url.hostname) ? /^\/([^/]+)\/([^/]+)\/blob\/(.+)$/.exec(url.pathname) : null;
|
|
307
|
+
const hint = gh
|
|
308
|
+
? ` — use the raw file URL https://raw.githubusercontent.com/${gh[1]}/${gh[2]}/${gh[3]}`
|
|
309
|
+
: html
|
|
310
|
+
? ' — it is an HTML page; for a repository use kind: "git"'
|
|
311
|
+
: ` — the saved file ${JSON.stringify(name)} has no indexable extension (${extensions.join(", ")}); for a repository use kind: "git"`;
|
|
312
|
+
throw new Error(`https source ${ref} yields nothing indexable${hint}`);
|
|
313
|
+
}
|
|
264
314
|
/**
|
|
265
315
|
* Lock-free, single-winner cache swap (review: concurrent refreshes).
|
|
266
316
|
*
|
|
@@ -371,7 +421,9 @@ export const httpsResolver = {
|
|
|
371
421
|
await extractArchiveSafely(kind, archive, out, hooks.archiveLimits);
|
|
372
422
|
}
|
|
373
423
|
else {
|
|
374
|
-
|
|
424
|
+
const name = plainFileName(url.pathname);
|
|
425
|
+
assertIndexableBody(spec.ref, url, name, body, ctx.extensions ?? DEFAULTS.extensions);
|
|
426
|
+
writeFileSync(join(out, name), body);
|
|
375
427
|
}
|
|
376
428
|
writeFileSync(join(out, ".fetched"), String(Date.now()));
|
|
377
429
|
swapInto(dest, out, hooks.rename ?? renameSync);
|