@remnic/core 9.69.102 → 9.69.104
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/access-admin-ops-surface.js +53 -52
- package/dist/access-authorization-probe.js +54 -53
- package/dist/access-boundary.js +53 -52
- package/dist/access-cli.js +153 -150
- package/dist/access-cli.js.map +1 -1
- package/dist/access-extraction-force-flush.js +53 -52
- package/dist/access-http-briefing.js +54 -53
- package/dist/access-http-query.js +55 -54
- package/dist/access-http.js +77 -76
- package/dist/access-identity-continuity-surface.js +53 -52
- package/dist/access-lcm-surface.js +53 -52
- package/dist/access-mcp.js +66 -65
- package/dist/access-namespace-preflight.js +53 -52
- package/dist/access-observe-write-category.js +9 -9
- package/dist/access-observe-write-surface.js +53 -52
- package/dist/access-offline-manifest.js +6 -6
- package/dist/access-operations-batch.js +57 -56
- package/dist/access-operations.js +64 -63
- package/dist/access-recall-concurrency.js +53 -52
- package/dist/access-recall-response.js +53 -52
- package/dist/access-recall-surface.js +53 -52
- package/dist/access-schema.js +8 -8
- package/dist/access-service.js +53 -52
- package/dist/access-surface-catalog.js +55 -54
- package/dist/access-surface-catalog.js.map +1 -1
- package/dist/active-recall.js +21 -20
- package/dist/active-recall.js.map +1 -1
- package/dist/adapters/index.js +4 -4
- package/dist/adapters/registry.js +2 -2
- package/dist/briefing.js +14 -13
- package/dist/buffer.js +5 -5
- package/dist/{capsule-crypto-7FJQINUR.js → capsule-crypto-YO5QJ6L3.js} +2 -2
- package/dist/{capsule-merge-ZCXUPLNJ.js → capsule-merge-42GJGDUC.js} +4 -3
- package/dist/{capsule-merge-ZCXUPLNJ.js.map → capsule-merge-42GJGDUC.js.map} +1 -1
- package/dist/causal-behavior.js +2 -2
- package/dist/causal-chain.js +2 -2
- package/dist/causal-consolidation.js +17 -16
- package/dist/causal-consolidation.js.map +1 -1
- package/dist/causal-retrieval.js +2 -2
- package/dist/causal-trajectory-graph.js +3 -3
- package/dist/causal-trajectory.js +1 -1
- package/dist/{chunk-47LTKAGL.js → chunk-2COXDQ6C.js} +21 -6
- package/dist/chunk-2COXDQ6C.js.map +1 -0
- package/dist/{chunk-IOYY6ROU.js → chunk-2MMBJE53.js} +7 -7
- package/dist/{chunk-QSXEQPC4.js → chunk-2OFDC3AK.js} +2 -2
- package/dist/{chunk-4MP2Q2EI.js → chunk-2TCNEJ36.js} +4 -4
- package/dist/{chunk-5FAGCOZD.js → chunk-2U3R3DDH.js} +9 -9
- package/dist/{chunk-SCXURCVT.js → chunk-2UPTRDGM.js} +3 -3
- package/dist/{chunk-XVZA6VXC.js → chunk-3SL52JKD.js} +4 -4
- package/dist/{chunk-SBOCJ47I.js → chunk-5R4YPRAR.js} +19 -6
- package/dist/chunk-5R4YPRAR.js.map +1 -0
- package/dist/{chunk-ANPRNTPT.js → chunk-63LFM77Z.js} +15 -2
- package/dist/chunk-63LFM77Z.js.map +1 -0
- package/dist/{chunk-DINOVGA5.js → chunk-6WRHNA4I.js} +48 -48
- package/dist/chunk-6WRHNA4I.js.map +1 -0
- package/dist/{chunk-DSPWVQZ6.js → chunk-73R4HOOK.js} +3 -3
- package/dist/chunk-7CT3AI52.js +84 -0
- package/dist/chunk-7CT3AI52.js.map +1 -0
- package/dist/{chunk-PHBH74Q6.js → chunk-7NBUE5VY.js} +2 -2
- package/dist/{chunk-S533KGX6.js → chunk-7X7A7KVN.js} +2 -2
- package/dist/{chunk-XEATJBNB.js → chunk-7YQR6XHY.js} +71 -71
- package/dist/{chunk-F5MINS3R.js → chunk-A6WNTVA7.js} +3 -3
- package/dist/{chunk-F5MINS3R.js.map → chunk-A6WNTVA7.js.map} +1 -1
- package/dist/{chunk-533RHNHB.js → chunk-ATFFWIKL.js} +2 -2
- package/dist/{chunk-QCYUIZK2.js → chunk-AU43D3IT.js} +7 -7
- package/dist/{chunk-JZ66PN72.js → chunk-AWSP3WNM.js} +2 -2
- package/dist/{chunk-IY47KPML.js → chunk-B3OFQP5Y.js} +6 -6
- package/dist/{chunk-4DXNOVNW.js → chunk-B454SHPU.js} +6 -6
- package/dist/{chunk-3LMOJXZR.js → chunk-BKVCTTEN.js} +2 -2
- package/dist/{chunk-2NLLXCJG.js → chunk-BXLOS5AJ.js} +2 -2
- package/dist/{chunk-CZN53OT5.js → chunk-CGBE3N7T.js} +2 -2
- package/dist/{chunk-HWLIMQE2.js → chunk-CHDGJJV6.js} +2 -2
- package/dist/{chunk-UYPQOASU.js → chunk-CNBGAFDY.js} +2 -2
- package/dist/{chunk-JTC3PBNH.js → chunk-DB6XFMOF.js} +3 -3
- package/dist/{chunk-X7Y7WX73.js → chunk-DQEMWVMT.js} +1 -1
- package/dist/{chunk-UFIZRMQZ.js → chunk-E4XLFYHV.js} +61 -29
- package/dist/chunk-E4XLFYHV.js.map +1 -0
- package/dist/{chunk-4OXXDL3X.js → chunk-EWWK65CI.js} +2 -2
- package/dist/{chunk-DFPG47ET.js → chunk-EZ3F4YIN.js} +11 -11
- package/dist/{chunk-V3I4NLZP.js → chunk-FYX2LXIX.js} +2 -2
- package/dist/{chunk-PNVOKGAX.js → chunk-G5I5ZT6O.js} +2 -2
- package/dist/{chunk-7Z2UKRNJ.js → chunk-GQ6ZF4LD.js} +2 -2
- package/dist/{chunk-PEZAHDDU.js → chunk-GZ2KV2RO.js} +5 -5
- package/dist/chunk-H6Z3RNW3.js +330 -0
- package/dist/chunk-H6Z3RNW3.js.map +1 -0
- package/dist/{chunk-645WOU5I.js → chunk-H7BZBSP6.js} +4 -4
- package/dist/{chunk-AXHU56C3.js → chunk-HWGFTTPS.js} +2 -2
- package/dist/{chunk-2SGLMP2E.js → chunk-IDSZNHIP.js} +2 -2
- package/dist/{chunk-LO4UKPKX.js → chunk-IFCKHPY4.js} +2 -2
- package/dist/{chunk-ZHXSOMYH.js → chunk-IOMLGJHG.js} +4 -4
- package/dist/{chunk-YRULQW5J.js → chunk-ISX7GVZE.js} +4 -4
- package/dist/{chunk-5PHZSD75.js → chunk-J3ZJBX7I.js} +2 -2
- package/dist/{chunk-X5TAWDRO.js → chunk-JC7QQ2DJ.js} +2 -2
- package/dist/{chunk-RFQT7IZO.js → chunk-JRDL3FGM.js} +3 -3
- package/dist/{chunk-OGZC2WUX.js → chunk-JWFTPRYD.js} +2 -2
- package/dist/{chunk-7OA4JWP5.js → chunk-KFHEZJQZ.js} +2 -2
- package/dist/{chunk-P3WRFSYF.js → chunk-KMN2JE4D.js} +2 -2
- package/dist/{chunk-GNBZB43J.js → chunk-KV7LFOPF.js} +2 -2
- package/dist/{chunk-L6YCGS7I.js → chunk-KYUVFCT2.js} +2 -2
- package/dist/{chunk-5BVL2XUD.js → chunk-LHDSCWDK.js} +17 -17
- package/dist/{chunk-SF7CWSR6.js → chunk-LXJZUNLX.js} +2 -2
- package/dist/{chunk-XCB6QDL6.js → chunk-M5GVCJSJ.js} +8 -2
- package/dist/chunk-M5GVCJSJ.js.map +1 -0
- package/dist/{chunk-DGS34QSY.js → chunk-MFZACYZ6.js} +2 -2
- package/dist/{chunk-PYYQCHJC.js → chunk-MZOQ26LH.js} +2 -2
- package/dist/{chunk-R2TVWQLR.js → chunk-NT2Q6AHC.js} +2 -2
- package/dist/{chunk-ABGM2BN4.js → chunk-O43AAJFQ.js} +2 -2
- package/dist/{chunk-G3BW6SDE.js → chunk-OFGTRDWX.js} +3 -3
- package/dist/{chunk-6Z263Z3E.js → chunk-OWV6LKNZ.js} +2 -2
- package/dist/{chunk-HIHN4XHL.js → chunk-PQ7EB5AD.js} +3 -3
- package/dist/{chunk-VVYLVE6R.js → chunk-PQKZLBCJ.js} +1 -1
- package/dist/{chunk-OFFW73OZ.js → chunk-PRNR47DI.js} +2 -2
- package/dist/{chunk-UL7KDVLC.js → chunk-PZ2QQULY.js} +11 -11
- package/dist/{chunk-55NZVUNI.js → chunk-QAIVTLL2.js} +3 -3
- package/dist/{chunk-M7T2NKET.js → chunk-QKCGOECM.js} +2 -2
- package/dist/{chunk-ARY6O3JN.js → chunk-QUNCLKHM.js} +2 -2
- package/dist/{chunk-Z3O53WZR.js → chunk-QWUJWBZ5.js} +2 -2
- package/dist/{chunk-RZXFXKWY.js → chunk-QX3K3INR.js} +2 -2
- package/dist/{chunk-HFOY2SBG.js → chunk-RYN4AIRM.js} +7 -5
- package/dist/chunk-RYN4AIRM.js.map +1 -0
- package/dist/{chunk-4LNCLZNK.js → chunk-S2GR3T7W.js} +2 -2
- package/dist/{chunk-VPOAMPDD.js → chunk-SFDBLCZV.js} +59 -59
- package/dist/{chunk-2IWBHZ3H.js → chunk-SIGDETMB.js} +2 -2
- package/dist/chunk-SP4DB6SX.js +19 -0
- package/dist/chunk-SP4DB6SX.js.map +1 -0
- package/dist/{chunk-DBWNTLLI.js → chunk-STQC2FYQ.js} +6 -6
- package/dist/{chunk-S5R77WHV.js → chunk-SWXPR5SE.js} +2 -2
- package/dist/{chunk-3DNTFZAT.js → chunk-T32YYUT2.js} +2 -2
- package/dist/{chunk-W5JQSVPZ.js → chunk-T6RQNV7E.js} +2 -2
- package/dist/{chunk-O23QMYN4.js → chunk-TRN56SPQ.js} +2 -2
- package/dist/{chunk-NM3BT2OH.js → chunk-TXTRHF3B.js} +2 -2
- package/dist/{chunk-7AUIGOH4.js → chunk-VDVHIRCK.js} +2 -2
- package/dist/{chunk-KQAFEZQX.js → chunk-VDX2J7OX.js} +2 -2
- package/dist/{chunk-ZGYLPCWN.js → chunk-VO2BNAA2.js} +3 -3
- package/dist/{chunk-WVEECBCG.js → chunk-VV2MVHCJ.js} +2 -2
- package/dist/{chunk-HVDEKJJR.js → chunk-VYIBRCVW.js} +70 -61
- package/dist/chunk-VYIBRCVW.js.map +1 -0
- package/dist/{chunk-B3O3IRZN.js → chunk-VZBW6CDG.js} +1 -1
- package/dist/{chunk-JPKK466T.js → chunk-W5XWHTDO.js} +2 -2
- package/dist/{chunk-CYG3K2T2.js → chunk-WR66CTVU.js} +6 -6
- package/dist/{chunk-JNAOTN7B.js → chunk-XLWMNDQR.js} +4 -4
- package/dist/chunk-XLWMNDQR.js.map +1 -0
- package/dist/{chunk-RP7RSENW.js → chunk-XQWKB6PY.js} +2 -2
- package/dist/{chunk-64S6X4IU.js → chunk-XTN54NML.js} +4 -4
- package/dist/{chunk-UCPGOUDZ.js → chunk-Y57GJDG5.js} +108 -3
- package/dist/chunk-Y57GJDG5.js.map +1 -0
- package/dist/{chunk-KYLYXGKD.js → chunk-YI6XIFQV.js} +2 -2
- package/dist/{chunk-EZ25VE3G.js → chunk-YNDLCWXS.js} +4 -4
- package/dist/{chunk-Y7427SL7.js → chunk-Z6EZCN6Z.js} +10 -10
- package/dist/{chunk-5K2ALMSZ.js → chunk-ZRUC7FD3.js} +2 -2
- package/dist/cli.js +103 -102
- package/dist/coding/export-okf-codegraph.js +13 -12
- package/dist/coding/export-okf-codegraph.js.map +1 -1
- package/dist/coding/pre-action-gate.js +2 -2
- package/dist/compounding/engine.js +14 -13
- package/dist/config.js +21 -20
- package/dist/connectors/codex-materialize-runner.js +14 -13
- package/dist/connectors/index.js +14 -13
- package/dist/consolidation-provenance-check.js +4 -3
- package/dist/consolidation-undo.js +3 -2
- package/dist/consolidation-undo.js.map +1 -1
- package/dist/contradiction/index.js +3 -2
- package/dist/convergence-refresh.js +16 -15
- package/dist/corpus-watermark.js +16 -15
- package/dist/dashboard-runtime.js +2 -2
- package/dist/deep-recall-http-glue.js +9 -9
- package/dist/deep-recall.js +2 -2
- package/dist/embedding-fallback.d.ts +2 -1
- package/dist/embedding-fallback.d.ts.map +1 -1
- package/dist/embedding-fallback.js +2 -2
- package/dist/embedding-index-storage.d.ts +28 -1
- package/dist/embedding-index-storage.d.ts.map +1 -1
- package/dist/embedding-index-storage.js +1 -1
- package/dist/entity-mention-carry.d.ts +16 -0
- package/dist/entity-mention-carry.d.ts.map +1 -0
- package/dist/entity-mention-carry.js +8 -0
- package/dist/entity-mention-epoch.d.ts +22 -0
- package/dist/entity-mention-epoch.d.ts.map +1 -0
- package/dist/entity-mention-epoch.js +8 -0
- package/dist/entity-mention-index-cache.d.ts +28 -0
- package/dist/entity-mention-index-cache.d.ts.map +1 -0
- package/dist/entity-mention-index-cache.js +29 -0
- package/dist/entity-mention-index-cache.js.map +1 -0
- package/dist/entity-retrieval.d.ts.map +1 -1
- package/dist/entity-retrieval.js +18 -15
- package/dist/event-order-recall.js +2 -2
- package/dist/external-wiki-access.js +54 -53
- package/dist/extraction-span-materialize.js +2 -2
- package/dist/extraction.js +21 -20
- package/dist/{graph-edge-decay-MKIRZ762.js → graph-edge-decay-PVKDKLQK.js} +6 -6
- package/dist/graph-edge-decay-PVKDKLQK.js.map +1 -0
- package/dist/graph-jsonl.js +4 -4
- package/dist/graph-snapshot.js +4 -4
- package/dist/graph.js +5 -5
- package/dist/harmonic-retrieval.js +1 -1
- package/dist/index.js +187 -184
- package/dist/lcm/engine.js +4 -4
- package/dist/lcm/index.js +13 -13
- package/dist/location/index.js +16 -15
- package/dist/maintenance/memory-governance.js +14 -13
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +14 -13
- package/dist/maintenance/rebuild-memory-projection.js +15 -14
- package/dist/memory-browse-operations.js +54 -53
- package/dist/memory-browse.js +5 -5
- package/dist/memory-corpus-version.d.ts +8 -3
- package/dist/memory-corpus-version.d.ts.map +1 -1
- package/dist/memory-corpus-version.js +2 -1
- package/dist/namespaces/migrate.js +15 -14
- package/dist/namespaces/search.js +7 -7
- package/dist/namespaces/storage.js +14 -13
- package/dist/offline-sync-changeset-generations.js +4 -4
- package/dist/offline-sync-embedding-generation.js +3 -3
- package/dist/offline-sync-exclude-globs.d.ts +8 -0
- package/dist/offline-sync-exclude-globs.d.ts.map +1 -1
- package/dist/offline-sync-exclude-globs.js +3 -1
- package/dist/offline-sync-snapshot-stream.js +6 -6
- package/dist/offline-sync.d.ts.map +1 -1
- package/dist/offline-sync.js +9 -9
- package/dist/operator-doctor-corpus.js +17 -16
- package/dist/operator-toolkit.js +34 -33
- package/dist/orchestration/maintenance.js +22 -21
- package/dist/orchestrator.js +153 -150
- package/dist/page-versioning.js +3 -2
- package/dist/preferences/preference-drift.d.ts.map +1 -1
- package/dist/procedural/library-maintenance.d.ts.map +1 -1
- package/dist/qmd.js +4 -4
- package/dist/recall-navigation-operations.js +54 -53
- package/dist/recall-navigation.js +53 -52
- package/dist/recall-state-view-admission.js +5 -5
- package/dist/recall-why-service.js +5 -5
- package/dist/{resolution-BROE3TRO.js → resolution-RSG4HZTL.js} +4 -3
- package/dist/resolution-RSG4HZTL.js.map +1 -0
- package/dist/resume-bundles.js +22 -21
- package/dist/search/factory.js +6 -6
- package/dist/search/index.js +12 -12
- package/dist/semantic-consolidation.js +15 -14
- package/dist/semantic-rule-promotion.js +14 -13
- package/dist/semantic-rule-verifier.js +14 -13
- package/dist/source-agent-qualifier.js +17 -16
- package/dist/standup/build.js +14 -13
- package/dist/storage/entity-mention-frontmatter-hold.d.ts +14 -0
- package/dist/storage/entity-mention-frontmatter-hold.d.ts.map +1 -0
- package/dist/storage.d.ts +13 -9
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +13 -12
- package/dist/support-passport/index.js +56 -55
- package/dist/transfer/backup.js +2 -2
- package/dist/transfer/capsule-export.js +2 -2
- package/dist/transfer/capsule-import.js +5 -4
- package/dist/transfer/export-okf.js +14 -13
- package/dist/verified-recall.js +14 -13
- package/dist/who-knows-cli.js +15 -14
- package/dist/who-knows.js +14 -13
- package/package.json +2 -2
- package/src/embedding-fallback-cross-process.test.ts +533 -0
- package/src/embedding-fallback.ts +19 -7
- package/src/embedding-index-storage.test.ts +482 -2
- package/src/embedding-index-storage.ts +131 -2
- package/src/entity-mention-carry.ts +31 -0
- package/src/entity-mention-epoch.ts +120 -0
- package/src/entity-mention-index-cache.ts +443 -0
- package/src/entity-retrieval.ts +72 -71
- package/src/maintenance/rebuild-memory-projection.ts +1 -1
- package/src/memory-corpus-version.ts +13 -3
- package/src/offline-sync-exclude-globs.ts +23 -0
- package/src/offline-sync.test.ts +325 -0
- package/src/offline-sync.ts +17 -1
- package/src/preferences/preference-drift.ts +5 -3
- package/src/procedural/library-maintenance.ts +4 -3
- package/src/semantic-rule-promotion.ts +1 -1
- package/src/storage/entity-mention-frontmatter-hold.ts +44 -0
- package/src/storage.ts +40 -38
- package/dist/chunk-47LTKAGL.js.map +0 -1
- package/dist/chunk-ANPRNTPT.js.map +0 -1
- package/dist/chunk-DINOVGA5.js.map +0 -1
- package/dist/chunk-HFOY2SBG.js.map +0 -1
- package/dist/chunk-HVDEKJJR.js.map +0 -1
- package/dist/chunk-JNAOTN7B.js.map +0 -1
- package/dist/chunk-SBOCJ47I.js.map +0 -1
- package/dist/chunk-UCPGOUDZ.js.map +0 -1
- package/dist/chunk-UFIZRMQZ.js.map +0 -1
- package/dist/chunk-XCB6QDL6.js.map +0 -1
- /package/dist/{capsule-crypto-7FJQINUR.js.map → capsule-crypto-YO5QJ6L3.js.map} +0 -0
- /package/dist/{chunk-IOYY6ROU.js.map → chunk-2MMBJE53.js.map} +0 -0
- /package/dist/{chunk-QSXEQPC4.js.map → chunk-2OFDC3AK.js.map} +0 -0
- /package/dist/{chunk-4MP2Q2EI.js.map → chunk-2TCNEJ36.js.map} +0 -0
- /package/dist/{chunk-5FAGCOZD.js.map → chunk-2U3R3DDH.js.map} +0 -0
- /package/dist/{chunk-SCXURCVT.js.map → chunk-2UPTRDGM.js.map} +0 -0
- /package/dist/{chunk-XVZA6VXC.js.map → chunk-3SL52JKD.js.map} +0 -0
- /package/dist/{chunk-DSPWVQZ6.js.map → chunk-73R4HOOK.js.map} +0 -0
- /package/dist/{chunk-PHBH74Q6.js.map → chunk-7NBUE5VY.js.map} +0 -0
- /package/dist/{chunk-S533KGX6.js.map → chunk-7X7A7KVN.js.map} +0 -0
- /package/dist/{chunk-XEATJBNB.js.map → chunk-7YQR6XHY.js.map} +0 -0
- /package/dist/{chunk-533RHNHB.js.map → chunk-ATFFWIKL.js.map} +0 -0
- /package/dist/{chunk-QCYUIZK2.js.map → chunk-AU43D3IT.js.map} +0 -0
- /package/dist/{chunk-JZ66PN72.js.map → chunk-AWSP3WNM.js.map} +0 -0
- /package/dist/{chunk-IY47KPML.js.map → chunk-B3OFQP5Y.js.map} +0 -0
- /package/dist/{chunk-4DXNOVNW.js.map → chunk-B454SHPU.js.map} +0 -0
- /package/dist/{chunk-3LMOJXZR.js.map → chunk-BKVCTTEN.js.map} +0 -0
- /package/dist/{chunk-2NLLXCJG.js.map → chunk-BXLOS5AJ.js.map} +0 -0
- /package/dist/{chunk-CZN53OT5.js.map → chunk-CGBE3N7T.js.map} +0 -0
- /package/dist/{chunk-HWLIMQE2.js.map → chunk-CHDGJJV6.js.map} +0 -0
- /package/dist/{chunk-UYPQOASU.js.map → chunk-CNBGAFDY.js.map} +0 -0
- /package/dist/{chunk-JTC3PBNH.js.map → chunk-DB6XFMOF.js.map} +0 -0
- /package/dist/{chunk-X7Y7WX73.js.map → chunk-DQEMWVMT.js.map} +0 -0
- /package/dist/{chunk-4OXXDL3X.js.map → chunk-EWWK65CI.js.map} +0 -0
- /package/dist/{chunk-DFPG47ET.js.map → chunk-EZ3F4YIN.js.map} +0 -0
- /package/dist/{chunk-V3I4NLZP.js.map → chunk-FYX2LXIX.js.map} +0 -0
- /package/dist/{chunk-PNVOKGAX.js.map → chunk-G5I5ZT6O.js.map} +0 -0
- /package/dist/{chunk-7Z2UKRNJ.js.map → chunk-GQ6ZF4LD.js.map} +0 -0
- /package/dist/{chunk-PEZAHDDU.js.map → chunk-GZ2KV2RO.js.map} +0 -0
- /package/dist/{chunk-645WOU5I.js.map → chunk-H7BZBSP6.js.map} +0 -0
- /package/dist/{chunk-AXHU56C3.js.map → chunk-HWGFTTPS.js.map} +0 -0
- /package/dist/{chunk-2SGLMP2E.js.map → chunk-IDSZNHIP.js.map} +0 -0
- /package/dist/{chunk-LO4UKPKX.js.map → chunk-IFCKHPY4.js.map} +0 -0
- /package/dist/{chunk-ZHXSOMYH.js.map → chunk-IOMLGJHG.js.map} +0 -0
- /package/dist/{chunk-YRULQW5J.js.map → chunk-ISX7GVZE.js.map} +0 -0
- /package/dist/{chunk-5PHZSD75.js.map → chunk-J3ZJBX7I.js.map} +0 -0
- /package/dist/{chunk-X5TAWDRO.js.map → chunk-JC7QQ2DJ.js.map} +0 -0
- /package/dist/{chunk-RFQT7IZO.js.map → chunk-JRDL3FGM.js.map} +0 -0
- /package/dist/{chunk-OGZC2WUX.js.map → chunk-JWFTPRYD.js.map} +0 -0
- /package/dist/{chunk-7OA4JWP5.js.map → chunk-KFHEZJQZ.js.map} +0 -0
- /package/dist/{chunk-P3WRFSYF.js.map → chunk-KMN2JE4D.js.map} +0 -0
- /package/dist/{chunk-GNBZB43J.js.map → chunk-KV7LFOPF.js.map} +0 -0
- /package/dist/{chunk-L6YCGS7I.js.map → chunk-KYUVFCT2.js.map} +0 -0
- /package/dist/{chunk-5BVL2XUD.js.map → chunk-LHDSCWDK.js.map} +0 -0
- /package/dist/{chunk-SF7CWSR6.js.map → chunk-LXJZUNLX.js.map} +0 -0
- /package/dist/{chunk-DGS34QSY.js.map → chunk-MFZACYZ6.js.map} +0 -0
- /package/dist/{chunk-PYYQCHJC.js.map → chunk-MZOQ26LH.js.map} +0 -0
- /package/dist/{chunk-R2TVWQLR.js.map → chunk-NT2Q6AHC.js.map} +0 -0
- /package/dist/{chunk-ABGM2BN4.js.map → chunk-O43AAJFQ.js.map} +0 -0
- /package/dist/{chunk-G3BW6SDE.js.map → chunk-OFGTRDWX.js.map} +0 -0
- /package/dist/{chunk-6Z263Z3E.js.map → chunk-OWV6LKNZ.js.map} +0 -0
- /package/dist/{chunk-HIHN4XHL.js.map → chunk-PQ7EB5AD.js.map} +0 -0
- /package/dist/{chunk-VVYLVE6R.js.map → chunk-PQKZLBCJ.js.map} +0 -0
- /package/dist/{chunk-OFFW73OZ.js.map → chunk-PRNR47DI.js.map} +0 -0
- /package/dist/{chunk-UL7KDVLC.js.map → chunk-PZ2QQULY.js.map} +0 -0
- /package/dist/{chunk-55NZVUNI.js.map → chunk-QAIVTLL2.js.map} +0 -0
- /package/dist/{chunk-M7T2NKET.js.map → chunk-QKCGOECM.js.map} +0 -0
- /package/dist/{chunk-ARY6O3JN.js.map → chunk-QUNCLKHM.js.map} +0 -0
- /package/dist/{chunk-Z3O53WZR.js.map → chunk-QWUJWBZ5.js.map} +0 -0
- /package/dist/{chunk-RZXFXKWY.js.map → chunk-QX3K3INR.js.map} +0 -0
- /package/dist/{chunk-4LNCLZNK.js.map → chunk-S2GR3T7W.js.map} +0 -0
- /package/dist/{chunk-VPOAMPDD.js.map → chunk-SFDBLCZV.js.map} +0 -0
- /package/dist/{chunk-2IWBHZ3H.js.map → chunk-SIGDETMB.js.map} +0 -0
- /package/dist/{chunk-DBWNTLLI.js.map → chunk-STQC2FYQ.js.map} +0 -0
- /package/dist/{chunk-S5R77WHV.js.map → chunk-SWXPR5SE.js.map} +0 -0
- /package/dist/{chunk-3DNTFZAT.js.map → chunk-T32YYUT2.js.map} +0 -0
- /package/dist/{chunk-W5JQSVPZ.js.map → chunk-T6RQNV7E.js.map} +0 -0
- /package/dist/{chunk-O23QMYN4.js.map → chunk-TRN56SPQ.js.map} +0 -0
- /package/dist/{chunk-NM3BT2OH.js.map → chunk-TXTRHF3B.js.map} +0 -0
- /package/dist/{chunk-7AUIGOH4.js.map → chunk-VDVHIRCK.js.map} +0 -0
- /package/dist/{chunk-KQAFEZQX.js.map → chunk-VDX2J7OX.js.map} +0 -0
- /package/dist/{chunk-ZGYLPCWN.js.map → chunk-VO2BNAA2.js.map} +0 -0
- /package/dist/{chunk-WVEECBCG.js.map → chunk-VV2MVHCJ.js.map} +0 -0
- /package/dist/{chunk-B3O3IRZN.js.map → chunk-VZBW6CDG.js.map} +0 -0
- /package/dist/{chunk-JPKK466T.js.map → chunk-W5XWHTDO.js.map} +0 -0
- /package/dist/{chunk-CYG3K2T2.js.map → chunk-WR66CTVU.js.map} +0 -0
- /package/dist/{chunk-RP7RSENW.js.map → chunk-XQWKB6PY.js.map} +0 -0
- /package/dist/{chunk-64S6X4IU.js.map → chunk-XTN54NML.js.map} +0 -0
- /package/dist/{chunk-KYLYXGKD.js.map → chunk-YI6XIFQV.js.map} +0 -0
- /package/dist/{chunk-EZ25VE3G.js.map → chunk-YNDLCWXS.js.map} +0 -0
- /package/dist/{chunk-Y7427SL7.js.map → chunk-Z6EZCN6Z.js.map} +0 -0
- /package/dist/{chunk-5K2ALMSZ.js.map → chunk-ZRUC7FD3.js.map} +0 -0
- /package/dist/{graph-edge-decay-MKIRZ762.js.map → entity-mention-carry.js.map} +0 -0
- /package/dist/{resolution-BROE3TRO.js.map → entity-mention-epoch.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/preferences/preference-drift.ts","../src/contradiction/resolution.ts"],"sourcesContent":["/**\n * Preference drift detection (issue #2371).\n *\n * Remnic already handles *explicit* preference change: the contradiction scan\n * catches a new statement that conflicts with a stored one, and temporal\n * supersession retires a fact that gets restated. Both require new evidence to\n * arrive. This module covers the opposite failure mode the agent-memory survey\n * calls stale preference reuse: a `category: preference` memory keeps being\n * injected at full prominence even though the last N days of conversation\n * contain no corroboration for it — or contain behavioral evidence pointing the\n * other way that never rose to an explicit contradiction.\n *\n * Per aging preference the scan gathers recent same-namespace evidence, then\n * classifies:\n *\n * - `corroborated` — recent evidence restates or is consistent with it.\n * - `stale` — the lookback window held nothing either way.\n * - `drifted` — recent evidence points away from it (judge verdict\n * `contradicts`), so a review item is opened.\n * - `skipped` — the classification could not be made honestly:\n * `backend_unavailable` (evidence lookup failed — §22:\n * never counted as \"no evidence\") or\n * `verification_unavailable` (evidence exists but no LLM\n * could judge it, so neither a positive nor a negative\n * claim is warranted).\n *\n * Apply mode stamps `lastCorroborated` / `driftState` and opens review items.\n * It never auto-deletes and never auto-supersedes: drift is inference, and the\n * least-privileged default for an inferred change to user state is \"ask\"\n * (Review Prevention Checklist §36). Resolution runs through the existing\n * review queue and `review_resolve`, with the drift verbs `keep`, `supersede`,\n * and `archive`.\n *\n * Deliberately NOT part of `runMemoryGovernance` — same isolation decision as\n * procedure mining and procedure-library maintenance.\n */\n\nimport path from \"node:path\";\nimport type { MemoryFile, MemoryStatus, PluginConfig } from \"../types.js\";\nimport type { StorageManager } from \"../storage.js\";\nimport type { LocalLlmClient } from \"../local-llm.js\";\nimport type { FallbackLlmClient } from \"../fallback-llm.js\";\nimport type { SemanticDedupHit, SemanticDedupLookup } from \"../dedup/semantic.js\";\nimport {\n judgeContradictionPairs,\n type ContradictionJudgeInput,\n type ContradictionJudgeResult,\n} from \"../contradiction/contradiction-judge.js\";\nimport {\n computeMemoryContentHash,\n writePairs,\n type ContradictionPair,\n} from \"../contradiction/contradiction-review.js\";\nimport { resolveScanStorage, type ScanStorageResolution } from \"../contradiction/contradiction-scan.js\";\nimport { bumpMemoryCorpusVersionForDir } from \"../memory-corpus-version.js\";\nimport { composeMemoryEnvelope } from \"../write-envelope.js\";\nimport { readJsonFile, writeJsonFileAtomic } from \"../json-store.js\";\nimport { log } from \"../logger.js\";\n\nconst DRIFT_ACTOR = \"preference-drift\";\nconst DRIFT_RULE_VERSION = \"preference-drift:1\";\nconst DAY_MS = 24 * 60 * 60 * 1000;\n\n/** Evidence hits fetched per preference. Bounded so one scan cannot fan out. */\nconst EVIDENCE_LOOKUP_LIMIT = 5;\n\nexport type PreferenceDriftClassification =\n | \"corroborated\"\n | \"stale\"\n | \"drifted\"\n | \"skipped\";\n\nexport type PreferenceDriftSkipReason =\n | \"backend_unavailable\"\n | \"verification_unavailable\";\n\nexport interface PreferenceDriftEvidence {\n memoryId: string;\n /** Similarity score reported by the evidence lookup. */\n score: number;\n /** `updated` (or `created`) of the evidence memory, ISO 8601. */\n observedAt: string;\n}\n\nexport interface PreferenceDriftFinding {\n memoryId: string;\n classification: PreferenceDriftClassification;\n /** Set only for `classification: \"skipped\"`. */\n skipped?: PreferenceDriftSkipReason;\n /** Age of the preference in whole days at the run instant. */\n ageDays: number;\n /** Existing `lastCorroborated` stamp, or null when never corroborated. */\n lastCorroborated: string | null;\n reason: string;\n evidence: PreferenceDriftEvidence[];\n /** Review pair id opened for a `drifted` finding in apply mode. */\n reviewPairId?: string;\n}\n\nexport interface PreferenceDriftReport {\n schemaVersion: 1;\n generatedAt: string;\n mode: \"shadow\" | \"apply\";\n namespace?: string;\n /** Active preferences examined after the min-age filter and per-run cap. */\n scanned: number;\n /** Active preferences that passed the category/status filter before the cap. */\n eligible: number;\n findings: PreferenceDriftFinding[];\n counts: Record<PreferenceDriftClassification, number>;\n /** Frontmatter stamps + review items actually written. Always 0 in shadow mode. */\n appliedCount: number;\n reviewItemsOpened: number;\n elapsedMs: number;\n skippedReason?: \"drift_disabled\" | \"scan_disabled\";\n}\n\nexport interface PreferenceDriftMarker {\n schemaVersion: 1;\n lastRunAt: string;\n lastApplyAt: string | null;\n appliedCount: number;\n}\n\nexport interface PreferenceDriftDependencies {\n storage: StorageManager;\n config: PluginConfig;\n memoryDir: string;\n /** Pre-built evidence lookup. Superseded by `embeddingLookupFactory`. */\n embeddingLookup?: SemanticDedupLookup;\n /** Builds a namespace-scoped evidence lookup from the scan's own storage. */\n embeddingLookupFactory?: (storage: StorageManager) => SemanticDedupLookup | undefined;\n storageForNamespace?: (\n namespace: string | undefined,\n ) => StorageManager | ScanStorageResolution | Promise<StorageManager | ScanStorageResolution>;\n localLlm: LocalLlmClient | null;\n fallbackLlm: FallbackLlmClient | null;\n namespace?: string;\n /** When true (and `driftDetection.enabled`), stamps and review items are written. */\n apply?: boolean;\n now?: Date;\n}\n\nfunction driftMarkerPath(memoryDir: string): string {\n return path.join(memoryDir, \"state\", \"preference-drift.json\");\n}\n\n/** Read the last-run marker. Absent marker (or shadow-only history) → null apply timestamp. */\nexport async function readPreferenceDriftMarker(\n memoryDir: string,\n): Promise<PreferenceDriftMarker | null> {\n try {\n const raw = await readJsonFile(driftMarkerPath(memoryDir));\n if (raw === null || typeof raw !== \"object\" || Array.isArray(raw)) return null;\n const m = raw as Record<string, unknown>;\n if (typeof m.lastRunAt !== \"string\") return null;\n return {\n schemaVersion: 1,\n lastRunAt: m.lastRunAt,\n lastApplyAt: typeof m.lastApplyAt === \"string\" ? m.lastApplyAt : null,\n appliedCount: typeof m.appliedCount === \"number\" ? m.appliedCount : 0,\n };\n } catch {\n return null;\n }\n}\n\nfunction tsMs(value: unknown): number | null {\n if (typeof value !== \"string\") return null;\n const ms = Date.parse(value);\n return Number.isFinite(ms) ? ms : null;\n}\n\n/**\n * Statuses that make a memory a drift candidate. Stated as an inclusion set,\n * never an exclusion list, so a newly added status can never leak through\n * (§41): `superseded`, `archived`, `quarantined`, `rejected`, and\n * `pending_review` preferences are all excluded by construction.\n */\nconst CANDIDATE_STATUSES: Partial<Record<MemoryStatus, true>> = { active: true };\n\n/**\n * Deterministic candidate order (§12): oldest preference first, stable id\n * tiebreak, so the per-run cap always selects the same slice on identical\n * fixtures.\n */\nfunction compareCandidates(a: MemoryFile, b: MemoryFile): number {\n const aMs = tsMs(a.frontmatter.created) ?? tsMs(a.frontmatter.updated) ?? 0;\n const bMs = tsMs(b.frontmatter.created) ?? tsMs(b.frontmatter.updated) ?? 0;\n if (aMs !== bMs) return aMs < bMs ? -1 : 1;\n const aId = a.frontmatter.id ?? \"\";\n const bId = b.frontmatter.id ?? \"\";\n if (aId !== bId) return aId < bId ? -1 : 1;\n return 0;\n}\n\ntype EvidenceResult =\n | { ok: true; hits: PreferenceDriftEvidence[]; hitMemories: MemoryFile[] }\n | { ok: false; reason: \"backend_unavailable\" };\n\n/**\n * Gather recent same-namespace evidence for one preference.\n *\n * §22: an empty result and a failed backend are DIFFERENT outcomes. The\n * `SemanticDedupLookup` contract is that implementations throw when the\n * embedding backend is unavailable and return `[]` only when a reachable\n * backend reports no hits, so the throw is the failure signal — it must never\n * be swallowed into \"no evidence\", which would mark a live preference stale.\n */\nasync function gatherEvidence(\n preference: MemoryFile,\n lookup: SemanticDedupLookup,\n byId: ReadonlyMap<string, MemoryFile>,\n windowStartMs: number,\n nowMs: number,\n): Promise<EvidenceResult> {\n let raw: SemanticDedupHit[];\n try {\n raw = await lookup(preference.content, EVIDENCE_LOOKUP_LIMIT);\n } catch (err) {\n log.debug(\"[preference-drift] evidence lookup failed\", {\n memoryId: preference.frontmatter.id,\n error: err instanceof Error ? err.message : String(err),\n });\n return { ok: false, reason: \"backend_unavailable\" };\n }\n\n const hits: PreferenceDriftEvidence[] = [];\n const hitMemories: MemoryFile[] = [];\n for (const hit of raw) {\n if (hit.id === preference.frontmatter.id) continue;\n const memory = byId.get(hit.id);\n if (!memory) continue;\n const observedMs = tsMs(memory.frontmatter.updated) ?? tsMs(memory.frontmatter.created);\n if (observedMs === null) continue;\n // Half-open window [windowStart, now): a memory observed exactly at the\n // window start counts, one observed exactly at the run instant does not\n // (§23).\n if (observedMs < windowStartMs || observedMs >= nowMs) continue;\n hits.push({\n memoryId: hit.id,\n score: hit.score,\n observedAt: memory.frontmatter.updated ?? memory.frontmatter.created ?? \"\",\n });\n hitMemories.push(memory);\n }\n return { ok: true, hits, hitMemories };\n}\n\n/**\n * Map judge verdicts over a preference's evidence to a drift classification.\n *\n * - `contradicts` on any hit wins: the preference has drifted.\n * - `duplicates` means the evidence restates the preference → corroborated.\n * - `independent` is evidence about something else, so it corroborates\n * nothing; with no better verdict the preference is stale.\n * - `needs-user` (which is also what the judge returns when no LLM is\n * reachable) leaves the question genuinely unanswered. Stamping\n * `lastCorroborated` would assert something unverified and stamping `stale`\n * would contradict the evidence we did find, so the honest outcome is\n * `skipped: verification_unavailable`.\n */\nfunction classifyFromVerdicts(\n verdicts: readonly ContradictionJudgeResult[],\n): { classification: PreferenceDriftClassification; skipped?: PreferenceDriftSkipReason; reason: string; driftedAgainst?: string } {\n const contradiction = verdicts.find((v) => v.verdict === \"contradicts\");\n if (contradiction) {\n return {\n classification: \"drifted\",\n reason: `recent evidence points away from this preference: ${contradiction.rationale}`,\n driftedAgainst: contradiction.memoryIdB,\n };\n }\n const restatement = verdicts.find((v) => v.verdict === \"duplicates\");\n if (restatement) {\n return {\n classification: \"corroborated\",\n reason: `recent evidence restates this preference: ${restatement.rationale}`,\n };\n }\n if (verdicts.some((v) => v.verdict === \"needs-user\")) {\n return {\n classification: \"skipped\",\n skipped: \"verification_unavailable\",\n reason: \"recent evidence found but no judge verdict was available to classify it\",\n };\n }\n return {\n classification: \"stale\",\n reason: \"recent evidence is independent of this preference — no corroboration either way\",\n };\n}\n\n/**\n * Run one preference-drift pass over a namespace.\n *\n * Shadow mode (the default) performs NO writes — not even the run marker.\n * Applying requires `apply: true` AND `driftDetection.enabled: true`.\n */\nexport async function runPreferenceDriftScan(\n deps: PreferenceDriftDependencies,\n): Promise<PreferenceDriftReport> {\n const startTime = Date.now();\n const now = deps.now ?? new Date();\n const nowIso = now.toISOString();\n const nowMs = now.getTime();\n const mode: \"shadow\" | \"apply\" = deps.apply === true ? \"apply\" : \"shadow\";\n const cfg = deps.config.driftDetection;\n\n const emptyCounts: Record<PreferenceDriftClassification, number> = {\n corroborated: 0,\n stale: 0,\n drifted: 0,\n skipped: 0,\n };\n\n if (cfg?.enabled !== true) {\n return {\n schemaVersion: 1,\n generatedAt: nowIso,\n mode,\n scanned: 0,\n eligible: 0,\n findings: [],\n counts: emptyCounts,\n appliedCount: 0,\n reviewItemsOpened: 0,\n elapsedMs: Date.now() - startTime,\n skippedReason: \"drift_disabled\",\n };\n }\n // `0` is the documented disable value and must behave as a true zero (§33).\n if (cfg.maxCandidatesPerRun === 0) {\n return {\n schemaVersion: 1,\n generatedAt: nowIso,\n mode,\n scanned: 0,\n eligible: 0,\n findings: [],\n counts: emptyCounts,\n appliedCount: 0,\n reviewItemsOpened: 0,\n elapsedMs: Date.now() - startTime,\n skippedReason: \"scan_disabled\",\n };\n }\n\n const { storage, namespace } = await resolveScanStorage(deps, deps.namespace?.trim() || undefined);\n const lookup = deps.embeddingLookupFactory\n ? deps.embeddingLookupFactory(storage)\n : deps.embeddingLookup;\n\n let all: MemoryFile[];\n try {\n all = await storage.readAllMemories();\n } catch (err) {\n log.warn(\n `[preference-drift] failed to read memories: ${err instanceof Error ? err.message : String(err)}`,\n );\n all = [];\n }\n\n const byId = new Map<string, MemoryFile>();\n for (const m of all) {\n const id = m.frontmatter.id;\n if (typeof id === \"string\" && id.length > 0) byId.set(id, m);\n }\n\n const minAgeMs = cfg.minAgeDays * DAY_MS;\n const eligible = all.filter((m) => {\n const fm = m.frontmatter;\n if (fm.category !== \"preference\") return false;\n if (CANDIDATE_STATUSES[fm.status ?? \"active\"] !== true) return false;\n if (typeof fm.id !== \"string\" || fm.id.length === 0) return false;\n if (!m.content || m.content.trim().length === 0) return false;\n const bornMs = tsMs(fm.created) ?? tsMs(fm.updated);\n if (bornMs === null) return false;\n return nowMs - bornMs >= minAgeMs;\n });\n\n const candidates = [...eligible].sort(compareCandidates).slice(0, cfg.maxCandidatesPerRun);\n\n const report: PreferenceDriftReport = {\n schemaVersion: 1,\n generatedAt: nowIso,\n mode,\n namespace,\n scanned: candidates.length,\n eligible: eligible.length,\n findings: [],\n counts: { ...emptyCounts },\n appliedCount: 0,\n reviewItemsOpened: 0,\n elapsedMs: 0,\n };\n\n const windowStartMs = nowMs - cfg.lookbackDays * DAY_MS;\n // One judge cache per run so the module-level singleton never leaks across\n // namespaces or scans.\n const judgeCache = new Map<string, ContradictionJudgeResult>();\n const driftedPairs: Array<{ preference: MemoryFile; evidenceId: string; finding: PreferenceDriftFinding; rationale: string; confidence: number }> = [];\n const stamps: Array<{ memory: MemoryFile; patch: { driftState?: \"stale\"; lastCorroborated?: string }; reasonCode: string }> = [];\n\n for (const preference of candidates) {\n const bornMs = tsMs(preference.frontmatter.created) ?? tsMs(preference.frontmatter.updated) ?? nowMs;\n const finding: PreferenceDriftFinding = {\n memoryId: preference.frontmatter.id,\n classification: \"stale\",\n ageDays: Math.floor((nowMs - bornMs) / DAY_MS),\n lastCorroborated: preference.frontmatter.lastCorroborated ?? null,\n reason: \"\",\n evidence: [],\n };\n\n if (!lookup) {\n finding.classification = \"skipped\";\n finding.skipped = \"backend_unavailable\";\n finding.reason = \"no evidence lookup is configured, so corroboration cannot be checked\";\n report.findings.push(finding);\n report.counts.skipped += 1;\n continue;\n }\n\n const evidence = await gatherEvidence(preference, lookup, byId, windowStartMs, nowMs);\n if (!evidence.ok) {\n finding.classification = \"skipped\";\n finding.skipped = evidence.reason;\n finding.reason = \"evidence lookup backend was unavailable — not classified as stale\";\n report.findings.push(finding);\n report.counts.skipped += 1;\n continue;\n }\n finding.evidence = evidence.hits;\n\n if (evidence.hits.length === 0) {\n finding.classification = \"stale\";\n finding.reason = `no corroborating evidence in the last ${cfg.lookbackDays} days`;\n report.findings.push(finding);\n report.counts.stale += 1;\n stamps.push({ memory: preference, patch: { driftState: \"stale\" }, reasonCode: \"drift_stale\" });\n continue;\n }\n\n // The judge call happens only when candidate evidence exists.\n const judgeInputs: ContradictionJudgeInput[] = evidence.hitMemories.map((hit) => ({\n memoryIdA: preference.frontmatter.id,\n memoryIdB: hit.frontmatter.id,\n textA: preference.content,\n textB: hit.content,\n categoryA: preference.frontmatter.category,\n categoryB: hit.frontmatter.category,\n }));\n const judged = await judgeContradictionPairs(\n judgeInputs,\n deps.config,\n deps.localLlm,\n deps.fallbackLlm,\n judgeCache,\n );\n // Preserve evidence order (score desc) so the verdict scan is deterministic\n // rather than dependent on Map iteration of the judge's keyed results.\n const orderedVerdicts: ContradictionJudgeResult[] = [];\n for (const input of judgeInputs) {\n for (const result of judged.results.values()) {\n if (result.memoryIdA === input.memoryIdA && result.memoryIdB === input.memoryIdB) {\n orderedVerdicts.push(result);\n break;\n }\n }\n }\n\n const outcome = classifyFromVerdicts(orderedVerdicts);\n finding.classification = outcome.classification;\n finding.reason = outcome.reason;\n if (outcome.skipped) finding.skipped = outcome.skipped;\n report.findings.push(finding);\n report.counts[outcome.classification] += 1;\n\n if (outcome.classification === \"corroborated\") {\n stamps.push({\n memory: preference,\n patch: { lastCorroborated: nowIso, driftState: undefined },\n reasonCode: \"drift_corroborated\",\n });\n } else if (outcome.classification === \"stale\") {\n stamps.push({ memory: preference, patch: { driftState: \"stale\" }, reasonCode: \"drift_stale\" });\n } else if (outcome.classification === \"drifted\" && outcome.driftedAgainst) {\n const verdict = orderedVerdicts.find((v) => v.verdict === \"contradicts\");\n driftedPairs.push({\n preference,\n evidenceId: outcome.driftedAgainst,\n finding,\n rationale: verdict?.rationale ?? outcome.reason,\n confidence: verdict?.confidence ?? 0,\n });\n }\n }\n\n if (mode === \"shadow\") {\n report.elapsedMs = Date.now() - startTime;\n return report;\n }\n\n let writes = 0;\n for (const stamp of stamps) {\n try {\n // `driftState: undefined` is an explicit clear: writeMemoryFrontmatter\n // merges the patch over existing frontmatter, and the serializer omits\n // undefined fields, so a corroborated preference loses its stale mark.\n await storage.writeMemoryFrontmatter(stamp.memory, { ...stamp.patch, updated: nowIso }, {\n at: now,\n actor: DRIFT_ACTOR,\n reasonCode: stamp.reasonCode,\n ruleVersion: DRIFT_RULE_VERSION,\n });\n writes += 1;\n report.appliedCount += 1;\n } catch (err) {\n log.warn(\n `[preference-drift] stamp ${stamp.reasonCode} on ${stamp.memory.frontmatter.id} failed: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n }\n\n if (driftedPairs.length > 0) {\n const queueEntries: Array<Omit<ContradictionPair, \"pairId\"> & { memoryIds: [string, string] }> =\n driftedPairs.map((d) => ({\n memoryIds: [d.preference.frontmatter.id, d.evidenceId],\n kind: \"preference-drift\",\n // A drift finding IS a detected conflict, so the honest verdict is\n // `contradicts`; `kind` is what distinguishes it from a pair the\n // contradiction scan produced. Existing review surfaces render it\n // unchanged.\n verdict: \"contradicts\",\n rationale: d.rationale,\n confidence: d.confidence,\n detectedAt: nowIso,\n memoryContentHashes: {\n [d.preference.frontmatter.id]: computeMemoryContentHash(\n d.preference.content,\n d.preference.frontmatter.category,\n ),\n },\n namespace,\n }));\n const written = writePairs(deps.memoryDir, queueEntries);\n report.reviewItemsOpened = written.length;\n report.appliedCount += written.length;\n for (const entry of written) {\n const match = driftedPairs.find((d) => d.preference.frontmatter.id === entry.memoryIds[0]);\n if (match) match.finding.reviewPairId = entry.pairId;\n }\n }\n\n if (writes > 0) {\n // Frontmatter stamps bypass the extraction write pipeline, so bump the\n // shared corpus version out of band — otherwise hot recall caches keep\n // serving pre-stamp frontmatter and the damping stage never sees the new\n // `driftState` (§25/§31).\n bumpMemoryCorpusVersionForDir(storage.dir);\n if (storage.dir !== deps.memoryDir) bumpMemoryCorpusVersionForDir(deps.memoryDir);\n }\n try {\n await writeJsonFileAtomic(driftMarkerPath(deps.memoryDir), {\n schemaVersion: 1,\n lastRunAt: nowIso,\n lastApplyAt: nowIso,\n appliedCount: report.appliedCount,\n } satisfies PreferenceDriftMarker);\n } catch (err) {\n log.warn(\n `[preference-drift] failed to persist run marker: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n\n report.elapsedMs = Date.now() - startTime;\n return report;\n}\n\n// ── Review resolution ────────────────────────────────────────────────────────\n\nexport interface PreferenceDriftResolutionOptions {\n /** Replacement preference text. Required for `supersede`. */\n mergedContent?: string;\n /** Fires after a resolution leaves a durable memory mutation in the namespace. */\n onMemoryWritten?: (namespace: string | undefined, storageDir: string) => void;\n now?: Date;\n}\n\nexport interface PreferenceDriftResolutionResult {\n affectedIds: string[];\n message: string;\n}\n\n/**\n * Execute a `kind: \"preference-drift\"` resolution verb.\n *\n * The first memory id on the item is the aging preference; the second is the\n * evidence that pointed away from it. Only the preference is ever mutated —\n * the evidence memory is a witness, not a target.\n *\n * - `keep` — the preference still holds: stamp `lastCorroborated`, clear\n * `driftState`.\n * - `supersede` — write the corrected preference and retire the old one\n * through the normal supersession path.\n * - `archive` — demote the preference to `archived`. Demotion, never\n * deletion; page versioning snapshots the overwrite.\n *\n * Callers resolve the pair record itself (`resolvePair`); this function owns\n * only the memory-side effects.\n */\nexport async function resolvePreferenceDrift(\n storage: StorageManager,\n pair: Pick<ContradictionPair, \"pairId\" | \"memoryIds\" | \"namespace\">,\n verb: \"keep\" | \"supersede\" | \"archive\",\n options: PreferenceDriftResolutionOptions = {},\n): Promise<PreferenceDriftResolutionResult> {\n const now = options.now ?? new Date();\n const nowIso = now.toISOString();\n const preferenceId = pair.memoryIds[0];\n const preference = await storage.getMemoryById(preferenceId);\n if (!preference) {\n return { affectedIds: [], message: `Preference ${preferenceId} not found; not resolving ${pair.pairId}` };\n }\n\n const touched = (): void => {\n try {\n options.onMemoryWritten?.(pair.namespace, storage.dir);\n } catch (err) {\n log.warn(\n `[preference-drift] catalog write touch failed for ${pair.pairId}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n };\n\n if (verb === \"keep\") {\n await storage.writeMemoryFrontmatter(\n preference,\n { lastCorroborated: nowIso, driftState: undefined, updated: nowIso },\n { at: now, actor: DRIFT_ACTOR, reasonCode: \"drift_kept\", ruleVersion: DRIFT_RULE_VERSION },\n );\n bumpMemoryCorpusVersionForDir(storage.dir);\n touched();\n return { affectedIds: [preferenceId], message: `Preference ${preferenceId} confirmed still current` };\n }\n\n if (verb === \"archive\") {\n const archivedPath = await storage.archiveMemory(preference, {\n at: now,\n actor: DRIFT_ACTOR,\n reasonCode: \"drift_archived\",\n ruleVersion: DRIFT_RULE_VERSION,\n relatedMemoryIds: [pair.memoryIds[1]],\n });\n if (archivedPath === null) {\n return { affectedIds: [], message: `Preference ${preferenceId} could not be archived; not resolving` };\n }\n bumpMemoryCorpusVersionForDir(storage.dir);\n touched();\n return { affectedIds: [preferenceId], message: `Preference ${preferenceId} archived` };\n }\n\n const replacementText = options.mergedContent?.trim();\n if (!replacementText) {\n return {\n affectedIds: [],\n message: \"supersede requires mergedContent carrying the updated preference; no memories changed\",\n };\n }\n\n // Sealed-envelope write: the replacement text is user- or LLM-supplied, so\n // compose with salvage and warn-log any dropped optional field rather than\n // failing the whole resolution on a cosmetic value.\n const envelope = composeMemoryEnvelope(\n {\n content: replacementText,\n category: \"preference\",\n confidence: preference.frontmatter.confidence ?? 0.8,\n tags: [\"preference-drift\", \"supersede\"],\n entityRef: preference.frontmatter.entityRef,\n },\n { source: DRIFT_ACTOR },\n { salvage: true },\n );\n if (envelope.salvageNotes.length > 0) {\n log.warn(`[preference-drift] supersede write salvaged invalid fields: ${envelope.salvageNotes.join(\"; \")}`);\n }\n const written = await storage.writeSealedMemory(envelope, {\n actor: DRIFT_ACTOR,\n lineage: [preferenceId],\n // `update` is the operator for \"newer version of the same claim\" — the\n // drift replacement restates one preference, it does not merge two.\n derivedVia: \"update\",\n });\n // A tombstone-blocked replacement is NOT active, so superseding the old\n // preference to it would retire the only live copy (§14: never destroy old\n // state before the new state is confirmed viable).\n if (written.tombstoneBlocked) {\n return {\n affectedIds: [],\n message: `Replacement preference for ${pair.pairId} was tombstone-blocked (pending_review); not resolving — original kept active`,\n };\n }\n const superseded = await storage.supersedeMemory(\n preferenceId,\n written.id,\n `preference drift resolved by supersede (${pair.pairId})`,\n undefined,\n { actor: DRIFT_ACTOR },\n );\n bumpMemoryCorpusVersionForDir(storage.dir);\n touched();\n if (!superseded) {\n return {\n affectedIds: [written.id],\n message: `Replacement ${written.id} written but superseding ${preferenceId} failed; both remain — re-run resolution`,\n };\n }\n return {\n affectedIds: [preferenceId, written.id],\n message: `Preference ${preferenceId} superseded by ${written.id}`,\n };\n}\n","/**\n * Resolution Verbs — executes user-chosen resolution actions on contradiction pairs (issue #520).\n *\n * All resolution paths delegate to StorageManager.supersedeMemory. Do not\n * reimplement supersession logic here (rule 22: deduplicate resolution).\n */\n\nimport { log } from \"../logger.js\";\nimport { composeMemoryEnvelope } from \"../write-envelope.js\";\nimport type { StorageManager } from \"../storage.js\";\nimport type { MemoryCategory, MemoryFile } from \"../types.js\";\nimport type { ResolutionVerb } from \"./contradiction-review.js\";\nimport {\n CONTRADICTION_VERBS,\n PREFERENCE_DRIFT_VERBS,\n readPair,\n resolvePair,\n} from \"./contradiction-review.js\";\nimport { resolvePreferenceDrift } from \"../preferences/preference-drift.js\";\n\nexport interface ResolutionResult {\n pairId: string;\n verb: ResolutionVerb;\n /** Memory IDs affected by the resolution. */\n affectedIds: string[];\n /** Human-readable status. */\n message: string;\n}\n\nexport interface ExecuteResolutionOptions {\n /** Existing merged memory to supersede both source memories to. */\n mergedMemoryId?: string;\n /** Content for a new merged memory. Required for merge when mergedMemoryId is omitted. */\n mergedContent?: string;\n /** Category for a newly created merged memory. Defaults to the shared source category, or fact. */\n mergedCategory?: MemoryCategory;\n /** Resolve storage for the pair namespace, or the default namespace for legacy unscoped pairs. */\n storageForNamespace?: (namespace: string | undefined) => StorageManager | Promise<StorageManager>;\n /**\n * Best-effort hook invoked after a contradiction resolution leaves a durable\n * mutation in the namespace's memory files (issue #1499 sweep, NH1dX / NH3X3).\n * Every mutating verb — `merge` (creates a new memory and supersedes both\n * sources), `keep-a`, and `keep-b` (supersede the losing source + rewrite\n * frontmatter) — writes directly to the pair's (possibly DYNAMIC) namespace\n * storage, bypassing the extraction write path that records catalog writes. So\n * without this the namespace's `lastWriteAt` stays stale and QMD maintenance /\n * `writtenSince` can skip a namespace whose only post-write mutation is\n * resolving a contradiction. It fires after the resolution commits, or after a\n * failed resolution/rollback path when durable memory changes are still left on\n * disk. If a failure rolls back cleanly, this is never called, so the catalog\n * never records a write that did not survive (rule #25). Non-mutating verbs\n * (`both-valid`, `needs-more-context`) never trigger it. Callers wire this to\n * `Orchestrator.recordCatalogWrite(namespace, storageDir)`. Must be\n * failure-tolerant: it is fire-and-forget and must never affect resolution.\n */\n onMergedMemoryWritten?: (namespace: string | undefined, storageDir: string) => void;\n}\n\n/**\n * Every verb the `review_resolve` surface accepts, across both review-item\n * kinds (issue #2371). This is a *surface-level* gate only: per-kind validity\n * is enforced inside {@link executeResolution}, which is the first place the\n * item's `kind` is known. Callers therefore reject an unknown verb early and\n * a cross-kind verb precisely.\n */\nconst VALID_VERBS: readonly ResolutionVerb[] = [...CONTRADICTION_VERBS, ...PREFERENCE_DRIFT_VERBS];\n\nexport function isValidResolutionVerb(value: string): value is ResolutionVerb {\n return VALID_VERBS.includes(value as ResolutionVerb);\n}\n\n/**\n * Execute a resolution verb on a contradiction pair.\n *\n * - `keep-a`: Supersede B, keep A active.\n * - `keep-b`: Supersede A, keep B active.\n * - `merge`: Create or verify a real merged memory, then supersede both inputs.\n * - `both-valid`: Mark pair as reviewed; no memories are superseded.\n * - `needs-more-context`: Defer; no action, short cooldown.\n */\nexport async function executeResolution(\n memoryDir: string,\n storage: StorageManager,\n pairId: string,\n verb: ResolutionVerb,\n options: ExecuteResolutionOptions = {},\n): Promise<ResolutionResult> {\n if (typeof verb !== \"string\" || !isValidResolutionVerb(verb)) {\n throw new Error(`Invalid contradiction resolution verb: ${String(verb)}`);\n }\n\n const pair = readPair(memoryDir, pairId);\n if (!pair) {\n return { pairId, verb, affectedIds: [], message: `Pair ${pairId} not found` };\n }\n\n if (pair.namespace && !options.storageForNamespace) {\n throw new Error(\n \"contradiction resolution requires storageForNamespace for namespaced pairs so callers resolve the correct namespace storage\",\n );\n }\n\n const resolutionStorage = options.storageForNamespace\n ? await options.storageForNamespace(pair.namespace)\n : storage;\n\n if (pair.resolution && pair.resolution !== \"needs-more-context\") {\n return { pairId, verb, affectedIds: [], message: `Pair already resolved with verb \"${pair.resolution}\"` };\n }\n // Verb validity is per review-item kind (issue #2371). A preference-drift\n // item never accepts keep-a/keep-b/merge (there is no \"B\" to keep — the\n // second id is witness evidence, not a competing claim), and a contradiction\n // pair never accepts keep/supersede/archive. Rejecting the cross-kind verb\n // here, after the record is loaded, is the only place both kinds are known.\n const isDriftItem = pair.kind === \"preference-drift\";\n const verbMatchesKind = isDriftItem\n ? PREFERENCE_DRIFT_VERBS.includes(verb)\n : CONTRADICTION_VERBS.includes(verb);\n if (!verbMatchesKind) {\n const allowed = (isDriftItem ? PREFERENCE_DRIFT_VERBS : CONTRADICTION_VERBS).join(\", \");\n return {\n pairId,\n verb,\n affectedIds: [],\n message: `Verb \"${verb}\" is not valid for a ${isDriftItem ? \"preference-drift\" : \"contradiction\"} item. Valid: ${allowed}`,\n };\n }\n\n if (isDriftItem) {\n const outcome = await resolvePreferenceDrift(\n resolutionStorage,\n pair,\n verb as \"keep\" | \"supersede\" | \"archive\",\n {\n mergedContent: options.mergedContent,\n onMemoryWritten: options.onMergedMemoryWritten,\n },\n );\n // Only record the terminal resolution when memories actually changed;\n // a refused resolution must stay actionable in the queue.\n if (outcome.affectedIds.length > 0) resolvePair(memoryDir, pairId, verb);\n return { pairId, verb, affectedIds: outcome.affectedIds, message: outcome.message };\n }\n\n\n const [idA, idB] = pair.memoryIds;\n const affectedIds: string[] = [];\n let message = \"\";\n let supersedeFailed = false;\n let rollbackAfterResolveFailure: (() => Promise<boolean>) | null = null;\n // Deferred catalog-write touch for any resolution that leaves durable namespace\n // memory mutations (issue #1499 sweep, NH1dX / NH3X3). Rule #25: never record a\n // catalog touch for a write that is fully rolled back. Successful mutating\n // resolutions invoke it after `resolvePair` persists. Failed paths invoke it\n // only when rollback inspection shows the namespace still differs from the\n // pre-mutation snapshot.\n let recordCatalogWriteTouch: (() => void) | null = null;\n // Returns the deferred touch fn for a mutating verb (or null when the caller\n // wired no catalog hook), so each branch assigns `recordCatalogWriteTouch`\n // directly in the function body — keeping TS control-flow narrowing intact at\n // the post-commit invocation below.\n const buildCatalogTouch = (): (() => void) | null => {\n if (!options.onMergedMemoryWritten) return null;\n const onMergedMemoryWritten = options.onMergedMemoryWritten;\n const namespace = pair.namespace;\n const storageDir = resolutionStorage.dir;\n return () => onMergedMemoryWritten(namespace, storageDir);\n };\n const catalogWriteTouch = buildCatalogTouch();\n const recordCatalogWriteTouchSafely = (context: string, touch = catalogWriteTouch): void => {\n if (!touch) return;\n try {\n touch();\n } catch (err) {\n log.warn(\n \"[contradiction-resolution] catalog write touch failed for pair=%s context=%s: %s\",\n pairId,\n context,\n err instanceof Error ? err.message : err,\n );\n }\n };\n const touchCatalogIfRollbackLeftChange = async (\n context: string,\n snapshots: MemoryFile[],\n replacement?: Extract<MergeReplacement, { ok: true }>,\n ): Promise<void> => {\n if (!catalogWriteTouch) return;\n if (await rollbackLeftDurableMutation(resolutionStorage, snapshots, replacement)) {\n recordCatalogWriteTouchSafely(context);\n }\n };\n\n switch (verb) {\n case \"keep-a\": {\n const keepTarget = await validateKeepTarget(resolutionStorage, pairId, idA);\n if (!keepTarget.ok) {\n supersedeFailed = true;\n message = keepTarget.message;\n break;\n }\n const sourceB = await loadSourceSnapshot(resolutionStorage, idB);\n const ok = sourceB\n ? await supersedeSafe(resolutionStorage, idB, idA, \"contradiction-resolution:keep-a\")\n : false;\n if (ok) {\n affectedIds.push(idB);\n rollbackAfterResolveFailure = async () =>\n restoreMemorySnapshot(resolutionStorage, sourceB!, \"contradiction-resolution:keep-a-rollback\");\n // keep-a superseded idB in this namespace — record a catalog touch once\n // the resolution durably commits (NH3X3).\n recordCatalogWriteTouch = catalogWriteTouch;\n message = `Kept ${idA}, superseded ${idB}`;\n }\n else {\n supersedeFailed = true;\n const rolledBack = sourceB\n ? await restoreMemorySnapshot(resolutionStorage, sourceB, \"contradiction-resolution:keep-a-rollback\")\n : false;\n if (sourceB && !rolledBack) {\n await touchCatalogIfRollbackLeftChange(\"keep-a-rollback-incomplete\", [sourceB]);\n }\n message = rolledBack\n ? `Supersede failed for ${idB}; restored ${idB} and did not resolve`\n : `Supersede failed for ${idB}; rollback incomplete for ${idB} and pair is not resolved`;\n }\n break;\n }\n case \"keep-b\": {\n const keepTarget = await validateKeepTarget(resolutionStorage, pairId, idB);\n if (!keepTarget.ok) {\n supersedeFailed = true;\n message = keepTarget.message;\n break;\n }\n const sourceA = await loadSourceSnapshot(resolutionStorage, idA);\n const ok = sourceA\n ? await supersedeSafe(resolutionStorage, idA, idB, \"contradiction-resolution:keep-b\")\n : false;\n if (ok) {\n affectedIds.push(idA);\n rollbackAfterResolveFailure = async () =>\n restoreMemorySnapshot(resolutionStorage, sourceA!, \"contradiction-resolution:keep-b-rollback\");\n // keep-b superseded idA in this namespace — record a catalog touch once\n // the resolution durably commits (NH3X3).\n recordCatalogWriteTouch = catalogWriteTouch;\n message = `Kept ${idB}, superseded ${idA}`;\n }\n else {\n supersedeFailed = true;\n const rolledBack = sourceA\n ? await restoreMemorySnapshot(resolutionStorage, sourceA, \"contradiction-resolution:keep-b-rollback\")\n : false;\n if (sourceA && !rolledBack) {\n await touchCatalogIfRollbackLeftChange(\"keep-b-rollback-incomplete\", [sourceA]);\n }\n message = rolledBack\n ? `Supersede failed for ${idA}; restored ${idA} and did not resolve`\n : `Supersede failed for ${idA}; rollback incomplete for ${idA} and pair is not resolved`;\n }\n break;\n }\n case \"merge\": {\n const replacement = await prepareMergeReplacement(resolutionStorage, pairId, idA, idB, options);\n if (!replacement.ok) {\n supersedeFailed = true;\n message = replacement.message;\n break;\n }\n\n const okA = await supersedeSafe(resolutionStorage, idA, replacement.mergedId, \"contradiction-resolution:merge\");\n if (!okA) {\n supersedeFailed = true;\n const rolledBackA = await restoreMemorySnapshot(resolutionStorage, replacement.sourceA);\n message = rolledBackA\n ? `Merge failed for ${idA}; restored ${idA} and did not resolve`\n : `Merge failed for ${idA}; rollback incomplete for ${idA} and pair is not resolved`;\n if (rolledBackA) {\n await cleanupCreatedReplacement(resolutionStorage, replacement);\n }\n else {\n await touchCatalogIfRollbackLeftChange(\"merge-first-rollback-incomplete\", [replacement.sourceA], replacement);\n }\n break;\n }\n\n const okB = await supersedeSafe(resolutionStorage, idB, replacement.mergedId, \"contradiction-resolution:merge\");\n if (!okB) {\n supersedeFailed = true;\n const rolledBackA = await restoreMemorySnapshot(resolutionStorage, replacement.sourceA);\n const rolledBackB = await restoreMemorySnapshot(resolutionStorage, replacement.sourceB);\n message = rolledBackA && rolledBackB\n ? `Merge failed for ${idB}; restored ${idA} and ${idB} and did not resolve`\n : `Merge failed for ${idB}; rollback incomplete for ${[\n rolledBackA ? undefined : idA,\n rolledBackB ? undefined : idB,\n ].filter(Boolean).join(\", \")} and pair is not resolved`;\n if (rolledBackA && rolledBackB) {\n await cleanupCreatedReplacement(resolutionStorage, replacement);\n }\n else {\n await touchCatalogIfRollbackLeftChange(\n \"merge-second-rollback-incomplete\",\n [replacement.sourceA, replacement.sourceB],\n replacement,\n );\n }\n break;\n }\n\n affectedIds.push(idA, idB);\n rollbackAfterResolveFailure = async () => {\n const rolledBackA = await restoreMemorySnapshot(resolutionStorage, replacement.sourceA);\n const rolledBackB = await restoreMemorySnapshot(resolutionStorage, replacement.sourceB);\n if (rolledBackA && rolledBackB) {\n await cleanupCreatedReplacement(resolutionStorage, replacement);\n }\n return rolledBackA && rolledBackB;\n };\n // Catalog write touch (issue #1499 sweep): the merge supersedes BOTH sources\n // (and, when created, writes a fresh merged memory) in the pair's (possibly\n // dynamic) namespace storage — but the resolution is not durable yet\n // (resolvePair persists below, and a failure rolls the merge back). Defer\n // the touch so it fires ONLY after the resolution commits past the rollback\n // point (NH1dX, rule #25). Arm it for EVERY successful merge — even reusing\n // an existing merged-id still supersedes both sources, a namespace mutation\n // that must refresh `lastWriteAt` (NH3X3). Otherwise a dynamic namespace\n // whose only durable mutation is a contradiction merge stays invisible to\n // QMD maintenance / `writtenSince`. Best-effort on the caller side.\n recordCatalogWriteTouch = catalogWriteTouch;\n message = `Both memories superseded by merged ${replacement.mergedId}`;\n break;\n }\n case \"both-valid\": {\n message = \"Pair marked as both-valid; cooldown applied\";\n break;\n }\n case \"needs-more-context\": {\n message = \"Deferred; no action taken, short cooldown applied\";\n break;\n }\n }\n\n if (!supersedeFailed) {\n let resolved = false;\n try {\n resolved = resolvePair(memoryDir, pairId, verb) !== null;\n } catch (err) {\n log.warn(\n \"[contradiction-resolution] failed to persist pair=%s verb=%s: %s\",\n pairId,\n verb,\n err instanceof Error ? err.message : err,\n );\n }\n if (!resolved) {\n if (rollbackAfterResolveFailure) {\n const rolledBack = await rollbackAfterResolveFailure();\n affectedIds.length = 0;\n message = rolledBack\n ? `Resolution persistence failed; rolled back memory changes and did not resolve ${pairId}`\n : \"Resolution persistence failed; rollback incomplete and pair is not resolved\";\n if (!rolledBack && recordCatalogWriteTouch) {\n recordCatalogWriteTouchSafely(\"resolve-persistence-rollback-incomplete\", recordCatalogWriteTouch);\n }\n } else {\n message = \"Resolution persistence failed; pair is not resolved\";\n }\n } else if (recordCatalogWriteTouch) {\n // The resolution durably committed (memory mutated AND the resolution\n // persisted past the rollback point). Only now is it safe to record the\n // catalog write for the namespace mutation (NH1dX / NH3X3, rule #25).\n // Best-effort: the caller's callback swallows errors; guard here so a\n // throwing callback never derails a successful resolution.\n recordCatalogWriteTouchSafely(\"resolved\", recordCatalogWriteTouch);\n }\n }\n log.info(\"[contradiction-resolution] pair=%s verb=%s affected=%d\", pairId, verb, affectedIds.length);\n return { pairId, verb, affectedIds, message };\n}\n\ntype MergeReplacement =\n | {\n ok: true;\n mergedId: string;\n sourceA: MemoryFile;\n sourceB: MemoryFile;\n created: boolean;\n }\n | {\n ok: false;\n message: string;\n };\n\nasync function prepareMergeReplacement(\n storage: StorageManager,\n pairId: string,\n idA: string,\n idB: string,\n options: ExecuteResolutionOptions,\n): Promise<MergeReplacement> {\n const sourceA = await storage.getMemoryById(idA);\n const sourceB = await storage.getMemoryById(idB);\n if (!sourceA || !sourceB) {\n return { ok: false, message: `Merge requires both source memories to exist; not resolving ${pairId}` };\n }\n\n const requestedMergedId = options.mergedMemoryId?.trim();\n if (requestedMergedId) {\n if (requestedMergedId === idA || requestedMergedId === idB) {\n return { ok: false, message: \"Merge replacement must be distinct from both source memories; not resolving\" };\n }\n const replacement = await storage.getMemoryById(requestedMergedId);\n if (!replacement) {\n return { ok: false, message: `Merged memory ${requestedMergedId} not found; not resolving` };\n }\n const replacementStatus = replacement.frontmatter.status ?? \"active\";\n if (replacementStatus !== \"active\") {\n return {\n ok: false,\n message: `Merged memory ${requestedMergedId} is ${replacementStatus}; not resolving`,\n };\n }\n return { ok: true, mergedId: requestedMergedId, sourceA, sourceB, created: false };\n }\n\n const mergedContent = options.mergedContent;\n if (typeof mergedContent !== \"string\" || mergedContent.trim().length === 0) {\n return {\n ok: false,\n message: \"Merge requires mergedMemoryId or mergedContent; no memories changed\",\n };\n }\n\n const category = options.mergedCategory ?? mergedMemoryCategory(sourceA, sourceB);\n let mergedId: string;\n try {\n // Sealed-envelope write (issue #1989 PR4): merged content is\n // LLM-produced — salvage; drops are warn-logged.\n const mergeEnvelope = composeMemoryEnvelope(\n {\n content: mergedContent,\n category,\n confidence: Math.min(sourceA.frontmatter.confidence ?? 0.8, sourceB.frontmatter.confidence ?? 0.8),\n tags: [\"contradiction-resolution\", \"merge\"],\n },\n { source: \"contradiction-resolution\" },\n { salvage: true },\n );\n if (mergeEnvelope.salvageNotes.length > 0) {\n log.warn(`contradiction-resolution write salvaged invalid fields: ${mergeEnvelope.salvageNotes.join(\"; \")}`);\n }\n const mergeResult = await storage.writeSealedMemory(mergeEnvelope, {\n actor: \"contradiction-resolution\",\n lineage: [idA, idB],\n derivedVia: \"merge\",\n });\n mergedId = mergeResult.id;\n if (mergeResult.tombstoneBlocked) {\n // #1645: merged content matched a tombstone (pending_review). Don't\n // supersede both sources to a non-active replacement — that retires\n // the only active copies. Clean up the pending merge and abort the pair.\n await cleanupMemoryId(storage, mergedId);\n return { ok: false, message: `Merged memory for ${pairId} was tombstone-blocked (pending_review); not resolving — sources kept active` };\n }\n } catch (err) {\n log.warn(\n \"[contradiction-resolution] merged memory creation failed for %s: %s\",\n pairId,\n err instanceof Error ? err.message : err,\n );\n return { ok: false, message: `Merged memory could not be created; not resolving ${pairId}` };\n }\n const replacement = await storage.getMemoryById(mergedId);\n if (!replacement) {\n await cleanupMemoryId(storage, mergedId);\n return { ok: false, message: `Merged memory ${mergedId} could not be verified; not resolving` };\n }\n return { ok: true, mergedId, sourceA, sourceB, created: true };\n}\n\nfunction mergedMemoryCategory(sourceA: MemoryFile, sourceB: MemoryFile): MemoryCategory {\n return sourceA.frontmatter.category === sourceB.frontmatter.category\n ? sourceA.frontmatter.category\n : \"fact\";\n}\n\ntype KeepTargetValidation =\n | { ok: true }\n | { ok: false; message: string };\n\nasync function validateKeepTarget(\n storage: StorageManager,\n pairId: string,\n keepId: string,\n): Promise<KeepTargetValidation> {\n const target = await loadSourceSnapshot(storage, keepId);\n if (!target) {\n return { ok: false, message: `Kept memory ${keepId} not found; not resolving ${pairId}` };\n }\n\n const status = target.frontmatter.status ?? \"active\";\n if (status !== \"active\") {\n return { ok: false, message: `Kept memory ${keepId} is ${status}; not resolving ${pairId}` };\n }\n\n return { ok: true };\n}\n\nasync function loadSourceSnapshot(storage: StorageManager, memoryId: string): Promise<MemoryFile | null> {\n try {\n return await storage.getMemoryById(memoryId);\n } catch (err) {\n log.warn(\n \"[contradiction-resolution] source snapshot failed for %s: %s\",\n memoryId,\n err instanceof Error ? err.message : err,\n );\n return null;\n }\n}\n\nasync function restoreMemorySnapshot(\n storage: StorageManager,\n memory: MemoryFile,\n reasonCode = \"contradiction-resolution:merge-rollback\",\n): Promise<boolean> {\n try {\n const current = await storage.getMemoryById(memory.frontmatter.id);\n if (!current) return false;\n const restoredFrontmatter: Partial<MemoryFile[\"frontmatter\"]> = {\n ...memory.frontmatter,\n status: memory.frontmatter.status,\n supersededBy: memory.frontmatter.supersededBy,\n supersededAt: memory.frontmatter.supersededAt,\n };\n return await storage.writeMemoryFrontmatter(current, restoredFrontmatter, {\n actor: \"contradiction-resolution\",\n reasonCode,\n });\n } catch (err) {\n log.warn(\n \"[contradiction-resolution] rollback failed for %s: %s\",\n memory.frontmatter.id,\n err instanceof Error ? err.message : err,\n );\n return false;\n }\n}\n\nasync function rollbackLeftDurableMutation(\n storage: StorageManager,\n snapshots: MemoryFile[],\n replacement?: Extract<MergeReplacement, { ok: true }>,\n): Promise<boolean> {\n for (const snapshot of snapshots) {\n try {\n const current = await storage.getMemoryById(snapshot.frontmatter.id);\n if (!current) return true;\n if (supersessionStateChanged(current, snapshot)) return true;\n } catch (err) {\n log.warn(\n \"[contradiction-resolution] rollback inspection failed for %s: %s\",\n snapshot.frontmatter.id,\n err instanceof Error ? err.message : err,\n );\n return true;\n }\n }\n\n if (replacement?.created) {\n try {\n return (await storage.getMemoryById(replacement.mergedId)) !== null;\n } catch (err) {\n log.warn(\n \"[contradiction-resolution] rollback replacement inspection failed for %s: %s\",\n replacement.mergedId,\n err instanceof Error ? err.message : err,\n );\n return true;\n }\n }\n\n return false;\n}\n\nfunction supersessionStateChanged(current: MemoryFile, snapshot: MemoryFile): boolean {\n return (\n current.frontmatter.status !== snapshot.frontmatter.status ||\n current.frontmatter.supersededBy !== snapshot.frontmatter.supersededBy ||\n current.frontmatter.supersededAt !== snapshot.frontmatter.supersededAt\n );\n}\n\nasync function cleanupCreatedReplacement(storage: StorageManager, replacement: Extract<MergeReplacement, { ok: true }>): Promise<void> {\n if (!replacement.created) return;\n await cleanupMemoryId(storage, replacement.mergedId);\n}\n\nasync function cleanupMemoryId(storage: StorageManager, memoryId: string): Promise<void> {\n try {\n const memory = await storage.getMemoryById(memoryId);\n const invalidated = await storage.invalidateMemory(memoryId);\n if (invalidated && memory?.frontmatter.category === \"fact\") {\n await storage.removeFactContentHashesForMemories([memory]);\n }\n } catch (err) {\n log.warn(\n \"[contradiction-resolution] cleanup failed for merged memory %s: %s\",\n memoryId,\n err instanceof Error ? err.message : err,\n );\n }\n}\n\nasync function supersedeSafe(\n storage: StorageManager,\n oldId: string,\n newId: string,\n reason: string,\n): Promise<boolean> {\n try {\n const result = await storage.supersedeMemory(oldId, newId, reason);\n if (result === false) {\n log.warn(\"[contradiction-resolution] supersede returned false for %s → %s\", oldId, newId);\n return false;\n }\n return true;\n } catch (err) {\n log.warn(\n \"[contradiction-resolution] supersede failed %s → %s: %s\",\n oldId,\n newId,\n err instanceof Error ? err.message : err,\n );\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,OAAO,UAAU;AAsBjB,IAAM,cAAc;AACpB,IAAM,qBAAqB;AAC3B,IAAM,SAAS,KAAK,KAAK,KAAK;AAG9B,IAAM,wBAAwB;AA+E9B,SAAS,gBAAgB,WAA2B;AAClD,SAAO,KAAK,KAAK,WAAW,SAAS,uBAAuB;AAC9D;AA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;AAAA,IACvC;AACA,WAAO;AAAA,EACT;AACF;","names":["replacement"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/entity-retrieval.ts"],"sourcesContent":["import { resolveNamespaceCapabilities } from \"./capabilities.js\";\nimport { renderAuthorityBoundContent } from \"./recall-context-composition.js\";\nimport { createHash } from \"node:crypto\";\nimport { sanitizeMemoryContent } from \"./sanitize.js\";\nimport { mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { collectNativeKnowledgeChunks, type NativeKnowledgeChunk } from \"./native-knowledge.js\";\nimport { compareEntityTimestamps, normalizeEntityName, type StorageManager } from \"./storage.js\";\nimport { normalizeEntityText, resolveRequestedEntitySectionKeys } from \"./entity-schema.js\";\nimport type { EntityStructuredSection, MemoryFile, PluginConfig, TranscriptEntry } from \"./types.js\";\nimport { truncateGraphemeSafe } from \"./whitespace.js\";\nimport { containsPhrase } from \"./entity-retrieval-boundaries.js\";\nimport {\n detectEntityQueryMode,\n isStructuralEntityFollowUpQuery,\n type EntityQueryMode,\n} from \"./entity-retrieval-i18n.js\";\nimport { buildOriginStructuredSections, sanitizeOriginatedFacts, type EntityOriginStructuredSection } from \"./entity-origin-fields.js\";\nimport {\n checkEntityRecallAbort,\n entityRecallSectionAbsent,\n yieldEntityRecallScan,\n yieldEntityRecallScanEvery,\n} from \"./entity-recall-cancellation.js\";\nconst ENTITY_INDEX_VERSION = 3;\nconst RECENT_TRANSCRIPT_LOOKBACK_HOURS = 24;\nconst INSTRUCTION_LIKE_RE = /\\b(always|never|must|should|remember to|do not|don't|process|workflow|template|checklist|instruction)\\b/i;\nconst METADATA_WRAPPER_RE = /^(source|context|metadata|notes?):/i;\nconst BELIEF_LEDGER_SECTION_KEY = \"belief_ledger\";\nconst BELIEF_LEDGER_FACT_RE = /^claim=([^;]+);\\s*status=([^;]+);\\s*updatedAt=([^;]+);\\s*(.+)$/;\ntype EntityMentionIndexEntry = {\n canonicalId: string;\n name: string;\n type: string;\n summary?: string;\n aliases: string[];\n facts: string[];\n timelineFacts: string[];\n timelineFactOrigins?: Array<string | undefined>;\n structuredSections: EntityOriginStructuredSection[];\n timeline: Array<{\n timestamp: string;\n text: string;\n source?: string;\n sessionKey?: string;\n principal?: string;\n origin?: string;\n }>;\n relationships: Array<{ target: string; label: string }>;\n activity: Array<{ date: string; note: string }>;\n factCount: number;\n memorySnippets: string[]; memorySnippetOrigins?: Array<string | undefined>;\n nativeChunks: Array<{\n chunkId: string;\n title: string;\n sourceKind: NativeKnowledgeChunk[\"sourceKind\"];\n sourcePath: string;\n snippet: string;\n derivedDate?: string;\n }>;\n};\ntype EntityMentionIndex = {\n version: number;\n updatedAt: string;\n entityStatusVersion?: number;\n entities: EntityMentionIndexEntry[];\n};\ntype EntityCandidate = {\n entry: EntityMentionIndexEntry;\n alias: string;\n score: number;\n source: \"query\" | \"recent_turn\";\n};\ntype EntityHintSnippet = {\n text: string;\n score: number;\n kind: \"summary\" | \"fact\" | \"section\" | \"relationship\" | \"activity\" | \"memory\" | \"native\"; origin?: string;\n};\nexport interface BuildEntityRecallSectionOptions {\n config: PluginConfig;\n storage: StorageManager;\n namespaceStorage?: (namespace: string) => Promise<StorageManager>;\n query: string;\n recallNamespaces?: string[];\n recentTurns: number;\n maxHints: number;\n maxSupportingFacts: number;\n maxRelatedEntities: number;\n maxChars: number;\n transcriptEntries: TranscriptEntry[];\n originAuthorityEnabled?: boolean; untrustedOrigins?: readonly string[];\n /**\n * Cancels the build at its next checkpoint (issue #2291). Entity recall reads\n * every entity and memory file across the recalled namespaces, which is\n * minutes of work on a large or slow store; without this the scan kept running\n * after the recall that asked for it had been abandoned.\n */\n abortSignal?: AbortSignal;\n}\nfunction tokenize(value: string): string[] {\n return normalizeEntityText(value).split(/\\s+/).filter((token) => token.length >= 2);\n}\nfunction uniqueStrings(values: string[]): string[] {\n return [...new Set(values.map((value) => value.trim()).filter((value) => value.length > 0))];\n}\nfunction compactLine(value: string, maxLength: number = 220): string {\n const normalized = value.replace(/\\s+/g, \" \").trim();\n if (normalized.length <= maxLength) return normalized;\n return `${truncateGraphemeSafe(normalized, maxLength - 1).trimEnd()}…`;\n}\nfunction dedupeHintSnippetsByText(snippets: EntityHintSnippet[]): EntityHintSnippet[] {\n const deduped = new Map<string, EntityHintSnippet>();\n for (const snippet of snippets) {\n const key = normalizeEntityText(snippet.text);\n const existing = deduped.get(key);\n if (!existing) {\n deduped.set(key, snippet);\n continue;\n }\n if (existing.origin !== snippet.origin) {\n existing.origin = undefined;\n }\n }\n return [...deduped.values()];\n}\nfunction isBeliefLedgerSection(section: Pick<EntityStructuredSection, \"key\">): boolean {\n return normalizeEntityText(section.key).replace(/\\s+/g, \"_\") === BELIEF_LEDGER_SECTION_KEY;\n}\nfunction beliefLedgerFactKeys(sections: EntityStructuredSection[]): Set<string> {\n const keys = new Set<string>();\n for (const section of sections) {\n if (!isBeliefLedgerSection(section)) continue;\n for (const fact of section.facts) {\n keys.add(normalizeEntityText(fact));\n }\n }\n return keys;\n}\ntype RecalledEntityFact = { text: string; sourceIndex: number };\nfunction recallFactsForStructuredSection(section: EntityStructuredSection): RecalledEntityFact[] {\n if (!isBeliefLedgerSection(section)) {\n return section.facts.map((text, sourceIndex) => ({ text, sourceIndex }));\n }\n return currentActiveBeliefLedgerFactTexts(section.facts);\n}\nfunction currentActiveBeliefLedgerFactTexts(facts: string[]): RecalledEntityFact[] {\n const byClaim = new Map<string, { status: string; updatedAtMs: number; texts: RecalledEntityFact[] }>();\n for (const [sourceIndex, fact] of facts.entries()) {\n const match = BELIEF_LEDGER_FACT_RE.exec(fact.trim());\n if (!match) continue;\n const [, claimId, status, updatedAt, text] = match;\n const updatedAtMs = Date.parse(updatedAt);\n if (!claimId?.trim() || !status?.trim() || !Number.isFinite(updatedAtMs) || !text?.trim()) continue;\n const normalizedStatus = status.trim().toLowerCase();\n const normalizedClaimId = claimId.trim();\n const current = byClaim.get(normalizedClaimId);\n const inactiveTieWins =\n current &&\n updatedAtMs === current.updatedAtMs &&\n current.status === \"active\" &&\n normalizedStatus !== \"active\";\n if (!current || updatedAtMs > current.updatedAtMs || inactiveTieWins) {\n byClaim.set(normalizedClaimId, { status: normalizedStatus, updatedAtMs, texts: [{ text: text.trim(), sourceIndex }] });\n continue;\n }\n if (updatedAtMs === current.updatedAtMs && current.status === normalizedStatus) {\n current.texts.push({ text: text.trim(), sourceIndex });\n }\n }\n return [...byClaim.values()].flatMap((current) => current.status === \"active\" ? current.texts : []);\n}\nfunction relationLine(entry: EntityMentionIndexEntry, relationship: { target: string; label: string }): string {\n const normalizedLabel = relationship.label.replace(/\\s+/g, \" \").trim();\n if (normalizedLabel.length === 0) return `${entry.name} is connected to ${relationship.target}`;\n return `${entry.name} ${normalizedLabel} ${relationship.target}`;\n}\nfunction scoreAliasMatch(query: string, alias: string): number {\n const normalizedQuery = normalizeEntityText(query);\n const normalizedAlias = normalizeEntityText(alias);\n if (!normalizedAlias) return 0;\n if (normalizedQuery === normalizedAlias) return 10;\n if (containsPhrase(normalizedQuery, normalizedAlias)) return 8 + Math.min(normalizedAlias.split(/\\s+/).length, 3);\n const queryTokens = new Set(tokenize(normalizedQuery));\n const aliasTokens = tokenize(normalizedAlias);\n if (aliasTokens.length === 0) return 0;\n const overlap = aliasTokens.filter((token) => queryTokens.has(token)).length;\n if (overlap === 0) return 0;\n // Cross-entity contamination guard (#682 PR 2/3 R-2). For multi-token\n // aliases, partial-token overlap that hits ONLY shared common tokens\n // (like \"person\" in \"Person-A1\" / \"Person-B1\") would surface every\n // similarly-prefixed entity for a query that named only one. Require\n // that the overlap include at least one DISTINCTIVE alias token —\n // i.e. a token that does not also appear in any other entity's\n // alias-token vocabulary. Since this function is pure / per-pair, we\n // approximate \"distinctive\" by requiring the overlap to include at\n // least one token that is not a substring-of common identifier\n // affixes. The aliasTokens with length > 1 must contribute at least\n // one non-affix overlap. \"Alice Example\" ([\"alice\", \"example\"])\n // matched by query \"Tell me about Alice\" → overlap = 1 on \"alice\",\n // and \"alice\" is not an affix → score = 1. \"Person-A1\" tokens\n // [\"person\", \"a1\"] matched by query \"Who is Person-B1?\" → overlap =\n // 1 on \"person\", and \"person\" IS an affix → score = 0.\n if (aliasTokens.length > 1) {\n const nonAffixOverlap = aliasTokens.filter(\n (token) => queryTokens.has(token) && !isAliasAffixToken(token),\n ).length;\n if (nonAffixOverlap === 0) return 0;\n }\n return overlap;\n}\n/**\n * Tokens that look like type prefixes / generic role identifiers and\n * therefore should not, on their own, count as evidence that a\n * multi-token alias matches a query (#682 PR 2/3 R-2).\n *\n * Kept as a small explicit list rather than a regex so additions are\n * deliberate. The list mirrors the entity types listed in\n * `entity-schema.ts` plus the most common generic role identifiers\n * that frequently appear as the leading token of a display name.\n */\nconst ALIAS_AFFIX_TOKENS = new Set<string>([\n \"person\", \"people\", \"user\", \"users\", \"team\", \"teams\",\n \"project\", \"projects\", \"topic\", \"topics\",\n \"org\", \"orgs\", \"organization\", \"organizations\", \"company\", \"companies\",\n \"place\", \"places\", \"tool\", \"tools\", \"service\", \"services\",\n \"system\", \"systems\", \"agent\", \"agents\", \"bot\", \"bots\",\n]);\nfunction isAliasAffixToken(token: string): boolean {\n return ALIAS_AFFIX_TOKENS.has(token);\n}\nfunction isLikelyInstructionLike(value: string): boolean {\n return INSTRUCTION_LIKE_RE.test(value) || METADATA_WRAPPER_RE.test(value);\n}\nfunction sanitizeEntityFact(fact: string): string {\n const sanitized = sanitizeMemoryContent(fact);\n const clean = sanitized.text.trim();\n if (!clean) return \"\";\n if (INSTRUCTION_LIKE_RE.test(clean) && clean.length > 100) return \"\";\n return clean;\n}\nfunction scoreHintSnippet(snippet: EntityHintSnippet, queryTokens: string[]): EntityHintSnippet | null {\n const normalized = normalizeEntityText(snippet.text);\n if (!normalized) return null;\n const scored = { ...snippet };\n if (isLikelyInstructionLike(scored.text) && scored.kind !== \"summary\") {\n scored.score -= 3;\n }\n const overlap = queryTokens.filter((token) => normalized.includes(token)).length;\n scored.score += overlap * 2;\n if (METADATA_WRAPPER_RE.test(scored.text)) scored.score -= 2;\n if (scored.text.length <= 160) scored.score += 1;\n return scored.score > 0 ? scored : null;\n}\nfunction sortTimelineEntriesDesc(\n left: EntityMentionIndexEntry[\"timeline\"][number],\n right: EntityMentionIndexEntry[\"timeline\"][number],\n): number {\n const timestampOrder = compareEntityTimestamps(right.timestamp, left.timestamp);\n if (timestampOrder !== 0) {\n return timestampOrder;\n }\n return right.text.localeCompare(left.text);\n}\nfunction jaccardSimilarity(a: string, b: string): number {\n const aTokens = new Set(tokenize(a));\n const bTokens = new Set(tokenize(b));\n if (aTokens.size === 0 || bTokens.size === 0) return 0;\n let intersection = 0;\n for (const token of aTokens) {\n if (bTokens.has(token)) intersection += 1;\n }\n const union = new Set([...aTokens, ...bTokens]).size;\n return union === 0 ? 0 : intersection / union;\n}\nfunction buildAliasIndex(entries: EntityMentionIndexEntry[]): Map<string, EntityMentionIndexEntry[]> {\n const index = new Map<string, EntityMentionIndexEntry[]>();\n for (const entry of entries) {\n const aliases = uniqueStrings([entry.name, ...entry.aliases]).map(normalizeEntityText).filter(Boolean);\n for (const alias of aliases) {\n const existing = index.get(alias) ?? [];\n existing.push(entry);\n index.set(alias, existing);\n }\n }\n return index;\n}\nasync function readNativeChunks(\n config: PluginConfig,\n recallNamespaces?: string[],\n): Promise<NativeKnowledgeChunk[]> {\n if (!config.nativeKnowledge?.enabled) return [];\n return collectNativeKnowledgeChunks({\n workspaceDir: config.workspaceDir,\n memoryDir: config.memoryDir,\n config: config.nativeKnowledge,\n recallNamespaces: resolveNamespaceCapabilities(config).namespaces ? recallNamespaces : undefined,\n defaultNamespace: config.defaultNamespace,\n }).catch(() => []);\n}\nasync function resolveEntityIndexStorages(\n storage: StorageManager,\n config: PluginConfig,\n recallNamespaces?: string[],\n namespaceStorage?: (namespace: string) => Promise<StorageManager>,\n): Promise<StorageManager[]> {\n if (\n !resolveNamespaceCapabilities(config).namespaces ||\n !namespaceStorage ||\n !recallNamespaces ||\n recallNamespaces.length === 0\n ) {\n return [storage];\n }\n const storages: StorageManager[] = [];\n const seenDirs = new Set<string>();\n for (const namespace of uniqueStrings(recallNamespaces)) {\n try {\n const scopedStorage = await namespaceStorage(namespace);\n const storageDir = path.resolve(scopedStorage.dir);\n if (seenDirs.has(storageDir)) continue;\n seenDirs.add(storageDir);\n storages.push(scopedStorage);\n } catch {\n continue;\n }\n }\n return storages.length > 0 ? storages : [storage];\n}\nfunction entityIndexStatePath(storage: StorageManager): string {\n return path.join(storage.dir, \"state\", \"entity-mention-index.json\");\n}\n\nasync function readEntityIndexState(storage: StorageManager): Promise<EntityMentionIndex | null> {\n const raw = await readFile(entityIndexStatePath(storage), \"utf-8\").catch(() => \"\");\n if (!raw) return null;\n try {\n const parsed = JSON.parse(raw) as Partial<EntityMentionIndex>;\n if (parsed.version !== ENTITY_INDEX_VERSION || !Array.isArray(parsed.entities)) return null;\n return parsed as EntityMentionIndex;\n } catch {\n return null;\n }\n}\nasync function readCurrentPersistedEntityIndex(\n storage: StorageManager,\n config: PluginConfig,\n recallNamespaces?: string[],\n namespaceStorage?: (namespace: string) => Promise<StorageManager>,\n): Promise<EntityMentionIndex | null> {\n if (\n resolveNamespaceCapabilities(config).namespaces &&\n namespaceStorage &&\n recallNamespaces &&\n recallNamespaces.length > 0\n ) {\n return null;\n }\n const index = await readEntityIndexState(storage);\n if (!index || index.entityStatusVersion !== storage.getMemoryStatusVersion()) {\n return null;\n }\n return index;\n}\nconst namespaceEntityIndexCache = new Map<string, EntityMentionIndex>();\nconst MAX_NAMESPACE_ENTITY_INDEX_CACHE_ENTRIES = 32;\n\nfunction nativeEntityIndexRevision(chunks: NativeKnowledgeChunk[]): string {\n const projection = chunks.map((chunk) => [\n chunk.chunkId,\n chunk.sourcePath,\n chunk.title,\n chunk.sourceKind,\n uniqueStrings(chunk.aliases ?? []),\n compactLine(chunk.content, 180),\n chunk.derivedDate ?? null,\n ]);\n return createHash(\"sha256\").update(JSON.stringify(projection)).digest(\"hex\");\n}\nfunction namespaceEntityIndexCacheKey(\n storages: StorageManager[],\n recallNamespaces: string[],\n nativeRevision: string,\n): string {\n const namespaceKey = uniqueStrings(recallNamespaces).join(\"\\u001f\");\n const storageKey = storages\n .map((scopedStorage) => {\n const aliases = Object.entries(scopedStorage.entityAliases)\n .sort(([left], [right]) => left.localeCompare(right));\n return (\n `${path.resolve(scopedStorage.dir)}@${scopedStorage.getMemoryStatusVersion()}` +\n `:${scopedStorage.getMemoryCorpusVersion()}:${scopedStorage.getEntityMutationVersion()}` +\n `:${scopedStorage.hotCacheKeyId()}:${JSON.stringify(aliases)}`\n );\n })\n .join(\"\\u001f\");\n return `${namespaceKey}\\u001e${storageKey}\\u001e${nativeRevision}`;\n}\nfunction rememberNamespaceEntityIndex(key: string, index: EntityMentionIndex): void {\n if (namespaceEntityIndexCache.size >= MAX_NAMESPACE_ENTITY_INDEX_CACHE_ENTRIES) {\n const oldestKey = namespaceEntityIndexCache.keys().next().value;\n if (typeof oldestKey === \"string\") namespaceEntityIndexCache.delete(oldestKey);\n }\n namespaceEntityIndexCache.set(key, index);\n}\n\nasync function writeEntityIndexState(storage: StorageManager, index: EntityMentionIndex): Promise<void> {\n const statePath = entityIndexStatePath(storage);\n await mkdir(path.dirname(statePath), { recursive: true });\n const nextContent = JSON.stringify(index, null, 2) + \"\\n\";\n const currentContent = await readFile(statePath, \"utf-8\").catch(() => \"\");\n if (currentContent === nextContent) return;\n await writeFile(statePath, nextContent, \"utf-8\");\n}\n\nfunction nativePseudoCanonicalId(chunk: NativeKnowledgeChunk): string {\n return `native:${createHash(\"sha256\").update(chunk.sourcePath).digest(\"hex\").slice(0, 12)}`;\n}\n\nfunction createPseudoNativeEntry(chunk: NativeKnowledgeChunk): EntityMentionIndexEntry {\n const canonicalId = nativePseudoCanonicalId(chunk);\n return {\n canonicalId,\n name: chunk.title,\n type: chunk.sourceKind,\n aliases: uniqueStrings(chunk.aliases ?? []),\n facts: [],\n structuredSections: [],\n timelineFacts: [],\n timeline: [],\n relationships: [],\n activity: [],\n factCount: 0,\n memorySnippets: [],\n nativeChunks: [\n {\n chunkId: chunk.chunkId,\n title: chunk.title,\n sourceKind: chunk.sourceKind,\n sourcePath: chunk.sourcePath,\n snippet: compactLine(chunk.content, 180),\n derivedDate: chunk.derivedDate,\n },\n ],\n };\n}\n\nfunction mergeNativeChunk(entry: EntityMentionIndexEntry, chunk: NativeKnowledgeChunk): void {\n const existing = entry.nativeChunks.find((item) => item.chunkId === chunk.chunkId);\n if (existing) return;\n entry.nativeChunks.push({\n chunkId: chunk.chunkId,\n title: chunk.title,\n sourceKind: chunk.sourceKind,\n sourcePath: chunk.sourcePath,\n snippet: compactLine(chunk.content, 180),\n derivedDate: chunk.derivedDate,\n });\n entry.aliases = uniqueStrings([...entry.aliases, ...(chunk.aliases ?? [])]);\n}\n\nfunction hasFreshNativeExplicitMention(\n index: EntityMentionIndex,\n nativeChunks: NativeKnowledgeChunk[],\n query: string,\n): boolean {\n if (nativeChunks.length === 0) return false;\n const nativeCanonicalIds = new Set(nativeChunks.map(nativePseudoCanonicalId));\n const freshNativeIndex: EntityMentionIndex = {\n ...index,\n entities: [\n ...index.entities.filter((entry) => !nativeCanonicalIds.has(entry.canonicalId)),\n ...nativeChunks.map(createPseudoNativeEntry),\n ],\n };\n return resolveLanguageIndependentExplicitCandidates(freshNativeIndex, query).length > 0;\n}\n\nasync function buildEntityMentionIndex(\n storage: StorageManager,\n config: PluginConfig,\n recallNamespaces?: string[],\n namespaceStorage?: (namespace: string) => Promise<StorageManager>,\n nativeChunksOverride?: NativeKnowledgeChunk[],\n resolvedStorages?: StorageManager[],\n abortSignal?: AbortSignal,\n): Promise<EntityMentionIndex> {\n checkEntityRecallAbort(abortSignal);\n const storages = resolvedStorages ?? await resolveEntityIndexStorages(\n storage,\n config,\n recallNamespaces,\n namespaceStorage,\n );\n const shouldPersistIndex =\n storages.length === 1 && path.resolve(storages[0]!.dir) === path.resolve(storage.dir);\n const entityStatusVersionBefore = shouldPersistIndex ? storage.getMemoryStatusVersion() : undefined;\n const [previousIndex, entityFileSets, memorySets, nativeChunks] = await Promise.all([\n shouldPersistIndex ? readEntityIndexState(storage) : Promise.resolve(null),\n Promise.all(storages.map((scopedStorage) => scopedStorage.readAllEntityFiles({ abortSignal }))),\n Promise.all(storages.map((scopedStorage) => scopedStorage.readAllMemories({ abortSignal }))),\n nativeChunksOverride ? Promise.resolve(nativeChunksOverride) : readNativeChunks(config, recallNamespaces),\n ]);\n // The bulk reads now stop at their own scan boundaries (issue #2307); this\n // checkpoint still guards the (larger) indexing pass over their results.\n checkEntityRecallAbort(abortSignal);\n // Pair each entity with the storage that owns it (#1534): canonical ids must\n // reflect that store's aliases and historical migration mappings, never another\n // namespace's.\n const entityRecords = entityFileSets.flatMap((set, index) =>\n set.map((entity) => ({ entity, storage: storages[index]! })),\n );\n const memories = memorySets.flat();\n\n // The two passes over the corpus below never await real I/O, so without an\n // explicit yield they hold the event loop and no recall section deadline can\n // fire during them (issue #2291).\n let scanned = 0;\n const entities = new Map<string, EntityMentionIndexEntry>();\n for (const { entity, storage: entityStorage } of entityRecords) {\n scanned += 1;\n await yieldEntityRecallScanEvery(scanned, abortSignal);\n const canonicalId =\n typeof entityStorage.normalizeEntityName === \"function\"\n ? entityStorage.normalizeEntityName(entity.name, entity.type)\n : normalizeEntityName(entity.name, entity.type, entityStorage.entityAliases);\n const rawStructuredSections = entity.structuredSections ?? [];\n const rawBeliefLedgerFactKeys = beliefLedgerFactKeys(rawStructuredSections);\n const sanitizedFacts = entity.facts\n .map((fact) => sanitizeEntityFact(fact))\n .filter(Boolean)\n .filter((fact) => !rawBeliefLedgerFactKeys.has(normalizeEntityText(fact)))\n .map((fact) => compactLine(fact, 180));\n const { facts: timelineFacts, origins: timelineFactOrigins } = sanitizeOriginatedFacts(\n entity.timeline,\n sanitizeEntityFact,\n compactLine,\n true,\n );\n const structuredSections = buildOriginStructuredSections(\n rawStructuredSections,\n recallFactsForStructuredSection,\n sanitizeEntityFact,\n compactLine,\n );\n entities.set(canonicalId, {\n canonicalId,\n name: entity.name,\n type: entity.type,\n aliases: uniqueStrings(entity.aliases),\n summary: entity.synthesis?.trim() || entity.summary?.trim() || undefined,\n facts: sanitizedFacts,\n timelineFacts,\n ...(timelineFactOrigins.some((origin) => origin !== undefined) ? { timelineFactOrigins } : {}),\n structuredSections,\n timeline: entity.timeline.map((entry) => ({ ...entry })),\n relationships: entity.relationships.map((relationship) => ({ ...relationship })),\n activity: entity.activity.map((activity) => ({ ...activity })),\n factCount: sanitizedFacts.length,\n memorySnippets: [],\n nativeChunks: [],\n });\n }\n\n scanned = 0;\n for (const memory of memories) {\n scanned += 1;\n await yieldEntityRecallScanEvery(scanned, abortSignal);\n const entry = typeof memory.frontmatter.entityRef === \"string\" ? entities.get(memory.frontmatter.entityRef) : undefined;\n if (!entry) continue;\n const snippet = await readMemorySnippet(memory);\n if (entry.memorySnippets.includes(snippet)) continue;\n entry.memorySnippets.push(snippet);\n entry.memorySnippetOrigins = [...(entry.memorySnippetOrigins ?? []), memory.frontmatter.origin];\n }\n // Each remaining phase is another synchronous pass over the whole index\n // (alias map, native-chunk merge, sort, two full serializations). Yield between\n // them so a section deadline can fire between passes instead of only after all\n // of them (issue #2291).\n await yieldEntityRecallScan(abortSignal);\n const aliasIndex = buildAliasIndex([...entities.values()]);\n for (const chunk of nativeChunks) {\n const existingPseudo = entities.get(nativePseudoCanonicalId(chunk));\n if (existingPseudo) {\n mergeNativeChunk(existingPseudo, chunk);\n continue;\n }\n const candidateAliases = uniqueStrings([chunk.title, ...(chunk.aliases ?? [])]).map(normalizeEntityText).filter(Boolean);\n let matched = false;\n for (const alias of candidateAliases) {\n for (const entry of aliasIndex.get(alias) ?? []) {\n mergeNativeChunk(entry, chunk);\n matched = true;\n }\n }\n if (matched) continue;\n const pseudoEntry = createPseudoNativeEntry(chunk);\n entities.set(pseudoEntry.canonicalId, pseudoEntry);\n }\n\n await yieldEntityRecallScan(abortSignal);\n const sortedEntities = [...entities.values()].sort((left, right) => left.name.localeCompare(right.name));\n await yieldEntityRecallScan(abortSignal);\n const previousEntities = previousIndex ? JSON.stringify(previousIndex.entities) : \"\";\n await yieldEntityRecallScan(abortSignal);\n const nextEntities = JSON.stringify(sortedEntities);\n const entityStatusVersionAfter = shouldPersistIndex ? storage.getMemoryStatusVersion() : undefined;\n const canPersistIndex = shouldPersistIndex && entityStatusVersionBefore === entityStatusVersionAfter;\n const index: EntityMentionIndex = {\n version: ENTITY_INDEX_VERSION,\n updatedAt:\n previousIndex && previousEntities === nextEntities\n ? previousIndex.updatedAt\n : new Date().toISOString(),\n entityStatusVersion: canPersistIndex ? entityStatusVersionAfter : undefined,\n entities: sortedEntities,\n };\n if (canPersistIndex) {\n // A build the caller has abandoned must not leave a persisted index behind:\n // the write is I/O the timed-out recall no longer needs, and the next recall\n // is already competing for the same disk.\n checkEntityRecallAbort(abortSignal);\n await writeEntityIndexState(storage, index);\n }\n return index;\n}\n\nfunction resolveExplicitCandidates(\n index: EntityMentionIndex,\n query: string,\n): EntityCandidate[] {\n const candidates: EntityCandidate[] = [];\n for (const entry of index.entities) {\n const aliases = uniqueStrings([entry.name, ...entry.aliases]);\n let bestAlias = \"\";\n let bestScore = 0;\n for (const alias of aliases) {\n const score = scoreAliasMatch(query, alias);\n if (score > bestScore) {\n bestAlias = alias;\n bestScore = score;\n }\n }\n if (bestScore <= 0) continue;\n candidates.push({ entry, alias: bestAlias, score: bestScore, source: \"query\" });\n }\n return candidates.sort((left, right) => right.score - left.score);\n}\n\nconst EXPLICIT_ENTITY_MENTION_SCORE = 9;\n\nconst IMPLICIT_ENTITY_STOP_WORDS = new Set([\n \"a\",\n \"an\",\n \"and\",\n \"are\",\n \"as\",\n \"at\",\n \"be\",\n \"by\",\n \"can\",\n \"do\",\n \"for\",\n \"from\",\n \"has\",\n \"how\",\n \"i\",\n \"if\",\n \"in\",\n \"is\",\n \"it\",\n \"me\",\n \"my\",\n \"of\",\n \"on\",\n \"or\",\n \"the\",\n \"to\",\n \"was\",\n \"what\",\n \"when\",\n \"where\",\n \"who\",\n \"why\",\n \"with\",\n \"you\",\n \"your\",\n]);\n\nfunction isDistinctiveImplicitAlias(normalizedAlias: string): boolean {\n const tokens = normalizedAlias.split(/\\s+/).filter(Boolean);\n if (tokens.length > 1 && tokens.every((token) => IMPLICIT_ENTITY_STOP_WORDS.has(token))) return false;\n if (tokens.length !== 1) return true;\n const token = tokens[0]!;\n return Array.from(token).length > 1 && !IMPLICIT_ENTITY_STOP_WORDS.has(token);\n}\n\nfunction isShortLatinAlias(alias: string): boolean {\n return /^[A-Za-z]{2,3}$/.test(alias.trim());\n}\n\nfunction hasStrongShortLatinAliasMention(query: string, alias: string): boolean {\n const normalizedAlias = alias.trim();\n const titleCaseAlias = `${normalizedAlias[0]!.toUpperCase()}${normalizedAlias.slice(1).toLowerCase()}`;\n const forms = new Set([normalizedAlias, normalizedAlias.toUpperCase(), titleCaseAlias]);\n return [...forms].some((form) => {\n if (form === form.toLowerCase()) return false;\n const escaped = form.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n return new RegExp(`(?:^|[^A-Za-z0-9])${escaped}(?:$|[^A-Za-z0-9])`).test(query);\n });\n}\n\nfunction resolveLanguageIndependentExplicitCandidates(\n index: EntityMentionIndex,\n query: string,\n): EntityCandidate[] {\n const canonicalIdsByAlias = new Map<string, Set<string>>();\n for (const entry of index.entities) {\n for (const alias of uniqueStrings([entry.name, ...entry.aliases])) {\n const normalizedAlias = normalizeEntityText(alias);\n if (!normalizedAlias) continue;\n const canonicalIds = canonicalIdsByAlias.get(normalizedAlias) ?? new Set<string>();\n canonicalIds.add(entry.canonicalId);\n canonicalIdsByAlias.set(normalizedAlias, canonicalIds);\n }\n }\n\n const candidates: EntityCandidate[] = [];\n for (const entry of index.entities) {\n let bestAlias = \"\";\n let bestScore = 0;\n for (const alias of uniqueStrings([entry.name, ...entry.aliases])) {\n const normalizedAlias = normalizeEntityText(alias);\n const score = scoreAliasMatch(query, alias);\n if (\n !normalizedAlias ||\n !isDistinctiveImplicitAlias(normalizedAlias) ||\n (isShortLatinAlias(alias) && !hasStrongShortLatinAliasMention(query, alias)) ||\n canonicalIdsByAlias.get(normalizedAlias)?.size !== 1 ||\n score < EXPLICIT_ENTITY_MENTION_SCORE ||\n score <= bestScore\n ) {\n continue;\n }\n bestAlias = alias;\n bestScore = score;\n }\n if (bestAlias) {\n candidates.push({ entry, alias: bestAlias, score: bestScore, source: \"query\" });\n }\n }\n\n return candidates.sort(\n (left, right) => right.score - left.score || left.entry.name.localeCompare(right.entry.name),\n );\n}\n\nfunction resolveRecentTurnCandidates(\n index: EntityMentionIndex,\n transcriptEntries: TranscriptEntry[],\n recentTurns: number,\n): EntityCandidate[] {\n if (recentTurns <= 0 || transcriptEntries.length === 0) return [];\n const recentEntries = transcriptEntries.slice(-recentTurns);\n const candidates = new Map<string, EntityCandidate>();\n for (let indexOffset = recentEntries.length - 1; indexOffset >= 0; indexOffset -= 1) {\n const turn = recentEntries[indexOffset];\n const recencyBoost = recentEntries.length - indexOffset;\n const roleWeight = turn.role === \"user\" ? 2 : turn.role === \"assistant\" ? -1 : 0;\n for (const entry of index.entities) {\n const aliases = uniqueStrings([entry.name, ...entry.aliases]);\n for (const alias of aliases) {\n const score = scoreAliasMatch(turn.content, alias);\n if (score <= 0) continue;\n const current = candidates.get(entry.canonicalId);\n const weightedScore = score + Math.max(0, 6 - recencyBoost) + roleWeight;\n if (!current || weightedScore > current.score) {\n candidates.set(entry.canonicalId, {\n entry,\n alias,\n score: weightedScore,\n source: \"recent_turn\",\n });\n }\n }\n }\n }\n return [...candidates.values()].sort((left, right) => right.score - left.score);\n}\n\nasync function readMemorySnippet(memory: MemoryFile): Promise<string> {\n const content = memory.content.replace(/\\s+/g, \" \").trim();\n return compactLine(content, 180);\n}\n\nasync function buildHintSnippets(\n entry: EntityMentionIndexEntry,\n queryTokens: string[],\n mode: EntityQueryMode,\n maxSupportingFacts: number,\n requestedSectionKeys: Set<string>,\n): Promise<EntityHintSnippet[]> {\n const snippets: EntityHintSnippet[] = [];\n const aliasTokens = new Set(tokenize(uniqueStrings([entry.name, ...entry.aliases]).join(\" \")));\n if (entry.summary) {\n snippets.push({ text: compactLine(entry.summary, 180), score: 10, kind: \"summary\" });\n }\n if (requestedSectionKeys.size > 0) {\n for (const section of entry.structuredSections) {\n if (!requestedSectionKeys.has(normalizeEntityText(section.key).replace(/\\s+/g, \"_\"))) continue;\n for (const [index, fact] of section.facts.entries()) {\n snippets.push({\n text: fact,\n score: mode === \"direct\" ? 8 : 9,\n kind: \"section\",\n origin: section.factOrigins?.[index],\n });\n }\n }\n } else {\n for (const [index, fact] of entry.timelineFacts.entries()) {\n snippets.push({\n text: fact,\n score: mode === \"direct\" ? 6 : 7,\n kind: \"fact\",\n origin: entry.timelineFactOrigins?.[index],\n });\n }\n for (const section of entry.structuredSections) {\n for (const [index, fact] of section.facts.entries()) {\n const normalizedFact = normalizeEntityText(fact);\n const hasNonAliasQueryOverlap = queryTokens.some((token) =>\n !aliasTokens.has(token) && normalizedFact.includes(token)\n );\n if (entry.timelineFacts.length > 0 && !hasNonAliasQueryOverlap) {\n continue;\n }\n snippets.push({\n text: fact,\n score: mode === \"direct\" ? 6 : 7,\n kind: \"fact\",\n origin: section.factOrigins?.[index],\n });\n }\n }\n if (entry.timelineFacts.length === 0 && entry.structuredSections.length === 0) {\n for (const fact of entry.facts) {\n if (!fact.trim()) continue;\n snippets.push({ text: fact, score: mode === \"direct\" ? 6 : 7, kind: \"fact\" });\n }\n }\n }\n\n if (requestedSectionKeys.size === 0) {\n for (const relationship of entry.relationships) {\n snippets.push({\n text: compactLine(relationLine(entry, relationship), 180),\n score: mode === \"direct\" && entry.type.toLowerCase() === \"person\" ? 6 : 4,\n kind: \"relationship\",\n });\n }\n\n for (const activity of entry.activity) {\n snippets.push({\n text: compactLine(`${activity.date}: ${activity.note}`, 180),\n score: 4,\n kind: \"activity\",\n });\n }\n\n for (const [index, memorySnippet] of entry.memorySnippets.slice(0, Math.min(maxSupportingFacts, 4)).entries()) {\n snippets.push({ text: memorySnippet, score: 5, kind: \"memory\", origin: entry.memorySnippetOrigins?.[index] });\n }\n\n for (const chunk of entry.nativeChunks) {\n snippets.push({\n text: compactLine(chunk.snippet, 180),\n score: 3,\n kind: \"native\",\n });\n }\n }\n\n const deduped = new Map<string, EntityHintSnippet>();\n for (const snippet of snippets) {\n const scored = scoreHintSnippet(snippet, queryTokens);\n if (!scored) continue;\n const normalized = normalizeEntityText(scored.text);\n const existing = deduped.get(normalized);\n if (!existing) {\n deduped.set(normalized, scored);\n } else if (existing.origin !== scored.origin) {\n deduped.set(normalized, { ...(scored.score > existing.score ? scored : existing), origin: undefined });\n } else if (scored.score > existing.score) {\n deduped.set(normalized, scored);\n }\n }\n\n return [...deduped.values()]\n .filter((snippet) => snippet.score > 0)\n .sort((left, right) => right.score - left.score)\n .slice(0, maxSupportingFacts);\n}\n\nfunction summarizeUncertainty(snippets: EntityHintSnippet[]): string | null {\n const direct = snippets.filter((snippet) =>\n snippet.kind === \"summary\"\n || snippet.kind === \"fact\"\n || snippet.kind === \"section\"\n || snippet.kind === \"memory\"\n );\n if (direct.length < 2) return null;\n for (let index = 0; index < direct.length; index += 1) {\n for (let compare = index + 1; compare < direct.length; compare += 1) {\n if (jaccardSimilarity(direct[index].text, direct[compare].text) < 0.2) {\n return \"Evidence is mixed across stored facts; treat the hints below as partial and verify before answering definitively.\";\n }\n }\n }\n return null;\n}\n\nfunction formatEntityHintSection(\n candidates: Array<{\n candidate: EntityCandidate;\n snippets: EntityHintSnippet[];\n uncertainty: string | null;\n }>,\n queryTokens: string[],\n mode: EntityQueryMode,\n maxRelatedEntities: number,\n maxChars: number,\n originAuthorityEnabled: boolean, untrustedOrigins: readonly string[],\n): string | null {\n if (candidates.length === 0) return null;\n const lines: string[] = [\"## entity_answer_hints\", \"\"];\n // #1955 review: non-native snippet kinds may embed extraction-written content\n // without per-field origin — fence as unknown (least privilege; plumbing #2397).\n const renderSnippet = (snippet: EntityHintSnippet): string => snippet.kind !== \"native\"\n ? renderAuthorityBoundContent(snippet.text, snippet.origin, { enabled: originAuthorityEnabled, untrustedOrigins }) : snippet.text;\n // (see comment above)\n // #1955 review: inline fields (names/types/aliases/targets) cannot carry the\n // multi-line block fence without collapsing the hint list structure —\n // per-field origin plumbing is tracked in #2397.\n for (const { candidate, snippets, uncertainty } of candidates) {\n const hasSummary = Boolean(candidate.entry.summary?.trim());\n const preferredTopSnippets = hasSummary\n ? snippets.filter((snippet) => snippet.kind !== \"fact\")\n : snippets;\n let topSnippets = (\n preferredTopSnippets.length > 0 ? preferredTopSnippets : snippets\n ).slice(0, 3);\n const buildTimelineSnippets = (seedExcludedTexts: Set<string>): EntityHintSnippet[] => {\n const explicitTimelinePool = dedupeHintSnippetsByText(\n (candidate.entry.timeline ?? [])\n .slice()\n .sort(sortTimelineEntriesDesc)\n .map((entry) => {\n const text = sanitizeEntityFact(entry.text);\n return text\n ? scoreHintSnippet({\n text: compactLine(text, 180),\n score: 7,\n kind: \"activity\" as const,\n origin: entry.origin,\n }, queryTokens)\n : null;\n })\n .filter((snippet): snippet is EntityHintSnippet => snippet !== null)\n .filter((snippet) => !seedExcludedTexts.has(normalizeEntityText(snippet.text))),\n ).slice(0, 2);\n const activityTimelinePool = dedupeHintSnippetsByText(\n snippets\n .filter((snippet) => (\n snippet.kind === \"activity\" || snippet.kind === \"memory\"\n ) && !seedExcludedTexts.has(normalizeEntityText(snippet.text))),\n ).slice(0, 2);\n return explicitTimelinePool.length > 0\n ? explicitTimelinePool\n : activityTimelinePool.length > 0\n ? activityTimelinePool\n : dedupeHintSnippetsByText(\n snippets\n .filter((snippet) => (\n snippet.kind === \"fact\" || snippet.kind === \"summary\"\n ) && !seedExcludedTexts.has(normalizeEntityText(snippet.text))),\n ).slice(0, 2);\n };\n const baseTopSnippetTexts = new Set(topSnippets.map((snippet) => normalizeEntityText(snippet.text)));\n const timelinePool = mode !== \"direct\" ? buildTimelineSnippets(baseTopSnippetTexts) : [];\n if (mode !== \"direct\" && hasSummary && topSnippets.length < 2) {\n if (timelinePool.length > 0) {\n topSnippets = [...topSnippets, timelinePool[0]!].slice(0, 3);\n }\n }\n const topSnippetTexts = new Set(topSnippets.map((snippet) => normalizeEntityText(snippet.text)));\n lines.push(`- target: ${candidate.entry.name} (${candidate.entry.type})`);\n lines.push(`- resolution: ${candidate.source === \"recent_turn\" ? \"carried forward from recent turns via alias\" : \"matched alias\"} \"${candidate.alias}\"${candidate.source === \"recent_turn\" ? \"\" : \" in the query\"}`);\n if (uncertainty) lines.push(`- uncertainty: ${uncertainty}`);\n if (topSnippets.length > 0) {\n lines.push(\"- likely answer:\");\n for (const snippet of topSnippets) {\n lines.push(` - ${renderSnippet(snippet)}`);\n }\n }\n if (mode !== \"direct\") {\n const fallbackTimeline = timelinePool.filter(\n (snippet) => !topSnippetTexts.has(normalizeEntityText(snippet.text)),\n );\n if (fallbackTimeline.length > 0) {\n lines.push(\"- recent timeline:\");\n for (const snippet of fallbackTimeline) {\n lines.push(` - ${renderSnippet(snippet)}`);\n }\n }\n }\n const related = candidate.entry.relationships.slice(0, maxRelatedEntities).map((relationship) => relationship.target);\n if (related.length > 0) {\n lines.push(`- related entities: ${related.join(\", \")}`);\n }\n lines.push(`- support counts: facts=${candidate.entry.factCount}, memories=${candidate.entry.memorySnippets.length}, native=${candidate.entry.nativeChunks.length}`);\n lines.push(\"\");\n }\n\n let result = lines.join(\"\\n\");\n if (result.length > maxChars) {\n result = `${truncateGraphemeSafe(result, Math.max(0, maxChars - 15)).trimEnd()}\\n\\n...(trimmed)\\n`;\n }\n return result.trim().length > 0 ? result.trimEnd() : null;\n}\n\nexport async function buildEntityRecallSection(options: BuildEntityRecallSectionOptions): Promise<string | null> {\n // Checkpoints sit at the real I/O boundaries below (persisted-index read,\n // native-chunk read, storage resolution, index build). The per-candidate\n // formatting that follows never awaits real I/O, so a deadline that fires\n // during a scan is observed here (issue #2291).\n checkEntityRecallAbort(options.abortSignal);\n const prefixedMode = detectEntityQueryMode(options.query);\n // #2193: in zero-pronoun scripts a short question with no entity name\n // never trips a pronoun word list, so the structural signal routes it\n // into the same coreference path as an English \"what about him?\".\n // Latin-script queries stay on the cue tables / English rules so the\n // generic technical-question guard keeps working. Resolution gates.\n const structuralFollowUp = prefixedMode === null\n && isStructuralEntityFollowUpQuery(\n options.query,\n options.recentTurns > 0 && options.transcriptEntries.length > 0,\n );\n const earlyMode = prefixedMode ?? (structuralFollowUp ? \"follow_up\" : null);\n const persistedIndex = earlyMode\n ? null\n : await readCurrentPersistedEntityIndex(\n options.storage,\n options.config,\n options.recallNamespaces,\n options.namespaceStorage,\n );\n checkEntityRecallAbort(options.abortSignal);\n let nativeChunks: NativeKnowledgeChunk[] | undefined;\n if (\n !earlyMode &&\n persistedIndex &&\n resolveLanguageIndependentExplicitCandidates(persistedIndex, options.query).length === 0\n ) {\n nativeChunks = await readNativeChunks(options.config, options.recallNamespaces);\n if (!hasFreshNativeExplicitMention(persistedIndex, nativeChunks, options.query)) {\n return entityRecallSectionAbsent(options.abortSignal);\n }\n }\n const namespaceScoped =\n resolveNamespaceCapabilities(options.config).namespaces &&\n options.namespaceStorage !== undefined &&\n (options.recallNamespaces?.length ?? 0) > 0;\n if (namespaceScoped) {\n nativeChunks = await readNativeChunks(options.config, options.recallNamespaces);\n }\n const resolvedStorages = namespaceScoped\n ? await resolveEntityIndexStorages(\n options.storage,\n options.config,\n options.recallNamespaces,\n options.namespaceStorage,\n )\n : undefined;\n const namespaceCacheKey =\n resolvedStorages && options.recallNamespaces && nativeChunks\n ? namespaceEntityIndexCacheKey(\n resolvedStorages,\n options.recallNamespaces,\n nativeEntityIndexRevision(nativeChunks),\n )\n : undefined;\n let index: EntityMentionIndex | undefined = namespaceCacheKey\n ? namespaceEntityIndexCache.get(namespaceCacheKey)\n : undefined;\n checkEntityRecallAbort(options.abortSignal);\n if (!index) {\n index = await buildEntityMentionIndex(\n options.storage,\n options.config,\n options.recallNamespaces,\n options.namespaceStorage,\n nativeChunks,\n resolvedStorages,\n options.abortSignal,\n );\n if (namespaceCacheKey) rememberNamespaceEntityIndex(namespaceCacheKey, index);\n }\n // Candidate resolution is another synchronous pass over every entity and alias,\n // reached even on a cache hit that did no I/O at all — so yield here too, or a\n // cached corpus could still hold the loop past the section budget (issue #2291).\n await yieldEntityRecallScan(options.abortSignal);\n const explicitCandidates = resolveExplicitCandidates(index, options.query);\n await yieldEntityRecallScan(options.abortSignal);\n const queryCandidates = prefixedMode\n ? explicitCandidates\n : resolveLanguageIndependentExplicitCandidates(index, options.query);\n if (\n queryCandidates.length === 0\n && /^what does (?:this|that|it|the|a|an|my|our|your|their)\\b/i.test(normalizeEntityText(options.query))\n ) {\n return entityRecallSectionAbsent(options.abortSignal);\n }\n\n // Explicit mentions keep #2161 behavior (direct mode) even when the\n // structural follow-up signal also fired; only name-less short questions\n // fall through to coreference.\n const mode = prefixedMode\n ?? (queryCandidates.length > 0\n ? \"direct\"\n : structuralFollowUp\n ? \"follow_up\"\n : null);\n if (!mode) return entityRecallSectionAbsent(options.abortSignal);\n\n const candidates = queryCandidates.length > 0\n ? queryCandidates\n : resolveRecentTurnCandidates(index, options.transcriptEntries, options.recentTurns);\n\n if (candidates.length === 0) return entityRecallSectionAbsent(options.abortSignal);\n\n const queryTokens = tokenize(options.query);\n const candidateLimit = queryCandidates.length === 0 && mode === \"follow_up\"\n ? 1\n : options.maxHints;\n const rankedCandidates = candidates.slice(0, candidateLimit);\n const enriched = await Promise.all(\n rankedCandidates.map(async (candidate) => {\n const requestedSectionKeys = new Set(\n resolveRequestedEntitySectionKeys(\n options.query,\n candidate.entry.type,\n candidate.entry.structuredSections,\n options.config.entitySchemas,\n ),\n );\n const snippets = await buildHintSnippets(\n candidate.entry,\n queryTokens,\n mode,\n options.maxSupportingFacts,\n requestedSectionKeys,\n );\n return {\n candidate,\n snippets,\n uncertainty: summarizeUncertainty(snippets),\n };\n }),\n );\n\n const section = formatEntityHintSection(\n enriched,\n queryTokens,\n mode,\n options.maxRelatedEntities,\n options.maxChars,\n options.originAuthorityEnabled === true,\n options.untrustedOrigins ?? [],\n );\n // `entityRecallSectionAbsent` so a cancelled build is not recorded as a\n // successful section that simply found no entities.\n if (!section) return entityRecallSectionAbsent(options.abortSignal);\n return section;\n}\n\nexport async function readRecentEntityTranscriptEntries(\n transcriptEntriesPromise: Promise<TranscriptEntry[]>,\n recentTurns: number,\n): Promise<TranscriptEntry[]> {\n if (recentTurns <= 0) return [];\n const transcriptEntries = await transcriptEntriesPromise.catch(() => []);\n if (transcriptEntries.length === 0) return [];\n return transcriptEntries.slice(-Math.max(1, recentTurns * 2));\n}\n\nexport const entityIndexVersion = ENTITY_INDEX_VERSION;\nexport const entityRecentTranscriptLookbackHours = RECENT_TRANSCRIPT_LOOKBACK_HOURS;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,kBAAkB;AAE3B,SAAS,OAAO,UAAU,iBAAiB;AAC3C,OAAO,UAAU;AAmBjB,IAAM,uBAAuB;AAC7B,IAAM,mCAAmC;AACzC,IAAM,sBAAsB;AAC5B,IAAM,sBAAsB;AAC5B,IAAM,4BAA4B;AAClC,IAAM,wBAAwB;AAsE9B,SAAS,SAAS,OAAyB;AACzC,SAAO,oBAAoB,KAAK,EAAE,MAAM,KAAK,EAAE,OAAO,CAAC,UAAU,MAAM,UAAU,CAAC;AACpF;AACA,SAAS,cAAc,QAA4B;AACjD,SAAO,CAAC,GAAG,IAAI,IAAI,OAAO,IAAI,CAAC,UAAU,MAAM,KAAK,CAAC,EAAE,OAAO,CAAC,UAAU,MAAM,SAAS,CAAC,CAAC,CAAC;AAC7F;AACA,SAAS,YAAY,OAAe,YAAoB,KAAa;AACnE,QAAM,aAAa,MAAM,QAAQ,QAAQ,GAAG,EAAE,KAAK;AACnD,MAAI,WAAW,UAAU,UAAW,QAAO;AAC3C,SAAO,GAAG,qBAAqB,YAAY,YAAY,CAAC,E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oBAAoB,CAAC;AAAA,EAC/B;AAGA,MAAI,CAAC,QAAS,QAAO,0BAA0B,QAAQ,WAAW;AAClE,SAAO;AACT;AAEA,eAAsB,kCACpB,0BACA,aAC4B;AAC5B,MAAI,eAAe,EAAG,QAAO,CAAC;AAC9B,QAAM,oBAAoB,MAAM,yBAAyB,MAAM,MAAM,CAAC,CAAC;AACvE,MAAI,kBAAkB,WAAW,EAAG,QAAO,CAAC;AAC5C,SAAO,kBAAkB,MAAM,CAAC,KAAK,IAAI,GAAG,cAAc,CAAC,CAAC;AAC9D;AAEO,IAAM,qBAAqB;AAC3B,IAAM,sCAAsC;","names":["index","token"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/maintenance/rebuild-memory-projection.ts"],"sourcesContent":["import path from \"node:path\";\nimport { mkdir, rm, stat } from \"node:fs/promises\";\nimport { StorageManager } from \"../storage.js\";\nimport { log } from \"../logger.js\";\nimport {\n listMemoryGovernanceRuns,\n readMemoryGovernanceRunArtifact,\n} from \"./memory-governance.js\";\nimport { loadPersistedNativeKnowledgeChunks } from \"../native-knowledge.js\";\nimport { toBackupStamp } from \"./backup-stamp.js\";\nimport type {\n MemoryFile,\n MemoryLifecycleEvent,\n MemoryProjectionCurrentState,\n MemoryStatus,\n} from \"../types.js\";\nimport {\n buildLifecycleEventsForMemory,\n inferMemoryStatus,\n MEMORY_LIFECYCLE_EVENT_SORT_ORDER,\n memoryLifecycleEventProjectionIdentity,\n sortMemoryLifecycleEvents,\n toMemoryPathRel,\n} from \"../memory-lifecycle-ledger-utils.js\";\nimport {\n getMemoryProjectionPath,\n initializeMemoryProjectionDb,\n isProjectedMemoryPathValid,\n type ProjectedEntityMentionRow,\n type MemoryProjectionGovernanceAppliedActionRow,\n type MemoryProjectionGovernanceReviewQueueRow,\n type ProjectedNativeKnowledgeChunkRow,\n MEMORY_PROJECTION_SCHEMA_VERSION,\n memoryCurrentSelectExpressions,\n parseCurrentRow,\n readProjectedEntityMentions,\n readProjectedGovernanceRecord,\n readProjectedNativeKnowledgeChunks,\n parseTimelineRows,\n} from \"../memory-projection-store.js\";\nimport {\n normalizeProjectionPreview,\n normalizeProjectionTags,\n} from \"../memory-projection-format.js\";\nimport { openBetterSqlite3 } from \"../runtime/better-sqlite.js\";\nimport { commitPreparedFileAtomically } from \"./atomic-file.js\";\nimport { isSupportPassportPrivateMemory } from \"../support-passport/card-projection.js\";\n\nexport interface RebuildMemoryProjectionOptions {\n memoryDir: string;\n /** Reuse the caller's live StorageManager (must be rooted at memoryDir). */\n storage?: StorageManager;\n defaultNamespace?: string;\n dryRun?: boolean;\n now?: Date;\n updatedAfter?: string;\n updatedBefore?: string;\n}\n\nexport type {\n SkippedBlankIdMemory,\n SkippedBlankIdTimelineEvent,\n SkippedDuplicateMemory,\n SkippedDuplicateTimelineEvent,\n} from \"./projection-support.js\";\nimport {\n assertInjectedStorageRooted,\n readProjectedEntityMentionRows,\n readProjectedGovernanceRows,\n readProjectedNativeKnowledgeRows,\n writeProjectionMetaHighWater,\n} from \"./projection-support.js\";\nimport type {\n SkippedBlankIdMemory,\n SkippedBlankIdTimelineEvent,\n SkippedDuplicateMemory,\n SkippedDuplicateTimelineEvent,\n} from \"./projection-support.js\";\nimport { isErrnoCode } from \"../utils/errno.js\";\n\n\nexport interface RebuildMemoryProjectionResult {\n dryRun: boolean;\n scannedMemories: number;\n currentRows: number;\n timelineRows: number;\n entityMentionRows: number;\n nativeKnowledgeRows: number;\n reviewQueueRows: number;\n outputPath: string;\n backupPath?: string;\n usedLifecycleLedger: boolean;\n skippedDuplicateMemories: SkippedDuplicateMemory[];\n skippedBlankIdMemories: SkippedBlankIdMemory[];\n skippedDuplicateTimelineEvents: SkippedDuplicateTimelineEvent[];\n skippedBlankIdTimelineEvents: SkippedBlankIdTimelineEvent[];\n scope: {\n updatedAfter: string | null;\n updatedBefore: string | null;\n };\n}\n\nexport interface VerifyMemoryProjectionOptions {\n memoryDir: string;\n defaultNamespace?: string;\n updatedAfter?: string;\n updatedBefore?: string;\n}\n\nexport interface VerifyMemoryProjectionResult {\n outputPath: string;\n projectionExists: boolean;\n ok: boolean;\n expectedCurrentRows: number;\n actualCurrentRows: number;\n expectedTimelineRows: number;\n actualTimelineRows: number;\n expectedEntityMentionRows: number;\n actualEntityMentionRows: number;\n expectedNativeKnowledgeRows: number;\n actualNativeKnowledgeRows: number;\n expectedReviewQueueRows: number;\n actualReviewQueueRows: number;\n missingCurrentMemoryIds: string[];\n extraCurrentMemoryIds: string[];\n mismatchedCurrentMemoryIds: string[];\n missingTimelineEventIds: string[];\n extraTimelineEventIds: string[];\n missingEntityMentionKeys: string[];\n extraEntityMentionKeys: string[];\n mismatchedEntityMentionKeys: string[];\n missingNativeKnowledgeChunkIds: string[];\n extraNativeKnowledgeChunkIds: string[];\n mismatchedNativeKnowledgeChunkIds: string[];\n missingReviewQueueEntryIds: string[];\n extraReviewQueueEntryIds: string[];\n mismatchedReviewQueueEntryIds: string[];\n usedLifecycleLedger: boolean;\n scope: {\n updatedAfter: string | null;\n updatedBefore: string | null;\n };\n}\n\nexport interface RepairMemoryProjectionOptions extends RebuildMemoryProjectionOptions {}\n\nexport interface RepairMemoryProjectionResult {\n dryRun: boolean;\n repaired: boolean;\n verify: VerifyMemoryProjectionResult;\n rebuild?: RebuildMemoryProjectionResult;\n}\n\nexport async function backupExistingProjection(\n memoryDir: string,\n outputPath: string,\n now: Date,\n): Promise<string | undefined> {\n try {\n await stat(outputPath);\n } catch (err) {\n if (isErrnoCode(err, \"ENOENT\")) {\n return undefined;\n }\n throw err;\n }\n\n const backupPath = path.join(\n memoryDir,\n \"archive\",\n \"memory-projection\",\n toBackupStamp(now),\n \"state\",\n \"memory-projection.sqlite\",\n );\n return backupPath;\n}\n\nfunction inferProjectedStatus(pathRel: string, memory: MemoryFile): MemoryStatus {\n return inferMemoryStatus(memory.frontmatter, pathRel);\n}\n\nfunction toCurrentStateRow(memoryDir: string, memory: MemoryFile): MemoryProjectionCurrentState {\n const pathRel = toMemoryPathRel(memoryDir, memory.path);\n return {\n memoryId: memory.frontmatter.id,\n category: memory.frontmatter.category,\n status: inferProjectedStatus(pathRel, memory),\n lifecycleState: memory.frontmatter.lifecycleState,\n path: memory.path,\n pathRel,\n created: memory.frontmatter.created,\n updated: memory.frontmatter.updated,\n archivedAt: memory.frontmatter.archivedAt,\n supersededAt: memory.frontmatter.supersededAt,\n entityRef: memory.frontmatter.entityRef,\n source: memory.frontmatter.source,\n confidence: memory.frontmatter.confidence,\n confidenceTier: memory.frontmatter.confidenceTier,\n memoryKind: memory.frontmatter.memoryKind,\n accessCount: memory.frontmatter.accessCount,\n lastAccessed: memory.frontmatter.lastAccessed,\n tags: normalizeProjectionTags(memory.frontmatter.tags),\n preview: normalizeProjectionPreview(memory.content),\n privateRecord: isSupportPassportPrivateMemory(memory),\n };\n}\n\nfunction buildEntityMentionRows(\n currentRows: MemoryProjectionCurrentState[],\n): ProjectedEntityMentionRow[] {\n return currentRows.flatMap((row) => {\n const mentions: ProjectedEntityMentionRow[] = [];\n if (row.entityRef) {\n mentions.push({\n memoryId: row.memoryId,\n entityRef: row.entityRef,\n mentionSource: \"frontmatter.entityRef\",\n created: row.created,\n updated: row.updated,\n });\n }\n for (const tag of row.tags ?? []) {\n if (!tag.includes(\":\")) continue;\n mentions.push({\n memoryId: row.memoryId,\n entityRef: tag,\n mentionSource: \"tag\",\n created: row.created,\n updated: row.updated,\n });\n }\n return mentions;\n });\n}\n\nfunction buildGovernanceActionRowKey(action: {\n action: string;\n memoryId: string;\n reasonCode: string;\n originalPath: string;\n currentPath: string;\n}): string {\n return [\n action.action,\n action.memoryId,\n action.reasonCode,\n action.originalPath,\n action.currentPath,\n ].join(\"::\");\n}\n\nasync function loadLatestGovernanceProjection(memoryDir: string): Promise<{\n runId: string;\n summary: unknown;\n metrics: unknown;\n reviewQueueRows: MemoryProjectionGovernanceReviewQueueRow[];\n appliedActionRows: MemoryProjectionGovernanceAppliedActionRow[];\n report: string;\n} | null> {\n const runId = (await listMemoryGovernanceRuns(memoryDir))[0];\n if (!runId) return null;\n try {\n const artifact = await readMemoryGovernanceRunArtifact(memoryDir, runId);\n return {\n runId,\n summary: artifact.summary,\n metrics: artifact.metrics,\n reviewQueueRows: artifact.reviewQueue.map((entry) => ({\n runId,\n entryId: entry.entryId,\n memoryId: entry.memoryId,\n path: entry.path,\n reasonCode: entry.reasonCode,\n severity: entry.severity,\n suggestedAction: entry.suggestedAction,\n suggestedStatus: entry.suggestedStatus,\n relatedMemoryIds: [...entry.relatedMemoryIds],\n })),\n appliedActionRows: artifact.appliedActions.map((action) => ({\n runId,\n rowKey: buildGovernanceActionRowKey(action),\n action: action.action,\n memoryId: action.memoryId,\n reasonCode: action.reasonCode,\n beforeStatus: action.beforeStatus,\n afterStatus: action.afterStatus,\n originalPath: action.originalPath,\n currentPath: action.currentPath,\n })),\n report: artifact.report,\n };\n } catch {\n return null;\n }\n}\n\nfunction loadTimelineEvents(\n memories: MemoryFile[],\n lifecycleEvents: MemoryLifecycleEvent[],\n): { events: MemoryLifecycleEvent[]; usedLifecycleLedger: boolean } {\n if (lifecycleEvents.length > 0) {\n return {\n events: sortMemoryLifecycleEvents(lifecycleEvents),\n usedLifecycleLedger: true,\n };\n }\n\n return {\n events: sortMemoryLifecycleEvents(memories.flatMap((memory) => buildLifecycleEventsForMemory(memory))),\n usedLifecycleLedger: false,\n };\n}\n\nfunction normalizeScopedIso(value: string | undefined): string | null {\n if (!value) return null;\n const trimmed = value.trim();\n if (!trimmed) return null;\n const parsed = new Date(trimmed);\n if (Number.isNaN(parsed.getTime())) {\n throw new Error(`invalid projection scope timestamp: ${value}`);\n }\n return parsed.toISOString();\n}\n\nfunction normalizeProjectionScope(options: {\n updatedAfter?: string;\n updatedBefore?: string;\n}): {\n updatedAfter: string | null;\n updatedBefore: string | null;\n} {\n const updatedAfter = normalizeScopedIso(options.updatedAfter);\n const updatedBefore = normalizeScopedIso(options.updatedBefore);\n if (\n updatedAfter &&\n updatedBefore &&\n new Date(updatedAfter).getTime() > new Date(updatedBefore).getTime()\n ) {\n throw new Error(\"updatedAfter must be less than or equal to updatedBefore\");\n }\n return {\n updatedAfter,\n updatedBefore,\n };\n}\n\nfunction hasScopedProjectionFilter(scope: {\n updatedAfter: string | null;\n updatedBefore: string | null;\n}): boolean {\n return scope.updatedAfter !== null || scope.updatedBefore !== null;\n}\n\nfunction memoryScopeTimestamp(memory: MemoryFile): string {\n const candidate = memory.frontmatter.updated || memory.frontmatter.created;\n return candidate;\n}\n\nfunction isTimestampInProjectionScope(\n timestamp: string,\n scope: { updatedAfter: string | null; updatedBefore: string | null },\n): boolean {\n if (!scope.updatedAfter && !scope.updatedBefore) return true;\n const parsed = new Date(timestamp);\n if (Number.isNaN(parsed.getTime())) return false;\n if (scope.updatedAfter && parsed.getTime() < new Date(scope.updatedAfter).getTime()) return false;\n if (scope.updatedBefore && parsed.getTime() >= new Date(scope.updatedBefore).getTime()) return false;\n return true;\n}\n\nfunction filterMemoriesForProjectionScope(\n memories: MemoryFile[],\n scope: { updatedAfter: string | null; updatedBefore: string | null },\n): MemoryFile[] {\n if (!scope.updatedAfter && !scope.updatedBefore) return memories;\n return memories.filter((memory) => isTimestampInProjectionScope(memoryScopeTimestamp(memory), scope));\n}\n\nfunction filterCurrentStateRowsForProjectionScope(\n rows: MemoryProjectionCurrentState[],\n scope: { updatedAfter: string | null; updatedBefore: string | null },\n): MemoryProjectionCurrentState[] {\n if (!scope.updatedAfter && !scope.updatedBefore) return rows;\n return rows.filter((row) => isTimestampInProjectionScope(row.updated || row.created, scope));\n}\n\nfunction serializeCurrentStateRow(row: MemoryProjectionCurrentState): string {\n return JSON.stringify({\n memoryId: row.memoryId,\n category: row.category,\n status: row.status,\n lifecycleState: row.lifecycleState ?? null,\n pathRel: row.pathRel,\n created: row.created,\n updated: row.updated,\n archivedAt: row.archivedAt ?? null,\n supersededAt: row.supersededAt ?? null,\n entityRef: row.entityRef ?? null,\n source: row.source,\n confidence: row.confidence,\n confidenceTier: row.confidenceTier,\n memoryKind: row.memoryKind ?? null,\n accessCount: row.accessCount ?? null,\n lastAccessed: row.lastAccessed ?? null,\n tags: row.tags ?? [],\n preview: row.preview ?? \"\",\n privateRecord: row.privateRecord === true,\n });\n}\n\nfunction serializeTimelineEvent(event: MemoryLifecycleEvent): string {\n return JSON.stringify({\n eventId: event.eventId,\n memoryId: event.memoryId,\n eventType: event.eventType,\n timestamp: event.timestamp,\n actor: event.actor,\n reasonCode: event.reasonCode ?? null,\n ruleVersion: event.ruleVersion,\n relatedMemoryIds: event.relatedMemoryIds ?? [],\n before: event.before ?? null,\n after: event.after ?? null,\n correlationId: event.correlationId ?? null,\n });\n}\n\nfunction serializeEntityMentionRow(row: ProjectedEntityMentionRow): string {\n return JSON.stringify(row);\n}\n\nfunction serializeNativeKnowledgeRow(row: ProjectedNativeKnowledgeChunkRow): string {\n return JSON.stringify({\n chunkId: row.chunkId,\n sourceKind: row.sourceKind,\n sourcePath: row.sourcePath,\n title: row.title,\n startLine: row.startLine,\n endLine: row.endLine,\n namespace: row.namespace ?? null,\n privacyClass: row.privacyClass ?? null,\n derivedDate: row.derivedDate ?? null,\n sessionKey: row.sessionKey ?? null,\n workflowKey: row.workflowKey ?? null,\n author: row.author ?? null,\n agent: row.agent ?? null,\n sourceHash: row.sourceHash ?? null,\n preview: row.preview,\n });\n}\n\nfunction serializeGovernanceReviewQueueRow(\n row: MemoryProjectionGovernanceReviewQueueRow,\n): string {\n return JSON.stringify({\n runId: row.runId,\n entryId: row.entryId,\n memoryId: row.memoryId,\n path: row.path,\n reasonCode: row.reasonCode,\n severity: row.severity,\n suggestedAction: row.suggestedAction,\n suggestedStatus: row.suggestedStatus ?? null,\n relatedMemoryIds: row.relatedMemoryIds,\n });\n}\n\nfunction selectProjectionMemories(\n tiers: MemoryFile[][],\n): {\n allMemories: MemoryFile[];\n memories: MemoryFile[];\n skippedDuplicateMemories: SkippedDuplicateMemory[];\n skippedBlankIdMemories: SkippedBlankIdMemory[];\n} {\n const allMemories = tiers.flat();\n const memories: MemoryFile[] = [];\n const keptById = new Map<string, MemoryFile>();\n const skippedDuplicateMemories: SkippedDuplicateMemory[] = [];\n const skippedBlankIdMemories: SkippedBlankIdMemory[] = [];\n\n // Tier order is authoritative: hot wins over cold, and cold wins over archive.\n // Paths break ties within a tier so the winner does not depend on readdir order.\n for (const tier of tiers) {\n for (const memory of [...tier].sort((left, right) => left.path.localeCompare(right.path))) {\n const memoryId = memory.frontmatter.id.trim();\n if (!memoryId) {\n skippedBlankIdMemories.push({ path: memory.path });\n log.warn(`projection rebuild skipped blank memory id: path=${memory.path}`);\n continue;\n }\n const kept = keptById.get(memoryId);\n if (kept) {\n skippedDuplicateMemories.push({\n memoryId,\n keptPath: kept.path,\n skippedPath: memory.path,\n });\n log.warn(\n `projection rebuild skipped duplicate memory id=${memoryId}: kept=${kept.path} skipped=${memory.path}`,\n );\n continue;\n }\n keptById.set(memoryId, memory);\n memories.push(memory);\n }\n }\n\n return { allMemories, memories, skippedDuplicateMemories, skippedBlankIdMemories };\n}\n\nfunction deduplicateTimelineEvents(\n events: MemoryLifecycleEvent[],\n sourcePathFor: (event: MemoryLifecycleEvent) => string,\n): {\n events: MemoryLifecycleEvent[];\n skipped: SkippedDuplicateTimelineEvent[];\n skippedBlankIds: SkippedBlankIdTimelineEvent[];\n} {\n const keptById = new Map<string, { event: MemoryLifecycleEvent; path: string }>();\n const unique: MemoryLifecycleEvent[] = [];\n const skipped: SkippedDuplicateTimelineEvent[] = [];\n const skippedBlankIds: SkippedBlankIdTimelineEvent[] = [];\n for (const event of sortMemoryLifecycleEvents(events)) {\n const sourcePath = sourcePathFor(event);\n if (!event.memoryId.trim()) {\n skippedBlankIds.push({ eventId: event.eventId, path: sourcePath });\n log.warn(\n `projection rebuild skipped timeline event with blank memory id: `\n + `event_id=${event.eventId} path=${sourcePath}`,\n );\n continue;\n }\n const kept = keptById.get(event.eventId);\n if (kept) {\n skipped.push({\n eventId: event.eventId,\n keptPath: kept.path,\n skippedPath: sourcePath,\n });\n log.warn(\n `projection rebuild skipped duplicate timeline event_id=${event.eventId}: `\n + `kept=${kept.path} skipped=${sourcePath}`,\n );\n continue;\n }\n keptById.set(event.eventId, { event, path: sourcePath });\n unique.push(event);\n }\n return { events: unique, skipped, skippedBlankIds };\n}\n\nasync function loadAuthoritativeProjectionSnapshot(options: {\n memoryDir: string;\n defaultNamespace?: string;\n storage?: StorageManager;\n updatedAfter?: string;\n updatedBefore?: string;\n}): Promise<{\n allMemories: MemoryFile[];\n currentRows: MemoryProjectionCurrentState[];\n timelineRows: MemoryLifecycleEvent[];\n scopedCurrentRows: MemoryProjectionCurrentState[];\n scopedTimelineRows: MemoryLifecycleEvent[];\n entityMentionRows: ProjectedEntityMentionRow[];\n scopedEntityMentionRows: ProjectedEntityMentionRow[];\n nativeKnowledgeRows: ProjectedNativeKnowledgeChunkRow[];\n governance:\n | {\n runId: string;\n summary: unknown;\n metrics: unknown;\n reviewQueueRows: MemoryProjectionGovernanceReviewQueueRow[];\n appliedActionRows: MemoryProjectionGovernanceAppliedActionRow[];\n report: string;\n }\n | null;\n usedLifecycleLedger: boolean;\n sourceLifecycleLedgerEventCount: number;\n scope: {\n updatedAfter: string | null;\n updatedBefore: string | null;\n };\n skippedDuplicateMemories: SkippedDuplicateMemory[];\n skippedBlankIdMemories: SkippedBlankIdMemory[];\n skippedDuplicateTimelineEvents: SkippedDuplicateTimelineEvent[];\n skippedBlankIdTimelineEvents: SkippedBlankIdTimelineEvent[];\n}> {\n const storage = assertInjectedStorageRooted(\"rebuildMemoryProjection\", options.memoryDir, options.storage) ?? new StorageManager(options.memoryDir);\n // Force a fresh disk read — projection verify/rebuild must see the true\n // on-disk state, not a potentially stale in-process cache.\n storage.invalidateAllMemoriesCacheForDir();\n const selected = selectProjectionMemories([\n await storage.readAllMemories(),\n await storage.readAllColdMemories(),\n await storage.readArchivedMemories(),\n ]);\n const allMemories = selected.allMemories;\n const projectionMemories = selected.memories;\n const lifecycleEvents = await storage.readAllMemoryLifecycleEvents();\n const timeline = loadTimelineEvents(projectionMemories, lifecycleEvents);\n const lifecycleLedgerPath = path.join(\n options.memoryDir,\n \"state\",\n \"memory-lifecycle-ledger.jsonl\",\n );\n const memoryPathById = new Map(\n projectionMemories.map((memory) => [memory.frontmatter.id, memory.path]),\n );\n const deduplicatedTimeline = deduplicateTimelineEvents(\n timeline.events,\n (event) => timeline.usedLifecycleLedger\n ? lifecycleLedgerPath\n : memoryPathById.get(event.memoryId) ?? lifecycleLedgerPath,\n );\n const events = deduplicatedTimeline.events;\n const usedLifecycleLedger = timeline.usedLifecycleLedger;\n const sourceLifecycleLedgerEventCount = new Set(\n lifecycleEvents.map(memoryLifecycleEventProjectionIdentity),\n ).size;\n const currentRows = projectionMemories.map((memory) => toCurrentStateRow(options.memoryDir, memory));\n const scope = normalizeProjectionScope(options);\n const scopedMemories = filterMemoriesForProjectionScope(projectionMemories, scope);\n const scopedMemoryIds = new Set(scopedMemories.map((memory) => memory.frontmatter.id));\n const nativeKnowledgeRows = await loadPersistedNativeKnowledgeChunks({\n memoryDir: options.memoryDir,\n defaultNamespace: options.defaultNamespace ?? \"default\",\n }).then((rows) => rows.map((row) => ({\n chunkId: row.chunkId,\n sourceKind: row.sourceKind,\n sourcePath: row.sourcePath,\n title: row.title,\n startLine: row.startLine,\n endLine: row.endLine,\n namespace: row.namespace ?? options.defaultNamespace ?? \"default\",\n privacyClass: row.privacyClass,\n derivedDate: row.derivedDate,\n sessionKey: row.sessionKey,\n workflowKey: row.workflowKey,\n author: row.author,\n agent: row.agent,\n sourceHash: row.sourceHash,\n preview: normalizeProjectionPreview(row.content),\n })));\n const governance = await loadLatestGovernanceProjection(options.memoryDir);\n const entityMentionRows = buildEntityMentionRows(currentRows);\n\n return {\n allMemories,\n currentRows,\n timelineRows: events,\n scopedCurrentRows: currentRows.filter((row) => scopedMemoryIds.has(row.memoryId)),\n scopedTimelineRows: events.filter((event) => scopedMemoryIds.has(event.memoryId)),\n entityMentionRows,\n scopedEntityMentionRows: entityMentionRows.filter((row) => scopedMemoryIds.has(row.memoryId)),\n nativeKnowledgeRows,\n governance,\n usedLifecycleLedger,\n sourceLifecycleLedgerEventCount,\n scope,\n skippedDuplicateMemories: selected.skippedDuplicateMemories,\n skippedBlankIdMemories: selected.skippedBlankIdMemories,\n skippedDuplicateTimelineEvents: deduplicatedTimeline.skipped,\n skippedBlankIdTimelineEvents: deduplicatedTimeline.skippedBlankIds,\n };\n}\n\nfunction readProjectedCurrentRows(\n memoryDir: string,\n): { projectionExists: boolean; rows: MemoryProjectionCurrentState[] } {\n const dbPath = getMemoryProjectionPath(memoryDir);\n try {\n const db = openBetterSqlite3(dbPath, { readonly: true, fileMustExist: true });\n try {\n const selectExpressions = memoryCurrentSelectExpressions(db);\n const rows = db.prepare(`\n SELECT\n memory_id,\n category,\n status,\n lifecycle_state,\n path_rel,\n created_at,\n updated_at,\n archived_at,\n superseded_at,\n entity_ref,\n source,\n confidence,\n confidence_tier,\n memory_kind,\n access_count,\n last_accessed,\n ${selectExpressions.tagsJson}, ${selectExpressions.previewText}, ${selectExpressions.privateRecord}\n FROM memory_current\n `).all() as Array<Record<string, unknown>>;\n\n return {\n projectionExists: true,\n rows: rows\n .map((row) => parseCurrentRow(memoryDir, row))\n .filter((row): row is MemoryProjectionCurrentState => row !== null),\n };\n } finally {\n db.close();\n }\n } catch {\n return { projectionExists: false, rows: [] };\n }\n}\n\nfunction readProjectedTimelineRows(\n memoryDir: string,\n): { projectionExists: boolean; rows: MemoryLifecycleEvent[] } {\n const dbPath = getMemoryProjectionPath(memoryDir);\n try {\n const db = openBetterSqlite3(dbPath, { readonly: true, fileMustExist: true });\n try {\n const rows = db.prepare(`\n SELECT\n event_id,\n memory_id,\n event_type,\n timestamp,\n actor,\n reason_code,\n rule_version,\n related_memory_ids_json,\n before_json,\n after_json,\n correlation_id\n FROM memory_timeline\n `).all() as Array<Record<string, unknown>>;\n\n return {\n projectionExists: true,\n rows: parseTimelineRows(rows),\n };\n } finally {\n db.close();\n }\n } catch {\n return { projectionExists: false, rows: [] };\n }\n}\n\n\nfunction writeProjectionDb(\n dbPath: string,\n nowIso: string,\n currentRows: MemoryProjectionCurrentState[],\n timelineRows: MemoryLifecycleEvent[],\n entityMentionRows: ProjectedEntityMentionRow[],\n nativeKnowledgeRows: ProjectedNativeKnowledgeChunkRow[],\n governance: Awaited<ReturnType<typeof loadLatestGovernanceProjection>>,\n usedLifecycleLedger: boolean,\n sourceLifecycleLedgerEventCount: number,\n): void {\n const db = openBetterSqlite3(dbPath);\n const memoryDir = path.dirname(path.dirname(dbPath));\n try {\n initializeMemoryProjectionDb(db);\n\n const insertMeta = db.prepare(\"INSERT OR REPLACE INTO meta(key, value) VALUES (?, ?)\");\n insertMeta.run(\"schemaVersion\", String(MEMORY_PROJECTION_SCHEMA_VERSION));\n insertMeta.run(\"rebuiltAt\", nowIso);\n insertMeta.run(\"usedLifecycleLedger\", usedLifecycleLedger ? \"true\" : \"false\");\n writeProjectionMetaHighWater(insertMeta, sourceLifecycleLedgerEventCount, timelineRows);\n insertMeta.run(\"latestGovernanceRunId\", governance?.runId ?? \"\");\n\n const insertCurrent = db.prepare(`\n INSERT INTO memory_current (\n memory_id,\n category,\n status,\n lifecycle_state,\n path_rel,\n path_valid,\n created_at,\n updated_at,\n archived_at,\n superseded_at,\n entity_ref,\n source,\n confidence,\n confidence_tier,\n memory_kind,\n access_count,\n last_accessed,\n tags_json, preview_text, private_record\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `);\n\n const insertTimeline = db.prepare(`\n INSERT INTO memory_timeline (\n event_id,\n memory_id,\n event_type,\n timestamp,\n event_order,\n actor,\n reason_code,\n rule_version,\n related_memory_ids_json,\n before_json,\n after_json,\n correlation_id\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `);\n\n const insertEntityMention = db.prepare(`\n INSERT INTO memory_entity_mentions (\n memory_id,\n entity_ref,\n mention_source,\n created_at,\n updated_at\n ) VALUES (?, ?, ?, ?, ?)\n `);\n\n const insertNativeKnowledge = db.prepare(`\n INSERT INTO native_knowledge_chunks (\n chunk_id,\n source_kind,\n source_path,\n title,\n start_line,\n end_line,\n namespace,\n privacy_class,\n derived_date,\n session_key,\n workflow_key,\n author,\n agent,\n source_hash,\n preview_text\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\n `);\n\n const insertGovernanceReviewQueue = db.prepare(`\n INSERT INTO memory_review_queue (\n entry_id,\n run_id,\n memory_id,\n path,\n reason_code,\n severity,\n suggested_action,\n suggested_status,\n related_memory_ids_json\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\n `);\n\n const insertGovernanceAppliedAction = db.prepare(`\n INSERT INTO memory_review_actions (\n row_key,\n run_id,\n action,\n memory_id,\n reason_code,\n before_status,\n after_status,\n original_path,\n current_path\n ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\n `);\n\n const insertGovernanceRun = db.prepare(`\n INSERT INTO memory_review_runs (\n run_id,\n created_at,\n mode,\n summary_json,\n metrics_json,\n applied_actions_json,\n report_markdown\n ) VALUES (?, ?, ?, ?, ?, ?, ?)\n `);\n\n const writeTx = db.transaction(() => {\n for (const row of currentRows) {\n insertCurrent.run(\n row.memoryId,\n row.category,\n row.status,\n row.lifecycleState ?? null,\n row.pathRel,\n isProjectedMemoryPathValid(memoryDir, row.pathRel) ? 1 : 0,\n row.created,\n row.updated,\n row.archivedAt ?? null,\n row.supersededAt ?? null,\n row.entityRef ?? null,\n row.source,\n row.confidence,\n row.confidenceTier,\n row.memoryKind ?? null,\n row.accessCount ?? null,\n row.lastAccessed ?? null, JSON.stringify(row.tags ?? []), row.preview ?? \"\",\n row.privateRecord === true ? 1 : 0,\n );\n }\n\n for (const event of timelineRows) {\n insertTimeline.run(\n event.eventId,\n event.memoryId,\n event.eventType,\n event.timestamp,\n MEMORY_LIFECYCLE_EVENT_SORT_ORDER[event.eventType],\n event.actor,\n event.reasonCode ?? null,\n event.ruleVersion,\n JSON.stringify(event.relatedMemoryIds ?? []),\n event.before ? JSON.stringify(event.before) : null,\n event.after ? JSON.stringify(event.after) : null,\n event.correlationId ?? null,\n );\n }\n\n for (const row of entityMentionRows) {\n insertEntityMention.run(\n row.memoryId,\n row.entityRef,\n row.mentionSource,\n row.created,\n row.updated,\n );\n }\n\n for (const row of nativeKnowledgeRows) {\n insertNativeKnowledge.run(\n row.chunkId,\n row.sourceKind,\n row.sourcePath,\n row.title,\n row.startLine,\n row.endLine,\n row.namespace ?? null,\n row.privacyClass ?? null,\n row.derivedDate ?? null,\n row.sessionKey ?? null,\n row.workflowKey ?? null,\n row.author ?? null,\n row.agent ?? null,\n row.sourceHash ?? null,\n row.preview,\n );\n }\n\n for (const row of governance?.reviewQueueRows ?? []) {\n insertGovernanceReviewQueue.run(\n row.entryId,\n row.runId,\n row.memoryId,\n row.path,\n row.reasonCode,\n row.severity,\n row.suggestedAction,\n row.suggestedStatus ?? null,\n JSON.stringify(row.relatedMemoryIds),\n );\n }\n\n for (const row of governance?.appliedActionRows ?? []) {\n insertGovernanceAppliedAction.run(\n row.rowKey,\n row.runId,\n row.action,\n row.memoryId,\n row.reasonCode,\n row.beforeStatus,\n row.afterStatus ?? null,\n row.originalPath,\n row.currentPath,\n );\n }\n\n if (governance) {\n const createdAt =\n typeof (governance.summary as { createdAt?: unknown } | undefined)?.createdAt === \"string\"\n ? (governance.summary as { createdAt: string }).createdAt\n : nowIso;\n const mode =\n typeof (governance.summary as { mode?: unknown } | undefined)?.mode === \"string\"\n ? (governance.summary as { mode: string }).mode\n : \"shadow\";\n insertGovernanceRun.run(\n governance.runId,\n createdAt,\n mode,\n JSON.stringify(governance.summary ?? null),\n JSON.stringify(governance.metrics ?? null),\n JSON.stringify(\n (governance.appliedActionRows ?? []).map((row) => ({\n action: row.action,\n memoryId: row.memoryId,\n reasonCode: row.reasonCode,\n beforeStatus: row.beforeStatus,\n afterStatus: row.afterStatus,\n originalPath: row.originalPath,\n currentPath: row.currentPath,\n })),\n ),\n governance.report,\n );\n }\n });\n\n writeTx();\n } finally {\n db.close();\n }\n}\n\nfunction mergeScopedCurrentRows(\n existingRows: MemoryProjectionCurrentState[],\n replacementRows: MemoryProjectionCurrentState[],\n scopedMemoryIds: Set<string>,\n): MemoryProjectionCurrentState[] {\n return [...existingRows.filter((row) => !scopedMemoryIds.has(row.memoryId)), ...replacementRows]\n .sort((a, b) => a.memoryId.localeCompare(b.memoryId));\n}\n\nfunction mergeScopedTimelineRows(\n existingRows: MemoryLifecycleEvent[],\n replacementRows: MemoryLifecycleEvent[],\n scopedMemoryIds: Set<string>,\n): MemoryLifecycleEvent[] {\n return sortMemoryLifecycleEvents([\n ...existingRows.filter((event) => !scopedMemoryIds.has(event.memoryId)),\n ...replacementRows,\n ]);\n}\n\nfunction mergeScopedEntityMentionRows(\n existingRows: ProjectedEntityMentionRow[],\n replacementRows: ProjectedEntityMentionRow[],\n scopedMemoryIds: Set<string>,\n): ProjectedEntityMentionRow[] {\n return [\n ...existingRows.filter((row) => !scopedMemoryIds.has(row.memoryId)),\n ...replacementRows,\n ].sort((left, right) =>\n [left.entityRef, left.memoryId, left.mentionSource].join(\"::\").localeCompare(\n [right.entityRef, right.memoryId, right.mentionSource].join(\"::\"),\n )\n );\n}\n\nexport async function rebuildMemoryProjection(\n options: RebuildMemoryProjectionOptions,\n): Promise<RebuildMemoryProjectionResult> {\n const dryRun = options.dryRun !== false;\n const now = options.now ?? new Date();\n const outputPath = getMemoryProjectionPath(options.memoryDir);\n const snapshot = await loadAuthoritativeProjectionSnapshot(options);\n\n let backupPath: string | undefined;\n if (!dryRun) {\n let nextCurrentRows = snapshot.currentRows;\n let nextTimelineRows = snapshot.timelineRows;\n let nextEntityMentionRows = snapshot.entityMentionRows;\n let nextNativeKnowledgeRows = snapshot.nativeKnowledgeRows;\n let nextGovernance = snapshot.governance;\n if (hasScopedProjectionFilter(snapshot.scope)) {\n nextCurrentRows = snapshot.scopedCurrentRows;\n nextTimelineRows = snapshot.scopedTimelineRows;\n nextEntityMentionRows = snapshot.scopedEntityMentionRows;\n const projectedCurrent = readProjectedCurrentRows(options.memoryDir);\n const projectedTimeline = readProjectedTimelineRows(options.memoryDir);\n const projectedEntityMentions = readProjectedEntityMentionRows(options.memoryDir);\n const projectedNativeKnowledge = readProjectedNativeKnowledgeRows(options.memoryDir);\n const projectedGovernance = readProjectedGovernanceRows(options.memoryDir);\n if (projectedCurrent.projectionExists && projectedTimeline.projectionExists) {\n const actualScopedCurrentRows = filterCurrentStateRowsForProjectionScope(\n projectedCurrent.rows,\n snapshot.scope,\n );\n const scopedMemoryIds = new Set([\n ...snapshot.scopedCurrentRows.map((row) => row.memoryId),\n ...snapshot.scopedTimelineRows.map((event) => event.memoryId),\n ...actualScopedCurrentRows.map((row) => row.memoryId),\n ]);\n nextCurrentRows = mergeScopedCurrentRows(\n projectedCurrent.rows,\n snapshot.scopedCurrentRows,\n scopedMemoryIds,\n );\n nextTimelineRows = mergeScopedTimelineRows(\n projectedTimeline.rows,\n snapshot.scopedTimelineRows,\n scopedMemoryIds,\n );\n nextEntityMentionRows = mergeScopedEntityMentionRows(\n projectedEntityMentions.rows,\n snapshot.scopedEntityMentionRows,\n scopedMemoryIds,\n );\n }\n if (projectedNativeKnowledge.projectionExists) {\n // Native knowledge rows are always loaded from the full persisted sync state,\n // so scoped memory rebuilds should publish the fresh snapshot instead of\n // pinning the projection to stale previously projected rows.\n nextNativeKnowledgeRows = snapshot.nativeKnowledgeRows;\n }\n if (projectedGovernance.projectionExists && projectedGovernance.runId) {\n // Governance rows are also sourced from standalone artifact snapshots, so\n // scoped memory rebuilds should keep the latest governance artifact data\n // instead of restoring whatever happened to be in the prior projection.\n nextGovernance = snapshot.governance;\n }\n }\n\n const tempPath = `${outputPath}.tmp`;\n await mkdir(path.dirname(outputPath), { recursive: true });\n await rm(tempPath, { force: true });\n writeProjectionDb(\n tempPath,\n now.toISOString(),\n nextCurrentRows,\n nextTimelineRows,\n nextEntityMentionRows,\n nextNativeKnowledgeRows,\n nextGovernance,\n snapshot.usedLifecycleLedger,\n snapshot.sourceLifecycleLedgerEventCount,\n );\n backupPath = await backupExistingProjection(options.memoryDir, outputPath, now);\n backupPath = await commitPreparedFileAtomically(tempPath, outputPath, backupPath);\n }\n\n return {\n dryRun,\n scannedMemories: snapshot.allMemories.length,\n currentRows: snapshot.scopedCurrentRows.length,\n timelineRows: snapshot.scopedTimelineRows.length,\n entityMentionRows: snapshot.scopedEntityMentionRows.length,\n nativeKnowledgeRows: snapshot.nativeKnowledgeRows.length,\n reviewQueueRows: snapshot.governance?.reviewQueueRows.length ?? 0,\n outputPath,\n backupPath,\n usedLifecycleLedger: snapshot.usedLifecycleLedger,\n skippedDuplicateMemories: snapshot.skippedDuplicateMemories,\n skippedBlankIdMemories: snapshot.skippedBlankIdMemories,\n skippedDuplicateTimelineEvents: snapshot.skippedDuplicateTimelineEvents,\n skippedBlankIdTimelineEvents: snapshot.skippedBlankIdTimelineEvents,\n scope: snapshot.scope,\n };\n}\n\nexport async function verifyMemoryProjection(\n options: VerifyMemoryProjectionOptions,\n): Promise<VerifyMemoryProjectionResult> {\n const outputPath = getMemoryProjectionPath(options.memoryDir);\n const snapshot = await loadAuthoritativeProjectionSnapshot(options);\n const projectedCurrent = readProjectedCurrentRows(options.memoryDir);\n const projectedTimeline = readProjectedTimelineRows(options.memoryDir);\n const projectedEntityMentions = readProjectedEntityMentionRows(options.memoryDir);\n const projectedNativeKnowledge = readProjectedNativeKnowledgeRows(options.memoryDir);\n const projectedGovernance = readProjectedGovernanceRows(options.memoryDir);\n const projectionExists = projectedCurrent.projectionExists\n || projectedTimeline.projectionExists\n || projectedEntityMentions.projectionExists\n || projectedNativeKnowledge.projectionExists\n || projectedGovernance.projectionExists;\n\n const actualScopedCurrentRows = filterCurrentStateRowsForProjectionScope(projectedCurrent.rows, snapshot.scope);\n const expectedCurrentById = new Map(\n snapshot.scopedCurrentRows.map((row) => [row.memoryId, serializeCurrentStateRow(row)]),\n );\n const actualCurrentById = new Map(\n actualScopedCurrentRows.map((row) => [row.memoryId, serializeCurrentStateRow(row)]),\n );\n\n const missingCurrentMemoryIds = [...expectedCurrentById.keys()]\n .filter((memoryId) => !actualCurrentById.has(memoryId))\n .sort();\n const extraCurrentMemoryIds = [...actualCurrentById.keys()]\n .filter((memoryId) => !expectedCurrentById.has(memoryId))\n .sort();\n const mismatchedCurrentMemoryIds = [...expectedCurrentById.keys()]\n .filter((memoryId) =>\n actualCurrentById.has(memoryId) && actualCurrentById.get(memoryId) !== expectedCurrentById.get(memoryId)\n )\n .sort();\n\n const selectedMemoryIds = new Set([\n ...snapshot.scopedCurrentRows.map((row) => row.memoryId),\n ...actualScopedCurrentRows.map((row) => row.memoryId),\n ]);\n const expectedTimelineById = new Map(\n snapshot.scopedTimelineRows.map((event) => [event.eventId, serializeTimelineEvent(event)]),\n );\n const actualTimelineRows = projectedTimeline.rows.filter((event) => selectedMemoryIds.has(event.memoryId));\n const actualTimelineById = new Map(\n actualTimelineRows.map((event) => [event.eventId, serializeTimelineEvent(event)]),\n );\n const missingTimelineEventIds = [...expectedTimelineById.keys()]\n .filter((eventId) => !actualTimelineById.has(eventId))\n .sort();\n const extraTimelineEventIds = [...actualTimelineById.keys()]\n .filter((eventId) => !expectedTimelineById.has(eventId))\n .sort();\n\n const expectedEntityMentionsByKey = new Map(\n snapshot.scopedEntityMentionRows.map((row) => [\n `${row.memoryId}::${row.entityRef}::${row.mentionSource}`,\n serializeEntityMentionRow(row),\n ]),\n );\n const actualScopedEntityMentionRows = projectedEntityMentions.rows.filter((row) => selectedMemoryIds.has(row.memoryId));\n const actualEntityMentionsByKey = new Map(\n actualScopedEntityMentionRows.map((row) => [\n `${row.memoryId}::${row.entityRef}::${row.mentionSource}`,\n serializeEntityMentionRow(row),\n ]),\n );\n const missingEntityMentionKeys = [...expectedEntityMentionsByKey.keys()]\n .filter((key) => !actualEntityMentionsByKey.has(key))\n .sort();\n const extraEntityMentionKeys = [...actualEntityMentionsByKey.keys()]\n .filter((key) => !expectedEntityMentionsByKey.has(key))\n .sort();\n const mismatchedEntityMentionKeys = [...expectedEntityMentionsByKey.keys()]\n .filter((key) =>\n actualEntityMentionsByKey.has(key) && actualEntityMentionsByKey.get(key) !== expectedEntityMentionsByKey.get(key)\n )\n .sort();\n\n const expectedNativeKnowledgeById = new Map(\n snapshot.nativeKnowledgeRows.map((row) => [row.chunkId, serializeNativeKnowledgeRow(row)]),\n );\n const actualNativeKnowledgeById = new Map(\n projectedNativeKnowledge.rows.map((row) => [row.chunkId, serializeNativeKnowledgeRow(row)]),\n );\n const missingNativeKnowledgeChunkIds = [...expectedNativeKnowledgeById.keys()]\n .filter((chunkId) => !actualNativeKnowledgeById.has(chunkId))\n .sort();\n const extraNativeKnowledgeChunkIds = [...actualNativeKnowledgeById.keys()]\n .filter((chunkId) => !expectedNativeKnowledgeById.has(chunkId))\n .sort();\n const mismatchedNativeKnowledgeChunkIds = [...expectedNativeKnowledgeById.keys()]\n .filter((chunkId) =>\n actualNativeKnowledgeById.has(chunkId) && actualNativeKnowledgeById.get(chunkId) !== expectedNativeKnowledgeById.get(chunkId)\n )\n .sort();\n\n const expectedReviewQueueById = new Map(\n (snapshot.governance?.reviewQueueRows ?? []).map((row) => [\n `${row.runId}::${row.entryId}`,\n serializeGovernanceReviewQueueRow(row),\n ]),\n );\n const actualReviewQueueById = new Map(\n projectedGovernance.reviewQueueRows.map((row) => [\n `${row.runId}::${row.entryId}`,\n serializeGovernanceReviewQueueRow(row),\n ]),\n );\n const missingReviewQueueEntryIds = [...expectedReviewQueueById.keys()]\n .filter((entryId) => !actualReviewQueueById.has(entryId))\n .sort();\n const extraReviewQueueEntryIds = [...actualReviewQueueById.keys()]\n .filter((entryId) => !expectedReviewQueueById.has(entryId))\n .sort();\n const mismatchedReviewQueueEntryIds = [...expectedReviewQueueById.keys()]\n .filter((entryId) =>\n actualReviewQueueById.has(entryId) && actualReviewQueueById.get(entryId) !== expectedReviewQueueById.get(entryId)\n )\n .sort();\n\n return {\n outputPath,\n projectionExists,\n ok:\n projectionExists &&\n missingCurrentMemoryIds.length === 0 &&\n extraCurrentMemoryIds.length === 0 &&\n mismatchedCurrentMemoryIds.length === 0 &&\n missingTimelineEventIds.length === 0 &&\n extraTimelineEventIds.length === 0 &&\n missingEntityMentionKeys.length === 0 &&\n extraEntityMentionKeys.length === 0 &&\n mismatchedEntityMentionKeys.length === 0 &&\n missingNativeKnowledgeChunkIds.length === 0 &&\n extraNativeKnowledgeChunkIds.length === 0 &&\n mismatchedNativeKnowledgeChunkIds.length === 0 &&\n missingReviewQueueEntryIds.length === 0 &&\n extraReviewQueueEntryIds.length === 0 &&\n mismatchedReviewQueueEntryIds.length === 0,\n expectedCurrentRows: snapshot.scopedCurrentRows.length,\n actualCurrentRows: actualScopedCurrentRows.length,\n expectedTimelineRows: snapshot.scopedTimelineRows.length,\n actualTimelineRows: actualTimelineRows.length,\n expectedEntityMentionRows: snapshot.scopedEntityMentionRows.length,\n actualEntityMentionRows: actualScopedEntityMentionRows.length,\n expectedNativeKnowledgeRows: snapshot.nativeKnowledgeRows.length,\n actualNativeKnowledgeRows: projectedNativeKnowledge.rows.length,\n expectedReviewQueueRows: snapshot.governance?.reviewQueueRows.length ?? 0,\n actualReviewQueueRows: projectedGovernance.reviewQueueRows.length,\n missingCurrentMemoryIds,\n extraCurrentMemoryIds,\n mismatchedCurrentMemoryIds,\n missingTimelineEventIds,\n extraTimelineEventIds,\n missingEntityMentionKeys,\n extraEntityMentionKeys,\n mismatchedEntityMentionKeys,\n missingNativeKnowledgeChunkIds,\n extraNativeKnowledgeChunkIds,\n mismatchedNativeKnowledgeChunkIds,\n missingReviewQueueEntryIds,\n extraReviewQueueEntryIds,\n mismatchedReviewQueueEntryIds,\n usedLifecycleLedger: snapshot.usedLifecycleLedger,\n scope: snapshot.scope,\n };\n}\n\nexport async function repairMemoryProjection(\n options: RepairMemoryProjectionOptions,\n): Promise<RepairMemoryProjectionResult> {\n const dryRun = options.dryRun !== false;\n const verify = await verifyMemoryProjection(options);\n if (verify.ok) {\n return {\n dryRun,\n repaired: false,\n verify,\n };\n }\n if (dryRun) {\n return {\n dryRun: true,\n repaired: false,\n verify,\n };\n }\n\n const rebuild = await rebuildMemoryProjection({\n ...options,\n dryRun: false,\n });\n const verified = await verifyMemoryProjection(options);\n return {\n dryRun: false,\n repaired: verified.ok,\n verify: verified,\n rebuild,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAO,UAAU;AACjB,SAAS,OAAO,IAAI,YAAY;AAwJhC,eAAsB,yBACpB,WACA,YACA,KAC6B;AAC7B,MAAI;AACF,UAAM,KAAK,UAAU;AAAA,EACvB,SAAS,KAAK;AACZ,QAAI,YAAY,KAAK,QAAQ,GAAG;AAC9B,aAAO;AAAA,IACT;AACA,UAAM;AAAA,EACR;AAEA,QAAM,aAAa,KAAK;AAAA,IACtB;AAAA,IACA;AAAA,IACA;AAAA,IACA,cAAc,GAAG;AAAA,IACjB;AAAA,IACA;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,qBAAqB,SAAiB,QAAkC;AAC/E,SAAO,kBAAkB,OAAO,aAAa,OAAO;AACtD;AAEA,SAAS,kBAAkB,WAAmB,QAAkD;AAC9F,QAAM,UAAU,gBAAgB,WAAW,OAAO,IAAI;AACtD,SAAO;AAAA,IACL,UAAU,OAAO,YAAY;AAAA,IAC7B,UAAU,OAAO,YAAY;AAAA,IAC7B,QAAQ,qBAAqB,SAAS,MAAM;AAAA,IAC5C,gBAAgB,OAAO,YAAY;AAAA,IACnC,MAAM,OAAO;AAAA,IACb;AAAA,IACA,SAAS,OAAO,YAAY;AAAA,IAC5B,SAAS,OAAO,YAAY;AAAA,IAC5B,YAAY,OAAO,YAAY;AAAA,IAC/B,cAAc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