@tangle-network/agent-eval 0.150.2 → 0.161.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (342) hide show
  1. package/CHANGELOG.md +158 -1
  2. package/README.md +7 -3
  3. package/dist/{active-curriculum-C4mk67HP.js → active-curriculum-CD5TU2yW.js} +3 -13
  4. package/dist/active-curriculum-CD5TU2yW.js.map +1 -0
  5. package/dist/{agent-profile-cell-BkcRDikH.d.ts → agent-profile-cell-CTOZJUuE.d.ts} +4 -2
  6. package/dist/agent-profile-cell-CTOZJUuE.d.ts.map +1 -0
  7. package/dist/analyst/index.d.ts +19 -36
  8. package/dist/analyst/index.d.ts.map +1 -1
  9. package/dist/analyst/index.js +8 -8
  10. package/dist/analyst/index.js.map +1 -1
  11. package/dist/{backend-integrity-DOCa_QrR.d.ts → backend-integrity-DxuQCu_A.d.ts} +4 -3
  12. package/dist/backend-integrity-DxuQCu_A.d.ts.map +1 -0
  13. package/dist/{benchmark-BtAWA8nT.d.ts → benchmark-CGPp-kDC.d.ts} +3 -3
  14. package/dist/{benchmark-BtAWA8nT.d.ts.map → benchmark-CGPp-kDC.d.ts.map} +1 -1
  15. package/dist/{benchmark-command-BU1Las59.js → benchmark-command-BDC3Gocz.js} +26 -31
  16. package/dist/benchmark-command-BDC3Gocz.js.map +1 -0
  17. package/dist/benchmarks/index.d.ts +6 -19
  18. package/dist/benchmarks/index.d.ts.map +1 -1
  19. package/dist/benchmarks/index.js +4 -4
  20. package/dist/benchmarks/index.js.map +1 -1
  21. package/dist/builder-eval/index.d.ts +3 -3
  22. package/dist/builder-eval/index.js +2 -2
  23. package/dist/campaign/index.d.ts +9 -9
  24. package/dist/campaign/index.js +7 -7
  25. package/dist/{campaign-la-gEYNz.js → campaign-BSmOwskD.js} +77 -795
  26. package/dist/campaign-BSmOwskD.js.map +1 -0
  27. package/dist/{canonical-D-XsTQ6_.js → canonical-IL-Bu-14.js} +26 -2
  28. package/dist/canonical-IL-Bu-14.js.map +1 -0
  29. package/dist/{capture-fetch-BBVFzhkk.d.ts → capture-fetch-CqwsJkkG.d.ts} +3 -3
  30. package/dist/{capture-fetch-BBVFzhkk.d.ts.map → capture-fetch-CqwsJkkG.d.ts.map} +1 -1
  31. package/dist/{chat-client-Bvmxedyv.js → chat-client-DlMlAeYI.js} +5 -55
  32. package/dist/{chat-client-Bvmxedyv.js.map → chat-client-DlMlAeYI.js.map} +1 -1
  33. package/dist/chat-json-call-6g5sJobJ.js +53 -0
  34. package/dist/chat-json-call-6g5sJobJ.js.map +1 -0
  35. package/dist/cli.js +54 -19
  36. package/dist/cli.js.map +1 -1
  37. package/dist/{client-LIuo-KPv.js → client-CX7KqIdB.js} +3 -3
  38. package/dist/client-CX7KqIdB.js.map +1 -0
  39. package/dist/{client-kPQYT_56.d.ts → client-L9VVPkim.d.ts} +4 -4
  40. package/dist/{client-kPQYT_56.d.ts.map → client-L9VVPkim.d.ts.map} +1 -1
  41. package/dist/contract/index.d.ts +13 -27
  42. package/dist/contract/index.d.ts.map +1 -1
  43. package/dist/contract/index.js +14 -17
  44. package/dist/contract/index.js.map +1 -1
  45. package/dist/{counterfactual--bpysZF0.d.ts → counterfactual-BaFUWK3H.d.ts} +4 -4
  46. package/dist/{counterfactual--bpysZF0.d.ts.map → counterfactual-BaFUWK3H.d.ts.map} +1 -1
  47. package/dist/{counterfactual-lDfCx0Uz.js → counterfactual-D_VWavVm.js} +2 -2
  48. package/dist/{counterfactual-lDfCx0Uz.js.map → counterfactual-D_VWavVm.js.map} +1 -1
  49. package/dist/{dataset-CJjKqQfA.d.ts → dataset-DQqhOCPt.d.ts} +5 -4
  50. package/dist/{dataset-CJjKqQfA.d.ts.map → dataset-DQqhOCPt.d.ts.map} +1 -1
  51. package/dist/{default-registry-Cw0Ohdoj.d.ts → default-registry-G9CKMNkc.d.ts} +7 -8
  52. package/dist/{default-registry-Cw0Ohdoj.d.ts.map → default-registry-G9CKMNkc.d.ts.map} +1 -1
  53. package/dist/{define-agent-eval-CEQWL9Hy.d.ts → define-agent-eval-Dx1JnPEa.d.ts} +26 -6
  54. package/dist/define-agent-eval-Dx1JnPEa.d.ts.map +1 -0
  55. package/dist/{define-agent-eval-C8V8sMqP.js → define-agent-eval-h-s-sI-v.js} +15 -9
  56. package/dist/define-agent-eval-h-s-sI-v.js.map +1 -0
  57. package/dist/{dspy-rlm-engine-CBYlPvNy.js → dspy-rlm-engine-DptEII26.js} +95 -15
  58. package/dist/dspy-rlm-engine-DptEII26.js.map +1 -0
  59. package/dist/{emitter-CPBAhxum.js → emitter-BpYFQPj4.js} +2 -18
  60. package/dist/emitter-BpYFQPj4.js.map +1 -0
  61. package/dist/{emitter-DGQGoLyj.d.ts → emitter-D_jYSGRd.d.ts} +4 -20
  62. package/dist/{emitter-DGQGoLyj.d.ts.map → emitter-D_jYSGRd.d.ts.map} +1 -1
  63. package/dist/{engine-BLzhNzoY.d.ts → engine-Cu5qD5Fc.d.ts} +9 -11
  64. package/dist/{engine-BLzhNzoY.d.ts.map → engine-Cu5qD5Fc.d.ts.map} +1 -1
  65. package/dist/{eval-campaign-CQuZrLR_.js → eval-campaign-BsXWL2-2.js} +17 -28
  66. package/dist/eval-campaign-BsXWL2-2.js.map +1 -0
  67. package/dist/{exact-types-ccQAyut1.d.ts → exact-types-qnexxJ1Z.d.ts} +2 -2
  68. package/dist/{exact-types-ccQAyut1.d.ts.map → exact-types-qnexxJ1Z.d.ts.map} +1 -1
  69. package/dist/{exec-y-DCLqK7.js → exec-D9WpA2p-.js} +2 -2
  70. package/dist/exec-D9WpA2p-.js.map +1 -0
  71. package/dist/experiment/index.d.ts +45 -11
  72. package/dist/experiment/index.d.ts.map +1 -1
  73. package/dist/experiment/index.js +30 -11
  74. package/dist/experiment/index.js.map +1 -1
  75. package/dist/{experiment-tracker-0MhuPArU.d.ts → experiment-tracker-DCO6Cz4s.d.ts} +2 -2
  76. package/dist/{experiment-tracker-0MhuPArU.d.ts.map → experiment-tracker-DCO6Cz4s.d.ts.map} +1 -1
  77. package/dist/{exporters-q9iL-2Jf.js → exporters-Df7TgHFv.js} +3 -3
  78. package/dist/exporters-Df7TgHFv.js.map +1 -0
  79. package/dist/{external-optimizer-contracts-DbLsm4Po.d.ts → external-optimizer-contracts-szBJ_1vh.d.ts} +2 -2
  80. package/dist/{external-optimizer-contracts-DbLsm4Po.d.ts.map → external-optimizer-contracts-szBJ_1vh.d.ts.map} +1 -1
  81. package/dist/{external-optimizer-process-x9oEXKsU.js → external-optimizer-process-WosTBChy.js} +4 -4
  82. package/dist/{external-optimizer-process-x9oEXKsU.js.map → external-optimizer-process-WosTBChy.js.map} +1 -1
  83. package/dist/{external-optimizer-subprocess-CKNb42oM.js → external-optimizer-subprocess-BIWbHpgD.js} +4 -4
  84. package/dist/{external-optimizer-subprocess-CKNb42oM.js.map → external-optimizer-subprocess-BIWbHpgD.js.map} +1 -1
  85. package/dist/{failure-cluster-BLURuWG4.d.ts → failure-cluster-CXL8NbEw.d.ts} +3 -3
  86. package/dist/{failure-cluster-BLURuWG4.d.ts.map → failure-cluster-CXL8NbEw.d.ts.map} +1 -1
  87. package/dist/{feedback-trajectory-DpTTjo0q.d.ts → feedback-trajectory-B3ZHaHV_.d.ts} +7 -7
  88. package/dist/{feedback-trajectory-DpTTjo0q.d.ts.map → feedback-trajectory-B3ZHaHV_.d.ts.map} +1 -1
  89. package/dist/fuzz.js +1 -1
  90. package/dist/{hf-dataset-XggBupCr.js → hf-dataset-D8_RNIis.js} +4 -4
  91. package/dist/{hf-dataset-XggBupCr.js.map → hf-dataset-D8_RNIis.js.map} +1 -1
  92. package/dist/hosted/index.d.ts +3 -14
  93. package/dist/hosted/index.d.ts.map +1 -1
  94. package/dist/hosted/index.js +2 -2
  95. package/dist/{index-Aj3WO3_a.d.ts → index-CGtH1piv.d.ts} +48 -26
  96. package/dist/index-CGtH1piv.d.ts.map +1 -0
  97. package/dist/{index-BNPtkBPf.d.ts → index-D-IiQIBB.d.ts} +5 -10
  98. package/dist/index-D-IiQIBB.d.ts.map +1 -0
  99. package/dist/{index-IQccV3Ou.d.ts → index-D-V8gCs_.d.ts} +13 -90
  100. package/dist/index-D-V8gCs_.d.ts.map +1 -0
  101. package/dist/{index-B8Ui1mr1.d.ts → index-lfaSeKSD.d.ts} +18 -2
  102. package/dist/index-lfaSeKSD.d.ts.map +1 -0
  103. package/dist/index-vrJugRal.d.ts +1 -0
  104. package/dist/index.d.ts +68 -56
  105. package/dist/index.d.ts.map +1 -1
  106. package/dist/index.js +59 -110
  107. package/dist/index.js.map +1 -1
  108. package/dist/{insight-report-BeT8KCgI.d.ts → insight-report-DRe8LB6d.d.ts} +4 -4
  109. package/dist/{insight-report-BeT8KCgI.d.ts.map → insight-report-DRe8LB6d.d.ts.map} +1 -1
  110. package/dist/{integrity-DL91tucI.js → integrity-CyWSSoQS.js} +2 -2
  111. package/dist/{integrity-DL91tucI.js.map → integrity-CyWSSoQS.js.map} +1 -1
  112. package/dist/{integrity-B0dZ96EO.d.ts → integrity-DUNX9Fao.d.ts} +3 -3
  113. package/dist/{integrity-B0dZ96EO.d.ts.map → integrity-DUNX9Fao.d.ts.map} +1 -1
  114. package/dist/{kind-factory-DmAa0h3K.js → kind-factory-DY8FdoXf.js} +3 -71
  115. package/dist/kind-factory-DY8FdoXf.js.map +1 -0
  116. package/dist/ledger-core/index.d.ts +2 -2
  117. package/dist/ledger-core/index.js +3 -3
  118. package/dist/{ledger-core-DTae9rv_.js → ledger-core-BOzlRygb.js} +2 -2
  119. package/dist/{ledger-core-DTae9rv_.js.map → ledger-core-BOzlRygb.js.map} +1 -1
  120. package/dist/{llm-client-Bg32RW0j.js → llm-client-hgDieDNN.js} +53 -98
  121. package/dist/llm-client-hgDieDNN.js.map +1 -0
  122. package/dist/{llm-judge-BqqMS8t7.js → llm-judge-BhasIPFT.js} +1135 -77
  123. package/dist/llm-judge-BhasIPFT.js.map +1 -0
  124. package/dist/{matrix-DrVnRp4G.d.ts → matrix-eXKRMHnL.d.ts} +74 -72
  125. package/dist/matrix-eXKRMHnL.d.ts.map +1 -0
  126. package/dist/meta-eval/index.d.ts +8 -6
  127. package/dist/meta-eval/index.d.ts.map +1 -1
  128. package/dist/meta-eval/index.js +8 -6
  129. package/dist/meta-eval/index.js.map +1 -1
  130. package/dist/{mint-BV6tLVWl.js → mint-DfODW1KW.js} +3 -3
  131. package/dist/{mint-BV6tLVWl.js.map → mint-DfODW1KW.js.map} +1 -1
  132. package/dist/multishot/golden/index.d.ts +2 -8
  133. package/dist/multishot/golden/index.d.ts.map +1 -1
  134. package/dist/multishot/golden/index.js +56 -86
  135. package/dist/multishot/golden/index.js.map +1 -1
  136. package/dist/multishot/index.d.ts +11 -46
  137. package/dist/multishot/index.d.ts.map +1 -1
  138. package/dist/multishot/index.js +30 -83
  139. package/dist/multishot/index.js.map +1 -1
  140. package/dist/openapi.json +1 -1
  141. package/dist/{opencode-sqlite-DJWAXLms.js → opencode-sqlite-eK6HW6dr.js} +2 -6
  142. package/dist/{opencode-sqlite-DJWAXLms.js.map → opencode-sqlite-eK6HW6dr.js.map} +1 -1
  143. package/dist/pipelines/index.d.ts +5 -5
  144. package/dist/pipelines/index.js +3 -3
  145. package/dist/{pre-registration-zFSLEiFU.d.ts → pre-registration-CzFCcwYk.d.ts} +55 -40
  146. package/dist/pre-registration-CzFCcwYk.d.ts.map +1 -0
  147. package/dist/pre-registration-KN9jkh58.js +110 -0
  148. package/dist/pre-registration-KN9jkh58.js.map +1 -0
  149. package/dist/{produced-state-Bnq4FaDO.js → produced-state-DZ89riy5.js} +8 -8
  150. package/dist/produced-state-DZ89riy5.js.map +1 -0
  151. package/dist/profile-cell.d.ts +1 -1
  152. package/dist/profile-cell.js +31 -5
  153. package/dist/profile-cell.js.map +1 -1
  154. package/dist/{promotion-policy-DLOUkYhI.d.ts → promotion-policy-DtnOIZvk.d.ts} +2 -2
  155. package/dist/{promotion-policy-DLOUkYhI.d.ts.map → promotion-policy-DtnOIZvk.d.ts.map} +1 -1
  156. package/dist/{query-Di7eEQ79.js → query-CHmMP42p.js} +20 -11
  157. package/dist/query-CHmMP42p.js.map +1 -0
  158. package/dist/{query-CJ_DX8vl.d.ts → query-DxPYqpmT.d.ts} +10 -4
  159. package/dist/query-DxPYqpmT.d.ts.map +1 -0
  160. package/dist/raw-provider-sink-BU29Sh8h.d.ts +134 -0
  161. package/dist/raw-provider-sink-BU29Sh8h.d.ts.map +1 -0
  162. package/dist/{registry-BQwrSYpC.d.ts → registry-8You7OK1.d.ts} +5 -7
  163. package/dist/{registry-BQwrSYpC.d.ts.map → registry-8You7OK1.d.ts.map} +1 -1
  164. package/dist/{release-confidence-BknrpBnO.js → release-confidence-DKfD2RYU.js} +28 -14
  165. package/dist/release-confidence-DKfD2RYU.js.map +1 -0
  166. package/dist/{release-confidence-4XrqlpFD.d.ts → release-confidence-Dqt0NFep.d.ts} +7 -6
  167. package/dist/release-confidence-Dqt0NFep.d.ts.map +1 -0
  168. package/dist/reporting.d.ts +3 -3
  169. package/dist/reporting.js +3 -3
  170. package/dist/{researcher-DJnoUE8c.d.ts → researcher-Cz565b7D.d.ts} +34 -21
  171. package/dist/researcher-Cz565b7D.d.ts.map +1 -0
  172. package/dist/{reward-hacking-62tojkQd.d.ts → reward-hacking-MBf7qpSB.d.ts} +2 -2
  173. package/dist/{reward-hacking-62tojkQd.d.ts.map → reward-hacking-MBf7qpSB.d.ts.map} +1 -1
  174. package/dist/{reward-hacking-C0x0xihA.js → reward-hacking-t4lB1yt8.js} +2 -2
  175. package/dist/{reward-hacking-C0x0xihA.js.map → reward-hacking-t4lB1yt8.js.map} +1 -1
  176. package/dist/rl.d.ts +11 -42
  177. package/dist/rl.d.ts.map +1 -1
  178. package/dist/rl.js +41 -24
  179. package/dist/rl.js.map +1 -1
  180. package/dist/rollout/index.d.ts +3 -3
  181. package/dist/rollout/index.js +7 -7
  182. package/dist/{rollout-ytVQ7WT8.js → rollout-Dm2tSdiQ.js} +6 -6
  183. package/dist/{rollout-ytVQ7WT8.js.map → rollout-Dm2tSdiQ.js.map} +1 -1
  184. package/dist/{rubric-predictive-validity-CzxLoZge.js → rubric-predictive-validity-CK8SCOg-.js} +5 -15
  185. package/dist/rubric-predictive-validity-CK8SCOg-.js.map +1 -0
  186. package/dist/{rubric-predictive-validity-C7LnNvF2.d.ts → rubric-predictive-validity-CxycqzX5.d.ts} +4 -3
  187. package/dist/rubric-predictive-validity-CxycqzX5.d.ts.map +1 -0
  188. package/dist/{run-record-D2lDdSAz.js → run-record-BC0ebuRP.js} +2 -2
  189. package/dist/{run-record-D2lDdSAz.js.map → run-record-BC0ebuRP.js.map} +1 -1
  190. package/dist/{run-record-DVV82Gwh.d.ts → run-record-VVy4T9OW.d.ts} +3 -3
  191. package/dist/{run-record-DVV82Gwh.d.ts.map → run-record-VVy4T9OW.d.ts.map} +1 -1
  192. package/dist/{schema-BtVldJ3T.d.ts → schema-Bjgdsn73.d.ts} +2 -4
  193. package/dist/{schema-BtVldJ3T.d.ts.map → schema-Bjgdsn73.d.ts.map} +1 -1
  194. package/dist/{schema-Cef2cFmb.d.ts → schema-BzWDXhOR.d.ts} +2 -5
  195. package/dist/schema-BzWDXhOR.d.ts.map +1 -0
  196. package/dist/{schema-C6DW4ZHR.js → schema-C1aaAxTf.js} +2 -2
  197. package/dist/schema-C1aaAxTf.js.map +1 -0
  198. package/dist/{schema-CRhEY1SO.js → schema-k6ZBftVv.js} +2 -8
  199. package/dist/{schema-CRhEY1SO.js.map → schema-k6ZBftVv.js.map} +1 -1
  200. package/dist/{semantic-concept-judge-laMCnTLn.js → semantic-concept-judge-BSkKKHeq.js} +14 -38
  201. package/dist/semantic-concept-judge-BSkKKHeq.js.map +1 -0
  202. package/dist/{sequential-eprocess-CbUt2htw.js → sequential-eprocess-D1jKoihe.js} +49 -2
  203. package/dist/sequential-eprocess-D1jKoihe.js.map +1 -0
  204. package/dist/{sequential-C458DXNf.js → sequential-rYW-Ophm.js} +41 -16
  205. package/dist/sequential-rYW-Ophm.js.map +1 -0
  206. package/dist/{series-convergence-BxKEgBwA.d.ts → series-convergence-D9WgpXGi.d.ts} +2 -2
  207. package/dist/{series-convergence-BxKEgBwA.d.ts.map → series-convergence-D9WgpXGi.d.ts.map} +1 -1
  208. package/dist/{server-dIWwF3j_.js → server-BtFd4uzB.js} +19 -42
  209. package/dist/server-BtFd4uzB.js.map +1 -0
  210. package/dist/{skillopt-optimization-method-CPBlTcj5.js → skillopt-optimization-method-DbaekMcn.js} +794 -8
  211. package/dist/skillopt-optimization-method-DbaekMcn.js.map +1 -0
  212. package/dist/{skillopt-optimization-method-BDD_o1xE.d.ts → skillopt-optimization-method-x7TTF23P.d.ts} +20 -7
  213. package/dist/{skillopt-optimization-method-BDD_o1xE.d.ts.map → skillopt-optimization-method-x7TTF23P.d.ts.map} +1 -1
  214. package/dist/{statistical-heldout-_woZ9q9j.d.ts → statistical-heldout-Cy3EhjlC.d.ts} +21 -8
  215. package/dist/statistical-heldout-Cy3EhjlC.d.ts.map +1 -0
  216. package/dist/{steps-AmkT-GIM.d.ts → steps-CiNVJry_.d.ts} +2 -17
  217. package/dist/steps-CiNVJry_.d.ts.map +1 -0
  218. package/dist/{store-CT9YIIve.d.ts → store-B06JdC56.d.ts} +2 -2
  219. package/dist/{store-CT9YIIve.d.ts.map → store-B06JdC56.d.ts.map} +1 -1
  220. package/dist/{store-otlp-CDYWW_8N.js → store-otlp-C_Rq5I4D.js} +2 -2
  221. package/dist/{store-otlp-CDYWW_8N.js.map → store-otlp-C_Rq5I4D.js.map} +1 -1
  222. package/dist/{store-tool-spans-Br2_IUhm.d.ts → store-tool-spans-DPUG7UUY.d.ts} +6 -6
  223. package/dist/{store-tool-spans-Br2_IUhm.d.ts.map → store-tool-spans-DPUG7UUY.d.ts.map} +1 -1
  224. package/dist/{store-tool-spans-CykkbOlv.js → store-tool-spans-Dlh9vkFK.js} +3 -3
  225. package/dist/{store-tool-spans-CykkbOlv.js.map → store-tool-spans-Dlh9vkFK.js.map} +1 -1
  226. package/dist/storyboard/index.d.ts +1 -1
  227. package/dist/{summary-report-DW2bEpdB.js → summary-report-BI5hUtvK.js} +6 -16
  228. package/dist/summary-report-BI5hUtvK.js.map +1 -0
  229. package/dist/{summary-report-B__Y5ub3.d.ts → summary-report-CC07PhEL.d.ts} +6 -5
  230. package/dist/summary-report-CC07PhEL.d.ts.map +1 -0
  231. package/dist/supervisor-run/index.d.ts +3 -16
  232. package/dist/supervisor-run/index.d.ts.map +1 -1
  233. package/dist/supervisor-run/index.js +3 -3
  234. package/dist/supervisor-run/index.js.map +1 -1
  235. package/dist/{task-failure-attributes--ZTP3tYO.js → task-failure-attributes-DTl-7-Kw.js} +3 -3
  236. package/dist/{task-failure-attributes--ZTP3tYO.js.map → task-failure-attributes-DTl-7-Kw.js.map} +1 -1
  237. package/dist/{tool-groups-B4tqh8jB.d.ts → tool-groups-Ci8i9ErB.d.ts} +3 -3
  238. package/dist/tool-groups-Ci8i9ErB.d.ts.map +1 -0
  239. package/dist/{tool-waste-C-VHSRwF.js → tool-waste-BqzmVdJk.js} +2 -2
  240. package/dist/{tool-waste-C-VHSRwF.js.map → tool-waste-BqzmVdJk.js.map} +1 -1
  241. package/dist/{tool-waste-DjRDEsuI.d.ts → tool-waste-Dro0gJi3.d.ts} +4 -4
  242. package/dist/{tool-waste-DjRDEsuI.d.ts.map → tool-waste-Dro0gJi3.d.ts.map} +1 -1
  243. package/dist/trace-repair/index.d.ts +4 -77
  244. package/dist/trace-repair/index.d.ts.map +1 -1
  245. package/dist/trace-repair/index.js +5 -15
  246. package/dist/trace-repair/index.js.map +1 -1
  247. package/dist/traces.d.ts +13 -23
  248. package/dist/traces.d.ts.map +1 -1
  249. package/dist/traces.js +9 -20
  250. package/dist/traces.js.map +1 -1
  251. package/dist/{trajectory-YC15QDYQ.d.ts → trajectory-Bi157Gun.d.ts} +3 -3
  252. package/dist/{trajectory-YC15QDYQ.d.ts.map → trajectory-Bi157Gun.d.ts.map} +1 -1
  253. package/dist/trajectory-replay/index.d.ts +5 -5
  254. package/dist/trajectory-replay/index.js +5 -5
  255. package/dist/{provenance-oA4-zUqm.d.ts → transient-failure-DKF5Mofa.d.ts} +468 -13
  256. package/dist/transient-failure-DKF5Mofa.d.ts.map +1 -0
  257. package/dist/types-B3jzCp0p.js.map +1 -1
  258. package/dist/{types-CLAwnY-L.d.ts → types-BPb2Kf_C2.d.ts} +3 -3
  259. package/dist/types-BPb2Kf_C2.d.ts.map +1 -0
  260. package/dist/types-Bfk0uxRj.d.ts +443 -0
  261. package/dist/types-Bfk0uxRj.d.ts.map +1 -0
  262. package/dist/{types-DdFNuyxQ.d.ts → types-D4s7Z6nq.d.ts} +30 -6
  263. package/dist/types-D4s7Z6nq.d.ts.map +1 -0
  264. package/dist/{types-B2NsbrNy.d.ts → types-D9ssmxKL.d.ts} +3 -3
  265. package/dist/{types-B2NsbrNy.d.ts.map → types-D9ssmxKL.d.ts.map} +1 -1
  266. package/dist/{types-I5WwVzQ7.d.ts → types-DeIUdzNd.d.ts} +2 -2
  267. package/dist/{types-I5WwVzQ7.d.ts.map → types-DeIUdzNd.d.ts.map} +1 -1
  268. package/dist/{verdict-BndeTAh_.js → verdict-B0xltqu6.js} +2 -2
  269. package/dist/{verdict-BndeTAh_.js.map → verdict-B0xltqu6.js.map} +1 -1
  270. package/dist/verdict-cache-CdVVTVmn.js +88 -0
  271. package/dist/verdict-cache-CdVVTVmn.js.map +1 -0
  272. package/dist/wire/index.d.ts +21 -111
  273. package/dist/wire/index.d.ts.map +1 -1
  274. package/dist/wire/index.js +2 -2
  275. package/docs/building-doctrine.md +3 -3
  276. package/docs/campaign-proposers.md +41 -10
  277. package/docs/design/statistics-decisions.md +89 -1
  278. package/docs/eval-surface-map.md +14 -0
  279. package/docs/experiment.md +19 -2
  280. package/docs/feedback-trajectories.md +1 -1
  281. package/docs/multishot-golden-records.md +4 -4
  282. package/docs/public-api.md +1616 -0
  283. package/docs/research-report-methodology.md +1 -1
  284. package/docs/search-history-receipts.md +39 -1
  285. package/docs/trace-analysis.md +1 -1
  286. package/docs/trace-repair-admission.md +1 -1
  287. package/docs/trace-repair-continuation.md +1 -1
  288. package/docs/verdicts.md +24 -0
  289. package/package.json +7 -3
  290. package/dist/active-curriculum-C4mk67HP.js.map +0 -1
  291. package/dist/agent-profile-cell-BkcRDikH.d.ts.map +0 -1
  292. package/dist/backend-integrity-DOCa_QrR.d.ts.map +0 -1
  293. package/dist/benchmark-command-BU1Las59.js.map +0 -1
  294. package/dist/campaign-la-gEYNz.js.map +0 -1
  295. package/dist/canonical-D-XsTQ6_.js.map +0 -1
  296. package/dist/client-LIuo-KPv.js.map +0 -1
  297. package/dist/define-agent-eval-C8V8sMqP.js.map +0 -1
  298. package/dist/define-agent-eval-CEQWL9Hy.d.ts.map +0 -1
  299. package/dist/dspy-rlm-engine-CBYlPvNy.js.map +0 -1
  300. package/dist/emitter-CPBAhxum.js.map +0 -1
  301. package/dist/eval-campaign-CQuZrLR_.js.map +0 -1
  302. package/dist/exec-y-DCLqK7.js.map +0 -1
  303. package/dist/exporters-q9iL-2Jf.js.map +0 -1
  304. package/dist/index-Aj3WO3_a.d.ts.map +0 -1
  305. package/dist/index-B8Ui1mr1.d.ts.map +0 -1
  306. package/dist/index-BNPtkBPf.d.ts.map +0 -1
  307. package/dist/index-C1ravkGA.d.ts +0 -1
  308. package/dist/index-IQccV3Ou.d.ts.map +0 -1
  309. package/dist/kind-factory-DmAa0h3K.js.map +0 -1
  310. package/dist/llm-client-Bg32RW0j.js.map +0 -1
  311. package/dist/llm-judge-BqqMS8t7.js.map +0 -1
  312. package/dist/matrix-DrVnRp4G.d.ts.map +0 -1
  313. package/dist/pre-registration-DakwTRXk.js +0 -96
  314. package/dist/pre-registration-DakwTRXk.js.map +0 -1
  315. package/dist/pre-registration-zFSLEiFU.d.ts.map +0 -1
  316. package/dist/produced-state-Bnq4FaDO.js.map +0 -1
  317. package/dist/provenance-oA4-zUqm.d.ts.map +0 -1
  318. package/dist/query-CJ_DX8vl.d.ts.map +0 -1
  319. package/dist/query-Di7eEQ79.js.map +0 -1
  320. package/dist/release-confidence-4XrqlpFD.d.ts.map +0 -1
  321. package/dist/release-confidence-BknrpBnO.js.map +0 -1
  322. package/dist/researcher-DJnoUE8c.d.ts.map +0 -1
  323. package/dist/rubric-predictive-validity-C7LnNvF2.d.ts.map +0 -1
  324. package/dist/rubric-predictive-validity-CzxLoZge.js.map +0 -1
  325. package/dist/schema-C6DW4ZHR.js.map +0 -1
  326. package/dist/schema-Cef2cFmb.d.ts.map +0 -1
  327. package/dist/semantic-concept-judge-laMCnTLn.js.map +0 -1
  328. package/dist/sequential-C458DXNf.js.map +0 -1
  329. package/dist/sequential-eprocess-CbUt2htw.js.map +0 -1
  330. package/dist/server-dIWwF3j_.js.map +0 -1
  331. package/dist/skillopt-optimization-method-CPBlTcj5.js.map +0 -1
  332. package/dist/statistical-heldout-_woZ9q9j.d.ts.map +0 -1
  333. package/dist/steps-AmkT-GIM.d.ts.map +0 -1
  334. package/dist/summary-report-B__Y5ub3.d.ts.map +0 -1
  335. package/dist/summary-report-DW2bEpdB.js.map +0 -1
  336. package/dist/tool-groups-B4tqh8jB.d.ts.map +0 -1
  337. package/dist/types-CLAwnY-L.d.ts.map +0 -1
  338. package/dist/types-DdFNuyxQ.d.ts.map +0 -1
  339. package/dist/types-jUBXJ7Iz.d.ts +0 -884
  340. package/dist/types-jUBXJ7Iz.d.ts.map +0 -1
  341. package/dist/verdict-cache-mZf5FEiY.js +0 -107
  342. package/dist/verdict-cache-mZf5FEiY.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"ledger-core-DTae9rv_.js","names":[],"sources":["../src/ledger-core/atomic-file-lock.ts","../src/concurrency.ts","../src/ledger-core/journal-file.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 fsyncSync,\n linkSync,\n openSync,\n readFileSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport { hostname } from 'node:os'\n\nexport interface AtomicFileLockOwner {\n readonly pid: number\n readonly host: string\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 = { pid, host: hostname(), 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 writeFileSync(descriptor, `${canonicalOwner(owner)}\\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\nfunction ownerState(lockPath: string): OwnerState {\n const owner = readOwner(lockPath)\n if (!owner) return { state: 'missing' }\n if (owner.host !== hostname()) return { state: 'held', owner }\n try {\n process.kill(owner.pid, 0)\n return { state: 'held', owner }\n } catch (error) {\n if (isNoSuchProcess(error)) return { state: 'stale', owner }\n return { state: 'held', owner }\n }\n}\n\nfunction readOwner(lockPath: string): AtomicFileLockOwner | undefined {\n let contents: string\n try {\n contents = readFileSync(lockPath, 'utf8').trim()\n } catch (error) {\n if (isMissing(error)) return undefined\n throw error\n }\n\n let value: unknown\n try {\n value = JSON.parse(contents)\n } catch (error) {\n throw invalidOwner(lockPath, error)\n }\n if (!isOwner(value)) throw invalidOwner(lockPath)\n return value\n}\n\nfunction isOwner(value: unknown): value is AtomicFileLockOwner {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const record = value as Record<string, unknown>\n return (\n Object.keys(record).length === 3 &&\n Number.isSafeInteger(record.pid) &&\n Number(record.pid) > 0 &&\n typeof record.host === 'string' &&\n record.host.trim().length > 0 &&\n typeof record.nonce === 'string' &&\n record.nonce.trim().length > 0\n )\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) !== 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 isNoSuchProcess(error: unknown): boolean {\n return error instanceof Error && 'code' in error && error.code === 'ESRCH'\n}\n\nfunction unlinkIfExists(path: string): void {\n try {\n unlinkSync(path)\n } catch (error) {\n if (!isMissing(error)) throw error\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\nexport interface 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","/** 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 * 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. */\nexport function verifyEntriesAgainstTrustedHead(\n entries: readonly LedgerAnchoredEntry[],\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[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 * 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 { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { Mutex } from '../concurrency'\nimport { canonicalString, hashCanonical, type LedgerHash } from './canonical'\nimport { appendLedgerLine, type LedgerFileContext, withLedgerFileLock } from './journal-file'\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 replayed over chain-verified entries in order.\n * `apply` throws (via the codec's error taxonomy) on an invalid transition;\n * `finish` builds the consumer's projection once every entry was applied. */\nexport interface LedgerProjector<Entry, Projection> {\n apply(entry: Entry, index: number): void\n finish(entries: 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. */\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}\n\nexport interface LedgerReplayResult<Entry, Projection> {\n entries: Entry[]\n projection: 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}\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; `append` and\n * `replay` validate the complete existing file under the locks. */\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 private readonly codec: LedgerJournalCodec<Header, Event, Projection>\n private readonly mutex: Mutex\n private readonly requireTrustedHead: boolean\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.codec = codec\n this.mutex = mutexFor(this.path)\n this.requireTrustedHead = options.requireTrustedHead === true\n }\n\n async replay(): Promise<LedgerReplayResult<LedgerEntryOf<Header, Event>, Projection>> {\n return this.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () => this.replayLocked()),\n )\n }\n\n async append(\n event: Event,\n options: LedgerAppendOptions = {},\n ): Promise<LedgerAppendResult<LedgerEntryOf<Header, Event>, Projection>> {\n return this.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () => {\n const before = this.replayLocked()\n const existing = before.entries.find((entry) => entry.event.eventId === event.eventId)\n if (existing) {\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(existing, before.entries)\n return { entry: existing, appended: false, projection: before.projection }\n }\n\n const material = {\n ...this.codec.header,\n sequence: before.entries.length,\n previousHash: before.entries.at(-1)?.entryHash ?? null,\n event,\n }\n const entry = { ...material, entryHash: hashCanonical(material) }\n\n // Apply the state transition before spending an append: an entry the\n // projector rejects must never reach the durable file.\n const projection = this.project([...before.entries, entry])\n appendLedgerLine(this.path, `${canonicalString(entry)}\\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 writeTrustedHeadFile(\n this.trustedHeadPath,\n { sequence: entry.sequence, entryHash: entry.entryHash },\n this.codec,\n )\n }\n return { entry, appended: true, projection }\n }),\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.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () => {\n const entries = this.readEntries()\n this.project(entries)\n // `requireTrustedHead` is deliberately not applied here: pinning is how\n // a journal that lacks a pin acquires one.\n this.verifyTrustedHead(entries, false)\n const last = entries.at(-1)\n if (last === undefined) {\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 = { sequence: last.sequence, entryHash: last.entryHash }\n writeTrustedHeadFile(this.trustedHeadPath, head, this.codec)\n return head\n }),\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.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () =>\n clearTrustedHeadFile(this.trustedHeadPath, this.codec),\n ),\n )\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 `replayLocked` has just verified: every entry up to this one\n * is bound to it by hash, so the pin can only ever come to name more history\n * than it 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 entry: LedgerEntryOf<Header, Event>,\n entries: LedgerEntryOf<Header, Event>[],\n ): void {\n const pinned = readTrustedHeadFile(this.trustedHeadPath, this.codec)\n if (pinned === null) {\n if (entry.sequence !== entries.length - 1) return\n } else if (pinned.sequence >= entry.sequence) {\n return\n }\n writeTrustedHeadFile(\n this.trustedHeadPath,\n { sequence: entry.sequence, entryHash: entry.entryHash },\n this.codec,\n )\n }\n\n private replayLocked(): LedgerReplayResult<LedgerEntryOf<Header, Event>, Projection> {\n const entries = this.readEntries()\n const projection = this.project(entries)\n // The anchor is meaningful only over a chain that already verified, so it\n // is checked last — and on every read path, so a violated pin is refused\n // before an append can extend the journal over it.\n this.verifyTrustedHead(entries, this.requireTrustedHead)\n return { entries, projection }\n }\n\n private verifyTrustedHead(entries: LedgerEntryOf<Header, Event>[], requirePin: boolean): void {\n const pinned = readTrustedHeadFile(this.trustedHeadPath, this.codec)\n if (pinned === null) {\n if (requirePin && entries.length > 0) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has ${entries.length} 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 verifyEntriesAgainstTrustedHead(entries, pinned, this.codec, {\n subject: `${this.codec.subject} ${this.path}`,\n trustedHeadPath: this.trustedHeadPath,\n })\n }\n\n private readEntries(): LedgerEntryOf<Header, Event>[] {\n if (!existsSync(this.path)) return []\n const text = readFileSync(this.path, 'utf8')\n if (text.length === 0) return []\n if (!text.endsWith('\\n')) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has a truncated final record (missing newline)`,\n )\n }\n\n const lines = text.slice(0, -1).split('\\n')\n const entries: LedgerEntryOf<Header, Event>[] = []\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index]!\n if (line.length === 0) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has a blank row at line ${index + 1}`,\n )\n }\n let raw: unknown\n try {\n raw = JSON.parse(line)\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 const entry = this.codec.parseEntry(raw, { path: this.path, line: index + 1 })\n let canonical: string\n try {\n canonical = canonicalString(entry)\n } catch (error) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has a row with no canonical JSON form at line ${index + 1}`,\n { cause: error },\n )\n }\n if (line !== canonical) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has non-canonical bytes at line ${index + 1}`,\n )\n }\n entries.push(entry)\n }\n return entries\n }\n\n private project(entries: LedgerEntryOf<Header, Event>[]): Projection {\n const projector = this.codec.createProjector()\n const eventIds = new Set<string>()\n let expectedPrevious: LedgerHash | null = null\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index]!\n this.codec.checkEntryHeader(entry, index)\n if (entry.sequence !== index) {\n throw this.codec.integrityError(\n `entry ${entry.event.eventId} has sequence ${entry.sequence}, expected ${index}`,\n )\n }\n if (entry.previousHash !== expectedPrevious) {\n throw this.codec.integrityError(\n `entry ${entry.event.eventId} does not extend the previous hash`,\n )\n }\n const { entryHash: _entryHash, ...material } = entry\n const expectedHash = hashCanonical(material)\n if (entry.entryHash !== expectedHash) {\n throw this.codec.integrityError(\n `entry ${entry.event.eventId} hash mismatch: expected ${expectedHash}, got ${entry.entryHash}`,\n )\n }\n expectedPrevious = entry.entryHash\n if (eventIds.has(entry.event.eventId)) {\n throw this.codec.integrityError(\n `duplicate eventId ${entry.event.eventId} in durable ledger`,\n )\n }\n eventIds.add(entry.event.eventId)\n projector.apply(entry, index)\n }\n return projector.finish(entries)\n }\n}\n"],"mappings":";;;;;;;AAyCA,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;EAAK,MAAM,SAAS;EAAG,OAAO,WAAW;CAAE;CAChF,KAAK,IAAI,UAAU,GAAG,UAAU,GAAG,WAAW,GAAG;EAC/C,IAAI,WAAW,aAAa,QAAQ,QAAQ,CAAC,GAAG;GAC9C,M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QAAQ,GAAG,KAAK,KAAK,iDAAiD,QAAQ,KAC5F,EAAE,OAAO,MAAM,CACjB;GACF;GACA,IAAI,SAAS,WACX,MAAM,KAAK,MAAM,eACf,GAAG,KAAK,MAAM,QAAQ,GAAG,KAAK,KAAK,mCAAmC,QAAQ,GAChF;GAEF,QAAQ,KAAK,KAAK;EACpB;EACA,OAAO;CACT;CAEA,QAAgB,SAAqD;EACnE,MAAM,YAAY,KAAK,MAAM,gBAAgB;EAC7C,MAAM,2BAAW,IAAI,IAAY;EACjC,IAAI,mBAAsC;EAC1C,KAAK,IAAI,QAAQ,GAAG,QAAQ,QAAQ,QAAQ,SAAS,GAAG;GACtD,MAAM,QAAQ,QAAQ;GACtB,KAAK,MAAM,iBAAiB,OAAO,KAAK;GACxC,IAAI,MAAM,aAAa,OACrB,MAAM,KAAK,MAAM,eACf,SAAS,MAAM,MAAM,QAAQ,gBAAgB,MAAM,SAAS,aAAa,OAC3E;GAEF,IAAI,MAAM,iBAAiB,kBACzB,MAAM,KAAK,MAAM,eACf,SAAS,MAAM,MAAM,QAAQ,mCAC/B;GAEF,MAAM,EAAE,WAAW,YAAY,GAAG,aAAa;GAC/C,MAAM,eAAe,cAAc,QAAQ;GAC3C,IAAI,MAAM,cAAc,cACtB,MAAM,KAAK,MAAM,eACf,SAAS,MAAM,MAAM,QAAQ,2BAA2B,aAAa,QAAQ,MAAM,WACrF;GAEF,mBAAmB,MAAM;GACzB,IAAI,SAAS,IAAI,MAAM,MAAM,OAAO,GAClC,MAAM,KAAK,MAAM,eACf,qBAAqB,MAAM,MAAM,QAAQ,mBAC3C;GAEF,SAAS,IAAI,MAAM,MAAM,OAAO;GAChC,UAAU,MAAM,OAAO,KAAK;EAC9B;EACA,OAAO,UAAU,OAAO,OAAO;CACjC;AACF"}
1
+ {"version":3,"file":"ledger-core-BOzlRygb.js","names":[],"sources":["../src/ledger-core/atomic-file-lock.ts","../src/concurrency.ts","../src/ledger-core/journal-file.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 fsyncSync,\n linkSync,\n openSync,\n readFileSync,\n renameSync,\n unlinkSync,\n writeFileSync,\n} from 'node:fs'\nimport { hostname } from 'node:os'\n\nexport interface AtomicFileLockOwner {\n readonly pid: number\n readonly host: string\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 = { pid, host: hostname(), 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 writeFileSync(descriptor, `${canonicalOwner(owner)}\\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\nfunction ownerState(lockPath: string): OwnerState {\n const owner = readOwner(lockPath)\n if (!owner) return { state: 'missing' }\n if (owner.host !== hostname()) return { state: 'held', owner }\n try {\n process.kill(owner.pid, 0)\n return { state: 'held', owner }\n } catch (error) {\n if (isNoSuchProcess(error)) return { state: 'stale', owner }\n return { state: 'held', owner }\n }\n}\n\nfunction readOwner(lockPath: string): AtomicFileLockOwner | undefined {\n let contents: string\n try {\n contents = readFileSync(lockPath, 'utf8').trim()\n } catch (error) {\n if (isMissing(error)) return undefined\n throw error\n }\n\n let value: unknown\n try {\n value = JSON.parse(contents)\n } catch (error) {\n throw invalidOwner(lockPath, error)\n }\n if (!isOwner(value)) throw invalidOwner(lockPath)\n return value\n}\n\nfunction isOwner(value: unknown): value is AtomicFileLockOwner {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false\n const record = value as Record<string, unknown>\n return (\n Object.keys(record).length === 3 &&\n Number.isSafeInteger(record.pid) &&\n Number(record.pid) > 0 &&\n typeof record.host === 'string' &&\n record.host.trim().length > 0 &&\n typeof record.nonce === 'string' &&\n record.nonce.trim().length > 0\n )\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) !== 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 isNoSuchProcess(error: unknown): boolean {\n return error instanceof Error && 'code' in error && error.code === 'ESRCH'\n}\n\nfunction unlinkIfExists(path: string): void {\n try {\n unlinkSync(path)\n } catch (error) {\n if (!isMissing(error)) throw error\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\nexport interface 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","/** 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 * 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. */\nexport function verifyEntriesAgainstTrustedHead(\n entries: readonly LedgerAnchoredEntry[],\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[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 * 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 { existsSync, readFileSync } from 'node:fs'\nimport { resolve } from 'node:path'\nimport { Mutex } from '../concurrency'\nimport { canonicalString, hashCanonical, type LedgerHash } from './canonical'\nimport { appendLedgerLine, type LedgerFileContext, withLedgerFileLock } from './journal-file'\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 replayed over chain-verified entries in order.\n * `apply` throws (via the codec's error taxonomy) on an invalid transition;\n * `finish` builds the consumer's projection once every entry was applied. */\nexport interface LedgerProjector<Entry, Projection> {\n apply(entry: Entry, index: number): void\n finish(entries: 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. */\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}\n\nexport interface LedgerReplayResult<Entry, Projection> {\n entries: Entry[]\n projection: 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}\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; `append` and\n * `replay` validate the complete existing file under the locks. */\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 private readonly codec: LedgerJournalCodec<Header, Event, Projection>\n private readonly mutex: Mutex\n private readonly requireTrustedHead: boolean\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.codec = codec\n this.mutex = mutexFor(this.path)\n this.requireTrustedHead = options.requireTrustedHead === true\n }\n\n async replay(): Promise<LedgerReplayResult<LedgerEntryOf<Header, Event>, Projection>> {\n return this.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () => this.replayLocked()),\n )\n }\n\n async append(\n event: Event,\n options: LedgerAppendOptions = {},\n ): Promise<LedgerAppendResult<LedgerEntryOf<Header, Event>, Projection>> {\n return this.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () => {\n const before = this.replayLocked()\n const existing = before.entries.find((entry) => entry.event.eventId === event.eventId)\n if (existing) {\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(existing, before.entries)\n return { entry: existing, appended: false, projection: before.projection }\n }\n\n const material = {\n ...this.codec.header,\n sequence: before.entries.length,\n previousHash: before.entries.at(-1)?.entryHash ?? null,\n event,\n }\n const entry = { ...material, entryHash: hashCanonical(material) }\n\n // Apply the state transition before spending an append: an entry the\n // projector rejects must never reach the durable file.\n const projection = this.project([...before.entries, entry])\n appendLedgerLine(this.path, `${canonicalString(entry)}\\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 writeTrustedHeadFile(\n this.trustedHeadPath,\n { sequence: entry.sequence, entryHash: entry.entryHash },\n this.codec,\n )\n }\n return { entry, appended: true, projection }\n }),\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.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () => {\n const entries = this.readEntries()\n this.project(entries)\n // `requireTrustedHead` is deliberately not applied here: pinning is how\n // a journal that lacks a pin acquires one.\n this.verifyTrustedHead(entries, false)\n const last = entries.at(-1)\n if (last === undefined) {\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 = { sequence: last.sequence, entryHash: last.entryHash }\n writeTrustedHeadFile(this.trustedHeadPath, head, this.codec)\n return head\n }),\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.mutex.runExclusive(() =>\n withLedgerFileLock(this.path, this.codec, () =>\n clearTrustedHeadFile(this.trustedHeadPath, this.codec),\n ),\n )\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 `replayLocked` has just verified: every entry up to this one\n * is bound to it by hash, so the pin can only ever come to name more history\n * than it 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 entry: LedgerEntryOf<Header, Event>,\n entries: LedgerEntryOf<Header, Event>[],\n ): void {\n const pinned = readTrustedHeadFile(this.trustedHeadPath, this.codec)\n if (pinned === null) {\n if (entry.sequence !== entries.length - 1) return\n } else if (pinned.sequence >= entry.sequence) {\n return\n }\n writeTrustedHeadFile(\n this.trustedHeadPath,\n { sequence: entry.sequence, entryHash: entry.entryHash },\n this.codec,\n )\n }\n\n private replayLocked(): LedgerReplayResult<LedgerEntryOf<Header, Event>, Projection> {\n const entries = this.readEntries()\n const projection = this.project(entries)\n // The anchor is meaningful only over a chain that already verified, so it\n // is checked last — and on every read path, so a violated pin is refused\n // before an append can extend the journal over it.\n this.verifyTrustedHead(entries, this.requireTrustedHead)\n return { entries, projection }\n }\n\n private verifyTrustedHead(entries: LedgerEntryOf<Header, Event>[], requirePin: boolean): void {\n const pinned = readTrustedHeadFile(this.trustedHeadPath, this.codec)\n if (pinned === null) {\n if (requirePin && entries.length > 0) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has ${entries.length} 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 verifyEntriesAgainstTrustedHead(entries, pinned, this.codec, {\n subject: `${this.codec.subject} ${this.path}`,\n trustedHeadPath: this.trustedHeadPath,\n })\n }\n\n private readEntries(): LedgerEntryOf<Header, Event>[] {\n if (!existsSync(this.path)) return []\n const text = readFileSync(this.path, 'utf8')\n if (text.length === 0) return []\n if (!text.endsWith('\\n')) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has a truncated final record (missing newline)`,\n )\n }\n\n const lines = text.slice(0, -1).split('\\n')\n const entries: LedgerEntryOf<Header, Event>[] = []\n for (let index = 0; index < lines.length; index += 1) {\n const line = lines[index]!\n if (line.length === 0) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has a blank row at line ${index + 1}`,\n )\n }\n let raw: unknown\n try {\n raw = JSON.parse(line)\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 const entry = this.codec.parseEntry(raw, { path: this.path, line: index + 1 })\n let canonical: string\n try {\n canonical = canonicalString(entry)\n } catch (error) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has a row with no canonical JSON form at line ${index + 1}`,\n { cause: error },\n )\n }\n if (line !== canonical) {\n throw this.codec.integrityError(\n `${this.codec.subject} ${this.path} has non-canonical bytes at line ${index + 1}`,\n )\n }\n entries.push(entry)\n }\n return entries\n }\n\n private project(entries: LedgerEntryOf<Header, Event>[]): Projection {\n const projector = this.codec.createProjector()\n const eventIds = new Set<string>()\n let expectedPrevious: LedgerHash | null = null\n for (let index = 0; index < entries.length; index += 1) {\n const entry = entries[index]!\n this.codec.checkEntryHeader(entry, index)\n if (entry.sequence !== index) {\n throw this.codec.integrityError(\n `entry ${entry.event.eventId} has sequence ${entry.sequence}, expected ${index}`,\n )\n }\n if (entry.previousHash !== expectedPrevious) {\n throw this.codec.integrityError(\n `entry ${entry.event.eventId} does not extend the previous hash`,\n )\n }\n const { entryHash: _entryHash, ...material } = entry\n const expectedHash = hashCanonical(material)\n if (entry.entryHash !== expectedHash) {\n throw this.codec.integrityError(\n `entry ${entry.event.eventId} hash mismatch: expected ${expectedHash}, got ${entry.entryHash}`,\n )\n }\n expectedPrevious = entry.entryHash\n if (eventIds.has(entry.event.eventId)) {\n throw this.codec.integrityError(\n `duplicate eventId ${entry.event.eventId} in durable ledger`,\n )\n }\n eventIds.add(entry.event.eventId)\n projector.apply(entry, index)\n }\n return projector.finish(entries)\n }\n}\n"],"mappings":";;;;;;;AAyCA,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;EAAK,MAAM,S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,OAAO;CACjC;AACF"}
@@ -1,4 +1,4 @@
1
- import { n as CaptureIntegrityError, t as AgentEvalError } from "./errors-Dngq5h35.js";
1
+ import { t as AgentEvalError } from "./errors-Dngq5h35.js";
2
2
  import { c as costForTokenPricing } from "./cost-ledger-B1qx30B4.js";
3
3
  import { a as providerFromBaseUrl, i as defaultProviderRedactor } from "./raw-provider-sink-BQd7mzyT.js";
4
4
  //#region src/judge-families.ts
@@ -276,7 +276,20 @@ function assertCrossFamilyServed(pairs, opts = {}) {
276
276
  //#endregion
277
277
  //#region src/llm-client.ts
278
278
  /**
279
- * LLM client with graceful degrade.
279
+ * INTERNAL OpenAI-compatible client. NOT part of the published surface.
280
+ *
281
+ * agent-eval executes no paid model on behalf of a consumer: `createChatClient`
282
+ * binds a caller-supplied transport, and this module is not reachable through
283
+ * any export subpath. Two in-repo callers hold it:
284
+ * - the `agent-eval` binary (`src/cli-config.ts`), a deployed server whose
285
+ * caller is a JSON-RPC client in another language and which therefore
286
+ * configures its own endpoint from its own environment;
287
+ * - the loopback optimizer proxy path (`src/analyst/benchmark-public-model.ts`,
288
+ * `src/analyst/dspy-rlm-engine.ts`), which targets `http://127.0.0.1:<port>/v1`
289
+ * with an ephemeral token and executes nothing itself.
290
+ *
291
+ * The canonical request/result TYPES it defines ARE public — they are the
292
+ * contract every caller-owned transport speaks.
280
293
  *
281
294
  * OpenAI-compatible `/v1/chat/completions` client with:
282
295
  * - Exponential-backoff retry on 429 + 5xx gateway errors (502/503/504).
@@ -290,16 +303,10 @@ function assertCrossFamilyServed(pairs, opts = {}) {
290
303
  * Usage:
291
304
  * const { value, result } = await callLlmJson<MyType>(
292
305
  * { model: 'gpt-4o', messages: [...], jsonSchema: { name: 'x', schema: {...} } },
293
- * { baseUrl: 'https://router.tangle.tools/v1', apiKey: process.env.KEY },
306
+ * { baseUrl: process.env.AGENT_EVAL_LLM_BASE_URL, apiKey: process.env.AGENT_EVAL_LLM_API_KEY },
294
307
  * )
295
308
  *
296
- * `createChatClient` wraps this implementation for provider-neutral package
297
- * entry points. Direct callers can use `callLlm` or `callLlmJson`.
298
309
  */
299
- /** Conservative priced bound for the exact text request sent to a provider.
300
- * Returns undefined when output or multimodal input is not bounded, causing a
301
- * capped CostLedger to reject the call before execution. Pass
302
- * `customTokenPricing` when package pricing does not cover the model or endpoint. */
303
310
  function maximumChargeForLlmRequest(request, options = {}) {
304
311
  if (request.maxTokens === void 0) return void 0;
305
312
  if (!Number.isInteger(request.maxTokens) || request.maxTokens <= 0) throw new RangeError(`maximumChargeForLlmRequest: maxTokens must be a positive integer`);
@@ -368,7 +375,6 @@ var LlmResponseError = class extends AgentEvalError {
368
375
  this.result = result;
369
376
  }
370
377
  };
371
- const DEFAULT_BASE_URL = "https://router.tangle.tools/v1";
372
378
  const DEFAULT_TIMEOUT_MS = Number(process.env.TANGLE_LLM_TIMEOUT_MS) || 3e5;
373
379
  const DEFAULT_MAXIMUM_ATTEMPTS = process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS === void 0 ? 3 : Number(process.env.TANGLE_LLM_MAXIMUM_ATTEMPTS);
374
380
  function resolveMaximumAttempts(configured) {
@@ -477,6 +483,10 @@ function buildBody(req, forceJsonObject, defaultThinking) {
477
483
  };
478
484
  if (req.maxTokens != null) if (usesMaxCompletionTokens(req.model)) body.max_completion_tokens = req.maxTokens;
479
485
  else body.max_tokens = req.maxTokens;
486
+ if (req.logprobs !== void 0) {
487
+ body.logprobs = true;
488
+ body.top_logprobs = req.logprobs.topLogprobs;
489
+ }
480
490
  if (req.tools !== void 0) body.tools = req.tools;
481
491
  if (req.toolChoice !== void 0) body.tool_choice = req.toolChoice;
482
492
  const thinking = req.thinking ?? defaultThinking;
@@ -519,6 +529,34 @@ function encodeWireMessage(message) {
519
529
  }))
520
530
  };
521
531
  }
532
+ /**
533
+ * Parse `choices[0].logprobs.content` into the canonical per-token shape.
534
+ * `null` when the provider returned nothing for a request that asked: a
535
+ * provider that ignores `logprobs` is a fact the caller must be able to read,
536
+ * not an error. A malformed entry is a contract violation and throws.
537
+ */
538
+ function parseWireLogprobs(value, model) {
539
+ if (value === void 0 || value === null) return null;
540
+ if (!Array.isArray(value)) throw new Error(`LLM response logprobs.content must be an array (model=${model})`);
541
+ return value.map((entry, index) => {
542
+ const record = entry;
543
+ if (!record || typeof record !== "object" || typeof record.token !== "string" || typeof record.logprob !== "number" || !Number.isFinite(record.logprob)) throw new Error(`LLM response logprobs.content[${index}] is not a token with a finite logprob (model=${model})`);
544
+ const top = record.top_logprobs;
545
+ if (top !== void 0 && top !== null && !Array.isArray(top)) throw new Error(`LLM response logprobs.content[${index}].top_logprobs must be an array (model=${model})`);
546
+ return {
547
+ token: record.token,
548
+ logprob: record.logprob,
549
+ top: (Array.isArray(top) ? top : []).map((alternative, position) => {
550
+ const candidate = alternative;
551
+ if (!candidate || typeof candidate !== "object" || typeof candidate.token !== "string" || typeof candidate.logprob !== "number" || !Number.isFinite(candidate.logprob)) throw new Error(`LLM response logprobs.content[${index}].top_logprobs[${position}] is not a token with a finite logprob (model=${model})`);
552
+ return {
553
+ token: candidate.token,
554
+ logprob: candidate.logprob
555
+ };
556
+ })
557
+ };
558
+ });
559
+ }
522
560
  /** Parse provider tool_calls into the canonical shape. A malformed entry is a
523
561
  * provider-contract violation and throws rather than degrading silently. */
524
562
  function parseWireToolCalls(value, model) {
@@ -623,7 +661,8 @@ function extractBalancedJson(input, start) {
623
661
  * degrade use `callLlmJson`.
624
662
  */
625
663
  async function callLlm(req, opts = {}) {
626
- const baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
664
+ if (!opts.baseUrl) throw new Error("callLlm: opts.baseUrl is required");
665
+ const baseUrl = opts.baseUrl.replace(/\/+$/, "");
627
666
  const url = `${baseUrl}/chat/completions`;
628
667
  const endpoint = "/chat/completions";
629
668
  const timeoutMs = req.timeoutMs ?? opts.defaultTimeoutMs ?? DEFAULT_TIMEOUT_MS;
@@ -783,6 +822,7 @@ async function callLlm(req, opts = {}) {
783
822
  return {
784
823
  content,
785
824
  ...toolCalls === void 0 ? {} : { toolCalls },
825
+ ...req.logprobs === void 0 ? {} : { logprobs: parseWireLogprobs(choice?.logprobs?.content, req.model) },
786
826
  finishReason: choice?.finish_reason ?? null,
787
827
  contentEmpty: content.trim().length === 0,
788
828
  usage: {
@@ -907,91 +947,6 @@ function parseJsonSafely(content, model, jsonPayloadMode) {
907
947
  throw new Error(`LLM returned non-JSON content (model=${model})`);
908
948
  }
909
949
  }
910
- var LlmRouteAssertionError = class extends CaptureIntegrityError {
911
- reason;
912
- baseUrl;
913
- constructor(message, reason, baseUrl) {
914
- super(message);
915
- this.reason = reason;
916
- this.baseUrl = baseUrl;
917
- }
918
- };
919
- /**
920
- * Fail-loud assertion that the configured LLM client points at the route
921
- * the caller intends. Designed for the matrix-runner preflight: invoke
922
- * once before any LLM call to catch misconfiguration before a sweep burns
923
- * dollars on the wrong provider.
924
- *
925
- * Throws `LlmRouteAssertionError`. Pure — no I/O — so it's safe to call
926
- * from constructors and CI gates.
927
- */
928
- function assertLlmRoute(opts, req = {}) {
929
- const baseUrlExplicit = opts.baseUrl !== void 0;
930
- const baseUrl = (opts.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, "");
931
- if (req.requireExplicitBaseUrl && !baseUrlExplicit) throw new LlmRouteAssertionError(`assertLlmRoute: requireExplicitBaseUrl set but opts.baseUrl is undefined; would fall back to ${DEFAULT_BASE_URL}.`, "no_explicit_base_url", baseUrl);
932
- if (req.blockedBaseUrls?.some((p) => matchUrl(baseUrl, p))) throw new LlmRouteAssertionError(`assertLlmRoute: baseUrl ${baseUrl} matches a blocked pattern.`, "base_url_blocked", baseUrl);
933
- if (req.allowedBaseUrls && req.allowedBaseUrls.length > 0) {
934
- if (!req.allowedBaseUrls.some((p) => matchUrl(baseUrl, p))) throw new LlmRouteAssertionError(`assertLlmRoute: baseUrl ${baseUrl} is not in the allowed list (${req.allowedBaseUrls.map(describePattern).join(", ")}).`, "base_url_not_allowed", baseUrl);
935
- }
936
- if (req.requireAuth && !opts.apiKey && !opts.bearer && !opts.authHeader) throw new LlmRouteAssertionError(`assertLlmRoute: requireAuth set but no apiKey, bearer, or authHeader was supplied.`, "no_auth", baseUrl);
937
- if (req.expectedProvider) {
938
- const actual = opts.provider ?? providerFromBaseUrl(baseUrl);
939
- if (actual !== req.expectedProvider) throw new LlmRouteAssertionError(`assertLlmRoute: expected provider ${req.expectedProvider} but baseUrl ${baseUrl} resolves to ${actual}.`, "wrong_provider", baseUrl);
940
- }
941
- }
942
- function matchUrl(url, pattern) {
943
- if (pattern instanceof RegExp) return pattern.test(url);
944
- return url.toLowerCase().startsWith(pattern.toLowerCase());
945
- }
946
- function describePattern(p) {
947
- return p instanceof RegExp ? p.source : p;
948
- }
949
- /**
950
- * Probe whether a model is reachable. Returns latency + null error on
951
- * success; `ok=false` + error message on any failure (HTTP, timeout,
952
- * network, parse). Designed for sweep preflights — fail loud at the
953
- * boundary before burning a 30-leaf run on a misconfigured router.
954
- *
955
- * Sends a tiny `ping` message with `maxTokens = PROBE_MAX_TOKENS`. Reasoning
956
- * models (glm-5.1, deepseek-v4) can burn the entire budget on internal
957
- * reasoning for short prompts, so don't tighten this further — the shared
958
- * constant keeps this probe and `preflightModels` on one answer. We don't
959
- * validate content.
960
- *
961
- * Reachability and identity are separate answers: `ok` means the route
962
- * answered, `servedModel` / `substituted` say WHICH model answered. A gateway
963
- * that serves another provider's model returns `ok: true` with
964
- * `substituted: true` — inspect both before treating the id as measured.
965
- */
966
- async function probeLlm(model, opts = {}) {
967
- const start = Date.now();
968
- try {
969
- const result = await callLlm({
970
- model,
971
- messages: [{
972
- role: "user",
973
- content: "ping"
974
- }],
975
- maxTokens: 64,
976
- timeoutMs: opts.timeoutMs ?? 3e4
977
- }, opts);
978
- return {
979
- ok: true,
980
- latencyMs: Date.now() - start,
981
- error: null,
982
- servedModel: result.servedModel ?? null,
983
- substituted: checkServedModel(model, result.servedModel).substituted
984
- };
985
- } catch (err) {
986
- return {
987
- ok: false,
988
- latencyMs: Date.now() - start,
989
- error: err instanceof Error ? err.message : String(err),
990
- servedModel: null,
991
- substituted: false
992
- };
993
- }
994
- }
995
950
  /**
996
951
  * Stateful client — construct once with defaults, call many times.
997
952
  * Thin wrapper around the free functions; exists for callers that want
@@ -1019,6 +974,6 @@ var LlmClient = class {
1019
974
  }
1020
975
  };
1021
976
  //#endregion
1022
- export { CrossFamilyError as C, servedModelAcceptable as S, judgeFamily as T, assertCrossFamilyServed as _, assertLlmRoute as a, assertServedModels as b, callLlmJson as c, isTransientLlmError as d, maximumChargeForLlmRequest as f, ServedCrossFamilyError as g, ModelSubstitutionError as h, LlmRouteAssertionError as i, costReceiptFromLlm as l, stripFencedJson as m, LlmClient as n, backoffMs as o, probeLlm as p, LlmResponseError as r, callLlm as s, LlmCallError as t, costReceiptFromLlmError as u, assertServedModel as v, assertCrossFamily as w, checkServedModel as x, assertServedModelPolicy as y };
977
+ export { judgeFamily as S, assertServedModels as _, callLlmJson as a, CrossFamilyError as b, extractJsonPayload as c, stripFencedJson as d, ModelSubstitutionError as f, assertServedModelPolicy as g, assertServedModel as h, backoffMs as i, isTransientLlmError as l, assertCrossFamilyServed as m, LlmClient as n, costReceiptFromLlm as o, ServedCrossFamilyError as p, LlmResponseError as r, costReceiptFromLlmError as s, LlmCallError as t, maximumChargeForLlmRequest as u, checkServedModel as v, assertCrossFamily as x, servedModelAcceptable as y };
1023
978
 
1024
- //# sourceMappingURL=llm-client-Bg32RW0j.js.map
979
+ //# sourceMappingURL=llm-client-hgDieDNN.js.map