@imliulian/dsh-zeromem 0.1.0 → 0.2.1
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/CHANGELOG.md +24 -0
- package/NOTICE +17 -0
- package/README.md +44 -13
- package/README.zh.md +44 -13
- package/assets/panel.js +110 -4
- package/bin/dsh-zeromem.mjs +187 -0
- package/lib/contracts.mjs +253 -2
- package/lib/expiry.mjs +105 -1
- package/lib/hooks.mjs +29 -6
- package/lib/index.mjs +4 -1
- package/lib/llm.mjs +6 -2
- package/lib/memory.mjs +263 -5
- package/lib/portability.mjs +819 -0
- package/lib/store.mjs +268 -28
- package/lib/tools.mjs +101 -7
- package/lib/web.mjs +86 -8
- package/package.json +8 -4
package/lib/store.mjs
CHANGED
|
@@ -15,8 +15,11 @@ import { DatabaseSync } from "node:sqlite";
|
|
|
15
15
|
import {
|
|
16
16
|
ADAPTIVE_MIN_LIMIT,
|
|
17
17
|
ADAPTIVE_SCORE_RATIO,
|
|
18
|
+
factMatchesOccurredRange,
|
|
19
|
+
normalizeOccurredRange,
|
|
18
20
|
parseUntilDate,
|
|
19
21
|
partitionExpired,
|
|
22
|
+
partitionSuperseded,
|
|
20
23
|
resolveAsOfDate,
|
|
21
24
|
resolveDefaultLimit,
|
|
22
25
|
selectAdaptiveHits,
|
|
@@ -87,6 +90,16 @@ CREATE VIRTUAL TABLE IF NOT EXISTS facts_fts USING fts5(
|
|
|
87
90
|
fact_id UNINDEXED,
|
|
88
91
|
tokenize = 'unicode61 remove_diacritics 2'
|
|
89
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);
|
|
90
103
|
`;
|
|
91
104
|
|
|
92
105
|
const EVICTED_TABLE_DDL = `
|
|
@@ -182,6 +195,54 @@ function safeJsonParse(raw, fallback) {
|
|
|
182
195
|
}
|
|
183
196
|
}
|
|
184
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
|
+
|
|
185
246
|
export class SQLiteMemoryStore {
|
|
186
247
|
constructor(dbPath) {
|
|
187
248
|
this.dbPath = path.resolve(String(dbPath));
|
|
@@ -282,6 +343,11 @@ export class SQLiteMemoryStore {
|
|
|
282
343
|
const insFts = db.prepare(
|
|
283
344
|
"INSERT INTO facts_fts(fact_tokens, evidence_tokens, namespace, fact_id) VALUES (?, ?, ?, ?)"
|
|
284
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
|
+
);
|
|
285
351
|
|
|
286
352
|
const savedIds = [];
|
|
287
353
|
for (const item of facts) {
|
|
@@ -312,6 +378,13 @@ export class SQLiteMemoryStore {
|
|
|
312
378
|
].join(" ");
|
|
313
379
|
const boundEvidence = evIds.map((eid) => segTextMap.get(eid) || "").join(" ");
|
|
314
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
|
+
}
|
|
315
388
|
}
|
|
316
389
|
|
|
317
390
|
return savedIds;
|
|
@@ -330,19 +403,35 @@ export class SQLiteMemoryStore {
|
|
|
330
403
|
scoreRatio = ADAPTIVE_SCORE_RATIO,
|
|
331
404
|
asOf = null,
|
|
332
405
|
untilEnabled = true,
|
|
406
|
+
occurredFrom = null,
|
|
407
|
+
occurredTo = null,
|
|
408
|
+
includeSuperseded = true,
|
|
333
409
|
} = {}
|
|
334
410
|
) {
|
|
411
|
+
const { fromDate, toDate } = normalizeOccurredRange(occurredFrom, occurredTo);
|
|
412
|
+
const hasTimeFilter = Boolean(fromDate || toDate);
|
|
335
413
|
const cap = resolveDefaultLimit(limit, { adaptive });
|
|
336
|
-
const fetchLimit = Math.max(cap * 3, 24);
|
|
414
|
+
const fetchLimit = hasTimeFilter || !includeSuperseded ? Math.max(cap * 4, 48) : Math.max(cap * 3, 24);
|
|
337
415
|
const qTokens = tokenizeForFts(query).split(/\s+/).filter(Boolean);
|
|
338
416
|
|
|
339
417
|
return this._withDb((db) => {
|
|
340
418
|
if (!qTokens.length) {
|
|
341
|
-
const rows = this._recentRows(db, { namespace, limit: fetchLimit });
|
|
342
|
-
|
|
419
|
+
const rows = this._recentRows(db, { namespace, limit: fetchLimit, fromDate, toDate });
|
|
420
|
+
let hydrated = this._hydrateRanked(
|
|
343
421
|
db,
|
|
344
422
|
rows.map((r) => [r, 0.0])
|
|
345
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
|
+
}
|
|
346
435
|
const { items } = partitionExpired(hydrated, { today: asOf, enabled: untilEnabled });
|
|
347
436
|
return items.slice(0, cap);
|
|
348
437
|
}
|
|
@@ -359,7 +448,12 @@ export class SQLiteMemoryStore {
|
|
|
359
448
|
|
|
360
449
|
if (quoted.length >= 1 && quoted.length <= 6) {
|
|
361
450
|
const andExpr = quoted.join(" AND ");
|
|
362
|
-
for (const [row, score] of this._ftsQuery(db, andExpr, {
|
|
451
|
+
for (const [row, score] of this._ftsQuery(db, andExpr, {
|
|
452
|
+
namespace,
|
|
453
|
+
limit: fetchLimit,
|
|
454
|
+
fromDate,
|
|
455
|
+
toDate,
|
|
456
|
+
})) {
|
|
363
457
|
const fid = Number(row.fact_id);
|
|
364
458
|
if (!seenIds.has(fid)) {
|
|
365
459
|
seenIds.add(fid);
|
|
@@ -370,7 +464,12 @@ export class SQLiteMemoryStore {
|
|
|
370
464
|
|
|
371
465
|
if (ranked.length < fetchLimit) {
|
|
372
466
|
const orExpr = quoted.join(" OR ");
|
|
373
|
-
for (const [row, score] of this._ftsQuery(db, orExpr, {
|
|
467
|
+
for (const [row, score] of this._ftsQuery(db, orExpr, {
|
|
468
|
+
namespace,
|
|
469
|
+
limit: fetchLimit * 2,
|
|
470
|
+
fromDate,
|
|
471
|
+
toDate,
|
|
472
|
+
})) {
|
|
374
473
|
const fid = Number(row.fact_id);
|
|
375
474
|
if (!seenIds.has(fid)) {
|
|
376
475
|
seenIds.add(fid);
|
|
@@ -380,7 +479,18 @@ export class SQLiteMemoryStore {
|
|
|
380
479
|
}
|
|
381
480
|
}
|
|
382
481
|
|
|
383
|
-
|
|
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
|
+
}
|
|
384
494
|
const { items } = partitionExpired(hydrated, { today: asOf, enabled: untilEnabled });
|
|
385
495
|
return selectAdaptiveHits(items, {
|
|
386
496
|
limit: cap,
|
|
@@ -391,7 +501,7 @@ export class SQLiteMemoryStore {
|
|
|
391
501
|
});
|
|
392
502
|
}
|
|
393
503
|
|
|
394
|
-
_ftsQuery(db, matchExpr, { namespace = null, limit = 24 }) {
|
|
504
|
+
_ftsQuery(db, matchExpr, { namespace = null, limit = 24, fromDate = null, toDate = null } = {}) {
|
|
395
505
|
let sql = `
|
|
396
506
|
SELECT f.*, bm25(facts_fts, 2.0, 1.0) AS rank_score
|
|
397
507
|
FROM facts_fts
|
|
@@ -403,6 +513,7 @@ export class SQLiteMemoryStore {
|
|
|
403
513
|
sql += " AND f.namespace = ?";
|
|
404
514
|
params.push(namespace);
|
|
405
515
|
}
|
|
516
|
+
sql = appendOccurredSqlPrefilter(sql, params, { alias: "f", fromDate, toDate });
|
|
406
517
|
sql += " ORDER BY rank_score ASC, f.mentioned_at DESC LIMIT ?";
|
|
407
518
|
params.push(limit);
|
|
408
519
|
|
|
@@ -410,22 +521,57 @@ export class SQLiteMemoryStore {
|
|
|
410
521
|
return rows.map((r) => [toPlainObject(r), Number((-Number(r.rank_score || 0)).toFixed(4))]);
|
|
411
522
|
}
|
|
412
523
|
|
|
413
|
-
_recentRows(db, { namespace = null, limit = 24 }) {
|
|
524
|
+
_recentRows(db, { namespace = null, limit = 24, fromDate = null, toDate = null } = {}) {
|
|
525
|
+
let sql = "SELECT * FROM facts WHERE 1=1";
|
|
526
|
+
const params = [];
|
|
414
527
|
if (namespace) {
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
.all(namespace, limit)
|
|
418
|
-
.map(toPlainObject);
|
|
528
|
+
sql += " AND namespace = ?";
|
|
529
|
+
params.push(namespace);
|
|
419
530
|
}
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
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);
|
|
424
539
|
}
|
|
425
540
|
|
|
426
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
|
+
|
|
427
572
|
const results = [];
|
|
428
573
|
for (const [row, score] of ranked) {
|
|
574
|
+
const fid = Number(row.fact_id);
|
|
429
575
|
const docId = String(row.doc_id);
|
|
430
576
|
const evIds = safeJsonParse(row.evidence_ids_json || "[]", []);
|
|
431
577
|
const evTexts = [];
|
|
@@ -447,8 +593,8 @@ export class SQLiteMemoryStore {
|
|
|
447
593
|
}
|
|
448
594
|
}
|
|
449
595
|
}
|
|
450
|
-
|
|
451
|
-
fact_id:
|
|
596
|
+
const item = {
|
|
597
|
+
fact_id: fid,
|
|
452
598
|
doc_id: docId,
|
|
453
599
|
namespace: String(row.namespace),
|
|
454
600
|
text: String(row.text),
|
|
@@ -462,7 +608,14 @@ export class SQLiteMemoryStore {
|
|
|
462
608
|
action: String(row.action),
|
|
463
609
|
mentioned_at: String(row.mentioned_at),
|
|
464
610
|
score,
|
|
465
|
-
}
|
|
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);
|
|
466
619
|
}
|
|
467
620
|
return results;
|
|
468
621
|
}
|
|
@@ -495,10 +648,7 @@ export class SQLiteMemoryStore {
|
|
|
495
648
|
}
|
|
496
649
|
|
|
497
650
|
let evictedCount = 0;
|
|
498
|
-
|
|
499
|
-
.prepare("SELECT 1 AS ok FROM sqlite_master WHERE type = 'table' AND name = 'evicted_records'")
|
|
500
|
-
.get();
|
|
501
|
-
if (hasEvicted) {
|
|
651
|
+
if (hasTable(db, "evicted_records")) {
|
|
502
652
|
evictedCount = namespace
|
|
503
653
|
? Number(
|
|
504
654
|
db.prepare("SELECT COUNT(*) AS c FROM evicted_records WHERE namespace = ?").get(namespace).c
|
|
@@ -506,6 +656,28 @@ export class SQLiteMemoryStore {
|
|
|
506
656
|
: Number(db.prepare("SELECT COUNT(*) AS c FROM evicted_records").get().c);
|
|
507
657
|
}
|
|
508
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
|
+
|
|
509
681
|
let dbSizeBytes = 0;
|
|
510
682
|
try {
|
|
511
683
|
dbSizeBytes = fs.statSync(this.dbPath).size;
|
|
@@ -520,6 +692,7 @@ export class SQLiteMemoryStore {
|
|
|
520
692
|
segments: segs,
|
|
521
693
|
facts,
|
|
522
694
|
revised_facts: revised,
|
|
695
|
+
supersessions,
|
|
523
696
|
evicted_records: evictedCount,
|
|
524
697
|
namespaces,
|
|
525
698
|
};
|
|
@@ -562,8 +735,12 @@ export class SQLiteMemoryStore {
|
|
|
562
735
|
deleteFact(factId) {
|
|
563
736
|
return this._withDb(
|
|
564
737
|
(db) => {
|
|
565
|
-
const
|
|
566
|
-
db.prepare("DELETE FROM
|
|
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
|
+
}
|
|
567
744
|
return Number(info.changes) > 0;
|
|
568
745
|
},
|
|
569
746
|
{ write: true }
|
|
@@ -578,7 +755,14 @@ export class SQLiteMemoryStore {
|
|
|
578
755
|
.all(String(docId))
|
|
579
756
|
.map((r) => Number(r.fact_id));
|
|
580
757
|
const delFts = db.prepare("DELETE FROM facts_fts WHERE fact_id = ?");
|
|
581
|
-
|
|
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
|
+
}
|
|
582
766
|
db.prepare("DELETE FROM facts WHERE doc_id = ?").run(String(docId));
|
|
583
767
|
db.prepare("DELETE FROM segments WHERE doc_id = ?").run(String(docId));
|
|
584
768
|
const info = db.prepare("DELETE FROM documents WHERE doc_id = ?").run(String(docId));
|
|
@@ -644,6 +828,7 @@ export class SQLiteMemoryStore {
|
|
|
644
828
|
}
|
|
645
829
|
}
|
|
646
830
|
|
|
831
|
+
const hasSup = hasTable(db, "fact_supersessions");
|
|
647
832
|
const docTargets = [...targetDocSet].sort();
|
|
648
833
|
const docFactIds = new Set();
|
|
649
834
|
const docPayloads = [];
|
|
@@ -661,6 +846,18 @@ export class SQLiteMemoryStore {
|
|
|
661
846
|
.map(toPlainObject);
|
|
662
847
|
for (const f of facts) docFactIds.add(Number(f.fact_id));
|
|
663
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
|
+
}
|
|
664
861
|
const payloadJson = canonicalJson(snapshot);
|
|
665
862
|
docPayloads.push({
|
|
666
863
|
kind: "document",
|
|
@@ -689,6 +886,13 @@ export class SQLiteMemoryStore {
|
|
|
689
886
|
.map(toPlainObject);
|
|
690
887
|
}
|
|
691
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
|
+
}
|
|
692
896
|
const payloadJson = canonicalJson(snapshot);
|
|
693
897
|
factPayloads.push({
|
|
694
898
|
kind: "fact",
|
|
@@ -728,6 +932,7 @@ export class SQLiteMemoryStore {
|
|
|
728
932
|
);
|
|
729
933
|
const delFts = db.prepare("DELETE FROM facts_fts WHERE fact_id = ?");
|
|
730
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;
|
|
731
936
|
|
|
732
937
|
for (const item of docPayloads) {
|
|
733
938
|
insEvict.run(
|
|
@@ -744,7 +949,10 @@ export class SQLiteMemoryStore {
|
|
|
744
949
|
.prepare("SELECT fact_id FROM facts WHERE doc_id = ?")
|
|
745
950
|
.all(item.id)
|
|
746
951
|
.map((r) => Number(r.fact_id));
|
|
747
|
-
for (const fid of fids)
|
|
952
|
+
for (const fid of fids) {
|
|
953
|
+
delFts.run(fid);
|
|
954
|
+
if (delSupNew) delSupNew.run(fid);
|
|
955
|
+
}
|
|
748
956
|
db.prepare("DELETE FROM facts WHERE doc_id = ?").run(item.id);
|
|
749
957
|
db.prepare("DELETE FROM segments WHERE doc_id = ?").run(item.id);
|
|
750
958
|
db.prepare("DELETE FROM documents WHERE doc_id = ?").run(item.id);
|
|
@@ -763,6 +971,7 @@ export class SQLiteMemoryStore {
|
|
|
763
971
|
);
|
|
764
972
|
delFact.run(Number(item.id));
|
|
765
973
|
delFts.run(Number(item.id));
|
|
974
|
+
if (delSupNew) delSupNew.run(Number(item.id));
|
|
766
975
|
}
|
|
767
976
|
|
|
768
977
|
const activeFactsAfter = namespace
|
|
@@ -893,6 +1102,13 @@ export class SQLiteMemoryStore {
|
|
|
893
1102
|
const insFts = db.prepare(
|
|
894
1103
|
"INSERT INTO facts_fts(fact_tokens, evidence_tokens, namespace, fact_id) VALUES (?, ?, ?, ?)"
|
|
895
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;
|
|
896
1112
|
|
|
897
1113
|
let restoredDocs = 0;
|
|
898
1114
|
let restoredFacts = 0;
|
|
@@ -913,7 +1129,26 @@ export class SQLiteMemoryStore {
|
|
|
913
1129
|
insFts.run(tokenizeForFts(factBlob), tokenizeForFts(boundEvidence), String(f.namespace), Number(f.fact_id));
|
|
914
1130
|
};
|
|
915
1131
|
|
|
916
|
-
|
|
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) {
|
|
917
1152
|
if (row.record_kind === "document") {
|
|
918
1153
|
const doc = snapshot.document;
|
|
919
1154
|
insDoc.run(
|
|
@@ -956,6 +1191,7 @@ export class SQLiteMemoryStore {
|
|
|
956
1191
|
indexFact(f, segMap);
|
|
957
1192
|
restoredFacts += 1;
|
|
958
1193
|
}
|
|
1194
|
+
restoreSupersessions(snapshot);
|
|
959
1195
|
restoredDocs += 1;
|
|
960
1196
|
} else {
|
|
961
1197
|
const f = snapshot.fact;
|
|
@@ -972,6 +1208,9 @@ export class SQLiteMemoryStore {
|
|
|
972
1208
|
);
|
|
973
1209
|
segMap.set(String(s.seg_id), String(s.text));
|
|
974
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
|
+
}
|
|
975
1214
|
insFact.run(
|
|
976
1215
|
Number(f.fact_id),
|
|
977
1216
|
f.doc_id,
|
|
@@ -988,6 +1227,7 @@ export class SQLiteMemoryStore {
|
|
|
988
1227
|
f.created_at
|
|
989
1228
|
);
|
|
990
1229
|
indexFact(f, segMap);
|
|
1230
|
+
restoreSupersessions(snapshot);
|
|
991
1231
|
restoredFacts += 1;
|
|
992
1232
|
}
|
|
993
1233
|
}
|