@blackbelt-technology/pi-dashboard-kb 0.6.1 → 0.8.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 +23 -0
- package/dist/chunker.d.ts +3 -1
- package/dist/chunker.js +3 -19
- package/dist/cli.js +65 -9
- package/dist/config.d.ts +25 -0
- package/dist/config.js +40 -3
- package/dist/dox-triage.d.ts +66 -0
- package/dist/dox-triage.js +176 -0
- package/dist/dox.d.ts +24 -2
- package/dist/dox.js +145 -4
- package/dist/eval.d.ts +6 -0
- package/dist/eval.js +14 -0
- package/dist/frontmatter.d.ts +38 -0
- package/dist/frontmatter.js +198 -0
- package/dist/index-run.d.ts +3 -0
- package/dist/index-run.js +18 -3
- package/dist/index.d.ts +6 -3
- package/dist/index.js +3 -1
- package/dist/indexer.d.ts +8 -1
- package/dist/indexer.js +26 -3
- package/dist/render.js +19 -2
- package/dist/sqlite-store.d.ts +49 -1
- package/dist/sqlite-store.js +447 -67
- package/dist/types.d.ts +50 -0
- package/package.json +3 -1
- package/src/chunker.ts +5 -18
- package/src/cli.ts +59 -9
- package/src/config.ts +53 -3
- package/src/dox-triage.ts +223 -0
- package/src/dox.ts +141 -6
- package/src/eval.ts +19 -0
- package/src/frontmatter.ts +221 -0
- package/src/index-run.ts +20 -3
- package/src/index.ts +7 -2
- package/src/indexer.ts +25 -3
- package/src/render.ts +18 -2
- package/src/sqlite-store.ts +414 -57
- package/src/types.ts +46 -0
- package/src/AGENTS.md +0 -23
package/dist/dox.js
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
// `kb agents <path>` nearest-applicable chain (design §6d). Pure-local,
|
|
3
3
|
// deterministic, no LLM/embedding. The detect-don't-write rule: `dox init`
|
|
4
4
|
// and `--fix` only fill PATH columns / prune orphans; the LLM authors purposes.
|
|
5
|
-
import { existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync, appendFileSync } from "node:fs";
|
|
6
|
-
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
7
5
|
import { createHash } from "node:crypto";
|
|
6
|
+
import { appendFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
8
8
|
// delta ②: exclude worktree checkouts, archived openspec proposals, and doc-example noise.
|
|
9
9
|
// Also exclude build output (`out`) and the electron bundled/vendored trees
|
|
10
10
|
// (`bundled-extensions`, `electron/resources/server`) — all gitignored, zero
|
|
@@ -16,8 +16,20 @@ import { createHash } from "node:crypto";
|
|
|
16
16
|
// navigable source) and self-evident top-level docs (`CHANGELOG.md`, `CLAUDE.md`,
|
|
17
17
|
// repo-root `README.md`) with no per-file DOX value; `README` anchored to root so
|
|
18
18
|
// package READMEs stay documented.
|
|
19
|
-
|
|
20
|
-
|
|
19
|
+
// `.pi` is NOT excluded wholesale: `.pi/skills/`, `.pi/agents/` and `.pi/prompts/`
|
|
20
|
+
// carry per-file DOX rows per the Documentation Update Protocol, and excluding the
|
|
21
|
+
// whole tree blinded the orphan check there. Only the non-source `.pi` subdirs
|
|
22
|
+
// (caches, kb index, npm/git mirrors, flow run state) are skipped.
|
|
23
|
+
const DEFAULT_EXCLUDE = /(^|\/)(node_modules|\.git|\.github|dist|build|out|\.next|coverage|\.kb|\.worktrees|\.reverse-spec-scratch|openspec|doc-example|bundled-extensions|mockups|research|site|Prompt stories)(\/|$)|(^|\/)\.pi\/(dashboard|npm|git|flows)(\/|$)|(^|\/)electron\/resources\/server(\/|$)|(^|\/)(CHANGELOG|CLAUDE)\.md$|^README\.md$/;
|
|
24
|
+
/**
|
|
25
|
+
* `AGENTS.override.md` (pi 0.84.0) REPLACES a directory's context rather than
|
|
26
|
+
* adding to it, so it is listed first and shadows the other candidates in the
|
|
27
|
+
* SAME directory. Mirrors pi's own first-match-wins candidate list in
|
|
28
|
+
* `dist/core/resource-loader.js`. Ancestor inheritance is unaffected.
|
|
29
|
+
* See change: update-pi-core-0-84-adopt-apis.
|
|
30
|
+
*/
|
|
31
|
+
const AGENTS_OVERRIDE_FILE = "AGENTS.override.md";
|
|
32
|
+
const AGENTS_FILES = [AGENTS_OVERRIDE_FILE, "AGENTS.md"];
|
|
21
33
|
// delta ①: dox init now maps SOURCE, not docs. Source globs, minus type decls and tests.
|
|
22
34
|
const SOURCE_EXT = /\.(ts|tsx|js|jsx)$/;
|
|
23
35
|
const MD_EXT = /\.(md|mdx)$/i;
|
|
@@ -63,7 +75,16 @@ export function agentsChain(cwd, targetPath, opts = {}) {
|
|
|
63
75
|
const ordered = dirs.reverse();
|
|
64
76
|
const chain = [];
|
|
65
77
|
ordered.forEach((dir, depth) => {
|
|
78
|
+
// An override replaces this directory's context: take it alone and skip the
|
|
79
|
+
// siblings, otherwise the same logical scope is injected twice.
|
|
80
|
+
const override = join(dir, AGENTS_OVERRIDE_FILE);
|
|
81
|
+
if (existsSync(override)) {
|
|
82
|
+
chain.push({ path: override, rel: relative(cwd, override) || AGENTS_OVERRIDE_FILE, depth });
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
66
85
|
for (const name of names) {
|
|
86
|
+
if (name === AGENTS_OVERRIDE_FILE)
|
|
87
|
+
continue;
|
|
67
88
|
const p = join(dir, name);
|
|
68
89
|
if (existsSync(p))
|
|
69
90
|
chain.push({ path: p, rel: relative(cwd, p) || name, depth });
|
|
@@ -245,6 +266,84 @@ export function doxInit(opts) {
|
|
|
245
266
|
}
|
|
246
267
|
return plan;
|
|
247
268
|
}
|
|
269
|
+
// --- dox lint ---
|
|
270
|
+
/**
|
|
271
|
+
* Pull repo-path REFERENCES out of a row's purpose cell.
|
|
272
|
+
*
|
|
273
|
+
* The lint hashes the file behind each row but never validates paths written
|
|
274
|
+
* inside the prose, so a directory move silently rots cross-references (this is
|
|
275
|
+
* how a routing rule kept pointing at two deleted dirs). The hard part is not
|
|
276
|
+
* finding candidates — it is rejecting the ~99% that are not repo paths at all:
|
|
277
|
+
* URL routes, MIME types, npm specifiers, `~`/absolute paths, model ids, code
|
|
278
|
+
* fragments like `get/list/remove`, and descriptions of OTHER projects' layouts.
|
|
279
|
+
*
|
|
280
|
+
* Discriminators, in order of how much noise each removes:
|
|
281
|
+
* 1. first segment must be a real top-level entry of THIS repo — kills
|
|
282
|
+
* `lib/validations.ts` (consumer-project prose) and `provider/model`
|
|
283
|
+
* 2. must carry a source-file extension or be a glob — kills bare route paths
|
|
284
|
+
* 3. structural rejects: leading `~` or `/`, `@` scopes, and any char that
|
|
285
|
+
* cannot appear in a path we would write (`:?="'()[]{}<>` , whitespace…)
|
|
286
|
+
*/
|
|
287
|
+
export function extractRefPaths(cell, topLevel) {
|
|
288
|
+
const out = [];
|
|
289
|
+
for (const m of cell.matchAll(/`([^`]+)`/g)) {
|
|
290
|
+
const raw = m[1].trim();
|
|
291
|
+
if (!raw.includes("/"))
|
|
292
|
+
continue;
|
|
293
|
+
if (/^[~/@]/.test(raw))
|
|
294
|
+
continue; // home, absolute, npm scope
|
|
295
|
+
if (/[:?="'()[\]{}<>|,;!#\s]/.test(raw))
|
|
296
|
+
continue; // routes, code, prose, placeholders
|
|
297
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: intentional non-ASCII guard
|
|
298
|
+
if (/[^\x20-\x7e]/.test(raw))
|
|
299
|
+
continue;
|
|
300
|
+
const p = raw.replace(/^\.\//, "").replace(/\/$/, "");
|
|
301
|
+
if (!p.includes("/"))
|
|
302
|
+
continue;
|
|
303
|
+
if (!topLevel.has(p.split("/")[0]))
|
|
304
|
+
continue;
|
|
305
|
+
if (!/\.[a-z0-9]{1,5}$/i.test(p) && !p.includes("*"))
|
|
306
|
+
continue;
|
|
307
|
+
// Build output and excluded trees (`packages/electron/out/*`, `.worktrees/*`)
|
|
308
|
+
// are legitimately absent until built/created — flagging them is noise, and a
|
|
309
|
+
// check that cries wolf gets ignored.
|
|
310
|
+
if (DEFAULT_EXCLUDE.test(p))
|
|
311
|
+
continue;
|
|
312
|
+
out.push(p);
|
|
313
|
+
}
|
|
314
|
+
return out;
|
|
315
|
+
}
|
|
316
|
+
/** Cheap glob test for `*` / `**` reference paths (no dependency on a matcher). */
|
|
317
|
+
function globHit(pattern, cwd) {
|
|
318
|
+
const rx = new RegExp(`^${pattern
|
|
319
|
+
.split("/")
|
|
320
|
+
.map((s) => s
|
|
321
|
+
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
|
|
322
|
+
.replace(/\*\*/g, "\u0001")
|
|
323
|
+
.replace(/\*/g, "[^/]*")
|
|
324
|
+
.replace(/\u0001/g, ".*"))
|
|
325
|
+
.join("/")}$`);
|
|
326
|
+
const walk = (dir, rel) => {
|
|
327
|
+
let entries = [];
|
|
328
|
+
try {
|
|
329
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
330
|
+
}
|
|
331
|
+
catch {
|
|
332
|
+
return false;
|
|
333
|
+
}
|
|
334
|
+
for (const e of entries) {
|
|
335
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
336
|
+
if (DEFAULT_EXCLUDE.test(r))
|
|
337
|
+
continue;
|
|
338
|
+
if (rx.test(r))
|
|
339
|
+
return true;
|
|
340
|
+
if (e.isDirectory() && walk(join(dir, e.name), r))
|
|
341
|
+
return true;
|
|
342
|
+
}
|
|
343
|
+
return false;
|
|
344
|
+
};
|
|
345
|
+
return walk(cwd, "");
|
|
346
|
+
}
|
|
248
347
|
function fileSha(p) {
|
|
249
348
|
try {
|
|
250
349
|
return createHash("sha256").update(readFileSync(p)).digest("hex");
|
|
@@ -265,6 +364,17 @@ export function doxLint(opts) {
|
|
|
265
364
|
const cwd = opts.cwd;
|
|
266
365
|
const issues = [];
|
|
267
366
|
let fixed = 0;
|
|
367
|
+
// Top-level entries of THIS repo — the primary discriminator that stops
|
|
368
|
+
// broken-ref from firing on prose that merely looks path-shaped.
|
|
369
|
+
const topLevelEntries = new Set();
|
|
370
|
+
try {
|
|
371
|
+
for (const e of readdirSync(cwd, { withFileTypes: true }))
|
|
372
|
+
topLevelEntries.add(e.name);
|
|
373
|
+
}
|
|
374
|
+
catch {
|
|
375
|
+
/* empty cwd — leave the set empty, which disables broken-ref entirely */
|
|
376
|
+
}
|
|
377
|
+
const seenRefs = new Set();
|
|
268
378
|
// find all AGENTS.md
|
|
269
379
|
const agentsFiles = [];
|
|
270
380
|
// Test the path RELATIVE to cwd (mirrors walkFiles) so an ancestor dir named
|
|
@@ -329,6 +439,19 @@ export function doxLint(opts) {
|
|
|
329
439
|
continue;
|
|
330
440
|
}
|
|
331
441
|
const rp = m[1];
|
|
442
|
+
// Cross-references inside the PURPOSE cell. Rot here is invisible to the
|
|
443
|
+
// hash check, because the row's own file is untouched by the move.
|
|
444
|
+
const purposeCell = line.slice(line.indexOf("|", line.indexOf("`" + rp + "`")) + 1);
|
|
445
|
+
for (const ref of extractRefPaths(purposeCell, topLevelEntries)) {
|
|
446
|
+
if (seenRefs.has(ref))
|
|
447
|
+
continue;
|
|
448
|
+
seenRefs.add(ref);
|
|
449
|
+
const hit = ref.includes("*")
|
|
450
|
+
? globHit(ref, cwd)
|
|
451
|
+
: existsSync(join(cwd, ref)) || existsSync(join(afDir, ref));
|
|
452
|
+
if (!hit)
|
|
453
|
+
issues.push({ kind: "broken-ref", agentsFile: afRel, path: ref, detail: `broken-ref: row prose cites ${ref}, which does not exist` });
|
|
454
|
+
}
|
|
332
455
|
const abs = resolveRowPath(afDir, cwd, rp);
|
|
333
456
|
const rel = relative(cwd, abs);
|
|
334
457
|
rowPaths.add(rel);
|
|
@@ -382,6 +505,24 @@ export function doxLint(opts) {
|
|
|
382
505
|
}
|
|
383
506
|
}
|
|
384
507
|
}
|
|
508
|
+
// missing rows, SOURCE arm (design D9): a .ts/.tsx in a covered area with no
|
|
509
|
+
// row in ANY ancestor AGENTS.md and no <file>.AGENTS.md sidecar is unreachable
|
|
510
|
+
// through the `agents` doc-type lane that retrieval depends on. Opt-in, and
|
|
511
|
+
// never auto-fixed: a blank purpose row is worse than an honest finding.
|
|
512
|
+
if (opts.sourceFileRows) {
|
|
513
|
+
for (const abs of sourceFiles(cwd)) {
|
|
514
|
+
const rel = relative(cwd, abs);
|
|
515
|
+
if (rowPaths.has(rel))
|
|
516
|
+
continue;
|
|
517
|
+
if (existsSync(join(cwd, `${rel}.AGENTS.md`)))
|
|
518
|
+
continue;
|
|
519
|
+
const dir = rel.includes("/") ? rel.slice(0, rel.lastIndexOf("/")) : ".";
|
|
520
|
+
const owner = ownerOf(dir);
|
|
521
|
+
if (!owner)
|
|
522
|
+
continue;
|
|
523
|
+
issues.push({ kind: "missing", arm: "source", agentsFile: relative(cwd, owner) || "AGENTS.md", path: rel, detail: `no row for source file ${rel}` });
|
|
524
|
+
}
|
|
525
|
+
}
|
|
385
526
|
// missing companions: large source/md files with no <file>.agent.md
|
|
386
527
|
for (const md of allMd) {
|
|
387
528
|
const abs = join(cwd, md);
|
package/dist/eval.d.ts
CHANGED
|
@@ -10,6 +10,12 @@ export interface EvalMetrics {
|
|
|
10
10
|
"Recall@K": number;
|
|
11
11
|
MRR: number;
|
|
12
12
|
"nDCG@K": number;
|
|
13
|
+
/** Mean count of distinct `(root, path)` sources per top-K page (D8). */
|
|
14
|
+
distinctSourcesAtK: number;
|
|
15
|
+
/** Mean fraction of slots whose source already appeared earlier on the page. */
|
|
16
|
+
duplicateSlotShare: number;
|
|
17
|
+
/** Fraction of queries whose whole top-K page comes from one source. */
|
|
18
|
+
singleSourcePageRate: number;
|
|
13
19
|
avgLatencyMs: number;
|
|
14
20
|
}
|
|
15
21
|
export declare function evaluate(store: KbStore, golden: GoldenItem[], opts?: SearchOpts & {
|
package/dist/eval.js
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
1
1
|
export function evaluate(store, golden, opts = {}) {
|
|
2
2
|
const k = opts.k ?? 10;
|
|
3
3
|
let p1 = 0, p5 = 0, recall = 0, mrr = 0, ndcg = 0, lat = 0;
|
|
4
|
+
// Redundancy accumulators (D8). Precision/recall are blind to page composition
|
|
5
|
+
// by construction, so redundancy is tracked as its own first-class metric.
|
|
6
|
+
let distinct = 0, dupShare = 0, singleSource = 0, pages = 0;
|
|
4
7
|
for (const g of golden) {
|
|
5
8
|
const t = performance.now();
|
|
6
9
|
const res = store.search(g.q, { ...opts, limit: k });
|
|
@@ -19,6 +22,14 @@ export function evaluate(store, golden, opts = {}) {
|
|
|
19
22
|
mrr += 1 / first;
|
|
20
23
|
ndcg += 1 / Math.log2(first + 1); // IDCG=1 (single relevant target)
|
|
21
24
|
}
|
|
25
|
+
if (res.length) {
|
|
26
|
+
const sources = new Set(res.map((r) => `${r.root}\u001f${r.path}`));
|
|
27
|
+
distinct += sources.size;
|
|
28
|
+
dupShare += (res.length - sources.size) / res.length;
|
|
29
|
+
if (sources.size === 1)
|
|
30
|
+
singleSource++;
|
|
31
|
+
pages++;
|
|
32
|
+
}
|
|
22
33
|
}
|
|
23
34
|
const n = golden.length || 1;
|
|
24
35
|
return {
|
|
@@ -28,6 +39,9 @@ export function evaluate(store, golden, opts = {}) {
|
|
|
28
39
|
"Recall@K": +(recall / n).toFixed(3),
|
|
29
40
|
MRR: +(mrr / n).toFixed(3),
|
|
30
41
|
"nDCG@K": +(ndcg / n).toFixed(3),
|
|
42
|
+
distinctSourcesAtK: +(distinct / (pages || 1)).toFixed(3),
|
|
43
|
+
duplicateSlotShare: +(dupShare / (pages || 1)).toFixed(3),
|
|
44
|
+
singleSourcePageRate: +(singleSource / (pages || 1)).toFixed(3),
|
|
31
45
|
avgLatencyMs: +(lat / n).toFixed(2),
|
|
32
46
|
};
|
|
33
47
|
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
export type FmScalar = string | number | boolean;
|
|
2
|
+
export type FmValue = FmScalar | string[];
|
|
3
|
+
export interface ParsedFrontmatter {
|
|
4
|
+
body: string;
|
|
5
|
+
fm: Record<string, FmValue> | null;
|
|
6
|
+
parseFailed: boolean;
|
|
7
|
+
}
|
|
8
|
+
/** Detect + parse a leading YAML-subset frontmatter block. Total + pure. */
|
|
9
|
+
export declare function parseFrontmatter(text: string): ParsedFrontmatter;
|
|
10
|
+
export interface FacetKeyConfig {
|
|
11
|
+
key: string;
|
|
12
|
+
type?: "string" | "number" | "date";
|
|
13
|
+
}
|
|
14
|
+
/** Default routing (superset of prior behavior: `tags` still drives has_tag). */
|
|
15
|
+
export declare const DEFAULT_SEARCHABLE_KEYS: string[];
|
|
16
|
+
export declare const DEFAULT_FACET_KEYS: FacetKeyConfig[];
|
|
17
|
+
export interface PropertyRow {
|
|
18
|
+
key: string;
|
|
19
|
+
value: string;
|
|
20
|
+
valueNum: number | null;
|
|
21
|
+
valueDate: string | null;
|
|
22
|
+
valueRaw: string;
|
|
23
|
+
}
|
|
24
|
+
/** Strict full-match numeric coercion; null when not a clean, finite number
|
|
25
|
+
* (a very long digit string parses to Infinity — rejected). */
|
|
26
|
+
export declare function strictNumber(v: FmValue): number | null;
|
|
27
|
+
/** Strict `YYYY-MM-DD` calendar date; null otherwise. Rejects impossible dates
|
|
28
|
+
* (e.g. `2024-02-31`) via a UTC round-trip. Instants deferred — design D3. */
|
|
29
|
+
export declare function strictDate(v: FmValue): string | null;
|
|
30
|
+
/** Build the searchable meta pieces: title (→ heading) and the rest (→ body).
|
|
31
|
+
* `tags` is never searchable (it is a facet). */
|
|
32
|
+
export declare function buildMeta(fm: Record<string, FmValue>, searchableKeys: string[]): {
|
|
33
|
+
title: string | null;
|
|
34
|
+
body: string;
|
|
35
|
+
};
|
|
36
|
+
/** Build de-duplicated property rows for the whitelisted facet keys.
|
|
37
|
+
* Array values → one row per distinct element; within-file duplicates collapse. */
|
|
38
|
+
export declare function buildProperties(fm: Record<string, FmValue>, facetKeys: FacetKeyConfig[]): PropertyRow[];
|
|
@@ -0,0 +1,198 @@
|
|
|
1
|
+
// Vendored, zero-dependency YAML-subset frontmatter parser + structural routing.
|
|
2
|
+
// See change: add-kb-frontmatter-structural-indexing (design D3/D4/D5).
|
|
3
|
+
//
|
|
4
|
+
// The parser is TOTAL (never throws) and PURE (same bytes → same output). It
|
|
5
|
+
// supports a bounded grammar: `key: scalar`, inline `[a, b]`, block `- item`
|
|
6
|
+
// lists, bool/int/float, `YYYY-MM-DD`, `#` comments, single/double quotes.
|
|
7
|
+
// Unsupported constructs (anchors/aliases, `|`/`>` block scalars, general nested
|
|
8
|
+
// maps, merge keys) fall back to string / skip — never a throw. A top-level
|
|
9
|
+
// `kb:` key and its indented subtree are consumed and discarded (owned by the
|
|
10
|
+
// semantic-annotation plane).
|
|
11
|
+
/** Strip a trailing `# comment`. For a quoted value, keep through the closing
|
|
12
|
+
* quote and drop any comment after it (`title: "H" # c` → `"H"`). */
|
|
13
|
+
function stripComment(s) {
|
|
14
|
+
const t = s.trim();
|
|
15
|
+
if (t.startsWith('"') || t.startsWith("'")) {
|
|
16
|
+
const close = t.indexOf(t[0], 1);
|
|
17
|
+
return close > 0 ? t.slice(0, close + 1) : t; // unterminated quote → leave as-is
|
|
18
|
+
}
|
|
19
|
+
const idx = t.indexOf(" #");
|
|
20
|
+
return (idx >= 0 ? t.slice(0, idx) : t).trim();
|
|
21
|
+
}
|
|
22
|
+
/** Coerce a bare scalar token to bool/int/float/string. Quoted → string. */
|
|
23
|
+
function coerceScalar(raw) {
|
|
24
|
+
const s = raw.trim();
|
|
25
|
+
if ((s.startsWith('"') && s.endsWith('"') && s.length >= 2) || (s.startsWith("'") && s.endsWith("'") && s.length >= 2)) {
|
|
26
|
+
return s.slice(1, -1);
|
|
27
|
+
}
|
|
28
|
+
if (s === "true")
|
|
29
|
+
return true;
|
|
30
|
+
if (s === "false")
|
|
31
|
+
return false;
|
|
32
|
+
if (/^-?\d+$/.test(s))
|
|
33
|
+
return parseInt(s, 10);
|
|
34
|
+
if (/^-?\d+\.\d+$/.test(s))
|
|
35
|
+
return parseFloat(s);
|
|
36
|
+
return s;
|
|
37
|
+
}
|
|
38
|
+
/** Parse an inline `[a, b, "c"]` array to a string[] (elements trimmed/unquoted). */
|
|
39
|
+
function parseInlineArray(s) {
|
|
40
|
+
const inner = s.replace(/^\[/, "").replace(/\]$/, "");
|
|
41
|
+
return inner
|
|
42
|
+
.split(",")
|
|
43
|
+
.map((e) => {
|
|
44
|
+
const t = e.trim();
|
|
45
|
+
const unq = (t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'")) ? t.slice(1, -1) : t;
|
|
46
|
+
return unq.trim();
|
|
47
|
+
})
|
|
48
|
+
.filter((e) => e.length > 0);
|
|
49
|
+
}
|
|
50
|
+
const isIndented = (line) => /^\s/.test(line);
|
|
51
|
+
const isBlank = (line) => line.trim() === "";
|
|
52
|
+
/** Detect + parse a leading YAML-subset frontmatter block. Total + pure. */
|
|
53
|
+
export function parseFrontmatter(text) {
|
|
54
|
+
const norm = text.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n"); // strip BOM; CRLF/CR → LF
|
|
55
|
+
const lines = norm.split("\n");
|
|
56
|
+
if (lines[0] !== "---")
|
|
57
|
+
return { body: norm, fm: null, parseFailed: false };
|
|
58
|
+
let end = -1;
|
|
59
|
+
for (let i = 1; i < lines.length; i++) {
|
|
60
|
+
if (lines[i] === "---") {
|
|
61
|
+
end = i;
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (end === -1)
|
|
66
|
+
return { body: norm, fm: null, parseFailed: false }; // no closing fence → not frontmatter
|
|
67
|
+
const fmLines = lines.slice(1, end);
|
|
68
|
+
const body = lines.slice(end + 1).join("\n");
|
|
69
|
+
const fm = {};
|
|
70
|
+
let parseFailed = false;
|
|
71
|
+
for (let i = 0; i < fmLines.length; i++) {
|
|
72
|
+
const line = fmLines[i];
|
|
73
|
+
if (isBlank(line) || line.trim().startsWith("#"))
|
|
74
|
+
continue;
|
|
75
|
+
if (isIndented(line))
|
|
76
|
+
continue; // stray indented line without a parent key context
|
|
77
|
+
const m = line.match(/^([A-Za-z0-9_.\/-]+):(.*)$/);
|
|
78
|
+
if (!m) {
|
|
79
|
+
parseFailed = true;
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const key = m[1];
|
|
83
|
+
const rest = stripComment(m[2]);
|
|
84
|
+
// Top-level `kb:` — consume + discard its entire indented subtree.
|
|
85
|
+
if (key === "kb") {
|
|
86
|
+
while (i + 1 < fmLines.length && (isIndented(fmLines[i + 1]) || isBlank(fmLines[i + 1])))
|
|
87
|
+
i++;
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
if (rest === "") {
|
|
91
|
+
// block list, nested map, or empty scalar
|
|
92
|
+
const items = [];
|
|
93
|
+
while (i + 1 < fmLines.length && /^\s*-\s+/.test(fmLines[i + 1])) {
|
|
94
|
+
i++;
|
|
95
|
+
items.push(stripComment(fmLines[i].replace(/^\s*-\s+/, "")).replace(/^["']|["']$/g, ""));
|
|
96
|
+
}
|
|
97
|
+
if (items.length) {
|
|
98
|
+
fm[key] = items.filter((e) => e.length > 0);
|
|
99
|
+
}
|
|
100
|
+
else if (i + 1 < fmLines.length && /^\s+\S/.test(fmLines[i + 1])) {
|
|
101
|
+
// nested map (unsupported) → skip its indented subtree, emit nothing
|
|
102
|
+
while (i + 1 < fmLines.length && (isIndented(fmLines[i + 1]) || isBlank(fmLines[i + 1])))
|
|
103
|
+
i++;
|
|
104
|
+
}
|
|
105
|
+
else {
|
|
106
|
+
fm[key] = "";
|
|
107
|
+
}
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
if (rest === "|" || rest === ">") {
|
|
111
|
+
// multiline block scalar (unsupported) → skip its indented subtree
|
|
112
|
+
while (i + 1 < fmLines.length && (isIndented(fmLines[i + 1]) || isBlank(fmLines[i + 1])))
|
|
113
|
+
i++;
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (rest.startsWith("[")) {
|
|
117
|
+
fm[key] = parseInlineArray(rest);
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
fm[key] = coerceScalar(rest);
|
|
121
|
+
}
|
|
122
|
+
return { body, fm, parseFailed };
|
|
123
|
+
}
|
|
124
|
+
/** Default routing (superset of prior behavior: `tags` still drives has_tag). */
|
|
125
|
+
export const DEFAULT_SEARCHABLE_KEYS = ["title", "description", "aliases", "keywords"];
|
|
126
|
+
export const DEFAULT_FACET_KEYS = [
|
|
127
|
+
{ key: "tags" },
|
|
128
|
+
{ key: "status" },
|
|
129
|
+
{ key: "author" },
|
|
130
|
+
{ key: "category" },
|
|
131
|
+
{ key: "date", type: "date" },
|
|
132
|
+
];
|
|
133
|
+
/** Strict full-match numeric coercion; null when not a clean, finite number
|
|
134
|
+
* (a very long digit string parses to Infinity — rejected). */
|
|
135
|
+
export function strictNumber(v) {
|
|
136
|
+
if (typeof v === "number")
|
|
137
|
+
return Number.isFinite(v) ? v : null;
|
|
138
|
+
if (typeof v === "string" && /^-?\d+(\.\d+)?$/.test(v.trim())) {
|
|
139
|
+
const n = Number(v.trim());
|
|
140
|
+
return Number.isFinite(n) ? n : null;
|
|
141
|
+
}
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
/** Strict `YYYY-MM-DD` calendar date; null otherwise. Rejects impossible dates
|
|
145
|
+
* (e.g. `2024-02-31`) via a UTC round-trip. Instants deferred — design D3. */
|
|
146
|
+
export function strictDate(v) {
|
|
147
|
+
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(v).trim());
|
|
148
|
+
if (!m)
|
|
149
|
+
return null;
|
|
150
|
+
const y = +m[1], mo = +m[2], d = +m[3];
|
|
151
|
+
// setUTCFullYear (not Date.UTC) so years 0000–0099 are NOT remapped to 1900–1999
|
|
152
|
+
// (JS legacy two-digit-year behavior) — keeps valid dates like 0001-01-01.
|
|
153
|
+
const dt = new Date(0);
|
|
154
|
+
dt.setUTCFullYear(y, mo - 1, d);
|
|
155
|
+
return dt.getUTCFullYear() === y && dt.getUTCMonth() === mo - 1 && dt.getUTCDate() === d ? `${m[1]}-${m[2]}-${m[3]}` : null;
|
|
156
|
+
}
|
|
157
|
+
/** Build the searchable meta pieces: title (→ heading) and the rest (→ body).
|
|
158
|
+
* `tags` is never searchable (it is a facet). */
|
|
159
|
+
export function buildMeta(fm, searchableKeys) {
|
|
160
|
+
const title = searchableKeys.includes("title") && fm.title != null ? String(Array.isArray(fm.title) ? fm.title.join(" ") : fm.title) : null;
|
|
161
|
+
const parts = [];
|
|
162
|
+
for (const key of searchableKeys) {
|
|
163
|
+
if (key === "title" || key === "tags")
|
|
164
|
+
continue;
|
|
165
|
+
const v = fm[key];
|
|
166
|
+
if (v == null)
|
|
167
|
+
continue;
|
|
168
|
+
parts.push(Array.isArray(v) ? v.join(" ") : String(v));
|
|
169
|
+
}
|
|
170
|
+
return { title, body: parts.join(" ").trim() };
|
|
171
|
+
}
|
|
172
|
+
/** Build de-duplicated property rows for the whitelisted facet keys.
|
|
173
|
+
* Array values → one row per distinct element; within-file duplicates collapse. */
|
|
174
|
+
export function buildProperties(fm, facetKeys) {
|
|
175
|
+
const rows = [];
|
|
176
|
+
for (const { key, type } of facetKeys) {
|
|
177
|
+
const v = fm[key];
|
|
178
|
+
if (v == null)
|
|
179
|
+
continue;
|
|
180
|
+
const elems = Array.isArray(v) ? v : [v];
|
|
181
|
+
const seen = new Set();
|
|
182
|
+
for (const e of elems) {
|
|
183
|
+
const raw = String(e);
|
|
184
|
+
const value = raw.toLowerCase().trim();
|
|
185
|
+
if (value === "" || seen.has(value))
|
|
186
|
+
continue;
|
|
187
|
+
seen.add(value);
|
|
188
|
+
rows.push({
|
|
189
|
+
key,
|
|
190
|
+
value,
|
|
191
|
+
valueNum: type === "number" ? strictNumber(e) : null,
|
|
192
|
+
valueDate: type === "date" ? strictDate(raw) : null,
|
|
193
|
+
valueRaw: raw,
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
return rows;
|
|
198
|
+
}
|
package/dist/index-run.d.ts
CHANGED
|
@@ -11,6 +11,9 @@ export interface RunIndexAtomicOpts {
|
|
|
11
11
|
indexOpts?: IndexOptions;
|
|
12
12
|
/** Sources came from an explicit `--source` arg; a missing one is a user typo. */
|
|
13
13
|
explicit?: boolean;
|
|
14
|
+
/** When set, participates in the schema-version reindex gate (design D6): a
|
|
15
|
+
* changed facet-config hash forces a one-time full reindex. */
|
|
16
|
+
facetConfigHash?: string;
|
|
14
17
|
}
|
|
15
18
|
/** Remove stale `<dbPath>.tmp-*` orphans (+ WAL sidecars) left by a prior
|
|
16
19
|
* SIGKILL'd first-index run, so temp husks do not accumulate. A temp file whose
|
package/dist/index-run.js
CHANGED
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
import { existsSync, readdirSync, unlinkSync } from "node:fs";
|
|
14
14
|
import { basename, dirname, join } from "node:path";
|
|
15
15
|
import { indexSource } from "./indexer.js";
|
|
16
|
-
import { SqliteFtsStore } from "./sqlite-store.js";
|
|
16
|
+
import { SCHEMA_VERSION, SqliteFtsStore } from "./sqlite-store.js";
|
|
17
17
|
/** True if `pid` names a live process (existence probe via signal 0). EPERM =
|
|
18
18
|
* alive but not ours; ESRCH = dead. kb is self-contained (no pi-dashboard-shared
|
|
19
19
|
* dep, same as `sources.ts`), so it probes with a raw signal-0 send rather than
|
|
@@ -77,19 +77,34 @@ export async function runIndexAtomic(opts) {
|
|
|
77
77
|
const target = preexisting ? dbPath : `${dbPath}.tmp-${process.pid}`;
|
|
78
78
|
const store = new SqliteFtsStore(target);
|
|
79
79
|
store.init();
|
|
80
|
+
// Schema-version / facet-config gate: a stale schema version or a changed
|
|
81
|
+
// facet-config hash forces a one-time full reindex so new structures populate.
|
|
82
|
+
let effOpts = indexOpts ?? {};
|
|
83
|
+
if (preexisting) {
|
|
84
|
+
const ver = store.getUserVersion?.() ?? 0;
|
|
85
|
+
const storedHash = store.getMeta?.("facetConfigHash") ?? null;
|
|
86
|
+
if (ver < SCHEMA_VERSION || (opts.facetConfigHash != null && storedHash !== opts.facetConfigHash)) {
|
|
87
|
+
effOpts = { ...effOpts, force: true };
|
|
88
|
+
}
|
|
89
|
+
}
|
|
80
90
|
let ok = false;
|
|
81
91
|
try {
|
|
82
|
-
const total = { scanned: 0, changed: 0, deleted: 0, chunks: 0 };
|
|
92
|
+
const total = { scanned: 0, changed: 0, deleted: 0, chunks: 0, parseFailures: 0 };
|
|
83
93
|
for (const s of sources) {
|
|
84
|
-
const st = await indexSource(store, { root: s.id, dir: s.dir },
|
|
94
|
+
const st = await indexSource(store, { root: s.id, dir: s.dir }, effOpts);
|
|
85
95
|
total.scanned += st.scanned;
|
|
86
96
|
total.changed += st.changed;
|
|
87
97
|
total.deleted += st.deleted;
|
|
88
98
|
total.chunks += st.chunks;
|
|
99
|
+
total.parseFailures = (total.parseFailures ?? 0) + (st.parseFailures ?? 0);
|
|
89
100
|
}
|
|
90
101
|
// Read counts from the still-open store so callers never need a second
|
|
91
102
|
// openStore() connection just to report them (keeps `index` off openStore).
|
|
92
103
|
const counts = store.counts();
|
|
104
|
+
// Stamp the schema version + facet-config hash so the gate is satisfied next open.
|
|
105
|
+
store.setUserVersion?.(SCHEMA_VERSION);
|
|
106
|
+
if (opts.facetConfigHash != null)
|
|
107
|
+
store.setMeta?.("facetConfigHash", opts.facetConfigHash);
|
|
93
108
|
if (preexisting)
|
|
94
109
|
store.close();
|
|
95
110
|
else
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
export type { Chunk, DocType, FileState, GraphEdge, GraphNode, KbHit, KbStore, SearchOpts, } from "./types.js";
|
|
1
|
+
export type { Chunk, DocType, FileState, GraphEdge, GraphNode, KbHit, KbStore, SearchOpts, Filter, StorePropertyRow, } from "./types.js";
|
|
2
|
+
export { parseFrontmatter, buildMeta, buildProperties, strictNumber, strictDate, DEFAULT_SEARCHABLE_KEYS, DEFAULT_FACET_KEYS } from "./frontmatter.js";
|
|
3
|
+
export type { FmValue, FacetKeyConfig, ParsedFrontmatter, PropertyRow } from "./frontmatter.js";
|
|
2
4
|
export { renderHits } from "./render.js";
|
|
3
5
|
export type { RenderOpts } from "./render.js";
|
|
4
6
|
export { chunkMarkdown } from "./chunker.js";
|
|
@@ -8,8 +10,9 @@ export { indexSource } from "./indexer.js";
|
|
|
8
10
|
export type { IndexSource, IndexOptions, IndexStats } from "./indexer.js";
|
|
9
11
|
export { kbInit } from "./init.js";
|
|
10
12
|
export type { InitOptions, InitResult } from "./init.js";
|
|
11
|
-
export { loadConfig, validateConfig, DEFAULTS } from "./config.js";
|
|
12
|
-
export type { KbConfig, SourceConfig, RankingConfig, ResolvedConfig } from "./config.js";
|
|
13
|
+
export { loadConfig, validateConfig, DEFAULTS, frontmatterConfigHash } from "./config.js";
|
|
14
|
+
export type { KbConfig, SourceConfig, RankingConfig, ResolvedConfig, FrontmatterConfig } from "./config.js";
|
|
15
|
+
export { SCHEMA_VERSION } from "./sqlite-store.js";
|
|
13
16
|
export { resolveAll, classifyRef, sourceIdentity, resolverFor } from "./sources.js";
|
|
14
17
|
export type { KbSourceKind, ResolvedSource, ResolveCtx, SourceResolver } from "./sources.js";
|
|
15
18
|
export { isTrusted, recordTrust, canonicalSource, sourceHash } from "./trust.js";
|
package/dist/index.js
CHANGED
|
@@ -1,9 +1,11 @@
|
|
|
1
|
+
export { parseFrontmatter, buildMeta, buildProperties, strictNumber, strictDate, DEFAULT_SEARCHABLE_KEYS, DEFAULT_FACET_KEYS } from "./frontmatter.js";
|
|
1
2
|
export { renderHits } from "./render.js";
|
|
2
3
|
export { chunkMarkdown } from "./chunker.js";
|
|
3
4
|
export { SqliteFtsStore } from "./sqlite-store.js";
|
|
4
5
|
export { indexSource } from "./indexer.js";
|
|
5
6
|
export { kbInit } from "./init.js";
|
|
6
|
-
export { loadConfig, validateConfig, DEFAULTS } from "./config.js";
|
|
7
|
+
export { loadConfig, validateConfig, DEFAULTS, frontmatterConfigHash } from "./config.js";
|
|
8
|
+
export { SCHEMA_VERSION } from "./sqlite-store.js";
|
|
7
9
|
export { resolveAll, classifyRef, sourceIdentity, resolverFor } from "./sources.js";
|
|
8
10
|
export { isTrusted, recordTrust, canonicalSource, sourceHash } from "./trust.js";
|
|
9
11
|
export { agentsChain, doxInit, doxLint, fallbackManifest, parseRowPaths, resolveRowPath } from "./dox.js";
|
package/dist/indexer.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type FacetKeyConfig } from "./frontmatter.js";
|
|
2
|
+
import type { DocType, KbStore } from "./types.js";
|
|
2
3
|
export interface IndexSource {
|
|
3
4
|
root: string;
|
|
4
5
|
dir: string;
|
|
@@ -11,12 +12,18 @@ export interface IndexOptions {
|
|
|
11
12
|
include?: string[];
|
|
12
13
|
exclude?: string[];
|
|
13
14
|
extensions?: string[];
|
|
15
|
+
frontmatter?: {
|
|
16
|
+
searchableKeys: string[];
|
|
17
|
+
facetKeys: FacetKeyConfig[];
|
|
18
|
+
};
|
|
14
19
|
}
|
|
15
20
|
export interface IndexStats {
|
|
16
21
|
scanned: number;
|
|
17
22
|
changed: number;
|
|
18
23
|
deleted: number;
|
|
19
24
|
chunks: number;
|
|
25
|
+
parseFailures?: number;
|
|
20
26
|
missing?: boolean;
|
|
21
27
|
}
|
|
28
|
+
export declare function docTypeOf(rel: string, includeSourceMarkdown: boolean): DocType;
|
|
22
29
|
export declare function indexSource(store: KbStore, src: IndexSource, opts?: IndexOptions): Promise<IndexStats>;
|
package/dist/indexer.js
CHANGED
|
@@ -4,6 +4,7 @@ import { createHash } from "node:crypto";
|
|
|
4
4
|
import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
|
|
5
5
|
import { join, relative } from "node:path";
|
|
6
6
|
import { chunkMarkdown } from "./chunker.js";
|
|
7
|
+
import { DEFAULT_FACET_KEYS, DEFAULT_SEARCHABLE_KEYS, buildMeta, buildProperties } from "./frontmatter.js";
|
|
7
8
|
const sha = (s) => createHash("sha256").update(s).digest("hex");
|
|
8
9
|
const DEFAULT_EXCLUDE = /(^|\/)(node_modules|\.git|dist|build|\.next|coverage|\.kb)(\/|$)/;
|
|
9
10
|
/** Files processed between event-loop yields + batch commits. A long synchronous
|
|
@@ -41,12 +42,12 @@ function walk(dir, base, out = []) {
|
|
|
41
42
|
}
|
|
42
43
|
return out;
|
|
43
44
|
}
|
|
44
|
-
function docTypeOf(rel, includeSourceMarkdown) {
|
|
45
|
+
export function docTypeOf(rel, includeSourceMarkdown) {
|
|
45
46
|
const base = rel.split("/").pop() ?? "";
|
|
46
47
|
// `<File>.AGENTS.md` = per-file index sidecar (large-row promotion). Classified
|
|
47
48
|
// `agents` so it is searchable, but its name != "AGENTS.md" so pi's native
|
|
48
49
|
// up-walk never auto-injects it (pull-only via kb search).
|
|
49
|
-
if (base === "AGENTS.md" || base === "CLAUDE.md" || base.endsWith(".AGENTS.md"))
|
|
50
|
+
if (base === "AGENTS.override.md" || base === "AGENTS.md" || base === "CLAUDE.md" || base.endsWith(".AGENTS.md"))
|
|
50
51
|
return "agents";
|
|
51
52
|
if (includeSourceMarkdown && /(^|\/)(src|lib|app|packages)\//.test(rel))
|
|
52
53
|
return "source-md";
|
|
@@ -108,7 +109,8 @@ export async function indexSource(store, src, opts = {}) {
|
|
|
108
109
|
}
|
|
109
110
|
// changed → replace
|
|
110
111
|
store.deleteByPath(src.root, rel);
|
|
111
|
-
const
|
|
112
|
+
const dt = docTypeOf(rel, includeSourceMd);
|
|
113
|
+
const { chunks, wikilinks, mdLinks, frontmatter, parseFailed } = chunkMarkdown({ root: src.root, path: rel, text: buf.toString("utf8"), docType: dt });
|
|
112
114
|
// file node
|
|
113
115
|
store.addNode({ type: "file", name: rel, path: rel });
|
|
114
116
|
for (const c of chunks) {
|
|
@@ -135,6 +137,27 @@ export async function indexSource(store, src, opts = {}) {
|
|
|
135
137
|
store.addNode({ type: "tag", name: `tag:${tag}`, path: null });
|
|
136
138
|
store.addEdge({ src: rel, dst: `tag:${tag}`, rel: "has_tag" });
|
|
137
139
|
}
|
|
140
|
+
// frontmatter structural indexing: synthetic meta chunk + property rows
|
|
141
|
+
if (frontmatter) {
|
|
142
|
+
const fmCfg = opts.frontmatter ?? { searchableKeys: DEFAULT_SEARCHABLE_KEYS, facetKeys: DEFAULT_FACET_KEYS };
|
|
143
|
+
const { title, body: metaBody } = buildMeta(frontmatter, fmCfg.searchableKeys);
|
|
144
|
+
const metaText = [title ?? "", metaBody].join("\n").trim();
|
|
145
|
+
if (metaText) {
|
|
146
|
+
// Searchable meta needs only insertChunk (required); it must NOT be
|
|
147
|
+
// gated on the optional insertProperty, or a chunk-capable store would
|
|
148
|
+
// silently lose title/description search.
|
|
149
|
+
const heading = title ?? (rel.split("/").pop() ?? rel).replace(/\.(md|mdx|markdown)$/i, "");
|
|
150
|
+
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
|
+
stats.chunks++;
|
|
152
|
+
}
|
|
153
|
+
if (store.insertProperty)
|
|
154
|
+
for (const row of buildProperties(frontmatter, fmCfg.facetKeys))
|
|
155
|
+
store.insertProperty({ root: src.root, path: rel, ...row });
|
|
156
|
+
}
|
|
157
|
+
// Mirror docType for EVERY file (facetable regardless of frontmatter presence).
|
|
158
|
+
store.insertProperty?.({ root: src.root, path: rel, key: "docType", value: dt, valueNum: null, valueDate: null, valueRaw: dt });
|
|
159
|
+
if (parseFailed)
|
|
160
|
+
stats.parseFailures = (stats.parseFailures ?? 0) + 1;
|
|
138
161
|
store.setFileState(src.root, rel, { mtimeMs: st.mtimeMs, sha256: hash }); // persist for incremental
|
|
139
162
|
stats.changed++;
|
|
140
163
|
stats.chunks += chunks.length;
|