@systemfsoftware/agent 0.0.0-bootstrap.0 → 0.1.0-beta.192

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 (717) hide show
  1. package/LICENSE +21 -0
  2. package/dist/ActivityStore-CEy3oY41.mjs +90 -0
  3. package/dist/ActivityStore-CEy3oY41.mjs.map +1 -0
  4. package/dist/ActivityStore-CPXWRHGz.d.mts +91 -0
  5. package/dist/Admin-BcQDrWKY.mjs +329 -0
  6. package/dist/Admin-BcQDrWKY.mjs.map +1 -0
  7. package/dist/Admin-BfolLkHj.d.mts +5678 -0
  8. package/dist/Agent-Bn3zMhDH.mjs +60 -0
  9. package/dist/Agent-Bn3zMhDH.mjs.map +1 -0
  10. package/dist/Agent-DSVEpq4e.d.mts +219 -0
  11. package/dist/AgentError-RkUaetX8.d.mts +128 -0
  12. package/dist/AgentError-yFdnS9bl.mjs +141 -0
  13. package/dist/AgentError-yFdnS9bl.mjs.map +1 -0
  14. package/dist/AgentPolicy-CI7LRBQa.mjs +116 -0
  15. package/dist/AgentPolicy-CI7LRBQa.mjs.map +1 -0
  16. package/dist/AgentPolicy-D-GmZQex.d.mts +128 -0
  17. package/dist/AgentRegistration-Dg53p6du.mjs +14 -0
  18. package/dist/AgentRegistration-Dg53p6du.mjs.map +1 -0
  19. package/dist/AgentRuntime-CoGy_5dm.d.mts +751 -0
  20. package/dist/AgentRuntime-CzP4I4RB.mjs +5249 -0
  21. package/dist/AgentRuntime-CzP4I4RB.mjs.map +1 -0
  22. package/dist/AgentUpdates-7xT0It_R.d.mts +54 -0
  23. package/dist/AgentUpdates-BS_6gR5K.mjs +66 -0
  24. package/dist/AgentUpdates-BS_6gR5K.mjs.map +1 -0
  25. package/dist/BrowserUse-C9vict2M.d.mts +196 -0
  26. package/dist/BrowserUse-DjEyFDLZ.mjs +156 -0
  27. package/dist/BrowserUse-DjEyFDLZ.mjs.map +1 -0
  28. package/dist/Budget-CXh_ChFJ.d.mts +112 -0
  29. package/dist/Budget-j1UkthgY.mjs +351 -0
  30. package/dist/Budget-j1UkthgY.mjs.map +1 -0
  31. package/dist/CodeExecutor-B_Vt1Ghy.mjs +281 -0
  32. package/dist/CodeExecutor-B_Vt1Ghy.mjs.map +1 -0
  33. package/dist/CodeExecutor-D5-Rda75.d.mts +198 -0
  34. package/dist/CodeMode-B7JvfKAD.d.mts +159 -0
  35. package/dist/CodeMode-BI7WhUkr.mjs +555 -0
  36. package/dist/CodeMode-BI7WhUkr.mjs.map +1 -0
  37. package/dist/CommittedActivity-DXyCKCtX.mjs +146 -0
  38. package/dist/CommittedActivity-DXyCKCtX.mjs.map +1 -0
  39. package/dist/CommittedActivity-LWOKXqdi.d.mts +62 -0
  40. package/dist/Compaction-C0hWAmOG.mjs +15 -0
  41. package/dist/Compaction-C0hWAmOG.mjs.map +1 -0
  42. package/dist/Compaction-e5cNeFmY.d.mts +5 -0
  43. package/dist/ContextCompactor-Chm9BLrD.d.mts +165 -0
  44. package/dist/ContextCompactor-DV4NOQvg.mjs +134 -0
  45. package/dist/ContextCompactor-DV4NOQvg.mjs.map +1 -0
  46. package/dist/ContextHistory-C80rW5M7.mjs +76 -0
  47. package/dist/ContextHistory-C80rW5M7.mjs.map +1 -0
  48. package/dist/ContextHistory-akQ1Td7a.d.mts +65 -0
  49. package/dist/ContextTools-917r7gpv.d.mts +186 -0
  50. package/dist/ContextTools-p8JDPo-W.mjs +88 -0
  51. package/dist/ContextTools-p8JDPo-W.mjs.map +1 -0
  52. package/dist/ContextWindow-BJZI4MMt.d.mts +61 -0
  53. package/dist/ContextWindow-kbFcs1IF.mjs +63 -0
  54. package/dist/ContextWindow-kbFcs1IF.mjs.map +1 -0
  55. package/dist/Digest-BDToAbaX.d.mts +25 -0
  56. package/dist/Digest-CU6IWj-2.mjs +106 -0
  57. package/dist/Digest-CU6IWj-2.mjs.map +1 -0
  58. package/dist/DurableAgentRuntime-BHXo8GPJ.mjs +8432 -0
  59. package/dist/DurableAgentRuntime-BHXo8GPJ.mjs.map +1 -0
  60. package/dist/DurableFailpoint-BD5nowNl.mjs +98 -0
  61. package/dist/DurableFailpoint-BD5nowNl.mjs.map +1 -0
  62. package/dist/DurableFailpoint-Cqi5tyof.d.mts +42 -0
  63. package/dist/DurableStep-CzVIho7y.mjs +54 -0
  64. package/dist/DurableStep-CzVIho7y.mjs.map +1 -0
  65. package/dist/DurableStep-cI_Ho_rU.d.mts +109 -0
  66. package/dist/EventSource-BwZVkEQi.mjs +66 -0
  67. package/dist/EventSource-BwZVkEQi.mjs.map +1 -0
  68. package/dist/EventSource-C0TCBeIf.d.mts +52 -0
  69. package/dist/FailureDiagnostic-DdHV2eFs.mjs +304 -0
  70. package/dist/FailureDiagnostic-DdHV2eFs.mjs.map +1 -0
  71. package/dist/FailureDiagnostic-DpzYNI8f.d.mts +232 -0
  72. package/dist/IdGenerator-BCzwV0ZI.mjs +29 -0
  73. package/dist/IdGenerator-BCzwV0ZI.mjs.map +1 -0
  74. package/dist/IdGenerator-BY8NH74o.d.mts +26 -0
  75. package/dist/Identifiers-LWd4837I.mjs +41 -0
  76. package/dist/Identifiers-LWd4837I.mjs.map +1 -0
  77. package/dist/Identifiers-qafW4EP0.d.mts +38 -0
  78. package/dist/InMemory-BrTm6XEO.mjs +57 -0
  79. package/dist/InMemory-BrTm6XEO.mjs.map +1 -0
  80. package/dist/InMemory-C3qXFT5k.d.mts +46 -0
  81. package/dist/InMemory.d.mts +2 -0
  82. package/dist/InMemory.mjs +1 -0
  83. package/dist/InteractiveBrowser-B-hlNJy5.mjs +237 -0
  84. package/dist/InteractiveBrowser-B-hlNJy5.mjs.map +1 -0
  85. package/dist/InteractiveBrowser-nnML0r7w.d.mts +258 -0
  86. package/dist/LifecyclePublication-BDc_ug5v.mjs +204 -0
  87. package/dist/LifecyclePublication-BDc_ug5v.mjs.map +1 -0
  88. package/dist/Memory-CT5bDZqi.d.mts +57 -0
  89. package/dist/Memory-Dl9ecPpm.mjs +204 -0
  90. package/dist/Memory-Dl9ecPpm.mjs.map +1 -0
  91. package/dist/MemoryNamespace-BtnlH_E6.d.mts +35 -0
  92. package/dist/MemoryNamespace-DZSpjLj9.mjs +116 -0
  93. package/dist/MemoryNamespace-DZSpjLj9.mjs.map +1 -0
  94. package/dist/MemoryNotes-4CRzkPBD.d.mts +425 -0
  95. package/dist/MemoryNotes-i41TsH11.mjs +132 -0
  96. package/dist/MemoryNotes-i41TsH11.mjs.map +1 -0
  97. package/dist/MemoryReference-Dd3KSMa7.d.mts +77 -0
  98. package/dist/MemoryReference-RFU0HQJG.mjs +108 -0
  99. package/dist/MemoryReference-RFU0HQJG.mjs.map +1 -0
  100. package/dist/MemoryRevalidation--aAh_Pfq.mjs +136 -0
  101. package/dist/MemoryRevalidation--aAh_Pfq.mjs.map +1 -0
  102. package/dist/MemoryRevalidation-FsJ8E61W.d.mts +64 -0
  103. package/dist/MemoryStore-Bg5RunTk.d.mts +187 -0
  104. package/dist/MemoryStore-E0J99hb2.mjs +245 -0
  105. package/dist/MemoryStore-E0J99hb2.mjs.map +1 -0
  106. package/dist/MessageDelivery-BE2Yf3FC.mjs +615 -0
  107. package/dist/MessageDelivery-BE2Yf3FC.mjs.map +1 -0
  108. package/dist/MessageDelivery-Dh6GZBt_.d.mts +1129 -0
  109. package/dist/Messaging-BqWHYf93.d.mts +216 -0
  110. package/dist/Messaging-DgSiv4f4.mjs +154 -0
  111. package/dist/Messaging-DgSiv4f4.mjs.map +1 -0
  112. package/dist/Messaging-DhM-APnP.d.mts +1074 -0
  113. package/dist/MessagingHost-Bm5e-kAX.mjs +117 -0
  114. package/dist/MessagingHost-Bm5e-kAX.mjs.map +1 -0
  115. package/dist/MessagingHost-CubWeYKN.d.mts +80 -0
  116. package/dist/OperationAuthorizer-VSiHCC2S.mjs +72 -0
  117. package/dist/OperationAuthorizer-VSiHCC2S.mjs.map +1 -0
  118. package/dist/OperationAuthorizer-y-F-Ox_Q.d.mts +62 -0
  119. package/dist/Output-DQ8mWcgf.mjs +7 -0
  120. package/dist/Output-DQ8mWcgf.mjs.map +1 -0
  121. package/dist/Output-SbOdlBFL.d.mts +22 -0
  122. package/dist/PageCapture-BfRURUOA.mjs +275 -0
  123. package/dist/PageCapture-BfRURUOA.mjs.map +1 -0
  124. package/dist/PageCapture-C_mE72Sd.d.mts +216 -0
  125. package/dist/PageScreenshot-BJTASs4o.mjs +53 -0
  126. package/dist/PageScreenshot-BJTASs4o.mjs.map +1 -0
  127. package/dist/PageScreenshot-CaoaH7mc.d.mts +48 -0
  128. package/dist/PersistentHistory-BrtZ0g2j.d.mts +14 -0
  129. package/dist/PersistentHistory-CTAVhHKH.mjs +147 -0
  130. package/dist/PersistentHistory-CTAVhHKH.mjs.map +1 -0
  131. package/dist/PreparedInputAdmission-Ci18uY4s.d.mts +973 -0
  132. package/dist/PreparedInputAdmission-adqVJJa6.mjs +95 -0
  133. package/dist/PreparedInputAdmission-adqVJJa6.mjs.map +1 -0
  134. package/dist/ProvisionalText-BcKpPYKQ.d.mts +70 -0
  135. package/dist/ProvisionalText-DXddTK4c.mjs +47 -0
  136. package/dist/ProvisionalText-DXddTK4c.mjs.map +1 -0
  137. package/dist/Receipt-B-FlCaNH.mjs +35 -0
  138. package/dist/Receipt-B-FlCaNH.mjs.map +1 -0
  139. package/dist/Receipt-B4feBxMY.d.mts +31 -0
  140. package/dist/RecordFormat-DoNh-AFe.mjs +79 -0
  141. package/dist/RecordFormat-DoNh-AFe.mjs.map +1 -0
  142. package/dist/RecordFormat-ZMus8Dx8.d.mts +52 -0
  143. package/dist/Records-C645aQks.mjs +1145 -0
  144. package/dist/Records-C645aQks.mjs.map +1 -0
  145. package/dist/Records-C9I1nCL9.d.mts +1423 -0
  146. package/dist/Recovery-zWy_kmZq.mjs +736 -0
  147. package/dist/Recovery-zWy_kmZq.mjs.map +1 -0
  148. package/dist/Redaction-C0zLBAn6.d.mts +28 -0
  149. package/dist/Redaction-CtyCBMEj.mjs +116 -0
  150. package/dist/Redaction-CtyCBMEj.mjs.map +1 -0
  151. package/dist/RememberingStore-BO-OnCgP.mjs +23 -0
  152. package/dist/RememberingStore-BO-OnCgP.mjs.map +1 -0
  153. package/dist/RememberingStore-DgqXmILx.d.mts +14 -0
  154. package/dist/RunContinuation-BVAHoYlN.d.mts +127 -0
  155. package/dist/RunContinuation-Bpfp087i.mjs +1060 -0
  156. package/dist/RunContinuation-Bpfp087i.mjs.map +1 -0
  157. package/dist/RunEvent-CwgDzXcH.d.mts +465 -0
  158. package/dist/RunEvent-DJxENnJi.mjs +345 -0
  159. package/dist/RunEvent-DJxENnJi.mjs.map +1 -0
  160. package/dist/RunEventSink-B8uM8bw2.mjs +22 -0
  161. package/dist/RunEventSink-B8uM8bw2.mjs.map +1 -0
  162. package/dist/RunEventSink-f-T4jbNB.d.mts +105 -0
  163. package/dist/RunHooks-Bob22Bcj.d.mts +40 -0
  164. package/dist/RunHooks-DWuLBVdU.mjs +60 -0
  165. package/dist/RunHooks-DWuLBVdU.mjs.map +1 -0
  166. package/dist/RunJournal-C_1eqQdr.mjs +1107 -0
  167. package/dist/RunJournal-C_1eqQdr.mjs.map +1 -0
  168. package/dist/RunOptions-BVSa3BO2.d.mts +560 -0
  169. package/dist/RunOptions-COEUCrx4.mjs +61 -0
  170. package/dist/RunOptions-COEUCrx4.mjs.map +1 -0
  171. package/dist/RunPolicyUsage-B-JXRZYO.mjs +25 -0
  172. package/dist/RunPolicyUsage-B-JXRZYO.mjs.map +1 -0
  173. package/dist/RunPolicyUsage-jvJo0vJp.d.mts +21 -0
  174. package/dist/RunStorage-CsQQ0Y5u.mjs +304 -0
  175. package/dist/RunStorage-CsQQ0Y5u.mjs.map +1 -0
  176. package/dist/Sandbox-37vXP0BV.d.mts +24 -0
  177. package/dist/Sandbox-Bze6pHYc.mjs +30 -0
  178. package/dist/Sandbox-Bze6pHYc.mjs.map +1 -0
  179. package/dist/Schedule-BY0lzbij.mjs +336 -0
  180. package/dist/Schedule-BY0lzbij.mjs.map +1 -0
  181. package/dist/ScheduleTransition-CjVP48I8.d.mts +22 -0
  182. package/dist/ScheduleTransition-DtNzlN9k.mjs +180 -0
  183. package/dist/ScheduleTransition-DtNzlN9k.mjs.map +1 -0
  184. package/dist/Scheduling-BpJN9E1j.mjs +699 -0
  185. package/dist/Scheduling-BpJN9E1j.mjs.map +1 -0
  186. package/dist/Scheduling-DYTM29s9.d.mts +57 -0
  187. package/dist/SemanticMemory-BRV0cuWg.mjs +300 -0
  188. package/dist/SemanticMemory-BRV0cuWg.mjs.map +1 -0
  189. package/dist/SemanticMemory-rgWlhW87.d.mts +431 -0
  190. package/dist/SemanticMemoryIndex-D7yNEWpt.d.mts +826 -0
  191. package/dist/SemanticMemoryIndex-godQDjNx.mjs +186 -0
  192. package/dist/SemanticMemoryIndex-godQDjNx.mjs.map +1 -0
  193. package/dist/SemanticMemoryRevalidation-Bm3_pfsI.d.mts +44 -0
  194. package/dist/SemanticMemoryRevalidation-D8VV-eU6.mjs +179 -0
  195. package/dist/SemanticMemoryRevalidation-D8VV-eU6.mjs.map +1 -0
  196. package/dist/Subagent-CSIRUgUo.mjs +1315 -0
  197. package/dist/Subagent-CSIRUgUo.mjs.map +1 -0
  198. package/dist/Subagent-CXEI5YZ8.d.mts +2368 -0
  199. package/dist/SubagentContract-B7vQPueI.d.mts +176 -0
  200. package/dist/SubagentContract-C-7AxTm_.mjs +187 -0
  201. package/dist/SubagentContract-C-7AxTm_.mjs.map +1 -0
  202. package/dist/SubagentHost-BEnICu7g.mjs +70 -0
  203. package/dist/SubagentHost-BEnICu7g.mjs.map +1 -0
  204. package/dist/SubagentHost-CKhz1vbH.d.mts +167 -0
  205. package/dist/SubagentReservations-BYNAHPpm.mjs +465 -0
  206. package/dist/SubagentReservations-BYNAHPpm.mjs.map +1 -0
  207. package/dist/SubagentReservations-WrmIVzO5.d.mts +185 -0
  208. package/dist/SubmissionLedger-WG0beEyt.mjs +921 -0
  209. package/dist/SubmissionLedger-WG0beEyt.mjs.map +1 -0
  210. package/dist/SubmissionStatus-CPZsOM5a.mjs +17 -0
  211. package/dist/SubmissionStatus-CPZsOM5a.mjs.map +1 -0
  212. package/dist/Subscription-BhQbmUD-.mjs +340 -0
  213. package/dist/Subscription-BhQbmUD-.mjs.map +1 -0
  214. package/dist/Subscription-CC--_OnU.d.mts +815 -0
  215. package/dist/SubscriptionInput-BEeB0Cj8.d.mts +42 -0
  216. package/dist/SubscriptionInput-Xcd4JjEs.mjs +53 -0
  217. package/dist/SubscriptionInput-Xcd4JjEs.mjs.map +1 -0
  218. package/dist/SubscriptionTransition-CWt9UVH0.d.mts +23 -0
  219. package/dist/SubscriptionTransition-lrf733c8.mjs +154 -0
  220. package/dist/SubscriptionTransition-lrf733c8.mjs.map +1 -0
  221. package/dist/Subscriptions-4K_qu_2f.mjs +638 -0
  222. package/dist/Subscriptions-4K_qu_2f.mjs.map +1 -0
  223. package/dist/Subscriptions-BF3aSf8X.d.mts +75 -0
  224. package/dist/Thread-B8JApGHa.mjs +283 -0
  225. package/dist/Thread-B8JApGHa.mjs.map +1 -0
  226. package/dist/Thread-BnAtkJl4.d.mts +116 -0
  227. package/dist/ThreadArchiveRange-1PMdjpdJ.mjs +64 -0
  228. package/dist/ThreadArchiveRange-1PMdjpdJ.mjs.map +1 -0
  229. package/dist/ThreadContextHistory-BSStMOLX.mjs +211 -0
  230. package/dist/ThreadContextHistory-BSStMOLX.mjs.map +1 -0
  231. package/dist/ThreadContextHistory-lTZ8Ftq1.d.mts +33 -0
  232. package/dist/ThreadContextHistoryProjection-Cp7_RR6V.d.mts +59 -0
  233. package/dist/ThreadContextHistoryProjection-_8uNz-h1.mjs +149 -0
  234. package/dist/ThreadContextHistoryProjection-_8uNz-h1.mjs.map +1 -0
  235. package/dist/ThreadHistory-BkyGfv5E.d.mts +76 -0
  236. package/dist/ThreadHistory-Blt_W31N.mjs +69 -0
  237. package/dist/ThreadHistory-Blt_W31N.mjs.map +1 -0
  238. package/dist/ThreadImport-C8Tqiezd.mjs +491 -0
  239. package/dist/ThreadImport-C8Tqiezd.mjs.map +1 -0
  240. package/dist/ThreadImport-DaSmrlRi.d.mts +843 -0
  241. package/dist/ThreadInvariants-DyPhMeo-.d.mts +23 -0
  242. package/dist/ThreadInvariants-fniroLRY.mjs +154 -0
  243. package/dist/ThreadInvariants-fniroLRY.mjs.map +1 -0
  244. package/dist/ThreadProjectionMaintenance-D6fBjr1q.mjs +37 -0
  245. package/dist/ThreadProjectionMaintenance-D6fBjr1q.mjs.map +1 -0
  246. package/dist/ThreadProjectionMaintenance-DjUy7kCa.d.mts +51 -0
  247. package/dist/ThreadStore-BMUAp5Ta.mjs +937 -0
  248. package/dist/ThreadStore-BMUAp5Ta.mjs.map +1 -0
  249. package/dist/ThreadTransfer-B3NkyO_y.mjs +154 -0
  250. package/dist/ThreadTransfer-B3NkyO_y.mjs.map +1 -0
  251. package/dist/ThreadTransfer-BM02cbOo.d.mts +63 -0
  252. package/dist/ThreadWork-C-xa2Boi.mjs +484 -0
  253. package/dist/ThreadWork-C-xa2Boi.mjs.map +1 -0
  254. package/dist/ToolBroker-DkoVyx6T.mjs +42 -0
  255. package/dist/ToolBroker-DkoVyx6T.mjs.map +1 -0
  256. package/dist/ToolBroker-Dy2xM6ht.d.mts +134 -0
  257. package/dist/ToolDiscovery-DHySvLQd.mjs +211 -0
  258. package/dist/ToolDiscovery-DHySvLQd.mjs.map +1 -0
  259. package/dist/ToolDiscovery-VjamzX3q.d.mts +119 -0
  260. package/dist/ToolExposure-Cn7xETn5.d.mts +6 -0
  261. package/dist/ToolExposure-D7id9Gt5.d.mts +37 -0
  262. package/dist/ToolExposure-DCvQWFIa.mjs +9 -0
  263. package/dist/ToolExposure-DCvQWFIa.mjs.map +1 -0
  264. package/dist/ToolExposure-DNME8BkG.d.mts +44 -0
  265. package/dist/ToolExposure-DPnq8Won.mjs +30 -0
  266. package/dist/ToolExposure-DPnq8Won.mjs.map +1 -0
  267. package/dist/ToolExposure-DaGaF5tj.mjs +20 -0
  268. package/dist/ToolExposure-DaGaF5tj.mjs.map +1 -0
  269. package/dist/ToolExposure.d.mts +4 -0
  270. package/dist/ToolExposure.mjs +4 -0
  271. package/dist/ToolReconciler-6bb7xlip.d.mts +81 -0
  272. package/dist/ToolReconciler-DJQd3SZA.mjs +87 -0
  273. package/dist/ToolReconciler-DJQd3SZA.mjs.map +1 -0
  274. package/dist/ToolResult-By5KAje4.d.mts +79 -0
  275. package/dist/ToolResult-DwZxjlHw.mjs +160 -0
  276. package/dist/ToolResult-DwZxjlHw.mjs.map +1 -0
  277. package/dist/ToolResultStorage-BmoRewhh.mjs +46 -0
  278. package/dist/ToolResultStorage-BmoRewhh.mjs.map +1 -0
  279. package/dist/ToolResultStorage-Bp5fm0do.d.mts +49 -0
  280. package/dist/ToolResults-C4-HsMCp.d.mts +33 -0
  281. package/dist/ToolResults-nCgBlTp2.mjs +45 -0
  282. package/dist/ToolResults-nCgBlTp2.mjs.map +1 -0
  283. package/dist/Usage-B0xgME5f.mjs +340 -0
  284. package/dist/Usage-B0xgME5f.mjs.map +1 -0
  285. package/dist/Usage-Bc-jXe_9.d.mts +128 -0
  286. package/dist/WakeScheduler-DVYj66C-.mjs +74 -0
  287. package/dist/WakeScheduler-DVYj66C-.mjs.map +1 -0
  288. package/dist/WakeScheduler-SFqj67Sk.d.mts +74 -0
  289. package/dist/WebCapture-CA4ZarW2.mjs +64 -0
  290. package/dist/WebCapture-CA4ZarW2.mjs.map +1 -0
  291. package/dist/WebCapture-pzIeUJ5W.d.mts +49 -0
  292. package/dist/WebSearch-CD0V--qh.d.mts +18 -0
  293. package/dist/WebSearch-DnbOzRL_.mjs +30 -0
  294. package/dist/WebSearch-DnbOzRL_.mjs.map +1 -0
  295. package/dist/Worker-CQu8Qp1j.mjs +267 -0
  296. package/dist/Worker-CQu8Qp1j.mjs.map +1 -0
  297. package/dist/Worker-xxucY_0b.d.mts +468 -0
  298. package/dist/WorkerAdmission-BhFjx86s.mjs +162 -0
  299. package/dist/WorkerAdmission-BhFjx86s.mjs.map +1 -0
  300. package/dist/WorkerAdmission-BnRuXLWF.d.mts +171 -0
  301. package/dist/WorkerHost-DtYzi54D.d.mts +150 -0
  302. package/dist/WorkerHost-DuQug9Bq.mjs +73 -0
  303. package/dist/WorkerHost-DuQug9Bq.mjs.map +1 -0
  304. package/dist/agent-registration-CNs2twrr.mjs +262 -0
  305. package/dist/agent-registration-CNs2twrr.mjs.map +1 -0
  306. package/dist/capabilities/BrowserUse.d.mts +2 -0
  307. package/dist/capabilities/BrowserUse.mjs +1 -0
  308. package/dist/capabilities/Budget.d.mts +2 -0
  309. package/dist/capabilities/Budget.mjs +1 -0
  310. package/dist/capabilities/CodeMode.d.mts +2 -0
  311. package/dist/capabilities/CodeMode.mjs +1 -0
  312. package/dist/capabilities/ContextTools.d.mts +2 -0
  313. package/dist/capabilities/ContextTools.mjs +1 -0
  314. package/dist/capabilities/MemoryNotes.d.mts +2 -0
  315. package/dist/capabilities/MemoryNotes.mjs +1 -0
  316. package/dist/capabilities/Messaging.d.mts +3 -0
  317. package/dist/capabilities/Messaging.mjs +4 -0
  318. package/dist/capabilities/Redaction.d.mts +2 -0
  319. package/dist/capabilities/Redaction.mjs +1 -0
  320. package/dist/capabilities/RunHooks.d.mts +2 -0
  321. package/dist/capabilities/RunHooks.mjs +1 -0
  322. package/dist/capabilities/SemanticMemory.d.mts +2 -0
  323. package/dist/capabilities/SemanticMemory.mjs +1 -0
  324. package/dist/capabilities/Subagent.d.mts +4 -0
  325. package/dist/capabilities/Subagent.mjs +6 -0
  326. package/dist/capabilities/SubagentReservations.d.mts +2 -0
  327. package/dist/capabilities/SubagentReservations.mjs +1 -0
  328. package/dist/capabilities/ToolDiscovery.d.mts +2 -0
  329. package/dist/capabilities/ToolDiscovery.mjs +1 -0
  330. package/dist/capabilities/ToolResults.d.mts +2 -0
  331. package/dist/capabilities/ToolResults.mjs +1 -0
  332. package/dist/capabilities/WebCapture.d.mts +2 -0
  333. package/dist/capabilities/WebCapture.mjs +1 -0
  334. package/dist/capabilities/WebSearch.d.mts +2 -0
  335. package/dist/capabilities/WebSearch.mjs +1 -0
  336. package/dist/compaction-C3hXuO4Z.mjs +539 -0
  337. package/dist/compaction-C3hXuO4Z.mjs.map +1 -0
  338. package/dist/completion-B_WDnSg-.d.mts +11 -0
  339. package/dist/core/Agent.d.mts +2 -0
  340. package/dist/core/Agent.mjs +1 -0
  341. package/dist/core/AgentError.d.mts +2 -0
  342. package/dist/core/AgentError.mjs +1 -0
  343. package/dist/core/AgentPolicy.d.mts +2 -0
  344. package/dist/core/AgentPolicy.mjs +1 -0
  345. package/dist/core/AgentUpdates.d.mts +2 -0
  346. package/dist/core/AgentUpdates.mjs +1 -0
  347. package/dist/core/FailureDiagnostic.d.mts +2 -0
  348. package/dist/core/FailureDiagnostic.mjs +1 -0
  349. package/dist/core/IdGenerator.d.mts +2 -0
  350. package/dist/core/IdGenerator.mjs +1 -0
  351. package/dist/core/Identifiers.d.mts +2 -0
  352. package/dist/core/Identifiers.mjs +1 -0
  353. package/dist/core/Memory.d.mts +2 -0
  354. package/dist/core/Memory.mjs +1 -0
  355. package/dist/core/MemoryNamespace.d.mts +2 -0
  356. package/dist/core/MemoryNamespace.mjs +1 -0
  357. package/dist/core/MemoryReference.d.mts +2 -0
  358. package/dist/core/MemoryReference.mjs +1 -0
  359. package/dist/core/MemoryRevalidation.d.mts +2 -0
  360. package/dist/core/MemoryRevalidation.mjs +1 -0
  361. package/dist/core/MemoryStore.d.mts +2 -0
  362. package/dist/core/MemoryStore.mjs +1 -0
  363. package/dist/core/ProvisionalText.d.mts +2 -0
  364. package/dist/core/ProvisionalText.mjs +1 -0
  365. package/dist/core/Receipt.d.mts +2 -0
  366. package/dist/core/Receipt.mjs +1 -0
  367. package/dist/core/RememberingStore.d.mts +2 -0
  368. package/dist/core/RememberingStore.mjs +1 -0
  369. package/dist/core/RunEvent.d.mts +3 -0
  370. package/dist/core/RunEvent.mjs +1 -0
  371. package/dist/core/RunPolicyUsage.d.mts +2 -0
  372. package/dist/core/RunPolicyUsage.mjs +1 -0
  373. package/dist/core/SemanticMemoryIndex.d.mts +2 -0
  374. package/dist/core/SemanticMemoryIndex.mjs +1 -0
  375. package/dist/core/SemanticMemoryRevalidation.d.mts +2 -0
  376. package/dist/core/SemanticMemoryRevalidation.mjs +1 -0
  377. package/dist/core/SubagentContract.d.mts +2 -0
  378. package/dist/core/SubagentContract.mjs +1 -0
  379. package/dist/core/Thread.d.mts +2 -0
  380. package/dist/core/Thread.mjs +1 -0
  381. package/dist/core/ToolResult.d.mts +2 -0
  382. package/dist/core/ToolResult.mjs +1 -0
  383. package/dist/core/ToolResultStorage.d.mts +2 -0
  384. package/dist/core/ToolResultStorage.mjs +1 -0
  385. package/dist/core/Usage.d.mts +2 -0
  386. package/dist/core/Usage.mjs +1 -0
  387. package/dist/core/Worker.d.mts +3 -0
  388. package/dist/core/Worker.mjs +3 -0
  389. package/dist/durable/ActivityStore.d.mts +2 -0
  390. package/dist/durable/ActivityStore.mjs +1 -0
  391. package/dist/durable/Admin.d.mts +2 -0
  392. package/dist/durable/Admin.mjs +1 -0
  393. package/dist/durable/AgentRegistration.d.mts +3 -0
  394. package/dist/durable/AgentRegistration.mjs +2 -0
  395. package/dist/durable/CommittedActivity.d.mts +2 -0
  396. package/dist/durable/CommittedActivity.mjs +1 -0
  397. package/dist/durable/Digest.d.mts +2 -0
  398. package/dist/durable/Digest.mjs +3 -0
  399. package/dist/durable/DurableAgentRuntime.d.mts +3 -0
  400. package/dist/durable/DurableAgentRuntime.mjs +4 -0
  401. package/dist/durable/DurableFailpoint.d.mts +2 -0
  402. package/dist/durable/DurableFailpoint.mjs +1 -0
  403. package/dist/durable/DurableFailpointTestControl.d.mts +14 -0
  404. package/dist/durable/DurableFailpointTestControl.mjs +21 -0
  405. package/dist/durable/DurableFailpointTestControl.mjs.map +1 -0
  406. package/dist/durable/EventSource.d.mts +2 -0
  407. package/dist/durable/EventSource.mjs +1 -0
  408. package/dist/durable/LifecyclePublication.d.mts +2 -0
  409. package/dist/durable/LifecyclePublication.mjs +1 -0
  410. package/dist/durable/MessageDelivery.d.mts +2 -0
  411. package/dist/durable/MessageDelivery.mjs +1 -0
  412. package/dist/durable/MessageDeliveryStoreConformance.d.mts +401 -0
  413. package/dist/durable/MessageDeliveryStoreConformance.mjs +273 -0
  414. package/dist/durable/MessageDeliveryStoreConformance.mjs.map +1 -0
  415. package/dist/durable/OperationAuthorizer.d.mts +2 -0
  416. package/dist/durable/OperationAuthorizer.mjs +1 -0
  417. package/dist/durable/PersistentHistory.d.mts +2 -0
  418. package/dist/durable/PersistentHistory.mjs +1 -0
  419. package/dist/durable/PreparedInputAdmission.d.mts +2 -0
  420. package/dist/durable/PreparedInputAdmission.mjs +1 -0
  421. package/dist/durable/RecordFormat.d.mts +2 -0
  422. package/dist/durable/RecordFormat.mjs +1 -0
  423. package/dist/durable/Records.d.mts +2 -0
  424. package/dist/durable/Records.mjs +1 -0
  425. package/dist/durable/Recovery.d.mts +2 -0
  426. package/dist/durable/Recovery.mjs +1 -0
  427. package/dist/durable/RunContinuation.d.mts +4 -0
  428. package/dist/durable/RunContinuation.mjs +4 -0
  429. package/dist/durable/RunJournal.d.mts +2 -0
  430. package/dist/durable/RunJournal.mjs +1 -0
  431. package/dist/durable/RunStorage.d.mts +2 -0
  432. package/dist/durable/RunStorage.mjs +1 -0
  433. package/dist/durable/Schedule.d.mts +2 -0
  434. package/dist/durable/Schedule.mjs +1 -0
  435. package/dist/durable/ScheduleStoreConformance.d.mts +16 -0
  436. package/dist/durable/ScheduleStoreConformance.mjs +421 -0
  437. package/dist/durable/ScheduleStoreConformance.mjs.map +1 -0
  438. package/dist/durable/ScheduleTransition.d.mts +2 -0
  439. package/dist/durable/ScheduleTransition.mjs +1 -0
  440. package/dist/durable/Scheduling.d.mts +2 -0
  441. package/dist/durable/Scheduling.mjs +1 -0
  442. package/dist/durable/SettlementPublisher.d.mts +2 -0
  443. package/dist/durable/SettlementPublisher.mjs +99 -0
  444. package/dist/durable/SettlementPublisher.mjs.map +1 -0
  445. package/dist/durable/SqlMemoryStore.d.mts +729 -0
  446. package/dist/durable/SqlMemoryStore.mjs +626 -0
  447. package/dist/durable/SqlMemoryStore.mjs.map +1 -0
  448. package/dist/durable/SqlStorageOwner.d.mts +18 -0
  449. package/dist/durable/SqlStorageOwner.mjs +6 -0
  450. package/dist/durable/SqlStorageOwner.mjs.map +1 -0
  451. package/dist/durable/SubmissionLedger.d.mts +3 -0
  452. package/dist/durable/SubmissionLedger.mjs +3 -0
  453. package/dist/durable/SubmissionLedgerConformance.d.mts +31 -0
  454. package/dist/durable/SubmissionLedgerConformance.mjs +2090 -0
  455. package/dist/durable/SubmissionLedgerConformance.mjs.map +1 -0
  456. package/dist/durable/SubmissionStatus.d.mts +2 -0
  457. package/dist/durable/SubmissionStatus.mjs +1 -0
  458. package/dist/durable/Subscription.d.mts +2 -0
  459. package/dist/durable/Subscription.mjs +1 -0
  460. package/dist/durable/SubscriptionInput.d.mts +2 -0
  461. package/dist/durable/SubscriptionInput.mjs +1 -0
  462. package/dist/durable/SubscriptionStoreConformance.d.mts +15 -0
  463. package/dist/durable/SubscriptionStoreConformance.mjs +816 -0
  464. package/dist/durable/SubscriptionStoreConformance.mjs.map +1 -0
  465. package/dist/durable/SubscriptionTransition.d.mts +2 -0
  466. package/dist/durable/SubscriptionTransition.mjs +1 -0
  467. package/dist/durable/Subscriptions.d.mts +2 -0
  468. package/dist/durable/Subscriptions.mjs +1 -0
  469. package/dist/durable/ThreadArchiveRange.d.mts +2 -0
  470. package/dist/durable/ThreadArchiveRange.mjs +1 -0
  471. package/dist/durable/ThreadContextHistory.d.mts +2 -0
  472. package/dist/durable/ThreadContextHistory.mjs +1 -0
  473. package/dist/durable/ThreadContextHistoryProjection.d.mts +2 -0
  474. package/dist/durable/ThreadContextHistoryProjection.mjs +1 -0
  475. package/dist/durable/ThreadImport.d.mts +2 -0
  476. package/dist/durable/ThreadImport.mjs +1 -0
  477. package/dist/durable/ThreadInvariants.d.mts +2 -0
  478. package/dist/durable/ThreadInvariants.mjs +1 -0
  479. package/dist/durable/ThreadProjectionMaintenance.d.mts +2 -0
  480. package/dist/durable/ThreadProjectionMaintenance.mjs +1 -0
  481. package/dist/durable/ThreadReader.d.mts +2 -0
  482. package/dist/durable/ThreadReader.mjs +1 -0
  483. package/dist/durable/ThreadStore.d.mts +3 -0
  484. package/dist/durable/ThreadStore.mjs +3 -0
  485. package/dist/durable/ThreadStoreConformance.d.mts +53 -0
  486. package/dist/durable/ThreadStoreConformance.mjs +402 -0
  487. package/dist/durable/ThreadStoreConformance.mjs.map +1 -0
  488. package/dist/durable/ThreadTransfer.d.mts +2 -0
  489. package/dist/durable/ThreadTransfer.mjs +1 -0
  490. package/dist/durable/ThreadWork.d.mts +2 -0
  491. package/dist/durable/ThreadWork.mjs +1 -0
  492. package/dist/durable/ToolReconciler.d.mts +2 -0
  493. package/dist/durable/ToolReconciler.mjs +1 -0
  494. package/dist/durable/WakeScheduler.d.mts +2 -0
  495. package/dist/durable/WakeScheduler.mjs +1 -0
  496. package/dist/durable/WorkerAdmission.d.mts +2 -0
  497. package/dist/durable/WorkerAdmission.mjs +1 -0
  498. package/dist/durable/WorkerHost.d.mts +2 -0
  499. package/dist/durable/WorkerHost.mjs +1 -0
  500. package/dist/engine/AgentRuntime.d.mts +2 -0
  501. package/dist/engine/AgentRuntime.mjs +1 -0
  502. package/dist/engine/Compaction.d.mts +4 -0
  503. package/dist/engine/Compaction.mjs +2 -0
  504. package/dist/engine/ContextCompactor.d.mts +2 -0
  505. package/dist/engine/ContextCompactor.mjs +1 -0
  506. package/dist/engine/ContextHistory.d.mts +2 -0
  507. package/dist/engine/ContextHistory.mjs +1 -0
  508. package/dist/engine/ContextWindow.d.mts +2 -0
  509. package/dist/engine/ContextWindow.mjs +1 -0
  510. package/dist/engine/DurableStep.d.mts +2 -0
  511. package/dist/engine/DurableStep.mjs +3 -0
  512. package/dist/engine/MessagingHost.d.mts +2 -0
  513. package/dist/engine/MessagingHost.mjs +1 -0
  514. package/dist/engine/Output.d.mts +3 -0
  515. package/dist/engine/Output.mjs +2 -0
  516. package/dist/engine/RunEventSink.d.mts +2 -0
  517. package/dist/engine/RunEventSink.mjs +1 -0
  518. package/dist/engine/RunOptions.d.mts +2 -0
  519. package/dist/engine/RunOptions.mjs +1 -0
  520. package/dist/engine/SubagentHost.d.mts +2 -0
  521. package/dist/engine/SubagentHost.mjs +1 -0
  522. package/dist/engine/ThreadHistory.d.mts +2 -0
  523. package/dist/engine/ThreadHistory.mjs +1 -0
  524. package/dist/engine/ToolBroker.d.mts +2 -0
  525. package/dist/engine/ToolBroker.mjs +1 -0
  526. package/dist/index.d.mts +90 -0
  527. package/dist/index.mjs +101 -0
  528. package/dist/output-contract-CYA4oBhe.mjs +128 -0
  529. package/dist/output-contract-CYA4oBhe.mjs.map +1 -0
  530. package/dist/rolldown-runtime-D3KUYPsf.mjs +12 -0
  531. package/dist/run-context-reader-CHox63hg.d.mts +17 -0
  532. package/dist/sandbox/CodeExecutor.d.mts +2 -0
  533. package/dist/sandbox/CodeExecutor.mjs +1 -0
  534. package/dist/sandbox/InteractiveBrowser.d.mts +2 -0
  535. package/dist/sandbox/InteractiveBrowser.mjs +1 -0
  536. package/dist/sandbox/PageCapture.d.mts +2 -0
  537. package/dist/sandbox/PageCapture.mjs +1 -0
  538. package/dist/sandbox/PageScreenshot.d.mts +2 -0
  539. package/dist/sandbox/PageScreenshot.mjs +1 -0
  540. package/dist/sandbox/Sandbox.d.mts +2 -0
  541. package/dist/sandbox/Sandbox.mjs +1 -0
  542. package/dist/subagent-policy-xRJhrc0a.mjs +133 -0
  543. package/dist/subagent-policy-xRJhrc0a.mjs.map +1 -0
  544. package/dist/tool-execution-Cl7v8fXU.mjs +16 -0
  545. package/dist/tool-execution-Cl7v8fXU.mjs.map +1 -0
  546. package/dist/tool-operations-CauPonM8.mjs +84 -0
  547. package/dist/tool-operations-CauPonM8.mjs.map +1 -0
  548. package/dist/utf8-Bl0ZhhGe.mjs +27 -0
  549. package/dist/utf8-Bl0ZhhGe.mjs.map +1 -0
  550. package/package.json +489 -5
  551. package/src/InMemory.ts +79 -0
  552. package/src/ToolExposure.ts +2 -0
  553. package/src/capabilities/BrowserUse.ts +212 -0
  554. package/src/capabilities/Budget.ts +544 -0
  555. package/src/capabilities/CodeMode.ts +1129 -0
  556. package/src/capabilities/ContextTools.ts +131 -0
  557. package/src/capabilities/MemoryNotes.ts +177 -0
  558. package/src/capabilities/Messaging.ts +260 -0
  559. package/src/capabilities/Redaction.ts +163 -0
  560. package/src/capabilities/RunHooks.ts +116 -0
  561. package/src/capabilities/SemanticMemory.ts +402 -0
  562. package/src/capabilities/Subagent.ts +2343 -0
  563. package/src/capabilities/SubagentReservations.ts +807 -0
  564. package/src/capabilities/ToolDiscovery.ts +291 -0
  565. package/src/capabilities/ToolResults.ts +50 -0
  566. package/src/capabilities/WebCapture.ts +64 -0
  567. package/src/capabilities/WebSearch.ts +45 -0
  568. package/src/capabilities/internal/subagent-background.ts +1137 -0
  569. package/src/capabilities/internal/subagent-contract.ts +92 -0
  570. package/src/capabilities/internal/subagent-policy.ts +205 -0
  571. package/src/capabilities/internal/subagent-reporting.ts +152 -0
  572. package/src/core/Agent.ts +528 -0
  573. package/src/core/AgentError.ts +189 -0
  574. package/src/core/AgentPolicy.ts +194 -0
  575. package/src/core/AgentUpdates.ts +104 -0
  576. package/src/core/FailureDiagnostic.ts +392 -0
  577. package/src/core/IdGenerator.ts +42 -0
  578. package/src/core/Identifiers.ts +64 -0
  579. package/src/core/Memory.ts +283 -0
  580. package/src/core/MemoryNamespace.ts +202 -0
  581. package/src/core/MemoryReference.ts +120 -0
  582. package/src/core/MemoryRevalidation.ts +151 -0
  583. package/src/core/MemoryStore.ts +371 -0
  584. package/src/core/Messaging.ts +72 -0
  585. package/src/core/ProvisionalText.ts +53 -0
  586. package/src/core/Receipt.ts +42 -0
  587. package/src/core/RememberingStore.ts +22 -0
  588. package/src/core/RunEvent.ts +345 -0
  589. package/src/core/RunPolicyUsage.ts +19 -0
  590. package/src/core/SemanticMemoryIndex.ts +259 -0
  591. package/src/core/SemanticMemoryRevalidation.ts +220 -0
  592. package/src/core/SubagentContract.ts +263 -0
  593. package/src/core/Thread.ts +447 -0
  594. package/src/core/ToolExposure.ts +75 -0
  595. package/src/core/ToolResult.ts +204 -0
  596. package/src/core/ToolResultStorage.ts +56 -0
  597. package/src/core/Usage.ts +562 -0
  598. package/src/core/Worker.ts +236 -0
  599. package/src/core/internal/agent-updates.ts +42 -0
  600. package/src/core/internal/completion.ts +33 -0
  601. package/src/core/internal/json.ts +17 -0
  602. package/src/core/internal/memory-document.ts +39 -0
  603. package/src/core/internal/message-status.ts +60 -0
  604. package/src/core/internal/strict-schema.ts +14 -0
  605. package/src/core/internal/tool-execution.ts +33 -0
  606. package/src/core/internal/utf8.ts +32 -0
  607. package/src/durable/ActivityStore.ts +131 -0
  608. package/src/durable/Admin.ts +504 -0
  609. package/src/durable/AgentRegistration.ts +16 -0
  610. package/src/durable/CommittedActivity.ts +262 -0
  611. package/src/durable/Digest.ts +57 -0
  612. package/src/durable/DurableAgentRuntime.ts +12758 -0
  613. package/src/durable/DurableFailpoint.ts +108 -0
  614. package/src/durable/DurableFailpointTestControl.ts +39 -0
  615. package/src/durable/EventSource.ts +179 -0
  616. package/src/durable/LifecyclePublication.ts +343 -0
  617. package/src/durable/MessageDelivery.ts +949 -0
  618. package/src/durable/MessageDeliveryStoreConformance.ts +407 -0
  619. package/src/durable/OperationAuthorizer.ts +89 -0
  620. package/src/durable/PersistentHistory.ts +322 -0
  621. package/src/durable/PreparedInputAdmission.ts +128 -0
  622. package/src/durable/RecordFormat.ts +113 -0
  623. package/src/durable/Records.ts +1396 -0
  624. package/src/durable/Recovery.ts +1022 -0
  625. package/src/durable/RunContinuation.ts +1946 -0
  626. package/src/durable/RunJournal.ts +1926 -0
  627. package/src/durable/RunStorage.ts +533 -0
  628. package/src/durable/Schedule.ts +445 -0
  629. package/src/durable/ScheduleStoreConformance.ts +642 -0
  630. package/src/durable/ScheduleTransition.ts +267 -0
  631. package/src/durable/Scheduling.ts +1031 -0
  632. package/src/durable/SettlementPublisher.ts +172 -0
  633. package/src/durable/SqlMemoryStore.ts +1042 -0
  634. package/src/durable/SqlStorageOwner.ts +25 -0
  635. package/src/durable/SubmissionLedger.ts +1247 -0
  636. package/src/durable/SubmissionLedgerConformance.ts +4695 -0
  637. package/src/durable/SubmissionStatus.ts +14 -0
  638. package/src/durable/Subscription.ts +527 -0
  639. package/src/durable/SubscriptionInput.ts +145 -0
  640. package/src/durable/SubscriptionStoreConformance.ts +1275 -0
  641. package/src/durable/SubscriptionTransition.ts +330 -0
  642. package/src/durable/Subscriptions.ts +1245 -0
  643. package/src/durable/ThreadArchiveRange.ts +91 -0
  644. package/src/durable/ThreadContextHistory.ts +338 -0
  645. package/src/durable/ThreadContextHistoryProjection.ts +219 -0
  646. package/src/durable/ThreadImport.ts +1199 -0
  647. package/src/durable/ThreadInvariants.ts +312 -0
  648. package/src/durable/ThreadProjectionMaintenance.ts +72 -0
  649. package/src/durable/ThreadReader.ts +21 -0
  650. package/src/durable/ThreadStore.ts +1258 -0
  651. package/src/durable/ThreadStoreConformance.ts +877 -0
  652. package/src/durable/ThreadTransfer.ts +263 -0
  653. package/src/durable/ThreadWork.ts +713 -0
  654. package/src/durable/ToolReconciler.ts +112 -0
  655. package/src/durable/WakeScheduler.ts +125 -0
  656. package/src/durable/WorkerAdmission.ts +98 -0
  657. package/src/durable/WorkerHost.ts +204 -0
  658. package/src/durable/internal/StorageOwner.ts +181 -0
  659. package/src/durable/internal/agent-registration.ts +713 -0
  660. package/src/durable/internal/agent-updates.ts +338 -0
  661. package/src/durable/internal/canonical-json.ts +110 -0
  662. package/src/durable/internal/evidence.ts +29 -0
  663. package/src/durable/internal/foreign-diagnostic.ts +48 -0
  664. package/src/durable/internal/history-prompt.ts +87 -0
  665. package/src/durable/internal/initial-context.ts +215 -0
  666. package/src/durable/internal/journal-metadata.ts +188 -0
  667. package/src/durable/internal/message-status.ts +18 -0
  668. package/src/durable/internal/messaging-host.ts +615 -0
  669. package/src/durable/internal/prompt-footprint.ts +47 -0
  670. package/src/durable/internal/prompt-history-cache.ts +604 -0
  671. package/src/durable/internal/record-encoding.ts +258 -0
  672. package/src/durable/internal/record-ownership.ts +68 -0
  673. package/src/durable/internal/run-context-reader.ts +51 -0
  674. package/src/durable/internal/run-context.ts +211 -0
  675. package/src/durable/internal/schedule-time.ts +304 -0
  676. package/src/durable/internal/thread-import-reader.ts +85 -0
  677. package/src/durable/internal/thread-initialization.ts +181 -0
  678. package/src/durable/internal/thread-transfer-source.ts +7 -0
  679. package/src/durable/internal/tool-operations.ts +138 -0
  680. package/src/durable/internal/transfer-dependencies.ts +40 -0
  681. package/src/durable/internal/usage-totals.ts +36 -0
  682. package/src/durable/internal/worker-host.ts +4041 -0
  683. package/src/durable/internal/worker-runtime.ts +10 -0
  684. package/src/engine/AgentRuntime.ts +100 -0
  685. package/src/engine/Compaction.ts +11 -0
  686. package/src/engine/ContextCompactor.ts +302 -0
  687. package/src/engine/ContextHistory.ts +75 -0
  688. package/src/engine/ContextWindow.ts +81 -0
  689. package/src/engine/DurableStep.ts +115 -0
  690. package/src/engine/MessagingHost.ts +118 -0
  691. package/src/engine/Output.ts +2 -0
  692. package/src/engine/RunEventSink.ts +124 -0
  693. package/src/engine/RunOptions.ts +664 -0
  694. package/src/engine/SubagentHost.ts +231 -0
  695. package/src/engine/ThreadHistory.ts +125 -0
  696. package/src/engine/ToolBroker.ts +159 -0
  697. package/src/engine/ToolExposure.ts +49 -0
  698. package/src/engine/internal/agent-runtime.ts +11137 -0
  699. package/src/engine/internal/bounded-value.ts +312 -0
  700. package/src/engine/internal/compaction.ts +673 -0
  701. package/src/engine/internal/error-diagnostic.ts +39 -0
  702. package/src/engine/internal/image-tokens.ts +61 -0
  703. package/src/engine/internal/interpreter-options.ts +569 -0
  704. package/src/engine/internal/output-contract.ts +226 -0
  705. package/src/engine/internal/primitive-delta.ts +103 -0
  706. package/src/engine/internal/provider-result-staging.ts +211 -0
  707. package/src/engine/internal/provisional-text.ts +107 -0
  708. package/src/engine/internal/tool-derivative.ts +47 -0
  709. package/src/engine/internal/tool-exposure.ts +228 -0
  710. package/src/engine/internal/tool-telemetry.ts +488 -0
  711. package/src/index.ts +100 -0
  712. package/src/sandbox/CodeExecutor.ts +352 -0
  713. package/src/sandbox/InteractiveBrowser.ts +343 -0
  714. package/src/sandbox/PageCapture.ts +391 -0
  715. package/src/sandbox/PageScreenshot.ts +83 -0
  716. package/src/sandbox/Sandbox.ts +29 -0
  717. package/README.md +0 -3
@@ -0,0 +1,4695 @@
1
+ import type * as CryptoDigest from 'effect/crypto/Digest'
2
+ import * as DateTime from 'effect/DateTime'
3
+ import * as Duration from 'effect/Duration'
4
+ import * as Effect from 'effect/Effect'
5
+ import * as Exit from 'effect/Exit'
6
+ import * as Option from 'effect/Option'
7
+ import * as Result from 'effect/Result'
8
+ import * as Schema from 'effect/Schema'
9
+ import * as Scope from 'effect/Scope'
10
+ import * as Stream from 'effect/Stream'
11
+ import * as TestClock from 'effect/testing/TestClock'
12
+
13
+ import { InputMessage, MessageAdmission } from '../capabilities/Messaging'
14
+ import { AgentPolicy } from '../core/AgentPolicy'
15
+ import { type ReceiptId } from '../core/Identifiers'
16
+ import { AgentId, DelegationId, SubmissionId, ThreadId, ToolCallId } from '../core/Identifiers'
17
+ import { SubagentDelegationCaps, SubagentGrant, SubagentReservationAmounts } from '../core/SubagentContract'
18
+ import { WorkerCompletion, WorkerUpdate } from '../core/Worker'
19
+ import { type DigestError, digestJson } from './Digest'
20
+ import {
21
+ CanonicalBatch,
22
+ CanonicalSequence,
23
+ DefinitionDigests,
24
+ DeploymentId,
25
+ Digest,
26
+ PersistedJson,
27
+ ProducerId,
28
+ RecordEnvelope,
29
+ type SettlementFailureDiagnostic,
30
+ SubmissionSettled,
31
+ SubmissionSettledRecord,
32
+ WorkerAdmission,
33
+ } from './Records'
34
+ import { runIdForSubmission } from './RunJournal'
35
+ import { make as makeRunStorage, type RunStorageSession, type StorageOwner } from './RunStorage'
36
+ import {
37
+ SettlementPublication,
38
+ type SettlementPublicationAuthority,
39
+ type SettlementPublicationFailure,
40
+ SettlementPublisher,
41
+ } from './SettlementPublisher'
42
+ import {
43
+ AbortCommand,
44
+ AbortIntentRequest,
45
+ AdmissionConflict,
46
+ AdmissionPolicyError,
47
+ AdmissionRequest,
48
+ type AdmissionResult,
49
+ ApprovalConflict,
50
+ ApprovalDecisionCommand,
51
+ ApprovalPendingSuspension,
52
+ BeginChildBudgetReleaseRequest,
53
+ ChildBudgetReservationRequest,
54
+ ChildReservationConflict,
55
+ ChildReservationId,
56
+ ChildSettledNotification,
57
+ ClaimHandoff,
58
+ ClaimRequest,
59
+ IdempotencyKey,
60
+ JoinedToHost,
61
+ LedgerError,
62
+ MarkInputAppliedRequest,
63
+ MarkJoinedRequest,
64
+ MarkReadyRequest,
65
+ MarkUnknownRequest,
66
+ OwnershipLost,
67
+ ParentLinkage,
68
+ Principal,
69
+ RecoverySnapshotRequest,
70
+ ReleaseChildBudgetRequest,
71
+ ResolutionCompletedWithResult,
72
+ ResolutionNeverHappened,
73
+ ResolutionSafeToRetry,
74
+ RevertJoiningRequest,
75
+ Settlement,
76
+ SettlementConflict,
77
+ SettlementFinalization,
78
+ submissionInputRecordId,
79
+ SubmissionLedger,
80
+ type SubmissionLedgerFailure,
81
+ SubmissionLookupById,
82
+ SubmissionLookupByKey,
83
+ submissionSettlementBatchId,
84
+ submissionSettlementId,
85
+ submissionSettlementRecordId,
86
+ SuspendRequest,
87
+ UnknownResolutionCommand,
88
+ UnknownResolutionConflict,
89
+ WaitingChild,
90
+ WaitingForChildSuspension,
91
+ } from './SubmissionLedger'
92
+ import {
93
+ AppendRequest,
94
+ getRecord,
95
+ ThreadMaterialization,
96
+ ThreadReader,
97
+ ThreadStore,
98
+ ThreadTailRequest,
99
+ } from './ThreadStore'
100
+
101
+ /** A SubmissionLedger contract invariant that an adapter under test violated. */
102
+ export class SubmissionLedgerConformanceViolation extends Schema.TaggedError<SubmissionLedgerConformanceViolation>()(
103
+ 'SubmissionLedgerConformanceViolation',
104
+ {
105
+ caseName: Schema.String,
106
+ message: Schema.String,
107
+ },
108
+ ) {}
109
+
110
+ export type SubmissionLedgerConformanceFailure =
111
+ | SubmissionLedgerFailure
112
+ | SettlementPublicationFailure
113
+ | DigestError
114
+ | SubmissionLedgerConformanceViolation
115
+
116
+ /**
117
+ * One adapter-neutral SubmissionLedger contract case. Each case owns disjoint Thread
118
+ * lanes, so a suite may run every case against one shared storage owner or a fresh
119
+ * owner per case. Cases drive elapsed time through `TestClock`, so they must run inside the
120
+ * `@effect/vitest` test environment (`it.effect`), and they compute real content digests, so the
121
+ * host suite must provide `CryptoDigest.Digest` and the same owner's `ThreadStore` and
122
+ * `SettlementPublisher`.
123
+ */
124
+ export interface SubmissionLedgerConformanceCase {
125
+ readonly name: string
126
+ readonly run: Effect.Effect<
127
+ void,
128
+ SubmissionLedgerConformanceFailure,
129
+ SubmissionLedger | ThreadStore | SettlementPublisher | CryptoDigest.Digest | StorageOwner
130
+ >
131
+ }
132
+
133
+ const decodeThreadId = Schema.decodeSync(ThreadId)
134
+ const decodeSubmissionId = Schema.decodeSync(SubmissionId)
135
+ const decodeIdempotencyKey = Schema.decodeSync(IdempotencyKey)
136
+ const decodeSequence = Schema.decodeSync(CanonicalSequence)
137
+ const decodeToolCallId = Schema.decodeSync(ToolCallId)
138
+ const decodeChildReservationId = Schema.decodeSync(ChildReservationId)
139
+
140
+ const persistedJsonEquivalent = Schema.toEquivalence(PersistedJson)
141
+ const isAdmissionConflict = Schema.is(AdmissionConflict)
142
+ const isApprovalConflict = Schema.is(ApprovalConflict)
143
+ const isChildReservationConflict = Schema.is(ChildReservationConflict)
144
+ const isJoinedToHost = Schema.is(JoinedToHost)
145
+ const isLedgerError = Schema.is(LedgerError)
146
+ const isOwnershipLost = Schema.is(OwnershipLost)
147
+ const isSettlementConflict = Schema.is(SettlementConflict)
148
+ const isUnknownResolutionConflict = Schema.is(UnknownResolutionConflict)
149
+
150
+ const CONFORMANCE_PRINCIPAL = Schema.decodeSync(Principal)('principal-ledger-conformance')
151
+ const OTHER_PRINCIPAL = Schema.decodeSync(Principal)('principal-ledger-conformance-other')
152
+ const CONFORMANCE_AGENT = Schema.decodeSync(AgentId)('agent-ledger-conformance')
153
+ const CONFORMANCE_DEPLOYMENT = Schema.decodeSync(DeploymentId)('deployment-ledger-conformance')
154
+ const CONFORMANCE_DEFINITION_DIGEST = Schema.decodeSync(Digest)('d'.repeat(64))
155
+
156
+ const CONFORMANCE_DIGESTS = DefinitionDigests.make({
157
+ agent: CONFORMANCE_DEFINITION_DIGEST,
158
+ model: CONFORMANCE_DEFINITION_DIGEST,
159
+ tools: CONFORMANCE_DEFINITION_DIGEST,
160
+ })
161
+
162
+ const CONFORMANCE_CREATED_AT = DateTime.toUtc(DateTime.makeUnsafe(1))
163
+ const PRODUCER_A = Schema.decodeSync(ProducerId)('producer-ledger-conformance-a')
164
+
165
+ const sameInstant = (left: DateTime.Utc, right: DateTime.Utc): boolean =>
166
+ DateTime.toEpochMillis(left) === DateTime.toEpochMillis(right)
167
+
168
+ const admissionRequest = Effect.fn('SubmissionLedgerConformance.admissionRequest')(function*(
169
+ threadId: ThreadId,
170
+ idempotencyKey: string,
171
+ input: PersistedJson,
172
+ parentLinkage?: ParentLinkage,
173
+ ) {
174
+ const inputDigest = yield* digestJson(input)
175
+
176
+ return AdmissionRequest.make({
177
+ threadId,
178
+ principal: CONFORMANCE_PRINCIPAL,
179
+ idempotencyKey: decodeIdempotencyKey(idempotencyKey),
180
+ agentId: CONFORMANCE_AGENT,
181
+ agentDigests: CONFORMANCE_DIGESTS,
182
+ deploymentId: CONFORMANCE_DEPLOYMENT,
183
+ inputPayload: input,
184
+ inputDigest,
185
+ ...(parentLinkage === undefined ? {} : { parentLinkage }),
186
+ })
187
+ })
188
+
189
+ const admitReady = Effect.fn('SubmissionLedgerConformance.admitReady')(function*(
190
+ threadId: ThreadId,
191
+ idempotencyKey: string,
192
+ input: PersistedJson,
193
+ ) {
194
+ const ledger = yield* SubmissionLedger
195
+ const admitted = yield* ledger.admit(yield* admissionRequest(threadId, idempotencyKey, input))
196
+
197
+ yield* ledger.markReady(MarkReadyRequest.make({ submissionId: admitted.submissionId }))
198
+
199
+ return admitted
200
+ })
201
+
202
+ const claimLane = Effect.fn('SubmissionLedgerConformance.claimLane')(function*(
203
+ threadId: ThreadId,
204
+ handoff?: ClaimHandoff,
205
+ ) {
206
+ const storage = yield* makeRunStorage
207
+
208
+ return Option.map(
209
+ yield* storage.claim(
210
+ ClaimRequest.make({ threadId, ...(handoff === undefined ? {} : { handoff }) }),
211
+ ),
212
+ (session) => ({ ...session.claim, session }),
213
+ )
214
+ })
215
+
216
+ const lookupById = Effect.fn('SubmissionLedgerConformance.lookupById')(function*(
217
+ submissionId: SubmissionId,
218
+ ) {
219
+ const ledger = yield* SubmissionLedger
220
+
221
+ return yield* ledger.lookup(SubmissionLookupById.make({ submissionId }))
222
+ })
223
+
224
+ const recoverySnapshot = Effect.fn('SubmissionLedgerConformance.recoverySnapshot')(function*(
225
+ submissionId: SubmissionId,
226
+ ) {
227
+ const ledger = yield* SubmissionLedger
228
+
229
+ return yield* ledger.loadRecoverySnapshot(RecoverySnapshotRequest.make({ submissionId }))
230
+ })
231
+
232
+ const readSettlementRecord = Effect.fn('SubmissionLedgerConformance.readSettlementRecord')(
233
+ function*(threadId: ThreadId, submissionId: SubmissionId) {
234
+ const store = yield* ThreadStore
235
+
236
+ return yield* getRecord({
237
+ threadId,
238
+ recordId: submissionSettlementRecordId(submissionId),
239
+ }).pipe(Effect.provideService(ThreadReader, ThreadReader.fromStore(store)))
240
+ },
241
+ )
242
+
243
+ interface PublicationIdentity {
244
+ readonly submissionId: SubmissionId
245
+ readonly authority: SettlementPublicationAuthority
246
+ readonly receiptId: ReceiptId
247
+ }
248
+
249
+ type PublicationOptions =
250
+ & PublicationIdentity
251
+ & (
252
+ | { readonly outcome: 'completed'; readonly result?: PersistedJson }
253
+ | { readonly outcome: 'failed'; readonly result: SettlementFailureDiagnostic }
254
+ | { readonly outcome: 'aborted'; readonly result?: never }
255
+ )
256
+
257
+ /** Build a real append request from the same storage owner's current canonical tail. */
258
+ const publicationForRecord = Effect.fn('SubmissionLedgerConformance.publicationForRecord')(
259
+ function*(
260
+ submissionId: SubmissionId,
261
+ authority: SettlementPublicationAuthority,
262
+ record: RecordEnvelope,
263
+ ) {
264
+ const store = yield* ThreadStore
265
+ const found = yield* lookupById(submissionId)
266
+
267
+ if (Option.isNone(found)) {
268
+ return yield* LedgerError.make({
269
+ operation: 'conformance publication',
270
+ message: 'Unknown Submission',
271
+ })
272
+ }
273
+ const threadId = found.value.threadId
274
+
275
+ const tail = yield* store
276
+ .inspectTail(ThreadTailRequest.make({ threadId }))
277
+ .pipe(
278
+ Effect.catchTag('ThreadNotMaterialized', () =>
279
+ store
280
+ .materialize(ThreadMaterialization.make({ threadId }))
281
+ .pipe(Effect.andThen(store.inspectTail(ThreadTailRequest.make({ threadId }))))),
282
+ )
283
+
284
+ return SettlementPublication.make({
285
+ submissionId,
286
+ authority,
287
+ append: AppendRequest.make({
288
+ threadId,
289
+
290
+ expectedTailSequence: tail.tailSequence,
291
+
292
+ batch: CanonicalBatch.make({
293
+ batchId: submissionSettlementBatchId(submissionId),
294
+ producerId: PRODUCER_A,
295
+ records: [record],
296
+ }),
297
+ }),
298
+ })
299
+ },
300
+ )
301
+
302
+ /** Deterministic canonical settlement candidate; publication itself chooses the immutable winner. */
303
+ const settlementPublication = Effect.fn('SubmissionLedgerConformance.settlementPublication')(
304
+ function*(options: PublicationOptions) {
305
+ const payload = yield* Schema.decodeEffect(SubmissionSettledRecord)(
306
+ SubmissionSettled.make({
307
+ submissionId: options.submissionId,
308
+ settlementId: submissionSettlementId(options.submissionId),
309
+ receiptId: options.receiptId,
310
+ outcome: options.outcome,
311
+ ...(options.authority._tag === 'Joined'
312
+ ? { runId: runIdForSubmission(options.authority.hostSubmissionId) }
313
+ : options.authority._tag === 'Owned'
314
+ ? { runId: runIdForSubmission(options.submissionId) }
315
+ : {}),
316
+ ...(options.result === undefined ? {} : { result: options.result }),
317
+ }),
318
+ ).pipe(Effect.orDie)
319
+
320
+ return yield* publicationForRecord(
321
+ options.submissionId,
322
+ options.authority,
323
+ RecordEnvelope.make({
324
+ recordId: submissionSettlementRecordId(options.submissionId),
325
+ family: 'thread',
326
+ schemaVersion: 1,
327
+ createdAt: CONFORMANCE_CREATED_AT,
328
+ deploymentId: CONFORMANCE_DEPLOYMENT,
329
+ payload,
330
+ }),
331
+ )
332
+ },
333
+ )
334
+
335
+ const publishSettlement = Effect.fn('SubmissionLedgerConformance.publishSettlement')(function*(
336
+ request: SettlementPublication,
337
+ ) {
338
+ return yield* (yield* SettlementPublisher).publish(request)
339
+ })
340
+
341
+ const recordEquivalent = Schema.toEquivalence(RecordEnvelope)
342
+
343
+ const settleClaimed = Effect.fn('SubmissionLedgerConformance.settleClaimed')(function*(
344
+ admitted: AdmissionResult,
345
+ session: RunStorageSession,
346
+ ) {
347
+ const ledger = yield* SubmissionLedger
348
+
349
+ const publication = yield* settlementPublication({
350
+ submissionId: admitted.submissionId,
351
+ authority: { _tag: 'Owned' },
352
+ receiptId: admitted.receiptId,
353
+ outcome: 'completed',
354
+ })
355
+
356
+ yield* session.publishSettlement(
357
+ yield* Schema.decodeUnknownEffect(Schema.toType(Schema.Struct(CanonicalBatch.fields)))(
358
+ publication.append.batch,
359
+ ).pipe(
360
+ Effect.map((value) => CanonicalBatch.make(value)),
361
+ Effect.orDie,
362
+ ),
363
+ )
364
+
365
+ return yield* ledger.finalizeSettlement(
366
+ SettlementFinalization.make({
367
+ submissionId: admitted.submissionId,
368
+ settlementId: submissionSettlementId(admitted.submissionId),
369
+ }),
370
+ )
371
+ })
372
+
373
+ const conformanceCase = (
374
+ name: string,
375
+ build: (assert: {
376
+ readonly ensure: (
377
+ condition: boolean,
378
+ message: string,
379
+ ) => Effect.Effect<void, SubmissionLedgerConformanceViolation>
380
+ readonly expectFailure: <A, E, R>(
381
+ description: string,
382
+ effect: Effect.Effect<A, E, R>,
383
+ ) => Effect.Effect<E, SubmissionLedgerConformanceViolation, R>
384
+ readonly expectSome: <A>(
385
+ description: string,
386
+ option: Option.Option<A>,
387
+ ) => Effect.Effect<A, SubmissionLedgerConformanceViolation>
388
+ }) => Effect.Effect<
389
+ void,
390
+ SubmissionLedgerConformanceFailure,
391
+ | SubmissionLedger
392
+ | ThreadStore
393
+ | SettlementPublisher
394
+ | CryptoDigest.Digest
395
+ | StorageOwner
396
+ | Scope.Scope
397
+ >,
398
+ ): SubmissionLedgerConformanceCase => ({
399
+ name,
400
+ run: build({
401
+ ensure: (condition, message) =>
402
+ condition
403
+ ? Effect.void
404
+ : Effect.fail(SubmissionLedgerConformanceViolation.make({ caseName: name, message })),
405
+ expectFailure: (description, effect) =>
406
+ Effect.flip(effect).pipe(
407
+ Effect.mapError(() =>
408
+ SubmissionLedgerConformanceViolation.make({
409
+ caseName: name,
410
+ message: `Expected failure but the operation succeeded: ${description}`,
411
+ })
412
+ ),
413
+ ),
414
+ expectSome: (description, option) =>
415
+ Effect.fromOption(option, () =>
416
+ SubmissionLedgerConformanceViolation.make({
417
+ caseName: name,
418
+ message: `Expected a value but found none: ${description}`,
419
+ })),
420
+ }).pipe(Effect.scoped, Effect.withSpan(`SubmissionLedgerConformance.${name}`)),
421
+ })
422
+
423
+ const admissionGroupRace = conformanceCase(
424
+ 'admits only one concurrent group request and retains immutable constraints',
425
+ ({ ensure, expectFailure, expectSome }) =>
426
+ Effect.gen(function*() {
427
+ const ledger = yield* SubmissionLedger
428
+
429
+ const requests = yield* Effect.forEach(['first', 'second'], (key) =>
430
+ admissionRequest(decodeThreadId('ledger-group-race'), key, {}).pipe(
431
+ Effect.map((request) =>
432
+ AdmissionRequest.make({ ...request, admissionGroup: 'entity' })
433
+ ),
434
+ ))
435
+
436
+ const outcomes = yield* Effect.forEach(
437
+ requests,
438
+ (request) => ledger.admit(request).pipe(Effect.result),
439
+ { concurrency: 2 },
440
+ )
441
+
442
+ yield* ensure(
443
+ outcomes.filter(Result.isSuccess).length === 1,
444
+ 'More than one unsettled group submission was admitted',
445
+ )
446
+ yield* ensure(
447
+ outcomes.some(
448
+ (outcome) =>
449
+ Result.isFailure(outcome) &&
450
+ Schema.is(AdmissionPolicyError)(outcome.failure) &&
451
+ outcome.failure.reason === 'occupied',
452
+ ),
453
+ 'Concurrent loser was not a typed capacity wait',
454
+ )
455
+ for (const [index, outcome] of outcomes.entries()) {
456
+ if (Result.isFailure(outcome)) continue
457
+ const request = requests[index]
458
+
459
+ if (request === undefined) return yield* Effect.die('Missing group race request')
460
+
461
+ const snapshot = yield* expectSome(
462
+ 'group snapshot',
463
+ yield* lookupById(outcome.success.submissionId),
464
+ )
465
+
466
+ yield* ensure(
467
+ snapshot.admissionGroup === 'entity',
468
+ 'Admission constraints disappeared from the durable snapshot',
469
+ )
470
+ yield* ensure(
471
+ isAdmissionConflict(
472
+ yield* expectFailure(
473
+ 'changed retained group',
474
+ ledger.admit(AdmissionRequest.make({ ...request, admissionGroup: 'other' })),
475
+ ),
476
+ ),
477
+ 'Changed constraints did not produce an admission conflict',
478
+ )
479
+ }
480
+ }),
481
+ )
482
+
483
+ const admissionGroupSettlement = conformanceCase(
484
+ 'retains group capacity until finalization and permits exact replay',
485
+ ({ ensure, expectFailure, expectSome }) =>
486
+ Effect.gen(function*() {
487
+ const ledger = yield* SubmissionLedger
488
+ const threadId = decodeThreadId('ledger-conformance-group')
489
+
490
+ const original = AdmissionRequest.make({
491
+ ...(yield* admissionRequest(threadId, 'group-first', { n: 1 })),
492
+ admissionGroup: 'entity-work',
493
+ })
494
+
495
+ const successor = AdmissionRequest.make({
496
+ ...(yield* admissionRequest(threadId, 'group-second', { n: 2 })),
497
+ admissionGroup: 'entity-work',
498
+ })
499
+
500
+ const first = yield* ledger.admit(original)
501
+
502
+ yield* expectFailure('occupied group', ledger.admit(successor))
503
+ yield* ensure(
504
+ (yield* ledger.admit(original)).submissionId === first.submissionId,
505
+ 'Exact retry must resolve before occupied group checks',
506
+ )
507
+ yield* ledger.markReady(MarkReadyRequest.make({ submissionId: first.submissionId }))
508
+ yield* expectSome('claimed group head', yield* claimLane(threadId))
509
+
510
+ yield* publishSettlement(
511
+ yield* settlementPublication({
512
+ submissionId: first.submissionId,
513
+ receiptId: first.receiptId,
514
+ authority: { _tag: 'Owned' },
515
+ outcome: 'completed',
516
+ }),
517
+ )
518
+
519
+ const published = yield* expectSome(
520
+ 'group snapshot after publication',
521
+ yield* lookupById(first.submissionId),
522
+ )
523
+
524
+ if (published.state !== 'settled') {
525
+ yield* expectFailure('published but unfinalized group', ledger.admit(successor))
526
+ }
527
+ yield* ledger.finalizeSettlement(
528
+ SettlementFinalization.make({
529
+ submissionId: first.submissionId,
530
+ settlementId: submissionSettlementId(first.submissionId),
531
+ }),
532
+ )
533
+ yield* ensure(
534
+ !(yield* ledger.admit(successor)).replayed,
535
+ 'Only finalized settlement releases group capacity',
536
+ )
537
+ }),
538
+ )
539
+
540
+ const admissionIdempotency = conformanceCase(
541
+ 'replays identical admissions and rejects conflicting input digests',
542
+ ({ ensure, expectFailure, expectSome }) =>
543
+ Effect.gen(function*() {
544
+ const threadId = decodeThreadId('ledger-conformance-admission')
545
+ const ledger = yield* SubmissionLedger
546
+
547
+ const request = yield* admissionRequest(threadId, 'admission-key-1', {
548
+ city: 'Lisbon',
549
+ })
550
+
551
+ const first = yield* ledger.admit(request)
552
+
553
+ yield* ensure(!first.replayed, 'The first admission of a key must not report replayed')
554
+ yield* ensure(first.state === 'admitted', 'A fresh admission must start in state admitted')
555
+
556
+ const afterAdmit = yield* expectSome(
557
+ 'lookup immediately after admission',
558
+ yield* lookupById(first.submissionId),
559
+ )
560
+
561
+ yield* ensure(
562
+ afterAdmit.inputDigest === request.inputDigest && afterAdmit.state === 'admitted',
563
+ 'Admission must be readable with strong consistency immediately after the write',
564
+ )
565
+
566
+ const replayed = yield* ledger.admit(request)
567
+
568
+ yield* ensure(
569
+ replayed.replayed &&
570
+ replayed.submissionId === first.submissionId &&
571
+ replayed.receiptId === first.receiptId &&
572
+ replayed.queueSequence === first.queueSequence,
573
+ 'An identical admission must replay the original identities with replayed set',
574
+ )
575
+
576
+ const conflicting = yield* admissionRequest(threadId, 'admission-key-1', {
577
+ city: 'Porto',
578
+ })
579
+
580
+ const conflict = yield* expectFailure(
581
+ 'an admission reusing the key with different canonical input',
582
+ ledger.admit(conflicting),
583
+ )
584
+
585
+ yield* ensure(
586
+ isAdmissionConflict(conflict) &&
587
+ conflict.existingInputDigest === request.inputDigest &&
588
+ conflict.attemptedInputDigest === conflicting.inputDigest,
589
+ 'A same-key admission with a different digest must fail with both digests reported',
590
+ )
591
+
592
+ yield* ledger.markReady(MarkReadyRequest.make({ submissionId: first.submissionId }))
593
+ yield* ledger.markReady(MarkReadyRequest.make({ submissionId: first.submissionId }))
594
+
595
+ const ready = yield* expectSome(
596
+ 'lookup after readiness',
597
+ yield* lookupById(first.submissionId),
598
+ )
599
+
600
+ yield* ensure(
601
+ ready.state === 'ready' && ready.readyAt !== undefined,
602
+ 'markReady must be idempotent and record readiness exactly once',
603
+ )
604
+
605
+ const retryAfterReady = yield* ledger.admit(request)
606
+
607
+ yield* ensure(
608
+ retryAfterReady.replayed && retryAfterReady.receiptId === first.receiptId,
609
+ 'A client retry after readiness must return the original Receipt',
610
+ )
611
+
612
+ const second = yield* ledger.admit(
613
+ yield* admissionRequest(threadId, 'admission-key-2', { city: 'Faro' }),
614
+ )
615
+
616
+ yield* ensure(
617
+ second.submissionId !== first.submissionId && second.queueSequence !== first.queueSequence,
618
+ 'A different key on the same lane must mint fresh identities and a fresh queue sequence',
619
+ )
620
+ }),
621
+ )
622
+
623
+ const workerMetadata = (base: AdmissionRequest) =>
624
+ WorkerAdmission.make({
625
+ executionRunId: null,
626
+ messageId: base.idempotencyKey,
627
+ sourceSubmissionId: Schema.decodeSync(SubmissionId)('source-input'),
628
+ deliveryPrincipal: base.principal,
629
+ parameters: { prompt: 'original projection parameters' },
630
+ createdAtMillis: 1,
631
+ origin: {
632
+ budgetScope: 'worker-run',
633
+ worker: {
634
+ schemaVersion: 1,
635
+ threadId: base.threadId,
636
+ targetAgentId: CONFORMANCE_AGENT,
637
+ delegationId: Schema.decodeSync(DelegationId)('worker-research'),
638
+ },
639
+ source: {
640
+ _tag: 'programmatic',
641
+ threadId: decodeThreadId('worker-source'),
642
+ agentId: CONFORMANCE_AGENT,
643
+ },
644
+ targetDigests: CONFORMANCE_DIGESTS,
645
+ policy: AgentPolicy.resolve(),
646
+ budget: {
647
+ caps: SubagentDelegationCaps.make({
648
+ maxConcurrentChildren: 1,
649
+ maxTotalChildInvocations: 2,
650
+ }),
651
+ allocation: SubagentReservationAmounts.make({
652
+ turns: 12,
653
+ toolCalls: 24,
654
+ durationMillis: 300_000,
655
+ inputTokens: 0,
656
+ outputTokens: 0,
657
+ costMicrousd: 0,
658
+ resultBytes: 1_000,
659
+ }),
660
+ },
661
+ grant: SubagentGrant.make({ maxDepth: 1, allowedToolNames: [] }),
662
+ depth: 1,
663
+ firstMessageId: base.idempotencyKey,
664
+ createdAtMillis: 1,
665
+ expiresAtMillis: 1_000_000,
666
+ },
667
+ })
668
+
669
+ const workerAdmissionIdentity = conformanceCase(
670
+ 'retains immutable worker admission metadata and rejects same-key changes or omission',
671
+ ({ ensure, expectFailure, expectSome }) =>
672
+ Effect.gen(function*() {
673
+ const ledger = yield* SubmissionLedger
674
+
675
+ const base = yield* admissionRequest(
676
+ decodeThreadId('ledger-conformance-worker'),
677
+ 'worker-message',
678
+ { text: 'first' },
679
+ )
680
+
681
+ const metadata = workerMetadata(base)
682
+
683
+ const admitted = yield* ledger.admit(
684
+ AdmissionRequest.make({ ...base, workerAdmission: metadata }),
685
+ )
686
+
687
+ const saved = yield* expectSome(
688
+ 'worker admission lookup',
689
+ yield* lookupById(admitted.submissionId),
690
+ )
691
+
692
+ yield* ensure(
693
+ saved.workerAdmission !== undefined &&
694
+ Schema.toEquivalence(WorkerAdmission)(saved.workerAdmission, metadata),
695
+ 'Worker origin and per-input parameters must survive admission lookup',
696
+ )
697
+ yield* ensure(
698
+ saved.parentLinkage === undefined,
699
+ 'Background work must not acquire attached-parent semantics',
700
+ )
701
+ const recovery = yield* recoverySnapshot(admitted.submissionId)
702
+
703
+ yield* ensure(
704
+ recovery.submission.workerAdmission !== undefined &&
705
+ Schema.toEquivalence(WorkerAdmission)(recovery.submission.workerAdmission, metadata),
706
+ 'Recovery must retain the exact worker envelope',
707
+ )
708
+
709
+ const replayed = yield* ledger.admit(
710
+ AdmissionRequest.make({ ...base, workerAdmission: metadata }),
711
+ )
712
+
713
+ yield* ensure(
714
+ replayed.replayed && replayed.receiptId === admitted.receiptId,
715
+ 'Identical metadata must replay the original receipt',
716
+ )
717
+ for (
718
+ const changed of [
719
+ undefined,
720
+ WorkerAdmission.make({ ...metadata, parameters: { prompt: 'changed' } }),
721
+ WorkerAdmission.make({
722
+ ...metadata,
723
+ sourceSubmissionId: yield* Schema.decodeEffect(SubmissionId)('other-source-input').pipe(
724
+ Effect.orDie,
725
+ ),
726
+ }),
727
+ WorkerAdmission.make({
728
+ ...metadata,
729
+ origin: { ...metadata.origin, expiresAtMillis: 2_000_000 },
730
+ }),
731
+ ]
732
+ ) {
733
+ const conflict = yield* expectFailure(
734
+ 'different or omitted worker metadata',
735
+ ledger.admit(
736
+ AdmissionRequest.make({
737
+ ...base,
738
+ ...(changed === undefined ? {} : { workerAdmission: changed }),
739
+ }),
740
+ ),
741
+ )
742
+
743
+ yield* ensure(
744
+ isAdmissionConflict(conflict),
745
+ 'Worker metadata changes must produce AdmissionConflict even when input is unchanged',
746
+ )
747
+ }
748
+
749
+ const nextKey = decodeIdempotencyKey('worker-follow-up')
750
+
751
+ const next = AdmissionRequest.make({
752
+ ...base,
753
+ idempotencyKey: nextKey,
754
+ workerAdmission: { ...metadata, messageId: nextKey, parameters: { prompt: 'next' } },
755
+ })
756
+
757
+ const followed = yield* ledger.admit(next)
758
+
759
+ yield* ensure(
760
+ followed.queueSequence > admitted.queueSequence,
761
+ 'Matching worker origins must admit later inputs',
762
+ )
763
+ for (
764
+ const changed of [
765
+ undefined,
766
+ WorkerAdmission.make({
767
+ ...metadata,
768
+ origin: { ...metadata.origin, expiresAtMillis: 3_000_000 },
769
+ }),
770
+ ]
771
+ ) {
772
+ const conflict = yield* expectFailure(
773
+ 'worker lane origin replacement',
774
+ ledger.admit(
775
+ AdmissionRequest.make({
776
+ ...base,
777
+ idempotencyKey: decodeIdempotencyKey('worker-lane-replacement'),
778
+ ...(changed === undefined ? {} : { workerAdmission: changed }),
779
+ }),
780
+ ),
781
+ )
782
+
783
+ yield* ensure(
784
+ conflict._tag === 'AdmissionPolicyError' && conflict.reason === 'refused',
785
+ 'New keys cannot remove or replace an established worker origin',
786
+ )
787
+ }
788
+
789
+ const ordinary = yield* admissionRequest(
790
+ decodeThreadId('ledger-conformance-ordinary-lane'),
791
+ 'ordinary',
792
+ { text: 'ordinary' },
793
+ )
794
+
795
+ yield* ledger.admit(ordinary)
796
+
797
+ const takeover = yield* expectFailure(
798
+ 'ordinary lane takeover',
799
+ ledger.admit(
800
+ AdmissionRequest.make({
801
+ ...ordinary,
802
+ idempotencyKey: decodeIdempotencyKey('takeover'),
803
+ workerAdmission: {
804
+ ...metadata,
805
+ origin: {
806
+ ...metadata.origin,
807
+ worker: { ...metadata.origin.worker, threadId: ordinary.threadId },
808
+ },
809
+ },
810
+ }),
811
+ ),
812
+ )
813
+
814
+ yield* ensure(
815
+ takeover._tag === 'AdmissionPolicyError' && takeover.reason === 'refused',
816
+ 'A worker cannot take over an ordinary lane before canonical materialization',
817
+ )
818
+
819
+ const racing = yield* admissionRequest(
820
+ decodeThreadId('ledger-conformance-lane-race'),
821
+ 'ordinary-race',
822
+ { text: 'race' },
823
+ )
824
+
825
+ const raced = yield* Effect.forEach(
826
+ [
827
+ racing,
828
+ AdmissionRequest.make({
829
+ ...racing,
830
+ idempotencyKey: decodeIdempotencyKey('worker-race'),
831
+ workerAdmission: {
832
+ ...metadata,
833
+ origin: {
834
+ ...metadata.origin,
835
+ worker: { ...metadata.origin.worker, threadId: racing.threadId },
836
+ },
837
+ },
838
+ }),
839
+ ],
840
+ (request) => ledger.admit(request).pipe(Effect.result),
841
+ { concurrency: 2 },
842
+ )
843
+
844
+ yield* ensure(
845
+ raced.filter((result) => result._tag === 'Success').length === 1 &&
846
+ raced.filter(
847
+ (result) => result._tag === 'Failure' && result.failure._tag === 'AdmissionPolicyError',
848
+ ).length === 1,
849
+ 'Concurrent ordinary/worker admissions must atomically choose exactly one lane identity',
850
+ )
851
+ }),
852
+ )
853
+
854
+ const messageAdmissionIdentity = conformanceCase(
855
+ 'retains authenticated peer provenance and rejects same-key changes or omission',
856
+ ({ ensure, expectFailure, expectSome }) =>
857
+ Effect.gen(function*() {
858
+ const ledger = yield* SubmissionLedger
859
+
860
+ const base = yield* admissionRequest(
861
+ decodeThreadId('ledger-conformance-peer'),
862
+ 'peer-message',
863
+ { text: 'hello' },
864
+ )
865
+
866
+ const metadata = yield* Schema.decodeEffect(MessageAdmission)({
867
+ schemaVersion: 1,
868
+ message: { ownerThreadId: 'peer-source', messageId: 'peer-message' },
869
+ peerName: 'reviewer',
870
+ sender: { threadId: 'peer-source', agentId: 'peer-agent' },
871
+ returnAddress: { threadId: 'peer-source', agentId: 'peer-agent' },
872
+ }).pipe(Effect.orDie)
873
+
874
+ const admitted = yield* ledger.admit(
875
+ AdmissionRequest.make({ ...base, messageAdmission: metadata }),
876
+ )
877
+
878
+ const saved = yield* expectSome(
879
+ 'peer admission lookup',
880
+ yield* lookupById(admitted.submissionId),
881
+ )
882
+
883
+ yield* ensure(
884
+ saved.messageAdmission !== undefined &&
885
+ Schema.toEquivalence(InputMessage)(saved.messageAdmission, metadata),
886
+ 'Peer sender and return address must survive lookup without becoming application input',
887
+ )
888
+ const recovery = yield* recoverySnapshot(admitted.submissionId)
889
+
890
+ yield* ensure(
891
+ recovery.submission.messageAdmission !== undefined &&
892
+ Schema.toEquivalence(InputMessage)(recovery.submission.messageAdmission, metadata),
893
+ 'Recovery must retain peer provenance',
894
+ )
895
+
896
+ const replayed = yield* ledger.admit(
897
+ AdmissionRequest.make({ ...base, messageAdmission: metadata }),
898
+ )
899
+
900
+ yield* ensure(
901
+ replayed.replayed && replayed.receiptId === admitted.receiptId,
902
+ 'Identical peer metadata must replay its receipt',
903
+ )
904
+ for (
905
+ const changed of [
906
+ undefined,
907
+ MessageAdmission.make({ ...metadata, peerName: 'other' }),
908
+ MessageAdmission.make({ ...metadata, inReplyTo: metadata.message }),
909
+ ]
910
+ ) {
911
+ const conflict = yield* expectFailure(
912
+ 'different or omitted peer metadata',
913
+ ledger.admit(
914
+ AdmissionRequest.make({
915
+ ...base,
916
+ ...(changed === undefined ? {} : { messageAdmission: changed }),
917
+ }),
918
+ ),
919
+ )
920
+
921
+ yield* ensure(
922
+ isAdmissionConflict(conflict),
923
+ 'Peer provenance changes must produce AdmissionConflict',
924
+ )
925
+ }
926
+ }),
927
+ )
928
+
929
+ const workerUpdateIdentity = conformanceCase(
930
+ 'retains framework updates separately and rejects changed same-key metadata',
931
+ ({ ensure, expectFailure, expectSome }) =>
932
+ Effect.gen(function*() {
933
+ const ledger = yield* SubmissionLedger
934
+
935
+ const base = yield* admissionRequest(
936
+ decodeThreadId('ledger-conformance-update'),
937
+ 'update-message',
938
+ { text: 'original application input' },
939
+ )
940
+
941
+ const metadata = yield* Schema.decodeEffect(WorkerUpdate)({
942
+ _tag: 'WorkerUpdate',
943
+ schemaVersion: 1,
944
+ worker: {
945
+ schemaVersion: 1,
946
+ delegationId: 'research',
947
+ targetAgentId: 'child',
948
+ threadId: 'child-thread',
949
+ },
950
+ update: {
951
+ schemaVersion: 1,
952
+ agentId: 'child',
953
+ threadId: 'child-thread',
954
+ runId: 'child-run',
955
+ updateId: 'finding',
956
+ sequence: 1,
957
+ value: { finding: 'partial' },
958
+ },
959
+ }).pipe(Effect.orDie)
960
+
961
+ const admitted = yield* ledger.admit(
962
+ AdmissionRequest.make({ ...base, messageAdmission: metadata }),
963
+ )
964
+
965
+ const saved = yield* expectSome(
966
+ 'update admission lookup',
967
+ yield* lookupById(admitted.submissionId),
968
+ )
969
+
970
+ yield* ensure(
971
+ saved.messageAdmission !== undefined &&
972
+ Schema.toEquivalence(InputMessage)(saved.messageAdmission, metadata),
973
+ 'Update identity and value must survive lookup',
974
+ )
975
+ yield* ensure(
976
+ Schema.toEquivalence(PersistedJson)(saved.inputPayload, base.inputPayload),
977
+ 'Framework update must not replace application input',
978
+ )
979
+ const recovery = yield* recoverySnapshot(admitted.submissionId)
980
+
981
+ yield* ensure(
982
+ recovery.submission.messageAdmission !== undefined &&
983
+ Schema.toEquivalence(InputMessage)(recovery.submission.messageAdmission, metadata),
984
+ 'Recovery must retain update provenance',
985
+ )
986
+
987
+ const replay = yield* ledger.admit(
988
+ AdmissionRequest.make({ ...base, messageAdmission: metadata }),
989
+ )
990
+
991
+ yield* ensure(
992
+ replay.replayed && replay.receiptId === admitted.receiptId,
993
+ 'Identical update retries must reuse the original receipt',
994
+ )
995
+ for (
996
+ const changed of [
997
+ undefined,
998
+ WorkerUpdate.make({ ...metadata, update: { ...metadata.update, sequence: 2 } }),
999
+ WorkerUpdate.make({
1000
+ ...metadata,
1001
+ update: { ...metadata.update, value: { finding: 'changed' } },
1002
+ }),
1003
+ ]
1004
+ ) {
1005
+ const conflict = yield* expectFailure(
1006
+ 'changed update metadata',
1007
+ ledger.admit(
1008
+ AdmissionRequest.make({
1009
+ ...base,
1010
+ ...(changed === undefined ? {} : { messageAdmission: changed }),
1011
+ }),
1012
+ ),
1013
+ )
1014
+
1015
+ yield* ensure(
1016
+ isAdmissionConflict(conflict),
1017
+ 'Changed update identity or value must conflict',
1018
+ )
1019
+ }
1020
+ }),
1021
+ )
1022
+
1023
+ const workerCompletionIdentity = conformanceCase(
1024
+ 'retains framework completions and rejects same-key changes or omission',
1025
+ ({ ensure, expectFailure, expectSome }) =>
1026
+ Effect.gen(function*() {
1027
+ const ledger = yield* SubmissionLedger
1028
+
1029
+ const base = yield* admissionRequest(
1030
+ decodeThreadId('ledger-conformance-completion'),
1031
+ 'completion-message',
1032
+ { text: 'hello' },
1033
+ )
1034
+
1035
+ const metadata = yield* Schema.decodeEffect(WorkerCompletion)({
1036
+ _tag: 'WorkerCompletion',
1037
+ schemaVersion: 1,
1038
+ budgetExhausted: false,
1039
+ report: {
1040
+ _tag: 'Settled',
1041
+ worker: {
1042
+ schemaVersion: 1,
1043
+ delegationId: 'research',
1044
+ targetAgentId: 'child',
1045
+ threadId: 'child-thread',
1046
+ },
1047
+ receipt: {
1048
+ threadId: 'child-thread',
1049
+ submissionId: 'child-input',
1050
+ receiptId: 'child-receipt',
1051
+ queueSequence: 1,
1052
+ },
1053
+ runId: 'child-run',
1054
+ settlementId: 'child-settlement',
1055
+ outcome: 'completed',
1056
+ result: { answer: 'done' },
1057
+ },
1058
+ }).pipe(Effect.orDie)
1059
+
1060
+ const admitted = yield* ledger.admit(
1061
+ AdmissionRequest.make({ ...base, messageAdmission: metadata }),
1062
+ )
1063
+
1064
+ const saved = yield* expectSome(
1065
+ 'completion admission lookup',
1066
+ yield* lookupById(admitted.submissionId),
1067
+ )
1068
+
1069
+ yield* ensure(
1070
+ saved.messageAdmission !== undefined &&
1071
+ Schema.toEquivalence(InputMessage)(saved.messageAdmission, metadata),
1072
+ 'Completion identity and projected result must survive lookup without becoming application input',
1073
+ )
1074
+ const recovery = yield* recoverySnapshot(admitted.submissionId)
1075
+
1076
+ yield* ensure(
1077
+ recovery.submission.messageAdmission !== undefined &&
1078
+ Schema.toEquivalence(InputMessage)(recovery.submission.messageAdmission, metadata),
1079
+ 'Recovery must retain completion provenance',
1080
+ )
1081
+
1082
+ const replayed = yield* ledger.admit(
1083
+ AdmissionRequest.make({ ...base, messageAdmission: metadata }),
1084
+ )
1085
+
1086
+ yield* ensure(
1087
+ replayed.replayed && replayed.receiptId === admitted.receiptId,
1088
+ 'Identical completion metadata must replay its receipt',
1089
+ )
1090
+ for (
1091
+ const changed of [
1092
+ undefined,
1093
+ WorkerCompletion.make({ ...metadata, budgetExhausted: true }),
1094
+ ]
1095
+ ) {
1096
+ const conflict = yield* expectFailure(
1097
+ 'different or omitted completion metadata',
1098
+ ledger.admit(
1099
+ AdmissionRequest.make({
1100
+ ...base,
1101
+ ...(changed === undefined ? {} : { messageAdmission: changed }),
1102
+ }),
1103
+ ),
1104
+ )
1105
+
1106
+ yield* ensure(
1107
+ isAdmissionConflict(conflict),
1108
+ 'Completion metadata changes must produce AdmissionConflict',
1109
+ )
1110
+ }
1111
+ }),
1112
+ )
1113
+
1114
+ const crossPrincipalAdmissionScoping = conformanceCase(
1115
+ 'scopes idempotency keys to their principal: a second principal reusing a key mints a distinct Submission',
1116
+ ({ ensure, expectSome }) =>
1117
+ Effect.gen(function*() {
1118
+ // SEC-002 (security-operations §2): "Client idempotency keys are scoped so one principal
1119
+ // cannot discover or collide with another principal's submission." This is the COLLIDE
1120
+ // half — a second principal reusing an existing (thread, idempotency key) must not
1121
+ // replay, overwrite, or conflict with the first principal's Submission, and must not learn
1122
+ // its identity. (The DISCOVER half — scoped lookup/resolveAdmission — is covered by
1123
+ // `lookupByIdAndKey` and `resolveAdmissionAuthority`.)
1124
+ const threadId = decodeThreadId('ledger-conformance-cross-principal')
1125
+ const ledger = yield* SubmissionLedger
1126
+ const idempotencyKey = decodeIdempotencyKey('shared-key-1')
1127
+
1128
+ const mineRequest = yield* admissionRequest(threadId, 'shared-key-1', {
1129
+ owner: 'mine',
1130
+ })
1131
+
1132
+ const mine = yield* ledger.admit(mineRequest)
1133
+
1134
+ // A DIFFERENT principal admits the SAME (thread, key) with different canonical input.
1135
+ // It is neither a replay nor an AdmissionConflict: keys are principal-scoped, so this mints
1136
+ // a fresh, distinct Submission with its own identities and queue position.
1137
+ const theirsRequest = AdmissionRequest.make({
1138
+ threadId,
1139
+ principal: OTHER_PRINCIPAL,
1140
+ idempotencyKey,
1141
+ agentId: CONFORMANCE_AGENT,
1142
+ agentDigests: CONFORMANCE_DIGESTS,
1143
+ deploymentId: CONFORMANCE_DEPLOYMENT,
1144
+ inputPayload: { owner: 'theirs' },
1145
+ inputDigest: yield* digestJson({ owner: 'theirs' }),
1146
+ })
1147
+
1148
+ const theirs = yield* ledger.admit(theirsRequest)
1149
+
1150
+ yield* ensure(
1151
+ !theirs.replayed &&
1152
+ theirs.submissionId !== mine.submissionId &&
1153
+ theirs.receiptId !== mine.receiptId &&
1154
+ theirs.queueSequence !== mine.queueSequence,
1155
+ 'A second principal reusing a key must mint a fresh, distinct Submission — never a replay or collision',
1156
+ )
1157
+
1158
+ // The first principal's own replay is unaffected by the second principal's admission.
1159
+ const mineReplay = yield* ledger.admit(mineRequest)
1160
+
1161
+ yield* ensure(
1162
+ mineReplay.replayed && mineReplay.submissionId === mine.submissionId,
1163
+ "The original principal's replay must still resolve to its own Submission after the other principal admitted",
1164
+ )
1165
+
1166
+ // Each principal's scoped lookup resolves ONLY its own Submission — no cross-principal
1167
+ // discovery through the shared key.
1168
+ const mineByKey = yield* expectSome(
1169
+ "the first principal's scoped lookup",
1170
+ yield* ledger.lookup(
1171
+ SubmissionLookupByKey.make({
1172
+ threadId,
1173
+ principal: CONFORMANCE_PRINCIPAL,
1174
+ idempotencyKey,
1175
+ }),
1176
+ ),
1177
+ )
1178
+
1179
+ const theirsByKey = yield* expectSome(
1180
+ "the second principal's scoped lookup",
1181
+ yield* ledger.lookup(
1182
+ SubmissionLookupByKey.make({
1183
+ threadId,
1184
+ principal: OTHER_PRINCIPAL,
1185
+ idempotencyKey,
1186
+ }),
1187
+ ),
1188
+ )
1189
+
1190
+ yield* ensure(
1191
+ mineByKey.submissionId === mine.submissionId &&
1192
+ theirsByKey.submissionId === theirs.submissionId &&
1193
+ mineByKey.submissionId !== theirsByKey.submissionId,
1194
+ "Each principal's scoped lookup must resolve only its own Submission under the shared key",
1195
+ )
1196
+ }),
1197
+ )
1198
+
1199
+ const admissionTupleBoundaries = conformanceCase(
1200
+ 'preserves admission tuple boundaries when principal and key contain separators',
1201
+ ({ ensure, expectSome }) =>
1202
+ Effect.gen(function*() {
1203
+ const threadId = decodeThreadId('ledger-conformance-admission-separators')
1204
+ const ledger = yield* SubmissionLedger
1205
+ const base = yield* admissionRequest(threadId, 'r', { work: 'separators' })
1206
+
1207
+ const firstRequest = AdmissionRequest.make({
1208
+ ...base,
1209
+ principal: yield* Schema.decodeEffect(Principal)('p\u001fq').pipe(Effect.orDie),
1210
+ })
1211
+
1212
+ const secondRequest = AdmissionRequest.make({
1213
+ ...base,
1214
+ principal: yield* Schema.decodeEffect(Principal)('p').pipe(Effect.orDie),
1215
+ idempotencyKey: decodeIdempotencyKey('q\u001fr'),
1216
+ })
1217
+
1218
+ const first = yield* ledger.admit(firstRequest)
1219
+ const second = yield* ledger.admit(secondRequest)
1220
+
1221
+ yield* ensure(
1222
+ !second.replayed &&
1223
+ second.submissionId !== first.submissionId &&
1224
+ second.receiptId !== first.receiptId &&
1225
+ second.queueSequence === first.queueSequence + 1,
1226
+ 'Distinct admission tuples must allocate distinct identities and consecutive queue positions',
1227
+ )
1228
+
1229
+ for (
1230
+ const [request, admitted] of [
1231
+ [firstRequest, first],
1232
+ [secondRequest, second],
1233
+ ] as const
1234
+ ) {
1235
+ const key = SubmissionLookupByKey.make({
1236
+ threadId,
1237
+ principal: request.principal,
1238
+ idempotencyKey: request.idempotencyKey,
1239
+ })
1240
+
1241
+ const found = yield* expectSome('the exact admission tuple', yield* ledger.lookup(key))
1242
+ const resolved = yield* ledger.resolveAdmission(key)
1243
+ const replay = yield* ledger.admit(request)
1244
+
1245
+ yield* ensure(
1246
+ found.submissionId === admitted.submissionId &&
1247
+ resolved._tag === 'Admitted' &&
1248
+ resolved.submission.submissionId === admitted.submissionId &&
1249
+ replay.replayed &&
1250
+ replay.submissionId === admitted.submissionId &&
1251
+ replay.receiptId === admitted.receiptId &&
1252
+ replay.queueSequence === admitted.queueSequence,
1253
+ 'Lookup, authoritative resolution, and replay must preserve the exact admission tuple',
1254
+ )
1255
+ }
1256
+ }),
1257
+ )
1258
+
1259
+ const concurrentAdmissionFifo = conformanceCase(
1260
+ 'allocates distinct FIFO queue sequences under concurrent admission and claims in order',
1261
+ ({ ensure, expectSome }) =>
1262
+ Effect.gen(function*() {
1263
+ const threadId = decodeThreadId('ledger-conformance-fifo-concurrent')
1264
+ const ledger = yield* SubmissionLedger
1265
+
1266
+ const requests = [
1267
+ yield* admissionRequest(threadId, 'fifo-key-0', { step: 0 }),
1268
+ yield* admissionRequest(threadId, 'fifo-key-1', { step: 1 }),
1269
+ yield* admissionRequest(threadId, 'fifo-key-2', { step: 2 }),
1270
+ ]
1271
+
1272
+ const admitted = yield* Effect.forEach(requests, (request) => ledger.admit(request), {
1273
+ concurrency: 'unbounded',
1274
+ })
1275
+
1276
+ const duplicate = yield* admissionRequest(threadId, 'fifo-key-dup', { step: 3 })
1277
+
1278
+ const duplicated = yield* Effect.all([ledger.admit(duplicate), ledger.admit(duplicate)], {
1279
+ concurrency: 'unbounded',
1280
+ })
1281
+
1282
+ yield* ensure(
1283
+ duplicated[0].submissionId === duplicated[1].submissionId &&
1284
+ duplicated[0].receiptId === duplicated[1].receiptId &&
1285
+ duplicated[0].queueSequence === duplicated[1].queueSequence,
1286
+ 'Concurrent duplicate admissions must resolve to one Submission and one Receipt',
1287
+ )
1288
+ yield* ensure(
1289
+ duplicated.filter((result) => !result.replayed).length === 1,
1290
+ 'Exactly one of two concurrent duplicate admissions must create the Submission',
1291
+ )
1292
+
1293
+ const lane = [...admitted, duplicated[0]]
1294
+
1295
+ yield* ensure(
1296
+ new Set(lane.map((result) => result.queueSequence)).size === lane.length,
1297
+ 'Concurrent admissions on one lane must allocate distinct queue sequences',
1298
+ )
1299
+ yield* ensure(
1300
+ new Set(lane.map((result) => result.submissionId)).size === lane.length,
1301
+ 'Concurrent admissions on one lane must mint distinct Submission identities',
1302
+ )
1303
+
1304
+ yield* Effect.forEach(
1305
+ lane,
1306
+ (result) => ledger.markReady(MarkReadyRequest.make({ submissionId: result.submissionId })),
1307
+ { discard: true },
1308
+ )
1309
+
1310
+ const expectedOrder = [...lane].sort((a, b) => a.queueSequence - b.queueSequence)
1311
+
1312
+ for (const expected of expectedOrder) {
1313
+ const claim = yield* expectSome(
1314
+ `a claim while ${expected.submissionId} heads the lane`,
1315
+ yield* claimLane(threadId),
1316
+ )
1317
+
1318
+ yield* ensure(
1319
+ claim.submissionId === expected.submissionId,
1320
+ 'Claims must deliver Submissions in ascending queue-sequence order',
1321
+ )
1322
+ yield* settleClaimed(expected, claim.session)
1323
+ }
1324
+ yield* ensure(
1325
+ Option.isNone(yield* claimLane(threadId)),
1326
+ 'A fully settled lane must produce no claim',
1327
+ )
1328
+ }),
1329
+ )
1330
+
1331
+ const fifoHeadClaim = conformanceCase(
1332
+ 'claims only the lowest unsettled head under a fresh local generation',
1333
+ ({ ensure, expectSome }) =>
1334
+ Effect.gen(function*() {
1335
+ const emptyLane = decodeThreadId('ledger-conformance-empty')
1336
+
1337
+ yield* ensure(
1338
+ Option.isNone(yield* claimLane(emptyLane)),
1339
+ 'Claiming a lane with no admitted work must return none',
1340
+ )
1341
+
1342
+ const threadId = decodeThreadId('ledger-conformance-head')
1343
+ const first = yield* admitReady(threadId, 'head-key-1', { order: 1 })
1344
+ const second = yield* admitReady(threadId, 'head-key-2', { order: 2 })
1345
+
1346
+ yield* ensure(
1347
+ second.queueSequence > first.queueSequence,
1348
+ 'Sequential admissions must allocate increasing queue sequences',
1349
+ )
1350
+
1351
+ const headClaim = yield* expectSome(
1352
+ 'the first claim on the lane',
1353
+ yield* claimLane(threadId),
1354
+ )
1355
+
1356
+ yield* ensure(
1357
+ headClaim.submissionId === first.submissionId,
1358
+ 'A claim must take the lowest unsettled queue sequence, never later work',
1359
+ )
1360
+
1361
+ const selected = yield* expectSome(
1362
+ 'lookup of the claimed head',
1363
+ yield* lookupById(first.submissionId),
1364
+ )
1365
+
1366
+ yield* ensure(
1367
+ selected.state === 'ready' && (yield* recoverySnapshot(first.submissionId)).hasOwner,
1368
+ 'Selection must preserve ready state and expose its local owner without a durable claim',
1369
+ )
1370
+ yield* ensure(
1371
+ Option.isNone(yield* claimLane(threadId)),
1372
+ 'A lane whose head has a live local owner must produce no claim',
1373
+ )
1374
+
1375
+ yield* settleClaimed(first, headClaim.session)
1376
+
1377
+ const nextClaim = yield* expectSome(
1378
+ 'the claim after the head settled',
1379
+ yield* claimLane(threadId),
1380
+ )
1381
+
1382
+ yield* ensure(
1383
+ nextClaim.submissionId === second.submissionId,
1384
+ 'Settling the head must make exactly the next queue sequence claimable',
1385
+ )
1386
+ yield* ensure(
1387
+ nextClaim.session.generation !== headClaim.session.generation,
1388
+ 'Every successful claim must create a distinct local generation',
1389
+ )
1390
+ yield* settleClaimed(second, nextClaim.session)
1391
+ yield* ensure(
1392
+ Option.isNone(yield* claimLane(threadId)),
1393
+ 'A drained lane must produce no claim',
1394
+ )
1395
+ }),
1396
+ )
1397
+
1398
+ const scopedOwnerExclusion = conformanceCase(
1399
+ 'elapsed time never grants a second owner before the active scope closes',
1400
+ ({ ensure, expectFailure, expectSome }) =>
1401
+ Effect.scoped(
1402
+ Effect.gen(function*() {
1403
+ const threadId = decodeThreadId('ledger-conformance-lease')
1404
+ const admitted = yield* admitReady(threadId, 'lease-key-1', { work: 'lease' })
1405
+ const storage = yield* makeRunStorage
1406
+
1407
+ const firstScope = yield* Effect.acquireRelease(Scope.make(), (scope) => Scope.close(scope, Exit.void))
1408
+
1409
+ const nextScope = yield* Effect.acquireRelease(Scope.make(), (scope) => Scope.close(scope, Exit.void))
1410
+
1411
+ const first = yield* expectSome(
1412
+ 'the initial scoped owner',
1413
+ yield* storage.claim(ClaimRequest.make({ threadId })).pipe(Scope.provide(firstScope)),
1414
+ )
1415
+
1416
+ yield* TestClock.adjust(Duration.hours(24))
1417
+ yield* ensure(
1418
+ Option.isNone(
1419
+ yield* storage.claim(ClaimRequest.make({ threadId })).pipe(Scope.provide(nextScope)),
1420
+ ),
1421
+ 'Elapsed time must never grant another owner while the original scope is alive',
1422
+ )
1423
+
1424
+ yield* Scope.close(firstScope, Exit.void)
1425
+
1426
+ const replacement = yield* expectSome(
1427
+ 'the replacement after the first scope actually closes',
1428
+ yield* storage.claim(ClaimRequest.make({ threadId })).pipe(Scope.provide(nextScope)),
1429
+ )
1430
+
1431
+ yield* ensure(
1432
+ replacement.claim.submissionId === admitted.submissionId &&
1433
+ replacement.claim.attemptId !== first.claim.attemptId,
1434
+ 'Actual scope close must make the same unfinished head claimable by a fresh Attempt',
1435
+ )
1436
+
1437
+ // Delayed cleanup from the old scope must not release its replacement.
1438
+ yield* first.release
1439
+ yield* replacement.checkActive
1440
+ yield* ensure(
1441
+ Option.isNone(
1442
+ yield* storage.claim(ClaimRequest.make({ threadId })).pipe(Scope.provide(firstScope)),
1443
+ ),
1444
+ 'An old release must not clear the replacement owner',
1445
+ )
1446
+
1447
+ const staleMark = yield* expectFailure(
1448
+ 'a late input marker from the closed session',
1449
+ first.markInputApplied({
1450
+ recordId: submissionInputRecordId(admitted.submissionId),
1451
+ sequence: decodeSequence(1),
1452
+ }),
1453
+ )
1454
+
1455
+ yield* ensure(isOwnershipLost(staleMark), 'A closed session must reject late results')
1456
+
1457
+ const publication = yield* settlementPublication({
1458
+ submissionId: admitted.submissionId,
1459
+ authority: { _tag: 'Owned' },
1460
+ receiptId: admitted.receiptId,
1461
+ outcome: 'completed',
1462
+ })
1463
+
1464
+ const stalePublication = yield* expectFailure(
1465
+ 'a late settlement from the closed session',
1466
+ first.publishSettlement(
1467
+ yield* Schema.decodeUnknownEffect(Schema.toType(Schema.Struct(CanonicalBatch.fields)))(
1468
+ publication.append.batch,
1469
+ ).pipe(
1470
+ Effect.map((value) => CanonicalBatch.make(value)),
1471
+ Effect.orDie,
1472
+ ),
1473
+ ),
1474
+ )
1475
+
1476
+ yield* ensure(
1477
+ isOwnershipLost(stalePublication),
1478
+ 'A closed session must reject settlement before canonical mutation',
1479
+ )
1480
+ yield* ensure(
1481
+ Option.isNone(yield* readSettlementRecord(threadId, admitted.submissionId)),
1482
+ 'A rejected late settlement must leave no canonical terminal record',
1483
+ )
1484
+ yield* replacement.checkActive
1485
+ }),
1486
+ ),
1487
+ )
1488
+
1489
+ const releaseMakesHeadClaimable = conformanceCase(
1490
+ 'releases ownership gracefully so the head is immediately claimable',
1491
+ ({ ensure, expectFailure, expectSome }) =>
1492
+ Effect.gen(function*() {
1493
+ const threadId = decodeThreadId('ledger-conformance-release')
1494
+ const admitted = yield* admitReady(threadId, 'release-key-1', { work: 'release' })
1495
+
1496
+ const firstClaim = yield* expectSome('the initial claim', yield* claimLane(threadId))
1497
+
1498
+ yield* firstClaim.session.release
1499
+
1500
+ const releasedRenew = yield* expectFailure(
1501
+ 'using a released session',
1502
+ firstClaim.session.checkActive,
1503
+ )
1504
+
1505
+ yield* ensure(
1506
+ isOwnershipLost(releasedRenew),
1507
+ 'A released session must no longer authorize work',
1508
+ )
1509
+
1510
+ const reclaim = yield* expectSome(
1511
+ 'the claim immediately after release',
1512
+ yield* claimLane(threadId),
1513
+ )
1514
+
1515
+ yield* ensure(
1516
+ reclaim.submissionId === admitted.submissionId &&
1517
+ reclaim.session.generation !== firstClaim.session.generation,
1518
+ 'A released nonterminal head must be claimable immediately with a fresh local generation',
1519
+ )
1520
+
1521
+ yield* firstClaim.session.release
1522
+ yield* reclaim.session.checkActive
1523
+ yield* settleClaimed(admitted, reclaim.session)
1524
+ }),
1525
+ )
1526
+
1527
+ const inputAppliedIdempotency = conformanceCase(
1528
+ 'marks canonical input applied idempotently under the owning token',
1529
+ ({ ensure, expectFailure, expectSome }) =>
1530
+ Effect.gen(function*() {
1531
+ const threadId = decodeThreadId('ledger-conformance-input')
1532
+ const ledger = yield* SubmissionLedger
1533
+ const admitted = yield* admitReady(threadId, 'input-key-1', { work: 'input' })
1534
+
1535
+ yield* expectSome('the claim before input apply', yield* claimLane(threadId))
1536
+
1537
+ const marker = MarkInputAppliedRequest.make({
1538
+ submissionId: admitted.submissionId,
1539
+
1540
+ recordId: submissionInputRecordId(admitted.submissionId),
1541
+ sequence: decodeSequence(2),
1542
+ })
1543
+
1544
+ yield* ledger.markInputApplied(marker)
1545
+
1546
+ const applied = yield* expectSome(
1547
+ 'lookup after marking input applied',
1548
+ yield* lookupById(admitted.submissionId),
1549
+ )
1550
+
1551
+ yield* ensure(
1552
+ applied.state === 'input-applied',
1553
+ 'Marking input applied must transition the Submission to input-applied',
1554
+ )
1555
+
1556
+ yield* ledger.markInputApplied(marker)
1557
+ for (
1558
+ const conflicting of [
1559
+ MarkInputAppliedRequest.make({
1560
+ ...marker,
1561
+ recordId: submissionInputRecordId(decodeSubmissionId('different-input-marker')),
1562
+ }),
1563
+ MarkInputAppliedRequest.make({ ...marker, sequence: decodeSequence(3) }),
1564
+ ]
1565
+ ) {
1566
+ const error = yield* expectFailure(
1567
+ 'a conflicting input-applied marker',
1568
+ ledger.markInputApplied(conflicting),
1569
+ )
1570
+
1571
+ yield* ensure(isLedgerError(error), 'Conflicting input markers must fail as LedgerError')
1572
+ }
1573
+ const snapshot = yield* recoverySnapshot(admitted.submissionId)
1574
+
1575
+ yield* ensure(
1576
+ snapshot.inputApplied !== undefined &&
1577
+ snapshot.inputApplied.recordId === marker.recordId &&
1578
+ snapshot.inputApplied.sequence === marker.sequence &&
1579
+ snapshot.submission.state === 'input-applied',
1580
+ 'Identical replays and rejected conflicts must retain the original input-applied marker',
1581
+ )
1582
+ }),
1583
+ )
1584
+
1585
+ const settlementLifecycle = conformanceCase(
1586
+ 'publishes and finalizes exactly one canonical settlement with idempotent replays',
1587
+ ({ ensure, expectFailure, expectSome }) =>
1588
+ Effect.gen(function*() {
1589
+ const threadId = decodeThreadId('ledger-conformance-settle')
1590
+ const ledger = yield* SubmissionLedger
1591
+ const admitted = yield* admitReady(threadId, 'settle-key-1', { work: 'settle' })
1592
+
1593
+ yield* expectSome('the claim before publication', yield* claimLane(threadId))
1594
+
1595
+ const publication = yield* settlementPublication({
1596
+ submissionId: admitted.submissionId,
1597
+ authority: { _tag: 'Owned' },
1598
+ receiptId: admitted.receiptId,
1599
+ outcome: 'completed',
1600
+ result: { answer: 42 },
1601
+ })
1602
+
1603
+ const finalization = SettlementFinalization.make({
1604
+ submissionId: admitted.submissionId,
1605
+ settlementId: submissionSettlementId(admitted.submissionId),
1606
+ })
1607
+
1608
+ yield* ensure(
1609
+ isLedgerError(
1610
+ yield* expectFailure(
1611
+ 'finalization without canonical publication',
1612
+ ledger.finalizeSettlement(finalization),
1613
+ ),
1614
+ ),
1615
+ 'A ledger marker alone cannot authorize finalization',
1616
+ )
1617
+ const published = yield* publishSettlement(publication)
1618
+
1619
+ yield* ensure(
1620
+ !published.replayed &&
1621
+ recordEquivalent(published.record, publication.append.batch.records[0]),
1622
+ 'First publication must commit the exact canonical record without replay',
1623
+ )
1624
+
1625
+ const canonical = yield* expectSome(
1626
+ 'the published canonical settlement',
1627
+ yield* readSettlementRecord(threadId, admitted.submissionId),
1628
+ )
1629
+
1630
+ yield* ensure(
1631
+ recordEquivalent(canonical.record, published.record),
1632
+ 'Publication must be visible in the real canonical ThreadStore',
1633
+ )
1634
+
1635
+ const pending = yield* expectSome(
1636
+ 'lookup after publication',
1637
+ yield* lookupById(admitted.submissionId),
1638
+ )
1639
+
1640
+ yield* ensure(
1641
+ pending.state === 'ready' ||
1642
+ (pending.state === 'settled' && pending.settledOutcome === 'completed'),
1643
+ 'Canonical publication may atomically finalize the same outcome',
1644
+ )
1645
+ if (pending.state === 'settled') {
1646
+ yield* ensure(
1647
+ isOwnershipLost(
1648
+ yield* expectFailure(
1649
+ 'Owned replay after atomic finalization',
1650
+ publishSettlement(publication),
1651
+ ),
1652
+ ),
1653
+ 'Atomic finalization releases authority; recover its acknowledgement through finalization',
1654
+ )
1655
+ } else {
1656
+ const replayed = yield* publishSettlement(publication)
1657
+
1658
+ yield* ensure(
1659
+ replayed.replayed &&
1660
+ recordEquivalent(replayed.record, published.record) &&
1661
+ replayed.tailSequence === published.tailSequence,
1662
+ 'Authorized publication replay must return the immutable winner and current canonical tail',
1663
+ )
1664
+ }
1665
+ const settlement = yield* ledger.finalizeSettlement(finalization)
1666
+
1667
+ yield* ensure(
1668
+ settlement.submissionId === admitted.submissionId &&
1669
+ settlement.settlementId === finalization.settlementId &&
1670
+ settlement.receiptId === admitted.receiptId &&
1671
+ settlement.outcome === 'completed',
1672
+ 'Finalization must return the canonical Settlement bound to the admission Receipt',
1673
+ )
1674
+
1675
+ const settled = yield* expectSome(
1676
+ 'lookup after finalization',
1677
+ yield* lookupById(admitted.submissionId),
1678
+ )
1679
+
1680
+ yield* ensure(
1681
+ settled.state === 'settled' && settled.settledOutcome === 'completed',
1682
+ 'Finalization must project the canonical outcome',
1683
+ )
1684
+ yield* TestClock.adjust('1 second')
1685
+ const retried = yield* ledger.finalizeSettlement(finalization)
1686
+
1687
+ yield* ensure(
1688
+ Schema.toEquivalence(Settlement)(retried, settlement) &&
1689
+ sameInstant(retried.settledAt, settlement.settledAt),
1690
+ 'Retrying finalization after a lost acknowledgment must retain the same Settlement and timestamp',
1691
+ )
1692
+ yield* ensure(
1693
+ Option.isNone(yield* claimLane(threadId)),
1694
+ 'A settled lane with no further work must produce no claim',
1695
+ )
1696
+
1697
+ const failedDiagnostic = {
1698
+ errorTag: 'ConformanceFailure',
1699
+ message: 'The conformance Submission failed',
1700
+ } as const
1701
+
1702
+ const failedAdmission = yield* admitReady(threadId, 'settle-key-2', { work: 'fail' })
1703
+
1704
+ yield* expectSome('the failed settlement claim', yield* claimLane(threadId))
1705
+
1706
+ yield* publishSettlement(
1707
+ yield* settlementPublication({
1708
+ submissionId: failedAdmission.submissionId,
1709
+ authority: { _tag: 'Owned' },
1710
+ receiptId: failedAdmission.receiptId,
1711
+ outcome: 'failed',
1712
+ result: failedDiagnostic,
1713
+ }),
1714
+ )
1715
+
1716
+ const failedFinalization = SettlementFinalization.make({
1717
+ submissionId: failedAdmission.submissionId,
1718
+ settlementId: submissionSettlementId(failedAdmission.submissionId),
1719
+ })
1720
+
1721
+ const failedSettlement = yield* ledger.finalizeSettlement(failedFinalization)
1722
+
1723
+ yield* ensure(
1724
+ failedSettlement.outcome === 'failed' &&
1725
+ failedSettlement.failure?.errorTag === failedDiagnostic.errorTag &&
1726
+ failedSettlement.failure.message === failedDiagnostic.message,
1727
+ 'Failed finalization must return the exact canonical diagnostic',
1728
+ )
1729
+ yield* TestClock.adjust('1 second')
1730
+ const failedReplay = yield* ledger.finalizeSettlement(failedFinalization)
1731
+
1732
+ yield* ensure(
1733
+ Schema.toEquivalence(Settlement)(failedReplay, failedSettlement),
1734
+ 'Failed finalization replay must retain the diagnostic and original timestamp',
1735
+ )
1736
+ }),
1737
+ )
1738
+
1739
+ const settlementConflicts = conformanceCase(
1740
+ 'adopts the first canonical settlement and rejects a wrong finalization identity',
1741
+ ({ ensure, expectFailure, expectSome }) =>
1742
+ Effect.gen(function*() {
1743
+ const threadId = decodeThreadId('ledger-conformance-settle-conflict')
1744
+ const ledger = yield* SubmissionLedger
1745
+ const admitted = yield* admitReady(threadId, 'conflict-key-1', { work: 'conflict' })
1746
+
1747
+ yield* expectSome('the publication claim', yield* claimLane(threadId))
1748
+
1749
+ const original = yield* publishSettlement(
1750
+ yield* settlementPublication({
1751
+ submissionId: admitted.submissionId,
1752
+ authority: { _tag: 'Owned' },
1753
+ receiptId: admitted.receiptId,
1754
+ outcome: 'completed',
1755
+ result: { attempt: 1 },
1756
+ }),
1757
+ )
1758
+
1759
+ const changedPublication = yield* settlementPublication({
1760
+ submissionId: admitted.submissionId,
1761
+ authority: { _tag: 'Owned' },
1762
+ receiptId: admitted.receiptId,
1763
+ outcome: 'completed',
1764
+ result: { attempt: 2 },
1765
+ })
1766
+
1767
+ const current = yield* expectSome(
1768
+ 'the published Submission',
1769
+ yield* lookupById(admitted.submissionId),
1770
+ )
1771
+
1772
+ if (current.state === 'settled') {
1773
+ yield* ensure(
1774
+ isOwnershipLost(
1775
+ yield* expectFailure(
1776
+ 'changed publication after atomic finalization',
1777
+ publishSettlement(changedPublication),
1778
+ ),
1779
+ ),
1780
+ 'The original token must lose authority when publication atomically finalizes',
1781
+ )
1782
+ } else {
1783
+ const changedContent = yield* publishSettlement(changedPublication)
1784
+
1785
+ yield* ensure(
1786
+ changedContent.replayed && recordEquivalent(changedContent.record, original.record),
1787
+ 'Different authorized candidate content must not replace the immutable canonical record',
1788
+ )
1789
+ }
1790
+
1791
+ const wrongFinalization = yield* expectFailure(
1792
+ 'finalizing another settlement identity',
1793
+ ledger.finalizeSettlement(
1794
+ SettlementFinalization.make({
1795
+ submissionId: admitted.submissionId,
1796
+ settlementId: submissionSettlementId(
1797
+ decodeSubmissionId(`${admitted.submissionId}-other`),
1798
+ ),
1799
+ }),
1800
+ ),
1801
+ )
1802
+
1803
+ yield* ensure(
1804
+ isSettlementConflict(wrongFinalization) &&
1805
+ wrongFinalization.existingOutcome === 'completed',
1806
+ 'A wrong finalization identity must conflict with canonical intent',
1807
+ )
1808
+
1809
+ const settlement = yield* ledger.finalizeSettlement(
1810
+ SettlementFinalization.make({
1811
+ submissionId: admitted.submissionId,
1812
+ settlementId: submissionSettlementId(admitted.submissionId),
1813
+ }),
1814
+ )
1815
+
1816
+ yield* ensure(
1817
+ settlement.outcome === 'completed',
1818
+ 'Finalization must retain the first canonical outcome',
1819
+ )
1820
+ }),
1821
+ )
1822
+
1823
+ const abortIdempotency = conformanceCase(
1824
+ 'records abort intent idempotently and refuses to abort settled work',
1825
+ ({ ensure, expectFailure, expectSome }) =>
1826
+ Effect.gen(function*() {
1827
+ const threadId = decodeThreadId('ledger-conformance-abort')
1828
+ const ledger = yield* SubmissionLedger
1829
+
1830
+ const admitted = yield* ledger.admit(
1831
+ yield* admissionRequest(threadId, 'abort-key-1', { work: 'abort' }),
1832
+ )
1833
+
1834
+ const readRequest = AbortIntentRequest.make({ submissionId: admitted.submissionId })
1835
+
1836
+ yield* ensure(
1837
+ (yield* ledger.readAbortIntent(readRequest)) === undefined,
1838
+ 'An admitted Submission without an abort intent must return undefined',
1839
+ )
1840
+
1841
+ const intent = yield* ledger.requestAbort(
1842
+ AbortCommand.make({
1843
+ submissionId: admitted.submissionId,
1844
+ author: 'conformance-operator',
1845
+ reason: 'first abort request',
1846
+ }),
1847
+ )
1848
+
1849
+ yield* TestClock.adjust('1 second')
1850
+
1851
+ const repeated = yield* ledger.requestAbort(
1852
+ AbortCommand.make({
1853
+ submissionId: admitted.submissionId,
1854
+ author: 'conformance-operator',
1855
+ reason: 'second abort request',
1856
+ }),
1857
+ )
1858
+
1859
+ yield* ensure(
1860
+ repeated.reason === intent.reason &&
1861
+ repeated.author === intent.author &&
1862
+ sameInstant(repeated.requestedAt, intent.requestedAt),
1863
+ 'Repeating an abort command must return the recorded intent unchanged',
1864
+ )
1865
+ const snapshot = yield* recoverySnapshot(admitted.submissionId)
1866
+ const narrow = yield* ledger.readAbortIntent(readRequest)
1867
+
1868
+ yield* ensure(
1869
+ snapshot.abortIntent !== undefined && snapshot.abortIntent.reason === intent.reason,
1870
+ 'The recovery snapshot must expose the recorded abort intent',
1871
+ )
1872
+ yield* ensure(
1873
+ narrow !== undefined &&
1874
+ narrow.submissionId === intent.submissionId &&
1875
+ narrow.author === intent.author &&
1876
+ narrow.reason === intent.reason &&
1877
+ sameInstant(narrow.requestedAt, intent.requestedAt) &&
1878
+ narrow.canonicalRecordId === snapshot.abortIntent?.canonicalRecordId,
1879
+ 'The narrow read must preserve the recorded intent and canonical proof',
1880
+ )
1881
+
1882
+ const unknown = yield* expectFailure(
1883
+ "reading an unknown Submission's abort intent",
1884
+ ledger.readAbortIntent(
1885
+ AbortIntentRequest.make({ submissionId: decodeSubmissionId('unknown-abort-target') }),
1886
+ ),
1887
+ )
1888
+
1889
+ yield* ensure(unknown._tag === 'LedgerError', 'Unknown abort targets must fail typed')
1890
+
1891
+ const settledLane = decodeThreadId('ledger-conformance-abort-settled')
1892
+ const settledWork = yield* admitReady(settledLane, 'abort-key-2', { work: 'settled' })
1893
+
1894
+ const claim = yield* expectSome(
1895
+ 'the claim on the settled lane',
1896
+ yield* claimLane(settledLane),
1897
+ )
1898
+
1899
+ yield* settleClaimed(settledWork, claim.session)
1900
+
1901
+ const terminalAbort = yield* expectFailure(
1902
+ 'aborting a settled Submission',
1903
+ ledger.requestAbort(
1904
+ AbortCommand.make({
1905
+ submissionId: settledWork.submissionId,
1906
+ author: 'conformance-operator',
1907
+ reason: 'too late',
1908
+ }),
1909
+ ),
1910
+ )
1911
+
1912
+ yield* ensure(
1913
+ isSettlementConflict(terminalAbort) && terminalAbort.existingOutcome === 'completed',
1914
+ 'Abort must never rewrite a terminal outcome',
1915
+ )
1916
+ }),
1917
+ )
1918
+
1919
+ const scanNonterminalWorklist = conformanceCase(
1920
+ 'scans exactly the unsettled work in lane order',
1921
+ ({ ensure, expectSome }) =>
1922
+ Effect.gen(function*() {
1923
+ const laneA = decodeThreadId('ledger-conformance-scan-a')
1924
+ const laneB = decodeThreadId('ledger-conformance-scan-b')
1925
+ const ledger = yield* SubmissionLedger
1926
+
1927
+ const first = yield* admitReady(laneA, 'scan-key-1', { step: 1 })
1928
+ const second = yield* admitReady(laneA, 'scan-key-2', { step: 2 })
1929
+ const third = yield* admitReady(laneA, 'scan-key-3', { step: 3 })
1930
+ const settledElsewhere = yield* admitReady(laneB, 'scan-key-4', { step: 4 })
1931
+
1932
+ const firstClaim = yield* expectSome('the claim on the first head', yield* claimLane(laneA))
1933
+
1934
+ yield* settleClaimed(first, firstClaim.session)
1935
+ yield* expectSome('the claim on the second head', yield* claimLane(laneA))
1936
+
1937
+ const otherClaim = yield* expectSome('the claim on the other lane', yield* claimLane(laneB))
1938
+
1939
+ yield* settleClaimed(settledElsewhere, otherClaim.session)
1940
+
1941
+ const scanned = yield* ledger.scanNonterminal.pipe(Stream.runCollect)
1942
+
1943
+ yield* ensure(
1944
+ scanned.every((snapshot) => snapshot.state !== 'settled'),
1945
+ 'scanNonterminal must never emit settled Submissions',
1946
+ )
1947
+
1948
+ const mine = scanned.filter(
1949
+ (snapshot) => snapshot.threadId === laneA || snapshot.threadId === laneB,
1950
+ )
1951
+
1952
+ yield* ensure(
1953
+ mine.length === 2 &&
1954
+ mine.at(0)?.submissionId === second.submissionId &&
1955
+ mine.at(1)?.submissionId === third.submissionId,
1956
+ 'scanNonterminal must emit exactly the unsettled Submissions in queue-sequence order',
1957
+ )
1958
+ yield* ensure(
1959
+ mine.at(0)?.state === 'ready' && mine.at(1)?.state === 'ready',
1960
+ 'scanNonterminal entries must carry the current Submission states',
1961
+ )
1962
+ yield* ensure(
1963
+ mine.at(0)?.receiptId === second.receiptId &&
1964
+ mine.at(1)?.receiptId === third.receiptId &&
1965
+ mine.every(
1966
+ (entry) =>
1967
+ entry.principal === CONFORMANCE_PRINCIPAL &&
1968
+ !('inputPayload' in entry) &&
1969
+ !('workerAdmission' in entry) &&
1970
+ !('messageAdmission' in entry),
1971
+ ),
1972
+ 'The worklist retains receipt and principal identity without execution payloads',
1973
+ )
1974
+ const start = scanned.findIndex((snapshot) => snapshot.submissionId === second.submissionId)
1975
+
1976
+ yield* ensure(
1977
+ start >= 0 && scanned.at(start + 1)?.submissionId === third.submissionId,
1978
+ "One lane's unsettled Submissions must be contiguous in (thread, sequence) order",
1979
+ )
1980
+ }),
1981
+ )
1982
+
1983
+ const lookupByIdAndKey = conformanceCase(
1984
+ 'looks up submissions by identity and scoped idempotency key with strong reads',
1985
+ ({ ensure, expectSome }) =>
1986
+ Effect.gen(function*() {
1987
+ const threadId = decodeThreadId('ledger-conformance-lookup')
1988
+ const ledger = yield* SubmissionLedger
1989
+ const request = yield* admissionRequest(threadId, 'lookup-key-1', { city: 'Kyoto' })
1990
+ const admitted = yield* ledger.admit(request)
1991
+
1992
+ const byId = yield* expectSome(
1993
+ 'lookup by Submission identity',
1994
+ yield* lookupById(admitted.submissionId),
1995
+ )
1996
+
1997
+ yield* ensure(
1998
+ byId.submissionId === admitted.submissionId &&
1999
+ byId.threadId === threadId &&
2000
+ byId.queueSequence === admitted.queueSequence &&
2001
+ byId.principal === request.principal &&
2002
+ byId.idempotencyKey === request.idempotencyKey &&
2003
+ byId.agentId === request.agentId &&
2004
+ byId.deploymentId === request.deploymentId &&
2005
+ byId.inputDigest === request.inputDigest &&
2006
+ byId.receiptId === admitted.receiptId &&
2007
+ byId.state === 'admitted' &&
2008
+ byId.settledOutcome === undefined &&
2009
+ byId.readyAt === undefined,
2010
+ 'Lookup by identity must return the full admission snapshot',
2011
+ )
2012
+
2013
+ const byKey = yield* expectSome(
2014
+ 'lookup by scoped idempotency key',
2015
+ yield* ledger.lookup(
2016
+ SubmissionLookupByKey.make({
2017
+ threadId,
2018
+ principal: request.principal,
2019
+ idempotencyKey: request.idempotencyKey,
2020
+ }),
2021
+ ),
2022
+ )
2023
+
2024
+ yield* ensure(
2025
+ byKey.submissionId === admitted.submissionId,
2026
+ 'Lookup by key must resolve to the same Submission as lookup by identity',
2027
+ )
2028
+
2029
+ yield* ensure(
2030
+ Option.isNone(
2031
+ yield* lookupById(decodeSubmissionId('submission-ledger-conformance-missing')),
2032
+ ),
2033
+ 'Lookup of an unknown Submission identity must return none',
2034
+ )
2035
+ yield* ensure(
2036
+ Option.isNone(
2037
+ yield* ledger.lookup(
2038
+ SubmissionLookupByKey.make({
2039
+ threadId,
2040
+ principal: request.principal,
2041
+ idempotencyKey: decodeIdempotencyKey('lookup-key-missing'),
2042
+ }),
2043
+ ),
2044
+ ),
2045
+ 'Lookup of an unknown idempotency key must return none',
2046
+ )
2047
+ yield* ensure(
2048
+ Option.isNone(
2049
+ yield* ledger.lookup(
2050
+ SubmissionLookupByKey.make({
2051
+ threadId,
2052
+ principal: OTHER_PRINCIPAL,
2053
+ idempotencyKey: request.idempotencyKey,
2054
+ }),
2055
+ ),
2056
+ ),
2057
+ 'Idempotency keys must be scoped to their principal',
2058
+ )
2059
+
2060
+ yield* ledger.markReady(MarkReadyRequest.make({ submissionId: admitted.submissionId }))
2061
+
2062
+ const readyByKey = yield* expectSome(
2063
+ 'lookup by key after readiness',
2064
+ yield* ledger.lookup(
2065
+ SubmissionLookupByKey.make({
2066
+ threadId,
2067
+ principal: request.principal,
2068
+ idempotencyKey: request.idempotencyKey,
2069
+ }),
2070
+ ),
2071
+ )
2072
+
2073
+ yield* ensure(
2074
+ readyByKey.state === 'ready' && readyByKey.readyAt !== undefined,
2075
+ 'Lookups must observe prior writes with strong consistency',
2076
+ )
2077
+ }),
2078
+ )
2079
+
2080
+ const recoverySnapshotConsistency = conformanceCase(
2081
+ 'loads a strongly consistent recovery snapshot without exposing the live token',
2082
+ ({ ensure, expectSome }) =>
2083
+ Effect.gen(function*() {
2084
+ const threadId = decodeThreadId('ledger-conformance-recovery')
2085
+ const ledger = yield* SubmissionLedger
2086
+ const admitted = yield* admitReady(threadId, 'recovery-key-1', { work: 'recovery' })
2087
+
2088
+ const initial = yield* recoverySnapshot(admitted.submissionId)
2089
+
2090
+ yield* ensure(
2091
+ initial.submission.state === 'ready' &&
2092
+ !initial.hasOwner &&
2093
+ initial.inputApplied === undefined &&
2094
+ initial.abortIntent === undefined,
2095
+ 'A ready, unclaimed Submission must have no ownership, marker, or intent',
2096
+ )
2097
+
2098
+ yield* expectSome('the claim before snapshotting', yield* claimLane(threadId))
2099
+
2100
+ const owned = yield* recoverySnapshot(admitted.submissionId)
2101
+
2102
+ yield* ensure(owned.hasOwner, 'The recovery snapshot must expose current local ownership')
2103
+
2104
+ const marker = MarkInputAppliedRequest.make({
2105
+ submissionId: admitted.submissionId,
2106
+
2107
+ recordId: submissionInputRecordId(admitted.submissionId),
2108
+ sequence: decodeSequence(3),
2109
+ })
2110
+
2111
+ yield* ledger.markInputApplied(marker)
2112
+ yield* ledger.requestAbort(
2113
+ AbortCommand.make({
2114
+ submissionId: admitted.submissionId,
2115
+ author: 'conformance-operator',
2116
+ reason: 'abort during recovery case',
2117
+ }),
2118
+ )
2119
+
2120
+ const publication = yield* settlementPublication({
2121
+ submissionId: admitted.submissionId,
2122
+ authority: { _tag: 'Owned' },
2123
+ receiptId: admitted.receiptId,
2124
+ outcome: 'aborted',
2125
+ })
2126
+
2127
+ yield* publishSettlement(publication)
2128
+
2129
+ const published = yield* recoverySnapshot(admitted.submissionId)
2130
+
2131
+ yield* ensure(
2132
+ published.inputApplied !== undefined &&
2133
+ published.inputApplied.recordId === marker.recordId &&
2134
+ published.inputApplied.sequence === marker.sequence,
2135
+ 'The recovery snapshot must expose the applied-input marker',
2136
+ )
2137
+ yield* ensure(
2138
+ published.abortIntent !== undefined &&
2139
+ published.abortIntent.reason === 'abort during recovery case',
2140
+ 'The recovery snapshot must expose the abort intent',
2141
+ )
2142
+
2143
+ const canonical = yield* expectSome(
2144
+ 'canonical settlement before finalization',
2145
+ yield* readSettlementRecord(threadId, admitted.submissionId),
2146
+ )
2147
+
2148
+ yield* ensure(
2149
+ (published.submission.state === 'input-applied' ||
2150
+ (published.submission.state === 'settled' &&
2151
+ published.submission.settledOutcome === 'aborted')) &&
2152
+ recordEquivalent(canonical.record, publication.append.batch.records[0]),
2153
+ 'Recovery must retain input and abort facts whether publication also finalized',
2154
+ )
2155
+
2156
+ yield* ledger.finalizeSettlement(
2157
+ SettlementFinalization.make({
2158
+ submissionId: admitted.submissionId,
2159
+ settlementId: submissionSettlementId(publication.submissionId),
2160
+ }),
2161
+ )
2162
+ const settled = yield* recoverySnapshot(admitted.submissionId)
2163
+
2164
+ yield* ensure(
2165
+ settled.submission.state === 'settled' && settled.submission.settledOutcome === 'aborted',
2166
+ 'After finalization the snapshot must show the canonical settled outcome',
2167
+ )
2168
+ }),
2169
+ )
2170
+
2171
+ const joiningPrefixClaim = conformanceCase(
2172
+ 'claims a contiguous joining prefix and stops at a gap',
2173
+ ({ ensure, expectSome }) =>
2174
+ Effect.gen(function*() {
2175
+ const threadId = decodeThreadId('ledger-conformance-joining-prefix')
2176
+ const ledger = yield* SubmissionLedger
2177
+
2178
+ const host = yield* admitReady(threadId, 'join-prefix-host', { work: 'host' })
2179
+ const second = yield* admitReady(threadId, 'join-prefix-2', { queued: 2 })
2180
+ const third = yield* admitReady(threadId, 'join-prefix-3', { queued: 3 })
2181
+
2182
+ // Admitted but never marked ready: the gap that breaks the contiguous prefix.
2183
+ const fourth = yield* ledger.admit(
2184
+ yield* admissionRequest(threadId, 'join-prefix-4', { queued: 4 }),
2185
+ )
2186
+
2187
+ const fifth = yield* admitReady(threadId, 'join-prefix-5', { queued: 5 })
2188
+
2189
+ const hostClaim = yield* expectSome('the host claim', yield* claimLane(threadId))
2190
+
2191
+ yield* ensure(
2192
+ hostClaim.submissionId === host.submissionId,
2193
+ 'The host must head the lane before joining later work',
2194
+ )
2195
+
2196
+ const first = yield* hostClaim.session.claimJoining(1)
2197
+
2198
+ yield* ensure(
2199
+ first.length === 1 &&
2200
+ first[0].submissionId === second.submissionId &&
2201
+ first[0].queueSequence === second.queueSequence &&
2202
+ persistedJsonEquivalent(first[0].inputPayload, { queued: 2 }),
2203
+ 'maxCount must bound the claim to exactly the next queued Submission with its input',
2204
+ )
2205
+
2206
+ const rest = yield* hostClaim.session.claimJoining(8)
2207
+
2208
+ yield* ensure(
2209
+ rest.length === 1 && rest[0].submissionId === third.submissionId,
2210
+ 'A repeated claim must skip already-joining rows and stop at the admitted gap',
2211
+ )
2212
+
2213
+ const blocked = yield* hostClaim.session.claimJoining(8)
2214
+
2215
+ yield* ensure(
2216
+ blocked.length === 0,
2217
+ 'An admitted-not-ready row must break the contiguous prefix and hide later ready work',
2218
+ )
2219
+
2220
+ const secondState = yield* expectSome(
2221
+ 'lookup of a claimed joining Submission',
2222
+ yield* lookupById(second.submissionId),
2223
+ )
2224
+
2225
+ const fourthState = yield* expectSome(
2226
+ 'lookup of the gap Submission',
2227
+ yield* lookupById(fourth.submissionId),
2228
+ )
2229
+
2230
+ const fifthState = yield* expectSome(
2231
+ 'lookup of the ready Submission after the gap',
2232
+ yield* lookupById(fifth.submissionId),
2233
+ )
2234
+
2235
+ yield* ensure(
2236
+ secondState.state === 'joining' &&
2237
+ fourthState.state === 'admitted' &&
2238
+ fifthState.state === 'ready',
2239
+ 'Claiming must transition exactly the claimed prefix to joining',
2240
+ )
2241
+
2242
+ const hostSnapshot = yield* recoverySnapshot(host.submissionId)
2243
+
2244
+ yield* ensure(
2245
+ hostSnapshot.joins.length === 2 &&
2246
+ hostSnapshot.joins[0].submissionId === second.submissionId &&
2247
+ hostSnapshot.joins[0].state === 'joining' &&
2248
+ hostSnapshot.joins[0].hostSubmissionId === host.submissionId &&
2249
+ hostSnapshot.joins[1].submissionId === third.submissionId,
2250
+ 'The host recovery snapshot must expose the claimed prefix in queue order',
2251
+ )
2252
+ const joinedSide = yield* recoverySnapshot(second.submissionId)
2253
+
2254
+ yield* ensure(
2255
+ joinedSide.hostSubmissionId === host.submissionId,
2256
+ "A joining Submission's recovery snapshot must expose its host linkage",
2257
+ )
2258
+
2259
+ yield* ledger.markReady(MarkReadyRequest.make({ submissionId: fourth.submissionId }))
2260
+
2261
+ const afterGap = yield* hostClaim.session.claimJoining(8)
2262
+
2263
+ yield* ensure(
2264
+ afterGap.length === 2 &&
2265
+ afterGap[0].submissionId === fourth.submissionId &&
2266
+ afterGap[1].submissionId === fifth.submissionId,
2267
+ 'Once the gap closes, the claim must extend past already-claimed rows in queue order',
2268
+ )
2269
+ }),
2270
+ )
2271
+
2272
+ const revertJoiningReturnsToReady = conformanceCase(
2273
+ 'revertJoining returns exactly the pre-append claims to ready',
2274
+ ({ ensure, expectFailure, expectSome }) =>
2275
+ Effect.gen(function*() {
2276
+ const threadId = decodeThreadId('ledger-conformance-revert-joining')
2277
+ const ledger = yield* SubmissionLedger
2278
+
2279
+ const host = yield* admitReady(threadId, 'revert-host', { work: 'host' })
2280
+ const second = yield* admitReady(threadId, 'revert-2', { queued: 2 })
2281
+ const third = yield* admitReady(threadId, 'revert-3', { queued: 3 })
2282
+ const hostClaim = yield* expectSome('the host claim', yield* claimLane(threadId))
2283
+
2284
+ const claims = yield* hostClaim.session.claimJoining(8)
2285
+
2286
+ yield* ensure(claims.length === 2, "Both queued Submissions must join the host's prefix")
2287
+
2288
+ // Regression in the unguarded recovery mutation (161aab335): a stale recovery view
2289
+ // must not clear a join still owned by the live host or a successor Attempt.
2290
+ yield* ledger.revertJoining(
2291
+ RevertJoiningRequest.make({
2292
+ submissionId: second.submissionId,
2293
+ guard: { hostSubmissionId: third.submissionId },
2294
+ }),
2295
+ )
2296
+ const unchangedHost = yield* recoverySnapshot(second.submissionId)
2297
+
2298
+ yield* ensure(
2299
+ unchangedHost.submission.state === 'joining' &&
2300
+ unchangedHost.hostSubmissionId === host.submissionId,
2301
+ 'A different guarded host must leave the current join unchanged',
2302
+ )
2303
+
2304
+ yield* hostClaim.session.release
2305
+
2306
+ const currentHostClaim = yield* expectSome(
2307
+ 'the successor host claim',
2308
+ yield* claimLane(threadId),
2309
+ )
2310
+
2311
+ const staleOwner = yield* expectFailure(
2312
+ 'reverting a join with the superseded host generation',
2313
+ hostClaim.session.revertJoining(second.submissionId),
2314
+ )
2315
+
2316
+ yield* ensure(isOwnershipLost(staleOwner), 'A superseded owner must not clear the join')
2317
+ const unchangedOwner = yield* recoverySnapshot(second.submissionId)
2318
+
2319
+ yield* ensure(
2320
+ unchangedOwner.submission.state === 'joining' &&
2321
+ unchangedOwner.hostSubmissionId === host.submissionId,
2322
+ "Rejected recovery must retain the live host's joining state and linkage",
2323
+ )
2324
+
2325
+ // third's canonical input is appended; second's never is.
2326
+ yield* currentHostClaim.session.markJoined(third.submissionId, {
2327
+ recordId: submissionInputRecordId(third.submissionId),
2328
+ sequence: decodeSequence(7),
2329
+ })
2330
+
2331
+ yield* currentHostClaim.session.revertJoining(second.submissionId)
2332
+
2333
+ const reverted = yield* expectSome(
2334
+ 'lookup after revert',
2335
+ yield* lookupById(second.submissionId),
2336
+ )
2337
+
2338
+ yield* ensure(
2339
+ reverted.state === 'ready',
2340
+ 'Reverting a pre-append joining Submission must return it to ready',
2341
+ )
2342
+ const revertedSnapshot = yield* recoverySnapshot(second.submissionId)
2343
+
2344
+ yield* ensure(
2345
+ revertedSnapshot.hostSubmissionId === undefined,
2346
+ 'Reverting must clear the host linkage',
2347
+ )
2348
+ const hostSnapshot = yield* recoverySnapshot(host.submissionId)
2349
+
2350
+ yield* ensure(
2351
+ hostSnapshot.joins.length === 1 &&
2352
+ hostSnapshot.joins[0].submissionId === third.submissionId &&
2353
+ hostSnapshot.joins[0].state === 'joined',
2354
+ "The reverted Submission must leave the host's join view",
2355
+ )
2356
+
2357
+ yield* ledger.revertJoining(RevertJoiningRequest.make({ submissionId: second.submissionId }))
2358
+
2359
+ const stillReady = yield* expectSome(
2360
+ 'lookup after repeating the revert',
2361
+ yield* lookupById(second.submissionId),
2362
+ )
2363
+
2364
+ yield* ensure(stillReady.state === 'ready', 'Repeating revertJoining must be a no-op')
2365
+
2366
+ // A post-append joined Submission must NOT revert (DUR-016: it reattaches instead).
2367
+ yield* ledger.revertJoining(RevertJoiningRequest.make({ submissionId: third.submissionId }))
2368
+
2369
+ const joined = yield* expectSome(
2370
+ 'lookup of the joined Submission after an attempted revert',
2371
+ yield* lookupById(third.submissionId),
2372
+ )
2373
+
2374
+ yield* ensure(
2375
+ joined.state === 'joined',
2376
+ 'revertJoining must be a no-op for an already-joined Submission',
2377
+ )
2378
+
2379
+ const reclaimed = yield* currentHostClaim.session.claimJoining(8)
2380
+
2381
+ yield* ensure(
2382
+ reclaimed.length === 1 && reclaimed[0].submissionId === second.submissionId,
2383
+ 'A reverted Submission must be claimable again exactly once',
2384
+ )
2385
+ yield* settleClaimed(host, currentHostClaim.session)
2386
+ yield* ledger.revertJoining(
2387
+ RevertJoiningRequest.make({
2388
+ submissionId: second.submissionId,
2389
+ guard: { hostSubmissionId: host.submissionId },
2390
+ }),
2391
+ )
2392
+ const afterSettlement = yield* recoverySnapshot(second.submissionId)
2393
+
2394
+ yield* ensure(
2395
+ afterSettlement.submission.state === 'ready' &&
2396
+ afterSettlement.hostSubmissionId === undefined,
2397
+ 'The exact settled host must permit administrative cleanup of its uncommitted join',
2398
+ )
2399
+ }),
2400
+ )
2401
+
2402
+ const markJoinedIdempotency = conformanceCase(
2403
+ 'markJoined is idempotent and repairable from history',
2404
+ ({ ensure, expectFailure, expectSome }) =>
2405
+ Effect.gen(function*() {
2406
+ const threadId = decodeThreadId('ledger-conformance-mark-joined')
2407
+ const ledger = yield* SubmissionLedger
2408
+
2409
+ const host = yield* admitReady(threadId, 'mark-joined-host', { work: 'host' })
2410
+ const second = yield* admitReady(threadId, 'mark-joined-2', { queued: 2 })
2411
+ const third = yield* admitReady(threadId, 'mark-joined-3', { queued: 3 })
2412
+ const hostClaim = yield* expectSome('the host claim', yield* claimLane(threadId))
2413
+
2414
+ yield* hostClaim.session.claimJoining(8)
2415
+
2416
+ const marker = MarkJoinedRequest.make({
2417
+ submissionId: second.submissionId,
2418
+
2419
+ recordId: submissionInputRecordId(second.submissionId),
2420
+ sequence: decodeSequence(4),
2421
+ })
2422
+
2423
+ yield* ledger.markJoined(marker)
2424
+
2425
+ const joined = yield* expectSome(
2426
+ 'lookup after marking joined',
2427
+ yield* lookupById(second.submissionId),
2428
+ )
2429
+
2430
+ yield* ensure(
2431
+ joined.state === 'joined',
2432
+ 'Marking the canonical input position must transition joining to joined',
2433
+ )
2434
+
2435
+ yield* ledger.markJoined(marker)
2436
+ const snapshot = yield* recoverySnapshot(second.submissionId)
2437
+
2438
+ yield* ensure(
2439
+ snapshot.submission.state === 'joined' &&
2440
+ snapshot.hostSubmissionId === host.submissionId &&
2441
+ snapshot.inputApplied !== undefined &&
2442
+ snapshot.inputApplied.recordId === marker.recordId &&
2443
+ snapshot.inputApplied.sequence === marker.sequence,
2444
+ 'Repeating the identical join marker must be a no-op with the marker retained',
2445
+ )
2446
+
2447
+ const divergent = yield* expectFailure(
2448
+ 're-marking with a different canonical position',
2449
+ hostClaim.session.markJoined(second.submissionId, {
2450
+ recordId: marker.recordId,
2451
+ sequence: decodeSequence(5),
2452
+ }),
2453
+ )
2454
+
2455
+ yield* ensure(
2456
+ !isOwnershipLost(divergent),
2457
+ 'A divergent join marker must fail as a ledger integrity error, not ownership loss',
2458
+ )
2459
+
2460
+ // Repairable from history: the host Attempt dies and a later host Attempt repairs the
2461
+ // lost marker under its fresh local generation (DUR-016).
2462
+ yield* hostClaim.session.release
2463
+
2464
+ const reclaim = yield* expectSome(
2465
+ 'the host reclaim after release',
2466
+ yield* claimLane(threadId),
2467
+ )
2468
+
2469
+ yield* ensure(
2470
+ reclaim.submissionId === host.submissionId &&
2471
+ reclaim.session.generation !== hostClaim.session.generation,
2472
+ 'The host must be reclaimable while its joined work is pending',
2473
+ )
2474
+
2475
+ const superseded = yield* expectFailure(
2476
+ 'repairing the marker with the superseded host generation',
2477
+ hostClaim.session.markJoined(third.submissionId, {
2478
+ recordId: submissionInputRecordId(third.submissionId),
2479
+ sequence: decodeSequence(6),
2480
+ }),
2481
+ )
2482
+
2483
+ yield* ensure(
2484
+ isOwnershipLost(superseded),
2485
+ 'A superseded host generation must not repair a join marker',
2486
+ )
2487
+ yield* reclaim.session.markJoined(third.submissionId, {
2488
+ recordId: submissionInputRecordId(third.submissionId),
2489
+ sequence: decodeSequence(6),
2490
+ })
2491
+
2492
+ const repaired = yield* expectSome(
2493
+ 'lookup after the repair',
2494
+ yield* lookupById(third.submissionId),
2495
+ )
2496
+
2497
+ yield* ensure(
2498
+ repaired.state === 'joined',
2499
+ 'A later host Attempt must repair the lost join marker from history',
2500
+ )
2501
+ }),
2502
+ )
2503
+
2504
+ const claimNeverGrantsBlockedHead = conformanceCase(
2505
+ 'claim never grants a suspended, unknown, joining, or joined head',
2506
+ ({ ensure, expectFailure, expectSome }) =>
2507
+ Effect.gen(function*() {
2508
+ const ledger = yield* SubmissionLedger
2509
+
2510
+ // joining head: the host settled while a claimed-but-unappended join was pending.
2511
+ const joiningLane = decodeThreadId('ledger-conformance-head-joining')
2512
+ const joiningHost = yield* admitReady(joiningLane, 'head-joining-host', { work: 'host' })
2513
+ const joiningSub = yield* admitReady(joiningLane, 'head-joining-2', { queued: 2 })
2514
+
2515
+ yield* admitReady(joiningLane, 'head-joining-3', { queued: 3 })
2516
+
2517
+ const joiningHostClaim = yield* expectSome(
2518
+ "the joining lane's host claim",
2519
+ yield* claimLane(joiningLane),
2520
+ )
2521
+
2522
+ yield* joiningHostClaim.session.claimJoining(1)
2523
+ yield* settleClaimed(joiningHost, joiningHostClaim.session)
2524
+ yield* ensure(
2525
+ Option.isNone(yield* claimLane(joiningLane)),
2526
+ 'A joining head must block the lane; later ready work is never skipped past it',
2527
+ )
2528
+ yield* ledger.revertJoining(
2529
+ RevertJoiningRequest.make({ submissionId: joiningSub.submissionId }),
2530
+ )
2531
+
2532
+ const afterRevert = yield* expectSome(
2533
+ 'the claim after reverting the joining head',
2534
+ yield* claimLane(joiningLane),
2535
+ )
2536
+
2537
+ yield* ensure(
2538
+ afterRevert.submissionId === joiningSub.submissionId,
2539
+ 'Reverting the joining head must make it claimable in FIFO order',
2540
+ )
2541
+
2542
+ // joined head: the host settled between its finalization and the joined settlement.
2543
+ const joinedLane = decodeThreadId('ledger-conformance-head-joined')
2544
+ const joinedHost = yield* admitReady(joinedLane, 'head-joined-host', { work: 'host' })
2545
+ const joinedSub = yield* admitReady(joinedLane, 'head-joined-2', { queued: 2 })
2546
+
2547
+ const joinedHostClaim = yield* expectSome(
2548
+ "the joined lane's host claim",
2549
+ yield* claimLane(joinedLane),
2550
+ )
2551
+
2552
+ yield* joinedHostClaim.session.claimJoining(1)
2553
+ yield* joinedHostClaim.session.markJoined(joinedSub.submissionId, {
2554
+ recordId: submissionInputRecordId(joinedSub.submissionId),
2555
+ sequence: decodeSequence(3),
2556
+ })
2557
+
2558
+ const joinedAbort = yield* expectFailure(
2559
+ 'aborting a joined Submission',
2560
+ ledger.requestAbort(
2561
+ AbortCommand.make({
2562
+ submissionId: joinedSub.submissionId,
2563
+ author: 'conformance-operator',
2564
+ reason: 'joined abort target',
2565
+ }),
2566
+ ),
2567
+ )
2568
+
2569
+ yield* ensure(
2570
+ isJoinedToHost(joinedAbort) && joinedAbort.hostSubmissionId === joinedHost.submissionId,
2571
+ 'Abort of a joined Submission must fail with the host linkage — the abort target is the host',
2572
+ )
2573
+ yield* settleClaimed(joinedHost, joinedHostClaim.session)
2574
+ yield* ensure(
2575
+ Option.isNone(yield* claimLane(joinedLane)),
2576
+ 'A joined head must block the lane; it settles with the host, never with a worker claim',
2577
+ )
2578
+
2579
+ // suspended head: durable approval waiting consumes no worker permit.
2580
+ const suspendedLane = decodeThreadId('ledger-conformance-head-suspended')
2581
+
2582
+ const suspendedHost = yield* admitReady(suspendedLane, 'head-suspended-host', {
2583
+ work: 'host',
2584
+ })
2585
+
2586
+ const suspendedClaim = yield* expectSome(
2587
+ "the suspended lane's claim",
2588
+ yield* claimLane(suspendedLane),
2589
+ )
2590
+
2591
+ const gatedCall = decodeToolCallId('call-head-suspended')
2592
+
2593
+ const suspendOutcome = yield* suspendedClaim.session.suspend(
2594
+ ApprovalPendingSuspension.make({ toolCallIds: [gatedCall] }),
2595
+ )
2596
+
2597
+ yield* ensure(suspendOutcome === 'suspended', 'An undecided approval must suspend durably')
2598
+ yield* ensure(
2599
+ Option.isNone(yield* claimLane(suspendedLane)),
2600
+ 'A suspended head must produce no claim',
2601
+ )
2602
+ yield* ledger.recordApprovalDecision(
2603
+ ApprovalDecisionCommand.make({
2604
+ submissionId: suspendedHost.submissionId,
2605
+ toolCallId: gatedCall,
2606
+ decision: 'approved',
2607
+ resolver: 'conformance-approver',
2608
+ reason: 'unblock the suspended head',
2609
+ }),
2610
+ )
2611
+
2612
+ const wokenClaim = yield* expectSome(
2613
+ 'the claim after the covering decision',
2614
+ yield* claimLane(suspendedLane),
2615
+ )
2616
+
2617
+ yield* ensure(
2618
+ wokenClaim.submissionId === suspendedHost.submissionId &&
2619
+ wokenClaim.session.generation !== suspendedClaim.session.generation,
2620
+ 'A covering decision must wake the lane for a fresh fenced Attempt',
2621
+ )
2622
+
2623
+ // unknown head: the DUR-017 blocked lane outlives owner disposal.
2624
+ const unknownLane = decodeThreadId('ledger-conformance-head-unknown')
2625
+ const unknownHost = yield* admitReady(unknownLane, 'head-unknown-host', { work: 'host' })
2626
+
2627
+ const unknownClaim = yield* expectSome(
2628
+ "the unknown lane's claim",
2629
+ yield* claimLane(unknownLane),
2630
+ )
2631
+
2632
+ const unknownCall = decodeToolCallId('call-head-unknown')
2633
+
2634
+ yield* ledger.markUnknown(
2635
+ MarkUnknownRequest.make({
2636
+ submissionId: unknownHost.submissionId,
2637
+ toolCallIds: [unknownCall],
2638
+ reason: 'an ordinary call may have executed',
2639
+ }),
2640
+ )
2641
+ yield* unknownClaim.session.release
2642
+ yield* ensure(
2643
+ Option.isNone(yield* claimLane(unknownLane)),
2644
+ 'An unknown head must stay blocked even after the former owner closes',
2645
+ )
2646
+ yield* ledger.recordUnknownResolution(
2647
+ UnknownResolutionCommand.make({
2648
+ submissionId: unknownHost.submissionId,
2649
+ toolCallId: unknownCall,
2650
+ author: 'conformance-operator',
2651
+ reason: 'supplier store shows no effect',
2652
+ resolution: ResolutionNeverHappened.make(),
2653
+ }),
2654
+ )
2655
+
2656
+ const reopened = yield* expectSome(
2657
+ 'the claim after the covering resolution',
2658
+ yield* claimLane(unknownLane),
2659
+ )
2660
+
2661
+ yield* ensure(
2662
+ reopened.submissionId === unknownHost.submissionId,
2663
+ 'A covering resolution must reopen the blocked lane',
2664
+ )
2665
+ }),
2666
+ )
2667
+
2668
+ const approvalDecisionIdempotency = conformanceCase(
2669
+ 'approval decisions are idempotent and conflict on divergence',
2670
+ ({ ensure, expectFailure, expectSome }) =>
2671
+ Effect.gen(function*() {
2672
+ const threadId = decodeThreadId('ledger-conformance-approval')
2673
+ const ledger = yield* SubmissionLedger
2674
+ const admitted = yield* admitReady(threadId, 'approval-key-1', { work: 'approve' })
2675
+
2676
+ const claim = yield* expectSome('the claim before decisions', yield* claimLane(threadId))
2677
+
2678
+ const callA = decodeToolCallId('call-approval-a')
2679
+ const callB = decodeToolCallId('call-approval-b')
2680
+
2681
+ const first = yield* ledger.recordApprovalDecision(
2682
+ ApprovalDecisionCommand.make({
2683
+ submissionId: admitted.submissionId,
2684
+ toolCallId: callA,
2685
+ decision: 'approved',
2686
+ resolver: 'conformance-approver',
2687
+ reason: 'policy allows the booking',
2688
+ }),
2689
+ )
2690
+
2691
+ yield* ensure(
2692
+ first.decision === 'approved' && first.toolCallId === callA,
2693
+ 'The first decision must record the intent',
2694
+ )
2695
+
2696
+ yield* TestClock.adjust('1 second')
2697
+
2698
+ const replayed = yield* ledger.recordApprovalDecision(
2699
+ ApprovalDecisionCommand.make({
2700
+ submissionId: admitted.submissionId,
2701
+ toolCallId: callA,
2702
+ decision: 'approved',
2703
+ resolver: 'conformance-approver-second',
2704
+ reason: 'a different reason text',
2705
+ }),
2706
+ )
2707
+
2708
+ yield* ensure(
2709
+ replayed.reason === first.reason &&
2710
+ replayed.resolver === first.resolver &&
2711
+ sameInstant(replayed.decidedAt, first.decidedAt),
2712
+ 'Repeating the same decision must replay the recorded intent unchanged',
2713
+ )
2714
+
2715
+ const conflict = yield* expectFailure(
2716
+ 're-deciding the same call divergently',
2717
+ ledger.recordApprovalDecision(
2718
+ ApprovalDecisionCommand.make({
2719
+ submissionId: admitted.submissionId,
2720
+ toolCallId: callA,
2721
+ decision: 'denied',
2722
+ resolver: 'conformance-approver',
2723
+ reason: 'changed my mind',
2724
+ }),
2725
+ ),
2726
+ )
2727
+
2728
+ yield* ensure(
2729
+ isApprovalConflict(conflict) &&
2730
+ conflict.toolCallId === callA &&
2731
+ conflict.existingDecision === 'approved',
2732
+ 'A divergent re-decision must conflict with the recorded decision',
2733
+ )
2734
+
2735
+ yield* ledger.recordApprovalDecision(
2736
+ ApprovalDecisionCommand.make({
2737
+ submissionId: admitted.submissionId,
2738
+ toolCallId: callB,
2739
+ decision: 'denied',
2740
+ resolver: 'conformance-approver',
2741
+ reason: 'policy denies the cancellation',
2742
+ }),
2743
+ )
2744
+ const snapshot = yield* recoverySnapshot(admitted.submissionId)
2745
+
2746
+ yield* ensure(
2747
+ snapshot.approvalDecisions.length === 2 &&
2748
+ snapshot.approvalDecisions.some(
2749
+ (intent) => intent.toolCallId === callA && intent.decision === 'approved',
2750
+ ) &&
2751
+ snapshot.approvalDecisions.some(
2752
+ (intent) => intent.toolCallId === callB && intent.decision === 'denied',
2753
+ ),
2754
+ 'The recovery snapshot must expose every recorded decision intent',
2755
+ )
2756
+
2757
+ yield* settleClaimed(admitted, claim.session)
2758
+
2759
+ const late = yield* expectFailure(
2760
+ 'deciding an approval for a settled Submission',
2761
+ ledger.recordApprovalDecision(
2762
+ ApprovalDecisionCommand.make({
2763
+ submissionId: admitted.submissionId,
2764
+ toolCallId: decodeToolCallId('call-approval-late'),
2765
+ decision: 'approved',
2766
+ resolver: 'conformance-approver',
2767
+ reason: 'too late',
2768
+ }),
2769
+ ),
2770
+ )
2771
+
2772
+ yield* ensure(
2773
+ isSettlementConflict(late) && late.existingOutcome === 'completed',
2774
+ 'A decision must never land on a settled Submission',
2775
+ )
2776
+ }),
2777
+ )
2778
+
2779
+ const unknownAbortClaim = conformanceCase(
2780
+ 'a durable abort makes an unknown head claimable without resolving or replaying its calls',
2781
+ ({ ensure, expectFailure, expectSome }) =>
2782
+ Effect.gen(function*() {
2783
+ const ledger = yield* SubmissionLedger
2784
+
2785
+ for (const abortFirst of [false, true]) {
2786
+ const threadId = decodeThreadId(`ledger-conformance-unknown-abort-${abortFirst}`)
2787
+ const head = yield* admitReady(threadId, 'head', { work: 'uncertain' })
2788
+
2789
+ const original = yield* expectSome('original claim', yield* claimLane(threadId))
2790
+
2791
+ const follower = yield* admitReady(threadId, 'follower', { work: 'later' })
2792
+
2793
+ const command = AbortCommand.make({
2794
+ submissionId: head.submissionId,
2795
+ author: 'first-operator',
2796
+ reason: 'stop without asserting external rollback',
2797
+ })
2798
+
2799
+ if (abortFirst) yield* ledger.requestAbort(command)
2800
+ yield* ledger.markUnknown(
2801
+ MarkUnknownRequest.make({
2802
+ submissionId: head.submissionId,
2803
+ toolCallIds: [decodeToolCallId('uncertain-one'), decodeToolCallId('uncertain-two')],
2804
+ reason: 'external replies were lost',
2805
+ }),
2806
+ )
2807
+ if (abortFirst) {
2808
+ yield* ensure(
2809
+ Option.isNone(yield* claimLane(threadId)),
2810
+ 'Abort must not bypass a still-live owner scope',
2811
+ )
2812
+ }
2813
+ yield* original.session.release
2814
+ if (!abortFirst) {
2815
+ const later = yield* expectSome(
2816
+ 'runnable follower behind unknown work',
2817
+ yield* claimLane(threadId),
2818
+ )
2819
+
2820
+ yield* ensure(
2821
+ later.submissionId === follower.submissionId,
2822
+ 'Unknown work must preserve the queue order of runnable followers',
2823
+ )
2824
+ yield* later.session.release
2825
+ }
2826
+ const intent = yield* ledger.requestAbort(command)
2827
+
2828
+ const duplicate = yield* ledger.requestAbort(
2829
+ AbortCommand.make({
2830
+ ...command,
2831
+ author: 'later-operator',
2832
+ reason: 'lost acknowledgement retry',
2833
+ }),
2834
+ )
2835
+
2836
+ yield* ensure(
2837
+ duplicate.author === intent.author &&
2838
+ duplicate.reason === intent.reason &&
2839
+ sameInstant(duplicate.requestedAt, intent.requestedAt),
2840
+ 'The first abort audit must win',
2841
+ )
2842
+
2843
+ const reclaimed = yield* expectSome(
2844
+ 'unknown head with durable abort',
2845
+ yield* claimLane(threadId),
2846
+ )
2847
+
2848
+ yield* ensure(
2849
+ reclaimed.submissionId === head.submissionId &&
2850
+ reclaimed.session.generation !== original.session.generation,
2851
+ 'Abort must claim the head with a fresh fence, never skip to its follower',
2852
+ )
2853
+ const snapshot = yield* recoverySnapshot(head.submissionId)
2854
+
2855
+ yield* ensure(
2856
+ snapshot.submission.state === 'unknown' && snapshot.unknownResolutions.length === 0,
2857
+ 'Claiming for abort must not erase uncertainty or manufacture tool resolutions',
2858
+ )
2859
+
2860
+ const stale = yield* expectFailure(
2861
+ 'stale owner',
2862
+ original.session.publishSettlement(
2863
+ yield* Schema.decodeUnknownEffect(Schema.toType(Schema.Struct(CanonicalBatch.fields)))(
2864
+ (yield* settlementPublication({
2865
+ ...head,
2866
+ authority: { _tag: 'Owned' },
2867
+ outcome: 'completed',
2868
+ })).append.batch,
2869
+ ).pipe(
2870
+ Effect.map((value) => CanonicalBatch.make(value)),
2871
+ Effect.orDie,
2872
+ ),
2873
+ ),
2874
+ )
2875
+
2876
+ yield* ensure(isOwnershipLost(stale), 'The original owner must remain fenced')
2877
+
2878
+ const publication = yield* settlementPublication({
2879
+ ...head,
2880
+ authority: { _tag: 'Owned' },
2881
+ outcome: 'aborted',
2882
+ })
2883
+
2884
+ yield* publishSettlement(publication)
2885
+
2886
+ const afterPublication = yield* expectSome(
2887
+ 'aborted submission after publication',
2888
+ yield* lookupById(head.submissionId),
2889
+ )
2890
+
2891
+ if (afterPublication.state === 'settled') {
2892
+ const duplicate = yield* expectFailure(
2893
+ 'abort after atomic finalization',
2894
+ ledger.requestAbort(command),
2895
+ )
2896
+
2897
+ yield* ensure(
2898
+ isSettlementConflict(duplicate) && duplicate.existingOutcome === 'aborted',
2899
+ 'Atomic finalization must retain the aborted outcome',
2900
+ )
2901
+ } else yield* ledger.requestAbort(command)
2902
+
2903
+ const settled = yield* ledger.finalizeSettlement(
2904
+ SettlementFinalization.make({
2905
+ submissionId: publication.submissionId,
2906
+ settlementId: submissionSettlementId(publication.submissionId),
2907
+ }),
2908
+ )
2909
+
2910
+ yield* ensure(
2911
+ settled.outcome === 'aborted',
2912
+ 'The abort publication must survive a duplicate command',
2913
+ )
2914
+ const late = yield* expectFailure('abort after settlement', ledger.requestAbort(command))
2915
+
2916
+ yield* ensure(
2917
+ isSettlementConflict(late) && late.existingOutcome === 'aborted',
2918
+ 'A terminal outcome must not change',
2919
+ )
2920
+ const next = yield* expectSome('follower claim', yield* claimLane(threadId))
2921
+
2922
+ yield* ensure(
2923
+ next.submissionId === follower.submissionId,
2924
+ 'Settlement must release the follower',
2925
+ )
2926
+ }
2927
+ }),
2928
+ )
2929
+
2930
+ const unknownResolutionLifecycle = conformanceCase(
2931
+ 'unknown resolutions reopen the lane only when no open call remains',
2932
+ ({ ensure, expectFailure, expectSome }) =>
2933
+ Effect.gen(function*() {
2934
+ const threadId = decodeThreadId('ledger-conformance-unknown')
2935
+ const ledger = yield* SubmissionLedger
2936
+ const admitted = yield* admitReady(threadId, 'unknown-key-1', { work: 'unknown' })
2937
+
2938
+ const claim = yield* expectSome(
2939
+ 'the claim before the unknown marking',
2940
+ yield* claimLane(threadId),
2941
+ )
2942
+
2943
+ const call1 = decodeToolCallId('call-unknown-1')
2944
+ const call2 = decodeToolCallId('call-unknown-2')
2945
+ const call3 = decodeToolCallId('call-unknown-3')
2946
+
2947
+ const marking = MarkUnknownRequest.make({
2948
+ submissionId: admitted.submissionId,
2949
+ toolCallIds: [call1, call2],
2950
+ reason: 'the worker died during two supplier calls',
2951
+ })
2952
+
2953
+ yield* ledger.markUnknown(marking)
2954
+ yield* ledger.markUnknown(marking)
2955
+
2956
+ const marked = yield* expectSome(
2957
+ 'lookup after marking unknown',
2958
+ yield* lookupById(admitted.submissionId),
2959
+ )
2960
+
2961
+ yield* ensure(
2962
+ marked.state === 'unknown',
2963
+ 'Marking unknown must be idempotent and block the lane',
2964
+ )
2965
+
2966
+ yield* claim.session.release
2967
+ yield* ensure(
2968
+ Option.isNone(yield* claimLane(threadId)),
2969
+ 'An unknown lane must consume no worker permit',
2970
+ )
2971
+
2972
+ const first = yield* ledger.recordUnknownResolution(
2973
+ UnknownResolutionCommand.make({
2974
+ submissionId: admitted.submissionId,
2975
+ toolCallId: call1,
2976
+ author: 'conformance-operator',
2977
+ reason: 'supplier store shows no booking',
2978
+ resolution: ResolutionNeverHappened.make(),
2979
+ }),
2980
+ )
2981
+
2982
+ const partiallyResolved = yield* expectSome(
2983
+ 'lookup after a partial resolution',
2984
+ yield* lookupById(admitted.submissionId),
2985
+ )
2986
+
2987
+ yield* ensure(
2988
+ partiallyResolved.state === 'unknown' && Option.isNone(yield* claimLane(threadId)),
2989
+ 'A partial resolution must keep the lane blocked while calls remain open',
2990
+ )
2991
+
2992
+ yield* TestClock.adjust('1 second')
2993
+
2994
+ const divergent = yield* expectFailure(
2995
+ 're-resolving the same call divergently',
2996
+ ledger.recordUnknownResolution(
2997
+ UnknownResolutionCommand.make({
2998
+ submissionId: admitted.submissionId,
2999
+ toolCallId: call1,
3000
+ author: 'conformance-operator',
3001
+ reason: 'changed my mind',
3002
+ resolution: ResolutionSafeToRetry.make(),
3003
+ }),
3004
+ ),
3005
+ )
3006
+
3007
+ yield* ensure(
3008
+ isUnknownResolutionConflict(divergent) && divergent.toolCallId === call1,
3009
+ 'A divergent re-resolution must conflict',
3010
+ )
3011
+
3012
+ const replayed = yield* ledger.recordUnknownResolution(
3013
+ UnknownResolutionCommand.make({
3014
+ submissionId: admitted.submissionId,
3015
+ toolCallId: call1,
3016
+ author: 'conformance-operator-second',
3017
+ reason: 'a different reason text',
3018
+ resolution: ResolutionNeverHappened.make(),
3019
+ }),
3020
+ )
3021
+
3022
+ yield* ensure(
3023
+ sameInstant(replayed.resolvedAt, first.resolvedAt) && replayed.reason === first.reason,
3024
+ 'Repeating the same resolution must replay the recorded intent unchanged',
3025
+ )
3026
+
3027
+ // A later marking extends the open set; the lane must not reopen until it is covered too.
3028
+ yield* ledger.markUnknown(
3029
+ MarkUnknownRequest.make({
3030
+ submissionId: admitted.submissionId,
3031
+ toolCallIds: [call3],
3032
+ reason: 'a second wave of uncertainty',
3033
+ }),
3034
+ )
3035
+ yield* ledger.recordUnknownResolution(
3036
+ UnknownResolutionCommand.make({
3037
+ submissionId: admitted.submissionId,
3038
+ toolCallId: call2,
3039
+ author: 'conformance-operator',
3040
+ reason: 'supplier confirmed the booking',
3041
+ resolution: ResolutionCompletedWithResult.make({
3042
+ result: { bookingRef: 'booking-1' },
3043
+ isFailure: false,
3044
+ }),
3045
+ }),
3046
+ )
3047
+
3048
+ const stillBlocked = yield* expectSome(
3049
+ 'lookup while the extended set stays open',
3050
+ yield* lookupById(admitted.submissionId),
3051
+ )
3052
+
3053
+ yield* ensure(
3054
+ stillBlocked.state === 'unknown' && Option.isNone(yield* claimLane(threadId)),
3055
+ 'The lane must stay blocked while any marked call lacks a resolution',
3056
+ )
3057
+
3058
+ yield* ledger.recordUnknownResolution(
3059
+ UnknownResolutionCommand.make({
3060
+ submissionId: admitted.submissionId,
3061
+ toolCallId: call3,
3062
+ author: 'conformance-operator',
3063
+ reason: 'idempotency key covers a repeat',
3064
+ resolution: ResolutionSafeToRetry.make(),
3065
+ }),
3066
+ )
3067
+
3068
+ const reopenedState = yield* expectSome(
3069
+ 'lookup after the covering resolution',
3070
+ yield* lookupById(admitted.submissionId),
3071
+ )
3072
+
3073
+ yield* ensure(
3074
+ reopenedState.state === 'input-applied',
3075
+ 'Covering every marked call must reopen the lane as input-applied',
3076
+ )
3077
+ const snapshot = yield* recoverySnapshot(admitted.submissionId)
3078
+
3079
+ yield* ensure(
3080
+ snapshot.unknownResolutions.length === 3,
3081
+ 'The recovery snapshot must expose every recorded resolution intent',
3082
+ )
3083
+
3084
+ const reclaim = yield* expectSome(
3085
+ 'the claim after the lane reopened',
3086
+ yield* claimLane(threadId),
3087
+ )
3088
+
3089
+ yield* ensure(
3090
+ reclaim.submissionId === admitted.submissionId &&
3091
+ reclaim.session.generation !== claim.session.generation,
3092
+ 'The reopened lane must grant a fresh fenced Attempt',
3093
+ )
3094
+
3095
+ yield* settleClaimed(admitted, reclaim.session)
3096
+
3097
+ yield* ledger.recordUnknownResolution(
3098
+ UnknownResolutionCommand.make({
3099
+ submissionId: admitted.submissionId,
3100
+ toolCallId: decodeToolCallId('call-unknown-late'),
3101
+ author: 'conformance-operator',
3102
+ reason: 'factual closure after settlement',
3103
+ resolution: ResolutionNeverHappened.make(),
3104
+ }),
3105
+ )
3106
+
3107
+ const afterLate = yield* expectSome(
3108
+ 'lookup after factual closure',
3109
+ yield* lookupById(admitted.submissionId),
3110
+ )
3111
+
3112
+ yield* ensure(
3113
+ afterLate.state === 'settled' && afterLate.settledOutcome === 'completed',
3114
+ 'Factual closure must preserve the original settlement',
3115
+ )
3116
+
3117
+ const lateRetry = yield* expectFailure(
3118
+ 'authorizing execution after settlement',
3119
+ ledger.recordUnknownResolution(
3120
+ UnknownResolutionCommand.make({
3121
+ submissionId: admitted.submissionId,
3122
+ toolCallId: decodeToolCallId('call-unknown-late-retry'),
3123
+ author: 'conformance-operator',
3124
+ reason: 'retry is execution authority',
3125
+ resolution: ResolutionSafeToRetry.make(),
3126
+ }),
3127
+ ),
3128
+ )
3129
+
3130
+ yield* ensure(
3131
+ isSettlementConflict(lateRetry),
3132
+ 'A settled Submission must never regain execution authority',
3133
+ )
3134
+ }),
3135
+ )
3136
+
3137
+ const suspendResumesImmediatelyWhenDecided = conformanceCase(
3138
+ 'suspend with an already-present decision resumes immediately',
3139
+ ({ ensure, expectFailure, expectSome }) =>
3140
+ Effect.gen(function*() {
3141
+ const threadId = decodeThreadId('ledger-conformance-suspend')
3142
+ const ledger = yield* SubmissionLedger
3143
+ const admitted = yield* admitReady(threadId, 'suspend-key-1', { work: 'suspend' })
3144
+
3145
+ const claim = yield* expectSome('the claim before suspension', yield* claimLane(threadId))
3146
+
3147
+ const callA = decodeToolCallId('call-suspend-a')
3148
+ const callB = decodeToolCallId('call-suspend-b')
3149
+
3150
+ // The decision raced ahead of the suspend transaction (plan §2.6).
3151
+ yield* ledger.recordApprovalDecision(
3152
+ ApprovalDecisionCommand.make({
3153
+ submissionId: admitted.submissionId,
3154
+ toolCallId: callA,
3155
+ decision: 'approved',
3156
+ resolver: 'conformance-approver',
3157
+ reason: 'decided before the suspend committed',
3158
+ }),
3159
+ )
3160
+
3161
+ const immediate = yield* claim.session.suspend(
3162
+ ApprovalPendingSuspension.make({ toolCallIds: [callA] }),
3163
+ )
3164
+
3165
+ yield* ensure(
3166
+ immediate === 'resume-immediately',
3167
+ 'A fully-decided suspension reason must resume immediately',
3168
+ )
3169
+
3170
+ const notSuspended = yield* expectSome(
3171
+ 'lookup after the immediate resume',
3172
+ yield* lookupById(admitted.submissionId),
3173
+ )
3174
+
3175
+ yield* ensure(
3176
+ notSuspended.state === 'ready',
3177
+ 'An immediate resume must not transition the Submission to suspended',
3178
+ )
3179
+ // The ownership period must survive an immediate resume: the caller keeps working.
3180
+ yield* claim.session.checkActive
3181
+
3182
+ const suspended = yield* claim.session.suspend(
3183
+ ApprovalPendingSuspension.make({ toolCallIds: [callA, callB] }),
3184
+ )
3185
+
3186
+ yield* ensure(
3187
+ suspended === 'suspended',
3188
+ 'An undecided call in the reason must suspend durably',
3189
+ )
3190
+
3191
+ const suspendedState = yield* expectSome(
3192
+ 'lookup after the suspension',
3193
+ yield* lookupById(admitted.submissionId),
3194
+ )
3195
+
3196
+ yield* ensure(suspendedState.state === 'suspended', 'The suspension must be durable')
3197
+ const suspendedSnapshot = yield* recoverySnapshot(admitted.submissionId)
3198
+
3199
+ yield* ensure(
3200
+ suspendedSnapshot.suspension !== undefined &&
3201
+ suspendedSnapshot.suspension.reason._tag === 'ApprovalPending' &&
3202
+ suspendedSnapshot.suspension.reason.toolCallIds.length === 2 &&
3203
+ suspendedSnapshot.approvalDecisions.length === 1,
3204
+ 'The recovery snapshot must expose the suspension reason and prior decisions',
3205
+ )
3206
+
3207
+ const ended = yield* expectFailure(
3208
+ 'renewing after the suspension ended the ownership period',
3209
+ claim.session.checkActive,
3210
+ )
3211
+
3212
+ yield* ensure(
3213
+ isOwnershipLost(ended),
3214
+ 'Suspension must end the ownership period without settling',
3215
+ )
3216
+
3217
+ yield* ledger.recordApprovalDecision(
3218
+ ApprovalDecisionCommand.make({
3219
+ submissionId: admitted.submissionId,
3220
+ toolCallId: callB,
3221
+ decision: 'denied',
3222
+ resolver: 'conformance-approver',
3223
+ reason: 'the covering decision',
3224
+ }),
3225
+ )
3226
+
3227
+ const woken = yield* expectSome(
3228
+ 'lookup after the covering decision',
3229
+ yield* lookupById(admitted.submissionId),
3230
+ )
3231
+
3232
+ yield* ensure(
3233
+ woken.state === 'input-applied',
3234
+ 'The covering decision must wake the suspended lane',
3235
+ )
3236
+ const wokenSnapshot = yield* recoverySnapshot(admitted.submissionId)
3237
+
3238
+ yield* ensure(
3239
+ wokenSnapshot.suspension === undefined,
3240
+ 'Waking must clear the durable suspension',
3241
+ )
3242
+
3243
+ const reclaim = yield* expectSome('the claim after waking', yield* claimLane(threadId))
3244
+
3245
+ yield* settleClaimed(admitted, reclaim.session)
3246
+
3247
+ const terminal = yield* expectFailure(
3248
+ 'suspending a settled Submission',
3249
+ ledger.suspend(
3250
+ SuspendRequest.make({
3251
+ submissionId: admitted.submissionId,
3252
+ reason: ApprovalPendingSuspension.make({ toolCallIds: [callA] }),
3253
+ }),
3254
+ ),
3255
+ )
3256
+
3257
+ yield* ensure(
3258
+ isSettlementConflict(terminal) && terminal.existingOutcome === 'completed',
3259
+ 'Suspension must never land on a settled Submission',
3260
+ )
3261
+ }),
3262
+ )
3263
+
3264
+ const joinedSettlementLinkageAuthority = conformanceCase(
3265
+ 'a joined settlement requires immutable host linkage and the canonical host outcome',
3266
+ ({ ensure, expectFailure, expectSome }) =>
3267
+ Effect.gen(function*() {
3268
+ const threadId = decodeThreadId('ledger-conformance-joined-settlement')
3269
+ const ledger = yield* SubmissionLedger
3270
+ const host = yield* admitReady(threadId, 'joined-settle-host', { work: 'host' })
3271
+ const queued = yield* admitReady(threadId, 'joined-settle-2', { queued: 2 })
3272
+ const hostClaim = yield* expectSome('the host claim', yield* claimLane(threadId))
3273
+
3274
+ const claims = yield* hostClaim.session.claimJoining(1)
3275
+
3276
+ yield* ensure(
3277
+ claims.length === 1 && claims[0]?.submissionId === queued.submissionId,
3278
+ "The queued Submission must join the host's contiguous prefix",
3279
+ )
3280
+
3281
+ const joiningPublication = yield* settlementPublication({
3282
+ submissionId: queued.submissionId,
3283
+ authority: { _tag: 'Joined', hostSubmissionId: host.submissionId },
3284
+ receiptId: queued.receiptId,
3285
+ outcome: 'completed',
3286
+ })
3287
+
3288
+ const fenced = yield* expectFailure(
3289
+ 'publishing before joined linkage is committed',
3290
+ publishSettlement(joiningPublication),
3291
+ )
3292
+
3293
+ yield* ensure(
3294
+ isLedgerError(fenced),
3295
+ 'A revertible joining row cannot authorize joined settlement publication',
3296
+ )
3297
+ yield* hostClaim.session.markJoined(queued.submissionId, {
3298
+ recordId: submissionInputRecordId(queued.submissionId),
3299
+ sequence: decodeSequence(7),
3300
+ })
3301
+ yield* publishSettlement(
3302
+ yield* settlementPublication({
3303
+ submissionId: host.submissionId,
3304
+ authority: { _tag: 'Owned' },
3305
+ receiptId: host.receiptId,
3306
+ outcome: 'completed',
3307
+ }),
3308
+ )
3309
+
3310
+ const joinedPublication = yield* settlementPublication({
3311
+ submissionId: queued.submissionId,
3312
+ authority: { _tag: 'Joined', hostSubmissionId: host.submissionId },
3313
+ receiptId: queued.receiptId,
3314
+ outcome: 'completed',
3315
+ })
3316
+
3317
+ yield* publishSettlement(joinedPublication)
3318
+
3319
+ const settlement = yield* ledger.finalizeSettlement(
3320
+ SettlementFinalization.make({
3321
+ submissionId: queued.submissionId,
3322
+ settlementId: submissionSettlementId(queued.submissionId),
3323
+ }),
3324
+ )
3325
+
3326
+ yield* ensure(
3327
+ settlement.outcome === 'completed',
3328
+ 'The joined receipt must finalize from its canonical host outcome',
3329
+ )
3330
+
3331
+ const settled = yield* expectSome(
3332
+ 'lookup after joined finalization',
3333
+ yield* lookupById(queued.submissionId),
3334
+ )
3335
+
3336
+ yield* ensure(
3337
+ settled.state === 'settled' && settled.settledOutcome === 'completed',
3338
+ 'The joined Submission must settle terminally',
3339
+ )
3340
+ }),
3341
+ )
3342
+
3343
+ const childReservationIdempotency = conformanceCase(
3344
+ 'replays an identical child reservation and rejects a divergent allocation digest',
3345
+ ({ ensure, expectFailure, expectSome }) =>
3346
+ Effect.gen(function*() {
3347
+ const threadId = decodeThreadId('ledger-conformance-child-reserve')
3348
+ const ledger = yield* SubmissionLedger
3349
+ const parent = yield* admitReady(threadId, 'child-reserve-parent', { work: 'parent' })
3350
+
3351
+ yield* expectSome('the parent claim', yield* claimLane(threadId))
3352
+
3353
+ const allocation = { turns: 4, toolCalls: 8 }
3354
+ const allocationDigest = yield* digestJson(allocation)
3355
+
3356
+ const requestFields = {
3357
+ reservationId: decodeChildReservationId('child-reservation:run-reserve:call-1'),
3358
+ parentSubmissionId: parent.submissionId,
3359
+ parentToolCallId: decodeToolCallId('call-child-reserve'),
3360
+
3361
+ allocation,
3362
+ allocationDigest,
3363
+ }
3364
+
3365
+ const request = ChildBudgetReservationRequest.make(requestFields)
3366
+ const first = yield* ledger.reserveChildBudget(request)
3367
+
3368
+ yield* ensure(
3369
+ !first.replayed &&
3370
+ first.reservation.status === 'reserved' &&
3371
+ first.reservation.allocationDigest === allocationDigest &&
3372
+ first.reservation.childSubmissionId === undefined &&
3373
+ persistedJsonEquivalent(first.reservation.allocation, allocation),
3374
+ 'The first reservation must create a reserved row carrying the exact allocation',
3375
+ )
3376
+
3377
+ yield* TestClock.adjust('1 second')
3378
+
3379
+ const replayed = yield* ledger.reserveChildBudget(
3380
+ ChildBudgetReservationRequest.make({
3381
+ ...requestFields,
3382
+ allocation: { toolCalls: 8, turns: 4 },
3383
+ }),
3384
+ )
3385
+
3386
+ yield* ensure(
3387
+ replayed.replayed &&
3388
+ replayed.reservation.status === 'reserved' &&
3389
+ persistedJsonEquivalent(replayed.reservation.allocation, allocation) &&
3390
+ sameInstant(replayed.reservation.reservedAt, first.reservation.reservedAt),
3391
+ 'An identical reservation must replay the stored row unchanged',
3392
+ )
3393
+
3394
+ const divergentAllocation = { turns: 64, toolCalls: 8 }
3395
+
3396
+ const divergent = yield* expectFailure(
3397
+ 'a divergent allocation for the same reservation id',
3398
+ ledger.reserveChildBudget(
3399
+ ChildBudgetReservationRequest.make({
3400
+ ...requestFields,
3401
+ allocation: divergentAllocation,
3402
+ allocationDigest: yield* digestJson(divergentAllocation),
3403
+ }),
3404
+ ),
3405
+ )
3406
+
3407
+ yield* ensure(
3408
+ isChildReservationConflict(divergent) && divergent.status === 'reserved',
3409
+ 'A divergent allocation must conflict with the recorded reservation',
3410
+ )
3411
+
3412
+ const secondId = yield* expectFailure(
3413
+ 'a second reservation id for the same parent Tool Call',
3414
+ ledger.reserveChildBudget(
3415
+ ChildBudgetReservationRequest.make({
3416
+ ...requestFields,
3417
+ reservationId: decodeChildReservationId('child-reservation:run-reserve:call-1-other'),
3418
+ }),
3419
+ ),
3420
+ )
3421
+
3422
+ yield* ensure(
3423
+ isChildReservationConflict(secondId),
3424
+ 'One parent Tool Call must never own two reservations',
3425
+ )
3426
+
3427
+ const snapshot = yield* recoverySnapshot(parent.submissionId)
3428
+
3429
+ yield* ensure(
3430
+ snapshot.childReservations.length === 1 &&
3431
+ snapshot.childReservations[0].reservationId === request.reservationId &&
3432
+ snapshot.childReservations[0].status === 'reserved' &&
3433
+ snapshot.childAttachments.length === 0,
3434
+ 'The parent recovery snapshot must expose the reservation before any attachment',
3435
+ )
3436
+ }),
3437
+ )
3438
+
3439
+ const childReservationFencing = conformanceCase(
3440
+ 'a stale parent token cannot transition a child reservation',
3441
+ ({ ensure, expectFailure, expectSome }) =>
3442
+ Effect.gen(function*() {
3443
+ const threadId = decodeThreadId('ledger-conformance-child-fence')
3444
+ const childLane = decodeThreadId('ledger-conformance-child-fence-child')
3445
+ const ledger = yield* SubmissionLedger
3446
+ const parent = yield* admitReady(threadId, 'child-fence-parent', { work: 'parent' })
3447
+ const child = yield* admitReady(childLane, 'child-fence-child', { work: 'child' })
3448
+
3449
+ const firstClaim = yield* expectSome('the first parent claim', yield* claimLane(threadId))
3450
+
3451
+ const allocation = { turns: 2 }
3452
+ const allocationDigest = yield* digestJson(allocation)
3453
+
3454
+ const requestFields = {
3455
+ reservationId: decodeChildReservationId('child-reservation:run-fence:call-1'),
3456
+ parentSubmissionId: parent.submissionId,
3457
+ parentToolCallId: decodeToolCallId('call-child-fence'),
3458
+
3459
+ allocation,
3460
+ allocationDigest,
3461
+ }
3462
+
3463
+ const request = ChildBudgetReservationRequest.make(requestFields)
3464
+
3465
+ yield* firstClaim.session.reserveChildBudget({ ...requestFields })
3466
+
3467
+ // The parent Attempt ends and a replacement claims the lane: the old local capability is closed.
3468
+ yield* firstClaim.session.release
3469
+
3470
+ const reclaim = yield* expectSome('the replacement parent claim', yield* claimLane(threadId))
3471
+
3472
+ yield* ensure(
3473
+ reclaim.session.generation !== firstClaim.session.generation,
3474
+ 'The replacement claim must fence the stale parent Attempt',
3475
+ )
3476
+
3477
+ const staleAttach = yield* expectFailure(
3478
+ 'attaching a child with the superseded parent token',
3479
+ firstClaim.session.attachChildToReservation({
3480
+ reservationId: request.reservationId,
3481
+ childSubmissionId: child.submissionId,
3482
+ }),
3483
+ )
3484
+
3485
+ yield* ensure(
3486
+ isOwnershipLost(staleAttach),
3487
+ 'A superseded parent token must not attach a child',
3488
+ )
3489
+
3490
+ const staleCreate = yield* expectFailure(
3491
+ 'creating a second-call reservation with the superseded parent token',
3492
+ firstClaim.session.reserveChildBudget({
3493
+ ...requestFields,
3494
+ reservationId: decodeChildReservationId('child-reservation:run-fence:call-2'),
3495
+ parentToolCallId: decodeToolCallId('call-child-fence-second'),
3496
+ }),
3497
+ )
3498
+
3499
+ yield* ensure(
3500
+ isOwnershipLost(staleCreate),
3501
+ 'A superseded parent token must not create new reservation state',
3502
+ )
3503
+
3504
+ // An identical child reservation replay creates nothing and may return its recorded
3505
+ // winner before checking the current parent fence.
3506
+ const staleReplay = yield* ledger.reserveChildBudget(
3507
+ ChildBudgetReservationRequest.make(requestFields),
3508
+ )
3509
+
3510
+ yield* ensure(
3511
+ staleReplay.replayed && staleReplay.reservation.status === 'reserved',
3512
+ 'An identical reservation replay must return the recorded row even from a stale caller',
3513
+ )
3514
+
3515
+ const attached = yield* reclaim.session.attachChildToReservation({
3516
+ reservationId: request.reservationId,
3517
+ childSubmissionId: child.submissionId,
3518
+ })
3519
+
3520
+ yield* ensure(
3521
+ attached.childSubmissionId === child.submissionId,
3522
+ 'The live replacement token must attach the child',
3523
+ )
3524
+ }),
3525
+ )
3526
+
3527
+ const attachChildIdempotency = conformanceCase(
3528
+ 'attachChildToReservation is idempotent and rejects a divergent child',
3529
+ ({ ensure, expectFailure, expectSome }) =>
3530
+ Effect.gen(function*() {
3531
+ const threadId = decodeThreadId('ledger-conformance-child-attach')
3532
+ const childLane = decodeThreadId('ledger-conformance-child-attach-child')
3533
+ const parent = yield* admitReady(threadId, 'child-attach-parent', { work: 'parent' })
3534
+ const child = yield* admitReady(childLane, 'child-attach-child', { queued: 1 })
3535
+ const otherChild = yield* admitReady(childLane, 'child-attach-other', { queued: 2 })
3536
+ const claim = yield* expectSome('the parent claim', yield* claimLane(threadId))
3537
+
3538
+ const allocation = { turns: 3 }
3539
+ const reservationId = decodeChildReservationId('child-reservation:run-attach:call-1')
3540
+
3541
+ yield* claim.session.reserveChildBudget({
3542
+ reservationId,
3543
+ parentToolCallId: decodeToolCallId('call-child-attach'),
3544
+ allocation,
3545
+ allocationDigest: yield* digestJson(allocation),
3546
+ })
3547
+
3548
+ const unknownReservation = yield* expectFailure(
3549
+ 'attaching to a reservation that was never created',
3550
+ claim.session.attachChildToReservation({
3551
+ reservationId: decodeChildReservationId('child-reservation:run-attach:missing'),
3552
+ childSubmissionId: child.submissionId,
3553
+ }),
3554
+ )
3555
+
3556
+ yield* ensure(
3557
+ isLedgerError(unknownReservation),
3558
+ 'Attaching to an unknown reservation must fail as a ledger error',
3559
+ )
3560
+
3561
+ const attached = yield* claim.session.attachChildToReservation({
3562
+ reservationId,
3563
+ childSubmissionId: child.submissionId,
3564
+ })
3565
+
3566
+ yield* ensure(
3567
+ attached.childSubmissionId === child.submissionId && attached.status === 'reserved',
3568
+ 'Attaching must record the child on the reservation row',
3569
+ )
3570
+
3571
+ const replayed = yield* claim.session.attachChildToReservation({
3572
+ reservationId,
3573
+ childSubmissionId: child.submissionId,
3574
+ })
3575
+
3576
+ yield* ensure(
3577
+ replayed.childSubmissionId === child.submissionId,
3578
+ 'Repeating the identical attachment must be a no-op',
3579
+ )
3580
+
3581
+ const divergent = yield* expectFailure(
3582
+ 'attaching a different child to the same reservation',
3583
+ claim.session.attachChildToReservation({
3584
+ reservationId,
3585
+ childSubmissionId: otherChild.submissionId,
3586
+ }),
3587
+ )
3588
+
3589
+ yield* ensure(
3590
+ isChildReservationConflict(divergent),
3591
+ 'A divergent child attachment must conflict with the recorded child',
3592
+ )
3593
+
3594
+ const snapshot = yield* recoverySnapshot(parent.submissionId)
3595
+
3596
+ yield* ensure(
3597
+ snapshot.childAttachments.length === 1 &&
3598
+ snapshot.childAttachments[0].childSubmissionId === child.submissionId &&
3599
+ snapshot.childAttachments[0].toolCallId === decodeToolCallId('call-child-attach') &&
3600
+ snapshot.childAttachments[0].childState === 'ready' &&
3601
+ snapshot.childAttachments[0].childOutcome === undefined,
3602
+ "The parent recovery snapshot must expose the attachment with the child's lane state",
3603
+ )
3604
+ }),
3605
+ )
3606
+
3607
+ const beginReleaseFreezesAccountingOnce = conformanceCase(
3608
+ 'beginRelease freezes the accounting decision exactly once',
3609
+ ({ ensure, expectFailure, expectSome }) =>
3610
+ Effect.gen(function*() {
3611
+ const threadId = decodeThreadId('ledger-conformance-child-freeze')
3612
+ const ledger = yield* SubmissionLedger
3613
+
3614
+ yield* admitReady(threadId, 'child-freeze-parent', { work: 'parent' })
3615
+ const claim = yield* expectSome('the parent claim', yield* claimLane(threadId))
3616
+
3617
+ const allocation = { turns: 4 }
3618
+ const reservationId = decodeChildReservationId('child-reservation:run-freeze:call-1')
3619
+
3620
+ yield* claim.session.reserveChildBudget({
3621
+ reservationId,
3622
+ parentToolCallId: decodeToolCallId('call-child-freeze'),
3623
+ allocation,
3624
+ allocationDigest: yield* digestJson(allocation),
3625
+ })
3626
+
3627
+ const accounting = { consumed: { turns: 1 }, released: { turns: 3 } }
3628
+
3629
+ const frozen = yield* ledger.beginChildBudgetRelease(
3630
+ BeginChildBudgetReleaseRequest.make({ reservationId, accounting }),
3631
+ )
3632
+
3633
+ yield* ensure(
3634
+ frozen.status === 'releasePending' &&
3635
+ frozen.accounting !== undefined &&
3636
+ persistedJsonEquivalent(frozen.accounting, accounting) &&
3637
+ frozen.releaseBeganAt !== undefined,
3638
+ 'The first beginRelease must freeze the accounting and move to releasePending',
3639
+ )
3640
+
3641
+ yield* TestClock.adjust('1 second')
3642
+
3643
+ const replayed = yield* ledger.beginChildBudgetRelease(
3644
+ BeginChildBudgetReleaseRequest.make({
3645
+ reservationId,
3646
+ accounting: { released: { turns: 3 }, consumed: { turns: 1 } },
3647
+ }),
3648
+ )
3649
+
3650
+ yield* ensure(
3651
+ replayed.status === 'releasePending' &&
3652
+ replayed.releaseBeganAt !== undefined &&
3653
+ frozen.releaseBeganAt !== undefined &&
3654
+ sameInstant(replayed.releaseBeganAt, frozen.releaseBeganAt),
3655
+ 'Replaying the identical accounting must be a no-op with the frozen decision retained',
3656
+ )
3657
+
3658
+ const divergent = yield* expectFailure(
3659
+ 'freezing a different accounting decision',
3660
+ ledger.beginChildBudgetRelease(
3661
+ BeginChildBudgetReleaseRequest.make({
3662
+ reservationId,
3663
+ accounting: { consumed: { turns: 4 }, released: { turns: 0 } },
3664
+ }),
3665
+ ),
3666
+ )
3667
+
3668
+ yield* ensure(
3669
+ isChildReservationConflict(divergent) && divergent.status === 'releasePending',
3670
+ 'A divergent accounting freeze must conflict with the frozen decision',
3671
+ )
3672
+
3673
+ yield* ledger.releaseChildBudget(ReleaseChildBudgetRequest.make({ reservationId }))
3674
+
3675
+ const afterRelease = yield* ledger.beginChildBudgetRelease(
3676
+ BeginChildBudgetReleaseRequest.make({ reservationId, accounting }),
3677
+ )
3678
+
3679
+ yield* ensure(
3680
+ afterRelease.status === 'released' &&
3681
+ afterRelease.accounting !== undefined &&
3682
+ persistedJsonEquivalent(afterRelease.accounting, accounting),
3683
+ 'Replaying the identical accounting after release must return the released row',
3684
+ )
3685
+
3686
+ const divergentAfterRelease = yield* expectFailure(
3687
+ 'freezing a different accounting decision after release',
3688
+ ledger.beginChildBudgetRelease(
3689
+ BeginChildBudgetReleaseRequest.make({
3690
+ reservationId,
3691
+ accounting: { consumed: { turns: 2 }, released: { turns: 2 } },
3692
+ }),
3693
+ ),
3694
+ )
3695
+
3696
+ yield* ensure(
3697
+ isChildReservationConflict(divergentAfterRelease) &&
3698
+ divergentAfterRelease.status === 'released',
3699
+ 'The frozen decision must stay immutable after release',
3700
+ )
3701
+ }),
3702
+ )
3703
+
3704
+ const releaseAppliedExactlyOnce = conformanceCase(
3705
+ 'release returns unused allocation exactly once',
3706
+ ({ ensure, expectFailure, expectSome }) =>
3707
+ Effect.gen(function*() {
3708
+ const threadId = decodeThreadId('ledger-conformance-child-release')
3709
+ const ledger = yield* SubmissionLedger
3710
+ const parent = yield* admitReady(threadId, 'child-release-parent', { work: 'parent' })
3711
+ const claim = yield* expectSome('the parent claim', yield* claimLane(threadId))
3712
+
3713
+ const allocation = { turns: 4 }
3714
+ const reservationId = decodeChildReservationId('child-reservation:run-release:call-1')
3715
+
3716
+ yield* claim.session.reserveChildBudget({
3717
+ reservationId,
3718
+ parentToolCallId: decodeToolCallId('call-child-release'),
3719
+ allocation,
3720
+ allocationDigest: yield* digestJson(allocation),
3721
+ })
3722
+
3723
+ const early = yield* expectFailure(
3724
+ 'releasing before the accounting decision is frozen',
3725
+ ledger.releaseChildBudget(ReleaseChildBudgetRequest.make({ reservationId })),
3726
+ )
3727
+
3728
+ yield* ensure(
3729
+ isChildReservationConflict(early) && early.status === 'reserved',
3730
+ 'Release must never skip the releasePending freeze',
3731
+ )
3732
+
3733
+ yield* ledger.beginChildBudgetRelease(
3734
+ BeginChildBudgetReleaseRequest.make({
3735
+ reservationId,
3736
+ accounting: { consumed: {}, released: { turns: 4 } },
3737
+ }),
3738
+ )
3739
+
3740
+ const released = yield* ledger.releaseChildBudget(
3741
+ ReleaseChildBudgetRequest.make({ reservationId }),
3742
+ )
3743
+
3744
+ yield* ensure(
3745
+ released.status === 'released' && released.releasedAt !== undefined,
3746
+ 'Release must transition releasePending to released',
3747
+ )
3748
+
3749
+ yield* TestClock.adjust('1 second')
3750
+
3751
+ const replayed = yield* ledger.releaseChildBudget(
3752
+ ReleaseChildBudgetRequest.make({ reservationId }),
3753
+ )
3754
+
3755
+ yield* ensure(
3756
+ replayed.status === 'released' &&
3757
+ replayed.releasedAt !== undefined &&
3758
+ released.releasedAt !== undefined &&
3759
+ sameInstant(replayed.releasedAt, released.releasedAt),
3760
+ 'Replaying the release must return the stored row unchanged — never applied twice',
3761
+ )
3762
+
3763
+ const snapshot = yield* recoverySnapshot(parent.submissionId)
3764
+
3765
+ yield* ensure(
3766
+ snapshot.childReservations.length === 1 &&
3767
+ snapshot.childReservations[0].status === 'released',
3768
+ 'The recovery snapshot must expose the released reservation',
3769
+ )
3770
+ }),
3771
+ )
3772
+
3773
+ const recordChildSettledWake = conformanceCase(
3774
+ 'recordChildSettled accepts canonical publication prefixes and wakes only when all are covered',
3775
+ ({ ensure, expectFailure, expectSome }) =>
3776
+ Effect.gen(function*() {
3777
+ const parentLane = decodeThreadId('ledger-conformance-child-wake')
3778
+ const childLaneA = decodeThreadId('ledger-conformance-child-wake-a')
3779
+ const childLaneB = decodeThreadId('ledger-conformance-child-wake-b')
3780
+ const ledger = yield* SubmissionLedger
3781
+
3782
+ const parent = yield* admitReady(parentLane, 'child-wake-parent', { work: 'parent' })
3783
+ const childA = yield* admitReady(childLaneA, 'child-wake-a', { child: 'a' })
3784
+ const childB = yield* admitReady(childLaneB, 'child-wake-b', { child: 'b' })
3785
+
3786
+ const parentClaim = yield* expectSome('the parent claim', yield* claimLane(parentLane))
3787
+
3788
+ const suspended = yield* parentClaim.session.suspend(
3789
+ WaitingForChildSuspension.make({
3790
+ children: [
3791
+ WaitingChild.make({
3792
+ toolCallId: decodeToolCallId('call-wake-a'),
3793
+ childSubmissionId: childA.submissionId,
3794
+ }),
3795
+ WaitingChild.make({
3796
+ toolCallId: decodeToolCallId('call-wake-b'),
3797
+ childSubmissionId: childB.submissionId,
3798
+ }),
3799
+ ],
3800
+ }),
3801
+ )
3802
+
3803
+ yield* ensure(
3804
+ suspended === 'suspended',
3805
+ 'Unsettled children must suspend the parent durably',
3806
+ )
3807
+
3808
+ const ended = yield* expectFailure(
3809
+ 'renewing after the waitingForChild suspension ended the ownership period',
3810
+ parentClaim.session.checkActive,
3811
+ )
3812
+
3813
+ yield* ensure(
3814
+ isOwnershipLost(ended),
3815
+ 'waitingForChild must end the ownership period without settling (SUB-030)',
3816
+ )
3817
+ yield* ensure(
3818
+ Option.isNone(yield* claimLane(parentLane)),
3819
+ 'A waitingForChild head must produce no claim and consume no worker permit',
3820
+ )
3821
+
3822
+ yield* expectSome('the first child claim', yield* claimLane(childLaneA))
3823
+
3824
+ const childPublicationA = yield* settlementPublication({
3825
+ submissionId: childA.submissionId,
3826
+ authority: { _tag: 'Owned' },
3827
+ receiptId: childA.receiptId,
3828
+ outcome: 'completed',
3829
+ })
3830
+
3831
+ yield* publishSettlement(childPublicationA)
3832
+
3833
+ const partial = yield* ledger.recordChildSettled(
3834
+ ChildSettledNotification.make({
3835
+ parentSubmissionId: parent.submissionId,
3836
+ childSubmissionId: childA.submissionId,
3837
+ }),
3838
+ )
3839
+
3840
+ yield* ensure(
3841
+ partial === 'still-waiting',
3842
+ 'A settlement notification must not wake the parent while a listed child is unsettled',
3843
+ )
3844
+ yield* ledger.finalizeSettlement(
3845
+ SettlementFinalization.make({
3846
+ submissionId: childA.submissionId,
3847
+ settlementId: submissionSettlementId(childPublicationA.submissionId),
3848
+ }),
3849
+ )
3850
+
3851
+ const stillSuspended = yield* expectSome(
3852
+ 'lookup while one child is outstanding',
3853
+ yield* lookupById(parent.submissionId),
3854
+ )
3855
+
3856
+ yield* ensure(
3857
+ stillSuspended.state === 'suspended' && Option.isNone(yield* claimLane(parentLane)),
3858
+ 'The parent lane must stay suspended until every listed child settled',
3859
+ )
3860
+
3861
+ yield* expectSome('the second child claim', yield* claimLane(childLaneB))
3862
+
3863
+ const childPublicationB = yield* settlementPublication({
3864
+ submissionId: childB.submissionId,
3865
+ authority: { _tag: 'Owned' },
3866
+ receiptId: childB.receiptId,
3867
+ outcome: 'completed',
3868
+ })
3869
+
3870
+ yield* publishSettlement(childPublicationB)
3871
+
3872
+ const woken = yield* ledger.recordChildSettled(
3873
+ ChildSettledNotification.make({
3874
+ parentSubmissionId: parent.submissionId,
3875
+ childSubmissionId: childB.submissionId,
3876
+ }),
3877
+ )
3878
+
3879
+ yield* ensure(
3880
+ woken === 'woken',
3881
+ 'The covering canonical settlement prefix must wake the parent before child finalization',
3882
+ )
3883
+ yield* ledger.finalizeSettlement(
3884
+ SettlementFinalization.make({
3885
+ submissionId: childB.submissionId,
3886
+ settlementId: submissionSettlementId(childPublicationB.submissionId),
3887
+ }),
3888
+ )
3889
+
3890
+ const awake = yield* expectSome(
3891
+ 'lookup after the covering settlement',
3892
+ yield* lookupById(parent.submissionId),
3893
+ )
3894
+
3895
+ yield* ensure(
3896
+ awake.state === 'input-applied',
3897
+ 'The woken parent must transition suspended(WaitingForChild) to input-applied',
3898
+ )
3899
+ const wokenSnapshot = yield* recoverySnapshot(parent.submissionId)
3900
+
3901
+ yield* ensure(
3902
+ wokenSnapshot.suspension === undefined,
3903
+ 'Waking must clear the durable suspension',
3904
+ )
3905
+
3906
+ const replayedNotification = yield* ledger.recordChildSettled(
3907
+ ChildSettledNotification.make({
3908
+ parentSubmissionId: parent.submissionId,
3909
+ childSubmissionId: childA.submissionId,
3910
+ }),
3911
+ )
3912
+
3913
+ yield* ensure(
3914
+ replayedNotification === 'not-waiting',
3915
+ 'Replaying a notification after the wake must be an idempotent no-op',
3916
+ )
3917
+
3918
+ const reclaim = yield* expectSome(
3919
+ 'the parent claim after waking',
3920
+ yield* claimLane(parentLane),
3921
+ )
3922
+
3923
+ yield* ensure(
3924
+ reclaim.submissionId === parent.submissionId &&
3925
+ reclaim.session.generation !== parentClaim.session.generation,
3926
+ 'The woken lane must grant a fresh fenced Attempt',
3927
+ )
3928
+ yield* settleClaimed(parent, reclaim.session)
3929
+
3930
+ const afterSettlement = yield* ledger.recordChildSettled(
3931
+ ChildSettledNotification.make({
3932
+ parentSubmissionId: parent.submissionId,
3933
+ childSubmissionId: childB.submissionId,
3934
+ }),
3935
+ )
3936
+
3937
+ yield* ensure(
3938
+ afterSettlement === 'not-waiting',
3939
+ 'A notification for a settled parent must answer not-waiting',
3940
+ )
3941
+ }),
3942
+ )
3943
+
3944
+ const suspendResumesImmediatelyForSettledChildren = conformanceCase(
3945
+ 'suspend returns resume-immediately when children already settled',
3946
+ ({ ensure, expectSome }) =>
3947
+ Effect.gen(function*() {
3948
+ const parentLane = decodeThreadId('ledger-conformance-child-raced')
3949
+ const childLaneA = decodeThreadId('ledger-conformance-child-raced-a')
3950
+ const childLaneB = decodeThreadId('ledger-conformance-child-raced-b')
3951
+
3952
+ // The child settles BEFORE the parent's suspend transaction commits (spec §12 step 10
3953
+ // race): the suspend must observe the settlement and resume immediately.
3954
+ const settledChild = yield* admitReady(childLaneA, 'child-raced-a', { child: 'a' })
3955
+
3956
+ const settledClaim = yield* expectSome(
3957
+ "the settled child's claim",
3958
+ yield* claimLane(childLaneA),
3959
+ )
3960
+
3961
+ yield* settleClaimed(settledChild, settledClaim.session)
3962
+ const pendingChild = yield* admitReady(childLaneB, 'child-raced-b', { child: 'b' })
3963
+
3964
+ const parent = yield* admitReady(parentLane, 'child-raced-parent', { work: 'parent' })
3965
+
3966
+ const parentClaim = yield* expectSome('the parent claim', yield* claimLane(parentLane))
3967
+
3968
+ const immediate = yield* parentClaim.session.suspend(
3969
+ WaitingForChildSuspension.make({
3970
+ children: [
3971
+ WaitingChild.make({
3972
+ toolCallId: decodeToolCallId('call-raced-a'),
3973
+ childSubmissionId: settledChild.submissionId,
3974
+ }),
3975
+ ],
3976
+ }),
3977
+ )
3978
+
3979
+ yield* ensure(
3980
+ immediate === 'resume-immediately',
3981
+ 'A suspend listing only settled children must resume immediately',
3982
+ )
3983
+
3984
+ const stillRunning = yield* expectSome(
3985
+ 'lookup after the immediate resume',
3986
+ yield* lookupById(parent.submissionId),
3987
+ )
3988
+
3989
+ yield* ensure(
3990
+ stillRunning.state === 'ready',
3991
+ 'An immediate resume must not transition the parent to suspended',
3992
+ )
3993
+ // The ownership period must survive an immediate resume: the caller keeps working.
3994
+ yield* parentClaim.session.checkActive
3995
+
3996
+ const suspended = yield* parentClaim.session.suspend(
3997
+ WaitingForChildSuspension.make({
3998
+ children: [
3999
+ WaitingChild.make({
4000
+ toolCallId: decodeToolCallId('call-raced-a'),
4001
+ childSubmissionId: settledChild.submissionId,
4002
+ }),
4003
+ WaitingChild.make({
4004
+ toolCallId: decodeToolCallId('call-raced-b'),
4005
+ childSubmissionId: pendingChild.submissionId,
4006
+ }),
4007
+ ],
4008
+ }),
4009
+ )
4010
+
4011
+ yield* ensure(
4012
+ suspended === 'suspended',
4013
+ 'One unsettled listed child must suspend the parent durably',
4014
+ )
4015
+ const snapshot = yield* recoverySnapshot(parent.submissionId)
4016
+
4017
+ yield* ensure(
4018
+ snapshot.suspension !== undefined &&
4019
+ snapshot.suspension.reason._tag === 'WaitingForChild' &&
4020
+ snapshot.suspension.reason.children.length === 2,
4021
+ 'The recovery snapshot must expose the WaitingForChild reason with its children',
4022
+ )
4023
+ }),
4024
+ )
4025
+
4026
+ const admissionParentLinkage = conformanceCase(
4027
+ 'admit records and replays parent linkage',
4028
+ ({ ensure, expectFailure, expectSome }) =>
4029
+ Effect.gen(function*() {
4030
+ const parentLane = decodeThreadId('ledger-conformance-linkage')
4031
+ const childLane = decodeThreadId('ledger-conformance-linkage-child')
4032
+ const ledger = yield* SubmissionLedger
4033
+ const parent = yield* admitReady(parentLane, 'linkage-parent', { work: 'parent' })
4034
+
4035
+ const linkage = ParentLinkage.make({
4036
+ parentSubmissionId: parent.submissionId,
4037
+ parentToolCallId: decodeToolCallId('call-linkage'),
4038
+ })
4039
+
4040
+ const request = yield* admissionRequest(
4041
+ childLane,
4042
+ 'linkage-child-key',
4043
+ { task: 'research' },
4044
+ linkage,
4045
+ )
4046
+
4047
+ const admitted = yield* ledger.admit(request)
4048
+
4049
+ yield* ensure(!admitted.replayed, 'The first linked admission must create the child')
4050
+
4051
+ const byId = yield* expectSome(
4052
+ 'lookup of the linked child',
4053
+ yield* lookupById(admitted.submissionId),
4054
+ )
4055
+
4056
+ yield* ensure(
4057
+ byId.parentLinkage !== undefined &&
4058
+ byId.parentLinkage.parentSubmissionId === parent.submissionId &&
4059
+ byId.parentLinkage.parentToolCallId === linkage.parentToolCallId,
4060
+ 'The child snapshot must expose its immutable parent linkage',
4061
+ )
4062
+ const childSnapshot = yield* recoverySnapshot(admitted.submissionId)
4063
+
4064
+ yield* ensure(
4065
+ childSnapshot.parentLinkage !== undefined &&
4066
+ childSnapshot.parentLinkage.parentSubmissionId === parent.submissionId,
4067
+ 'The child recovery snapshot must expose its parent linkage',
4068
+ )
4069
+
4070
+ const replayed = yield* ledger.admit(request)
4071
+
4072
+ yield* ensure(
4073
+ replayed.replayed &&
4074
+ replayed.submissionId === admitted.submissionId &&
4075
+ replayed.receiptId === admitted.receiptId,
4076
+ 'An identical linked admission must replay the original identities (SUB-016)',
4077
+ )
4078
+
4079
+ const divergentLinkage = yield* expectFailure(
4080
+ 'replaying the admission with a different parent Tool Call',
4081
+ ledger.admit(
4082
+ yield* admissionRequest(
4083
+ childLane,
4084
+ 'linkage-child-key',
4085
+ { task: 'research' },
4086
+ ParentLinkage.make({
4087
+ parentSubmissionId: parent.submissionId,
4088
+ parentToolCallId: decodeToolCallId('call-linkage-other'),
4089
+ }),
4090
+ ),
4091
+ ),
4092
+ )
4093
+
4094
+ yield* ensure(
4095
+ isAdmissionConflict(divergentLinkage),
4096
+ 'A divergent parent linkage must conflict even when the input digest matches',
4097
+ )
4098
+
4099
+ const droppedLinkage = yield* expectFailure(
4100
+ 'replaying the admission without its parent linkage',
4101
+ ledger.admit(yield* admissionRequest(childLane, 'linkage-child-key', { task: 'research' })),
4102
+ )
4103
+
4104
+ yield* ensure(
4105
+ isAdmissionConflict(droppedLinkage),
4106
+ 'Dropping the recorded linkage on replay must conflict',
4107
+ )
4108
+
4109
+ const plain = yield* ledger.admit(
4110
+ yield* admissionRequest(childLane, 'linkage-plain-key', { task: 'plain' }),
4111
+ )
4112
+
4113
+ const addedLinkage = yield* expectFailure(
4114
+ 'replaying an unlinked admission with a parent linkage',
4115
+ ledger.admit(
4116
+ yield* admissionRequest(childLane, 'linkage-plain-key', { task: 'plain' }, linkage),
4117
+ ),
4118
+ )
4119
+
4120
+ yield* ensure(
4121
+ isAdmissionConflict(addedLinkage),
4122
+ 'Adding a linkage to an unlinked admission on replay must conflict',
4123
+ )
4124
+
4125
+ const plainSnapshot = yield* expectSome(
4126
+ 'lookup of the unlinked Submission',
4127
+ yield* lookupById(plain.submissionId),
4128
+ )
4129
+
4130
+ yield* ensure(
4131
+ plainSnapshot.parentLinkage === undefined,
4132
+ 'An unlinked Submission must expose no parent linkage',
4133
+ )
4134
+ }),
4135
+ )
4136
+
4137
+ const resolveAdmissionAuthority = conformanceCase(
4138
+ 'resolveAdmission distinguishes notAdmitted from admitted authoritatively',
4139
+ ({ ensure, expectSome }) =>
4140
+ Effect.gen(function*() {
4141
+ const threadId = decodeThreadId('ledger-conformance-resolve')
4142
+ const ledger = yield* SubmissionLedger
4143
+
4144
+ const key = SubmissionLookupByKey.make({
4145
+ threadId,
4146
+ principal: CONFORMANCE_PRINCIPAL,
4147
+ idempotencyKey: decodeIdempotencyKey('resolve-key-1'),
4148
+ })
4149
+
4150
+ const before = yield* ledger.resolveAdmission(key)
4151
+
4152
+ yield* ensure(
4153
+ before._tag === 'NotAdmitted',
4154
+ 'The authoritative store must prove absence before admission (SUB-031)',
4155
+ )
4156
+
4157
+ const admitted = yield* ledger.admit(
4158
+ yield* admissionRequest(threadId, 'resolve-key-1', { work: 'resolve' }),
4159
+ )
4160
+
4161
+ const after = yield* ledger.resolveAdmission(key)
4162
+
4163
+ yield* ensure(
4164
+ after._tag === 'Admitted' &&
4165
+ after.submission.submissionId === admitted.submissionId &&
4166
+ after.submission.receiptId === admitted.receiptId &&
4167
+ after.submission.state === 'admitted',
4168
+ 'An admitted key must resolve to the full authoritative snapshot',
4169
+ )
4170
+
4171
+ const foreign = yield* ledger.resolveAdmission(
4172
+ SubmissionLookupByKey.make({
4173
+ threadId,
4174
+ principal: OTHER_PRINCIPAL,
4175
+ idempotencyKey: decodeIdempotencyKey('resolve-key-1'),
4176
+ }),
4177
+ )
4178
+
4179
+ yield* ensure(
4180
+ foreign._tag === 'NotAdmitted',
4181
+ 'Admission resolution must stay scoped to the requesting principal',
4182
+ )
4183
+
4184
+ yield* ledger.markReady(MarkReadyRequest.make({ submissionId: admitted.submissionId }))
4185
+
4186
+ const claim = yield* expectSome(
4187
+ 'the claim before terminal resolution',
4188
+ yield* claimLane(threadId),
4189
+ )
4190
+
4191
+ yield* settleClaimed(admitted, claim.session)
4192
+ const settled = yield* ledger.resolveAdmission(key)
4193
+
4194
+ yield* ensure(
4195
+ settled._tag === 'Admitted' &&
4196
+ settled.submission.state === 'settled' &&
4197
+ settled.submission.settledOutcome === 'completed',
4198
+ 'A settled Submission still resolves as admitted — terminality never becomes absence',
4199
+ )
4200
+ }),
4201
+ )
4202
+
4203
+ const queuedAbortSettlementAuthority = conformanceCase(
4204
+ 'publishes an unowned queued abort only under its durable intent',
4205
+ ({ ensure, expectFailure }) =>
4206
+ Effect.gen(function*() {
4207
+ // P7 §7(c): an aborted, never-claimed, still-queued `ready` Submission has no live
4208
+ // ownership to fence against, so its durable abort intent authorizes exactly its
4209
+ // ABORTED settlement — recovery settles it without waiting for it to head the lane.
4210
+ // The authorization is outcome- and state-narrow and stays fail-closed otherwise.
4211
+ const threadId = decodeThreadId('ledger-conformance-queued-abort')
4212
+ const ledger = yield* SubmissionLedger
4213
+
4214
+ const head = yield* admitReady(threadId, 'queued-abort-head', { work: 'head' })
4215
+ const second = yield* admitReady(threadId, 'queued-abort-2', { queued: 2 })
4216
+ const third = yield* admitReady(threadId, 'queued-abort-3', { queued: 3 })
4217
+
4218
+ yield* ledger.requestAbort(
4219
+ AbortCommand.make({
4220
+ submissionId: second.submissionId,
4221
+ author: 'operator',
4222
+ reason: 'cancelled while queued',
4223
+ }),
4224
+ )
4225
+
4226
+ // Fail-closed control: a queued row WITHOUT an abort intent never accepts an unowned
4227
+ // publication, aborted or not.
4228
+ const unaborted = yield* expectFailure(
4229
+ 'publishing an aborted settlement for a queued row without an abort intent',
4230
+ settlementPublication({
4231
+ submissionId: third.submissionId,
4232
+ authority: { _tag: 'QueuedAbort' },
4233
+ receiptId: third.receiptId,
4234
+ outcome: 'aborted',
4235
+ }).pipe(Effect.flatMap((publication) => publishSettlement(publication))),
4236
+ )
4237
+
4238
+ yield* ensure(
4239
+ isLedgerError(unaborted),
4240
+ 'A queued publication without a durable abort intent must stay fenced (LedgerError)',
4241
+ )
4242
+
4243
+ // Fail-closed control: the durable intent authorizes ONLY the aborted outcome.
4244
+ const wrongOutcome = yield* expectFailure(
4245
+ 'publishing a completed settlement for the aborted queued row',
4246
+ settlementPublication({
4247
+ submissionId: second.submissionId,
4248
+ authority: { _tag: 'QueuedAbort' },
4249
+ receiptId: second.receiptId,
4250
+ outcome: 'completed',
4251
+ result: { fabricated: true },
4252
+ }).pipe(Effect.flatMap((publication) => publishSettlement(publication))),
4253
+ )
4254
+
4255
+ yield* ensure(
4256
+ isLedgerError(wrongOutcome),
4257
+ 'An abort intent must never authorize a non-aborted settlement outcome',
4258
+ )
4259
+
4260
+ const publication = yield* settlementPublication({
4261
+ submissionId: second.submissionId,
4262
+ authority: { _tag: 'QueuedAbort' },
4263
+ receiptId: second.receiptId,
4264
+ outcome: 'aborted',
4265
+ })
4266
+
4267
+ const published = yield* publishSettlement(publication)
4268
+
4269
+ yield* ensure(
4270
+ published.replayed === false &&
4271
+ published.record.payload._tag === 'SubmissionSettled' &&
4272
+ published.record.payload.outcome === 'aborted',
4273
+ 'The abort intent must authorize the aborted publication without lane ownership',
4274
+ )
4275
+ // The canonical publication is an immutable replay even before ledger finalization.
4276
+ const replayed = yield* publishSettlement(publication)
4277
+
4278
+ yield* ensure(
4279
+ replayed.replayed === true,
4280
+ 'Replaying the identical aborted publication must short-circuit idempotently',
4281
+ )
4282
+ yield* ledger.finalizeSettlement(
4283
+ SettlementFinalization.make({
4284
+ submissionId: second.submissionId,
4285
+ settlementId: submissionSettlementId(second.submissionId),
4286
+ }),
4287
+ )
4288
+
4289
+ const settled = yield* recoverySnapshot(second.submissionId)
4290
+
4291
+ yield* ensure(
4292
+ settled.submission.state === 'settled' && settled.submission.settledOutcome === 'aborted',
4293
+ 'The aborted queued Submission must settle while the head is still unsettled',
4294
+ )
4295
+ const headState = yield* recoverySnapshot(head.submissionId)
4296
+
4297
+ yield* ensure(
4298
+ headState.submission.state === 'ready',
4299
+ 'Settling the aborted queued row must not disturb the unclaimed head',
4300
+ )
4301
+ }),
4302
+ )
4303
+
4304
+ const abortedSettledRowIsNotAJoiningGap = conformanceCase(
4305
+ 'claimJoining treats an aborted-settled row as a non-gap',
4306
+ ({ ensure, expectSome }) =>
4307
+ Effect.gen(function*() {
4308
+ // P7 §7(c): an aborted-settled row is a CLOSED obligation — the contiguous joining
4309
+ // prefix walks over it so later ready work still joins the host (the pre-P7 rule
4310
+ // treated every settled row as a conservative gap).
4311
+ const threadId = decodeThreadId('ledger-conformance-aborted-non-gap')
4312
+ const ledger = yield* SubmissionLedger
4313
+
4314
+ const host = yield* admitReady(threadId, 'aborted-gap-host', { work: 'host' })
4315
+ const second = yield* admitReady(threadId, 'aborted-gap-2', { queued: 2 })
4316
+ const third = yield* admitReady(threadId, 'aborted-gap-3', { queued: 3 })
4317
+
4318
+ yield* ledger.requestAbort(
4319
+ AbortCommand.make({
4320
+ submissionId: second.submissionId,
4321
+ author: 'operator',
4322
+ reason: 'cancelled while queued',
4323
+ }),
4324
+ )
4325
+
4326
+ const publication = yield* settlementPublication({
4327
+ submissionId: second.submissionId,
4328
+ authority: { _tag: 'QueuedAbort' },
4329
+ receiptId: second.receiptId,
4330
+ outcome: 'aborted',
4331
+ })
4332
+
4333
+ yield* publishSettlement(publication)
4334
+ yield* ledger.finalizeSettlement(
4335
+ SettlementFinalization.make({
4336
+ submissionId: second.submissionId,
4337
+ settlementId: submissionSettlementId(second.submissionId),
4338
+ }),
4339
+ )
4340
+
4341
+ const hostClaim = yield* expectSome('the host claim', yield* claimLane(threadId))
4342
+
4343
+ yield* ensure(
4344
+ hostClaim.submissionId === host.submissionId,
4345
+ 'The host must head the lane (the aborted-settled row is out of the queue)',
4346
+ )
4347
+
4348
+ const claims = yield* hostClaim.session.claimJoining(8)
4349
+
4350
+ yield* ensure(
4351
+ claims.length === 1 && claims[0].submissionId === third.submissionId,
4352
+ 'The joining prefix must skip the aborted-settled row and claim the later ready work',
4353
+ )
4354
+ const settled = yield* recoverySnapshot(second.submissionId)
4355
+
4356
+ yield* ensure(
4357
+ settled.submission.state === 'settled' && settled.submission.settledOutcome === 'aborted',
4358
+ 'Walking the prefix must never disturb the aborted-settled row',
4359
+ )
4360
+ }),
4361
+ )
4362
+
4363
+ const assignmentSettlement = conformanceCase(
4364
+ 'seals terminal assignments atomically while waiting and unapplied corrections remain steerable',
4365
+ ({ ensure, expectSome, expectFailure }) =>
4366
+ Effect.gen(function*() {
4367
+ const ledger = yield* SubmissionLedger
4368
+
4369
+ if (ledger.inspectWorker === undefined) return
4370
+
4371
+ // Each row isolates one ownership rule. The same cases run on every native adapter.
4372
+ const cases = [
4373
+ {
4374
+ name: 'completed',
4375
+ outcome: 'completed',
4376
+ disposition: 'completed',
4377
+ terminal: 'completed',
4378
+ },
4379
+ { name: 'waiting', outcome: 'completed', disposition: 'waiting', terminal: undefined },
4380
+ { name: 'failure', outcome: 'failed', queued: true, terminal: 'failed' },
4381
+ {
4382
+ name: 'failure-joining',
4383
+ outcome: 'failed',
4384
+ queued: true,
4385
+ joining: true,
4386
+ terminal: 'failed',
4387
+ },
4388
+ { name: 'exhaustion', outcome: 'completed', exhausted: true, terminal: 'failed' },
4389
+ { name: 'active-abort', outcome: 'aborted', terminal: 'cancelled' },
4390
+ { name: 'queued-abort', outcome: 'aborted', noRun: true, terminal: undefined },
4391
+ {
4392
+ name: 'reusable',
4393
+ outcome: 'completed',
4394
+ disposition: 'completed',
4395
+ reusable: true,
4396
+ terminal: undefined,
4397
+ },
4398
+ {
4399
+ name: 'late-correction',
4400
+ outcome: 'completed',
4401
+ disposition: 'completed',
4402
+ queued: true,
4403
+ terminal: undefined,
4404
+ },
4405
+ {
4406
+ name: 'applied-correction',
4407
+ outcome: 'completed',
4408
+ disposition: 'completed',
4409
+ queued: true,
4410
+ joined: true,
4411
+ terminal: 'completed',
4412
+ },
4413
+ ] as const
4414
+
4415
+ for (const scenario of cases) {
4416
+ const threadId = decodeThreadId(`assignment-${scenario.name}`)
4417
+ const base = yield* admissionRequest(threadId, 'first', { text: 'first' })
4418
+ const metadata = workerMetadata(base)
4419
+
4420
+ const workerAdmission = WorkerAdmission.make({
4421
+ ...metadata,
4422
+ origin: {
4423
+ ...metadata.origin,
4424
+ ...('reusable' in scenario ? {} : { lifecycle: 'assignment' as const }),
4425
+ },
4426
+ })
4427
+
4428
+ const request = AdmissionRequest.make({ ...base, workerAdmission })
4429
+
4430
+ const first = yield* ledger.admit(request)
4431
+
4432
+ yield* ledger.markReady(MarkReadyRequest.make({ submissionId: first.submissionId }))
4433
+ const claim = yield* expectSome('assignment claim', yield* claimLane(threadId))
4434
+ const runId = runIdForSubmission(first.submissionId)
4435
+
4436
+ const payload = yield* Schema.decodeEffect(SubmissionSettledRecord)(
4437
+ SubmissionSettled.make({
4438
+ submissionId: first.submissionId,
4439
+ settlementId: submissionSettlementId(first.submissionId),
4440
+ receiptId: first.receiptId,
4441
+ outcome: scenario.outcome,
4442
+ ...('noRun' in scenario ? {} : { runId }),
4443
+ ...(scenario.outcome === 'aborted'
4444
+ ? {}
4445
+ : {
4446
+ result: scenario.outcome === 'failed'
4447
+ ? { errorTag: 'TestFailure', message: 'Failed task' }
4448
+ : { answer: 'done' },
4449
+ }),
4450
+ ...('disposition' in scenario ? { runDisposition: scenario.disposition } : {}),
4451
+ ...('exhausted' in scenario
4452
+ ? { finishReason: 'budget-exhausted' as const, exhausted: 'turns' as const }
4453
+ : {}),
4454
+ }),
4455
+ ).pipe(Effect.orDie)
4456
+
4457
+ const record = RecordEnvelope.make({
4458
+ recordId: submissionSettlementRecordId(first.submissionId),
4459
+ family: 'thread',
4460
+ schemaVersion: 1,
4461
+ createdAt: CONFORMANCE_CREATED_AT,
4462
+ deploymentId: CONFORMANCE_DEPLOYMENT,
4463
+ payload,
4464
+ })
4465
+
4466
+ let queued: AdmissionResult | undefined
4467
+
4468
+ if ('queued' in scenario) {
4469
+ const next = yield* admissionRequest(threadId, 'correction', { text: 'correction' })
4470
+
4471
+ queued = yield* ledger.admit(
4472
+ AdmissionRequest.make({
4473
+ ...next,
4474
+ workerAdmission: { ...workerAdmission, messageId: next.idempotencyKey },
4475
+ }),
4476
+ )
4477
+ yield* ledger.markReady(MarkReadyRequest.make({ submissionId: queued.submissionId }))
4478
+ if ('joined' in scenario || 'joining' in scenario) {
4479
+ yield* claim.session.claimJoining(1)
4480
+ }
4481
+ if ('joined' in scenario) {
4482
+ yield* claim.session.markJoined(queued.submissionId, {
4483
+ recordId: submissionInputRecordId(queued.submissionId),
4484
+ sequence: yield* Schema.decodeEffect(CanonicalSequence)(2).pipe(Effect.orDie),
4485
+ })
4486
+ }
4487
+ }
4488
+ yield* publishSettlement(
4489
+ yield* publicationForRecord(first.submissionId, { _tag: 'Owned' }, record),
4490
+ )
4491
+
4492
+ const finalization = SettlementFinalization.make({
4493
+ submissionId: first.submissionId,
4494
+ settlementId: payload.settlementId,
4495
+ })
4496
+
4497
+ const settled = yield* ledger.finalizeSettlement(finalization)
4498
+
4499
+ yield* ensure(
4500
+ Schema.toEquivalence(Settlement)(settled, yield* ledger.finalizeSettlement(finalization)),
4501
+ 'Finalization replay must preserve its exact outcome',
4502
+ )
4503
+ const control = yield* ledger.inspectWorker(threadId)
4504
+
4505
+ yield* ensure(
4506
+ control.terminal === scenario.terminal &&
4507
+ control.stopped === (scenario.terminal !== undefined),
4508
+ `Wrong assignment state for ${scenario.name}`,
4509
+ )
4510
+ yield* ensure(
4511
+ (yield* ledger.admit(request)).receiptId === first.receiptId,
4512
+ 'A seal must preserve same-command receipt replay',
4513
+ )
4514
+ const next = yield* admissionRequest(threadId, 'later', { text: 'later' })
4515
+
4516
+ const later = AdmissionRequest.make({
4517
+ ...next,
4518
+ workerAdmission: { ...workerAdmission, messageId: next.idempotencyKey },
4519
+ })
4520
+
4521
+ if (scenario.terminal !== undefined) {
4522
+ const refusal = yield* expectFailure('terminal admission', ledger.admit(later))
4523
+
4524
+ yield* ensure(
4525
+ Schema.is(AdmissionPolicyError)(refusal) && refusal.code === 'worker-stopped',
4526
+ 'New instructions cannot reopen a terminal assignment',
4527
+ )
4528
+ } else {
4529
+ yield* ledger.admit(later)
4530
+ }
4531
+ if (queued !== undefined) {
4532
+ if ('joining' in scenario) {
4533
+ yield* ledger.revertJoining(
4534
+ RevertJoiningRequest.make({ submissionId: queued.submissionId }),
4535
+ )
4536
+ }
4537
+ const state = yield* recoverySnapshot(queued.submissionId)
4538
+
4539
+ yield* ensure(
4540
+ (state.abortIntent !== undefined) === (scenario.outcome === 'failed'),
4541
+ 'Failure aborts queued inputs; completion never cancels an accepted correction or joined member',
4542
+ )
4543
+ }
4544
+ if (scenario.terminal !== undefined && ledger.stopWorker !== undefined) {
4545
+ yield* ledger.stopWorker({ threadId, author: CONFORMANCE_PRINCIPAL })
4546
+ yield* ensure(
4547
+ (yield* ledger.inspectWorker(threadId)).terminal === scenario.terminal,
4548
+ "Explicit stop cannot replace an assignment's first terminal outcome",
4549
+ )
4550
+ }
4551
+ }
4552
+ }),
4553
+ )
4554
+
4555
+ // Native turn-boundary yielding retained the active FIFO head:
4556
+ // https://github.com/yielded-dev/agent/commit/2259fc05eec3bfac2a92a8d055953f3482e54735
4557
+ const cooperativeHandoff = conformanceCase(
4558
+ 'hands off complete Turns without bypassing ownership, ordering, cancellation or approval',
4559
+ ({ ensure, expectSome }) =>
4560
+ Effect.gen(function*() {
4561
+ const ledger = yield* SubmissionLedger
4562
+
4563
+ for (
4564
+ const scenario of [
4565
+ 'ready',
4566
+ 'live',
4567
+ 'abort',
4568
+ 'approval',
4569
+ 'gap',
4570
+ 'ready-prefix',
4571
+ 'unapplied',
4572
+ 'foreign',
4573
+ ] as const
4574
+ ) {
4575
+ const threadId = decodeThreadId(`ledger-handoff-${scenario}`)
4576
+ const first = yield* admitReady(threadId, 'first', { work: 'old' })
4577
+ const claim = yield* expectSome('original claim', yield* claimLane(threadId))
4578
+
4579
+ if (scenario !== 'unapplied') {
4580
+ yield* claim.session.markInputApplied({
4581
+ recordId: submissionInputRecordId(first.submissionId),
4582
+ sequence: decodeSequence(1),
4583
+ })
4584
+ }
4585
+ if (scenario === 'gap') {
4586
+ yield* ledger.admit(yield* admissionRequest(threadId, 'gap', { work: 'not-ready' }))
4587
+ }
4588
+ if (scenario === 'ready-prefix') yield* admitReady(threadId, 'prefix', { work: 'earlier' })
4589
+ const next = yield* admitReady(threadId, 'next', { work: 'human' })
4590
+
4591
+ const handoff = ClaimHandoff.make({
4592
+ deferredSubmissionIds: [first.submissionId],
4593
+ submissionId: scenario === 'foreign' ? decodeSubmissionId('foreign') : next.submissionId,
4594
+ })
4595
+
4596
+ if (scenario === 'approval') {
4597
+ yield* claim.session.suspend(
4598
+ ApprovalPendingSuspension.make({
4599
+ toolCallIds: [decodeToolCallId('purchase')],
4600
+ }),
4601
+ )
4602
+ } else if (scenario !== 'live') {
4603
+ yield* claim.session.release
4604
+ }
4605
+ if (scenario === 'abort') {
4606
+ yield* ledger.requestAbort(
4607
+ AbortCommand.make({
4608
+ submissionId: first.submissionId,
4609
+ author: 'human',
4610
+ reason: 'stop',
4611
+ }),
4612
+ )
4613
+ }
4614
+ const selected = yield* claimLane(threadId, handoff)
4615
+
4616
+ if (scenario !== 'ready') {
4617
+ yield* ensure(Option.isNone(selected), `Handoff must preserve the ${scenario} boundary`)
4618
+ continue
4619
+ }
4620
+ const nextClaim = yield* expectSome('ordered handoff claim', selected)
4621
+
4622
+ yield* ensure(
4623
+ nextClaim.submissionId === next.submissionId &&
4624
+ nextClaim.session.generation !== claim.session.generation,
4625
+ 'Handoff must claim the next Submission with a new local generation',
4626
+ )
4627
+ const store = yield* ThreadStore
4628
+
4629
+ yield* store.materialize(ThreadMaterialization.make({ threadId }))
4630
+ yield* settleClaimed(next, nextClaim.session)
4631
+
4632
+ const resumed = yield* expectSome('original Run resumes', yield* claimLane(threadId))
4633
+
4634
+ yield* ensure(
4635
+ resumed.submissionId === first.submissionId,
4636
+ 'The deferred Submission must retain its original obligation',
4637
+ )
4638
+ yield* ensure(
4639
+ (yield* recoverySnapshot(first.submissionId)).submission.receiptId === first.receiptId &&
4640
+ (yield* recoverySnapshot(next.submissionId)).submission.receiptId === next.receiptId,
4641
+ 'Handoff must preserve both receipt identities',
4642
+ )
4643
+ }
4644
+ }),
4645
+ )
4646
+
4647
+ /**
4648
+ * The shared, adapter-parameterized SubmissionLedger contract suite (STORE-010). Every durable
4649
+ * ledger adapter test suite must execute each case against its own ledger provisioning, inside
4650
+ * the `@effect/vitest` test environment (TestClock) and with `CryptoDigest.Digest` provided.
4651
+ */
4652
+ export const submissionLedgerConformanceCases: ReadonlyArray<SubmissionLedgerConformanceCase> = [
4653
+ admissionIdempotency,
4654
+ workerAdmissionIdentity,
4655
+ assignmentSettlement,
4656
+ messageAdmissionIdentity,
4657
+ workerCompletionIdentity,
4658
+ workerUpdateIdentity,
4659
+ admissionGroupRace,
4660
+ admissionGroupSettlement,
4661
+ crossPrincipalAdmissionScoping,
4662
+ admissionTupleBoundaries,
4663
+ concurrentAdmissionFifo,
4664
+ fifoHeadClaim,
4665
+ cooperativeHandoff,
4666
+ scopedOwnerExclusion,
4667
+ releaseMakesHeadClaimable,
4668
+ inputAppliedIdempotency,
4669
+ settlementLifecycle,
4670
+ settlementConflicts,
4671
+ abortIdempotency,
4672
+ scanNonterminalWorklist,
4673
+ lookupByIdAndKey,
4674
+ recoverySnapshotConsistency,
4675
+ joiningPrefixClaim,
4676
+ revertJoiningReturnsToReady,
4677
+ markJoinedIdempotency,
4678
+ claimNeverGrantsBlockedHead,
4679
+ approvalDecisionIdempotency,
4680
+ unknownResolutionLifecycle,
4681
+ unknownAbortClaim,
4682
+ suspendResumesImmediatelyWhenDecided,
4683
+ joinedSettlementLinkageAuthority,
4684
+ childReservationIdempotency,
4685
+ childReservationFencing,
4686
+ attachChildIdempotency,
4687
+ beginReleaseFreezesAccountingOnce,
4688
+ releaseAppliedExactlyOnce,
4689
+ recordChildSettledWake,
4690
+ suspendResumesImmediatelyForSettledChildren,
4691
+ admissionParentLinkage,
4692
+ resolveAdmissionAuthority,
4693
+ queuedAbortSettlementAuthority,
4694
+ abortedSettledRowIsNotAJoiningGap,
4695
+ ]