@remnic/core 10.0.59 → 10.0.61
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/access-admin-ops-surface.js +53 -50
- package/dist/access-authorization-probe.js +54 -51
- package/dist/access-boundary.js +53 -50
- package/dist/access-cli.js +143 -140
- package/dist/access-cli.js.map +1 -1
- package/dist/access-extraction-force-flush.js +53 -50
- package/dist/access-http-briefing.js +54 -51
- package/dist/access-http-query.js +55 -52
- package/dist/access-http.js +76 -73
- package/dist/access-identity-continuity-surface.js +53 -50
- package/dist/access-lcm-surface.js +53 -50
- package/dist/access-mcp.js +64 -61
- package/dist/access-namespace-preflight.js +53 -50
- package/dist/access-observe-write-category.js +10 -10
- package/dist/access-observe-write-surface.js +53 -50
- package/dist/access-offline-manifest.js +7 -7
- package/dist/access-operations-batch.js +56 -53
- package/dist/access-operations.js +63 -60
- package/dist/access-recall-concurrency.js +53 -50
- package/dist/access-recall-response.js +53 -50
- package/dist/access-recall-surface.js +53 -50
- package/dist/access-schema.js +9 -9
- package/dist/access-service.js +53 -50
- package/dist/access-surface-catalog.js +55 -52
- package/dist/access-surface-catalog.js.map +1 -1
- package/dist/active-recall.js +24 -20
- package/dist/active-recall.js.map +1 -1
- package/dist/adapters/index.js +7 -7
- package/dist/adapters/registry.js +3 -3
- package/dist/briefing.js +16 -12
- package/dist/buffer-persistence.d.ts +14 -3
- package/dist/buffer-persistence.d.ts.map +1 -1
- package/dist/buffer-persistence.js +1 -1
- package/dist/buffer-turn-helpers.d.ts +7 -0
- package/dist/buffer-turn-helpers.d.ts.map +1 -1
- package/dist/buffer-turn-helpers.js +5 -3
- package/dist/buffer.d.ts +2 -0
- package/dist/buffer.d.ts.map +1 -1
- package/dist/buffer.js +7 -7
- package/dist/{capsule-crypto-7FJQINUR.js → capsule-crypto-GWVG7LGC.js} +2 -2
- package/dist/causal-behavior.js +2 -2
- package/dist/causal-chain.js +2 -2
- package/dist/causal-consolidation.js +19 -15
- package/dist/causal-consolidation.js.map +1 -1
- package/dist/causal-retrieval.js +2 -2
- package/dist/causal-trajectory-graph.js +2 -2
- package/dist/causal-trajectory.js +1 -1
- package/dist/{chunk-ZAZZOQAQ.js → chunk-23OEPU3K.js} +2 -2
- package/dist/{chunk-XDKEHZUC.js → chunk-264B57GV.js} +2 -2
- package/dist/{chunk-5U2BBF7E.js → chunk-46U6L5DM.js} +20 -10
- package/dist/chunk-46U6L5DM.js.map +1 -0
- package/dist/chunk-4LZ7SVKM.js +211 -0
- package/dist/chunk-4LZ7SVKM.js.map +1 -0
- package/dist/{chunk-NRGQ5HJO.js → chunk-4P4VLPGB.js} +1 -1
- package/dist/{chunk-GIRWNTMV.js → chunk-4PG5R6BJ.js} +2 -2
- package/dist/{chunk-52II7PB6.js → chunk-645WOU5I.js} +4 -4
- package/dist/{chunk-RG3I2663.js → chunk-64JLBFCQ.js} +2 -2
- package/dist/{chunk-G3T6YMBO.js → chunk-64S6X4IU.js} +7 -7
- package/dist/{chunk-WASVDS6G.js → chunk-6HTEPYOI.js} +4 -4
- package/dist/{chunk-6AEKSOWV.js → chunk-6I6DFULH.js} +8 -8
- package/dist/{chunk-DJR37Q37.js → chunk-6T4CMKNP.js} +2 -2
- package/dist/{chunk-RHJ5VGB3.js → chunk-73A2DDDR.js} +2 -2
- package/dist/{chunk-4B73TQQV.js → chunk-7AKPLEJV.js} +2 -2
- package/dist/{chunk-UHH67NLU.js → chunk-7OKYO2UC.js} +2 -2
- package/dist/{chunk-KAL5SXPP.js → chunk-7ULSP7AU.js} +6 -6
- package/dist/{chunk-USNU3BEQ.js → chunk-A4FZLM6Q.js} +2 -2
- package/dist/{chunk-VV73XT3A.js → chunk-BJLCV2P3.js} +2 -2
- package/dist/{chunk-KQAFEZQX.js → chunk-BUKK5SWA.js} +2 -2
- package/dist/{chunk-DJFULNXK.js → chunk-C2AYUXEF.js} +2 -2
- package/dist/{chunk-QY24FSXT.js → chunk-D3BYJSHX.js} +51 -51
- package/dist/{chunk-JZRQY7ZQ.js → chunk-D4WR56FR.js} +2 -2
- package/dist/{chunk-3E3Z6UA3.js → chunk-DMYNM3WG.js} +124 -97
- package/dist/chunk-DMYNM3WG.js.map +1 -0
- package/dist/{chunk-FB4JQEFS.js → chunk-DP22K7IC.js} +2 -2
- package/dist/{chunk-EJFOGYF3.js → chunk-DTQJ7BRN.js} +3 -3
- package/dist/{chunk-MLUPSZFK.js → chunk-DZL5PBEJ.js} +2 -2
- package/dist/{chunk-JD5F5MYN.js → chunk-EGCC5OJE.js} +3 -3
- package/dist/{chunk-IQSRVR6Z.js → chunk-EJ4RS7I7.js} +2 -2
- package/dist/{chunk-WBN66HPI.js → chunk-ELHJK7LM.js} +6 -6
- package/dist/{chunk-EH46DHBU.js → chunk-ENAPZQA6.js} +2 -2
- package/dist/{chunk-LLG5VNK7.js → chunk-F2UAAI6B.js} +2 -2
- package/dist/{chunk-YZNTAOPZ.js → chunk-FKNNWH7P.js} +2 -2
- package/dist/{chunk-AAANTXCQ.js → chunk-FZVZYU5C.js} +2 -2
- package/dist/{chunk-ON77FQXH.js → chunk-G6GMZJQ4.js} +2 -2
- package/dist/{chunk-OL7A7NKH.js → chunk-GNP4BV4Z.js} +2 -2
- package/dist/{chunk-GDYLZ6FR.js → chunk-HJ3UTGIW.js} +3 -3
- package/dist/{chunk-CCL2OXFO.js → chunk-HSHLDSPX.js} +3 -3
- package/dist/{chunk-R4BR62UO.js → chunk-HWMGQDZI.js} +2 -2
- package/dist/{chunk-BPIAXMGC.js → chunk-IIUEHIQ2.js} +2 -2
- package/dist/{chunk-RTJJPW3C.js → chunk-ILMB3X4X.js} +5 -5
- package/dist/{chunk-RFT4OPYI.js → chunk-IPN67KVR.js} +2 -2
- package/dist/chunk-JCL7RO2G.js +674 -0
- package/dist/chunk-JCL7RO2G.js.map +1 -0
- package/dist/{chunk-IEW6NDHX.js → chunk-JGSWWD33.js} +9 -9
- package/dist/{chunk-A3UFV4K3.js → chunk-JIYJIH5N.js} +2 -2
- package/dist/{chunk-4G2A7MH3.js → chunk-JKUVPVKR.js} +3 -3
- package/dist/{chunk-YJHOVA42.js → chunk-JL5FHZ7O.js} +30 -6
- package/dist/chunk-JL5FHZ7O.js.map +1 -0
- package/dist/{chunk-VCLNU6MY.js → chunk-L2HSSVVD.js} +2 -2
- package/dist/{chunk-U2A56LLF.js → chunk-L334PSLW.js} +8 -8
- package/dist/{chunk-HQUYENKK.js → chunk-LIUI46BX.js} +3 -3
- package/dist/{chunk-ERMT5WQM.js → chunk-MKE5DP3S.js} +2 -2
- package/dist/{chunk-4OFXLQJD.js → chunk-MPDLLLOG.js} +8 -3
- package/dist/chunk-MPDLLLOG.js.map +1 -0
- package/dist/{chunk-6BO27AWQ.js → chunk-MPJ7VHHA.js} +2 -2
- package/dist/{chunk-WXBVGKS6.js → chunk-N7RAABFM.js} +182 -421
- package/dist/chunk-N7RAABFM.js.map +1 -0
- package/dist/{chunk-KMJDH4KX.js → chunk-NSUGAIIB.js} +16 -16
- package/dist/{chunk-7NT3FKAF.js → chunk-NXHBQC2O.js} +2 -2
- package/dist/{chunk-JEX2JL3U.js → chunk-OH55F76C.js} +2 -2
- package/dist/{chunk-37VTMUAL.js → chunk-OUJ4DVR5.js} +2 -2
- package/dist/{chunk-2NLLXCJG.js → chunk-OWHERGF2.js} +2 -2
- package/dist/{chunk-2IVK5IDY.js → chunk-P5F7ISLV.js} +2 -2
- package/dist/{chunk-PM4PKC3Y.js → chunk-PNVQNAJM.js} +3 -3
- package/dist/{chunk-FXWX7VD3.js → chunk-PRYDNBCO.js} +12 -12
- package/dist/{chunk-YDDLSGYE.js → chunk-PUTH5REB.js} +2 -2
- package/dist/{chunk-GFAEKSFR.js → chunk-QBK3IM6W.js} +5 -5
- package/dist/{chunk-KRAMCBIW.js → chunk-QKXPOLQD.js} +4 -4
- package/dist/{chunk-YDT3OEYF.js → chunk-R4ZHF4K2.js} +2 -2
- package/dist/{chunk-ISNPYOXR.js → chunk-RBUR6USI.js} +5 -5
- package/dist/{chunk-WZYAXOGO.js → chunk-RZSHIJYY.js} +2 -2
- package/dist/{chunk-TYSD7UQO.js → chunk-SVTIWBSA.js} +2 -2
- package/dist/{chunk-AMKIIRLL.js → chunk-TBFAQHQZ.js} +2 -2
- package/dist/{chunk-ZE5N4JSY.js → chunk-TKCJI7WA.js} +2 -2
- package/dist/{chunk-RYB553SS.js → chunk-TLOAAOT3.js} +2 -2
- package/dist/{chunk-RKRX4C4H.js → chunk-TPKB7T6Z.js} +2 -2
- package/dist/{chunk-JZCBMKR5.js → chunk-TUCEP2LS.js} +5 -5
- package/dist/{chunk-KZMRMKC7.js → chunk-U7MIMS2Y.js} +11 -1
- package/dist/chunk-U7MIMS2Y.js.map +1 -0
- package/dist/{chunk-OMWQO7H6.js → chunk-UEDC2VGP.js} +2 -2
- package/dist/{chunk-X7Y7WX73.js → chunk-UVYI6VIX.js} +1 -1
- package/dist/{chunk-JY2BGCYN.js → chunk-VCYH2XUY.js} +2 -2
- package/dist/{chunk-NGH74LDV.js → chunk-WD2QH3JM.js} +9 -9
- package/dist/{chunk-G6A3SGCE.js → chunk-WVEEVYMH.js} +8 -25
- package/dist/chunk-WVEEVYMH.js.map +1 -0
- package/dist/{chunk-UGTYADB4.js → chunk-WWSJQ7MP.js} +3 -3
- package/dist/{chunk-UQBOPCDK.js → chunk-X4PAATLA.js} +2 -2
- package/dist/{chunk-KBOQQEVC.js → chunk-XAFSZ4DP.js} +2 -2
- package/dist/{chunk-2S6JADBB.js → chunk-XICJL56Z.js} +2 -2
- package/dist/{chunk-Y5KESB7T.js → chunk-XJDSZFBZ.js} +45 -45
- package/dist/{chunk-24SIB3EW.js → chunk-XWE3EOWX.js} +2 -2
- package/dist/{chunk-Y77FXULH.js → chunk-XWXBXBOX.js} +2 -2
- package/dist/{chunk-VKQI47DJ.js → chunk-Y7427SL7.js} +4 -4
- package/dist/{chunk-TEH5MDX5.js → chunk-YH7HJNWV.js} +22 -22
- package/dist/chunk-YHTG64XV.js +117 -0
- package/dist/chunk-YHTG64XV.js.map +1 -0
- package/dist/{chunk-EZ25VE3G.js → chunk-YNDLCWXS.js} +4 -4
- package/dist/{chunk-2M36PR7R.js → chunk-Z2T5BPOZ.js} +2 -2
- package/dist/cli.js +100 -97
- package/dist/coding/export-okf-codegraph.js +15 -11
- package/dist/coding/export-okf-codegraph.js.map +1 -1
- package/dist/coding/pre-action-gate.js +2 -2
- package/dist/compounding/engine.js +17 -13
- package/dist/config.js +24 -20
- package/dist/connectors/codex-materialize-runner.js +16 -12
- package/dist/connectors/index.js +16 -12
- package/dist/convergence-refresh.js +18 -14
- package/dist/corpus-scan-worker-host.d.ts +109 -0
- package/dist/corpus-scan-worker-host.d.ts.map +1 -0
- package/dist/corpus-scan-worker-host.js +15 -0
- package/dist/corpus-scan-worker.entry.d.ts +21 -0
- package/dist/corpus-scan-worker.entry.d.ts.map +1 -0
- package/dist/corpus-scan-worker.entry.js +60 -0
- package/dist/corpus-scan-worker.entry.js.map +1 -0
- package/dist/corpus-scan-worker.entry.mjs +176 -0
- package/dist/corpus-scan.d.ts +71 -0
- package/dist/corpus-scan.d.ts.map +1 -0
- package/dist/corpus-scan.js +16 -0
- package/dist/corpus-watermark.d.ts.map +1 -1
- package/dist/corpus-watermark.js +18 -14
- package/dist/dashboard-runtime.js +2 -2
- package/dist/deep-recall-http-glue.js +10 -10
- package/dist/embedding-fallback.js +2 -2
- package/dist/{entity-canonical-id-migration-F3JVG6K6.js → entity-canonical-id-migration-CUDCKWPF.js} +4 -2
- package/dist/entity-canonical-id-migration-CUDCKWPF.js.map +1 -0
- package/dist/entity-retrieval.js +18 -14
- package/dist/event-order-recall.js +3 -3
- package/dist/external-wiki-access.js +54 -51
- package/dist/extraction.js +21 -17
- package/dist/{graph-edge-decay-IU75NV42.js → graph-edge-decay-2BZTY2IM.js} +5 -5
- package/dist/graph-edge-decay-2BZTY2IM.js.map +1 -0
- package/dist/graph-jsonl.js +3 -3
- package/dist/graph-snapshot.js +3 -3
- package/dist/graph.js +2 -2
- package/dist/harmonic-retrieval.js +16 -12
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +174 -169
- package/dist/lcm/engine.js +2 -2
- package/dist/lcm/index.js +5 -5
- package/dist/location/index.js +18 -14
- package/dist/maintenance/memory-governance.js +16 -12
- package/dist/maintenance/rebuild-memory-lifecycle-ledger.js +16 -12
- package/dist/maintenance/rebuild-memory-projection-runner.js +18 -14
- package/dist/maintenance/rebuild-memory-projection.js +17 -13
- package/dist/memory-browse-operations.js +54 -51
- package/dist/memory-browse.js +5 -5
- package/dist/namespaces/migrate.js +17 -13
- package/dist/namespaces/search.js +7 -7
- package/dist/namespaces/storage.js +16 -12
- 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 +19 -15
- package/dist/operator-toolkit.js +35 -31
- package/dist/orchestration/buffer-drain-gate.d.ts +21 -0
- package/dist/orchestration/buffer-drain-gate.d.ts.map +1 -0
- package/dist/orchestration/buffer-drain-runner.d.ts +79 -0
- package/dist/orchestration/buffer-drain-runner.d.ts.map +1 -0
- package/dist/orchestration/buffer-drain-runner.js +780 -0
- package/dist/orchestration/buffer-drain-runner.js.map +1 -0
- package/dist/orchestration/buffer-swap.d.ts +12 -0
- package/dist/orchestration/buffer-swap.d.ts.map +1 -0
- package/dist/orchestration/maintenance.js +26 -22
- package/dist/orchestration/turn-ingestion.d.ts.map +1 -1
- package/dist/orchestrator.d.ts +4 -1
- package/dist/orchestrator.d.ts.map +1 -1
- package/dist/orchestrator.js +143 -140
- package/dist/qmd.js +4 -4
- package/dist/recall-navigation-operations.js +54 -51
- package/dist/recall-navigation.js +53 -50
- package/dist/recall-state-view-admission.js +5 -5
- package/dist/recall-why-service.js +5 -5
- package/dist/resume-bundles.js +25 -21
- package/dist/search/factory.js +6 -6
- package/dist/search/index.js +12 -12
- package/dist/semantic-consolidation.js +17 -13
- package/dist/semantic-rule-promotion.js +16 -12
- package/dist/semantic-rule-verifier.js +16 -12
- package/dist/source-agent-qualifier.js +19 -15
- package/dist/standup/build.js +16 -12
- package/dist/storage/buffer-drain-claims.d.ts +159 -0
- package/dist/storage/buffer-drain-claims.d.ts.map +1 -0
- package/dist/storage/buffer-drain-claims.js +18 -0
- package/dist/storage/buffer-drain-claims.js.map +1 -0
- package/dist/storage/buffer-session-files.d.ts +14 -2
- package/dist/storage/buffer-session-files.d.ts.map +1 -1
- package/dist/storage/buffer-session-files.js +22 -0
- package/dist/storage/buffer-session-files.js.map +1 -0
- package/dist/storage/entity-canonical-id-migration.d.ts.map +1 -1
- package/dist/storage/memory-read-store.d.ts +5 -9
- package/dist/storage/memory-read-store.d.ts.map +1 -1
- package/dist/storage.d.ts +6 -1
- package/dist/storage.d.ts.map +1 -1
- package/dist/storage.js +17 -13
- package/dist/support-passport/index.js +56 -53
- package/dist/transfer/backup.js +2 -2
- package/dist/transfer/capsule-export.js +2 -2
- package/dist/transfer/capsule-import.js +2 -2
- package/dist/transfer/export-okf.js +16 -12
- package/dist/verified-recall.js +16 -12
- package/dist/who-knows-cli.js +17 -13
- package/dist/who-knows.js +16 -12
- package/package.json +32 -2
- package/scripts/build-with-heap.mjs +8 -0
- package/src/buffer-drain-handover.test.ts +307 -0
- package/src/buffer-persistence.ts +27 -5
- package/src/buffer-turn-helpers.ts +16 -0
- package/src/buffer.ts +32 -2
- package/src/corpus-scan-worker-host.ts +314 -0
- package/src/corpus-scan-worker.entry.mjs +176 -0
- package/src/corpus-scan-worker.entry.ts +95 -0
- package/src/corpus-scan.ts +215 -0
- package/src/corpus-watermark.ts +28 -12
- package/src/index.ts +1 -1
- package/src/orchestration/buffer-drain-gate.test.ts +40 -0
- package/src/orchestration/buffer-drain-gate.ts +38 -0
- package/src/orchestration/buffer-drain-runner.ts +312 -0
- package/src/orchestration/buffer-swap.ts +27 -0
- package/src/orchestration/turn-ingestion.ts +2 -0
- package/src/orchestrator.ts +9 -6
- package/src/storage/buffer-drain-claims.test.ts +448 -0
- package/src/storage/buffer-drain-claims.ts +593 -0
- package/src/storage/buffer-session-files.ts +50 -3
- package/src/storage/entity-canonical-id-migration.ts +4 -26
- package/src/storage/memory-read-store.ts +17 -99
- package/src/storage.ts +8 -11
- package/src/testing/subjects/extraction-lifecycle.test.ts +34 -0
- package/dist/chunk-3E3Z6UA3.js.map +0 -1
- package/dist/chunk-4OFXLQJD.js.map +0 -1
- package/dist/chunk-5U2BBF7E.js.map +0 -1
- package/dist/chunk-G6A3SGCE.js.map +0 -1
- package/dist/chunk-KZMRMKC7.js.map +0 -1
- package/dist/chunk-WXBVGKS6.js.map +0 -1
- package/dist/chunk-YJHOVA42.js.map +0 -1
- /package/dist/{capsule-crypto-7FJQINUR.js.map → capsule-crypto-GWVG7LGC.js.map} +0 -0
- /package/dist/{chunk-ZAZZOQAQ.js.map → chunk-23OEPU3K.js.map} +0 -0
- /package/dist/{chunk-XDKEHZUC.js.map → chunk-264B57GV.js.map} +0 -0
- /package/dist/{chunk-NRGQ5HJO.js.map → chunk-4P4VLPGB.js.map} +0 -0
- /package/dist/{chunk-GIRWNTMV.js.map → chunk-4PG5R6BJ.js.map} +0 -0
- /package/dist/{chunk-52II7PB6.js.map → chunk-645WOU5I.js.map} +0 -0
- /package/dist/{chunk-RG3I2663.js.map → chunk-64JLBFCQ.js.map} +0 -0
- /package/dist/{chunk-G3T6YMBO.js.map → chunk-64S6X4IU.js.map} +0 -0
- /package/dist/{chunk-WASVDS6G.js.map → chunk-6HTEPYOI.js.map} +0 -0
- /package/dist/{chunk-6AEKSOWV.js.map → chunk-6I6DFULH.js.map} +0 -0
- /package/dist/{chunk-DJR37Q37.js.map → chunk-6T4CMKNP.js.map} +0 -0
- /package/dist/{chunk-RHJ5VGB3.js.map → chunk-73A2DDDR.js.map} +0 -0
- /package/dist/{chunk-4B73TQQV.js.map → chunk-7AKPLEJV.js.map} +0 -0
- /package/dist/{chunk-UHH67NLU.js.map → chunk-7OKYO2UC.js.map} +0 -0
- /package/dist/{chunk-KAL5SXPP.js.map → chunk-7ULSP7AU.js.map} +0 -0
- /package/dist/{chunk-USNU3BEQ.js.map → chunk-A4FZLM6Q.js.map} +0 -0
- /package/dist/{chunk-VV73XT3A.js.map → chunk-BJLCV2P3.js.map} +0 -0
- /package/dist/{chunk-KQAFEZQX.js.map → chunk-BUKK5SWA.js.map} +0 -0
- /package/dist/{chunk-DJFULNXK.js.map → chunk-C2AYUXEF.js.map} +0 -0
- /package/dist/{chunk-QY24FSXT.js.map → chunk-D3BYJSHX.js.map} +0 -0
- /package/dist/{chunk-JZRQY7ZQ.js.map → chunk-D4WR56FR.js.map} +0 -0
- /package/dist/{chunk-FB4JQEFS.js.map → chunk-DP22K7IC.js.map} +0 -0
- /package/dist/{chunk-EJFOGYF3.js.map → chunk-DTQJ7BRN.js.map} +0 -0
- /package/dist/{chunk-MLUPSZFK.js.map → chunk-DZL5PBEJ.js.map} +0 -0
- /package/dist/{chunk-JD5F5MYN.js.map → chunk-EGCC5OJE.js.map} +0 -0
- /package/dist/{chunk-IQSRVR6Z.js.map → chunk-EJ4RS7I7.js.map} +0 -0
- /package/dist/{chunk-WBN66HPI.js.map → chunk-ELHJK7LM.js.map} +0 -0
- /package/dist/{chunk-EH46DHBU.js.map → chunk-ENAPZQA6.js.map} +0 -0
- /package/dist/{chunk-LLG5VNK7.js.map → chunk-F2UAAI6B.js.map} +0 -0
- /package/dist/{chunk-YZNTAOPZ.js.map → chunk-FKNNWH7P.js.map} +0 -0
- /package/dist/{chunk-AAANTXCQ.js.map → chunk-FZVZYU5C.js.map} +0 -0
- /package/dist/{chunk-ON77FQXH.js.map → chunk-G6GMZJQ4.js.map} +0 -0
- /package/dist/{chunk-OL7A7NKH.js.map → chunk-GNP4BV4Z.js.map} +0 -0
- /package/dist/{chunk-GDYLZ6FR.js.map → chunk-HJ3UTGIW.js.map} +0 -0
- /package/dist/{chunk-CCL2OXFO.js.map → chunk-HSHLDSPX.js.map} +0 -0
- /package/dist/{chunk-R4BR62UO.js.map → chunk-HWMGQDZI.js.map} +0 -0
- /package/dist/{chunk-BPIAXMGC.js.map → chunk-IIUEHIQ2.js.map} +0 -0
- /package/dist/{chunk-RTJJPW3C.js.map → chunk-ILMB3X4X.js.map} +0 -0
- /package/dist/{chunk-RFT4OPYI.js.map → chunk-IPN67KVR.js.map} +0 -0
- /package/dist/{chunk-IEW6NDHX.js.map → chunk-JGSWWD33.js.map} +0 -0
- /package/dist/{chunk-A3UFV4K3.js.map → chunk-JIYJIH5N.js.map} +0 -0
- /package/dist/{chunk-4G2A7MH3.js.map → chunk-JKUVPVKR.js.map} +0 -0
- /package/dist/{chunk-VCLNU6MY.js.map → chunk-L2HSSVVD.js.map} +0 -0
- /package/dist/{chunk-U2A56LLF.js.map → chunk-L334PSLW.js.map} +0 -0
- /package/dist/{chunk-HQUYENKK.js.map → chunk-LIUI46BX.js.map} +0 -0
- /package/dist/{chunk-ERMT5WQM.js.map → chunk-MKE5DP3S.js.map} +0 -0
- /package/dist/{chunk-6BO27AWQ.js.map → chunk-MPJ7VHHA.js.map} +0 -0
- /package/dist/{chunk-KMJDH4KX.js.map → chunk-NSUGAIIB.js.map} +0 -0
- /package/dist/{chunk-7NT3FKAF.js.map → chunk-NXHBQC2O.js.map} +0 -0
- /package/dist/{chunk-JEX2JL3U.js.map → chunk-OH55F76C.js.map} +0 -0
- /package/dist/{chunk-37VTMUAL.js.map → chunk-OUJ4DVR5.js.map} +0 -0
- /package/dist/{chunk-2NLLXCJG.js.map → chunk-OWHERGF2.js.map} +0 -0
- /package/dist/{chunk-2IVK5IDY.js.map → chunk-P5F7ISLV.js.map} +0 -0
- /package/dist/{chunk-PM4PKC3Y.js.map → chunk-PNVQNAJM.js.map} +0 -0
- /package/dist/{chunk-FXWX7VD3.js.map → chunk-PRYDNBCO.js.map} +0 -0
- /package/dist/{chunk-YDDLSGYE.js.map → chunk-PUTH5REB.js.map} +0 -0
- /package/dist/{chunk-GFAEKSFR.js.map → chunk-QBK3IM6W.js.map} +0 -0
- /package/dist/{chunk-KRAMCBIW.js.map → chunk-QKXPOLQD.js.map} +0 -0
- /package/dist/{chunk-YDT3OEYF.js.map → chunk-R4ZHF4K2.js.map} +0 -0
- /package/dist/{chunk-ISNPYOXR.js.map → chunk-RBUR6USI.js.map} +0 -0
- /package/dist/{chunk-WZYAXOGO.js.map → chunk-RZSHIJYY.js.map} +0 -0
- /package/dist/{chunk-TYSD7UQO.js.map → chunk-SVTIWBSA.js.map} +0 -0
- /package/dist/{chunk-AMKIIRLL.js.map → chunk-TBFAQHQZ.js.map} +0 -0
- /package/dist/{chunk-ZE5N4JSY.js.map → chunk-TKCJI7WA.js.map} +0 -0
- /package/dist/{chunk-RYB553SS.js.map → chunk-TLOAAOT3.js.map} +0 -0
- /package/dist/{chunk-RKRX4C4H.js.map → chunk-TPKB7T6Z.js.map} +0 -0
- /package/dist/{chunk-JZCBMKR5.js.map → chunk-TUCEP2LS.js.map} +0 -0
- /package/dist/{chunk-OMWQO7H6.js.map → chunk-UEDC2VGP.js.map} +0 -0
- /package/dist/{chunk-X7Y7WX73.js.map → chunk-UVYI6VIX.js.map} +0 -0
- /package/dist/{chunk-JY2BGCYN.js.map → chunk-VCYH2XUY.js.map} +0 -0
- /package/dist/{chunk-NGH74LDV.js.map → chunk-WD2QH3JM.js.map} +0 -0
- /package/dist/{chunk-UGTYADB4.js.map → chunk-WWSJQ7MP.js.map} +0 -0
- /package/dist/{chunk-UQBOPCDK.js.map → chunk-X4PAATLA.js.map} +0 -0
- /package/dist/{chunk-KBOQQEVC.js.map → chunk-XAFSZ4DP.js.map} +0 -0
- /package/dist/{chunk-2S6JADBB.js.map → chunk-XICJL56Z.js.map} +0 -0
- /package/dist/{chunk-Y5KESB7T.js.map → chunk-XJDSZFBZ.js.map} +0 -0
- /package/dist/{chunk-24SIB3EW.js.map → chunk-XWE3EOWX.js.map} +0 -0
- /package/dist/{chunk-Y77FXULH.js.map → chunk-XWXBXBOX.js.map} +0 -0
- /package/dist/{chunk-VKQI47DJ.js.map → chunk-Y7427SL7.js.map} +0 -0
- /package/dist/{chunk-TEH5MDX5.js.map → chunk-YH7HJNWV.js.map} +0 -0
- /package/dist/{chunk-EZ25VE3G.js.map → chunk-YNDLCWXS.js.map} +0 -0
- /package/dist/{chunk-2M36PR7R.js.map → chunk-Z2T5BPOZ.js.map} +0 -0
- /package/dist/{entity-canonical-id-migration-F3JVG6K6.js.map → corpus-scan-worker-host.js.map} +0 -0
- /package/dist/{graph-edge-decay-IU75NV42.js.map → corpus-scan.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/storage/buffer-drain-claims.ts","../src/storage/buffer-session-files.ts"],"sourcesContent":["/**\n * Durable drain claims for the extraction buffer (`remnic buffer drain`).\n *\n * A claim is the atomic handover of one session's buffered turns from the\n * live buffer (daemon or CLI process) to a drain worker, so extraction can\n * run out of process without a live buffer owner resurrecting or losing the\n * turns. Files under `<stateDir>/buffer/drain/`:\n *\n * s-<sha256(key)>.json claim content: { key, entry, claimedAt }\n * — the turns NOT yet extracted. Renamed into\n * place from the session file (atomic on one\n * filesystem), rewritten atomically as chunks\n * drain.\n * s-<sha256(key)>.lease.json { ownerId, pid, acquiredAt, heartbeatAt,\n * leaseMs } — created with exclusive-create so\n * exactly one drainer holds a key.\n *\n * Invariants (see the buffer-drain PR for the full protocol):\n * - At every instant the claim content file holds exactly the turns whose\n * extraction is not durably finished, so a kill at any point loses\n * nothing and the next run resumes.\n * - A live buffer owner that must persist a claimed session hands its\n * in-memory entry INTO the claim (merge, identity-deduped) instead of\n * writing a session file — it can never resurrect claimed turns.\n * - Claims are idempotent: re-claiming, double-draining, and two\n * concurrent drainers are all safe (per-key mutation lock + exclusive\n * lease; the lock also fences lease takeover and progress writes).\n *\n * All content reads/writes go through the storage's secure file I/O\n * (`BufferFileIo`); only lease/existence checks touch raw paths, and claim\n * rewrites serialize on a cross-process held file lock.\n */\n\nimport { hostname } from \"node:os\";\nimport { z } from \"zod\";\nimport { existsSync } from \"node:fs\";\nimport { mkdir, readdir, rename, unlink, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { bufferSessionFileName, type BufferFileIo } from \"./buffer-session-files.js\";\nimport { bufferTurnsEqual, subtractBufferTurns } from \"../buffer-turn-helpers.js\";\nimport { log } from \"../logger.js\";\nimport { withHeldFileLock } from \"../utils/serialize-mutations.js\";\nimport type { BufferEntryState, BufferTurn } from \"../types.js\";\n\n/** Result of persisting one session's entry. */\nexport interface BufferSessionSaveOutcome {\n /** \"saved\": the session file holds the entry. \"handed_over\": the entry moved into a drain claim. */\n status: \"saved\" | \"handed_over\";\n /** Turns a drain already extracted (claim tombstone): the owner subtracts them from its copy. */\n drainedTurns?: BufferTurn[];\n}\n\nexport interface DrainLease {\n ownerId: string;\n pid: number;\n /** Host the owner runs on: a takeover may only judge liveness on that host. */\n host: string;\n acquiredAt: string;\n heartbeatAt: string;\n leaseMs: number;\n}\n\nexport interface DrainClaimFile {\n key: string;\n entry: BufferEntryState;\n claimedAt: string;\n /**\n * Turns the drain already extracted. Non-empty means the session was\n * drained and the claim is a TOMBSTONE: a live buffer owner subtracts\n * these from its (possibly stale) copy instead of writing them back, so\n * drained turns can never be resurrected.\n */\n drained?: BufferTurn[];\n /** Same tombstone for turns the drain extracted from `retainedTurns`. */\n drainedRetained?: BufferTurn[];\n}\n\nexport type ClaimFromSessionOutcome = \"claimed\" | \"empty\" | \"already_claimed\";\nexport type AdoptOutcome = \"adopted\" | \"busy\";\nexport type AckOutcome = \"acked\" | \"not_empty\" | \"busy\";\n\nexport interface DrainClaimListing {\n key: string;\n turnCount: number;\n leased: boolean;\n leaseExpired: boolean;\n}\n\n/** Lock while a claim is read-modify-written; released on settle. */\nconst CLAIM_LOCK_STALE_MS = 120_000;\nconst CLAIM_LOCK_MAX_WAIT_MS = 120_000;\n\nfunction emptyEntry(): BufferEntryState {\n return { turns: [], lastExtractionAt: null, extractionCount: 0 };\n}\n\n/** Identity-dedupe `incoming` turns into `existing` (they are the same turns a\n * live owner still held after claiming; only genuinely NEW turns append). */\nfunction mergeTurns<T>(existing: T[], incoming: readonly T[], isEqual: (a: T, b: T) => boolean): T[] {\n const merged = [...existing];\n for (const turn of incoming) {\n if (merged.some((kept) => isEqual(kept, turn))) continue;\n merged.push(turn);\n }\n return merged;\n}\n\nfunction mergeEntries(claim: DrainClaimFile, incoming: BufferEntryState): DrainClaimFile {\n const entry = emptyEntry();\n // Turns already extracted stay out of the pending entry even when the\n // owner's incoming copy is stale and still carries them (either tombstone\n // list counts — a turn in either one left the claim for good).\n const gone = [...(claim.drained ?? []), ...(claim.drainedRetained ?? [])];\n entry.turns = mergeTurns(\n subtractBufferTurns(claim.entry.turns, gone),\n subtractBufferTurns(incoming.turns, gone),\n bufferTurnsEqual,\n );\n const retained = [\n ...subtractBufferTurns(claim.entry.retainedTurns ?? [], gone),\n ...subtractBufferTurns(incoming.retainedTurns ?? [], gone),\n ];\n // SAFETY: an empty accumulator of the same element type.\n const dedupedRetained = mergeTurns([] as typeof retained, retained, bufferTurnsEqual);\n if (dedupedRetained.length > 0) entry.retainedTurns = dedupedRetained;\n const stamps = [claim.entry.lastExtractionAt, incoming.lastExtractionAt].filter(\n (value): value is string => value !== null && value !== undefined,\n );\n entry.lastExtractionAt = stamps.sort().at(-1) ?? null;\n entry.extractionCount = Math.max(claim.entry.extractionCount, incoming.extractionCount);\n return { ...claim, entry };\n}\n\n/**\n * Is the lease owner still running? Only decidable on the owner's host; a\n * lease from another host counts as alive (its expiry decides).\n */\nfunction isOwnerAlive(lease: DrainLease): boolean {\n if (lease.host !== hostname()) return true;\n if (!Number.isInteger(lease.pid) || lease.pid <= 0) return true;\n try {\n process.kill(lease.pid, 0);\n return true;\n } catch (err) {\n // EPERM: the process exists but belongs to another user.\n // SAFETY: the value comes from this module's own write path; the shape is checked above.\n return (err as NodeJS.ErrnoException)?.code === \"EPERM\";\n }\n}\n\nfunction isLeaseExpired(lease: DrainLease, now = Date.now()): boolean {\n const heartbeat = Date.parse(lease.heartbeatAt);\n return !Number.isFinite(heartbeat) || now - heartbeat > lease.leaseMs;\n}\n\nconst claimBodySchema = z.object({\n key: z.string().min(1),\n entry: z.object({\n turns: z.array(z.unknown()),\n retainedTurns: z.array(z.unknown()).optional(),\n lastExtractionAt: z.string().nullable().optional(),\n extractionCount: z.number().optional(),\n }).optional(),\n turns: z.array(z.unknown()).optional(),\n retainedTurns: z.array(z.unknown()).optional(),\n lastExtractionAt: z.string().nullable().optional(),\n extractionCount: z.number().optional(),\n claimedAt: z.string().optional(),\n drained: z.array(z.unknown()).optional(),\n drainedRetained: z.array(z.unknown()).optional(),\n});\n\nfunction parseBody(raw: string): DrainClaimFile | null {\n let body: z.infer<typeof claimBodySchema>;\n try {\n body = claimBodySchema.parse(JSON.parse(raw));\n } catch {\n return null;\n }\n // Two on-disk shapes, one format: a claim born from rename keeps the flat\n // session-file shape ({key, turns, ...}) until its first rewrite, which\n // nests under `entry`. Accept both.\n const source = body.entry && Array.isArray(body.entry.turns) ? body.entry : body;\n if (!Array.isArray(source.turns)) return null;\n const entry = emptyEntry();\n // SAFETY: the schema parsed these as an array of unknown; the claim file\n // is written only by this module (BufferSessionFiles.save), so the entries\n // are BufferTurn values.\n // SAFETY: the claim file is written only by this module, so the parsed\n // turn arrays hold BufferTurn values.\n // SAFETY: the value comes from this module's own write path; the shape is checked above.\n entry.turns = source.turns as BufferTurn[];\n if (source.retainedTurns) {\n // SAFETY: same boundary as the turns above (this module writes the file).\n entry.retainedTurns = source.retainedTurns as BufferTurn[];\n }\n entry.lastExtractionAt = source.lastExtractionAt ?? null;\n entry.extractionCount = Number.isFinite(source.extractionCount) ? Number(source.extractionCount) : 0;\n const claim: DrainClaimFile = {\n key: body.key,\n entry,\n claimedAt: body.claimedAt ?? new Date().toISOString(),\n };\n if (Array.isArray(body.drained)) {\n // SAFETY: same boundary as the turns above (this module writes the file).\n claim.drained = body.drained as BufferTurn[];\n }\n if (Array.isArray(body.drainedRetained)) {\n // SAFETY: same boundary as the turns above (this module writes the file).\n claim.drainedRetained = body.drainedRetained as BufferTurn[];\n }\n return claim;\n}\n\nconst leaseSchema = z.object({\n ownerId: z.string().min(1),\n pid: z.number().optional(),\n host: z.string().optional(),\n acquiredAt: z.string().optional(),\n heartbeatAt: z.string(),\n leaseMs: z.number(),\n});\n\nfunction parseLease(raw: string): DrainLease | null {\n let lease: z.infer<typeof leaseSchema>;\n try {\n lease = leaseSchema.parse(JSON.parse(raw));\n } catch {\n return null;\n }\n return {\n ownerId: lease.ownerId,\n pid: lease.pid ?? 0,\n host: lease.host ?? \"\",\n acquiredAt: lease.acquiredAt ?? lease.heartbeatAt,\n heartbeatAt: lease.heartbeatAt,\n leaseMs: lease.leaseMs,\n };\n}\n\nexport class BufferDrainClaims {\n constructor(\n private readonly stateDir: string,\n private readonly io: BufferFileIo,\n ) {}\n\n private get dir(): string {\n return path.join(this.stateDir, \"buffer\", \"drain\");\n }\n\n private fileFor(key: string): string {\n return path.join(this.dir, bufferSessionFileName(key));\n }\n\n private leaseFileFor(key: string): string {\n return `${this.fileFor(key)}.lease.json`;\n }\n\n private lockFileFor(key: string): string {\n return `${this.fileFor(key)}.lock`;\n }\n\n /** Sync existence check for hot-path gates (`SmartBuffer.isSessionClaimed`). */\n isClaimed(key: string): boolean {\n return existsSync(this.fileFor(key));\n }\n\n /** Test + CLI seam: the lease file path for direct inspection. */\n leasePathForTest(key: string): string {\n return this.leaseFileFor(key);\n }\n\n private async readClaimBody(key: string): Promise<DrainClaimFile | null> {\n try {\n return parseBody(await this.io.read(this.fileFor(key)));\n } catch {\n return null;\n }\n }\n\n /** The claim content for `key`, or null when the key is not claimed. */\n load(key: string): Promise<DrainClaimFile | null> {\n return this.readClaimBody(key);\n }\n\n private async writeClaimBody(key: string, claim: DrainClaimFile): Promise<void> {\n await mkdir(this.dir, { recursive: true });\n await this.io.write(this.fileFor(key), JSON.stringify({ ...claim, key }));\n }\n\n private async readLease(key: string): Promise<DrainLease | null> {\n try {\n return parseLease(await this.io.read(this.leaseFileFor(key)));\n } catch {\n return null;\n }\n }\n\n private async writeLease(key: string, lease: DrainLease): Promise<void> {\n await mkdir(this.dir, { recursive: true });\n await this.io.write(this.leaseFileFor(key), JSON.stringify(lease));\n }\n\n /**\n * Atomically move a session's persisted file into a claim. The rename is\n * the handover: after it settles the turns exist ONLY as a claim, so no\n * crash window can lose them or leave them in both places. Callers that\n * lose the race (`already_claimed`) simply skip the key.\n *\n * The whole handover runs under the claim's mutation lock, so a claim\n * create can never land on top of an existing claim (POSIX rename would\n * silently replace it) and the lease write cannot race an adopter.\n */\n async claimFromSessionFile(key: string, lease: DrainLease): Promise<ClaimFromSessionOutcome> {\n await mkdir(this.dir, { recursive: true });\n const sessionPath = path.join(this.stateDir, \"buffer\", bufferSessionFileName(key));\n if (existsSync(sessionPath)) {\n // Advisory pre-read: an empty live session belongs to its owner, not\n // the drain. A turn landing between this read and the rename is fine —\n // the rename moves whatever is there and the claim drains it.\n try {\n const seeded = parseBody(await this.io.read(sessionPath));\n if (seeded && seeded.entry.turns.length === 0 && (seeded.entry.retainedTurns?.length ?? 0) === 0) {\n return \"empty\";\n }\n } catch {\n // Unreadable live file: proceed with the rename and let the claim\n // path report it loudly, like the loader skips corrupt files.\n }\n }\n return await withHeldFileLock(\n this.lockFileFor(key),\n { staleMs: CLAIM_LOCK_STALE_MS, maxWaitMs: CLAIM_LOCK_MAX_WAIT_MS },\n async (acquired) => {\n if (!acquired) return \"already_claimed\";\n // Under the lock the claim check is authoritative: an existing claim\n // keeps its content and its lease; the session file stays with its\n // owner (their next save merges into the claim).\n if (this.isClaimed(key)) return \"already_claimed\";\n try {\n await rename(sessionPath, this.fileFor(key));\n } catch (err) {\n // The session file is gone: either it never existed, or another\n // drainer claimed it first.\n if (!existsSync(sessionPath)) {\n if (this.isClaimed(key)) return \"already_claimed\";\n return \"empty\";\n }\n throw err;\n }\n const claim = await this.readClaimBody(key);\n if (!claim || (claim.entry.turns.length === 0 && (claim.entry.retainedTurns?.length ?? 0) === 0)) {\n // Empty content: nothing to drain. Delete the moved file so the\n // empty entry keeps living with its owner, not as a stale claim.\n await unlink(this.fileFor(key)).catch(() => {});\n return \"empty\";\n }\n await this.writeLease(key, lease);\n return \"claimed\";\n },\n );\n }\n\n /**\n * Take over a claim whose lease is missing, expired, or whose owner died.\n * The whole judgement runs under the claim's mutation lock and re-reads\n * the lease inside it, so exactly one concurrent adopter wins: the loser\n * re-reads the winner's fresh lease and reports \"busy\" instead of\n * unlinking it. A lease whose owner died is taken over in the same call.\n */\n async adopt(key: string, lease: DrainLease): Promise<AdoptOutcome> {\n if (!this.isClaimed(key)) return \"busy\";\n return await withHeldFileLock(\n this.lockFileFor(key),\n { staleMs: CLAIM_LOCK_STALE_MS, maxWaitMs: CLAIM_LOCK_MAX_WAIT_MS },\n async (acquired) => {\n if (!acquired) return \"busy\";\n const existing = await this.readLease(key);\n if (existing && !isLeaseExpired(existing)) {\n if (existing.ownerId === lease.ownerId) {\n // The same drainer already holds it: renew the lease.\n await this.writeLease(key, { ...existing, heartbeatAt: new Date().toISOString(), leaseMs: lease.leaseMs });\n return \"adopted\";\n }\n if (isOwnerAlive(existing)) return \"busy\";\n // The owner died without releasing the claim (killed worker):\n // take it over now instead of waiting for the lease to expire.\n await unlink(this.leaseFileFor(key)).catch(() => {});\n } else if (existing) {\n // Expired lease: clear it before the exclusive create. We hold the\n // lock, so no concurrent adopter can interleave its own\n // unlink/create between these steps.\n await unlink(this.leaseFileFor(key)).catch(() => {});\n }\n try {\n await writeFile(this.leaseFileFor(key), JSON.stringify(lease), { flag: \"wx\" });\n } catch (err) {\n // The lease file exists: another drainer took it first.\n if (existsSync(this.leaseFileFor(key))) return \"busy\";\n throw err;\n }\n return \"adopted\";\n },\n );\n }\n\n /**\n * Merge a live owner's in-memory entry INTO the claim (the handover path a\n * buffer owner takes instead of persisting a claimed session). Serialized\n * against drainer progress writes on the same lock.\n */\n async mergeIntoClaim(key: string, incoming: BufferEntryState): Promise<void> {\n await withHeldFileLock(this.lockFileFor(key), { staleMs: CLAIM_LOCK_STALE_MS, maxWaitMs: CLAIM_LOCK_MAX_WAIT_MS }, async (acquired) => {\n if (!acquired) {\n // Never fall back to a session-file write behind a held claim lock:\n // that would resurrect claimed turns. Fail so the owner's save stays\n // pending and retries (SmartBuffer keeps pending state on failure).\n throw new Error(`buffer drain claim for ${key} is busy; retrying the save later`);\n }\n const claim = await this.readClaimBody(key);\n if (!claim) {\n // The claim vanished (acked between the isClaimed check and now):\n // nothing to hand over; the drain already owns everything.\n return;\n }\n await this.writeClaimBody(key, mergeEntries(claim, incoming));\n });\n }\n\n /** Drainer progress: replace the claim content with what is left to do.\n *\n * Fenced: `ownerId` must still match the claim's lease (checked under the\n * same lock), so a drainer that lost its lease cannot write progress that\n * would restore turns the new owner already extracted.\n *\n * `seen` is the entry the drainer LOADED (its snapshot of the claim). Only\n * turns that were in that snapshot and are absent from BOTH of the\n * drainer's lists were actually extracted and move to the tombstones — a\n * turn the drainer moved into `entry.retainedTurns` is retained for retry,\n * not extracted. Turns a live owner merged into the claim afterwards stay\n * pending. Without `seen` the pre-existing behavior is kept (every claim\n * turn missing from `entry` counts as extracted).\n */\n async writeEntry(key: string, ownerId: string, entry: BufferEntryState, seen?: BufferEntryState): Promise<void> {\n await withHeldFileLock(this.lockFileFor(key), { staleMs: CLAIM_LOCK_STALE_MS, maxWaitMs: CLAIM_LOCK_MAX_WAIT_MS }, async (acquired) => {\n if (!acquired) throw new Error(`buffer drain claim for ${key} is busy; progress write skipped`);\n const lease = await this.readLease(key);\n if (!lease || lease.ownerId !== ownerId) {\n throw new Error(`buffer drain claim for ${key} is no longer owned by ${ownerId}; progress write skipped`);\n }\n const claim = await this.readClaimBody(key);\n if (!claim) return;\n const seenTurns = seen?.turns ?? claim.entry.turns;\n const seenRetained = seen?.retainedTurns ?? claim.entry.retainedTurns ?? [];\n const entryRetained = entry.retainedTurns ?? [];\n // Still held by the drainer: in its remaining turns OR retained for retry.\n const kept = (turn: BufferTurn): boolean =>\n entry.turns.some((held) => bufferTurnsEqual(held, turn)) || entryRetained.some((held) => bufferTurnsEqual(held, turn));\n // Progress: the snapshot turns that vanished from the entry were extracted.\n const drained = [...(claim.drained ?? [])];\n for (const turn of claim.entry.turns) {\n const extracted =\n seenTurns.some((snapshot) => bufferTurnsEqual(snapshot, turn)) && !kept(turn);\n if (!extracted) continue;\n if (drained.some((gone) => bufferTurnsEqual(gone, turn))) continue;\n drained.push(turn);\n }\n const drainedRetained = [...(claim.drainedRetained ?? [])];\n for (const turn of claim.entry.retainedTurns ?? []) {\n const extracted =\n seenRetained.some((snapshot) => bufferTurnsEqual(snapshot, turn)) && !kept(turn);\n if (!extracted) continue;\n if (drained.some((gone) => bufferTurnsEqual(gone, turn)) || drainedRetained.some((gone) => bufferTurnsEqual(gone, turn))) continue;\n drainedRetained.push(turn);\n }\n // Turns merged in after the drainer loaded stay pending, in extraction\n // order behind the drainer's own remainder.\n const late = claim.entry.turns.filter(\n (turn) =>\n !seenTurns.some((snapshot) => bufferTurnsEqual(snapshot, turn)) && !kept(turn),\n );\n const next: BufferEntryState = { ...entry, turns: [...entry.turns, ...late] };\n const lateRetained = (claim.entry.retainedTurns ?? []).filter(\n (turn) =>\n !seenRetained.some((snapshot) => bufferTurnsEqual(snapshot, turn)) && !kept(turn),\n );\n if (lateRetained.length > 0) next.retainedTurns = mergeTurns(entryRetained, lateRetained, bufferTurnsEqual);\n await this.writeClaimBody(key, { ...claim, entry: next, drained, drainedRetained });\n });\n }\n\n /** Extend the lease. \"lost\" means another drainer took the claim over.\n * Serialized on the claim lock so a stale heartbeat can never overwrite a\n * new owner's lease mid-takeover; a contended lock just skips this tick\n * (usually the drainer's own progress write holds it). */\n async heartbeat(key: string, ownerId: string, leaseMs: number): Promise<\"ok\" | \"lost\"> {\n return await withHeldFileLock(this.lockFileFor(key), { staleMs: CLAIM_LOCK_STALE_MS, maxWaitMs: CLAIM_LOCK_MAX_WAIT_MS }, async (acquired) => {\n if (!acquired) return \"ok\";\n const lease = await this.readLease(key);\n if (!lease || lease.ownerId !== ownerId) return \"lost\";\n await this.writeLease(key, { ...lease, heartbeatAt: new Date().toISOString(), leaseMs });\n return \"ok\";\n });\n }\n\n /** Give the key back (content stays; the next run resumes it). */\n async releaseLease(key: string, ownerId: string): Promise<void> {\n const lease = await this.readLease(key);\n if (!lease || lease.ownerId !== ownerId) return;\n await unlink(this.leaseFileFor(key)).catch(() => {});\n }\n\n /**\n * Finish a claim: only its owner may ack, and only when nothing is left to\n * extract. Non-empty claims stay (deferred content is never dropped here).\n */\n async ack(key: string, ownerId: string): Promise<AckOutcome> {\n const lease = await this.readLease(key);\n if (!lease || lease.ownerId !== ownerId) return \"busy\";\n const claim = await this.readClaimBody(key);\n if (!claim) {\n await unlink(this.leaseFileFor(key)).catch(() => {});\n return \"acked\";\n }\n if (claim.entry.turns.length > 0 || (claim.entry.retainedTurns?.length ?? 0) > 0) return \"not_empty\";\n // Keep the (empty) claim file as a TOMBSTONE: a live buffer owner that\n // still holds a stale copy subtracts the drained turns instead of\n // writing them back. The owner consumes the tombstone on its next save.\n await unlink(this.leaseFileFor(key)).catch(() => {});\n return \"acked\";\n }\n\n /** The turns a drain already extracted for `key` (tombstone content). */\n async drainedTurns(key: string): Promise<BufferTurn[]> {\n const claim = await this.readClaimBody(key);\n return claim?.drained ?? [];\n }\n\n /**\n * Is the drain for `key` FINISHED (acked): the claim holds extracted turns\n * and nothing pending, and the drainer dropped its lease. A claim with\n * partial progress or a live lease is still being drained — its owner must\n * merge into it, never release it.\n */\n async isDrained(key: string): Promise<boolean> {\n const claim = await this.readClaimBody(key);\n if (!claim) return false;\n if ((claim.drained?.length ?? 0) === 0 && (claim.drainedRetained?.length ?? 0) === 0) return false;\n if (claim.entry.turns.length > 0 || (claim.entry.retainedTurns?.length ?? 0) > 0) return false;\n return (await this.readLease(key)) === null;\n }\n\n /** Drop the claim file entirely (its owner consumed the tombstone). */\n async release(key: string): Promise<void> {\n await unlink(this.fileFor(key)).catch(() => {});\n await unlink(this.leaseFileFor(key)).catch(() => {});\n }\n\n /** Every claim with its lease state (CLI scan + summaries). */\n async list(): Promise<DrainClaimListing[]> {\n let names: string[];\n try {\n names = (await readdir(this.dir)).filter((name) => name.endsWith(\".json\") && !name.endsWith(\".lease.json\"));\n } catch (err) {\n // SAFETY: the value comes from this module's own write path; the shape is checked above.\n if ((err as NodeJS.ErrnoException)?.code === \"ENOENT\") return [];\n throw err;\n }\n const out: DrainClaimListing[] = [];\n for (const name of names) {\n const claim = await this.readClaimBodyByKey(name);\n if (!claim) continue;\n const lease = await this.readLease(claim.key);\n out.push({\n key: claim.key,\n turnCount: claim.entry.turns.length + (claim.entry.retainedTurns?.length ?? 0),\n leased: lease !== null,\n leaseExpired: lease !== null ? isLeaseExpired(lease) : true,\n });\n }\n return out;\n }\n\n private async readClaimBodyByKey(name: string): Promise<DrainClaimFile | null> {\n try {\n return parseBody(await this.io.read(path.join(this.dir, name)));\n } catch (err) {\n log.debug(`buffer drain: skipping unreadable claim file ${name}: ${err instanceof Error ? err.message : String(err)}`);\n return null;\n }\n }\n}\n","import { BufferDrainClaims, type BufferSessionSaveOutcome } from \"./buffer-drain-claims.js\";\nimport { createHash } from \"node:crypto\";\nimport type { Stats } from \"node:fs\";\nimport { lstat, readdir, unlink } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { subtractBufferTurns } from \"../buffer-turn-helpers.js\";\nimport { log } from \"../logger.js\";\nimport { SecureStoreDecryptError, SecureStoreLockedError } from \"../secure-store/secure-fs.js\";\nimport type { BufferEntryState, BufferState, BufferTurn } from \"../types.js\";\n\n/** The secure-store file I/O the owning StorageManager already provides. */\nexport interface BufferFileIo {\n read(filePath: string): Promise<string>;\n write(filePath: string, content: string): Promise<void>;\n}\n\ntype FsError = NodeJS.ErrnoException;\n\nfunction isMissing(err: FsError | null): boolean {\n return err?.code === \"ENOENT\";\n}\n\nfunction asFsError(err: Error): FsError {\n return err;\n}\n\n/**\n * Case-independent, collision-free file name for a buffer key: the lowercase\n * hex SHA-256 of the key under a fixed prefix. Hex has no case and no path\n * characters, so `Session-A` and `session-a` get different names even on\n * case-insensitive filesystems, every key (short or long) lives in the same\n * naming domain, and the key itself is stored inside the file (loading never\n * inverts the hash).\n */\nexport function bufferSessionFileName(key: string): string {\n return `s-${createHash(\"sha256\").update(key).digest(\"hex\")}.json`;\n}\n\n/** Flatten a legacy BufferState into per-session entries (top-level fields\n * are the legacy mirror of the \"default\" entry). */\nexport function legacyStateToEntries(state: BufferState): Map<string, BufferEntryState> {\n const entries = new Map<string, BufferEntryState>();\n for (const [key, value] of Object.entries(state.entries ?? {})) {\n if (value && Array.isArray(value.turns)) entries.set(key, value);\n }\n if (!entries.has(\"default\")) {\n entries.set(\"default\", {\n turns: Array.isArray(state.turns) ? state.turns : [],\n lastExtractionAt: state.lastExtractionAt ?? null,\n extractionCount: Number.isFinite(state.extractionCount) ? state.extractionCount : 0,\n });\n }\n return entries;\n}\n\n/** What a per-session file contains once parsed (written only by this module). */\ninterface SessionFileBody {\n key?: string;\n turns?: BufferTurn[];\n retainedTurns?: BufferTurn[];\n lastExtractionAt?: string | null;\n extractionCount?: number;\n}\n\nfunction entryFromBody(body: SessionFileBody): { key: string; entry: BufferEntryState } | null {\n if (!body || !Array.isArray(body.turns) || (body.key?.length ?? 0) === 0) return null;\n const entry: BufferEntryState = {\n turns: body.turns,\n lastExtractionAt: body.lastExtractionAt ?? null,\n extractionCount: Number.isFinite(body.extractionCount) ? Number(body.extractionCount) : 0,\n };\n if (Array.isArray(body.retainedTurns)) entry.retainedTurns = body.retainedTurns;\n return { key: String(body.key), entry };\n}\n\n/**\n * One file per buffer session under `<stateDir>/buffer/`, so the observe hot\n * path persists only the session that changed. All writes happen under\n * SmartBuffer's serialized mutation chain (one writer per process).\n *\n * Sessions claimed by `remnic buffer drain` (see buffer-drain-claims.ts) are\n * owned by the drain: `save` hands the in-memory entry INTO the claim\n * (identity-deduped merge) instead of writing a session file, so a live\n * buffer owner can never resurrect claimed turns.\n */\nexport class BufferSessionFiles {\n private dirVerified = false;\n private readonly claimsStore: BufferDrainClaims;\n\n constructor(\n private readonly stateDir: string,\n private readonly io: BufferFileIo,\n ) {\n this.claimsStore = new BufferDrainClaims(stateDir, io);\n }\n\n /** The drain-claim store for this state dir (CLI scan + claim ops). */\n get claims(): BufferDrainClaims {\n return this.claimsStore;\n }\n\n /** Sync gate check: is this session claimed by a buffer drain? */\n isClaimed(key: string): boolean {\n return this.claimsStore.isClaimed(key);\n }\n\n private get dir(): string {\n return path.join(this.stateDir, \"buffer\");\n }\n\n private fileFor(key: string): string {\n return path.join(this.dir, bufferSessionFileName(key));\n }\n\n /**\n * Refuse a symlinked buffer directory: following it would send buffered\n * conversation data (and deletions) outside the memory root. One lstat of\n * one directory, cached after it passes, so the observe path pays nothing\n * per write; the cache is dropped on any failure.\n */\n private async assertDirSafe(): Promise<void> {\n if (this.dirVerified) return;\n let stat: Stats | null = null;\n try {\n stat = await lstat(this.dir);\n } catch (err) {\n if (!(err instanceof Error) || !isMissing(asFsError(err))) throw err;\n }\n if (stat && (stat.isSymbolicLink() || !stat.isDirectory())) {\n throw new Error(`buffer session directory must be a real directory, not a symlink or file: ${this.dir}`);\n }\n this.dirVerified = stat !== null;\n }\n\n /** Persist ONE session atomically. Compact JSON: machine-read state, and\n * pretty-printing a large buffer costs CPU and bytes on every observe.\n * A drain-claimed session is handed over instead (see class doc). */\n async save(key: string, entry: BufferEntryState): Promise<BufferSessionSaveOutcome> {\n if (this.isClaimed(key)) {\n // Consume the tombstone ONLY when the drain finished (acked: extracted\n // turns recorded, nothing pending, no lease). Partial `drained` just\n // means chunks completed — the drainer may still be running, and\n // releasing here would unlink its claim and turn its later writes into\n // no-ops.\n if (await this.claimsStore.isDrained(key)) {\n const drained = await this.claimsStore.drainedTurns(key);\n // The drain finished this session: the claim is a tombstone. Write\n // the owner's fresh remainder back as a session file (the drained\n // turns are subtracted here too, so a caller that did not subtract\n // them cannot resurrect them) and release the tombstone.\n const fresh: BufferEntryState = { ...entry, turns: subtractBufferTurns(entry.turns, drained) };\n if (entry.retainedTurns && entry.retainedTurns.length > 0) {\n fresh.retainedTurns = subtractBufferTurns(entry.retainedTurns, drained);\n if (fresh.retainedTurns.length === 0) delete fresh.retainedTurns;\n }\n await this.assertDirSafe();\n await this.io.write(this.fileFor(key), JSON.stringify({ key, ...fresh }));\n await this.claimsStore.release(key);\n return { status: \"saved\", drainedTurns: drained };\n }\n await this.claimsStore.mergeIntoClaim(key, entry);\n return { status: \"handed_over\" };\n }\n await this.assertDirSafe();\n await this.io.write(this.fileFor(key), JSON.stringify({ key, ...entry }));\n return { status: \"saved\" };\n }\n\n /** Remove one session's file. Idempotent: an absent file is fine. */\n async remove(key: string): Promise<void> {\n await this.assertDirSafe();\n try {\n await unlink(this.fileFor(key));\n } catch (err) {\n if (!(err instanceof Error) || !isMissing(asFsError(err))) throw err;\n }\n }\n\n private async listFiles(): Promise<string[]> {\n await this.assertDirSafe();\n try {\n const dirents = await readdir(this.dir, { withFileTypes: true });\n // Regular files only: a symlink inside the directory is never followed.\n return dirents.filter((d) => d.isFile() && d.name.endsWith(\".json\")).map((d) => d.name);\n } catch (err) {\n if (err instanceof Error && isMissing(asFsError(err))) return [];\n throw err;\n }\n }\n\n /** Read every per-session file. Corrupt files are skipped (and logged) so\n * one bad file cannot nuke the other sessions' buffered turns. */\n private async readAll(): Promise<{ entries: Map<string, BufferEntryState>; fileCount: number }> {\n const names = await this.listFiles();\n const entries = new Map<string, BufferEntryState>();\n for (const name of names) {\n try {\n const body: SessionFileBody = JSON.parse(await this.io.read(path.join(this.dir, name)));\n const parsed = entryFromBody(body);\n if (!parsed) throw new Error(\"invalid buffer session file shape\");\n if (entries.has(parsed.key)) {\n log.warn(`buffer: duplicate session file for key ${parsed.key} (${name}); keeping the first`);\n continue;\n }\n entries.set(parsed.key, parsed.entry);\n } catch (err) {\n // A locked store or a wrong key is not a corrupt file: reading it as empty would let\n // later saves replace the real encrypted session.\n if (err instanceof SecureStoreLockedError || err instanceof SecureStoreDecryptError) throw err;\n log.warn(`buffer: skipping unreadable per-session buffer file ${name}: ${err instanceof Error ? err.message : String(err)}`);\n }\n }\n return { entries, fileCount: names.length };\n }\n\n /**\n * Read the legacy single-file buffer.json for migration. Null when absent,\n * or unreadable while session files exist (they are authoritative; a\n * corrupt leftover must not block startup). With no session files a corrupt\n * legacy file THROWS, preserving the old contract so callers can reset it.\n */\n private async readLegacy(hasSessionFiles: boolean): Promise<BufferState | null> {\n let raw: string;\n try {\n raw = await this.io.read(path.join(this.stateDir, \"buffer.json\"));\n } catch (err) {\n if (err instanceof SecureStoreLockedError) throw err;\n if (err instanceof Error && isMissing(asFsError(err))) return null;\n throw err;\n }\n try {\n const legacy: BufferState = JSON.parse(raw);\n return legacy;\n } catch (err) {\n if (!hasSessionFiles) throw err;\n log.warn(\n `buffer: legacy buffer.json is unreadable but per-session buffer files exist; ` +\n `ignoring the legacy file (${err instanceof Error ? err.message : String(err)})`,\n );\n return null;\n }\n }\n\n /**\n * Load the whole buffer, migrating a legacy buffer.json once. A per-session\n * file that parsed wins over the legacy snapshot (a crash mid-migration\n * leaves exactly that pair); legacy entries without a usable file are\n * written out, then the legacy file is retired. Both steps are idempotent.\n */\n async load(): Promise<BufferState> {\n const { entries, fileCount } = await this.readAll();\n const legacy = await this.readLegacy(fileCount > 0);\n if (legacy !== null) {\n for (const [key, entry] of legacyStateToEntries(legacy)) {\n if (entries.has(key)) continue;\n entries.set(key, entry);\n await this.save(key, entry);\n }\n try {\n await unlink(path.join(this.stateDir, \"buffer.json\"));\n } catch (err) {\n if (!(err instanceof Error) || !isMissing(asFsError(err))) throw err;\n }\n }\n const out: NonNullable<BufferState[\"entries\"]> = Object.create(null);\n for (const [key, entry] of entries) out[key] = entry;\n const def = entries.get(\"default\");\n return {\n turns: def?.turns ?? [],\n lastExtractionAt: def?.lastExtractionAt ?? null,\n extractionCount: def?.extractionCount ?? 0,\n entries: out,\n };\n }\n\n /**\n * Reconcile the files with a WHOLE buffer state: write every entry, then\n * delete files for keys no longer present. Writes first, deletes last: a\n * crash leaves stale extra files (removed by the next reconcile) but never\n * loses sessions the state says exist. Not on the observe hot path.\n */\n async reconcile(state: BufferState): Promise<void> {\n const entries = legacyStateToEntries(state);\n const existing = await this.listFiles();\n for (const [key, entry] of entries) await this.save(key, entry);\n const live = new Set([...entries.keys()].map((key) => bufferSessionFileName(key)));\n for (const name of existing) {\n if (live.has(name)) continue;\n try {\n await unlink(path.join(this.dir, name));\n } catch (err) {\n if (!(err instanceof Error) || !isMissing(asFsError(err))) throw err;\n }\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAiCA,SAAS,gBAAgB;AACzB,SAAS,SAAS;AAClB,SAAS,kBAAkB;AAC3B,SAAS,OAAO,WAAAA,UAAS,QAAQ,UAAAC,SAAQ,iBAAiB;AAC1D,OAAOC,WAAU;;;ACpCjB,SAAS,kBAAkB;AAE3B,SAAS,OAAO,SAAS,cAAc;AACvC,OAAO,UAAU;AAcjB,SAAS,UAAU,KAA8B;AAC/C,SAAO,KAAK,SAAS;AACvB;AAEA,SAAS,UAAU,KAAqB;AACtC,SAAO;AACT;AAUO,SAAS,sBAAsB,KAAqB;AACzD,SAAO,KAAK,WAAW,QAAQ,EAAE,OAAO,GAAG,EAAE,OAAO,KAAK,CAAC;AAC5D;AAIO,SAAS,qBAAqB,OAAmD;AACtF,QAAM,UAAU,oBAAI,IAA8B;AAClD,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,MAAM,WAAW,CAAC,CAAC,GAAG;AAC9D,QAAI,SAAS,MAAM,QAAQ,MAAM,KAAK,EAAG,SAAQ,IAAI,KAAK,KAAK;AAAA,EACjE;AACA,MAAI,CAAC,QAAQ,IAAI,SAAS,GAAG;AAC3B,YAAQ,IAAI,WAAW;AAAA,MACr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;AACrH,aAAO;AAAA,IACT;AAAA,EACF;AACF;","names":["readdir","unlink","path","path","unlink","readdir"]}
|
|
@@ -1,3 +1,6 @@
|
|
|
1
|
+
import {
|
|
2
|
+
PROJECTION_REBUILD_RUNNER_FLAG
|
|
3
|
+
} from "./chunk-XAFSZ4DP.js";
|
|
1
4
|
import {
|
|
2
5
|
ensureContradictionScanCron,
|
|
3
6
|
ensureDaySummaryCron,
|
|
@@ -7,28 +10,25 @@ import {
|
|
|
7
10
|
ensureProceduralMiningCron,
|
|
8
11
|
graphEdgeDecayCadenceToCronExpr
|
|
9
12
|
} from "./chunk-666A3MOW.js";
|
|
10
|
-
import {
|
|
11
|
-
PROJECTION_REBUILD_RUNNER_FLAG
|
|
12
|
-
} from "./chunk-KBOQQEVC.js";
|
|
13
13
|
import {
|
|
14
14
|
startLocationAutoSync
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-PUTH5REB.js";
|
|
16
16
|
import {
|
|
17
17
|
CompoundingEngine,
|
|
18
18
|
isIsoWeekId,
|
|
19
19
|
msUntilNextIsoWeek,
|
|
20
20
|
previousIsoWeekId
|
|
21
|
-
} from "./chunk-
|
|
21
|
+
} from "./chunk-JKUVPVKR.js";
|
|
22
22
|
import {
|
|
23
23
|
rebuildMemoryLifecycleLedger
|
|
24
|
-
} from "./chunk-
|
|
24
|
+
} from "./chunk-ENAPZQA6.js";
|
|
25
25
|
import {
|
|
26
26
|
planNamespaceMaintenance,
|
|
27
27
|
runNamespaceMaintenanceBatchPlan
|
|
28
|
-
} from "./chunk-
|
|
28
|
+
} from "./chunk-DTQJ7BRN.js";
|
|
29
29
|
import {
|
|
30
30
|
rebuildMemoryProjection
|
|
31
|
-
} from "./chunk-
|
|
31
|
+
} from "./chunk-EGCC5OJE.js";
|
|
32
32
|
import {
|
|
33
33
|
DEFAULT_TIMELINE_CATEGORIES,
|
|
34
34
|
TIMELINE_RESERVED_IDLE,
|
|
@@ -2874,4 +2874,4 @@ export {
|
|
|
2874
2874
|
ActivitySyncScheduler,
|
|
2875
2875
|
MaintenanceScheduler
|
|
2876
2876
|
};
|
|
2877
|
-
//# sourceMappingURL=chunk-
|
|
2877
|
+
//# sourceMappingURL=chunk-JGSWWD33.js.map
|
|
@@ -19,7 +19,7 @@ import {
|
|
|
19
19
|
import {
|
|
20
20
|
decryptCapsuleFileInMemory,
|
|
21
21
|
isEncryptedCapsuleFile
|
|
22
|
-
} from "./chunk-
|
|
22
|
+
} from "./chunk-UVYI6VIX.js";
|
|
23
23
|
import {
|
|
24
24
|
assertIsDirectoryNotSymlink,
|
|
25
25
|
assertRealpathInsideRoot,
|
|
@@ -294,4 +294,4 @@ function mintForkId(capsuleId, originalId, now) {
|
|
|
294
294
|
export {
|
|
295
295
|
importCapsule
|
|
296
296
|
};
|
|
297
|
-
//# sourceMappingURL=chunk-
|
|
297
|
+
//# sourceMappingURL=chunk-JIYJIH5N.js.map
|
|
@@ -8,11 +8,11 @@ import {
|
|
|
8
8
|
} from "./chunk-WR5POHQ3.js";
|
|
9
9
|
import {
|
|
10
10
|
resolveDefaultNamespaceRoot
|
|
11
|
-
} from "./chunk-
|
|
11
|
+
} from "./chunk-TBFAQHQZ.js";
|
|
12
12
|
import {
|
|
13
13
|
StorageManager,
|
|
14
14
|
readRawMemoryDocument
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-N7RAABFM.js";
|
|
16
16
|
import {
|
|
17
17
|
parseContinuityImprovementLoops
|
|
18
18
|
} from "./chunk-LDXUBPMO.js";
|
|
@@ -1869,4 +1869,4 @@ export {
|
|
|
1869
1869
|
defaultTierMigrationCycleBudget,
|
|
1870
1870
|
CompoundingEngine
|
|
1871
1871
|
};
|
|
1872
|
-
//# sourceMappingURL=chunk-
|
|
1872
|
+
//# sourceMappingURL=chunk-JKUVPVKR.js.map
|
|
@@ -3,13 +3,13 @@ import {
|
|
|
3
3
|
} from "./chunk-KASJJGRG.js";
|
|
4
4
|
import {
|
|
5
5
|
BufferSessionPersistence
|
|
6
|
-
} from "./chunk-
|
|
6
|
+
} from "./chunk-MPDLLLOG.js";
|
|
7
7
|
import {
|
|
8
8
|
scanSignals
|
|
9
9
|
} from "./chunk-H3FZVNRN.js";
|
|
10
10
|
import {
|
|
11
11
|
ExtractionDeadlineError
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-264B57GV.js";
|
|
13
13
|
import {
|
|
14
14
|
bufferTurnArrayIsSuffixOfSnapshot,
|
|
15
15
|
bufferTurnArraysEqual,
|
|
@@ -21,8 +21,9 @@ import {
|
|
|
21
21
|
matchingQueuedExtractionPrefixLength,
|
|
22
22
|
probeWithTimeout,
|
|
23
23
|
scopeProfilePlanIdentity,
|
|
24
|
-
selectRetainedDeferredTurns
|
|
25
|
-
|
|
24
|
+
selectRetainedDeferredTurns,
|
|
25
|
+
subtractBufferTurns
|
|
26
|
+
} from "./chunk-U7MIMS2Y.js";
|
|
26
27
|
import {
|
|
27
28
|
resolvePrincipal
|
|
28
29
|
} from "./chunk-ESG6ITGP.js";
|
|
@@ -223,7 +224,30 @@ var SmartBuffer = class {
|
|
|
223
224
|
this.loaded = true;
|
|
224
225
|
}
|
|
225
226
|
async saveUnlocked() {
|
|
226
|
-
await this.persistence.persist(this.storage, this.state, (key) => this.peekEntry(key) ?? void 0);
|
|
227
|
+
const { handedOver, drainedTurns } = await this.persistence.persist(this.storage, this.state, (key) => this.peekEntry(key) ?? void 0);
|
|
228
|
+
for (const [key, drained] of drainedTurns) {
|
|
229
|
+
const entry = this.peekEntry(key);
|
|
230
|
+
if (!entry) continue;
|
|
231
|
+
entry.turns = subtractBufferTurns(entry.turns, drained);
|
|
232
|
+
if (entry.retainedTurns && entry.retainedTurns.length > 0) {
|
|
233
|
+
entry.retainedTurns = subtractBufferTurns(entry.retainedTurns, drained);
|
|
234
|
+
if (entry.retainedTurns.length === 0) delete entry.retainedTurns;
|
|
235
|
+
}
|
|
236
|
+
if (key === "default") this.state.turns = entry.turns;
|
|
237
|
+
}
|
|
238
|
+
if (handedOver.length === 0) return;
|
|
239
|
+
const entries = this.state.entries;
|
|
240
|
+
if (!entries) return;
|
|
241
|
+
for (const key of handedOver) {
|
|
242
|
+
delete entries[key];
|
|
243
|
+
if (key === "default") {
|
|
244
|
+
this.state.turns = [];
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
/** Sync gate for the extraction queue: is this session claimed by a buffer drain? */
|
|
249
|
+
isSessionClaimed(key) {
|
|
250
|
+
return this.storage.isBufferSessionClaimed?.(key) === true;
|
|
227
251
|
}
|
|
228
252
|
async save() {
|
|
229
253
|
await this.enqueueMutation(async () => this.saveUnlocked());
|
|
@@ -885,4 +909,4 @@ var SmartBuffer = class {
|
|
|
885
909
|
export {
|
|
886
910
|
SmartBuffer
|
|
887
911
|
};
|
|
888
|
-
//# sourceMappingURL=chunk-
|
|
912
|
+
//# sourceMappingURL=chunk-JL5FHZ7O.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/buffer.ts"],"sourcesContent":["import { log } from \"./logger.js\";\nimport { throwIfAborted } from \"./abort-error.js\";\nimport { scanSignals } from \"./signal.js\";\nimport { BufferSessionPersistence, type BufferStorage } from \"./buffer-persistence.js\";\nimport { selectEvictedBufferKeys } from \"./buffer-eviction.js\";\nimport type {\n BufferEntryState,\n BufferState,\n BufferSurpriseEvent,\n BufferTurn,\n PluginConfig,\n SignalLevel,\n} from \"./types.js\";\nimport { resolvePresentationCapabilities, resolveNamespaceCapabilities } from \"./capabilities.js\";\nimport { resolvePrincipal } from \"./namespaces/principal.js\";\nimport { scopeProfilePlanIdentity, subtractBufferTurns } from \"./buffer-turn-helpers.js\";\nimport { ExtractionDeadlineError } from \"./orchestration/extraction-run.js\";\nimport type { ExtractionBufferSnapshot } from \"./extraction-liveness.js\";\nimport {\n bufferTurnArrayIsSuffixOfSnapshot,\n bufferTurnArraysEqual,\n bufferTurnsEqual,\n copyBufferTurn,\n describeError,\n hasPinnedCaptureScope,\n liveTurnsFromExtractionSnapshot,\n matchingQueuedExtractionPrefixLength,\n probeWithTimeout,\n selectRetainedDeferredTurns,\n} from \"./buffer-turn-helpers.js\";\n\nexport type TriggerDecision = \"extract_now\" | \"extract_batch\" | \"keep_buffering\";\n\nexport type { BufferSurpriseProbe } from \"./buffer-types.js\";\nimport type { BufferSurpriseProbe, SurpriseTelemetryQueueEntry } from \"./buffer-types.js\";\n\nexport interface AddTurnOutcome {\n decision: TriggerDecision;\n extractionTurns?: BufferTurn[];\n}\n\nexport interface RetainedTurnCleanupOptions {\n abortSignal?: AbortSignal;\n deadlineMs?: number;\n /** Keep cleanup within the accepted namespace. */\n writeNamespaceOverride?: string;\n /** Match the original profile and project binding, not just its write namespace. */\n scopeProfileWritePlan?: import(\"./namespaces/scope-profiles.js\").ResolvedScopeProfilePlan | null;\n codingContext?: import(\"./types.js\").CodingContext;\n}\n\nconst MAX_BUFFER_ENTRY_COUNT = 200;\nconst isAcceptedTurn = (t: { acceptedCapture?: boolean; writeNamespaceOverride?: string }): boolean =>\n t.acceptedCapture === true || t.writeNamespaceOverride !== undefined;\n\n/**\n * Upper bound on how long a debounced buffer save may be deferred under\n * sustained activity (issue #1909). Each new turn re-arms the trailing-edge\n * timer, so a steady stream of turns could otherwise push the save out\n * indefinitely and widen the crash-loss window without bound. Once a pending\n * save has been deferred this many debounce windows, the next scheduled save\n * forces an inline flush instead of re-arming.\n */\nconst BUFFER_SAVE_MAX_DEFER_MULTIPLIER = 5;\n\n/**\n * Node's maximum 32-bit `setTimeout` delay (2^31-1 ms, ~24.8 days). A larger\n * value is overflow-clamped by Node to 1ms with a TimeoutOverflowWarning, so we\n * clamp defensively at every timer arm (issue #1909 review round 5) even though\n * parseConfig already caps `bufferSaveDebounceMs` — a directly-constructed config\n * could still exceed it.\n */\nconst MAX_SET_TIMEOUT_MS = 2_147_483_647;\n\ninterface AddTurnMutationResult {\n decision: TriggerDecision;\n signalLevel: SignalLevel;\n priorTurns: BufferTurn[];\n activeTurnsSnapshot: BufferTurn[];\n retainedTurnsSnapshot: BufferTurn[];\n turnCountInWindow: number;\n}\n\nexport class SmartBuffer {\n private state: BufferState;\n private loaded = false;\n private loadPromise: Promise<void> | null = null;\n private readonly surpriseProbe: BufferSurpriseProbe | null;\n private mutationChain: Promise<unknown> = Promise.resolve();\n /**\n * Serialized write chain for `BUFFER_SURPRISE` telemetry events.\n *\n * The telemetry path is fire-and-forget (`addTurn` does not await the\n * ledger append), but multiple concurrent appends would still settle\n * out of order under variable filesystem latency. The report path\n * assumes chronological ordering — it slices the tail of the ledger\n * and treats the most recent entry as the current threshold in force.\n * Chaining ensures each append only runs after the previous settles,\n * preserving wall-clock order.\n *\n * We include a `.catch` on every link so a rejected append does not\n * poison the chain (CLAUDE.md rule #40).\n */\n private surpriseTelemetryWriteChain: Promise<unknown> = Promise.resolve();\n\n /**\n * Debounced buffer-save state (issue #1909). Steady-state buffering used to\n * serialize + rewrite the whole multi-session buffer on EVERY turn. We now\n * coalesce those writes onto a trailing-edge timer; correctness boundaries\n * (extraction trigger, extraction clear, shutdown) still force an immediate\n * flush. `bufferSaveDebounceMs: 0` restores save-every-turn exactly.\n */\n private saveTimer: NodeJS.Timeout | null = null;\n private pendingSave = false;\n /** Wall-clock ms when the currently-pending save was first scheduled (issue\n * #1909). Null when nothing is pending. Used to bound deferral under sustained\n * activity (see BUFFER_SAVE_MAX_DEFER_MULTIPLIER). */\n private firstPendingAtMs: number | null = null;\n\n /** Which sessions' persisted files are stale (per-session incremental saves). */\n private readonly persistence = new BufferSessionPersistence();\n\n constructor(\n private readonly config: PluginConfig,\n private readonly storage: BufferStorage,\n surpriseProbe: BufferSurpriseProbe | null = null,\n ) {\n this.state = { turns: [], lastExtractionAt: null, extractionCount: 0 };\n this.surpriseProbe = surpriseProbe;\n }\n\n private enqueueMutation<T>(op: () => Promise<T>): Promise<T> {\n const run = this.mutationChain.catch(() => {}).then(op);\n this.mutationChain = run.catch(() => {});\n return run;\n }\n\n private entryFor(key: string): BufferEntryState {\n if (!this.state.entries) {\n this.state.entries = Object.create(null) as NonNullable<BufferState[\"entries\"]>;\n }\n const entries = this.state.entries as NonNullable<BufferState[\"entries\"]>;\n if (Object.hasOwn(entries, key)) {\n const stored = entries[key];\n // Guard against corrupted state/buffer.json — if the stored entry\n // is not a valid object shape, discard it and recreate.\n if (stored && typeof stored === \"object\" && Array.isArray(stored.turns)) {\n return stored;\n }\n // Corrupted — fall through to recreate.\n }\n const created: BufferEntryState = {\n turns: [],\n lastExtractionAt: null,\n extractionCount: 0,\n };\n entries[key] = created;\n return created;\n }\n\n private peekEntry(key: string): BufferEntryState | null {\n const existing = this.state.entries?.[key];\n if (existing) return existing;\n if (key !== \"default\") return null;\n return {\n turns: Array.isArray(this.state.turns) ? this.state.turns : [],\n lastExtractionAt: this.state.lastExtractionAt ?? null,\n extractionCount:\n typeof this.state.extractionCount === \"number\" ? this.state.extractionCount : 0,\n };\n }\n\n private normalizeState(state: BufferState): BufferState {\n const entries = Object.assign(\n Object.create(null),\n state.entries ?? {},\n ) as NonNullable<BufferState[\"entries\"]>;\n if (!entries.default) {\n entries.default = {\n turns: Array.isArray(state.turns) ? [...state.turns] : [],\n lastExtractionAt: state.lastExtractionAt ?? null,\n extractionCount:\n typeof state.extractionCount === \"number\" ? state.extractionCount : 0,\n };\n }\n return {\n turns: entries.default.turns,\n lastExtractionAt: entries.default.lastExtractionAt,\n extractionCount: entries.default.extractionCount,\n entries,\n };\n }\n\n private entryActivityAt(entry: BufferEntryState): number {\n const lastTurnAt = entry.turns.reduce((latest, turn) => {\n const parsed = Date.parse(turn.timestamp);\n return Number.isFinite(parsed) ? Math.max(latest, parsed) : latest;\n }, -1);\n const lastExtractionAt =\n typeof entry.lastExtractionAt === \"string\"\n ? Date.parse(entry.lastExtractionAt)\n : Number.NaN;\n return Math.max(\n lastTurnAt,\n Number.isFinite(lastExtractionAt) ? lastExtractionAt : -1,\n );\n }\n\n /** Evict oldest entries past MAX_BUFFER_ENTRY_COUNT and queue their session files for deletion. */\n private pruneEntries(retainKeys: string[]): void {\n const entries = this.state.entries;\n if (!entries) return;\n const evicted = selectEvictedBufferKeys(entries, retainKeys, MAX_BUFFER_ENTRY_COUNT, {\n activityAt: (entry) => this.entryActivityAt(entry),\n holdsAcceptedCapture: (entry) => this.entryHoldsAcceptedCapture(entry),\n });\n for (const key of evicted) delete entries[key];\n this.persistence.markEvicted(evicted);\n if (evicted.length > 0) {\n // Loud degradation (extraction hot-loop hardening, Step 7): buffer\n // pressure during a provider outage is bounded and expected, but must\n // be observable, not silent.\n log.warn(\n `buffer: pruned ${evicted.length} oldest session entr${evicted.length === 1 ? \"y\" : \"ies\"} ` +\n `past MAX_BUFFER_ENTRY_COUNT=${MAX_BUFFER_ENTRY_COUNT}; buffered turn data for those sessions was dropped`,\n );\n }\n }\n\n private async loadUnlocked(): Promise<void> {\n if (this.loaded) return;\n if (!this.loadPromise) {\n this.loadPromise = this.storage.loadBuffer()\n .then((state) => {\n this.state = this.normalizeState(state);\n this.loaded = true;\n })\n .finally(() => {\n this.loadPromise = null;\n });\n }\n await this.loadPromise;\n }\n\n async load(): Promise<void> {\n await this.enqueueMutation(async () => this.loadUnlocked());\n }\n\n /** Snapshot of buffered, not-yet-extracted work across sessions (#2151): session count,\n * pending-turn total, oldest buffered turn. Counts retained (#562) + active turns per entry. */\n async getBufferSnapshot(): Promise<ExtractionBufferSnapshot> {\n await this.load();\n let bufferedSessionCount = 0;\n let pendingTurnCount = 0;\n let oldestMs = Number.POSITIVE_INFINITY;\n let oldestTurnTimestamp: string | null = null;\n const consider = (turns: BufferTurn[] | undefined): void => {\n if (!Array.isArray(turns) || turns.length === 0) return;\n bufferedSessionCount += 1;\n pendingTurnCount += turns.length;\n const first = turns[0]?.timestamp;\n const parsed = typeof first === \"string\" ? Date.parse(first) : Number.NaN;\n if (Number.isFinite(parsed) && parsed < oldestMs) {\n oldestMs = parsed;\n oldestTurnTimestamp = first ?? null;\n }\n };\n const entries = this.state.entries;\n if (entries) {\n // Retained turns (deferred #562) are pending too - count with active (oldest-first), like getTurns().\n for (const entry of Object.values(entries)) consider([...(entry?.retainedTurns ?? []), ...(entry?.turns ?? [])]);\n } else {\n consider(this.state.turns);\n }\n return { bufferedSessionCount, pendingTurnCount, oldestTurnTimestamp };\n }\n\n /**\n * Reset the buffer to an empty, usable state.\n * Called when the persisted buffer file is corrupt and load() fails,\n * so the buffer can still accept new turns for the rest of the session.\n */\n resetToEmpty(): void {\n for (const key of Object.keys(this.state.entries ?? {})) {\n this.persistence.markDeleted(key);\n }\n this.state = { turns: [], lastExtractionAt: null, extractionCount: 0 };\n this.loaded = true;\n }\n\n private async saveUnlocked(): Promise<void> {\n const { handedOver, drainedTurns } = await this.persistence.persist(this.storage, this.state, (key) => this.peekEntry(key) ?? undefined);\n // A drain tombstone: the turns the drain extracted leave this copy too,\n // so a stale owner never extracts (or persists) them a second time.\n for (const [key, drained] of drainedTurns) {\n const entry = this.peekEntry(key);\n if (!entry) continue;\n entry.turns = subtractBufferTurns(entry.turns, drained);\n if (entry.retainedTurns && entry.retainedTurns.length > 0) {\n entry.retainedTurns = subtractBufferTurns(entry.retainedTurns, drained);\n if (entry.retainedTurns.length === 0) delete entry.retainedTurns;\n }\n if (key === \"default\") this.state.turns = entry.turns;\n }\n if (handedOver.length === 0) return;\n // A drain claim now owns these sessions' turns (durable in the claim\n // file): drop the in-memory entries so this process cannot resurrect\n // them. A later observe for the same key starts a fresh entry whose\n // turns flow into the claim at the next handover.\n const entries = this.state.entries;\n if (!entries) return;\n for (const key of handedOver) {\n delete entries[key];\n if (key === \"default\") {\n this.state.turns = [];\n }\n }\n }\n\n /** Sync gate for the extraction queue: is this session claimed by a buffer drain? */\n isSessionClaimed(key: string): boolean {\n return this.storage.isBufferSessionClaimed?.(key) === true;\n }\n\n async save(): Promise<void> {\n await this.enqueueMutation(async () => this.saveUnlocked());\n }\n\n /**\n * Schedule a coalesced, TRUE trailing-edge buffer save (issue #1909). Only\n * used for the debounced (`bufferSaveDebounceMs > 0`) steady-state buffering\n * path; the debounce-off and correctness-boundary paths save inline within the\n * mutation (see `recordTurnUnlocked`). Each call re-arms the timer from now so\n * the write lands one full window after the LAST turn, not the first. To keep\n * sustained activity from deferring the save without bound (which would widen\n * the crash-loss window), once a pending save has been deferred\n * BUFFER_SAVE_MAX_DEFER_MULTIPLIER windows it is flushed inline instead of\n * re-armed. Runs inside the record mutation, so the inline save is awaited.\n */\n private async scheduleSave(): Promise<void> {\n const ms = Math.min(this.config.bufferSaveDebounceMs, MAX_SET_TIMEOUT_MS);\n const now = Date.now();\n this.pendingSave = true;\n if (this.firstPendingAtMs === null) this.firstPendingAtMs = now;\n if (now - this.firstPendingAtMs >= ms * BUFFER_SAVE_MAX_DEFER_MULTIPLIER) {\n // Staleness cap hit: persist now rather than deferring further. Drop the\n // armed timer, attempt the write, and only mark clean on success — a\n // failure keeps the save pending + re-arms so shutdown/the next timer\n // retries (issue #1909 review round 2), never diverging memory from disk.\n clearTimeout(this.saveTimer ?? undefined);\n this.saveTimer = null;\n try {\n await this.saveUnlocked();\n this.pendingSave = false;\n this.firstPendingAtMs = null;\n } catch (err) {\n log.warn(`buffer.scheduleSave: staleness-cap save failed, keeping it pending: ${describeError(err)}`);\n this.saveTimer = setTimeout(() => {\n this.saveTimer = null;\n void this.flushPendingSave();\n }, ms);\n this.saveTimer.unref?.();\n }\n return;\n }\n // True trailing edge: drop any armed timer and re-arm from now.\n clearTimeout(this.saveTimer ?? undefined);\n this.saveTimer = setTimeout(() => {\n this.saveTimer = null;\n void this.flushPendingSave();\n }, ms);\n this.saveTimer.unref?.();\n }\n\n /** Cancel any armed debounced save without persisting. */\n private cancelScheduledSave(): void {\n if (this.saveTimer) {\n clearTimeout(this.saveTimer);\n this.saveTimer = null;\n }\n this.pendingSave = false;\n this.firstPendingAtMs = null;\n }\n\n /**\n * Persist the current in-memory buffer state inline, keeping the global\n * pending-save state armed until the write SUCCEEDS (issue #1909). On failure\n * the save stays pending and — when debounced — a background retry timer is\n * (re-)armed before the error propagates, so a graceful shutdown flush and the\n * next timer tick both retry. A failed post-mutation save therefore can never\n * silently drop buffered turns, including turns from OTHER sessions that were\n * only in the debounced pending state. The pending flag is cleared (and any\n * armed timer dropped) only after a durable write.\n */\n private async saveNowRetainingPendingOnFailure(context: string): Promise<void> {\n this.pendingSave = true;\n if (this.firstPendingAtMs === null) this.firstPendingAtMs = Date.now();\n try {\n await this.saveUnlocked();\n } catch (err) {\n log.warn(\n `buffer.${context}: inline save failed, keeping it pending for retry: ${describeError(err)}`,\n );\n const ms = Math.min(this.config.bufferSaveDebounceMs, MAX_SET_TIMEOUT_MS);\n if (ms > 0 && !this.saveTimer) {\n this.saveTimer = setTimeout(() => {\n this.saveTimer = null;\n void this.flushPendingSave();\n }, ms);\n this.saveTimer.unref?.();\n }\n throw err;\n }\n this.cancelScheduledSave();\n }\n\n /**\n * Force any pending debounced save to land now (issue #1909). Idempotent and\n * safe to call from outside a mutation (timer tick, shutdown/dispose, or the\n * surprise-promotion path in `addTurnWithOutcome`). Do NOT `await` this from\n * inside a mutation — it enqueues its own mutation and would deadlock the\n * serializer.\n *\n * `throwOnFailure` (review round 7 finding 5): when set, a failed write is\n * rethrown AFTER the keep-pending + re-arm bookkeeping, so the surprise\n * extraction boundary gets the same durability guarantee as the built-in\n * extract triggers (which propagate saveUnlocked failures) instead of\n * proceeding to extract_now on a non-durable triggering turn. Default false\n * keeps the fail-open behavior for the timer/shutdown callers.\n */\n async flushPendingSave(opts?: { throwOnFailure?: boolean }): Promise<void> {\n if (this.saveTimer) {\n clearTimeout(this.saveTimer);\n this.saveTimer = null;\n }\n // resetToEmpty-only deletions are pending work too, even with no\n // pending-save flag set.\n if (!this.pendingSave && !this.persistence.hasPending()) return;\n try {\n await this.enqueueMutation(async () => {\n // Re-check under the serializer: a concurrent flush may have already\n // persisted this pending save. Skip the redundant write (no phantom\n // writes). resetToEmpty-only deletions also land here without a\n // pending-save flag.\n if (!this.pendingSave && !this.persistence.hasPending()) return;\n await this.saveUnlocked();\n // Clear the pending flag INSIDE the same serialized mutation as the\n // write (issue #1909 review). Clearing it after the enqueue await\n // resolved raced an addTurn interleaving between the write and the\n // clear: that turn's scheduleSave re-armed pendingSave + a timer, then\n // this clear wiped it and the debounced flush was lost. Atomic\n // write+clear means any addTurn runs wholly before (its turn is in the\n // write) or wholly after (its pendingSave survives and its timer\n // persists it).\n this.pendingSave = false;\n this.firstPendingAtMs = null;\n });\n } catch (err) {\n // The write failed: memory and disk diverge (issue #1909 review round 2).\n // Keep the save PENDING (do NOT clear pendingSave/firstPendingAtMs) so a\n // graceful shutdown flush and the re-armed timer both retry it — clearing\n // the flag here would drop the buffered turns permanently. Re-arm a\n // background retry when debounced.\n log.warn(`buffer.flushPendingSave: save failed, keeping it pending for retry: ${describeError(err)}`);\n const ms = Math.min(this.config.bufferSaveDebounceMs, MAX_SET_TIMEOUT_MS);\n if (ms > 0 && !this.saveTimer) {\n this.saveTimer = setTimeout(() => {\n this.saveTimer = null;\n void this.flushPendingSave();\n }, ms);\n this.saveTimer.unref?.();\n }\n // Surprise-extraction boundary needs the durability guarantee — surface\n // the failure so the caller does not proceed with a non-durable flush.\n if (opts?.throwOnFailure) throw err;\n return; // fail-open for timer/shutdown callers\n }\n }\n\n async addTurn(bufferKey: string, turn: BufferTurn): Promise<TriggerDecision> {\n return (await this.addTurnWithOutcome(bufferKey, turn)).decision;\n }\n\n /** Admit atomically; refuse at capacity rather than evict accepted work. */\n async addTurnBounded(bufferKey: string, turn: BufferTurn): Promise<AddTurnOutcome | null> {\n const mutation = await this.enqueueMutation(async () => {\n await this.loadUnlocked();\n if (this.peekEntry(bufferKey) === null) {\n this.makeRoomForEntryUnlocked();\n if (Object.keys(this.state.entries ?? {}).length >= MAX_BUFFER_ENTRY_COUNT) {\n log.warn(\n `buffer[${bufferKey}]: durable capture refused at MAX_BUFFER_ENTRY_COUNT=${MAX_BUFFER_ENTRY_COUNT}`,\n );\n return null;\n }\n }\n return this.recordTurnUnlocked(bufferKey, turn);\n });\n if (mutation === null) return null;\n return this.completeAddTurnOutcome(bufferKey, turn, mutation);\n }\n\n /** Prune empty entries only; accepted work must survive capacity pressure. */\n private makeRoomForEntryUnlocked(): void {\n const entries = this.state.entries;\n if (!entries) return;\n const keys = Object.keys(entries);\n if (keys.length < MAX_BUFFER_ENTRY_COUNT) return;\n const byOldestActivity = (left: string, right: string): number =>\n this.entryActivityAt(entries[left] ?? { turns: [], lastExtractionAt: null, extractionCount: 0 }) -\n this.entryActivityAt(entries[right] ?? { turns: [], lastExtractionAt: null, extractionCount: 0 });\n const emptyRemovable = keys\n .filter(\n (key) =>\n key !== \"default\" &&\n (entries[key]?.turns.length ?? 0) === 0 &&\n (entries[key]?.retainedTurns?.length ?? 0) === 0,\n )\n .sort(byOldestActivity);\n for (const key of emptyRemovable) {\n if (Object.keys(entries).length < MAX_BUFFER_ENTRY_COUNT) break;\n delete entries[key];\n this.persistence.markDeleted(key);\n }\n }\n\n private entryHoldsAcceptedCapture(entry: BufferEntryState | undefined): boolean {\n return (entry?.turns ?? []).some(isAcceptedTurn) || (entry?.retainedTurns ?? []).some(isAcceptedTurn);\n }\n\n async addTurnWithOutcome(\n bufferKey: string,\n turn: BufferTurn,\n ): Promise<AddTurnOutcome> {\n const mutation = await this.enqueueMutation(() => this.recordTurnUnlocked(bufferKey, turn));\n return this.completeAddTurnOutcome(bufferKey, turn, mutation);\n }\n\n /** Run probes outside the mutation lock to avoid reentrancy deadlocks. */\n private async completeAddTurnOutcome(\n bufferKey: string,\n turn: BufferTurn,\n mutation: AddTurnMutationResult,\n ): Promise<AddTurnOutcome> {\n let decision = mutation.decision;\n let extractionTurns: BufferTurn[] | undefined;\n\n // Surprise-gated flush (issue #563). Additive only: if the probe is\n // disabled, unavailable, or the score is below threshold, the decision\n // from the existing trigger logic stands. The probe only ever *promotes*\n // `keep_buffering` → `extract_now`; it never suppresses an existing\n // flush. This preserves the invariant that enabling surprise cannot\n // *reduce* extraction frequency.\n if (\n decision === \"keep_buffering\" &&\n resolvePresentationCapabilities(this.config).bufferSurpriseTrigger &&\n this.surpriseProbe !== null &&\n // Matching the existing \"smart\" branch: surprise is a lower-tier\n // novelty signal that should not second-guess a high-signal hit\n // (which already flushes) or fight `every_n` / `time_based` modes.\n this.config.triggerMode === \"smart\" &&\n mutation.signalLevel !== \"high\"\n ) {\n const surprise = await this.computeSurpriseSafe(bufferKey, turn, mutation.priorTurns);\n if (surprise !== null) {\n const shouldPromote = surprise > this.config.bufferSurpriseThreshold;\n let triggered = false;\n if (shouldPromote) {\n const currentTurns = await this.getExtractionTurnsIfBufferSnapshotStillCurrent(\n bufferKey,\n mutation.activeTurnsSnapshot,\n mutation.retainedTurnsSnapshot,\n );\n if (currentTurns) {\n log.debug(\n `buffer[${bufferKey}]: surprise=${surprise.toFixed(3)} > threshold=${this.config.bufferSurpriseThreshold} → extract_now`,\n );\n decision = \"extract_now\";\n triggered = true;\n extractionTurns = currentTurns;\n // Issue #1909 (review): the record mutation for a `keep_buffering`\n // turn only SCHEDULED a debounced save. Surprise now promotes it to\n // extract_now AFTER that mutation, so force the buffer durable before\n // the caller runs extraction — otherwise state/buffer.json lags the\n // extracted turns by up to the debounce window on a crash. Safe to\n // await here: we are outside the record mutation (deadlock-free).\n // throwOnFailure (round 7 finding 5): match the built-in extract\n // triggers — a failed durability write must NOT silently proceed to\n // extract_now on a non-durable turn.\n await this.flushPendingSave({ throwOnFailure: true });\n } else {\n log.debug(\n `buffer[${bufferKey}]: surprise=${surprise.toFixed(3)} ignored because buffer changed before probe resolved`,\n );\n }\n }\n // Emit telemetry on every scored turn — both triggering and\n // non-triggering — so operators can fit the threshold to real\n // traffic distributions. Fire-and-forget: `addTurn` does NOT\n // await the ledger append, so slow/contended filesystems cannot\n // add JSONL-append latency to every `processTurn`. But we DO\n // serialize writes through a promise chain so concurrent\n // appends settle in wall-clock order — the report path assumes\n // chronological tail rows and reads the most recent as the\n // \"current\" threshold.\n //\n // Project only the fields we need into the queue entry rather\n // than capturing the full `BufferTurn` — under slow filesystem\n // latency the chain can back up, and we must not retain the\n // (potentially large) `turn.content` string for every pending\n // append.\n this.queueSurpriseTelemetryWrite({\n bufferKey,\n turnRole: turn.role,\n sessionKey:\n typeof turn.sessionKey === \"string\" ? turn.sessionKey : null,\n surpriseScore: surprise,\n triggered,\n turnCountInWindow: mutation.turnCountInWindow,\n // Stamp at decision time so backpressure on the write chain\n // does not shift the event's apparent moment away from when\n // the turn was actually scored.\n timestamp: new Date().toISOString(),\n // Snapshot the threshold used to compute `triggered` so a\n // concurrent config mutation cannot retroactively change\n // what the ledger row claims the decision was against.\n threshold: this.config.bufferSurpriseThreshold,\n });\n }\n }\n\n log.debug(\n `buffer[${bufferKey}]: ${mutation.turnCountInWindow} turns, signal=${mutation.signalLevel}, decision=${decision}`,\n );\n if (decision !== \"keep_buffering\" && extractionTurns === undefined) {\n extractionTurns = [\n ...mutation.retainedTurnsSnapshot,\n ...mutation.activeTurnsSnapshot,\n ];\n }\n return extractionTurns ? { decision, extractionTurns } : { decision };\n }\n\n private async recordTurnUnlocked(bufferKey: string, turn: BufferTurn): Promise<AddTurnMutationResult> {\n await this.loadUnlocked();\n const entry = this.entryFor(bufferKey);\n const priorTurns = entry.turns.slice();\n entry.turns.push(turn);\n const activeTurnsSnapshot = entry.turns.map(copyBufferTurn);\n const retainedTurnsSnapshot = (entry.retainedTurns ?? []).map(copyBufferTurn);\n if (bufferKey === \"default\") {\n this.state.turns = entry.turns;\n }\n\n const signal = scanSignals(turn.content, this.config.highSignalPatterns);\n const decision = this.evaluate(entry, signal.level);\n const turnCountInWindow = entry.turns.length;\n\n this.persistence.markDirty(bufferKey);\n this.pruneEntries([bufferKey]);\n if (decision === \"keep_buffering\" && this.config.bufferSaveDebounceMs > 0) {\n // Steady-state buffering: coalesce the whole-state serialize onto a\n // trailing-edge timer (issue #1909) instead of rewriting per turn.\n await this.scheduleSave();\n } else {\n // Persist immediately within this mutation (awaited) when either:\n // - the turn triggered extraction (the buffer must be durable), or\n // - debounce is disabled (bufferSaveDebounceMs <= 0), which reproduces\n // the legacy save-every-turn behavior byte-for-byte.\n // Round 8 thread 4: the write is attempted BEFORE the pending state is\n // cleared, and a failed write leaves it pending (+ a re-armed timer) for\n // shutdown/timer retry instead of dropping the in-memory turns.\n await this.saveNowRetainingPendingOnFailure(\"recordTurn\");\n }\n return {\n decision,\n signalLevel: signal.level,\n priorTurns,\n activeTurnsSnapshot,\n retainedTurnsSnapshot,\n turnCountInWindow,\n };\n }\n\n private async getExtractionTurnsIfBufferSnapshotStillCurrent(\n bufferKey: string,\n activeTurnsSnapshot: readonly BufferTurn[],\n retainedTurnsSnapshot: readonly BufferTurn[],\n ): Promise<BufferTurn[] | null> {\n return this.enqueueMutation(async () => {\n await this.loadUnlocked();\n const entry = this.peekEntry(bufferKey);\n if (!entry) return null;\n const retained = entry.retainedTurns ?? [];\n const stillCurrent =\n bufferTurnArrayIsSuffixOfSnapshot(entry.turns, activeTurnsSnapshot) &&\n bufferTurnArraysEqual(retained, retainedTurnsSnapshot);\n if (!stillCurrent) return null;\n return [...retained, ...entry.turns];\n });\n }\n\n /**\n * Enqueue a telemetry append on the serialized write chain.\n *\n * The chain is a classic `writeChain = writeChain.then(fn).catch(...)`\n * — each link waits for the previous to settle before its append\n * starts, so out-of-order chronology cannot happen even under\n * variable filesystem latency. We always attach `.catch` so one\n * rejection does not poison the chain for the rest of the session\n * (CLAUDE.md rule #40). The error is logged through\n * `emitSurpriseEventSafe` itself, which swallows its own rejections.\n *\n * Public surface is deliberately narrow — only `addTurn` should call\n * this, so the surprise telemetry path stays centralized.\n */\n private queueSurpriseTelemetryWrite(params: SurpriseTelemetryQueueEntry): void {\n this.surpriseTelemetryWriteChain = this.surpriseTelemetryWriteChain\n .then(() => this.emitSurpriseEventSafe(params))\n .catch(() => {\n // `emitSurpriseEventSafe` already handles the logging. We\n // swallow here only so one failure does not break the chain\n // for future writes.\n });\n }\n\n /**\n * Append a single `BUFFER_SURPRISE` telemetry row (issue #563 PR 3).\n *\n * Deliberately swallows write errors: the buffer must never fail to\n * record a turn because the observation ledger is read-only, out of\n * disk, or otherwise unhappy. The log line at debug lets operators\n * confirm the path fired without polluting the error channel.\n */\n private async emitSurpriseEventSafe(\n params: SurpriseTelemetryQueueEntry,\n ): Promise<void> {\n const storage = this.storage;\n if (typeof storage.appendBufferSurpriseEvents !== \"function\") {\n // Older StorageManager / test double without the telemetry sink.\n // Silently skip — core path is still covered by the log line above.\n return;\n }\n const event: BufferSurpriseEvent = {\n event: \"BUFFER_SURPRISE\",\n // Use the decision-time stamp captured when the event was\n // queued, NOT `Date.now()` here — backpressure on the write\n // chain could otherwise shift timestamps into the future relative\n // to when the turn was scored.\n timestamp: params.timestamp,\n bufferKey: params.bufferKey,\n sessionKey: params.sessionKey,\n turnRole: params.turnRole,\n surpriseScore: params.surpriseScore,\n // Use the snapshotted threshold from the queue entry, not the\n // live config — see `SurpriseTelemetryQueueEntry.threshold`\n // doc for the rationale.\n threshold: params.threshold,\n triggeredFlush: params.triggered,\n turnCountInWindow: params.turnCountInWindow,\n };\n try {\n await storage.appendBufferSurpriseEvents([event]);\n } catch (err) {\n // Same guard as `computeSurpriseSafe`: non-Error rejections must\n // not crash the telemetry helper, which would defeat the whole\n // point of isolating the ledger write from the hot path.\n log.debug(\n `buffer[${params.bufferKey}]: surprise telemetry write failed, continuing: ${describeError(err)}`,\n );\n }\n }\n\n /**\n * Invoke the injected surprise probe defensively. Any error (probe throws,\n * embedder unavailable, timeout) is swallowed and logged at debug: the\n * surprise path must never crash the happy-path trigger evaluation. A\n * `null` return indicates \"no score available, fall through to existing\n * triggers\".\n */\n private async computeSurpriseSafe(\n bufferKey: string,\n turn: BufferTurn,\n priorTurns: readonly BufferTurn[],\n ): Promise<number | null> {\n if (!this.surpriseProbe) return null;\n try {\n // Hard timeout around the probe so a hung embedder cannot stall\n // `addTurn()` before `save()`. A slow probe would otherwise\n // prevent the just-appended turn from ever being persisted. The\n // timeout is a soft bound — we race it against the probe, take\n // whichever settles first, and treat the timeout as\n // \"probe unavailable, fall through\" rather than an error that\n // surfaces to the caller.\n const score = await probeWithTimeout(\n this.surpriseProbe.scoreTurn(bufferKey, turn, priorTurns),\n this.config.bufferSurpriseProbeTimeoutMs,\n );\n if (score === null) return null;\n if (typeof score !== \"number\" || !Number.isFinite(score)) {\n log.debug(\n `buffer[${bufferKey}]: surprise probe returned non-finite score (${String(score)}), ignoring`,\n );\n return null;\n }\n // Defensive clamp: formula lives in buffer-surprise.ts, but we never\n // want a misbehaving probe to inject an out-of-range value into the\n // threshold comparison.\n if (score < 0) return 0;\n if (score > 1) return 1;\n return score;\n } catch (err) {\n // `err` may be any thrown value — `throw null` and\n // `Promise.reject(\"x\")` are both legal. Accessing `.message` on a\n // non-Error would itself throw and defeat the failure-isolation\n // contract, so describe the value safely.\n log.debug(\n `buffer[${bufferKey}]: surprise probe failed, falling back to existing triggers: ${describeError(err)}`,\n );\n return null;\n }\n }\n\n private evaluate(entry: BufferEntryState, signalLevel: SignalLevel): TriggerDecision {\n if (this.config.triggerMode === \"smart\") {\n if (signalLevel === \"high\") return \"extract_now\";\n\n if (entry.turns.length >= this.config.bufferMaxTurns) {\n return \"extract_batch\";\n }\n\n if (entry.lastExtractionAt) {\n const elapsed =\n Date.now() - new Date(entry.lastExtractionAt).getTime();\n if (elapsed >= this.config.bufferMaxMinutes * 60_000) {\n return \"extract_batch\";\n }\n }\n\n return \"keep_buffering\";\n }\n\n if (this.config.triggerMode === \"every_n\") {\n return entry.turns.length >= this.config.bufferMaxTurns\n ? \"extract_batch\"\n : \"keep_buffering\";\n }\n\n if (this.config.triggerMode === \"time_based\") {\n if (!entry.lastExtractionAt) {\n return entry.turns.length >= this.config.bufferMaxTurns\n ? \"extract_batch\"\n : \"keep_buffering\";\n }\n const elapsed =\n Date.now() - new Date(entry.lastExtractionAt).getTime();\n return elapsed >= this.config.bufferMaxMinutes * 60_000\n ? \"extract_batch\"\n : \"keep_buffering\";\n }\n\n return \"keep_buffering\";\n }\n\n getTurns(bufferKey = \"default\"): BufferTurn[] {\n const entry = this.peekEntry(bufferKey);\n if (!entry) return [];\n const retained = entry.retainedTurns ?? [];\n // Retained turns (from a previous defer verdict, issue #562 PR 2) are\n // prepended so the chronological order — oldest context first — is\n // preserved for the next extraction pass.\n return [...retained, ...entry.turns];\n }\n\n /**\n * Retain a subset of the current turns across `clearAfterExtraction` so a\n * future extraction pass sees the context behind a deferred candidate\n * (issue #562, PR 2). Callers pass the turns that were seen during the\n * current extraction; the buffer keeps the tail (latest `max` turns) as\n * the retention window. Passing an empty array or `max <= 0` clears the\n * retention slot instead.\n */\n async retainDeferredTurns(\n bufferKey: string,\n turns: BufferTurn[],\n max = 10,\n originalTurns?: readonly BufferTurn[],\n ): Promise<void> {\n await this.enqueueMutation(async () => {\n await this.loadUnlocked();\n const entry = this.entryFor(bufferKey);\n const retained = selectRetainedDeferredTurns(\n entry.retainedTurns ?? [], turns, max, originalTurns,\n );\n if (retained.length > 0) entry.retainedTurns = retained;\n else delete entry.retainedTurns;\n this.persistence.markDirty(bufferKey);\n await this.saveUnlocked();\n });\n }\n\n /**\n * Return the current retention window (issue #562, PR 2). Primarily for\n * tests and diagnostics.\n */\n getRetainedDeferredTurns(bufferKey = \"default\"): BufferTurn[] {\n const entry = this.peekEntry(bufferKey);\n return entry?.retainedTurns ? [...entry.retainedTurns] : [];\n }\n\n /**\n * Clear deferred retention copies for a force-flushed session. Normal\n * extraction preserves these copies so a deferred candidate can be retried;\n * an explicit force flush is the caller's request to drain that context.\n */\n async clearRetainedTurnsForSession(\n sessionKey: string,\n ownerPrincipal?: string,\n options: RetainedTurnCleanupOptions = {},\n ): Promise<void> {\n if (typeof sessionKey !== \"string\" || sessionKey.length === 0) return;\n const normalizedOwnerPrincipal =\n typeof ownerPrincipal === \"string\" && ownerPrincipal.trim().length > 0\n ? ownerPrincipal.trim()\n : undefined;\n const namespacesEnabled = resolveNamespaceCapabilities(this.config).namespaces === true;\n const normalizedCleanupNamespace =\n namespacesEnabled && options.writeNamespaceOverride !== undefined && options.writeNamespaceOverride.length > 0\n ? options.writeNamespaceOverride\n : undefined;\n const assertLifecycle = (): void => {\n throwIfAborted(options.abortSignal, \"extraction force-flush aborted\");\n if (typeof options.deadlineMs === \"number\" && Date.now() >= options.deadlineMs) {\n throw new ExtractionDeadlineError(\"retained_turn_cleanup\");\n }\n };\n assertLifecycle();\n await this.enqueueMutation(async () => {\n assertLifecycle();\n const hadPendingSave = this.pendingSave;\n if (this.saveTimer) {\n clearTimeout(this.saveTimer);\n this.saveTimer = null;\n }\n await this.loadUnlocked();\n assertLifecycle();\n const bufferKeys = this.matchingSessionBufferKeysUnlocked(sessionKey);\n if (bufferKeys.length === 0) {\n if (hadPendingSave) {\n assertLifecycle();\n await this.saveNowRetainingPendingOnFailure(\"clearRetainedTurnsForSession\");\n }\n return;\n }\n let changed = false;\n const matchesCleanupScope = (turn: BufferTurn): boolean => {\n // Legacy unpinned turns keep their existing cleanup semantics.\n if (\n turn.writeNamespaceOverride !== undefined &&\n normalizedCleanupNamespace !== undefined &&\n turn.writeNamespaceOverride !== normalizedCleanupNamespace\n ) {\n return false;\n }\n // Equal write namespaces can still belong to different project bindings.\n if (options.scopeProfileWritePlan && hasPinnedCaptureScope(turn)) {\n if (\n scopeProfilePlanIdentity(turn.scopeProfileWritePlan) !== scopeProfilePlanIdentity(options.scopeProfileWritePlan) &&\n !(turn.acceptedCapture === true && turn.scopeProfileWritePlan === undefined)\n ) {\n return false;\n }\n const ctx = options.codingContext;\n if (\n ctx && turn.codingContext &&\n (turn.codingContext.projectId !== ctx.projectId ||\n turn.codingContext.rootPath !== ctx.rootPath ||\n turn.codingContext.branch !== ctx.branch ||\n turn.codingContext.defaultBranch !== ctx.defaultBranch)\n ) {\n return false;\n }\n }\n return true;\n };\n const belongsToOwner = (turn: BufferTurn): boolean => {\n if (turn.sessionKey !== sessionKey) return false;\n if (!matchesCleanupScope(turn)) return false;\n if (normalizedOwnerPrincipal === undefined) return true;\n if (turn.sessionOwnerPrincipal === normalizedOwnerPrincipal) return true;\n return (\n turn.sessionOwnerPrincipal === undefined &&\n resolvePrincipal(turn.sessionKey, this.config) === normalizedOwnerPrincipal\n );\n };\n for (const bufferKey of bufferKeys) {\n const entry = this.entryFor(bufferKey);\n const retainedTurns = entry.retainedTurns ?? [];\n const remainingTurns = retainedTurns.filter((turn) => !belongsToOwner(turn));\n if (remainingTurns.length === retainedTurns.length) continue;\n changed = true;\n if (remainingTurns.length > 0) entry.retainedTurns = remainingTurns;\n else delete entry.retainedTurns;\n if (bufferKey === \"default\") this.state.turns = entry.turns;\n this.persistence.markDirty(bufferKey);\n }\n if (changed || hadPendingSave) {\n assertLifecycle();\n await this.saveNowRetainingPendingOnFailure(\"clearRetainedTurnsForSession\");\n }\n assertLifecycle();\n });\n }\n\n async findBufferKeyForSession(sessionKey: string): Promise<string | null> {\n const bufferKeys = await this.findBufferKeysForSession(sessionKey);\n return bufferKeys[0] ?? null;\n }\n\n private matchingSessionBufferKeysUnlocked(sessionKey: string): string[] {\n const matches: string[] = [];\n const hasSessionTurns = (entry: BufferEntryState | null | undefined): boolean =>\n [...(entry?.turns ?? []), ...(entry?.retainedTurns ?? [])].some(\n (turn) => typeof turn.sessionKey === \"string\" && turn.sessionKey === sessionKey,\n );\n const directEntry = this.peekEntry(sessionKey);\n if (hasSessionTurns(directEntry)) {\n matches.push(sessionKey);\n }\n\n const entries = this.state.entries ?? {};\n for (const [bufferKey, entry] of Object.entries(entries)) {\n if (!matches.includes(bufferKey) && hasSessionTurns(entry)) {\n matches.push(bufferKey);\n }\n }\n\n return matches;\n }\n\n async findBufferKeysForSession(sessionKey: string): Promise<string[]> {\n if (typeof sessionKey !== \"string\" || sessionKey.length === 0) return [];\n await this.mutationChain.catch(() => {});\n await this.load();\n return this.matchingSessionBufferKeysUnlocked(sessionKey);\n }\n\n async clearAfterExtraction(\n bufferKey = \"default\",\n extractedTurns?: readonly BufferTurn[],\n options?: { allowNonPrefix?: boolean },\n ): Promise<void> {\n await this.enqueueMutation(async () => {\n // Drop any armed debounce TIMER so it cannot fire mid-mutation and race\n // our post-clear write, but KEEP the pending-save state (issue #1909\n // review round 13): the post-clear save below can fail, and clearing the\n // pending flag here would strand buffered turns — including turns from\n // OTHER sessions that only ever entered the debounced pending state — with\n // nothing left to retry them. saveNowRetainingPendingOnFailure clears the\n // pending state only after a durable write, or re-arms it on failure.\n if (this.saveTimer) {\n clearTimeout(this.saveTimer);\n this.saveTimer = null;\n }\n await this.loadUnlocked();\n const entry = this.entryFor(bufferKey);\n if (Array.isArray(extractedTurns)) {\n const liveExtractedTurns = liveTurnsFromExtractionSnapshot(\n entry,\n extractedTurns,\n );\n let clearedLiveTurns = false;\n if (liveExtractedTurns.length > 0) {\n if (options?.allowNonPrefix === true) {\n const remainingTurns = [...entry.turns];\n for (const extractedTurn of liveExtractedTurns) {\n const matchingIndex = remainingTurns.findIndex((liveTurn) =>\n bufferTurnsEqual(liveTurn, extractedTurn),\n );\n if (matchingIndex >= 0) {\n remainingTurns.splice(matchingIndex, 1);\n clearedLiveTurns = true;\n }\n }\n if (clearedLiveTurns) entry.turns = remainingTurns;\n } else {\n const matchedCount = matchingQueuedExtractionPrefixLength(\n entry.turns,\n liveExtractedTurns,\n );\n if (matchedCount > 0) {\n entry.turns = entry.turns.slice(matchedCount);\n clearedLiveTurns = true;\n }\n }\n if (!clearedLiveTurns) {\n log.debug(\n `buffer[${bufferKey}]: extraction clear skipped because live turns changed before clear`,\n );\n }\n }\n if (!clearedLiveTurns) {\n await this.saveNowRetainingPendingOnFailure(\"clearAfterExtraction\");\n return;\n }\n } else {\n entry.turns = [];\n }\n entry.lastExtractionAt = new Date().toISOString();\n entry.extractionCount += 1;\n if (bufferKey === \"default\") {\n this.state.turns = entry.turns;\n this.state.lastExtractionAt = entry.lastExtractionAt;\n this.state.extractionCount = entry.extractionCount;\n }\n this.persistence.markDirty(bufferKey);\n this.pruneEntries([bufferKey]);\n await this.saveNowRetainingPendingOnFailure(\"clearAfterExtraction\");\n });\n }\n\n /**\n * Remove an extraction-window chunk from the buffer WITHOUT recording an\n * extraction (trigger-drain drop path). Used when a chunk fails extraction\n * repeatedly and must be dropped so the session can drain; the caller is\n * responsible for the side-file copy and logging. Returns the number of\n * live turns dropped; 0 when the turns no longer match. `allowNonPrefix`\n * matches by identity, like `clearAfterExtraction`, for callers (native\n * groups) whose chunk can sit behind a pinned capture.\n */\n async dropExtractionChunk(\n bufferKey = \"default\",\n turns: readonly BufferTurn[],\n options?: { allowNonPrefix?: boolean },\n ): Promise<number> {\n return await this.enqueueMutation(async () => {\n await this.loadUnlocked();\n const entry = this.entryFor(bufferKey);\n // A window's head can be deferred-retained turns (retainDeferredTurns): take those out of the chunk first.\n const retained = [...(entry.retainedTurns ?? [])];\n const liveTurns: BufferTurn[] = [];\n for (const turn of turns) {\n const at = retained.findIndex((kept) => bufferTurnsEqual(kept, turn));\n if (at >= 0) retained.splice(at, 1);\n else liveTurns.push(turn);\n }\n const retainedDropped = (entry.retainedTurns?.length ?? 0) - retained.length;\n let remaining = entry.turns;\n if (options?.allowNonPrefix === true) {\n remaining = [...entry.turns];\n for (const turn of liveTurns) {\n const at = remaining.findIndex((live) => bufferTurnsEqual(live, turn));\n if (at >= 0) remaining.splice(at, 1);\n }\n } else {\n remaining = entry.turns.slice(matchingQueuedExtractionPrefixLength(entry.turns, liveTurns));\n }\n const matchedCount = entry.turns.length - remaining.length + retainedDropped;\n if (matchedCount === 0) return 0;\n if (this.saveTimer) {\n clearTimeout(this.saveTimer);\n this.saveTimer = null;\n }\n entry.turns = remaining;\n if (retainedDropped > 0) {\n if (retained.length > 0) entry.retainedTurns = retained;\n else delete entry.retainedTurns;\n }\n if (bufferKey === \"default\") {\n this.state.turns = entry.turns;\n }\n this.persistence.markDirty(bufferKey);\n this.pruneEntries([bufferKey]);\n await this.saveNowRetainingPendingOnFailure(\"dropExtractionChunk\");\n return matchedCount;\n });\n }\n\n getExtractionCount(bufferKey = \"default\"): number {\n return this.peekEntry(bufferKey)?.extractionCount ?? 0;\n }\n\n /**\n * Await any pending `BUFFER_SURPRISE` telemetry writes.\n *\n * The telemetry path is fire-and-forget from the hot path's point of\n * view, but tests and before-exit hooks sometimes need to make sure\n * the ledger has been flushed before they assert on its contents or\n * close the process. This method resolves once the current chain\n * head has settled; new writes scheduled after this call return a\n * separate, later settlement.\n *\n * Never throws — the chain already catches its own rejections.\n */\n async flushSurpriseTelemetry(): Promise<void> {\n await this.surpriseTelemetryWriteChain;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmDA,IAAM,yBAAyB;AAC/B,IAAM,iBAAiB,CAAC,MACtB,EAAE,oBAAoB,QAAQ,EAAE,2BAA2B;AAU7D,IAAM,mCAAmC;AASzC,IAAM,qBAAqB;AAWpB,IAAM,cAAN,MAAkB;AAAA,EAuCvB,YACmB,QACA,SACjB,gBAA4C,MAC5C;AAHiB;AACA;AAGjB,SAAK,QAAQ,EAAE,OAAO,CAAC,GAAG,kBAAkB,MAAM,iBAAiB,EAAE;AACrE,SAAK,gBAAgB;AAAA,EACvB;AAAA,EANmB;AAAA,EACA;AAAA,EAxCX;AAAA,EACA,SAAS;AAAA,EACT,cAAoC;AAAA,EAC3B;AAAA,EACT,gBAAkC,QAAQ,QAAQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAelD,8BAAgD,QAAQ,QAAQ;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAShE,YAAmC;AAAA,EACnC,cAAc;AAAA;AAAA;AAAA;AAAA,EAId,mBAAkC;AAAA;AAAA,EAGzB,cAAc,IAAI,yBAAyB;AAAA,EAWpD,gBAAmB,IAAkC;AAC3D,UAAM,MAAM,KAAK,cAAc,MAAM,MAAM;AAAA,IAAC,CAAC,EAAE,KAAK,EAAE;AACt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U,CAAC,SAAS,iBAAiB,MAAM,IAAI,CAAC;AACrE,cAAI,MAAM,EAAG,WAAU,OAAO,IAAI,CAAC;AAAA,QACrC;AAAA,MACF,OAAO;AACL,oBAAY,MAAM,MAAM,MAAM,qCAAqC,MAAM,OAAO,SAAS,CAAC;AAAA,MAC5F;AACA,YAAM,eAAe,MAAM,MAAM,SAAS,UAAU,SAAS;AAC7D,UAAI,iBAAiB,EAAG,QAAO;AAC/B,UAAI,KAAK,WAAW;AAClB,qBAAa,KAAK,SAAS;AAC3B,aAAK,YAAY;AAAA,MACnB;AACA,YAAM,QAAQ;AACd,UAAI,kBAAkB,GAAG;AACvB,YAAI,SAAS,SAAS,EAAG,OAAM,gBAAgB;AAAA,YAC1C,QAAO,MAAM;AAAA,MACpB;AACA,UAAI,cAAc,WAAW;AAC3B,aAAK,MAAM,QAAQ,MAAM;AAAA,MAC3B;AACA,WAAK,YAAY,UAAU,SAAS;AACpC,WAAK,aAAa,CAAC,SAAS,CAAC;AAC7B,YAAM,KAAK,iCAAiC,qBAAqB;AACjE,aAAO;AAAA,IACT,CAAC;AAAA,EACH;AAAA,EAEA,mBAAmB,YAAY,WAAmB;AAChD,WAAO,KAAK,UAAU,SAAS,GAAG,mBAAmB;AAAA,EACvD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAcA,MAAM,yBAAwC;AAC5C,UAAM,KAAK;AAAA,EACb;AACF;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
StorageManager
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-N7RAABFM.js";
|
|
4
4
|
import {
|
|
5
5
|
getCachedRuleMemories,
|
|
6
6
|
setCachedRuleMemories
|
|
@@ -119,4 +119,4 @@ export {
|
|
|
119
119
|
compareVerifiedSemanticRuleResults,
|
|
120
120
|
searchVerifiedSemanticRules
|
|
121
121
|
};
|
|
122
|
-
//# sourceMappingURL=chunk-
|
|
122
|
+
//# sourceMappingURL=chunk-L2HSSVVD.js.map
|
|
@@ -1,9 +1,3 @@
|
|
|
1
|
-
import {
|
|
2
|
-
LanceDbBackend
|
|
3
|
-
} from "./chunk-DOJBV6WR.js";
|
|
4
|
-
import {
|
|
5
|
-
MeilisearchBackend
|
|
6
|
-
} from "./chunk-PFUXPTBT.js";
|
|
7
1
|
import {
|
|
8
2
|
NoopSearchBackend
|
|
9
3
|
} from "./chunk-CYEPCZN5.js";
|
|
@@ -16,6 +10,12 @@ import {
|
|
|
16
10
|
import {
|
|
17
11
|
EmbedHelper
|
|
18
12
|
} from "./chunk-EXYT52NR.js";
|
|
13
|
+
import {
|
|
14
|
+
LanceDbBackend
|
|
15
|
+
} from "./chunk-DOJBV6WR.js";
|
|
16
|
+
import {
|
|
17
|
+
MeilisearchBackend
|
|
18
|
+
} from "./chunk-PFUXPTBT.js";
|
|
19
19
|
import {
|
|
20
20
|
createConversationIndexBackend
|
|
21
21
|
} from "./chunk-TFA6HPOA.js";
|
|
@@ -24,7 +24,7 @@ import {
|
|
|
24
24
|
} from "./chunk-F4TWWUMP.js";
|
|
25
25
|
import {
|
|
26
26
|
QmdClient
|
|
27
|
-
} from "./chunk-
|
|
27
|
+
} from "./chunk-ELHJK7LM.js";
|
|
28
28
|
import {
|
|
29
29
|
resolveIndexingCapabilities,
|
|
30
30
|
resolvePipelineProcessingCapabilities,
|
|
@@ -179,4 +179,4 @@ export {
|
|
|
179
179
|
createConversationSearchBackend,
|
|
180
180
|
createConversationIndexRuntime
|
|
181
181
|
};
|
|
182
|
-
//# sourceMappingURL=chunk-
|
|
182
|
+
//# sourceMappingURL=chunk-L334PSLW.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
isValidCapsuleSince
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-BUKK5SWA.js";
|
|
4
4
|
import {
|
|
5
5
|
CAPSULE_ID_PATTERN
|
|
6
6
|
} from "./chunk-WEHSQBFR.js";
|
|
@@ -12,7 +12,7 @@ import {
|
|
|
12
12
|
import {
|
|
13
13
|
OFFLINE_SYNC_FILE_CONTENT_MAX_CHUNK_BYTES,
|
|
14
14
|
OFFLINE_SYNC_MAX_MTIME_MS
|
|
15
|
-
} from "./chunk-
|
|
15
|
+
} from "./chunk-YH7HJNWV.js";
|
|
16
16
|
import {
|
|
17
17
|
validateArchiveRelativePath
|
|
18
18
|
} from "./chunk-GCGJW34D.js";
|
|
@@ -560,4 +560,4 @@ export {
|
|
|
560
560
|
actionConfidenceRequestSchema,
|
|
561
561
|
validateRequest
|
|
562
562
|
};
|
|
563
|
-
//# sourceMappingURL=chunk-
|
|
563
|
+
//# sourceMappingURL=chunk-LIUI46BX.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
readAllEdges
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-QKXPOLQD.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-MKE5DP3S.js.map
|
|
@@ -34,8 +34,10 @@ var BufferSessionPersistence = class {
|
|
|
34
34
|
await storage.saveBuffer(state);
|
|
35
35
|
this.dirty.clear();
|
|
36
36
|
this.deleted.clear();
|
|
37
|
-
return;
|
|
37
|
+
return { handedOver: [], drainedTurns: /* @__PURE__ */ new Map() };
|
|
38
38
|
}
|
|
39
|
+
const handedOver = [];
|
|
40
|
+
const drainedTurns = /* @__PURE__ */ new Map();
|
|
39
41
|
for (const key of [...this.deleted]) {
|
|
40
42
|
await deleteSession(key);
|
|
41
43
|
this.deleted.delete(key);
|
|
@@ -46,13 +48,16 @@ var BufferSessionPersistence = class {
|
|
|
46
48
|
this.markDeleted(key);
|
|
47
49
|
continue;
|
|
48
50
|
}
|
|
49
|
-
await saveSession(key, entry);
|
|
51
|
+
const outcome = await saveSession(key, entry);
|
|
50
52
|
this.dirty.delete(key);
|
|
53
|
+
if (outcome?.status === "handed_over") handedOver.push(key);
|
|
54
|
+
if (outcome?.drainedTurns && outcome.drainedTurns.length > 0) drainedTurns.set(key, outcome.drainedTurns);
|
|
51
55
|
}
|
|
56
|
+
return { handedOver, drainedTurns };
|
|
52
57
|
}
|
|
53
58
|
};
|
|
54
59
|
|
|
55
60
|
export {
|
|
56
61
|
BufferSessionPersistence
|
|
57
62
|
};
|
|
58
|
-
//# sourceMappingURL=chunk-
|
|
63
|
+
//# sourceMappingURL=chunk-MPDLLLOG.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/buffer-persistence.ts"],"sourcesContent":["import type { BufferEntryState, BufferState, BufferSurpriseEvent, BufferTurn } from \"./types.js\";\nimport type { BufferSessionSaveOutcome } from \"./storage/buffer-drain-claims.js\";\n\n/**\n * The buffer persistence surface SmartBuffer depends on.\n *\n * `saveBufferSession` / `deleteBufferSession` are the per-session incremental\n * writes (one file per session); when a storage backend does not provide\n * them, the buffer falls back to the whole-state `saveBuffer`. Both are\n * optional in the type so a storage double only has to implement what it\n * actually supports.\n */\nexport interface BufferStorage {\n loadBuffer(): Promise<BufferState>;\n saveBuffer(state: BufferState): Promise<void>;\n /** Reports \"handed_over\" when the session is claimed by `remnic buffer drain` and the entry moved into the claim instead of a session file. Legacy doubles may return void (treated as \"saved\"). */\n saveBufferSession?(key: string, entry: BufferEntryState): Promise<BufferSessionSaveOutcome | void>;\n deleteBufferSession?(key: string): Promise<void>;\n /** Sync claim check for the extraction gate; omitted when the backend has no drain-claim store. */\n isBufferSessionClaimed?(key: string): boolean;\n /** Optional surprise-telemetry sink; older storage and test doubles omit it. */\n appendBufferSurpriseEvents?(events: BufferSurpriseEvent[]): Promise<number>;\n}\n\n/** What one persist pass changed beyond plain writes. */\nexport interface BufferPersistOutcome {\n /** Sessions whose in-memory entry moved into a drain claim: the caller must evict them (a claimed session no longer lives in this process). */\n handedOver: string[];\n /** Per session, the turns a drain already extracted: the caller subtracts them from its in-memory copy. */\n drainedTurns: Map<string, BufferTurn[]>;\n}\n\n/**\n * Tracks which sessions' persisted files are stale and writes only those.\n *\n * Marks are cleared only after a durable write of that session. All calls\n * happen under SmartBuffer's serialized mutation chain: one writer.\n */\nexport class BufferSessionPersistence {\n private readonly dirty = new Set<string>();\n private readonly deleted = new Set<string>();\n\n markDirty(key: string): void {\n this.dirty.add(key);\n this.deleted.delete(key);\n }\n\n markDeleted(key: string): void {\n this.deleted.add(key);\n this.dirty.delete(key);\n }\n\n /** Eviction removed `key` from memory: its session file must go, any pending write is moot. */\n markEvicted(keys: readonly string[]): void {\n for (const key of keys) this.markDeleted(key);\n }\n\n hasPending(): boolean {\n return this.dirty.size > 0 || this.deleted.size > 0;\n }\n\n /**\n * Persist buffer state. On session-capable storage this writes ONLY the\n * sessions whose state changed since the last successful persist and\n * deletes files for evicted/reset sessions, so the observe path never\n * re-serializes other sessions' turns. On legacy storage it falls back to\n * the whole-state saveBuffer. Files are deleted before dirty writes: a\n * crash mid-persist can then only resurrect already-evicted data (the same\n * exposure as a whole-file rewrite), never drop sessions the state says\n * exist.\n */\n async persist(\n storage: BufferStorage,\n state: BufferState,\n peekEntry: (key: string) => BufferEntryState | undefined,\n ): Promise<BufferPersistOutcome> {\n const saveSession = storage.saveBufferSession?.bind(storage);\n const deleteSession = storage.deleteBufferSession?.bind(storage);\n if (!saveSession || !deleteSession) {\n await storage.saveBuffer(state);\n this.dirty.clear();\n this.deleted.clear();\n return { handedOver: [], drainedTurns: new Map() };\n }\n const handedOver: string[] = [];\n const drainedTurns = new Map<string, BufferTurn[]>();\n for (const key of [...this.deleted]) {\n await deleteSession(key);\n this.deleted.delete(key);\n }\n for (const key of [...this.dirty]) {\n const entry = peekEntry(key);\n if (!entry) {\n // A dirty key without state must not be written from a fabricated\n // empty entry: treat it as a deletion instead.\n this.markDeleted(key);\n continue;\n }\n const outcome = await saveSession(key, entry);\n this.dirty.delete(key);\n // \"handed_over\": the entry moved into a drain claim. Content is durable\n // in the claim, so this key's pending state is settled — the caller\n // evicts the in-memory entry on its side.\n if (outcome?.status === \"handed_over\") handedOver.push(key);\n // A drain tombstone: the turns it extracted must leave this process's\n // copy too, or the owner would extract them a second time.\n if (outcome?.drainedTurns && outcome.drainedTurns.length > 0) drainedTurns.set(key, outcome.drainedTurns);\n }\n return { handedOver, drainedTurns };\n }\n}\n"],"mappings":";AAsCO,IAAM,2BAAN,MAA+B;AAAA,EACnB,QAAQ,oBAAI,IAAY;AAAA,EACxB,UAAU,oBAAI,IAAY;AAAA,EAE3C,UAAU,KAAmB;AAC3B,SAAK,MAAM,IAAI,GAAG;AAClB,SAAK,QAAQ,OAAO,GAAG;AAAA,EACzB;AAAA,EAEA,YAAY,KAAmB;AAC7B,SAAK,QAAQ,IAAI,GAAG;AACpB,SAAK,MAAM,OAAO,GAAG;AAAA,EACvB;AAAA;AAAA,EAGA,YAAY,MAA+B;AACzC,eAAW,OAAO,KAAM,MAAK,YAAY,GAAG;AAAA,EAC9C;AAAA,EAEA,aAAsB;AACpB,WAAO,KAAK,MAAM,OAAO,KAAK,KAAK,QAAQ,OAAO;AAAA,EACpD;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAYA,MAAM,QACJ,SACA,OACA,WAC+B;AAC/B,UAAM,cAAc,QAAQ,mBAAmB,KAAK,OAAO;AAC3D,UAAM,gBAAgB,QAAQ,qBAAqB,KAAK,OAAO;AAC/D,QAAI,CAAC,eAAe,CAAC,eAAe;AAClC,YAAM,QAAQ,WAAW,KAAK;AAC9B,WAAK,MAAM,MAAM;AACjB,WAAK,QAAQ,MAAM;AACnB,aAAO,EAAE,YAAY,CAAC,GAAG,cAAc,oBAAI,IAAI,EAAE;AAAA,IACnD;AACA,UAAM,aAAuB,CAAC;AAC9B,UAAM,eAAe,oBAAI,IAA0B;AACnD,eAAW,OAAO,CAAC,GAAG,KAAK,OAAO,GAAG;AACnC,YAAM,cAAc,GAAG;AACvB,WAAK,QAAQ,OAAO,GAAG;AAAA,IACzB;AACA,eAAW,OAAO,CAAC,GAAG,KAAK,KAAK,GAAG;AACjC,YAAM,QAAQ,UAAU,GAAG;AAC3B,UAAI,CAAC,OAAO;AAGV,aAAK,YAAY,GAAG;AACpB;AAAA,MACF;AACA,YAAM,UAAU,MAAM,YAAY,KAAK,KAAK;AAC5C,WAAK,MAAM,OAAO,GAAG;AAIrB,UAAI,SAAS,WAAW,cAAe,YAAW,KAAK,GAAG;AAG1D,UAAI,SAAS,gBAAgB,QAAQ,aAAa,SAAS,EAAG,cAAa,IAAI,KAAK,QAAQ,YAAY;AAAA,IAC1G;AACA,WAAO,EAAE,YAAY,aAAa;AAAA,EACpC;AACF;","names":[]}
|
|
@@ -5,7 +5,7 @@ import {
|
|
|
5
5
|
} from "./chunk-5JMAGU26.js";
|
|
6
6
|
import {
|
|
7
7
|
runPostConsolidationMaterialize
|
|
8
|
-
} from "./chunk-
|
|
8
|
+
} from "./chunk-GNP4BV4Z.js";
|
|
9
9
|
import {
|
|
10
10
|
isSemanticConsolidationLlmOperator
|
|
11
11
|
} from "./chunk-G7D6GZ5J.js";
|
|
@@ -220,4 +220,4 @@ export {
|
|
|
220
220
|
buildExtensionsBlockForConsolidation,
|
|
221
221
|
materializeAfterSemanticConsolidation
|
|
222
222
|
};
|
|
223
|
-
//# sourceMappingURL=chunk-
|
|
223
|
+
//# sourceMappingURL=chunk-MPJ7VHHA.js.map
|