@remnic/core 10.0.168 → 10.0.169
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 +138 -137
- package/dist/access-cli.js +138 -137
- package/dist/access-cli.js.map +1 -1
- package/dist/access-coding-context-resolution.js +11 -11
- package/dist/access-extraction-force-flush-preempt.js +138 -137
- package/dist/access-extraction-force-flush.js +138 -137
- package/dist/access-http-briefing.js +138 -137
- package/dist/access-http-query.js +138 -137
- package/dist/access-http.js +138 -137
- package/dist/access-identity-continuity-surface.js +138 -137
- package/dist/access-lcm-surface.js +138 -137
- package/dist/access-mcp.js +138 -137
- package/dist/access-observe-write-category.js +11 -11
- package/dist/access-observe-write-surface.js +138 -137
- package/dist/access-offline-manifest.js +9 -9
- package/dist/access-operations-batch.js +138 -137
- package/dist/access-operations.js +138 -137
- package/dist/access-recall-concurrency.js +138 -137
- package/dist/access-recall-excerpt-attribution.d.ts +19 -0
- package/dist/access-recall-excerpt-attribution.d.ts.map +1 -0
- package/dist/access-recall-excerpt-attribution.js +8 -0
- package/dist/access-recall-response.js +138 -137
- package/dist/access-recall-surface.d.ts.map +1 -1
- package/dist/access-recall-surface.js +138 -137
- package/dist/access-schema.js +10 -10
- package/dist/access-service.js +138 -137
- package/dist/active-recall.js +24 -24
- package/dist/adapters/index.js +4 -4
- package/dist/adapters/registry.js +2 -2
- package/dist/{auto-sync-L3M4RKJD.js → auto-sync-ACP5U5A3.js} +3 -3
- package/dist/binary-lifecycle/scanner.d.ts +2 -4
- package/dist/binary-lifecycle/scanner.d.ts.map +1 -1
- package/dist/briefing.js +13 -13
- package/dist/buffer-add-turns-bounded.d.ts +11 -1
- package/dist/buffer-add-turns-bounded.d.ts.map +1 -1
- package/dist/buffer-add-turns-bounded.js +3 -3
- package/dist/buffer-session-cap.d.ts +2 -2
- package/dist/buffer-session-cap.d.ts.map +1 -1
- package/dist/buffer-session-cap.js +1 -1
- package/dist/buffer.d.ts +3 -2
- package/dist/buffer.d.ts.map +1 -1
- package/dist/buffer.js +12 -12
- package/dist/calibration.d.ts +19 -2
- package/dist/calibration.d.ts.map +1 -1
- package/dist/calibration.js +28 -5
- package/dist/calibration.js.map +1 -1
- package/dist/{capsule-crypto-GWVG7LGC.js → capsule-crypto-7FJQINUR.js} +2 -2
- package/dist/{capsule-merge-VHBRF65A.js → capsule-merge-BADOICNP.js} +2 -2
- package/dist/causal-behavior.js +2 -2
- package/dist/causal-chain.js +2 -2
- package/dist/causal-consolidation.js +17 -17
- 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-OWHERGF2.js → chunk-2NLLXCJG.js} +2 -2
- package/dist/{chunk-D6BOOYNJ.js → chunk-32OTLNAU.js} +271 -237
- package/dist/chunk-32OTLNAU.js.map +1 -0
- package/dist/{chunk-L7SEYUHS.js → chunk-3I3NXB6X.js} +3 -3
- package/dist/{chunk-4NBUHYUV.js → chunk-3LADDLAF.js} +5 -5
- package/dist/{chunk-2DL3OFLD.js → chunk-45GEJRIG.js} +2 -2
- package/dist/{chunk-5BE3FLKL.js → chunk-5KDDAQ6K.js} +8 -8
- package/dist/{chunk-BPCR5DZP.js → chunk-62YZOQFR.js} +5 -5
- package/dist/chunk-62YZOQFR.js.map +1 -0
- package/dist/{chunk-HLWXCDUQ.js → chunk-63A2BU2B.js} +5 -5
- package/dist/{chunk-MOUSHJAR.js → chunk-7FPI5MFB.js} +5 -5
- package/dist/{chunk-ZX546Y3Y.js → chunk-7OYDFIL4.js} +2 -2
- package/dist/{chunk-CKZWLAHN.js → chunk-ACPFBVUD.js} +2 -2
- package/dist/{chunk-BKTCVXMK.js → chunk-AHOYKJ5X.js} +3 -3
- package/dist/{chunk-WEHSQBFR.js → chunk-AIF6V2OX.js} +9 -4
- package/dist/chunk-AIF6V2OX.js.map +1 -0
- package/dist/{chunk-FGT7CUYZ.js → chunk-ALTLOHO7.js} +2 -2
- package/dist/{chunk-FMFCQRDM.js → chunk-AUFPPBC3.js} +3 -3
- package/dist/{chunk-OAQRZ4SV.js → chunk-B5KTTWC7.js} +2 -2
- package/dist/{chunk-73TPOGS4.js → chunk-BFBS7OFQ.js} +9 -9
- package/dist/{chunk-QFTK6EDM.js → chunk-BFZFNXOC.js} +13 -13
- package/dist/{chunk-ZQUOUPP3.js → chunk-BHRPZBAH.js} +4 -4
- package/dist/{chunk-4L25GAYL.js → chunk-CX24SVLK.js} +2 -2
- package/dist/{chunk-YY57TRKN.js → chunk-D5ZLTLHF.js} +2 -2
- package/dist/{chunk-WEFFO2MJ.js → chunk-D6YCETHG.js} +2 -2
- package/dist/{chunk-ZDZJNXL6.js → chunk-DK2VBJ6Q.js} +4 -4
- package/dist/{chunk-VRHY7Y5A.js → chunk-DPL5VO5V.js} +3 -3
- package/dist/{chunk-LVGTH6IQ.js → chunk-E7ATID4Z.js} +11 -11
- package/dist/{chunk-CKELO7Q6.js → chunk-FHWX2REL.js} +2 -2
- package/dist/{chunk-CUPILBIP.js → chunk-FMIM36I4.js} +2 -2
- package/dist/{chunk-OWM2VWNX.js → chunk-FSXYBIEZ.js} +25 -24
- package/dist/chunk-FSXYBIEZ.js.map +1 -0
- package/dist/{chunk-A5UOREWD.js → chunk-FWTGO4NE.js} +2 -2
- package/dist/{chunk-3SL52JKD.js → chunk-FZVROZKC.js} +5 -5
- package/dist/{chunk-U3BCW7GX.js → chunk-G3RLCVJC.js} +3 -3
- package/dist/{chunk-UYIBNDQE.js → chunk-GF5NN3LE.js} +2 -2
- package/dist/{chunk-7OCKK5M5.js → chunk-GWY5ZFHP.js} +6 -6
- package/dist/{chunk-AL3TCNSJ.js → chunk-H3MLOQ7F.js} +24 -53
- package/dist/chunk-H3MLOQ7F.js.map +1 -0
- package/dist/{chunk-TNRGWJYT.js → chunk-H4IU24V5.js} +2 -2
- package/dist/{chunk-T4BT4FQN.js → chunk-HH6PXQ2B.js} +3 -3
- package/dist/{chunk-FEUWI5QH.js → chunk-HHPY5SSE.js} +2 -2
- package/dist/{chunk-OM5ESBES.js → chunk-HQPFACXO.js} +2 -2
- package/dist/{chunk-QLQUAVVP.js → chunk-I7WPLMUX.js} +16 -16
- package/dist/chunk-I7WPLMUX.js.map +1 -0
- package/dist/{chunk-IMULTENA.js → chunk-ID65XTF3.js} +2 -2
- package/dist/{chunk-WWQMZBDI.js → chunk-IJVU4ILJ.js} +4 -4
- package/dist/{chunk-GBSXTTLP.js → chunk-ITGAGNX5.js} +2 -2
- package/dist/chunk-IUGOGDCP.js +39 -0
- package/dist/chunk-IUGOGDCP.js.map +1 -0
- package/dist/{chunk-3PNJZTDV.js → chunk-JGGNUEVD.js} +2 -2
- package/dist/{chunk-YYXYZM2I.js → chunk-JN7OSQJR.js} +2 -2
- package/dist/{chunk-4D2EY4WM.js → chunk-K2DTHNDY.js} +6 -6
- package/dist/{chunk-TH6OYP6I.js → chunk-K36RMINQ.js} +3 -3
- package/dist/{chunk-OZKVVUJB.js → chunk-KIM5VNZN.js} +2 -2
- package/dist/{chunk-BFPQJNFZ.js → chunk-LXSDEPEK.js} +60 -11
- package/dist/{chunk-BFPQJNFZ.js.map → chunk-LXSDEPEK.js.map} +1 -1
- package/dist/{chunk-ZWDDY4WF.js → chunk-M7CFCRWJ.js} +2 -2
- package/dist/{chunk-QPFM6DHY.js → chunk-MTJFK42O.js} +2 -2
- package/dist/{chunk-RO5EGRAI.js → chunk-N3FRR6II.js} +2 -2
- package/dist/{chunk-UMEUU66X.js → chunk-O3OEVYUR.js} +2 -2
- package/dist/{chunk-J74YOBB3.js → chunk-PFR6ZKQI.js} +8 -8
- package/dist/{chunk-TAD6QMMD.js → chunk-PRC7SZYM.js} +2 -2
- package/dist/{chunk-LWZNSQN3.js → chunk-PUQQPLVV.js} +3 -3
- package/dist/{chunk-LWZNSQN3.js.map → chunk-PUQQPLVV.js.map} +1 -1
- package/dist/{chunk-GMO3BGOF.js → chunk-QC2MHZDD.js} +1 -1
- package/dist/{chunk-FOTFLHBN.js → chunk-QPLI7LUU.js} +3 -2
- package/dist/chunk-QPLI7LUU.js.map +1 -0
- package/dist/{chunk-2MWKUVHT.js → chunk-RK7SE3BL.js} +5 -5
- package/dist/{chunk-HDWISXFH.js → chunk-RVAPK2S7.js} +2 -2
- package/dist/{chunk-5PUZV73Z.js → chunk-SEIGLG62.js} +11 -11
- package/dist/{chunk-AVWOULJH.js → chunk-SH3GOZWK.js} +2 -2
- package/dist/{chunk-PFLN6TTW.js → chunk-T3MCVSUC.js} +2 -2
- package/dist/{chunk-WQUGCOKF.js → chunk-TFA6HPOA.js} +4 -4
- package/dist/{chunk-CLVILSBR.js → chunk-TGQW3AMK.js} +22 -22
- package/dist/{chunk-YZYAYUJQ.js → chunk-TLRIRISJ.js} +4 -4
- package/dist/{chunk-7VIJUZYW.js → chunk-TQ4CELUR.js} +3 -3
- package/dist/{chunk-5QDTZIGH.js → chunk-U7KP6QFU.js} +2 -2
- package/dist/{chunk-BUKK5SWA.js → chunk-UPD5XDJX.js} +5 -5
- package/dist/{chunk-BUKK5SWA.js.map → chunk-UPD5XDJX.js.map} +1 -1
- package/dist/{chunk-QVXEXGIM.js → chunk-VF6SC4OD.js} +2 -2
- package/dist/{chunk-EZG54YDS.js → chunk-VKXJQF5C.js} +2 -2
- package/dist/{chunk-RFLC6PKQ.js → chunk-VMRPLHEU.js} +2 -2
- package/dist/{chunk-U2PSE7MB.js → chunk-VPEIWMUT.js} +2 -2
- package/dist/{chunk-X67XNZ64.js → chunk-W4EJMMPP.js} +10 -10
- package/dist/{chunk-RB7NXZ2E.js → chunk-W4Q65VJL.js} +2 -2
- package/dist/{chunk-HDDRVXX4.js → chunk-W5LJ3SJ7.js} +2 -2
- package/dist/{chunk-W7N7NWG5.js → chunk-WCJQ3OUP.js} +2 -2
- package/dist/{chunk-JIF22AXI.js → chunk-WGKIXNLY.js} +5 -2
- package/dist/{chunk-JIF22AXI.js.map → chunk-WGKIXNLY.js.map} +1 -1
- package/dist/{chunk-FFWFFAP3.js → chunk-WI2WTIMY.js} +14 -8
- package/dist/chunk-WI2WTIMY.js.map +1 -0
- package/dist/{chunk-UVYI6VIX.js → chunk-X7Y7WX73.js} +1 -1
- package/dist/{chunk-22V3CMIW.js → chunk-XJTRIHTH.js} +8 -8
- package/dist/{chunk-SIONKXLU.js → chunk-XTRC6SSS.js} +14 -14
- package/dist/{chunk-SBRUTD5O.js → chunk-YSATDEBY.js} +5 -5
- package/dist/{chunk-3YOX2BQD.js → chunk-YWMCV5HL.js} +3 -3
- package/dist/{chunk-L272A5QW.js → chunk-YYDUBGUF.js} +30 -22
- package/dist/chunk-YYDUBGUF.js.map +1 -0
- package/dist/{chunk-6QWFZ3X5.js → chunk-ZA6CYFAK.js} +2 -2
- package/dist/cli.js +138 -137
- package/dist/coding/export-okf-codegraph.js +24 -24
- package/dist/coding/pre-action-gate.js +2 -2
- package/dist/compounding/engine.js +14 -14
- package/dist/config.js +24 -24
- package/dist/connectors/codex-marketplace.d.ts.map +1 -1
- package/dist/connectors/codex-materialize-runner.js +14 -14
- package/dist/connectors/codex-materialize.d.ts.map +1 -1
- package/dist/connectors/codex-materialize.js +1 -1
- package/dist/connectors/index.js +15 -15
- package/dist/consolidation-provenance-check.js +2 -2
- package/dist/convergence-refresh.js +15 -15
- package/dist/conversation-index/backend.js +2 -2
- package/dist/corpus-watermark.js +15 -15
- package/dist/deep-recall-http-glue.js +11 -11
- package/dist/embedding-fallback.js +2 -2
- package/dist/entity-retrieval.js +14 -14
- package/dist/event-order-recall.js +3 -3
- package/dist/explicit-capture.js +138 -137
- package/dist/extraction-judge.js +1 -1
- package/dist/extraction-normalization.js +1 -1
- package/dist/extraction-span-materialize.js +2 -2
- package/dist/extraction.js +27 -27
- package/dist/{graph-edge-decay-BC3IO2J4.js → graph-edge-decay-CXTNJ7IQ.js} +6 -6
- package/dist/graph-edge-decay-CXTNJ7IQ.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 +13 -13
- package/dist/index.js +197 -196
- package/dist/lcm/index.js +3 -3
- package/dist/local-llm.js +2 -2
- package/dist/location/index.js +14 -14
- package/dist/maintenance/memory-governance.js +13 -13
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +13 -13
- package/dist/maintenance/rebuild-memory-projection-runner.js +15 -15
- package/dist/maintenance/rebuild-memory-projection.js +14 -14
- package/dist/memory-browse.js +5 -5
- package/dist/memory-controller.d.ts.map +1 -1
- package/dist/memory-controller.js +1 -1
- package/dist/namespaces/migrate.js +14 -14
- package/dist/namespaces/search.js +7 -7
- package/dist/namespaces/storage.d.ts.map +1 -1
- package/dist/namespaces/storage.js +13 -13
- package/dist/offline-sync-changeset-generations.js +4 -4
- package/dist/offline-sync-embedding-generation.js +3 -3
- package/dist/offline-sync-snapshot-stream.js +7 -7
- package/dist/offline-sync.js +6 -6
- package/dist/operator-doctor-corpus.js +16 -16
- package/dist/operator-toolkit.js +35 -35
- package/dist/orchestration/backlog-scheduler.d.ts +4 -0
- package/dist/orchestration/backlog-scheduler.d.ts.map +1 -1
- package/dist/orchestration/backlog-scheduler.js +149 -142
- package/dist/orchestration/backlog-scheduler.js.map +1 -1
- package/dist/orchestration/buffer-drain-runner.js +139 -138
- package/dist/orchestration/extraction-persist-citation.d.ts +2 -2
- package/dist/orchestration/extraction-persist-citation.d.ts.map +1 -1
- package/dist/orchestration/extraction-persist.d.ts.map +1 -1
- package/dist/orchestration/maintenance.js +23 -23
- package/dist/orchestration/recall-internal.d.ts.map +1 -1
- package/dist/orchestration/turn-ingestion-buffered.d.ts.map +1 -1
- package/dist/orchestrator.d.ts.map +1 -1
- package/dist/orchestrator.js +140 -139
- package/dist/qmd.js +4 -4
- package/dist/recall-navigation.js +138 -137
- package/dist/recall-state-view-admission.js +5 -5
- package/dist/recall-state-view-packet.d.ts.map +1 -1
- package/dist/recall-state-view-packet.js +30 -8
- package/dist/recall-state-view-packet.js.map +1 -1
- package/dist/recall-why-service.js +5 -5
- package/dist/reconcile/manifest.js +2 -2
- package/dist/resume-bundles.js +25 -25
- package/dist/search/factory.js +6 -6
- package/dist/search/index.js +8 -8
- package/dist/semantic-consolidation.js +18 -18
- package/dist/semantic-rule-promotion.js +13 -13
- package/dist/semantic-rule-verifier.js +13 -13
- package/dist/source-agent-qualifier.js +18 -18
- package/dist/source-attribution.d.ts +3 -3
- package/dist/source-attribution.d.ts.map +1 -1
- package/dist/source-attribution.js +1 -1
- package/dist/standup/build.js +13 -13
- package/dist/storage.d.ts +1 -0
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +12 -12
- package/dist/summarizer.d.ts +7 -1
- package/dist/summarizer.d.ts.map +1 -1
- package/dist/summarizer.js +3 -3
- package/dist/support-passport/index.js +16 -16
- package/dist/transfer/autodetect.js +3 -3
- package/dist/transfer/backup.js +2 -2
- package/dist/transfer/capsule-export.js +3 -3
- package/dist/transfer/capsule-import.js +3 -3
- package/dist/transfer/export-okf.js +13 -13
- package/dist/transfer/import-json.js +2 -2
- package/dist/transfer/import-md.js +2 -2
- package/dist/transfer/types.d.ts +15 -3
- package/dist/transfer/types.d.ts.map +1 -1
- package/dist/transfer/types.js +3 -1
- package/dist/verified-recall.js +13 -13
- package/dist/who-knows-cli.js +14 -14
- package/dist/who-knows.js +13 -13
- package/package.json +2 -2
- package/src/access-cli.test.ts +9 -9
- package/src/access-recall-excerpt-attribution.ts +69 -0
- package/src/access-recall-surface.ts +23 -21
- package/src/access-service-raw-excerpt-read-gate.test.ts +192 -11
- package/src/backlog-scheduler.test.ts +31 -0
- package/src/binary-lifecycle/scanner.ts +35 -14
- package/src/buffer-add-turns-bounded.ts +16 -2
- package/src/buffer-session-cap.ts +4 -4
- package/src/buffer.ts +5 -5
- package/src/calibration.ts +56 -4
- package/src/connectors/codex-marketplace-git.test.ts +267 -0
- package/src/connectors/codex-marketplace.ts +76 -13
- package/src/connectors/codex-materialize.ts +29 -55
- package/src/memory-controller.test.ts +11 -0
- package/src/memory-controller.ts +5 -1
- package/src/namespaces/storage.ts +1 -0
- package/src/orchestration/backlog-scheduler.ts +12 -3
- package/src/orchestration/extraction-persist-citation.ts +5 -3
- package/src/orchestration/extraction-persist.ts +15 -14
- package/src/orchestration/recall-internal.ts +2 -3
- package/src/orchestration/turn-ingestion-buffered.test.ts +52 -1
- package/src/orchestration/turn-ingestion-buffered.ts +26 -8
- package/src/orchestrator.ts +1 -0
- package/src/recall-state-view-packet.test.ts +40 -0
- package/src/recall-state-view-packet.ts +46 -9
- package/src/source-attribution.test.ts +57 -0
- package/src/source-attribution.ts +46 -43
- package/src/storage.ts +4 -3
- package/src/summarizer-shutdown.test.ts +49 -16
- package/src/summarizer.ts +13 -5
- package/src/testing/subjects/memory-maintenance.test.ts +293 -0
- package/src/transfer/capsule-export.ts +2 -1
- package/src/transfer/capsule-taxonomy-version.test.ts +70 -0
- package/src/transfer/types.ts +13 -3
- package/dist/chunk-AL3TCNSJ.js.map +0 -1
- package/dist/chunk-BPCR5DZP.js.map +0 -1
- package/dist/chunk-D6BOOYNJ.js.map +0 -1
- package/dist/chunk-FFWFFAP3.js.map +0 -1
- package/dist/chunk-FOTFLHBN.js.map +0 -1
- package/dist/chunk-L272A5QW.js.map +0 -1
- package/dist/chunk-OWM2VWNX.js.map +0 -1
- package/dist/chunk-QLQUAVVP.js.map +0 -1
- package/dist/chunk-WEHSQBFR.js.map +0 -1
- /package/dist/{capsule-crypto-GWVG7LGC.js.map → access-recall-excerpt-attribution.js.map} +0 -0
- /package/dist/{auto-sync-L3M4RKJD.js.map → auto-sync-ACP5U5A3.js.map} +0 -0
- /package/dist/{graph-edge-decay-BC3IO2J4.js.map → capsule-crypto-7FJQINUR.js.map} +0 -0
- /package/dist/{capsule-merge-VHBRF65A.js.map → capsule-merge-BADOICNP.js.map} +0 -0
- /package/dist/{chunk-OWHERGF2.js.map → chunk-2NLLXCJG.js.map} +0 -0
- /package/dist/{chunk-L7SEYUHS.js.map → chunk-3I3NXB6X.js.map} +0 -0
- /package/dist/{chunk-4NBUHYUV.js.map → chunk-3LADDLAF.js.map} +0 -0
- /package/dist/{chunk-2DL3OFLD.js.map → chunk-45GEJRIG.js.map} +0 -0
- /package/dist/{chunk-5BE3FLKL.js.map → chunk-5KDDAQ6K.js.map} +0 -0
- /package/dist/{chunk-HLWXCDUQ.js.map → chunk-63A2BU2B.js.map} +0 -0
- /package/dist/{chunk-MOUSHJAR.js.map → chunk-7FPI5MFB.js.map} +0 -0
- /package/dist/{chunk-ZX546Y3Y.js.map → chunk-7OYDFIL4.js.map} +0 -0
- /package/dist/{chunk-CKZWLAHN.js.map → chunk-ACPFBVUD.js.map} +0 -0
- /package/dist/{chunk-BKTCVXMK.js.map → chunk-AHOYKJ5X.js.map} +0 -0
- /package/dist/{chunk-FGT7CUYZ.js.map → chunk-ALTLOHO7.js.map} +0 -0
- /package/dist/{chunk-FMFCQRDM.js.map → chunk-AUFPPBC3.js.map} +0 -0
- /package/dist/{chunk-OAQRZ4SV.js.map → chunk-B5KTTWC7.js.map} +0 -0
- /package/dist/{chunk-73TPOGS4.js.map → chunk-BFBS7OFQ.js.map} +0 -0
- /package/dist/{chunk-QFTK6EDM.js.map → chunk-BFZFNXOC.js.map} +0 -0
- /package/dist/{chunk-ZQUOUPP3.js.map → chunk-BHRPZBAH.js.map} +0 -0
- /package/dist/{chunk-4L25GAYL.js.map → chunk-CX24SVLK.js.map} +0 -0
- /package/dist/{chunk-YY57TRKN.js.map → chunk-D5ZLTLHF.js.map} +0 -0
- /package/dist/{chunk-WEFFO2MJ.js.map → chunk-D6YCETHG.js.map} +0 -0
- /package/dist/{chunk-ZDZJNXL6.js.map → chunk-DK2VBJ6Q.js.map} +0 -0
- /package/dist/{chunk-VRHY7Y5A.js.map → chunk-DPL5VO5V.js.map} +0 -0
- /package/dist/{chunk-LVGTH6IQ.js.map → chunk-E7ATID4Z.js.map} +0 -0
- /package/dist/{chunk-CKELO7Q6.js.map → chunk-FHWX2REL.js.map} +0 -0
- /package/dist/{chunk-CUPILBIP.js.map → chunk-FMIM36I4.js.map} +0 -0
- /package/dist/{chunk-A5UOREWD.js.map → chunk-FWTGO4NE.js.map} +0 -0
- /package/dist/{chunk-3SL52JKD.js.map → chunk-FZVROZKC.js.map} +0 -0
- /package/dist/{chunk-U3BCW7GX.js.map → chunk-G3RLCVJC.js.map} +0 -0
- /package/dist/{chunk-UYIBNDQE.js.map → chunk-GF5NN3LE.js.map} +0 -0
- /package/dist/{chunk-7OCKK5M5.js.map → chunk-GWY5ZFHP.js.map} +0 -0
- /package/dist/{chunk-TNRGWJYT.js.map → chunk-H4IU24V5.js.map} +0 -0
- /package/dist/{chunk-T4BT4FQN.js.map → chunk-HH6PXQ2B.js.map} +0 -0
- /package/dist/{chunk-FEUWI5QH.js.map → chunk-HHPY5SSE.js.map} +0 -0
- /package/dist/{chunk-OM5ESBES.js.map → chunk-HQPFACXO.js.map} +0 -0
- /package/dist/{chunk-IMULTENA.js.map → chunk-ID65XTF3.js.map} +0 -0
- /package/dist/{chunk-WWQMZBDI.js.map → chunk-IJVU4ILJ.js.map} +0 -0
- /package/dist/{chunk-GBSXTTLP.js.map → chunk-ITGAGNX5.js.map} +0 -0
- /package/dist/{chunk-3PNJZTDV.js.map → chunk-JGGNUEVD.js.map} +0 -0
- /package/dist/{chunk-YYXYZM2I.js.map → chunk-JN7OSQJR.js.map} +0 -0
- /package/dist/{chunk-4D2EY4WM.js.map → chunk-K2DTHNDY.js.map} +0 -0
- /package/dist/{chunk-TH6OYP6I.js.map → chunk-K36RMINQ.js.map} +0 -0
- /package/dist/{chunk-OZKVVUJB.js.map → chunk-KIM5VNZN.js.map} +0 -0
- /package/dist/{chunk-ZWDDY4WF.js.map → chunk-M7CFCRWJ.js.map} +0 -0
- /package/dist/{chunk-QPFM6DHY.js.map → chunk-MTJFK42O.js.map} +0 -0
- /package/dist/{chunk-RO5EGRAI.js.map → chunk-N3FRR6II.js.map} +0 -0
- /package/dist/{chunk-UMEUU66X.js.map → chunk-O3OEVYUR.js.map} +0 -0
- /package/dist/{chunk-J74YOBB3.js.map → chunk-PFR6ZKQI.js.map} +0 -0
- /package/dist/{chunk-TAD6QMMD.js.map → chunk-PRC7SZYM.js.map} +0 -0
- /package/dist/{chunk-GMO3BGOF.js.map → chunk-QC2MHZDD.js.map} +0 -0
- /package/dist/{chunk-2MWKUVHT.js.map → chunk-RK7SE3BL.js.map} +0 -0
- /package/dist/{chunk-HDWISXFH.js.map → chunk-RVAPK2S7.js.map} +0 -0
- /package/dist/{chunk-5PUZV73Z.js.map → chunk-SEIGLG62.js.map} +0 -0
- /package/dist/{chunk-AVWOULJH.js.map → chunk-SH3GOZWK.js.map} +0 -0
- /package/dist/{chunk-PFLN6TTW.js.map → chunk-T3MCVSUC.js.map} +0 -0
- /package/dist/{chunk-WQUGCOKF.js.map → chunk-TFA6HPOA.js.map} +0 -0
- /package/dist/{chunk-CLVILSBR.js.map → chunk-TGQW3AMK.js.map} +0 -0
- /package/dist/{chunk-YZYAYUJQ.js.map → chunk-TLRIRISJ.js.map} +0 -0
- /package/dist/{chunk-7VIJUZYW.js.map → chunk-TQ4CELUR.js.map} +0 -0
- /package/dist/{chunk-5QDTZIGH.js.map → chunk-U7KP6QFU.js.map} +0 -0
- /package/dist/{chunk-QVXEXGIM.js.map → chunk-VF6SC4OD.js.map} +0 -0
- /package/dist/{chunk-EZG54YDS.js.map → chunk-VKXJQF5C.js.map} +0 -0
- /package/dist/{chunk-RFLC6PKQ.js.map → chunk-VMRPLHEU.js.map} +0 -0
- /package/dist/{chunk-U2PSE7MB.js.map → chunk-VPEIWMUT.js.map} +0 -0
- /package/dist/{chunk-X67XNZ64.js.map → chunk-W4EJMMPP.js.map} +0 -0
- /package/dist/{chunk-RB7NXZ2E.js.map → chunk-W4Q65VJL.js.map} +0 -0
- /package/dist/{chunk-HDDRVXX4.js.map → chunk-W5LJ3SJ7.js.map} +0 -0
- /package/dist/{chunk-W7N7NWG5.js.map → chunk-WCJQ3OUP.js.map} +0 -0
- /package/dist/{chunk-UVYI6VIX.js.map → chunk-X7Y7WX73.js.map} +0 -0
- /package/dist/{chunk-22V3CMIW.js.map → chunk-XJTRIHTH.js.map} +0 -0
- /package/dist/{chunk-SIONKXLU.js.map → chunk-XTRC6SSS.js.map} +0 -0
- /package/dist/{chunk-SBRUTD5O.js.map → chunk-YSATDEBY.js.map} +0 -0
- /package/dist/{chunk-3YOX2BQD.js.map → chunk-YWMCV5HL.js.map} +0 -0
- /package/dist/{chunk-6QWFZ3X5.js.map → chunk-ZA6CYFAK.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/transfer/capsule-export.ts"],"sourcesContent":["import { mkdir, readFile, stat, unlink, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { gzipSync } from \"node:zlib\";\nimport { CAPSULE_SCHEMA_VERSION, EXPORT_FORMAT } from \"./constants.js\";\nimport {\n listFilesRecursive,\n sha256File,\n toPosixRelPath,\n writeJsonFile,\n} from \"./fs-utils.js\";\nimport {\n CAPSULE_ID_PATTERN,\n CapsuleBlockSchema,\n ExportBundleV2Schema,\n ExportManifestV2Schema,\n type CapsuleBlock,\n type ExportBundleV2,\n type ExportManifestV2,\n type ExportMemoryRecordV1,\n} from \"./types.js\";\nimport { encryptCapsuleFile } from \"./capsule-crypto.js\";\nimport { computeTransferOutputRel, DEFAULT_TRANSFER_EXCLUDE_DIRS } from \"./exclusions.js\";\n\n/**\n * Default subdirectory excludes applied to every capsule export. These match\n * the shared plaintext transfer exclusions plus the `transcripts`\n * directory, which is excluded by default and only included when the caller\n * explicitly passes `transcripts` in {@link ExportCapsuleOptions.includeKinds}.\n */\nconst DEFAULT_EXCLUDE_DIRS = DEFAULT_TRANSFER_EXCLUDE_DIRS;\n\nconst TRANSCRIPTS_DIR = \"transcripts\" as const;\n\n/**\n * Top-level directory under {@link ExportCapsuleOptions.root} that holds\n * per-peer profile bundles. When {@link ExportCapsuleOptions.peerIds} is\n * provided, only files under `peers/<peerId>/...` for the listed ids are\n * included; the rest of the `peers/` tree is excluded.\n */\nconst PEERS_DIR = \"peers\" as const;\n\n/**\n * Options accepted by {@link exportCapsule}.\n *\n * `name` — capsule id, validated against {@link CAPSULE_ID_PATTERN}. The id\n * also forms the manifest's `capsule.id` and the archive filename.\n *\n * `root` — absolute or cwd-relative path to the memory directory to export.\n *\n * `since` — optional ISO-8601 timestamp; only files with `mtime >= since`\n * are included.\n *\n * `includeKinds` — optional allow-list of top-level subdirectory names\n * (e.g. `facts`, `entities`, `corrections`, `transcripts`). When set, files\n * directly under {@link root} are excluded and only files whose first path\n * segment is in the allow-list are kept. Pass `transcripts` here explicitly\n * to opt-in transcripts (they are excluded by default).\n *\n * `peerIds` — optional allow-list restricting the `peers/` tree to files\n * under `peers/<peerId>/...`. When omitted the entire `peers/` tree is\n * included (subject to {@link includeKinds}). When set to an empty array\n * the `peers/` tree is excluded entirely.\n *\n * `outDir` — optional output directory. Defaults to `<root>/.capsules`.\n *\n * `pluginVersion` — recorded in the manifest. Defaults to `\"0.0.0\"` so\n * tests do not need to thread a version through; production callers SHOULD\n * pass the running plugin version.\n *\n * `capsule` — optional overrides for the manifest's `capsule` block. The\n * caller may pass any subset; remaining fields are filled with conservative\n * defaults documented inline below.\n *\n * `now` — optional clock override (ms epoch) used for `manifest.createdAt`.\n * Tests pass a fixed value for deterministic output.\n *\n * `encrypt` — when `true`, encrypt the output archive using the secure-store\n * master key for `memoryDir`. The keyring must be unlocked before calling\n * (`remnic secure-store unlock`). The plaintext `.capsule.json.gz` is written\n * first, then encrypted to `<name>.capsule.json.gz.enc`; the plaintext is\n * removed after successful encryption. Requires `memoryDir` to be provided.\n *\n * `memoryDir` — required when `encrypt` is `true`. The memory directory whose\n * secure-store keyring holds the master key.\n */\nexport interface ExportCapsuleOptions {\n name: string;\n root: string;\n since?: string;\n includeKinds?: readonly string[];\n peerIds?: readonly string[];\n outDir?: string;\n pluginVersion?: string;\n capsule?: Partial<Omit<CapsuleBlock, \"id\">>;\n now?: number;\n /**\n * When `true`, encrypt the output archive. Requires the secure-store to be\n * unlocked and `memoryDir` to be set. The plaintext `.capsule.json.gz` is\n * replaced by `<name>.capsule.json.gz.enc` on success.\n */\n encrypt?: boolean;\n /**\n * Memory directory whose secure-store keyring holds the master key. Required\n * when `encrypt` is `true`; ignored otherwise.\n */\n memoryDir?: string;\n /**\n * When `true`, include the `transcripts/` directory in the export even\n * though it is excluded by default. Using this flag avoids hard-coding an\n * explicit `includeKinds` allow-list that would inadvertently drop other\n * valid memory directories (`peers/`, `forks/`, etc.). (Cursor / #747)\n *\n * Ignored when `includeKinds` is provided and already contains\n * `\"transcripts\"`.\n */\n includeTranscripts?: boolean;\n}\n\nexport interface ExportCapsuleResult {\n archivePath: string;\n manifestPath: string;\n manifest: ExportManifestV2;\n /** When the export was encrypted, the `.enc` path. `null` when unencrypted. */\n encryptedArchivePath: string | null;\n}\n\n/**\n * Pure function that exports a memory directory as a portable, capsule-aware\n * V2 bundle.\n *\n * The output is a single `.capsule.json.gz` archive containing the entire\n * `ExportBundleV2` (manifest + records) plus a sidecar `manifest.json` for\n * cheap inspection. The bundle format is intentionally identical to the\n * existing `export-json` shape so PR 3/6's importer can reuse the V1 code\n * path with only a manifest version-dispatch.\n *\n * Determinism guarantees:\n * - `manifest.files` and `bundle.records` are sorted by posix path.\n * - `manifest.createdAt` is taken from {@link ExportCapsuleOptions.now}\n * when provided.\n * - The archive is gzip-compressed with default settings; no timestamp is\n * embedded (Node's `gzipSync` does not write a header timestamp when\n * using the synchronous helper, so byte-identical outputs are possible\n * given identical inputs).\n *\n * Empty result handling: a capsule with zero matching files is still a\n * valid capsule and produces a well-formed manifest with an empty `files`\n * array and an archive containing the empty bundle.\n */\nexport async function exportCapsule(\n opts: ExportCapsuleOptions,\n): Promise<ExportCapsuleResult> {\n validateName(opts.name);\n if (opts.encrypt === true && !opts.memoryDir) {\n throw new Error(\n \"exportCapsule: 'memoryDir' is required when 'encrypt' is true so the \" +\n \"secure-store key can be retrieved.\",\n );\n }\n const encryptionMemoryDir = opts.encrypt === true ? opts.memoryDir : undefined;\n const sinceMs = parseSince(opts.since);\n const includeKinds = normalizeIncludeKinds(opts.includeKinds);\n const peerFilter = normalizePeerIds(opts.peerIds);\n // `includeTranscripts: true` overrides the default transcripts exclusion\n // without requiring an explicit `includeKinds` list — so callers that want\n // all memory dirs + transcripts don't need to hard-code a list that would\n // inadvertently drop new dirs like `peers/` or `forks/`. (Cursor / #747)\n const transcriptsOverride = opts.includeTranscripts === true;\n\n const rootAbs = path.resolve(opts.root);\n await assertIsDirectory(rootAbs);\n\n const outDirAbs = path.resolve(opts.outDir ?? path.join(rootAbs, \".capsules\"));\n // Reject outDir === root: the input scan would otherwise be entirely\n // skipped by `shouldInclude` (outDirRelPosix === \".\") and the export would\n // silently succeed with an empty manifest/archive — a Rule 51 violation\n // and a data-loss footgun for callers that point outDir at the root.\n if (outDirAbs === rootAbs) {\n throw new Error(\n \"exportCapsule: 'outDir' must not equal 'root'. \" +\n \"Choose a separate directory (default: <root>/.capsules) so the \" +\n \"export does not overwrite or shadow the source tree.\",\n );\n }\n await mkdir(outDirAbs, { recursive: true });\n\n // If the output directory lives inside the export root, scan results would\n // re-import previous capsule archives on subsequent runs. Compute the\n // posix-relative path of the outDir under rootAbs (or `null` when it sits\n // outside) so {@link shouldInclude} can skip the entire subtree.\n const outDirRelPosix = computeTransferOutputRel(rootAbs, outDirAbs);\n\n const filesAbs = await listFilesRecursive(rootAbs);\n\n const records: ExportMemoryRecordV1[] = [];\n const manifestFiles: ExportManifestV2[\"files\"] = [];\n\n for (const abs of filesAbs) {\n const relPosix = toPosixRelPath(abs, rootAbs);\n if (!shouldInclude(relPosix, includeKinds, peerFilter, outDirRelPosix, transcriptsOverride)) continue;\n\n if (sinceMs !== null) {\n const st = await stat(abs);\n if (st.mtimeMs < sinceMs) continue;\n }\n\n const content = await readFile(abs, \"utf-8\");\n records.push({ path: relPosix, content });\n const { sha256, bytes } = await sha256File(abs);\n manifestFiles.push({ path: relPosix, sha256, bytes });\n }\n\n records.sort((a, b) => a.path.localeCompare(b.path));\n manifestFiles.sort((a, b) => a.path.localeCompare(b.path));\n\n const capsule = buildCapsuleBlock(opts.name, opts.capsule);\n const includesTranscripts =\n transcriptsOverride || (includeKinds ?? new Set<string>()).has(TRANSCRIPTS_DIR);\n\n const createdAtMs = opts.now ?? Date.now();\n const manifest = ExportManifestV2Schema.parse({\n format: EXPORT_FORMAT,\n schemaVersion: CAPSULE_SCHEMA_VERSION,\n createdAt: new Date(createdAtMs).toISOString(),\n pluginVersion: opts.pluginVersion ?? \"0.0.0\",\n includesTranscripts,\n files: manifestFiles,\n capsule,\n } satisfies ExportManifestV2);\n\n const bundle: ExportBundleV2 = ExportBundleV2Schema.parse({\n manifest,\n records,\n });\n\n const archivePath = path.join(outDirAbs, `${opts.name}.capsule.json.gz`);\n const manifestPath = path.join(outDirAbs, `${opts.name}.manifest.json`);\n\n // Sidecar manifest for cheap inspection without decompressing the archive.\n await writeJsonFile(manifestPath, manifest);\n\n // Single-artifact gzip archive containing the whole bundle. JSON encoded\n // before gzip so the archive is opaque to file-tree filtering. Using the\n // sync helper keeps the function pure async (no filesystem callback chain)\n // and matches the existing transfer modules' style.\n const json = JSON.stringify(bundle);\n const gz = gzipSync(Buffer.from(json, \"utf-8\"));\n await writeFile(archivePath, gz);\n\n // Optional encryption (PR 4/4). When opts.encrypt is true, wrap the\n // plaintext gzip in a REMNIC-ENC sealed envelope and remove the plaintext.\n // Per gotcha #54: write the encrypted file before removing the plaintext so\n // a crash mid-encrypt does not destroy the only copy.\n if (opts.encrypt === true) {\n try {\n const { encPath } = await encryptCapsuleFile({\n sourceGzPath: archivePath,\n memoryDir: encryptionMemoryDir!,\n });\n // Remove the plaintext only after the encrypted file was written successfully.\n await unlink(archivePath);\n return { archivePath: encPath, manifestPath, manifest, encryptedArchivePath: encPath };\n } catch (error) {\n try {\n await unlink(archivePath);\n } catch {\n // Best-effort cleanup: do not leave a plaintext capsule after a failed encrypted export.\n }\n throw error;\n }\n }\n\n return { archivePath, manifestPath, manifest, encryptedArchivePath: null };\n}\n\n// ---------------------------------------------------------------------------\n// Validation helpers\n// ---------------------------------------------------------------------------\n\nfunction validateName(name: unknown): void {\n if (typeof name !== \"string\" || !CAPSULE_ID_PATTERN.test(name)) {\n throw new Error(\n `exportCapsule: invalid capsule name. Expected /${CAPSULE_ID_PATTERN.source}/`,\n );\n }\n if (name.length > 64) {\n throw new Error(\n \"exportCapsule: invalid capsule name. Must be 64 characters or fewer.\",\n );\n }\n}\n\n/**\n * Strict ISO-8601 form accepted by {@link parseSince}. We accept exactly two\n * shapes:\n *\n * 1. Date-only: `YYYY-MM-DD` — interpreted as UTC midnight per ECMAScript.\n * 2. Date+time with an explicit timezone designator:\n * `YYYY-MM-DDTHH:MM(:SS(.fff)?)?(Z|±HH:MM)`.\n *\n * Notably **rejected**: date+time **without** a timezone (e.g.\n * `2026-02-28T00:00:00`). ECMAScript treats this as local time, which makes\n * acceptance and the resulting cutoff depend on the host's `TZ` and silently\n * shifts incremental-export windows for users outside UTC. Rule 51: reject\n * inputs that silently coerce to a host-dependent meaning.\n */\nconst ISO_8601_RE =\n /^\\d{4}-\\d{2}-\\d{2}(?:[Tt]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?(?:[Zz]|[+-]\\d{2}:?\\d{2}))?$/;\n\nfunction parseSince(since: string | undefined): number | null {\n if (since === undefined) return null;\n if (typeof since !== \"string\" || since.trim() === \"\") {\n throw new Error(\"exportCapsule: 'since' must be a non-empty ISO-8601 string\");\n }\n if (!ISO_8601_RE.test(since)) {\n throw new Error(\n `exportCapsule: 'since' is not a valid ISO-8601 timestamp: ${since}`,\n );\n }\n const ms = Date.parse(since);\n if (!Number.isFinite(ms)) {\n throw new Error(\n `exportCapsule: 'since' is not a valid ISO-8601 timestamp: ${since}`,\n );\n }\n // Reject calendar overflow: `Date.parse(\"2026-02-31\")` returns a finite ms\n // for March 3 because the JS Date constructor silently normalizes invalid\n // calendar values. Round-trip through `Date` and compare the year/month/day\n // components against the input prefix to catch this. Rule 51: silent\n // coercion of an exact time boundary is a Rule 51 violation that breaks\n // incremental exports.\n assertCalendarRoundTrip(since, ms);\n return ms;\n}\n\nexport function isValidCapsuleSince(since: string): boolean {\n try {\n parseSince(since);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Verify that parsing {@link since} did not silently normalize an invalid\n * calendar date (e.g. `2026-02-31` → `2026-03-03`). We extract the\n * year/month/day from the input string (regex-validated above) and compare\n * against the parsed Date's UTC components. Both date-only forms and forms\n * with an explicit Z/offset are normalized to UTC by `Date.parse`; for the\n * non-Z case where the offset shifts the calendar day across midnight, we\n * re-derive the input's intended UTC instant by accounting for the offset\n * before the comparison.\n */\nfunction assertCalendarRoundTrip(since: string, ms: number): void {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})/.exec(since);\n if (!m) return;\n const wantY = Number(m[1]);\n const wantMo = Number(m[2]);\n const wantD = Number(m[3]);\n\n // For inputs with an explicit non-zero offset, compare against the\n // wall-clock components of that offset instead of UTC. Date.parse maps to\n // UTC, so 2026-02-31T00:00:00-05:00 and 2026-02-31T00:00:00Z both fail the\n // calendar check; the wall-clock comparison via `m[1..3]` is still the\n // right reference because the input's stated calendar day must exist.\n const offsetMatch = /([+-])(\\d{2}):?(\\d{2})$/.exec(since);\n let displayMs = ms;\n if (offsetMatch) {\n const sign = offsetMatch[1] === \"-\" ? -1 : 1;\n const offsetMin = sign * (Number(offsetMatch[2]) * 60 + Number(offsetMatch[3]));\n displayMs = ms + offsetMin * 60_000;\n }\n const dd = new Date(displayMs);\n const gotY = dd.getUTCFullYear();\n const gotMo = dd.getUTCMonth() + 1;\n const gotD = dd.getUTCDate();\n if (gotY !== wantY || gotMo !== wantMo || gotD !== wantD) {\n throw new Error(\n `exportCapsule: 'since' is not a valid ISO-8601 timestamp: ${since}`,\n );\n }\n}\n\nfunction normalizeIncludeKinds(\n kinds: readonly string[] | undefined,\n): ReadonlySet<string> | null {\n if (kinds === undefined) return null;\n // Empty array is treated as \"include nothing\" rather than \"include all\"\n // so callers cannot accidentally widen the filter by passing []. This\n // mirrors PR-1/6 Rule 51: reject ambiguous input — but here we model it\n // as \"explicit empty allow-list\" rather than throwing, because empty\n // capsules ARE valid (see acceptance criteria).\n const set = new Set<string>();\n for (const raw of kinds) {\n if (typeof raw !== \"string\" || raw.trim() === \"\") {\n throw new Error(\"exportCapsule: 'includeKinds' entries must be non-empty strings\");\n }\n if (raw.includes(\"/\") || raw.includes(\"\\\\\")) {\n throw new Error(\n `exportCapsule: 'includeKinds' entries must be top-level segment names, got: ${raw}`,\n );\n }\n set.add(raw);\n }\n return set;\n}\n\nfunction normalizePeerIds(\n peerIds: readonly string[] | undefined,\n): ReadonlySet<string> | null {\n if (peerIds === undefined) return null;\n const set = new Set<string>();\n for (const raw of peerIds) {\n if (typeof raw !== \"string\" || raw.trim() === \"\") {\n throw new Error(\"exportCapsule: 'peerIds' entries must be non-empty strings\");\n }\n if (raw.includes(\"/\") || raw.includes(\"\\\\\") || raw === \".\" || raw === \"..\") {\n throw new Error(\n `exportCapsule: 'peerIds' entries must be plain segment names, got: ${raw}`,\n );\n }\n set.add(raw);\n }\n return set;\n}\n\nasync function assertIsDirectory(absPath: string): Promise<void> {\n // Mirror gotcha #24: existsSync returns true for files. The export root\n // MUST be a directory or the walk silently succeeds with zero entries.\n const st = await stat(absPath).catch(() => null);\n if (!st || !st.isDirectory()) {\n throw new Error(\n `exportCapsule: 'root' must be an existing directory: ${absPath}`,\n );\n }\n}\n\nfunction shouldInclude(\n relPosix: string,\n includeKinds: ReadonlySet<string> | null,\n peerFilter: ReadonlySet<string> | null,\n outDirRelPosix: string | null,\n transcriptsOverride = false,\n): boolean {\n const parts = relPosix.split(\"/\");\n if (parts.some((p) => DEFAULT_EXCLUDE_DIRS.has(p))) return false;\n\n // Exclude the output directory subtree. Without this, re-running against\n // the same root packages prior `.capsule.json.gz` archives and sidecar\n // manifests as records, causing bundle bloat and leaking stale exports.\n // `outDir === root` is rejected at the entrypoint (`exportCapsule`), so\n // {@link computeOutDirRel} never returns `\".\"` for the in-tree case here.\n if (outDirRelPosix !== null) {\n if (relPosix === outDirRelPosix) return false;\n if (relPosix.startsWith(`${outDirRelPosix}/`)) return false;\n }\n\n const top = parts[0];\n\n // Transcripts are opt-in: excluded unless caller explicitly listed them\n // in includeKinds OR passed `includeTranscripts: true`. The override flag\n // avoids the footgun of having the CLI build a hard-coded kinds list that\n // inadvertently drops valid memory dirs like `peers/` or `forks/`. (Cursor / #747)\n if (\n top === TRANSCRIPTS_DIR &&\n !transcriptsOverride &&\n (includeKinds === null || !includeKinds.has(TRANSCRIPTS_DIR))\n ) {\n return false;\n }\n\n if (includeKinds !== null) {\n // includeKinds restricts to whitelisted top-level segments. Files at\n // the repo root (no top-level dir) are excluded under an explicit\n // allow-list because they are not categorized.\n if (parts.length < 2) return false;\n if (!includeKinds.has(top)) return false;\n }\n\n if (top === PEERS_DIR && peerFilter !== null) {\n if (peerFilter.size === 0) return false;\n if (parts.length < 2) return false;\n if (!peerFilter.has(parts[1])) return false;\n }\n\n return true;\n}\n\n// ---------------------------------------------------------------------------\n// Capsule-block defaults\n// ---------------------------------------------------------------------------\n\n/**\n * Build a {@link CapsuleBlock} for the manifest. PR 2/6 ships a minimal\n * snapshot: tier-weights and `directAnswerEnabled` default to zod-passing\n * placeholders so the bundle parses cleanly. PRs 3/6+ will wire real\n * retrieval-policy and identity-anchor snapshots into the override path.\n *\n * Defaults (chosen to be safe + least-surprising):\n * - `version` — `0.1.0` (capsule authors override per release).\n * - `schemaVersion` — `taxonomy-v1` until the taxonomy registry stabilizes.\n * - `parentCapsule` — `null` (explicit \"no parent\" sentinel).\n * - `description` — empty string. Capsule authors override.\n * - `retrievalPolicy` — empty `tierWeights` map + `directAnswerEnabled: false`.\n * Empty weights mean \"no overrides\"; importers fall back to their local\n * policy. `false` is the least-privileged default per Rule 48.\n * - `includes` — all flags `false` until later PRs wire the\n * sub-bundles in.\n */\nfunction buildCapsuleBlock(\n name: string,\n override: Partial<Omit<CapsuleBlock, \"id\">> | undefined,\n): CapsuleBlock {\n // `parent` (structured, PR 4/6) and `parentCapsule` (legacy string) carry\n // overlapping information. The schema documents the invariant: when\n // `parent` is non-null, `parentCapsule` SHOULD equal `parent.capsuleId`.\n // We derive the legacy field from the structured field whenever the\n // caller supplies `parent` but omits `parentCapsule`, so a single-source\n // override path produces a manifest that satisfies the documented\n // invariant for legacy V2 readers (Cursor medium #751 round 3).\n // An explicit `parentCapsule` override still wins — including an explicit\n // `null` — so callers can intentionally diverge from the structured field\n // for migration scenarios.\n const parent = override?.parent ?? null;\n const parentCapsule =\n override && Object.prototype.hasOwnProperty.call(override, \"parentCapsule\")\n ? (override.parentCapsule ?? null)\n : (parent?.capsuleId ?? null);\n\n const merged: CapsuleBlock = {\n id: name,\n version: override?.version ?? \"0.1.0\",\n schemaVersion: override?.schemaVersion ?? \"taxonomy-v1\",\n parentCapsule,\n parent,\n description: override?.description ?? \"\",\n retrievalPolicy: override?.retrievalPolicy ?? {\n tierWeights: {},\n directAnswerEnabled: false,\n },\n includes: override?.includes ?? {\n taxonomy: false,\n identityAnchors: false,\n peerProfiles: false,\n procedural: false,\n },\n };\n // Re-parse to surface invalid overrides with the same zod errors a caller\n // would get when constructing a CapsuleBlock by hand.\n return CapsuleBlockSchema.parse(merged);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,UAAU,MAAM,QAAQ,iBAAiB;AACzD,OAAO,UAAU;AACjB,SAAS,gBAAgB;AA2BzB,IAAM,uBAAuB;AAE7B,IAAM,kBAAkB;AAQxB,IAAM,YAAY;AA8GlB,eAAsB,cACpB,MAC8B;AAC9B,eAAa,KAAK,IAAI;AACtB,MAAI,KAAK,YAAY,QAAQ,CAAC,KAAK,WAAW;AAC5C,UAAM,IAAI;AAAA,MACR;AAAA,I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,cAAc;AAAA,MACd,YAAY;AAAA,IACd;AAAA,EACF;AAGA,SAAO,mBAAmB,MAAM,MAAM;AACxC;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/transfer/capsule-export.ts"],"sourcesContent":["import { mkdir, readFile, stat, unlink, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { gzipSync } from \"node:zlib\";\nimport { CAPSULE_SCHEMA_VERSION, EXPORT_FORMAT } from \"./constants.js\";\nimport {\n listFilesRecursive,\n sha256File,\n toPosixRelPath,\n writeJsonFile,\n} from \"./fs-utils.js\";\nimport {\n CAPSULE_ID_PATTERN,\n CapsuleBlockSchema,\n ExportBundleV2Schema,\n ExportManifestV2Schema,\n type CapsuleBlock,\n type ExportBundleV2,\n type ExportManifestV2,\n type ExportMemoryRecordV1,\n} from \"./types.js\";\nimport { encryptCapsuleFile } from \"./capsule-crypto.js\";\nimport { computeTransferOutputRel, DEFAULT_TRANSFER_EXCLUDE_DIRS } from \"./exclusions.js\";\n\n/**\n * Default subdirectory excludes applied to every capsule export. These match\n * the shared plaintext transfer exclusions plus the `transcripts`\n * directory, which is excluded by default and only included when the caller\n * explicitly passes `transcripts` in {@link ExportCapsuleOptions.includeKinds}.\n */\nconst DEFAULT_EXCLUDE_DIRS = DEFAULT_TRANSFER_EXCLUDE_DIRS;\n\nconst TRANSCRIPTS_DIR = \"transcripts\" as const;\n\n/**\n * Top-level directory under {@link ExportCapsuleOptions.root} that holds\n * per-peer profile bundles. When {@link ExportCapsuleOptions.peerIds} is\n * provided, only files under `peers/<peerId>/...` for the listed ids are\n * included; the rest of the `peers/` tree is excluded.\n */\nconst PEERS_DIR = \"peers\" as const;\n\n/**\n * Options accepted by {@link exportCapsule}.\n *\n * `name` — capsule id, validated against {@link CAPSULE_ID_PATTERN}. The id\n * also forms the manifest's `capsule.id` and the archive filename.\n *\n * `root` — absolute or cwd-relative path to the memory directory to export.\n *\n * `since` — optional ISO-8601 timestamp; only files with `mtime >= since`\n * are included.\n *\n * `includeKinds` — optional allow-list of top-level subdirectory names\n * (e.g. `facts`, `entities`, `corrections`, `transcripts`). When set, files\n * directly under {@link root} are excluded and only files whose first path\n * segment is in the allow-list are kept. Pass `transcripts` here explicitly\n * to opt-in transcripts (they are excluded by default).\n *\n * `peerIds` — optional allow-list restricting the `peers/` tree to files\n * under `peers/<peerId>/...`. When omitted the entire `peers/` tree is\n * included (subject to {@link includeKinds}). When set to an empty array\n * the `peers/` tree is excluded entirely.\n *\n * `outDir` — optional output directory. Defaults to `<root>/.capsules`.\n *\n * `pluginVersion` — recorded in the manifest. Defaults to `\"0.0.0\"` so\n * tests do not need to thread a version through; production callers SHOULD\n * pass the running plugin version.\n *\n * `capsule` — optional overrides for the manifest's `capsule` block. The\n * caller may pass any subset; remaining fields are filled with conservative\n * defaults documented inline below.\n *\n * `now` — optional clock override (ms epoch) used for `manifest.createdAt`.\n * Tests pass a fixed value for deterministic output.\n *\n * `encrypt` — when `true`, encrypt the output archive using the secure-store\n * master key for `memoryDir`. The keyring must be unlocked before calling\n * (`remnic secure-store unlock`). The plaintext `.capsule.json.gz` is written\n * first, then encrypted to `<name>.capsule.json.gz.enc`; the plaintext is\n * removed after successful encryption. Requires `memoryDir` to be provided.\n *\n * `memoryDir` — required when `encrypt` is `true`. The memory directory whose\n * secure-store keyring holds the master key.\n */\nexport interface ExportCapsuleOptions {\n name: string;\n root: string;\n since?: string;\n includeKinds?: readonly string[];\n peerIds?: readonly string[];\n outDir?: string;\n pluginVersion?: string;\n capsule?: Partial<Omit<CapsuleBlock, \"id\">>;\n now?: number;\n /**\n * When `true`, encrypt the output archive. Requires the secure-store to be\n * unlocked and `memoryDir` to be set. The plaintext `.capsule.json.gz` is\n * replaced by `<name>.capsule.json.gz.enc` on success.\n */\n encrypt?: boolean;\n /**\n * Memory directory whose secure-store keyring holds the master key. Required\n * when `encrypt` is `true`; ignored otherwise.\n */\n memoryDir?: string;\n /**\n * When `true`, include the `transcripts/` directory in the export even\n * though it is excluded by default. Using this flag avoids hard-coding an\n * explicit `includeKinds` allow-list that would inadvertently drop other\n * valid memory directories (`peers/`, `forks/`, etc.). (Cursor / #747)\n *\n * Ignored when `includeKinds` is provided and already contains\n * `\"transcripts\"`.\n */\n includeTranscripts?: boolean;\n}\n\nexport interface ExportCapsuleResult {\n archivePath: string;\n manifestPath: string;\n manifest: ExportManifestV2;\n /** When the export was encrypted, the `.enc` path. `null` when unencrypted. */\n encryptedArchivePath: string | null;\n}\n\n/**\n * Pure function that exports a memory directory as a portable, capsule-aware\n * V2 bundle.\n *\n * The output is a single `.capsule.json.gz` archive containing the entire\n * `ExportBundleV2` (manifest + records) plus a sidecar `manifest.json` for\n * cheap inspection. The bundle format is intentionally identical to the\n * existing `export-json` shape so PR 3/6's importer can reuse the V1 code\n * path with only a manifest version-dispatch.\n *\n * Determinism guarantees:\n * - `manifest.files` and `bundle.records` are sorted by posix path.\n * - `manifest.createdAt` is taken from {@link ExportCapsuleOptions.now}\n * when provided.\n * - The archive is gzip-compressed with default settings; no timestamp is\n * embedded (Node's `gzipSync` does not write a header timestamp when\n * using the synchronous helper, so byte-identical outputs are possible\n * given identical inputs).\n *\n * Empty result handling: a capsule with zero matching files is still a\n * valid capsule and produces a well-formed manifest with an empty `files`\n * array and an archive containing the empty bundle.\n */\nexport async function exportCapsule(\n opts: ExportCapsuleOptions,\n): Promise<ExportCapsuleResult> {\n validateName(opts.name);\n if (opts.encrypt === true && !opts.memoryDir) {\n throw new Error(\n \"exportCapsule: 'memoryDir' is required when 'encrypt' is true so the \" +\n \"secure-store key can be retrieved.\",\n );\n }\n const encryptionMemoryDir = opts.encrypt === true ? opts.memoryDir : undefined;\n const sinceMs = parseSince(opts.since);\n const includeKinds = normalizeIncludeKinds(opts.includeKinds);\n const peerFilter = normalizePeerIds(opts.peerIds);\n // `includeTranscripts: true` overrides the default transcripts exclusion\n // without requiring an explicit `includeKinds` list — so callers that want\n // all memory dirs + transcripts don't need to hard-code a list that would\n // inadvertently drop new dirs like `peers/` or `forks/`. (Cursor / #747)\n const transcriptsOverride = opts.includeTranscripts === true;\n\n const rootAbs = path.resolve(opts.root);\n await assertIsDirectory(rootAbs);\n\n const outDirAbs = path.resolve(opts.outDir ?? path.join(rootAbs, \".capsules\"));\n // Reject outDir === root: the input scan would otherwise be entirely\n // skipped by `shouldInclude` (outDirRelPosix === \".\") and the export would\n // silently succeed with an empty manifest/archive — a Rule 51 violation\n // and a data-loss footgun for callers that point outDir at the root.\n if (outDirAbs === rootAbs) {\n throw new Error(\n \"exportCapsule: 'outDir' must not equal 'root'. \" +\n \"Choose a separate directory (default: <root>/.capsules) so the \" +\n \"export does not overwrite or shadow the source tree.\",\n );\n }\n await mkdir(outDirAbs, { recursive: true });\n\n // If the output directory lives inside the export root, scan results would\n // re-import previous capsule archives on subsequent runs. Compute the\n // posix-relative path of the outDir under rootAbs (or `null` when it sits\n // outside) so {@link shouldInclude} can skip the entire subtree.\n const outDirRelPosix = computeTransferOutputRel(rootAbs, outDirAbs);\n\n const filesAbs = await listFilesRecursive(rootAbs);\n\n const records: ExportMemoryRecordV1[] = [];\n const manifestFiles: ExportManifestV2[\"files\"] = [];\n\n for (const abs of filesAbs) {\n const relPosix = toPosixRelPath(abs, rootAbs);\n if (!shouldInclude(relPosix, includeKinds, peerFilter, outDirRelPosix, transcriptsOverride)) continue;\n\n if (sinceMs !== null) {\n const st = await stat(abs);\n if (st.mtimeMs < sinceMs) continue;\n }\n\n const content = await readFile(abs, \"utf-8\");\n records.push({ path: relPosix, content });\n const { sha256, bytes } = await sha256File(abs);\n manifestFiles.push({ path: relPosix, sha256, bytes });\n }\n\n records.sort((a, b) => a.path.localeCompare(b.path));\n manifestFiles.sort((a, b) => a.path.localeCompare(b.path));\n\n const capsule = buildCapsuleBlock(opts.name, opts.capsule);\n const includesTranscripts =\n transcriptsOverride || (includeKinds ?? new Set<string>()).has(TRANSCRIPTS_DIR);\n\n const createdAtMs = opts.now ?? Date.now();\n const manifest = ExportManifestV2Schema.parse({\n format: EXPORT_FORMAT,\n schemaVersion: CAPSULE_SCHEMA_VERSION,\n createdAt: new Date(createdAtMs).toISOString(),\n pluginVersion: opts.pluginVersion ?? \"0.0.0\",\n includesTranscripts,\n files: manifestFiles,\n capsule,\n } satisfies ExportManifestV2);\n\n const bundle: ExportBundleV2 = ExportBundleV2Schema.parse({\n manifest,\n records,\n });\n\n const archivePath = path.join(outDirAbs, `${opts.name}.capsule.json.gz`);\n const manifestPath = path.join(outDirAbs, `${opts.name}.manifest.json`);\n\n // Sidecar manifest for cheap inspection without decompressing the archive.\n await writeJsonFile(manifestPath, manifest);\n\n // Single-artifact gzip archive containing the whole bundle. JSON encoded\n // before gzip so the archive is opaque to file-tree filtering. Using the\n // sync helper keeps the function pure async (no filesystem callback chain)\n // and matches the existing transfer modules' style.\n const json = JSON.stringify(bundle);\n const gz = gzipSync(Buffer.from(json, \"utf-8\"));\n await writeFile(archivePath, gz);\n\n // Optional encryption (PR 4/4). When opts.encrypt is true, wrap the\n // plaintext gzip in a REMNIC-ENC sealed envelope and remove the plaintext.\n // Per gotcha #54: write the encrypted file before removing the plaintext so\n // a crash mid-encrypt does not destroy the only copy.\n if (opts.encrypt === true) {\n try {\n const { encPath } = await encryptCapsuleFile({\n sourceGzPath: archivePath,\n memoryDir: encryptionMemoryDir!,\n });\n // Remove the plaintext only after the encrypted file was written successfully.\n await unlink(archivePath);\n return { archivePath: encPath, manifestPath, manifest, encryptedArchivePath: encPath };\n } catch (error) {\n try {\n await unlink(archivePath);\n } catch {\n // Best-effort cleanup: do not leave a plaintext capsule after a failed encrypted export.\n }\n throw error;\n }\n }\n\n return { archivePath, manifestPath, manifest, encryptedArchivePath: null };\n}\n\n// ---------------------------------------------------------------------------\n// Validation helpers\n// ---------------------------------------------------------------------------\n\nfunction validateName(name: unknown): void {\n if (typeof name !== \"string\" || !CAPSULE_ID_PATTERN.test(name)) {\n throw new Error(\n `exportCapsule: invalid capsule name. Expected /${CAPSULE_ID_PATTERN.source}/`,\n );\n }\n if (name.length > 64) {\n throw new Error(\n \"exportCapsule: invalid capsule name. Must be 64 characters or fewer.\",\n );\n }\n}\n\n/**\n * Strict ISO-8601 form accepted by {@link parseSince}. We accept exactly two\n * shapes:\n *\n * 1. Date-only: `YYYY-MM-DD` — interpreted as UTC midnight per ECMAScript.\n * 2. Date+time with an explicit timezone designator:\n * `YYYY-MM-DDTHH:MM(:SS(.fff)?)?(Z|±HH:MM)`.\n *\n * Notably **rejected**: date+time **without** a timezone (e.g.\n * `2026-02-28T00:00:00`). ECMAScript treats this as local time, which makes\n * acceptance and the resulting cutoff depend on the host's `TZ` and silently\n * shifts incremental-export windows for users outside UTC. Rule 51: reject\n * inputs that silently coerce to a host-dependent meaning.\n */\nconst ISO_8601_RE =\n /^\\d{4}-\\d{2}-\\d{2}(?:[Tt]\\d{2}:\\d{2}(?::\\d{2}(?:\\.\\d{1,9})?)?(?:[Zz]|[+-]\\d{2}:?\\d{2}))?$/;\n\nfunction parseSince(since: string | undefined): number | null {\n if (since === undefined) return null;\n if (typeof since !== \"string\" || since.trim() === \"\") {\n throw new Error(\"exportCapsule: 'since' must be a non-empty ISO-8601 string\");\n }\n if (!ISO_8601_RE.test(since)) {\n throw new Error(\n `exportCapsule: 'since' is not a valid ISO-8601 timestamp: ${since}`,\n );\n }\n const ms = Date.parse(since);\n if (!Number.isFinite(ms)) {\n throw new Error(\n `exportCapsule: 'since' is not a valid ISO-8601 timestamp: ${since}`,\n );\n }\n // Reject calendar overflow: `Date.parse(\"2026-02-31\")` returns a finite ms\n // for March 3 because the JS Date constructor silently normalizes invalid\n // calendar values. Round-trip through `Date` and compare the year/month/day\n // components against the input prefix to catch this. Rule 51: silent\n // coercion of an exact time boundary is a Rule 51 violation that breaks\n // incremental exports.\n assertCalendarRoundTrip(since, ms);\n return ms;\n}\n\nexport function isValidCapsuleSince(since: string): boolean {\n try {\n parseSince(since);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Verify that parsing {@link since} did not silently normalize an invalid\n * calendar date (e.g. `2026-02-31` → `2026-03-03`). We extract the\n * year/month/day from the input string (regex-validated above) and compare\n * against the parsed Date's UTC components. Both date-only forms and forms\n * with an explicit Z/offset are normalized to UTC by `Date.parse`; for the\n * non-Z case where the offset shifts the calendar day across midnight, we\n * re-derive the input's intended UTC instant by accounting for the offset\n * before the comparison.\n */\nfunction assertCalendarRoundTrip(since: string, ms: number): void {\n const m = /^(\\d{4})-(\\d{2})-(\\d{2})/.exec(since);\n if (!m) return;\n const wantY = Number(m[1]);\n const wantMo = Number(m[2]);\n const wantD = Number(m[3]);\n\n // For inputs with an explicit non-zero offset, compare against the\n // wall-clock components of that offset instead of UTC. Date.parse maps to\n // UTC, so 2026-02-31T00:00:00-05:00 and 2026-02-31T00:00:00Z both fail the\n // calendar check; the wall-clock comparison via `m[1..3]` is still the\n // right reference because the input's stated calendar day must exist.\n const offsetMatch = /([+-])(\\d{2}):?(\\d{2})$/.exec(since);\n let displayMs = ms;\n if (offsetMatch) {\n const sign = offsetMatch[1] === \"-\" ? -1 : 1;\n const offsetMin = sign * (Number(offsetMatch[2]) * 60 + Number(offsetMatch[3]));\n displayMs = ms + offsetMin * 60_000;\n }\n const dd = new Date(displayMs);\n const gotY = dd.getUTCFullYear();\n const gotMo = dd.getUTCMonth() + 1;\n const gotD = dd.getUTCDate();\n if (gotY !== wantY || gotMo !== wantMo || gotD !== wantD) {\n throw new Error(\n `exportCapsule: 'since' is not a valid ISO-8601 timestamp: ${since}`,\n );\n }\n}\n\nfunction normalizeIncludeKinds(\n kinds: readonly string[] | undefined,\n): ReadonlySet<string> | null {\n if (kinds === undefined) return null;\n // Empty array is treated as \"include nothing\" rather than \"include all\"\n // so callers cannot accidentally widen the filter by passing []. This\n // mirrors PR-1/6 Rule 51: reject ambiguous input — but here we model it\n // as \"explicit empty allow-list\" rather than throwing, because empty\n // capsules ARE valid (see acceptance criteria).\n const set = new Set<string>();\n for (const raw of kinds) {\n if (typeof raw !== \"string\" || raw.trim() === \"\") {\n throw new Error(\"exportCapsule: 'includeKinds' entries must be non-empty strings\");\n }\n if (raw.includes(\"/\") || raw.includes(\"\\\\\")) {\n throw new Error(\n `exportCapsule: 'includeKinds' entries must be top-level segment names, got: ${raw}`,\n );\n }\n set.add(raw);\n }\n return set;\n}\n\nfunction normalizePeerIds(\n peerIds: readonly string[] | undefined,\n): ReadonlySet<string> | null {\n if (peerIds === undefined) return null;\n const set = new Set<string>();\n for (const raw of peerIds) {\n if (typeof raw !== \"string\" || raw.trim() === \"\") {\n throw new Error(\"exportCapsule: 'peerIds' entries must be non-empty strings\");\n }\n if (raw.includes(\"/\") || raw.includes(\"\\\\\") || raw === \".\" || raw === \"..\") {\n throw new Error(\n `exportCapsule: 'peerIds' entries must be plain segment names, got: ${raw}`,\n );\n }\n set.add(raw);\n }\n return set;\n}\n\nasync function assertIsDirectory(absPath: string): Promise<void> {\n // Mirror gotcha #24: existsSync returns true for files. The export root\n // MUST be a directory or the walk silently succeeds with zero entries.\n const st = await stat(absPath).catch(() => null);\n if (!st || !st.isDirectory()) {\n throw new Error(\n `exportCapsule: 'root' must be an existing directory: ${absPath}`,\n );\n }\n}\n\nfunction shouldInclude(\n relPosix: string,\n includeKinds: ReadonlySet<string> | null,\n peerFilter: ReadonlySet<string> | null,\n outDirRelPosix: string | null,\n transcriptsOverride = false,\n): boolean {\n const parts = relPosix.split(\"/\");\n if (parts.some((p) => DEFAULT_EXCLUDE_DIRS.has(p))) return false;\n\n // Exclude the output directory subtree. Without this, re-running against\n // the same root packages prior `.capsule.json.gz` archives and sidecar\n // manifests as records, causing bundle bloat and leaking stale exports.\n // `outDir === root` is rejected at the entrypoint (`exportCapsule`), so\n // {@link computeOutDirRel} never returns `\".\"` for the in-tree case here.\n if (outDirRelPosix !== null) {\n if (relPosix === outDirRelPosix) return false;\n if (relPosix.startsWith(`${outDirRelPosix}/`)) return false;\n }\n\n const top = parts[0];\n\n // Transcripts are opt-in: excluded unless caller explicitly listed them\n // in includeKinds OR passed `includeTranscripts: true`. The override flag\n // avoids the footgun of having the CLI build a hard-coded kinds list that\n // inadvertently drops valid memory dirs like `peers/` or `forks/`. (Cursor / #747)\n if (\n top === TRANSCRIPTS_DIR &&\n !transcriptsOverride &&\n (includeKinds === null || !includeKinds.has(TRANSCRIPTS_DIR))\n ) {\n return false;\n }\n\n if (includeKinds !== null) {\n // includeKinds restricts to whitelisted top-level segments. Files at\n // the repo root (no top-level dir) are excluded under an explicit\n // allow-list because they are not categorized.\n if (parts.length < 2) return false;\n if (!includeKinds.has(top)) return false;\n }\n\n if (top === PEERS_DIR && peerFilter !== null) {\n if (peerFilter.size === 0) return false;\n if (parts.length < 2) return false;\n if (!peerFilter.has(parts[1])) return false;\n }\n\n return true;\n}\n\n// ---------------------------------------------------------------------------\n// Capsule-block defaults\n// ---------------------------------------------------------------------------\n\n/**\n * Build a {@link CapsuleBlock} for the manifest. PR 2/6 ships a minimal\n * snapshot: tier-weights and `directAnswerEnabled` default to zod-passing\n * placeholders so the bundle parses cleanly. PRs 3/6+ will wire real\n * retrieval-policy and identity-anchor snapshots into the override path.\n *\n * Defaults (chosen to be safe + least-surprising):\n * - `version` — `0.1.0` (capsule authors override per release).\n * - `schemaVersion` — `taxonomy-v1` (the only member of\n * {@link CAPSULE_TAXONOMY_VERSIONS}; see issue 3572).\n * - `parentCapsule` — `null` (explicit \"no parent\" sentinel).\n * - `description` — empty string. Capsule authors override.\n * - `retrievalPolicy` — empty `tierWeights` map + `directAnswerEnabled: false`.\n * Empty weights mean \"no overrides\"; importers fall back to their local\n * policy. `false` is the least-privileged default per Rule 48.\n * - `includes` — all flags `false` until later PRs wire the\n * sub-bundles in.\n */\nfunction buildCapsuleBlock(\n name: string,\n override: Partial<Omit<CapsuleBlock, \"id\">> | undefined,\n): CapsuleBlock {\n // `parent` (structured, PR 4/6) and `parentCapsule` (legacy string) carry\n // overlapping information. The schema documents the invariant: when\n // `parent` is non-null, `parentCapsule` SHOULD equal `parent.capsuleId`.\n // We derive the legacy field from the structured field whenever the\n // caller supplies `parent` but omits `parentCapsule`, so a single-source\n // override path produces a manifest that satisfies the documented\n // invariant for legacy V2 readers (Cursor medium #751 round 3).\n // An explicit `parentCapsule` override still wins — including an explicit\n // `null` — so callers can intentionally diverge from the structured field\n // for migration scenarios.\n const parent = override?.parent ?? null;\n const parentCapsule =\n override && Object.prototype.hasOwnProperty.call(override, \"parentCapsule\")\n ? (override.parentCapsule ?? null)\n : (parent?.capsuleId ?? null);\n\n const merged: CapsuleBlock = {\n id: name,\n version: override?.version ?? \"0.1.0\",\n schemaVersion: override?.schemaVersion ?? \"taxonomy-v1\",\n parentCapsule,\n parent,\n description: override?.description ?? \"\",\n retrievalPolicy: override?.retrievalPolicy ?? {\n tierWeights: {},\n directAnswerEnabled: false,\n },\n includes: override?.includes ?? {\n taxonomy: false,\n identityAnchors: false,\n peerProfiles: false,\n procedural: false,\n },\n };\n // Re-parse to surface invalid overrides with the same zod errors a caller\n // would get when constructing a CapsuleBlock by hand.\n return CapsuleBlockSchema.parse(merged);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,OAAO,UAAU,MAAM,QAAQ,iBAAiB;AACzD,OAAO,UAAU;AACjB,SAAS,gBAAgB;AA2BzB,IAAM,uBAAuB;AAE7B,IAAM,kBAAkB;AAQxB,IAAM,YAAY;AA8GlB,eAAsB,cACpB,MAC8B;AAC9B,eAAa,KAAK,IAAI;AACtB,MAAI,KAAK,YAAY,QAAQ,CAAC,KAAK,WAAW;AAC5C,UAAM,IAAI;AAAA,MACR;AAAA,IAEF;AAAA,EACF;AACA,QAAM,sBAAsB,KAAK,YAAY,OAAO,KAAK,YAAY;AACrE,QAAM,UAAU,WAAW,KAAK,KAAK;AACrC,QAAM,eAAe,sBAAsB,KAAK,YAAY;AAC5D,QAAM,aAAa,iBAAiB,KAAK,OAAO;AAKhD,QAAM,sBAAsB,KAAK,uBAAuB;AAExD,QAAM,UAAU,KAAK,QAAQ,KAAK,IAAI;AACtC,QAA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import {
|
|
6
6
|
getConfiguredNamespaces
|
|
7
7
|
} from "./chunk-WECKZ3KT.js";
|
|
@@ -2308,4 +2308,4 @@ export {
|
|
|
2308
2308
|
runNamespaceMaintenancePlan,
|
|
2309
2309
|
runNamespaceMaintenanceBatchPlan
|
|
2310
2310
|
};
|
|
2311
|
-
//# sourceMappingURL=chunk-
|
|
2311
|
+
//# sourceMappingURL=chunk-VF6SC4OD.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import {
|
|
2
2
|
rebuildMemoryProjection,
|
|
3
3
|
watchProjectionRebuildParent
|
|
4
|
-
} from "./chunk-
|
|
4
|
+
} from "./chunk-TQ4CELUR.js";
|
|
5
5
|
import {
|
|
6
6
|
initLogger,
|
|
7
7
|
log
|
|
@@ -77,4 +77,4 @@ if (invokedAsRunner) {
|
|
|
77
77
|
export {
|
|
78
78
|
PROJECTION_REBUILD_RUNNER_FLAG
|
|
79
79
|
};
|
|
80
|
-
//# sourceMappingURL=chunk-
|
|
80
|
+
//# sourceMappingURL=chunk-VKXJQF5C.js.map
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
} from "./chunk-KJTKLXTH.js";
|
|
4
4
|
import {
|
|
5
5
|
StorageManager
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-FSXYBIEZ.js";
|
|
7
7
|
import {
|
|
8
8
|
assertInjectedStorageRooted
|
|
9
9
|
} from "./chunk-BNZAR6PO.js";
|
|
@@ -260,4 +260,4 @@ export {
|
|
|
260
260
|
backupExistingLedger,
|
|
261
261
|
rebuildMemoryLifecycleLedger
|
|
262
262
|
};
|
|
263
|
-
//# sourceMappingURL=chunk-
|
|
263
|
+
//# sourceMappingURL=chunk-VMRPLHEU.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
readAllEdges
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-BFBS7OFQ.js";
|
|
4
4
|
import {
|
|
5
5
|
readEdgeConfidence
|
|
6
6
|
} from "./chunk-2LSZVONP.js";
|
|
@@ -162,4 +162,4 @@ export {
|
|
|
162
162
|
parseGraphSnapshotSince,
|
|
163
163
|
buildGraphSnapshot
|
|
164
164
|
};
|
|
165
|
-
//# sourceMappingURL=chunk-
|
|
165
|
+
//# sourceMappingURL=chunk-VPEIWMUT.js.map
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import {
|
|
2
|
+
PROJECTION_REBUILD_RUNNER_FLAG
|
|
3
|
+
} from "./chunk-VKXJQF5C.js";
|
|
1
4
|
import {
|
|
2
5
|
ensureContradictionScanCron,
|
|
3
6
|
ensureDaySummaryCron,
|
|
@@ -9,29 +12,26 @@ import {
|
|
|
9
12
|
} from "./chunk-666A3MOW.js";
|
|
10
13
|
import {
|
|
11
14
|
rebuildMemoryLifecycleLedger
|
|
12
|
-
} from "./chunk-
|
|
13
|
-
import {
|
|
14
|
-
PROJECTION_REBUILD_RUNNER_FLAG
|
|
15
|
-
} from "./chunk-EZG54YDS.js";
|
|
15
|
+
} from "./chunk-VMRPLHEU.js";
|
|
16
16
|
import {
|
|
17
17
|
startLocationAutoSync
|
|
18
|
-
} from "./chunk-
|
|
18
|
+
} from "./chunk-AHOYKJ5X.js";
|
|
19
19
|
import {
|
|
20
20
|
CompoundingEngine,
|
|
21
21
|
isIsoWeekId,
|
|
22
22
|
msUntilNextIsoWeek,
|
|
23
23
|
previousIsoWeekId
|
|
24
|
-
} from "./chunk-
|
|
24
|
+
} from "./chunk-DPL5VO5V.js";
|
|
25
25
|
import {
|
|
26
26
|
planNamespaceMaintenance,
|
|
27
27
|
runNamespaceMaintenanceBatchPlan
|
|
28
|
-
} from "./chunk-
|
|
28
|
+
} from "./chunk-VF6SC4OD.js";
|
|
29
29
|
import {
|
|
30
30
|
rebuildMemoryProjection
|
|
31
|
-
} from "./chunk-
|
|
31
|
+
} from "./chunk-TQ4CELUR.js";
|
|
32
32
|
import {
|
|
33
33
|
LocalLlmClient
|
|
34
|
-
} from "./chunk-
|
|
34
|
+
} from "./chunk-BFZFNXOC.js";
|
|
35
35
|
import {
|
|
36
36
|
DEFAULT_TIMELINE_CATEGORIES,
|
|
37
37
|
TIMELINE_RESERVED_IDLE,
|
|
@@ -2874,4 +2874,4 @@ export {
|
|
|
2874
2874
|
ActivitySyncScheduler,
|
|
2875
2875
|
MaintenanceScheduler
|
|
2876
2876
|
};
|
|
2877
|
-
//# sourceMappingURL=chunk-
|
|
2877
|
+
//# sourceMappingURL=chunk-W4EJMMPP.js.map
|
|
@@ -3,7 +3,7 @@ import {
|
|
|
3
3
|
} from "./chunk-B7RWBZXW.js";
|
|
4
4
|
import {
|
|
5
5
|
resolveCausalTrajectoryStoreDir
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-QC2MHZDD.js";
|
|
7
7
|
import {
|
|
8
8
|
normalizeRecallTokens
|
|
9
9
|
} from "./chunk-YCVB7X56.js";
|
|
@@ -339,4 +339,4 @@ export {
|
|
|
339
339
|
scoreStitchCandidate,
|
|
340
340
|
stitchCausalChain
|
|
341
341
|
};
|
|
342
|
-
//# sourceMappingURL=chunk-
|
|
342
|
+
//# sourceMappingURL=chunk-W4Q65VJL.js.map
|
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
} from "./chunk-G4IAEX6D.js";
|
|
5
5
|
import {
|
|
6
6
|
ExportManifestV1Schema
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-AIF6V2OX.js";
|
|
8
8
|
import {
|
|
9
9
|
fileExists,
|
|
10
10
|
listFilesRecursive,
|
|
@@ -73,4 +73,4 @@ async function importMarkdownBundle(opts) {
|
|
|
73
73
|
export {
|
|
74
74
|
importMarkdownBundle
|
|
75
75
|
};
|
|
76
|
-
//# sourceMappingURL=chunk-
|
|
76
|
+
//# sourceMappingURL=chunk-W5LJ3SJ7.js.map
|
|
@@ -4,7 +4,7 @@ import {
|
|
|
4
4
|
import {
|
|
5
5
|
computeCorpusWatermarks,
|
|
6
6
|
resolveCorpusNamespaceRoots
|
|
7
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-U7KP6QFU.js";
|
|
8
8
|
|
|
9
9
|
// src/operator-doctor-corpus.ts
|
|
10
10
|
var DIGEST_PREFIX_LENGTH = 12;
|
|
@@ -78,4 +78,4 @@ export {
|
|
|
78
78
|
corpusWatermarksFromCheck,
|
|
79
79
|
summarizeCorpusAndReplica
|
|
80
80
|
};
|
|
81
|
-
//# sourceMappingURL=chunk-
|
|
81
|
+
//# sourceMappingURL=chunk-WCJQ3OUP.js.map
|
|
@@ -316,7 +316,10 @@ var MemoryControllerCoordinator = class {
|
|
|
316
316
|
} catch {
|
|
317
317
|
recorded = 1;
|
|
318
318
|
}
|
|
319
|
-
if (Number.isFinite(recorded)
|
|
319
|
+
if (!Number.isFinite(recorded)) {
|
|
320
|
+
recorded = 1;
|
|
321
|
+
}
|
|
322
|
+
if (recorded > this.consecutiveReceiptFailures) {
|
|
320
323
|
this.consecutiveReceiptFailures = recorded;
|
|
321
324
|
}
|
|
322
325
|
}
|
|
@@ -339,4 +342,4 @@ export {
|
|
|
339
342
|
evaluateActiveGates,
|
|
340
343
|
MemoryControllerCoordinator
|
|
341
344
|
};
|
|
342
|
-
//# sourceMappingURL=chunk-
|
|
345
|
+
//# sourceMappingURL=chunk-WGKIXNLY.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/memory-controller.ts"],"sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport { planRecallMode } from \"./intent.js\";\nimport { evaluateMemoryActionPolicy } from \"./memory-action-policy.js\";\nimport type { RuntimePolicyValues } from \"./policy-runtime.js\";\nimport type { UtilityRuntimeValues } from \"./utility-runtime.js\";\nimport type { MemoryActionEligibilityContext, MemoryActionType, RecallPlanMode } from \"./types.js\";\n\n/**\n * Gated unified memory controller (#2348).\n *\n * One state enters, one choice leaves. Host-free: every effectful collaborator\n * (adapters, executors, report reader, recorder, telemetry, clock) is injected.\n * The coordinator creates no store and claims no counterfactual lift.\n */\n\nexport type MemoryControllerMode = \"off\" | \"shadow\" | \"active\";\n\nexport type MemoryControllerActionFamily = \"persistent_memory\" | \"recall\" | \"active_context\" | \"no_op\";\n\n/** #2347 adapter seam: the host supplies plans, core only picks one. */\nexport interface ActiveContextMessage {\n id: string;\n text: string;\n}\n\nexport interface ActiveContextPlan {\n transform: \"SUMMARY\" | \"FILTER\";\n messageIds: string[];\n planId: string;\n}\n\nexport interface ActiveContextAdapter {\n plan(messages: ActiveContextMessage[]): ActiveContextPlan | null;\n}\n\n/** #2345 report + #2346 paired-seed evidence, read through one port. */\nexport interface MemoryControllerEvidenceReport {\n status: \"pass\" | \"fail\";\n version: string;\n configHash: string;\n generatedAt: string;\n /** sha256 over the canonical report fields; recomputed on verification. */\n reportHash: string;\n}\n\nexport interface MemoryControllerPairedSeedEvidence {\n status: \"pass\" | \"fail\";\n seedCount: number;\n generatedAt: string;\n}\n\nexport interface MemoryControllerEvidence {\n report: MemoryControllerEvidenceReport;\n pairedSeed: MemoryControllerPairedSeedEvidence;\n}\n\nexport interface MemoryControllerReportReader {\n read(): Promise<MemoryControllerEvidence | null>;\n}\n\nexport interface MemoryControllerReceipt {\n decisionId: string;\n ok: boolean;\n detail?: string;\n}\n\nexport interface MemoryControllerExecutors {\n executePersistentMemory?(input: {\n decisionId: string;\n action: MemoryActionType;\n eligibility: MemoryActionEligibilityContext;\n stateHash: string;\n }): Promise<MemoryControllerReceipt>;\n executeRecall?(input: { decisionId: string; mode: RecallPlanMode }): Promise<MemoryControllerReceipt>;\n executeActiveContext?(input: {\n decisionId: string;\n plan: ActiveContextPlan;\n }): Promise<MemoryControllerReceipt>;\n}\n\nexport interface MemoryControllerEvent {\n schemaVersion: 1;\n phase: \"choice\" | \"outcome\";\n decisionId: string;\n timestamp: string;\n requestedMode: MemoryControllerMode;\n effectiveMode: MemoryControllerMode;\n stateHash: string;\n choice: MemoryControllerChoice;\n scores: Record<MemoryControllerActionFamily, number>;\n executed: boolean;\n reviewOnly?: boolean;\n demotionReasons?: string[];\n failureClass?: \"record_failed\" | \"executor_error\" | \"bad_receipt\" | \"no_executor\";\n receipt?: MemoryControllerReceipt;\n}\n\nexport interface MemoryControllerRecorder {\n record(event: MemoryControllerEvent): Promise<void>;\n /** Prior shadow choice records; active promotion requires shadow history. */\n countShadowRecords(): Promise<number>;\n /**\n * Failed outcomes (executor_error, bad_receipt, no_executor) at the end of\n * the recorded stream, newest first, stopping at the first success. A new\n * coordinator seeds its receipt-failure gate from this count.\n */\n trailingReceiptFailures?(): Promise<number>;\n}\n\nexport interface MemoryControllerConfig {\n mode: MemoryControllerMode;\n /** Expected #2345 report schema version. */\n reportVersion: string;\n /** Evidence older than this is stale and forces shadow. */\n evidenceMaxAgeMs: number;\n /** Paired-seed arms must cover at least this many seeds (#2346). */\n minPairedSeeds: number;\n /** Active promotion requires at least this many prior shadow records. */\n shadowMinRecords: number;\n}\n\nexport interface MemoryControllerState {\n prompt: string;\n persistentMemoryCandidate?: {\n action: MemoryActionType;\n eligibility: MemoryActionEligibilityContext;\n };\n contextMessages?: ActiveContextMessage[];\n /** 0..1 host-measured context pressure. */\n contextPressure?: number;\n}\n\nexport type MemoryControllerChoice =\n | { family: \"persistent_memory\"; action: MemoryActionType; eligibility: MemoryActionEligibilityContext }\n | { family: \"recall\"; mode: RecallPlanMode }\n | { family: \"active_context\"; plan: ActiveContextPlan }\n | { family: \"no_op\" };\n\nexport interface MemoryControllerRunResult {\n decisionId: string;\n requestedMode: MemoryControllerMode;\n effectiveMode: MemoryControllerMode;\n stateHash: string;\n choice: MemoryControllerChoice;\n scores: Record<MemoryControllerActionFamily, number>;\n executed: boolean;\n reviewOnly: boolean;\n recorded: boolean;\n receipt?: MemoryControllerReceipt;\n demotionReasons: string[];\n}\n\nexport interface MemoryControllerDeps {\n config: MemoryControllerConfig;\n reportReader?: MemoryControllerReportReader;\n recorder?: MemoryControllerRecorder;\n executors?: MemoryControllerExecutors;\n activeContextAdapter?: ActiveContextAdapter;\n policyRuntime?: { loadRuntimeValues(): Promise<RuntimePolicyValues | null> };\n readUtilityRuntime?: () => Promise<UtilityRuntimeValues | null>;\n telemetry?: (event: MemoryControllerEvent) => void;\n clock?: () => Date;\n}\n\nconst NO_OP_FLOOR = 0.35;\n/** `discard` (and any destructive change) stays review-only in active mode. */\nconst REVIEW_ONLY_ACTIONS: Partial<Record<MemoryActionType, true>> = { discard: true };\n\nexport function controllerConfigHash(config: MemoryControllerConfig): string {\n return sha256(\n JSON.stringify({\n mode: config.mode,\n reportVersion: config.reportVersion,\n evidenceMaxAgeMs: config.evidenceMaxAgeMs,\n minPairedSeeds: config.minPairedSeeds,\n shadowMinRecords: config.shadowMinRecords,\n })\n );\n}\n\nexport function hashControllerState(state: MemoryControllerState): string {\n return sha256(\n JSON.stringify({\n prompt: state.prompt,\n persistentMemoryCandidate: state.persistentMemoryCandidate ?? null,\n contextMessages: state.contextMessages ?? null,\n contextPressure: state.contextPressure ?? null,\n })\n );\n}\n\n/** Canonical #2345 report hash; producers sign with this, the controller verifies. */\nexport function computeEvidenceReportHash(fields: {\n status: MemoryControllerEvidenceReport[\"status\"];\n version: string;\n configHash: string;\n generatedAt: string;\n}): string {\n return sha256(JSON.stringify(fields));\n}\n\n/** Verifies the #2345 report hash over its canonical fields. */\nexport function verifyEvidenceReport(report: MemoryControllerEvidenceReport): boolean {\n return (\n computeEvidenceReportHash({\n status: report.status,\n version: report.version,\n configHash: report.configHash,\n generatedAt: report.generatedAt,\n }) === report.reportHash\n );\n}\n\nfunction sha256(input: string): string {\n return createHash(\"sha256\").update(input).digest(\"hex\");\n}\n\nfunction clampScore(value: number): number {\n if (!Number.isFinite(value)) return Number.NaN;\n return Math.max(0, Math.min(1, value));\n}\n\n/**\n * Bad scores fail closed to `no_op`.\n */\nexport function chooseAction(input: {\n state: MemoryControllerState;\n activeContextAdapter?: ActiveContextAdapter;\n runtimeValues?: RuntimePolicyValues | null;\n utilityValues?: UtilityRuntimeValues | null;\n}): { choice: MemoryControllerChoice; scores: Record<MemoryControllerActionFamily, number> } {\n const { state, activeContextAdapter, runtimeValues, utilityValues } = input;\n\n // recall: current recall path.\n const recallMode = planRecallMode(state.prompt ?? \"\");\n const recallScore =\n recallMode === \"no_recall\" ? 0 : recallMode === \"minimal\" ? 0.4 : 0.6 + 0.2 * (runtimeValues?.recencyWeight ?? 0);\n\n // persistent_memory: current action path + policy.\n let persistentScore = 0;\n const candidate = state.persistentMemoryCandidate;\n if (candidate) {\n const policy = evaluateMemoryActionPolicy({\n action: candidate.action,\n eligibility: candidate.eligibility,\n options: { actionsEnabled: true, maxCompressionTokensPerHour: Number.POSITIVE_INFINITY },\n });\n if (policy.decision === \"allow\") {\n persistentScore = 0.4 + 0.4 * (candidate.eligibility.confidence ?? 0);\n } else if (policy.decision === \"defer\") {\n persistentScore = 0.2;\n }\n // Utility runtime may suppress the persistent family.\n if (utilityValues && utilityValues.rankingSuppressMultiplier > 1) {\n persistentScore *= 1 / utilityValues.rankingSuppressMultiplier;\n }\n }\n\n // active_context: current context path through the #2347 adapter.\n let contextScore = 0;\n let contextPlan: ActiveContextPlan | null = null;\n const pressure = state.contextPressure;\n if (activeContextAdapter && typeof pressure === \"number\" && Number.isFinite(pressure) && pressure > 0.5) {\n contextPlan = activeContextAdapter.plan(state.contextMessages ?? []);\n if (contextPlan && contextPlan.messageIds.length > 0) {\n contextScore = 0.3 + 0.5 * Math.max(0, Math.min(1, pressure));\n }\n }\n\n const scores: Record<MemoryControllerActionFamily, number> = {\n recall: clampScore(recallScore),\n persistent_memory: clampScore(persistentScore),\n active_context: clampScore(contextScore),\n no_op: NO_OP_FLOOR,\n };\n\n // Bad scores fail closed.\n if (Object.values(scores).some((score) => !Number.isFinite(score) || score < 0 || score > 1)) {\n return { choice: { family: \"no_op\" }, scores };\n }\n\n let choice: MemoryControllerChoice = { family: \"no_op\" };\n let best = scores.no_op;\n if (scores.recall > best) {\n best = scores.recall;\n choice = { family: \"recall\", mode: recallMode };\n }\n if (scores.persistent_memory > best) {\n best = scores.persistent_memory;\n choice = {\n family: \"persistent_memory\",\n action: candidate!.action,\n eligibility: candidate!.eligibility,\n };\n }\n if (scores.active_context > best) {\n choice = { family: \"active_context\", plan: contextPlan! };\n }\n return { choice, scores };\n}\n\n/** Returns the demotion reasons when active-mode gates fail; empty means go. */\nexport async function evaluateActiveGates(input: {\n config: MemoryControllerConfig;\n reportReader?: MemoryControllerReportReader;\n recorder?: MemoryControllerRecorder;\n consecutiveReceiptFailures: number;\n now: Date;\n}): Promise<string[]> {\n const { config, reportReader, recorder, consecutiveReceiptFailures, now } = input;\n const reasons: string[] = [];\n\n if (!reportReader) return [\"no_report_reader\"];\n\n const evidence = await reportReader.read();\n if (!evidence) return [\"no_evidence\"];\n\n const { report, pairedSeed } = evidence;\n if (report.status !== \"pass\") reasons.push(\"report_not_passing\");\n if (report.version !== config.reportVersion) reasons.push(\"report_version_mismatch\");\n if (report.configHash !== controllerConfigHash(config)) reasons.push(\"report_config_unbound\");\n if (!verifyEvidenceReport(report)) reasons.push(\"report_hash_invalid\");\n const reportGeneratedAt = Date.parse(report.generatedAt);\n if (!Number.isFinite(reportGeneratedAt) || now.getTime() - reportGeneratedAt > config.evidenceMaxAgeMs) {\n reasons.push(\"report_stale\");\n }\n\n if (pairedSeed.status !== \"pass\") reasons.push(\"paired_seed_not_passing\");\n if (pairedSeed.seedCount < config.minPairedSeeds) reasons.push(\"paired_seed_count_low\");\n const seedGeneratedAt = Date.parse(pairedSeed.generatedAt);\n if (!Number.isFinite(seedGeneratedAt) || now.getTime() - seedGeneratedAt > config.evidenceMaxAgeMs) {\n reasons.push(\"paired_seed_stale\");\n }\n\n const shadowRecords = recorder ? await recorder.countShadowRecords() : 0;\n if (shadowRecords < config.shadowMinRecords) reasons.push(\"shadow_history_insufficient\");\n\n if (consecutiveReceiptFailures > 0) reasons.push(\"recent_receipt_failures\");\n\n return reasons;\n}\n\nexport class MemoryControllerCoordinator {\n private readonly deps: MemoryControllerDeps;\n private readonly clock: () => Date;\n private consecutiveReceiptFailures = 0;\n private receiptFailuresSeeded = false;\n\n constructor(deps: MemoryControllerDeps) {\n this.deps = deps;\n this.clock = deps.clock ?? (() => new Date());\n }\n\n async run(state: MemoryControllerState): Promise<MemoryControllerRunResult> {\n const decisionId = randomUUID();\n const stateHash = hashControllerState(state);\n const requestedMode = this.deps.config.mode;\n\n // off: no choice, no read, no write, no call.\n if (requestedMode === \"off\") {\n return {\n decisionId,\n requestedMode,\n effectiveMode: \"off\",\n stateHash,\n choice: { family: \"no_op\" },\n scores: { persistent_memory: 0, recall: 0, active_context: 0, no_op: 0 },\n executed: false,\n reviewOnly: false,\n recorded: false,\n demotionReasons: [\"mode_off\"],\n };\n }\n\n const [runtimeValues, utilityValues] = await Promise.all([\n this.deps.policyRuntime?.loadRuntimeValues() ?? null,\n this.deps.readUtilityRuntime?.() ?? null,\n ]);\n const { choice, scores } = chooseAction({\n state,\n activeContextAdapter: this.deps.activeContextAdapter,\n runtimeValues,\n utilityValues,\n });\n\n let demotionReasons: string[] = [];\n let effectiveMode = requestedMode;\n if (requestedMode === \"active\") {\n await this.seedReceiptFailures();\n demotionReasons = await evaluateActiveGates({\n config: this.deps.config,\n reportReader: this.deps.reportReader,\n recorder: this.deps.recorder,\n consecutiveReceiptFailures: this.consecutiveReceiptFailures,\n now: this.clock(),\n });\n if (demotionReasons.length > 0) effectiveMode = \"shadow\";\n }\n\n const baseEvent: MemoryControllerEvent = {\n schemaVersion: 1,\n phase: \"choice\",\n decisionId,\n timestamp: this.clock().toISOString(),\n requestedMode,\n effectiveMode,\n stateHash,\n choice,\n scores,\n executed: false,\n ...(demotionReasons.length > 0 ? { demotionReasons } : {}),\n };\n\n // Shadow records before any active dispatch.\n let recorded = false;\n if (this.deps.recorder) {\n try {\n await this.deps.recorder.record(baseEvent);\n this.deps.telemetry?.(baseEvent);\n recorded = true;\n } catch {\n // Bad recorder stops work: no dispatch, no outcome event.\n return {\n decisionId,\n requestedMode,\n effectiveMode,\n stateHash,\n choice,\n scores,\n executed: false,\n reviewOnly: false,\n recorded: false,\n demotionReasons: [...demotionReasons, \"record_failed\"],\n };\n }\n }\n\n if (effectiveMode !== \"active\") {\n return {\n decisionId,\n requestedMode,\n effectiveMode,\n stateHash,\n choice,\n scores,\n executed: false,\n reviewOnly: false,\n recorded,\n demotionReasons,\n };\n }\n\n // First active scope: reversible actions only.\n if (choice.family === \"persistent_memory\" && REVIEW_ONLY_ACTIONS[choice.action]) {\n const event: MemoryControllerEvent = {\n ...baseEvent,\n phase: \"outcome\",\n reviewOnly: true,\n demotionReasons: [\"review_only_action\"],\n };\n await this.recordOutcome(event);\n return {\n decisionId,\n requestedMode,\n effectiveMode,\n stateHash,\n choice,\n scores,\n executed: false,\n reviewOnly: true,\n recorded,\n demotionReasons,\n };\n }\n\n const receipt = await this.dispatch(choice, stateHash, decisionId, baseEvent);\n return {\n decisionId,\n requestedMode,\n effectiveMode,\n stateHash,\n choice,\n scores,\n executed: receipt?.ok === true,\n reviewOnly: false,\n recorded,\n ...(receipt ? { receipt } : {}),\n demotionReasons,\n };\n }\n\n private async dispatch(\n choice: MemoryControllerChoice,\n stateHash: string,\n decisionId: string,\n baseEvent: MemoryControllerEvent\n ): Promise<MemoryControllerReceipt | undefined> {\n const executors = this.deps.executors ?? {};\n try {\n let receipt: MemoryControllerReceipt | undefined;\n if (choice.family === \"persistent_memory\") {\n if (!executors.executePersistentMemory) throw new Error(\"no_executor:persistent_memory\");\n receipt = await executors.executePersistentMemory({\n decisionId,\n action: choice.action,\n eligibility: choice.eligibility,\n stateHash,\n });\n } else if (choice.family === \"recall\") {\n if (!executors.executeRecall) throw new Error(\"no_executor:recall\");\n receipt = await executors.executeRecall({ decisionId, mode: choice.mode });\n } else if (choice.family === \"active_context\") {\n if (!executors.executeActiveContext) throw new Error(\"no_executor:active_context\");\n receipt = await executors.executeActiveContext({ decisionId, plan: choice.plan });\n } else {\n // no_op executed trivially; no executor call.\n receipt = { decisionId, ok: true };\n }\n if (!isValidReceipt(receipt, decisionId)) {\n this.consecutiveReceiptFailures += 1;\n await this.recordOutcome({ ...baseEvent, phase: \"outcome\", failureClass: \"bad_receipt\" });\n return undefined;\n }\n this.consecutiveReceiptFailures = 0;\n await this.recordOutcome({ ...baseEvent, phase: \"outcome\", executed: receipt.ok, receipt });\n return receipt;\n } catch (error) {\n this.consecutiveReceiptFailures += 1;\n await this.recordOutcome({\n ...baseEvent,\n phase: \"outcome\",\n failureClass: (error as Error)?.message?.startsWith(\"no_executor:\") ? \"no_executor\" : \"executor_error\",\n });\n return undefined;\n }\n }\n\n private async seedReceiptFailures(): Promise<void> {\n if (this.receiptFailuresSeeded) return;\n this.receiptFailuresSeeded = true;\n const reader = this.deps.recorder?.trailingReceiptFailures;\n if (!reader) return;\n let recorded: number;\n try {\n recorded = await reader.call(this.deps.recorder);\n } catch {\n // Unknown receipt health keeps the gate closed.\n recorded = 1;\n }\n if (Number.isFinite(recorded) && recorded > this.consecutiveReceiptFailures) {\n this.consecutiveReceiptFailures = recorded;\n }\n }\n\n private async recordOutcome(event: MemoryControllerEvent): Promise<void> {\n if (!this.deps.recorder) return;\n await this.deps.recorder.record(event);\n this.deps.telemetry?.(event);\n }\n}\n\nfunction isValidReceipt(receipt: unknown, decisionId: string): boolean {\n return (\n typeof receipt === \"object\" &&\n receipt !== null &&\n (receipt as MemoryControllerReceipt).decisionId === decisionId &&\n typeof (receipt as MemoryControllerReceipt).ok === \"boolean\"\n );\n}\n\n"],"mappings":";;;;;;;;AAAA,SAAS,YAAY,kBAAkB;AAoKvC,IAAM,cAAc;AAEpB,IAAM,sBAA+D,EAAE,SAAS,KAAK;AAE9E,SAAS,qBAAqB,QAAwC;AAC3E,SAAO;AAAA,IACL,KAAK,UAAU;AAAA,MACb,MAAM,OAAO;AAAA,MACb,eAAe,OAAO;AAAA,MACtB,kBAAkB,OAAO;AAAA,MACzB,gBAAgB,OAAO;AAAA,MACvB,kBAAkB,OAAO;AAAA,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,SAAS,OAAO;AACd,WAAK,8BAA8B;AACnC,YAAM,KAAK,cAAc;AAAA,QACvB,GAAG;AAAA,QACH,OAAO;AAAA,QACP,cAAe,OAAiB,SAAS,WAAW,cAAc,IAAI,gBAAgB;AAAA,MACxF,CAAC;AACD,aAAO;AAAA,IACT;AAAA,EACF;AAAA,EAEA,MAAc,sBAAqC;AACjD,QAAI,KAAK,sBAAuB;AAChC,SAAK,wBAAwB;AAC7B,UAAM,SAAS,KAAK,KAAK,UAAU;AACnC,QAAI,CAAC,OAAQ;AACb,QAAI;AACJ,QAAI;AACF,iBAAW,MAAM,OAAO,KAAK,KAAK,KAAK,QAAQ;AAAA,IACjD,QAAQ;AAEN,iBAAW;AAAA,IACb;AACA,QAAI,OAAO,SAAS,QAAQ,KAAK,WAAW,KAAK,4BAA4B;AAC3E,WAAK,6BAA6B;AAAA,IACpC;AAAA,EACF;AAAA,EAEA,MAAc,cAAc,OAA6C;AACvE,QAAI,CAAC,KAAK,KAAK,SAAU;AACzB,UAAM,KAAK,KAAK,SAAS,OAAO,KAAK;AACrC,SAAK,KAAK,YAAY,KAAK;AAAA,EAC7B;AACF;AAEA,SAAS,eAAe,SAAkB,YAA6B;AACrE,SACE,OAAO,YAAY,YACnB,YAAY,QACX,QAAoC,eAAe,cACpD,OAAQ,QAAoC,OAAO;AAEvD;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/memory-controller.ts"],"sourcesContent":["import { createHash, randomUUID } from \"node:crypto\";\nimport { planRecallMode } from \"./intent.js\";\nimport { evaluateMemoryActionPolicy } from \"./memory-action-policy.js\";\nimport type { RuntimePolicyValues } from \"./policy-runtime.js\";\nimport type { UtilityRuntimeValues } from \"./utility-runtime.js\";\nimport type { MemoryActionEligibilityContext, MemoryActionType, RecallPlanMode } from \"./types.js\";\n\n/**\n * Gated unified memory controller (#2348).\n *\n * One state enters, one choice leaves. Host-free: every effectful collaborator\n * (adapters, executors, report reader, recorder, telemetry, clock) is injected.\n * The coordinator creates no store and claims no counterfactual lift.\n */\n\nexport type MemoryControllerMode = \"off\" | \"shadow\" | \"active\";\n\nexport type MemoryControllerActionFamily = \"persistent_memory\" | \"recall\" | \"active_context\" | \"no_op\";\n\n/** #2347 adapter seam: the host supplies plans, core only picks one. */\nexport interface ActiveContextMessage {\n id: string;\n text: string;\n}\n\nexport interface ActiveContextPlan {\n transform: \"SUMMARY\" | \"FILTER\";\n messageIds: string[];\n planId: string;\n}\n\nexport interface ActiveContextAdapter {\n plan(messages: ActiveContextMessage[]): ActiveContextPlan | null;\n}\n\n/** #2345 report + #2346 paired-seed evidence, read through one port. */\nexport interface MemoryControllerEvidenceReport {\n status: \"pass\" | \"fail\";\n version: string;\n configHash: string;\n generatedAt: string;\n /** sha256 over the canonical report fields; recomputed on verification. */\n reportHash: string;\n}\n\nexport interface MemoryControllerPairedSeedEvidence {\n status: \"pass\" | \"fail\";\n seedCount: number;\n generatedAt: string;\n}\n\nexport interface MemoryControllerEvidence {\n report: MemoryControllerEvidenceReport;\n pairedSeed: MemoryControllerPairedSeedEvidence;\n}\n\nexport interface MemoryControllerReportReader {\n read(): Promise<MemoryControllerEvidence | null>;\n}\n\nexport interface MemoryControllerReceipt {\n decisionId: string;\n ok: boolean;\n detail?: string;\n}\n\nexport interface MemoryControllerExecutors {\n executePersistentMemory?(input: {\n decisionId: string;\n action: MemoryActionType;\n eligibility: MemoryActionEligibilityContext;\n stateHash: string;\n }): Promise<MemoryControllerReceipt>;\n executeRecall?(input: { decisionId: string; mode: RecallPlanMode }): Promise<MemoryControllerReceipt>;\n executeActiveContext?(input: {\n decisionId: string;\n plan: ActiveContextPlan;\n }): Promise<MemoryControllerReceipt>;\n}\n\nexport interface MemoryControllerEvent {\n schemaVersion: 1;\n phase: \"choice\" | \"outcome\";\n decisionId: string;\n timestamp: string;\n requestedMode: MemoryControllerMode;\n effectiveMode: MemoryControllerMode;\n stateHash: string;\n choice: MemoryControllerChoice;\n scores: Record<MemoryControllerActionFamily, number>;\n executed: boolean;\n reviewOnly?: boolean;\n demotionReasons?: string[];\n failureClass?: \"record_failed\" | \"executor_error\" | \"bad_receipt\" | \"no_executor\";\n receipt?: MemoryControllerReceipt;\n}\n\nexport interface MemoryControllerRecorder {\n record(event: MemoryControllerEvent): Promise<void>;\n /** Prior shadow choice records; active promotion requires shadow history. */\n countShadowRecords(): Promise<number>;\n /**\n * Failed outcomes (executor_error, bad_receipt, no_executor) at the end of\n * the recorded stream, newest first, stopping at the first success. A new\n * coordinator seeds its receipt-failure gate from this count.\n */\n trailingReceiptFailures?(): Promise<number>;\n}\n\nexport interface MemoryControllerConfig {\n mode: MemoryControllerMode;\n /** Expected #2345 report schema version. */\n reportVersion: string;\n /** Evidence older than this is stale and forces shadow. */\n evidenceMaxAgeMs: number;\n /** Paired-seed arms must cover at least this many seeds (#2346). */\n minPairedSeeds: number;\n /** Active promotion requires at least this many prior shadow records. */\n shadowMinRecords: number;\n}\n\nexport interface MemoryControllerState {\n prompt: string;\n persistentMemoryCandidate?: {\n action: MemoryActionType;\n eligibility: MemoryActionEligibilityContext;\n };\n contextMessages?: ActiveContextMessage[];\n /** 0..1 host-measured context pressure. */\n contextPressure?: number;\n}\n\nexport type MemoryControllerChoice =\n | { family: \"persistent_memory\"; action: MemoryActionType; eligibility: MemoryActionEligibilityContext }\n | { family: \"recall\"; mode: RecallPlanMode }\n | { family: \"active_context\"; plan: ActiveContextPlan }\n | { family: \"no_op\" };\n\nexport interface MemoryControllerRunResult {\n decisionId: string;\n requestedMode: MemoryControllerMode;\n effectiveMode: MemoryControllerMode;\n stateHash: string;\n choice: MemoryControllerChoice;\n scores: Record<MemoryControllerActionFamily, number>;\n executed: boolean;\n reviewOnly: boolean;\n recorded: boolean;\n receipt?: MemoryControllerReceipt;\n demotionReasons: string[];\n}\n\nexport interface MemoryControllerDeps {\n config: MemoryControllerConfig;\n reportReader?: MemoryControllerReportReader;\n recorder?: MemoryControllerRecorder;\n executors?: MemoryControllerExecutors;\n activeContextAdapter?: ActiveContextAdapter;\n policyRuntime?: { loadRuntimeValues(): Promise<RuntimePolicyValues | null> };\n readUtilityRuntime?: () => Promise<UtilityRuntimeValues | null>;\n telemetry?: (event: MemoryControllerEvent) => void;\n clock?: () => Date;\n}\n\nconst NO_OP_FLOOR = 0.35;\n/** `discard` (and any destructive change) stays review-only in active mode. */\nconst REVIEW_ONLY_ACTIONS: Partial<Record<MemoryActionType, true>> = { discard: true };\n\nexport function controllerConfigHash(config: MemoryControllerConfig): string {\n return sha256(\n JSON.stringify({\n mode: config.mode,\n reportVersion: config.reportVersion,\n evidenceMaxAgeMs: config.evidenceMaxAgeMs,\n minPairedSeeds: config.minPairedSeeds,\n shadowMinRecords: config.shadowMinRecords,\n })\n );\n}\n\nexport function hashControllerState(state: MemoryControllerState): string {\n return sha256(\n JSON.stringify({\n prompt: state.prompt,\n persistentMemoryCandidate: state.persistentMemoryCandidate ?? null,\n contextMessages: state.contextMessages ?? null,\n contextPressure: state.contextPressure ?? null,\n })\n );\n}\n\n/** Canonical #2345 report hash; producers sign with this, the controller verifies. */\nexport function computeEvidenceReportHash(fields: {\n status: MemoryControllerEvidenceReport[\"status\"];\n version: string;\n configHash: string;\n generatedAt: string;\n}): string {\n return sha256(JSON.stringify(fields));\n}\n\n/** Verifies the #2345 report hash over its canonical fields. */\nexport function verifyEvidenceReport(report: MemoryControllerEvidenceReport): boolean {\n return (\n computeEvidenceReportHash({\n status: report.status,\n version: report.version,\n configHash: report.configHash,\n generatedAt: report.generatedAt,\n }) === report.reportHash\n );\n}\n\nfunction sha256(input: string): string {\n return createHash(\"sha256\").update(input).digest(\"hex\");\n}\n\nfunction clampScore(value: number): number {\n if (!Number.isFinite(value)) return Number.NaN;\n return Math.max(0, Math.min(1, value));\n}\n\n/**\n * Bad scores fail closed to `no_op`.\n */\nexport function chooseAction(input: {\n state: MemoryControllerState;\n activeContextAdapter?: ActiveContextAdapter;\n runtimeValues?: RuntimePolicyValues | null;\n utilityValues?: UtilityRuntimeValues | null;\n}): { choice: MemoryControllerChoice; scores: Record<MemoryControllerActionFamily, number> } {\n const { state, activeContextAdapter, runtimeValues, utilityValues } = input;\n\n // recall: current recall path.\n const recallMode = planRecallMode(state.prompt ?? \"\");\n const recallScore =\n recallMode === \"no_recall\" ? 0 : recallMode === \"minimal\" ? 0.4 : 0.6 + 0.2 * (runtimeValues?.recencyWeight ?? 0);\n\n // persistent_memory: current action path + policy.\n let persistentScore = 0;\n const candidate = state.persistentMemoryCandidate;\n if (candidate) {\n const policy = evaluateMemoryActionPolicy({\n action: candidate.action,\n eligibility: candidate.eligibility,\n options: { actionsEnabled: true, maxCompressionTokensPerHour: Number.POSITIVE_INFINITY },\n });\n if (policy.decision === \"allow\") {\n persistentScore = 0.4 + 0.4 * (candidate.eligibility.confidence ?? 0);\n } else if (policy.decision === \"defer\") {\n persistentScore = 0.2;\n }\n // Utility runtime may suppress the persistent family.\n if (utilityValues && utilityValues.rankingSuppressMultiplier > 1) {\n persistentScore *= 1 / utilityValues.rankingSuppressMultiplier;\n }\n }\n\n // active_context: current context path through the #2347 adapter.\n let contextScore = 0;\n let contextPlan: ActiveContextPlan | null = null;\n const pressure = state.contextPressure;\n if (activeContextAdapter && typeof pressure === \"number\" && Number.isFinite(pressure) && pressure > 0.5) {\n contextPlan = activeContextAdapter.plan(state.contextMessages ?? []);\n if (contextPlan && contextPlan.messageIds.length > 0) {\n contextScore = 0.3 + 0.5 * Math.max(0, Math.min(1, pressure));\n }\n }\n\n const scores: Record<MemoryControllerActionFamily, number> = {\n recall: clampScore(recallScore),\n persistent_memory: clampScore(persistentScore),\n active_context: clampScore(contextScore),\n no_op: NO_OP_FLOOR,\n };\n\n // Bad scores fail closed.\n if (Object.values(scores).some((score) => !Number.isFinite(score) || score < 0 || score > 1)) {\n return { choice: { family: \"no_op\" }, scores };\n }\n\n let choice: MemoryControllerChoice = { family: \"no_op\" };\n let best = scores.no_op;\n if (scores.recall > best) {\n best = scores.recall;\n choice = { family: \"recall\", mode: recallMode };\n }\n if (scores.persistent_memory > best) {\n best = scores.persistent_memory;\n choice = {\n family: \"persistent_memory\",\n action: candidate!.action,\n eligibility: candidate!.eligibility,\n };\n }\n if (scores.active_context > best) {\n choice = { family: \"active_context\", plan: contextPlan! };\n }\n return { choice, scores };\n}\n\n/** Returns the demotion reasons when active-mode gates fail; empty means go. */\nexport async function evaluateActiveGates(input: {\n config: MemoryControllerConfig;\n reportReader?: MemoryControllerReportReader;\n recorder?: MemoryControllerRecorder;\n consecutiveReceiptFailures: number;\n now: Date;\n}): Promise<string[]> {\n const { config, reportReader, recorder, consecutiveReceiptFailures, now } = input;\n const reasons: string[] = [];\n\n if (!reportReader) return [\"no_report_reader\"];\n\n const evidence = await reportReader.read();\n if (!evidence) return [\"no_evidence\"];\n\n const { report, pairedSeed } = evidence;\n if (report.status !== \"pass\") reasons.push(\"report_not_passing\");\n if (report.version !== config.reportVersion) reasons.push(\"report_version_mismatch\");\n if (report.configHash !== controllerConfigHash(config)) reasons.push(\"report_config_unbound\");\n if (!verifyEvidenceReport(report)) reasons.push(\"report_hash_invalid\");\n const reportGeneratedAt = Date.parse(report.generatedAt);\n if (!Number.isFinite(reportGeneratedAt) || now.getTime() - reportGeneratedAt > config.evidenceMaxAgeMs) {\n reasons.push(\"report_stale\");\n }\n\n if (pairedSeed.status !== \"pass\") reasons.push(\"paired_seed_not_passing\");\n if (pairedSeed.seedCount < config.minPairedSeeds) reasons.push(\"paired_seed_count_low\");\n const seedGeneratedAt = Date.parse(pairedSeed.generatedAt);\n if (!Number.isFinite(seedGeneratedAt) || now.getTime() - seedGeneratedAt > config.evidenceMaxAgeMs) {\n reasons.push(\"paired_seed_stale\");\n }\n\n const shadowRecords = recorder ? await recorder.countShadowRecords() : 0;\n if (shadowRecords < config.shadowMinRecords) reasons.push(\"shadow_history_insufficient\");\n\n if (consecutiveReceiptFailures > 0) reasons.push(\"recent_receipt_failures\");\n\n return reasons;\n}\n\nexport class MemoryControllerCoordinator {\n private readonly deps: MemoryControllerDeps;\n private readonly clock: () => Date;\n private consecutiveReceiptFailures = 0;\n private receiptFailuresSeeded = false;\n\n constructor(deps: MemoryControllerDeps) {\n this.deps = deps;\n this.clock = deps.clock ?? (() => new Date());\n }\n\n async run(state: MemoryControllerState): Promise<MemoryControllerRunResult> {\n const decisionId = randomUUID();\n const stateHash = hashControllerState(state);\n const requestedMode = this.deps.config.mode;\n\n // off: no choice, no read, no write, no call.\n if (requestedMode === \"off\") {\n return {\n decisionId,\n requestedMode,\n effectiveMode: \"off\",\n stateHash,\n choice: { family: \"no_op\" },\n scores: { persistent_memory: 0, recall: 0, active_context: 0, no_op: 0 },\n executed: false,\n reviewOnly: false,\n recorded: false,\n demotionReasons: [\"mode_off\"],\n };\n }\n\n const [runtimeValues, utilityValues] = await Promise.all([\n this.deps.policyRuntime?.loadRuntimeValues() ?? null,\n this.deps.readUtilityRuntime?.() ?? null,\n ]);\n const { choice, scores } = chooseAction({\n state,\n activeContextAdapter: this.deps.activeContextAdapter,\n runtimeValues,\n utilityValues,\n });\n\n let demotionReasons: string[] = [];\n let effectiveMode = requestedMode;\n if (requestedMode === \"active\") {\n await this.seedReceiptFailures();\n demotionReasons = await evaluateActiveGates({\n config: this.deps.config,\n reportReader: this.deps.reportReader,\n recorder: this.deps.recorder,\n consecutiveReceiptFailures: this.consecutiveReceiptFailures,\n now: this.clock(),\n });\n if (demotionReasons.length > 0) effectiveMode = \"shadow\";\n }\n\n const baseEvent: MemoryControllerEvent = {\n schemaVersion: 1,\n phase: \"choice\",\n decisionId,\n timestamp: this.clock().toISOString(),\n requestedMode,\n effectiveMode,\n stateHash,\n choice,\n scores,\n executed: false,\n ...(demotionReasons.length > 0 ? { demotionReasons } : {}),\n };\n\n // Shadow records before any active dispatch.\n let recorded = false;\n if (this.deps.recorder) {\n try {\n await this.deps.recorder.record(baseEvent);\n this.deps.telemetry?.(baseEvent);\n recorded = true;\n } catch {\n // Bad recorder stops work: no dispatch, no outcome event.\n return {\n decisionId,\n requestedMode,\n effectiveMode,\n stateHash,\n choice,\n scores,\n executed: false,\n reviewOnly: false,\n recorded: false,\n demotionReasons: [...demotionReasons, \"record_failed\"],\n };\n }\n }\n\n if (effectiveMode !== \"active\") {\n return {\n decisionId,\n requestedMode,\n effectiveMode,\n stateHash,\n choice,\n scores,\n executed: false,\n reviewOnly: false,\n recorded,\n demotionReasons,\n };\n }\n\n // First active scope: reversible actions only.\n if (choice.family === \"persistent_memory\" && REVIEW_ONLY_ACTIONS[choice.action]) {\n const event: MemoryControllerEvent = {\n ...baseEvent,\n phase: \"outcome\",\n reviewOnly: true,\n demotionReasons: [\"review_only_action\"],\n };\n await this.recordOutcome(event);\n return {\n decisionId,\n requestedMode,\n effectiveMode,\n stateHash,\n choice,\n scores,\n executed: false,\n reviewOnly: true,\n recorded,\n demotionReasons,\n };\n }\n\n const receipt = await this.dispatch(choice, stateHash, decisionId, baseEvent);\n return {\n decisionId,\n requestedMode,\n effectiveMode,\n stateHash,\n choice,\n scores,\n executed: receipt?.ok === true,\n reviewOnly: false,\n recorded,\n ...(receipt ? { receipt } : {}),\n demotionReasons,\n };\n }\n\n private async dispatch(\n choice: MemoryControllerChoice,\n stateHash: string,\n decisionId: string,\n baseEvent: MemoryControllerEvent\n ): Promise<MemoryControllerReceipt | undefined> {\n const executors = this.deps.executors ?? {};\n try {\n let receipt: MemoryControllerReceipt | undefined;\n if (choice.family === \"persistent_memory\") {\n if (!executors.executePersistentMemory) throw new Error(\"no_executor:persistent_memory\");\n receipt = await executors.executePersistentMemory({\n decisionId,\n action: choice.action,\n eligibility: choice.eligibility,\n stateHash,\n });\n } else if (choice.family === \"recall\") {\n if (!executors.executeRecall) throw new Error(\"no_executor:recall\");\n receipt = await executors.executeRecall({ decisionId, mode: choice.mode });\n } else if (choice.family === \"active_context\") {\n if (!executors.executeActiveContext) throw new Error(\"no_executor:active_context\");\n receipt = await executors.executeActiveContext({ decisionId, plan: choice.plan });\n } else {\n // no_op executed trivially; no executor call.\n receipt = { decisionId, ok: true };\n }\n if (!isValidReceipt(receipt, decisionId)) {\n this.consecutiveReceiptFailures += 1;\n await this.recordOutcome({ ...baseEvent, phase: \"outcome\", failureClass: \"bad_receipt\" });\n return undefined;\n }\n this.consecutiveReceiptFailures = 0;\n await this.recordOutcome({ ...baseEvent, phase: \"outcome\", executed: receipt.ok, receipt });\n return receipt;\n } catch (error) {\n this.consecutiveReceiptFailures += 1;\n await this.recordOutcome({\n ...baseEvent,\n phase: \"outcome\",\n failureClass: (error as Error)?.message?.startsWith(\"no_executor:\") ? \"no_executor\" : \"executor_error\",\n });\n return undefined;\n }\n }\n\n private async seedReceiptFailures(): Promise<void> {\n if (this.receiptFailuresSeeded) return;\n this.receiptFailuresSeeded = true;\n const reader = this.deps.recorder?.trailingReceiptFailures;\n if (!reader) return;\n let recorded: number;\n try {\n recorded = await reader.call(this.deps.recorder);\n } catch {\n // Unknown receipt health keeps the gate closed.\n recorded = 1;\n }\n if (!Number.isFinite(recorded)) {\n // A count that is not a real number is unreadable history too.\n recorded = 1;\n }\n if (recorded > this.consecutiveReceiptFailures) {\n this.consecutiveReceiptFailures = recorded;\n }\n }\n\n private async recordOutcome(event: MemoryControllerEvent): Promise<void> {\n if (!this.deps.recorder) return;\n await this.deps.recorder.record(event);\n this.deps.telemetry?.(event);\n }\n}\n\nfunction isValidReceipt(receipt: unknown, decisionId: string): boolean {\n return (\n typeof receipt === \"object\" &&\n receipt !== null &&\n (receipt as MemoryControllerReceipt).decisionId === decisionId &&\n typeof (receipt as MemoryControllerReceipt).ok === \"boolean\"\n );\n}\n\n"],"mappings":";;;;;;;;AAAA,SAAS,YAAY,kBAAkB;AAoKvC,IAAM,cAAc;AAEpB,IAAM,sBAA+D,EAAE,SAAS,KAAK;AAE9E,SAAS,qBAAqB,QAAwC;AAC3E,SAAO;AAAA,IACL,KAAK,UAAU;AAAA,MACb,MAAM,OAAO;AAAA,MACb,eAAe,OAAO;AAAA,MACtB,kBAAkB,OAAO;AAAA,MACzB,gBAAgB,OAAO;AAAA,MAC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;AAC1F,aAAO;AAAA,IACT,SAAS,OAAO;AACd,WAAK,8BAA8B;AACnC,YAAM,KAAK,cAAc;AAAA,QACvB,GAAG;AAAA,QACH,OAAO;AAAA,QACP,cAAe,OAAiB,SAAS,WAAW,cAAc,IAAI,gBAAgB;AAAA,MACxF,CAAC;AACD,aAAO;AAAA,IACT;AAAA,EACF;AAAA,EAEA,MAAc,sBAAqC;AACjD,QAAI,KAAK,sBAAuB;AAChC,SAAK,wBAAwB;AAC7B,UAAM,SAAS,KAAK,KAAK,UAAU;AACnC,QAAI,CAAC,OAAQ;AACb,QAAI;AACJ,QAAI;AACF,iBAAW,MAAM,OAAO,KAAK,KAAK,KAAK,QAAQ;AAAA,IACjD,QAAQ;AAEN,iBAAW;AAAA,IACb;AACA,QAAI,CAAC,OAAO,SAAS,QAAQ,GAAG;AAE9B,iBAAW;AAAA,IACb;AACA,QAAI,WAAW,KAAK,4BAA4B;AAC9C,WAAK,6BAA6B;AAAA,IACpC;AAAA,EACF;AAAA,EAEA,MAAc,cAAc,OAA6C;AACvE,QAAI,CAAC,KAAK,KAAK,SAAU;AACzB,UAAM,KAAK,KAAK,SAAS,OAAO,KAAK;AACrC,SAAK,KAAK,YAAY,KAAK;AAAA,EAC7B;AACF;AAEA,SAAS,eAAe,SAAkB,YAA6B;AACrE,SACE,OAAO,YAAY,YACnB,YAAY,QACX,QAAoC,eAAe,cACpD,OAAQ,QAAoC,OAAO;AAEvD;","names":[]}
|
|
@@ -1,20 +1,20 @@
|
|
|
1
|
+
import {
|
|
2
|
+
selectEvictedBufferKeys
|
|
3
|
+
} from "./chunk-6ZELOK6O.js";
|
|
1
4
|
import {
|
|
2
5
|
refuseOverCapBatch,
|
|
3
6
|
resolveMaxTurnsPerSession
|
|
4
|
-
} from "./chunk-
|
|
7
|
+
} from "./chunk-PUQQPLVV.js";
|
|
5
8
|
import {
|
|
6
9
|
hasBufferedAdmissionIdempotencyKey,
|
|
7
10
|
recordBufferedAdmissionIdempotencyKey
|
|
8
11
|
} from "./chunk-5EP2V675.js";
|
|
9
|
-
import {
|
|
10
|
-
selectEvictedBufferKeys
|
|
11
|
-
} from "./chunk-6ZELOK6O.js";
|
|
12
12
|
import {
|
|
13
13
|
EVICTION_HOOKS
|
|
14
14
|
} from "./chunk-MEVBSF6T.js";
|
|
15
15
|
|
|
16
16
|
// src/buffer-add-turns-bounded.ts
|
|
17
|
-
async function addTurnsBoundedWithAdmissionKey(host, batches, admissionKey) {
|
|
17
|
+
async function addTurnsBoundedWithAdmissionKey(host, batches, admissionKey, onRefused) {
|
|
18
18
|
const pending = await host.enqueueMutation(async () => {
|
|
19
19
|
await host.loadUnlocked();
|
|
20
20
|
if (admissionKey && hasBufferedAdmissionIdempotencyKey(host.state, admissionKey)) {
|
|
@@ -26,7 +26,10 @@ async function addTurnsBoundedWithAdmissionKey(host, batches, admissionKey) {
|
|
|
26
26
|
additions.push({ bufferKey: batch.bufferKey, turn });
|
|
27
27
|
}
|
|
28
28
|
}
|
|
29
|
-
|
|
29
|
+
const maxTurnsPerSession = resolveMaxTurnsPerSession(host.config.bufferMaxTurnsPerSession);
|
|
30
|
+
const overCapKey = refuseOverCapBatch((key) => host.peekEntry(key) ?? null, batches, maxTurnsPerSession);
|
|
31
|
+
if (overCapKey !== null) {
|
|
32
|
+
onRefused?.({ reason: "session_turn_cap", bufferKey: overCapKey, maxTurnsPerSession });
|
|
30
33
|
return host.ingress.refuseAll(additions);
|
|
31
34
|
}
|
|
32
35
|
const entries = host.state.entries ?? {};
|
|
@@ -40,7 +43,10 @@ async function addTurnsBoundedWithAdmissionKey(host, batches, admissionKey) {
|
|
|
40
43
|
if (requiredEvictions > 0) {
|
|
41
44
|
const target = Math.max(0, host.maxSessionEntries - newKeys.length);
|
|
42
45
|
const evicted = selectEvictedBufferKeys(entries, newKeys, target, EVICTION_HOOKS);
|
|
43
|
-
if (newKeys.length > 0 && evicted.length < requiredEvictions)
|
|
46
|
+
if (newKeys.length > 0 && evicted.length < requiredEvictions) {
|
|
47
|
+
onRefused?.({ reason: "session_entry_cap", maxSessionEntries: host.maxSessionEntries });
|
|
48
|
+
return host.ingress.refuseAll(additions);
|
|
49
|
+
}
|
|
44
50
|
for (const key of evicted) delete entries[key];
|
|
45
51
|
host.persistence.markEvicted(evicted);
|
|
46
52
|
}
|
|
@@ -70,4 +76,4 @@ async function addTurnsBoundedWithAdmissionKey(host, batches, admissionKey) {
|
|
|
70
76
|
export {
|
|
71
77
|
addTurnsBoundedWithAdmissionKey
|
|
72
78
|
};
|
|
73
|
-
//# sourceMappingURL=chunk-
|
|
79
|
+
//# sourceMappingURL=chunk-WI2WTIMY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/buffer-add-turns-bounded.ts"],"sourcesContent":["/** Bounded multi-session turn admission (#3368 split from buffer.ts). */\n\nimport { selectEvictedBufferKeys } from \"./buffer-eviction.js\";\nimport {\n hasBufferedAdmissionIdempotencyKey,\n recordBufferedAdmissionIdempotencyKey,\n} from \"./buffer-admission-idempotency.js\";\nimport { refuseOverCapBatch, resolveMaxTurnsPerSession } from \"./buffer-session-cap.js\";\nimport type { BufferSessionPersistence } from \"./buffer-persistence.js\";\nimport type { BufferIngressCounters } from \"./buffer-ingress-counters.js\";\nimport type { AddTurnMutationResult, AddTurnOutcome } from \"./buffer-types.js\";\nimport { EVICTION_HOOKS } from \"./buffer-turn-helpers.js\";\nimport type { BufferEntryState, BufferState, BufferTurn, PluginConfig } from \"./types.js\";\n\nexport type AddTurnsBoundedOutcome =\n | Array<{ bufferKey: string; turn: BufferTurn; outcome: AddTurnOutcome }>\n | null\n | \"duplicate\";\n\n/** Why a bounded batch was refused; the batch itself still resolves to null. */\nexport type BoundedAdmissionRefusal =\n | { reason: \"session_turn_cap\"; bufferKey: string; maxTurnsPerSession: number }\n | { reason: \"session_entry_cap\"; maxSessionEntries: number };\n\nexport type BoundedRefusalListener = (refusal: BoundedAdmissionRefusal) => void;\n\nexport interface AddTurnsBoundedHost {\n readonly config: PluginConfig;\n readonly maxSessionEntries: number;\n get state(): BufferState;\n readonly persistence: BufferSessionPersistence;\n readonly ingress: BufferIngressCounters;\n enqueueMutation<T>(work: () => Promise<T>): Promise<T>;\n loadUnlocked(): Promise<void>;\n peekEntry(bufferKey: string): BufferEntryState | null;\n recordTurnUnlocked(bufferKey: string, turn: BufferTurn): Promise<AddTurnMutationResult>;\n completeAddTurnOutcome(\n bufferKey: string,\n turn: BufferTurn,\n mutation: AddTurnMutationResult,\n ): Promise<AddTurnOutcome>;\n}\n\nexport async function addTurnsBoundedWithAdmissionKey(\n host: AddTurnsBoundedHost,\n batches: readonly { bufferKey: string; turns: readonly BufferTurn[] }[],\n admissionKey?: string,\n onRefused?: BoundedRefusalListener,\n): Promise<AddTurnsBoundedOutcome> {\n const pending = await host.enqueueMutation(async () => {\n await host.loadUnlocked();\n if (admissionKey && hasBufferedAdmissionIdempotencyKey(host.state, admissionKey)) {\n return \"duplicate\" as const;\n }\n const additions: Array<{ bufferKey: string; turn: BufferTurn }> = [];\n for (const batch of batches) {\n for (const turn of batch.turns) {\n additions.push({ bufferKey: batch.bufferKey, turn });\n }\n }\n\n const maxTurnsPerSession = resolveMaxTurnsPerSession(host.config.bufferMaxTurnsPerSession);\n const overCapKey = refuseOverCapBatch((key) => host.peekEntry(key) ?? null, batches, maxTurnsPerSession);\n if (overCapKey !== null) {\n onRefused?.({ reason: \"session_turn_cap\", bufferKey: overCapKey, maxTurnsPerSession });\n return host.ingress.refuseAll(additions);\n }\n const entries = host.state.entries ?? {};\n const newKeys = [\n ...new Set(\n additions\n .map(({ bufferKey }) => bufferKey)\n .filter((bufferKey) => host.peekEntry(bufferKey) === null),\n ),\n ];\n const count = Object.keys(entries).length;\n const requiredEvictions = Math.max(0, count + newKeys.length - host.maxSessionEntries);\n if (requiredEvictions > 0) {\n const target = Math.max(0, host.maxSessionEntries - newKeys.length);\n const evicted = selectEvictedBufferKeys(entries, newKeys, target, EVICTION_HOOKS);\n if (newKeys.length > 0 && evicted.length < requiredEvictions) {\n onRefused?.({ reason: \"session_entry_cap\", maxSessionEntries: host.maxSessionEntries });\n return host.ingress.refuseAll(additions);\n }\n for (const key of evicted) delete entries[key];\n host.persistence.markEvicted(evicted);\n }\n\n const recorded: Array<{ bufferKey: string; turn: BufferTurn; mutation: AddTurnMutationResult }> = [];\n for (const { bufferKey, turn } of additions) {\n recorded.push({ bufferKey, turn, mutation: await host.recordTurnUnlocked(bufferKey, turn) });\n }\n if (admissionKey) {\n recordBufferedAdmissionIdempotencyKey(host.state, admissionKey, recorded.length);\n host.persistence.markAdmissionIdempotencyDirty();\n }\n return recorded;\n });\n if (pending === \"duplicate\") return \"duplicate\";\n if (pending === null) return null;\n\n const outcomes: Array<{ bufferKey: string; turn: BufferTurn; outcome: AddTurnOutcome }> = [];\n for (const item of pending) {\n outcomes.push({\n bufferKey: item.bufferKey,\n turn: item.turn,\n outcome: await host.completeAddTurnOutcome(item.bufferKey, item.turn, item.mutation),\n });\n }\n return outcomes;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AA2CA,eAAsB,gCACpB,MACA,SACA,cACA,WACiC;AACjC,QAAM,UAAU,MAAM,KAAK,gBAAgB,YAAY;AACrD,UAAM,KAAK,aAAa;AACxB,QAAI,gBAAgB,mCAAmC,KAAK,OAAO,YAAY,GAAG;AAChF,aAAO;AAAA,IACT;AACA,UAAM,YAA4D,CAAC;AACnE,eAAW,SAAS,SAAS;AAC3B,iBAAW,QAAQ,MAAM,OAAO;AAC9B,kBAAU,KAAK,EAAE,WAAW,MAAM,WAAW,KAAK,CAAC;AAAA,MACrD;AAAA,IACF;AAEA,UAAM,qBAAqB,0BAA0B,KAAK,OAAO,wBAAwB;AACzF,UAAM,aAAa,mBAAmB,CAAC,QAAQ,KAAK,UAAU,GAAG,KAAK,MAAM,SAAS,kBAAkB;AACvG,QAAI,eAAe,MAAM;AACvB,kBAAY,EAAE,QAAQ,oBAAoB,WAAW,YAAY,mBAAmB,CAAC;AACrF,a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AM,KAAK;AAAA,MACX,SAAS,MAAM,KAAK,uBAAuB,KAAK,WAAW,KAAK,MAAM,KAAK,QAAQ;AAAA,IACrF,CAAC;AAAA,EACH;AACA,SAAO;AACT;","names":[]}
|
|
@@ -1,12 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
LocalLlmClient
|
|
3
|
-
} from "./chunk-
|
|
4
|
-
import {
|
|
5
|
-
FallbackLlmClient
|
|
6
|
-
} from "./chunk-MMRTPH3J.js";
|
|
7
|
-
import {
|
|
8
|
-
extractJsonCandidates
|
|
9
|
-
} from "./chunk-YBA52OKG.js";
|
|
3
|
+
} from "./chunk-BFZFNXOC.js";
|
|
10
4
|
import {
|
|
11
5
|
SupportPassportCreateGrantInputSchema,
|
|
12
6
|
SupportPassportCreateGrantRequestSchema,
|
|
@@ -19,6 +13,12 @@ import {
|
|
|
19
13
|
SupportPassportPublicGuideSchema,
|
|
20
14
|
SupportPassportRevokeGrantInputSchema
|
|
21
15
|
} from "./chunk-QWWHYBPT.js";
|
|
16
|
+
import {
|
|
17
|
+
FallbackLlmClient
|
|
18
|
+
} from "./chunk-MMRTPH3J.js";
|
|
19
|
+
import {
|
|
20
|
+
extractJsonCandidates
|
|
21
|
+
} from "./chunk-YBA52OKG.js";
|
|
22
22
|
import {
|
|
23
23
|
composeMemoryEnvelope
|
|
24
24
|
} from "./chunk-X26YOFGS.js";
|
|
@@ -4497,4 +4497,4 @@ export {
|
|
|
4497
4497
|
parseSupportPassportModelJob,
|
|
4498
4498
|
SupportPassportModelBridge
|
|
4499
4499
|
};
|
|
4500
|
-
//# sourceMappingURL=chunk-
|
|
4500
|
+
//# sourceMappingURL=chunk-XJTRIHTH.js.map
|