@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/lib/memory.mjs CHANGED
@@ -11,9 +11,15 @@ import { createHash } from "node:crypto";
11
11
  import {
12
12
  FACT_ADMISSION_SYSTEM,
13
13
  FACT_EXTRACTION_SYSTEM,
14
+ FACT_SUPERSESSION_SYSTEM,
15
+ SUPERSESSION_STOPWORDS,
14
16
  VALID_DECISIONS,
15
17
  buildSegments,
18
+ buildSupersessionSchema,
16
19
  guardFact,
20
+ hasSupersessionCue,
21
+ inferGroundedOccurredStart,
22
+ isNoopRevision,
17
23
  parseJsonObject,
18
24
  segmentToPayload,
19
25
  windowSegments,
@@ -27,7 +33,8 @@ import {
27
33
  pullOllamaModel,
28
34
  startLocalOllamaService,
29
35
  } from "./llm.mjs";
30
- import { SQLiteMemoryStore } from "./store.mjs";
36
+ import { backupDatabase, exportMarkdown } from "./portability.mjs";
37
+ import { SQLiteMemoryStore, tokenizeForFts } from "./store.mjs";
31
38
 
32
39
  function utcNowIso() {
33
40
  return new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
@@ -364,7 +371,7 @@ export class ZeroMemEngine {
364
371
  }
365
372
 
366
373
  /**
367
- * Ingest text or chat turns: redact -> short-window chunk -> extract -> 1-round admit -> guard -> SQLite.
374
+ * Ingest text or chat turns: redact -> short-window chunk -> extract -> prior FTS5 lookup -> 1-round admit -> guard -> SQLite.
368
375
  */
369
376
  async remember(
370
377
  content,
@@ -373,6 +380,7 @@ export class ZeroMemEngine {
373
380
  sourceId = null,
374
381
  mentionedAt = null,
375
382
  verify = null,
383
+ linkSupersessions = true,
376
384
  maxWindowChars = 1400,
377
385
  } = {}
378
386
  ) {
@@ -392,6 +400,7 @@ export class ZeroMemEngine {
392
400
  extracted: 0,
393
401
  saved: 0,
394
402
  revised: 0,
403
+ superseded: 0,
395
404
  dropped: 0,
396
405
  held: 0,
397
406
  guard_rejected: 0,
@@ -415,6 +424,7 @@ export class ZeroMemEngine {
415
424
  extracted: 0,
416
425
  saved: 0,
417
426
  revised: 0,
427
+ superseded: 0,
418
428
  dropped: 0,
419
429
  held: 0,
420
430
  guard_rejected: 0,
@@ -438,6 +448,7 @@ export class ZeroMemEngine {
438
448
  extracted: 0,
439
449
  saved: 0,
440
450
  revised: 0,
451
+ superseded: 0,
441
452
  dropped: 0,
442
453
  held: 0,
443
454
  guard_rejected: 0,
@@ -480,6 +491,7 @@ export class ZeroMemEngine {
480
491
  reviewed = candidates.map((c) => ({ ...c, action: "bypass" }));
481
492
  }
482
493
 
494
+ const windowAccepted = [];
483
495
  for (const cand of reviewed) {
484
496
  const action = String(cand.action || "pass");
485
497
  const { guarded } = guardFact(cand, segMap, { mentionedAt: ts });
@@ -490,8 +502,18 @@ export class ZeroMemEngine {
490
502
  const dedupKey = guarded.text.toLowerCase();
491
503
  if (seenFactKeys.has(dedupKey)) continue;
492
504
  seenFactKeys.add(dedupKey);
493
- acceptedFacts.push({ ...guarded, action });
505
+ windowAccepted.push({ ...guarded, action });
494
506
  }
507
+
508
+ if (shouldVerify && linkSupersessions && windowAccepted.length) {
509
+ await this._linkSupersessionsGated(llm, store, {
510
+ namespace,
511
+ acceptedFacts: windowAccepted,
512
+ maxPriorItems: 4,
513
+ });
514
+ }
515
+
516
+ acceptedFacts.push(...windowAccepted);
495
517
  }
496
518
 
497
519
  task.update("saving", "入库中");
@@ -507,6 +529,7 @@ export class ZeroMemEngine {
507
529
  });
508
530
 
509
531
  result.saved = savedIds.length;
532
+ result.superseded = acceptedFacts.filter((f) => f.supersedes_fact_id !== undefined).length;
510
533
  result.fact_ids = savedIds;
511
534
  result.facts = acceptedFacts;
512
535
  this.runtimeMetrics.lastRememberAt = createdAt;
@@ -532,14 +555,198 @@ export class ZeroMemEngine {
532
555
  return { candidates, model: String(meta?.model || "") };
533
556
  }
534
557
 
558
+ _contentTokens(text) {
559
+ const out = new Set();
560
+ for (const t of tokenizeForFts(text).split(/\s+/)) {
561
+ if (t.length >= 2 && !SUPERSESSION_STOPWORDS.has(t) && !/^\d{1,2}$/.test(t)) {
562
+ out.add(t);
563
+ }
564
+ }
565
+ return out;
566
+ }
567
+
568
+ _isGatedPriorMatch(candText, priorText) {
569
+ const a = this._contentTokens(candText);
570
+ const b = this._contentTokens(priorText);
571
+ if (!a.size || !b.size) return false;
572
+ let inter = 0;
573
+ for (const tok of a) {
574
+ if (b.has(tok)) inter += 1;
575
+ }
576
+ const union = a.size + b.size - inter;
577
+ const jac = inter / Math.max(1, union);
578
+ const cont = inter / Math.max(1, Math.min(a.size, b.size));
579
+ if (Math.min(a.size, b.size) >= 20 && jac >= 0.58) return false;
580
+ return inter >= 2 && cont >= 0.22 && jac >= 0.11;
581
+ }
582
+
583
+ _findGatedPriorFacts(store, { namespace, acceptedFacts, maxItems = 4 }) {
584
+ if (!Array.isArray(acceptedFacts) || !acceptedFacts.length || maxItems <= 0) {
585
+ return { eligibleIndices: [], priorFacts: [] };
586
+ }
587
+ const eligibleIndices = [];
588
+ const collected = new Map();
589
+
590
+ for (let idx = 0; idx < acceptedFacts.length; idx++) {
591
+ const fact = acceptedFacts[idx];
592
+ const text = String(fact?.text || "").trim();
593
+ if (!hasSupersessionCue(text)) continue;
594
+
595
+ const entities = Array.isArray(fact?.entities) ? fact.entities : [];
596
+ const parts = entities
597
+ .slice(0, 4)
598
+ .map((e) => String(e || "").trim())
599
+ .filter(Boolean);
600
+ if (text) parts.push(text.slice(0, 120));
601
+ const query = parts.join(" ").trim();
602
+ if (!query) continue;
603
+
604
+ let rows = [];
605
+ try {
606
+ rows = store.search(query, {
607
+ namespace,
608
+ limit: 3,
609
+ adaptive: false,
610
+ includeSuperseded: false,
611
+ });
612
+ } catch {
613
+ continue;
614
+ }
615
+
616
+ let matchedAny = false;
617
+ let perCandAdded = 0;
618
+ for (const r of rows) {
619
+ const fid = Number(r.fact_id);
620
+ const score = Number(r.score || 0);
621
+ if (!this._isGatedPriorMatch(text, String(r.text || ""))) continue;
622
+ matchedAny = true;
623
+ perCandAdded += 1;
624
+ const prev = collected.get(fid);
625
+ if (!prev || score > prev.score) {
626
+ collected.set(fid, {
627
+ score,
628
+ item: {
629
+ fact_id: fid,
630
+ text: String(r.text),
631
+ occurred_start: r.occurred_start ?? null,
632
+ mentioned_at: String(r.mentioned_at || ""),
633
+ entities: Array.isArray(r.entities) ? r.entities.slice(0, 6) : [],
634
+ },
635
+ });
636
+ }
637
+ if (perCandAdded >= 2) break;
638
+ }
639
+ if (matchedAny) eligibleIndices.push(idx);
640
+ }
641
+
642
+ if (!eligibleIndices.length || !collected.size) {
643
+ return { eligibleIndices: [], priorFacts: [] };
644
+ }
645
+ const priorFacts = [...collected.values()]
646
+ .sort((a, b) => (b.score !== a.score ? b.score - a.score : a.item.fact_id - b.item.fact_id))
647
+ .slice(0, maxItems)
648
+ .map((entry) => entry.item);
649
+ return { eligibleIndices, priorFacts };
650
+ }
651
+
652
+ _parseSinglePriorId(raw, offeredPriorIds) {
653
+ if (!offeredPriorIds || !offeredPriorIds.size || raw === undefined || raw === null || typeof raw === "boolean") {
654
+ return null;
655
+ }
656
+ const rawCandidates = Array.isArray(raw) ? raw : [raw];
657
+ for (const val of rawCandidates) {
658
+ if (typeof val === "boolean") continue;
659
+ let parsed = null;
660
+ if (typeof val === "number" && Number.isInteger(val)) {
661
+ parsed = val;
662
+ } else if (typeof val === "string" && /^\d+$/.test(val.trim())) {
663
+ parsed = Number(val.trim());
664
+ } else if (val && typeof val === "object" && "supersedes_fact_id" in val) {
665
+ const inner = val.supersedes_fact_id;
666
+ if (typeof inner === "number" && Number.isInteger(inner)) {
667
+ parsed = inner;
668
+ } else if (typeof inner === "string" && /^\d+$/.test(inner.trim())) {
669
+ parsed = Number(inner.trim());
670
+ }
671
+ }
672
+ if (parsed !== null && offeredPriorIds.has(parsed)) {
673
+ return parsed;
674
+ }
675
+ }
676
+ return null;
677
+ }
678
+
679
+ async _linkSupersessionsGated(llm, store, { namespace, acceptedFacts, maxPriorItems = 4 }) {
680
+ const { eligibleIndices, priorFacts } = this._findGatedPriorFacts(store, {
681
+ namespace,
682
+ acceptedFacts,
683
+ maxItems: maxPriorItems,
684
+ });
685
+ if (!eligibleIndices.length || !priorFacts.length) return;
686
+
687
+ const offeredPriorIds = new Set();
688
+ for (const pf of priorFacts) {
689
+ if (typeof pf?.fact_id === "number" && Number.isInteger(pf.fact_id) && pf.fact_id > 0) {
690
+ offeredPriorIds.add(pf.fact_id);
691
+ }
692
+ }
693
+ if (!offeredPriorIds.size) return;
694
+
695
+ const newFactsMap = {};
696
+ const slotKeys = [];
697
+ for (const idx of eligibleIndices) {
698
+ const slot = String(idx);
699
+ slotKeys.push(slot);
700
+ const f = acceptedFacts[idx];
701
+ newFactsMap[slot] = {
702
+ text: String(f.text || ""),
703
+ occurred_start: f.occurred_start ?? null,
704
+ entities: Array.isArray(f.entities) ? f.entities.slice(0, 6) : [],
705
+ };
706
+ }
707
+
708
+ const payload = {
709
+ new_facts: newFactsMap,
710
+ prior_facts: priorFacts,
711
+ };
712
+ const supSchema = buildSupersessionSchema(slotKeys, [...offeredPriorIds]);
713
+ let content;
714
+ try {
715
+ const resp = await llm.chatJson(FACT_SUPERSESSION_SYSTEM, payload, {
716
+ numPredict: 128,
717
+ responseFormat: supSchema,
718
+ });
719
+ content = resp?.content;
720
+ } catch {
721
+ return;
722
+ }
723
+ const mapping = parseJsonObject(content);
724
+ if (!mapping) return;
725
+
726
+ for (const idx of eligibleIndices) {
727
+ const slot = String(idx);
728
+ if (!(slot in mapping)) continue;
729
+ const supId = this._parseSinglePriorId(mapping[slot], offeredPriorIds);
730
+ if (supId !== null) {
731
+ acceptedFacts[idx].supersedes_fact_id = supId;
732
+ }
733
+ }
734
+ }
735
+
535
736
  async _admitWindow(llm, { window, candidates, mentionedAt, namespace, result }) {
737
+ const winSegText = new Map(window.map((s) => [s.id, s.text]));
536
738
  const factsMap = {};
537
739
  for (let idx = 0; idx < candidates.length; idx++) {
538
740
  const cand = candidates[idx];
741
+ let occStart = cand.occurred_start ?? null;
742
+ if (!occStart && Array.isArray(cand.evidence) && cand.evidence.length) {
743
+ const evBlob = cand.evidence.map((eid) => winSegText.get(String(eid)) || "").join("\n");
744
+ occStart = inferGroundedOccurredStart(cand.text, evBlob, mentionedAt);
745
+ }
539
746
  factsMap[String(idx)] = {
540
747
  text: String(cand.text || ""),
541
748
  type: String(cand.type || "world"),
542
- occurred_start: cand.occurred_start ?? null,
749
+ occurred_start: occStart,
543
750
  occurred_end: cand.occurred_end ?? null,
544
751
  where: cand.where ?? null,
545
752
  entities: Array.isArray(cand.entities) ? cand.entities : [],
@@ -553,6 +760,7 @@ export class ZeroMemEngine {
553
760
  evidence: window.map(segmentToPayload),
554
761
  facts: factsMap,
555
762
  };
763
+
556
764
  const { content } = await llm.chatJson(FACT_ADMISSION_SYSTEM, payload, { numPredict: 768 });
557
765
  const verdicts = parseJsonObject(content);
558
766
  if (!verdicts) {
@@ -579,10 +787,11 @@ export class ZeroMemEngine {
579
787
  approved.push({ ...cand, evidence: ev, action: "pass" });
580
788
  } else if (decision === "revise") {
581
789
  const replacement = String(verdict.replacement || "").trim();
582
- if (replacement) {
790
+ if (replacement && !isNoopRevision(String(cand.text || ""), replacement)) {
583
791
  result.revised += 1;
584
792
  approved.push({ ...cand, text: replacement, evidence: ev, action: "revise" });
585
793
  } else {
794
+ // Intercept empty or no-op revise (replacement identical to rejected original text)
586
795
  result.held += 1;
587
796
  }
588
797
  } else if (decision === "drop") {
@@ -604,6 +813,9 @@ export class ZeroMemEngine {
604
813
  scoreRatio = ADAPTIVE_SCORE_RATIO,
605
814
  asOf = null,
606
815
  untilEnabled = null,
816
+ occurredFrom = null,
817
+ occurredTo = null,
818
+ includeSuperseded = true,
607
819
  } = {}
608
820
  ) {
609
821
  const cfg = this.getConfig();
@@ -617,6 +829,9 @@ export class ZeroMemEngine {
617
829
  scoreRatio,
618
830
  asOf,
619
831
  untilEnabled: useUntil,
832
+ occurredFrom,
833
+ occurredTo,
834
+ includeSuperseded,
620
835
  });
621
836
  }
622
837
 
@@ -651,4 +866,47 @@ export class ZeroMemEngine {
651
866
  deleteDocument(docId) {
652
867
  return this.getStore().deleteDocument(docId);
653
868
  }
869
+
870
+ exportMarkdown({
871
+ outputPath = null,
872
+ outputDir = null,
873
+ ns = null,
874
+ occurredFrom = null,
875
+ occurredTo = null,
876
+ asOf = null,
877
+ includeSuperseded = true,
878
+ includeEvicted = false,
879
+ frontmatter = true,
880
+ } = {}) {
881
+ const store = this.getStore();
882
+ return exportMarkdown({
883
+ dbPath: store.dbPath,
884
+ outputPath,
885
+ outputDir,
886
+ namespace: ns || null,
887
+ occurredFrom,
888
+ occurredTo,
889
+ asOf,
890
+ includeSuperseded,
891
+ includeEvicted,
892
+ frontmatter,
893
+ });
894
+ }
895
+
896
+ async backup(outputPath = null, { overwrite = false, verify = true, writeSha256 = false, pages = 256 } = {}) {
897
+ const store = this.getStore();
898
+ const task = this.beginActivity("backup", "备份中");
899
+ try {
900
+ return await backupDatabase({
901
+ dbPath: store.dbPath,
902
+ outputPath,
903
+ overwrite,
904
+ verify,
905
+ writeSha256,
906
+ pages,
907
+ });
908
+ } finally {
909
+ task.end();
910
+ }
911
+ }
654
912
  }