@blackbelt-technology/pi-dashboard-kb 0.7.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +69 -0
- package/bin/kb.mjs +84 -0
- package/bin/lib/engine-fingerprint.mjs +183 -0
- package/dist/adoc-chunker.d.ts +29 -0
- package/dist/adoc-chunker.js +274 -0
- package/dist/archive-guard.d.ts +12 -0
- package/dist/archive-guard.js +154 -0
- package/dist/chunker.d.ts +3 -0
- package/dist/chunker.js +5 -3
- package/dist/cli.js +137 -19
- package/dist/config.d.ts +49 -0
- package/dist/config.js +43 -6
- package/dist/dox-triage.d.ts +67 -0
- package/dist/dox-triage.js +183 -0
- package/dist/dox.d.ts +68 -7
- package/dist/dox.js +370 -94
- package/dist/eval.d.ts +30 -0
- package/dist/eval.js +120 -13
- package/dist/gitignore.d.ts +24 -0
- package/dist/gitignore.js +205 -0
- package/dist/index.d.ts +25 -17
- package/dist/index.js +17 -8
- package/dist/indexer.d.ts +9 -1
- package/dist/indexer.js +40 -11
- package/dist/net-guard.d.ts +35 -0
- package/dist/net-guard.js +285 -0
- package/dist/render.js +37 -2
- package/dist/search-opts.d.ts +22 -0
- package/dist/search-opts.js +21 -0
- package/dist/sources.d.ts +29 -0
- package/dist/sources.js +230 -32
- package/dist/sqlite-store.d.ts +72 -2
- package/dist/sqlite-store.js +482 -78
- package/dist/staleness.d.ts +25 -0
- package/dist/staleness.js +69 -0
- package/dist/trust.d.ts +33 -1
- package/dist/trust.js +72 -5
- package/dist/types.d.ts +59 -0
- package/dist/verdict.d.ts +45 -0
- package/dist/verdict.js +368 -0
- package/engine-fingerprint.json +5 -0
- package/package.json +8 -4
- package/src/adoc-chunker.ts +308 -0
- package/src/archive-guard.ts +144 -0
- package/src/chunker.ts +5 -3
- package/src/cli.ts +130 -20
- package/src/config.ts +81 -6
- package/src/dox-triage.ts +231 -0
- package/src/dox.ts +390 -70
- package/src/eval.ts +136 -14
- package/src/gitignore.ts +215 -0
- package/src/index.ts +45 -20
- package/src/indexer.ts +46 -10
- package/src/net-guard.ts +288 -0
- package/src/render.ts +35 -3
- package/src/search-opts.ts +52 -0
- package/src/sources.ts +232 -28
- package/src/sqlite-store.ts +448 -67
- package/src/staleness.ts +76 -0
- package/src/trust.ts +81 -8
- package/src/types.ts +58 -0
- package/src/verdict.ts +412 -0
- package/src/AGENTS.md +0 -23
package/dist/eval.js
CHANGED
|
@@ -1,13 +1,105 @@
|
|
|
1
|
+
// Retrieval-quality evaluation (design §6c Tier E, research §2.5).
|
|
2
|
+
// Scores search against a golden `query -> expected path-substring` set.
|
|
3
|
+
// Gate ranking changes on these metrics; track normal + paraphrase sets.
|
|
4
|
+
//
|
|
5
|
+
// change fix-kb-eval-measurement-integrity: loadGolden fixture contract (D3),
|
|
6
|
+
// two-tier expect normalization + filesystem-anchored reachability (D4).
|
|
7
|
+
import { existsSync, readdirSync } from "node:fs";
|
|
8
|
+
const MSG_SHAPES = `a bare array of {q, expect} items or an object with an "items" array`;
|
|
9
|
+
/** Load + validate a golden fixture (design D3). Accepts a bare array or an
|
|
10
|
+
* object with an `items` array (the mined sets' bundled shape); anything else
|
|
11
|
+
* throws naming BOTH accepted shapes + the file. Every item must carry a
|
|
12
|
+
* string `q` and a string `expect` — today a non-string expect is a SILENT
|
|
13
|
+
* zero (`includes(undefined)`); rejected items name file + array index.
|
|
14
|
+
* Provenance (`intent`/`minedAt` on the object shape) prints a stderr header
|
|
15
|
+
* and never affects scoring; stdout stays byte-clean for `--json` pipes. */
|
|
16
|
+
export function loadGolden(raw, file) {
|
|
17
|
+
const isObj = raw !== null && typeof raw === "object" && !Array.isArray(raw);
|
|
18
|
+
const items = Array.isArray(raw) ? raw : isObj && Array.isArray(raw.items) ? (raw.items) : undefined;
|
|
19
|
+
if (!items)
|
|
20
|
+
throw new Error(`golden fixture must be ${MSG_SHAPES} — got neither in ${file}`);
|
|
21
|
+
const out = items.map((it, i) => {
|
|
22
|
+
if (it === null || typeof it !== "object" || typeof it.q !== "string" || typeof it.expect !== "string") {
|
|
23
|
+
throw new Error(`${file}: golden item [${i}] must be an object with string "q" and string "expect"`);
|
|
24
|
+
}
|
|
25
|
+
return { q: it.q, expect: it.expect };
|
|
26
|
+
});
|
|
27
|
+
const p = isObj ? raw : undefined;
|
|
28
|
+
if (p && (p.intent !== undefined || p.minedAt !== undefined)) {
|
|
29
|
+
console.error(`[kb eval] golden set ${file}: intent=${JSON.stringify(p.intent ?? null)} minedAt=${JSON.stringify(p.minedAt ?? null)} n=${out.length}`);
|
|
30
|
+
}
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
/** Normalize a relPrefix: forward slashes, no trailing separator, no "./". */
|
|
34
|
+
function normPrefix(p) {
|
|
35
|
+
return (p ?? "").replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
|
|
36
|
+
}
|
|
37
|
+
function hasSep(expect) {
|
|
38
|
+
return expect.includes("/") || expect.includes("\\");
|
|
39
|
+
}
|
|
40
|
+
function firstSeg(expect) {
|
|
41
|
+
return normPrefix(expect).split("/")[0];
|
|
42
|
+
}
|
|
1
43
|
export function evaluate(store, golden, opts = {}) {
|
|
2
|
-
const k =
|
|
3
|
-
|
|
44
|
+
const { k = 10, roots, verbose, ...search } = opts;
|
|
45
|
+
// --- Reachability scaffolding (design D4, filesystem-anchored). ---
|
|
46
|
+
const firstSegs = new Set(); // (a) first segments of configured root prefixes
|
|
47
|
+
const topSegs = new Set(); // (b) top-level entries of the configured root dirs
|
|
48
|
+
for (const r of roots ?? []) {
|
|
49
|
+
// An empty-relPrefix root (root === cwd) has NO first segment to contribute
|
|
50
|
+
// to rule (a); it still contributes its top-level entries to rule (b). Only
|
|
51
|
+
// named roots can satisfy rule (a) — an item under a named root is inside
|
|
52
|
+
// the configured roots and must never be marked unreachable (spec R3).
|
|
53
|
+
if (r.dir && existsSync(r.dir)) {
|
|
54
|
+
try {
|
|
55
|
+
for (const e of readdirSync(r.dir))
|
|
56
|
+
topSegs.add(e);
|
|
57
|
+
}
|
|
58
|
+
catch {
|
|
59
|
+
// unreadable root dir → rule (b) contributes nothing for it
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
const rel = normPrefix(r.relPrefix);
|
|
63
|
+
if (rel)
|
|
64
|
+
firstSegs.add(rel.split("/")[0]);
|
|
65
|
+
}
|
|
66
|
+
const isUnreachable = (expect) => {
|
|
67
|
+
if (!hasSep(expect))
|
|
68
|
+
return false; // bare basename → reachable attempt
|
|
69
|
+
const seg = firstSeg(expect);
|
|
70
|
+
if (firstSegs.has(seg))
|
|
71
|
+
return false; // rule (a)
|
|
72
|
+
return !topSegs.has(seg); // rule (b): first segment is a top-level entry of some root dir
|
|
73
|
+
};
|
|
74
|
+
// --- Candidate generation: longest separator-checked prefix strip. ---
|
|
75
|
+
const prefixes = (roots ?? []).map((r) => normPrefix(r.relPrefix)).filter((p) => p.length > 0).sort((a, b) => b.length - a.length);
|
|
76
|
+
const candidates = (expect) => {
|
|
77
|
+
for (const p of prefixes) {
|
|
78
|
+
if (expect.startsWith(p + "/") || expect.startsWith(p + "\\"))
|
|
79
|
+
return [expect.slice(p.length + 1), expect];
|
|
80
|
+
}
|
|
81
|
+
return [expect]; // raw expect always kept as a second candidate
|
|
82
|
+
};
|
|
83
|
+
let p1 = 0, p5 = 0, recall = 0, mrr = 0, ndcg = 0, lat = 0, searched = 0;
|
|
84
|
+
// Redundancy accumulators (D8). Precision/recall are blind to page composition
|
|
85
|
+
// by construction, so redundancy is tracked as its own first-class metric.
|
|
86
|
+
let distinct = 0, dupShare = 0, singleSource = 0, pages = 0;
|
|
87
|
+
const unreachablePaths = [];
|
|
4
88
|
for (const g of golden) {
|
|
89
|
+
// Unreachable items are decided BEFORE retrieval: no search call, no
|
|
90
|
+
// latency, no contribution to any rank/redundancy/latency metric (D4).
|
|
91
|
+
if (isUnreachable(g.expect)) {
|
|
92
|
+
unreachablePaths.push(g.expect);
|
|
93
|
+
continue;
|
|
94
|
+
}
|
|
95
|
+
const cands = candidates(g.expect);
|
|
5
96
|
const t = performance.now();
|
|
6
|
-
const res = store.search(g.q, { ...
|
|
97
|
+
const res = store.search(g.q, { ...search, limit: k });
|
|
7
98
|
lat += performance.now() - t;
|
|
99
|
+
searched++;
|
|
8
100
|
let first = 0;
|
|
9
101
|
res.forEach((r, i) => {
|
|
10
|
-
if (!first && r.path.includes(
|
|
102
|
+
if (!first && cands.some((c) => r.path.includes(c)))
|
|
11
103
|
first = i + 1;
|
|
12
104
|
});
|
|
13
105
|
if (first === 1)
|
|
@@ -19,15 +111,30 @@ export function evaluate(store, golden, opts = {}) {
|
|
|
19
111
|
mrr += 1 / first;
|
|
20
112
|
ndcg += 1 / Math.log2(first + 1); // IDCG=1 (single relevant target)
|
|
21
113
|
}
|
|
114
|
+
if (res.length) {
|
|
115
|
+
const sources = new Set(res.map((r) => `${r.root}\u001f${r.path}`));
|
|
116
|
+
distinct += sources.size;
|
|
117
|
+
dupShare += (res.length - sources.size) / res.length;
|
|
118
|
+
if (sources.size === 1)
|
|
119
|
+
singleSource++;
|
|
120
|
+
pages++;
|
|
121
|
+
}
|
|
22
122
|
}
|
|
23
|
-
const n = golden.length
|
|
24
|
-
|
|
25
|
-
n
|
|
26
|
-
"P@1": +(p1 / n).toFixed(3),
|
|
27
|
-
"P@5": +(p5 / n).toFixed(3),
|
|
28
|
-
"Recall@K": +(recall / n).toFixed(3),
|
|
29
|
-
MRR: +(mrr / n).toFixed(3),
|
|
30
|
-
"nDCG@K": +(ndcg / n).toFixed(3),
|
|
31
|
-
|
|
123
|
+
const n = searched; // golden.length - unreachable; may be 0 → all metrics 0
|
|
124
|
+
const m = {
|
|
125
|
+
n,
|
|
126
|
+
"P@1": +(p1 / (n || 1)).toFixed(3),
|
|
127
|
+
"P@5": +(p5 / (n || 1)).toFixed(3),
|
|
128
|
+
"Recall@K": +(recall / (n || 1)).toFixed(3),
|
|
129
|
+
MRR: +(mrr / (n || 1)).toFixed(3),
|
|
130
|
+
"nDCG@K": +(ndcg / (n || 1)).toFixed(3),
|
|
131
|
+
distinctSourcesAtK: +(distinct / (pages || 1)).toFixed(3),
|
|
132
|
+
duplicateSlotShare: +(dupShare / (pages || 1)).toFixed(3),
|
|
133
|
+
singleSourcePageRate: +(singleSource / (pages || 1)).toFixed(3),
|
|
134
|
+
avgLatencyMs: +(lat / (n || 1)).toFixed(2),
|
|
135
|
+
unreachable: unreachablePaths.length,
|
|
32
136
|
};
|
|
137
|
+
if (verbose)
|
|
138
|
+
m.unreachablePaths = [...unreachablePaths];
|
|
139
|
+
return m;
|
|
33
140
|
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export interface GitignoreMatcher {
|
|
2
|
+
/** File candidate: gitignore verdict for a walk-root-relative path. */
|
|
3
|
+
isIgnored(relPath: string): boolean;
|
|
4
|
+
/** Directory candidate: does a pattern match this directory itself? */
|
|
5
|
+
isIgnoredDir(relPath: string): boolean;
|
|
6
|
+
/** True when a `.gitignore` exists at or below this dir — hard-pruning the
|
|
7
|
+
* dir would blind a deeper negation (design D3 conservative pruning). */
|
|
8
|
+
hasDeeperGitignore(relPath: string): boolean;
|
|
9
|
+
}
|
|
10
|
+
export interface GitignoreMatcherOptions {
|
|
11
|
+
/** Project boundary for the up-walk (usually the cwd the walk serves). The
|
|
12
|
+
* up-walk stops at a `.git` dir, at `cwd`, or when it would leave the cwd
|
|
13
|
+
* subtree. Omit to stop at `.git` / fs root only. */
|
|
14
|
+
cwd?: string;
|
|
15
|
+
/** Dirs never descended when collecting nested `.gitignore` files (the
|
|
16
|
+
* walk's own exclude test, e.g. dox.ts DEFAULT_EXCLUDE). */
|
|
17
|
+
prune?: (relFromWalkRoot: string) => boolean;
|
|
18
|
+
}
|
|
19
|
+
/** Pure single-pattern test (base = ""): does this gitignore line match the
|
|
20
|
+
* path? Negation flips the loader's verdict, not the match itself. */
|
|
21
|
+
export declare function patternMatches(rawPattern: string, relPath: string, opts?: {
|
|
22
|
+
dir?: boolean;
|
|
23
|
+
}): boolean;
|
|
24
|
+
export declare function loadGitignoreMatcher(walkRoot: string, opts?: GitignoreMatcherOptions): GitignoreMatcher;
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// gitignore-honouring walk filter for the kb dox walks + indexer (design D3,
|
|
2
|
+
// fix-dox-lint-blind-rows). Best-effort git semantics, case-SENSITIVE:
|
|
3
|
+
// bare names, `dir/`, `*.ext`, mid-name globs, `**` (leading/mid/trailing),
|
|
4
|
+
// bare `*` + file negations, `!` negation (dir + content + root-level file
|
|
5
|
+
// forms), leading-slash anchors. Last-match-wins within a file; a deeper
|
|
6
|
+
// `.gitignore` overrides a shallower one. The pattern stack is seeded by an
|
|
7
|
+
// up-walk from the walk start to the repo root (`.git` boundary or the project
|
|
8
|
+
// cwd), so root-anchored patterns apply from nested walk roots.
|
|
9
|
+
// NOT implemented (design Non-Goals): the tracked-file override and character
|
|
10
|
+
// classes — brackets are matched literally; an UNbalanced-bracket line is
|
|
11
|
+
// skipped without throwing (X2).
|
|
12
|
+
import { existsSync, readdirSync, readFileSync } from "node:fs";
|
|
13
|
+
import { dirname, join, relative, sep } from "node:path";
|
|
14
|
+
/** Pure single-pattern test (base = ""): does this gitignore line match the
|
|
15
|
+
* path? Negation flips the loader's verdict, not the match itself. */
|
|
16
|
+
export function patternMatches(rawPattern, relPath, opts = {}) {
|
|
17
|
+
const pat = compile(rawPattern);
|
|
18
|
+
if (!pat)
|
|
19
|
+
return false;
|
|
20
|
+
return matches(pat, relPath, opts.dir === true);
|
|
21
|
+
}
|
|
22
|
+
function compile(raw) {
|
|
23
|
+
const p0 = raw.replace(/\s+$/, ""); // git trims trailing (unescaped) whitespace
|
|
24
|
+
if (p0 === "" || p0.startsWith("#"))
|
|
25
|
+
return null;
|
|
26
|
+
let p = p0;
|
|
27
|
+
const negated = p.startsWith("!");
|
|
28
|
+
if (negated)
|
|
29
|
+
p = p.slice(1);
|
|
30
|
+
const dirOnly = p.endsWith("/");
|
|
31
|
+
if (dirOnly)
|
|
32
|
+
p = p.replace(/\/+$/, "");
|
|
33
|
+
let anchored;
|
|
34
|
+
if (p.startsWith("/")) {
|
|
35
|
+
anchored = true;
|
|
36
|
+
p = p.slice(1);
|
|
37
|
+
}
|
|
38
|
+
else if (p.startsWith("**/")) {
|
|
39
|
+
p = p.slice(3); // `**/foo` matches at any depth ≡ unanchored `foo`
|
|
40
|
+
anchored = false;
|
|
41
|
+
}
|
|
42
|
+
else {
|
|
43
|
+
anchored = p.includes("/");
|
|
44
|
+
}
|
|
45
|
+
if (p === "" || p === "!")
|
|
46
|
+
return null;
|
|
47
|
+
// Unbalanced brackets = malformed line (git skips it); balanced brackets are
|
|
48
|
+
// matched literally (no character-class support — pass-through escaping).
|
|
49
|
+
for (const seg of p.split("/")) {
|
|
50
|
+
const open = (seg.match(/\[/g) ?? []).length;
|
|
51
|
+
const close = (seg.match(/\]/g) ?? []).length;
|
|
52
|
+
if (open !== close)
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
const segs = p.split("/");
|
|
56
|
+
let body;
|
|
57
|
+
if (segs.length === 1 && segs[0] === "**") {
|
|
58
|
+
body = ".+";
|
|
59
|
+
}
|
|
60
|
+
else {
|
|
61
|
+
body = "";
|
|
62
|
+
for (let i = 0; i < segs.length; i++) {
|
|
63
|
+
const isLast = i === segs.length - 1;
|
|
64
|
+
const seg = segs[i];
|
|
65
|
+
if (seg === "**") {
|
|
66
|
+
body += isLast ? ".+" : "(?:[^/]+/)*";
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
body += segRe(seg);
|
|
70
|
+
if (!isLast)
|
|
71
|
+
body += "/";
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
const full = anchored ? body : `(?:[^/]+/)*${body}`;
|
|
75
|
+
let re = null;
|
|
76
|
+
try {
|
|
77
|
+
re = new RegExp(`^${full}$`);
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
re = null;
|
|
81
|
+
}
|
|
82
|
+
return { negated, dirOnly, anchored, re };
|
|
83
|
+
}
|
|
84
|
+
function segRe(seg) {
|
|
85
|
+
return seg
|
|
86
|
+
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
|
|
87
|
+
.replace(/\*\*/g, "*") // non-special consecutive asterisks ≡ regular *
|
|
88
|
+
.replace(/\*/g, "[^/]*")
|
|
89
|
+
.replace(/\?/g, "[^/]");
|
|
90
|
+
}
|
|
91
|
+
function ancestorsOf(rel) {
|
|
92
|
+
const out = [];
|
|
93
|
+
const parts = rel.split("/");
|
|
94
|
+
parts.pop(); // drop the file name
|
|
95
|
+
let cur = "";
|
|
96
|
+
for (const part of parts) {
|
|
97
|
+
cur = cur ? `${cur}/${part}` : part;
|
|
98
|
+
out.push(cur);
|
|
99
|
+
}
|
|
100
|
+
return out;
|
|
101
|
+
}
|
|
102
|
+
function matches(pat, rel, dirMode) {
|
|
103
|
+
if (!pat.re)
|
|
104
|
+
return false;
|
|
105
|
+
if (dirMode) {
|
|
106
|
+
// A directory candidate matches when the pattern matches the dir path
|
|
107
|
+
// itself (dirOnly or not — a bare name ignores the dir AND its contents).
|
|
108
|
+
return pat.re.test(rel);
|
|
109
|
+
}
|
|
110
|
+
if (pat.dirOnly)
|
|
111
|
+
return ancestorsOf(rel).some((a) => pat.re.test(a));
|
|
112
|
+
if (pat.re.test(rel))
|
|
113
|
+
return true;
|
|
114
|
+
// Unanchored name also ignores the contents of a matching directory.
|
|
115
|
+
if (!pat.anchored)
|
|
116
|
+
return ancestorsOf(rel).some((a) => pat.re.test(a));
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
export function loadGitignoreMatcher(walkRoot, opts = {}) {
|
|
120
|
+
const boundary = opts.cwd;
|
|
121
|
+
const sets = [];
|
|
122
|
+
const nestedBases = []; // walk-root-relative dirs holding a .gitignore
|
|
123
|
+
const parseFile = (abs) => {
|
|
124
|
+
let text = "";
|
|
125
|
+
try {
|
|
126
|
+
text = readFileSync(abs, "utf8");
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
const patterns = [];
|
|
132
|
+
for (const line of text.split("\n")) {
|
|
133
|
+
const pat = compile(line);
|
|
134
|
+
if (pat)
|
|
135
|
+
patterns.push(pat);
|
|
136
|
+
}
|
|
137
|
+
if (patterns.length)
|
|
138
|
+
sets.push({ baseAbs: dirname(abs), patterns });
|
|
139
|
+
};
|
|
140
|
+
// 1. Seed: up-walk from the walk start collecting ancestor .gitignore files,
|
|
141
|
+
// shallow-most first (stack order = later/deeper overrides earlier).
|
|
142
|
+
const up = [];
|
|
143
|
+
for (let d = walkRoot;; d = dirname(d)) {
|
|
144
|
+
up.push(d);
|
|
145
|
+
if (existsSync(join(d, ".git")))
|
|
146
|
+
break; // repo root reached
|
|
147
|
+
if (boundary && d === boundary)
|
|
148
|
+
break; // project boundary reached
|
|
149
|
+
if (boundary && !d.startsWith(boundary + sep))
|
|
150
|
+
break; // left the project subtree
|
|
151
|
+
const parent = dirname(d);
|
|
152
|
+
if (parent === d)
|
|
153
|
+
break; // fs root
|
|
154
|
+
}
|
|
155
|
+
for (const d of up.reverse()) {
|
|
156
|
+
if (d === walkRoot)
|
|
157
|
+
continue; // walk root's own file comes from the descend phase
|
|
158
|
+
if (existsSync(join(d, ".gitignore")))
|
|
159
|
+
parseFile(join(d, ".gitignore"));
|
|
160
|
+
}
|
|
161
|
+
// 2. Descend: nested .gitignore files under the walk root (pre-order =
|
|
162
|
+
// shallow before deep). Pruned dirs are skipped — the walk never visits
|
|
163
|
+
// them, so their patterns could never apply.
|
|
164
|
+
const scan = (dir) => {
|
|
165
|
+
const rel = relative(walkRoot, dir).split(sep).join("/");
|
|
166
|
+
if (rel && opts.prune?.(rel))
|
|
167
|
+
return;
|
|
168
|
+
if (existsSync(join(dir, ".gitignore"))) {
|
|
169
|
+
parseFile(join(dir, ".gitignore"));
|
|
170
|
+
nestedBases.push(rel);
|
|
171
|
+
}
|
|
172
|
+
let entries;
|
|
173
|
+
try {
|
|
174
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
175
|
+
}
|
|
176
|
+
catch {
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
for (const e of entries.sort((a, b) => a.name.localeCompare(b.name))) {
|
|
180
|
+
if (e.isDirectory() && e.name !== ".git")
|
|
181
|
+
scan(join(dir, e.name));
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
scan(walkRoot);
|
|
185
|
+
const verdictFor = (rel, dirMode) => {
|
|
186
|
+
const abs = join(walkRoot, rel);
|
|
187
|
+
let verdict = false;
|
|
188
|
+
for (const set of sets) {
|
|
189
|
+
const baseRel = relative(set.baseAbs, abs);
|
|
190
|
+
if (!baseRel || baseRel.startsWith(".."))
|
|
191
|
+
continue;
|
|
192
|
+
const p = baseRel.split(sep).join("/");
|
|
193
|
+
for (const pat of set.patterns) {
|
|
194
|
+
if (matches(pat, p, dirMode))
|
|
195
|
+
verdict = !pat.negated;
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
return verdict;
|
|
199
|
+
};
|
|
200
|
+
return {
|
|
201
|
+
isIgnored: (rel) => verdictFor(rel, false),
|
|
202
|
+
isIgnoredDir: (rel) => verdictFor(rel, true),
|
|
203
|
+
hasDeeperGitignore: (rel) => nestedBases.some((b) => b === rel || b.startsWith(`${rel}/`)),
|
|
204
|
+
};
|
|
205
|
+
}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,20 +1,28 @@
|
|
|
1
|
-
export type {
|
|
2
|
-
export {
|
|
3
|
-
export type { FmValue, FacetKeyConfig, ParsedFrontmatter, PropertyRow } from "./frontmatter.js";
|
|
4
|
-
export { renderHits } from "./render.js";
|
|
5
|
-
export type { RenderOpts } from "./render.js";
|
|
6
|
-
export { chunkMarkdown } from "./chunker.js";
|
|
1
|
+
export type { AdocChunkInput, AdocParseResult } from "./adoc-chunker.js";
|
|
2
|
+
export { chunkAsciiDoc, extractXrefs, NEGATED } from "./adoc-chunker.js";
|
|
7
3
|
export type { ChunkInput, ParseResult } from "./chunker.js";
|
|
8
|
-
export {
|
|
4
|
+
export { chunkMarkdown } from "./chunker.js";
|
|
5
|
+
export type { DoctrineConfig, FrontmatterConfig, GuardMode, KbConfig, RankingConfig, ReadDisciplineConfig, ResolvedConfig, SourceConfig } from "./config.js";
|
|
6
|
+
export { DEFAULTS, frontmatterConfigHash, loadConfig, validateConfig } from "./config.js";
|
|
7
|
+
export type { AgentsEntry, DoxInitPlan, DoxIssue, DoxLintResult } from "./dox.js";
|
|
8
|
+
export { agentsChain, doxInit, doxLint, fallbackManifest, parseRowPaths, resolveRowPath } from "./dox.js";
|
|
9
|
+
export { ackTargets, applyDecisions, buildWorkItems, parseRows, replaceRowPurpose } from "./dox-triage.js";
|
|
10
|
+
export type { FacetKeyConfig, FmValue, ParsedFrontmatter, PropertyRow } from "./frontmatter.js";
|
|
11
|
+
export { buildMeta, buildProperties, DEFAULT_FACET_KEYS, DEFAULT_SEARCHABLE_KEYS, parseFrontmatter, strictDate, strictNumber } from "./frontmatter.js";
|
|
12
|
+
export type { IndexOptions, IndexSource, IndexStats } from "./indexer.js";
|
|
9
13
|
export { indexSource } from "./indexer.js";
|
|
10
|
-
export type { IndexSource, IndexOptions, IndexStats } from "./indexer.js";
|
|
11
|
-
export { kbInit } from "./init.js";
|
|
12
14
|
export type { InitOptions, InitResult } from "./init.js";
|
|
13
|
-
export {
|
|
14
|
-
export type {
|
|
15
|
-
export {
|
|
16
|
-
export {
|
|
17
|
-
export
|
|
18
|
-
export {
|
|
19
|
-
export {
|
|
20
|
-
export
|
|
15
|
+
export { kbInit } from "./init.js";
|
|
16
|
+
export type { RenderOpts } from "./render.js";
|
|
17
|
+
export { renderHits } from "./render.js";
|
|
18
|
+
export type { SearchOptsOverrides } from "./search-opts.js";
|
|
19
|
+
export { searchOptsFromConfig } from "./search-opts.js";
|
|
20
|
+
export type { KbSourceKind, ResolveCtx, ResolvedSource, SourceResolver } from "./sources.js";
|
|
21
|
+
export { classifyRef, KbUntrustedSourceError, resolveAll, resolverFor, sourceIdentity } from "./sources.js";
|
|
22
|
+
export { SCHEMA_VERSION, SqliteFtsStore } from "./sqlite-store.js";
|
|
23
|
+
export type { AckRecord, StalenessFile } from "./staleness.js";
|
|
24
|
+
export { readStaleness, STALENESS_VERSION, stalenessVersionOnDisk } from "./staleness.js";
|
|
25
|
+
export { canonicalSource, isTrusted, listTrustedSources, recordTrust, revokeTrust, revokeTrustByHash, sourceHash, sourceSubject, } from "./trust.js";
|
|
26
|
+
export type { Chunk, DocType, FileState, Filter, GraphEdge, GraphNode, HitVerdict, KbHit, KbStore, SearchOpts, StorePropertyRow, VerdictCounts, VerdictLabel, } from "./types.js";
|
|
27
|
+
export type { EnrichCtx, VerdictFs } from "./verdict.js";
|
|
28
|
+
export { COVERAGE_CAP_BYTES, enrichHits, HASH_CAP_BYTES, SUBJECT_CAP } from "./verdict.js";
|
package/dist/index.js
CHANGED
|
@@ -1,11 +1,20 @@
|
|
|
1
|
-
|
|
2
|
-
export {
|
|
1
|
+
// Public API barrel for @blackbelt-technology/pi-dashboard-kb (Phase 1 slice).
|
|
2
|
+
export { chunkAsciiDoc, extractXrefs, NEGATED } from "./adoc-chunker.js";
|
|
3
3
|
export { chunkMarkdown } from "./chunker.js";
|
|
4
|
-
export {
|
|
4
|
+
export { DEFAULTS, frontmatterConfigHash, loadConfig, validateConfig } from "./config.js";
|
|
5
|
+
export { agentsChain, doxInit, doxLint, fallbackManifest, parseRowPaths, resolveRowPath } from "./dox.js";
|
|
6
|
+
export { ackTargets, applyDecisions, buildWorkItems, parseRows, replaceRowPurpose } from "./dox-triage.js";
|
|
7
|
+
export { buildMeta, buildProperties, DEFAULT_FACET_KEYS, DEFAULT_SEARCHABLE_KEYS, parseFrontmatter, strictDate, strictNumber } from "./frontmatter.js";
|
|
5
8
|
export { indexSource } from "./indexer.js";
|
|
6
9
|
export { kbInit } from "./init.js";
|
|
7
|
-
export {
|
|
8
|
-
export {
|
|
9
|
-
export {
|
|
10
|
-
export {
|
|
11
|
-
export {
|
|
10
|
+
export { renderHits } from "./render.js";
|
|
11
|
+
export { searchOptsFromConfig } from "./search-opts.js";
|
|
12
|
+
export { classifyRef, KbUntrustedSourceError, resolveAll, resolverFor, sourceIdentity } from "./sources.js";
|
|
13
|
+
export { SCHEMA_VERSION, SqliteFtsStore } from "./sqlite-store.js";
|
|
14
|
+
export { readStaleness, STALENESS_VERSION, stalenessVersionOnDisk } from "./staleness.js";
|
|
15
|
+
// The Access review surface (change: add-access-grants-and-review) needs the
|
|
16
|
+
// trust store's revoke + displayable listing. Exported from the package ROOT
|
|
17
|
+
// because kb's `exports` map exposes only "." — a `/trust.js` subpath import
|
|
18
|
+
// does not resolve.
|
|
19
|
+
export { canonicalSource, isTrusted, listTrustedSources, recordTrust, revokeTrust, revokeTrustByHash, sourceHash, sourceSubject, } from "./trust.js";
|
|
20
|
+
export { COVERAGE_CAP_BYTES, enrichHits, HASH_CAP_BYTES, SUBJECT_CAP } from "./verdict.js";
|
package/dist/indexer.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type FacetKeyConfig } from "./frontmatter.js";
|
|
2
|
-
import type { KbStore } from "./types.js";
|
|
2
|
+
import type { DocType, KbStore } from "./types.js";
|
|
3
3
|
export interface IndexSource {
|
|
4
4
|
root: string;
|
|
5
5
|
dir: string;
|
|
@@ -16,6 +16,13 @@ export interface IndexOptions {
|
|
|
16
16
|
searchableKeys: string[];
|
|
17
17
|
facetKeys: FacetKeyConfig[];
|
|
18
18
|
};
|
|
19
|
+
/** Honour `.gitignore` in the walk (design D3, fix-dox-lint-blind-rows).
|
|
20
|
+
* Default true — makes the long-declared `respectGitignore` config real.
|
|
21
|
+
* A source dir absent from a fresh clone must not be indexed. */
|
|
22
|
+
respectGitignore?: boolean;
|
|
23
|
+
/** Project boundary for the gitignore up-walk (usually the resolved cwd).
|
|
24
|
+
* Omit to seed the pattern stack from the `.git` root discovered upward. */
|
|
25
|
+
cwd?: string;
|
|
19
26
|
}
|
|
20
27
|
export interface IndexStats {
|
|
21
28
|
scanned: number;
|
|
@@ -25,4 +32,5 @@ export interface IndexStats {
|
|
|
25
32
|
parseFailures?: number;
|
|
26
33
|
missing?: boolean;
|
|
27
34
|
}
|
|
35
|
+
export declare function docTypeOf(rel: string, includeSourceMarkdown: boolean): DocType;
|
|
28
36
|
export declare function indexSource(store: KbStore, src: IndexSource, opts?: IndexOptions): Promise<IndexStats>;
|
package/dist/indexer.js
CHANGED
|
@@ -3,10 +3,22 @@
|
|
|
3
3
|
import { createHash } from "node:crypto";
|
|
4
4
|
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
5
5
|
import { join, relative } from "node:path";
|
|
6
|
+
import { chunkAsciiDoc } from "./adoc-chunker.js";
|
|
6
7
|
import { chunkMarkdown } from "./chunker.js";
|
|
7
|
-
import {
|
|
8
|
+
import { buildMeta, buildProperties, DEFAULT_FACET_KEYS, DEFAULT_SEARCHABLE_KEYS } from "./frontmatter.js";
|
|
9
|
+
import { loadGitignoreMatcher } from "./gitignore.js";
|
|
8
10
|
const sha = (s) => createHash("sha256").update(s).digest("hex");
|
|
9
11
|
const DEFAULT_EXCLUDE = /(^|\/)(node_modules|\.git|dist|build|\.next|coverage|\.kb)(\/|$)/;
|
|
12
|
+
/** Selectable source extensions. Widened together with `config.ts` defaults and
|
|
13
|
+
* the per-extension chunker dispatch (design D4) — widening one gate alone
|
|
14
|
+
* indexes zero extra files. */
|
|
15
|
+
const SELECTABLE_RE = /\.(md|mdx|markdown|adoc|asciidoc)$/i;
|
|
16
|
+
const ADOC_RE = /\.(adoc|asciidoc)$/i;
|
|
17
|
+
/** Extension strip for the meta-chunk heading fallback. Reached only when a file
|
|
18
|
+
* HAS frontmatter/attributes but no title; an AsciiDoc header always carries a
|
|
19
|
+
* doctitle, so a headerless `.adoc` gets its `guide`-style heading from the
|
|
20
|
+
* chunker's own file-name fallback, not from here. */
|
|
21
|
+
const TITLE_EXT_RE = /\.(md|mdx|markdown|adoc|asciidoc)$/i;
|
|
10
22
|
/** Files processed between event-loop yields + batch commits. A long synchronous
|
|
11
23
|
* walk would otherwise pin the single Node thread for its whole duration, so a
|
|
12
24
|
* concurrent `/stats` reader could never observe `indexing:true` (no spinner)
|
|
@@ -14,6 +26,10 @@ const DEFAULT_EXCLUDE = /(^|\/)(node_modules|\.git|dist|build|\.next|coverage|\.
|
|
|
14
26
|
* write lock so the reader is served. See change: fix-kb-index-feedback. */
|
|
15
27
|
const YIELD_EVERY = 100;
|
|
16
28
|
const yieldToEventLoop = () => new Promise((r) => setImmediate(r));
|
|
29
|
+
/** Escape every RegExp metacharacter in a literal. */
|
|
30
|
+
function escapeRegExp(s) {
|
|
31
|
+
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
32
|
+
}
|
|
17
33
|
/** Minimal glob → RegExp (supports **, *, ?). Good enough for include/exclude. */
|
|
18
34
|
function globToRe(g) {
|
|
19
35
|
const body = g
|
|
@@ -29,25 +45,30 @@ function globToRe(g) {
|
|
|
29
45
|
function matchAny(pats, rel) {
|
|
30
46
|
return pats.some((re) => re.test(rel));
|
|
31
47
|
}
|
|
32
|
-
function walk(dir, base, out = []) {
|
|
48
|
+
function walk(dir, base, out = [], ignore) {
|
|
33
49
|
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
|
34
50
|
const abs = join(dir, e.name);
|
|
35
51
|
const rel = relative(base, abs);
|
|
36
52
|
if (DEFAULT_EXCLUDE.test(rel))
|
|
37
53
|
continue;
|
|
38
|
-
if (e.isDirectory())
|
|
39
|
-
|
|
40
|
-
|
|
54
|
+
if (e.isDirectory()) {
|
|
55
|
+
// Conservative dir-pruning (design D3): descend unless the dir matches
|
|
56
|
+
// AND no deeper .gitignore could negate the match.
|
|
57
|
+
if (ignore?.isIgnoredDir(rel) && !ignore.hasDeeperGitignore(rel))
|
|
58
|
+
continue;
|
|
59
|
+
walk(abs, base, out, ignore);
|
|
60
|
+
}
|
|
61
|
+
else if (SELECTABLE_RE.test(e.name) && !ignore?.isIgnored(rel))
|
|
41
62
|
out.push(abs);
|
|
42
63
|
}
|
|
43
64
|
return out;
|
|
44
65
|
}
|
|
45
|
-
function docTypeOf(rel, includeSourceMarkdown) {
|
|
66
|
+
export function docTypeOf(rel, includeSourceMarkdown) {
|
|
46
67
|
const base = rel.split("/").pop() ?? "";
|
|
47
68
|
// `<File>.AGENTS.md` = per-file index sidecar (large-row promotion). Classified
|
|
48
69
|
// `agents` so it is searchable, but its name != "AGENTS.md" so pi's native
|
|
49
70
|
// up-walk never auto-injects it (pull-only via kb search).
|
|
50
|
-
if (base === "AGENTS.md" || base === "CLAUDE.md" || base.endsWith(".AGENTS.md"))
|
|
71
|
+
if (base === "AGENTS.override.md" || base === "AGENTS.md" || base === "CLAUDE.md" || base.endsWith(".AGENTS.md"))
|
|
51
72
|
return "agents";
|
|
52
73
|
if (includeSourceMarkdown && /(^|\/)(src|lib|app|packages)\//.test(rel))
|
|
53
74
|
return "source-md";
|
|
@@ -61,11 +82,17 @@ export async function indexSource(store, src, opts = {}) {
|
|
|
61
82
|
console.warn(`kb index: source directory does not exist, skipping: ${src.dir}`);
|
|
62
83
|
return { scanned: 0, changed: 0, deleted: 0, chunks: 0, missing: true };
|
|
63
84
|
}
|
|
64
|
-
|
|
85
|
+
// NOTE: `extRe` is dead (never applied to the file list) — kept as-is, only its
|
|
86
|
+
// default widened alongside the live gates. See design D4.
|
|
87
|
+
// Escape EVERY regex metacharacter, not just `.` — a caller-supplied extension
|
|
88
|
+
// is untrusted input and a lone `\` escape leaves the pattern injectable
|
|
89
|
+
// (`js/incomplete-sanitization`).
|
|
90
|
+
const extRe = opts.extensions?.length ? new RegExp("(" + opts.extensions.map(escapeRegExp).join("|") + ")$", "i") : SELECTABLE_RE;
|
|
65
91
|
const inc = opts.include?.map(globToRe);
|
|
66
92
|
const exc = opts.exclude?.map(globToRe);
|
|
67
93
|
const includeSourceMd = opts.includeSourceMarkdown !== false;
|
|
68
|
-
const
|
|
94
|
+
const gi = opts.respectGitignore === false ? undefined : loadGitignoreMatcher(src.dir, { cwd: opts.cwd, prune: (rel) => DEFAULT_EXCLUDE.test(rel) });
|
|
95
|
+
const files = walk(src.dir, src.dir, [], gi).filter((abs) => {
|
|
69
96
|
const rel = relative(src.dir, abs);
|
|
70
97
|
if (src.include && !src.include(rel))
|
|
71
98
|
return false;
|
|
@@ -110,7 +137,9 @@ export async function indexSource(store, src, opts = {}) {
|
|
|
110
137
|
// changed → replace
|
|
111
138
|
store.deleteByPath(src.root, rel);
|
|
112
139
|
const dt = docTypeOf(rel, includeSourceMd);
|
|
113
|
-
|
|
140
|
+
// per-extension chunker dispatch (design D4)
|
|
141
|
+
const chunkFile = ADOC_RE.test(rel) ? chunkAsciiDoc : chunkMarkdown;
|
|
142
|
+
const { chunks, wikilinks, mdLinks, frontmatter, parseFailed } = chunkFile({ root: src.root, path: rel, text: buf.toString("utf8"), docType: dt });
|
|
114
143
|
// file node
|
|
115
144
|
store.addNode({ type: "file", name: rel, path: rel });
|
|
116
145
|
for (const c of chunks) {
|
|
@@ -146,7 +175,7 @@ export async function indexSource(store, src, opts = {}) {
|
|
|
146
175
|
// Searchable meta needs only insertChunk (required); it must NOT be
|
|
147
176
|
// gated on the optional insertProperty, or a chunk-capable store would
|
|
148
177
|
// silently lose title/description search.
|
|
149
|
-
const heading = title ?? (rel.split("/").pop() ?? rel).replace(
|
|
178
|
+
const heading = title ?? (rel.split("/").pop() ?? rel).replace(TITLE_EXT_RE, "");
|
|
150
179
|
store.insertChunk({ root: src.root, path: rel, chunkId: `${sha(rel).slice(0, 8)}:meta`, headingPath: heading, heading, level: 0, parentChunkId: null, docType: dt, body: metaBody, bodyHash: sha(metaText) });
|
|
151
180
|
stats.chunks++;
|
|
152
181
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import dns from "node:dns";
|
|
2
|
+
import https from "node:https";
|
|
3
|
+
import { type LookupFunction } from "node:net";
|
|
4
|
+
/**
|
|
5
|
+
* True when `ip` is anything but a public-internet unicast address. Fails
|
|
6
|
+
* closed: an unparseable value is non-public. Deliberately NOT named
|
|
7
|
+
* `isBlockedAddress` (server webhook-url.ts applies a different policy).
|
|
8
|
+
*/
|
|
9
|
+
export declare function isNonPublicAddress(input: string): boolean;
|
|
10
|
+
export type LookupAll = (hostname: string, options: dns.LookupOptions, cb: (err: NodeJS.ErrnoException | null, addrs: dns.LookupAddress[]) => void) => void;
|
|
11
|
+
export interface GuardOptions {
|
|
12
|
+
/** Test seam: DNS resolver (default `dns.lookup`, called with `all:true`). */
|
|
13
|
+
lookup?: LookupAll;
|
|
14
|
+
/** Test seam: address policy, given the address and the host it was reached by (default `isNonPublicAddress`). */
|
|
15
|
+
isBlocked?: (addr: string, host: string) => boolean;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* Build a `lookup` for https.request: resolves with `all:true`, rejects when ANY
|
|
19
|
+
* answer is blocked, and answers in the shape the caller asked for (`options.all`).
|
|
20
|
+
*/
|
|
21
|
+
export declare function makeGuardedLookup(g?: GuardOptions): LookupFunction;
|
|
22
|
+
/**
|
|
23
|
+
* Resolve `host` and require EVERY answer to be public (IP literals are checked
|
|
24
|
+
* directly). Returns the checked addresses so a caller can pin one (git/curl).
|
|
25
|
+
*/
|
|
26
|
+
export declare function assertPublicHost(host: string, g?: GuardOptions): Promise<dns.LookupAddress[]>;
|
|
27
|
+
export interface GuardedFetchOptions extends GuardOptions {
|
|
28
|
+
maxBytes?: number;
|
|
29
|
+
timeoutMs?: number;
|
|
30
|
+
maxRedirects?: number;
|
|
31
|
+
/** Test seam: extra TLS options (e.g. a test CA). */
|
|
32
|
+
tls?: https.RequestOptions;
|
|
33
|
+
}
|
|
34
|
+
/** GET `rawUrl` over https, returning the (decoded) body. */
|
|
35
|
+
export declare function guardedFetch(rawUrl: string, opts?: GuardedFetchOptions): Promise<Buffer>;
|