@tangle-network/agent-eval 0.221.7 → 0.222.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +146 -0
- package/dist/adapters/http.d.ts +3 -5
- package/dist/adapters/http.d.ts.map +1 -1
- package/dist/adapters/http.js +1 -2
- package/dist/{adversarial-smnADNFS.d.ts → adversarial-DnQQFqTR.d.ts} +1 -3
- package/dist/adversarial-DnQQFqTR.d.ts.map +1 -0
- package/dist/{agent-profile-CNmwfaqq.d.ts → agent-profile-CoD1Dotf.d.ts} +4 -10
- package/dist/agent-profile-CoD1Dotf.d.ts.map +1 -0
- package/dist/agent-profile-Dngk3LZ0.js +153 -0
- package/dist/agent-profile-Dngk3LZ0.js.map +1 -0
- package/dist/{agent-profile-cell-BcpFbNd5.d.ts → agent-profile-cell-3kYxUsK2.d.ts} +3 -5
- package/dist/agent-profile-cell-3kYxUsK2.d.ts.map +1 -0
- package/dist/{agent-profile-cell-B1V1gUZs.js → agent-profile-cell-CT5JYueM.js} +5 -7
- package/dist/{agent-profile-cell-B1V1gUZs.js.map → agent-profile-cell-CT5JYueM.js.map} +1 -1
- package/dist/{agreement-irr-BhAqjluA.js → agreement-irr-BTjDN0i6.js} +4 -5
- package/dist/{agreement-irr-BhAqjluA.js.map → agreement-irr-BTjDN0i6.js.map} +1 -1
- package/dist/analyst/index.d.ts +95 -159
- package/dist/analyst/index.d.ts.map +1 -1
- package/dist/analyst/index.js +28 -39
- package/dist/analyst/index.js.map +1 -1
- package/dist/{analyze-runs-DfX6dHP0.d.ts → analyze-runs-C-pP1sK9.d.ts} +7 -13
- package/dist/analyze-runs-C-pP1sK9.d.ts.map +1 -0
- package/dist/{analyze-runs-CHmsykNJ.js → analyze-runs-CTheASYV.js} +23 -32
- package/dist/{analyze-runs-CHmsykNJ.js.map → analyze-runs-CTheASYV.js.map} +1 -1
- package/dist/{attribute-vocabulary-CcXqHODT.d.ts → attribute-vocabulary-5oo8ykIx.d.ts} +2 -4
- package/dist/attribute-vocabulary-5oo8ykIx.d.ts.map +1 -0
- package/dist/authenticity/index.d.ts +0 -2
- package/dist/authenticity/index.d.ts.map +1 -1
- package/dist/authenticity/index.js +1 -2
- package/dist/{benchmark-command-Cnjfo0Zh.js → benchmark-command-jYWR2gya.js} +61 -94
- package/dist/benchmark-command-jYWR2gya.js.map +1 -0
- package/dist/benchmarks/index.d.ts +5 -15
- package/dist/benchmarks/index.d.ts.map +1 -1
- package/dist/benchmarks/index.js +27 -38
- package/dist/benchmarks/index.js.map +1 -1
- package/dist/{bounded-process-Cj9YjXbE.js → bounded-process-BZrWXIKW.js} +2 -3
- package/dist/{bounded-process-Cj9YjXbE.js.map → bounded-process-BZrWXIKW.js.map} +1 -1
- package/dist/builder-eval/index.d.ts +5 -14
- package/dist/builder-eval/index.d.ts.map +1 -1
- package/dist/builder-eval/index.js +11 -17
- package/dist/builder-eval/index.js.map +1 -1
- package/dist/{calibration-CTwxpJ-t.js → calibration-6usfVYYo.js} +4 -5
- package/dist/{calibration-CTwxpJ-t.js.map → calibration-6usfVYYo.js.map} +1 -1
- package/dist/campaign/index.d.ts +9 -9
- package/dist/campaign/index.js +15 -14
- package/dist/{campaign-uddTlFg5.js → campaign-ddr1N3yD.js} +61 -58
- package/dist/campaign-ddr1N3yD.js.map +1 -0
- package/dist/{campaign-evidence-DunzcJGv.js → campaign-evidence-DN8rWuBj.js} +20 -322
- package/dist/campaign-evidence-DN8rWuBj.js.map +1 -0
- package/dist/{canonical-Dq2hOQ8L.js → canonical-CicJlINA.js} +3 -4
- package/dist/{canonical-Dq2hOQ8L.js.map → canonical-CicJlINA.js.map} +1 -1
- package/dist/{canonical-CFpojCN5.d.ts → canonical-gLeHiqzd.d.ts} +2 -4
- package/dist/canonical-gLeHiqzd.d.ts.map +1 -0
- package/dist/{cell-spend-DEWR3nj-.js → cell-spend-zxmzg4GH.js} +3 -4
- package/dist/{cell-spend-DEWR3nj-.js.map → cell-spend-zxmzg4GH.js.map} +1 -1
- package/dist/{chat-client-BNATB3rJ.js → chat-client-CO3uB33i.js} +3 -4
- package/dist/{chat-client-BNATB3rJ.js.map → chat-client-CO3uB33i.js.map} +1 -1
- package/dist/{chat-json-call-BzWYp18J.js → chat-json-call-8yUv4LFO.js} +4 -5
- package/dist/{chat-json-call-BzWYp18J.js.map → chat-json-call-8yUv4LFO.js.map} +1 -1
- package/dist/{claim-BPVuyHuy.js → claim-Dod_mjk3.js} +5 -6
- package/dist/{claim-BPVuyHuy.js.map → claim-Dod_mjk3.js.map} +1 -1
- package/dist/cli.js +179 -23
- package/dist/cli.js.map +1 -1
- package/dist/{client-hwo3cJjR.d.ts → client-BIFwUg7I.d.ts} +6 -12
- package/dist/client-BIFwUg7I.d.ts.map +1 -0
- package/dist/{cluster-bootstrap-DEwwhl0C.js → cluster-bootstrap-SbaeM44s.js} +4 -5
- package/dist/{cluster-bootstrap-DEwwhl0C.js.map → cluster-bootstrap-SbaeM44s.js.map} +1 -1
- package/dist/completion-verifier-7KEfroqx.d.ts +168 -0
- package/dist/completion-verifier-7KEfroqx.d.ts.map +1 -0
- package/dist/{completion-verifier-asaV1nSj.js → completion-verifier-rqbMh5-4.js} +9 -160
- package/dist/completion-verifier-rqbMh5-4.js.map +1 -0
- package/dist/contract/index.d.ts +13 -13
- package/dist/contract/index.js +41 -60
- package/dist/contract/index.js.map +1 -1
- package/dist/{cost-ledger-BGZB6yY2.js → cost-ledger-CS8R3IZj.js} +10 -17
- package/dist/{cost-ledger-BGZB6yY2.js.map → cost-ledger-CS8R3IZj.js.map} +1 -1
- package/dist/{cost-ledger-C1W3ICmP.d.ts → cost-ledger-Czro9wmo.d.ts} +1 -5
- package/dist/cost-ledger-Czro9wmo.d.ts.map +1 -0
- package/dist/{dataset-DQqhOCPt.d.ts → dataset-DThC1S6G.d.ts} +1 -3
- package/dist/dataset-DThC1S6G.d.ts.map +1 -0
- package/dist/{decision-point-0nJubuoM.js → decision-point-lhMgODOR.js} +14 -18
- package/dist/{decision-point-0nJubuoM.js.map → decision-point-lhMgODOR.js.map} +1 -1
- package/dist/{deep-freeze-CurcOQg3.js → deep-freeze-CK8-2W7p.js} +2 -3
- package/dist/{deep-freeze-CurcOQg3.js.map → deep-freeze-CK8-2W7p.js.map} +1 -1
- package/dist/{default-registry-CLG5YqGS.d.ts → default-registry-B1DstPYg.d.ts} +53 -61
- package/dist/default-registry-B1DstPYg.d.ts.map +1 -0
- package/dist/{default-registry-BBTDgkDM.js → default-registry-C1tPEjZ4.js} +29 -45
- package/dist/{default-registry-BBTDgkDM.js.map → default-registry-C1tPEjZ4.js.map} +1 -1
- package/dist/{define-agent-eval-CCbT7Kfr.js → define-agent-eval-BLoP4Lf9.js} +15 -18
- package/dist/{define-agent-eval-CCbT7Kfr.js.map → define-agent-eval-BLoP4Lf9.js.map} +1 -1
- package/dist/{define-agent-eval-JKt3gMQr.d.ts → define-agent-eval-CAffiFbN.d.ts} +19 -27
- package/dist/define-agent-eval-CAffiFbN.d.ts.map +1 -0
- package/dist/{descriptive-CVNy48rR.js → descriptive-cPwITVfy.js} +30 -8
- package/dist/descriptive-cPwITVfy.js.map +1 -0
- package/dist/diagnosis/index.d.ts +5 -15
- package/dist/diagnosis/index.d.ts.map +1 -1
- package/dist/diagnosis/index.js +13 -19
- package/dist/diagnosis/index.js.map +1 -1
- package/dist/{dspy-rlm-engine-DN1p_5jx.js → dspy-rlm-engine-jDiWkul6.js} +7 -10
- package/dist/{dspy-rlm-engine-DN1p_5jx.js.map → dspy-rlm-engine-jDiWkul6.js.map} +1 -1
- package/dist/{emitter-DbMXUIVP.js → emitter-DhQ65mza.js} +3 -4
- package/dist/{emitter-DbMXUIVP.js.map → emitter-DhQ65mza.js.map} +1 -1
- package/dist/{emitter-DABYYTcH.d.ts → emitter-mAXC5PSN.d.ts} +3 -5
- package/dist/emitter-mAXC5PSN.d.ts.map +1 -0
- package/dist/{engine-dtRVeuQs.d.ts → engine-CaHaCc3W.d.ts} +10 -18
- package/dist/engine-CaHaCc3W.d.ts.map +1 -0
- package/dist/{equal-terms-DbPGcVtI.js → equal-terms-K11VHmR3.js} +3 -4
- package/dist/{equal-terms-DbPGcVtI.js.map → equal-terms-K11VHmR3.js.map} +1 -1
- package/dist/{errors-BcOs5MKW.js → errors-DeEEV9Vx.js} +2 -3
- package/dist/{errors-BcOs5MKW.js.map → errors-DeEEV9Vx.js.map} +1 -1
- package/dist/{errors-DEE6u6ot.d.ts → errors-E9I2hldP.d.ts} +1 -3
- package/dist/errors-E9I2hldP.d.ts.map +1 -0
- package/dist/{eval-campaign-DoX5vz3E.js → eval-campaign-Cgixrvf7.js} +8 -9
- package/dist/{eval-campaign-DoX5vz3E.js.map → eval-campaign-Cgixrvf7.js.map} +1 -1
- package/dist/{evaluation-wdGyZ7jV.js → evaluation-B8H3GYej.js} +4 -6
- package/dist/{evaluation-wdGyZ7jV.js.map → evaluation-B8H3GYej.js.map} +1 -1
- package/dist/{evaluation-DblGquCB.d.ts → evaluation-BPqUvZ66.d.ts} +4 -6
- package/dist/evaluation-BPqUvZ66.d.ts.map +1 -0
- package/dist/evaluation.d.ts +1 -1
- package/dist/evaluation.js +1 -2
- package/dist/{exact-types-Do63KoKn.d.ts → exact-types-D98BKpxo.d.ts} +8 -10
- package/dist/exact-types-D98BKpxo.d.ts.map +1 -0
- package/dist/{exec-CpbtOXVt.js → exec-C0_AkLUv.js} +3 -5
- package/dist/{exec-CpbtOXVt.js.map → exec-C0_AkLUv.js.map} +1 -1
- package/dist/{execution-tracks-CpgFPpS5.js → execution-tracks-DaDXYwAq.js} +2 -3
- package/dist/{execution-tracks-CpgFPpS5.js.map → execution-tracks-DaDXYwAq.js.map} +1 -1
- package/dist/experiment/index.d.ts +9 -37
- package/dist/experiment/index.d.ts.map +1 -1
- package/dist/experiment/index.js +29 -40
- package/dist/experiment/index.js.map +1 -1
- package/dist/{exporters-Dk3oEbK_.d.ts → exporters-B5Ze_RKh.d.ts} +4 -4
- package/dist/exporters-B5Ze_RKh.d.ts.map +1 -0
- package/dist/{exporters-DWvM16LE.js → exporters-ByLcILYU.js} +23 -5
- package/dist/exporters-ByLcILYU.js.map +1 -0
- package/dist/{external-optimizer-process-DEzJ2CGX.js → external-optimizer-process-BRVmaDFe.js} +5 -6
- package/dist/{external-optimizer-process-DEzJ2CGX.js.map → external-optimizer-process-BRVmaDFe.js.map} +1 -1
- package/dist/{external-optimizer-subprocess-B_ukPtRD.js → external-optimizer-subprocess-U616hV_l.js} +24 -37
- package/dist/{external-optimizer-subprocess-B_ukPtRD.js.map → external-optimizer-subprocess-U616hV_l.js.map} +1 -1
- package/dist/{extract-usage-BZLU01kR.js → extract-usage-ISFqhfDz.js} +2 -3
- package/dist/{extract-usage-BZLU01kR.js.map → extract-usage-ISFqhfDz.js.map} +1 -1
- package/dist/{failure-cluster-DN0t63Z0.d.ts → failure-cluster-DOoa7CBg.d.ts} +3 -7
- package/dist/failure-cluster-DOoa7CBg.d.ts.map +1 -0
- package/dist/{failure-taxonomy-Bx5oWqaW.js → failure-taxonomy-9eQfXKoW.js} +2 -3
- package/dist/{failure-taxonomy-Bx5oWqaW.js.map → failure-taxonomy-9eQfXKoW.js.map} +1 -1
- package/dist/{feedback-trajectory-CYVJXolG.d.ts → feedback-trajectory-SBGncrCP.d.ts} +7 -13
- package/dist/feedback-trajectory-SBGncrCP.d.ts.map +1 -0
- package/dist/{finding-composition-8n0fFgVI.js → finding-composition-DlvE1Qul.js} +4 -6
- package/dist/{finding-composition-8n0fFgVI.js.map → finding-composition-DlvE1Qul.js.map} +1 -1
- package/dist/{findings-store-Bg4sdS-e.js → findings-store-B75Dspaq.js} +11 -14
- package/dist/{findings-store-Bg4sdS-e.js.map → findings-store-B75Dspaq.js.map} +1 -1
- package/dist/fuzz.d.ts +3 -17
- package/dist/fuzz.d.ts.map +1 -1
- package/dist/fuzz.js +30 -29
- package/dist/fuzz.js.map +1 -1
- package/dist/{hf-dataset-CKxIJQba.js → hf-dataset-DPVQXW5n.js} +362 -21
- package/dist/hf-dataset-DPVQXW5n.js.map +1 -0
- package/dist/hosted/index.d.ts +2 -6
- package/dist/hosted/index.d.ts.map +1 -1
- package/dist/hosted/index.js +1 -2
- package/dist/{index-CalAsXMR.d.ts → index-B1Bm9oJA.d.ts} +3 -15
- package/dist/index-B1Bm9oJA.d.ts.map +1 -0
- package/dist/{index-CdEVr8-O.d.ts → index-B7v2QHlD.d.ts} +24 -299
- package/dist/index-B7v2QHlD.d.ts.map +1 -0
- package/dist/{index-CTIRz-AB.d.ts → index-CUjeTDPv.d.ts} +14 -36
- package/dist/index-CUjeTDPv.d.ts.map +1 -0
- package/dist/{index-CfJULcW5.d.ts → index-DAk2quYu.d.ts} +18 -38
- package/dist/index-DAk2quYu.d.ts.map +1 -0
- package/dist/{index-D7fmC-1K.d.ts → index-DUn0GNiZ.d.ts} +183 -36
- package/dist/index-DUn0GNiZ.d.ts.map +1 -0
- package/dist/{index-CHxwfW5g.d.ts → index-DwUGehqX.d.ts} +3 -9
- package/dist/index-DwUGehqX.d.ts.map +1 -0
- package/dist/{index-jnuFLxOs.d.ts → index-aDPVYBIM.d.ts} +11 -39
- package/dist/index-aDPVYBIM.d.ts.map +1 -0
- package/dist/index.d.ts +55 -188
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +122 -195
- package/dist/index.js.map +1 -1
- package/dist/{integrity-D-s2iHiT.js → integrity-B1V6klyO.js} +12 -363
- package/dist/integrity-B1V6klyO.js.map +1 -0
- package/dist/{integrity-D9lBnv_K.d.ts → integrity-BAdVzT8u.d.ts} +4 -6
- package/dist/integrity-BAdVzT8u.d.ts.map +1 -0
- package/dist/{integrity-W4CADcFc.js → integrity-DOHt1mwU.js} +3 -4
- package/dist/{integrity-W4CADcFc.js.map → integrity-DOHt1mwU.js.map} +1 -1
- package/dist/{internal-BTK91Bqt.js → internal-v6XfOeJW.js} +6 -8
- package/dist/{internal-BTK91Bqt.js.map → internal-v6XfOeJW.js.map} +1 -1
- package/dist/{interval-Dq9gt7jx.js → interval-Bd2f4CRT.js} +6 -8
- package/dist/{interval-Dq9gt7jx.js.map → interval-Bd2f4CRT.js.map} +1 -1
- package/dist/{interval-ohuOJurX.d.ts → interval-CWyxqDpE.d.ts} +1 -5
- package/dist/interval-CWyxqDpE.d.ts.map +1 -0
- package/dist/{journal-C7om8Gum.js → journal-C1uLJi0w.js} +115 -121
- package/dist/{journal-C7om8Gum.js.map → journal-C1uLJi0w.js.map} +1 -1
- package/dist/{json-BhdsJaOQ.js → json-DtvZNAU9.js} +4 -6
- package/dist/{json-BhdsJaOQ.js.map → json-DtvZNAU9.js.map} +1 -1
- package/dist/json-recovery-DK4MDm5r.js +296 -0
- package/dist/json-recovery-DK4MDm5r.js.map +1 -0
- package/dist/{judge-calibration-BkXMIWA4.js → judge-calibration-DGqlfWW8.js} +5 -6
- package/dist/{judge-calibration-BkXMIWA4.js.map → judge-calibration-DGqlfWW8.js.map} +1 -1
- package/dist/{judge-calibration-DFtEMlde.d.ts → judge-calibration-DnrbQaXI.d.ts} +1 -3
- package/dist/judge-calibration-DnrbQaXI.d.ts.map +1 -0
- package/dist/{judge-gate-BVvmP00P.js → judge-gate-C2BCOt-M.js} +8 -12
- package/dist/{judge-gate-BVvmP00P.js.map → judge-gate-C2BCOt-M.js.map} +1 -1
- package/dist/judges-BLxg5p8E.js +20 -0
- package/dist/judges-BLxg5p8E.js.map +1 -0
- package/dist/{kind-factory-Dl0PmNQL.js → kind-factory-VKysp1ds.js} +23 -39
- package/dist/{kind-factory-Dl0PmNQL.js.map → kind-factory-VKysp1ds.js.map} +1 -1
- package/dist/ledger-core/index.d.ts +2 -2
- package/dist/ledger-core/index.js +3 -3
- package/dist/ledger-core/lock-holder.d.ts +1 -1
- package/dist/ledger-core/lock-holder.js +1 -2
- package/dist/{ledger-core-CAxUdDk0.js → ledger-core-CfT-FzPf.js} +5 -6
- package/dist/{ledger-core-CAxUdDk0.js.map → ledger-core-CfT-FzPf.js.map} +1 -1
- package/dist/{llm-client-b1ysZVIU.js → llm-client-kJ9EOqjt.js} +22 -30
- package/dist/{llm-client-b1ysZVIU.js.map → llm-client-kJ9EOqjt.js.map} +1 -1
- package/dist/{llm-judge-Cybq29bL.js → llm-judge-cgbhTKQp.js} +108 -164
- package/dist/llm-judge-cgbhTKQp.js.map +1 -0
- package/dist/{lock-holder-DaJbfpci.d.ts → lock-holder-DoxlZFkQ.d.ts} +1 -3
- package/dist/lock-holder-DoxlZFkQ.d.ts.map +1 -0
- package/dist/matrix/index.d.ts +3 -3
- package/dist/matrix/index.js +2 -2
- package/dist/{matrix-DtkZLD_3.d.ts → matrix-CBUzIZs4.d.ts} +4 -12
- package/dist/matrix-CBUzIZs4.d.ts.map +1 -0
- package/dist/{matrix-B8l-Nsxd.js → matrix-CgpX8wdm.js} +8 -13
- package/dist/matrix-CgpX8wdm.js.map +1 -0
- package/dist/{mean-BbA_JCzW.js → mean-CdDYG-us.js} +6 -9
- package/dist/{mean-BbA_JCzW.js.map → mean-CdDYG-us.js.map} +1 -1
- package/dist/meta-eval/index.d.ts +3 -3
- package/dist/meta-eval/index.js +17 -21
- package/dist/meta-eval/index.js.map +1 -1
- package/dist/{metrics-BKaPBtIG.js → metrics-DNCAUtuB.js} +2 -3
- package/dist/{metrics-BKaPBtIG.js.map → metrics-DNCAUtuB.js.map} +1 -1
- package/dist/{mint-CbdwjTPW.js → mint-D9ZysYtY.js} +7 -8
- package/dist/{mint-CbdwjTPW.js.map → mint-D9ZysYtY.js.map} +1 -1
- package/dist/{multi-layer-verifier-DEgMUk6v.d.ts → multi-layer-verifier-lM4aVN78.d.ts} +2 -4
- package/dist/multi-layer-verifier-lM4aVN78.d.ts.map +1 -0
- package/dist/{multiplicity-Sg0U7h8j.js → multiplicity-DAd4xaDC.js} +3 -4
- package/dist/{multiplicity-Sg0U7h8j.js.map → multiplicity-DAd4xaDC.js.map} +1 -1
- package/dist/{multiplicity-DIWHvysC.d.ts → multiplicity-D_SEsc5j.d.ts} +1 -3
- package/dist/multiplicity-D_SEsc5j.d.ts.map +1 -0
- package/dist/multishot/golden/index.d.ts +1 -17
- package/dist/multishot/golden/index.d.ts.map +1 -1
- package/dist/multishot/golden/index.js +10 -17
- package/dist/multishot/golden/index.js.map +1 -1
- package/dist/multishot/index.d.ts +2 -10
- package/dist/multishot/index.d.ts.map +1 -1
- package/dist/multishot/index.js +11 -18
- package/dist/multishot/index.js.map +1 -1
- package/dist/{nonnegative-number-DvdMxg_f.js → nonnegative-number-lEYbOsuh.js} +2 -3
- package/dist/{nonnegative-number-DvdMxg_f.js.map → nonnegative-number-lEYbOsuh.js.map} +1 -1
- package/dist/openapi.json +1 -1
- package/dist/{otel-spans-CdN909k1.js → otel-spans-BsGzTWIK.js} +5 -6
- package/dist/{otel-spans-CdN909k1.js.map → otel-spans-BsGzTWIK.js.map} +1 -1
- package/dist/{otlp-attributes-D9ptWaIJ.js → otlp-attributes-Boeb7gtH.js} +2 -3
- package/dist/{otlp-attributes-D9ptWaIJ.js.map → otlp-attributes-Boeb7gtH.js.map} +1 -1
- package/dist/{outcome-observations-FLmRpgYa.js → outcome-observations-D4snOtUb.js} +4 -5
- package/dist/{outcome-observations-FLmRpgYa.js.map → outcome-observations-D4snOtUb.js.map} +1 -1
- package/dist/{outcome-store-DUcMj-3D.js → outcome-store-TarrcfHG.js} +2 -3
- package/dist/{outcome-store-DUcMj-3D.js.map → outcome-store-TarrcfHG.js.map} +1 -1
- package/dist/{package-version-D7lQHt_-.js → package-version-CJl_pY9W.js} +2 -3
- package/dist/{package-version-D7lQHt_-.js.map → package-version-CJl_pY9W.js.map} +1 -1
- package/dist/{paired-arms-B2ttLc0_.js → paired-arms-D-54hO-k.js} +10 -14
- package/dist/{paired-arms-B2ttLc0_.js.map → paired-arms-D-54hO-k.js.map} +1 -1
- package/dist/{paired-binary-B_nejA44.js → paired-binary-BR0nwHOA.js} +3 -4
- package/dist/{paired-binary-B_nejA44.js.map → paired-binary-BR0nwHOA.js.map} +1 -1
- package/dist/{paired-promotion-decision-CQMJ5xGN.d.ts → paired-promotion-decision-BDnqepZ1.d.ts} +1 -5
- package/dist/paired-promotion-decision-BDnqepZ1.d.ts.map +1 -0
- package/dist/{paired-promotion-decision-D0SHb-ZL.js → paired-promotion-decision-FGvHA4p_.js} +5 -7
- package/dist/{paired-promotion-decision-D0SHb-ZL.js.map → paired-promotion-decision-FGvHA4p_.js.map} +1 -1
- package/dist/{pareto-BiBnQXAE.js → pareto-B9udAt2i.js} +28 -50
- package/dist/pareto-B9udAt2i.js.map +1 -0
- package/dist/pipelines/index.d.ts +5 -11
- package/dist/pipelines/index.d.ts.map +1 -1
- package/dist/pipelines/index.js +6 -8
- package/dist/pipelines/index.js.map +1 -1
- package/dist/{power-and-mde-CQX-0weG.js → power-and-mde-ClI6RWw4.js} +4 -5
- package/dist/{power-and-mde-CQX-0weG.js.map → power-and-mde-ClI6RWw4.js.map} +1 -1
- package/dist/{predicate-FdKmElA_.js → predicate-BYHA4MBn.js} +2 -3
- package/dist/{predicate-FdKmElA_.js.map → predicate-BYHA4MBn.js.map} +1 -1
- package/dist/{prime-bridge-transport-6feEglLf.d.ts → prime-bridge-transport-Cfqir_Im.d.ts} +1 -3
- package/dist/prime-bridge-transport-Cfqir_Im.d.ts.map +1 -0
- package/dist/{prime-bridge-transport-Z3cpKGoV.js → prime-bridge-transport-Csd5SQg7.js} +2 -3
- package/dist/{prime-bridge-transport-Z3cpKGoV.js.map → prime-bridge-transport-Csd5SQg7.js.map} +1 -1
- package/dist/{prime-protocol-BGxjfhM4.d.ts → prime-protocol-COFkxas6.d.ts} +4 -8
- package/dist/prime-protocol-COFkxas6.d.ts.map +1 -0
- package/dist/{prime-protocol-BFgGrEMP.js → prime-protocol-CrhpXRz9.js} +4 -6
- package/dist/{prime-protocol-BFgGrEMP.js.map → prime-protocol-CrhpXRz9.js.map} +1 -1
- package/dist/profile-cell.d.ts +1 -1
- package/dist/profile-cell.js +1 -2
- package/dist/{promotion-gate-CkVZHagC.d.ts → promotion-gate-CixshGI8.d.ts} +5 -11
- package/dist/promotion-gate-CixshGI8.d.ts.map +1 -0
- package/dist/{promotion-policy-6A8osGr_.js → promotion-policy-CBYeD4zi.js} +5 -6
- package/dist/{promotion-policy-6A8osGr_.js.map → promotion-policy-CBYeD4zi.js.map} +1 -1
- package/dist/{proposal-findings-DqLUWsAG.js → proposal-findings-WFQrxnfe.js} +3 -4
- package/dist/{proposal-findings-DqLUWsAG.js.map → proposal-findings-WFQrxnfe.js.map} +1 -1
- package/dist/{quantile--0yb07pD.js → quantile-CncXP-Ss.js} +2 -3
- package/dist/{quantile--0yb07pD.js.map → quantile-CncXP-Ss.js.map} +1 -1
- package/dist/{query-B_RZ36an.js → query-CGXzO9d4.js} +5 -6
- package/dist/{query-B_RZ36an.js.map → query-CGXzO9d4.js.map} +1 -1
- package/dist/{query-Cmv_U8vf.d.ts → query-UD0B08Sb.d.ts} +4 -6
- package/dist/query-UD0B08Sb.d.ts.map +1 -0
- package/dist/{random-DGEyr3zG.d.ts → random-BN150Q_X.d.ts} +1 -5
- package/dist/random-BN150Q_X.d.ts.map +1 -0
- package/dist/{random-DDDcC7YU.js → random-DrzcgC7F.js} +3 -4
- package/dist/{random-DDDcC7YU.js.map → random-DrzcgC7F.js.map} +1 -1
- package/dist/{raw-provider-sink-75w4FWBj.js → raw-provider-sink-DDLkP_eF.js} +3 -4
- package/dist/{raw-provider-sink-75w4FWBj.js.map → raw-provider-sink-DDLkP_eF.js.map} +1 -1
- package/dist/{record-id-DUgsK5qp.js → record-id-CWZXFh58.js} +2 -3
- package/dist/{record-id-DUgsK5qp.js.map → record-id-CWZXFh58.js.map} +1 -1
- package/dist/{redact-DXdlFb_U.d.ts → redact-C_wzC4c_.d.ts} +1 -3
- package/dist/redact-C_wzC4c_.d.ts.map +1 -0
- package/dist/{redact-mtkTiJVk.js → redact-D6APJS1d.js} +3 -5
- package/dist/{redact-mtkTiJVk.js.map → redact-D6APJS1d.js.map} +1 -1
- package/dist/{registry-BcdJmyoU.d.ts → registry-dhdDoAV8.d.ts} +5 -11
- package/dist/registry-dhdDoAV8.d.ts.map +1 -0
- package/dist/{release-confidence-CYIFH-fp.js → release-confidence-CTUJz5mM.js} +10 -16
- package/dist/release-confidence-CTUJz5mM.js.map +1 -0
- package/dist/{render-BhJqXoBH.js → render-pfAZ7IR4.js} +266 -33
- package/dist/render-pfAZ7IR4.js.map +1 -0
- package/dist/{reporting-html-Kvlc8oMt.js → reporting-html-DMXIjATy.js} +2 -3
- package/dist/{reporting-html-Kvlc8oMt.js.map → reporting-html-DMXIjATy.js.map} +1 -1
- package/dist/reporting.d.ts +6 -6
- package/dist/reporting.js +7 -7
- package/dist/{researcher-DKWtoMWk.d.ts → researcher-CLnNJ7Or.d.ts} +8 -12
- package/dist/researcher-CLnNJ7Or.d.ts.map +1 -0
- package/dist/{reward-nw2xZGZG.js → reward-P0VD_Aft.js} +2 -3
- package/dist/{reward-nw2xZGZG.js.map → reward-P0VD_Aft.js.map} +1 -1
- package/dist/{reward-BeUgVVC_.d.ts → reward-ST4PXNXF.d.ts} +2 -4
- package/dist/reward-ST4PXNXF.d.ts.map +1 -0
- package/dist/{reward-hacking-WTxUbtbb.d.ts → reward-hacking-C9hPVT0Q.d.ts} +4 -8
- package/dist/reward-hacking-C9hPVT0Q.d.ts.map +1 -0
- package/dist/{reward-hacking-ByuETaIb.js → reward-hacking-DZzHZlS1.js} +5 -7
- package/dist/{reward-hacking-ByuETaIb.js.map → reward-hacking-DZzHZlS1.js.map} +1 -1
- package/dist/rl.d.ts +26 -63
- package/dist/rl.d.ts.map +1 -1
- package/dist/rl.js +35 -52
- package/dist/rl.js.map +1 -1
- package/dist/{rolldown-runtime-8H4AJuhK.js → rolldown-runtime-BJohB4LM.js} +1 -2
- package/dist/rollout/index.d.ts +6 -6
- package/dist/rollout/index.js +7 -7
- package/dist/{rollout-Dd1ucT_M.js → rollout-BhkMpAJT.js} +279 -16
- package/dist/rollout-BhkMpAJT.js.map +1 -0
- package/dist/{terminal-record-CB9BFtjS.js → rollout-nodes-BHR9Q5jP.js} +351 -11
- package/dist/rollout-nodes-BHR9Q5jP.js.map +1 -0
- package/dist/{round-decimal-COrKglMh.js → round-decimal-ZmjAQPo1.js} +2 -3
- package/dist/{round-decimal-COrKglMh.js.map → round-decimal-ZmjAQPo1.js.map} +1 -1
- package/dist/{rubric-predictive-validity-Cd5SCtAf.d.ts → rubric-predictive-validity-B3RzbwOx.d.ts} +2 -8
- package/dist/rubric-predictive-validity-B3RzbwOx.d.ts.map +1 -0
- package/dist/{rubric-predictive-validity-CeKW2GQN.js → rubric-predictive-validity-CQp_M0vy.js} +3 -4
- package/dist/{rubric-predictive-validity-CeKW2GQN.js.map → rubric-predictive-validity-CQp_M0vy.js.map} +1 -1
- package/dist/{run-record-CysKLB93.js → run-record-CZy4-TnZ.js} +4 -5
- package/dist/{run-record-CysKLB93.js.map → run-record-CZy4-TnZ.js.map} +1 -1
- package/dist/{run-record-C3awiXPf.d.ts → run-record-D2BFMPGl.d.ts} +5 -7
- package/dist/run-record-D2BFMPGl.d.ts.map +1 -0
- package/dist/{run-record-DhEJgoPz.js → run-record-DEjx43cI.js} +6 -7
- package/dist/{run-record-DhEJgoPz.js.map → run-record-DEjx43cI.js.map} +1 -1
- package/dist/{sandbox-harness-BlSOu4LX.d.ts → sandbox-harness-B3Kx1fOA.d.ts} +1 -3
- package/dist/sandbox-harness-B3Kx1fOA.d.ts.map +1 -0
- package/dist/{schema-D6EVKzTB.d.ts → schema-CkIvnmLU.d.ts} +2 -43
- package/dist/schema-CkIvnmLU.d.ts.map +1 -0
- package/dist/{schema-Bt2vLFm3.js → schema-D-xu3MU_.js} +2 -3
- package/dist/{schema-Bt2vLFm3.js.map → schema-D-xu3MU_.js.map} +1 -1
- package/dist/{schema-C-ziyJD7.d.ts → schema-DkFJr3Y8.d.ts} +111 -48
- package/dist/schema-DkFJr3Y8.d.ts.map +1 -0
- package/dist/{schema-CvhfLjtZ.js → schema-YUIXT8iW.js} +37 -7
- package/dist/schema-YUIXT8iW.js.map +1 -0
- package/dist/search/index.d.ts +3 -35
- package/dist/search/index.d.ts.map +1 -1
- package/dist/search/index.js +4 -5
- package/dist/{search-kernel-CctpiDd2.d.ts → search-kernel-CBdwFZ05.d.ts} +10 -36
- package/dist/search-kernel-CBdwFZ05.d.ts.map +1 -0
- package/dist/{search-ledger-CZRqtFbW.js → search-ledger-BsVi-Ngv.js} +17 -26
- package/dist/{search-ledger-CZRqtFbW.js.map → search-ledger-BsVi-Ngv.js.map} +1 -1
- package/dist/{search-ledger-file-Bd5Tioq6.js → search-ledger-file-DTBD6X-y.js} +6 -8
- package/dist/{search-ledger-file-Bd5Tioq6.js.map → search-ledger-file-DTBD6X-y.js.map} +1 -1
- package/dist/{search-ledger-types-p2xKfiDJ.d.ts → search-ledger-types-qiYRUo_N.d.ts} +5 -9
- package/dist/search-ledger-types-qiYRUo_N.d.ts.map +1 -0
- package/dist/{search-shipper-Dn3NLsuH.js → search-shipper-pdg4viK7.js} +8 -13
- package/dist/{search-shipper-Dn3NLsuH.js.map → search-shipper-pdg4viK7.js.map} +1 -1
- package/dist/{search-summary-D4bwYnAE.js → search-summary-Ct7SrmVc.js} +6 -7
- package/dist/{search-summary-D4bwYnAE.js.map → search-summary-Ct7SrmVc.js.map} +1 -1
- package/dist/{sequential-CimQrbjv.js → sequential-B1I0tRfL.js} +6 -7
- package/dist/{sequential-CimQrbjv.js.map → sequential-B1I0tRfL.js.map} +1 -1
- package/dist/{sequential-KwGspfeR.d.ts → sequential-Bb_pdTqG.d.ts} +1 -3
- package/dist/sequential-Bb_pdTqG.d.ts.map +1 -0
- package/dist/{sequential-BVv1sjsw.js → sequential-Bjs5roiK.js} +2 -3
- package/dist/{sequential-BVv1sjsw.js.map → sequential-Bjs5roiK.js.map} +1 -1
- package/dist/{sequential-eprocess-DodI6RoF.js → sequential-eprocess-C1YLwFaz.js} +3 -4
- package/dist/{sequential-eprocess-DodI6RoF.js.map → sequential-eprocess-C1YLwFaz.js.map} +1 -1
- package/dist/{server-ChhXPCgX.js → server-DA6h3co5.js} +11 -17
- package/dist/{server-ChhXPCgX.js.map → server-DA6h3co5.js.map} +1 -1
- package/dist/{single-run-lock-Dekd8_Wv.js → single-run-lock-BGlW3OSk.js} +3 -4
- package/dist/{single-run-lock-Dekd8_Wv.js.map → single-run-lock-BGlW3OSk.js.map} +1 -1
- package/dist/{skillopt-optimization-method-sB_-yi1G.js → skillopt-optimization-method-qB1M554K.js} +38 -57
- package/dist/{skillopt-optimization-method-sB_-yi1G.js.map → skillopt-optimization-method-qB1M554K.js.map} +1 -1
- package/dist/{spans-CVngGij3.d.ts → spans-vZoW__3q.d.ts} +2 -4
- package/dist/spans-vZoW__3q.d.ts.map +1 -0
- package/dist/{statistical-heldout-BjzSOmLH.d.ts → statistical-heldout-Cei036nE.d.ts} +9 -37
- package/dist/statistical-heldout-Cei036nE.d.ts.map +1 -0
- package/dist/{statistical-heldout-Bksv92Th.js → statistical-heldout-TP6ndL0B.js} +4 -5
- package/dist/{statistical-heldout-Bksv92Th.js.map → statistical-heldout-TP6ndL0B.js.map} +1 -1
- package/dist/{steps-DlepJPwD.d.ts → steps-B8fYY_Vo.d.ts} +1 -3
- package/dist/steps-B8fYY_Vo.d.ts.map +1 -0
- package/dist/{store-B3nWRy3B.d.ts → store-CMs5wGXP.d.ts} +2 -4
- package/dist/store-CMs5wGXP.d.ts.map +1 -0
- package/dist/{store-BhNuLdJw.js → store-ZykIyQmy.js} +2 -3
- package/dist/{store-BhNuLdJw.js.map → store-ZykIyQmy.js.map} +1 -1
- package/dist/{store-otlp-CFf27E8_.js → store-otlp-DmLm65XW.js} +8 -13
- package/dist/{store-otlp-CFf27E8_.js.map → store-otlp-DmLm65XW.js.map} +1 -1
- package/dist/{store-tool-spans-DxsFwtdr.d.ts → store-tool-spans-B3i3fl0A.d.ts} +11 -29
- package/dist/store-tool-spans-B3i3fl0A.d.ts.map +1 -0
- package/dist/{store-tool-spans-BK_8FjGG.js → store-tool-spans-C2g8UYm-.js} +17 -41
- package/dist/{store-tool-spans-BK_8FjGG.js.map → store-tool-spans-C2g8UYm-.js.map} +1 -1
- package/dist/storyboard/index.d.ts +1 -5
- package/dist/storyboard/index.d.ts.map +1 -1
- package/dist/storyboard/index.js +3 -5
- package/dist/storyboard/index.js.map +1 -1
- package/dist/{summary-report-C8V49Jt3.d.ts → summary-report-0La5vejY.d.ts} +5 -13
- package/dist/summary-report-0La5vejY.d.ts.map +1 -0
- package/dist/{summary-report-DHDWxe6p.js → summary-report-CPfsrLac.js} +21 -30
- package/dist/summary-report-CPfsrLac.js.map +1 -0
- package/dist/supervisor-run/index.d.ts +30 -29
- package/dist/supervisor-run/index.d.ts.map +1 -1
- package/dist/supervisor-run/index.js +6 -7
- package/dist/{systemone-CHnqwmYg.d.ts → systemone-Cw2txK5m.d.ts} +12 -24
- package/dist/systemone-Cw2txK5m.d.ts.map +1 -0
- package/dist/{systemone-protocol-Bl2EI2KQ.d.ts → systemone-protocol-C4t7JH4Y.d.ts} +1 -3
- package/dist/systemone-protocol-C4t7JH4Y.d.ts.map +1 -0
- package/dist/systemone-protocol.d.ts +1 -1
- package/dist/systemone-protocol.js +2 -3
- package/dist/{systemone-review-cQ9acAsb.d.ts → systemone-review-BLgxt-4Q.d.ts} +8 -10
- package/dist/systemone-review-BLgxt-4Q.d.ts.map +1 -0
- package/dist/{systemone-review-DFGtIUcf.js → systemone-review-S49gsy_y.js} +5 -6
- package/dist/{systemone-review-DFGtIUcf.js.map → systemone-review-S49gsy_y.js.map} +1 -1
- package/dist/systemone.d.ts +4 -4
- package/dist/systemone.js +3 -3
- package/dist/{task-failure-attributes-BMsblaDh.js → task-failure-attributes-CC6VuIpk.js} +12 -11
- package/dist/task-failure-attributes-CC6VuIpk.js.map +1 -0
- package/dist/{tool-groups-b3oU_D88.d.ts → tool-groups-C3K-d3gd.d.ts} +3 -5
- package/dist/tool-groups-C3K-d3gd.d.ts.map +1 -0
- package/dist/{tool-waste-CkjzWmeY.d.ts → tool-waste-BFG1vwTV.d.ts} +4 -16
- package/dist/tool-waste-BFG1vwTV.d.ts.map +1 -0
- package/dist/{tool-waste-DLsjS_p-.js → tool-waste-CLJ46AbT.js} +10 -26
- package/dist/{tool-waste-DLsjS_p-.js.map → tool-waste-CLJ46AbT.js.map} +1 -1
- package/dist/trace-attributes.d.ts +1 -1
- package/dist/trace-attributes.js +1 -2
- package/dist/{trace-questions-BmT8M6UQ.d.ts → trace-questions-ej5AEJ5X.d.ts} +4 -6
- package/dist/trace-questions-ej5AEJ5X.d.ts.map +1 -0
- package/dist/trace-repair/index.d.ts +46 -92
- package/dist/trace-repair/index.d.ts.map +1 -1
- package/dist/trace-repair/index.js +32 -54
- package/dist/trace-repair/index.js.map +1 -1
- package/dist/traces.d.ts +13 -29
- package/dist/traces.d.ts.map +1 -1
- package/dist/traces.js +18 -22
- package/dist/traces.js.map +1 -1
- package/dist/{trajectory-D_7rLrvE.js → trajectory-O3GDHmev.js} +2 -3
- package/dist/{trajectory-D_7rLrvE.js.map → trajectory-O3GDHmev.js.map} +1 -1
- package/dist/trajectory-replay/index.d.ts +2 -22
- package/dist/trajectory-replay/index.d.ts.map +1 -1
- package/dist/trajectory-replay/index.js +19 -30
- package/dist/trajectory-replay/index.js.map +1 -1
- package/dist/{tree-DSqwJpL9.js → tree-DrIChF4a.js} +39 -68
- package/dist/{tree-DSqwJpL9.js.map → tree-DrIChF4a.js.map} +1 -1
- package/dist/{types-B_IFcKp5.d.ts → types-0KglnQ9o.d.ts} +3 -15
- package/dist/types-0KglnQ9o.d.ts.map +1 -0
- package/dist/{types-DZ0mYVw9.d.ts → types-0oMg7zee.d.ts} +3 -5
- package/dist/types-0oMg7zee.d.ts.map +1 -0
- package/dist/{types-CnWmj8NW.js → types-BK0blWhe.js} +3 -4
- package/dist/{types-CnWmj8NW.js.map → types-BK0blWhe.js.map} +1 -1
- package/dist/{types-CmXY0PQf.d.ts → types-C-aOqgt2.d.ts} +2 -5
- package/dist/types-C-aOqgt2.d.ts.map +1 -0
- package/dist/{types-M6eF9m-r.d.ts → types-C54Uk_a1.d.ts} +84 -24
- package/dist/types-C54Uk_a1.d.ts.map +1 -0
- package/dist/{types-BXgASBCL.js → types-DK4vNv5q.js} +2 -3
- package/dist/{types-BXgASBCL.js.map → types-DK4vNv5q.js.map} +1 -1
- package/dist/{types-6Lfdlshp.d.ts → types-DzCO-S1m.d.ts} +50 -62
- package/dist/types-DzCO-S1m.d.ts.map +1 -0
- package/dist/{verdict-BGQmxQ8A.js → verdict-C8TcdwfD.js} +3 -4
- package/dist/{verdict-BGQmxQ8A.js.map → verdict-C8TcdwfD.js.map} +1 -1
- package/dist/{verdict-C24NELtN.d.ts → verdict-D_qiBQ6_.d.ts} +1 -5
- package/dist/verdict-D_qiBQ6_.d.ts.map +1 -0
- package/dist/{verdict-cache-CL_7tePD.js → verdict-cache-BVH-fl18.js} +3 -4
- package/dist/{verdict-cache-CL_7tePD.js.map → verdict-cache-BVH-fl18.js.map} +1 -1
- package/dist/wire/index.d.ts +43 -51
- package/dist/wire/index.d.ts.map +1 -1
- package/dist/wire/index.js +1 -2
- package/docs/concepts.md +1 -0
- package/docs/eval-surface-map.md +15 -0
- package/docs/rollout.md +132 -6
- package/package.json +18 -18
- package/dist/adversarial-smnADNFS.d.ts.map +0 -1
- package/dist/agent-profile-CNmwfaqq.d.ts.map +0 -1
- package/dist/agent-profile-cell-BcpFbNd5.d.ts.map +0 -1
- package/dist/analyze-runs-DfX6dHP0.d.ts.map +0 -1
- package/dist/attribute-vocabulary-CcXqHODT.d.ts.map +0 -1
- package/dist/benchmark-command-Cnjfo0Zh.js.map +0 -1
- package/dist/campaign-evidence-DunzcJGv.js.map +0 -1
- package/dist/campaign-uddTlFg5.js.map +0 -1
- package/dist/canonical-CFpojCN5.d.ts.map +0 -1
- package/dist/client-hwo3cJjR.d.ts.map +0 -1
- package/dist/completion-verifier-asaV1nSj.js.map +0 -1
- package/dist/cost-ledger-C1W3ICmP.d.ts.map +0 -1
- package/dist/dataset-DQqhOCPt.d.ts.map +0 -1
- package/dist/default-registry-CLG5YqGS.d.ts.map +0 -1
- package/dist/define-agent-eval-JKt3gMQr.d.ts.map +0 -1
- package/dist/descriptive-B2iPaT9J.d.ts +0 -89
- package/dist/descriptive-B2iPaT9J.d.ts.map +0 -1
- package/dist/descriptive-CVNy48rR.js.map +0 -1
- package/dist/emitter-DABYYTcH.d.ts.map +0 -1
- package/dist/engine-dtRVeuQs.d.ts.map +0 -1
- package/dist/errors-DEE6u6ot.d.ts.map +0 -1
- package/dist/evaluation-DblGquCB.d.ts.map +0 -1
- package/dist/exact-types-Do63KoKn.d.ts.map +0 -1
- package/dist/exporters-DWvM16LE.js.map +0 -1
- package/dist/exporters-Dk3oEbK_.d.ts.map +0 -1
- package/dist/failure-cluster-DN0t63Z0.d.ts.map +0 -1
- package/dist/feedback-trajectory-CYVJXolG.d.ts.map +0 -1
- package/dist/hf-dataset-CKxIJQba.js.map +0 -1
- package/dist/index-CHxwfW5g.d.ts.map +0 -1
- package/dist/index-CTIRz-AB.d.ts.map +0 -1
- package/dist/index-CalAsXMR.d.ts.map +0 -1
- package/dist/index-CdEVr8-O.d.ts.map +0 -1
- package/dist/index-CfJULcW5.d.ts.map +0 -1
- package/dist/index-D7fmC-1K.d.ts.map +0 -1
- package/dist/index-jnuFLxOs.d.ts.map +0 -1
- package/dist/integrity-D-s2iHiT.js.map +0 -1
- package/dist/integrity-D9lBnv_K.d.ts.map +0 -1
- package/dist/interval-ohuOJurX.d.ts.map +0 -1
- package/dist/judge-calibration-DFtEMlde.d.ts.map +0 -1
- package/dist/llm-judge-Cybq29bL.js.map +0 -1
- package/dist/lock-holder-DaJbfpci.d.ts.map +0 -1
- package/dist/matrix-B8l-Nsxd.js.map +0 -1
- package/dist/matrix-DtkZLD_3.d.ts.map +0 -1
- package/dist/mint-CkzpVPdz.d.ts +0 -81
- package/dist/mint-CkzpVPdz.d.ts.map +0 -1
- package/dist/multi-layer-verifier-DEgMUk6v.d.ts.map +0 -1
- package/dist/multiplicity-DIWHvysC.d.ts.map +0 -1
- package/dist/paired-promotion-decision-CQMJ5xGN.d.ts.map +0 -1
- package/dist/pareto-BiBnQXAE.js.map +0 -1
- package/dist/prime-bridge-transport-6feEglLf.d.ts.map +0 -1
- package/dist/prime-protocol-BGxjfhM4.d.ts.map +0 -1
- package/dist/promotion-gate-CkVZHagC.d.ts.map +0 -1
- package/dist/query-Cmv_U8vf.d.ts.map +0 -1
- package/dist/random-DGEyr3zG.d.ts.map +0 -1
- package/dist/redact-DXdlFb_U.d.ts.map +0 -1
- package/dist/registry-BcdJmyoU.d.ts.map +0 -1
- package/dist/release-confidence-CYIFH-fp.js.map +0 -1
- package/dist/render-BhJqXoBH.js.map +0 -1
- package/dist/researcher-DKWtoMWk.d.ts.map +0 -1
- package/dist/reward-BeUgVVC_.d.ts.map +0 -1
- package/dist/reward-hacking-WTxUbtbb.d.ts.map +0 -1
- package/dist/rollout-Dd1ucT_M.js.map +0 -1
- package/dist/rubric-predictive-validity-Cd5SCtAf.d.ts.map +0 -1
- package/dist/run-record-C3awiXPf.d.ts.map +0 -1
- package/dist/sandbox-harness-BlSOu4LX.d.ts.map +0 -1
- package/dist/schema-C-ziyJD7.d.ts.map +0 -1
- package/dist/schema-CvhfLjtZ.js.map +0 -1
- package/dist/schema-D6EVKzTB.d.ts.map +0 -1
- package/dist/search-kernel-CctpiDd2.d.ts.map +0 -1
- package/dist/search-ledger-types-p2xKfiDJ.d.ts.map +0 -1
- package/dist/sequential-KwGspfeR.d.ts.map +0 -1
- package/dist/spans-CVngGij3.d.ts.map +0 -1
- package/dist/statistical-heldout-BjzSOmLH.d.ts.map +0 -1
- package/dist/steps-DlepJPwD.d.ts.map +0 -1
- package/dist/store-B3nWRy3B.d.ts.map +0 -1
- package/dist/store-tool-spans-DxsFwtdr.d.ts.map +0 -1
- package/dist/summary-report-C8V49Jt3.d.ts.map +0 -1
- package/dist/summary-report-DHDWxe6p.js.map +0 -1
- package/dist/systemone-CHnqwmYg.d.ts.map +0 -1
- package/dist/systemone-protocol-Bl2EI2KQ.d.ts.map +0 -1
- package/dist/systemone-review-cQ9acAsb.d.ts.map +0 -1
- package/dist/task-failure-attributes-BMsblaDh.js.map +0 -1
- package/dist/terminal-record-CB9BFtjS.js.map +0 -1
- package/dist/tool-groups-b3oU_D88.d.ts.map +0 -1
- package/dist/tool-waste-CkjzWmeY.d.ts.map +0 -1
- package/dist/trace-questions-BmT8M6UQ.d.ts.map +0 -1
- package/dist/types-6Lfdlshp.d.ts.map +0 -1
- package/dist/types-B_IFcKp5.d.ts.map +0 -1
- package/dist/types-CmXY0PQf.d.ts.map +0 -1
- package/dist/types-DZ0mYVw9.d.ts.map +0 -1
- package/dist/types-M6eF9m-r.d.ts.map +0 -1
- package/dist/verdict-C24NELtN.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"journal-C7om8Gum.js","names":[],"sources":["../src/ledger-core/atomic-file-lock.ts","../src/ledger-core/journal-file.ts","../src/concurrency.ts","../src/ledger-core/projector-snapshot.ts","../src/ledger-core/trusted-head.ts","../src/ledger-core/journal.ts"],"sourcesContent":["/** Crash-safe filesystem lock shared by campaign persistence and run exclusion. */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n closeSync,\n constants,\n existsSync,\n fstatSync,\n fsyncSync,\n linkSync,\n openSync,\n readFileSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport {\n type LockHolderIdentity,\n type LockHolderRecord,\n type LockIdentity,\n lockHolderVerdict,\n lockIdentity,\n parseLockHolderRecord,\n readLockHolderIdentity,\n} from './lock-holder'\n\n/**\n * The holder of a lock path. The lock file holds this record plus the identity\n * of its own inode, so `lockHolderVerdict` can prove a crashed holder dead.\n */\nexport interface AtomicFileLockOwner extends LockHolderIdentity {\n readonly nonce: string\n}\n\nexport interface AtomicFileLock {\n readonly owner: AtomicFileLockOwner\n release(): void\n}\n\nexport type AtomicFileLockUnavailable =\n | { readonly acquired: false; readonly reason: 'held'; readonly holder: AtomicFileLockOwner }\n | { readonly acquired: false; readonly reason: 'recovery' }\n\nexport type AtomicFileLockAcquisition =\n | { readonly acquired: true; readonly lock: AtomicFileLock }\n | AtomicFileLockUnavailable\n\nexport interface AtomicFileLockOptions {\n readonly lockPath: string\n readonly pid?: number\n}\n\nexport class AtomicFileLockError extends Error {\n override readonly name = 'AtomicFileLockError'\n}\n\ntype OwnerState =\n | { readonly state: 'missing' }\n | { readonly state: 'stale'; readonly owner: AtomicFileLockOwner }\n | { readonly state: 'held'; readonly owner: AtomicFileLockOwner }\n\n/** Report whether another lock path prevents acquisition without modifying it. */\nexport function probeAtomicFileLock(\n options: AtomicFileLockOptions,\n): AtomicFileLockUnavailable | null {\n if (existsSync(recoveryPath(options.lockPath))) return { acquired: false, reason: 'recovery' }\n const state = ownerState(options.lockPath)\n if (state.state === 'held') {\n return { acquired: false, reason: 'held', holder: state.owner }\n }\n return null\n}\n\n/**\n * Try to acquire a complete, uniquely-owned lock inode.\n *\n * A hard link publishes fully-written owner metadata atomically. Stale-owner\n * removal is serialized so one reclaimer cannot delete a new owner's lock.\n */\nexport function tryAcquireAtomicFileLock(\n options: AtomicFileLockOptions,\n): AtomicFileLockAcquisition {\n const pid = options.pid ?? process.pid\n if (!Number.isSafeInteger(pid) || pid <= 0) {\n throw new AtomicFileLockError('atomic file lock pid must be a positive integer')\n }\n const owner: AtomicFileLockOwner = { ...readLockHolderIdentity(pid), nonce: randomUUID() }\n for (let attempt = 0; attempt < 8; attempt += 1) {\n if (existsSync(recoveryPath(options.lockPath))) {\n const recovery = tryAcquireRecoveryLease(options.lockPath, owner, attempt)\n if (!recovery) return { acquired: false, reason: 'recovery' }\n try {\n return recoverLock(options.lockPath, owner, attempt)\n } finally {\n recovery.release()\n }\n }\n if (tryLinkOwner(options.lockPath, owner, `acquire.${attempt}`)) {\n return acquired(options.lockPath, owner)\n }\n\n const holder = ownerState(options.lockPath)\n if (holder.state === 'missing') continue\n if (holder.state === 'held') {\n return { acquired: false, reason: 'held', holder: holder.owner }\n }\n\n const recovery = tryAcquireRecoveryLease(options.lockPath, owner, attempt)\n if (!recovery) return { acquired: false, reason: 'recovery' }\n try {\n return recoverLock(options.lockPath, owner, attempt)\n } finally {\n recovery.release()\n }\n }\n\n throw new AtomicFileLockError(`could not acquire atomic file lock ${options.lockPath}`)\n}\n\ninterface RecoveryLease {\n release(): void\n}\n\nfunction tryAcquireRecoveryLease(\n lockPath: string,\n owner: AtomicFileLockOwner,\n attempt: number,\n): RecoveryLease | null {\n let leasePath = recoveryPath(lockPath)\n const staleOwners: Array<{ path: string; owner: AtomicFileLockOwner }> = []\n\n for (let depth = 0; depth < 64; depth += 1) {\n const state = ownerState(leasePath)\n if (state.state === 'missing') {\n if (!tryLinkOwner(leasePath, owner, `reclaim.${attempt}.${depth}`)) continue\n return {\n release: () => {\n for (const stale of staleOwners) releaseOwnedPath(stale.path, stale.owner)\n releaseOwnedPath(leasePath, owner)\n },\n }\n }\n if (state.state === 'held') return null\n staleOwners.push({ path: leasePath, owner: state.owner })\n leasePath = `${leasePath}.next.${state.owner.nonce}`\n }\n\n throw new AtomicFileLockError(`atomic file lock recovery chain is too deep (${lockPath})`)\n}\n\nfunction recoverLock(\n lockPath: string,\n owner: AtomicFileLockOwner,\n attempt: number,\n): AtomicFileLockAcquisition {\n const current = ownerState(lockPath)\n if (current.state === 'held') {\n return { acquired: false, reason: 'held', holder: current.owner }\n }\n if (current.state === 'stale') {\n const tombstone = `${lockPath}.stale.${owner.nonce}.${attempt}`\n try {\n renameSync(lockPath, tombstone)\n unlinkSync(tombstone)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n }\n if (tryLinkOwner(lockPath, owner, `recovered.${attempt}`)) {\n return acquired(lockPath, owner)\n }\n const holder = ownerState(lockPath)\n if (holder.state === 'held') {\n return { acquired: false, reason: 'held', holder: holder.owner }\n }\n return { acquired: false, reason: 'recovery' }\n}\n\nfunction acquired(lockPath: string, owner: AtomicFileLockOwner): AtomicFileLockAcquisition {\n return {\n acquired: true,\n lock: {\n owner,\n release: () => releaseOwnedPath(lockPath, owner),\n },\n }\n}\n\nfunction tryLinkOwner(lockPath: string, owner: AtomicFileLockOwner, suffix: string): boolean {\n const ownerPath = `${lockPath}.${owner.pid}.${owner.nonce}.${suffix}.owner`\n const descriptor = openSync(\n ownerPath,\n constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,\n 0o600,\n )\n try {\n // A hard link keeps the inode, so this identity is the lock path's once linked.\n const lock = lockIdentity(fstatSync(descriptor, { bigint: true }))\n writeFileSync(descriptor, `${JSON.stringify({ ...owner, lock })}\\n`, 'utf8')\n fsyncSync(descriptor)\n } catch (error) {\n closeSync(descriptor)\n unlinkIfExists(ownerPath)\n throw error\n }\n closeSync(descriptor)\n\n try {\n linkSync(ownerPath, lockPath)\n return true\n } catch (error) {\n if (!isAlreadyExists(error)) throw error\n return false\n } finally {\n unlinkIfExists(ownerPath)\n }\n}\n\n/** Only a holder proved dead is stale; an alive or unknown holder keeps the lock. */\nfunction ownerState(lockPath: string): OwnerState {\n const current = readOwner(lockPath)\n if (!current) return { state: 'missing' }\n const verdict = lockHolderVerdict(current.record, current.identity)\n return { state: verdict.liveness === 'dead' ? 'stale' : 'held', owner: current.owner }\n}\n\ninterface LockFileOwner {\n readonly owner: AtomicFileLockOwner\n readonly record: LockHolderRecord & { readonly nonce: string }\n /** The inode the record was read from, so a verdict compares it with the recorded lock. */\n readonly identity: LockIdentity\n}\n\nfunction readOwner(lockPath: string): LockFileOwner | undefined {\n let descriptor: number\n try {\n descriptor = openSync(lockPath, 'r')\n } catch (error) {\n if (isMissing(error)) return undefined\n throw error\n }\n let contents: string\n let identity: LockIdentity\n try {\n identity = lockIdentity(fstatSync(descriptor, { bigint: true }))\n contents = readFileSync(descriptor, 'utf8').trim()\n } finally {\n closeSync(descriptor)\n }\n\n let value: unknown\n try {\n value = JSON.parse(contents)\n } catch (error) {\n throw invalidOwner(lockPath, error)\n }\n const record = parseOwnerRecord(value)\n if (!record) throw invalidOwner(lockPath)\n const { lock: _lock, ...owner } = record\n return { owner, record, identity }\n}\n\n/**\n * Accept exactly the fields a lock owner writes: a holder record that parses\n * whole, plus the nonce. A record from before holder identity carried only pid,\n * host and nonce; it still parses, and its holder is never proved dead.\n */\nfunction parseOwnerRecord(value: unknown): LockFileOwner['record'] | undefined {\n const holder = parseLockHolderRecord(value)\n if (!holder) return undefined\n const { nonce, ...rest } = value as Record<string, unknown>\n if (typeof nonce !== 'string' || nonce.trim().length === 0) return undefined\n // A field the holder parse dropped is malformed; refuse it instead of guessing.\n if (Object.keys(rest).length !== Object.keys(holder).length) return undefined\n return { ...holder, nonce }\n}\n\nfunction invalidOwner(lockPath: string, cause?: unknown): AtomicFileLockError {\n const error = new AtomicFileLockError(\n `atomic file lock has an invalid owner (${lockPath}); refusing unsafe recovery`,\n )\n if (cause !== undefined) Object.defineProperty(error, 'cause', { value: cause })\n return error\n}\n\nfunction releaseOwnedPath(lockPath: string, owner: AtomicFileLockOwner): void {\n const current = readOwner(lockPath)\n if (!current) return\n if (canonicalOwner(current.owner) !== canonicalOwner(owner)) {\n throw new AtomicFileLockError(`atomic file lock owner changed before release (${lockPath})`)\n }\n try {\n unlinkSync(lockPath)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n}\n\nfunction canonicalOwner(owner: AtomicFileLockOwner): string {\n return JSON.stringify({ host: owner.host, nonce: owner.nonce, pid: owner.pid })\n}\n\nfunction recoveryPath(lockPath: string): string {\n return `${lockPath}.reclaim`\n}\n\nfunction isAlreadyExists(error: unknown): boolean {\n return error instanceof Error && 'code' in error && error.code === 'EEXIST'\n}\n\nfunction isMissing(error: unknown): boolean {\n return error instanceof Error && 'code' in error && error.code === 'ENOENT'\n}\n\nfunction unlinkIfExists(path: string): void {\n try {\n unlinkSync(path)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n}\n","/** Filesystem durability and cross-process exclusion for append-only journal files. */\n\nimport {\n closeSync,\n constants,\n fstatSync,\n fsyncSync,\n mkdirSync,\n openSync,\n readSync,\n renameSync,\n rmSync,\n writeSync,\n} from 'node:fs'\nimport { dirname } from 'node:path'\nimport { AtomicFileLockError, tryAcquireAtomicFileLock } from './atomic-file-lock'\n\n/** How a journal binding reports file-layer faults in its own error taxonomy. */\nexport interface LedgerFileContext {\n /** Noun used in error messages, e.g. 'search ledger'. */\n subject: string\n integrityError(message: string, options?: { cause?: unknown }): Error\n}\n\n/** Append one already-serialized line; the write is fsynced (file and directory)\n * before returning so an acknowledged append survives a crash. */\nexport function appendLedgerLine(path: string, line: string, context: LedgerFileContext): void {\n mkdirSync(dirname(path), { recursive: true })\n recoverTornFinalWrite(path, context)\n const fd = openSync(path, constants.O_CREAT | constants.O_WRONLY | constants.O_APPEND, 0o600)\n try {\n writeAll(fd, Buffer.from(line, 'utf8'), context)\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n fsyncDirectory(dirname(path))\n}\n\nfunction recoverTornFinalWrite(path: string, context: LedgerFileContext): void {\n let fd: number\n try {\n fd = openSync(path, constants.O_RDWR)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return\n throw context.integrityError(`${context.subject} ${path} could not be opened for recovery`, {\n cause: error,\n })\n }\n\n try {\n const size = fstatSync(fd).size\n if (size === 0 || readByte(fd, size - 1) === 0x0a) return\n const tailStart = findFinalLineStart(fd, size)\n const replacement = Buffer.alloc(size - tailStart, 0x20)\n replacement[replacement.length - 1] = 0x0a\n writeAllAt(fd, replacement, tailStart, context)\n fsyncSync(fd)\n } catch (error) {\n throw context.integrityError(\n `${context.subject} ${path} has an unrecoverable final journal write`,\n { cause: error },\n )\n } finally {\n closeSync(fd)\n }\n}\n\n/** Replace a small sidecar file whole: write a temporary sibling, fsync it,\n * then rename over the target. A reader therefore sees the previous contents\n * or the new ones, never a partial file. */\nexport function writeLedgerFileAtomically(\n path: string,\n contents: string,\n context: LedgerFileContext,\n): void {\n const directory = dirname(path)\n mkdirSync(directory, { recursive: true })\n const temporaryPath = `${path}.tmp`\n const fd = openSync(\n temporaryPath,\n constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC,\n 0o600,\n )\n try {\n writeAll(fd, Buffer.from(contents, 'utf8'), context)\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n renameSync(temporaryPath, path)\n fsyncDirectory(directory)\n}\n\n/** Remove whatever occupies a sidecar path and fsync its directory, so the\n * removal is as durable as the write that created it. False when the path was\n * already empty. Recursive because a sidecar path holding a directory is one of\n * the states this has to be able to clear, not one it can refuse. */\nexport function removeLedgerFile(path: string, context: LedgerFileContext): boolean {\n try {\n rmSync(path, { recursive: true })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false\n throw context.integrityError(`${context.subject} ${path} could not be removed`, {\n cause: error,\n })\n }\n fsyncDirectory(dirname(path))\n return true\n}\n\nexport function withLedgerFileLock<T>(path: string, context: LedgerFileContext, run: () => T): T {\n const result = tryWithLedgerFileLock(path, context, run)\n if (!result.acquired) {\n throw context.integrityError(`${context.subject} lock is held (${path})`)\n }\n return result.value\n}\n\nexport type FileLockResult<T> = { acquired: true; value: T } | { acquired: false }\n\nexport function tryWithLedgerFileLock<T>(\n path: string,\n context: LedgerFileContext,\n run: () => T,\n): FileLockResult<T> {\n mkdirSync(dirname(path), { recursive: true })\n const lockPath = `${path}.lock`\n try {\n const acquisition = tryAcquireAtomicFileLock({ lockPath })\n if (!acquisition.acquired) return { acquired: false }\n try {\n return { acquired: true, value: run() }\n } finally {\n acquisition.lock.release()\n }\n } catch (error) {\n if (error instanceof AtomicFileLockError) {\n throw context.integrityError(error.message, { cause: error })\n }\n throw error\n }\n}\n\nfunction writeAll(fd: number, bytes: Buffer, context: LedgerFileContext): void {\n let offset = 0\n while (offset < bytes.byteLength) {\n const written = writeSync(fd, bytes, offset, bytes.byteLength - offset)\n if (written <= 0) throw context.integrityError('filesystem wrote zero bytes')\n offset += written\n }\n}\n\nfunction writeAllAt(fd: number, bytes: Buffer, position: number, context: LedgerFileContext): void {\n let offset = 0\n while (offset < bytes.byteLength) {\n const written = writeSync(fd, bytes, offset, bytes.byteLength - offset, position + offset)\n if (written <= 0) throw context.integrityError('filesystem wrote zero bytes')\n offset += written\n }\n}\n\nfunction findFinalLineStart(fd: number, size: number): number {\n const chunk = Buffer.alloc(Math.min(4_096, size))\n let cursor = size\n while (cursor > 0) {\n const length = Math.min(chunk.byteLength, cursor)\n cursor -= length\n const read = readSync(fd, chunk, 0, length, cursor)\n for (let index = read - 1; index >= 0; index -= 1) {\n if (chunk[index] === 0x0a) return cursor + index + 1\n }\n }\n return 0\n}\n\nfunction readByte(fd: number, position: number): number {\n const byte = Buffer.allocUnsafe(1)\n const read = readSync(fd, byte, 0, 1, position)\n return read === 1 ? byte[0]! : -1\n}\n\nfunction fsyncDirectory(path: string): void {\n const fd = openSync(path, constants.O_RDONLY)\n try {\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n}\n","/**\n * concurrency — small primitives the evolution loop needs.\n *\n * `Mutex` is a zero-dep async lock with FIFO fairness. The evolution loop\n * uses it to serialise checkout/build/commit sequences inside a single\n * pool slot, and to gate concurrent JSONL writers (see\n * `lockedJsonlReferenceReplayStore`).\n *\n * Deliberately minimal — no priority queue, no timeouts. If you need\n * those, swap to `async-mutex` at the call site.\n */\n\nexport class Mutex {\n private locked = false\n private readonly waiters: Array<() => void> = []\n\n async acquire(): Promise<() => void> {\n if (!this.locked) {\n this.locked = true\n return () => this.release()\n }\n return new Promise<() => void>((resolve) => {\n this.waiters.push(() => {\n resolve(() => this.release())\n })\n })\n }\n\n private release(): void {\n const next = this.waiters.shift()\n if (next) {\n next()\n } else {\n this.locked = false\n }\n }\n\n async runExclusive<T>(fn: () => Promise<T> | T): Promise<T> {\n const release = await this.acquire()\n try {\n return await fn()\n } finally {\n release()\n }\n }\n\n /** True iff someone holds the lock right now. Diagnostics only. */\n get isLocked(): boolean {\n return this.locked\n }\n\n /** Pending waiter count. Diagnostics only. */\n get pending(): number {\n return this.waiters.length\n }\n}\n\ninterface MapConcurrentRangeOptions<R> {\n count: number\n maxConcurrency: number\n label: string\n signal?: AbortSignal\n map(index: number, signal: AbortSignal): Promise<R>\n}\n\n/** Map an integer range with bounded work, cancellation, and first-error cleanup. */\nexport async function mapConcurrentRange<R>(options: MapConcurrentRangeOptions<R>): Promise<R[]> {\n if (!Number.isSafeInteger(options.count) || options.count < 0) {\n throw new Error(`${options.label} count must be a non-negative integer`)\n }\n if (!Number.isSafeInteger(options.maxConcurrency) || options.maxConcurrency < 1) {\n throw new Error(`${options.label} maxConcurrency must be a positive integer`)\n }\n\n const controller = new AbortController()\n const abortFromCaller = () => controller.abort(options.signal?.reason)\n if (options.signal?.aborted) abortFromCaller()\n else options.signal?.addEventListener('abort', abortFromCaller, { once: true })\n\n const results = new Array<R>(options.count)\n let nextIndex = 0\n let failed = false\n let firstFailure: unknown\n const workers = Array.from(\n { length: Math.min(options.maxConcurrency, options.count) },\n async () => {\n while (!controller.signal.aborted) {\n const index = nextIndex\n nextIndex += 1\n if (index >= options.count) return\n try {\n results[index] = await options.map(index, controller.signal)\n } catch (error) {\n if (!failed) {\n failed = true\n firstFailure = error\n controller.abort(error)\n }\n return\n }\n }\n },\n )\n\n try {\n await Promise.all(workers)\n if (options.signal?.aborted) throw abortError(options.signal, options.label)\n if (failed) throw firstFailure\n if (controller.signal.aborted) throw abortError(controller.signal, options.label)\n return results\n } finally {\n options.signal?.removeEventListener('abort', abortFromCaller)\n }\n}\n\n/**\n * Map independent work with a fixed worker count while preserving input order.\n * After the first rejection, no new items start; already-running work is allowed\n * to settle before the returned promise rejects. Partial results are discarded.\n */\nexport async function mapConcurrent<T, R>(\n items: readonly T[],\n concurrency: number,\n map: (item: T, index: number, signal: AbortSignal) => Promise<R>,\n signal?: AbortSignal,\n): Promise<R[]> {\n return mapConcurrentRange({\n count: items.length,\n maxConcurrency: concurrency,\n label: 'mapConcurrent',\n signal,\n map(index, signal) {\n return map(items[index]!, index, signal)\n },\n })\n}\n\nfunction abortError(signal: AbortSignal, label: string): Error {\n return signal.reason instanceof Error ? signal.reason : new Error(`${label} aborted`)\n}\n","/**\n * Projector snapshot — the cache that lets opening a large journal replay\n * only its tail.\n *\n * `trusted-head.ts`'s pin proves a journal's length and prefix content\n * without trusting a producer's summary; it does not make PROVING that\n * cheap. Every open still walks every row from sequence 0, parses it through\n * the domain codec, and applies it to a fresh projector, because that was the\n * only way this module knew to rebuild `Projection`.\n *\n * This file adds one more sidecar: `<journal>.snapshot` holds a `Projection`\n * a codec that opts in (`snapshotProjection` on its `LedgerJournalCodec`)\n * serialized, alongside the `(sequence, entryHash)` it was taken after. A\n * reader that finds one still verifies the generic hash chain of every row up\n * to that checkpoint — self-consistency and chain linkage, the same two\n * checks `journal.ts`'s `admitEntry` runs on every row — because that\n * verification is what the pin's guarantee actually rests on (see\n * `trusted-head.ts`'s module comment: an entry hash commits to its whole\n * prefix, so there is no way to prove a prefix unchanged without touching\n * every byte of it at least once). What the cache lets a reader skip is the\n * codec's OWN parsing (`parseEntry`, typically zod validation) and the domain\n * projector's `apply` for every row before the checkpoint: rows that already\n * passed both once, at write time, and whose bytes the chain walk has just\n * proven are unchanged since. Only the checkpoint row itself, and every row\n * after it, go through the full domain path — exactly as an already-open\n * instance that had verified up to there would already do.\n *\n * A snapshot that does not match the journal's actual bytes — a chain that\n * does not reach the claimed hash, a wrong entry count for its byte range —\n * fails loudly with the same kind of `integrityError` a full replay would\n * raise for the same tampered bytes; the tampering is real regardless of\n * which path found it, so it is never swallowed in favor of a fallback that\n * would silently re-read the same bytes a different way. Only a MISSING\n * cache file, or one this journal's current pin cannot vouch for at all\n * (§`journal.ts`'s `seedFromSnapshot`), is treated as \"no cache\" and falls\n * back to full verification.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { LEDGER_HASH_PATTERN, type LedgerHash } from './canonical'\nimport { type LedgerFileContext, removeLedgerFile, writeLedgerFileAtomically } from './journal-file'\nimport type { LedgerTrustedHead } from './trusted-head'\n\n/** A cached projection and the pinned entry it was taken after. */\nexport interface LedgerProjectorSnapshot {\n head: LedgerTrustedHead\n /** Byte length of the journal file up to and including the pinned entry's\n * own row. Where the rows this snapshot covers end and the tail it did not\n * cover begins. */\n byteLength: number\n /** The codec's serialized projection. Opaque to this module. */\n projection: unknown\n}\n\n/** Sibling cache file for a journal, alongside its `.head` pin. */\nexport function projectorSnapshotPathFor(journalPath: string): string {\n return `${journalPath}.snapshot`\n}\n\nconst RECOVERY =\n ' Restore the file, or remove it and let the journal rebuild it at its next checkpoint.'\n\n/** The cached snapshot, or null when none has been written. Present but\n * unparseable is corruption of the cache itself, not its absence, and fails\n * loudly for the same reason `readTrustedHeadFile` does: silently treating it\n * as \"no cache\" would just make the next read replay from scratch without\n * ever explaining why the cache stopped working. */\nexport function readProjectorSnapshotFile(\n path: string,\n context: LedgerFileContext,\n): LedgerProjectorSnapshot | null {\n let text: string\n try {\n text = readFileSync(path, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} could not be read.${RECOVERY}`,\n { cause: error },\n )\n }\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch (error) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} is not valid JSON.${RECOVERY}`,\n { cause: error },\n )\n }\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} is not an object.${RECOVERY}`,\n )\n }\n const record = raw as Record<string, unknown>\n const keys = Object.keys(record).sort()\n if (\n keys.length !== 3 ||\n keys[0] !== 'byteLength' ||\n keys[1] !== 'head' ||\n keys[2] !== 'projection'\n ) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} has keys [${keys.join(', ')}], expected [byteLength, head, projection].${RECOVERY}`,\n )\n }\n const { byteLength, head, projection } = record\n if (typeof byteLength !== 'number' || !Number.isSafeInteger(byteLength) || byteLength <= 0) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} byteLength is not a positive integer.${RECOVERY}`,\n )\n }\n if (typeof head !== 'object' || head === null || Array.isArray(head)) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} head is not an object.${RECOVERY}`,\n )\n }\n const headRecord = head as Record<string, unknown>\n const headKeys = Object.keys(headRecord).sort()\n if (headKeys.length !== 2 || headKeys[0] !== 'entryHash' || headKeys[1] !== 'sequence') {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} head has keys [${headKeys.join(', ')}], expected [entryHash, sequence].${RECOVERY}`,\n )\n }\n const { sequence, entryHash } = headRecord\n if (typeof sequence !== 'number' || !Number.isSafeInteger(sequence) || sequence < 0) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} head.sequence is not a non-negative integer.${RECOVERY}`,\n )\n }\n if (typeof entryHash !== 'string' || !LEDGER_HASH_PATTERN.test(entryHash)) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} head.entryHash is not a sha256 digest.${RECOVERY}`,\n )\n }\n return {\n head: { sequence, entryHash: entryHash as LedgerHash },\n byteLength,\n projection,\n }\n}\n\n/** Publish a snapshot by write-then-rename, so a crash leaves either the\n * previous cache or the new one and never a torn file a reader would have to\n * refuse. Not re-exported from the package's public surface, for the same\n * reason `writeTrustedHeadFile` is not: it takes no lock and enforces no\n * monotonicity against the journal it caches. `FileLedgerJournal` is the only\n * writer, always immediately after its own `sync()` has verified the exact\n * state it is about to cache. */\nexport function writeProjectorSnapshotFile(\n path: string,\n snapshot: LedgerProjectorSnapshot,\n context: LedgerFileContext,\n): void {\n const body = JSON.stringify({\n byteLength: snapshot.byteLength,\n head: snapshot.head,\n projection: snapshot.projection,\n })\n try {\n writeLedgerFileAtomically(path, `${body}\\n`, context)\n } catch (error) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} could not be written`,\n { cause: error },\n )\n }\n}\n\n/** Discard a journal's cached snapshot. A missing cache is not an error: this\n * is how `clearTrustedHead()` keeps the two sidecars from disagreeing about\n * what the journal's writer has vouched for, and it is safe to call whether\n * or not a cache ever existed. */\nexport function removeProjectorSnapshotFile(path: string, context: LedgerFileContext): void {\n removeLedgerFile(path, context)\n removeLedgerFile(`${path}.tmp`, context)\n}\n","/**\n * Trusted head — the pin that makes deletion detectable.\n *\n * ## What the chain binds\n *\n * Every entry hashes the journal header, its sequence, the previous entry's\n * hash, and its event, so editing, reordering, or removing an entry in the\n * middle of a journal invalidates every hash after it. What a hash chain\n * cannot bind is its own length. Dropping entries off the END leaves a shorter\n * journal that is internally perfect, and rebuilding a journal from sequence 0\n * with recomputed hashes produces a different, equally perfect chain. For an\n * audit log of candidate registrations and promotion decisions that is the\n * difference between a record of a search that happened and a record of one\n * that did not.\n *\n * ## What the pin binds\n *\n * `<journal>.head` holds `{sequence, entryHash}` for one entry a writer\n * actually appended, in a file separate from the journal it attests. Each\n * entry hash commits to the entire prefix before it, so checking that the\n * entry at exactly `sequence` still carries `entryHash` proves two things at\n * once: the journal is at least `sequence + 1` entries long, and those entries\n * are byte-for-byte the ones the writer saw. A journal that merely grew past\n * the pin still verifies; a truncated, rolled-back, or wholesale-rewritten one\n * cannot.\n *\n * ## What the pin does NOT defend against\n *\n * The pin is a second file, not a signature. A writer with access to BOTH the\n * journal and its pin can rewrite both consistently, and the result verifies.\n * Pinning raises the cost of undetected tampering from one file to two and\n * nothing more; defending against a writer who holds both requires an anchor\n * outside this store entirely — a signed head, or a digest published to an\n * append-only service the tamperer does not control.\n *\n * Deleting the pin file downgrades a pinned journal to an unpinned one, which\n * cannot be distinguished from a journal written before pinning existed. That\n * is what `requireTrustedHead` is for: a journal opened under it refuses to\n * read at all once a non-empty journal has no pin.\n *\n * ## Abandoning a pin\n *\n * A pin outlives the journal it attests: deleting or rebuilding the journal\n * leaves a pin naming history the file no longer carries, and every read is\n * refused because that is precisely the deletion the pin exists to catch. The\n * refusal names the pin file, and `clearTrustedHeadFile` is the explicit way to\n * discard it — the same downgrade a writer with filesystem access could already\n * perform with `rm`, made reachable through the API so it is a decision in the\n * code rather than an undocumented manual step. It returns the guarantee it\n * gave up and writes no record of its own; a caller that needs the discard on\n * the record has to write one.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { canonicalString, LEDGER_HASH_PATTERN, type LedgerHash } from './canonical'\nimport { type LedgerFileContext, removeLedgerFile, writeLedgerFileAtomically } from './journal-file'\n\n/** A `(sequence, entryHash)` pair a writer pinned outside the journal. */\nexport interface LedgerTrustedHead {\n sequence: number\n entryHash: LedgerHash\n}\n\n/** Minimum entry shape the anchor check needs. */\nexport interface LedgerAnchoredEntry {\n sequence: number\n entryHash: LedgerHash\n}\n\n/** Sibling pin file for a journal — deliberately NOT the journal, so rewriting\n * the log is not enough to rewrite the trust recorded about it. */\nexport function trustedHeadPathFor(journalPath: string): string {\n return `${journalPath}.head`\n}\n\nconst TRUSTED_HEAD_RECOVERY =\n ' Restore the file, or discard the pin it held with clearTrustedHead().'\n\n/** The pin, or null when this journal has never been pinned. A pin that exists\n * but does not parse is corruption or tamper of the trust record itself and\n * fails loudly: reporting it as \"no pin\" would silently downgrade what the\n * journal can prove. */\nexport function readTrustedHeadFile(\n path: string,\n context: LedgerFileContext,\n): LedgerTrustedHead | null {\n let text: string\n try {\n text = readFileSync(path, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null\n throw context.integrityError(\n `${context.subject} trusted head ${path} could not be read.${TRUSTED_HEAD_RECOVERY}`,\n { cause: error },\n )\n }\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch (error) {\n throw context.integrityError(\n `${context.subject} trusted head ${path} is not valid JSON.${TRUSTED_HEAD_RECOVERY}`,\n { cause: error },\n )\n }\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n throw context.integrityError(\n `${context.subject} trusted head ${path} is not an object.${TRUSTED_HEAD_RECOVERY}`,\n )\n }\n const record = raw as Record<string, unknown>\n const keys = Object.keys(record).sort()\n if (keys.length !== 2 || keys[0] !== 'entryHash' || keys[1] !== 'sequence') {\n throw context.integrityError(\n `${context.subject} trusted head ${path} has keys [${keys.join(', ')}], expected [entryHash, sequence].${TRUSTED_HEAD_RECOVERY}`,\n )\n }\n const { sequence, entryHash } = record\n if (typeof sequence !== 'number' || !Number.isSafeInteger(sequence) || sequence < 0) {\n throw context.integrityError(\n `${context.subject} trusted head ${path} sequence is not a non-negative integer.${TRUSTED_HEAD_RECOVERY}`,\n )\n }\n if (typeof entryHash !== 'string' || !LEDGER_HASH_PATTERN.test(entryHash)) {\n throw context.integrityError(\n `${context.subject} trusted head ${path} entryHash is not a sha256 digest.${TRUSTED_HEAD_RECOVERY}`,\n )\n }\n return { sequence, entryHash: entryHash as LedgerHash }\n}\n\n/** Publish a pin by write-then-rename, so a crash leaves either the previous\n * pin or the new one and never a torn file that would lock a journal out of\n * its own trust record.\n *\n * Not re-exported from the package's public surface. It takes no lock, checks no\n * chain, and enforces no monotonicity, so a public form would be the one call\n * able to move a pin BACKWARD onto a journal it never read — which is the\n * truncation the pin exists to refuse. `FileLedgerJournal.pinTrustedHead` is\n * the public writer: locked, chain-verified, forward-only. */\nexport function writeTrustedHeadFile(\n path: string,\n head: LedgerTrustedHead,\n context: LedgerFileContext,\n): void {\n try {\n writeLedgerFileAtomically(path, `${canonicalString(head)}\\n`, context)\n } catch (error) {\n throw context.integrityError(`${context.subject} trusted head ${path} could not be written`, {\n cause: error,\n })\n }\n}\n\n/** Outcome of discarding a pin: the guarantee that was given up. `unreadable`\n * carries why the discarded pin could not be named — corruption, a permission\n * fault, a wrong file type — so a caller recording the decision never has to\n * treat \"no pin was there\" and \"the pin could not be read\" as one state.\n * `cleanupError` reports a stale atomic-write sibling that remains after the\n * actual pin was cleared. */\nexport type LedgerTrustedHeadRemoval =\n | { removed: true; head: LedgerTrustedHead; cleanupError?: string }\n | { removed: true; head: null; unreadable: string; cleanupError?: string }\n | { removed: false; cleanupError?: string }\n\n/** Discard a journal's pin, reporting what was discarded. The journal file is\n * untouched and reads as unpinned afterwards, so the next pinning append opens\n * a new pin at the entry it writes. This gives up the deletion guarantee for\n * every entry the pin covered; it is the recovery for a pin whose journal was\n * deliberately deleted or rebuilt, and the only way past a pin file that can no\n * longer be read at all. */\nexport function clearTrustedHeadFile(\n path: string,\n context: LedgerFileContext,\n): LedgerTrustedHeadRemoval {\n let head: LedgerTrustedHead | null = null\n let unreadable = ''\n try {\n head = readTrustedHeadFile(path, context)\n } catch (error) {\n // A pin nobody can read is precisely what clearing has to get past, so the\n // fault is reported on a removal that still happens rather than raised —\n // but it is reported, never flattened into \"there was no pin\".\n unreadable = error instanceof Error ? error.message : String(error)\n }\n const removed = removeLedgerFile(path, context)\n let cleanupError: string | undefined\n try {\n // Cleanup cannot block the requested trust-state change. Report a stale\n // atomic-write sibling so the caller can repair it before the next write.\n removeLedgerFile(`${path}.tmp`, context)\n } catch (error) {\n cleanupError = error instanceof Error ? error.message : String(error)\n }\n const cleanup = cleanupError === undefined ? {} : { cleanupError }\n if (!removed) return { removed: false, ...cleanup }\n if (head === null) return { removed: true, head: null, unreadable, ...cleanup }\n return { removed: true, head, ...cleanup }\n}\n\n/** How a journal is named when a trusted-head check refuses it. */\nexport interface LedgerTrustedHeadSubject {\n /** The journal in error messages, e.g. `search ledger /runs/a/ledger.jsonl`. */\n subject: string\n /** The sibling pin file, named in every refusal so the operator can see which\n * of the two files carries the claim being enforced. */\n trustedHeadPath: string\n}\n\n/** The entry at exactly `head.sequence` must still carry `head.entryHash`.\n * Entries must already have passed chain verification, which is what makes\n * index and sequence interchangeable here. An array serves as `entries`; a\n * journal that keeps no entries in memory passes a reader with the same\n * `length` and `at`. */\nexport function verifyEntriesAgainstTrustedHead(\n entries: Pick<readonly LedgerAnchoredEntry[], 'length' | 'at'>,\n head: LedgerTrustedHead,\n context: LedgerFileContext,\n naming: LedgerTrustedHeadSubject,\n): void {\n // A caller passing the bare subject string an untyped build would accept\n // destructures into two undefineds, which would corrupt the text of a\n // security refusal rather than fail. Refuse instead.\n if (typeof naming !== 'object' || naming === null) {\n throw new TypeError(\n 'verifyEntriesAgainstTrustedHead expects { subject, trustedHeadPath } as its fourth argument',\n )\n }\n const { subject, trustedHeadPath } = naming\n const pinned = entries.at(head.sequence)\n if (pinned === undefined) {\n throw context.integrityError(\n `${subject} trusted head ${trustedHeadPath} pins sequence ${head.sequence} (${head.entryHash}) but the journal has ${entries.length} entries — pinned history is missing (truncation, rollback, or rewrite). Restore the journal, or abandon the pinned history on purpose with clearTrustedHead().`,\n )\n }\n if (pinned.sequence !== head.sequence) {\n throw context.integrityError(\n `${subject} entry at index ${head.sequence} carries sequence ${pinned.sequence}; the chain was not verified before the trusted head ${trustedHeadPath}`,\n )\n }\n if (pinned.entryHash !== head.entryHash) {\n throw context.integrityError(\n `${subject} entry at pinned sequence ${head.sequence} carries ${pinned.entryHash} but the trusted head ${trustedHeadPath} recorded ${head.entryHash} — the journal was rewritten. Restore the journal, or abandon the pinned history on purpose with clearTrustedHead().`,\n )\n }\n}\n","/**\n * Generic durable append-only journal with a SHA-256 hash chain.\n *\n * The file format is canonical JSONL: every row is the canonical JSON encoding\n * (RFC 8785, object keys sorted recursively) of one entry, and every entry\n * hashes the previous entry's hash so the log is tamper-evident. Appends are\n * serialized in-process per path and across processes via a lock file, fsynced\n * before acknowledgement, and idempotent by `eventId`. A malformed,\n * non-canonical, truncated, reordered, or conflicting log fails loudly; a bad\n * row is never skipped.\n *\n * A hash chain binds each entry to its predecessor, which cannot prove that no\n * entry was removed from the end: a valid shorter prefix is still a valid\n * chain. `pinHead` records the appended entry in a sibling `<journal>.head`\n * file and every read re-verifies the journal against a pin that is present,\n * so truncation and wholesale rewrite are refused. `trusted-head.ts` carries\n * the full threat model, including what a pin does not defend against.\n *\n * Verification is incremental. A journal instance verifies its whole file once,\n * on its first call, and keeps the verified head, the live projector, and an\n * eventId index. Every later call checks that the head line it verified is\n * still in place, then reads, verifies, and projects only the bytes past it, so\n * an append reads one entry however long the journal is. Rows another writer\n * appended are verified as that tail. A file that was replaced, shrank, or no\n * longer carries the verified head is verified whole again. What an open\n * instance cannot see is a same-length rewrite of rows before its head; a new\n * instance verifies every row and refuses one.\n *\n * That \"whole file once\" is still every row, however long ago it was already\n * proven unchanged. A codec that opts into `snapshotProjection` lets a fresh\n * instance shortcut it: `projector-snapshot.ts`'s cache still walks the whole\n * hash chain up to its checkpoint — nothing is exempted from tamper detection\n * — but only the checkpoint row and the true tail after it go through the\n * codec's own parsing and projector; the FileLedgerJournalOptions.projectorSnapshot\n * option controls how often a pinning append refreshes it.\n *\n * Domain vocabulary lives entirely in the consumer's codec: entry schema\n * validation, the constant header fields stamped into every entry, the error\n * taxonomy, and the state machine replayed over verified entries.\n */\n\nimport { closeSync, constants, fstatSync, openSync, readSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { Mutex } from '../concurrency'\nimport { canonicalString, hashCanonical, type LedgerHash } from './canonical'\nimport { deepFreezeCanonicalJson } from './deep-freeze'\nimport { appendLedgerLine, type LedgerFileContext, withLedgerFileLock } from './journal-file'\nimport {\n type LedgerProjectorSnapshot,\n projectorSnapshotPathFor,\n readProjectorSnapshotFile,\n removeProjectorSnapshotFile,\n writeProjectorSnapshotFile,\n} from './projector-snapshot'\nimport {\n clearTrustedHeadFile,\n type LedgerTrustedHead,\n type LedgerTrustedHeadRemoval,\n readTrustedHeadFile,\n trustedHeadPathFor,\n verifyEntriesAgainstTrustedHead,\n writeTrustedHeadFile,\n} from './trusted-head'\n\n/** Minimum shape of a journal event: the idempotency key. */\nexport interface LedgerEventBase {\n eventId: string\n}\n\n/** Chain envelope every entry carries in addition to the journal's constant\n * header fields. `entryHash` covers the header, sequence, previous hash, and\n * event, so any rewrite of history invalidates every later entry. */\nexport interface LedgerChainFields<Event extends LedgerEventBase> {\n sequence: number\n previousHash: LedgerHash | null\n event: Event\n entryHash: LedgerHash\n}\n\nexport type LedgerEntryOf<Header extends object, Event extends LedgerEventBase> = Header &\n LedgerChainFields<Event>\n\nexport interface LedgerLineContext {\n path: string\n line: number\n}\n\n/** Domain state machine applied to chain-verified entries in order.\n *\n * One projector lives as long as its journal instance's verified state: the\n * journal applies each entry once, including entries appended later, and asks\n * for `snapshot()` after any number of them. `apply` throws (via the codec's\n * error taxonomy) on an invalid transition; after a throw the journal discards\n * the projector and replays the file into a new one, so `apply` need not undo\n * a partial update. Entries are deep-frozen before `apply` sees them. */\nexport interface LedgerProjector<Entry, Projection> {\n apply(entry: Entry, index: number): void\n /** The projection of every entry applied so far. A later `apply` must not\n * change a projection already returned, so a snapshot copies any state the\n * projector keeps mutating. */\n snapshot(): Projection\n}\n\n/** Serialize a projection into JSON-safe cache data, and rebuild a projector\n * from it whose next `apply` continues right after the entry it was taken\n * after — as if that projector had been live since sequence 0. Supplying\n * both opts a codec into the projector snapshot cache (`projector-snapshot.ts`):\n * a fresh journal open can then verify the generic hash chain of the rows\n * before a cached checkpoint without parsing or applying any of them through\n * this codec. Omit to disable the cache for this codec; every open then\n * fully replays through `createProjector`, exactly as before. */\nexport interface LedgerProjectorSnapshotCodec<Entry, Projection> {\n serialize(projection: Projection): unknown\n restore(serialized: unknown): LedgerProjector<Entry, Projection>\n}\n\nexport interface LedgerJournalCodec<\n Header extends object,\n Event extends LedgerEventBase,\n Projection,\n> extends LedgerFileContext {\n /** Constant fields stamped into every entry and covered by its hash. */\n header: Header\n conflictError(message: string): Error\n /** Validate one parsed JSON row into a typed entry. Must reject malformed\n * rows and non-canonical event encodings with the binding's own errors;\n * the journal itself verifies the stored bytes and the hash chain. A new\n * entry passes through the same parse before it is written, so the journal\n * never writes a row it would refuse to read. */\n parseEntry(raw: unknown, context: LedgerLineContext): LedgerEntryOf<Header, Event>\n /** Reject an entry whose constant header fields do not match this journal. */\n checkEntryHeader(entry: LedgerEntryOf<Header, Event>, index: number): void\n createProjector(): LedgerProjector<LedgerEntryOf<Header, Event>, Projection>\n snapshotProjection?: LedgerProjectorSnapshotCodec<LedgerEntryOf<Header, Event>, Projection>\n}\n\nexport interface LedgerAppendResult<Entry, Projection> {\n entry: Entry\n /** False when the exact event was already durably present. */\n appended: boolean\n projection: Projection\n}\n\nexport interface LedgerAppendOptions {\n /** Record the appended entry as this journal's trusted head, so a later read\n * can prove nothing was deleted from the end.\n *\n * On the idempotent path — the event is already durable — the pin moves up to\n * that entry only when the entry is ahead of it, along a chain this call has\n * just verified. So a pin write that failed after its row was fsynced is\n * repaired by the retry that idempotency already asks the caller for, and the\n * pin still only ever moves forward over history it has checked.\n *\n * A strict journal whose first pin write failed still refuses the retry\n * because it cannot distinguish that failure from a deleted pin. Recover it\n * explicitly with `pinTrustedHead()`; silently adopting the current file\n * would defeat `requireTrustedHead`. */\n pinHead?: boolean\n}\n\nexport interface FileLedgerJournalOptions {\n /** Refuse to read a non-empty journal that has no trusted head.\n *\n * Off by default because journals written before pinning have no pin and\n * must keep opening. Turn it on for a journal this process pins: without it,\n * deleting the sibling pin file silently downgrades the journal back to a\n * chain that cannot detect deletion. */\n requireTrustedHead?: boolean\n /** Cache a projector snapshot at the trusted head, refreshed once at least\n * this many entries have appended past the last cached one, so the cost\n * amortizes and a fresh open's tail stays bounded by this interval however\n * large the journal grows. Requires the codec's `snapshotProjection`; a\n * codec without it ignores this option and every open fully replays. */\n projectorSnapshot?: { everyEntries: number }\n}\n\n/** The part of a journal file one instance has verified. It is valid only\n * between successful locked calls: any failure discards it, and the next call\n * verifies the whole file again. */\ninterface VerifiedJournal<Entry, Projection> {\n /** Device and inode of the verified file; null until the file exists. */\n identity: { dev: bigint; ino: bigint } | null\n /** Verified byte length, which is where the next entry starts. */\n size: number\n /** Byte offset of each entry's row, indexed by sequence. */\n offsets: number[]\n /** The last entry and its row bytes, newline included. Finding these bytes\n * at the end of the verified length is what lets a call trust every row\n * before them without reading them. */\n head: { entry: Entry; row: Buffer } | null\n sequenceByEventId: Map<string, number>\n projector: LedgerProjector<Entry, Projection>\n /** The pin last verified against this chain, or null when there was none. */\n pin: LedgerTrustedHead | null\n /** Sequence of the last projector snapshot this instance wrote or seeded\n * from, or null when it has not cached one. Tracked in memory so a run of\n * pinning appends checks whether a refresh is due without re-reading the\n * cache file on every one of them. */\n snapshotSequence: number | null\n}\n\n// One async mutex per resolved journal path so concurrent appends from a single\n// process queue up instead of failing on the held cross-process lock file.\nconst journalMutexes = new Map<string, Mutex>()\n\nfunction mutexFor(path: string): Mutex {\n const existing = journalMutexes.get(path)\n if (existing) return existing\n const mutex = new Mutex()\n journalMutexes.set(path, mutex)\n return mutex\n}\n\n/** Durable filesystem journal. Construction performs no I/O. The first call\n * verifies the complete file under the locks; later calls verify the retained\n * head and only the bytes past it (see the module comment). */\nexport class FileLedgerJournal<Header extends object, Event extends LedgerEventBase, Projection> {\n readonly path: string\n /** Sibling file holding this journal's trusted head. */\n readonly trustedHeadPath: string\n /** Sibling file holding this journal's cached projector snapshot, if its\n * codec opts in. */\n readonly projectorSnapshotPath: string\n private readonly codec: LedgerJournalCodec<Header, Event, Projection>\n private readonly mutex: Mutex\n private readonly requireTrustedHead: boolean\n private readonly snapshotEvery: number | null\n private verified: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection> | null = null\n\n constructor(\n path: string,\n codec: LedgerJournalCodec<Header, Event, Projection>,\n options: FileLedgerJournalOptions = {},\n ) {\n this.path = resolve(path)\n this.trustedHeadPath = trustedHeadPathFor(this.path)\n this.projectorSnapshotPath = projectorSnapshotPathFor(this.path)\n this.codec = codec\n this.mutex = mutexFor(this.path)\n this.requireTrustedHead = options.requireTrustedHead === true\n this.snapshotEvery =\n codec.snapshotProjection !== undefined && options.projectorSnapshot !== undefined\n ? options.projectorSnapshot.everyEntries\n : null\n }\n\n async replay(): Promise<Projection> {\n return this.locked(() => this.sync(this.requireTrustedHead).projector.snapshot())\n }\n\n async append(\n event: Event,\n options: LedgerAppendOptions = {},\n ): Promise<LedgerAppendResult<LedgerEntryOf<Header, Event>, Projection>> {\n return this.locked(() => {\n const state = this.sync(this.requireTrustedHead)\n const existingSequence = state.sequenceByEventId.get(event.eventId)\n if (existingSequence !== undefined) {\n const existing = this.entryAt(state, existingSequence)!\n if (canonicalString(existing.event) !== canonicalString(event)) {\n throw this.codec.conflictError(\n `eventId ${event.eventId} already exists with different content`,\n )\n }\n if (options.pinHead === true) this.pinAcknowledged(state, existing)\n return { entry: existing, appended: false, projection: state.projector.snapshot() }\n }\n\n const sequence = state.offsets.length\n const material = {\n ...this.codec.header,\n sequence,\n previousHash: state.head?.entry.entryHash ?? null,\n event,\n }\n const text = canonicalString({ ...material, entryHash: hashCanonical(material) })\n // The new row goes through the reader's own parse and the projector's\n // transition before it is written: a row the journal would refuse to\n // read, or an entry the projector rejects, never reaches the file.\n const entry = parseRow(text, { path: this.path, line: sequence + 1 }, this.codec)\n const row = Buffer.from(`${text}\\n`, 'utf8')\n admitEntry(state, entry, row, this.codec)\n appendLedgerLine(this.path, `${text}\\n`, this.codec)\n if (options.pinHead === true) {\n // Journal first, pin second: a crash or a failed pin write between\n // them leaves the pin one entry behind, which still verifies and is\n // repaired by the next pinning append, including the idempotent\n // retry of this same event. The reverse order would leave a pin\n // naming an entry the journal does not carry, locking the journal\n // out of its own history.\n const head = { sequence: entry.sequence, entryHash: entry.entryHash }\n writeTrustedHeadFile(this.trustedHeadPath, head, this.codec)\n state.pin = head\n this.maybeWriteProjectorSnapshot(state)\n }\n return { entry, appended: true, projection: state.projector.snapshot() }\n })\n }\n\n /** The pinned head, or null when this journal has never been pinned. */\n async trustedHead(): Promise<LedgerTrustedHead | null> {\n return this.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () =>\n readTrustedHeadFile(this.trustedHeadPath, this.codec),\n ),\n )\n }\n\n /** Pin the current verified head. The chain and any existing pin are checked\n * first, so the pin only ever moves forward along a journal that still\n * carries the history it already recorded. */\n async pinTrustedHead(): Promise<LedgerTrustedHead> {\n return this.locked(() => {\n // `requireTrustedHead` is deliberately not applied here: pinning is how\n // a journal that lacks a pin acquires one.\n const state = this.sync(false)\n if (state.head === null) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} is empty; there is no head to pin`,\n )\n }\n const head: LedgerTrustedHead = {\n sequence: state.head.entry.sequence,\n entryHash: state.head.entry.entryHash,\n }\n writeTrustedHeadFile(this.trustedHeadPath, head, this.codec)\n state.pin = head\n // An explicit pin is already a deliberate, infrequent checkpoint call,\n // so — when the caller opted into the cache at all — it always\n // refreshes it rather than waiting for the interval. Gated on\n // `snapshotEvery`, not just the codec's support, so a journal that\n // never asked for `projectorSnapshot` never gets a cache file from\n // this path either; caching stays one on/off decision, not two.\n if (this.snapshotEvery !== null) this.writeProjectorSnapshotNow(state)\n return head\n })\n }\n\n /** Discard this journal's pin, reporting what was discarded. The journal file\n * is untouched and reads as unpinned afterwards, so the next pinning append\n * opens a new pin at the entry it writes. It is the way out of a pin whose\n * journal was deliberately deleted or rebuilt — every read of such a path is\n * refused, correctly, because a pin naming history the file no longer carries\n * is indistinguishable from a deletion. Clearing removes the deletion\n * guarantee for every entry the pin covered. */\n async clearTrustedHead(): Promise<LedgerTrustedHeadRemoval> {\n return this.locked(() => {\n const removal = clearTrustedHeadFile(this.trustedHeadPath, this.codec)\n // A cached snapshot that survived would be pinned to a head this\n // journal no longer vouches for, indistinguishable from a stale one a\n // future re-pin could seed from without earning it. It is not\n // security-critical to remove it — a reader only ever trusts a cached\n // checkpoint the current pin can vouch for — but keeping the sidecars\n // in agreement about what has been given up is the honest state to\n // leave on disk.\n removeProjectorSnapshotFile(this.projectorSnapshotPath, this.codec)\n if (this.verified !== null) {\n this.verified.pin = null\n this.verified.snapshotSequence = null\n }\n return removal\n })\n }\n\n /** Run under both locks. Any failure discards the verified state, because a\n * throw can leave it describing bytes the file does not hold: a projector\n * half way through a rejected transition, or a row whose write failed. */\n private locked<T>(run: () => T): Promise<T> {\n return this.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () => {\n try {\n return run()\n } catch (error) {\n this.verified = null\n throw error\n }\n }),\n )\n }\n\n /** Bring the verified state up to the file: keep it when its head row is\n * still where it was verified, else start over from byte 0; then verify and\n * apply every row past it, and check the pin. */\n private sync(requirePin: boolean): VerifiedJournal<LedgerEntryOf<Header, Event>, Projection> {\n let state = this.verified\n const fd = openForReading(this.path, this.codec)\n if (fd === null) {\n // A missing file is an empty journal, whatever this instance saw before.\n if (state === null || state.size > 0) state = emptyJournal(this.codec)\n this.verified = state\n this.verifyPin(state, requirePin)\n return state\n }\n try {\n const stats = fstatSync(fd, { bigint: true })\n const size = Number(stats.size)\n const identity = { dev: stats.dev, ino: stats.ino }\n if (\n state === null ||\n (state.identity !== null &&\n (state.identity.dev !== identity.dev || state.identity.ino !== identity.ino)) ||\n size < state.size ||\n !headInPlace(fd, state.size, state.head?.row ?? null)\n ) {\n // This is the case a full verification exists to catch — a fresh\n // instance, or one whose retained head is no longer where it was\n // verified — so a cached checkpoint is only ever a shortcut to the\n // SAME conclusion a full replay would reach, never a substitute for\n // reaching it.\n state = (size > 0 ? this.seedFromSnapshot(fd, size) : null) ?? emptyJournal(this.codec)\n }\n state.identity = identity\n this.verified = state\n if (size > state.size) {\n extendJournal(state, readRange(fd, state.size, size), this.path, this.codec)\n }\n } finally {\n closeSync(fd)\n }\n this.verifyPin(state, requirePin)\n return state\n }\n\n private verifyPin(\n state: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>,\n requirePin: boolean,\n ): void {\n const pinned = readTrustedHeadFile(this.trustedHeadPath, this.codec)\n const count = state.offsets.length\n if (pinned === null) {\n state.pin = null\n if (requirePin && count > 0) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has ${count} entries but no trusted head at ${this.trustedHeadPath} — without its pin the journal cannot prove nothing was deleted. Restore the pin file, or adopt the current head with pinTrustedHead().`,\n )\n }\n return\n }\n // A pin already verified against this chain stays verified while the\n // chain's head is in place; sync has just checked that.\n if (state.pin?.sequence === pinned.sequence && state.pin.entryHash === pinned.entryHash) {\n return\n }\n // The anchor is meaningful only over a chain that already verified, so it\n // is checked after sync — and on every call, so a violated pin is refused\n // before an append can extend the journal over it.\n const chain = { length: count, at: (sequence: number) => this.entryAt(state, sequence) }\n verifyEntriesAgainstTrustedHead(chain, pinned, this.codec, {\n subject: `${this.codec.subject} ${this.path}`,\n trustedHeadPath: this.trustedHeadPath,\n })\n state.pin = pinned\n }\n\n /** Move the pin up to an entry this caller just acknowledged on the\n * idempotent path, when a pin write that failed after its row was already\n * fsynced left the pin behind. The move is safe because it is forward-only\n * along a chain `sync` has just verified: every entry up to this one is bound\n * to it by hash, so the pin can only ever come to name more history than it\n * did, never different history.\n *\n * With no pin at all this only pins the journal's current head. An entry in\n * the middle would publish a pin that reads as protection while leaving every\n * later entry silently truncatable, which is a worse state to hand an auditor\n * than the honest absence of a pin; `pinTrustedHead()` is the way to pin an\n * unpinned journal on purpose. */\n private pinAcknowledged(\n state: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>,\n entry: LedgerEntryOf<Header, Event>,\n ): void {\n const pinned = state.pin\n if (pinned === null) {\n if (entry.sequence !== state.offsets.length - 1) return\n } else if (pinned.sequence >= entry.sequence) {\n return\n }\n const head = { sequence: entry.sequence, entryHash: entry.entryHash }\n writeTrustedHeadFile(this.trustedHeadPath, head, this.codec)\n state.pin = head\n this.maybeWriteProjectorSnapshot(state)\n }\n\n /** Refresh the cached projector snapshot once the current pin has moved at\n * least `snapshotEvery` entries past the last one cached, so the write cost\n * amortizes across many appends and a fresh open's uncached tail stays\n * bounded by that interval no matter how large the journal grows. A no-op\n * when the codec does not support the cache, the option is off, or the\n * head this call just pinned is not actually new (the idempotent-append\n * path can call this after re-acknowledging an already-durable entry). */\n private maybeWriteProjectorSnapshot(\n state: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>,\n ): void {\n if (this.codec.snapshotProjection === undefined || this.snapshotEvery === null) return\n if (state.pin === null || state.pin.sequence !== state.head?.entry.sequence) return\n if (\n state.snapshotSequence !== null &&\n state.pin.sequence - state.snapshotSequence < this.snapshotEvery\n ) {\n return\n }\n this.writeProjectorSnapshotNow(state)\n }\n\n /** Serialize the live projector and write it as the cache, unconditionally.\n * Callers have already established that `state.pin` names `state.head`, so\n * the cache and the pin agree on the checkpoint by construction. */\n private writeProjectorSnapshotNow(\n state: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>,\n ): void {\n const head = state.pin!\n const projection = this.codec.snapshotProjection!.serialize(state.projector.snapshot())\n const snapshot: LedgerProjectorSnapshot = { head, byteLength: state.size, projection }\n writeProjectorSnapshotFile(this.projectorSnapshotPath, snapshot, this.codec)\n state.snapshotSequence = head.sequence\n }\n\n /** Seed a fresh verified state from the cached projector snapshot, or null\n * when there is none this reader can use — a missing or out-of-reach\n * cache, never something this instance found actually wrong. Everything it\n * DOES accept is checked against the real bytes: rows 0 through the\n * checkpoint are read and chain-verified exactly as `admitEntry` would\n * verify them (self-consistent hash, correct sequence, linked previousHash,\n * unique eventId), just without this codec's own `parseEntry` or\n * `apply` — the checkpoint row itself still goes through both, through the\n * ordinary `parseRow`, so it is exactly as trustworthy as any entry a full\n * replay would produce. Any mismatch found along the way throws the same\n * `integrityError` a full replay of the same bytes would raise, because it\n * is the same tampering either path would have found; this is never turned\n * into a quiet fallback that would just re-read the same bytes differently\n * and risk reporting a different, more confusing failure — or none. */\n private seedFromSnapshot(\n fd: number,\n size: number,\n ): VerifiedJournal<LedgerEntryOf<Header, Event>, Projection> | null {\n const restore = this.codec.snapshotProjection\n if (restore === undefined) return null\n const cached = readProjectorSnapshotFile(this.projectorSnapshotPath, this.codec)\n if (cached === null) return null\n // Only a cache the CURRENT pin can vouch for is trusted. A pin moves\n // forward only past history that has already chain-verified (sync\n // verifies every appended row before a pinning append can move it), so a\n // cache at or behind the pin names a real, already-proven checkpoint; one\n // ahead of it — or present with no pin at all — names history nothing\n // external currently vouches for, and is ignored rather than trusted.\n const pin = readTrustedHeadFile(this.trustedHeadPath, this.codec)\n if (pin === null || cached.head.sequence > pin.sequence) return null\n if (cached.byteLength <= 0 || cached.byteLength > size) return null\n\n const prefix = readRange(fd, 0, cached.byteLength)\n const rows = splitRows(prefix, this.path, this.codec)\n if (rows.length !== cached.head.sequence + 1) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} projector snapshot ${this.projectorSnapshotPath} expects ${cached.head.sequence + 1} entries in its first ${cached.byteLength} bytes but the journal has ${rows.length}`,\n )\n }\n\n const offsets: number[] = []\n const sequenceByEventId = new Map<string, number>()\n let previousHash: LedgerHash | null = null\n for (let index = 0; index < rows.length - 1; index += 1) {\n const row = rows[index]!\n offsets.push(row.start)\n let raw: unknown\n try {\n raw = JSON.parse(row.text)\n } catch (error) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has invalid JSON at line ${index + 1}`,\n { cause: error },\n )\n }\n if (canonicalString(raw) !== row.text) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has non-canonical bytes at line ${index + 1}`,\n )\n }\n const fields = raw as {\n sequence?: unknown\n previousHash?: unknown\n entryHash?: unknown\n event?: { eventId?: unknown }\n }\n if (fields.sequence !== index) {\n throw this.codec.integrityError(\n `entry at line ${index + 1} has sequence ${String(fields.sequence)}, expected ${index}`,\n )\n }\n if ((fields.previousHash ?? null) !== previousHash) {\n throw this.codec.integrityError(\n `entry at line ${index + 1} does not extend the previous hash`,\n )\n }\n const { entryHash, ...material } = raw as Record<string, unknown>\n const expected = hashCanonical(material)\n if (entryHash !== expected) {\n throw this.codec.integrityError(\n `entry at line ${index + 1} hash mismatch: expected ${expected}, got ${String(entryHash)}`,\n )\n }\n const eventId = fields.event?.eventId\n if (typeof eventId !== 'string' || eventId === '') {\n throw this.codec.integrityError(`entry at line ${index + 1} has no eventId`)\n }\n if (sequenceByEventId.has(eventId)) {\n throw this.codec.integrityError(`duplicate eventId ${eventId} in durable ledger`)\n }\n sequenceByEventId.set(eventId, index)\n previousHash = entryHash as LedgerHash\n }\n\n // The checkpoint row itself carries this codec's own validation, exactly\n // like any other entry — the cache never substitutes for parsing it.\n const boundary = rows[rows.length - 1]!\n offsets.push(boundary.start)\n const entry = parseRow(\n boundary.text,\n { path: this.path, line: cached.head.sequence + 1 },\n this.codec,\n )\n const { entryHash: _boundaryHash, ...boundaryMaterial } = entry\n if (\n entry.sequence !== cached.head.sequence ||\n entry.previousHash !== previousHash ||\n entry.entryHash !== cached.head.entryHash ||\n hashCanonical(boundaryMaterial) !== cached.head.entryHash\n ) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} projector snapshot ${this.projectorSnapshotPath} does not match the journal at sequence ${cached.head.sequence}`,\n )\n }\n this.codec.checkEntryHeader(entry, cached.head.sequence)\n if (sequenceByEventId.has(entry.event.eventId)) {\n throw this.codec.integrityError(`duplicate eventId ${entry.event.eventId} in durable ledger`)\n }\n sequenceByEventId.set(entry.event.eventId, entry.sequence)\n\n let projector: LedgerProjector<LedgerEntryOf<Header, Event>, Projection>\n try {\n projector = restore.restore(cached.projection)\n } catch (error) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} projector snapshot ${this.projectorSnapshotPath} could not be restored`,\n { cause: error },\n )\n }\n\n return {\n identity: null,\n size: cached.byteLength,\n offsets,\n head: { entry, row: Buffer.from(`${boundary.text}\\n`, 'utf8') },\n sequenceByEventId,\n projector,\n pin: null,\n snapshotSequence: cached.head.sequence,\n }\n }\n\n /** The verified entry at `sequence`, read back from the file. The rows from\n * it to the head are re-read and must chain to the verified head hash, which\n * binds the returned entry to the history this instance verified. Callers ask\n * for recent entries — an idempotent retry, a pin one entry behind — so this\n * usually reads nothing or one row. */\n private entryAt(\n state: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>,\n sequence: number,\n ): LedgerEntryOf<Header, Event> | undefined {\n const count = state.offsets.length\n if (!Number.isSafeInteger(sequence) || sequence < 0 || sequence >= count) return undefined\n if (sequence === count - 1) return state.head!.entry\n const changed = () =>\n this.codec.integrityError(\n `${this.codec.subject} ${this.path} changed at or after sequence ${sequence} since this reader verified it`,\n )\n const fd = openForReading(this.path, this.codec)\n if (fd === null) throw changed()\n let bytes: Buffer\n try {\n bytes = readRange(fd, state.offsets[sequence]!, state.size)\n } finally {\n closeSync(fd)\n }\n const rows = splitRows(bytes, this.path, this.codec)\n if (rows.length !== count - sequence) throw changed()\n let first: LedgerEntryOf<Header, Event> | undefined\n let previous: LedgerEntryOf<Header, Event> | undefined\n for (let index = 0; index < rows.length; index += 1) {\n const entry = parseRow(\n rows[index]!.text,\n { path: this.path, line: sequence + index + 1 },\n this.codec,\n )\n const { entryHash, ...material } = entry\n if (\n entry.sequence !== sequence + index ||\n hashCanonical(material) !== entryHash ||\n (previous !== undefined && entry.previousHash !== previous.entryHash)\n ) {\n throw changed()\n }\n first ??= entry\n previous = entry\n }\n if (previous?.entryHash !== state.head!.entry.entryHash) throw changed()\n return first\n }\n}\n\n/** Where a memory journal keeps its text: an in-process store keyed by path,\n * such as an in-memory `CampaignStorage`. */\nexport interface LedgerTextStore {\n read(path: string): string | undefined\n write(path: string, text: string): void\n}\n\n/**\n * A journal for runs without a filesystem. It keeps its rows as text in a\n * store and applies the file journal's rules: the same row parse, hash chain,\n * idempotent append by `eventId`, and projector transition before a row is\n * kept. It has no lock, fsync or trusted head, because its rows live and die\n * with the process that holds the store.\n */\nexport class MemoryLedgerJournal<Header extends object, Event extends LedgerEventBase, Projection> {\n readonly path: string\n private readonly codec: LedgerJournalCodec<Header, Event, Projection>\n private readonly store: LedgerTextStore\n private verified: {\n text: string\n journal: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>\n entries: LedgerEntryOf<Header, Event>[]\n } | null = null\n\n constructor(\n path: string,\n codec: LedgerJournalCodec<Header, Event, Projection>,\n store: LedgerTextStore,\n ) {\n this.path = path\n this.codec = codec\n this.store = store\n }\n\n async replay(): Promise<Projection> {\n return this.guarded(() => this.sync().journal.projector.snapshot())\n }\n\n async append(\n event: Event,\n ): Promise<LedgerAppendResult<LedgerEntryOf<Header, Event>, Projection>> {\n return this.guarded(() => {\n const verified = this.sync()\n const { journal, entries } = verified\n const existingSequence = journal.sequenceByEventId.get(event.eventId)\n if (existingSequence !== undefined) {\n const existing = entries[existingSequence]!\n if (canonicalString(existing.event) !== canonicalString(event)) {\n throw this.codec.conflictError(\n `eventId ${event.eventId} already exists with different content`,\n )\n }\n return { entry: existing, appended: false, projection: journal.projector.snapshot() }\n }\n const sequence = entries.length\n const material = {\n ...this.codec.header,\n sequence,\n previousHash: journal.head?.entry.entryHash ?? null,\n event,\n }\n const text = canonicalString({ ...material, entryHash: hashCanonical(material) })\n const entry = parseRow(text, { path: this.path, line: sequence + 1 }, this.codec)\n admitEntry(journal, entry, Buffer.from(`${text}\\n`, 'utf8'), this.codec)\n entries.push(entry)\n verified.text = `${verified.text}${text}\\n`\n this.store.write(this.path, verified.text)\n return { entry, appended: true, projection: journal.projector.snapshot() }\n })\n }\n\n /** Verify the stored text again whenever it is not the text this instance wrote. */\n private sync(): NonNullable<MemoryLedgerJournal<Header, Event, Projection>['verified']> {\n const text = this.store.read(this.path) ?? ''\n if (this.verified?.text === text) return this.verified\n const journal = emptyJournal(this.codec)\n const entries: LedgerEntryOf<Header, Event>[] = []\n const bytes = Buffer.from(text, 'utf8')\n for (const row of splitRows(bytes, this.path, this.codec)) {\n const entry = parseRow(row.text, { path: this.path, line: entries.length + 1 }, this.codec)\n admitEntry(journal, entry, Buffer.from(bytes.subarray(row.start, row.end)), this.codec)\n entries.push(entry)\n }\n this.verified = { text, journal, entries }\n return this.verified\n }\n\n /** A refused transition can leave the projector half applied; discard it. */\n private async guarded<T>(run: () => T): Promise<T> {\n try {\n return run()\n } catch (error) {\n this.verified = null\n throw error\n }\n }\n}\n\n/** Verify and replay resolved immutable journal bytes without filesystem I/O. */\nexport function replayLedgerText<Header extends object, Event extends LedgerEventBase, Projection>(\n text: string,\n path: string,\n codec: LedgerJournalCodec<Header, Event, Projection>,\n): Projection {\n const state = emptyJournal(codec)\n extendJournal(state, Buffer.from(text, 'utf8'), path, codec)\n return state.projector.snapshot()\n}\n\nfunction emptyJournal<Header extends object, Event extends LedgerEventBase, Projection>(\n codec: LedgerJournalCodec<Header, Event, Projection>,\n): VerifiedJournal<LedgerEntryOf<Header, Event>, Projection> {\n return {\n identity: null,\n size: 0,\n offsets: [],\n head: null,\n sequenceByEventId: new Map(),\n projector: codec.createProjector(),\n pin: null,\n snapshotSequence: null,\n }\n}\n\n/** Verify and apply the rows in `bytes`, which start at the state's verified\n * length. */\nfunction extendJournal<Header extends object, Event extends LedgerEventBase, Projection>(\n state: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>,\n bytes: Buffer,\n path: string,\n codec: LedgerJournalCodec<Header, Event, Projection>,\n): void {\n const rows = splitRows(bytes, path, codec)\n for (const { text, start, end } of rows) {\n const entry = parseRow(text, { path, line: state.offsets.length + 1 }, codec)\n // Copy the row: a view would keep the whole read buffer alive.\n admitEntry(state, entry, Buffer.from(bytes.subarray(start, end)), codec)\n }\n}\n\n/** Check one parsed entry against the chain and apply it. Every row, read or\n * about to be written, enters the verified state here. */\nfunction admitEntry<Header extends object, Event extends LedgerEventBase, Projection>(\n state: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>,\n entry: LedgerEntryOf<Header, Event>,\n row: Buffer,\n codec: LedgerJournalCodec<Header, Event, Projection>,\n): void {\n const index = state.offsets.length\n codec.checkEntryHeader(entry, index)\n if (entry.sequence !== index) {\n throw codec.integrityError(\n `entry ${entry.event.eventId} has sequence ${entry.sequence}, expected ${index}`,\n )\n }\n if (entry.previousHash !== (state.head?.entry.entryHash ?? null)) {\n throw codec.integrityError(`entry ${entry.event.eventId} does not extend the previous hash`)\n }\n const { entryHash: _entryHash, ...material } = entry\n const expectedHash = hashCanonical(material)\n if (entry.entryHash !== expectedHash) {\n throw codec.integrityError(\n `entry ${entry.event.eventId} hash mismatch: expected ${expectedHash}, got ${entry.entryHash}`,\n )\n }\n if (state.sequenceByEventId.has(entry.event.eventId)) {\n throw codec.integrityError(`duplicate eventId ${entry.event.eventId} in durable ledger`)\n }\n state.projector.apply(entry, index)\n state.sequenceByEventId.set(entry.event.eventId, index)\n state.offsets.push(state.size)\n state.size += row.byteLength\n state.head = { entry, row }\n}\n\n/** Parse one canonical row into a frozen entry. The projector and every caller\n * share entries, so none of them can change what the journal verified. */\nfunction parseRow<Header extends object, Event extends LedgerEventBase, Projection>(\n text: string,\n context: LedgerLineContext,\n codec: LedgerJournalCodec<Header, Event, Projection>,\n): LedgerEntryOf<Header, Event> {\n const { path, line } = context\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch (error) {\n throw codec.integrityError(`${codec.subject} ${path} has invalid JSON at line ${line}`, {\n cause: error,\n })\n }\n const entry = codec.parseEntry(raw, context)\n let canonical: string\n try {\n canonical = canonicalString(entry)\n } catch (error) {\n throw codec.integrityError(\n `${codec.subject} ${path} has a row with no canonical JSON form at line ${line}`,\n { cause: error },\n )\n }\n if (text !== canonical) {\n throw codec.integrityError(`${codec.subject} ${path} has non-canonical bytes at line ${line}`)\n }\n return deepFreezeCanonicalJson(entry)\n}\n\ninterface JournalRow {\n text: string\n /** Byte range of the row in the buffer, newline included. */\n start: number\n end: number\n}\n\nfunction splitRows(bytes: Buffer, path: string, context: LedgerFileContext): JournalRow[] {\n if (bytes.byteLength === 0) return []\n if (bytes[bytes.byteLength - 1] !== 0x0a) {\n throw context.integrityError(\n `${context.subject} ${path} has a truncated final record (missing newline)`,\n )\n }\n const rows: JournalRow[] = []\n let start = 0\n while (start < bytes.byteLength) {\n const newline = bytes.indexOf(0x0a, start)\n if (newline === start) {\n throw context.integrityError(\n `${context.subject} ${path} has a blank row at line ${rows.length + 1}`,\n )\n }\n rows.push({ text: bytes.toString('utf8', start, newline), start, end: newline + 1 })\n start = newline + 1\n }\n return rows\n}\n\n/** True when the verified head row still ends the verified length of the file. */\nfunction headInPlace(fd: number, size: number, row: Buffer | null): boolean {\n return row === null || readRange(fd, size - row.byteLength, size).equals(row)\n}\n\n/** A read-only descriptor, or null when the file does not exist. */\nfunction openForReading(path: string, context: LedgerFileContext): number | null {\n try {\n return openSync(path, constants.O_RDONLY)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null\n throw context.integrityError(`${context.subject} ${path} could not be opened for reading`, {\n cause: error,\n })\n }\n}\n\nfunction readRange(fd: number, start: number, end: number): Buffer {\n const bytes = Buffer.allocUnsafe(end - start)\n let offset = 0\n while (offset < bytes.byteLength) {\n const read = readSync(fd, bytes, offset, bytes.byteLength - offset, start + offset)\n if (read === 0) return bytes.subarray(0, offset)\n offset += read\n }\n return bytes\n}\n"],"mappings":";;;;;;;;AAoDA,IAAa,sBAAb,cAAyC,MAAM;CAC7C,OAAyB;AAC3B;;AAQA,SAAgB,oBACd,SACkC;CAClC,IAAI,WAAW,aAAa,QAAQ,QAAQ,CAAC,GAAG,OAAO;EAAE,UAAU;EAAO,QAAQ;CAAW;CAC7F,MAAM,QAAQ,WAAW,QAAQ,QAAQ;CACzC,IAAI,MAAM,UAAU,QAClB,OAAO;EAAE,UAAU;EAAO,QAAQ;EAAQ,QAAQ,MAAM;CAAM;CAEhE,OAAO;AACT;;;;;;;AAQA,SAAgB,yBACd,SAC2B;CAC3B,MAAM,MAAM,QAAQ,OAAO,QAAQ;CACnC,IAAI,CAAC,OAAO,cAAc,GAAG,KAAK,OAAO,GACvC,MAAM,IAAI,oBAAoB,iDAAiD;CAEjF,MAAM,QAA6B;EAAE,GAAG,uBAAuB,GAAG;EAAG,OAAO,WAAW;CAAE;CACzF,KAAK,IAAI,UAAU,GAAG,UAAU,GAAG,WAAW,GAAG;EAC/C,IAAI,WAAW,aAAa,QAAQ,QAAQ,CAAC,GAAG;GAC9C,MAAM,WAAW,wBAAwB,QAAQ,UAAU,OAAO,OAAO;GACzE,IAAI,CAAC,UAAU,OAAO;IAAE,UAAU;IAAO,QAAQ;GAAW;GAC5D,IAAI;IACF,OAAO,YAAY,QAAQ,UAAU,OAAO,OAAO;GACrD,UAAU;IACR,SAAS,QAAQ;GACnB;EACF;EACA,IAAI,aAAa,QAAQ,UAAU,OAAO,WAAW,SAAS,GAC5D,OAAO,SAAS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AI,OAAO,QAAQ,MAAM,aAAa,QAAQ,QAAQ,MAAM;EAClF,IAAI,SAAS,GAAG,OAAO,MAAM,SAAS,GAAG,MAAM;EAC/C,UAAU;CACZ;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"journal-C1uLJi0w.js","names":[],"sources":["../src/concurrency.ts","../src/ledger-core/atomic-file-lock.ts","../src/ledger-core/journal-file.ts","../src/ledger-core/projector-snapshot.ts","../src/ledger-core/trusted-head.ts","../src/ledger-core/journal.ts"],"sourcesContent":["/**\n * concurrency — small primitives the evolution loop needs.\n *\n * `Mutex` is a zero-dep async lock with FIFO fairness. The evolution loop\n * uses it to serialise checkout/build/commit sequences inside a single\n * pool slot, and to gate concurrent JSONL writers (see\n * `lockedJsonlReferenceReplayStore`).\n *\n * Deliberately minimal — no priority queue, no timeouts. If you need\n * those, swap to `async-mutex` at the call site.\n */\n\nexport class Mutex {\n private locked = false\n private readonly waiters: Array<() => void> = []\n\n async acquire(): Promise<() => void> {\n if (!this.locked) {\n this.locked = true\n return () => this.release()\n }\n return new Promise<() => void>((resolve) => {\n this.waiters.push(() => {\n resolve(() => this.release())\n })\n })\n }\n\n private release(): void {\n const next = this.waiters.shift()\n if (next) {\n next()\n } else {\n this.locked = false\n }\n }\n\n async runExclusive<T>(fn: () => Promise<T> | T): Promise<T> {\n const release = await this.acquire()\n try {\n return await fn()\n } finally {\n release()\n }\n }\n\n /** True iff someone holds the lock right now. Diagnostics only. */\n get isLocked(): boolean {\n return this.locked\n }\n\n /** Pending waiter count. Diagnostics only. */\n get pending(): number {\n return this.waiters.length\n }\n}\n\ninterface MapConcurrentRangeOptions<R> {\n count: number\n maxConcurrency: number\n label: string\n signal?: AbortSignal\n map(index: number, signal: AbortSignal): Promise<R>\n}\n\n/** Map an integer range with bounded work, cancellation, and first-error cleanup. */\nexport async function mapConcurrentRange<R>(options: MapConcurrentRangeOptions<R>): Promise<R[]> {\n if (!Number.isSafeInteger(options.count) || options.count < 0) {\n throw new Error(`${options.label} count must be a non-negative integer`)\n }\n if (!Number.isSafeInteger(options.maxConcurrency) || options.maxConcurrency < 1) {\n throw new Error(`${options.label} maxConcurrency must be a positive integer`)\n }\n\n const controller = new AbortController()\n const abortFromCaller = () => controller.abort(options.signal?.reason)\n if (options.signal?.aborted) abortFromCaller()\n else options.signal?.addEventListener('abort', abortFromCaller, { once: true })\n\n const results = new Array<R>(options.count)\n let nextIndex = 0\n let failed = false\n let firstFailure: unknown\n const workers = Array.from(\n { length: Math.min(options.maxConcurrency, options.count) },\n async () => {\n while (!controller.signal.aborted) {\n const index = nextIndex\n nextIndex += 1\n if (index >= options.count) return\n try {\n results[index] = await options.map(index, controller.signal)\n } catch (error) {\n if (!failed) {\n failed = true\n firstFailure = error\n controller.abort(error)\n }\n return\n }\n }\n },\n )\n\n try {\n await Promise.all(workers)\n if (options.signal?.aborted) throw abortError(options.signal, options.label)\n if (failed) throw firstFailure\n if (controller.signal.aborted) throw abortError(controller.signal, options.label)\n return results\n } finally {\n options.signal?.removeEventListener('abort', abortFromCaller)\n }\n}\n\n/**\n * Map independent work with a fixed worker count while preserving input order.\n * After the first rejection, no new items start; already-running work is allowed\n * to settle before the returned promise rejects. Partial results are discarded.\n */\nexport async function mapConcurrent<T, R>(\n items: readonly T[],\n concurrency: number,\n map: (item: T, index: number, signal: AbortSignal) => Promise<R>,\n signal?: AbortSignal,\n): Promise<R[]> {\n return mapConcurrentRange({\n count: items.length,\n maxConcurrency: concurrency,\n label: 'mapConcurrent',\n signal,\n map(index, signal) {\n return map(items[index]!, index, signal)\n },\n })\n}\n\nfunction abortError(signal: AbortSignal, label: string): Error {\n return signal.reason instanceof Error ? signal.reason : new Error(`${label} aborted`)\n}\n","/** Crash-safe filesystem lock shared by campaign persistence and run exclusion. */\n\nimport { randomUUID } from 'node:crypto'\nimport {\n closeSync,\n constants,\n existsSync,\n fstatSync,\n fsyncSync,\n linkSync,\n openSync,\n readFileSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport {\n type LockHolderIdentity,\n type LockHolderRecord,\n type LockIdentity,\n lockHolderVerdict,\n lockIdentity,\n parseLockHolderRecord,\n readLockHolderIdentity,\n} from './lock-holder'\n\n/**\n * The holder of a lock path. The lock file holds this record plus the identity\n * of its own inode, so `lockHolderVerdict` can prove a crashed holder dead.\n */\nexport interface AtomicFileLockOwner extends LockHolderIdentity {\n readonly nonce: string\n}\n\nexport interface AtomicFileLock {\n readonly owner: AtomicFileLockOwner\n release(): void\n}\n\nexport type AtomicFileLockUnavailable =\n | { readonly acquired: false; readonly reason: 'held'; readonly holder: AtomicFileLockOwner }\n | { readonly acquired: false; readonly reason: 'recovery' }\n\nexport type AtomicFileLockAcquisition =\n | { readonly acquired: true; readonly lock: AtomicFileLock }\n | AtomicFileLockUnavailable\n\nexport interface AtomicFileLockOptions {\n readonly lockPath: string\n readonly pid?: number\n}\n\nexport class AtomicFileLockError extends Error {\n override readonly name = 'AtomicFileLockError'\n}\n\ntype OwnerState =\n | { readonly state: 'missing' }\n | { readonly state: 'stale'; readonly owner: AtomicFileLockOwner }\n | { readonly state: 'held'; readonly owner: AtomicFileLockOwner }\n\n/** Report whether another lock path prevents acquisition without modifying it. */\nexport function probeAtomicFileLock(\n options: AtomicFileLockOptions,\n): AtomicFileLockUnavailable | null {\n if (existsSync(recoveryPath(options.lockPath))) return { acquired: false, reason: 'recovery' }\n const state = ownerState(options.lockPath)\n if (state.state === 'held') {\n return { acquired: false, reason: 'held', holder: state.owner }\n }\n return null\n}\n\n/**\n * Try to acquire a complete, uniquely-owned lock inode.\n *\n * A hard link publishes fully-written owner metadata atomically. Stale-owner\n * removal is serialized so one reclaimer cannot delete a new owner's lock.\n */\nexport function tryAcquireAtomicFileLock(\n options: AtomicFileLockOptions,\n): AtomicFileLockAcquisition {\n const pid = options.pid ?? process.pid\n if (!Number.isSafeInteger(pid) || pid <= 0) {\n throw new AtomicFileLockError('atomic file lock pid must be a positive integer')\n }\n const owner: AtomicFileLockOwner = { ...readLockHolderIdentity(pid), nonce: randomUUID() }\n for (let attempt = 0; attempt < 8; attempt += 1) {\n if (existsSync(recoveryPath(options.lockPath))) {\n const recovery = tryAcquireRecoveryLease(options.lockPath, owner, attempt)\n if (!recovery) return { acquired: false, reason: 'recovery' }\n try {\n return recoverLock(options.lockPath, owner, attempt)\n } finally {\n recovery.release()\n }\n }\n if (tryLinkOwner(options.lockPath, owner, `acquire.${attempt}`)) {\n return acquired(options.lockPath, owner)\n }\n\n const holder = ownerState(options.lockPath)\n if (holder.state === 'missing') continue\n if (holder.state === 'held') {\n return { acquired: false, reason: 'held', holder: holder.owner }\n }\n\n const recovery = tryAcquireRecoveryLease(options.lockPath, owner, attempt)\n if (!recovery) return { acquired: false, reason: 'recovery' }\n try {\n return recoverLock(options.lockPath, owner, attempt)\n } finally {\n recovery.release()\n }\n }\n\n throw new AtomicFileLockError(`could not acquire atomic file lock ${options.lockPath}`)\n}\n\ninterface RecoveryLease {\n release(): void\n}\n\nfunction tryAcquireRecoveryLease(\n lockPath: string,\n owner: AtomicFileLockOwner,\n attempt: number,\n): RecoveryLease | null {\n let leasePath = recoveryPath(lockPath)\n const staleOwners: Array<{ path: string; owner: AtomicFileLockOwner }> = []\n\n for (let depth = 0; depth < 64; depth += 1) {\n const state = ownerState(leasePath)\n if (state.state === 'missing') {\n if (!tryLinkOwner(leasePath, owner, `reclaim.${attempt}.${depth}`)) continue\n return {\n release: () => {\n for (const stale of staleOwners) releaseOwnedPath(stale.path, stale.owner)\n releaseOwnedPath(leasePath, owner)\n },\n }\n }\n if (state.state === 'held') return null\n staleOwners.push({ path: leasePath, owner: state.owner })\n leasePath = `${leasePath}.next.${state.owner.nonce}`\n }\n\n throw new AtomicFileLockError(`atomic file lock recovery chain is too deep (${lockPath})`)\n}\n\nfunction recoverLock(\n lockPath: string,\n owner: AtomicFileLockOwner,\n attempt: number,\n): AtomicFileLockAcquisition {\n const current = ownerState(lockPath)\n if (current.state === 'held') {\n return { acquired: false, reason: 'held', holder: current.owner }\n }\n if (current.state === 'stale') {\n const tombstone = `${lockPath}.stale.${owner.nonce}.${attempt}`\n try {\n renameSync(lockPath, tombstone)\n unlinkSync(tombstone)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n }\n if (tryLinkOwner(lockPath, owner, `recovered.${attempt}`)) {\n return acquired(lockPath, owner)\n }\n const holder = ownerState(lockPath)\n if (holder.state === 'held') {\n return { acquired: false, reason: 'held', holder: holder.owner }\n }\n return { acquired: false, reason: 'recovery' }\n}\n\nfunction acquired(lockPath: string, owner: AtomicFileLockOwner): AtomicFileLockAcquisition {\n return {\n acquired: true,\n lock: {\n owner,\n release: () => releaseOwnedPath(lockPath, owner),\n },\n }\n}\n\nfunction tryLinkOwner(lockPath: string, owner: AtomicFileLockOwner, suffix: string): boolean {\n const ownerPath = `${lockPath}.${owner.pid}.${owner.nonce}.${suffix}.owner`\n const descriptor = openSync(\n ownerPath,\n constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY,\n 0o600,\n )\n try {\n // A hard link keeps the inode, so this identity is the lock path's once linked.\n const lock = lockIdentity(fstatSync(descriptor, { bigint: true }))\n writeFileSync(descriptor, `${JSON.stringify({ ...owner, lock })}\\n`, 'utf8')\n fsyncSync(descriptor)\n } catch (error) {\n closeSync(descriptor)\n unlinkIfExists(ownerPath)\n throw error\n }\n closeSync(descriptor)\n\n try {\n linkSync(ownerPath, lockPath)\n return true\n } catch (error) {\n if (!isAlreadyExists(error)) throw error\n return false\n } finally {\n unlinkIfExists(ownerPath)\n }\n}\n\n/** Only a holder proved dead is stale; an alive or unknown holder keeps the lock. */\nfunction ownerState(lockPath: string): OwnerState {\n const current = readOwner(lockPath)\n if (!current) return { state: 'missing' }\n const verdict = lockHolderVerdict(current.record, current.identity)\n return { state: verdict.liveness === 'dead' ? 'stale' : 'held', owner: current.owner }\n}\n\ninterface LockFileOwner {\n readonly owner: AtomicFileLockOwner\n readonly record: LockHolderRecord & { readonly nonce: string }\n /** The inode the record was read from, so a verdict compares it with the recorded lock. */\n readonly identity: LockIdentity\n}\n\nfunction readOwner(lockPath: string): LockFileOwner | undefined {\n let descriptor: number\n try {\n descriptor = openSync(lockPath, 'r')\n } catch (error) {\n if (isMissing(error)) return undefined\n throw error\n }\n let contents: string\n let identity: LockIdentity\n try {\n identity = lockIdentity(fstatSync(descriptor, { bigint: true }))\n contents = readFileSync(descriptor, 'utf8').trim()\n } finally {\n closeSync(descriptor)\n }\n\n let value: unknown\n try {\n value = JSON.parse(contents)\n } catch (error) {\n throw invalidOwner(lockPath, error)\n }\n const record = parseOwnerRecord(value)\n if (!record) throw invalidOwner(lockPath)\n const { lock: _lock, ...owner } = record\n return { owner, record, identity }\n}\n\n/**\n * Accept exactly the fields a lock owner writes: a holder record that parses\n * whole, plus the nonce. A record from before holder identity carried only pid,\n * host and nonce; it still parses, and its holder is never proved dead.\n */\nfunction parseOwnerRecord(value: unknown): LockFileOwner['record'] | undefined {\n const holder = parseLockHolderRecord(value)\n if (!holder) return undefined\n const { nonce, ...rest } = value as Record<string, unknown>\n if (typeof nonce !== 'string' || nonce.trim().length === 0) return undefined\n // A field the holder parse dropped is malformed; refuse it instead of guessing.\n if (Object.keys(rest).length !== Object.keys(holder).length) return undefined\n return { ...holder, nonce }\n}\n\nfunction invalidOwner(lockPath: string, cause?: unknown): AtomicFileLockError {\n const error = new AtomicFileLockError(\n `atomic file lock has an invalid owner (${lockPath}); refusing unsafe recovery`,\n )\n if (cause !== undefined) Object.defineProperty(error, 'cause', { value: cause })\n return error\n}\n\nfunction releaseOwnedPath(lockPath: string, owner: AtomicFileLockOwner): void {\n const current = readOwner(lockPath)\n if (!current) return\n if (canonicalOwner(current.owner) !== canonicalOwner(owner)) {\n throw new AtomicFileLockError(`atomic file lock owner changed before release (${lockPath})`)\n }\n try {\n unlinkSync(lockPath)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n}\n\nfunction canonicalOwner(owner: AtomicFileLockOwner): string {\n return JSON.stringify({ host: owner.host, nonce: owner.nonce, pid: owner.pid })\n}\n\nfunction recoveryPath(lockPath: string): string {\n return `${lockPath}.reclaim`\n}\n\nfunction isAlreadyExists(error: unknown): boolean {\n return error instanceof Error && 'code' in error && error.code === 'EEXIST'\n}\n\nfunction isMissing(error: unknown): boolean {\n return error instanceof Error && 'code' in error && error.code === 'ENOENT'\n}\n\nfunction unlinkIfExists(path: string): void {\n try {\n unlinkSync(path)\n } catch (error) {\n if (!isMissing(error)) throw error\n }\n}\n","/** Filesystem durability and cross-process exclusion for append-only journal files. */\n\nimport {\n closeSync,\n constants,\n fstatSync,\n fsyncSync,\n mkdirSync,\n openSync,\n readSync,\n renameSync,\n rmSync,\n writeSync,\n} from 'node:fs'\nimport { dirname } from 'node:path'\nimport { AtomicFileLockError, tryAcquireAtomicFileLock } from './atomic-file-lock'\n\n/** How a journal binding reports file-layer faults in its own error taxonomy. */\nexport interface LedgerFileContext {\n /** Noun used in error messages, e.g. 'search ledger'. */\n subject: string\n integrityError(message: string, options?: { cause?: unknown }): Error\n}\n\n/** Append one already-serialized line; the write is fsynced (file and directory)\n * before returning so an acknowledged append survives a crash. */\nexport function appendLedgerLine(path: string, line: string, context: LedgerFileContext): void {\n mkdirSync(dirname(path), { recursive: true })\n recoverTornFinalWrite(path, context)\n const fd = openSync(path, constants.O_CREAT | constants.O_WRONLY | constants.O_APPEND, 0o600)\n try {\n writeAll(fd, Buffer.from(line, 'utf8'), context)\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n fsyncDirectory(dirname(path))\n}\n\nfunction recoverTornFinalWrite(path: string, context: LedgerFileContext): void {\n let fd: number\n try {\n fd = openSync(path, constants.O_RDWR)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return\n throw context.integrityError(`${context.subject} ${path} could not be opened for recovery`, {\n cause: error,\n })\n }\n\n try {\n const size = fstatSync(fd).size\n if (size === 0 || readByte(fd, size - 1) === 0x0a) return\n const tailStart = findFinalLineStart(fd, size)\n const replacement = Buffer.alloc(size - tailStart, 0x20)\n replacement[replacement.length - 1] = 0x0a\n writeAllAt(fd, replacement, tailStart, context)\n fsyncSync(fd)\n } catch (error) {\n throw context.integrityError(\n `${context.subject} ${path} has an unrecoverable final journal write`,\n { cause: error },\n )\n } finally {\n closeSync(fd)\n }\n}\n\n/** Replace a small sidecar file whole: write a temporary sibling, fsync it,\n * then rename over the target. A reader therefore sees the previous contents\n * or the new ones, never a partial file. */\nexport function writeLedgerFileAtomically(\n path: string,\n contents: string,\n context: LedgerFileContext,\n): void {\n const directory = dirname(path)\n mkdirSync(directory, { recursive: true })\n const temporaryPath = `${path}.tmp`\n const fd = openSync(\n temporaryPath,\n constants.O_CREAT | constants.O_WRONLY | constants.O_TRUNC,\n 0o600,\n )\n try {\n writeAll(fd, Buffer.from(contents, 'utf8'), context)\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n renameSync(temporaryPath, path)\n fsyncDirectory(directory)\n}\n\n/** Remove whatever occupies a sidecar path and fsync its directory, so the\n * removal is as durable as the write that created it. False when the path was\n * already empty. Recursive because a sidecar path holding a directory is one of\n * the states this has to be able to clear, not one it can refuse. */\nexport function removeLedgerFile(path: string, context: LedgerFileContext): boolean {\n try {\n rmSync(path, { recursive: true })\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return false\n throw context.integrityError(`${context.subject} ${path} could not be removed`, {\n cause: error,\n })\n }\n fsyncDirectory(dirname(path))\n return true\n}\n\nexport function withLedgerFileLock<T>(path: string, context: LedgerFileContext, run: () => T): T {\n const result = tryWithLedgerFileLock(path, context, run)\n if (!result.acquired) {\n throw context.integrityError(`${context.subject} lock is held (${path})`)\n }\n return result.value\n}\n\nexport type FileLockResult<T> = { acquired: true; value: T } | { acquired: false }\n\nexport function tryWithLedgerFileLock<T>(\n path: string,\n context: LedgerFileContext,\n run: () => T,\n): FileLockResult<T> {\n mkdirSync(dirname(path), { recursive: true })\n const lockPath = `${path}.lock`\n try {\n const acquisition = tryAcquireAtomicFileLock({ lockPath })\n if (!acquisition.acquired) return { acquired: false }\n try {\n return { acquired: true, value: run() }\n } finally {\n acquisition.lock.release()\n }\n } catch (error) {\n if (error instanceof AtomicFileLockError) {\n throw context.integrityError(error.message, { cause: error })\n }\n throw error\n }\n}\n\nfunction writeAll(fd: number, bytes: Buffer, context: LedgerFileContext): void {\n let offset = 0\n while (offset < bytes.byteLength) {\n const written = writeSync(fd, bytes, offset, bytes.byteLength - offset)\n if (written <= 0) throw context.integrityError('filesystem wrote zero bytes')\n offset += written\n }\n}\n\nfunction writeAllAt(fd: number, bytes: Buffer, position: number, context: LedgerFileContext): void {\n let offset = 0\n while (offset < bytes.byteLength) {\n const written = writeSync(fd, bytes, offset, bytes.byteLength - offset, position + offset)\n if (written <= 0) throw context.integrityError('filesystem wrote zero bytes')\n offset += written\n }\n}\n\nfunction findFinalLineStart(fd: number, size: number): number {\n const chunk = Buffer.alloc(Math.min(4_096, size))\n let cursor = size\n while (cursor > 0) {\n const length = Math.min(chunk.byteLength, cursor)\n cursor -= length\n const read = readSync(fd, chunk, 0, length, cursor)\n for (let index = read - 1; index >= 0; index -= 1) {\n if (chunk[index] === 0x0a) return cursor + index + 1\n }\n }\n return 0\n}\n\nfunction readByte(fd: number, position: number): number {\n const byte = Buffer.allocUnsafe(1)\n const read = readSync(fd, byte, 0, 1, position)\n return read === 1 ? byte[0]! : -1\n}\n\nfunction fsyncDirectory(path: string): void {\n const fd = openSync(path, constants.O_RDONLY)\n try {\n fsyncSync(fd)\n } finally {\n closeSync(fd)\n }\n}\n","/**\n * Projector snapshot — the cache that lets opening a large journal replay\n * only its tail.\n *\n * `trusted-head.ts`'s pin proves a journal's length and prefix content\n * without trusting a producer's summary; it does not make PROVING that\n * cheap. Every open still walks every row from sequence 0, parses it through\n * the domain codec, and applies it to a fresh projector, because that was the\n * only way this module knew to rebuild `Projection`.\n *\n * This file adds one more sidecar: `<journal>.snapshot` holds a `Projection`\n * a codec that opts in (`snapshotProjection` on its `LedgerJournalCodec`)\n * serialized, alongside the `(sequence, entryHash)` it was taken after. A\n * reader that finds one still verifies the generic hash chain of every row up\n * to that checkpoint — self-consistency and chain linkage, the same two\n * checks `journal.ts`'s `admitEntry` runs on every row — because that\n * verification is what the pin's guarantee actually rests on (see\n * `trusted-head.ts`'s module comment: an entry hash commits to its whole\n * prefix, so there is no way to prove a prefix unchanged without touching\n * every byte of it at least once). What the cache lets a reader skip is the\n * codec's OWN parsing (`parseEntry`, typically zod validation) and the domain\n * projector's `apply` for every row before the checkpoint: rows that already\n * passed both once, at write time, and whose bytes the chain walk has just\n * proven are unchanged since. Only the checkpoint row itself, and every row\n * after it, go through the full domain path — exactly as an already-open\n * instance that had verified up to there would already do.\n *\n * A snapshot that does not match the journal's actual bytes — a chain that\n * does not reach the claimed hash, a wrong entry count for its byte range —\n * fails loudly with the same kind of `integrityError` a full replay would\n * raise for the same tampered bytes; the tampering is real regardless of\n * which path found it, so it is never swallowed in favor of a fallback that\n * would silently re-read the same bytes a different way. Only a MISSING\n * cache file, or one this journal's current pin cannot vouch for at all\n * (§`journal.ts`'s `seedFromSnapshot`), is treated as \"no cache\" and falls\n * back to full verification.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { LEDGER_HASH_PATTERN, type LedgerHash } from './canonical'\nimport { type LedgerFileContext, removeLedgerFile, writeLedgerFileAtomically } from './journal-file'\nimport type { LedgerTrustedHead } from './trusted-head'\n\n/** A cached projection and the pinned entry it was taken after. */\nexport interface LedgerProjectorSnapshot {\n head: LedgerTrustedHead\n /** Byte length of the journal file up to and including the pinned entry's\n * own row. Where the rows this snapshot covers end and the tail it did not\n * cover begins. */\n byteLength: number\n /** The codec's serialized projection. Opaque to this module. */\n projection: unknown\n}\n\n/** Sibling cache file for a journal, alongside its `.head` pin. */\nexport function projectorSnapshotPathFor(journalPath: string): string {\n return `${journalPath}.snapshot`\n}\n\nconst RECOVERY =\n ' Restore the file, or remove it and let the journal rebuild it at its next checkpoint.'\n\n/** The cached snapshot, or null when none has been written. Present but\n * unparseable is corruption of the cache itself, not its absence, and fails\n * loudly for the same reason `readTrustedHeadFile` does: silently treating it\n * as \"no cache\" would just make the next read replay from scratch without\n * ever explaining why the cache stopped working. */\nexport function readProjectorSnapshotFile(\n path: string,\n context: LedgerFileContext,\n): LedgerProjectorSnapshot | null {\n let text: string\n try {\n text = readFileSync(path, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} could not be read.${RECOVERY}`,\n { cause: error },\n )\n }\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch (error) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} is not valid JSON.${RECOVERY}`,\n { cause: error },\n )\n }\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} is not an object.${RECOVERY}`,\n )\n }\n const record = raw as Record<string, unknown>\n const keys = Object.keys(record).sort()\n if (\n keys.length !== 3 ||\n keys[0] !== 'byteLength' ||\n keys[1] !== 'head' ||\n keys[2] !== 'projection'\n ) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} has keys [${keys.join(', ')}], expected [byteLength, head, projection].${RECOVERY}`,\n )\n }\n const { byteLength, head, projection } = record\n if (typeof byteLength !== 'number' || !Number.isSafeInteger(byteLength) || byteLength <= 0) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} byteLength is not a positive integer.${RECOVERY}`,\n )\n }\n if (typeof head !== 'object' || head === null || Array.isArray(head)) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} head is not an object.${RECOVERY}`,\n )\n }\n const headRecord = head as Record<string, unknown>\n const headKeys = Object.keys(headRecord).sort()\n if (headKeys.length !== 2 || headKeys[0] !== 'entryHash' || headKeys[1] !== 'sequence') {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} head has keys [${headKeys.join(', ')}], expected [entryHash, sequence].${RECOVERY}`,\n )\n }\n const { sequence, entryHash } = headRecord\n if (typeof sequence !== 'number' || !Number.isSafeInteger(sequence) || sequence < 0) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} head.sequence is not a non-negative integer.${RECOVERY}`,\n )\n }\n if (typeof entryHash !== 'string' || !LEDGER_HASH_PATTERN.test(entryHash)) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} head.entryHash is not a sha256 digest.${RECOVERY}`,\n )\n }\n return {\n head: { sequence, entryHash: entryHash as LedgerHash },\n byteLength,\n projection,\n }\n}\n\n/** Publish a snapshot by write-then-rename, so a crash leaves either the\n * previous cache or the new one and never a torn file a reader would have to\n * refuse. Not re-exported from the package's public surface, for the same\n * reason `writeTrustedHeadFile` is not: it takes no lock and enforces no\n * monotonicity against the journal it caches. `FileLedgerJournal` is the only\n * writer, always immediately after its own `sync()` has verified the exact\n * state it is about to cache. */\nexport function writeProjectorSnapshotFile(\n path: string,\n snapshot: LedgerProjectorSnapshot,\n context: LedgerFileContext,\n): void {\n const body = JSON.stringify({\n byteLength: snapshot.byteLength,\n head: snapshot.head,\n projection: snapshot.projection,\n })\n try {\n writeLedgerFileAtomically(path, `${body}\\n`, context)\n } catch (error) {\n throw context.integrityError(\n `${context.subject} projector snapshot ${path} could not be written`,\n { cause: error },\n )\n }\n}\n\n/** Discard a journal's cached snapshot. A missing cache is not an error: this\n * is how `clearTrustedHead()` keeps the two sidecars from disagreeing about\n * what the journal's writer has vouched for, and it is safe to call whether\n * or not a cache ever existed. */\nexport function removeProjectorSnapshotFile(path: string, context: LedgerFileContext): void {\n removeLedgerFile(path, context)\n removeLedgerFile(`${path}.tmp`, context)\n}\n","/**\n * Trusted head — the pin that makes deletion detectable.\n *\n * ## What the chain binds\n *\n * Every entry hashes the journal header, its sequence, the previous entry's\n * hash, and its event, so editing, reordering, or removing an entry in the\n * middle of a journal invalidates every hash after it. What a hash chain\n * cannot bind is its own length. Dropping entries off the END leaves a shorter\n * journal that is internally perfect, and rebuilding a journal from sequence 0\n * with recomputed hashes produces a different, equally perfect chain. For an\n * audit log of candidate registrations and promotion decisions that is the\n * difference between a record of a search that happened and a record of one\n * that did not.\n *\n * ## What the pin binds\n *\n * `<journal>.head` holds `{sequence, entryHash}` for one entry a writer\n * actually appended, in a file separate from the journal it attests. Each\n * entry hash commits to the entire prefix before it, so checking that the\n * entry at exactly `sequence` still carries `entryHash` proves two things at\n * once: the journal is at least `sequence + 1` entries long, and those entries\n * are byte-for-byte the ones the writer saw. A journal that merely grew past\n * the pin still verifies; a truncated, rolled-back, or wholesale-rewritten one\n * cannot.\n *\n * ## What the pin does NOT defend against\n *\n * The pin is a second file, not a signature. A writer with access to BOTH the\n * journal and its pin can rewrite both consistently, and the result verifies.\n * Pinning raises the cost of undetected tampering from one file to two and\n * nothing more; defending against a writer who holds both requires an anchor\n * outside this store entirely — a signed head, or a digest published to an\n * append-only service the tamperer does not control.\n *\n * Deleting the pin file downgrades a pinned journal to an unpinned one, which\n * cannot be distinguished from a journal written before pinning existed. That\n * is what `requireTrustedHead` is for: a journal opened under it refuses to\n * read at all once a non-empty journal has no pin.\n *\n * ## Abandoning a pin\n *\n * A pin outlives the journal it attests: deleting or rebuilding the journal\n * leaves a pin naming history the file no longer carries, and every read is\n * refused because that is precisely the deletion the pin exists to catch. The\n * refusal names the pin file, and `clearTrustedHeadFile` is the explicit way to\n * discard it — the same downgrade a writer with filesystem access could already\n * perform with `rm`, made reachable through the API so it is a decision in the\n * code rather than an undocumented manual step. It returns the guarantee it\n * gave up and writes no record of its own; a caller that needs the discard on\n * the record has to write one.\n */\n\nimport { readFileSync } from 'node:fs'\nimport { canonicalString, LEDGER_HASH_PATTERN, type LedgerHash } from './canonical'\nimport { type LedgerFileContext, removeLedgerFile, writeLedgerFileAtomically } from './journal-file'\n\n/** A `(sequence, entryHash)` pair a writer pinned outside the journal. */\nexport interface LedgerTrustedHead {\n sequence: number\n entryHash: LedgerHash\n}\n\n/** Minimum entry shape the anchor check needs. */\nexport interface LedgerAnchoredEntry {\n sequence: number\n entryHash: LedgerHash\n}\n\n/** Sibling pin file for a journal — deliberately NOT the journal, so rewriting\n * the log is not enough to rewrite the trust recorded about it. */\nexport function trustedHeadPathFor(journalPath: string): string {\n return `${journalPath}.head`\n}\n\nconst TRUSTED_HEAD_RECOVERY =\n ' Restore the file, or discard the pin it held with clearTrustedHead().'\n\n/** The pin, or null when this journal has never been pinned. A pin that exists\n * but does not parse is corruption or tamper of the trust record itself and\n * fails loudly: reporting it as \"no pin\" would silently downgrade what the\n * journal can prove. */\nexport function readTrustedHeadFile(\n path: string,\n context: LedgerFileContext,\n): LedgerTrustedHead | null {\n let text: string\n try {\n text = readFileSync(path, 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null\n throw context.integrityError(\n `${context.subject} trusted head ${path} could not be read.${TRUSTED_HEAD_RECOVERY}`,\n { cause: error },\n )\n }\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch (error) {\n throw context.integrityError(\n `${context.subject} trusted head ${path} is not valid JSON.${TRUSTED_HEAD_RECOVERY}`,\n { cause: error },\n )\n }\n if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {\n throw context.integrityError(\n `${context.subject} trusted head ${path} is not an object.${TRUSTED_HEAD_RECOVERY}`,\n )\n }\n const record = raw as Record<string, unknown>\n const keys = Object.keys(record).sort()\n if (keys.length !== 2 || keys[0] !== 'entryHash' || keys[1] !== 'sequence') {\n throw context.integrityError(\n `${context.subject} trusted head ${path} has keys [${keys.join(', ')}], expected [entryHash, sequence].${TRUSTED_HEAD_RECOVERY}`,\n )\n }\n const { sequence, entryHash } = record\n if (typeof sequence !== 'number' || !Number.isSafeInteger(sequence) || sequence < 0) {\n throw context.integrityError(\n `${context.subject} trusted head ${path} sequence is not a non-negative integer.${TRUSTED_HEAD_RECOVERY}`,\n )\n }\n if (typeof entryHash !== 'string' || !LEDGER_HASH_PATTERN.test(entryHash)) {\n throw context.integrityError(\n `${context.subject} trusted head ${path} entryHash is not a sha256 digest.${TRUSTED_HEAD_RECOVERY}`,\n )\n }\n return { sequence, entryHash: entryHash as LedgerHash }\n}\n\n/** Publish a pin by write-then-rename, so a crash leaves either the previous\n * pin or the new one and never a torn file that would lock a journal out of\n * its own trust record.\n *\n * Not re-exported from the package's public surface. It takes no lock, checks no\n * chain, and enforces no monotonicity, so a public form would be the one call\n * able to move a pin BACKWARD onto a journal it never read — which is the\n * truncation the pin exists to refuse. `FileLedgerJournal.pinTrustedHead` is\n * the public writer: locked, chain-verified, forward-only. */\nexport function writeTrustedHeadFile(\n path: string,\n head: LedgerTrustedHead,\n context: LedgerFileContext,\n): void {\n try {\n writeLedgerFileAtomically(path, `${canonicalString(head)}\\n`, context)\n } catch (error) {\n throw context.integrityError(`${context.subject} trusted head ${path} could not be written`, {\n cause: error,\n })\n }\n}\n\n/** Outcome of discarding a pin: the guarantee that was given up. `unreadable`\n * carries why the discarded pin could not be named — corruption, a permission\n * fault, a wrong file type — so a caller recording the decision never has to\n * treat \"no pin was there\" and \"the pin could not be read\" as one state.\n * `cleanupError` reports a stale atomic-write sibling that remains after the\n * actual pin was cleared. */\nexport type LedgerTrustedHeadRemoval =\n | { removed: true; head: LedgerTrustedHead; cleanupError?: string }\n | { removed: true; head: null; unreadable: string; cleanupError?: string }\n | { removed: false; cleanupError?: string }\n\n/** Discard a journal's pin, reporting what was discarded. The journal file is\n * untouched and reads as unpinned afterwards, so the next pinning append opens\n * a new pin at the entry it writes. This gives up the deletion guarantee for\n * every entry the pin covered; it is the recovery for a pin whose journal was\n * deliberately deleted or rebuilt, and the only way past a pin file that can no\n * longer be read at all. */\nexport function clearTrustedHeadFile(\n path: string,\n context: LedgerFileContext,\n): LedgerTrustedHeadRemoval {\n let head: LedgerTrustedHead | null = null\n let unreadable = ''\n try {\n head = readTrustedHeadFile(path, context)\n } catch (error) {\n // A pin nobody can read is precisely what clearing has to get past, so the\n // fault is reported on a removal that still happens rather than raised —\n // but it is reported, never flattened into \"there was no pin\".\n unreadable = error instanceof Error ? error.message : String(error)\n }\n const removed = removeLedgerFile(path, context)\n let cleanupError: string | undefined\n try {\n // Cleanup cannot block the requested trust-state change. Report a stale\n // atomic-write sibling so the caller can repair it before the next write.\n removeLedgerFile(`${path}.tmp`, context)\n } catch (error) {\n cleanupError = error instanceof Error ? error.message : String(error)\n }\n const cleanup = cleanupError === undefined ? {} : { cleanupError }\n if (!removed) return { removed: false, ...cleanup }\n if (head === null) return { removed: true, head: null, unreadable, ...cleanup }\n return { removed: true, head, ...cleanup }\n}\n\n/** How a journal is named when a trusted-head check refuses it. */\nexport interface LedgerTrustedHeadSubject {\n /** The journal in error messages, e.g. `search ledger /runs/a/ledger.jsonl`. */\n subject: string\n /** The sibling pin file, named in every refusal so the operator can see which\n * of the two files carries the claim being enforced. */\n trustedHeadPath: string\n}\n\n/** The entry at exactly `head.sequence` must still carry `head.entryHash`.\n * Entries must already have passed chain verification, which is what makes\n * index and sequence interchangeable here. An array serves as `entries`; a\n * journal that keeps no entries in memory passes a reader with the same\n * `length` and `at`. */\nexport function verifyEntriesAgainstTrustedHead(\n entries: Pick<readonly LedgerAnchoredEntry[], 'length' | 'at'>,\n head: LedgerTrustedHead,\n context: LedgerFileContext,\n naming: LedgerTrustedHeadSubject,\n): void {\n // A caller passing the bare subject string an untyped build would accept\n // destructures into two undefineds, which would corrupt the text of a\n // security refusal rather than fail. Refuse instead.\n if (typeof naming !== 'object' || naming === null) {\n throw new TypeError(\n 'verifyEntriesAgainstTrustedHead expects { subject, trustedHeadPath } as its fourth argument',\n )\n }\n const { subject, trustedHeadPath } = naming\n const pinned = entries.at(head.sequence)\n if (pinned === undefined) {\n throw context.integrityError(\n `${subject} trusted head ${trustedHeadPath} pins sequence ${head.sequence} (${head.entryHash}) but the journal has ${entries.length} entries — pinned history is missing (truncation, rollback, or rewrite). Restore the journal, or abandon the pinned history on purpose with clearTrustedHead().`,\n )\n }\n if (pinned.sequence !== head.sequence) {\n throw context.integrityError(\n `${subject} entry at index ${head.sequence} carries sequence ${pinned.sequence}; the chain was not verified before the trusted head ${trustedHeadPath}`,\n )\n }\n if (pinned.entryHash !== head.entryHash) {\n throw context.integrityError(\n `${subject} entry at pinned sequence ${head.sequence} carries ${pinned.entryHash} but the trusted head ${trustedHeadPath} recorded ${head.entryHash} — the journal was rewritten. Restore the journal, or abandon the pinned history on purpose with clearTrustedHead().`,\n )\n }\n}\n","/**\n * Generic durable append-only journal with a SHA-256 hash chain.\n *\n * The file format is canonical JSONL: every row is the canonical JSON encoding\n * (RFC 8785, object keys sorted recursively) of one entry, and every entry\n * hashes the previous entry's hash so the log is tamper-evident. Appends are\n * serialized in-process per path and across processes via a lock file, fsynced\n * before acknowledgement, and idempotent by `eventId`. A malformed,\n * non-canonical, truncated, reordered, or conflicting log fails loudly; a bad\n * row is never skipped.\n *\n * A hash chain binds each entry to its predecessor, which cannot prove that no\n * entry was removed from the end: a valid shorter prefix is still a valid\n * chain. `pinHead` records the appended entry in a sibling `<journal>.head`\n * file and every read re-verifies the journal against a pin that is present,\n * so truncation and wholesale rewrite are refused. `trusted-head.ts` carries\n * the full threat model, including what a pin does not defend against.\n *\n * Verification is incremental. A journal instance verifies its whole file once,\n * on its first call, and keeps the verified head, the live projector, and an\n * eventId index. Every later call checks that the head line it verified is\n * still in place, then reads, verifies, and projects only the bytes past it, so\n * an append reads one entry however long the journal is. Rows another writer\n * appended are verified as that tail. A file that was replaced, shrank, or no\n * longer carries the verified head is verified whole again. What an open\n * instance cannot see is a same-length rewrite of rows before its head; a new\n * instance verifies every row and refuses one.\n *\n * That \"whole file once\" is still every row, however long ago it was already\n * proven unchanged. A codec that opts into `snapshotProjection` lets a fresh\n * instance shortcut it: `projector-snapshot.ts`'s cache still walks the whole\n * hash chain up to its checkpoint — nothing is exempted from tamper detection\n * — but only the checkpoint row and the true tail after it go through the\n * codec's own parsing and projector; the FileLedgerJournalOptions.projectorSnapshot\n * option controls how often a pinning append refreshes it.\n *\n * Domain vocabulary lives entirely in the consumer's codec: entry schema\n * validation, the constant header fields stamped into every entry, the error\n * taxonomy, and the state machine replayed over verified entries.\n */\n\nimport { closeSync, constants, fstatSync, openSync, readSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { Mutex } from '../concurrency'\nimport { canonicalString, hashCanonical, type LedgerHash } from './canonical'\nimport { deepFreezeCanonicalJson } from './deep-freeze'\nimport { appendLedgerLine, type LedgerFileContext, withLedgerFileLock } from './journal-file'\nimport {\n type LedgerProjectorSnapshot,\n projectorSnapshotPathFor,\n readProjectorSnapshotFile,\n removeProjectorSnapshotFile,\n writeProjectorSnapshotFile,\n} from './projector-snapshot'\nimport {\n clearTrustedHeadFile,\n type LedgerTrustedHead,\n type LedgerTrustedHeadRemoval,\n readTrustedHeadFile,\n trustedHeadPathFor,\n verifyEntriesAgainstTrustedHead,\n writeTrustedHeadFile,\n} from './trusted-head'\n\n/** Minimum shape of a journal event: the idempotency key. */\nexport interface LedgerEventBase {\n eventId: string\n}\n\n/** Chain envelope every entry carries in addition to the journal's constant\n * header fields. `entryHash` covers the header, sequence, previous hash, and\n * event, so any rewrite of history invalidates every later entry. */\nexport interface LedgerChainFields<Event extends LedgerEventBase> {\n sequence: number\n previousHash: LedgerHash | null\n event: Event\n entryHash: LedgerHash\n}\n\nexport type LedgerEntryOf<Header extends object, Event extends LedgerEventBase> = Header &\n LedgerChainFields<Event>\n\nexport interface LedgerLineContext {\n path: string\n line: number\n}\n\n/** Domain state machine applied to chain-verified entries in order.\n *\n * One projector lives as long as its journal instance's verified state: the\n * journal applies each entry once, including entries appended later, and asks\n * for `snapshot()` after any number of them. `apply` throws (via the codec's\n * error taxonomy) on an invalid transition; after a throw the journal discards\n * the projector and replays the file into a new one, so `apply` need not undo\n * a partial update. Entries are deep-frozen before `apply` sees them. */\nexport interface LedgerProjector<Entry, Projection> {\n apply(entry: Entry, index: number): void\n /** The projection of every entry applied so far. A later `apply` must not\n * change a projection already returned, so a snapshot copies any state the\n * projector keeps mutating. */\n snapshot(): Projection\n}\n\n/** Serialize a projection into JSON-safe cache data, and rebuild a projector\n * from it whose next `apply` continues right after the entry it was taken\n * after — as if that projector had been live since sequence 0. Supplying\n * both opts a codec into the projector snapshot cache (`projector-snapshot.ts`):\n * a fresh journal open can then verify the generic hash chain of the rows\n * before a cached checkpoint without parsing or applying any of them through\n * this codec. Omit to disable the cache for this codec; every open then\n * fully replays through `createProjector`, exactly as before. */\nexport interface LedgerProjectorSnapshotCodec<Entry, Projection> {\n serialize(projection: Projection): unknown\n restore(serialized: unknown): LedgerProjector<Entry, Projection>\n}\n\nexport interface LedgerJournalCodec<\n Header extends object,\n Event extends LedgerEventBase,\n Projection,\n> extends LedgerFileContext {\n /** Constant fields stamped into every entry and covered by its hash. */\n header: Header\n conflictError(message: string): Error\n /** Validate one parsed JSON row into a typed entry. Must reject malformed\n * rows and non-canonical event encodings with the binding's own errors;\n * the journal itself verifies the stored bytes and the hash chain. A new\n * entry passes through the same parse before it is written, so the journal\n * never writes a row it would refuse to read. */\n parseEntry(raw: unknown, context: LedgerLineContext): LedgerEntryOf<Header, Event>\n /** Reject an entry whose constant header fields do not match this journal. */\n checkEntryHeader(entry: LedgerEntryOf<Header, Event>, index: number): void\n createProjector(): LedgerProjector<LedgerEntryOf<Header, Event>, Projection>\n snapshotProjection?: LedgerProjectorSnapshotCodec<LedgerEntryOf<Header, Event>, Projection>\n}\n\nexport interface LedgerAppendResult<Entry, Projection> {\n entry: Entry\n /** False when the exact event was already durably present. */\n appended: boolean\n projection: Projection\n}\n\nexport interface LedgerAppendOptions {\n /** Record the appended entry as this journal's trusted head, so a later read\n * can prove nothing was deleted from the end.\n *\n * On the idempotent path — the event is already durable — the pin moves up to\n * that entry only when the entry is ahead of it, along a chain this call has\n * just verified. So a pin write that failed after its row was fsynced is\n * repaired by the retry that idempotency already asks the caller for, and the\n * pin still only ever moves forward over history it has checked.\n *\n * A strict journal whose first pin write failed still refuses the retry\n * because it cannot distinguish that failure from a deleted pin. Recover it\n * explicitly with `pinTrustedHead()`; silently adopting the current file\n * would defeat `requireTrustedHead`. */\n pinHead?: boolean\n}\n\nexport interface FileLedgerJournalOptions {\n /** Refuse to read a non-empty journal that has no trusted head.\n *\n * Off by default because journals written before pinning have no pin and\n * must keep opening. Turn it on for a journal this process pins: without it,\n * deleting the sibling pin file silently downgrades the journal back to a\n * chain that cannot detect deletion. */\n requireTrustedHead?: boolean\n /** Cache a projector snapshot at the trusted head, refreshed once at least\n * this many entries have appended past the last cached one, so the cost\n * amortizes and a fresh open's tail stays bounded by this interval however\n * large the journal grows. Requires the codec's `snapshotProjection`; a\n * codec without it ignores this option and every open fully replays. */\n projectorSnapshot?: { everyEntries: number }\n}\n\n/** The part of a journal file one instance has verified. It is valid only\n * between successful locked calls: any failure discards it, and the next call\n * verifies the whole file again. */\ninterface VerifiedJournal<Entry, Projection> {\n /** Device and inode of the verified file; null until the file exists. */\n identity: { dev: bigint; ino: bigint } | null\n /** Verified byte length, which is where the next entry starts. */\n size: number\n /** Byte offset of each entry's row, indexed by sequence. */\n offsets: number[]\n /** The last entry and its row bytes, newline included. Finding these bytes\n * at the end of the verified length is what lets a call trust every row\n * before them without reading them. */\n head: { entry: Entry; row: Buffer } | null\n sequenceByEventId: Map<string, number>\n projector: LedgerProjector<Entry, Projection>\n /** The pin last verified against this chain, or null when there was none. */\n pin: LedgerTrustedHead | null\n /** Sequence of the last projector snapshot this instance wrote or seeded\n * from, or null when it has not cached one. Tracked in memory so a run of\n * pinning appends checks whether a refresh is due without re-reading the\n * cache file on every one of them. */\n snapshotSequence: number | null\n}\n\n// One async mutex per resolved journal path so concurrent appends from a single\n// process queue up instead of failing on the held cross-process lock file.\nconst journalMutexes = new Map<string, Mutex>()\n\nfunction mutexFor(path: string): Mutex {\n const existing = journalMutexes.get(path)\n if (existing) return existing\n const mutex = new Mutex()\n journalMutexes.set(path, mutex)\n return mutex\n}\n\n/** Durable filesystem journal. Construction performs no I/O. The first call\n * verifies the complete file under the locks; later calls verify the retained\n * head and only the bytes past it (see the module comment). */\nexport class FileLedgerJournal<Header extends object, Event extends LedgerEventBase, Projection> {\n readonly path: string\n /** Sibling file holding this journal's trusted head. */\n readonly trustedHeadPath: string\n /** Sibling file holding this journal's cached projector snapshot, if its\n * codec opts in. */\n readonly projectorSnapshotPath: string\n private readonly codec: LedgerJournalCodec<Header, Event, Projection>\n private readonly mutex: Mutex\n private readonly requireTrustedHead: boolean\n private readonly snapshotEvery: number | null\n private verified: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection> | null = null\n\n constructor(\n path: string,\n codec: LedgerJournalCodec<Header, Event, Projection>,\n options: FileLedgerJournalOptions = {},\n ) {\n this.path = resolve(path)\n this.trustedHeadPath = trustedHeadPathFor(this.path)\n this.projectorSnapshotPath = projectorSnapshotPathFor(this.path)\n this.codec = codec\n this.mutex = mutexFor(this.path)\n this.requireTrustedHead = options.requireTrustedHead === true\n this.snapshotEvery =\n codec.snapshotProjection !== undefined && options.projectorSnapshot !== undefined\n ? options.projectorSnapshot.everyEntries\n : null\n }\n\n async replay(): Promise<Projection> {\n return this.locked(() => this.sync(this.requireTrustedHead).projector.snapshot())\n }\n\n async append(\n event: Event,\n options: LedgerAppendOptions = {},\n ): Promise<LedgerAppendResult<LedgerEntryOf<Header, Event>, Projection>> {\n return this.locked(() => {\n const state = this.sync(this.requireTrustedHead)\n const existingSequence = state.sequenceByEventId.get(event.eventId)\n if (existingSequence !== undefined) {\n const existing = this.entryAt(state, existingSequence)!\n if (canonicalString(existing.event) !== canonicalString(event)) {\n throw this.codec.conflictError(\n `eventId ${event.eventId} already exists with different content`,\n )\n }\n if (options.pinHead === true) this.pinAcknowledged(state, existing)\n return { entry: existing, appended: false, projection: state.projector.snapshot() }\n }\n\n const sequence = state.offsets.length\n const material = {\n ...this.codec.header,\n sequence,\n previousHash: state.head?.entry.entryHash ?? null,\n event,\n }\n const text = canonicalString({ ...material, entryHash: hashCanonical(material) })\n // The new row goes through the reader's own parse and the projector's\n // transition before it is written: a row the journal would refuse to\n // read, or an entry the projector rejects, never reaches the file.\n const entry = parseRow(text, { path: this.path, line: sequence + 1 }, this.codec)\n const row = Buffer.from(`${text}\\n`, 'utf8')\n admitEntry(state, entry, row, this.codec)\n appendLedgerLine(this.path, `${text}\\n`, this.codec)\n if (options.pinHead === true) {\n // Journal first, pin second: a crash or a failed pin write between\n // them leaves the pin one entry behind, which still verifies and is\n // repaired by the next pinning append, including the idempotent\n // retry of this same event. The reverse order would leave a pin\n // naming an entry the journal does not carry, locking the journal\n // out of its own history.\n const head = { sequence: entry.sequence, entryHash: entry.entryHash }\n writeTrustedHeadFile(this.trustedHeadPath, head, this.codec)\n state.pin = head\n this.maybeWriteProjectorSnapshot(state)\n }\n return { entry, appended: true, projection: state.projector.snapshot() }\n })\n }\n\n /** The pinned head, or null when this journal has never been pinned. */\n async trustedHead(): Promise<LedgerTrustedHead | null> {\n return this.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () =>\n readTrustedHeadFile(this.trustedHeadPath, this.codec),\n ),\n )\n }\n\n /** Pin the current verified head. The chain and any existing pin are checked\n * first, so the pin only ever moves forward along a journal that still\n * carries the history it already recorded. */\n async pinTrustedHead(): Promise<LedgerTrustedHead> {\n return this.locked(() => {\n // `requireTrustedHead` is deliberately not applied here: pinning is how\n // a journal that lacks a pin acquires one.\n const state = this.sync(false)\n if (state.head === null) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} is empty; there is no head to pin`,\n )\n }\n const head: LedgerTrustedHead = {\n sequence: state.head.entry.sequence,\n entryHash: state.head.entry.entryHash,\n }\n writeTrustedHeadFile(this.trustedHeadPath, head, this.codec)\n state.pin = head\n // An explicit pin is already a deliberate, infrequent checkpoint call,\n // so — when the caller opted into the cache at all — it always\n // refreshes it rather than waiting for the interval. Gated on\n // `snapshotEvery`, not just the codec's support, so a journal that\n // never asked for `projectorSnapshot` never gets a cache file from\n // this path either; caching stays one on/off decision, not two.\n if (this.snapshotEvery !== null) this.writeProjectorSnapshotNow(state)\n return head\n })\n }\n\n /** Discard this journal's pin, reporting what was discarded. The journal file\n * is untouched and reads as unpinned afterwards, so the next pinning append\n * opens a new pin at the entry it writes. It is the way out of a pin whose\n * journal was deliberately deleted or rebuilt — every read of such a path is\n * refused, correctly, because a pin naming history the file no longer carries\n * is indistinguishable from a deletion. Clearing removes the deletion\n * guarantee for every entry the pin covered. */\n async clearTrustedHead(): Promise<LedgerTrustedHeadRemoval> {\n return this.locked(() => {\n const removal = clearTrustedHeadFile(this.trustedHeadPath, this.codec)\n // A cached snapshot that survived would be pinned to a head this\n // journal no longer vouches for, indistinguishable from a stale one a\n // future re-pin could seed from without earning it. It is not\n // security-critical to remove it — a reader only ever trusts a cached\n // checkpoint the current pin can vouch for — but keeping the sidecars\n // in agreement about what has been given up is the honest state to\n // leave on disk.\n removeProjectorSnapshotFile(this.projectorSnapshotPath, this.codec)\n if (this.verified !== null) {\n this.verified.pin = null\n this.verified.snapshotSequence = null\n }\n return removal\n })\n }\n\n /** Run under both locks. Any failure discards the verified state, because a\n * throw can leave it describing bytes the file does not hold: a projector\n * half way through a rejected transition, or a row whose write failed. */\n private locked<T>(run: () => T): Promise<T> {\n return this.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () => {\n try {\n return run()\n } catch (error) {\n this.verified = null\n throw error\n }\n }),\n )\n }\n\n /** Bring the verified state up to the file: keep it when its head row is\n * still where it was verified, else start over from byte 0; then verify and\n * apply every row past it, and check the pin. */\n private sync(requirePin: boolean): VerifiedJournal<LedgerEntryOf<Header, Event>, Projection> {\n let state = this.verified\n const fd = openForReading(this.path, this.codec)\n if (fd === null) {\n // A missing file is an empty journal, whatever this instance saw before.\n if (state === null || state.size > 0) state = emptyJournal(this.codec)\n this.verified = state\n this.verifyPin(state, requirePin)\n return state\n }\n try {\n const stats = fstatSync(fd, { bigint: true })\n const size = Number(stats.size)\n const identity = { dev: stats.dev, ino: stats.ino }\n if (\n state === null ||\n (state.identity !== null &&\n (state.identity.dev !== identity.dev || state.identity.ino !== identity.ino)) ||\n size < state.size ||\n !headInPlace(fd, state.size, state.head?.row ?? null)\n ) {\n // This is the case a full verification exists to catch — a fresh\n // instance, or one whose retained head is no longer where it was\n // verified — so a cached checkpoint is only ever a shortcut to the\n // SAME conclusion a full replay would reach, never a substitute for\n // reaching it.\n state = (size > 0 ? this.seedFromSnapshot(fd, size) : null) ?? emptyJournal(this.codec)\n }\n state.identity = identity\n this.verified = state\n if (size > state.size) {\n extendJournal(state, readRange(fd, state.size, size), this.path, this.codec)\n }\n } finally {\n closeSync(fd)\n }\n this.verifyPin(state, requirePin)\n return state\n }\n\n private verifyPin(\n state: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>,\n requirePin: boolean,\n ): void {\n const pinned = readTrustedHeadFile(this.trustedHeadPath, this.codec)\n const count = state.offsets.length\n if (pinned === null) {\n state.pin = null\n if (requirePin && count > 0) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has ${count} entries but no trusted head at ${this.trustedHeadPath} — without its pin the journal cannot prove nothing was deleted. Restore the pin file, or adopt the current head with pinTrustedHead().`,\n )\n }\n return\n }\n // A pin already verified against this chain stays verified while the\n // chain's head is in place; sync has just checked that.\n if (state.pin?.sequence === pinned.sequence && state.pin.entryHash === pinned.entryHash) {\n return\n }\n // The anchor is meaningful only over a chain that already verified, so it\n // is checked after sync — and on every call, so a violated pin is refused\n // before an append can extend the journal over it.\n const chain = { length: count, at: (sequence: number) => this.entryAt(state, sequence) }\n verifyEntriesAgainstTrustedHead(chain, pinned, this.codec, {\n subject: `${this.codec.subject} ${this.path}`,\n trustedHeadPath: this.trustedHeadPath,\n })\n state.pin = pinned\n }\n\n /** Move the pin up to an entry this caller just acknowledged on the\n * idempotent path, when a pin write that failed after its row was already\n * fsynced left the pin behind. The move is safe because it is forward-only\n * along a chain `sync` has just verified: every entry up to this one is bound\n * to it by hash, so the pin can only ever come to name more history than it\n * did, never different history.\n *\n * With no pin at all this only pins the journal's current head. An entry in\n * the middle would publish a pin that reads as protection while leaving every\n * later entry silently truncatable, which is a worse state to hand an auditor\n * than the honest absence of a pin; `pinTrustedHead()` is the way to pin an\n * unpinned journal on purpose. */\n private pinAcknowledged(\n state: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>,\n entry: LedgerEntryOf<Header, Event>,\n ): void {\n const pinned = state.pin\n if (pinned === null) {\n if (entry.sequence !== state.offsets.length - 1) return\n } else if (pinned.sequence >= entry.sequence) {\n return\n }\n const head = { sequence: entry.sequence, entryHash: entry.entryHash }\n writeTrustedHeadFile(this.trustedHeadPath, head, this.codec)\n state.pin = head\n this.maybeWriteProjectorSnapshot(state)\n }\n\n /** Refresh the cached projector snapshot once the current pin has moved at\n * least `snapshotEvery` entries past the last one cached, so the write cost\n * amortizes across many appends and a fresh open's uncached tail stays\n * bounded by that interval no matter how large the journal grows. A no-op\n * when the codec does not support the cache, the option is off, or the\n * head this call just pinned is not actually new (the idempotent-append\n * path can call this after re-acknowledging an already-durable entry). */\n private maybeWriteProjectorSnapshot(\n state: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>,\n ): void {\n if (this.codec.snapshotProjection === undefined || this.snapshotEvery === null) return\n if (state.pin === null || state.pin.sequence !== state.head?.entry.sequence) return\n if (\n state.snapshotSequence !== null &&\n state.pin.sequence - state.snapshotSequence < this.snapshotEvery\n ) {\n return\n }\n this.writeProjectorSnapshotNow(state)\n }\n\n /** Serialize the live projector and write it as the cache, unconditionally.\n * Callers have already established that `state.pin` names `state.head`, so\n * the cache and the pin agree on the checkpoint by construction. */\n private writeProjectorSnapshotNow(\n state: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>,\n ): void {\n const head = state.pin!\n const projection = this.codec.snapshotProjection!.serialize(state.projector.snapshot())\n const snapshot: LedgerProjectorSnapshot = { head, byteLength: state.size, projection }\n writeProjectorSnapshotFile(this.projectorSnapshotPath, snapshot, this.codec)\n state.snapshotSequence = head.sequence\n }\n\n /** Seed a fresh verified state from the cached projector snapshot, or null\n * when there is none this reader can use — a missing or out-of-reach\n * cache, never something this instance found actually wrong. Everything it\n * DOES accept is checked against the real bytes: rows 0 through the\n * checkpoint are read and chain-verified exactly as `admitEntry` would\n * verify them (self-consistent hash, correct sequence, linked previousHash,\n * unique eventId), just without this codec's own `parseEntry` or\n * `apply` — the checkpoint row itself still goes through both, through the\n * ordinary `parseRow`, so it is exactly as trustworthy as any entry a full\n * replay would produce. Any mismatch found along the way throws the same\n * `integrityError` a full replay of the same bytes would raise, because it\n * is the same tampering either path would have found; this is never turned\n * into a quiet fallback that would just re-read the same bytes differently\n * and risk reporting a different, more confusing failure — or none. */\n private seedFromSnapshot(\n fd: number,\n size: number,\n ): VerifiedJournal<LedgerEntryOf<Header, Event>, Projection> | null {\n const restore = this.codec.snapshotProjection\n if (restore === undefined) return null\n const cached = readProjectorSnapshotFile(this.projectorSnapshotPath, this.codec)\n if (cached === null) return null\n // Only a cache the CURRENT pin can vouch for is trusted. A pin moves\n // forward only past history that has already chain-verified (sync\n // verifies every appended row before a pinning append can move it), so a\n // cache at or behind the pin names a real, already-proven checkpoint; one\n // ahead of it — or present with no pin at all — names history nothing\n // external currently vouches for, and is ignored rather than trusted.\n const pin = readTrustedHeadFile(this.trustedHeadPath, this.codec)\n if (pin === null || cached.head.sequence > pin.sequence) return null\n if (cached.byteLength <= 0 || cached.byteLength > size) return null\n\n const prefix = readRange(fd, 0, cached.byteLength)\n const rows = splitRows(prefix, this.path, this.codec)\n if (rows.length !== cached.head.sequence + 1) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} projector snapshot ${this.projectorSnapshotPath} expects ${cached.head.sequence + 1} entries in its first ${cached.byteLength} bytes but the journal has ${rows.length}`,\n )\n }\n\n const offsets: number[] = []\n const sequenceByEventId = new Map<string, number>()\n let previousHash: LedgerHash | null = null\n for (let index = 0; index < rows.length - 1; index += 1) {\n const row = rows[index]!\n offsets.push(row.start)\n let raw: unknown\n try {\n raw = JSON.parse(row.text)\n } catch (error) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has invalid JSON at line ${index + 1}`,\n { cause: error },\n )\n }\n if (canonicalString(raw) !== row.text) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has non-canonical bytes at line ${index + 1}`,\n )\n }\n const fields = raw as {\n sequence?: unknown\n previousHash?: unknown\n entryHash?: unknown\n event?: { eventId?: unknown }\n }\n if (fields.sequence !== index) {\n throw this.codec.integrityError(\n `entry at line ${index + 1} has sequence ${String(fields.sequence)}, expected ${index}`,\n )\n }\n if ((fields.previousHash ?? null) !== previousHash) {\n throw this.codec.integrityError(\n `entry at line ${index + 1} does not extend the previous hash`,\n )\n }\n const { entryHash, ...material } = raw as Record<string, unknown>\n const expected = hashCanonical(material)\n if (entryHash !== expected) {\n throw this.codec.integrityError(\n `entry at line ${index + 1} hash mismatch: expected ${expected}, got ${String(entryHash)}`,\n )\n }\n const eventId = fields.event?.eventId\n if (typeof eventId !== 'string' || eventId === '') {\n throw this.codec.integrityError(`entry at line ${index + 1} has no eventId`)\n }\n if (sequenceByEventId.has(eventId)) {\n throw this.codec.integrityError(`duplicate eventId ${eventId} in durable ledger`)\n }\n sequenceByEventId.set(eventId, index)\n previousHash = entryHash as LedgerHash\n }\n\n // The checkpoint row itself carries this codec's own validation, exactly\n // like any other entry — the cache never substitutes for parsing it.\n const boundary = rows[rows.length - 1]!\n offsets.push(boundary.start)\n const entry = parseRow(\n boundary.text,\n { path: this.path, line: cached.head.sequence + 1 },\n this.codec,\n )\n const { entryHash: _boundaryHash, ...boundaryMaterial } = entry\n if (\n entry.sequence !== cached.head.sequence ||\n entry.previousHash !== previousHash ||\n entry.entryHash !== cached.head.entryHash ||\n hashCanonical(boundaryMaterial) !== cached.head.entryHash\n ) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} projector snapshot ${this.projectorSnapshotPath} does not match the journal at sequence ${cached.head.sequence}`,\n )\n }\n this.codec.checkEntryHeader(entry, cached.head.sequence)\n if (sequenceByEventId.has(entry.event.eventId)) {\n throw this.codec.integrityError(`duplicate eventId ${entry.event.eventId} in durable ledger`)\n }\n sequenceByEventId.set(entry.event.eventId, entry.sequence)\n\n let projector: LedgerProjector<LedgerEntryOf<Header, Event>, Projection>\n try {\n projector = restore.restore(cached.projection)\n } catch (error) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} projector snapshot ${this.projectorSnapshotPath} could not be restored`,\n { cause: error },\n )\n }\n\n return {\n identity: null,\n size: cached.byteLength,\n offsets,\n head: { entry, row: Buffer.from(`${boundary.text}\\n`, 'utf8') },\n sequenceByEventId,\n projector,\n pin: null,\n snapshotSequence: cached.head.sequence,\n }\n }\n\n /** The verified entry at `sequence`, read back from the file. The rows from\n * it to the head are re-read and must chain to the verified head hash, which\n * binds the returned entry to the history this instance verified. Callers ask\n * for recent entries — an idempotent retry, a pin one entry behind — so this\n * usually reads nothing or one row. */\n private entryAt(\n state: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>,\n sequence: number,\n ): LedgerEntryOf<Header, Event> | undefined {\n const count = state.offsets.length\n if (!Number.isSafeInteger(sequence) || sequence < 0 || sequence >= count) return undefined\n if (sequence === count - 1) return state.head!.entry\n const changed = () =>\n this.codec.integrityError(\n `${this.codec.subject} ${this.path} changed at or after sequence ${sequence} since this reader verified it`,\n )\n const fd = openForReading(this.path, this.codec)\n if (fd === null) throw changed()\n let bytes: Buffer\n try {\n bytes = readRange(fd, state.offsets[sequence]!, state.size)\n } finally {\n closeSync(fd)\n }\n const rows = splitRows(bytes, this.path, this.codec)\n if (rows.length !== count - sequence) throw changed()\n let first: LedgerEntryOf<Header, Event> | undefined\n let previous: LedgerEntryOf<Header, Event> | undefined\n for (let index = 0; index < rows.length; index += 1) {\n const entry = parseRow(\n rows[index]!.text,\n { path: this.path, line: sequence + index + 1 },\n this.codec,\n )\n const { entryHash, ...material } = entry\n if (\n entry.sequence !== sequence + index ||\n hashCanonical(material) !== entryHash ||\n (previous !== undefined && entry.previousHash !== previous.entryHash)\n ) {\n throw changed()\n }\n first ??= entry\n previous = entry\n }\n if (previous?.entryHash !== state.head!.entry.entryHash) throw changed()\n return first\n }\n}\n\n/** Where a memory journal keeps its text: an in-process store keyed by path,\n * such as an in-memory `CampaignStorage`. */\nexport interface LedgerTextStore {\n read(path: string): string | undefined\n write(path: string, text: string): void\n}\n\n/**\n * A journal for runs without a filesystem. It keeps its rows as text in a\n * store and applies the file journal's rules: the same row parse, hash chain,\n * idempotent append by `eventId`, and projector transition before a row is\n * kept. It has no lock, fsync or trusted head, because its rows live and die\n * with the process that holds the store.\n */\nexport class MemoryLedgerJournal<Header extends object, Event extends LedgerEventBase, Projection> {\n readonly path: string\n private readonly codec: LedgerJournalCodec<Header, Event, Projection>\n private readonly store: LedgerTextStore\n private verified: {\n text: string\n journal: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>\n entries: LedgerEntryOf<Header, Event>[]\n } | null = null\n\n constructor(\n path: string,\n codec: LedgerJournalCodec<Header, Event, Projection>,\n store: LedgerTextStore,\n ) {\n this.path = path\n this.codec = codec\n this.store = store\n }\n\n async replay(): Promise<Projection> {\n return this.guarded(() => this.sync().journal.projector.snapshot())\n }\n\n async append(\n event: Event,\n ): Promise<LedgerAppendResult<LedgerEntryOf<Header, Event>, Projection>> {\n return this.guarded(() => {\n const verified = this.sync()\n const { journal, entries } = verified\n const existingSequence = journal.sequenceByEventId.get(event.eventId)\n if (existingSequence !== undefined) {\n const existing = entries[existingSequence]!\n if (canonicalString(existing.event) !== canonicalString(event)) {\n throw this.codec.conflictError(\n `eventId ${event.eventId} already exists with different content`,\n )\n }\n return { entry: existing, appended: false, projection: journal.projector.snapshot() }\n }\n const sequence = entries.length\n const material = {\n ...this.codec.header,\n sequence,\n previousHash: journal.head?.entry.entryHash ?? null,\n event,\n }\n const text = canonicalString({ ...material, entryHash: hashCanonical(material) })\n const entry = parseRow(text, { path: this.path, line: sequence + 1 }, this.codec)\n admitEntry(journal, entry, Buffer.from(`${text}\\n`, 'utf8'), this.codec)\n entries.push(entry)\n verified.text = `${verified.text}${text}\\n`\n this.store.write(this.path, verified.text)\n return { entry, appended: true, projection: journal.projector.snapshot() }\n })\n }\n\n /** Verify the stored text again whenever it is not the text this instance wrote. */\n private sync(): NonNullable<MemoryLedgerJournal<Header, Event, Projection>['verified']> {\n const text = this.store.read(this.path) ?? ''\n if (this.verified?.text === text) return this.verified\n const journal = emptyJournal(this.codec)\n const entries: LedgerEntryOf<Header, Event>[] = []\n const bytes = Buffer.from(text, 'utf8')\n for (const row of splitRows(bytes, this.path, this.codec)) {\n const entry = parseRow(row.text, { path: this.path, line: entries.length + 1 }, this.codec)\n admitEntry(journal, entry, Buffer.from(bytes.subarray(row.start, row.end)), this.codec)\n entries.push(entry)\n }\n this.verified = { text, journal, entries }\n return this.verified\n }\n\n /** A refused transition can leave the projector half applied; discard it. */\n private async guarded<T>(run: () => T): Promise<T> {\n try {\n return run()\n } catch (error) {\n this.verified = null\n throw error\n }\n }\n}\n\n/** Verify and replay resolved immutable journal bytes without filesystem I/O. */\nexport function replayLedgerText<Header extends object, Event extends LedgerEventBase, Projection>(\n text: string,\n path: string,\n codec: LedgerJournalCodec<Header, Event, Projection>,\n): Projection {\n const state = emptyJournal(codec)\n extendJournal(state, Buffer.from(text, 'utf8'), path, codec)\n return state.projector.snapshot()\n}\n\nfunction emptyJournal<Header extends object, Event extends LedgerEventBase, Projection>(\n codec: LedgerJournalCodec<Header, Event, Projection>,\n): VerifiedJournal<LedgerEntryOf<Header, Event>, Projection> {\n return {\n identity: null,\n size: 0,\n offsets: [],\n head: null,\n sequenceByEventId: new Map(),\n projector: codec.createProjector(),\n pin: null,\n snapshotSequence: null,\n }\n}\n\n/** Verify and apply the rows in `bytes`, which start at the state's verified\n * length. */\nfunction extendJournal<Header extends object, Event extends LedgerEventBase, Projection>(\n state: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>,\n bytes: Buffer,\n path: string,\n codec: LedgerJournalCodec<Header, Event, Projection>,\n): void {\n const rows = splitRows(bytes, path, codec)\n for (const { text, start, end } of rows) {\n const entry = parseRow(text, { path, line: state.offsets.length + 1 }, codec)\n // Copy the row: a view would keep the whole read buffer alive.\n admitEntry(state, entry, Buffer.from(bytes.subarray(start, end)), codec)\n }\n}\n\n/** Check one parsed entry against the chain and apply it. Every row, read or\n * about to be written, enters the verified state here. */\nfunction admitEntry<Header extends object, Event extends LedgerEventBase, Projection>(\n state: VerifiedJournal<LedgerEntryOf<Header, Event>, Projection>,\n entry: LedgerEntryOf<Header, Event>,\n row: Buffer,\n codec: LedgerJournalCodec<Header, Event, Projection>,\n): void {\n const index = state.offsets.length\n codec.checkEntryHeader(entry, index)\n if (entry.sequence !== index) {\n throw codec.integrityError(\n `entry ${entry.event.eventId} has sequence ${entry.sequence}, expected ${index}`,\n )\n }\n if (entry.previousHash !== (state.head?.entry.entryHash ?? null)) {\n throw codec.integrityError(`entry ${entry.event.eventId} does not extend the previous hash`)\n }\n const { entryHash: _entryHash, ...material } = entry\n const expectedHash = hashCanonical(material)\n if (entry.entryHash !== expectedHash) {\n throw codec.integrityError(\n `entry ${entry.event.eventId} hash mismatch: expected ${expectedHash}, got ${entry.entryHash}`,\n )\n }\n if (state.sequenceByEventId.has(entry.event.eventId)) {\n throw codec.integrityError(`duplicate eventId ${entry.event.eventId} in durable ledger`)\n }\n state.projector.apply(entry, index)\n state.sequenceByEventId.set(entry.event.eventId, index)\n state.offsets.push(state.size)\n state.size += row.byteLength\n state.head = { entry, row }\n}\n\n/** Parse one canonical row into a frozen entry. The projector and every caller\n * share entries, so none of them can change what the journal verified. */\nfunction parseRow<Header extends object, Event extends LedgerEventBase, Projection>(\n text: string,\n context: LedgerLineContext,\n codec: LedgerJournalCodec<Header, Event, Projection>,\n): LedgerEntryOf<Header, Event> {\n const { path, line } = context\n let raw: unknown\n try {\n raw = JSON.parse(text)\n } catch (error) {\n throw codec.integrityError(`${codec.subject} ${path} has invalid JSON at line ${line}`, {\n cause: error,\n })\n }\n const entry = codec.parseEntry(raw, context)\n let canonical: string\n try {\n canonical = canonicalString(entry)\n } catch (error) {\n throw codec.integrityError(\n `${codec.subject} ${path} has a row with no canonical JSON form at line ${line}`,\n { cause: error },\n )\n }\n if (text !== canonical) {\n throw codec.integrityError(`${codec.subject} ${path} has non-canonical bytes at line ${line}`)\n }\n return deepFreezeCanonicalJson(entry)\n}\n\ninterface JournalRow {\n text: string\n /** Byte range of the row in the buffer, newline included. */\n start: number\n end: number\n}\n\nfunction splitRows(bytes: Buffer, path: string, context: LedgerFileContext): JournalRow[] {\n if (bytes.byteLength === 0) return []\n if (bytes[bytes.byteLength - 1] !== 0x0a) {\n throw context.integrityError(\n `${context.subject} ${path} has a truncated final record (missing newline)`,\n )\n }\n const rows: JournalRow[] = []\n let start = 0\n while (start < bytes.byteLength) {\n const newline = bytes.indexOf(0x0a, start)\n if (newline === start) {\n throw context.integrityError(\n `${context.subject} ${path} has a blank row at line ${rows.length + 1}`,\n )\n }\n rows.push({ text: bytes.toString('utf8', start, newline), start, end: newline + 1 })\n start = newline + 1\n }\n return rows\n}\n\n/** True when the verified head row still ends the verified length of the file. */\nfunction headInPlace(fd: number, size: number, row: Buffer | null): boolean {\n return row === null || readRange(fd, size - row.byteLength, size).equals(row)\n}\n\n/** A read-only descriptor, or null when the file does not exist. */\nfunction openForReading(path: string, context: LedgerFileContext): number | null {\n try {\n return openSync(path, constants.O_RDONLY)\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return null\n throw context.integrityError(`${context.subject} ${path} could not be opened for reading`, {\n cause: error,\n })\n }\n}\n\nfunction readRange(fd: number, start: number, end: number): Buffer {\n const bytes = Buffer.allocUnsafe(end - start)\n let offset = 0\n while (offset < bytes.byteLength) {\n const read = readSync(fd, bytes, offset, bytes.byteLength - offset, start + offset)\n if (read === 0) return bytes.subarray(0, offset)\n offset += read\n }\n return bytes\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAYA,IAAa,QAAb,MAAmB;CACjB,SAAiB;CACjB,UAA8C,CAAC;CAE/C,M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CACZ,OAAO,QAAQ,MAAM,YAAY;EAC/B,MAAM,UAAU,MAAM,QAAQ,IAAM,KAAK;EACzC,IAAI,YAAY,OACd,MAAM,QAAQ,eACZ,GAAG,QAAQ,QAAQ,GAAG,KAAK,2BAA2B,KAAK,SAAS,GACtE;EAEF,KAAK,KAAK;GAAE,MAAM,MAAM,SAAS,QAAQ,OAAO,OAAO;GAAG;GAAO,KAAK,UAAU;EAAE,CAAC;EACnF,QAAQ,UAAU;CACpB;CACA,OAAO;AACT;;AAGA,SAAS,YAAY,IAAY,MAAc,KAA6B;CAC1E,OAAO,QAAQ,QAAQ,UAAU,IAAI,OAAO,IAAI,YAAY,IAAI,CAAC,CAAC,OAAO,GAAG;AAC9E;;AAGA,SAAS,eAAe,MAAc,SAA2C;CAC/E,IAAI;EACF,OAAO,SAAS,MAAM,UAAU,QAAQ;CAC1C,SAAS,OAAO;EACd,IAAK,MAAgC,SAAS,UAAU,OAAO;EAC/D,MAAM,QAAQ,eAAe,GAAG,QAAQ,QAAQ,GAAG,KAAK,mCAAmC,EACzF,OAAO,MACT,CAAC;CACH;AACF;AAEA,SAAS,UAAU,IAAY,OAAe,KAAqB;CACjE,MAAM,QAAQ,OAAO,YAAY,MAAM,KAAK;CAC5C,IAAI,SAAS;CACb,OAAO,SAAS,MAAM,YAAY;EAChC,MAAM,OAAO,SAAS,IAAI,OAAO,QAAQ,MAAM,aAAa,QAAQ,QAAQ,MAAM;EAClF,IAAI,SAAS,GAAG,OAAO,MAAM,SAAS,GAAG,MAAM;EAC/C,UAAU;CACZ;CACA,OAAO;AACT"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as AgentEvalError } from "./errors-
|
|
2
|
-
|
|
1
|
+
import { t as AgentEvalError } from "./errors-DeEEV9Vx.js";
|
|
2
|
+
// src/llm-client/errors.ts
|
|
3
3
|
var LlmCallError = class extends AgentEvalError {
|
|
4
4
|
status;
|
|
5
5
|
body;
|
|
@@ -21,8 +21,7 @@ var LlmResponseError = class extends AgentEvalError {
|
|
|
21
21
|
this.result = result;
|
|
22
22
|
}
|
|
23
23
|
};
|
|
24
|
-
|
|
25
|
-
//#region src/llm-client/json.ts
|
|
24
|
+
// src/llm-client/json.ts
|
|
26
25
|
/**
|
|
27
26
|
* Strip a ```json / ``` code fence if the model emitted one.
|
|
28
27
|
* Idempotent for naked JSON. Some models (claude-code via router, certain
|
|
@@ -105,7 +104,6 @@ function parseJsonSafely(content, model, jsonPayloadMode) {
|
|
|
105
104
|
function isRecord(value) {
|
|
106
105
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
107
106
|
}
|
|
108
|
-
//#endregion
|
|
109
107
|
export { LlmCallError as a, stripFencedJson as i, isRecord as n, LlmResponseError as o, parseJsonResult as r, extractJsonPayload as t };
|
|
110
108
|
|
|
111
|
-
//# sourceMappingURL=json-
|
|
109
|
+
//# sourceMappingURL=json-DtvZNAU9.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"json-
|
|
1
|
+
{"version":3,"file":"json-DtvZNAU9.js","names":[],"sources":["../src/llm-client/errors.ts","../src/llm-client/json.ts"],"sourcesContent":["import { AgentEvalError } from '../errors'\nimport type { LlmCallResult } from './contract'\n\nexport class LlmCallError extends AgentEvalError {\n constructor(\n message: string,\n public readonly status: number,\n public readonly body: string,\n public readonly model: string,\n ) {\n super('judge', message)\n }\n}\n\n/** A provider response completed and incurred measurable usage, but its content\n * could not satisfy the caller's response contract. The response envelope is\n * retained so accounting can commit the receipt before the error propagates. */\nexport class LlmResponseError extends AgentEvalError {\n constructor(\n message: string,\n public readonly result: LlmCallResult,\n options?: { cause?: unknown },\n ) {\n super('judge', message, options)\n }\n}\n","import type { LlmCallResult, LlmClientOptions } from './contract'\nimport { LlmResponseError } from './errors'\n\n// ─── Public API ─────────────────────────────────────────────────────────\n\n/**\n * Strip a ```json / ``` code fence if the model emitted one.\n * Idempotent for naked JSON. Some models (claude-code via router, certain\n * deepseek models) wrap output even under json_object.\n */\nexport function stripFencedJson(raw: string): string {\n const trimmed = raw.trim()\n const m = trimmed.match(/^```(?:json)?\\s*\\n?([\\s\\S]*?)\\n?```\\s*$/)\n return m ? m[1]!.trim() : trimmed\n}\n\nexport function extractJsonPayload(raw: string): string {\n const stripped = stripFencedJson(raw)\n try {\n JSON.parse(stripped)\n return stripped\n } catch {\n // A response that declares a JSON root must parse as that complete root.\n // Scanning onward could turn a truncated object into one of its valid nested\n // arrays or objects and silently change the response schema.\n if (stripped.startsWith('{') || stripped.startsWith('[')) return stripped\n }\n\n // Only prose-leading responses may contain a recoverable JSON payload.\n const starts = [...stripped.matchAll(/[[{]/g)]\n .map((match) => match.index)\n .filter((index) => index != null)\n for (const start of starts) {\n const candidate = extractBalancedJson(stripped, start)\n if (!candidate) continue\n try {\n JSON.parse(candidate)\n return candidate\n } catch {\n // Keep scanning; earlier braces may belong to prose.\n }\n }\n\n return stripped\n}\n\nfunction extractBalancedJson(input: string, start: number): string | null {\n const opener = input[start]\n const closer = opener === '{' ? '}' : opener === '[' ? ']' : null\n if (!closer) return null\n\n const stack: string[] = [closer]\n let isInString = false\n let isEscaped = false\n\n for (let i = start + 1; i < input.length; i++) {\n const char = input[i]!\n if (isEscaped) {\n isEscaped = false\n continue\n }\n if (char === '\\\\') {\n isEscaped = isInString\n continue\n }\n if (char === '\"') {\n isInString = !isInString\n continue\n }\n if (isInString) continue\n\n if (char === '{') stack.push('}')\n else if (char === '[') stack.push(']')\n else if (char === stack[stack.length - 1]) {\n stack.pop()\n if (stack.length === 0) return input.slice(start, i + 1)\n }\n }\n\n return null\n}\n\nexport function parseJsonResult<T>(\n result: LlmCallResult,\n jsonPayloadMode: NonNullable<LlmClientOptions['jsonPayloadMode']>,\n): T {\n try {\n if (result.finishReason === 'length') {\n throw new Error(\n `LLM returned truncated JSON content (model=${result.model}, finishReason=length)`,\n )\n }\n return parseJsonSafely<T>(result.content, result.model, jsonPayloadMode)\n } catch (error) {\n if (error instanceof LlmResponseError) throw error\n const cause = error instanceof Error ? error : new Error(String(error))\n throw new LlmResponseError(cause.message, result, { cause })\n }\n}\n\nfunction parseJsonSafely<T>(\n content: string,\n model: string,\n jsonPayloadMode: NonNullable<LlmClientOptions['jsonPayloadMode']>,\n): T {\n const payload = jsonPayloadMode === 'exact' ? content : extractJsonPayload(content)\n try {\n return JSON.parse(payload) as T\n } catch {\n throw new Error(`LLM returned non-JSON content (model=${model})`)\n }\n}\n\n/** A non-array object: the JSON object shape that model and export payloads are narrowed to. */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === 'object' && value !== null && !Array.isArray(value)\n}\n"],"mappings":";;AAGA,IAAa,eAAb,cAAkC,eAAe;CAG7B;CACA;CACA;CAJlB,YACE,SACA,QACA,MACA,OACA;EACA,MAAM,SAAS,OAAO;EAJN,KAAA,SAAA;EACA,KAAA,OAAA;EACA,KAAA,QAAA;CAGlB;AACF;;;;AAKA,IAAa,mBAAb,cAAsC,eAAe;CAGjC;CAFlB,YACE,SACA,QACA,SACA;EACA,MAAM,SAAS,SAAS,OAAO;EAHf,KAAA,SAAA;CAIlB;AACF;;;;;;;ACfA,SAAgB,gBAAgB,KAAqB;CACnD,MAAM,UAAU,IAAI,KAAK;CACzB,MAAM,IAAI,QAAQ,MAAM,yCAAyC;CACjE,OAAO,IAAI,EAAE,EAAE,CAAE,KAAK,IAAI;AAC5B;AAEA,SAAgB,mBAAmB,KAAqB;CACtD,MAAM,WAAW,gBAAgB,GAAG;CACpC,IAAI;EACF,KAAK,MAAM,QAAQ;EACnB,OAAO;CACT,QAAQ;EAIN,IAAI,SAAS,WAAW,GAAG,KAAK,SAAS,WAAW,GAAG,GAAG,OAAO;CACnE;CAGA,MAAM,SAAS,CAAC,GAAG,SAAS,SAAS,OAAO,CAAC,CAAC,CAC3C,KAAK,UAAU,MAAM,KAAK,CAAC,CAC3B,QAAQ,UAAU,SAAS,IAAI;CAClC,KAAK,MAAM,SAAS,QAAQ;EAC1B,MAAM,YAAY,oBAAoB,UAA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