@blackbelt-technology/pi-dashboard-kb 0.8.0 → 0.10.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 +46 -0
- package/bin/kb.mjs +89 -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 +53 -5
- package/dist/cli.js +140 -37
- package/dist/config.d.ts +80 -0
- package/dist/config.js +157 -6
- package/dist/dox-row.d.ts +9 -0
- package/dist/dox-row.js +32 -0
- package/dist/dox-triage.d.ts +3 -3
- package/dist/dox-triage.js +22 -15
- package/dist/dox.d.ts +45 -6
- package/dist/dox.js +236 -94
- package/dist/eval.d.ts +24 -0
- package/dist/eval.js +106 -13
- package/dist/git-scope/commits.d.ts +26 -0
- package/dist/git-scope/commits.js +243 -0
- package/dist/git-scope/deps.d.ts +41 -0
- package/dist/git-scope/deps.js +78 -0
- package/dist/git-scope/forge/cli.d.ts +16 -0
- package/dist/git-scope/forge/cli.js +66 -0
- package/dist/git-scope/forge/gitea.d.ts +15 -0
- package/dist/git-scope/forge/gitea.js +98 -0
- package/dist/git-scope/forge/github.d.ts +8 -0
- package/dist/git-scope/forge/github.js +50 -0
- package/dist/git-scope/forge/gitlab.d.ts +8 -0
- package/dist/git-scope/forge/gitlab.js +49 -0
- package/dist/git-scope/forge/index.d.ts +7 -0
- package/dist/git-scope/forge/index.js +13 -0
- package/dist/git-scope/forge/types.d.ts +70 -0
- package/dist/git-scope/forge/types.js +21 -0
- package/dist/git-scope/index.d.ts +4 -0
- package/dist/git-scope/index.js +2 -0
- package/dist/git-scope/lease.d.ts +24 -0
- package/dist/git-scope/lease.js +80 -0
- package/dist/git-scope/links.d.ts +23 -0
- package/dist/git-scope/links.js +61 -0
- package/dist/git-scope/repo.d.ts +36 -0
- package/dist/git-scope/repo.js +99 -0
- package/dist/git-scope/scope.d.ts +78 -0
- package/dist/git-scope/scope.js +406 -0
- package/dist/git-scope/store.d.ts +16 -0
- package/dist/git-scope/store.js +71 -0
- package/dist/git-scope/sync.d.ts +44 -0
- package/dist/git-scope/sync.js +215 -0
- package/dist/gitignore.d.ts +37 -0
- package/dist/gitignore.js +267 -0
- package/dist/index-gate.d.ts +27 -0
- package/dist/index-gate.js +71 -0
- package/dist/index-run.d.ts +66 -5
- package/dist/index-run.js +317 -60
- package/dist/index.d.ts +33 -18
- package/dist/index.js +22 -9
- package/dist/indexer.d.ts +29 -0
- package/dist/indexer.js +100 -15
- package/dist/migrate-file-index.js +4 -4
- package/dist/migrate-runner.js +7 -5
- package/dist/net-guard.d.ts +35 -0
- package/dist/net-guard.js +285 -0
- package/dist/render.js +18 -0
- package/dist/search-opts.d.ts +22 -0
- package/dist/search-opts.js +21 -0
- package/dist/seed.d.ts +59 -0
- package/dist/seed.js +235 -0
- package/dist/sources.d.ts +29 -0
- package/dist/sources.js +230 -32
- package/dist/sqlite-store.d.ts +111 -8
- package/dist/sqlite-store.js +412 -56
- 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 +81 -0
- package/dist/verdict.d.ts +53 -0
- package/dist/verdict.js +377 -0
- package/engine-fingerprint.json +5 -0
- package/package.json +6 -4
- package/src/adoc-chunker.ts +308 -0
- package/src/archive-guard.ts +144 -0
- package/src/chunker.ts +51 -5
- package/src/cli.ts +137 -37
- package/src/config.ts +199 -6
- package/src/dox-row.ts +35 -0
- package/src/dox-triage.ts +24 -16
- package/src/dox.ts +259 -68
- package/src/eval.ts +117 -14
- package/src/git-scope/commits.ts +267 -0
- package/src/git-scope/deps.ts +111 -0
- package/src/git-scope/forge/cli.ts +76 -0
- package/src/git-scope/forge/gitea.ts +124 -0
- package/src/git-scope/forge/github.ts +73 -0
- package/src/git-scope/forge/gitlab.ts +71 -0
- package/src/git-scope/forge/index.ts +17 -0
- package/src/git-scope/forge/types.ts +88 -0
- package/src/git-scope/index.ts +6 -0
- package/src/git-scope/lease.ts +80 -0
- package/src/git-scope/links.ts +73 -0
- package/src/git-scope/repo.ts +108 -0
- package/src/git-scope/scope.ts +424 -0
- package/src/git-scope/store.ts +73 -0
- package/src/git-scope/sync.ts +240 -0
- package/src/gitignore.ts +282 -0
- package/src/index-gate.ts +73 -0
- package/src/index-run.ts +362 -58
- package/src/index.ts +52 -20
- package/src/indexer.ts +120 -14
- package/src/migrate-file-index.ts +4 -4
- package/src/migrate-runner.ts +6 -4
- package/src/net-guard.ts +288 -0
- package/src/node-sqlite.d.ts +9 -0
- package/src/render.ts +17 -1
- package/src/search-opts.ts +52 -0
- package/src/seed.ts +249 -0
- package/src/sources.ts +235 -28
- package/src/sqlite-store.ts +404 -55
- package/src/staleness.ts +76 -0
- package/src/trust.ts +81 -8
- package/src/types.ts +86 -1
- package/src/verdict.ts +426 -0
package/README.md
CHANGED
|
@@ -18,6 +18,52 @@ 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
|
+
## Evaluate retrieval (kb eval)
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
kb eval --golden golden.json [--limit N] [--doc-type doc|agents|source-md]
|
|
25
|
+
[--allow-zero] [--verbose] [--json]
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
`--golden` accepts two fixture shapes:
|
|
29
|
+
|
|
30
|
+
- a **bare array** of `{"q": "...", "expect": "path-substring"}` items;
|
|
31
|
+
- an **object with an `items` array** (the bundled `eval/golden.*-intent.json`
|
|
32
|
+
shape — its `intent`/`minedAt` provenance prints a stderr run header).
|
|
33
|
+
|
|
34
|
+
Anything else — including `eval/golden.provenance.json`, which is mining
|
|
35
|
+
metadata, not a fixture — is rejected with a diagnostic naming both accepted
|
|
36
|
+
shapes. Items must carry string `q` and `expect`; a bad item names the file and
|
|
37
|
+
array index instead of silently scoring zero.
|
|
38
|
+
|
|
39
|
+
Scoring normalizes repo-relative `expect` values against the configured roots:
|
|
40
|
+
an `expect` of `packages/foo/AGENTS.md` matches the indexed path
|
|
41
|
+
`foo/AGENTS.md` (longest prefix wins, separator-checked, so `packages` never
|
|
42
|
+
strips against `packages-x/`). Items whose `expect` lies under a directory no
|
|
43
|
+
root can reach are counted in the `unreachable` metric — reported, never
|
|
44
|
+
searched, excluded from every other metric (`n + unreachable` always sums to
|
|
45
|
+
the fixture size). Pass `--verbose` to list the unreachable paths on stderr.
|
|
46
|
+
|
|
47
|
+
A **vacuous run fails loudly**: zero scored items or zero recall exits non-zero
|
|
48
|
+
with a stderr diagnostic (an all-zero score is far more often a harness fault
|
|
49
|
+
than a retrieval fault), while still printing the metrics JSON on stdout.
|
|
50
|
+
Pass `--allow-zero` to measure a deliberately broken setup anyway.
|
|
51
|
+
|
|
52
|
+
`kb eval` scores the same `SearchOpts` the `kb_search` tool passes — both are
|
|
53
|
+
built by one shared `searchOptsFromConfig` helper.
|
|
54
|
+
|
|
55
|
+
## Engine freshness
|
|
56
|
+
|
|
57
|
+
The `kb` bin runs `bin/kb.mjs`, a committed shim. In a **development checkout**
|
|
58
|
+
it checks `engine-fingerprint.json` (committed by `npm run build`) against the
|
|
59
|
+
working tree and rebuilds stale source automatically, so the bin and the
|
|
60
|
+
extension always run the same engine. In an **installed package** a fingerprint
|
|
61
|
+
mismatch cannot self-heal: it is detected and printed as a loud warning while
|
|
62
|
+
the shipped `dist` runs unchanged, a malformed fingerprint hard-errors, and a
|
|
63
|
+
missing `dist` hard-errors. CI enforces commit discipline via
|
|
64
|
+
`scripts/check-kb-dist-fresh.mjs`, so the engines can only diverge if someone
|
|
65
|
+
edits `src` without rebuilding AND ignores CI.
|
|
66
|
+
|
|
21
67
|
## License
|
|
22
68
|
|
|
23
69
|
MIT — part of [pi-agent-dashboard](https://github.com/BlackBeltTechnology/pi-agent-dashboard).
|
package/bin/kb.mjs
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawnSync } from "node:child_process";
|
|
3
|
+
// Committed, NEVER-BUILT plain-JS bin shim (design D1,
|
|
4
|
+
// change fix-kb-eval-measurement-integrity). The old bin pointed straight at
|
|
5
|
+
// dist/cli.js — a tsc artifact that is gitignored and only rebuilt by hand, so
|
|
6
|
+
// the `kb` CLI silently ran a week-old engine while the kb_search tool ran the
|
|
7
|
+
// working tree. This shim makes the divergence impossible to miss:
|
|
8
|
+
//
|
|
9
|
+
// fingerprint present + srcHash/tsconfigHash/distHash all match
|
|
10
|
+
// → import dist/cli.js (silent, the hot path);
|
|
11
|
+
// mismatch / missing fingerprint in a dev checkout (tsconfig.json resolvable)
|
|
12
|
+
// → rebuild via the nearest typescript install, refresh the fingerprint,
|
|
13
|
+
// import;
|
|
14
|
+
// mismatch in an installed package (no tsconfig — the tarball ships src + the
|
|
15
|
+
// fingerprint but not the tsconfig chain)
|
|
16
|
+
// → loud stderr warning, import dist/cli.js unchanged;
|
|
17
|
+
// dist/cli.js missing in an installed package
|
|
18
|
+
// → hard error naming the divergence.
|
|
19
|
+
import { existsSync } from "node:fs";
|
|
20
|
+
import { dirname, join, resolve } from "node:path";
|
|
21
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
22
|
+
import { computeDistHash, computeSrcHash, computeTsconfigHash, FINGERPRINT_MALFORMED, readCommittedFingerprint, writeFingerprint } from "./lib/engine-fingerprint.mjs";
|
|
23
|
+
|
|
24
|
+
const pkgRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
|
25
|
+
const distCli = join(pkgRoot, "dist", "cli.js");
|
|
26
|
+
|
|
27
|
+
/** The compiler entry to spawn: the repo's TypeScript 7 wrapper
|
|
28
|
+
* (`<repo>/scripts/tsc7.mjs`, found walking up) when present, else the nearest
|
|
29
|
+
* `node_modules/typescript/lib/tsc.js` (the published kb tarball has no repo
|
|
30
|
+
* `scripts/`). See change: migrate-typecheck-to-ts7. */
|
|
31
|
+
function findTsc() {
|
|
32
|
+
const walkUp = (rel) => {
|
|
33
|
+
for (let d = pkgRoot; ; d = dirname(d)) {
|
|
34
|
+
const c = join(d, ...rel);
|
|
35
|
+
if (existsSync(c)) return c;
|
|
36
|
+
if (d === dirname(d)) return null; // filesystem root
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
return walkUp(["scripts", "tsc7.mjs"]) ?? walkUp(["node_modules", "typescript", "lib", "tsc.js"]);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function staleness() {
|
|
43
|
+
const fp = readCommittedFingerprint(pkgRoot);
|
|
44
|
+
if (fp === FINGERPRINT_MALFORMED) return "engine-fingerprint.json is malformed";
|
|
45
|
+
if (!fp) return "engine-fingerprint.json missing";
|
|
46
|
+
if (computeSrcHash(pkgRoot) !== fp.srcHash) return "src changed since the last build";
|
|
47
|
+
const tscHash = computeTsconfigHash(pkgRoot);
|
|
48
|
+
// An incomplete fingerprint is treated as mismatched, never as fresh: a
|
|
49
|
+
// record that omits tsconfigHash/distHash must not skip those comparisons.
|
|
50
|
+
if (tscHash !== null && (typeof fp.tsconfigHash !== "string" || tscHash !== fp.tsconfigHash)) return "tsconfig changed since the last build";
|
|
51
|
+
const distHash = computeDistHash(pkgRoot);
|
|
52
|
+
if (distHash !== null && (typeof fp.distHash !== "string" || distHash !== fp.distHash)) return "dist is not the committed emit";
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const hasTsconfig = existsSync(join(pkgRoot, "tsconfig.json"));
|
|
57
|
+
const stale = staleness();
|
|
58
|
+
|
|
59
|
+
if (!stale && existsSync(distCli)) {
|
|
60
|
+
await import(pathToFileURL(distCli).href);
|
|
61
|
+
} else if (hasTsconfig) {
|
|
62
|
+
// Dev checkout: rebuild (tsc incremental is sub-second) + refresh fingerprint.
|
|
63
|
+
const tsc = findTsc();
|
|
64
|
+
if (!tsc) {
|
|
65
|
+
console.error(`[kb] stale engine (${stale}) but no typescript install found walking up from ${pkgRoot} — run \`npm run build\` in packages/kb`);
|
|
66
|
+
process.exit(1);
|
|
67
|
+
}
|
|
68
|
+
const r = spawnSync(process.execPath, [tsc, "-p", join(pkgRoot, "tsconfig.json")], { stdio: "inherit" });
|
|
69
|
+
if (r.status !== 0) {
|
|
70
|
+
console.error("[kb] rebuild failed — see tsc output above");
|
|
71
|
+
process.exit(r.status ?? 1);
|
|
72
|
+
}
|
|
73
|
+
writeFingerprint(pkgRoot); // truthful: the tree WAS stale; self-heals on the next commit-with-build
|
|
74
|
+
await import(pathToFileURL(distCli).href);
|
|
75
|
+
} else if (stale === "engine-fingerprint.json is malformed") {
|
|
76
|
+
// Fail closed: a corrupt fingerprint is not evidence of freshness, and in an
|
|
77
|
+
// installed package it cannot self-heal. Repo convention — unparseable JSON
|
|
78
|
+
// fails closed, never warns-and-continues.
|
|
79
|
+
console.error(`[kb] ERROR: ${stale} — refusing to guess engine freshness. The kb bin and the extension would run different engines. Reinstall @blackbelt-technology/pi-dashboard-kb.`);
|
|
80
|
+
process.exit(1);
|
|
81
|
+
} else if (existsSync(distCli)) {
|
|
82
|
+
// Installed package: prepublishOnly built the tarball, so a mismatch means
|
|
83
|
+
// post-install tampering — loud, not fatal; only fires on actual mismatch.
|
|
84
|
+
console.error(`[kb] WARNING: engine fingerprint mismatch (${stale}) — running the shipped dist unchanged. The kb bin and the extension would run different engines; reinstall the package.`);
|
|
85
|
+
await import(pathToFileURL(distCli).href);
|
|
86
|
+
} else {
|
|
87
|
+
console.error(`[kb] ERROR: ${stale ?? "dist missing"} and dist/cli.js is absent with no tsconfig to rebuild — the kb bin and the extension would run different engines. Reinstall @blackbelt-technology/pi-dashboard-kb.`);
|
|
88
|
+
process.exit(1);
|
|
89
|
+
}
|
|
@@ -0,0 +1,183 @@
|
|
|
1
|
+
// Engine fingerprint for @blackbelt-technology/pi-dashboard-kb (design D1,
|
|
2
|
+
// change fix-kb-eval-measurement-integrity). ONE shared, dependency-free
|
|
3
|
+
// module: `npm run build` writes the committed engine-fingerprint.json with it,
|
|
4
|
+
// the bin shim (bin/kb.mjs) re-checks staleness with it, and the CI freshness
|
|
5
|
+
// gate (scripts/check-kb-dist-fresh.mjs) recomputes with it — no three-way
|
|
6
|
+
// reimplementation.
|
|
7
|
+
//
|
|
8
|
+
// Three hashes:
|
|
9
|
+
// srcHash — LF-normalized contents of src/**/*.ts minus src/__tests__,
|
|
10
|
+
// sorted relative paths (a src edit without a rebuild forks
|
|
11
|
+
// the hash → observable in CI).
|
|
12
|
+
// tsconfigHash — LF-normalized contents of the tsconfig extends chain (a
|
|
13
|
+
// compilerOptions change alters emit without changing src).
|
|
14
|
+
// distHash — the emitted dist/** (proves the dist on disk is a complete
|
|
15
|
+
// emit, catching fresh-src-over-stale-dist from an interrupted
|
|
16
|
+
// build).
|
|
17
|
+
// LF normalization because the repo has no .gitattributes and CI runs Windows
|
|
18
|
+
// jobs where autocrlf would otherwise fork the hash.
|
|
19
|
+
import { createHash } from "node:crypto";
|
|
20
|
+
import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
21
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
22
|
+
import { fileURLToPath } from "node:url";
|
|
23
|
+
|
|
24
|
+
const LF = (s) => s.replace(/\r\n/g, "\n");
|
|
25
|
+
|
|
26
|
+
/** Recursively collect files under `dir` (posix relative paths, sorted). */
|
|
27
|
+
function walk(dir, prefix = "") {
|
|
28
|
+
const out = [];
|
|
29
|
+
if (!existsSync(dir)) return out;
|
|
30
|
+
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
|
31
|
+
const rel = prefix ? `${prefix}/${e.name}` : e.name;
|
|
32
|
+
if (e.isDirectory()) out.push(...walk(join(dir, e.name), rel));
|
|
33
|
+
else if (e.isFile()) out.push(rel);
|
|
34
|
+
}
|
|
35
|
+
return out.sort();
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function hashFiles(pkgRoot, rels) {
|
|
39
|
+
const h = createHash("sha256");
|
|
40
|
+
for (const rel of rels) {
|
|
41
|
+
h.update(rel);
|
|
42
|
+
h.update("\u0000");
|
|
43
|
+
h.update(LF(readFileSync(join(pkgRoot, rel), "utf8")));
|
|
44
|
+
h.update("\u0001");
|
|
45
|
+
}
|
|
46
|
+
return h.digest("hex");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** All .ts under src/, excluding any __tests__ dir (and this bin lib — plain
|
|
50
|
+
* JS, never matched). Sorted by path so creation order cannot fork the hash. */
|
|
51
|
+
export function computeSrcHash(pkgRoot) {
|
|
52
|
+
const srcDir = join(pkgRoot, "src");
|
|
53
|
+
const rels = walk(srcDir)
|
|
54
|
+
.filter((rel) => rel.endsWith(".ts") && !rel.split("/").includes("__tests__"))
|
|
55
|
+
.map((rel) => `src/${rel}`);
|
|
56
|
+
return hashFiles(pkgRoot, rels);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** The tsconfig extends chain (root first, then each resolved extends target).
|
|
60
|
+
* Only relative extends targets are followed — a package-spec extends target
|
|
61
|
+
* cannot resolve reliably without a module resolver and this package has none. */
|
|
62
|
+
/** Strip JSONC comments (// and /* *) and trailing commas, STRING-AWARE:
|
|
63
|
+
* a `//` or `,}` inside a string literal must survive. Single pass, no deps. */
|
|
64
|
+
function stripJsonc(raw) {
|
|
65
|
+
let out = "";
|
|
66
|
+
let inString = false;
|
|
67
|
+
for (let i = 0; i < raw.length; i++) {
|
|
68
|
+
const c = raw[i];
|
|
69
|
+
if (inString) {
|
|
70
|
+
out += c;
|
|
71
|
+
if (c === "\\") {
|
|
72
|
+
out += raw[i + 1] ?? ""; // preserve escaped char verbatim
|
|
73
|
+
i++;
|
|
74
|
+
} else if (c === '"') inString = false;
|
|
75
|
+
continue;
|
|
76
|
+
}
|
|
77
|
+
if (c === '"') {
|
|
78
|
+
inString = true;
|
|
79
|
+
out += c;
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (c === "/" && raw[i + 1] === "/") {
|
|
83
|
+
while (i < raw.length && raw[i] !== "\n") i++; // skip to EOL (newline kept)
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
if (c === "/" && raw[i + 1] === "*") {
|
|
87
|
+
i += 2;
|
|
88
|
+
while (i < raw.length && !(raw[i] === "*" && raw[i + 1] === "/")) i++;
|
|
89
|
+
i++; // skip the closing "/" of "*/" (loop's i++ adds the rest)
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (c === ",") {
|
|
93
|
+
// trailing comma: drop when the next non-whitespace char closes a block
|
|
94
|
+
let j = i + 1;
|
|
95
|
+
while (j < raw.length && /\s/.test(raw[j])) j++;
|
|
96
|
+
if (raw[j] === "}" || raw[j] === "]") continue;
|
|
97
|
+
}
|
|
98
|
+
out += c;
|
|
99
|
+
}
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
export function tsconfigChain(pkgRoot) {
|
|
104
|
+
const chain = [];
|
|
105
|
+
let cur = join(pkgRoot, "tsconfig.json");
|
|
106
|
+
const seen = new Set();
|
|
107
|
+
while (existsSync(cur) && !seen.has(cur)) {
|
|
108
|
+
seen.add(cur);
|
|
109
|
+
chain.push(cur);
|
|
110
|
+
let m;
|
|
111
|
+
try {
|
|
112
|
+
m = JSON.parse(stripJsonc(readFileSync(cur, "utf8")));
|
|
113
|
+
} catch {
|
|
114
|
+
break; // unparseable config: hash what exists, stop following
|
|
115
|
+
}
|
|
116
|
+
const ext = m && m.extends;
|
|
117
|
+
if (typeof ext !== "string" || ext.startsWith("$")) break;
|
|
118
|
+
cur = resolve(dirname(cur), ext);
|
|
119
|
+
if (!cur.endsWith(".json")) cur += ".json";
|
|
120
|
+
}
|
|
121
|
+
return chain;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** null = no tsconfig at the package root (the installed-tarball shape). */
|
|
125
|
+
export function computeTsconfigHash(pkgRoot) {
|
|
126
|
+
const chain = tsconfigChain(pkgRoot);
|
|
127
|
+
if (!chain.length) return null;
|
|
128
|
+
return hashFiles(pkgRoot, chain.map((p) => relative(pkgRoot, p)));
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** null = no dist on disk. */
|
|
132
|
+
export function computeDistHash(pkgRoot) {
|
|
133
|
+
const distDir = join(pkgRoot, "dist");
|
|
134
|
+
if (!existsSync(distDir)) return null;
|
|
135
|
+
return hashFiles(pkgRoot, walk(distDir).map((rel) => `dist/${rel}`));
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function fingerprintPackage(pkgRoot) {
|
|
139
|
+
return {
|
|
140
|
+
srcHash: computeSrcHash(pkgRoot),
|
|
141
|
+
tsconfigHash: computeTsconfigHash(pkgRoot),
|
|
142
|
+
distHash: computeDistHash(pkgRoot),
|
|
143
|
+
};
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export const FINGERPRINT_FILE = "engine-fingerprint.json";
|
|
147
|
+
|
|
148
|
+
/** Sentinel returned by readCommittedFingerprint when the file exists but is
|
|
149
|
+
* not valid JSON — distinct from missing, so consumers can FAIL CLOSED
|
|
150
|
+
* (unparseable JSON must never look like a clean fingerprint). */
|
|
151
|
+
export const FINGERPRINT_MALFORMED = { malformed: true };
|
|
152
|
+
|
|
153
|
+
export function readCommittedFingerprint(pkgRoot) {
|
|
154
|
+
const p = join(pkgRoot, FINGERPRINT_FILE);
|
|
155
|
+
if (!existsSync(p)) return null;
|
|
156
|
+
try {
|
|
157
|
+
return JSON.parse(readFileSync(p, "utf8"));
|
|
158
|
+
} catch {
|
|
159
|
+
return FINGERPRINT_MALFORMED; // unparseable JSON fails closed, never null-as-missing
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Compute + write engine-fingerprint.json (committed; npm `files` ships it). */
|
|
164
|
+
export function writeFingerprint(pkgRoot) {
|
|
165
|
+
const fp = fingerprintPackage(pkgRoot);
|
|
166
|
+
writeFileSync(join(pkgRoot, FINGERPRINT_FILE), JSON.stringify(fp, null, 2) + "\n");
|
|
167
|
+
return fp;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// CLI mode (used by `npm run build` and the sandbox tests):
|
|
171
|
+
// node bin/lib/engine-fingerprint.mjs [--write] [pkgRoot=.]
|
|
172
|
+
const isMain = process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url);
|
|
173
|
+
if (isMain) {
|
|
174
|
+
const args = process.argv.slice(2).filter((a) => !a.startsWith("-"));
|
|
175
|
+
const pkgRoot = resolve(args[0] ?? ".");
|
|
176
|
+
if (process.argv.includes("--write")) {
|
|
177
|
+
const fp = writeFingerprint(pkgRoot);
|
|
178
|
+
console.log(`wrote ${join(pkgRoot, FINGERPRINT_FILE)}`);
|
|
179
|
+
console.log(JSON.stringify(fp));
|
|
180
|
+
} else {
|
|
181
|
+
console.log(JSON.stringify(fingerprintPackage(pkgRoot)));
|
|
182
|
+
}
|
|
183
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { FmValue } from "./frontmatter.js";
|
|
2
|
+
import type { Chunk, DocType } from "./types.js";
|
|
3
|
+
export interface AdocChunkInput {
|
|
4
|
+
root: string;
|
|
5
|
+
path: string;
|
|
6
|
+
text: string;
|
|
7
|
+
docType?: DocType;
|
|
8
|
+
}
|
|
9
|
+
export interface AdocParseResult {
|
|
10
|
+
chunks: Chunk[];
|
|
11
|
+
/** Document header attributes as a key/value map, or null when the document
|
|
12
|
+
* has no `= Title` header. Negated entries (`:!name:`) carry `NEGATED`. */
|
|
13
|
+
attributes: Record<string, string> | null;
|
|
14
|
+
doctitle: string | null;
|
|
15
|
+
/** Attribute map + `title: <doctitle>`, shaped for the frontmatter meta path
|
|
16
|
+
* the indexer already applies to markdown (design D3b). */
|
|
17
|
+
frontmatter: Record<string, FmValue> | null;
|
|
18
|
+
wikilinks: string[];
|
|
19
|
+
/** Outbound document links from `xref:`/`<<>>` refs (design D6). Fed into the
|
|
20
|
+
* same file-level link aggregation as markdown links. */
|
|
21
|
+
mdLinks: string[];
|
|
22
|
+
parseFailed: boolean;
|
|
23
|
+
}
|
|
24
|
+
/** Value stored for a negated attribute entry (`:!sectnums:` / `:sectnums!:`). */
|
|
25
|
+
export declare const NEGATED = "!";
|
|
26
|
+
/** Outbound document links: `xref:target[]` and `<<target>>` whose file
|
|
27
|
+
* component (fragment stripped first) ends in `.adoc`/`.asciidoc`. */
|
|
28
|
+
export declare function extractXrefs(text: string): string[];
|
|
29
|
+
export declare function chunkAsciiDoc(input: AdocChunkInput): AdocParseResult;
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
// AsciiDoc structural chunker — sibling of the markdown chunker (design D3).
|
|
2
|
+
// Line-based with a delimited-block state machine: a `== Title`-shaped line is a
|
|
3
|
+
// section boundary ONLY outside a delimited block. Shares the markdown chunker's
|
|
4
|
+
// thresholds + id/hash scheme (chunk-contract parity), but NOT its oversize
|
|
5
|
+
// splitter: the markdown splitter breaks at any blank line, which would split
|
|
6
|
+
// mid-listing. Here a split point must sit outside every delimited block.
|
|
7
|
+
// Parser is TOTAL (never throws) and PURE (same bytes → same output).
|
|
8
|
+
// See change: asciidoc-support.
|
|
9
|
+
import { MAX_CHUNK_CHARS, MIN_CHUNK_CHARS, sha } from "./chunker.js";
|
|
10
|
+
/** Value stored for a negated attribute entry (`:!sectnums:` / `:sectnums!:`). */
|
|
11
|
+
export const NEGATED = "!";
|
|
12
|
+
const ADOC_EXT_RE = /\.(adoc|asciidoc)$/i;
|
|
13
|
+
/** One to six `=` followed by whitespace and title text. Seven `=` never
|
|
14
|
+
* matches (the 7th char is not whitespace at any backtrack length). */
|
|
15
|
+
const TITLE_RE = /^(={1,6})\s+(\S.*?)\s*$/;
|
|
16
|
+
const ATTR_RE = /^:(!?)([A-Za-z0-9_][A-Za-z0-9_-]*)(!?):(?:[ \t]+(.*?))?[ \t]*$/;
|
|
17
|
+
/** Canonical delimiter token for a delimited-block boundary line, else null.
|
|
18
|
+
* A block closes only on a line with the SAME canonical token, so any other
|
|
19
|
+
* delimiter inside it is opaque content. */
|
|
20
|
+
function delimiterOf(line) {
|
|
21
|
+
const t = line.replace(/[ \t]+$/, "");
|
|
22
|
+
if (/^\/{4,}$/.test(t))
|
|
23
|
+
return "////"; // comment
|
|
24
|
+
if (/^-{4,}$/.test(t))
|
|
25
|
+
return "----"; // listing
|
|
26
|
+
if (/^\.{4,}$/.test(t))
|
|
27
|
+
return "...."; // literal
|
|
28
|
+
if (/^={4,}$/.test(t))
|
|
29
|
+
return "===="; // example
|
|
30
|
+
if (/^\*{4,}$/.test(t))
|
|
31
|
+
return "****"; // sidebar
|
|
32
|
+
if (/^_{4,}$/.test(t))
|
|
33
|
+
return "____"; // quote
|
|
34
|
+
if (/^\+{4,}$/.test(t))
|
|
35
|
+
return "++++"; // passthrough
|
|
36
|
+
if (/^\|={3,}$/.test(t))
|
|
37
|
+
return "|==="; // table
|
|
38
|
+
if (t === "--")
|
|
39
|
+
return "--"; // open
|
|
40
|
+
return null;
|
|
41
|
+
}
|
|
42
|
+
const bodyOf = (s) => s.bodyLines.map((l) => l + "\n").join("");
|
|
43
|
+
/** Parse the document header: `= Title` on line 1 plus the `:name: value`
|
|
44
|
+
* entries that follow it, up to the first blank or non-attribute line. */
|
|
45
|
+
function parseHeader(lines) {
|
|
46
|
+
const first = lines[0] ?? "";
|
|
47
|
+
const m = first.match(/^=[ \t]+(\S.*?)[ \t]*$/);
|
|
48
|
+
if (!m)
|
|
49
|
+
return { doctitle: null, attributes: null, bodyStart: 0 };
|
|
50
|
+
const attributes = {};
|
|
51
|
+
let i = 1;
|
|
52
|
+
for (; i < lines.length; i++) {
|
|
53
|
+
const line = lines[i];
|
|
54
|
+
if (line.trim() === "")
|
|
55
|
+
break;
|
|
56
|
+
const a = line.match(ATTR_RE);
|
|
57
|
+
if (!a)
|
|
58
|
+
break; // author/revision or anything else ends the header
|
|
59
|
+
const negated = a[1] === "!" || a[3] === "!";
|
|
60
|
+
// Asciidoctor normalizes attribute NAMES to lowercase (values keep their
|
|
61
|
+
// case), so `:Tags:` and `:tags:` are the same attribute. Canonicalize here
|
|
62
|
+
// or the indexer's facet/meta keys would miss a mixed-case declaration.
|
|
63
|
+
attributes[a[2].toLowerCase()] = negated ? NEGATED : (a[4] ?? "");
|
|
64
|
+
}
|
|
65
|
+
return { doctitle: m[1], attributes, bodyStart: i };
|
|
66
|
+
}
|
|
67
|
+
/** Upper bound on a cross-reference target/label. Every quantifier below is
|
|
68
|
+
* BOUNDED on purpose: an unbounded character class scanning from each of n
|
|
69
|
+
* start positions is polynomial (`js/polynomial-redos`) on adversarial input,
|
|
70
|
+
* and the indexer feeds these regexes arbitrary repository files. No real
|
|
71
|
+
* xref target or label approaches this length. */
|
|
72
|
+
const XREF_MAX = 256;
|
|
73
|
+
const XREF_MACRO_RE = new RegExp(String.raw `xref:([^\[\s]{1,${XREF_MAX}})\[`, "g");
|
|
74
|
+
const XREF_ANGLE_RE = new RegExp(String.raw `<<([^>,\s]{1,${XREF_MAX}})(?:,[^>]{0,${XREF_MAX}})?>>`, "g");
|
|
75
|
+
/** Outbound document links: `xref:target[]` and `<<target>>` whose file
|
|
76
|
+
* component (fragment stripped first) ends in `.adoc`/`.asciidoc`. */
|
|
77
|
+
export function extractXrefs(text) {
|
|
78
|
+
const out = [];
|
|
79
|
+
const take = (raw) => {
|
|
80
|
+
const file = raw.split("#")[0].trim();
|
|
81
|
+
if (file && ADOC_EXT_RE.test(file))
|
|
82
|
+
out.push(file);
|
|
83
|
+
};
|
|
84
|
+
for (const m of text.matchAll(XREF_MACRO_RE))
|
|
85
|
+
take(m[1]);
|
|
86
|
+
for (const m of text.matchAll(XREF_ANGLE_RE))
|
|
87
|
+
take(m[1]);
|
|
88
|
+
return out;
|
|
89
|
+
}
|
|
90
|
+
/** Split a section's body into paragraph groups whose boundaries (blank lines)
|
|
91
|
+
* all sit OUTSIDE delimited blocks. A section with no safe boundary yields a
|
|
92
|
+
* single group — which the caller emits as one oversized chunk. */
|
|
93
|
+
function safeGroups(bodyLines, lineNos) {
|
|
94
|
+
const groups = [];
|
|
95
|
+
let cur = { lines: [], nos: [] };
|
|
96
|
+
let open = null;
|
|
97
|
+
for (let i = 0; i < bodyLines.length; i++) {
|
|
98
|
+
const line = bodyLines[i];
|
|
99
|
+
const d = delimiterOf(line);
|
|
100
|
+
if (open) {
|
|
101
|
+
if (d === open)
|
|
102
|
+
open = null;
|
|
103
|
+
}
|
|
104
|
+
else if (d) {
|
|
105
|
+
open = d;
|
|
106
|
+
}
|
|
107
|
+
else if (line.trim() === "") {
|
|
108
|
+
if (cur.lines.length)
|
|
109
|
+
groups.push(cur);
|
|
110
|
+
cur = { lines: [], nos: [] };
|
|
111
|
+
continue; // blank separators are dropped (markdown splitter parity)
|
|
112
|
+
}
|
|
113
|
+
cur.lines.push(line);
|
|
114
|
+
cur.nos.push(lineNos[i]);
|
|
115
|
+
}
|
|
116
|
+
if (cur.lines.length)
|
|
117
|
+
groups.push(cur);
|
|
118
|
+
return groups;
|
|
119
|
+
}
|
|
120
|
+
export function chunkAsciiDoc(input) {
|
|
121
|
+
const docType = input.docType ?? "doc";
|
|
122
|
+
const norm = input.text.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n");
|
|
123
|
+
const lines = norm.split("\n");
|
|
124
|
+
const fileTitle = (input.path.split("/").pop() ?? input.path).replace(ADOC_EXT_RE, "");
|
|
125
|
+
const { doctitle, attributes, bodyStart } = parseHeader(lines);
|
|
126
|
+
const rootTitle = doctitle ?? fileTitle;
|
|
127
|
+
const raw = [];
|
|
128
|
+
// A doctitle is a real level-0 document heading, so it roots the breadcrumb.
|
|
129
|
+
// Without a header the preamble heading is the file name and roots nothing
|
|
130
|
+
// (markdown chunker parity).
|
|
131
|
+
const stack = [];
|
|
132
|
+
if (doctitle)
|
|
133
|
+
stack.push({ level: 0, title: doctitle, chunkOrdinal: -1 });
|
|
134
|
+
let cur = null;
|
|
135
|
+
let open = null;
|
|
136
|
+
let ordinal = 0;
|
|
137
|
+
const flush = () => {
|
|
138
|
+
if (!cur || !bodyOf(cur).trim())
|
|
139
|
+
return; // empty section → no chunk, slot stays -1
|
|
140
|
+
raw.push(cur);
|
|
141
|
+
if (cur.slot)
|
|
142
|
+
cur.slot.chunkOrdinal = cur.ordinal;
|
|
143
|
+
};
|
|
144
|
+
for (let i = bodyStart; i < lines.length; i++) {
|
|
145
|
+
const line = lines[i];
|
|
146
|
+
const lineNo = i + 1;
|
|
147
|
+
const d = delimiterOf(line);
|
|
148
|
+
if (open) {
|
|
149
|
+
if (d === open)
|
|
150
|
+
open = null;
|
|
151
|
+
}
|
|
152
|
+
else if (d) {
|
|
153
|
+
open = d;
|
|
154
|
+
}
|
|
155
|
+
else {
|
|
156
|
+
const tm = line.match(TITLE_RE);
|
|
157
|
+
if (tm) {
|
|
158
|
+
flush();
|
|
159
|
+
const level = tm[1].length;
|
|
160
|
+
const title = tm[2];
|
|
161
|
+
while (stack.length && stack[stack.length - 1].level >= level)
|
|
162
|
+
stack.pop();
|
|
163
|
+
const parentOrdinal = stack.length ? stack[stack.length - 1].chunkOrdinal : -1;
|
|
164
|
+
const slot = { level, title, chunkOrdinal: -1 };
|
|
165
|
+
stack.push(slot);
|
|
166
|
+
cur = {
|
|
167
|
+
headingPath: stack.map((s) => s.title).join(" > "),
|
|
168
|
+
heading: title,
|
|
169
|
+
level,
|
|
170
|
+
parentOrdinal,
|
|
171
|
+
headingLine: lineNo,
|
|
172
|
+
ordinal,
|
|
173
|
+
slot,
|
|
174
|
+
bodyLines: [],
|
|
175
|
+
lineNos: [],
|
|
176
|
+
};
|
|
177
|
+
ordinal++;
|
|
178
|
+
continue;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
if (!cur) {
|
|
182
|
+
// The preamble IS the doctitle's chunk, so it claims the doctitle's slot.
|
|
183
|
+
cur = { headingPath: rootTitle, heading: rootTitle, level: 0, parentOrdinal: -1, headingLine: lineNo, ordinal, slot: doctitle ? stack[0] : null, bodyLines: [], lineNos: [] };
|
|
184
|
+
ordinal++;
|
|
185
|
+
}
|
|
186
|
+
cur.bodyLines.push(line);
|
|
187
|
+
cur.lineNos.push(lineNo);
|
|
188
|
+
}
|
|
189
|
+
flush();
|
|
190
|
+
// tiny-merge — same threshold constant as the markdown chunker (parity)
|
|
191
|
+
const merged = [];
|
|
192
|
+
for (const c of raw) {
|
|
193
|
+
if (bodyOf(c).trim().length < MIN_CHUNK_CHARS && merged.length) {
|
|
194
|
+
const prev = merged[merged.length - 1];
|
|
195
|
+
prev.bodyLines.push("", c.heading, ...c.bodyLines);
|
|
196
|
+
prev.lineNos.push(c.headingLine, c.headingLine, ...c.lineNos);
|
|
197
|
+
}
|
|
198
|
+
else
|
|
199
|
+
merged.push(c);
|
|
200
|
+
}
|
|
201
|
+
// oversize-split — block-safe: split points are blank lines outside blocks
|
|
202
|
+
const sized = [];
|
|
203
|
+
for (const c of merged) {
|
|
204
|
+
if (bodyOf(c).length <= MAX_CHUNK_CHARS) {
|
|
205
|
+
sized.push(c);
|
|
206
|
+
continue;
|
|
207
|
+
}
|
|
208
|
+
const groups = safeGroups(c.bodyLines, c.lineNos);
|
|
209
|
+
let buf = { lines: [], nos: [] };
|
|
210
|
+
const emit = () => {
|
|
211
|
+
if (buf.lines.length)
|
|
212
|
+
sized.push({ ...c, bodyLines: buf.lines, lineNos: buf.nos });
|
|
213
|
+
buf = { lines: [], nos: [] };
|
|
214
|
+
};
|
|
215
|
+
for (const g of groups) {
|
|
216
|
+
const glen = g.lines.reduce((n, l) => n + l.length + 1, 0);
|
|
217
|
+
const blen = buf.lines.reduce((n, l) => n + l.length + 1, 0);
|
|
218
|
+
if (blen && blen + glen > MAX_CHUNK_CHARS)
|
|
219
|
+
emit();
|
|
220
|
+
buf.lines.push(...g.lines, "");
|
|
221
|
+
buf.nos.push(...g.nos, g.nos[g.nos.length - 1]);
|
|
222
|
+
}
|
|
223
|
+
emit();
|
|
224
|
+
}
|
|
225
|
+
const fileSha = sha(input.path);
|
|
226
|
+
// ordinal → final array index. An oversize split yields several pieces for one
|
|
227
|
+
// ordinal; children point at the first. A section whose ordinal is absent was
|
|
228
|
+
// dropped or merged away, so its children get a null parent rather than a
|
|
229
|
+
// dangling (or self-referential) id.
|
|
230
|
+
const indexByOrdinal = new Map();
|
|
231
|
+
sized.forEach((c, i) => {
|
|
232
|
+
if (!indexByOrdinal.has(c.ordinal))
|
|
233
|
+
indexByOrdinal.set(c.ordinal, i);
|
|
234
|
+
});
|
|
235
|
+
const chunks = sized.map((c, i) => {
|
|
236
|
+
const body = bodyOf(c);
|
|
237
|
+
const anchors = realAnchors(c);
|
|
238
|
+
return {
|
|
239
|
+
root: input.root,
|
|
240
|
+
path: input.path,
|
|
241
|
+
chunkId: `${fileSha.slice(0, 8)}:${i}`,
|
|
242
|
+
headingPath: c.headingPath,
|
|
243
|
+
heading: c.heading,
|
|
244
|
+
level: c.level,
|
|
245
|
+
parentChunkId: parentIdOf(c, i),
|
|
246
|
+
docType,
|
|
247
|
+
body: body.trimEnd(),
|
|
248
|
+
bodyHash: sha(body.trim()),
|
|
249
|
+
startLine: anchors.startLine,
|
|
250
|
+
endLine: anchors.endLine,
|
|
251
|
+
};
|
|
252
|
+
});
|
|
253
|
+
function parentIdOf(c, ownIndex) {
|
|
254
|
+
const idx = indexByOrdinal.get(c.parentOrdinal);
|
|
255
|
+
if (idx === undefined || idx === ownIndex)
|
|
256
|
+
return null; // dropped/merged parent, or self
|
|
257
|
+
return `${fileSha.slice(0, 8)}:${idx}`;
|
|
258
|
+
}
|
|
259
|
+
const frontmatter = attributes ? { ...attributes, ...(doctitle ? { title: doctitle } : {}) } : null;
|
|
260
|
+
return { chunks, attributes, doctitle, frontmatter, wikilinks: [], mdLinks: extractXrefs(norm), parseFailed: false };
|
|
261
|
+
}
|
|
262
|
+
/** Line anchors bound the section's real content — blank padding at either end
|
|
263
|
+
* is excluded so the range matches what the chunk body actually covers. */
|
|
264
|
+
function realAnchors(c) {
|
|
265
|
+
let first = 0;
|
|
266
|
+
let last = c.bodyLines.length - 1;
|
|
267
|
+
while (first < c.bodyLines.length && c.bodyLines[first].trim() === "")
|
|
268
|
+
first++;
|
|
269
|
+
while (last >= 0 && c.bodyLines[last].trim() === "")
|
|
270
|
+
last--;
|
|
271
|
+
if (first > last)
|
|
272
|
+
return { startLine: c.headingLine, endLine: c.headingLine };
|
|
273
|
+
return { startLine: c.lineNos[first], endLine: c.lineNos[last] };
|
|
274
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export type ArchiveKind = "tar" | "zip";
|
|
2
|
+
export interface ArchiveLimits {
|
|
3
|
+
maxEntries?: number;
|
|
4
|
+
maxExpandedBytes?: number;
|
|
5
|
+
}
|
|
6
|
+
export declare const DEFAULT_MAX_ENTRIES = 50000;
|
|
7
|
+
export declare const DEFAULT_MAX_EXPANDED_BYTES: number;
|
|
8
|
+
/**
|
|
9
|
+
* Validate `archive`, then extract it into the (fresh, empty) `outDir`, then run
|
|
10
|
+
* the post-extraction backstop. Throws before extracting on any unsafe entry.
|
|
11
|
+
*/
|
|
12
|
+
export declare function extractArchiveSafely(kind: ArchiveKind, archive: string, outDir: string, limits?: ArchiveLimits): Promise<void>;
|