@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 +3 -1
- package/dist/chunker.js +3 -19
- package/dist/cli.js +13 -4
- package/dist/config.d.ts +9 -0
- package/dist/config.js +24 -1
- package/dist/dox.js +1 -1
- 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 +6 -0
- package/dist/indexer.js +24 -1
- package/dist/sqlite-store.d.ts +16 -1
- package/dist/sqlite-store.js +106 -2
- package/dist/types.d.ts +31 -0
- package/package.json +1 -1
- package/src/AGENTS.md +1 -1
- package/src/chunker.ts +5 -18
- package/src/cli.ts +13 -4
- package/src/config.ts +26 -1
- package/src/dox.ts +1 -1
- package/src/frontmatter.ts +221 -0
- package/src/index-run.ts +20 -3
- package/src/index.ts +7 -2
- package/src/indexer.ts +23 -1
- package/src/sqlite-store.ts +101 -3
- package/src/types.ts +31 -0
package/src/index-run.ts
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 { type IndexOptions, type IndexStats, indexSource } from "./indexer.js";
|
|
16
|
-
import { SqliteFtsStore } from "./sqlite-store.js";
|
|
16
|
+
import { SCHEMA_VERSION, SqliteFtsStore } from "./sqlite-store.js";
|
|
17
17
|
|
|
18
18
|
type StoreCounts = ReturnType<SqliteFtsStore["counts"]>;
|
|
19
19
|
|
|
@@ -27,6 +27,9 @@ export interface RunIndexAtomicOpts {
|
|
|
27
27
|
indexOpts?: IndexOptions;
|
|
28
28
|
/** Sources came from an explicit `--source` arg; a missing one is a user typo. */
|
|
29
29
|
explicit?: boolean;
|
|
30
|
+
/** When set, participates in the schema-version reindex gate (design D6): a
|
|
31
|
+
* changed facet-config hash forces a one-time full reindex. */
|
|
32
|
+
facetConfigHash?: string;
|
|
30
33
|
}
|
|
31
34
|
|
|
32
35
|
/** True if `pid` names a live process (existence probe via signal 0). EPERM =
|
|
@@ -92,19 +95,33 @@ export async function runIndexAtomic(opts: RunIndexAtomicOpts): Promise<IndexSta
|
|
|
92
95
|
|
|
93
96
|
const store = new SqliteFtsStore(target);
|
|
94
97
|
store.init();
|
|
98
|
+
// Schema-version / facet-config gate: a stale schema version or a changed
|
|
99
|
+
// facet-config hash forces a one-time full reindex so new structures populate.
|
|
100
|
+
let effOpts: IndexOptions = indexOpts ?? {};
|
|
101
|
+
if (preexisting) {
|
|
102
|
+
const ver = store.getUserVersion?.() ?? 0;
|
|
103
|
+
const storedHash = store.getMeta?.("facetConfigHash") ?? null;
|
|
104
|
+
if (ver < SCHEMA_VERSION || (opts.facetConfigHash != null && storedHash !== opts.facetConfigHash)) {
|
|
105
|
+
effOpts = { ...effOpts, force: true };
|
|
106
|
+
}
|
|
107
|
+
}
|
|
95
108
|
let ok = false;
|
|
96
109
|
try {
|
|
97
|
-
const total: IndexStats = { scanned: 0, changed: 0, deleted: 0, chunks: 0 };
|
|
110
|
+
const total: IndexStats = { scanned: 0, changed: 0, deleted: 0, chunks: 0, parseFailures: 0 };
|
|
98
111
|
for (const s of sources) {
|
|
99
|
-
const st = await indexSource(store, { root: s.id, dir: s.dir },
|
|
112
|
+
const st = await indexSource(store, { root: s.id, dir: s.dir }, effOpts);
|
|
100
113
|
total.scanned += st.scanned;
|
|
101
114
|
total.changed += st.changed;
|
|
102
115
|
total.deleted += st.deleted;
|
|
103
116
|
total.chunks += st.chunks;
|
|
117
|
+
total.parseFailures = (total.parseFailures ?? 0) + (st.parseFailures ?? 0);
|
|
104
118
|
}
|
|
105
119
|
// Read counts from the still-open store so callers never need a second
|
|
106
120
|
// openStore() connection just to report them (keeps `index` off openStore).
|
|
107
121
|
const counts = store.counts();
|
|
122
|
+
// Stamp the schema version + facet-config hash so the gate is satisfied next open.
|
|
123
|
+
store.setUserVersion?.(SCHEMA_VERSION);
|
|
124
|
+
if (opts.facetConfigHash != null) store.setMeta?.("facetConfigHash", opts.facetConfigHash);
|
|
108
125
|
if (preexisting) store.close();
|
|
109
126
|
else store.finalizeRename(dbPath);
|
|
110
127
|
ok = true;
|
package/src/index.ts
CHANGED
|
@@ -8,7 +8,11 @@ export type {
|
|
|
8
8
|
KbHit,
|
|
9
9
|
KbStore,
|
|
10
10
|
SearchOpts,
|
|
11
|
+
Filter,
|
|
12
|
+
StorePropertyRow,
|
|
11
13
|
} from "./types.js";
|
|
14
|
+
export { parseFrontmatter, buildMeta, buildProperties, strictNumber, strictDate, DEFAULT_SEARCHABLE_KEYS, DEFAULT_FACET_KEYS } from "./frontmatter.js";
|
|
15
|
+
export type { FmValue, FacetKeyConfig, ParsedFrontmatter, PropertyRow } from "./frontmatter.js";
|
|
12
16
|
export { renderHits } from "./render.js";
|
|
13
17
|
export type { RenderOpts } from "./render.js";
|
|
14
18
|
export { chunkMarkdown } from "./chunker.js";
|
|
@@ -18,8 +22,9 @@ export { indexSource } from "./indexer.js";
|
|
|
18
22
|
export type { IndexSource, IndexOptions, IndexStats } from "./indexer.js";
|
|
19
23
|
export { kbInit } from "./init.js";
|
|
20
24
|
export type { InitOptions, InitResult } from "./init.js";
|
|
21
|
-
export { loadConfig, validateConfig, DEFAULTS } from "./config.js";
|
|
22
|
-
export type { KbConfig, SourceConfig, RankingConfig, ResolvedConfig } from "./config.js";
|
|
25
|
+
export { loadConfig, validateConfig, DEFAULTS, frontmatterConfigHash } from "./config.js";
|
|
26
|
+
export type { KbConfig, SourceConfig, RankingConfig, ResolvedConfig, FrontmatterConfig } from "./config.js";
|
|
27
|
+
export { SCHEMA_VERSION } from "./sqlite-store.js";
|
|
23
28
|
export { resolveAll, classifyRef, sourceIdentity, resolverFor } from "./sources.js";
|
|
24
29
|
export type { KbSourceKind, ResolvedSource, ResolveCtx, SourceResolver } from "./sources.js";
|
|
25
30
|
export { isTrusted, recordTrust, canonicalSource, sourceHash } from "./trust.js";
|
package/src/indexer.ts
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, type FacetKeyConfig, buildMeta, buildProperties } from "./frontmatter.js";
|
|
7
8
|
import type { DocType, KbStore } from "./types.js";
|
|
8
9
|
|
|
9
10
|
export interface IndexSource {
|
|
@@ -18,12 +19,14 @@ export interface IndexOptions {
|
|
|
18
19
|
include?: string[]; // glob patterns to include
|
|
19
20
|
exclude?: string[]; // glob patterns to exclude
|
|
20
21
|
extensions?: string[]; // e.g. [".md"]
|
|
22
|
+
frontmatter?: { searchableKeys: string[]; facetKeys: FacetKeyConfig[] }; // structural indexing routing
|
|
21
23
|
}
|
|
22
24
|
export interface IndexStats {
|
|
23
25
|
scanned: number;
|
|
24
26
|
changed: number;
|
|
25
27
|
deleted: number;
|
|
26
28
|
chunks: number;
|
|
29
|
+
parseFailures?: number; // files whose frontmatter block was present but did not parse
|
|
27
30
|
missing?: boolean; // source dir did not exist → skipped (degrade, not abort)
|
|
28
31
|
}
|
|
29
32
|
|
|
@@ -128,7 +131,8 @@ export async function indexSource(store: KbStore, src: IndexSource, opts: IndexO
|
|
|
128
131
|
}
|
|
129
132
|
// changed → replace
|
|
130
133
|
store.deleteByPath(src.root, rel);
|
|
131
|
-
const
|
|
134
|
+
const dt = docTypeOf(rel, includeSourceMd);
|
|
135
|
+
const { chunks, wikilinks, mdLinks, frontmatter, parseFailed } = chunkMarkdown({ root: src.root, path: rel, text: buf.toString("utf8"), docType: dt });
|
|
132
136
|
// file node
|
|
133
137
|
store.addNode({ type: "file", name: rel, path: rel });
|
|
134
138
|
for (const c of chunks) {
|
|
@@ -154,6 +158,24 @@ export async function indexSource(store: KbStore, src: IndexSource, opts: IndexO
|
|
|
154
158
|
store.addNode({ type: "tag", name: `tag:${tag}`, path: null });
|
|
155
159
|
store.addEdge({ src: rel, dst: `tag:${tag}`, rel: "has_tag" });
|
|
156
160
|
}
|
|
161
|
+
// frontmatter structural indexing: synthetic meta chunk + property rows
|
|
162
|
+
if (frontmatter) {
|
|
163
|
+
const fmCfg = opts.frontmatter ?? { searchableKeys: DEFAULT_SEARCHABLE_KEYS, facetKeys: DEFAULT_FACET_KEYS };
|
|
164
|
+
const { title, body: metaBody } = buildMeta(frontmatter, fmCfg.searchableKeys);
|
|
165
|
+
const metaText = [title ?? "", metaBody].join("\n").trim();
|
|
166
|
+
if (metaText) {
|
|
167
|
+
// Searchable meta needs only insertChunk (required); it must NOT be
|
|
168
|
+
// gated on the optional insertProperty, or a chunk-capable store would
|
|
169
|
+
// silently lose title/description search.
|
|
170
|
+
const heading = title ?? (rel.split("/").pop() ?? rel).replace(/\.(md|mdx|markdown)$/i, "");
|
|
171
|
+
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) });
|
|
172
|
+
stats.chunks++;
|
|
173
|
+
}
|
|
174
|
+
if (store.insertProperty) for (const row of buildProperties(frontmatter, fmCfg.facetKeys)) store.insertProperty({ root: src.root, path: rel, ...row });
|
|
175
|
+
}
|
|
176
|
+
// Mirror docType for EVERY file (facetable regardless of frontmatter presence).
|
|
177
|
+
store.insertProperty?.({ root: src.root, path: rel, key: "docType", value: dt, valueNum: null, valueDate: null, valueRaw: dt });
|
|
178
|
+
if (parseFailed) stats.parseFailures = (stats.parseFailures ?? 0) + 1;
|
|
157
179
|
store.setFileState(src.root, rel, { mtimeMs: st.mtimeMs, sha256: hash }); // persist for incremental
|
|
158
180
|
stats.changed++;
|
|
159
181
|
stats.chunks += chunks.length;
|
package/src/sqlite-store.ts
CHANGED
|
@@ -5,7 +5,11 @@
|
|
|
5
5
|
import { mkdirSync, renameSync, unlinkSync } from "node:fs";
|
|
6
6
|
import { dirname } from "node:path";
|
|
7
7
|
import { DatabaseSync } from "node:sqlite";
|
|
8
|
-
import type { Chunk, FileState, GraphEdge, GraphNode, KbHit, KbStore, SearchOpts } from "./types.js";
|
|
8
|
+
import type { Chunk, FileState, Filter, GraphEdge, GraphNode, KbHit, KbStore, SearchOpts, StorePropertyRow } from "./types.js";
|
|
9
|
+
|
|
10
|
+
/** Bump when the frontmatter structural schema/behavior changes so an existing
|
|
11
|
+
* DB force-reindexes once on open (design D6). */
|
|
12
|
+
export const SCHEMA_VERSION = 2;
|
|
9
13
|
|
|
10
14
|
const DDL = `
|
|
11
15
|
CREATE VIRTUAL TABLE IF NOT EXISTS chunks USING fts5(
|
|
@@ -28,8 +32,49 @@ CREATE TABLE IF NOT EXISTS edges (
|
|
|
28
32
|
);
|
|
29
33
|
CREATE INDEX IF NOT EXISTS idx_edges_src ON edges(src);
|
|
30
34
|
CREATE INDEX IF NOT EXISTS idx_edges_dst ON edges(dst);
|
|
35
|
+
CREATE TABLE IF NOT EXISTS properties (
|
|
36
|
+
root TEXT, path TEXT, key TEXT,
|
|
37
|
+
value TEXT, value_num REAL, value_date TEXT, value_raw TEXT
|
|
38
|
+
);
|
|
39
|
+
-- The unique index doubles as the (root,path) lookup for delete-by-path (its
|
|
40
|
+
-- leading columns), so no separate idx_props_path is needed — one fewer index to
|
|
41
|
+
-- maintain on the hot per-file insert path.
|
|
42
|
+
CREATE UNIQUE INDEX IF NOT EXISTS idx_props_uniq ON properties(root, path, key, value);
|
|
43
|
+
CREATE INDEX IF NOT EXISTS idx_props_kv ON properties(key, value);
|
|
44
|
+
CREATE TABLE IF NOT EXISTS kb_meta (k TEXT PRIMARY KEY, v TEXT);
|
|
31
45
|
`;
|
|
32
46
|
|
|
47
|
+
/** Build correlated EXISTS predicates for facet filters. All values are bound as
|
|
48
|
+
* parameters (never interpolated) — SQL-injection guard (design D7). */
|
|
49
|
+
function buildFilterClauses(filters: Filter[] | undefined, outer: string): { clauses: string[]; args: unknown[] } {
|
|
50
|
+
const clauses: string[] = [];
|
|
51
|
+
const args: unknown[] = [];
|
|
52
|
+
const norm = (v: unknown) => String(v).toLowerCase().trim();
|
|
53
|
+
// Match column for equality by declared type: number→value_num, date→value_date,
|
|
54
|
+
// else the normalized string value (the parser may pre-coerce numeric scalars,
|
|
55
|
+
// so eq on a typed key must not compare the lossy string column).
|
|
56
|
+
const eqCol = (t?: string) => (t === "number" ? "value_num" : t === "date" ? "value_date" : "value");
|
|
57
|
+
const eqVal = (t: string | undefined, v: unknown) => (t === "number" ? Number(v) : t === "date" ? String(v) : norm(v));
|
|
58
|
+
for (const f of filters ?? []) {
|
|
59
|
+
if (f.op === "eq" && f.value != null) {
|
|
60
|
+
const col = eqCol(f.type);
|
|
61
|
+
clauses.push(`EXISTS (SELECT 1 FROM properties p WHERE p.root=${outer}.root AND p.path=${outer}.path AND p.key=? AND p.${col}=?)`);
|
|
62
|
+
args.push(f.key, eqVal(f.type, f.value));
|
|
63
|
+
} else if (f.op === "in" && f.values?.length) {
|
|
64
|
+
const col = eqCol(f.type);
|
|
65
|
+
const ph = f.values.map(() => "?").join(",");
|
|
66
|
+
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}))`);
|
|
67
|
+
args.push(f.key, ...f.values.map((v) => eqVal(f.type, v)));
|
|
68
|
+
} else if ((f.op === "gte" || f.op === "lte") && f.value != null) {
|
|
69
|
+
const col = f.type === "number" ? "value_num" : f.type === "date" ? "value_date" : "value";
|
|
70
|
+
const cmp = f.op === "gte" ? ">=" : "<=";
|
|
71
|
+
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} ?)`);
|
|
72
|
+
args.push(f.key, f.type === "number" ? Number(f.value) : f.type === "date" ? String(f.value) : norm(f.value));
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return { clauses, args };
|
|
76
|
+
}
|
|
77
|
+
|
|
33
78
|
// FTS5 query builder: OR the alphanumeric terms (recall + BM25 ranks).
|
|
34
79
|
function toMatch(q: string): string {
|
|
35
80
|
const terms = tokenize(q);
|
|
@@ -40,6 +85,14 @@ function toMatch(q: string): string {
|
|
|
40
85
|
export class SqliteFtsStore implements KbStore {
|
|
41
86
|
private db: DatabaseSync;
|
|
42
87
|
readonly dbPath: string;
|
|
88
|
+
// Prepared-statement cache: re-preparing per row on a hot insert path (chunks
|
|
89
|
+
// + properties, many per file) is a measurable reindex cost. Cache by SQL.
|
|
90
|
+
private stmts = new Map<string, ReturnType<DatabaseSync["prepare"]>>();
|
|
91
|
+
private prep(sql: string) {
|
|
92
|
+
let s = this.stmts.get(sql);
|
|
93
|
+
if (!s) { s = this.db.prepare(sql); this.stmts.set(sql, s); }
|
|
94
|
+
return s;
|
|
95
|
+
}
|
|
43
96
|
constructor(dbPath: string) {
|
|
44
97
|
this.dbPath = dbPath;
|
|
45
98
|
if (dbPath !== ":memory:") mkdirSync(dirname(dbPath), { recursive: true });
|
|
@@ -107,17 +160,58 @@ export class SqliteFtsStore implements KbStore {
|
|
|
107
160
|
return (this.db.prepare("SELECT path FROM files WHERE root=?").all(root) as any[]).map((r) => r.path);
|
|
108
161
|
}
|
|
109
162
|
deleteByPath(root: string, path: string) {
|
|
163
|
+
// chunks includes the file's synthetic `:meta` chunk (same path) — removed here.
|
|
110
164
|
this.db.prepare("DELETE FROM chunks WHERE root=? AND path=?").run(root, path);
|
|
111
165
|
// outbound edges originate from this file's nodes; prune nodes owned by path then dangling edges
|
|
112
166
|
const owned = this.db.prepare("SELECT id FROM nodes WHERE path=?").all(path) as any[];
|
|
113
167
|
for (const n of owned) this.db.prepare("DELETE FROM edges WHERE src=? OR dst=?").run(n.id, n.id);
|
|
114
168
|
this.db.prepare("DELETE FROM nodes WHERE path=?").run(path);
|
|
169
|
+
this.db.prepare("DELETE FROM properties WHERE root=? AND path=?").run(root, path);
|
|
115
170
|
this.db.prepare("DELETE FROM files WHERE root=? AND path=?").run(root, path);
|
|
116
171
|
}
|
|
117
172
|
|
|
173
|
+
deletePropertiesByPath(root: string, path: string) {
|
|
174
|
+
this.db.prepare("DELETE FROM properties WHERE root=? AND path=?").run(root, path);
|
|
175
|
+
}
|
|
176
|
+
insertProperty(r: StorePropertyRow) {
|
|
177
|
+
// INSERT OR IGNORE + UNIQUE(root,path,key,value) de-dups within-file duplicates.
|
|
178
|
+
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);
|
|
179
|
+
}
|
|
180
|
+
facets(keys: string[], opts: { root?: string; filters?: Filter[] } = {}): Record<string, Record<string, number>> {
|
|
181
|
+
const out: Record<string, Record<string, number>> = {};
|
|
182
|
+
if (!keys.length) return out;
|
|
183
|
+
const where: string[] = [`key IN (${keys.map(() => "?").join(",")})`];
|
|
184
|
+
const args: unknown[] = [...keys];
|
|
185
|
+
if (opts.root) { where.push("o.root = ?"); args.push(opts.root); }
|
|
186
|
+
const f = buildFilterClauses(opts.filters, "o");
|
|
187
|
+
where.push(...f.clauses);
|
|
188
|
+
args.push(...f.args);
|
|
189
|
+
// Distinct FILES, not rows: two sources with the same relative path are two
|
|
190
|
+
// files, so count distinct (root,path) — within-file duplicates already
|
|
191
|
+
// collapse via the UNIQUE(root,path,key,value) index.
|
|
192
|
+
const sql = `SELECT key, value, COUNT(DISTINCT root || char(31) || path) n FROM properties o WHERE ${where.join(" AND ")} GROUP BY key, value`;
|
|
193
|
+
for (const r of this.db.prepare(sql).all(...(args as any[])) as any[]) {
|
|
194
|
+
(out[r.key] ??= {})[r.value] = r.n as number;
|
|
195
|
+
}
|
|
196
|
+
return out;
|
|
197
|
+
}
|
|
198
|
+
getUserVersion(): number {
|
|
199
|
+
return (this.db.prepare("PRAGMA user_version").get() as any).user_version as number;
|
|
200
|
+
}
|
|
201
|
+
setUserVersion(v: number) {
|
|
202
|
+
// PRAGMA does not accept a bound parameter; v is an internal integer constant.
|
|
203
|
+
this.db.exec(`PRAGMA user_version = ${Math.trunc(v)}`);
|
|
204
|
+
}
|
|
205
|
+
getMeta(k: string): string | null {
|
|
206
|
+
const r = this.db.prepare("SELECT v FROM kb_meta WHERE k=?").get(k) as any;
|
|
207
|
+
return r ? (r.v as string) : null;
|
|
208
|
+
}
|
|
209
|
+
setMeta(k: string, v: string) {
|
|
210
|
+
this.db.prepare("INSERT INTO kb_meta(k,v) VALUES(?,?) ON CONFLICT(k) DO UPDATE SET v=excluded.v").run(k, v);
|
|
211
|
+
}
|
|
212
|
+
|
|
118
213
|
insertChunk(c: Chunk) {
|
|
119
|
-
this.
|
|
120
|
-
.prepare("INSERT INTO chunks(root,path,chunk_id,doc_type,parent_chunk_id,level,body_hash,heading_path,heading,body) VALUES(?,?,?,?,?,?,?,?,?,?)")
|
|
214
|
+
this.prep("INSERT INTO chunks(root,path,chunk_id,doc_type,parent_chunk_id,level,body_hash,heading_path,heading,body) VALUES(?,?,?,?,?,?,?,?,?,?)")
|
|
121
215
|
.run(c.root, c.path, c.chunkId, c.docType, c.parentChunkId, c.level, c.bodyHash, c.headingPath, c.heading, c.body);
|
|
122
216
|
}
|
|
123
217
|
addNode(n: GraphNode) {
|
|
@@ -153,6 +247,10 @@ export class SqliteFtsStore implements KbStore {
|
|
|
153
247
|
const args: any[] = [m];
|
|
154
248
|
if (opts.root) { where.push("root = ?"); args.push(opts.root); }
|
|
155
249
|
if (opts.docType) { where.push("doc_type = ?"); args.push(opts.docType); }
|
|
250
|
+
// structured facet filters (opt-in; absent → no clause → identical query)
|
|
251
|
+
const ff = buildFilterClauses(opts.filters, "chunks");
|
|
252
|
+
where.push(...ff.clauses);
|
|
253
|
+
args.push(...ff.args);
|
|
156
254
|
const sql = `SELECT root, path, chunk_id chunkId, doc_type docType, body_hash bodyHash,
|
|
157
255
|
parent_chunk_id parentChunkId, heading_path headingPath, heading, body,
|
|
158
256
|
bm25(chunks, 0,0,0,0,0,0,0, ${w.headingPath}, ${w.heading}, ${w.body}) score,
|
package/src/types.ts
CHANGED
|
@@ -46,6 +46,28 @@ export interface KbHit {
|
|
|
46
46
|
/** A pluggable reranker: rescoring BM25 top-k. Default = none (no-op). */
|
|
47
47
|
export type Reranker = (query: string, candidates: KbHit[]) => Promise<KbHit[]> | KbHit[];
|
|
48
48
|
|
|
49
|
+
/** Structured frontmatter facet filter (add-kb-frontmatter-structural-indexing).
|
|
50
|
+
* Values are always parameter-bound. `type` selects the range column for
|
|
51
|
+
* gte/lte: number → value_num, date → value_date, string/omitted → value. */
|
|
52
|
+
export interface Filter {
|
|
53
|
+
key: string;
|
|
54
|
+
op: "eq" | "in" | "gte" | "lte";
|
|
55
|
+
value?: string | number;
|
|
56
|
+
values?: Array<string | number>;
|
|
57
|
+
type?: "string" | "number" | "date";
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** A property row persisted for a file's facet frontmatter. */
|
|
61
|
+
export interface StorePropertyRow {
|
|
62
|
+
root: string;
|
|
63
|
+
path: string;
|
|
64
|
+
key: string;
|
|
65
|
+
value: string; // normalized (lowercased/trimmed)
|
|
66
|
+
valueNum: number | null;
|
|
67
|
+
valueDate: string | null;
|
|
68
|
+
valueRaw: string;
|
|
69
|
+
}
|
|
70
|
+
|
|
49
71
|
export interface SearchOpts {
|
|
50
72
|
limit?: number;
|
|
51
73
|
root?: string;
|
|
@@ -61,6 +83,7 @@ export interface SearchOpts {
|
|
|
61
83
|
reranker?: Reranker; // injected reranker; if absent, --rerank is a clean no-op
|
|
62
84
|
queryExpansion?: "off" | "prf" | "synonym" | "agent";
|
|
63
85
|
synonyms?: Record<string, string[]>; // curated glossary for synonym expansion
|
|
86
|
+
filters?: Filter[]; // structured frontmatter facet filters (opt-in; no-op when absent)
|
|
64
87
|
}
|
|
65
88
|
|
|
66
89
|
export interface FileState {
|
|
@@ -87,6 +110,14 @@ export interface KbStore {
|
|
|
87
110
|
insertChunk(c: Chunk): void;
|
|
88
111
|
addNode(n: GraphNode): void;
|
|
89
112
|
addEdge(e: GraphEdge): void;
|
|
113
|
+
// frontmatter structural indexing (optional — additive backend capability)
|
|
114
|
+
insertProperty?(row: StorePropertyRow): void;
|
|
115
|
+
deletePropertiesByPath?(root: string, path: string): void;
|
|
116
|
+
facets?(keys: string[], opts?: { root?: string; filters?: Filter[] }): Record<string, Record<string, number>>;
|
|
117
|
+
getUserVersion?(): number;
|
|
118
|
+
setUserVersion?(v: number): void;
|
|
119
|
+
getMeta?(k: string): string | null;
|
|
120
|
+
setMeta?(k: string, v: string): void;
|
|
90
121
|
|
|
91
122
|
// query
|
|
92
123
|
search(query: string, opts?: SearchOpts): KbHit[];
|