@blackbelt-technology/pi-dashboard-kb 0.8.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 +46 -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 +96 -25
- package/dist/config.d.ts +33 -0
- package/dist/config.js +27 -4
- package/dist/dox-triage.d.ts +3 -2
- package/dist/dox-triage.js +15 -8
- package/dist/dox.d.ts +45 -6
- package/dist/dox.js +228 -93
- package/dist/eval.d.ts +24 -0
- package/dist/eval.js +106 -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 +7 -0
- package/dist/indexer.js +38 -9
- 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/sources.d.ts +29 -0
- package/dist/sources.js +230 -32
- package/dist/sqlite-store.d.ts +39 -2
- package/dist/sqlite-store.js +145 -17
- 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 +40 -0
- package/dist/verdict.d.ts +45 -0
- package/dist/verdict.js +368 -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 +5 -3
- package/src/cli.ts +93 -24
- package/src/config.ts +54 -4
- package/src/dox-triage.ts +17 -9
- package/src/dox.ts +252 -67
- package/src/eval.ts +117 -14
- package/src/gitignore.ts +215 -0
- package/src/index.ts +45 -20
- package/src/indexer.ts +44 -8
- package/src/net-guard.ts +288 -0
- package/src/render.ts +17 -1
- package/src/search-opts.ts +52 -0
- package/src/sources.ts +232 -28
- package/src/sqlite-store.ts +139 -17
- package/src/staleness.ts +76 -0
- package/src/trust.ts +81 -8
- package/src/types.ts +43 -0
- package/src/verdict.ts +412 -0
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// Traversal-safe archive extraction (change: harden-untrusted-content-ingestion,
|
|
2
|
+
// design D4 / B13). The archive is LISTED and validated first; any absolute, `..`,
|
|
3
|
+
// control-char or non-file (link/device/fifo) entry rejects the whole archive.
|
|
4
|
+
// Names and types come from two listings matched by line index — names are never
|
|
5
|
+
// parsed out of a verbose line, so ` -> ` and spaces in names are harmless.
|
|
6
|
+
// Fail closed: an unparseable listing, a count mismatch or a non-zero exit rejects.
|
|
7
|
+
import { execFile } from "node:child_process"; // ban:child_process-ok (kb package is self-contained; owns tar/zip listing + extract for the https resolver)
|
|
8
|
+
import { lstatSync, readdirSync, realpathSync } from "node:fs";
|
|
9
|
+
import { join, sep } from "node:path";
|
|
10
|
+
import { promisify } from "node:util";
|
|
11
|
+
export const DEFAULT_MAX_ENTRIES = 50_000;
|
|
12
|
+
export const DEFAULT_MAX_EXPANDED_BYTES = 256 * 1024 * 1024;
|
|
13
|
+
const execFileAsync = promisify(execFile);
|
|
14
|
+
/** Per-call bound: a hung tar/unzip must not pin a reindex job forever. */
|
|
15
|
+
const RUN_TIMEOUT_MS = 120_000;
|
|
16
|
+
const MAX_LISTING_BYTES = 256 * 1024 * 1024;
|
|
17
|
+
// Async on purpose (change: improve-kb-settings-sources-and-search, D6): a large archive must
|
|
18
|
+
// never stall the dashboard server's event loop. Env is read per call, not at import.
|
|
19
|
+
const env = () => ({ ...process.env, LC_ALL: "C" });
|
|
20
|
+
const run = async (cmd, args) => (await execFileAsync(cmd, args, { encoding: "latin1", env: env(), timeout: RUN_TIMEOUT_MS, maxBuffer: MAX_LISTING_BYTES })).stdout;
|
|
21
|
+
/** Decode tar's C-locale escapes (`\NNN`, `\t`, `\n`, `\\` …) to a latin1 byte string. */
|
|
22
|
+
function decodeTarName(raw) {
|
|
23
|
+
const simple = { a: "\x07", b: "\b", f: "\f", n: "\n", r: "\r", t: "\t", v: "\v", "\\": "\\", "'": "'", '"': '"' };
|
|
24
|
+
return raw.replace(/\\([0-7]{1,3}|.)/gs, (_m, c) => (/^[0-7]+$/.test(c) ? String.fromCharCode(parseInt(c, 8) & 0xff) : (simple[c] ?? `\\${c}`)));
|
|
25
|
+
}
|
|
26
|
+
function checkName(name, display) {
|
|
27
|
+
if (name.length === 0)
|
|
28
|
+
throw new Error(`unsafe archive entry: empty name`);
|
|
29
|
+
// eslint-disable-next-line no-control-regex
|
|
30
|
+
if (/[\x00-\x1f\x7f]/.test(name))
|
|
31
|
+
throw new Error(`unsafe archive entry (control character): ${JSON.stringify(display)}`);
|
|
32
|
+
if (name.startsWith("/") || name.startsWith("\\") || /^[A-Za-z]:/.test(name))
|
|
33
|
+
throw new Error(`unsafe archive entry (absolute path): ${display}`);
|
|
34
|
+
if (name.split(/[\\/]/).includes(".."))
|
|
35
|
+
throw new Error(`unsafe archive entry (.. segment): ${display}`);
|
|
36
|
+
}
|
|
37
|
+
const lines = (s) => {
|
|
38
|
+
const l = s.split("\n");
|
|
39
|
+
if (l.length && l[l.length - 1] === "")
|
|
40
|
+
l.pop();
|
|
41
|
+
return l;
|
|
42
|
+
};
|
|
43
|
+
/** Validate a tar archive (any compression the host tar auto-detects). Throws on any unsafe entry. */
|
|
44
|
+
async function validateTar(archive, maxEntries) {
|
|
45
|
+
const names = lines(await run("tar", ["-tf", archive]));
|
|
46
|
+
const verbose = lines(await run("tar", ["-tvf", archive]));
|
|
47
|
+
if (names.length > maxEntries)
|
|
48
|
+
throw new Error(`archive has too many entries (${names.length} > ${maxEntries})`);
|
|
49
|
+
if (names.length !== verbose.length)
|
|
50
|
+
throw new Error(`cannot validate archive: listing mismatch (${names.length} names vs ${verbose.length} entries)`);
|
|
51
|
+
for (let i = 0; i < names.length; i++) {
|
|
52
|
+
const v = verbose[i];
|
|
53
|
+
const type = v[0];
|
|
54
|
+
if (type !== "-" && type !== "d")
|
|
55
|
+
throw new Error(`unsafe archive entry (type '${type}'): ${names[i]}`);
|
|
56
|
+
// bsdtar renders a hardlink as `-… name link to target`; reject fail-closed.
|
|
57
|
+
if (v.includes(" link to ") || v.includes(" ==> "))
|
|
58
|
+
throw new Error(`unsafe archive entry (link): ${names[i]}`);
|
|
59
|
+
checkName(decodeTarName(names[i]), names[i]);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
/** Validate a zip archive. Throws on any unsafe entry; returns `true` when it is empty. */
|
|
63
|
+
async function validateZip(archive, maxEntries) {
|
|
64
|
+
let header;
|
|
65
|
+
try {
|
|
66
|
+
header = await run("unzip", ["-Z", archive]);
|
|
67
|
+
}
|
|
68
|
+
catch (e) {
|
|
69
|
+
// `Empty zipfile.` exits 1 — recover its stdout and look at the entry count.
|
|
70
|
+
header = String(e.stdout ?? "");
|
|
71
|
+
if (!/number of entries: 0\b/.test(header))
|
|
72
|
+
throw e;
|
|
73
|
+
}
|
|
74
|
+
const hl = lines(header);
|
|
75
|
+
const sizeIdx = hl.findIndex((l) => l.startsWith("Zip file size:"));
|
|
76
|
+
const count = Number(/number of entries: (\d+)/.exec(hl[sizeIdx] ?? "")?.[1]);
|
|
77
|
+
if (sizeIdx < 0 || !Number.isInteger(count))
|
|
78
|
+
throw new Error("cannot validate archive: unparseable zip listing");
|
|
79
|
+
if (count > maxEntries)
|
|
80
|
+
throw new Error(`archive has too many entries (${count} > ${maxEntries})`);
|
|
81
|
+
if (count === 0)
|
|
82
|
+
return true; // `unzip -Z1` prints `Empty zipfile.` and exits 1
|
|
83
|
+
const names = lines(await run("unzip", ["-Z1", archive]));
|
|
84
|
+
const typeLines = hl.slice(sizeIdx + 1, sizeIdx + 1 + count);
|
|
85
|
+
if (names.length !== count || typeLines.length !== count)
|
|
86
|
+
throw new Error(`cannot validate archive: zip listing mismatch (${names.length} names, ${typeLines.length} types, ${count} entries)`);
|
|
87
|
+
for (let i = 0; i < count; i++) {
|
|
88
|
+
const type = typeLines[i][0];
|
|
89
|
+
if (type !== "-" && type !== "d")
|
|
90
|
+
throw new Error(`unsafe archive entry (type '${type}'): ${names[i]}`);
|
|
91
|
+
// Info-ZIP renders control characters as ^X (fail-closed for a literal `^A`).
|
|
92
|
+
if (/\^[@-_]/.test(names[i]))
|
|
93
|
+
throw new Error(`unsafe archive entry (control character): ${JSON.stringify(names[i])}`);
|
|
94
|
+
checkName(names[i], names[i]);
|
|
95
|
+
}
|
|
96
|
+
return false;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Stream the archive's decompressed content to a bounded buffer BEFORE extracting to disk:
|
|
100
|
+
* a decompression bomb (tiny download, huge expansion) aborts once `maxBytes` is exceeded.
|
|
101
|
+
*/
|
|
102
|
+
async function assertExpandedWithin(cmd, args, maxBytes) {
|
|
103
|
+
try {
|
|
104
|
+
await execFileAsync(cmd, args, { encoding: "buffer", env: env(), timeout: RUN_TIMEOUT_MS, maxBuffer: maxBytes });
|
|
105
|
+
}
|
|
106
|
+
catch (e) {
|
|
107
|
+
// sync execFile reports ENOBUFS; the async one reports ERR_CHILD_PROCESS_STDIO_MAXBUFFER.
|
|
108
|
+
const code = e.code;
|
|
109
|
+
if (code === "ENOBUFS" || code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER")
|
|
110
|
+
throw new Error(`archive expands beyond the ${maxBytes}-byte limit`);
|
|
111
|
+
throw e;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/** Walk `out` and reject any symlink, escaping realpath or multiply-linked file (backstop, not the control). */
|
|
115
|
+
function backstopWalk(out) {
|
|
116
|
+
const root = realpathSync(out);
|
|
117
|
+
const walk = (dir) => {
|
|
118
|
+
for (const name of readdirSync(dir)) {
|
|
119
|
+
const p = join(dir, name);
|
|
120
|
+
const st = lstatSync(p);
|
|
121
|
+
if (st.isSymbolicLink())
|
|
122
|
+
throw new Error(`extracted symlink rejected: ${p}`);
|
|
123
|
+
const real = realpathSync(p);
|
|
124
|
+
if (real !== root && !real.startsWith(root + sep))
|
|
125
|
+
throw new Error(`extracted entry escapes destination: ${p}`);
|
|
126
|
+
if (st.isDirectory())
|
|
127
|
+
walk(p);
|
|
128
|
+
else if (st.isFile() && st.nlink > 1)
|
|
129
|
+
throw new Error(`extracted hardlink rejected: ${p}`);
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
walk(root);
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* Validate `archive`, then extract it into the (fresh, empty) `outDir`, then run
|
|
136
|
+
* the post-extraction backstop. Throws before extracting on any unsafe entry.
|
|
137
|
+
*/
|
|
138
|
+
export async function extractArchiveSafely(kind, archive, outDir, limits = {}) {
|
|
139
|
+
const maxEntries = limits.maxEntries ?? DEFAULT_MAX_ENTRIES;
|
|
140
|
+
const maxBytes = limits.maxExpandedBytes ?? DEFAULT_MAX_EXPANDED_BYTES;
|
|
141
|
+
if (kind === "zip") {
|
|
142
|
+
const empty = await validateZip(archive, maxEntries);
|
|
143
|
+
if (!empty) {
|
|
144
|
+
await assertExpandedWithin("unzip", ["-p", archive], maxBytes);
|
|
145
|
+
await run("unzip", ["-o", "-q", archive, "-d", outDir]);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
else {
|
|
149
|
+
await validateTar(archive, maxEntries);
|
|
150
|
+
await assertExpandedWithin("tar", ["-xOf", archive], maxBytes);
|
|
151
|
+
await run("tar", ["-xf", archive, "-C", outDir, "--no-same-owner"]);
|
|
152
|
+
}
|
|
153
|
+
backstopWalk(outDir);
|
|
154
|
+
}
|
package/dist/chunker.d.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { type FmValue } from "./frontmatter.js";
|
|
2
2
|
import type { Chunk, DocType } from "./types.js";
|
|
3
|
+
export declare const MIN_CHUNK_CHARS = 100;
|
|
4
|
+
export declare const MAX_CHUNK_CHARS = 4000;
|
|
5
|
+
export declare const sha: (s: string) => string;
|
|
3
6
|
export interface ChunkInput {
|
|
4
7
|
root: string;
|
|
5
8
|
path: string;
|
package/dist/chunker.js
CHANGED
|
@@ -3,9 +3,11 @@
|
|
|
3
3
|
// (research §2.5). mdast (unified/remark) is the documented refinement.
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
5
5
|
import { parseFrontmatter } from "./frontmatter.js";
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
const
|
|
6
|
+
// Shared with the AsciiDoc chunker (adoc-chunker.ts) so both normalize with the
|
|
7
|
+
// SAME thresholds and id/hash scheme (chunk-contract parity, design D3).
|
|
8
|
+
export const MIN_CHUNK_CHARS = 100;
|
|
9
|
+
export const MAX_CHUNK_CHARS = 4000;
|
|
10
|
+
export const sha = (s) => createHash("sha256").update(s).digest("hex");
|
|
9
11
|
export function chunkMarkdown(input) {
|
|
10
12
|
const docType = input.docType ?? "doc";
|
|
11
13
|
const { body: text, fm, parseFailed } = parseFrontmatter(input.text);
|
package/dist/cli.js
CHANGED
|
@@ -2,19 +2,22 @@
|
|
|
2
2
|
// kb CLI (Phase 1): index | search | neighbors | backlinks | get | config
|
|
3
3
|
// Run (dev): NODE_OPTIONS=--experimental-sqlite tsx src/cli.ts <cmd> ...
|
|
4
4
|
// Shipped bin builds to dist/cli.js (build step deferred).
|
|
5
|
-
import {
|
|
6
|
-
import { join, resolve } from "node:path";
|
|
5
|
+
import { readFileSync } from "node:fs";
|
|
6
|
+
import { join, relative, resolve } from "node:path";
|
|
7
7
|
import { frontmatterConfigHash, loadConfig } from "./config.js";
|
|
8
|
-
import { agentsChain, doxInit, doxLint } from "./dox.js";
|
|
8
|
+
import { agentsChain, doxInit, doxLint, listEmptyPurposeRows } from "./dox.js";
|
|
9
9
|
import { ackTargets, applyDecisions, buildWorkItems } from "./dox-triage.js";
|
|
10
|
-
import { evaluate } from "./eval.js";
|
|
10
|
+
import { evaluate, loadGolden } from "./eval.js";
|
|
11
11
|
import { runIndexAtomic } from "./index-run.js";
|
|
12
12
|
import { indexSource } from "./indexer.js";
|
|
13
13
|
import { kbInit } from "./init.js";
|
|
14
14
|
import { renderHits } from "./render.js";
|
|
15
|
+
import { searchOptsFromConfig } from "./search-opts.js";
|
|
15
16
|
import { resolveAll } from "./sources.js";
|
|
16
17
|
import { SCHEMA_VERSION, SqliteFtsStore } from "./sqlite-store.js";
|
|
18
|
+
import { readStaleness } from "./staleness.js";
|
|
17
19
|
import { defaultPromptTrust } from "./trust.js";
|
|
20
|
+
import { enrichHits } from "./verdict.js";
|
|
18
21
|
function parse(argv) {
|
|
19
22
|
const f = { _: [] };
|
|
20
23
|
for (let i = 0; i < argv.length; i++) {
|
|
@@ -85,7 +88,7 @@ async function runIndex(cfg, store, sources, force = false) {
|
|
|
85
88
|
const eff = force || stale;
|
|
86
89
|
let scanned = 0, changed = 0, deleted = 0, chunks = 0;
|
|
87
90
|
for (const s of sources) {
|
|
88
|
-
const st = await indexSource(store, { root: s.id, dir: s.dir }, { force: eff, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions, frontmatter: cfg.frontmatter });
|
|
91
|
+
const st = await indexSource(store, { root: s.id, dir: s.dir }, { force: eff, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions, frontmatter: cfg.frontmatter, respectGitignore: cfg.respectGitignore, cwd: cfg.cwd });
|
|
89
92
|
scanned += st.scanned;
|
|
90
93
|
changed += st.changed;
|
|
91
94
|
deleted += st.deleted;
|
|
@@ -116,8 +119,8 @@ Usage:
|
|
|
116
119
|
kb search "<query>" [--limit N] [--root id] [--doc-type doc|agents|source-md]
|
|
117
120
|
[--expand-parent|--no-expand-parent] [--expand-graph] [--rerank]
|
|
118
121
|
[--expand-query] [--json] [--no-reindex] [--source <dir>...] [--db <path>]
|
|
119
|
-
[--no-source-dedup] [--no-lane-quota] [--no-coverage-rerank]
|
|
120
|
-
(--limit bounds distinct SOURCES, not chunks)
|
|
122
|
+
[--no-source-dedup] [--no-lane-quota] [--no-coverage-rerank] [--verdicts]
|
|
123
|
+
(--limit bounds distinct SOURCES, not chunks; --verdicts = opt-in trust labels)
|
|
121
124
|
kb neighbors "<node>" [--depth N] [--rel child_of|links_to|references|has_tag]
|
|
122
125
|
kb backlinks "<node>"
|
|
123
126
|
kb get <path> [--section "<heading_path>"]
|
|
@@ -127,7 +130,12 @@ Usage:
|
|
|
127
130
|
(--source-rows also reports undocumented .ts/.tsx)
|
|
128
131
|
kb dox triage [--json] [--limit N] triage STALE rows vs the git diff since ack
|
|
129
132
|
[--apply <d.json> [--write]] [--ack <targets.json>]
|
|
133
|
+
kb dox describe --list [--json] [--dir <path>] list rows with an empty Purpose cell
|
|
130
134
|
kb eval --golden <file.json> [--limit N] [--doc-type ...] [--no-reindex]
|
|
135
|
+
[--allow-zero] [--verbose] [--json]
|
|
136
|
+
(--golden accepts a bare array of {q, expect} or an {"items": [...]} object;
|
|
137
|
+
items outside the configured roots are reported as unreachable;
|
|
138
|
+
a run with 0 scored items or 0 recall exits non-zero unless --allow-zero)
|
|
131
139
|
kb config show resolved config
|
|
132
140
|
Global: --cwd <dir> --config <file>`;
|
|
133
141
|
function main() {
|
|
@@ -188,9 +196,13 @@ function main() {
|
|
|
188
196
|
const r = doxLint({ cwd, json: !!flags.json, fix: !!flags.fix, sourceFileRows: !!flags["source-rows"] });
|
|
189
197
|
if (flags.json)
|
|
190
198
|
console.log(JSON.stringify(r, null, 2));
|
|
191
|
-
else
|
|
199
|
+
else {
|
|
200
|
+
// Coverage line (design D4, fix-dox-lint-blind-rows): a clean verdict
|
|
201
|
+
// must be distinguishable from an unread file.
|
|
202
|
+
console.log(`${r.filesScanned} files, ${r.rowsScanned} rows scanned, ${r.issues.length} findings`);
|
|
192
203
|
for (const i of r.issues)
|
|
193
204
|
console.log(`${i.kind}\t${i.agentsFile}${i.path ? "\t" + i.path : ""}\t${i.detail}`);
|
|
205
|
+
}
|
|
194
206
|
if (r.issues.length)
|
|
195
207
|
process.exit(1);
|
|
196
208
|
return;
|
|
@@ -212,7 +224,7 @@ function main() {
|
|
|
212
224
|
console.log(`re-acked ${ackTargets({ cwd, targets, stalenessFile })} entries`);
|
|
213
225
|
return;
|
|
214
226
|
}
|
|
215
|
-
const staleness =
|
|
227
|
+
const staleness = readStaleness(stalenessFile);
|
|
216
228
|
const items = buildWorkItems({ cwd, issues: doxLint({ cwd }).issues, staleness, limit: flags.limit ? Number(flags.limit) : undefined });
|
|
217
229
|
if (flags.json) {
|
|
218
230
|
console.log(JSON.stringify(items, null, 2));
|
|
@@ -226,6 +238,25 @@ function main() {
|
|
|
226
238
|
console.log(` ${i.baselineFound ? "diff" : "????"}\t${i.agentsFile}\t${i.row}`);
|
|
227
239
|
return;
|
|
228
240
|
}
|
|
241
|
+
if (sub === "describe") {
|
|
242
|
+
// --list is the only v1 op; accept it (and its absence) uniformly.
|
|
243
|
+
const r = listEmptyPurposeRows({ cwd, dir: typeof flags.dir === "string" ? flags.dir : undefined });
|
|
244
|
+
if (flags.json) {
|
|
245
|
+
console.log(JSON.stringify(r, null, 2));
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
if (r.total === 0) {
|
|
249
|
+
console.log("no empty-purpose rows");
|
|
250
|
+
return;
|
|
251
|
+
}
|
|
252
|
+
console.log(`${r.total} empty-purpose row(s) across ${r.groups.length} AGENTS.md file(s)`);
|
|
253
|
+
for (const g of r.groups) {
|
|
254
|
+
console.log(g.agentsPath);
|
|
255
|
+
for (const s of g.subjects)
|
|
256
|
+
console.log(` ${s}`);
|
|
257
|
+
}
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
229
260
|
console.error(`unknown dox subcommand: ${sub}`);
|
|
230
261
|
process.exit(2);
|
|
231
262
|
}
|
|
@@ -253,7 +284,7 @@ async function runCmd(cmd, flags) {
|
|
|
253
284
|
const s = await runIndexAtomic({
|
|
254
285
|
dbPath: cfg.dbAbsPath,
|
|
255
286
|
sources: sources.map((x) => ({ id: x.id, dir: x.dir })),
|
|
256
|
-
indexOpts: { force: !!flags.force, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions, frontmatter: cfg.frontmatter },
|
|
287
|
+
indexOpts: { force: !!flags.force, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions, frontmatter: cfg.frontmatter, respectGitignore: cfg.respectGitignore, cwd: cfg.cwd },
|
|
257
288
|
facetConfigHash: frontmatterConfigHash(cfg.frontmatter),
|
|
258
289
|
explicit,
|
|
259
290
|
});
|
|
@@ -273,25 +304,31 @@ async function runCmd(cmd, flags) {
|
|
|
273
304
|
const docType = enumFlag(flags["doc-type"], ["doc", "agents", "source-md"], "--doc-type");
|
|
274
305
|
if (!flags["no-reindex"])
|
|
275
306
|
await runIndex(cfg, store, sources); // auto incremental freshness
|
|
307
|
+
// One shared mapping (design D2, fix-kb-eval-measurement-integrity): the
|
|
308
|
+
// CLI's flag-derived overrides are the ONLY difference from the tool.
|
|
276
309
|
const so = {
|
|
277
310
|
limit: limit ?? 10,
|
|
278
311
|
root: flags.root,
|
|
279
312
|
docType: docType,
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
rootPriority: Object.fromEntries(sources.map((s) => [s.id, s.priority])),
|
|
313
|
+
...searchOptsFromConfig(cfg, {
|
|
314
|
+
sources,
|
|
315
|
+
overrides: {
|
|
316
|
+
sourceDedup: flags["no-source-dedup"] ? false : undefined,
|
|
317
|
+
laneQuota: flags["no-lane-quota"] ? 0 : undefined,
|
|
318
|
+
coverageRerank: flags["no-coverage-rerank"] ? false : undefined,
|
|
319
|
+
expandParent: flags["no-expand-parent"] ? false : flags["expand-parent"] ? true : undefined,
|
|
320
|
+
expandGraph: flags["expand-graph"] ? true : undefined,
|
|
321
|
+
rerank: flags.rerank ? true : undefined,
|
|
322
|
+
queryExpansion: flags["expand-query"] && cfg.queryExpansion.mode === "off" ? "synonym" : undefined,
|
|
323
|
+
},
|
|
324
|
+
}),
|
|
293
325
|
};
|
|
294
326
|
const hits = store.search(q, so);
|
|
327
|
+
// Opt-in trust verdicts (arm A): post-search enrichment OUTSIDE the store
|
|
328
|
+
// (design D10) — labels only, ordering untouched (D1); bodies from disk.
|
|
329
|
+
// See change: add-kb-trust-verdicts-and-search-guard.
|
|
330
|
+
if (flags.verdicts)
|
|
331
|
+
await enrichHits(hits, { cwd: cfg.cwd });
|
|
295
332
|
if (flags.json)
|
|
296
333
|
console.log(JSON.stringify(hits, null, 2));
|
|
297
334
|
else if (hits.length)
|
|
@@ -328,9 +365,43 @@ async function runCmd(cmd, flags) {
|
|
|
328
365
|
}
|
|
329
366
|
if (!flags["no-reindex"])
|
|
330
367
|
await runIndex(cfg, store, sources);
|
|
331
|
-
|
|
332
|
-
const
|
|
368
|
+
// Fixture contract (design D3): bare array | {items}, item shapes validated.
|
|
369
|
+
const golden = loadGolden(JSON.parse(readFileSync(resolve(cfg.cwd, gf), "utf8")), gf);
|
|
370
|
+
// Eval measures the TOOL path (spec R1): the extension's option set. Roots
|
|
371
|
+
// enable repo-relative expect normalization + reachability (design D4).
|
|
372
|
+
const roots = sources.map((s) => ({ id: s.id, relPrefix: relative(cfg.cwd, s.dir), dir: s.dir }));
|
|
373
|
+
// Same validation contract as `search`: reject garbage instead of
|
|
374
|
+
// passing an invalid limit to the backend or an unknown doc-type as an
|
|
375
|
+
// empty filter (CodeRabbit round, fix-kb-eval-measurement-integrity).
|
|
376
|
+
const limit = posInt(flags.limit, "--limit") ?? 10;
|
|
377
|
+
const docType = enumFlag(flags["doc-type"], ["doc", "agents", "source-md"], "--doc-type");
|
|
378
|
+
const m = evaluate(store, golden, {
|
|
379
|
+
k: limit,
|
|
380
|
+
docType: docType,
|
|
381
|
+
verbose: !!flags.verbose,
|
|
382
|
+
roots,
|
|
383
|
+
...searchOptsFromConfig(cfg, { sources, overrides: { expandGraph: false, rerank: false } }),
|
|
384
|
+
});
|
|
333
385
|
console.log(JSON.stringify(m, null, flags.json ? 2 : 0));
|
|
386
|
+
if (flags.verbose && m.unreachablePaths?.length) {
|
|
387
|
+
for (const p of m.unreachablePaths)
|
|
388
|
+
console.error(`[kb eval] unreachable: ${p}`);
|
|
389
|
+
}
|
|
390
|
+
// Vacuous-run guard (design D5): an all-zero score is a harness fault far
|
|
391
|
+
// more often than a retrieval fault. Metrics stay on stdout; the failure
|
|
392
|
+
// signal is the exit code. --allow-zero measures anyway.
|
|
393
|
+
const why = m.n === 0
|
|
394
|
+
? golden.length === 0
|
|
395
|
+
? "the golden fixture has no items"
|
|
396
|
+
: `all ${m.unreachable} of ${golden.length} golden items are unreachable under the configured roots (${roots.map((r) => r.relPrefix || ".").join(", ")}) — check root normalization`
|
|
397
|
+
: m["Recall@K"] === 0
|
|
398
|
+
? `recall is 0 across all ${m.n} scored items — check the fixture shape and root normalization`
|
|
399
|
+
: null;
|
|
400
|
+
if (why) {
|
|
401
|
+
console.error(`[kb eval] VACUOUS RUN: ${why}. Re-run with --allow-zero to measure anyway.`);
|
|
402
|
+
if (!flags["allow-zero"])
|
|
403
|
+
process.exit(1);
|
|
404
|
+
}
|
|
334
405
|
}
|
|
335
406
|
else {
|
|
336
407
|
console.error(`unknown command: ${cmd}\n\n${HELP}`);
|
package/dist/config.d.ts
CHANGED
|
@@ -26,6 +26,15 @@ export interface RankingConfig {
|
|
|
26
26
|
* 0 disables the quota. SWEPT over the bundled fixtures — see
|
|
27
27
|
* openspec/changes/fix-kb-search-retrieval-quality/measurements.md. */
|
|
28
28
|
laneQuota: number;
|
|
29
|
+
/** Relative score margin that lets the reserved `agents` lane take result
|
|
30
|
+
* slot 1, 0..1 (change fix-kb-search-lane-composition, design D2/D3).
|
|
31
|
+
* `0` disables the rule and restores the pre-change interleaving exactly.
|
|
32
|
+
* The running-share quota is structurally incapable of taking slot 1
|
|
33
|
+
* (`(0+1)/(0+1) <= share` is false for every share < 1), so rank 1 needs
|
|
34
|
+
* its own knob. Inert whenever there is no reserved lane: an explicit
|
|
35
|
+
* `doc_type` or `laneQuota: 0` zeroes `laneShare` at the call site, so
|
|
36
|
+
* `interleaveLanes` — and this rule inside it — is never reached. */
|
|
37
|
+
laneLeadMargin: number;
|
|
29
38
|
/** IDF-weighted coverage rerank over the candidate pool (design D4).
|
|
30
39
|
* Implemented, DEFAULT OFF: on the bundled fixtures it costs markdown-intent
|
|
31
40
|
* R@10 0.620 → 0.472 to buy source-intent 0.423 → 0.462, a net regression. */
|
|
@@ -59,6 +68,25 @@ export interface FrontmatterConfig {
|
|
|
59
68
|
searchableKeys: string[];
|
|
60
69
|
facetKeys: FacetKeyConfig[];
|
|
61
70
|
}
|
|
71
|
+
/** kb search-guard enforcement mode (arm B). Shipped default `warn` (resolved
|
|
72
|
+
* at planning): a guard that is off does nothing about the measured 10:1
|
|
73
|
+
* under-use; `block` can refuse tool calls and is therefore NEVER a default —
|
|
74
|
+
* reachable only by explicit config. The KB_GUARD_MODE env override may
|
|
75
|
+
* select `off`/`warn` only (it can weaken, never enable blocking — D14). */
|
|
76
|
+
export type GuardMode = "off" | "warn" | "block";
|
|
77
|
+
export interface ReadDisciplineConfig {
|
|
78
|
+
guard: {
|
|
79
|
+
mode: GuardMode;
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
/** Per-turn DOX doctrine delivery (change: inject-dox-doctrine-and-describe).
|
|
83
|
+
* `inject: "kb"` appends the READ doctrine to the system prompt; `write`
|
|
84
|
+
* additionally appends the WRITE discipline. `inject: "off"` suppresses both
|
|
85
|
+
* and makes `write` inert. */
|
|
86
|
+
export interface DoctrineConfig {
|
|
87
|
+
inject: "kb" | "off";
|
|
88
|
+
write: boolean;
|
|
89
|
+
}
|
|
62
90
|
export interface KbConfig {
|
|
63
91
|
sources: SourceConfig[];
|
|
64
92
|
roots?: Array<{
|
|
@@ -94,6 +122,8 @@ export interface KbConfig {
|
|
|
94
122
|
directoryLevelAgents: DirectoryLevelAgentsConfig;
|
|
95
123
|
frontmatter: FrontmatterConfig;
|
|
96
124
|
doxEnforcement: boolean;
|
|
125
|
+
readDiscipline: ReadDisciplineConfig;
|
|
126
|
+
doctrine: DoctrineConfig;
|
|
97
127
|
ranking: RankingConfig;
|
|
98
128
|
expand: ExpandConfig;
|
|
99
129
|
rerank: RerankConfig;
|
|
@@ -112,6 +142,9 @@ export interface ResolvedConfig extends KbConfig {
|
|
|
112
142
|
allSourceSpecs: SourceConfig[];
|
|
113
143
|
resolvedSources: ResolvedSource[];
|
|
114
144
|
origin: "project" | "global" | "defaults";
|
|
145
|
+
/** Highest layer that supplied a `doctrine` KEY (`{}` counts) — distinct from
|
|
146
|
+
* `origin`, which is file-presence. Callers use it to detect first contact. */
|
|
147
|
+
doctrineSource: "project" | "global" | "none";
|
|
115
148
|
}
|
|
116
149
|
export declare const DEFAULTS: KbConfig;
|
|
117
150
|
/** Stable hash of the frontmatter routing config. A change forces a full reindex
|
package/dist/config.js
CHANGED
|
@@ -13,9 +13,11 @@ function expandTilde(p) {
|
|
|
13
13
|
export const DEFAULTS = {
|
|
14
14
|
sources: [],
|
|
15
15
|
sourceCacheDir: "~/.pi/dashboard/kb/sources",
|
|
16
|
-
|
|
16
|
+
// Widened for AsciiDoc together with the indexer walk regex + chunker dispatch
|
|
17
|
+
// (design D4) — widening one gate alone indexes zero extra files.
|
|
18
|
+
include: ["**/*.md", "**/*.adoc", "**/*.asciidoc"],
|
|
17
19
|
exclude: ["**/node_modules/**", "**/archive/**"],
|
|
18
|
-
extensions: [".md"],
|
|
20
|
+
extensions: [".md", ".adoc", ".asciidoc"],
|
|
19
21
|
maxFileCount: null, // no cap
|
|
20
22
|
maxDepth: null,
|
|
21
23
|
respectGitignore: true,
|
|
@@ -32,6 +34,8 @@ export const DEFAULTS = {
|
|
|
32
34
|
directoryLevelAgents: { enabled: true, claudeMd: true, mode: "pull", fallbackManifest: true },
|
|
33
35
|
frontmatter: { searchableKeys: DEFAULT_SEARCHABLE_KEYS, facetKeys: DEFAULT_FACET_KEYS },
|
|
34
36
|
doxEnforcement: false,
|
|
37
|
+
readDiscipline: { guard: { mode: "warn" } },
|
|
38
|
+
doctrine: { inject: "kb", write: false },
|
|
35
39
|
ranking: {
|
|
36
40
|
fieldWeights: { headingPath: 10, heading: 3, body: 1 },
|
|
37
41
|
proximityBoost: true,
|
|
@@ -41,6 +45,9 @@ export const DEFAULTS = {
|
|
|
41
45
|
// (R@10 0.630 vs 0.611 unquota'd) while source-intent rises 0.317 → 0.500.
|
|
42
46
|
laneQuota: 0.5,
|
|
43
47
|
coverageRerank: false,
|
|
48
|
+
// Chosen by measurement over both golden sets — see
|
|
49
|
+
// openspec/changes/fix-kb-search-lane-composition/measurements.md.
|
|
50
|
+
laneLeadMargin: 0,
|
|
44
51
|
},
|
|
45
52
|
expand: { parent: true, graph: false },
|
|
46
53
|
rerank: { enabled: false, model: "ms-marco-MiniLM-L-6-v2", candidateK: 50 },
|
|
@@ -51,7 +58,7 @@ export const DEFAULTS = {
|
|
|
51
58
|
};
|
|
52
59
|
// Nested object keys that need one-level field fill-in (not wholesale replace),
|
|
53
60
|
// so a partial `{ranking:{proximityBoost:false}}` keeps default fieldWeights/diversity.
|
|
54
|
-
const NESTED_KEYS = ["chunking", "dedup", "graph", "directoryLevelAgents", "frontmatter", "ranking", "expand", "rerank", "queryExpansion"];
|
|
61
|
+
const NESTED_KEYS = ["chunking", "dedup", "graph", "directoryLevelAgents", "frontmatter", "readDiscipline", "doctrine", "ranking", "expand", "rerank", "queryExpansion"];
|
|
55
62
|
/** Stable hash of the frontmatter routing config. A change forces a full reindex
|
|
56
63
|
* (design D6) since existing property rows/meta chunks reflect the old routing. */
|
|
57
64
|
export function frontmatterConfigHash(fm) {
|
|
@@ -97,9 +104,22 @@ export function validateConfig(c, origin = "config") {
|
|
|
97
104
|
throw err("dbPath must be a non-empty string");
|
|
98
105
|
if (!/^(off|prf|synonym|agent)$/.test(merged.queryExpansion.mode))
|
|
99
106
|
throw err(`queryExpansion.mode "${merged.queryExpansion.mode}" unknown`);
|
|
107
|
+
const gm = merged.readDiscipline?.guard?.mode;
|
|
108
|
+
if (gm !== undefined && !/^(off|warn|block)$/.test(gm))
|
|
109
|
+
throw err(`readDiscipline.guard.mode "${gm}" unknown (off | warn | block)`);
|
|
110
|
+
const doc = merged.doctrine;
|
|
111
|
+
if (!doc || typeof doc !== "object" || Array.isArray(doc))
|
|
112
|
+
throw err("doctrine must be an object ({ inject, write })");
|
|
113
|
+
if (doc.inject !== undefined && !/^(kb|off)$/.test(doc.inject))
|
|
114
|
+
throw err(`doctrine.inject "${doc.inject}" unknown (kb | off)`);
|
|
115
|
+
if (doc.write !== undefined && typeof doc.write !== "boolean")
|
|
116
|
+
throw err("doctrine.write must be a boolean");
|
|
100
117
|
const lq = merged.ranking.laneQuota;
|
|
101
118
|
if (typeof lq !== "number" || !Number.isFinite(lq) || lq < 0 || lq > 1)
|
|
102
119
|
throw err("ranking.laneQuota must be a number in [0,1]");
|
|
120
|
+
const llm = merged.ranking.laneLeadMargin;
|
|
121
|
+
if (typeof llm !== "number" || !Number.isFinite(llm) || llm < 0 || llm > 1)
|
|
122
|
+
throw err("ranking.laneLeadMargin must be a number in [0,1]");
|
|
103
123
|
const fm = merged.frontmatter;
|
|
104
124
|
if (!fm || !Array.isArray(fm.searchableKeys) || fm.searchableKeys.some((k) => typeof k !== "string"))
|
|
105
125
|
throw err("frontmatter.searchableKeys must be a string array");
|
|
@@ -134,6 +154,9 @@ export function loadConfig(cwd, opts = {}) {
|
|
|
134
154
|
const project = opts.configPath ? readJson(opts.configPath) : readJson(projectConfigPath(cwd));
|
|
135
155
|
const global = readJson(globalConfigPath());
|
|
136
156
|
const origin = project ? "project" : global ? "global" : "defaults";
|
|
157
|
+
// KEY-presence (a non-null object, `{}` included) — NOT file-presence. A
|
|
158
|
+
// project file holding only `readDiscipline` has recorded no doctrine choice.
|
|
159
|
+
const doctrineSource = project?.doctrine !== undefined ? "project" : global?.doctrine !== undefined ? "global" : "none";
|
|
137
160
|
const merged = validateConfig(mergeConfig(DEFAULTS, global, project), origin);
|
|
138
161
|
// legacy roots[] → filesystem sources
|
|
139
162
|
const fromRoots = (merged.roots ?? []).map((r) => ({ kind: "filesystem", ref: r.path, priority: r.priority }));
|
|
@@ -146,5 +169,5 @@ export function loadConfig(cwd, opts = {}) {
|
|
|
146
169
|
});
|
|
147
170
|
const dbAbsPath = isAbsolute(merged.dbPath) ? merged.dbPath : resolve(cwd, merged.dbPath);
|
|
148
171
|
const cacheDirAbs = expandTilde(merged.sourceCacheDir);
|
|
149
|
-
return { ...merged, cwd, dbAbsPath, cacheDirAbs, allSourceSpecs, resolvedSources, origin };
|
|
172
|
+
return { ...merged, cwd, dbAbsPath, cacheDirAbs, allSourceSpecs, resolvedSources, origin, doctrineSource };
|
|
150
173
|
}
|
package/dist/dox-triage.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type AckRecord } from "./staleness.js";
|
|
1
2
|
import { type DoxIssue } from "./dox.js";
|
|
2
3
|
export declare const ROW_RE: RegExp;
|
|
3
4
|
/** History window scanned for a blob matching the acked hash. */
|
|
@@ -37,7 +38,7 @@ export interface WorkItem {
|
|
|
37
38
|
export declare function buildWorkItems(opts: {
|
|
38
39
|
cwd: string;
|
|
39
40
|
issues: DoxIssue[];
|
|
40
|
-
staleness: Record<string,
|
|
41
|
+
staleness: Record<string, AckRecord>;
|
|
41
42
|
depth?: number;
|
|
42
43
|
limit?: number;
|
|
43
44
|
}): WorkItem[];
|
|
@@ -58,7 +59,7 @@ export declare function applyDecisions(opts: {
|
|
|
58
59
|
decisions: Decision[];
|
|
59
60
|
write?: boolean;
|
|
60
61
|
}): ApplyResult;
|
|
61
|
-
/** Re-acknowledge rows: record each target's
|
|
62
|
+
/** Re-acknowledge rows: record each target's sha256 + stat baseline (v2). */
|
|
62
63
|
export declare function ackTargets(opts: {
|
|
63
64
|
cwd: string;
|
|
64
65
|
targets: string[];
|
package/dist/dox-triage.js
CHANGED
|
@@ -16,6 +16,7 @@ import { execFileSync } from "node:child_process"; // ban:child_process-ok (kb p
|
|
|
16
16
|
import { createHash } from "node:crypto";
|
|
17
17
|
import { existsSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
18
18
|
import { dirname, join, relative } from "node:path";
|
|
19
|
+
import { STALENESS_VERSION, readStaleness, stalenessVersionOnDisk } from "./staleness.js";
|
|
19
20
|
import { resolveRowPath } from "./dox.js";
|
|
20
21
|
export const ROW_RE = /^\|\s*`([^`]+)`\s*\|\s*(.*?)\s*\|\s*$/;
|
|
21
22
|
/** History window scanned for a blob matching the acked hash. */
|
|
@@ -116,8 +117,8 @@ export function buildWorkItems(opts) {
|
|
|
116
117
|
if (!row)
|
|
117
118
|
continue;
|
|
118
119
|
const acked = staleness[target] ?? staleness[iss.path];
|
|
119
|
-
const base = acked
|
|
120
|
-
? resolveBaseline({ cwd, file: target, ackedSha: acked, depth })
|
|
120
|
+
const base = acked?.sha256
|
|
121
|
+
? resolveBaseline({ cwd, file: target, ackedSha: acked.sha256, depth })
|
|
121
122
|
: { found: false, commit: null, diff: "", reason: "not-acked" };
|
|
122
123
|
items.push({
|
|
123
124
|
agentsFile: iss.agentsFile,
|
|
@@ -157,20 +158,26 @@ export function applyDecisions(opts) {
|
|
|
157
158
|
}
|
|
158
159
|
return res;
|
|
159
160
|
}
|
|
160
|
-
/** Re-acknowledge rows: record each target's
|
|
161
|
+
/** Re-acknowledge rows: record each target's sha256 + stat baseline (v2). */
|
|
161
162
|
export function ackTargets(opts) {
|
|
162
163
|
const { cwd, targets, stalenessFile } = opts;
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
164
|
+
// Fail closed: a sidecar from a NEWER version carries records this code
|
|
165
|
+
// cannot see — rewriting it as v2 would silently delete them.
|
|
166
|
+
const onDisk = stalenessVersionOnDisk(stalenessFile);
|
|
167
|
+
if (onDisk != null && onDisk > STALENESS_VERSION) {
|
|
168
|
+
throw new Error(`dox-staleness.json is version ${onDisk} (> supported ${STALENESS_VERSION}); refusing to overwrite — upgrade the kb package first`);
|
|
169
|
+
}
|
|
170
|
+
const map = readStaleness(stalenessFile);
|
|
166
171
|
let n = 0;
|
|
167
172
|
for (const t of targets) {
|
|
168
173
|
const p = join(cwd, t);
|
|
169
174
|
if (!existsSync(p) || !statSync(p).isFile())
|
|
170
175
|
continue;
|
|
171
|
-
|
|
176
|
+
const st = statSync(p);
|
|
177
|
+
map[t] = { sha256: sha256(readFileSync(p)), size: st.size, mtimeMs: st.mtimeMs };
|
|
172
178
|
n++;
|
|
173
179
|
}
|
|
174
|
-
|
|
180
|
+
const file = { version: STALENESS_VERSION, files: map };
|
|
181
|
+
writeFileSync(stalenessFile, `${JSON.stringify(file, null, 2)}\n`, "utf8");
|
|
175
182
|
return n;
|
|
176
183
|
}
|