@blackbelt-technology/pi-dashboard-kb 0.6.0 → 0.7.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.
@@ -4,6 +4,9 @@
4
4
  import { mkdirSync, renameSync, unlinkSync } from "node:fs";
5
5
  import { dirname } from "node:path";
6
6
  import { DatabaseSync } from "node:sqlite";
7
+ /** Bump when the frontmatter structural schema/behavior changes so an existing
8
+ * DB force-reindexes once on open (design D6). */
9
+ export const SCHEMA_VERSION = 2;
7
10
  const DDL = `
8
11
  CREATE VIRTUAL TABLE IF NOT EXISTS chunks USING fts5(
9
12
  root UNINDEXED, path UNINDEXED, chunk_id UNINDEXED, doc_type UNINDEXED,
@@ -25,7 +28,49 @@ CREATE TABLE IF NOT EXISTS edges (
25
28
  );
26
29
  CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src);
27
30
  CREATE INDEX IF NOT EXISTS idx_edges_dst ON edges(dst);
31
+ CREATE TABLE IF NOT EXISTS properties (
32
+ root TEXT, path TEXT, key TEXT,
33
+ value TEXT, value_num REAL, value_date TEXT, value_raw TEXT
34
+ );
35
+ -- The unique index doubles as the (root,path) lookup for delete-by-path (its
36
+ -- leading columns), so no separate idx_props_path is needed — one fewer index to
37
+ -- maintain on the hot per-file insert path.
38
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_props_uniq ON properties(root, path, key, value);
39
+ CREATE INDEX IF NOT EXISTS idx_props_kv ON properties(key, value);
40
+ CREATE TABLE IF NOT EXISTS kb_meta (k TEXT PRIMARY KEY, v TEXT);
28
41
  `;
42
+ /** Build correlated EXISTS predicates for facet filters. All values are bound as
43
+ * parameters (never interpolated) — SQL-injection guard (design D7). */
44
+ function buildFilterClauses(filters, outer) {
45
+ const clauses = [];
46
+ const args = [];
47
+ const norm = (v) => String(v).toLowerCase().trim();
48
+ // Match column for equality by declared type: number→value_num, date→value_date,
49
+ // else the normalized string value (the parser may pre-coerce numeric scalars,
50
+ // so eq on a typed key must not compare the lossy string column).
51
+ const eqCol = (t) => (t === "number" ? "value_num" : t === "date" ? "value_date" : "value");
52
+ const eqVal = (t, v) => (t === "number" ? Number(v) : t === "date" ? String(v) : norm(v));
53
+ for (const f of filters ?? []) {
54
+ if (f.op === "eq" && f.value != null) {
55
+ const col = eqCol(f.type);
56
+ clauses.push(`EXISTS (SELECT 1 FROM properties p WHERE p.root=${outer}.root AND p.path=${outer}.path AND p.key=? AND p.${col}=?)`);
57
+ args.push(f.key, eqVal(f.type, f.value));
58
+ }
59
+ else if (f.op === "in" && f.values?.length) {
60
+ const col = eqCol(f.type);
61
+ const ph = f.values.map(() => "?").join(",");
62
+ clauses.push(`EXISTS (SELECT 1 FROM properties p WHERE p.root=${outer}.root AND p.path=${outer}.path AND p.key=? AND p.${col} IN (${ph}))`);
63
+ args.push(f.key, ...f.values.map((v) => eqVal(f.type, v)));
64
+ }
65
+ else if ((f.op === "gte" || f.op === "lte") && f.value != null) {
66
+ const col = f.type === "number" ? "value_num" : f.type === "date" ? "value_date" : "value";
67
+ const cmp = f.op === "gte" ? ">=" : "<=";
68
+ clauses.push(`EXISTS (SELECT 1 FROM properties p WHERE p.root=${outer}.root AND p.path=${outer}.path AND p.key=? AND p.${col} IS NOT NULL AND p.${col} ${cmp} ?)`);
69
+ args.push(f.key, f.type === "number" ? Number(f.value) : f.type === "date" ? String(f.value) : norm(f.value));
70
+ }
71
+ }
72
+ return { clauses, args };
73
+ }
29
74
  // FTS5 query builder: OR the alphanumeric terms (recall + BM25 ranks).
30
75
  function toMatch(q) {
31
76
  const terms = tokenize(q);
@@ -35,6 +80,17 @@ function toMatch(q) {
35
80
  export class SqliteFtsStore {
36
81
  db;
37
82
  dbPath;
83
+ // Prepared-statement cache: re-preparing per row on a hot insert path (chunks
84
+ // + properties, many per file) is a measurable reindex cost. Cache by SQL.
85
+ stmts = new Map();
86
+ prep(sql) {
87
+ let s = this.stmts.get(sql);
88
+ if (!s) {
89
+ s = this.db.prepare(sql);
90
+ this.stmts.set(sql, s);
91
+ }
92
+ return s;
93
+ }
38
94
  constructor(dbPath) {
39
95
  this.dbPath = dbPath;
40
96
  if (dbPath !== ":memory:")
@@ -107,17 +163,61 @@ export class SqliteFtsStore {
107
163
  return this.db.prepare("SELECT path FROM files WHERE root=?").all(root).map((r) => r.path);
108
164
  }
109
165
  deleteByPath(root, path) {
166
+ // chunks includes the file's synthetic `:meta` chunk (same path) — removed here.
110
167
  this.db.prepare("DELETE FROM chunks WHERE root=? AND path=?").run(root, path);
111
168
  // outbound edges originate from this file's nodes; prune nodes owned by path then dangling edges
112
169
  const owned = this.db.prepare("SELECT id FROM nodes WHERE path=?").all(path);
113
170
  for (const n of owned)
114
171
  this.db.prepare("DELETE FROM edges WHERE src=? OR dst=?").run(n.id, n.id);
115
172
  this.db.prepare("DELETE FROM nodes WHERE path=?").run(path);
173
+ this.db.prepare("DELETE FROM properties WHERE root=? AND path=?").run(root, path);
116
174
  this.db.prepare("DELETE FROM files WHERE root=? AND path=?").run(root, path);
117
175
  }
176
+ deletePropertiesByPath(root, path) {
177
+ this.db.prepare("DELETE FROM properties WHERE root=? AND path=?").run(root, path);
178
+ }
179
+ insertProperty(r) {
180
+ // INSERT OR IGNORE + UNIQUE(root,path,key,value) de-dups within-file duplicates.
181
+ this.prep("INSERT OR IGNORE INTO properties(root,path,key,value,value_num,value_date,value_raw) VALUES(?,?,?,?,?,?,?)").run(r.root, r.path, r.key, r.value, r.valueNum, r.valueDate, r.valueRaw);
182
+ }
183
+ facets(keys, opts = {}) {
184
+ const out = {};
185
+ if (!keys.length)
186
+ return out;
187
+ const where = [`key IN (${keys.map(() => "?").join(",")})`];
188
+ const args = [...keys];
189
+ if (opts.root) {
190
+ where.push("o.root = ?");
191
+ args.push(opts.root);
192
+ }
193
+ const f = buildFilterClauses(opts.filters, "o");
194
+ where.push(...f.clauses);
195
+ args.push(...f.args);
196
+ // Distinct FILES, not rows: two sources with the same relative path are two
197
+ // files, so count distinct (root,path) — within-file duplicates already
198
+ // collapse via the UNIQUE(root,path,key,value) index.
199
+ const sql = `SELECT key, value, COUNT(DISTINCT root || char(31) || path) n FROM properties o WHERE ${where.join(" AND ")} GROUP BY key, value`;
200
+ for (const r of this.db.prepare(sql).all(...args)) {
201
+ (out[r.key] ??= {})[r.value] = r.n;
202
+ }
203
+ return out;
204
+ }
205
+ getUserVersion() {
206
+ return this.db.prepare("PRAGMA user_version").get().user_version;
207
+ }
208
+ setUserVersion(v) {
209
+ // PRAGMA does not accept a bound parameter; v is an internal integer constant.
210
+ this.db.exec(`PRAGMA user_version = ${Math.trunc(v)}`);
211
+ }
212
+ getMeta(k) {
213
+ const r = this.db.prepare("SELECT v FROM kb_meta WHERE k=?").get(k);
214
+ return r ? r.v : null;
215
+ }
216
+ setMeta(k, v) {
217
+ this.db.prepare("INSERT INTO kb_meta(k,v) VALUES(?,?) ON CONFLICT(k) DO UPDATE SET v=excluded.v").run(k, v);
218
+ }
118
219
  insertChunk(c) {
119
- this.db
120
- .prepare("INSERT INTO chunks(root,path,chunk_id,doc_type,parent_chunk_id,level,body_hash,heading_path,heading,body) VALUES(?,?,?,?,?,?,?,?,?,?)")
220
+ this.prep("INSERT INTO chunks(root,path,chunk_id,doc_type,parent_chunk_id,level,body_hash,heading_path,heading,body) VALUES(?,?,?,?,?,?,?,?,?,?)")
121
221
  .run(c.root, c.path, c.chunkId, c.docType, c.parentChunkId, c.level, c.bodyHash, c.headingPath, c.heading, c.body);
122
222
  }
123
223
  addNode(n) {
@@ -160,6 +260,10 @@ export class SqliteFtsStore {
160
260
  where.push("doc_type = ?");
161
261
  args.push(opts.docType);
162
262
  }
263
+ // structured facet filters (opt-in; absent → no clause → identical query)
264
+ const ff = buildFilterClauses(opts.filters, "chunks");
265
+ where.push(...ff.clauses);
266
+ args.push(...ff.args);
163
267
  const sql = `SELECT root, path, chunk_id chunkId, doc_type docType, body_hash bodyHash,
164
268
  parent_chunk_id parentChunkId, heading_path headingPath, heading, body,
165
269
  bm25(chunks, 0,0,0,0,0,0,0, ${w.headingPath}, ${w.heading}, ${w.body}) score,
package/dist/types.d.ts CHANGED
@@ -38,6 +38,26 @@ export interface KbHit {
38
38
  }
39
39
  /** A pluggable reranker: rescoring BM25 top-k. Default = none (no-op). */
40
40
  export type Reranker = (query: string, candidates: KbHit[]) => Promise<KbHit[]> | KbHit[];
41
+ /** Structured frontmatter facet filter (add-kb-frontmatter-structural-indexing).
42
+ * Values are always parameter-bound. `type` selects the range column for
43
+ * gte/lte: number → value_num, date → value_date, string/omitted → value. */
44
+ export interface Filter {
45
+ key: string;
46
+ op: "eq" | "in" | "gte" | "lte";
47
+ value?: string | number;
48
+ values?: Array<string | number>;
49
+ type?: "string" | "number" | "date";
50
+ }
51
+ /** A property row persisted for a file's facet frontmatter. */
52
+ export interface StorePropertyRow {
53
+ root: string;
54
+ path: string;
55
+ key: string;
56
+ value: string;
57
+ valueNum: number | null;
58
+ valueDate: string | null;
59
+ valueRaw: string;
60
+ }
41
61
  export interface SearchOpts {
42
62
  limit?: number;
43
63
  root?: string;
@@ -60,6 +80,7 @@ export interface SearchOpts {
60
80
  reranker?: Reranker;
61
81
  queryExpansion?: "off" | "prf" | "synonym" | "agent";
62
82
  synonyms?: Record<string, string[]>;
83
+ filters?: Filter[];
63
84
  }
64
85
  export interface FileState {
65
86
  mtimeMs: number;
@@ -79,6 +100,16 @@ export interface KbStore {
79
100
  insertChunk(c: Chunk): void;
80
101
  addNode(n: GraphNode): void;
81
102
  addEdge(e: GraphEdge): void;
103
+ insertProperty?(row: StorePropertyRow): void;
104
+ deletePropertiesByPath?(root: string, path: string): void;
105
+ facets?(keys: string[], opts?: {
106
+ root?: string;
107
+ filters?: Filter[];
108
+ }): Record<string, Record<string, number>>;
109
+ getUserVersion?(): number;
110
+ setUserVersion?(v: number): void;
111
+ getMeta?(k: string): string | null;
112
+ setMeta?(k: string, v: string): void;
82
113
  search(query: string, opts?: SearchOpts): KbHit[];
83
114
  neighbors(node: string, depth: number, rel?: GraphEdge["rel"]): GraphNode[];
84
115
  backlinks(node: string): GraphNode[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-dashboard-kb",
3
- "version": "0.6.0",
3
+ "version": "0.7.0",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/BlackBeltTechnology/pi-agent-dashboard",
package/src/AGENTS.md CHANGED
@@ -7,7 +7,7 @@ Files in this directory. One row per source file.
7
7
  | `chunker.ts` | Structural heading chunker. Fence-safe, breadcrumb-aware. Line-based fenced-code state machine. |
8
8
  | `cli.ts` | kb CLI. Commands init\|index\|search\|neighbors\|backlinks\|get\|agents\|dox\|eval\|config. Dev run NODE_OPTIONS=--experimental-sqlite tsx src/cli.ts. `index` routes through `runIndexAtomic` (index-run.ts) and does NOT `openStore` — opening pre-creates the DB husk. `search`/`eval` still `openStore` + auto-reindex. `search` non-json branch calls shared `renderHits(leading:"score")`. See change: harden-kb-index-failure-atomicity; slim-kb-search-output. |
9
9
  | `config.ts` | Config layering. project .pi/dashboard/knowledge_base.json → global ~/.pi/dashboard/knowledge_base.json → defaults. No file-count cap default. |
10
- | `dox.ts` | DOX tree. Directory-level AGENTS.md scaffold + audit. kb agents <path> nearest-applicable chain. Detect-don't-write: dox init/--fix fill PATH columns + prune orphans only. `over-threshold` lint splits two arms: `arm:"bytes"` (actionable — bytes > `AGENTS_BYTE_CAP` 30 KB, auto-injected per turn, remedy sidecar split) + `arm:"rows"` (informational — inline count > `ROW_CAP` 40, no per-turn cost, optional foldering). `countInlineRows(af)` counts INLINE rows only (excludes sidecar-pointer rows matching `/→ see \`<File>.AGENTS.md\`/`) — sibling to `parseRowPaths` (public export consumed by kb-extension; signature untouched, stays complete path list). Splitting a heavy row to its sidecar drops both byte + counted-row totals. `ROW_CAP`/`AGENTS_BYTE_CAP` numeric values unchanged. `isMdFile` excludes `*.AGENTS.md` sidecars + `*.agent.md` companions (both DOX index artifacts, not documentable source). `DEFAULT_EXCLUDE` skips build output (`out`) + electron bundled/vendored trees (`bundled-extensions`, `electron/resources/server`) — all gitignored, fs-walk-only, else bogus missing/companion rows; `server` scoped to `electron/resources/server` so real `server` source dirs stay indexed. `resolveRowPath(agentsDir,cwd,rp)` resolves rows relative to their OWN AGENTS.md dir, repo-root `cwd` fallback (nested AGENTS.md may document a file living at project root) before orphan. `parseRowPaths` + `doxLint` scan only rows under a `# DOX —` heading (prose tables like Subagent Routing ignored). `doxLint` `walkAgents` tests `DEFAULT_EXCLUDE` on the cwd-RELATIVE path (mirrors `walkFiles`) so running inside `.worktrees/` does not exclude the whole tree. `rowPaths`/staleness keyed cwd-relative. See change: split-components-agents-dedup-rollup. See change: fix-dox-lint-false-positives. See change: fold-oversized-agents-directories. |
10
+ | `dox.ts` | DOX tree. Directory-level AGENTS.md scaffold + audit. kb agents <path> nearest-applicable chain. Detect-don't-write: dox init/--fix fill PATH columns + prune orphans only. `over-threshold` lint splits two arms: `arm:"bytes"` (actionable — bytes > `AGENTS_BYTE_CAP` 30 KB, auto-injected per turn, remedy sidecar split) + `arm:"rows"` (informational — inline count > `ROW_CAP` 40, no per-turn cost, optional foldering). `countInlineRows(af)` counts INLINE rows only (excludes sidecar-pointer rows matching `/→ see \`<File>.AGENTS.md\`/`) — sibling to `parseRowPaths` (public export consumed by kb-extension; signature untouched, stays complete path list). Splitting a heavy row to its sidecar drops both byte + counted-row totals. `ROW_CAP`/`AGENTS_BYTE_CAP` numeric values unchanged. `isMdFile` excludes `*.AGENTS.md` sidecars + `*.agent.md` companions (both DOX index artifacts, not documentable source). `DEFAULT_EXCLUDE` skips build output (`out`) + electron bundled/vendored trees (`bundled-extensions`, `electron/resources/server`) + `.reverse-spec-scratch` (transient reverse-spec experiment output) — all gitignored, fs-walk-only, else bogus missing/companion rows; `server` scoped to `electron/resources/server` so real `server` source dirs stay indexed. `resolveRowPath(agentsDir,cwd,rp)` resolves rows relative to their OWN AGENTS.md dir, repo-root `cwd` fallback (nested AGENTS.md may document a file living at project root) before orphan. `parseRowPaths` + `doxLint` scan only rows under a `# DOX —` heading (prose tables like Subagent Routing ignored). `doxLint` `walkAgents` tests `DEFAULT_EXCLUDE` on the cwd-RELATIVE path (mirrors `walkFiles`) so running inside `.worktrees/` does not exclude the whole tree. `rowPaths`/staleness keyed cwd-relative. See change: split-components-agents-dedup-rollup. See change: fix-dox-lint-false-positives. See change: fold-oversized-agents-directories. |
11
11
  | `eval.ts` | Retrieval-quality eval. Scores search against golden set. Gates ranking changes. |
12
12
  | `index-run.ts` | Atomic `kb index` orchestration. `runIndexAtomic({dbPath,sources,indexOpts,explicit})` returns `IndexStats & {counts}` (counts read from the still-open store so `index` never re-`openStore`s). First index (no dbPath) builds into `<dbPath>.tmp-<pid>` + `rename()` on success (survives OOM/SIGKILL — real path only on success); incremental (dbPath exists) indexes in place (mid-run failure leaves prior DB valid & queryable). All-sources-missing + explicit-`--source`-missing throw BEFORE any store opens (no husk). `sweepOrphanTemps` unlinks stale `.tmp-*` but SKIPS a temp whose PID is a live process (concurrent peer's active build). See change: harden-kb-index-failure-atomicity. |
13
13
  | `index.ts` | Public API barrel for @blackbelt-technology/pi-dashboard-kb. Exports `renderHits` + `RenderOpts`. |
package/src/chunker.ts CHANGED
@@ -2,6 +2,7 @@
2
2
  // Line-based with a fenced-code state machine; validated in the prototype
3
3
  // (research §2.5). mdast (unified/remark) is the documented refinement.
4
4
  import { createHash } from "node:crypto";
5
+ import { type FmValue, parseFrontmatter } from "./frontmatter.js";
5
6
  import type { Chunk, DocType } from "./types.js";
6
7
 
7
8
  const MIN_CHUNK_CHARS = 100;
@@ -18,29 +19,15 @@ export interface ChunkInput {
18
19
 
19
20
  export interface ParseResult {
20
21
  chunks: Chunk[];
21
- frontmatter: Record<string, unknown> | null;
22
+ frontmatter: Record<string, FmValue> | null;
22
23
  wikilinks: string[]; // [[name]] targets found anywhere in the file
23
24
  mdLinks: string[]; // [text](path.md) relative targets
24
- }
25
-
26
- function parseFrontmatter(text: string): { body: string; fm: Record<string, unknown> | null } {
27
- if (!text.startsWith("---\n")) return { body: text, fm: null };
28
- const end = text.indexOf("\n---", 4);
29
- if (end === -1) return { body: text, fm: null };
30
- const raw = text.slice(4, end);
31
- const fm: Record<string, unknown> = {};
32
- for (const line of raw.split("\n")) {
33
- const m = line.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);
34
- if (!m) continue;
35
- const [, k, v] = m;
36
- fm[k] = v.startsWith("[") ? v.replace(/^\[|\]$/g, "").split(",").map((s) => s.trim().replace(/^["']|["']$/g, "")).filter(Boolean) : v.replace(/^["']|["']$/g, "");
37
- }
38
- return { body: text.slice(end + 4), fm };
25
+ parseFailed: boolean; // frontmatter block present but a line did not parse
39
26
  }
40
27
 
41
28
  export function chunkMarkdown(input: ChunkInput): ParseResult {
42
29
  const docType: DocType = input.docType ?? "doc";
43
- const { body: text, fm } = parseFrontmatter(input.text);
30
+ const { body: text, fm, parseFailed } = parseFrontmatter(input.text);
44
31
  const lines = text.split("\n");
45
32
  const fileTitle = input.path.split("/").pop()!.replace(/\.(md|mdx|markdown)$/i, "");
46
33
 
@@ -138,5 +125,5 @@ export function chunkMarkdown(input: ChunkInput): ParseResult {
138
125
  const wikilinks = [...input.text.matchAll(/\[\[([^\]]+)\]\]/g)].map((m) => m[1].trim());
139
126
  const mdLinks = [...input.text.matchAll(/\]\(([^)]+\.mdx?)\)/g)].map((m) => m[1].trim());
140
127
 
141
- return { chunks, frontmatter: fm, wikilinks, mdLinks };
128
+ return { chunks, frontmatter: fm, wikilinks, mdLinks, parseFailed };
142
129
  }
package/src/cli.ts CHANGED
@@ -4,7 +4,7 @@
4
4
  // Shipped bin builds to dist/cli.js (build step deferred).
5
5
  import { readFileSync } from "node:fs";
6
6
  import { resolve } from "node:path";
7
- import { loadConfig, type ResolvedConfig, type ResolvedSource } from "./config.js";
7
+ import { frontmatterConfigHash, loadConfig, type ResolvedConfig, type ResolvedSource } from "./config.js";
8
8
  import { agentsChain, doxInit, doxLint } from "./dox.js";
9
9
  import { evaluate, type GoldenItem } from "./eval.js";
10
10
  import { runIndexAtomic } from "./index-run.js";
@@ -12,7 +12,7 @@ import { indexSource } from "./indexer.js";
12
12
  import { kbInit } from "./init.js";
13
13
  import { renderHits } from "./render.js";
14
14
  import { classifyRef, type ResolvedSource as RResolvedSource, resolveAll } from "./sources.js";
15
- import { SqliteFtsStore } from "./sqlite-store.js";
15
+ import { SCHEMA_VERSION, SqliteFtsStore } from "./sqlite-store.js";
16
16
  import { defaultPromptTrust } from "./trust.js";
17
17
  import type { DocType, SearchOpts } from "./types.js";
18
18
 
@@ -71,11 +71,19 @@ function openStore(cfg: ResolvedConfig): SqliteFtsStore {
71
71
  return store;
72
72
  }
73
73
  async function runIndex(cfg: ResolvedConfig, store: SqliteFtsStore, sources: RResolvedSource[], force = false) {
74
+ // Apply the same schema-version / facet-config gate as runIndexAtomic so the
75
+ // auto-index-on-search path also picks up new structures after an upgrade or a
76
+ // frontmatter-config change (else the DB stays stale until an explicit `index`).
77
+ const hash = frontmatterConfigHash(cfg.frontmatter);
78
+ const stale = (store.getUserVersion?.() ?? 0) < SCHEMA_VERSION || (store.getMeta?.("facetConfigHash") ?? null) !== hash;
79
+ const eff = force || stale;
74
80
  let scanned = 0, changed = 0, deleted = 0, chunks = 0;
75
81
  for (const s of sources) {
76
- const st = await indexSource(store, { root: s.id, dir: s.dir }, { force, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions });
82
+ 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 });
77
83
  scanned += st.scanned; changed += st.changed; deleted += st.deleted; chunks += st.chunks;
78
84
  }
85
+ store.setUserVersion?.(SCHEMA_VERSION);
86
+ store.setMeta?.("facetConfigHash", hash);
79
87
  return { scanned, changed, deleted, chunks };
80
88
  }
81
89
 
@@ -188,7 +196,8 @@ async function runCmd(cmd: string, flags: Flags): Promise<void> {
188
196
  const s = await runIndexAtomic({
189
197
  dbPath: cfg.dbAbsPath,
190
198
  sources: sources.map((x) => ({ id: x.id, dir: x.dir })),
191
- indexOpts: { force: !!flags.force, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions },
199
+ indexOpts: { force: !!flags.force, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions, frontmatter: cfg.frontmatter },
200
+ facetConfigHash: frontmatterConfigHash(cfg.frontmatter),
192
201
  explicit,
193
202
  });
194
203
  console.log(`indexed ${s.scanned} files (${s.changed} changed, ${s.deleted} deleted, ${s.chunks} chunks) in ${(performance.now() - t).toFixed(0)}ms`);
package/src/config.ts CHANGED
@@ -2,9 +2,11 @@
2
2
  // → global `~/.pi/dashboard/knowledge_base.json` → built-in defaults.
3
3
  // Project file is used whole; absent fields fall back to global, then defaults.
4
4
  // No file-count cap by default (requirement #1).
5
+ import { createHash } from "node:crypto";
5
6
  import { existsSync, readFileSync } from "node:fs";
6
7
  import { homedir } from "node:os";
7
8
  import { isAbsolute, join, resolve } from "node:path";
9
+ import { DEFAULT_FACET_KEYS, DEFAULT_SEARCHABLE_KEYS, type FacetKeyConfig } from "./frontmatter.js";
8
10
 
9
11
  function expandTilde(p: string): string {
10
12
  return p.startsWith("~/") ? join(homedir(), p.slice(2)) : p;
@@ -41,6 +43,10 @@ export interface DirectoryLevelAgentsConfig {
41
43
  mode: "pull" | "push";
42
44
  fallbackManifest: boolean;
43
45
  }
46
+ export interface FrontmatterConfig {
47
+ searchableKeys: string[]; // frontmatter values indexed as searchable meta
48
+ facetKeys: FacetKeyConfig[]; // whitelisted facet keys (+ optional declared type)
49
+ }
44
50
  export interface KbConfig {
45
51
  sources: SourceConfig[];
46
52
  roots?: Array<{ path: string; priority?: number }>; // legacy alias → filesystem sources
@@ -59,6 +65,7 @@ export interface KbConfig {
59
65
  dedup: { exactContentCollapse: boolean; preferHigherPriorityRoot: boolean };
60
66
  graph: { wikilinks: boolean; headingTree: boolean; frontmatter: boolean };
61
67
  directoryLevelAgents: DirectoryLevelAgentsConfig;
68
+ frontmatter: FrontmatterConfig;
62
69
  doxEnforcement: boolean; // opt-in Phase-2 hook Job 2 (default OFF)
63
70
  ranking: RankingConfig;
64
71
  expand: ExpandConfig;
@@ -101,6 +108,7 @@ export const DEFAULTS: KbConfig = {
101
108
  // no per-turn injection. Push mode stays gated behind the context-cost spike
102
109
  // (see change migrate-file-index-to-agents-tree design §5).
103
110
  directoryLevelAgents: { enabled: true, claudeMd: true, mode: "pull", fallbackManifest: true },
111
+ frontmatter: { searchableKeys: DEFAULT_SEARCHABLE_KEYS, facetKeys: DEFAULT_FACET_KEYS },
104
112
  doxEnforcement: false,
105
113
  ranking: { fieldWeights: { headingPath: 10, heading: 3, body: 1 }, proximityBoost: true, diversity: { enabled: true, lambda: 0.7 } },
106
114
  expand: { parent: true, graph: false },
@@ -111,7 +119,17 @@ export const DEFAULTS: KbConfig = {
111
119
 
112
120
  // Nested object keys that need one-level field fill-in (not wholesale replace),
113
121
  // so a partial `{ranking:{proximityBoost:false}}` keeps default fieldWeights/diversity.
114
- const NESTED_KEYS = ["chunking", "dedup", "graph", "directoryLevelAgents", "ranking", "expand", "rerank", "queryExpansion"] as const;
122
+ const NESTED_KEYS = ["chunking", "dedup", "graph", "directoryLevelAgents", "frontmatter", "ranking", "expand", "rerank", "queryExpansion"] as const;
123
+
124
+ /** Stable hash of the frontmatter routing config. A change forces a full reindex
125
+ * (design D6) since existing property rows/meta chunks reflect the old routing. */
126
+ export function frontmatterConfigHash(fm: FrontmatterConfig): string {
127
+ const norm = {
128
+ searchableKeys: [...fm.searchableKeys].sort(),
129
+ facetKeys: [...fm.facetKeys].map((f) => ({ key: f.key, type: f.type ?? "string" })).sort((a, b) => a.key.localeCompare(b.key)),
130
+ };
131
+ return createHash("sha256").update(JSON.stringify(norm)).digest("hex").slice(0, 16);
132
+ }
115
133
 
116
134
  /** Layer configs left→right, deep-merging the known nested object keys. */
117
135
  export function mergeConfig(...layers: Array<Partial<KbConfig> | null | undefined>): Partial<KbConfig> {
@@ -142,6 +160,13 @@ export function validateConfig(c: Partial<KbConfig>, origin = "config"): KbConfi
142
160
  if (typeof merged.maxFileCount !== "number" && merged.maxFileCount !== null) throw err("maxFileCount must be a number or null");
143
161
  if (typeof merged.dbPath !== "string" || !merged.dbPath) throw err("dbPath must be a non-empty string");
144
162
  if (!/^(off|prf|synonym|agent)$/.test(merged.queryExpansion.mode)) throw err(`queryExpansion.mode "${merged.queryExpansion.mode}" unknown`);
163
+ const fm = merged.frontmatter;
164
+ if (!fm || !Array.isArray(fm.searchableKeys) || fm.searchableKeys.some((k) => typeof k !== "string")) throw err("frontmatter.searchableKeys must be a string array");
165
+ if (!Array.isArray(fm.facetKeys)) throw err("frontmatter.facetKeys must be an array");
166
+ for (const f of fm.facetKeys) {
167
+ if (typeof f !== "object" || f === null || typeof f.key !== "string") throw err("each frontmatter.facetKeys entry needs a string `key`");
168
+ if (f.type != null && !/^(string|number|date)$/.test(f.type)) throw err(`frontmatter facet key "${f.key}" has unknown type "${f.type}"`);
169
+ }
145
170
  return merged;
146
171
  }
147
172
 
package/src/dox.ts CHANGED
@@ -18,7 +18,7 @@ import type { KbStore } from "./types.js";
18
18
  // navigable source) and self-evident top-level docs (`CHANGELOG.md`, `CLAUDE.md`,
19
19
  // repo-root `README.md`) with no per-file DOX value; `README` anchored to root so
20
20
  // package READMEs stay documented.
21
- const DEFAULT_EXCLUDE = /(^|\/)(node_modules|\.git|\.github|dist|build|out|\.next|coverage|\.kb|\.pi|\.worktrees|openspec|doc-example|bundled-extensions|mockups|research|site|Prompt stories)(\/|$)|(^|\/)electron\/resources\/server(\/|$)|(^|\/)(CHANGELOG|CLAUDE)\.md$|^README\.md$/;
21
+ const DEFAULT_EXCLUDE = /(^|\/)(node_modules|\.git|\.github|dist|build|out|\.next|coverage|\.kb|\.pi|\.worktrees|\.reverse-spec-scratch|openspec|doc-example|bundled-extensions|mockups|research|site|Prompt stories)(\/|$)|(^|\/)electron\/resources\/server(\/|$)|(^|\/)(CHANGELOG|CLAUDE)\.md$|^README\.md$/;
22
22
  const AGENTS_FILES = ["AGENTS.md"];
23
23
  // delta ①: dox init now maps SOURCE, not docs. Source globs, minus type decls and tests.
24
24
  const SOURCE_EXT = /\.(ts|tsx|js|jsx)$/;
@@ -0,0 +1,221 @@
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
+
12
+ export type FmScalar = string | number | boolean;
13
+ export type FmValue = FmScalar | string[];
14
+
15
+ export interface ParsedFrontmatter {
16
+ body: string; // markdown after the frontmatter block (CRLF-normalized)
17
+ fm: Record<string, FmValue> | null; // null when no/malformed frontmatter
18
+ parseFailed: boolean; // a frontmatter block was present but a line did not parse
19
+ }
20
+
21
+ /** Strip a trailing `# comment`. For a quoted value, keep through the closing
22
+ * quote and drop any comment after it (`title: "H" # c` → `"H"`). */
23
+ function stripComment(s: string): string {
24
+ const t = s.trim();
25
+ if (t.startsWith('"') || t.startsWith("'")) {
26
+ const close = t.indexOf(t[0], 1);
27
+ return close > 0 ? t.slice(0, close + 1) : t; // unterminated quote → leave as-is
28
+ }
29
+ const idx = t.indexOf(" #");
30
+ return (idx >= 0 ? t.slice(0, idx) : t).trim();
31
+ }
32
+
33
+ /** Coerce a bare scalar token to bool/int/float/string. Quoted → string. */
34
+ function coerceScalar(raw: string): FmScalar {
35
+ const s = raw.trim();
36
+ if ((s.startsWith('"') && s.endsWith('"') && s.length >= 2) || (s.startsWith("'") && s.endsWith("'") && s.length >= 2)) {
37
+ return s.slice(1, -1);
38
+ }
39
+ if (s === "true") return true;
40
+ if (s === "false") return false;
41
+ if (/^-?\d+$/.test(s)) return parseInt(s, 10);
42
+ if (/^-?\d+\.\d+$/.test(s)) return parseFloat(s);
43
+ return s;
44
+ }
45
+
46
+ /** Parse an inline `[a, b, "c"]` array to a string[] (elements trimmed/unquoted). */
47
+ function parseInlineArray(s: string): string[] {
48
+ const inner = s.replace(/^\[/, "").replace(/\]$/, "");
49
+ return inner
50
+ .split(",")
51
+ .map((e) => {
52
+ const t = e.trim();
53
+ const unq = (t.startsWith('"') && t.endsWith('"')) || (t.startsWith("'") && t.endsWith("'")) ? t.slice(1, -1) : t;
54
+ return unq.trim();
55
+ })
56
+ .filter((e) => e.length > 0);
57
+ }
58
+
59
+ const isIndented = (line: string): boolean => /^\s/.test(line);
60
+ const isBlank = (line: string): boolean => line.trim() === "";
61
+
62
+ /** Detect + parse a leading YAML-subset frontmatter block. Total + pure. */
63
+ export function parseFrontmatter(text: string): ParsedFrontmatter {
64
+ const norm = text.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n"); // strip BOM; CRLF/CR → LF
65
+ const lines = norm.split("\n");
66
+ if (lines[0] !== "---") return { body: norm, fm: null, parseFailed: false };
67
+ let end = -1;
68
+ for (let i = 1; i < lines.length; i++) {
69
+ if (lines[i] === "---") {
70
+ end = i;
71
+ break;
72
+ }
73
+ }
74
+ if (end === -1) return { body: norm, fm: null, parseFailed: false }; // no closing fence → not frontmatter
75
+
76
+ const fmLines = lines.slice(1, end);
77
+ const body = lines.slice(end + 1).join("\n");
78
+ const fm: Record<string, FmValue> = {};
79
+ let parseFailed = false;
80
+
81
+ for (let i = 0; i < fmLines.length; i++) {
82
+ const line = fmLines[i];
83
+ if (isBlank(line) || line.trim().startsWith("#")) continue;
84
+ if (isIndented(line)) continue; // stray indented line without a parent key context
85
+ const m = line.match(/^([A-Za-z0-9_.\/-]+):(.*)$/);
86
+ if (!m) {
87
+ parseFailed = true;
88
+ continue;
89
+ }
90
+ const key = m[1];
91
+ const rest = stripComment(m[2]);
92
+
93
+ // Top-level `kb:` — consume + discard its entire indented subtree.
94
+ if (key === "kb") {
95
+ while (i + 1 < fmLines.length && (isIndented(fmLines[i + 1]) || isBlank(fmLines[i + 1]))) i++;
96
+ continue;
97
+ }
98
+
99
+ if (rest === "") {
100
+ // block list, nested map, or empty scalar
101
+ const items: string[] = [];
102
+ while (i + 1 < fmLines.length && /^\s*-\s+/.test(fmLines[i + 1])) {
103
+ i++;
104
+ items.push(stripComment(fmLines[i].replace(/^\s*-\s+/, "")).replace(/^["']|["']$/g, ""));
105
+ }
106
+ if (items.length) {
107
+ fm[key] = items.filter((e) => e.length > 0);
108
+ } else if (i + 1 < fmLines.length && /^\s+\S/.test(fmLines[i + 1])) {
109
+ // nested map (unsupported) → skip its indented subtree, emit nothing
110
+ while (i + 1 < fmLines.length && (isIndented(fmLines[i + 1]) || isBlank(fmLines[i + 1]))) i++;
111
+ } else {
112
+ fm[key] = "";
113
+ }
114
+ continue;
115
+ }
116
+
117
+ if (rest === "|" || rest === ">") {
118
+ // multiline block scalar (unsupported) → skip its indented subtree
119
+ while (i + 1 < fmLines.length && (isIndented(fmLines[i + 1]) || isBlank(fmLines[i + 1]))) i++;
120
+ continue;
121
+ }
122
+
123
+ if (rest.startsWith("[")) {
124
+ fm[key] = parseInlineArray(rest);
125
+ continue;
126
+ }
127
+
128
+ fm[key] = coerceScalar(rest);
129
+ }
130
+
131
+ return { body, fm, parseFailed };
132
+ }
133
+
134
+ // ── Structural routing (design D5): frontmatter → searchable meta + property rows
135
+
136
+ export interface FacetKeyConfig {
137
+ key: string;
138
+ type?: "string" | "number" | "date";
139
+ }
140
+
141
+ /** Default routing (superset of prior behavior: `tags` still drives has_tag). */
142
+ export const DEFAULT_SEARCHABLE_KEYS: string[] = ["title", "description", "aliases", "keywords"];
143
+ export const DEFAULT_FACET_KEYS: FacetKeyConfig[] = [
144
+ { key: "tags" },
145
+ { key: "status" },
146
+ { key: "author" },
147
+ { key: "category" },
148
+ { key: "date", type: "date" },
149
+ ];
150
+
151
+ export interface PropertyRow {
152
+ key: string;
153
+ value: string; // normalized: lowercased + trimmed (filters/facets match this)
154
+ valueNum: number | null; // set only for declared-numeric keys with a strict match
155
+ valueDate: string | null; // set only for declared-date keys, canonical YYYY-MM-DD
156
+ valueRaw: string; // original, for display
157
+ }
158
+
159
+ /** Strict full-match numeric coercion; null when not a clean, finite number
160
+ * (a very long digit string parses to Infinity — rejected). */
161
+ export function strictNumber(v: FmValue): number | null {
162
+ if (typeof v === "number") return Number.isFinite(v) ? v : null;
163
+ if (typeof v === "string" && /^-?\d+(\.\d+)?$/.test(v.trim())) {
164
+ const n = Number(v.trim());
165
+ return Number.isFinite(n) ? n : null;
166
+ }
167
+ return null;
168
+ }
169
+
170
+ /** Strict `YYYY-MM-DD` calendar date; null otherwise. Rejects impossible dates
171
+ * (e.g. `2024-02-31`) via a UTC round-trip. Instants deferred — design D3. */
172
+ export function strictDate(v: FmValue): string | null {
173
+ const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(v).trim());
174
+ if (!m) return null;
175
+ const y = +m[1], mo = +m[2], d = +m[3];
176
+ // setUTCFullYear (not Date.UTC) so years 0000–0099 are NOT remapped to 1900–1999
177
+ // (JS legacy two-digit-year behavior) — keeps valid dates like 0001-01-01.
178
+ const dt = new Date(0);
179
+ dt.setUTCFullYear(y, mo - 1, d);
180
+ return dt.getUTCFullYear() === y && dt.getUTCMonth() === mo - 1 && dt.getUTCDate() === d ? `${m[1]}-${m[2]}-${m[3]}` : null;
181
+ }
182
+
183
+ /** Build the searchable meta pieces: title (→ heading) and the rest (→ body).
184
+ * `tags` is never searchable (it is a facet). */
185
+ export function buildMeta(fm: Record<string, FmValue>, searchableKeys: string[]): { title: string | null; body: string } {
186
+ const title = searchableKeys.includes("title") && fm.title != null ? String(Array.isArray(fm.title) ? fm.title.join(" ") : fm.title) : null;
187
+ const parts: string[] = [];
188
+ for (const key of searchableKeys) {
189
+ if (key === "title" || key === "tags") continue;
190
+ const v = fm[key];
191
+ if (v == null) continue;
192
+ parts.push(Array.isArray(v) ? v.join(" ") : String(v));
193
+ }
194
+ return { title, body: parts.join(" ").trim() };
195
+ }
196
+
197
+ /** Build de-duplicated property rows for the whitelisted facet keys.
198
+ * Array values → one row per distinct element; within-file duplicates collapse. */
199
+ export function buildProperties(fm: Record<string, FmValue>, facetKeys: FacetKeyConfig[]): PropertyRow[] {
200
+ const rows: PropertyRow[] = [];
201
+ for (const { key, type } of facetKeys) {
202
+ const v = fm[key];
203
+ if (v == null) continue;
204
+ const elems: FmScalar[] = Array.isArray(v) ? v : [v];
205
+ const seen = new Set<string>();
206
+ for (const e of elems) {
207
+ const raw = String(e);
208
+ const value = raw.toLowerCase().trim();
209
+ if (value === "" || seen.has(value)) continue;
210
+ seen.add(value);
211
+ rows.push({
212
+ key,
213
+ value,
214
+ valueNum: type === "number" ? strictNumber(e) : null,
215
+ valueDate: type === "date" ? strictDate(raw) : null,
216
+ valueRaw: raw,
217
+ });
218
+ }
219
+ }
220
+ return rows;
221
+ }