chainlesschain 0.166.90 → 0.166.92

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 (222) hide show
  1. package/README.md +15 -13
  2. package/package.json +4 -4
  3. package/src/assets/linux-subreaper/linux-arm64/manifest.json +1 -1
  4. package/src/assets/linux-subreaper/linux-x64/manifest.json +1 -1
  5. package/src/assets/web-panel/assets/{AIOps-CZzXRe1-.js → AIOps-C74YzqwJ.js} +1 -1
  6. package/src/assets/web-panel/assets/{ActionButton-_AZfbW1Q.js → ActionButton-TFef1hOE.js} +1 -1
  7. package/src/assets/web-panel/assets/{Analytics-CzaUx_wv.js → Analytics-CYsWpkkU.js} +3 -3
  8. package/src/assets/web-panel/assets/{AppLayout-xHEeeD-m.js → AppLayout-CFf9kjwu.js} +4 -4
  9. package/src/assets/web-panel/assets/{Artifacts-DmTbtudE.js → Artifacts-TQqa94YO.js} +1 -1
  10. package/src/assets/web-panel/assets/{Audit-Cn4ng4fo.js → Audit-B79ayqfS.js} +1 -1
  11. package/src/assets/web-panel/assets/{BackgroundAgents-DLUY1VD2.js → BackgroundAgents-pjkHfLP9.js} +1 -1
  12. package/src/assets/web-panel/assets/{Backup-B2v--wB6.js → Backup-CE6A-t_r.js} +1 -1
  13. package/src/assets/web-panel/assets/{BaseInput-Bgih7yAv.js → BaseInput-CwcgWMBY.js} +1 -1
  14. package/src/assets/web-panel/assets/{Chat-1MiiA3yA.js → Chat-BIkDNesY.js} +6 -6
  15. package/src/assets/web-panel/assets/{ChatBubbleRenderer-CPLynmbb.js → ChatBubbleRenderer-DgaokYts.js} +1 -1
  16. package/src/assets/web-panel/assets/{Checkbox-DsyBa_NO.js → Checkbox-MbypIy5V.js} +1 -1
  17. package/src/assets/web-panel/assets/{Codegen-B7WCFx9H.js → Codegen-DiFHWDnt.js} +1 -1
  18. package/src/assets/web-panel/assets/{Col-D2x4GBGm.js → Col-BNMlYMso.js} +1 -1
  19. package/src/assets/web-panel/assets/{Community-Rnwg9nea.js → Community-B3HVyHOX.js} +1 -1
  20. package/src/assets/web-panel/assets/{Compact-BPczlrRh.js → Compact-C7hlAubb.js} +1 -1
  21. package/src/assets/web-panel/assets/{Compliance-Br1L_wGU.js → Compliance-PaXZu6sE.js} +1 -1
  22. package/src/assets/web-panel/assets/{Cowork-DlsWB_oS.js → Cowork-BGiojbm-.js} +2 -2
  23. package/src/assets/web-panel/assets/{Cron-BWo_KGpG.js → Cron-Bmr-1QAx.js} +2 -2
  24. package/src/assets/web-panel/assets/{Crosschain-Cug7N8ge.js → Crosschain-BwUvWCVd.js} +1 -1
  25. package/src/assets/web-panel/assets/{DID-CMbyOZJN.js → DID-k_4QZocW.js} +2 -2
  26. package/src/assets/web-panel/assets/{Dashboard-C4dl_UaE.js → Dashboard-_ieRo2C5.js} +2 -2
  27. package/src/assets/web-panel/assets/{Dropdown-CBrC7M-9.js → Dropdown-DYHh6T27.js} +1 -1
  28. package/src/assets/web-panel/assets/{EmailListRenderer-DTq7tU4b.js → EmailListRenderer-BNlQcWQX.js} +1 -1
  29. package/src/assets/web-panel/assets/{EvolutionSettings-DWP3csxS.js → EvolutionSettings-DIkZ6U2D.js} +1 -1
  30. package/src/assets/web-panel/assets/{FamilyGuardDashboard-DZl7zuv_.js → FamilyGuardDashboard-Dq7qSr0P.js} +1 -1
  31. package/src/assets/web-panel/assets/{Federation-W-GSlVK5.js → Federation-C64e3Cbx.js} +1 -1
  32. package/src/assets/web-panel/assets/{FormItemContext-DMB7xYFV.js → FormItemContext-D-GE2vUa.js} +1 -1
  33. package/src/assets/web-panel/assets/{GenericCardRenderer-DNv8GEoq.js → GenericCardRenderer-DO3B2gis.js} +1 -1
  34. package/src/assets/web-panel/assets/{Git-BZ0Bbzw6.js → Git-0ETirIQH.js} +2 -2
  35. package/src/assets/web-panel/assets/{Governance-BNEdcOM5.js → Governance-C9fnRygX.js} +1 -1
  36. package/src/assets/web-panel/assets/{Inference-C8249gIz.js → Inference-CLJ9RTsK.js} +1 -1
  37. package/src/assets/web-panel/assets/{KnowledgeGraph-ngzebU3e.js → KnowledgeGraph-D3C_GxrN.js} +1 -1
  38. package/src/assets/web-panel/assets/{Logs-CP15th-f.js → Logs-C5ctGbkN.js} +2 -2
  39. package/src/assets/web-panel/assets/MarkdownRenderer-Ce-eWK3j.js +1 -0
  40. package/src/assets/web-panel/assets/{Marketplace-CaH59OsY.js → Marketplace-GF_t6hJ_.js} +1 -1
  41. package/src/assets/web-panel/assets/{McpTools-C07vnJev.js → McpTools-BGsGzgQs.js} +3 -3
  42. package/src/assets/web-panel/assets/{Memory-CqAOkVAS.js → Memory-CcrY2A0j.js} +2 -2
  43. package/src/assets/web-panel/assets/{MobileBridge-qp7mZimq.js → MobileBridge-Bi4T0RlS.js} +1 -1
  44. package/src/assets/web-panel/assets/{MobileProjects-DKhbqvTw.js → MobileProjects-DvjEGyvf.js} +1 -1
  45. package/src/assets/web-panel/assets/{Mtc-CRYCnWXv.js → Mtc-DL77Vf-k.js} +4 -4
  46. package/src/assets/web-panel/assets/{MtcAudit-Z08IrKws.js → MtcAudit-CDy_Uswb.js} +4 -4
  47. package/src/assets/web-panel/assets/{Multisig-BWdatUnH.js → Multisig-DL0BAO_c.js} +3 -3
  48. package/src/assets/web-panel/assets/{NLProgramming-BKWiCZ_m.js → NLProgramming-B-woh5IR.js} +1 -1
  49. package/src/assets/web-panel/assets/{Notes-Bgpzk3sm.js → Notes-CEFVCxk7.js} +3 -3
  50. package/src/assets/web-panel/assets/{NotificationSettings-DvtZEktR.js → NotificationSettings-BqPPMuAP.js} +1 -1
  51. package/src/assets/web-panel/assets/{OrderTableRenderer-CBcy0szc.js → OrderTableRenderer-GUKQ1xwp.js} +1 -1
  52. package/src/assets/web-panel/assets/{Organization-DRRL6vW1.js → Organization-B1gX8jlr.js} +4 -4
  53. package/src/assets/web-panel/assets/{Overflow-COmfB8Ns.js → Overflow-CeMxuUZy.js} +1 -1
  54. package/src/assets/web-panel/assets/{P2P-BqMq_DSa.js → P2P-B5aIRWwJ.js} +2 -2
  55. package/src/assets/web-panel/assets/{PdhVaultBrowser-BX7iNvle.js → PdhVaultBrowser-6rYgejd4.js} +4 -4
  56. package/src/assets/web-panel/assets/{Permissions-DzYkjmV_.js → Permissions-CqCp2SIl.js} +4 -4
  57. package/src/assets/web-panel/assets/{PersonalDataHub-BBTcxBbN.js → PersonalDataHub-BsA7DJWW.js} +4 -4
  58. package/src/assets/web-panel/assets/{Pipeline-eRkYFSbO.js → Pipeline-CiW6HeZh.js} +1 -1
  59. package/src/assets/web-panel/assets/{Privacy-Ch7IFKBh.js → Privacy-DckUOLYq.js} +1 -1
  60. package/src/assets/web-panel/assets/{ProjectInit-Ci8EcBYg.js → ProjectInit-CZppOOYR.js} +2 -2
  61. package/src/assets/web-panel/assets/{ProjectSettings-B4lYHFbI.js → ProjectSettings-B9QPzhDU.js} +2 -2
  62. package/src/assets/web-panel/assets/{Projects-zkE5cCo_.js → Projects-BErjjGha.js} +1 -1
  63. package/src/assets/web-panel/assets/{Providers-BKDVD3_e.js → Providers-DehU6Qiz.js} +1 -1
  64. package/src/assets/web-panel/assets/{QrScannerModal-BromrHlf.js → QrScannerModal-E1SUvv1m.js} +1 -1
  65. package/src/assets/web-panel/assets/{QuickAsk-CCgoY1gR.js → QuickAsk-COWFxyH3.js} +1 -1
  66. package/src/assets/web-panel/assets/{Recommend-DCPZvpq7.js → Recommend-D26pWKxX.js} +1 -1
  67. package/src/assets/web-panel/assets/{RemoteSession-DPnFP8HU.js → RemoteSession-DCOIaId3.js} +3 -3
  68. package/src/assets/web-panel/assets/{Reputation-l6r8ytAs.js → Reputation-DT_AHGAR.js} +1 -1
  69. package/src/assets/web-panel/assets/{Row-ke9Mk1cx.js → Row-B50S-1nl.js} +1 -1
  70. package/src/assets/web-panel/assets/{RssFeed-DQOEzUEn.js → RssFeed-BaBnHg3Q.js} +2 -2
  71. package/src/assets/web-panel/assets/{Search-BqgA0aUz.js → Search-BVdnLuuS.js} +1 -1
  72. package/src/assets/web-panel/assets/{Security-FeGD_jqV.js → Security-BnacH74J.js} +3 -3
  73. package/src/assets/web-panel/assets/{Services-4kiYYAjZ.js → Services-CxM08Zch.js} +2 -2
  74. package/src/assets/web-panel/assets/{Skeleton-BbU8Xegs.js → Skeleton-DE7CIc1N.js} +1 -1
  75. package/src/assets/web-panel/assets/{Skills-Dl2bUMUL.js → Skills-CGI0SJmf.js} +1 -1
  76. package/src/assets/web-panel/assets/{Sla-xRGALeaZ.js → Sla-DpEzPcqc.js} +1 -1
  77. package/src/assets/web-panel/assets/{SpeechSettings-DZfd4RDm.js → SpeechSettings-CTmnmMHn.js} +1 -1
  78. package/src/assets/web-panel/assets/{SyncSettings-BRtCV9Ga.js → SyncSettings-Dxgrd9hd.js} +2 -2
  79. package/src/assets/web-panel/assets/{Tasks-DVRQklfG.js → Tasks-CW4slS0A.js} +1 -1
  80. package/src/assets/web-panel/assets/{Templates-BbhE5jt5.js → Templates-DxvGWDgB.js} +1 -1
  81. package/src/assets/web-panel/assets/{Tenant-qXPDNKbK.js → Tenant-_Q0o2tNK.js} +1 -1
  82. package/src/assets/web-panel/assets/{Terminal-CV48Ks7E.js → Terminal-BTZn8pow.js} +2 -2
  83. package/src/assets/web-panel/assets/{TimelineRenderer-BLGfJIDr.js → TimelineRenderer-CauL0KFe.js} +1 -1
  84. package/src/assets/web-panel/assets/{Tokens-7G9H6Hrt.js → Tokens-CDoM2qeT.js} +1 -1
  85. package/src/assets/web-panel/assets/{Trigger--F64N11F.js → Trigger-B-QYGEU7.js} +1 -1
  86. package/src/assets/web-panel/assets/{Trust-Cq1r-D_y.js → Trust-BD6XJHT-.js} +1 -1
  87. package/src/assets/web-panel/assets/{UkeySign-Dqyu4RVh.js → UkeySign-x4TFwCy0.js} +1 -1
  88. package/src/assets/web-panel/assets/{VideoEditing-DuFmWH_B.js → VideoEditing-t3imBK_0.js} +1 -1
  89. package/src/assets/web-panel/assets/{Wallet-C3mg7EWP.js → Wallet-BCfkWwNC.js} +4 -4
  90. package/src/assets/web-panel/assets/{WebAuthn-CDK-Aj_X.js → WebAuthn-WH314Mdm.js} +5 -5
  91. package/src/assets/web-panel/assets/{WorkflowEditor--K7K-T1F.js → WorkflowEditor-jUlcjrUg.js} +1 -1
  92. package/src/assets/web-panel/assets/{chat-BQDcS6VP.js → chat-Dg3VASTL.js} +1 -1
  93. package/src/assets/web-panel/assets/{colors-BKxJL2-T.js → colors-BNvmBRKE.js} +1 -1
  94. package/src/assets/web-panel/assets/{compact-item-CFjQAMbY.js → compact-item-BGOfoqf4.js} +1 -1
  95. package/src/assets/web-panel/assets/{createContext-DbgCsdQd.js → createContext-BNQeqKAs.js} +1 -1
  96. package/src/assets/web-panel/assets/devWarning-B7_ypN1G.js +1 -0
  97. package/src/assets/web-panel/assets/{hasIn-BhkaOBNv.js → hasIn-Bg3AjCrq.js} +1 -1
  98. package/src/assets/web-panel/assets/{index-DvWWFJHJ.js → index--I3UF5t1.js} +1 -1
  99. package/src/assets/web-panel/assets/{index-DJ2OiRvh.js → index-2D04Zltx.js} +3 -3
  100. package/src/assets/web-panel/assets/{index-BuWPqSGT.js → index-60AnjUTX.js} +1 -1
  101. package/src/assets/web-panel/assets/{index-D2Zb-Kd1.js → index-7QJUWemf.js} +1 -1
  102. package/src/assets/web-panel/assets/{index-C0DzhUOX.js → index-B--0QM0S.js} +1 -1
  103. package/src/assets/web-panel/assets/index-B-jSKJK6.js +1 -0
  104. package/src/assets/web-panel/assets/{index-COGy6wXn.js → index-B0mgngoB.js} +1 -1
  105. package/src/assets/web-panel/assets/{index-bMX8BBLE.js → index-BBCMulQ-.js} +1 -1
  106. package/src/assets/web-panel/assets/{index-CE506mgj.js → index-BSNhW95G.js} +1 -1
  107. package/src/assets/web-panel/assets/{index-CoOu7sdP.js → index-B_JmInC0.js} +1 -1
  108. package/src/assets/web-panel/assets/{index-B4LlAJqc.js → index-BaPvEvB4.js} +1 -1
  109. package/src/assets/web-panel/assets/{index-CRtUDiXx.js → index-Bkz1tgFR.js} +1 -1
  110. package/src/assets/web-panel/assets/{index-Du_SxxBY.js → index-BmTacaQV.js} +1 -1
  111. package/src/assets/web-panel/assets/{index-CSUDlsIr.js → index-CCFZN66A.js} +1 -1
  112. package/src/assets/web-panel/assets/{index-3uR0ThJO.js → index-COol3xfA.js} +1 -1
  113. package/src/assets/web-panel/assets/{index-DmYK9Tqt.js → index-CY8cRKHR.js} +1 -1
  114. package/src/assets/web-panel/assets/{index-T9ka3Xj3.js → index-Cbp-wp-U.js} +1 -1
  115. package/src/assets/web-panel/assets/{index-CB4oHynY.js → index-Co_LnCWD.js} +1 -1
  116. package/src/assets/web-panel/assets/{index-DEwHywz9.js → index-Cx2EXRfr.js} +1 -1
  117. package/src/assets/web-panel/assets/{index-CUs7XpUO.js → index-D-mSvCQK.js} +1 -1
  118. package/src/assets/web-panel/assets/{index-BRqlCTrz.js → index-D072oLjp.js} +1 -1
  119. package/src/assets/web-panel/assets/{index-sKfUUldY.js → index-D6UqK83L.js} +1 -1
  120. package/src/assets/web-panel/assets/{index-Dhfa_BIl.js → index-DF_FKSVH.js} +1 -1
  121. package/src/assets/web-panel/assets/{index-D9sVcw6v.js → index-DLwEXRrb.js} +1 -1
  122. package/src/assets/web-panel/assets/{index-3djsY75k.js → index-DO0VlNtc.js} +1 -1
  123. package/src/assets/web-panel/assets/{index-BfGGsAU7.js → index-DS04wRll.js} +1 -1
  124. package/src/assets/web-panel/assets/{index-Dn2QSsuI.js → index-DYn5DnDk.js} +1 -1
  125. package/src/assets/web-panel/assets/{index-D-Yh3-1z.js → index-D_O2ZjPk.js} +1 -1
  126. package/src/assets/web-panel/assets/{index-BNjYPJNU.js → index-DcCnO0RU.js} +1 -1
  127. package/src/assets/web-panel/assets/{index-DP1NrM9J.js → index-Dkp-okWa.js} +1 -1
  128. package/src/assets/web-panel/assets/{index-DdcrixaQ.js → index-OUFoxUgH.js} +1 -1
  129. package/src/assets/web-panel/assets/index-P4FXZJqI.js +1 -0
  130. package/src/assets/web-panel/assets/{index-7BY44UEv.js → index-Wo0f2iqb.js} +1 -1
  131. package/src/assets/web-panel/assets/{index-DjmVlpap.js → index-ZD5Kd8tx.js} +1 -1
  132. package/src/assets/web-panel/assets/{index-3YutaXnp.js → index-fOwii3LP.js} +1 -1
  133. package/src/assets/web-panel/assets/{index-aPdVzagA.js → index-hG7jXGEW.js} +1 -1
  134. package/src/assets/web-panel/assets/{index-De7daEnc.js → index-pVdQieac.js} +1 -1
  135. package/src/assets/web-panel/assets/{index-CJoXgJ2N.js → index-uH2LnAs_.js} +1 -1
  136. package/src/assets/web-panel/assets/{index-DFt48Z-x.js → index-xzaUx19r.js} +1 -1
  137. package/src/assets/web-panel/assets/{initDefaultProps-wrqabmui.js → initDefaultProps-B8PN9AxJ.js} +1 -1
  138. package/src/assets/web-panel/assets/{motion-BoyB3ilP.js → motion-BHivfw5Q.js} +1 -1
  139. package/src/assets/web-panel/assets/{move-Cq31cSFE.js → move-B0QU5nDd.js} +1 -1
  140. package/src/assets/web-panel/assets/{mtc-parser-BkxNt-8H.js → mtc-parser-DRwRM3PE.js} +1 -1
  141. package/src/assets/web-panel/assets/{omit-DofGni53.js → omit-SHt2rV2p.js} +1 -1
  142. package/src/assets/web-panel/assets/{pickAttrs-BnluLL16.js → pickAttrs-CcmDlEb2.js} +1 -1
  143. package/src/assets/web-panel/assets/{placementArrow-C-yegJSP.js → placementArrow-DYatmXDS.js} +1 -1
  144. package/src/assets/web-panel/assets/{responsiveObserve-CD3ziNhu.js → responsiveObserve-B7qrsXq5.js} +1 -1
  145. package/src/assets/web-panel/assets/{slide-ToZO4gQ1.js → slide-BRGhlOWd.js} +1 -1
  146. package/src/assets/web-panel/assets/{statusUtils-DFVmDmVl.js → statusUtils-CT-7NXsQ.js} +1 -1
  147. package/src/assets/web-panel/assets/{styleChecker-De0Y8g1O.js → styleChecker-rZdw_Yyp.js} +1 -1
  148. package/src/assets/web-panel/assets/{useFlexGapSupport-wBKIYFKX.js → useFlexGapSupport-D8YNIP4P.js} +1 -1
  149. package/src/assets/web-panel/assets/{useFs-CP9nmUMJ.js → useFs-B8pt0Gu-.js} +1 -1
  150. package/src/assets/web-panel/assets/{usePersonalDataHub-vFGrVDyp.js → usePersonalDataHub-VMmYM1tt.js} +1 -1
  151. package/src/assets/web-panel/assets/{vnode-BcBIjvjH.js → vnode-UNDuoPoq.js} +1 -1
  152. package/src/assets/web-panel/assets/{zoom-DnXDAQxA.js → zoom-dN-u667S.js} +1 -1
  153. package/src/assets/web-panel/index.html +1 -1
  154. package/src/command-help-index.json +1 -1
  155. package/src/commands/agent-process-ownership.js +121 -0
  156. package/src/commands/agent.js +2 -0
  157. package/src/commands/hub.js +86 -9
  158. package/src/data/changelog.json +54 -2
  159. package/src/lib/audit-logger.js +46 -20
  160. package/src/lib/checkpoint-restore-saga.js +11 -1
  161. package/src/lib/eval/verify01-host-evidence.js +36 -3
  162. package/src/lib/evolution/evolution-artifact-ports.js +26 -0
  163. package/src/lib/evolution/evolution-eval-cohort-enrollment.js +713 -47
  164. package/src/lib/evolution/evolution-eval-gate.js +146 -0
  165. package/src/lib/evolution/evolution-eval-launch-admission.js +168 -90
  166. package/src/lib/evolution/evolution-eval-ledger-capture.js +50 -0
  167. package/src/lib/evolution/evolution-eval-readonly-audit.js +106 -0
  168. package/src/lib/evolution/evolution-ledger-file-backend.js +20 -0
  169. package/src/lib/evolution/evolution-ledger-ports.js +59 -27
  170. package/src/lib/evolution/evolution-ledger-v2-journal.js +55 -18
  171. package/src/lib/evolution/evolution-workbench-file-resources.js +19 -1
  172. package/src/lib/evolution/rrsi-cohort-registration.js +275 -0
  173. package/src/lib/evolution/rrsi-contracts.js +742 -0
  174. package/src/lib/evolution/rrsi-data.js +196 -0
  175. package/src/lib/evolution/rrsi-evaluation-adapter.js +275 -0
  176. package/src/lib/evolution/rrsi-evaluation-variants.js +267 -0
  177. package/src/lib/evolution/rrsi-group-statistics.js +553 -0
  178. package/src/lib/evolution/rrsi-history-ledger-adapter.js +3261 -0
  179. package/src/lib/evolution/rrsi-native-batch-evidence.js +520 -0
  180. package/src/lib/evolution/rrsi-native-eval-row-collector.js +538 -0
  181. package/src/lib/evolution/rrsi-native-evaluation-batch.js +547 -0
  182. package/src/lib/evolution/rrsi-native-evaluation-plan.js +431 -0
  183. package/src/lib/evolution/rrsi-native-group-statistics-plan.js +121 -0
  184. package/src/lib/evolution/rrsi-native-group-statistics.js +482 -0
  185. package/src/lib/evolution/rrsi-native-quality-receipt-contracts.js +321 -0
  186. package/src/lib/evolution/rrsi-native-quality-receipt.js +256 -0
  187. package/src/lib/evolution/rrsi-native-statistics-protocol.js +330 -0
  188. package/src/lib/evolution/rrsi-parent-binding.js +290 -0
  189. package/src/lib/evolution/rrsi-pm-execution-bridge.js +500 -0
  190. package/src/lib/evolution/rrsi-pm-training-mapping.js +134 -0
  191. package/src/lib/evolution/rrsi-preparation-contracts.js +213 -0
  192. package/src/lib/evolution/rrsi-registry-history-binding.js +193 -0
  193. package/src/lib/evolution/rrsi-registry-store-policy.js +1191 -0
  194. package/src/lib/evolution/rrsi-runtime-composition.js +79 -0
  195. package/src/lib/evolution/rrsi-selector.js +434 -0
  196. package/src/lib/evolution/rrsi-statistics-simulation.js +354 -0
  197. package/src/lib/evolution/skill-candidate-registry.js +216 -29
  198. package/src/lib/evolution/skill-registry-maintenance.js +80 -0
  199. package/src/lib/evolution/skill-registry-writer-control.js +138 -0
  200. package/src/lib/evolution/skill-release-registry.js +399 -169
  201. package/src/lib/formal-quality-eval-runtime.js +2 -14
  202. package/src/lib/goal-store.js +225 -16
  203. package/src/lib/process-execution-broker/index.js +91 -1
  204. package/src/lib/process-execution-broker/platform-sandbox.js +42 -0
  205. package/src/lib/process-execution-broker/windows-native-evaluator-capabilities.js +757 -0
  206. package/src/lib/process-execution-broker/windows-native-evaluator.js +316 -0
  207. package/src/lib/process-execution-broker/windows-sandbox-helper.dll +0 -0
  208. package/src/lib/process-execution-broker/windows-sandbox-helper.exe +0 -0
  209. package/src/lib/process-execution-broker/windows-sandbox.cs +383 -11
  210. package/src/lib/record-replay/skill-recorder.js +38 -3
  211. package/src/lib/scheduler-kernel/authority-resolver.js +12 -163
  212. package/src/lib/scheduler-kernel/contract.js +27 -414
  213. package/src/lib/scheduler-kernel/runtime.js +21 -823
  214. package/src/lib/scheduler-kernel/service.js +11 -328
  215. package/src/lib/scheduler-kernel/source-locator-path.js +7 -142
  216. package/src/lib/scheduler-kernel/store.js +67 -5931
  217. package/src/lib/secure-fs.js +16 -1314
  218. package/src/lib/with-file-lock.js +122 -20
  219. package/src/assets/web-panel/assets/MarkdownRenderer-CW3B3JDq.js +0 -1
  220. package/src/assets/web-panel/assets/devWarning-DlIv9Mbc.js +0 -1
  221. package/src/assets/web-panel/assets/index-BC972Grv.js +0 -1
  222. package/src/assets/web-panel/assets/index-CVifyQqL.js +0 -1
@@ -0,0 +1,3261 @@
1
+ /** Durable RRSI controls. Recording history never grants model or promotion authority. */
2
+ import {
3
+ KeyObject,
4
+ createHash,
5
+ createPublicKey,
6
+ verify as verifySignature,
7
+ } from "node:crypto";
8
+ import { isProxy } from "node:util/types";
9
+ import path from "node:path";
10
+ import { withFileLock } from "../with-file-lock.js";
11
+ import {
12
+ EvolutionLedger,
13
+ EVOLUTION_LEDGER_MAX_EVENTS,
14
+ EVOLUTION_LEDGER_DOMAIN_EVENT_SCHEMA,
15
+ EVOLUTION_ARTIFACT_RESOLUTION_SCHEMA,
16
+ EVOLUTION_ARTIFACT_REF_SCHEMA,
17
+ } from "./evolution-ledger.js";
18
+ import { captureEvolutionLedgerFileBackend } from "./evolution-ledger-file-backend.js";
19
+ import { isEvolutionLedgerV2Journal } from "./evolution-ledger-v2-journal.js";
20
+ import {
21
+ EvolutionArtifactPorts,
22
+ isEvolutionLedgerArtifactResolver,
23
+ EVOLUTION_DURABLE_ARTIFACT_RECORD_SCHEMA,
24
+ } from "./evolution-artifact-ports.js";
25
+ import {
26
+ RRSI_PARTITIONS,
27
+ RRSI_BUDGET_FIELDS,
28
+ verifyRrsiCampaign,
29
+ verifyRrsiCandidate,
30
+ } from "./rrsi-contracts.js";
31
+ import {
32
+ isRrsiPreparationReservation,
33
+ RRSI_PREPARATION_SETTLEMENT_SCHEMA,
34
+ RRSI_PREPARATION_PHASES,
35
+ RRSI_PREPARATION_BINDING_FIELDS,
36
+ normalizeRrsiPreparationPlan,
37
+ normalizeRrsiPreparationRequest,
38
+ rrsiTrainingSourcesDigest,
39
+ } from "./rrsi-preparation-contracts.js";
40
+ import {
41
+ snapshotRrsiData,
42
+ rrsiExact,
43
+ rrsiId,
44
+ rrsiDigest,
45
+ rrsiInteger,
46
+ rrsiBoolean,
47
+ rrsiHash,
48
+ rrsiCanonical,
49
+ rrsiEnvelope,
50
+ freezeRrsiData,
51
+ rrsiFail,
52
+ } from "./rrsi-data.js";
53
+ import {
54
+ RRSI_NATIVE_RESERVATION_SCHEMA,
55
+ RRSI_NATIVE_SETTLEMENT_SCHEMA,
56
+ RRSI_NATIVE_EXECUTION_UNITS,
57
+ isRrsiNativeReservation,
58
+ rrsiNativeUnitCount,
59
+ buildRrsiNativeEvaluationBatch,
60
+ normalizeRrsiNativeEvaluationBatch,
61
+ } from "./rrsi-native-evaluation-batch.js";
62
+ import {
63
+ buildRrsiNativeStatisticsScopeProtocol,
64
+ verifyRrsiNativeStatisticsScopeProtocol,
65
+ assertRrsiNativeStatisticsScopeBatch,
66
+ normalizeRrsiNativeStatisticsExecutionContract,
67
+ } from "./rrsi-native-statistics-protocol.js";
68
+ import { verifyRecordedRrsiNativeQualityReceipt } from "./rrsi-native-quality-receipt-contracts.js";
69
+ import { buildRrsiNativeGroupStatisticsPlan } from "./rrsi-native-group-statistics-plan.js";
70
+
71
+ export const RRSI_HISTORY_EVENT_SCHEMA = "chainlesschain.rrsi-history-event/v1";
72
+ export const RRSI_HISTORY_STATUS_SCHEMA =
73
+ "chainlesschain.rrsi-history-status/v1";
74
+ export const RRSI_RESERVATION_SCHEMA = "chainlesschain.rrsi-reservation/v1";
75
+ export const RRSI_SETTLEMENT_SCHEMA = "chainlesschain.rrsi-settlement/v1";
76
+ export const RRSI_HISTORY_EVENT_TYPE = "rrsi.history.committed";
77
+ const ARTIFACT_TYPE = "rrsi-history-event";
78
+ const VERIFIERS = new WeakMap();
79
+ const ADAPTERS = new WeakMap();
80
+ const NATIVE_STATISTICS_SCOPE_OPERATION = "register.native-statistics-scope-v2";
81
+ const NATIVE_STATISTICS_SCOPE_KIND = "register-native-statistics-scope-v2";
82
+ const NATIVE_STATISTICS_PLAN_KIND = "register-native-statistics-plan-v2";
83
+ const NATIVE_STATISTICS_RESERVE_KIND = "reserve-native-batch-v2";
84
+ const NATIVE_QUALITY_RECEIPT_KIND = "record-native-quality-receipt-v1";
85
+ const nativeQualityReceiptOperation = (digest) =>
86
+ `quality.${rrsiDigest(digest, "native quality receipt digest").slice(7)}`;
87
+ const auditHead = (head) =>
88
+ Object.fromEntries(
89
+ ["ledgerId", "identityDigest", "epoch", "sequence", "headDigest"].map(
90
+ (field) => [field, head[field]],
91
+ ),
92
+ );
93
+ const nativeStatisticsPlanOperation = (queryId) =>
94
+ `statistics-plan.${rrsiHash("chainlesschain.rrsi-native-query-operation/v1", queryId).slice(7)}`;
95
+
96
+ /** Capture only methods of an already composed, genuine history adapter. */
97
+ export function captureRrsiHistoryLedgerAdapter(value) {
98
+ const captured = ADAPTERS.get(value);
99
+ if (!captured) rrsiFail("a branded RRSI history adapter is required");
100
+ return captured;
101
+ }
102
+ const USAGE_FIELDS = [
103
+ "tokens",
104
+ "toolCalls",
105
+ "wallClockMs",
106
+ "costMicrounits",
107
+ "executions",
108
+ ];
109
+ const USAGE_TO_BUDGET = Object.fromEntries(
110
+ USAGE_FIELDS.map((key, index) => [key, RRSI_BUDGET_FIELDS[index]]),
111
+ );
112
+ const FLAGS = [
113
+ "structuralOnly",
114
+ "authenticated",
115
+ "readyForExecution",
116
+ "qualifiesForPromotion",
117
+ ];
118
+
119
+ function ownOptions(input, keys) {
120
+ if (
121
+ !input ||
122
+ typeof input !== "object" ||
123
+ isProxy(input) ||
124
+ Object.getPrototypeOf(input) !== Object.prototype
125
+ )
126
+ rrsiFail("RRSI composition options must be plain own data fields");
127
+ if (Reflect.ownKeys(input).length !== keys.length)
128
+ rrsiFail("RRSI composition fields differ");
129
+ return Object.fromEntries(
130
+ keys.map((key) => {
131
+ const descriptor = Object.getOwnPropertyDescriptor(input, key);
132
+ if (!descriptor?.enumerable || !("value" in descriptor))
133
+ rrsiFail("RRSI composition cannot use accessors");
134
+ return [key, descriptor.value];
135
+ }),
136
+ );
137
+ }
138
+
139
+ function timestamp(value, label) {
140
+ if (
141
+ typeof value !== "string" ||
142
+ !Number.isFinite(Date.parse(value)) ||
143
+ new Date(value).toISOString() !== value
144
+ )
145
+ rrsiFail(`${label} must be a canonical timestamp`);
146
+ return value;
147
+ }
148
+
149
+ function budget(value, label) {
150
+ rrsiExact(value, RRSI_BUDGET_FIELDS, label);
151
+ return Object.fromEntries(
152
+ RRSI_BUDGET_FIELDS.map((key) => [
153
+ key,
154
+ rrsiInteger(value[key], `${label}.${key}`),
155
+ ]),
156
+ );
157
+ }
158
+
159
+ function digestList(value, label) {
160
+ if (!Array.isArray(value) || value.length < 1 || value.length > 64)
161
+ rrsiFail(`${label} must be a bounded nonempty list`);
162
+ const result = value.map((entry) => rrsiDigest(entry, label)).sort();
163
+ if (new Set(result).size !== result.length)
164
+ rrsiFail(`${label} contains duplicate digests`);
165
+ return result;
166
+ }
167
+
168
+ /** Genuine v2 journals use null-prototype JSON refs. Copy their exact typed fields. */
169
+ function copyRetainedRef(input) {
170
+ if (
171
+ !input ||
172
+ typeof input !== "object" ||
173
+ isProxy(input) ||
174
+ ![Object.prototype, null].includes(Object.getPrototypeOf(input)) ||
175
+ Reflect.ownKeys(input).length !== 3
176
+ )
177
+ rrsiFail("history artifact reference is invalid");
178
+ const output = Object.fromEntries(
179
+ ["schema", "ref", "digest"].map((name) => {
180
+ const field = Object.getOwnPropertyDescriptor(input, name);
181
+ if (
182
+ !field?.enumerable ||
183
+ !("value" in field) ||
184
+ typeof field.value !== "string"
185
+ )
186
+ rrsiFail("history artifact reference must be own data");
187
+ return [name, field.value];
188
+ }),
189
+ );
190
+ if (
191
+ output.schema !== EVOLUTION_ARTIFACT_REF_SCHEMA ||
192
+ output.ref.length > 2048 ||
193
+ !/^[a-z][a-z0-9+.-]*:[^\\\s]+$/iu.test(output.ref)
194
+ )
195
+ rrsiFail("history artifact reference scope differs");
196
+ rrsiDigest(output.digest, "history artifact reference digest");
197
+ return output;
198
+ }
199
+
200
+ /** Trusted composition pins this independent public key; no caller callbacks. */
201
+ export function createRrsiSettlementVerifier(input) {
202
+ const options = ownOptions(input, [
203
+ "publicKey",
204
+ "authorityId",
205
+ "trustPolicyDigest",
206
+ ]);
207
+ if (
208
+ options.publicKey &&
209
+ typeof options.publicKey === "object" &&
210
+ isProxy(options.publicKey)
211
+ )
212
+ rrsiFail("settlement public key cannot be a Proxy");
213
+ const publicKey =
214
+ options.publicKey instanceof KeyObject &&
215
+ options.publicKey.type === "public"
216
+ ? options.publicKey
217
+ : createPublicKey(options.publicKey);
218
+ if (publicKey.asymmetricKeyType !== "ed25519")
219
+ rrsiFail("RRSI settlement requires Ed25519");
220
+ const descriptor = freezeRrsiData({
221
+ authorityId: rrsiId(options.authorityId, "settlement authority"),
222
+ trustPolicyDigest: rrsiDigest(
223
+ options.trustPolicyDigest,
224
+ "settlement trust policy",
225
+ ),
226
+ publicKeyDigest: `sha256:${createHash("sha256")
227
+ .update(publicKey.export({ format: "der", type: "spki" }))
228
+ .digest("hex")}`,
229
+ });
230
+ const verifier = Object.freeze({ descriptor });
231
+ VERIFIERS.set(verifier, { publicKey, descriptor });
232
+ return verifier;
233
+ }
234
+
235
+ function settlementCore(input) {
236
+ const value = snapshotRrsiData(input);
237
+ if (value.schema === RRSI_NATIVE_SETTLEMENT_SCHEMA) {
238
+ rrsiExact(
239
+ value,
240
+ [
241
+ "schema",
242
+ "receiptId",
243
+ "bindings",
244
+ "statusByArm",
245
+ "cleanupConfirmedByArm",
246
+ "usageByArm",
247
+ "executionUnitsByArm",
248
+ "sourceReceiptDigests",
249
+ "issuedAt",
250
+ "validUntil",
251
+ ],
252
+ "native child settlement core",
253
+ );
254
+ rrsiId(value.receiptId, "native receipt ID");
255
+ rrsiExact(
256
+ value.bindings,
257
+ [
258
+ "tenantId",
259
+ "scopeId",
260
+ "ledgerId",
261
+ "identityDigest",
262
+ "epoch",
263
+ "campaignDigest",
264
+ "batchDigest",
265
+ "childId",
266
+ "requestDigest",
267
+ "evaluationContextDigest",
268
+ "attributionDigest",
269
+ "armReservationDigests",
270
+ ],
271
+ "native child settlement bindings",
272
+ );
273
+ for (const name of ["tenantId", "scopeId", "childId"])
274
+ rrsiId(value.bindings[name], name);
275
+ for (const name of ["ledgerId", "epoch"])
276
+ if (
277
+ typeof value.bindings[name] !== "string" ||
278
+ !/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/u.test(value.bindings[name])
279
+ )
280
+ rrsiFail(`invalid native ${name}`);
281
+ for (const name of [
282
+ "identityDigest",
283
+ "campaignDigest",
284
+ "batchDigest",
285
+ "requestDigest",
286
+ "evaluationContextDigest",
287
+ "attributionDigest",
288
+ ])
289
+ rrsiDigest(value.bindings[name], name);
290
+ const arms = Object.keys(value.bindings.armReservationDigests ?? {});
291
+ if (
292
+ arms.length !== 2 ||
293
+ arms.some((arm) => !["baseline", "rsi", "rrsi"].includes(arm))
294
+ )
295
+ rrsiFail("native child settlement needs both frozen arms");
296
+ rrsiExact(
297
+ value.bindings.armReservationDigests,
298
+ arms,
299
+ "native arm reservations",
300
+ );
301
+ for (const digest of Object.values(value.bindings.armReservationDigests))
302
+ rrsiDigest(digest, "arm reservation digest");
303
+ for (const name of [
304
+ "statusByArm",
305
+ "cleanupConfirmedByArm",
306
+ "usageByArm",
307
+ "executionUnitsByArm",
308
+ ])
309
+ rrsiExact(value[name], arms, name);
310
+ for (const arm of arms) {
311
+ if (
312
+ ![
313
+ "succeeded",
314
+ "failed",
315
+ "cancelled",
316
+ "not-started",
317
+ "unknown",
318
+ ].includes(value.statusByArm[arm])
319
+ )
320
+ rrsiFail("invalid native settlement status");
321
+ rrsiBoolean(value.cleanupConfirmedByArm[arm], "native cleanup");
322
+ rrsiExact(value.usageByArm[arm], USAGE_FIELDS, "native arm usage");
323
+ for (const amount of Object.values(value.usageByArm[arm]))
324
+ if (amount !== null) rrsiInteger(amount, "native usage");
325
+ rrsiExact(
326
+ value.executionUnitsByArm[arm],
327
+ RRSI_NATIVE_EXECUTION_UNITS,
328
+ "native settlement execution units",
329
+ );
330
+ for (const amount of Object.values(value.executionUnitsByArm[arm]))
331
+ if (amount !== null) rrsiInteger(amount, "native execution units");
332
+ const complete = RRSI_NATIVE_EXECUTION_UNITS.every(
333
+ (name) => value.executionUnitsByArm[arm][name] !== null,
334
+ );
335
+ if (
336
+ complete
337
+ ? value.usageByArm[arm].executions !==
338
+ rrsiNativeUnitCount(value.executionUnitsByArm[arm])
339
+ : value.usageByArm[arm].executions !== null
340
+ )
341
+ rrsiFail(
342
+ "native execution usage must match the typed charged-unit vector",
343
+ );
344
+ }
345
+ value.sourceReceiptDigests = digestList(
346
+ value.sourceReceiptDigests,
347
+ "native child source receipts",
348
+ );
349
+ timestamp(value.issuedAt, "issuedAt");
350
+ timestamp(value.validUntil, "validUntil");
351
+ if (Date.parse(value.validUntil) < Date.parse(value.issuedAt))
352
+ rrsiFail("native settlement validity window is reversed");
353
+ return value;
354
+ }
355
+ rrsiExact(
356
+ value,
357
+ [
358
+ "schema",
359
+ "receiptId",
360
+ "bindings",
361
+ "status",
362
+ "cleanupConfirmed",
363
+ "usage",
364
+ "sourceReceiptDigests",
365
+ "issuedAt",
366
+ "validUntil",
367
+ ],
368
+ "settlement core",
369
+ );
370
+ const preparation = value.schema === RRSI_PREPARATION_SETTLEMENT_SCHEMA;
371
+ if (!preparation && value.schema !== RRSI_SETTLEMENT_SCHEMA)
372
+ rrsiFail("RRSI settlement schema differs");
373
+ rrsiId(value.receiptId, "settlement receipt ID");
374
+ rrsiExact(
375
+ value.bindings,
376
+ [
377
+ "tenantId",
378
+ "scopeId",
379
+ "ledgerId",
380
+ "identityDigest",
381
+ "epoch",
382
+ "campaignDigest",
383
+ ...(preparation
384
+ ? RRSI_PREPARATION_BINDING_FIELDS
385
+ : ["candidateDigest", "contentDigest"]),
386
+ "executionDigest",
387
+ "reservationDigest",
388
+ "executionId",
389
+ "slotId",
390
+ "partition",
391
+ ],
392
+ "settlement bindings",
393
+ );
394
+ for (const key of [
395
+ "tenantId",
396
+ "scopeId",
397
+ "executionId",
398
+ "slotId",
399
+ ...(preparation ? ["roundId", "branchId"] : []),
400
+ ])
401
+ rrsiId(value.bindings[key], key);
402
+ for (const key of ["ledgerId", "epoch"])
403
+ if (
404
+ typeof value.bindings[key] !== "string" ||
405
+ !/^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$/u.test(value.bindings[key])
406
+ )
407
+ rrsiFail(`invalid settlement ${key}`);
408
+ rrsiDigest(value.bindings.identityDigest, "ledger identity digest");
409
+ for (const key of [
410
+ "campaignDigest",
411
+ ...(preparation
412
+ ? RRSI_PREPARATION_BINDING_FIELDS.filter((key) => key.endsWith("Digest"))
413
+ : ["candidateDigest", "contentDigest"]),
414
+ "executionDigest",
415
+ "reservationDigest",
416
+ ])
417
+ rrsiDigest(value.bindings[key], key);
418
+ if (
419
+ preparation
420
+ ? value.bindings.partition !== "train" ||
421
+ !RRSI_PREPARATION_PHASES.includes(value.bindings.phase)
422
+ : !RRSI_PARTITIONS.includes(value.bindings.partition) ||
423
+ value.bindings.partition === "train"
424
+ )
425
+ rrsiFail("invalid settlement partition");
426
+ if (
427
+ !["succeeded", "failed", "cancelled", "not-started", "unknown"].includes(
428
+ value.status,
429
+ )
430
+ )
431
+ rrsiFail("invalid settlement status");
432
+ rrsiBoolean(value.cleanupConfirmed, "settlement cleanup");
433
+ rrsiExact(value.usage, USAGE_FIELDS, "settlement usage");
434
+ for (const key of USAGE_FIELDS)
435
+ if (value.usage[key] !== null) rrsiInteger(value.usage[key], key);
436
+ value.sourceReceiptDigests = digestList(
437
+ value.sourceReceiptDigests,
438
+ "source receipt digests",
439
+ );
440
+ timestamp(value.issuedAt, "issuedAt");
441
+ timestamp(value.validUntil, "validUntil");
442
+ if (Date.parse(value.validUntil) < Date.parse(value.issuedAt))
443
+ rrsiFail("settlement validity window is reversed");
444
+ return value;
445
+ }
446
+
447
+ export function buildRrsiSettlementMessage(core, authorityInput) {
448
+ const normalized = settlementCore(core);
449
+ const authority = snapshotRrsiData(authorityInput);
450
+ rrsiExact(
451
+ authority,
452
+ ["authorityId", "trustPolicyDigest", "publicKeyDigest"],
453
+ "signed settlement authority",
454
+ );
455
+ rrsiId(authority.authorityId, "signed authority ID");
456
+ rrsiDigest(authority.trustPolicyDigest, "signed policy digest");
457
+ rrsiDigest(authority.publicKeyDigest, "signed public key digest");
458
+ return Buffer.from(
459
+ `${normalized.schema}\0${rrsiCanonical(authority)}\0${rrsiCanonical(normalized)}`,
460
+ "utf8",
461
+ );
462
+ }
463
+
464
+ function verifySettlement(verifier, input, reservation, acceptanceTime) {
465
+ const authority = VERIFIERS.get(verifier);
466
+ if (!authority)
467
+ rrsiFail(
468
+ "independent settlement verification is unavailable",
469
+ "CC_RRSI_SETTLEMENT_UNAVAILABLE",
470
+ );
471
+ const evidence = snapshotRrsiData(input);
472
+ rrsiExact(evidence, ["core", "attestation"], "signed settlement");
473
+ const core = settlementCore(evidence.core);
474
+ const expectedSchema = isRrsiPreparationReservation(reservation)
475
+ ? RRSI_PREPARATION_SETTLEMENT_SCHEMA
476
+ : isRrsiNativeReservation(reservation)
477
+ ? RRSI_NATIVE_SETTLEMENT_SCHEMA
478
+ : RRSI_SETTLEMENT_SCHEMA;
479
+ if (core.schema !== expectedSchema)
480
+ rrsiFail(
481
+ "settlement domain differs from reservation",
482
+ "CC_RRSI_SETTLEMENT_INVALID",
483
+ );
484
+ rrsiExact(
485
+ evidence.attestation,
486
+ ["authorityId", "trustPolicyDigest", "publicKeyDigest", "signature"],
487
+ "settlement attestation",
488
+ );
489
+ for (const key of Object.keys(authority.descriptor))
490
+ if (evidence.attestation[key] !== authority.descriptor[key])
491
+ rrsiFail("settlement authority differs", "CC_RRSI_SETTLEMENT_INVALID");
492
+ const signature = evidence.attestation.signature;
493
+ if (
494
+ typeof signature !== "string" ||
495
+ !/^[A-Za-z0-9_-]{86}$/u.test(signature) ||
496
+ Buffer.from(signature, "base64url").toString("base64url") !== signature ||
497
+ !verifySignature(
498
+ null,
499
+ buildRrsiSettlementMessage(core, authority.descriptor),
500
+ authority.publicKey,
501
+ Buffer.from(signature, "base64url"),
502
+ )
503
+ )
504
+ rrsiFail(
505
+ "settlement signature verification failed",
506
+ "CC_RRSI_SETTLEMENT_INVALID",
507
+ );
508
+ if (rrsiCanonical(core.bindings) !== rrsiCanonical(reservation.bindings))
509
+ rrsiFail(
510
+ "settlement does not bind the reserved execution",
511
+ "CC_RRSI_SETTLEMENT_INVALID",
512
+ );
513
+ // Historical reads use the authenticated original acceptance time, not today.
514
+ if (
515
+ Date.parse(acceptanceTime) < Date.parse(core.issuedAt) ||
516
+ Date.parse(acceptanceTime) > Date.parse(core.validUntil)
517
+ )
518
+ rrsiFail(
519
+ "settlement was outside its acceptance window",
520
+ "CC_RRSI_SETTLEMENT_INVALID",
521
+ );
522
+ return { evidence: { core, attestation: evidence.attestation }, core };
523
+ }
524
+
525
+ function sourceKeys(campaign, partition) {
526
+ const keys = new Set();
527
+ for (const task of campaign.dataset.tasks.filter(
528
+ (task) => task.partition === partition,
529
+ )) {
530
+ keys.add(`content:${task.contentDigest}`);
531
+ for (const [dimension, group] of Object.entries(task.groups))
532
+ keys.add(`${dimension}:${group}`);
533
+ }
534
+ return [...keys].sort();
535
+ }
536
+
537
+ function sameIdentity(left, right) {
538
+ return [
539
+ "ledgerId",
540
+ "identityDigest",
541
+ "epoch",
542
+ "sequence",
543
+ "headDigest",
544
+ ].every((key) => left[key] === right[key]);
545
+ }
546
+
547
+ /** Only caller-owned branded storage is accepted. A migrated v2 journal stays v2. */
548
+ export function createRrsiHistoryLedgerAdapter(input) {
549
+ const options = ownOptions(input, [
550
+ "backend",
551
+ "artifactPorts",
552
+ "ledgerArtifactResolver",
553
+ "descriptor",
554
+ "settlementVerifier",
555
+ "now",
556
+ ]);
557
+ const backend = captureEvolutionLedgerFileBackend(options.backend);
558
+ if (
559
+ isProxy(options.artifactPorts) ||
560
+ !(options.artifactPorts instanceof EvolutionArtifactPorts) ||
561
+ !isEvolutionLedgerArtifactResolver(options.ledgerArtifactResolver) ||
562
+ typeof options.now !== "function" ||
563
+ isProxy(options.now)
564
+ )
565
+ rrsiFail("RRSI history requires trusted storage composition");
566
+ if (
567
+ options.settlementVerifier !== null &&
568
+ !VERIFIERS.has(options.settlementVerifier)
569
+ )
570
+ rrsiFail("RRSI history requires a branded independent settlement verifier");
571
+ const configured = snapshotRrsiData(options.descriptor);
572
+ rrsiExact(
573
+ configured,
574
+ ["tenantId", "artifactTenantId", "goalId", "audience", "purpose"],
575
+ "history descriptor",
576
+ );
577
+ for (const key of Object.keys(configured)) rrsiId(configured[key], key);
578
+ if (configured.purpose !== "evolution-ledger")
579
+ rrsiFail("RRSI history requires Ledger retention");
580
+ if (!/^[a-z][a-z0-9-]{0,127}$/u.test(configured.goalId))
581
+ rrsiFail("history goal must be a canonical artifact target");
582
+ const descriptor = freezeRrsiData({
583
+ ...configured,
584
+ // Stable per tenant/goal, independent of caller candidate/campaign/dataset IDs.
585
+ scopeId: `rrsi.${rrsiHash("chainlesschain.rrsi-history-scope/v1", { tenantId: configured.tenantId, goalId: configured.goalId }).slice(7)}`,
586
+ settlementAuthority: options.settlementVerifier?.descriptor ?? null,
587
+ });
588
+ const ledger = backend.ledger;
589
+ const methods = {};
590
+ for (const name of ["read", "verify", "appendDomainEvent"]) {
591
+ if (ledger instanceof EvolutionLedger)
592
+ methods[name] = (...args) =>
593
+ Reflect.apply(EvolutionLedger.prototype[name], ledger, args);
594
+ else if (isEvolutionLedgerV2Journal(ledger)) {
595
+ const method = Object.getOwnPropertyDescriptor(ledger, name)?.value;
596
+ if (typeof method !== "function")
597
+ rrsiFail("RRSI history v2 method is missing");
598
+ methods[name] = (...args) => Reflect.apply(method, ledger, args);
599
+ } else
600
+ rrsiFail("RRSI history requires the branded backend's original journal");
601
+ }
602
+ const freshReservations = new WeakMap();
603
+ const freshNativeChildren = new WeakMap();
604
+ // ArtifactPorts correctly rejects changing descriptor snapshots. Serialize
605
+ // all RRSI read/publish/CAS/readback on this backend, without weakening it.
606
+ const withHistoryLock = (operation) =>
607
+ withFileLock(
608
+ path.join(backend.descriptor.authorityRootDir, "rrsi-history-operations"),
609
+ operation,
610
+ {
611
+ failIfUnavailable: true,
612
+ timeoutMs: 30_000,
613
+ retryMs: 1,
614
+ maxRetryMs: 8,
615
+ retryJitterMs: 4,
616
+ },
617
+ );
618
+ const now = () => {
619
+ const milliseconds = options.now();
620
+ if (!Number.isSafeInteger(milliseconds))
621
+ rrsiFail("RRSI history clock is invalid");
622
+ return new Date(milliseconds).toISOString();
623
+ };
624
+ const scopeDigest = rrsiHash(
625
+ "chainlesschain.rrsi-history-descriptor/v1",
626
+ descriptor,
627
+ );
628
+
629
+ function emptyState(identity) {
630
+ return {
631
+ identity: {
632
+ ledgerId: identity.ledgerId,
633
+ identityDigest: identity.identityDigest,
634
+ epoch: identity.epoch,
635
+ },
636
+ root: null,
637
+ campaigns: new Map(),
638
+ operations: new Map(),
639
+ reservations: new Map(),
640
+ nativeBatches: new Map(),
641
+ nativeChildren: new Map(),
642
+ nativeControls: null,
643
+ nativeStatisticsScope: null,
644
+ nativeStatisticsPlans: new Map(),
645
+ nativeStatisticsBindings: new Map(),
646
+ nativeQualityReceipts: new Map(),
647
+ nativeRecoveryHolds: new Map(),
648
+ nativeInvocations: new Set(),
649
+ nativeInvocationIds: new Set(),
650
+ nativeInvocationNonces: new Set(),
651
+ nativeRequestContexts: new Set(),
652
+ nativeCandidateOwners: new Map(),
653
+ nativeQueryOrdinals: new Map(),
654
+ slots: new Set(),
655
+ candidates: new Map(),
656
+ finalCandidates: new Map(),
657
+ sources: new Map(),
658
+ receiptIds: new Set(),
659
+ sourceReceiptOwners: new Map(),
660
+ selectionQueries: 0,
661
+ preparationPlan: null,
662
+ preparationAttempts: 0,
663
+ preparationRequests: new Set(),
664
+ overrun: false,
665
+ lastRecordDigest: null,
666
+ };
667
+ }
668
+ function campaignFor(state, digest) {
669
+ rrsiDigest(digest, "campaign digest");
670
+ const campaign = state.campaigns.get(digest);
671
+ if (!campaign)
672
+ rrsiFail(
673
+ "campaign has not been durably registered",
674
+ "CC_RRSI_UNREGISTERED",
675
+ );
676
+ return campaign;
677
+ }
678
+ function reservationFor(state, executionId, digest) {
679
+ rrsiId(executionId, "execution ID");
680
+ rrsiDigest(digest, "reservation digest");
681
+ const value = state.reservations.get(executionId);
682
+ if (!value || value.reservation.reservationDigest !== digest)
683
+ rrsiFail("reserved execution binding differs");
684
+ return value;
685
+ }
686
+ function charges(state, stage = null, arm = null) {
687
+ if (arm === null && state.nativeBatches.size) {
688
+ const perArm = ["baseline", "rsi", "rrsi"].map((name) =>
689
+ charges(state, stage, name),
690
+ );
691
+ return Object.fromEntries(
692
+ RRSI_BUDGET_FIELDS.map((name) => [
693
+ name,
694
+ perArm.reduce(
695
+ (max, total) => (total[name] > max ? total[name] : max),
696
+ 0n,
697
+ ),
698
+ ]),
699
+ );
700
+ }
701
+ const totals = Object.fromEntries(
702
+ RRSI_BUDGET_FIELDS.map((key) => [key, 0n]),
703
+ );
704
+ for (const entry of state.reservations.values()) {
705
+ const native = isRrsiNativeReservation(entry.reservation);
706
+ if (native && arm !== entry.reservation.bindings.arm) continue;
707
+ if (
708
+ stage &&
709
+ stage !==
710
+ (native
711
+ ? entry.reservation.bindings.stage === "selection"
712
+ ? "selection"
713
+ : "final"
714
+ : entry.reservation.bindings.partition === "train"
715
+ ? "proposal"
716
+ : entry.reservation.bindings.partition === "select"
717
+ ? "selection"
718
+ : "final")
719
+ )
720
+ continue;
721
+ for (const [usage, ceiling] of Object.entries(USAGE_TO_BUDGET)) {
722
+ const known = BigInt(entry.knownUsage[usage] ?? 0);
723
+ const held =
724
+ entry.status === "settled"
725
+ ? known
726
+ : BigInt(entry.reservation.budget[ceiling]);
727
+ totals[ceiling] += known > held ? known : held;
728
+ }
729
+ }
730
+ return totals;
731
+ }
732
+ function checkBudget(state, reserved, stage, arm = null) {
733
+ const total = charges(state, null, arm);
734
+ const staged = charges(state, stage, arm);
735
+ const cap =
736
+ stage === "proposal"
737
+ ? state.root.budget.proposalPerExploringArm
738
+ : stage === "selection"
739
+ ? state.root.budget.selectionPerExploringArm
740
+ : state.root.budget.finalEvaluationPerArm;
741
+ for (const key of RRSI_BUDGET_FIELDS)
742
+ if (
743
+ total[key] + BigInt(reserved[key]) >
744
+ BigInt(state.root.budget.totalPerArm[key]) ||
745
+ staged[key] + BigInt(reserved[key]) > BigInt(cap[key])
746
+ )
747
+ rrsiFail(
748
+ "RRSI durable resource budget is exhausted",
749
+ "CC_RRSI_BUDGET_EXCEEDED",
750
+ );
751
+ }
752
+ function checkPreparationHold(state) {
753
+ if (
754
+ [...state.reservations.values()].some(
755
+ (entry) =>
756
+ isRrsiPreparationReservation(entry.reservation) &&
757
+ entry.status !== "settled",
758
+ )
759
+ )
760
+ rrsiFail(
761
+ "unresolved preparation requires independent settlement",
762
+ "CC_RRSI_HISTORY_HOLD",
763
+ );
764
+ }
765
+ function historyRegistrationRecord(operation) {
766
+ if (!operation)
767
+ rrsiFail(
768
+ "required statistics registration is absent",
769
+ "CC_RRSI_PREREGISTRATION_REQUIRED",
770
+ );
771
+ return freezeRrsiData({
772
+ recordDigest: operation.record.recordDigest,
773
+ ref: operation.ref,
774
+ sequence: operation.sequence,
775
+ });
776
+ }
777
+ function rootRegistrationOperation(state) {
778
+ return [...state.operations.values()].find(
779
+ (entry) =>
780
+ entry.record.kind === "register" &&
781
+ entry.record.payload.campaign.campaignDigest ===
782
+ state.root?.campaignDigest,
783
+ );
784
+ }
785
+ function nativeStatisticsScopeBinding(state) {
786
+ return freezeRrsiData({
787
+ historyScopeId: descriptor.scopeId,
788
+ historyDescriptorDigest: scopeDigest,
789
+ ledgerIdentity: state.identity,
790
+ rootRegistrationRecord: historyRegistrationRecord(
791
+ rootRegistrationOperation(state),
792
+ ),
793
+ });
794
+ }
795
+ function assertNativeStatisticsCampaign(state, campaign) {
796
+ if (state.nativeStatisticsScope)
797
+ verifyRrsiNativeStatisticsScopeProtocol(
798
+ state.nativeStatisticsScope.protocol,
799
+ {
800
+ campaign,
801
+ execution: state.nativeStatisticsScope.execution,
802
+ },
803
+ );
804
+ }
805
+ function nativeStatisticsScopeResolution(state) {
806
+ if (!state.nativeStatisticsScope)
807
+ rrsiFail(
808
+ "native statistics scope is not preregistered",
809
+ "CC_RRSI_PREREGISTRATION_REQUIRED",
810
+ );
811
+ const operation = state.operations.get(NATIVE_STATISTICS_SCOPE_OPERATION);
812
+ if (
813
+ operation?.record.kind !== NATIVE_STATISTICS_SCOPE_KIND ||
814
+ operation.record.payload !== state.nativeStatisticsScope
815
+ )
816
+ rrsiFail(
817
+ "native statistics scope provenance is substituted",
818
+ "CC_RRSI_HISTORY_CORRUPT",
819
+ );
820
+ return freezeRrsiData({
821
+ schema: "chainlesschain.rrsi-native-statistics-scope-resolution/v1",
822
+ protocol: state.nativeStatisticsScope.protocol,
823
+ binding: state.nativeStatisticsScope.binding,
824
+ registrationRecord: historyRegistrationRecord(operation),
825
+ historyAuthenticated: true,
826
+ preObservationRegistrationVerified: true,
827
+ statisticalProtocolValidated: false,
828
+ readyForExecution: false,
829
+ qualifiesForPromotion: false,
830
+ });
831
+ }
832
+ function nativeStatisticsReserveBinding(state, batch) {
833
+ const scope = nativeStatisticsScopeResolution(state);
834
+ const registered = state.nativeStatisticsPlans.get(batch.queryId);
835
+ if (!registered || rrsiCanonical(registered.batch) !== rrsiCanonical(batch))
836
+ rrsiFail(
837
+ "native batch has no matching observation-before-reservation plan",
838
+ "CC_RRSI_PREREGISTRATION_REQUIRED",
839
+ );
840
+ const planOperation = state.operations.get(
841
+ nativeStatisticsPlanOperation(batch.queryId),
842
+ );
843
+ if (
844
+ planOperation?.record.kind !== NATIVE_STATISTICS_PLAN_KIND ||
845
+ planOperation.record.payload !== registered
846
+ )
847
+ rrsiFail(
848
+ "native statistics plan provenance is substituted",
849
+ "CC_RRSI_HISTORY_CORRUPT",
850
+ );
851
+ return {
852
+ scopeStatisticsRegistrationDigest: scope.registrationRecord.recordDigest,
853
+ batchStatisticsRegistrationDigest:
854
+ historyRegistrationRecord(planOperation).recordDigest,
855
+ statisticsPlanDigest: registered.statisticsPlan.statisticsPlanDigest,
856
+ };
857
+ }
858
+ function nativeStatisticsSourceRefs(state, kind, payload) {
859
+ let refs;
860
+ if (kind === NATIVE_QUALITY_RECEIPT_KIND) {
861
+ const receipt = payload.qualityReceipt;
862
+ refs = [receipt.reservationRecord.ref];
863
+ if (receipt.statisticsRegistration)
864
+ refs.push(
865
+ receipt.statisticsRegistration.scopeRegistrationRecord.ref,
866
+ receipt.statisticsRegistration.planRegistrationRecord.ref,
867
+ );
868
+ } else if (kind === NATIVE_STATISTICS_SCOPE_KIND)
869
+ refs = [payload.binding.rootRegistrationRecord.ref];
870
+ else if (kind === NATIVE_STATISTICS_PLAN_KIND)
871
+ refs = [payload.scopeRegistrationRecord.ref];
872
+ else if (kind === NATIVE_STATISTICS_RESERVE_KIND)
873
+ refs = [
874
+ historyRegistrationRecord(
875
+ state.operations.get(NATIVE_STATISTICS_SCOPE_OPERATION),
876
+ ).ref,
877
+ historyRegistrationRecord(
878
+ state.operations.get(
879
+ nativeStatisticsPlanOperation(payload.batch.queryId),
880
+ ),
881
+ ).ref,
882
+ ];
883
+ else return null;
884
+ return refs.sort((a, b) => (a.ref < b.ref ? -1 : a.ref > b.ref ? 1 : 0));
885
+ }
886
+ function reserveNativeBatch(state, payload, statisticsBinding = null) {
887
+ rrsiExact(payload, ["batch"], "native batch reservation");
888
+ if (state.nativeStatisticsScope && !statisticsBinding)
889
+ rrsiFail(
890
+ "a frozen statistics scope prohibits legacy native reservation",
891
+ "CC_RRSI_PREREGISTRATION_REQUIRED",
892
+ );
893
+ const campaign = campaignFor(state, payload.batch?.campaignDigest);
894
+ const batch = normalizeRrsiNativeEvaluationBatch(payload.batch, campaign);
895
+ if (state.finalCandidates.size > 1)
896
+ rrsiFail(
897
+ "native history requires a unique global finalist",
898
+ "CC_RRSI_HISTORY_HOLD",
899
+ );
900
+ if (state.overrun)
901
+ rrsiFail(
902
+ "history contains a resource overrun",
903
+ "CC_RRSI_BUDGET_EXCEEDED",
904
+ );
905
+ if (
906
+ rrsiCanonical(campaign.experiment) !==
907
+ rrsiCanonical(state.root.experiment)
908
+ )
909
+ rrsiFail("native experiment cannot reset the frozen statistical design");
910
+ if (
911
+ [...state.reservations.values()].some(
912
+ (entry) => entry.status !== "settled",
913
+ )
914
+ )
915
+ rrsiFail(
916
+ "native batch requires complete preceding history accounting",
917
+ "CC_RRSI_HISTORY_HOLD",
918
+ );
919
+ const slot = `${descriptor.scopeId}:native:${batch.queryId}`;
920
+ if (state.slots.has(slot))
921
+ rrsiFail("native query slot is already occupied", "CC_RRSI_SLOT_USED");
922
+ const candidate = batch.candidate;
923
+ for (const identity of [
924
+ batch.versions.rrsi,
925
+ batch.nativeCandidateContents.rrsi,
926
+ ]) {
927
+ const owner = state.nativeCandidateOwners.get(identity);
928
+ if (owner && owner !== candidate.contentDigest)
929
+ rrsiFail(
930
+ "native candidate identity is already bound to another RRSI content",
931
+ "CC_RRSI_DUPLICATE_CONTENT",
932
+ );
933
+ }
934
+ for (const child of batch.children) {
935
+ const contextKey = rrsiCanonical(child.request.evaluationContext);
936
+ if (
937
+ state.nativeInvocations.has(child.invocationDigest) ||
938
+ state.nativeInvocationIds.has(child.invocationIdDigest) ||
939
+ state.nativeInvocationNonces.has(child.invocationNonceDigest) ||
940
+ state.nativeRequestContexts.has(contextKey)
941
+ )
942
+ rrsiFail(
943
+ "native invocation or original request context has already been consumed",
944
+ "CC_RRSI_QUERY_USED",
945
+ );
946
+ }
947
+ const prior = state.candidates.get(candidate.contentDigest);
948
+ if (prior && prior.candidateDigest !== candidate.candidateDigest)
949
+ rrsiFail(
950
+ "content is already bound to another candidate identity",
951
+ "CC_RRSI_DUPLICATE_CONTENT",
952
+ );
953
+ const stage = batch.stage === "selection" ? "selection" : "final";
954
+ if (stage === "selection") {
955
+ if (state.finalCandidates.size)
956
+ rrsiFail("frozen finalist prohibits further native selection");
957
+ if (prior)
958
+ rrsiFail(
959
+ "candidate selection query has already been consumed",
960
+ "CC_RRSI_QUERY_USED",
961
+ );
962
+ if (
963
+ state.selectionQueries >=
964
+ state.root.policy.limits.maxSelectionQueries ||
965
+ state.candidates.size >= state.root.policy.limits.maxCandidates
966
+ )
967
+ rrsiFail(
968
+ "history selection quota is exhausted",
969
+ "CC_RRSI_QUERY_EXHAUSTED",
970
+ );
971
+ } else {
972
+ if (
973
+ state.finalCandidates.get(campaign.campaignDigest) !==
974
+ candidate.contentDigest
975
+ )
976
+ rrsiFail("native final requires the unique frozen candidate");
977
+ const selected = [...state.nativeBatches.values()].find(
978
+ (entry) =>
979
+ entry.stage === "selection" &&
980
+ entry.campaignDigest === campaign.campaignDigest &&
981
+ entry.candidate.contentDigest === candidate.contentDigest,
982
+ );
983
+ if (!selected)
984
+ rrsiFail("native final cannot relabel legacy selection evidence");
985
+ for (const field of [
986
+ "versions",
987
+ "nativeCandidateContents",
988
+ "lifecycleDigests",
989
+ "parentIdentity",
990
+ "targetIdentity",
991
+ ])
992
+ if (rrsiCanonical(batch[field]) !== rrsiCanonical(selected[field]))
993
+ rrsiFail(
994
+ "native final changes frozen selection artifacts or runtime",
995
+ );
996
+ if (
997
+ [...state.nativeBatches.values()].some(
998
+ (entry) =>
999
+ entry.stage === "generalization" &&
1000
+ entry.campaignDigest === campaign.campaignDigest,
1001
+ ) ||
1002
+ [...state.reservations.values()].some(
1003
+ (entry) =>
1004
+ !isRrsiNativeReservation(entry.reservation) &&
1005
+ entry.reservation.bindings.campaignDigest ===
1006
+ campaign.campaignDigest &&
1007
+ ["gate-validation", "gate-test", "audit"].includes(
1008
+ entry.reservation.bindings.partition,
1009
+ ),
1010
+ )
1011
+ )
1012
+ rrsiFail(
1013
+ "final partitions have already been consumed",
1014
+ "CC_RRSI_QUERY_USED",
1015
+ );
1016
+ }
1017
+ const controls = {
1018
+ versions: { baseline: batch.versions.baseline, rsi: batch.versions.rsi },
1019
+ nativeRsiContentDigest: batch.nativeCandidateContents.rsi,
1020
+ lifecycles: {
1021
+ baseline: batch.lifecycleDigests.baseline,
1022
+ rsi: batch.lifecycleDigests.rsi,
1023
+ },
1024
+ parentIdentity: batch.parentIdentity,
1025
+ targetIdentity: batch.targetIdentity,
1026
+ };
1027
+ if (
1028
+ state.nativeControls &&
1029
+ rrsiCanonical(controls) !== rrsiCanonical(state.nativeControls)
1030
+ )
1031
+ rrsiFail("native control arms or target scope cannot be reset");
1032
+ const partitions =
1033
+ stage === "selection"
1034
+ ? ["select"]
1035
+ : ["gate-validation", "gate-test", "audit"];
1036
+ const keys = [
1037
+ ...new Set(
1038
+ partitions.flatMap((partition) => sourceKeys(campaign, partition)),
1039
+ ),
1040
+ ];
1041
+ for (const key of keys) {
1042
+ const previous = state.sources.get(key);
1043
+ if (
1044
+ previous &&
1045
+ (previous.stage !== stage ||
1046
+ (stage === "final" &&
1047
+ previous.campaignDigest !== campaign.campaignDigest))
1048
+ )
1049
+ rrsiFail(
1050
+ "previously exposed source cannot be treated as unseen",
1051
+ "CC_RRSI_HOLDOUT_USED",
1052
+ );
1053
+ }
1054
+ const totals = Object.fromEntries(
1055
+ campaign.experiment.arms.map((arm) => [
1056
+ arm,
1057
+ Object.fromEntries(RRSI_BUDGET_FIELDS.map((field) => [field, 0])),
1058
+ ]),
1059
+ );
1060
+ for (const child of batch.children)
1061
+ for (const [arm, allocation] of Object.entries(child.byArm))
1062
+ for (const field of RRSI_BUDGET_FIELDS)
1063
+ totals[arm][field] += allocation.budget[field];
1064
+ for (const [arm, ceiling] of Object.entries(totals))
1065
+ checkBudget(state, ceiling, stage, arm);
1066
+ // One reservation event, plus capacity for dispatch, unknown and two settlement
1067
+ // attempts per child. Do not admit work that cannot retain its minimum recovery graph.
1068
+ if (state.operations.size + 1 + 4 * batch.children.length > 5000)
1069
+ rrsiFail(
1070
+ "native batch exceeds remaining history recovery capacity",
1071
+ "CC_RRSI_HISTORY_HOLD",
1072
+ );
1073
+ const result = [];
1074
+ for (const child of batch.children) {
1075
+ const reservations = Object.entries(child.byArm).map(
1076
+ ([arm, allocation]) => {
1077
+ const executionId = `eval.${rrsiHash("chainlesschain.rrsi-native-arm-execution/v1", { batchDigest: batch.batchDigest, childId: child.childId, arm }).slice(7)}`;
1078
+ if (state.reservations.has(executionId))
1079
+ rrsiFail(
1080
+ "native arm execution is already occupied",
1081
+ "CC_RRSI_SLOT_USED",
1082
+ );
1083
+ const partition =
1084
+ child.role === "selection"
1085
+ ? "select"
1086
+ : child.role === "gate"
1087
+ ? "gate-validation"
1088
+ : "audit";
1089
+ const core = {
1090
+ tenantId: descriptor.tenantId,
1091
+ scopeId: descriptor.scopeId,
1092
+ ...state.identity,
1093
+ campaignDigest: campaign.campaignDigest,
1094
+ candidateDigest: candidate.candidateDigest,
1095
+ contentDigest: candidate.contentDigest,
1096
+ executionDigest: rrsiHash(
1097
+ "chainlesschain.rrsi-execution-bindings/v1",
1098
+ campaign.execution,
1099
+ ),
1100
+ executionId,
1101
+ slotId: child.slotId,
1102
+ partition,
1103
+ queryId: batch.queryId,
1104
+ childId: child.childId,
1105
+ batchDigest: batch.batchDigest,
1106
+ stage: batch.stage,
1107
+ role: child.role,
1108
+ variant: child.variant,
1109
+ pairId: child.pairId,
1110
+ arm,
1111
+ cohortId: child.cohortId,
1112
+ nativePlanDigest: child.nativePlanDigest,
1113
+ requestDigest: child.requestDigest,
1114
+ evaluationContextDigest: child.evaluationContextDigest,
1115
+ invocationDigest: child.invocationDigest,
1116
+ nativeArtifactId: batch.versions[arm],
1117
+ nativeContentDigest:
1118
+ arm === "baseline"
1119
+ ? batch.parentIdentity.contentDigest
1120
+ : batch.nativeCandidateContents[arm],
1121
+ lifecycleDigest: batch.lifecycleDigests[arm],
1122
+ executionUnitsDigest: rrsiHash(
1123
+ "chainlesschain.rrsi-native-execution-units/v1",
1124
+ allocation.executionUnits,
1125
+ ),
1126
+ costInventoryDigest: allocation.costInventoryDigest,
1127
+ };
1128
+ const plannedExecutions = rrsiNativeUnitCount(
1129
+ allocation.executionUnits,
1130
+ );
1131
+ const reservationDigest = rrsiHash(RRSI_NATIVE_RESERVATION_SCHEMA, {
1132
+ bindings: core,
1133
+ budget: allocation.budget,
1134
+ plannedExecutions,
1135
+ executionUnits: allocation.executionUnits,
1136
+ coveredPartitions: Object.keys(
1137
+ child.plannedObservationsPerArmByPartition,
1138
+ ).sort(),
1139
+ });
1140
+ const reservation = freezeRrsiData({
1141
+ schema: RRSI_NATIVE_RESERVATION_SCHEMA,
1142
+ bindings: { ...core, reservationDigest },
1143
+ budget: allocation.budget,
1144
+ plannedExecutions,
1145
+ executionUnits: allocation.executionUnits,
1146
+ coveredPartitions: Object.keys(
1147
+ child.plannedObservationsPerArmByPartition,
1148
+ ).sort(),
1149
+ reservationDigest,
1150
+ });
1151
+ state.reservations.set(executionId, {
1152
+ reservation,
1153
+ status: "reserved",
1154
+ knownUsage: Object.fromEntries(
1155
+ USAGE_FIELDS.map((name) => [name, null]),
1156
+ ),
1157
+ knownExecutionUnits: Object.fromEntries(
1158
+ RRSI_NATIVE_EXECUTION_UNITS.map((name) => [name, null]),
1159
+ ),
1160
+ settlement: null,
1161
+ dispatched: false,
1162
+ });
1163
+ return reservation;
1164
+ },
1165
+ );
1166
+ const bindings = freezeRrsiData({
1167
+ tenantId: descriptor.tenantId,
1168
+ scopeId: descriptor.scopeId,
1169
+ ...state.identity,
1170
+ campaignDigest: campaign.campaignDigest,
1171
+ batchDigest: batch.batchDigest,
1172
+ childId: child.childId,
1173
+ requestDigest: child.requestDigest,
1174
+ evaluationContextDigest: child.evaluationContextDigest,
1175
+ attributionDigest: rrsiHash(
1176
+ "chainlesschain.rrsi-native-cost-attribution/v1",
1177
+ { method: batch.costAttribution, byArm: child.byArm },
1178
+ ),
1179
+ armReservationDigests: Object.fromEntries(
1180
+ reservations.map((reservation) => [
1181
+ reservation.bindings.arm,
1182
+ reservation.reservationDigest,
1183
+ ]),
1184
+ ),
1185
+ });
1186
+ if (state.nativeChildren.has(child.childId))
1187
+ rrsiFail("native child is already occupied", "CC_RRSI_SLOT_USED");
1188
+ state.nativeChildren.set(child.childId, { bindings, reservations });
1189
+ state.nativeRecoveryHolds.set(child.childId, 4);
1190
+ result.push(
1191
+ freezeRrsiData({ childId: child.childId, bindings, reservations }),
1192
+ );
1193
+ }
1194
+ state.slots.add(slot);
1195
+ for (const identity of [
1196
+ batch.versions.rrsi,
1197
+ batch.nativeCandidateContents.rrsi,
1198
+ ])
1199
+ state.nativeCandidateOwners.set(identity, candidate.contentDigest);
1200
+ for (const child of batch.children) {
1201
+ state.nativeInvocations.add(child.invocationDigest);
1202
+ state.nativeInvocationIds.add(child.invocationIdDigest);
1203
+ state.nativeInvocationNonces.add(child.invocationNonceDigest);
1204
+ state.nativeRequestContexts.add(
1205
+ rrsiCanonical(child.request.evaluationContext),
1206
+ );
1207
+ }
1208
+ state.nativeControls ??= controls;
1209
+ state.nativeBatches.set(batch.batchDigest, batch);
1210
+ if (statisticsBinding)
1211
+ state.nativeStatisticsBindings.set(
1212
+ batch.batchDigest,
1213
+ freezeRrsiData(statisticsBinding),
1214
+ );
1215
+ state.candidates.set(candidate.contentDigest, candidate);
1216
+ if (stage === "selection") state.selectionQueries++;
1217
+ state.nativeQueryOrdinals.set(
1218
+ batch.batchDigest,
1219
+ stage === "selection"
1220
+ ? state.selectionQueries
1221
+ : state.nativeQueryOrdinals.get(
1222
+ [...state.nativeBatches.values()].find(
1223
+ (entry) =>
1224
+ entry.stage === "selection" &&
1225
+ entry.campaignDigest === batch.campaignDigest &&
1226
+ entry.candidate.contentDigest === batch.candidate.contentDigest,
1227
+ ).batchDigest,
1228
+ ),
1229
+ );
1230
+ for (const key of keys)
1231
+ state.sources.set(key, {
1232
+ campaignDigest: campaign.campaignDigest,
1233
+ stage,
1234
+ });
1235
+ const response = { batchDigest: batch.batchDigest, children: result };
1236
+ snapshotRrsiData({
1237
+ ...response,
1238
+ children: result.map((child) => ({
1239
+ ...child,
1240
+ newlyCommitted: true,
1241
+ historyAuthenticated: true,
1242
+ readyForExecution: false,
1243
+ qualifiesForPromotion: false,
1244
+ })),
1245
+ newlyCommitted: true,
1246
+ historyAuthenticated: true,
1247
+ readyForExecution: false,
1248
+ qualifiesForPromotion: false,
1249
+ });
1250
+ return freezeRrsiData(response);
1251
+ }
1252
+ function apply(
1253
+ state,
1254
+ kind,
1255
+ payload,
1256
+ acceptedAt,
1257
+ liveAdmission = false,
1258
+ previousHead = null,
1259
+ ) {
1260
+ if (kind === NATIVE_QUALITY_RECEIPT_KIND) {
1261
+ rrsiExact(payload, ["qualityReceipt"], "native quality receipt record");
1262
+ const receipt = verifyRecordedRrsiNativeQualityReceipt(
1263
+ payload.qualityReceipt,
1264
+ nativeQualityContext(
1265
+ state,
1266
+ payload.qualityReceipt.batchDigest,
1267
+ previousHead,
1268
+ ),
1269
+ );
1270
+ if (state.nativeQualityReceipts.has(receipt.qualityReceiptDigest))
1271
+ rrsiFail("native quality receipt is already recorded");
1272
+ state.nativeQualityReceipts.set(receipt.qualityReceiptDigest, payload);
1273
+ return receipt;
1274
+ }
1275
+ if (kind === "register") {
1276
+ rrsiExact(payload, ["campaign"], "campaign registration");
1277
+ const campaign = verifyRrsiCampaign(payload.campaign);
1278
+ if (
1279
+ campaign.tenantId !== descriptor.tenantId ||
1280
+ campaign.goalId !== descriptor.goalId
1281
+ )
1282
+ rrsiFail("campaign history scope differs");
1283
+ for (const existing of state.campaigns.values())
1284
+ if (
1285
+ existing.campaignId === campaign.campaignId &&
1286
+ existing.campaignDigest !== campaign.campaignDigest
1287
+ )
1288
+ rrsiFail(
1289
+ "campaign ID is already bound",
1290
+ "CC_RRSI_OPERATION_CONFLICT",
1291
+ );
1292
+ if (
1293
+ state.root &&
1294
+ ["parentReleaseDigest", "anchorReleaseDigest", "candidateKind"].some(
1295
+ (key) => campaign[key] !== state.root[key],
1296
+ )
1297
+ )
1298
+ rrsiFail("history baseline cannot be reset by a new campaign ID");
1299
+ if (
1300
+ state.root &&
1301
+ (campaign.policy.policyDigest !== state.root.policy.policyDigest ||
1302
+ rrsiCanonical(campaign.execution) !==
1303
+ rrsiCanonical(state.root.execution) ||
1304
+ rrsiCanonical(campaign.budget) !== rrsiCanonical(state.root.budget))
1305
+ )
1306
+ rrsiFail("history policy, model, or budget cannot be reset");
1307
+ assertNativeStatisticsCampaign(state, campaign);
1308
+ const trainingKeys = sourceKeys(campaign, "train");
1309
+ for (const key of trainingKeys) {
1310
+ const previous = state.sources.get(key);
1311
+ if (previous && previous.stage !== "train")
1312
+ rrsiFail(
1313
+ "exposed selection or holdout sources require explicit retirement before training",
1314
+ "CC_RRSI_HOLDOUT_USED",
1315
+ );
1316
+ }
1317
+ for (const key of trainingKeys)
1318
+ state.sources.set(key, {
1319
+ campaignDigest: campaign.campaignDigest,
1320
+ stage: "train",
1321
+ });
1322
+ state.root ??= campaign;
1323
+ state.campaigns.set(campaign.campaignDigest, campaign);
1324
+ return campaign;
1325
+ }
1326
+ if (!state.root) rrsiFail("RRSI history has no registered root campaign");
1327
+ if (kind === NATIVE_STATISTICS_SCOPE_KIND) {
1328
+ rrsiExact(
1329
+ payload,
1330
+ ["execution", "protocol", "binding"],
1331
+ "native statistics scope registration",
1332
+ );
1333
+ if (
1334
+ state.nativeStatisticsScope ||
1335
+ state.reservations.size ||
1336
+ state.nativeBatches.size ||
1337
+ state.preparationAttempts ||
1338
+ state.selectionQueries
1339
+ )
1340
+ rrsiFail(
1341
+ "native statistics scope must freeze before any execution reservation",
1342
+ "CC_RRSI_PREREGISTRATION_TOO_LATE",
1343
+ );
1344
+ if (
1345
+ rrsiCanonical(payload.binding) !==
1346
+ rrsiCanonical(nativeStatisticsScopeBinding(state))
1347
+ )
1348
+ rrsiFail(
1349
+ "native statistics scope belongs to another History root or journal",
1350
+ );
1351
+ verifyRrsiNativeStatisticsScopeProtocol(payload.protocol, {
1352
+ campaign: state.root,
1353
+ execution: payload.execution,
1354
+ });
1355
+ for (const campaign of state.campaigns.values())
1356
+ verifyRrsiNativeStatisticsScopeProtocol(payload.protocol, {
1357
+ campaign,
1358
+ execution: payload.execution,
1359
+ });
1360
+ state.nativeStatisticsScope = freezeRrsiData(payload);
1361
+ return payload.protocol;
1362
+ }
1363
+ if (kind === NATIVE_STATISTICS_PLAN_KIND) {
1364
+ rrsiExact(
1365
+ payload,
1366
+ ["batch", "statisticsPlan", "scopeRegistrationRecord"],
1367
+ "native statistics batch preregistration",
1368
+ );
1369
+ const scope = nativeStatisticsScopeResolution(state);
1370
+ const campaign = campaignFor(state, payload.batch?.campaignDigest);
1371
+ const batch = normalizeRrsiNativeEvaluationBatch(payload.batch, campaign);
1372
+ if (
1373
+ [...state.nativeBatches.values()].some(
1374
+ (entry) =>
1375
+ entry.queryId === batch.queryId ||
1376
+ entry.batchDigest === batch.batchDigest,
1377
+ )
1378
+ )
1379
+ rrsiFail(
1380
+ "an already reserved batch cannot be retrospectively preregistered",
1381
+ "CC_RRSI_PREREGISTRATION_TOO_LATE",
1382
+ );
1383
+ if (state.nativeStatisticsPlans.has(batch.queryId))
1384
+ rrsiFail(
1385
+ "native statistics query is already registered",
1386
+ "CC_RRSI_OPERATION_CONFLICT",
1387
+ );
1388
+ if (
1389
+ rrsiCanonical(payload.scopeRegistrationRecord) !==
1390
+ rrsiCanonical(scope.registrationRecord)
1391
+ )
1392
+ rrsiFail("native statistics plan replaces its scope registration");
1393
+ const rebuilt = assertRrsiNativeStatisticsScopeBatch(scope.protocol, {
1394
+ campaign,
1395
+ batch,
1396
+ });
1397
+ if (rrsiCanonical(rebuilt) !== rrsiCanonical(payload.statisticsPlan))
1398
+ rrsiFail("native statistics plan differs from the frozen protocol");
1399
+ state.nativeStatisticsPlans.set(batch.queryId, freezeRrsiData(payload));
1400
+ return payload.statisticsPlan;
1401
+ }
1402
+ if (kind === NATIVE_STATISTICS_RESERVE_KIND) {
1403
+ rrsiExact(
1404
+ payload,
1405
+ [
1406
+ "batch",
1407
+ "scopeStatisticsRegistrationDigest",
1408
+ "batchStatisticsRegistrationDigest",
1409
+ "statisticsPlanDigest",
1410
+ ],
1411
+ "preregistered native batch reservation",
1412
+ );
1413
+ const binding = nativeStatisticsReserveBinding(state, payload.batch);
1414
+ for (const name of Object.keys(binding))
1415
+ if (payload[name] !== binding[name])
1416
+ rrsiFail("native reservation replaces its statistics registration");
1417
+ if (liveAdmission && payload.batch.stage === "generalization")
1418
+ rrsiFail(
1419
+ "preregistered final evaluation requires a verified native selection quality receipt",
1420
+ "CC_RRSI_QUALITY_RECEIPT_REQUIRED",
1421
+ );
1422
+ return reserveNativeBatch(state, { batch: payload.batch }, binding);
1423
+ }
1424
+ if (kind === "reserve-native-batch")
1425
+ return reserveNativeBatch(state, payload);
1426
+ if (kind === "dispatch-native" || kind === "unknown-native") {
1427
+ rrsiExact(payload, ["childId", "batchDigest"], "native child transition");
1428
+ const child = state.nativeChildren.get(payload.childId);
1429
+ if (!child || child.bindings.batchDigest !== payload.batchDigest)
1430
+ rrsiFail("native child binding differs");
1431
+ if (kind === "dispatch-native") {
1432
+ if (
1433
+ liveAdmission &&
1434
+ state.nativeStatisticsScope &&
1435
+ state.nativeBatches.get(payload.batchDigest)?.stage ===
1436
+ "generalization"
1437
+ )
1438
+ rrsiFail(
1439
+ "preregistered final dispatch requires a verified native selection quality receipt",
1440
+ "CC_RRSI_QUALITY_RECEIPT_REQUIRED",
1441
+ );
1442
+ if (state.overrun)
1443
+ rrsiFail(
1444
+ "history contains a resource overrun",
1445
+ "CC_RRSI_BUDGET_EXCEEDED",
1446
+ );
1447
+ checkPreparationHold(state);
1448
+ }
1449
+ for (const reservation of child.reservations) {
1450
+ const entry = state.reservations.get(reservation.bindings.executionId);
1451
+ if (kind === "dispatch-native") {
1452
+ if (entry.status !== "reserved" || entry.dispatched)
1453
+ rrsiFail(
1454
+ "native child cannot be dispatched twice",
1455
+ "CC_RRSI_REPLAY_FORBIDDEN",
1456
+ );
1457
+ entry.dispatched = true;
1458
+ entry.status = "dispatch-intent";
1459
+ } else if (entry.status !== "settled") entry.status = "unknown";
1460
+ }
1461
+ state.nativeRecoveryHolds.set(
1462
+ payload.childId,
1463
+ child.reservations.every(
1464
+ (reservation) =>
1465
+ state.reservations.get(reservation.bindings.executionId).status ===
1466
+ "settled",
1467
+ )
1468
+ ? 0
1469
+ : Math.max(1, state.nativeRecoveryHolds.get(payload.childId) - 1),
1470
+ );
1471
+ return child.bindings;
1472
+ }
1473
+ if (kind === "settle-native") {
1474
+ rrsiExact(payload, ["evidence"], "native child settlement");
1475
+ const child = state.nativeChildren.get(
1476
+ payload.evidence?.core?.bindings?.childId,
1477
+ );
1478
+ if (!child) rrsiFail("native settlement child is not reserved");
1479
+ const checked = verifySettlement(
1480
+ options.settlementVerifier,
1481
+ payload.evidence,
1482
+ { schema: RRSI_NATIVE_RESERVATION_SCHEMA, bindings: child.bindings },
1483
+ acceptedAt,
1484
+ );
1485
+ const core = checked.core;
1486
+ if (
1487
+ child.reservations.every(
1488
+ (reservation) =>
1489
+ state.reservations.get(reservation.bindings.executionId).status ===
1490
+ "settled",
1491
+ )
1492
+ )
1493
+ rrsiFail(
1494
+ "native child is already settled",
1495
+ "CC_RRSI_OPERATION_CONFLICT",
1496
+ );
1497
+ if (state.receiptIds.has(core.receiptId))
1498
+ rrsiFail("native settlement receipt ID is already used");
1499
+ const owner = rrsiHash(
1500
+ "chainlesschain.rrsi-native-child-settlement-owner/v1",
1501
+ child.bindings,
1502
+ );
1503
+ for (const digest of core.sourceReceiptDigests) {
1504
+ if (
1505
+ state.sourceReceiptOwners.has(digest) &&
1506
+ state.sourceReceiptOwners.get(digest) !== owner
1507
+ )
1508
+ rrsiFail(
1509
+ "source receipt is already bound to another child or reservation",
1510
+ "CC_RRSI_SETTLEMENT_INVALID",
1511
+ );
1512
+ state.sourceReceiptOwners.set(digest, owner);
1513
+ }
1514
+ for (const reservation of child.reservations) {
1515
+ const entry = state.reservations.get(reservation.bindings.executionId);
1516
+ const arm = reservation.bindings.arm;
1517
+ const usage = core.usageByArm[arm],
1518
+ units = core.executionUnitsByArm[arm],
1519
+ status = core.statusByArm[arm];
1520
+ if (entry.status === "settled") {
1521
+ const prior = entry.settlement.core;
1522
+ if (
1523
+ rrsiCanonical([
1524
+ usage,
1525
+ units,
1526
+ status,
1527
+ core.cleanupConfirmedByArm[arm],
1528
+ ]) !==
1529
+ rrsiCanonical([
1530
+ prior.usageByArm[arm],
1531
+ prior.executionUnitsByArm[arm],
1532
+ prior.statusByArm[arm],
1533
+ prior.cleanupConfirmedByArm[arm],
1534
+ ])
1535
+ )
1536
+ rrsiFail("settled native arm cannot be rewritten");
1537
+ continue;
1538
+ }
1539
+ for (const name of RRSI_NATIVE_EXECUTION_UNITS) {
1540
+ if (
1541
+ units[name] !== null &&
1542
+ entry.knownExecutionUnits[name] !== null &&
1543
+ units[name] < entry.knownExecutionUnits[name]
1544
+ )
1545
+ rrsiFail("native execution units cannot decrease known totals");
1546
+ if (units[name] !== null)
1547
+ entry.knownExecutionUnits[name] = units[name];
1548
+ if (
1549
+ status === "succeeded" &&
1550
+ units[name] !== null &&
1551
+ units[name] < reservation.executionUnits[name]
1552
+ )
1553
+ rrsiFail(
1554
+ "successful native settlement omits a frozen execution category",
1555
+ );
1556
+ }
1557
+ for (const name of USAGE_FIELDS) {
1558
+ if (
1559
+ usage[name] !== null &&
1560
+ entry.knownUsage[name] !== null &&
1561
+ usage[name] < entry.knownUsage[name]
1562
+ )
1563
+ rrsiFail("native usage cannot decrease known totals");
1564
+ if (usage[name] !== null) entry.knownUsage[name] = usage[name];
1565
+ if (
1566
+ usage[name] !== null &&
1567
+ usage[name] > reservation.budget[USAGE_TO_BUDGET[name]]
1568
+ )
1569
+ state.overrun = true;
1570
+ }
1571
+ const knownUnitFloor = rrsiNativeUnitCount(
1572
+ Object.fromEntries(
1573
+ RRSI_NATIVE_EXECUTION_UNITS.map((name) => [
1574
+ name,
1575
+ entry.knownExecutionUnits[name] ?? 0,
1576
+ ]),
1577
+ ),
1578
+ );
1579
+ entry.knownUsage.executions = Math.max(
1580
+ entry.knownUsage.executions ?? 0,
1581
+ knownUnitFloor,
1582
+ );
1583
+ if (knownUnitFloor > reservation.budget.maxExecutions)
1584
+ state.overrun = true;
1585
+ if (
1586
+ status === "not-started" &&
1587
+ (entry.dispatched ||
1588
+ Object.values(usage).some((amount) => amount !== 0) ||
1589
+ Object.values(units).some((amount) => amount !== 0))
1590
+ )
1591
+ rrsiFail(
1592
+ "native not-started settlement contradicts dispatch or usage",
1593
+ );
1594
+ if (!["not-started", "unknown"].includes(status) && !entry.dispatched)
1595
+ rrsiFail("native terminal settlement has no durable dispatch intent");
1596
+ entry.settlement = checked.evidence;
1597
+ entry.status =
1598
+ status !== "unknown" &&
1599
+ core.cleanupConfirmedByArm[arm] &&
1600
+ Object.values(usage).every((amount) => amount !== null) &&
1601
+ Object.values(units).every((amount) => amount !== null)
1602
+ ? "settled"
1603
+ : "unknown";
1604
+ }
1605
+ state.nativeRecoveryHolds.set(
1606
+ child.bindings.childId,
1607
+ child.reservations.every(
1608
+ (reservation) =>
1609
+ state.reservations.get(reservation.bindings.executionId).status ===
1610
+ "settled",
1611
+ )
1612
+ ? 0
1613
+ : Math.max(
1614
+ 1,
1615
+ state.nativeRecoveryHolds.get(child.bindings.childId) - 1,
1616
+ ),
1617
+ );
1618
+ state.receiptIds.add(core.receiptId);
1619
+ return child.bindings;
1620
+ }
1621
+ if (kind === "register-preparation-plan") {
1622
+ const campaign = campaignFor(state, payload.campaignDigest);
1623
+ const plan = normalizeRrsiPreparationPlan(payload, state.root);
1624
+ if (state.finalCandidates.size)
1625
+ rrsiFail("frozen finalist prohibits preparation plan registration");
1626
+ if (rrsiTrainingSourcesDigest(campaign) !== plan.trainingSourcesDigest)
1627
+ rrsiFail("preparation plan training sources differ from root");
1628
+ if (state.preparationPlan)
1629
+ rrsiFail(
1630
+ "preparation plan is already frozen",
1631
+ "CC_RRSI_OPERATION_CONFLICT",
1632
+ );
1633
+ state.preparationPlan = plan;
1634
+ return plan;
1635
+ }
1636
+ if (kind === "reserve-preparation") {
1637
+ if (state.overrun)
1638
+ rrsiFail(
1639
+ "history contains a resource overrun",
1640
+ "CC_RRSI_BUDGET_EXCEEDED",
1641
+ );
1642
+ if (!state.preparationPlan)
1643
+ rrsiFail(
1644
+ "preparation plan has not been durably registered",
1645
+ "CC_RRSI_UNREGISTERED",
1646
+ );
1647
+ if (state.finalCandidates.size)
1648
+ rrsiFail("frozen finalist prohibits further preparation");
1649
+ checkPreparationHold(state);
1650
+ if (
1651
+ [...state.reservations.values()].some(
1652
+ (entry) => entry.status !== "settled",
1653
+ )
1654
+ )
1655
+ rrsiFail(
1656
+ "unresolved query prohibits preparation admission",
1657
+ "CC_RRSI_HISTORY_HOLD",
1658
+ );
1659
+ const campaign = campaignFor(state, payload.campaignDigest);
1660
+ const normalized = normalizeRrsiPreparationRequest(
1661
+ payload,
1662
+ campaign,
1663
+ state.preparationPlan,
1664
+ );
1665
+ if (state.preparationRequests.has(normalized.bindings.requestDigest))
1666
+ rrsiFail(
1667
+ "semantic preparation request has already been consumed",
1668
+ "CC_RRSI_PREPARATION_USED",
1669
+ );
1670
+ if (state.preparationAttempts >= state.preparationPlan.maxAttempts)
1671
+ rrsiFail(
1672
+ "preparation attempt limit is exhausted",
1673
+ "CC_RRSI_PREPARATION_EXHAUSTED",
1674
+ );
1675
+ const slot = `${descriptor.scopeId}:preparation:${payload.slotId}`;
1676
+ if (state.slots.has(slot) || state.reservations.has(payload.executionId))
1677
+ rrsiFail("execution or slot is already occupied", "CC_RRSI_SLOT_USED");
1678
+ checkBudget(state, normalized.budget, "proposal");
1679
+ const core = {
1680
+ tenantId: descriptor.tenantId,
1681
+ scopeId: descriptor.scopeId,
1682
+ ...state.identity,
1683
+ campaignDigest: campaign.campaignDigest,
1684
+ executionDigest: state.preparationPlan.executionDigest,
1685
+ executionId: payload.executionId,
1686
+ slotId: payload.slotId,
1687
+ partition: "train",
1688
+ ...normalized.bindings,
1689
+ };
1690
+ const reservationDigest = rrsiHash(normalized.schema, {
1691
+ bindings: core,
1692
+ budget: normalized.budget,
1693
+ plannedExecutions: normalized.plannedExecutions,
1694
+ });
1695
+ const reservation = freezeRrsiData({
1696
+ schema: normalized.schema,
1697
+ bindings: { ...core, reservationDigest },
1698
+ budget: normalized.budget,
1699
+ plannedExecutions: normalized.plannedExecutions,
1700
+ reservationDigest,
1701
+ });
1702
+ state.reservations.set(payload.executionId, {
1703
+ reservation,
1704
+ status: "reserved",
1705
+ knownUsage: Object.fromEntries(USAGE_FIELDS.map((key) => [key, null])),
1706
+ settlement: null,
1707
+ dispatched: false,
1708
+ });
1709
+ state.slots.add(slot);
1710
+ state.preparationAttempts++;
1711
+ state.preparationRequests.add(normalized.bindings.requestDigest);
1712
+ return reservation;
1713
+ }
1714
+ if (kind === "reserve") {
1715
+ if (state.nativeStatisticsScope)
1716
+ rrsiFail(
1717
+ "a frozen statistics scope prohibits legacy evaluation reservation",
1718
+ "CC_RRSI_PREREGISTRATION_REQUIRED",
1719
+ );
1720
+ rrsiExact(
1721
+ payload,
1722
+ [
1723
+ "campaignDigest",
1724
+ "candidate",
1725
+ "partition",
1726
+ "slotId",
1727
+ "executionId",
1728
+ "budget",
1729
+ ],
1730
+ "query reservation",
1731
+ );
1732
+ if (state.overrun)
1733
+ rrsiFail(
1734
+ "history contains a resource overrun",
1735
+ "CC_RRSI_BUDGET_EXCEEDED",
1736
+ );
1737
+ checkPreparationHold(state);
1738
+ const campaign = campaignFor(state, payload.campaignDigest);
1739
+ if (
1740
+ state.nativeBatches.size &&
1741
+ state.finalCandidates.size &&
1742
+ payload.partition === "select"
1743
+ )
1744
+ rrsiFail("frozen native finalist prohibits legacy selection fallback");
1745
+ if (
1746
+ payload.partition !== "select" &&
1747
+ [...state.nativeBatches.values()].some(
1748
+ (batch) => batch.campaignDigest === campaign.campaignDigest,
1749
+ )
1750
+ )
1751
+ rrsiFail(
1752
+ "native candidate cannot fall back to legacy final reservations",
1753
+ );
1754
+ if (
1755
+ [...state.nativeBatches.values()].some(
1756
+ (batch) =>
1757
+ batch.stage === "generalization" &&
1758
+ batch.campaignDigest === campaign.campaignDigest,
1759
+ ) &&
1760
+ payload.partition !== "select"
1761
+ )
1762
+ rrsiFail(
1763
+ "native final partitions have already been consumed",
1764
+ "CC_RRSI_QUERY_USED",
1765
+ );
1766
+ const candidate = verifyRrsiCandidate(campaign, payload.candidate);
1767
+ if (
1768
+ !RRSI_PARTITIONS.includes(payload.partition) ||
1769
+ payload.partition === "train"
1770
+ )
1771
+ rrsiFail("invalid reserved partition");
1772
+ const slotId = rrsiId(payload.slotId, "slot ID");
1773
+ const executionId = rrsiId(payload.executionId, "execution ID");
1774
+ const slot = `${campaign.campaignDigest}:${payload.partition}:${slotId}`;
1775
+ if (state.slots.has(slot) || state.reservations.has(executionId))
1776
+ rrsiFail("execution or slot is already occupied", "CC_RRSI_SLOT_USED");
1777
+ const priorCandidate = state.candidates.get(candidate.contentDigest);
1778
+ if (
1779
+ priorCandidate &&
1780
+ priorCandidate.candidateDigest !== candidate.candidateDigest
1781
+ )
1782
+ rrsiFail(
1783
+ "content is already bound to another candidate identity",
1784
+ "CC_RRSI_DUPLICATE_CONTENT",
1785
+ );
1786
+ const stage = payload.partition === "select" ? "selection" : "final";
1787
+ if (stage === "selection") {
1788
+ if (state.finalCandidates.has(campaign.campaignDigest))
1789
+ rrsiFail("frozen candidate prohibits further selection");
1790
+ if (priorCandidate)
1791
+ rrsiFail(
1792
+ "candidate selection query has already been consumed",
1793
+ "CC_RRSI_QUERY_USED",
1794
+ );
1795
+ if (
1796
+ state.selectionQueries >=
1797
+ state.root.policy.limits.maxSelectionQueries ||
1798
+ state.candidates.size >= state.root.policy.limits.maxCandidates
1799
+ )
1800
+ rrsiFail(
1801
+ "history selection quota is exhausted",
1802
+ "CC_RRSI_QUERY_EXHAUSTED",
1803
+ );
1804
+ } else if (
1805
+ state.finalCandidates.get(campaign.campaignDigest) !==
1806
+ candidate.contentDigest
1807
+ )
1808
+ rrsiFail("final query requires the unique frozen candidate");
1809
+ if (
1810
+ stage === "final" &&
1811
+ [...state.reservations.values()].some(
1812
+ (entry) =>
1813
+ entry.reservation.bindings.campaignDigest ===
1814
+ campaign.campaignDigest &&
1815
+ entry.reservation.bindings.partition === payload.partition,
1816
+ )
1817
+ )
1818
+ rrsiFail(
1819
+ "final partition has already been consumed",
1820
+ "CC_RRSI_QUERY_USED",
1821
+ );
1822
+ const keys = sourceKeys(campaign, payload.partition);
1823
+ for (const key of keys) {
1824
+ const previous = state.sources.get(key);
1825
+ if (
1826
+ previous &&
1827
+ (previous.stage !== stage ||
1828
+ (stage === "final" &&
1829
+ previous.campaignDigest !== campaign.campaignDigest))
1830
+ )
1831
+ rrsiFail(
1832
+ "previously exposed source cannot be treated as unseen",
1833
+ "CC_RRSI_HOLDOUT_USED",
1834
+ );
1835
+ }
1836
+ const ceiling = budget(payload.budget, "reserved budget");
1837
+ const minimumExecutions =
1838
+ campaign.dataset.pools[payload.partition].taskCount *
1839
+ campaign.experiment.seeds.length *
1840
+ (stage === "selection"
1841
+ ? 2 * (1 + campaign.experiment.perturbations.length)
1842
+ : 1);
1843
+ if (ceiling.maxExecutions < minimumExecutions)
1844
+ rrsiFail("reservation does not cover its frozen execution denominator");
1845
+ checkBudget(state, ceiling, stage);
1846
+ const core = {
1847
+ tenantId: descriptor.tenantId,
1848
+ scopeId: descriptor.scopeId,
1849
+ ...state.identity,
1850
+ campaignDigest: campaign.campaignDigest,
1851
+ candidateDigest: candidate.candidateDigest,
1852
+ contentDigest: candidate.contentDigest,
1853
+ executionDigest: rrsiHash(
1854
+ "chainlesschain.rrsi-execution-bindings/v1",
1855
+ campaign.execution,
1856
+ ),
1857
+ executionId,
1858
+ slotId,
1859
+ partition: payload.partition,
1860
+ };
1861
+ const reservationDigest = rrsiHash(RRSI_RESERVATION_SCHEMA, {
1862
+ bindings: core,
1863
+ budget: ceiling,
1864
+ plannedExecutions: minimumExecutions,
1865
+ });
1866
+ const reservation = freezeRrsiData({
1867
+ schema: RRSI_RESERVATION_SCHEMA,
1868
+ bindings: { ...core, reservationDigest },
1869
+ budget: ceiling,
1870
+ plannedExecutions: minimumExecutions,
1871
+ reservationDigest,
1872
+ });
1873
+ state.reservations.set(executionId, {
1874
+ reservation,
1875
+ status: "reserved",
1876
+ knownUsage: Object.fromEntries(USAGE_FIELDS.map((key) => [key, null])),
1877
+ settlement: null,
1878
+ dispatched: false,
1879
+ });
1880
+ state.slots.add(slot);
1881
+ state.candidates.set(candidate.contentDigest, candidate);
1882
+ if (stage === "selection") state.selectionQueries++;
1883
+ for (const key of keys)
1884
+ state.sources.set(key, {
1885
+ campaignDigest: campaign.campaignDigest,
1886
+ stage,
1887
+ });
1888
+ return reservation;
1889
+ }
1890
+ if (kind === "freeze") {
1891
+ rrsiExact(
1892
+ payload,
1893
+ ["campaignDigest", "contentDigest"],
1894
+ "candidate freeze",
1895
+ );
1896
+ const campaign = campaignFor(state, payload.campaignDigest);
1897
+ if (liveAdmission && state.nativeStatisticsScope)
1898
+ rrsiFail(
1899
+ "preregistered native freeze requires a verified selection quality receipt",
1900
+ "CC_RRSI_QUALITY_RECEIPT_REQUIRED",
1901
+ );
1902
+ if (
1903
+ liveAdmission &&
1904
+ state.nativeBatches.size &&
1905
+ state.finalCandidates.size
1906
+ )
1907
+ rrsiFail("native history already has its unique global finalist");
1908
+ rrsiDigest(payload.contentDigest, "frozen content digest");
1909
+ if (
1910
+ state.overrun ||
1911
+ [...state.reservations.values()].some(
1912
+ (entry) => entry.status !== "settled",
1913
+ )
1914
+ )
1915
+ rrsiFail(
1916
+ "candidate freeze requires complete history accounting without overruns",
1917
+ "CC_RRSI_HISTORY_HOLD",
1918
+ );
1919
+ const selected = [...state.reservations.values()].find(
1920
+ (entry) =>
1921
+ entry.reservation.bindings.campaignDigest ===
1922
+ campaign.campaignDigest &&
1923
+ entry.reservation.bindings.contentDigest === payload.contentDigest &&
1924
+ entry.reservation.bindings.partition === "select",
1925
+ );
1926
+ const nativeSelection = [...state.nativeBatches.values()].find(
1927
+ (batch) =>
1928
+ batch.stage === "selection" &&
1929
+ batch.campaignDigest === campaign.campaignDigest &&
1930
+ batch.candidate.contentDigest === payload.contentDigest,
1931
+ );
1932
+ if (
1933
+ nativeSelection &&
1934
+ nativeSelection.children.some((child) => {
1935
+ const group = state.nativeChildren.get(child.childId);
1936
+ return group.reservations.some((reservation) => {
1937
+ const entry = state.reservations.get(
1938
+ reservation.bindings.executionId,
1939
+ );
1940
+ return (
1941
+ entry.status !== "settled" ||
1942
+ entry.settlement.core.statusByArm[reservation.bindings.arm] !==
1943
+ "succeeded"
1944
+ );
1945
+ });
1946
+ })
1947
+ )
1948
+ rrsiFail(
1949
+ "native candidate freeze requires every planned paired arm to settle successfully",
1950
+ );
1951
+ if (
1952
+ !selected ||
1953
+ selected.status !== "settled" ||
1954
+ (nativeSelection
1955
+ ? selected.settlement.core.statusByArm[
1956
+ selected.reservation.bindings.arm
1957
+ ] !== "succeeded"
1958
+ : selected.settlement.core.status !== "succeeded")
1959
+ )
1960
+ rrsiFail(
1961
+ "candidate requires independently settled successful selection before freezing",
1962
+ );
1963
+ if (state.finalCandidates.has(campaign.campaignDigest))
1964
+ rrsiFail("campaign finalist is already frozen");
1965
+ state.finalCandidates.set(campaign.campaignDigest, payload.contentDigest);
1966
+ return payload;
1967
+ }
1968
+ if (kind === "dispatch" || kind === "unknown") {
1969
+ rrsiExact(
1970
+ payload,
1971
+ ["executionId", "reservationDigest"],
1972
+ "execution transition",
1973
+ );
1974
+ const entry = reservationFor(
1975
+ state,
1976
+ payload.executionId,
1977
+ payload.reservationDigest,
1978
+ );
1979
+ if (isRrsiNativeReservation(entry.reservation))
1980
+ rrsiFail("native arms require the atomic child transition");
1981
+ if (kind === "dispatch") {
1982
+ // New admission guards must not erase authenticated pre-upgrade costs.
1983
+ // Old v1 dispatch history remains readable; every new dispatch rechecks.
1984
+ if (liveAdmission) {
1985
+ if (state.overrun)
1986
+ rrsiFail(
1987
+ "history contains a resource overrun",
1988
+ "CC_RRSI_BUDGET_EXCEEDED",
1989
+ );
1990
+ if (!isRrsiPreparationReservation(entry.reservation))
1991
+ checkPreparationHold(state);
1992
+ }
1993
+ if (entry.status !== "reserved" || entry.dispatched)
1994
+ rrsiFail(
1995
+ "execution cannot be dispatched twice",
1996
+ "CC_RRSI_REPLAY_FORBIDDEN",
1997
+ );
1998
+ entry.dispatched = true;
1999
+ entry.status = "dispatch-intent";
2000
+ } else {
2001
+ if (entry.status === "settled")
2002
+ rrsiFail("settled execution cannot become unknown");
2003
+ entry.status = "unknown";
2004
+ }
2005
+ return entry.reservation;
2006
+ }
2007
+ if (kind === "observe-preparation") {
2008
+ rrsiExact(
2009
+ payload,
2010
+ ["executionId", "reservationDigest", "observation"],
2011
+ "preparation execution observation",
2012
+ );
2013
+ const entry = reservationFor(
2014
+ state,
2015
+ payload.executionId,
2016
+ payload.reservationDigest,
2017
+ );
2018
+ if (!isRrsiPreparationReservation(entry.reservation) || !entry.dispatched)
2019
+ rrsiFail(
2020
+ "preparation observation requires durable preparation dispatch",
2021
+ );
2022
+ rrsiExact(
2023
+ payload.observation,
2024
+ ["result", "failureCode", "driftDetected"],
2025
+ "PM execution observation",
2026
+ );
2027
+ rrsiBoolean(payload.observation.driftDetected, "PM journal drift");
2028
+ if (payload.observation.failureCode !== null)
2029
+ rrsiId(payload.observation.failureCode, "PM failure code");
2030
+ if (
2031
+ payload.observation.result !== null &&
2032
+ (typeof payload.observation.result !== "object" ||
2033
+ Array.isArray(payload.observation.result))
2034
+ )
2035
+ rrsiFail("PM observation result must be a record or null");
2036
+ entry.observation = freezeRrsiData({
2037
+ ...payload.observation,
2038
+ independentlyReverified: false,
2039
+ costEvidenceVerified: false,
2040
+ qualifiesForPromotion: false,
2041
+ });
2042
+ // A PM receipt does not settle money or cleanup. Never erase signed settlement.
2043
+ if (entry.status !== "settled") entry.status = "unknown";
2044
+ return entry.reservation;
2045
+ }
2046
+ if (kind === "settle") {
2047
+ rrsiExact(payload, ["evidence"], "execution settlement");
2048
+ const bindings = payload.evidence?.core?.bindings;
2049
+ const entry = reservationFor(
2050
+ state,
2051
+ bindings?.executionId,
2052
+ bindings?.reservationDigest,
2053
+ );
2054
+ if (isRrsiNativeReservation(entry.reservation))
2055
+ rrsiFail("native arms require a paired child settlement");
2056
+ const checked = verifySettlement(
2057
+ options.settlementVerifier,
2058
+ payload.evidence,
2059
+ entry.reservation,
2060
+ acceptedAt,
2061
+ );
2062
+ if (entry.status === "settled")
2063
+ rrsiFail(
2064
+ "execution is already independently settled",
2065
+ "CC_RRSI_OPERATION_CONFLICT",
2066
+ );
2067
+ if (state.receiptIds.has(checked.core.receiptId))
2068
+ rrsiFail("settlement receipt ID is already used");
2069
+ for (const digest of checked.core.sourceReceiptDigests) {
2070
+ const owner = state.sourceReceiptOwners.get(digest);
2071
+ if (owner && owner !== entry.reservation.reservationDigest)
2072
+ rrsiFail(
2073
+ "source receipt is already bound to another reservation",
2074
+ "CC_RRSI_SETTLEMENT_INVALID",
2075
+ );
2076
+ state.sourceReceiptOwners.set(
2077
+ digest,
2078
+ entry.reservation.reservationDigest,
2079
+ );
2080
+ }
2081
+ for (const field of USAGE_FIELDS) {
2082
+ const actual = checked.core.usage[field];
2083
+ if (
2084
+ actual !== null &&
2085
+ entry.knownUsage[field] !== null &&
2086
+ actual < entry.knownUsage[field]
2087
+ )
2088
+ rrsiFail("settlement usage cannot decrease previous known totals");
2089
+ if (actual !== null) entry.knownUsage[field] = actual;
2090
+ if (
2091
+ actual !== null &&
2092
+ actual > entry.reservation.budget[USAGE_TO_BUDGET[field]]
2093
+ )
2094
+ state.overrun = true;
2095
+ }
2096
+ if (
2097
+ checked.core.status === "not-started" &&
2098
+ (entry.dispatched ||
2099
+ USAGE_FIELDS.some((key) => checked.core.usage[key] !== 0))
2100
+ )
2101
+ rrsiFail("not-started settlement contradicts dispatch or usage");
2102
+ if (
2103
+ checked.core.status !== "not-started" &&
2104
+ checked.core.status !== "unknown" &&
2105
+ !entry.dispatched
2106
+ )
2107
+ rrsiFail("terminal settlement has no durable dispatch intent");
2108
+ if (
2109
+ checked.core.status === "succeeded" &&
2110
+ checked.core.usage.executions !== null &&
2111
+ checked.core.usage.executions < entry.reservation.plannedExecutions
2112
+ )
2113
+ rrsiFail(
2114
+ "successful settlement does not cover the frozen execution denominator",
2115
+ );
2116
+ entry.settlement = checked.evidence;
2117
+ entry.status =
2118
+ checked.core.status !== "unknown" &&
2119
+ checked.core.cleanupConfirmed &&
2120
+ USAGE_FIELDS.every((key) => checked.core.usage[key] !== null)
2121
+ ? "settled"
2122
+ : "unknown";
2123
+ state.receiptIds.add(checked.core.receiptId);
2124
+ return entry.reservation;
2125
+ }
2126
+ rrsiFail("unsupported RRSI history operation");
2127
+ }
2128
+
2129
+ function load() {
2130
+ for (let attempt = 0; attempt < 8; attempt++) {
2131
+ const before = methods.verify();
2132
+ if (
2133
+ before.authenticated !== true ||
2134
+ before.durable !== true ||
2135
+ before.status !== "verified"
2136
+ )
2137
+ rrsiFail("RRSI Ledger head is unauthenticated");
2138
+ const events = methods.read({
2139
+ afterSequence: 0,
2140
+ limit: EVOLUTION_LEDGER_MAX_EVENTS,
2141
+ });
2142
+ const after = methods.verify();
2143
+ if (!sameIdentity(before, after)) continue;
2144
+ if (
2145
+ events.length !== after.sequence ||
2146
+ events.some((event, index) => event.sequence !== index + 1)
2147
+ )
2148
+ rrsiFail(
2149
+ "RRSI history requires complete contiguous Ledger coverage",
2150
+ "CC_RRSI_HISTORY_CORRUPT",
2151
+ );
2152
+ const state = emptyState(before);
2153
+ let count = 0;
2154
+ for (const event of events) {
2155
+ if (
2156
+ event.type !== RRSI_HISTORY_EVENT_TYPE ||
2157
+ event.tenantId !== descriptor.tenantId ||
2158
+ event.skillName !== descriptor.goalId
2159
+ )
2160
+ continue;
2161
+ if (
2162
+ ++count > 5000 ||
2163
+ event.schema !== EVOLUTION_LEDGER_DOMAIN_EVENT_SCHEMA ||
2164
+ event.artifactTenantId !== descriptor.artifactTenantId ||
2165
+ event.correlationId !== descriptor.scopeId
2166
+ )
2167
+ rrsiFail(
2168
+ "RRSI history event scope is inconsistent",
2169
+ "CC_RRSI_HISTORY_CORRUPT",
2170
+ );
2171
+ const resolution = options.ledgerArtifactResolver({
2172
+ epoch: before.epoch,
2173
+ ledgerId: before.ledgerId,
2174
+ ref: copyRetainedRef(event.subjectRef),
2175
+ tenantId: descriptor.artifactTenantId,
2176
+ });
2177
+ if (
2178
+ resolution?.schema !== EVOLUTION_ARTIFACT_RESOLUTION_SCHEMA ||
2179
+ resolution.authenticated !== true ||
2180
+ resolution.found !== true ||
2181
+ resolution.ref !== event.subjectRef.ref ||
2182
+ resolution.digest !== event.subjectRef.digest ||
2183
+ !Buffer.isBuffer(resolution.bytes)
2184
+ )
2185
+ rrsiFail(
2186
+ "RRSI durable artifact cannot be authenticated",
2187
+ "CC_RRSI_HISTORY_CORRUPT",
2188
+ );
2189
+ const stored = snapshotRrsiData(
2190
+ JSON.parse(
2191
+ new TextDecoder("utf-8", { fatal: true }).decode(resolution.bytes),
2192
+ ),
2193
+ );
2194
+ if (
2195
+ stored.schema !== EVOLUTION_DURABLE_ARTIFACT_RECORD_SCHEMA ||
2196
+ stored.tenantId !== descriptor.artifactTenantId ||
2197
+ stored.audience !== descriptor.audience ||
2198
+ stored.purpose !== descriptor.purpose ||
2199
+ stored.retention !== "ledger" ||
2200
+ stored.type !== ARTIFACT_TYPE
2201
+ )
2202
+ rrsiFail(
2203
+ "RRSI durable artifact retention scope differs",
2204
+ "CC_RRSI_HISTORY_CORRUPT",
2205
+ );
2206
+ const record = stored.value;
2207
+ rrsiExact(
2208
+ record,
2209
+ [
2210
+ "schema",
2211
+ "descriptor",
2212
+ "ledgerId",
2213
+ "epoch",
2214
+ "operationId",
2215
+ "kind",
2216
+ "payload",
2217
+ "previousRecordDigest",
2218
+ "acceptedAt",
2219
+ ...FLAGS,
2220
+ "recordDigest",
2221
+ ],
2222
+ "RRSI history record",
2223
+ );
2224
+ const core = Object.fromEntries(
2225
+ [
2226
+ "descriptor",
2227
+ "ledgerId",
2228
+ "epoch",
2229
+ "operationId",
2230
+ "kind",
2231
+ "payload",
2232
+ "previousRecordDigest",
2233
+ "acceptedAt",
2234
+ ].map((key) => [key, record[key]]),
2235
+ );
2236
+ const rebuilt = rrsiEnvelope(
2237
+ RRSI_HISTORY_EVENT_SCHEMA,
2238
+ "recordDigest",
2239
+ core,
2240
+ );
2241
+ if (
2242
+ rrsiCanonical(record) !== rrsiCanonical(rebuilt) ||
2243
+ rrsiCanonical(record.descriptor) !== rrsiCanonical(descriptor) ||
2244
+ record.ledgerId !== before.ledgerId ||
2245
+ record.epoch !== before.epoch ||
2246
+ record.acceptedAt !== event.timestamp ||
2247
+ record.previousRecordDigest !== state.lastRecordDigest ||
2248
+ event.eventId !== operationEventId(record.operationId)
2249
+ )
2250
+ rrsiFail(
2251
+ "RRSI history record chain or identity differs",
2252
+ "CC_RRSI_HISTORY_CORRUPT",
2253
+ );
2254
+ if (state.operations.has(record.operationId))
2255
+ rrsiFail("RRSI history has duplicate operations");
2256
+ if (
2257
+ record.kind === NATIVE_QUALITY_RECEIPT_KIND &&
2258
+ record.operationId !==
2259
+ nativeQualityReceiptOperation(
2260
+ record.payload.qualityReceipt?.qualityReceiptDigest,
2261
+ )
2262
+ )
2263
+ rrsiFail(
2264
+ "native quality receipt operation ID differs",
2265
+ "CC_RRSI_HISTORY_CORRUPT",
2266
+ );
2267
+ if (
2268
+ record.kind === NATIVE_STATISTICS_SCOPE_KIND &&
2269
+ record.operationId !== NATIVE_STATISTICS_SCOPE_OPERATION
2270
+ )
2271
+ rrsiFail(
2272
+ "native statistics scope operation ID differs",
2273
+ "CC_RRSI_HISTORY_CORRUPT",
2274
+ );
2275
+ if (
2276
+ [
2277
+ NATIVE_STATISTICS_PLAN_KIND,
2278
+ NATIVE_STATISTICS_RESERVE_KIND,
2279
+ ].includes(record.kind)
2280
+ ) {
2281
+ rrsiId(record.payload.batch?.queryId, "native statistics query ID");
2282
+ const expectedOperationId =
2283
+ record.kind === NATIVE_STATISTICS_PLAN_KIND
2284
+ ? nativeStatisticsPlanOperation(record.payload.batch.queryId)
2285
+ : `reserve-native.${rrsiHash("chainlesschain.rrsi-native-query-operation/v1", record.payload.batch.queryId).slice(7)}`;
2286
+ if (record.operationId !== expectedOperationId)
2287
+ rrsiFail(
2288
+ "native statistics query operation ID differs",
2289
+ "CC_RRSI_HISTORY_CORRUPT",
2290
+ );
2291
+ }
2292
+ const statisticsRefs = nativeStatisticsSourceRefs(
2293
+ state,
2294
+ record.kind,
2295
+ record.payload,
2296
+ );
2297
+ if (
2298
+ statisticsRefs &&
2299
+ rrsiCanonical(event.sourceRefs) !== rrsiCanonical(statisticsRefs)
2300
+ )
2301
+ rrsiFail(
2302
+ "native statistics History source references differ",
2303
+ "CC_RRSI_HISTORY_CORRUPT",
2304
+ );
2305
+ const result = apply(
2306
+ state,
2307
+ record.kind,
2308
+ record.payload,
2309
+ record.acceptedAt,
2310
+ false,
2311
+ auditHead({
2312
+ ...state.identity,
2313
+ sequence: event.sequence - 1,
2314
+ headDigest: event.prevDigest,
2315
+ }),
2316
+ );
2317
+ state.operations.set(record.operationId, {
2318
+ record,
2319
+ result,
2320
+ ref: copyRetainedRef(event.subjectRef),
2321
+ sequence: event.sequence,
2322
+ });
2323
+ state.lastRecordDigest = record.recordDigest;
2324
+ }
2325
+ if (!sameIdentity(before, methods.verify())) continue;
2326
+ return { state, head: before };
2327
+ }
2328
+ rrsiFail(
2329
+ "RRSI history changed repeatedly during verification",
2330
+ "CC_RRSI_HEAD_CONFLICT",
2331
+ );
2332
+ }
2333
+ function operationEventId(operationId) {
2334
+ return `rrsi.${rrsiHash("chainlesschain.rrsi-history-operation/v1", { scopeDigest, operationId }).slice(7)}`;
2335
+ }
2336
+ function nativeQualityContext(state, batchDigest, observedHead) {
2337
+ const rootOperation = [...state.operations.values()].find(
2338
+ (entry) =>
2339
+ entry.record.kind === "register" &&
2340
+ entry.record.payload.campaign.campaignDigest ===
2341
+ state.root?.campaignDigest,
2342
+ );
2343
+ const batchOperation = [...state.operations.values()].find(
2344
+ (entry) =>
2345
+ ["reserve-native-batch", NATIVE_STATISTICS_RESERVE_KIND].includes(
2346
+ entry.record.kind,
2347
+ ) && entry.record.payload.batch.batchDigest === batchDigest,
2348
+ );
2349
+ if (!rootOperation || !batchOperation)
2350
+ rrsiFail("native quality requires an actual registered batch");
2351
+ const resolution = nativeBatchResolution(
2352
+ state,
2353
+ batchDigest,
2354
+ historyRegistrationRecord(batchOperation),
2355
+ );
2356
+ const statisticsPlan =
2357
+ resolution.statisticsRegistration?.statisticsPlan ??
2358
+ buildRrsiNativeGroupStatisticsPlan({
2359
+ campaign: resolution.campaign,
2360
+ batch: resolution.batch,
2361
+ });
2362
+ return {
2363
+ descriptor,
2364
+ rootResolution: {
2365
+ descriptor,
2366
+ identity: state.identity,
2367
+ campaign: state.root,
2368
+ registrationRecord: historyRegistrationRecord(rootOperation),
2369
+ historyAuthenticated: true,
2370
+ productionBudgetAuthorityVerified: false,
2371
+ },
2372
+ batchResolution: resolution,
2373
+ statisticsPlan,
2374
+ observedHead,
2375
+ };
2376
+ }
2377
+ function nativeQualityResolution(state, digest) {
2378
+ const payload = state.nativeQualityReceipts.get(digest);
2379
+ const operation = state.operations.get(
2380
+ nativeQualityReceiptOperation(digest),
2381
+ );
2382
+ if (!payload || !operation)
2383
+ rrsiFail("native quality receipt is not recorded");
2384
+ if (
2385
+ operation.record.kind !== NATIVE_QUALITY_RECEIPT_KIND ||
2386
+ operation.record.payload !== payload
2387
+ )
2388
+ rrsiFail(
2389
+ "native quality receipt record provenance differs",
2390
+ "CC_RRSI_HISTORY_CORRUPT",
2391
+ );
2392
+ return freezeRrsiData({
2393
+ qualityReceipt: payload.qualityReceipt,
2394
+ registrationRecord: historyRegistrationRecord(operation),
2395
+ identity: state.identity,
2396
+ historyAuthenticated: true,
2397
+ historicalSnapshotOnly: true,
2398
+ currentReceiptFreshnessVerified: false,
2399
+ qualityVerdictVerified: false,
2400
+ grantsFinalEvaluationAuthority: false,
2401
+ readyForExecution: false,
2402
+ qualifiesForPromotion: false,
2403
+ });
2404
+ }
2405
+ function nativeBatchResolution(state, batchDigest, reservationRecord) {
2406
+ const batch = state.nativeBatches.get(batchDigest);
2407
+ if (!batch) rrsiFail("native batch is not registered");
2408
+ const result = {
2409
+ batch,
2410
+ campaign: campaignFor(state, batch.campaignDigest),
2411
+ queryOrdinal: state.nativeQueryOrdinals.get(batch.batchDigest),
2412
+ reservationRecord,
2413
+ identity: state.identity,
2414
+ budgetOverrun: state.overrun,
2415
+ recoveryEventsHeld: [...state.nativeRecoveryHolds.values()].reduce(
2416
+ (sum, amount) => sum + amount,
2417
+ 0,
2418
+ ),
2419
+ children: batch.children.map((child) => {
2420
+ const group = state.nativeChildren.get(child.childId);
2421
+ return {
2422
+ bindings: group.bindings,
2423
+ states: group.reservations.map((reservation) => {
2424
+ const entry = state.reservations.get(
2425
+ reservation.bindings.executionId,
2426
+ );
2427
+ return {
2428
+ arm: reservation.bindings.arm,
2429
+ status: entry.status,
2430
+ dispatched: entry.dispatched,
2431
+ };
2432
+ }),
2433
+ };
2434
+ }),
2435
+ historyAuthenticated: true,
2436
+ readyForExecution: false,
2437
+ qualifiesForPromotion: false,
2438
+ };
2439
+ const binding = state.nativeStatisticsBindings.get(batchDigest);
2440
+ if (binding) {
2441
+ const scope = nativeStatisticsScopeResolution(state);
2442
+ const planOperation = state.operations.get(
2443
+ nativeStatisticsPlanOperation(batch.queryId),
2444
+ );
2445
+ const planRegistrationRecord = historyRegistrationRecord(planOperation);
2446
+ const registered = state.nativeStatisticsPlans.get(batch.queryId);
2447
+ const expected = nativeStatisticsReserveBinding(state, batch);
2448
+ if (
2449
+ rrsiCanonical(expected) !== rrsiCanonical(binding) ||
2450
+ !(
2451
+ scope.binding.rootRegistrationRecord.sequence <
2452
+ scope.registrationRecord.sequence &&
2453
+ scope.registrationRecord.sequence < planRegistrationRecord.sequence &&
2454
+ planRegistrationRecord.sequence < reservationRecord.sequence
2455
+ )
2456
+ )
2457
+ rrsiFail(
2458
+ "native statistics registration sequence or reservation binding differs",
2459
+ "CC_RRSI_HISTORY_CORRUPT",
2460
+ );
2461
+ result.statisticsRegistration = freezeRrsiData({
2462
+ schema:
2463
+ "chainlesschain.rrsi-native-statistics-registration-resolution/v1",
2464
+ binding: scope.binding,
2465
+ protocolDigest: scope.protocol.protocolDigest,
2466
+ statisticsPlanDigest: registered.statisticsPlan.statisticsPlanDigest,
2467
+ statisticsPlan: registered.statisticsPlan,
2468
+ scopeRegistrationRecord: scope.registrationRecord,
2469
+ planRegistrationRecord,
2470
+ reservationRecord,
2471
+ reservationKind: NATIVE_STATISTICS_RESERVE_KIND,
2472
+ historyAuthenticated: true,
2473
+ preObservationRegistrationVerified: true,
2474
+ statisticalProtocolValidated: false,
2475
+ readyForExecution: false,
2476
+ qualifiesForPromotion: false,
2477
+ });
2478
+ }
2479
+ // Reserve enough byte/node space for the longest later status as well as
2480
+ // the actual retained event reference. Do not admit an unreadable batch.
2481
+ snapshotRrsiData({
2482
+ ...result,
2483
+ children: result.children.map((child) => ({
2484
+ ...child,
2485
+ states: child.states.map((arm) => ({
2486
+ ...arm,
2487
+ status: "dispatch-intent",
2488
+ })),
2489
+ })),
2490
+ });
2491
+ return freezeRrsiData(result);
2492
+ }
2493
+ function commitUnlocked(
2494
+ kind,
2495
+ operationId,
2496
+ input,
2497
+ expectedHead = null,
2498
+ assertFreshness = null,
2499
+ ) {
2500
+ const payload = snapshotRrsiData(input);
2501
+ rrsiId(operationId, "operation ID");
2502
+ for (let attempt = 0; attempt < 8; attempt++) {
2503
+ const { state, head } = load();
2504
+ const existing = state.operations.get(operationId);
2505
+ if (existing) {
2506
+ if (
2507
+ existing.record.kind !== kind ||
2508
+ rrsiCanonical(existing.record.payload) !== rrsiCanonical(payload)
2509
+ )
2510
+ rrsiFail(
2511
+ "RRSI operation ID is bound to different data",
2512
+ "CC_RRSI_OPERATION_CONFLICT",
2513
+ );
2514
+ return { result: existing.result, newlyCommitted: false };
2515
+ }
2516
+ if (expectedHead && !sameIdentity(head, expectedHead))
2517
+ rrsiFail(
2518
+ "native quality census head changed before commit",
2519
+ "CC_RRSI_QUALITY_STALE",
2520
+ );
2521
+ const acceptedAt = now();
2522
+ const result = apply(
2523
+ state,
2524
+ kind,
2525
+ payload,
2526
+ acceptedAt,
2527
+ true,
2528
+ auditHead(head),
2529
+ );
2530
+ if (
2531
+ (state.nativeBatches.size ||
2532
+ kind === NATIVE_STATISTICS_SCOPE_KIND ||
2533
+ kind === NATIVE_STATISTICS_PLAN_KIND) &&
2534
+ (state.operations.size +
2535
+ 1 +
2536
+ [...state.nativeRecoveryHolds.values()].reduce(
2537
+ (sum, amount) => sum + amount,
2538
+ 0,
2539
+ ) >
2540
+ 5000 ||
2541
+ head.sequence +
2542
+ 1 +
2543
+ [...state.nativeRecoveryHolds.values()].reduce(
2544
+ (sum, amount) => sum + amount,
2545
+ 0,
2546
+ ) >
2547
+ EVOLUTION_LEDGER_MAX_EVENTS)
2548
+ )
2549
+ rrsiFail(
2550
+ "history must retain native recovery capacity",
2551
+ "CC_RRSI_HISTORY_HOLD",
2552
+ );
2553
+ const record = rrsiEnvelope(RRSI_HISTORY_EVENT_SCHEMA, "recordDigest", {
2554
+ descriptor,
2555
+ ledgerId: head.ledgerId,
2556
+ epoch: head.epoch,
2557
+ operationId,
2558
+ kind,
2559
+ payload,
2560
+ previousRecordDigest: state.lastRecordDigest,
2561
+ acceptedAt,
2562
+ });
2563
+ if (kind.includes("native")) snapshotRrsiData(record);
2564
+ if (assertFreshness) assertFreshness();
2565
+ const published = EvolutionArtifactPorts.prototype.putCanonical.call(
2566
+ options.artifactPorts,
2567
+ ARTIFACT_TYPE,
2568
+ record,
2569
+ {
2570
+ audience: descriptor.audience,
2571
+ purpose: descriptor.purpose,
2572
+ retention: "ledger",
2573
+ },
2574
+ );
2575
+ if (
2576
+ published?.receipt?.persisted !== true ||
2577
+ published.receipt.readbackVerified !== true ||
2578
+ published.receipt.integrityVerified !== true ||
2579
+ published.receipt.retention !== "ledger"
2580
+ )
2581
+ rrsiFail("RRSI history artifact was not durably retained");
2582
+ if (kind.includes("native")) {
2583
+ const resolution = options.ledgerArtifactResolver({
2584
+ epoch: head.epoch,
2585
+ ledgerId: head.ledgerId,
2586
+ ref: copyRetainedRef(published.ref),
2587
+ tenantId: descriptor.artifactTenantId,
2588
+ });
2589
+ if (!resolution?.found || !Buffer.isBuffer(resolution.bytes))
2590
+ rrsiFail("native history wrapper cannot be read back");
2591
+ snapshotRrsiData(
2592
+ JSON.parse(
2593
+ new TextDecoder("utf-8", { fatal: true }).decode(resolution.bytes),
2594
+ ),
2595
+ );
2596
+ }
2597
+ if (
2598
+ kind === "reserve-native-batch" ||
2599
+ kind === NATIVE_STATISTICS_RESERVE_KIND
2600
+ )
2601
+ nativeBatchResolution(state, payload.batch.batchDigest, {
2602
+ recordDigest: record.recordDigest,
2603
+ ref: copyRetainedRef(published.ref),
2604
+ sequence: head.sequence + 1,
2605
+ });
2606
+ if (assertFreshness) assertFreshness();
2607
+ try {
2608
+ const receipt = methods.appendDomainEvent(
2609
+ {
2610
+ type: RRSI_HISTORY_EVENT_TYPE,
2611
+ eventId: operationEventId(operationId),
2612
+ tenantId: descriptor.tenantId,
2613
+ artifactTenantId: descriptor.artifactTenantId,
2614
+ correlationId: descriptor.scopeId,
2615
+ skillName: descriptor.goalId,
2616
+ decision: "accepted",
2617
+ reason:
2618
+ "RRSI durable control history; independent execution admission remains required",
2619
+ sourceRefs: nativeStatisticsSourceRefs(state, kind, payload) ?? [],
2620
+ subjectRef: published.ref,
2621
+ timestamp: acceptedAt,
2622
+ },
2623
+ {
2624
+ expectedHeadDigest: head.headDigest,
2625
+ expectedSequence: head.sequence,
2626
+ },
2627
+ );
2628
+ if (receipt?.authenticated !== true || receipt.durable !== true)
2629
+ rrsiFail("RRSI append returned an uncertain receipt");
2630
+ } catch (error) {
2631
+ if (error.code === "CC_EVOLUTION_LEDGER_HEAD_CONFLICT") {
2632
+ if (expectedHead)
2633
+ rrsiFail(
2634
+ "native quality census head changed during commit",
2635
+ "CC_RRSI_QUALITY_STALE",
2636
+ );
2637
+ continue;
2638
+ }
2639
+ // Could have committed. Readback can recover history, never replay execution.
2640
+ rrsiFail(
2641
+ "RRSI commit outcome requires readback",
2642
+ "CC_RRSI_COMMIT_UNKNOWN",
2643
+ );
2644
+ }
2645
+ const reread = load().state.operations.get(operationId);
2646
+ if (
2647
+ !reread ||
2648
+ rrsiCanonical(reread.record.payload) !== rrsiCanonical(payload)
2649
+ )
2650
+ rrsiFail(
2651
+ "RRSI committed operation could not be read back",
2652
+ "CC_RRSI_COMMIT_UNKNOWN",
2653
+ );
2654
+ return { result, newlyCommitted: true };
2655
+ }
2656
+ rrsiFail(
2657
+ "RRSI operation exceeded CAS retry bound",
2658
+ "CC_RRSI_HEAD_CONFLICT",
2659
+ );
2660
+ }
2661
+
2662
+ function commit(kind, operationId, input) {
2663
+ return withHistoryLock(() => commitUnlocked(kind, operationId, input));
2664
+ }
2665
+
2666
+ function reservationResponse(result) {
2667
+ const response = freezeRrsiData({
2668
+ reservation: result.result,
2669
+ newlyCommitted: result.newlyCommitted,
2670
+ historyAuthenticated: true,
2671
+ executionEvidenceVerified: false,
2672
+ readyForExecution: false,
2673
+ qualifiesForPromotion: false,
2674
+ });
2675
+ if (result.newlyCommitted) freshReservations.set(response, result.result);
2676
+ return response;
2677
+ }
2678
+ function nativeReservationResponse(result) {
2679
+ return freezeRrsiData({
2680
+ batchDigest: result.result.batchDigest,
2681
+ children: result.result.children.map((child) => {
2682
+ const value = freezeRrsiData({
2683
+ ...child,
2684
+ newlyCommitted: result.newlyCommitted,
2685
+ historyAuthenticated: true,
2686
+ readyForExecution: false,
2687
+ qualifiesForPromotion: false,
2688
+ });
2689
+ if (result.newlyCommitted)
2690
+ freshNativeChildren.set(value, child.bindings);
2691
+ return value;
2692
+ }),
2693
+ newlyCommitted: result.newlyCommitted,
2694
+ historyAuthenticated: true,
2695
+ readyForExecution: false,
2696
+ qualifiesForPromotion: false,
2697
+ });
2698
+ }
2699
+
2700
+ const adapter = Object.freeze({
2701
+ descriptor,
2702
+ resolveCampaignRoot() {
2703
+ return withHistoryLock(() => {
2704
+ const { state } = load();
2705
+ if (!state.root) rrsiFail("RRSI root campaign is not registered");
2706
+ const operation = [...state.operations.values()].find(
2707
+ (entry) =>
2708
+ entry.record.kind === "register" &&
2709
+ entry.record.payload.campaign.campaignDigest ===
2710
+ state.root.campaignDigest,
2711
+ );
2712
+ return freezeRrsiData({
2713
+ descriptor,
2714
+ identity: state.identity,
2715
+ campaign: state.root,
2716
+ registrationRecord: {
2717
+ recordDigest: operation.record.recordDigest,
2718
+ ref: operation.ref,
2719
+ sequence: operation.sequence,
2720
+ },
2721
+ historyAuthenticated: true,
2722
+ productionBudgetAuthorityVerified: false,
2723
+ });
2724
+ });
2725
+ },
2726
+ resolveNativeBatch(input) {
2727
+ const lookup = snapshotRrsiData(input);
2728
+ rrsiExact(lookup, ["batchDigest"], "native batch lookup");
2729
+ rrsiDigest(lookup.batchDigest, "native batch digest");
2730
+ return withHistoryLock(() => {
2731
+ const { state } = load();
2732
+ const batch = state.nativeBatches.get(lookup.batchDigest);
2733
+ if (!batch) rrsiFail("native batch is not registered");
2734
+ const operation = [...state.operations.values()].find(
2735
+ (entry) =>
2736
+ ["reserve-native-batch", NATIVE_STATISTICS_RESERVE_KIND].includes(
2737
+ entry.record.kind,
2738
+ ) && entry.record.payload.batch.batchDigest === batch.batchDigest,
2739
+ );
2740
+ return nativeBatchResolution(state, batch.batchDigest, {
2741
+ recordDigest: operation.record.recordDigest,
2742
+ ref: operation.ref,
2743
+ sequence: operation.sequence,
2744
+ });
2745
+ });
2746
+ },
2747
+ registerCampaign(campaign) {
2748
+ const normalized = verifyRrsiCampaign(campaign);
2749
+ const result = commit(
2750
+ "register",
2751
+ `register.${rrsiHash("rrsi-campaign-id/v1", normalized.campaignId).slice(7)}`,
2752
+ { campaign: normalized },
2753
+ );
2754
+ return freezeRrsiData({
2755
+ campaignDigest: normalized.campaignDigest,
2756
+ newlyCommitted: result.newlyCommitted,
2757
+ historyAuthenticated: true,
2758
+ controlBudgetCoverage: "selection-and-final-only",
2759
+ readyForExecution: false,
2760
+ qualifiesForPromotion: false,
2761
+ });
2762
+ },
2763
+ registerNativeStatisticsScope(input) {
2764
+ const value = ownOptions(input, ["execution"]);
2765
+ return withHistoryLock(() => {
2766
+ const { state } = load();
2767
+ if (!state.root) rrsiFail("RRSI root campaign is not registered");
2768
+ const execution = normalizeRrsiNativeStatisticsExecutionContract({
2769
+ campaign: state.root,
2770
+ execution: value.execution,
2771
+ });
2772
+ const payload = {
2773
+ execution,
2774
+ protocol: buildRrsiNativeStatisticsScopeProtocol({
2775
+ campaign: state.root,
2776
+ execution,
2777
+ }),
2778
+ binding: nativeStatisticsScopeBinding(state),
2779
+ };
2780
+ const committed = commitUnlocked(
2781
+ NATIVE_STATISTICS_SCOPE_KIND,
2782
+ NATIVE_STATISTICS_SCOPE_OPERATION,
2783
+ payload,
2784
+ );
2785
+ return freezeRrsiData({
2786
+ ...nativeStatisticsScopeResolution(load().state),
2787
+ newlyCommitted: committed.newlyCommitted,
2788
+ });
2789
+ });
2790
+ },
2791
+ resolveNativeStatisticsScope() {
2792
+ return withHistoryLock(() =>
2793
+ nativeStatisticsScopeResolution(load().state),
2794
+ );
2795
+ },
2796
+ registerNativeStatisticsPlan(input) {
2797
+ const batch = buildRrsiNativeEvaluationBatch(input);
2798
+ return withHistoryLock(() => {
2799
+ const { state } = load();
2800
+ const scope = nativeStatisticsScopeResolution(state);
2801
+ const campaign = campaignFor(state, batch.campaignDigest);
2802
+ const statisticsPlan = assertRrsiNativeStatisticsScopeBatch(
2803
+ scope.protocol,
2804
+ { campaign, batch },
2805
+ );
2806
+ const result = commitUnlocked(
2807
+ NATIVE_STATISTICS_PLAN_KIND,
2808
+ nativeStatisticsPlanOperation(batch.queryId),
2809
+ {
2810
+ batch,
2811
+ statisticsPlan,
2812
+ scopeRegistrationRecord: scope.registrationRecord,
2813
+ },
2814
+ );
2815
+ const operation = load().state.operations.get(
2816
+ nativeStatisticsPlanOperation(batch.queryId),
2817
+ );
2818
+ return freezeRrsiData({
2819
+ statisticsPlan: result.result,
2820
+ scopeRegistrationRecord: scope.registrationRecord,
2821
+ registrationRecord: historyRegistrationRecord(operation),
2822
+ newlyCommitted: result.newlyCommitted,
2823
+ historyAuthenticated: true,
2824
+ preObservationRegistrationVerified: true,
2825
+ statisticalProtocolValidated: false,
2826
+ readyForExecution: false,
2827
+ qualifiesForPromotion: false,
2828
+ });
2829
+ });
2830
+ },
2831
+ reserve(input) {
2832
+ const value = snapshotRrsiData(input);
2833
+ const result = commit(
2834
+ "reserve",
2835
+ `reserve.${rrsiHash("rrsi-execution-id/v1", value.executionId).slice(7)}`,
2836
+ value,
2837
+ );
2838
+ return reservationResponse(result);
2839
+ },
2840
+ reserveNativeBatch(input) {
2841
+ const batch = buildRrsiNativeEvaluationBatch(input);
2842
+ const result = commit(
2843
+ "reserve-native-batch",
2844
+ `reserve-native.${rrsiHash("chainlesschain.rrsi-native-query-operation/v1", batch.queryId).slice(7)}`,
2845
+ { batch },
2846
+ );
2847
+ return nativeReservationResponse(result);
2848
+ },
2849
+ reserveNativeBatchV2(input) {
2850
+ const batch = buildRrsiNativeEvaluationBatch(input);
2851
+ return withHistoryLock(() => {
2852
+ const { state } = load();
2853
+ const binding = nativeStatisticsReserveBinding(state, batch);
2854
+ return nativeReservationResponse(
2855
+ commitUnlocked(
2856
+ NATIVE_STATISTICS_RESERVE_KIND,
2857
+ `reserve-native.${rrsiHash("chainlesschain.rrsi-native-query-operation/v1", batch.queryId).slice(7)}`,
2858
+ { batch, ...binding },
2859
+ ),
2860
+ );
2861
+ });
2862
+ },
2863
+ recordNativeDispatch(response) {
2864
+ const bindings = freshNativeChildren.get(response);
2865
+ if (!bindings)
2866
+ rrsiFail(
2867
+ "native dispatch requires this process's fresh child reservation",
2868
+ "CC_RRSI_REPLAY_FORBIDDEN",
2869
+ );
2870
+ freshNativeChildren.delete(response);
2871
+ const result = commit(
2872
+ "dispatch-native",
2873
+ `dispatch-native.${rrsiHash("chainlesschain.rrsi-native-child-operation/v1", bindings.childId).slice(7)}`,
2874
+ { childId: bindings.childId, batchDigest: bindings.batchDigest },
2875
+ );
2876
+ return freezeRrsiData({
2877
+ newlyCommitted: result.newlyCommitted,
2878
+ historyAuthenticated: true,
2879
+ readyForExecution: false,
2880
+ qualifiesForPromotion: false,
2881
+ });
2882
+ },
2883
+ markNativeUnknown(input) {
2884
+ const value = snapshotRrsiData(input);
2885
+ return commit(
2886
+ "unknown-native",
2887
+ `unknown-native.${rrsiHash("chainlesschain.rrsi-native-child-operation/v1", value.childId).slice(7)}`,
2888
+ value,
2889
+ ).newlyCommitted;
2890
+ },
2891
+ registerPreparationPlan(input) {
2892
+ const result = commit(
2893
+ "register-preparation-plan",
2894
+ "register.preparation-plan",
2895
+ input,
2896
+ );
2897
+ return freezeRrsiData({
2898
+ plan: result.result,
2899
+ newlyCommitted: result.newlyCommitted,
2900
+ historyAuthenticated: true,
2901
+ mappingAuthenticated: false,
2902
+ readyForExecution: false,
2903
+ qualifiesForPromotion: false,
2904
+ });
2905
+ },
2906
+ reservePreparation(input) {
2907
+ const value = snapshotRrsiData(input);
2908
+ return reservationResponse(
2909
+ commit(
2910
+ "reserve-preparation",
2911
+ `reserve.${rrsiHash("rrsi-execution-id/v1", value.executionId).slice(7)}`,
2912
+ value,
2913
+ ),
2914
+ );
2915
+ },
2916
+ recordDispatch(response) {
2917
+ const reservation = freshReservations.get(response);
2918
+ if (!reservation)
2919
+ rrsiFail(
2920
+ "dispatch requires this process's fresh reservation",
2921
+ "CC_RRSI_REPLAY_FORBIDDEN",
2922
+ );
2923
+ freshReservations.delete(response);
2924
+ const payload = {
2925
+ executionId: reservation.bindings.executionId,
2926
+ reservationDigest: reservation.reservationDigest,
2927
+ };
2928
+ const result = commit(
2929
+ "dispatch",
2930
+ `dispatch.${rrsiHash("rrsi-execution-id/v1", payload.executionId).slice(7)}`,
2931
+ payload,
2932
+ );
2933
+ return freezeRrsiData({
2934
+ newlyCommitted: result.newlyCommitted,
2935
+ historyAuthenticated: true,
2936
+ executionEvidenceVerified: false,
2937
+ readyForExecution: false,
2938
+ qualifiesForPromotion: false,
2939
+ });
2940
+ },
2941
+ markUnknown(input) {
2942
+ const payload = snapshotRrsiData(input);
2943
+ return commit(
2944
+ "unknown",
2945
+ `unknown.${rrsiHash("rrsi-execution-id/v1", payload.executionId).slice(7)}`,
2946
+ payload,
2947
+ ).newlyCommitted;
2948
+ },
2949
+ recordPreparationObservation(input) {
2950
+ const payload = snapshotRrsiData(input);
2951
+ return commit(
2952
+ "observe-preparation",
2953
+ `observe.${rrsiHash("rrsi-execution-id/v1", payload.executionId).slice(7)}`,
2954
+ payload,
2955
+ ).newlyCommitted;
2956
+ },
2957
+ freezeCandidate(input) {
2958
+ const payload = snapshotRrsiData(input);
2959
+ return commit(
2960
+ "freeze",
2961
+ `freeze.${rrsiDigest(payload.campaignDigest, "campaign digest").slice(7)}`,
2962
+ payload,
2963
+ ).newlyCommitted;
2964
+ },
2965
+ async recordNativeQualityReceipt(input) {
2966
+ const { qualityReceipt } = ownOptions(input, ["qualityReceipt"]);
2967
+ const { captureRrsiNativeQualityReceipt } =
2968
+ await import("./rrsi-native-quality-receipt.js");
2969
+ const captured = captureRrsiNativeQualityReceipt(qualityReceipt);
2970
+ if (
2971
+ captured.historyLedger !== ledger ||
2972
+ rrsiCanonical(captured.historyDescriptor) !== rrsiCanonical(descriptor)
2973
+ )
2974
+ rrsiFail(
2975
+ "native quality receipt belongs to another genuine History journal",
2976
+ );
2977
+ const operationId = nativeQualityReceiptOperation(
2978
+ qualityReceipt.qualityReceiptDigest,
2979
+ );
2980
+ const recovered = withHistoryLock(() => {
2981
+ const { state } = load();
2982
+ const existing = state.operations.get(operationId);
2983
+ if (!existing) return null;
2984
+ if (
2985
+ existing.record.kind !== NATIVE_QUALITY_RECEIPT_KIND ||
2986
+ rrsiCanonical(existing.record.payload.qualityReceipt) !==
2987
+ captured.receiptBytes
2988
+ )
2989
+ rrsiFail(
2990
+ "native quality operation is bound to different data",
2991
+ "CC_RRSI_OPERATION_CONFLICT",
2992
+ );
2993
+ return freezeRrsiData({
2994
+ ...nativeQualityResolution(
2995
+ state,
2996
+ qualityReceipt.qualityReceiptDigest,
2997
+ ),
2998
+ newlyCommitted: false,
2999
+ });
3000
+ });
3001
+ // A successful append makes its old census head stale. Recovery may read
3002
+ // back this exact historical observation, never grant a new capability.
3003
+ if (recovered) return recovered;
3004
+ await captured.assertCurrentHistory(adapter);
3005
+ return withHistoryLock(() => {
3006
+ const { state, head } = load();
3007
+ if (!sameIdentity(head, captured.auditHead))
3008
+ rrsiFail(
3009
+ "native quality census head changed before recording",
3010
+ "CC_RRSI_QUALITY_STALE",
3011
+ );
3012
+ verifyRecordedRrsiNativeQualityReceipt(
3013
+ qualityReceipt,
3014
+ nativeQualityContext(
3015
+ state,
3016
+ captured.batch.batchDigest,
3017
+ auditHead(head),
3018
+ ),
3019
+ );
3020
+ captured.assertCurrentFreshness();
3021
+ const committed = commitUnlocked(
3022
+ NATIVE_QUALITY_RECEIPT_KIND,
3023
+ operationId,
3024
+ { qualityReceipt },
3025
+ captured.auditHead,
3026
+ captured.assertCurrentFreshness,
3027
+ );
3028
+ return freezeRrsiData({
3029
+ ...nativeQualityResolution(
3030
+ load().state,
3031
+ qualityReceipt.qualityReceiptDigest,
3032
+ ),
3033
+ newlyCommitted: committed.newlyCommitted,
3034
+ });
3035
+ });
3036
+ },
3037
+ resolveNativeQualityReceipt(input) {
3038
+ const lookup = snapshotRrsiData(input);
3039
+ rrsiExact(
3040
+ lookup,
3041
+ ["qualityReceiptDigest"],
3042
+ "native quality receipt lookup",
3043
+ );
3044
+ rrsiDigest(lookup.qualityReceiptDigest, "native quality receipt digest");
3045
+ return withHistoryLock(() =>
3046
+ nativeQualityResolution(load().state, lookup.qualityReceiptDigest),
3047
+ );
3048
+ },
3049
+ async freezeNativeCandidateV2(input) {
3050
+ const { qualityReceipt } = ownOptions(input, ["qualityReceipt"]);
3051
+ const { captureRrsiNativeQualityReceipt } =
3052
+ await import("./rrsi-native-quality-receipt.js");
3053
+ const captured = captureRrsiNativeQualityReceipt(qualityReceipt);
3054
+ if (
3055
+ captured.historyLedger !== ledger ||
3056
+ rrsiCanonical(captured.historyDescriptor) !== rrsiCanonical(descriptor)
3057
+ )
3058
+ rrsiFail(
3059
+ "native quality receipt belongs to another genuine History journal",
3060
+ );
3061
+ if (captured.batch.stage !== "selection")
3062
+ rrsiFail("candidate freeze requires a selection quality receipt");
3063
+ await captured.assertCurrentHistory(adapter);
3064
+ return withHistoryLock(() => {
3065
+ const { state, head } = load();
3066
+ if (!sameIdentity(head, captured.auditHead))
3067
+ rrsiFail(
3068
+ "native quality census head changed before freeze",
3069
+ "CC_RRSI_QUALITY_STALE",
3070
+ );
3071
+ verifyRecordedRrsiNativeQualityReceipt(
3072
+ qualityReceipt,
3073
+ nativeQualityContext(
3074
+ state,
3075
+ captured.batch.batchDigest,
3076
+ auditHead(head),
3077
+ ),
3078
+ );
3079
+ captured.assertCurrentFreshness();
3080
+ // v1 assessments cannot certify the still-unimplemented prerequisites.
3081
+ rrsiFail(
3082
+ "native required-quality receipt remains HOLD",
3083
+ "CC_RRSI_QUALITY_HOLD",
3084
+ );
3085
+ });
3086
+ },
3087
+ settle(input) {
3088
+ const evidence = snapshotRrsiData(input);
3089
+ const receiptId = rrsiId(
3090
+ evidence.core?.receiptId,
3091
+ "settlement receipt ID",
3092
+ );
3093
+ return commit(
3094
+ evidence.core.schema === RRSI_NATIVE_SETTLEMENT_SCHEMA
3095
+ ? "settle-native"
3096
+ : "settle",
3097
+ `settle.${rrsiHash("rrsi-settlement-id/v1", receiptId).slice(7)}`,
3098
+ { evidence },
3099
+ ).newlyCommitted;
3100
+ },
3101
+ inspect() {
3102
+ return withHistoryLock(() => {
3103
+ const { state, head } = load();
3104
+ const charged = charges(state);
3105
+ return rrsiEnvelope(RRSI_HISTORY_STATUS_SCHEMA, "statusDigest", {
3106
+ controlBudgetCoverage: state.preparationPlan
3107
+ ? "preparation-selection-and-final"
3108
+ : "selection-and-final-only",
3109
+ preparationPlan: state.preparationPlan,
3110
+ preparationAttempts: state.preparationAttempts,
3111
+ chargedResourcesByStage: Object.fromEntries(
3112
+ ["proposal", "selection", "final"].map((stage) => [
3113
+ stage,
3114
+ Object.fromEntries(
3115
+ Object.entries(charges(state, stage)).map(([key, value]) => [
3116
+ key,
3117
+ value.toString(),
3118
+ ]),
3119
+ ),
3120
+ ]),
3121
+ ),
3122
+ qualityVerdictVerified: false,
3123
+ descriptor,
3124
+ ledgerId: head.ledgerId,
3125
+ epoch: head.epoch,
3126
+ headDigest: head.headDigest,
3127
+ historyAuthenticated: true,
3128
+ candidateCount: state.candidates.size,
3129
+ campaignCount: state.campaigns.size,
3130
+ selectionQueries: state.selectionQueries,
3131
+ chargedResources: Object.fromEntries(
3132
+ Object.entries(charged).map(([key, value]) => [
3133
+ key,
3134
+ value.toString(),
3135
+ ]),
3136
+ ),
3137
+ budgetOverrun: state.overrun,
3138
+ ...(state.nativeBatches.size
3139
+ ? {
3140
+ nativeBatches: [...state.nativeBatches.values()].map(
3141
+ (batch) => ({
3142
+ batchDigest: batch.batchDigest,
3143
+ queryId: batch.queryId,
3144
+ stage: batch.stage,
3145
+ nativeEvaluationPlanDigest:
3146
+ batch.nativeEvaluationPlanDigest,
3147
+ childCount: batch.children.length,
3148
+ }),
3149
+ ),
3150
+ legacyCostAttribution: "conservatively-charged-to-every-arm/v1",
3151
+ nativeRecoveryEventHolds: [
3152
+ ...state.nativeRecoveryHolds.values(),
3153
+ ].reduce((sum, amount) => sum + amount, 0),
3154
+ chargedResourcesInterpretation:
3155
+ "componentwise-maximum-of-arm-charges/v1",
3156
+ chargedResourcesByArm: Object.fromEntries(
3157
+ ["baseline", "rsi", "rrsi"].map((arm) => [
3158
+ arm,
3159
+ Object.fromEntries(
3160
+ Object.entries(charges(state, null, arm)).map(
3161
+ ([name, amount]) => [name, amount.toString()],
3162
+ ),
3163
+ ),
3164
+ ]),
3165
+ ),
3166
+ chargedResourcesByStageByArm: Object.fromEntries(
3167
+ ["baseline", "rsi", "rrsi"].map((arm) => [
3168
+ arm,
3169
+ Object.fromEntries(
3170
+ ["proposal", "selection", "final"].map((stage) => [
3171
+ stage,
3172
+ Object.fromEntries(
3173
+ Object.entries(charges(state, stage, arm)).map(
3174
+ ([name, amount]) => [name, amount.toString()],
3175
+ ),
3176
+ ),
3177
+ ]),
3178
+ ),
3179
+ ]),
3180
+ ),
3181
+ requestCostGraphVerified: false,
3182
+ billingComplete: false,
3183
+ }
3184
+ : {}),
3185
+ executions: [...state.reservations.values()]
3186
+ .map((entry) => ({
3187
+ reservation: entry.reservation,
3188
+ status: entry.status,
3189
+ dispatched: entry.dispatched,
3190
+ knownUsage: entry.knownUsage,
3191
+ executionObservation: entry.observation ?? null,
3192
+ settlementSignatureVerified: entry.settlement !== null,
3193
+ executionEvidenceVerified:
3194
+ !isRrsiNativeReservation(entry.reservation) &&
3195
+ entry.status === "settled" &&
3196
+ entry.settlement.core.usage.executions > 0,
3197
+ costEvidenceVerified:
3198
+ !isRrsiNativeReservation(entry.reservation) &&
3199
+ entry.status === "settled",
3200
+ ...(isRrsiNativeReservation(entry.reservation)
3201
+ ? {
3202
+ knownExecutionUnits: entry.knownExecutionUnits,
3203
+ executionCountKnowledge: RRSI_NATIVE_EXECUTION_UNITS.every(
3204
+ (name) => entry.knownExecutionUnits[name] !== null,
3205
+ )
3206
+ ? "signed-category-total"
3207
+ : "known-category-lower-bound",
3208
+ budgetSettlementVerified: entry.status === "settled",
3209
+ nativeExecutionDenominatorVerified: false,
3210
+ }
3211
+ : {}),
3212
+ }))
3213
+ .sort((a, b) =>
3214
+ a.reservation.bindings.executionId <
3215
+ b.reservation.bindings.executionId
3216
+ ? -1
3217
+ : 1,
3218
+ ),
3219
+ });
3220
+ });
3221
+ },
3222
+ });
3223
+ // Validate existing roots immediately, including a changed settlement authority.
3224
+ withHistoryLock(load);
3225
+ ADAPTERS.set(
3226
+ adapter,
3227
+ Object.freeze({
3228
+ descriptor,
3229
+ ledger,
3230
+ artifactPorts: options.artifactPorts,
3231
+ ledgerArtifactResolver: options.ledgerArtifactResolver,
3232
+ resolveCampaignRoot: adapter.resolveCampaignRoot,
3233
+ resolveNativeBatch: adapter.resolveNativeBatch,
3234
+ resolveNativeStatisticsScope: adapter.resolveNativeStatisticsScope,
3235
+ assertNativeFreshChild(response, expectedBindings) {
3236
+ const bindings = freshNativeChildren.get(response);
3237
+ if (!bindings)
3238
+ rrsiFail(
3239
+ "native admission requires this process's fresh child capability",
3240
+ "CC_RRSI_REPLAY_FORBIDDEN",
3241
+ );
3242
+ if (
3243
+ rrsiCanonical(bindings) !==
3244
+ rrsiCanonical(snapshotRrsiData(expectedBindings))
3245
+ )
3246
+ rrsiFail("fresh native child differs from signed enrollment");
3247
+ return bindings;
3248
+ },
3249
+ inspect: adapter.inspect,
3250
+ reservePreparation: adapter.reservePreparation,
3251
+ reserveNativeBatch: adapter.reserveNativeBatch,
3252
+ reserveNativeBatchV2: adapter.reserveNativeBatchV2,
3253
+ recordNativeDispatch: adapter.recordNativeDispatch,
3254
+ markNativeUnknown: adapter.markNativeUnknown,
3255
+ recordDispatch: adapter.recordDispatch,
3256
+ markUnknown: adapter.markUnknown,
3257
+ recordPreparationObservation: adapter.recordPreparationObservation,
3258
+ }),
3259
+ );
3260
+ return adapter;
3261
+ }