@blackbelt-technology/pi-dashboard-kb 0.6.1 → 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.
package/dist/chunker.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type FmValue } from "./frontmatter.js";
1
2
  import type { Chunk, DocType } from "./types.js";
2
3
  export interface ChunkInput {
3
4
  root: string;
@@ -7,8 +8,9 @@ export interface ChunkInput {
7
8
  }
8
9
  export interface ParseResult {
9
10
  chunks: Chunk[];
10
- frontmatter: Record<string, unknown> | null;
11
+ frontmatter: Record<string, FmValue> | null;
11
12
  wikilinks: string[];
12
13
  mdLinks: string[];
14
+ parseFailed: boolean;
13
15
  }
14
16
  export declare function chunkMarkdown(input: ChunkInput): ParseResult;
package/dist/chunker.js CHANGED
@@ -2,29 +2,13 @@
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 { parseFrontmatter } from "./frontmatter.js";
5
6
  const MIN_CHUNK_CHARS = 100;
6
7
  const MAX_CHUNK_CHARS = 4000;
7
8
  const sha = (s) => createHash("sha256").update(s).digest("hex");
8
- function parseFrontmatter(text) {
9
- if (!text.startsWith("---\n"))
10
- return { body: text, fm: null };
11
- const end = text.indexOf("\n---", 4);
12
- if (end === -1)
13
- return { body: text, fm: null };
14
- const raw = text.slice(4, end);
15
- const fm = {};
16
- for (const line of raw.split("\n")) {
17
- const m = line.match(/^([A-Za-z0-9_-]+):\s*(.*)$/);
18
- if (!m)
19
- continue;
20
- const [, k, v] = m;
21
- fm[k] = v.startsWith("[") ? v.replace(/^\[|\]$/g, "").split(",").map((s) => s.trim().replace(/^["']|["']$/g, "")).filter(Boolean) : v.replace(/^["']|["']$/g, "");
22
- }
23
- return { body: text.slice(end + 4), fm };
24
- }
25
9
  export function chunkMarkdown(input) {
26
10
  const docType = input.docType ?? "doc";
27
- const { body: text, fm } = parseFrontmatter(input.text);
11
+ const { body: text, fm, parseFailed } = parseFrontmatter(input.text);
28
12
  const lines = text.split("\n");
29
13
  const fileTitle = input.path.split("/").pop().replace(/\.(md|mdx|markdown)$/i, "");
30
14
  const raw = [];
@@ -122,5 +106,5 @@ export function chunkMarkdown(input) {
122
106
  }));
123
107
  const wikilinks = [...input.text.matchAll(/\[\[([^\]]+)\]\]/g)].map((m) => m[1].trim());
124
108
  const mdLinks = [...input.text.matchAll(/\]\(([^)]+\.mdx?)\)/g)].map((m) => m[1].trim());
125
- return { chunks, frontmatter: fm, wikilinks, mdLinks };
109
+ return { chunks, frontmatter: fm, wikilinks, mdLinks, parseFailed };
126
110
  }
package/dist/cli.js 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 } from "./config.js";
7
+ import { frontmatterConfigHash, loadConfig } from "./config.js";
8
8
  import { agentsChain, doxInit, doxLint } from "./dox.js";
9
9
  import { evaluate } 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 { 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
  function parse(argv) {
18
18
  const f = { _: [] };
@@ -76,14 +76,22 @@ function openStore(cfg) {
76
76
  return store;
77
77
  }
78
78
  async function runIndex(cfg, store, sources, force = false) {
79
+ // Apply the same schema-version / facet-config gate as runIndexAtomic so the
80
+ // auto-index-on-search path also picks up new structures after an upgrade or a
81
+ // frontmatter-config change (else the DB stays stale until an explicit `index`).
82
+ const hash = frontmatterConfigHash(cfg.frontmatter);
83
+ const stale = (store.getUserVersion?.() ?? 0) < SCHEMA_VERSION || (store.getMeta?.("facetConfigHash") ?? null) !== hash;
84
+ const eff = force || stale;
79
85
  let scanned = 0, changed = 0, deleted = 0, chunks = 0;
80
86
  for (const s of sources) {
81
- 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 });
87
+ 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 });
82
88
  scanned += st.scanned;
83
89
  changed += st.changed;
84
90
  deleted += st.deleted;
85
91
  chunks += st.chunks;
86
92
  }
93
+ store.setUserVersion?.(SCHEMA_VERSION);
94
+ store.setMeta?.("facetConfigHash", hash);
87
95
  return { scanned, changed, deleted, chunks };
88
96
  }
89
97
  /** Resolve sources for a run. --source overrides (filesystem, sync); otherwise
@@ -206,7 +214,8 @@ async function runCmd(cmd, flags) {
206
214
  const s = await runIndexAtomic({
207
215
  dbPath: cfg.dbAbsPath,
208
216
  sources: sources.map((x) => ({ id: x.id, dir: x.dir })),
209
- indexOpts: { force: !!flags.force, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions },
217
+ indexOpts: { force: !!flags.force, indexAgentsFiles: cfg.indexAgentsFiles, includeSourceMarkdown: cfg.includeSourceMarkdown, include: cfg.include, exclude: cfg.exclude, extensions: cfg.extensions, frontmatter: cfg.frontmatter },
218
+ facetConfigHash: frontmatterConfigHash(cfg.frontmatter),
210
219
  explicit,
211
220
  });
212
221
  console.log(`indexed ${s.scanned} files (${s.changed} changed, ${s.deleted} deleted, ${s.chunks} chunks) in ${(performance.now() - t).toFixed(0)}ms`);
package/dist/config.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type FacetKeyConfig } from "./frontmatter.js";
1
2
  export interface SourceConfig {
2
3
  kind?: "filesystem" | "npm" | "git" | "https";
3
4
  ref: string;
@@ -38,6 +39,10 @@ export interface DirectoryLevelAgentsConfig {
38
39
  mode: "pull" | "push";
39
40
  fallbackManifest: boolean;
40
41
  }
42
+ export interface FrontmatterConfig {
43
+ searchableKeys: string[];
44
+ facetKeys: FacetKeyConfig[];
45
+ }
41
46
  export interface KbConfig {
42
47
  sources: SourceConfig[];
43
48
  roots?: Array<{
@@ -71,6 +76,7 @@ export interface KbConfig {
71
76
  frontmatter: boolean;
72
77
  };
73
78
  directoryLevelAgents: DirectoryLevelAgentsConfig;
79
+ frontmatter: FrontmatterConfig;
74
80
  doxEnforcement: boolean;
75
81
  ranking: RankingConfig;
76
82
  expand: ExpandConfig;
@@ -92,6 +98,9 @@ export interface ResolvedConfig extends KbConfig {
92
98
  origin: "project" | "global" | "defaults";
93
99
  }
94
100
  export declare const DEFAULTS: KbConfig;
101
+ /** Stable hash of the frontmatter routing config. A change forces a full reindex
102
+ * (design D6) since existing property rows/meta chunks reflect the old routing. */
103
+ export declare function frontmatterConfigHash(fm: FrontmatterConfig): string;
95
104
  /** Layer configs left→right, deep-merging the known nested object keys. */
96
105
  export declare function mergeConfig(...layers: Array<Partial<KbConfig> | null | undefined>): Partial<KbConfig>;
97
106
  /** Validate a parsed config shape; throw with a precise message on violation. */
package/dist/config.js 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 } from "./frontmatter.js";
8
10
  function expandTilde(p) {
9
11
  return p.startsWith("~/") ? join(homedir(), p.slice(2)) : p;
10
12
  }
@@ -28,6 +30,7 @@ export const DEFAULTS = {
28
30
  // no per-turn injection. Push mode stays gated behind the context-cost spike
29
31
  // (see change migrate-file-index-to-agents-tree design §5).
30
32
  directoryLevelAgents: { enabled: true, claudeMd: true, mode: "pull", fallbackManifest: true },
33
+ frontmatter: { searchableKeys: DEFAULT_SEARCHABLE_KEYS, facetKeys: DEFAULT_FACET_KEYS },
31
34
  doxEnforcement: false,
32
35
  ranking: { fieldWeights: { headingPath: 10, heading: 3, body: 1 }, proximityBoost: true, diversity: { enabled: true, lambda: 0.7 } },
33
36
  expand: { parent: true, graph: false },
@@ -37,7 +40,16 @@ export const DEFAULTS = {
37
40
  };
38
41
  // Nested object keys that need one-level field fill-in (not wholesale replace),
39
42
  // so a partial `{ranking:{proximityBoost:false}}` keeps default fieldWeights/diversity.
40
- const NESTED_KEYS = ["chunking", "dedup", "graph", "directoryLevelAgents", "ranking", "expand", "rerank", "queryExpansion"];
43
+ const NESTED_KEYS = ["chunking", "dedup", "graph", "directoryLevelAgents", "frontmatter", "ranking", "expand", "rerank", "queryExpansion"];
44
+ /** Stable hash of the frontmatter routing config. A change forces a full reindex
45
+ * (design D6) since existing property rows/meta chunks reflect the old routing. */
46
+ export function frontmatterConfigHash(fm) {
47
+ const norm = {
48
+ searchableKeys: [...fm.searchableKeys].sort(),
49
+ facetKeys: [...fm.facetKeys].map((f) => ({ key: f.key, type: f.type ?? "string" })).sort((a, b) => a.key.localeCompare(b.key)),
50
+ };
51
+ return createHash("sha256").update(JSON.stringify(norm)).digest("hex").slice(0, 16);
52
+ }
41
53
  /** Layer configs left→right, deep-merging the known nested object keys. */
42
54
  export function mergeConfig(...layers) {
43
55
  const out = {};
@@ -74,6 +86,17 @@ export function validateConfig(c, origin = "config") {
74
86
  throw err("dbPath must be a non-empty string");
75
87
  if (!/^(off|prf|synonym|agent)$/.test(merged.queryExpansion.mode))
76
88
  throw err(`queryExpansion.mode "${merged.queryExpansion.mode}" unknown`);
89
+ const fm = merged.frontmatter;
90
+ if (!fm || !Array.isArray(fm.searchableKeys) || fm.searchableKeys.some((k) => typeof k !== "string"))
91
+ throw err("frontmatter.searchableKeys must be a string array");
92
+ if (!Array.isArray(fm.facetKeys))
93
+ throw err("frontmatter.facetKeys must be an array");
94
+ for (const f of fm.facetKeys) {
95
+ if (typeof f !== "object" || f === null || typeof f.key !== "string")
96
+ throw err("each frontmatter.facetKeys entry needs a string `key`");
97
+ if (f.type != null && !/^(string|number|date)$/.test(f.type))
98
+ throw err(`frontmatter facet key "${f.key}" has unknown type "${f.type}"`);
99
+ }
77
100
  return merged;
78
101
  }
79
102
  export function projectConfigPath(cwd) {
package/dist/dox.js CHANGED
@@ -16,7 +16,7 @@ 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
- 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$/;
19
+ 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$/;
20
20
  const AGENTS_FILES = ["AGENTS.md"];
21
21
  // delta ①: dox init now maps SOURCE, not docs. Source globs, minus type decls and tests.
22
22
  const SOURCE_EXT = /\.(ts|tsx|js|jsx)$/;
@@ -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
+ }
@@ -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 }, indexOpts ?? {});
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,3 +1,4 @@
1
+ import { type FacetKeyConfig } from "./frontmatter.js";
1
2
  import type { KbStore } from "./types.js";
2
3
  export interface IndexSource {
3
4
  root: string;
@@ -11,12 +12,17 @@ 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
  }
22
28
  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
@@ -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 { chunks, wikilinks, mdLinks, frontmatter } = chunkMarkdown({ root: src.root, path: rel, text: buf.toString("utf8"), docType: docTypeOf(rel, includeSourceMd) });
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;
@@ -1,7 +1,12 @@
1
- import type { Chunk, FileState, GraphEdge, GraphNode, KbHit, KbStore, SearchOpts } from "./types.js";
1
+ import type { Chunk, FileState, Filter, GraphEdge, GraphNode, KbHit, KbStore, SearchOpts, StorePropertyRow } from "./types.js";
2
+ /** Bump when the frontmatter structural schema/behavior changes so an existing
3
+ * DB force-reindexes once on open (design D6). */
4
+ export declare const SCHEMA_VERSION = 2;
2
5
  export declare class SqliteFtsStore implements KbStore {
3
6
  private db;
4
7
  readonly dbPath: string;
8
+ private stmts;
9
+ private prep;
5
10
  constructor(dbPath: string);
6
11
  init(): void;
7
12
  begin(): void;
@@ -20,6 +25,16 @@ export declare class SqliteFtsStore implements KbStore {
20
25
  setFileState(root: string, path: string, s: FileState): void;
21
26
  listPaths(root: string): string[];
22
27
  deleteByPath(root: string, path: string): void;
28
+ deletePropertiesByPath(root: string, path: string): void;
29
+ insertProperty(r: StorePropertyRow): void;
30
+ facets(keys: string[], opts?: {
31
+ root?: string;
32
+ filters?: Filter[];
33
+ }): Record<string, Record<string, number>>;
34
+ getUserVersion(): number;
35
+ setUserVersion(v: number): void;
36
+ getMeta(k: string): string | null;
37
+ setMeta(k: string, v: string): void;
23
38
  insertChunk(c: Chunk): void;
24
39
  addNode(n: GraphNode): void;
25
40
  addEdge(e: GraphEdge): void;