@imliulian/dsh-zeromem 0.0.0-stage → 0.2.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/lib/store.mjs ADDED
@@ -0,0 +1,1248 @@
1
+ /**
2
+ * Single-file SQLite store powered by Node built-in `node:sqlite` (zero native builds).
3
+ *
4
+ * 100% schema & tokenization compatible with Python ZeroMem (`v2mem/store.py` & `v2mem/governance.py`):
5
+ * - PRAGMA application_id = 0x494D4C4C
6
+ * - meta(schema_version='1', schema_sig='42e7ab99494de6a6b4e88eb2')
7
+ * - documents, segments, facts, facts_fts (dual-track fact_tokens + evidence_tokens)
8
+ * - evicted_records side table with canonical SHA-256 tamper verification
9
+ */
10
+
11
+ import { createHash, randomBytes } from "node:crypto";
12
+ import fs from "node:fs";
13
+ import path from "node:path";
14
+ import { DatabaseSync } from "node:sqlite";
15
+ import {
16
+ ADAPTIVE_MIN_LIMIT,
17
+ ADAPTIVE_SCORE_RATIO,
18
+ factMatchesOccurredRange,
19
+ normalizeOccurredRange,
20
+ parseUntilDate,
21
+ partitionExpired,
22
+ partitionSuperseded,
23
+ resolveAsOfDate,
24
+ resolveDefaultLimit,
25
+ selectAdaptiveHits,
26
+ } from "./expiry.mjs";
27
+
28
+ // SQLite file format application_id & schema format signature (ZeroMem v1 parity)
29
+ export const APP_FORMAT_ID = 0x494d4c4c;
30
+ export const SCHEMA_SIG = "42e7ab99494de6a6b4e88eb2";
31
+ export const FORMAT_DIGEST = "c9f48efabf95bb82308f0c10";
32
+
33
+ const ASCII_WORD_RE = /[a-z0-9][a-z0-9._:/-]*/g;
34
+ const CJK_RUN_RE = /[\u4e00-\u9fff]+/g;
35
+
36
+ const SCHEMA_SQL = `
37
+ PRAGMA application_id = ${APP_FORMAT_ID};
38
+ PRAGMA journal_mode = WAL;
39
+ PRAGMA synchronous = NORMAL;
40
+
41
+ CREATE TABLE IF NOT EXISTS meta (
42
+ key TEXT PRIMARY KEY,
43
+ value TEXT NOT NULL
44
+ );
45
+
46
+ CREATE TABLE IF NOT EXISTS documents (
47
+ doc_id TEXT PRIMARY KEY,
48
+ namespace TEXT NOT NULL,
49
+ content_sha256 TEXT NOT NULL,
50
+ source_id TEXT,
51
+ mentioned_at TEXT NOT NULL,
52
+ created_at TEXT NOT NULL
53
+ );
54
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_docs_ns_sha
55
+ ON documents(namespace, content_sha256);
56
+
57
+ CREATE TABLE IF NOT EXISTS segments (
58
+ doc_id TEXT NOT NULL,
59
+ seg_id TEXT NOT NULL,
60
+ namespace TEXT NOT NULL,
61
+ path_json TEXT NOT NULL,
62
+ role TEXT,
63
+ text TEXT NOT NULL,
64
+ mentioned_at TEXT NOT NULL,
65
+ PRIMARY KEY (doc_id, seg_id)
66
+ );
67
+
68
+ CREATE TABLE IF NOT EXISTS facts (
69
+ fact_id INTEGER PRIMARY KEY AUTOINCREMENT,
70
+ doc_id TEXT NOT NULL,
71
+ namespace TEXT NOT NULL,
72
+ text TEXT NOT NULL,
73
+ type TEXT NOT NULL,
74
+ occurred_start TEXT,
75
+ occurred_end TEXT,
76
+ where_loc TEXT,
77
+ entities_json TEXT NOT NULL,
78
+ evidence_ids_json TEXT NOT NULL,
79
+ action TEXT NOT NULL,
80
+ mentioned_at TEXT NOT NULL,
81
+ created_at TEXT NOT NULL
82
+ );
83
+ CREATE INDEX IF NOT EXISTS idx_facts_ns_time
84
+ ON facts(namespace, mentioned_at DESC);
85
+
86
+ CREATE VIRTUAL TABLE IF NOT EXISTS facts_fts USING fts5(
87
+ fact_tokens,
88
+ evidence_tokens,
89
+ namespace UNINDEXED,
90
+ fact_id UNINDEXED,
91
+ tokenize = 'unicode61 remove_diacritics 2'
92
+ );
93
+
94
+ CREATE TABLE IF NOT EXISTS fact_supersessions (
95
+ new_fact_id INTEGER NOT NULL,
96
+ old_fact_id INTEGER NOT NULL,
97
+ namespace TEXT NOT NULL,
98
+ created_at TEXT NOT NULL,
99
+ PRIMARY KEY (new_fact_id, old_fact_id)
100
+ );
101
+ CREATE INDEX IF NOT EXISTS idx_fact_supersessions_old
102
+ ON fact_supersessions(old_fact_id);
103
+ `;
104
+
105
+ const EVICTED_TABLE_DDL = `
106
+ CREATE TABLE IF NOT EXISTS evicted_records (
107
+ batch_id TEXT NOT NULL,
108
+ record_kind TEXT NOT NULL CHECK(record_kind IN ('fact', 'document')),
109
+ record_id TEXT NOT NULL,
110
+ namespace TEXT NOT NULL,
111
+ payload_json TEXT NOT NULL,
112
+ content_sha256 TEXT NOT NULL,
113
+ reason TEXT NOT NULL,
114
+ evicted_at TEXT NOT NULL,
115
+ PRIMARY KEY (batch_id, record_kind, record_id)
116
+ );
117
+ CREATE INDEX IF NOT EXISTS idx_evicted_records_batch
118
+ ON evicted_records(batch_id);
119
+ `;
120
+
121
+ /**
122
+ * Deterministic canonical JSON matching Python `json.dumps(val, ensure_ascii=False, sort_keys=True, separators=(",", ":"))`.
123
+ */
124
+ export function canonicalJson(value) {
125
+ if (value === null || typeof value !== "object") {
126
+ return JSON.stringify(value);
127
+ }
128
+ if (Array.isArray(value)) {
129
+ return `[${value.map((item) => canonicalJson(item)).join(",")}]`;
130
+ }
131
+ const keys = Object.keys(value).sort();
132
+ const pairs = [];
133
+ for (const k of keys) {
134
+ if (value[k] === undefined) continue;
135
+ pairs.push(`${JSON.stringify(k)}:${canonicalJson(value[k])}`);
136
+ }
137
+ return `{${pairs.join(",")}}`;
138
+ }
139
+
140
+ export function sha256Text(text) {
141
+ return createHash("sha256").update(String(text), "utf8").digest("hex");
142
+ }
143
+
144
+ /**
145
+ * Zero-dependency bilingual tokenizer (ASCII identifiers + CJK 2-grams), exact parity with Python ZeroMem.
146
+ */
147
+ export function tokenizeForFts(text) {
148
+ const low = String(text || "").toLowerCase();
149
+ const tokens = [];
150
+
151
+ ASCII_WORD_RE.lastIndex = 0;
152
+ let m;
153
+ while ((m = ASCII_WORD_RE.exec(low)) !== null) {
154
+ const w = m[0].replace(/^[._:/-]+|[._:/-]+$/g, "");
155
+ if (w) {
156
+ tokens.push(w);
157
+ const parts = w.split(/[._:/-]+/).filter((p) => p && p !== w);
158
+ tokens.push(...parts);
159
+ }
160
+ }
161
+
162
+ CJK_RUN_RE.lastIndex = 0;
163
+ while ((m = CJK_RUN_RE.exec(low)) !== null) {
164
+ const run = m[0];
165
+ if (run.length === 1) {
166
+ tokens.push(run);
167
+ } else {
168
+ for (let i = 0; i < run.length - 1; i++) {
169
+ tokens.push(run.slice(i, i + 2));
170
+ }
171
+ if (run.length <= 4) {
172
+ tokens.push(run);
173
+ }
174
+ }
175
+ }
176
+
177
+ return tokens.join(" ");
178
+ }
179
+
180
+ function ftsQuote(tok) {
181
+ const safe = String(tok).replace(/"/g, "");
182
+ return `"${safe}"`;
183
+ }
184
+
185
+ function toPlainObject(row) {
186
+ if (!row || typeof row !== "object") return null;
187
+ return { ...row };
188
+ }
189
+
190
+ function safeJsonParse(raw, fallback) {
191
+ try {
192
+ return JSON.parse(raw);
193
+ } catch {
194
+ return fallback;
195
+ }
196
+ }
197
+
198
+ function hasTable(db, tableName) {
199
+ const row = db
200
+ .prepare("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = ?")
201
+ .get(String(tableName));
202
+ return Boolean(row);
203
+ }
204
+
205
+ function extractSupersedesIds(item) {
206
+ const ids = [];
207
+ const candidates = [];
208
+ if (item?.supersedes_fact_id !== undefined && item?.supersedes_fact_id !== null) {
209
+ candidates.push(item.supersedes_fact_id);
210
+ }
211
+ if (Array.isArray(item?.supersedes_fact_ids)) {
212
+ candidates.push(...item.supersedes_fact_ids);
213
+ }
214
+ for (const val of candidates) {
215
+ if (typeof val === "boolean") continue;
216
+ let parsed = null;
217
+ if (typeof val === "number" && Number.isInteger(val)) {
218
+ parsed = val;
219
+ } else if (typeof val === "string" && /^\d+$/.test(val.trim())) {
220
+ parsed = Number(val.trim());
221
+ }
222
+ if (parsed !== null && Number.isInteger(parsed) && parsed > 0 && !ids.includes(parsed)) {
223
+ ids.push(parsed);
224
+ }
225
+ }
226
+ return ids;
227
+ }
228
+
229
+ function appendOccurredSqlPrefilter(sql, params, { alias = "", fromDate = null, toDate = null } = {}) {
230
+ if (!fromDate && !toDate) return sql;
231
+ const colStart = alias ? `${alias}.occurred_start` : "occurred_start";
232
+ const colEnd = alias ? `${alias}.occurred_end` : "occurred_end";
233
+ let out = `${sql} AND ${colStart} IS NOT NULL AND ${colStart} != ''`;
234
+ if (toDate) {
235
+ out += ` AND substr(${colStart}, 1, 10) <= ?`;
236
+ params.push(toDate);
237
+ }
238
+ if (fromDate) {
239
+ const endExpr = `COALESCE(NULLIF(${colEnd}, ''), ${colStart})`;
240
+ out += ` AND (substr(${endExpr}, 1, 10) >= ? OR length(${endExpr}) < 10)`;
241
+ params.push(fromDate);
242
+ }
243
+ return out;
244
+ }
245
+
246
+ export class SQLiteMemoryStore {
247
+ constructor(dbPath) {
248
+ this.dbPath = path.resolve(String(dbPath));
249
+ fs.mkdirSync(path.dirname(this.dbPath), { recursive: true });
250
+ this._initDb();
251
+ }
252
+
253
+ _withDb(fn, { write = false } = {}) {
254
+ const db = new DatabaseSync(this.dbPath, { timeout: 15_000 });
255
+ try {
256
+ db.exec("PRAGMA busy_timeout = 15000;");
257
+ if (write) {
258
+ db.exec("BEGIN IMMEDIATE;");
259
+ try {
260
+ const result = fn(db);
261
+ db.exec("COMMIT;");
262
+ return result;
263
+ } catch (err) {
264
+ try {
265
+ db.exec("ROLLBACK;");
266
+ } catch {
267
+ // ignore rollback error
268
+ }
269
+ throw err;
270
+ }
271
+ }
272
+ return fn(db);
273
+ } finally {
274
+ db.close();
275
+ }
276
+ }
277
+
278
+ _initDb() {
279
+ const db = new DatabaseSync(this.dbPath, { timeout: 15_000 });
280
+ try {
281
+ db.exec("PRAGMA busy_timeout = 15000;");
282
+ db.exec(SCHEMA_SQL);
283
+ db.prepare("INSERT OR IGNORE INTO meta(key, value) VALUES (?, ?)").run("schema_version", "1");
284
+ db.prepare("INSERT OR IGNORE INTO meta(key, value) VALUES (?, ?)").run("schema_sig", SCHEMA_SIG);
285
+ db.prepare("INSERT OR IGNORE INTO meta(key, value) VALUES (?, ?)").run("format_digest", FORMAT_DIGEST);
286
+ } finally {
287
+ db.close();
288
+ }
289
+ }
290
+
291
+ hasDocument(namespace, contentSha256) {
292
+ return this._withDb((db) => {
293
+ const row = db
294
+ .prepare("SELECT doc_id FROM documents WHERE namespace = ? AND content_sha256 = ?")
295
+ .get(namespace, contentSha256);
296
+ return row ? String(row.doc_id) : null;
297
+ });
298
+ }
299
+
300
+ saveDocumentAndFacts({
301
+ docId,
302
+ namespace,
303
+ contentSha256,
304
+ sourceId = null,
305
+ mentionedAt,
306
+ createdAt,
307
+ segments,
308
+ facts,
309
+ }) {
310
+ const segTextMap = new Map();
311
+ for (const s of segments) segTextMap.set(s.id, s.text);
312
+
313
+ return this._withDb(
314
+ (db) => {
315
+ db.prepare(
316
+ `INSERT INTO documents(doc_id, namespace, content_sha256, source_id, mentioned_at, created_at)
317
+ VALUES (?, ?, ?, ?, ?, ?)`
318
+ ).run(docId, namespace, contentSha256, sourceId ?? null, mentionedAt, createdAt);
319
+
320
+ const insSeg = db.prepare(
321
+ `INSERT INTO segments(doc_id, seg_id, namespace, path_json, role, text, mentioned_at)
322
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
323
+ );
324
+ for (const s of segments) {
325
+ insSeg.run(
326
+ docId,
327
+ s.id,
328
+ namespace,
329
+ JSON.stringify(s.path || []),
330
+ s.role ?? null,
331
+ s.text,
332
+ mentionedAt
333
+ );
334
+ }
335
+
336
+ const insFact = db.prepare(
337
+ `INSERT INTO facts(
338
+ doc_id, namespace, text, type, occurred_start, occurred_end,
339
+ where_loc, entities_json, evidence_ids_json, action, mentioned_at, created_at
340
+ )
341
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
342
+ );
343
+ const insFts = db.prepare(
344
+ "INSERT INTO facts_fts(fact_tokens, evidence_tokens, namespace, fact_id) VALUES (?, ?, ?, ?)"
345
+ );
346
+ const checkOldFact = db.prepare("SELECT fact_id FROM facts WHERE fact_id = ? AND namespace = ?");
347
+ const insSup = db.prepare(
348
+ `INSERT OR IGNORE INTO fact_supersessions(new_fact_id, old_fact_id, namespace, created_at)
349
+ VALUES (?, ?, ?, ?)`
350
+ );
351
+
352
+ const savedIds = [];
353
+ for (const item of facts) {
354
+ const entities = Array.isArray(item.entities) ? item.entities : [];
355
+ const evIds = Array.isArray(item.evidence) ? item.evidence : [];
356
+ const info = insFact.run(
357
+ docId,
358
+ namespace,
359
+ item.text,
360
+ item.type || "world",
361
+ item.occurred_start ?? null,
362
+ item.occurred_end ?? null,
363
+ item.where ?? null,
364
+ JSON.stringify(entities),
365
+ JSON.stringify(evIds),
366
+ item.action || "pass",
367
+ mentionedAt,
368
+ createdAt
369
+ );
370
+ const factId = Number(info.lastInsertRowid);
371
+ savedIds.push(factId);
372
+
373
+ const factBlob = [
374
+ item.text,
375
+ entities.map((e) => String(e)).join(" "),
376
+ String(item.occurred_start || ""),
377
+ String(item.where || ""),
378
+ ].join(" ");
379
+ const boundEvidence = evIds.map((eid) => segTextMap.get(eid) || "").join(" ");
380
+ insFts.run(tokenizeForFts(factBlob), tokenizeForFts(boundEvidence), namespace, factId);
381
+
382
+ for (const oldFid of extractSupersedesIds(item)) {
383
+ if (oldFid === factId) continue;
384
+ if (checkOldFact.get(oldFid, namespace)) {
385
+ insSup.run(factId, oldFid, namespace, createdAt);
386
+ }
387
+ }
388
+ }
389
+
390
+ return savedIds;
391
+ },
392
+ { write: true }
393
+ );
394
+ }
395
+
396
+ search(
397
+ query,
398
+ {
399
+ namespace = null,
400
+ limit = null,
401
+ adaptive = true,
402
+ minLimit = ADAPTIVE_MIN_LIMIT,
403
+ scoreRatio = ADAPTIVE_SCORE_RATIO,
404
+ asOf = null,
405
+ untilEnabled = true,
406
+ occurredFrom = null,
407
+ occurredTo = null,
408
+ includeSuperseded = true,
409
+ } = {}
410
+ ) {
411
+ const { fromDate, toDate } = normalizeOccurredRange(occurredFrom, occurredTo);
412
+ const hasTimeFilter = Boolean(fromDate || toDate);
413
+ const cap = resolveDefaultLimit(limit, { adaptive });
414
+ const fetchLimit = hasTimeFilter || !includeSuperseded ? Math.max(cap * 4, 48) : Math.max(cap * 3, 24);
415
+ const qTokens = tokenizeForFts(query).split(/\s+/).filter(Boolean);
416
+
417
+ return this._withDb((db) => {
418
+ if (!qTokens.length) {
419
+ const rows = this._recentRows(db, { namespace, limit: fetchLimit, fromDate, toDate });
420
+ let hydrated = this._hydrateRanked(
421
+ db,
422
+ rows.map((r) => [r, 0.0])
423
+ );
424
+ if (hasTimeFilter) {
425
+ hydrated = hydrated.filter((r) =>
426
+ factMatchesOccurredRange(r.occurred_start, r.occurred_end, { fromDate, toDate })
427
+ );
428
+ }
429
+ if (!includeSuperseded) {
430
+ hydrated = hydrated.filter((r) => !(Array.isArray(r.superseded_by) && r.superseded_by.length > 0));
431
+ }
432
+ if (!hasTimeFilter) {
433
+ hydrated = partitionSuperseded(hydrated).items;
434
+ }
435
+ const { items } = partitionExpired(hydrated, { today: asOf, enabled: untilEnabled });
436
+ return items.slice(0, cap);
437
+ }
438
+
439
+ const uniqTokens = [];
440
+ for (const t of qTokens) {
441
+ if (!uniqTokens.includes(t)) uniqTokens.push(t);
442
+ if (uniqTokens.length >= 24) break;
443
+ }
444
+
445
+ const quoted = uniqTokens.map(ftsQuote);
446
+ const seenIds = new Set();
447
+ const ranked = [];
448
+
449
+ if (quoted.length >= 1 && quoted.length <= 6) {
450
+ const andExpr = quoted.join(" AND ");
451
+ for (const [row, score] of this._ftsQuery(db, andExpr, {
452
+ namespace,
453
+ limit: fetchLimit,
454
+ fromDate,
455
+ toDate,
456
+ })) {
457
+ const fid = Number(row.fact_id);
458
+ if (!seenIds.has(fid)) {
459
+ seenIds.add(fid);
460
+ ranked.push([row, Number((score + 1.0).toFixed(4))]);
461
+ }
462
+ }
463
+ }
464
+
465
+ if (ranked.length < fetchLimit) {
466
+ const orExpr = quoted.join(" OR ");
467
+ for (const [row, score] of this._ftsQuery(db, orExpr, {
468
+ namespace,
469
+ limit: fetchLimit * 2,
470
+ fromDate,
471
+ toDate,
472
+ })) {
473
+ const fid = Number(row.fact_id);
474
+ if (!seenIds.has(fid)) {
475
+ seenIds.add(fid);
476
+ ranked.push([row, score]);
477
+ }
478
+ if (ranked.length >= fetchLimit) break;
479
+ }
480
+ }
481
+
482
+ let hydrated = this._hydrateRanked(db, ranked.slice(0, fetchLimit));
483
+ if (hasTimeFilter) {
484
+ hydrated = hydrated.filter((r) =>
485
+ factMatchesOccurredRange(r.occurred_start, r.occurred_end, { fromDate, toDate })
486
+ );
487
+ }
488
+ if (!includeSuperseded) {
489
+ hydrated = hydrated.filter((r) => !(Array.isArray(r.superseded_by) && r.superseded_by.length > 0));
490
+ }
491
+ if (!hasTimeFilter) {
492
+ hydrated = partitionSuperseded(hydrated).items;
493
+ }
494
+ const { items } = partitionExpired(hydrated, { today: asOf, enabled: untilEnabled });
495
+ return selectAdaptiveHits(items, {
496
+ limit: cap,
497
+ minLimit,
498
+ scoreRatio,
499
+ adaptive,
500
+ });
501
+ });
502
+ }
503
+
504
+ _ftsQuery(db, matchExpr, { namespace = null, limit = 24, fromDate = null, toDate = null } = {}) {
505
+ let sql = `
506
+ SELECT f.*, bm25(facts_fts, 2.0, 1.0) AS rank_score
507
+ FROM facts_fts
508
+ JOIN facts f ON f.fact_id = facts_fts.fact_id
509
+ WHERE facts_fts MATCH ?
510
+ `;
511
+ const params = [matchExpr];
512
+ if (namespace) {
513
+ sql += " AND f.namespace = ?";
514
+ params.push(namespace);
515
+ }
516
+ sql = appendOccurredSqlPrefilter(sql, params, { alias: "f", fromDate, toDate });
517
+ sql += " ORDER BY rank_score ASC, f.mentioned_at DESC LIMIT ?";
518
+ params.push(limit);
519
+
520
+ const rows = db.prepare(sql).all(...params);
521
+ return rows.map((r) => [toPlainObject(r), Number((-Number(r.rank_score || 0)).toFixed(4))]);
522
+ }
523
+
524
+ _recentRows(db, { namespace = null, limit = 24, fromDate = null, toDate = null } = {}) {
525
+ let sql = "SELECT * FROM facts WHERE 1=1";
526
+ const params = [];
527
+ if (namespace) {
528
+ sql += " AND namespace = ?";
529
+ params.push(namespace);
530
+ }
531
+ sql = appendOccurredSqlPrefilter(sql, params, { alias: "", fromDate, toDate });
532
+ if (fromDate || toDate) {
533
+ sql += " ORDER BY occurred_start DESC, mentioned_at DESC, fact_id DESC LIMIT ?";
534
+ } else {
535
+ sql += " ORDER BY mentioned_at DESC, fact_id DESC LIMIT ?";
536
+ }
537
+ params.push(limit);
538
+ return db.prepare(sql).all(...params).map(toPlainObject);
539
+ }
540
+
541
+ _hydrateRanked(db, ranked) {
542
+ const supersedesMap = new Map();
543
+ const supersededByMap = new Map();
544
+ if (ranked.length && hasTable(db, "fact_supersessions")) {
545
+ const fids = ranked.map(([row]) => Number(row.fact_id));
546
+ const ph = fids.map(() => "?").join(",");
547
+ for (const srow of db
548
+ .prepare(
549
+ `SELECT new_fact_id, old_fact_id FROM fact_supersessions
550
+ WHERE new_fact_id IN (${ph}) ORDER BY old_fact_id ASC`
551
+ )
552
+ .all(...fids)) {
553
+ const nid = Number(srow.new_fact_id);
554
+ const oid = Number(srow.old_fact_id);
555
+ if (!supersedesMap.has(nid)) supersedesMap.set(nid, []);
556
+ supersedesMap.get(nid).push(oid);
557
+ }
558
+ for (const srow of db
559
+ .prepare(
560
+ `SELECT fs.old_fact_id, fs.new_fact_id FROM fact_supersessions fs
561
+ JOIN facts nf ON nf.fact_id = fs.new_fact_id
562
+ WHERE fs.old_fact_id IN (${ph}) ORDER BY fs.new_fact_id ASC`
563
+ )
564
+ .all(...fids)) {
565
+ const oid = Number(srow.old_fact_id);
566
+ const nid = Number(srow.new_fact_id);
567
+ if (!supersededByMap.has(oid)) supersededByMap.set(oid, []);
568
+ supersededByMap.get(oid).push(nid);
569
+ }
570
+ }
571
+
572
+ const results = [];
573
+ for (const [row, score] of ranked) {
574
+ const fid = Number(row.fact_id);
575
+ const docId = String(row.doc_id);
576
+ const evIds = safeJsonParse(row.evidence_ids_json || "[]", []);
577
+ const evTexts = [];
578
+ if (Array.isArray(evIds) && evIds.length) {
579
+ const placeholders = evIds.map(() => "?").join(",");
580
+ const segRows = db
581
+ .prepare(`SELECT seg_id, role, text FROM segments WHERE doc_id = ? AND seg_id IN (${placeholders})`)
582
+ .all(docId, ...evIds);
583
+ const segLookup = new Map();
584
+ for (const sr of segRows) segLookup.set(String(sr.seg_id), sr);
585
+ for (const sid of evIds) {
586
+ const sr = segLookup.get(String(sid));
587
+ if (sr) {
588
+ evTexts.push({
589
+ id: String(sid),
590
+ role: sr.role ?? null,
591
+ text: String(sr.text),
592
+ });
593
+ }
594
+ }
595
+ }
596
+ const item = {
597
+ fact_id: fid,
598
+ doc_id: docId,
599
+ namespace: String(row.namespace),
600
+ text: String(row.text),
601
+ type: String(row.type),
602
+ occurred_start: row.occurred_start ?? null,
603
+ occurred_end: row.occurred_end ?? null,
604
+ where: row.where_loc ?? null,
605
+ entities: safeJsonParse(row.entities_json || "[]", []),
606
+ evidence_ids: Array.isArray(evIds) ? evIds.map(String) : [],
607
+ evidence: evTexts,
608
+ action: String(row.action),
609
+ mentioned_at: String(row.mentioned_at),
610
+ score,
611
+ };
612
+ if (supersedesMap.has(fid)) {
613
+ item.supersedes_fact_id = supersedesMap.get(fid)[0];
614
+ }
615
+ if (supersededByMap.has(fid)) {
616
+ item.superseded_by = supersededByMap.get(fid);
617
+ }
618
+ results.push(item);
619
+ }
620
+ return results;
621
+ }
622
+
623
+ stats(namespace = null) {
624
+ return this._withDb((db) => {
625
+ let docs = 0;
626
+ let segs = 0;
627
+ let facts = 0;
628
+ let revised = 0;
629
+ let namespaces = [];
630
+
631
+ if (namespace) {
632
+ docs = Number(db.prepare("SELECT COUNT(*) AS c FROM documents WHERE namespace = ?").get(namespace).c);
633
+ segs = Number(db.prepare("SELECT COUNT(*) AS c FROM segments WHERE namespace = ?").get(namespace).c);
634
+ facts = Number(db.prepare("SELECT COUNT(*) AS c FROM facts WHERE namespace = ?").get(namespace).c);
635
+ revised = Number(
636
+ db.prepare("SELECT COUNT(*) AS c FROM facts WHERE namespace = ? AND action = 'revise'").get(namespace).c
637
+ );
638
+ namespaces = [namespace];
639
+ } else {
640
+ docs = Number(db.prepare("SELECT COUNT(*) AS c FROM documents").get().c);
641
+ segs = Number(db.prepare("SELECT COUNT(*) AS c FROM segments").get().c);
642
+ facts = Number(db.prepare("SELECT COUNT(*) AS c FROM facts").get().c);
643
+ revised = Number(db.prepare("SELECT COUNT(*) AS c FROM facts WHERE action = 'revise'").get().c);
644
+ namespaces = db
645
+ .prepare("SELECT DISTINCT namespace FROM documents ORDER BY namespace")
646
+ .all()
647
+ .map((r) => String(r.namespace));
648
+ }
649
+
650
+ let evictedCount = 0;
651
+ if (hasTable(db, "evicted_records")) {
652
+ evictedCount = namespace
653
+ ? Number(
654
+ db.prepare("SELECT COUNT(*) AS c FROM evicted_records WHERE namespace = ?").get(namespace).c
655
+ )
656
+ : Number(db.prepare("SELECT COUNT(*) AS c FROM evicted_records").get().c);
657
+ }
658
+
659
+ let supersessions = 0;
660
+ if (hasTable(db, "fact_supersessions")) {
661
+ supersessions = namespace
662
+ ? Number(
663
+ db
664
+ .prepare(
665
+ `SELECT COUNT(*) AS c FROM fact_supersessions fs
666
+ JOIN facts nf ON nf.fact_id = fs.new_fact_id
667
+ WHERE fs.namespace = ?`
668
+ )
669
+ .get(namespace).c
670
+ )
671
+ : Number(
672
+ db
673
+ .prepare(
674
+ `SELECT COUNT(*) AS c FROM fact_supersessions fs
675
+ JOIN facts nf ON nf.fact_id = fs.new_fact_id`
676
+ )
677
+ .get().c
678
+ );
679
+ }
680
+
681
+ let dbSizeBytes = 0;
682
+ try {
683
+ dbSizeBytes = fs.statSync(this.dbPath).size;
684
+ } catch {
685
+ dbSizeBytes = 0;
686
+ }
687
+
688
+ return {
689
+ db_path: this.dbPath,
690
+ db_size_bytes: dbSizeBytes,
691
+ documents: docs,
692
+ segments: segs,
693
+ facts,
694
+ revised_facts: revised,
695
+ supersessions,
696
+ evicted_records: evictedCount,
697
+ namespaces,
698
+ };
699
+ });
700
+ }
701
+
702
+ getDocument(docId) {
703
+ return this._withDb((db) => {
704
+ const doc = db.prepare("SELECT * FROM documents WHERE doc_id = ?").get(String(docId));
705
+ if (!doc) return null;
706
+ const segRows = db
707
+ .prepare("SELECT seg_id, path_json, role, text FROM segments WHERE doc_id = ?")
708
+ .all(String(docId))
709
+ .map(toPlainObject)
710
+ .sort((a, b) => {
711
+ const na = Number(String(a.seg_id).slice(1));
712
+ const nb = Number(String(b.seg_id).slice(1));
713
+ return (Number.isFinite(na) ? na : 0) - (Number.isFinite(nb) ? nb : 0);
714
+ });
715
+ const factCount = Number(
716
+ db.prepare("SELECT COUNT(*) AS c FROM facts WHERE doc_id = ?").get(String(docId)).c
717
+ );
718
+ return {
719
+ doc_id: String(doc.doc_id),
720
+ namespace: String(doc.namespace),
721
+ source_id: doc.source_id ?? null,
722
+ mentioned_at: String(doc.mentioned_at),
723
+ created_at: String(doc.created_at),
724
+ segments: segRows.map((r) => ({
725
+ id: String(r.seg_id),
726
+ path: safeJsonParse(r.path_json || "[]", []),
727
+ role: r.role ?? null,
728
+ text: String(r.text),
729
+ })),
730
+ fact_count: factCount,
731
+ };
732
+ });
733
+ }
734
+
735
+ deleteFact(factId) {
736
+ return this._withDb(
737
+ (db) => {
738
+ const fid = Number(factId);
739
+ const info = db.prepare("DELETE FROM facts WHERE fact_id = ?").run(fid);
740
+ db.prepare("DELETE FROM facts_fts WHERE fact_id = ?").run(fid);
741
+ if (hasTable(db, "fact_supersessions")) {
742
+ db.prepare("DELETE FROM fact_supersessions WHERE new_fact_id = ? OR old_fact_id = ?").run(fid, fid);
743
+ }
744
+ return Number(info.changes) > 0;
745
+ },
746
+ { write: true }
747
+ );
748
+ }
749
+
750
+ deleteDocument(docId) {
751
+ return this._withDb(
752
+ (db) => {
753
+ const fids = db
754
+ .prepare("SELECT fact_id FROM facts WHERE doc_id = ?")
755
+ .all(String(docId))
756
+ .map((r) => Number(r.fact_id));
757
+ const delFts = db.prepare("DELETE FROM facts_fts WHERE fact_id = ?");
758
+ const hasSup = hasTable(db, "fact_supersessions");
759
+ const delSup = hasSup
760
+ ? db.prepare("DELETE FROM fact_supersessions WHERE new_fact_id = ? OR old_fact_id = ?")
761
+ : null;
762
+ for (const fid of fids) {
763
+ delFts.run(fid);
764
+ if (delSup) delSup.run(fid, fid);
765
+ }
766
+ db.prepare("DELETE FROM facts WHERE doc_id = ?").run(String(docId));
767
+ db.prepare("DELETE FROM segments WHERE doc_id = ?").run(String(docId));
768
+ const info = db.prepare("DELETE FROM documents WHERE doc_id = ?").run(String(docId));
769
+ return Number(info.changes) > 0;
770
+ },
771
+ { write: true }
772
+ );
773
+ }
774
+
775
+ /**
776
+ * Lossless same-DB soft eviction into `evicted_records` side table (compatible with Python `v2mem/governance.py`).
777
+ */
778
+ softEvict({
779
+ factIds = [],
780
+ docIds = [],
781
+ expired = false,
782
+ namespace = null,
783
+ asOf = null,
784
+ reason = "soft-evict",
785
+ batchId = null,
786
+ force = false,
787
+ } = {}) {
788
+ const cleanReason = String(reason || "soft-evict").trim() || "soft-evict";
789
+ const stamp = new Date().toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
790
+ const effectiveBatchId =
791
+ String(batchId || "").trim() || `evict-${stamp}-${randomBytes(3).toString("hex")}`;
792
+ const evictedAt = new Date().toISOString();
793
+
794
+ return this._withDb(
795
+ (db) => {
796
+ db.exec(EVICTED_TABLE_DDL);
797
+
798
+ const targetFactSet = new Set(
799
+ (Array.isArray(factIds) ? factIds : []).map((x) => Number(x)).filter(Number.isInteger)
800
+ );
801
+ const targetDocSet = new Set(
802
+ (Array.isArray(docIds) ? docIds : []).map((x) => String(x).trim()).filter(Boolean)
803
+ );
804
+
805
+ if (expired) {
806
+ const asOfIso = resolveAsOfDate(asOf);
807
+ const rows = namespace
808
+ ? db.prepare("SELECT * FROM facts WHERE namespace = ?").all(namespace)
809
+ : db.prepare("SELECT * FROM facts").all();
810
+ for (const row of rows) {
811
+ const entities = safeJsonParse(row.entities_json || "[]", []);
812
+ const evIds = safeJsonParse(row.evidence_ids_json || "[]", []);
813
+ let boundSegs = [];
814
+ if (Array.isArray(evIds) && evIds.length) {
815
+ const ph = evIds.map(() => "?").join(",");
816
+ boundSegs = db
817
+ .prepare(`SELECT text FROM segments WHERE doc_id = ? AND seg_id IN (${ph})`)
818
+ .all(String(row.doc_id), ...evIds);
819
+ }
820
+ const until = parseUntilDate({
821
+ tags: entities,
822
+ text: String(row.text),
823
+ evidence: boundSegs,
824
+ });
825
+ if (until && until < asOfIso) {
826
+ targetFactSet.add(Number(row.fact_id));
827
+ }
828
+ }
829
+ }
830
+
831
+ const hasSup = hasTable(db, "fact_supersessions");
832
+ const docTargets = [...targetDocSet].sort();
833
+ const docFactIds = new Set();
834
+ const docPayloads = [];
835
+ for (const docId of docTargets) {
836
+ const doc = db.prepare("SELECT * FROM documents WHERE doc_id = ?").get(docId);
837
+ if (!doc) continue;
838
+ if (namespace && String(doc.namespace) !== namespace) continue;
839
+ const segs = db
840
+ .prepare("SELECT * FROM segments WHERE doc_id = ? ORDER BY seg_id")
841
+ .all(docId)
842
+ .map(toPlainObject);
843
+ const facts = db
844
+ .prepare("SELECT * FROM facts WHERE doc_id = ? ORDER BY fact_id ASC")
845
+ .all(docId)
846
+ .map(toPlainObject);
847
+ for (const f of facts) docFactIds.add(Number(f.fact_id));
848
+ const snapshot = { document: toPlainObject(doc), segments: segs, facts };
849
+ if (facts.length && hasSup) {
850
+ const fids = facts.map((f) => Number(f.fact_id));
851
+ const ph = fids.map(() => "?").join(",");
852
+ const supRows = db
853
+ .prepare(
854
+ `SELECT * FROM fact_supersessions WHERE new_fact_id IN (${ph})
855
+ ORDER BY new_fact_id ASC, old_fact_id ASC`
856
+ )
857
+ .all(...fids)
858
+ .map(toPlainObject);
859
+ if (supRows.length) snapshot.supersessions = supRows;
860
+ }
861
+ const payloadJson = canonicalJson(snapshot);
862
+ docPayloads.push({
863
+ kind: "document",
864
+ id: docId,
865
+ namespace: String(doc.namespace),
866
+ payloadJson,
867
+ sha: sha256Text(payloadJson),
868
+ factCount: facts.length,
869
+ });
870
+ }
871
+
872
+ const factTargets = [...targetFactSet].filter((fid) => !docFactIds.has(fid)).sort((a, b) => a - b);
873
+ const factPayloads = [];
874
+ for (const fid of factTargets) {
875
+ const row = db.prepare("SELECT * FROM facts WHERE fact_id = ?").get(fid);
876
+ if (!row) continue;
877
+ if (namespace && String(row.namespace) !== namespace) continue;
878
+ const factObj = toPlainObject(row);
879
+ const evIds = safeJsonParse(factObj.evidence_ids_json || "[]", []);
880
+ let segs = [];
881
+ if (Array.isArray(evIds) && evIds.length) {
882
+ const ph = evIds.map(() => "?").join(",");
883
+ segs = db
884
+ .prepare(`SELECT * FROM segments WHERE doc_id = ? AND seg_id IN (${ph}) ORDER BY seg_id`)
885
+ .all(String(factObj.doc_id), ...evIds)
886
+ .map(toPlainObject);
887
+ }
888
+ const snapshot = { fact: factObj, bound_segments: segs };
889
+ if (hasSup) {
890
+ const supRows = db
891
+ .prepare("SELECT * FROM fact_supersessions WHERE new_fact_id = ? ORDER BY old_fact_id ASC")
892
+ .all(fid)
893
+ .map(toPlainObject);
894
+ if (supRows.length) snapshot.supersessions = supRows;
895
+ }
896
+ const payloadJson = canonicalJson(snapshot);
897
+ factPayloads.push({
898
+ kind: "fact",
899
+ id: String(fid),
900
+ namespace: String(factObj.namespace),
901
+ payloadJson,
902
+ sha: sha256Text(payloadJson),
903
+ });
904
+ }
905
+
906
+ const movedFactsTotal = factPayloads.length + docPayloads.reduce((acc, d) => acc + d.factCount, 0);
907
+ if (factPayloads.length === 0 && docPayloads.length === 0) {
908
+ return {
909
+ ok: true,
910
+ batch_id: effectiveBatchId,
911
+ moved_facts: 0,
912
+ moved_documents: 0,
913
+ total_records: 0,
914
+ reason: cleanReason,
915
+ };
916
+ }
917
+
918
+ const activeFactsBefore = namespace
919
+ ? Number(db.prepare("SELECT COUNT(*) AS c FROM facts WHERE namespace = ?").get(namespace).c)
920
+ : Number(db.prepare("SELECT COUNT(*) AS c FROM facts").get().c);
921
+
922
+ if (!force && activeFactsBefore > 0 && movedFactsTotal >= activeFactsBefore && activeFactsBefore > 1) {
923
+ throw new Error(
924
+ `evict-safety-guard: refusing to empty all ${activeFactsBefore} active facts without force=true`
925
+ );
926
+ }
927
+
928
+ const insEvict = db.prepare(
929
+ `INSERT INTO evicted_records(
930
+ batch_id, record_kind, record_id, namespace, payload_json, content_sha256, reason, evicted_at
931
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`
932
+ );
933
+ const delFts = db.prepare("DELETE FROM facts_fts WHERE fact_id = ?");
934
+ const delFact = db.prepare("DELETE FROM facts WHERE fact_id = ?");
935
+ const delSupNew = hasSup ? db.prepare("DELETE FROM fact_supersessions WHERE new_fact_id = ?") : null;
936
+
937
+ for (const item of docPayloads) {
938
+ insEvict.run(
939
+ effectiveBatchId,
940
+ "document",
941
+ item.id,
942
+ item.namespace,
943
+ item.payloadJson,
944
+ item.sha,
945
+ cleanReason,
946
+ evictedAt
947
+ );
948
+ const fids = db
949
+ .prepare("SELECT fact_id FROM facts WHERE doc_id = ?")
950
+ .all(item.id)
951
+ .map((r) => Number(r.fact_id));
952
+ for (const fid of fids) {
953
+ delFts.run(fid);
954
+ if (delSupNew) delSupNew.run(fid);
955
+ }
956
+ db.prepare("DELETE FROM facts WHERE doc_id = ?").run(item.id);
957
+ db.prepare("DELETE FROM segments WHERE doc_id = ?").run(item.id);
958
+ db.prepare("DELETE FROM documents WHERE doc_id = ?").run(item.id);
959
+ }
960
+
961
+ for (const item of factPayloads) {
962
+ insEvict.run(
963
+ effectiveBatchId,
964
+ "fact",
965
+ item.id,
966
+ item.namespace,
967
+ item.payloadJson,
968
+ item.sha,
969
+ cleanReason,
970
+ evictedAt
971
+ );
972
+ delFact.run(Number(item.id));
973
+ delFts.run(Number(item.id));
974
+ if (delSupNew) delSupNew.run(Number(item.id));
975
+ }
976
+
977
+ const activeFactsAfter = namespace
978
+ ? Number(db.prepare("SELECT COUNT(*) AS c FROM facts WHERE namespace = ?").get(namespace).c)
979
+ : Number(db.prepare("SELECT COUNT(*) AS c FROM facts").get().c);
980
+
981
+ if (activeFactsAfter + movedFactsTotal !== activeFactsBefore) {
982
+ throw new Error(
983
+ `conservation-failed: before=${activeFactsBefore}, after=${activeFactsAfter}, moved=${movedFactsTotal}`
984
+ );
985
+ }
986
+
987
+ return {
988
+ ok: true,
989
+ batch_id: effectiveBatchId,
990
+ moved_facts: factPayloads.length,
991
+ moved_documents: docPayloads.length,
992
+ total_facts_affected: movedFactsTotal,
993
+ total_records: factPayloads.length + docPayloads.length,
994
+ reason: cleanReason,
995
+ evicted_at: evictedAt,
996
+ };
997
+ },
998
+ { write: true }
999
+ );
1000
+ }
1001
+
1002
+ listEvictedBatches(limit = 50) {
1003
+ return this._withDb((db) => {
1004
+ const exists = db
1005
+ .prepare("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = 'evicted_records'")
1006
+ .get();
1007
+ if (!exists) return [];
1008
+ const rows = db
1009
+ .prepare(
1010
+ `SELECT batch_id, reason, MIN(evicted_at) AS evicted_at,
1011
+ COUNT(*) AS record_count,
1012
+ GROUP_CONCAT(DISTINCT namespace) AS namespaces
1013
+ FROM evicted_records
1014
+ GROUP BY batch_id, reason
1015
+ ORDER BY evicted_at DESC
1016
+ LIMIT ?`
1017
+ )
1018
+ .all(Math.max(1, Math.min(Number(limit) || 50, 200)));
1019
+
1020
+ return rows.map((r) => {
1021
+ const sample = db
1022
+ .prepare(
1023
+ "SELECT record_kind, record_id, payload_json FROM evicted_records WHERE batch_id = ? LIMIT 3"
1024
+ )
1025
+ .all(String(r.batch_id))
1026
+ .map((item) => {
1027
+ const parsed = safeJsonParse(item.payload_json, {});
1028
+ const preview =
1029
+ item.record_kind === "fact"
1030
+ ? String(parsed?.fact?.text || "").slice(0, 120)
1031
+ : `doc ${item.record_id} (${Array.isArray(parsed?.facts) ? parsed.facts.length : 0} facts)`;
1032
+ return {
1033
+ kind: String(item.record_kind),
1034
+ id: String(item.record_id),
1035
+ preview,
1036
+ };
1037
+ });
1038
+ return {
1039
+ batch_id: String(r.batch_id),
1040
+ reason: String(r.reason),
1041
+ evicted_at: String(r.evicted_at),
1042
+ record_count: Number(r.record_count),
1043
+ namespaces: String(r.namespaces || "")
1044
+ .split(",")
1045
+ .filter(Boolean),
1046
+ samples: sample,
1047
+ };
1048
+ });
1049
+ });
1050
+ }
1051
+
1052
+ /**
1053
+ * Fail-closed SHA-256 tamper-checked atomic restore from `evicted_records`.
1054
+ */
1055
+ restoreEvicted(batchId) {
1056
+ const cleanBatch = String(batchId || "").trim();
1057
+ if (!cleanBatch) throw new Error("batch_id is required");
1058
+
1059
+ return this._withDb(
1060
+ (db) => {
1061
+ const exists = db
1062
+ .prepare("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = 'evicted_records'")
1063
+ .get();
1064
+ if (!exists) throw new Error(`batch-not-found: ${cleanBatch}`);
1065
+
1066
+ const rows = db
1067
+ .prepare("SELECT * FROM evicted_records WHERE batch_id = ? ORDER BY record_kind, record_id")
1068
+ .all(cleanBatch)
1069
+ .map(toPlainObject);
1070
+ if (!rows.length) throw new Error(`batch-not-found: ${cleanBatch}`);
1071
+
1072
+ // Phase 1: verify every single row SHA-256 BEFORE modifying anything
1073
+ const verified = [];
1074
+ for (const r of rows) {
1075
+ const parsed = JSON.parse(String(r.payload_json));
1076
+ const canonical = canonicalJson(parsed);
1077
+ const actualSha = sha256Text(canonical);
1078
+ if (actualSha !== String(r.content_sha256)) {
1079
+ throw new Error(
1080
+ `tamper-detected: batch=${cleanBatch} ${r.record_kind}:${r.record_id} expected=${r.content_sha256} actual=${actualSha}`
1081
+ );
1082
+ }
1083
+ verified.push({ row: r, snapshot: parsed });
1084
+ }
1085
+
1086
+ // Phase 2: atomic restore + rebuild dual-track facts_fts
1087
+ const insDoc = db.prepare(
1088
+ `INSERT OR IGNORE INTO documents(doc_id, namespace, content_sha256, source_id, mentioned_at, created_at)
1089
+ VALUES (?, ?, ?, ?, ?, ?)`
1090
+ );
1091
+ const insSeg = db.prepare(
1092
+ `INSERT OR IGNORE INTO segments(doc_id, seg_id, namespace, path_json, role, text, mentioned_at)
1093
+ VALUES (?, ?, ?, ?, ?, ?, ?)`
1094
+ );
1095
+ const insFact = db.prepare(
1096
+ `INSERT OR REPLACE INTO facts(
1097
+ fact_id, doc_id, namespace, text, type, occurred_start, occurred_end,
1098
+ where_loc, entities_json, evidence_ids_json, action, mentioned_at, created_at
1099
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`
1100
+ );
1101
+ const delFts = db.prepare("DELETE FROM facts_fts WHERE fact_id = ?");
1102
+ const insFts = db.prepare(
1103
+ "INSERT INTO facts_fts(fact_tokens, evidence_tokens, namespace, fact_id) VALUES (?, ?, ?, ?)"
1104
+ );
1105
+ const hasSup = hasTable(db, "fact_supersessions");
1106
+ const insSup = hasSup
1107
+ ? db.prepare(
1108
+ `INSERT OR IGNORE INTO fact_supersessions(new_fact_id, old_fact_id, namespace, created_at)
1109
+ VALUES (?, ?, ?, ?)`
1110
+ )
1111
+ : null;
1112
+
1113
+ let restoredDocs = 0;
1114
+ let restoredFacts = 0;
1115
+
1116
+ const indexFact = (f, segTextById) => {
1117
+ const entities = safeJsonParse(f.entities_json || "[]", []);
1118
+ const evIds = safeJsonParse(f.evidence_ids_json || "[]", []);
1119
+ const factBlob = [
1120
+ String(f.text || ""),
1121
+ Array.isArray(entities) ? entities.map(String).join(" ") : "",
1122
+ String(f.occurred_start || ""),
1123
+ String(f.where_loc || ""),
1124
+ ].join(" ");
1125
+ const boundEvidence = (Array.isArray(evIds) ? evIds : [])
1126
+ .map((eid) => segTextById.get(String(eid)) || "")
1127
+ .join(" ");
1128
+ delFts.run(Number(f.fact_id));
1129
+ insFts.run(tokenizeForFts(factBlob), tokenizeForFts(boundEvidence), String(f.namespace), Number(f.fact_id));
1130
+ };
1131
+
1132
+ const restoreSupersessions = (snapshot) => {
1133
+ if (!insSup || !Array.isArray(snapshot?.supersessions)) return;
1134
+ for (const sup of snapshot.supersessions) {
1135
+ insSup.run(
1136
+ Number(sup.new_fact_id),
1137
+ Number(sup.old_fact_id),
1138
+ String(sup.namespace),
1139
+ String(sup.created_at)
1140
+ );
1141
+ }
1142
+ };
1143
+
1144
+ // Restore documents first in case standalone facts refer to them
1145
+ const ordered = [...verified].sort((a, b) => {
1146
+ const ka = a.row.record_kind === "document" ? 0 : 1;
1147
+ const kb = b.row.record_kind === "document" ? 0 : 1;
1148
+ return ka !== kb ? ka - kb : String(a.row.record_id).localeCompare(String(b.row.record_id));
1149
+ });
1150
+
1151
+ for (const { row, snapshot } of ordered) {
1152
+ if (row.record_kind === "document") {
1153
+ const doc = snapshot.document;
1154
+ insDoc.run(
1155
+ doc.doc_id,
1156
+ doc.namespace,
1157
+ doc.content_sha256,
1158
+ doc.source_id ?? null,
1159
+ doc.mentioned_at,
1160
+ doc.created_at
1161
+ );
1162
+ const segMap = new Map();
1163
+ for (const s of snapshot.segments || []) {
1164
+ insSeg.run(
1165
+ s.doc_id,
1166
+ s.seg_id,
1167
+ s.namespace,
1168
+ s.path_json,
1169
+ s.role ?? null,
1170
+ s.text,
1171
+ s.mentioned_at
1172
+ );
1173
+ segMap.set(String(s.seg_id), String(s.text));
1174
+ }
1175
+ for (const f of snapshot.facts || []) {
1176
+ insFact.run(
1177
+ Number(f.fact_id),
1178
+ f.doc_id,
1179
+ f.namespace,
1180
+ f.text,
1181
+ f.type,
1182
+ f.occurred_start ?? null,
1183
+ f.occurred_end ?? null,
1184
+ f.where_loc ?? null,
1185
+ f.entities_json,
1186
+ f.evidence_ids_json,
1187
+ f.action,
1188
+ f.mentioned_at,
1189
+ f.created_at
1190
+ );
1191
+ indexFact(f, segMap);
1192
+ restoredFacts += 1;
1193
+ }
1194
+ restoreSupersessions(snapshot);
1195
+ restoredDocs += 1;
1196
+ } else {
1197
+ const f = snapshot.fact;
1198
+ const segMap = new Map();
1199
+ for (const s of snapshot.bound_segments || []) {
1200
+ insSeg.run(
1201
+ s.doc_id,
1202
+ s.seg_id,
1203
+ s.namespace,
1204
+ s.path_json,
1205
+ s.role ?? null,
1206
+ s.text,
1207
+ s.mentioned_at
1208
+ );
1209
+ segMap.set(String(s.seg_id), String(s.text));
1210
+ }
1211
+ for (const sr of db.prepare("SELECT seg_id, text FROM segments WHERE doc_id = ?").all(String(f.doc_id))) {
1212
+ if (!segMap.has(String(sr.seg_id))) segMap.set(String(sr.seg_id), String(sr.text));
1213
+ }
1214
+ insFact.run(
1215
+ Number(f.fact_id),
1216
+ f.doc_id,
1217
+ f.namespace,
1218
+ f.text,
1219
+ f.type,
1220
+ f.occurred_start ?? null,
1221
+ f.occurred_end ?? null,
1222
+ f.where_loc ?? null,
1223
+ f.entities_json,
1224
+ f.evidence_ids_json,
1225
+ f.action,
1226
+ f.mentioned_at,
1227
+ f.created_at
1228
+ );
1229
+ indexFact(f, segMap);
1230
+ restoreSupersessions(snapshot);
1231
+ restoredFacts += 1;
1232
+ }
1233
+ }
1234
+
1235
+ db.prepare("DELETE FROM evicted_records WHERE batch_id = ?").run(cleanBatch);
1236
+
1237
+ return {
1238
+ ok: true,
1239
+ batch_id: cleanBatch,
1240
+ restored_documents: restoredDocs,
1241
+ restored_facts: restoredFacts,
1242
+ verified_rows: verified.length,
1243
+ };
1244
+ },
1245
+ { write: true }
1246
+ );
1247
+ }
1248
+ }