@yielded/agent 0.1.0-beta.174 → 0.1.0-beta.175

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 (175) hide show
  1. package/dist/{Admin-BHmp2V9p.d.mts → Admin-Qa3I1oA5.d.mts} +38 -7
  2. package/dist/{AgentRuntime-BD3ZHAMq.d.mts → AgentRuntime-CHDyRbSf.d.mts} +3 -3
  3. package/dist/{AgentRuntime-B6qZlD3f.mjs → AgentRuntime-DaDKMasp.mjs} +123 -114
  4. package/dist/AgentRuntime-DaDKMasp.mjs.map +1 -0
  5. package/dist/{Digest-EpeqWEdv.mjs → Digest-C3EODOee.mjs} +2 -2
  6. package/dist/{Digest-EpeqWEdv.mjs.map → Digest-C3EODOee.mjs.map} +1 -1
  7. package/dist/{DurableAgentRuntime-CBBjRNJN.mjs → DurableAgentRuntime-CPlw5_7e.mjs} +161 -85
  8. package/dist/DurableAgentRuntime-CPlw5_7e.mjs.map +1 -0
  9. package/dist/{EventSource-C9aaJaXT.d.mts → EventSource-BTu68yDW.d.mts} +2 -2
  10. package/dist/InMemory.d.mts +2 -2
  11. package/dist/{MessageDelivery-BGDm-c46.d.mts → MessageDelivery-DjAZJ4Fd.d.mts} +4 -4
  12. package/dist/{MessagingHost-CRUK4JBi.mjs → MessagingHost-CZCyrnvJ.mjs} +27 -26
  13. package/dist/MessagingHost-CZCyrnvJ.mjs.map +1 -0
  14. package/dist/{PreparedInputAdmission-BvDqlgiP.d.mts → PreparedInputAdmission-wgY4JMZY.d.mts} +3 -3
  15. package/dist/{Records-BiuJDWNe.mjs → Records-DzL4Kbtw.mjs} +2 -2
  16. package/dist/{Records-BiuJDWNe.mjs.map → Records-DzL4Kbtw.mjs.map} +1 -1
  17. package/dist/{RunContinuation-CTJ1jGrO.d.mts → RunContinuation-3jB5pULC.d.mts} +10 -4
  18. package/dist/{RunContinuation-4ZATcVLB.mjs → RunContinuation-BiyKJK32.mjs} +74 -40
  19. package/dist/RunContinuation-BiyKJK32.mjs.map +1 -0
  20. package/dist/{RunJournal-CNZqA3Ge.mjs → RunJournal-CPMKcfd0.mjs} +84 -79
  21. package/dist/RunJournal-CPMKcfd0.mjs.map +1 -0
  22. package/dist/{RunStorage-BHjuuERI.mjs → RunStorage-CzutHJBE.mjs} +3 -2
  23. package/dist/RunStorage-CzutHJBE.mjs.map +1 -0
  24. package/dist/{Scheduling-NG8slKdI.mjs → Scheduling-07_dsGED.mjs} +3 -3
  25. package/dist/{Scheduling-NG8slKdI.mjs.map → Scheduling-07_dsGED.mjs.map} +1 -1
  26. package/dist/{Subagent-CTIpnzlB.mjs → Subagent-CexndZSp.mjs} +2 -2
  27. package/dist/{Subagent-CTIpnzlB.mjs.map → Subagent-CexndZSp.mjs.map} +1 -1
  28. package/dist/{Subagent-DKhZA72u.d.mts → Subagent-xhN_aD1r.d.mts} +3 -3
  29. package/dist/{Subscription-BNg9VCRl.d.mts → Subscription-DmIHlOJK.d.mts} +2 -2
  30. package/dist/{SubscriptionInput-BUoXv-_K.d.mts → SubscriptionInput-DgcQhvbe.d.mts} +2 -2
  31. package/dist/{Thread-dk-QiNml.d.mts → Thread-DzdJAY4J.d.mts} +4 -3
  32. package/dist/{ThreadHistory-ByxS8HU1.d.mts → ThreadHistory-KPPBJLJb.d.mts} +12 -2
  33. package/dist/{ThreadImport-CodYoJoa.mjs → ThreadImport-CjlG57vH.mjs} +8 -8
  34. package/dist/{ThreadImport-CodYoJoa.mjs.map → ThreadImport-CjlG57vH.mjs.map} +1 -1
  35. package/dist/{ThreadImport-CMgzttvr.d.mts → ThreadImport-DP-vOk2F.d.mts} +4 -4
  36. package/dist/{ThreadStore-59uDGXul.mjs → ThreadStore-EuUilthA.mjs} +5 -7
  37. package/dist/ThreadStore-EuUilthA.mjs.map +1 -0
  38. package/dist/{ThreadTransfer-3jigUl3g.mjs → ThreadTransfer-DB_zsrtJ.mjs} +4 -4
  39. package/dist/{ThreadTransfer-3jigUl3g.mjs.map → ThreadTransfer-DB_zsrtJ.mjs.map} +1 -1
  40. package/dist/{WorkerAdmission-DDYJdOsU.mjs → WorkerAdmission-eBeXt_mu.mjs} +5 -5
  41. package/dist/{WorkerAdmission-DDYJdOsU.mjs.map → WorkerAdmission-eBeXt_mu.mjs.map} +1 -1
  42. package/dist/{agent-registration-DRbyhAu-.mjs → agent-registration-a6QYaG3h.mjs} +4 -4
  43. package/dist/{agent-registration-DRbyhAu-.mjs.map → agent-registration-a6QYaG3h.mjs.map} +1 -1
  44. package/dist/capabilities/Messaging.mjs +1 -1
  45. package/dist/capabilities/ModelContext.d.mts +1 -1
  46. package/dist/capabilities/RunHooks.d.mts +1 -1
  47. package/dist/capabilities/Subagent.d.mts +1 -1
  48. package/dist/capabilities/Subagent.mjs +1 -1
  49. package/dist/core/Thread.d.mts +2 -2
  50. package/dist/core/Thread.mjs +5 -3
  51. package/dist/core/Thread.mjs.map +1 -1
  52. package/dist/durable/ActivityStore.mjs +1 -1
  53. package/dist/durable/Admin.d.mts +1 -1
  54. package/dist/durable/Admin.mjs +1 -1
  55. package/dist/durable/AgentRegistration.d.mts +1 -1
  56. package/dist/durable/AgentRegistration.mjs +1 -1
  57. package/dist/durable/Certification.d.mts +1 -1
  58. package/dist/durable/CommittedActivity.d.mts +1 -1
  59. package/dist/durable/CommittedActivity.mjs +3 -3
  60. package/dist/durable/Digest.mjs +1 -1
  61. package/dist/durable/DurableAgentRuntime.d.mts +1 -1
  62. package/dist/durable/DurableAgentRuntime.mjs +2 -2
  63. package/dist/durable/EventSource.d.mts +1 -1
  64. package/dist/durable/EventSource.mjs +1 -1
  65. package/dist/durable/GitHubWorkflowSource.d.mts +3 -3
  66. package/dist/durable/LifecyclePublication.d.mts +1 -1
  67. package/dist/durable/LifecyclePublication.mjs +2 -2
  68. package/dist/durable/MessageDelivery.d.mts +1 -1
  69. package/dist/durable/MessageDelivery.mjs +2 -2
  70. package/dist/durable/MessageDeliveryStoreConformance.d.mts +40 -40
  71. package/dist/durable/MessageDeliveryStoreConformance.mjs +2 -2
  72. package/dist/durable/PersistentHistory.d.mts +2 -2
  73. package/dist/durable/PersistentHistory.mjs +4 -4
  74. package/dist/durable/PreparedInputAdmission.d.mts +1 -1
  75. package/dist/durable/RecordFormat.mjs +1 -1
  76. package/dist/durable/Records.mjs +1 -1
  77. package/dist/durable/Recovery.d.mts +1 -1
  78. package/dist/durable/Recovery.mjs +1 -1
  79. package/dist/durable/RunContinuation.d.mts +2 -2
  80. package/dist/durable/RunContinuation.mjs +3 -3
  81. package/dist/durable/RunJournal.d.mts +2 -2
  82. package/dist/durable/RunJournal.mjs +2 -2
  83. package/dist/durable/RunStorage.d.mts +1 -1
  84. package/dist/durable/RunStorage.mjs +1 -1
  85. package/dist/durable/Schedule.mjs +1 -1
  86. package/dist/durable/ScheduleStoreConformance.mjs +1 -1
  87. package/dist/durable/ScheduleTransition.mjs +1 -1
  88. package/dist/durable/Scheduling.d.mts +1 -1
  89. package/dist/durable/Scheduling.mjs +1 -1
  90. package/dist/durable/SettlementPublisher.d.mts +1 -1
  91. package/dist/durable/SettlementPublisher.mjs +3 -3
  92. package/dist/durable/SqlMemoryStore.mjs +5 -3
  93. package/dist/durable/SqlMemoryStore.mjs.map +1 -1
  94. package/dist/durable/SubmissionLedger.d.mts +1 -1
  95. package/dist/durable/SubmissionLedger.mjs +7 -3
  96. package/dist/durable/SubmissionLedger.mjs.map +1 -1
  97. package/dist/durable/SubmissionLedgerConformance.d.mts +1 -1
  98. package/dist/durable/SubmissionLedgerConformance.mjs +6 -6
  99. package/dist/durable/SubmissionStatus.d.mts +1 -1
  100. package/dist/durable/Subscription.d.mts +1 -1
  101. package/dist/durable/Subscription.mjs +2 -2
  102. package/dist/durable/SubscriptionInput.d.mts +1 -1
  103. package/dist/durable/SubscriptionInput.mjs +2 -2
  104. package/dist/durable/SubscriptionStoreConformance.d.mts +1 -1
  105. package/dist/durable/SubscriptionStoreConformance.mjs +1 -1
  106. package/dist/durable/SubscriptionTools.d.mts +2 -2
  107. package/dist/durable/SubscriptionTransition.d.mts +1 -1
  108. package/dist/durable/SubscriptionTransition.mjs +1 -1
  109. package/dist/durable/Subscriptions.d.mts +5 -5
  110. package/dist/durable/Subscriptions.mjs +2 -2
  111. package/dist/durable/ThreadArchiveRange.d.mts +1 -1
  112. package/dist/durable/ThreadArchiveRange.mjs +1 -1
  113. package/dist/durable/ThreadContextHistory.d.mts +1 -1
  114. package/dist/durable/ThreadContextHistory.mjs +2 -2
  115. package/dist/durable/ThreadContextHistoryProjection.mjs +1 -1
  116. package/dist/durable/ThreadImport.d.mts +1 -1
  117. package/dist/durable/ThreadImport.mjs +1 -1
  118. package/dist/durable/ThreadInvariants.d.mts +3 -3
  119. package/dist/durable/ThreadInvariants.mjs +4 -4
  120. package/dist/durable/ThreadProjection.mjs +1 -1
  121. package/dist/durable/ThreadProjectionMaintenance.d.mts +1 -1
  122. package/dist/durable/ThreadReader.d.mts +1 -1
  123. package/dist/durable/ThreadReader.mjs +1 -1
  124. package/dist/durable/ThreadStore.d.mts +1 -1
  125. package/dist/durable/ThreadStore.mjs +2 -2
  126. package/dist/durable/ThreadStoreConformance.d.mts +1 -1
  127. package/dist/durable/ThreadStoreConformance.mjs +4 -4
  128. package/dist/durable/ThreadTransfer.d.mts +1 -1
  129. package/dist/durable/ThreadTransfer.mjs +1 -1
  130. package/dist/durable/ThreadWork.d.mts +2 -2
  131. package/dist/durable/ThreadWork.mjs +12 -6
  132. package/dist/durable/ThreadWork.mjs.map +1 -1
  133. package/dist/durable/ToolReconciler.mjs +1 -1
  134. package/dist/durable/WakeScheduler.mjs +23 -39
  135. package/dist/durable/WakeScheduler.mjs.map +1 -1
  136. package/dist/durable/WorkerAdmission.d.mts +1 -1
  137. package/dist/durable/WorkerAdmission.mjs +1 -1
  138. package/dist/durable/WorkerHost.d.mts +1 -1
  139. package/dist/engine/AgentRuntime.d.mts +1 -1
  140. package/dist/engine/AgentRuntime.mjs +1 -1
  141. package/dist/engine/MessagingHost.mjs +1 -1
  142. package/dist/engine/Output.mjs +1 -1
  143. package/dist/engine/ThreadHistory.d.mts +1 -1
  144. package/dist/engine/ThreadHistory.mjs +3 -2
  145. package/dist/engine/ThreadHistory.mjs.map +1 -1
  146. package/dist/index.d.mts +12 -12
  147. package/dist/index.mjs +13 -13
  148. package/dist/{output-contract-CMIhu4Cw.mjs → output-contract-DCnLYCdp.mjs} +12 -15
  149. package/dist/{output-contract-CMIhu4Cw.mjs.map → output-contract-DCnLYCdp.mjs.map} +1 -1
  150. package/dist/{run-context-reader-CC7ZD95F.d.mts → run-context-reader-DVhJZ1Qe.d.mts} +2 -2
  151. package/package.json +1 -1
  152. package/src/core/Thread.ts +143 -146
  153. package/src/durable/DurableAgentRuntime.ts +381 -206
  154. package/src/durable/RunContinuation.ts +113 -62
  155. package/src/durable/RunJournal.ts +99 -108
  156. package/src/durable/RunStorage.ts +7 -0
  157. package/src/durable/SqlMemoryStore.ts +8 -6
  158. package/src/durable/SubmissionLedger.ts +7 -0
  159. package/src/durable/ThreadStore.ts +9 -7
  160. package/src/durable/ThreadWork.ts +10 -0
  161. package/src/durable/WakeScheduler.ts +34 -66
  162. package/src/durable/internal/usage-totals.ts +28 -31
  163. package/src/engine/MessagingHost.ts +4 -2
  164. package/src/engine/ThreadHistory.ts +47 -48
  165. package/src/engine/internal/agent-runtime.ts +234 -202
  166. package/src/engine/internal/output-contract.ts +15 -15
  167. package/src/engine/internal/primitive-delta.ts +2 -3
  168. package/src/engine/internal/tool-telemetry.ts +3 -5
  169. package/dist/AgentRuntime-B6qZlD3f.mjs.map +0 -1
  170. package/dist/DurableAgentRuntime-CBBjRNJN.mjs.map +0 -1
  171. package/dist/MessagingHost-CRUK4JBi.mjs.map +0 -1
  172. package/dist/RunContinuation-4ZATcVLB.mjs.map +0 -1
  173. package/dist/RunJournal-CNZqA3Ge.mjs.map +0 -1
  174. package/dist/RunStorage-BHjuuERI.mjs.map +0 -1
  175. package/dist/ThreadStore-59uDGXul.mjs.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"file":"MessagingHost-CRUK4JBi.mjs","names":[],"sources":["../src/core/Messaging.ts","../src/engine/MessagingHost.ts"],"sourcesContent":["import * as Schema from \"effect/Schema\";\n\nimport { AgentId, ThreadId } from \"./Identifiers.ts\";\nimport { MessageRef } from \"./internal/message-status.ts\";\nimport { FrameworkMessage } from \"./Worker.ts\";\n\nexport { MessageRef, MessageStatus } from \"./internal/message-status.ts\";\n\n/** Application-chosen fixed route name; it never authorizes a destination by itself. */\nexport const PeerName = Schema.NonEmptyString.check(\n Schema.isMaxLength(64),\n Schema.isPattern(/^[a-zA-Z0-9_-]+$/u),\n);\n\nexport type PeerName = typeof PeerName.Type;\n\nexport const MessageAddress = Schema.Struct({ threadId: ThreadId, agentId: AgentId });\nexport type MessageAddress = typeof MessageAddress.Type;\n\n/** Host-authenticated provenance stored separately from destination-owned application input. */\nexport const MessageAdmission = Schema.Struct({\n schemaVersion: Schema.Literal(1),\n message: MessageRef,\n peerName: PeerName,\n sender: MessageAddress,\n returnAddress: MessageAddress,\n inReplyTo: Schema.optionalKey(MessageRef),\n}).check(\n Schema.makeFilter(\n (value) =>\n value.message.ownerThreadId === value.sender.threadId &&\n value.sender.threadId === value.returnAddress.threadId &&\n value.sender.agentId === value.returnAddress.agentId,\n ),\n);\n\nexport type MessageAdmission = typeof MessageAdmission.Type;\n\nexport const InboxEntry = Schema.Struct({\n sequence: Schema.Natural.check(Schema.isGreaterThan(0)),\n admission: MessageAdmission,\n});\n\nexport type InboxEntry = typeof InboxEntry.Type;\n\nexport const InboxPage = Schema.Struct({\n items: Schema.Array(InboxEntry).check(Schema.isMaxLength(100)),\n next: Schema.NullOr(Schema.Natural),\n});\n\nexport type InboxPage = typeof InboxPage.Type;\n\nexport class MessagingError extends Schema.TaggedError<MessagingError>()(\"MessagingError\", {\n operation: Schema.Literals([\"context\", \"send\", \"reply\", \"inbox\", \"inspect\", \"retry\"]),\n reason: Schema.Literals([\n \"denied\",\n \"unavailable\",\n \"route-unavailable\",\n \"binding-mismatch\",\n \"invalid-input\",\n \"invalid-reference\",\n \"conflict\",\n \"capacity\",\n \"not-found\",\n \"storage\",\n \"corrupt\",\n ]),\n}) {}\n\n/** Canonical input provenance: peer input or a framework-owned completion message. */\nexport const InputMessage = Schema.Union([MessageAdmission, FrameworkMessage]);\nexport type InputMessage = typeof InputMessage.Type;\n","import type { Effect } from \"effect\";\nimport * as Context from \"effect/Context\";\n\nimport type { AnyDefinition } from \"../core/Agent.ts\";\nimport type { ThreadId } from \"../core/Identifiers.ts\";\nimport {\n type InboxPage,\n type MessageAddress,\n type MessageRef,\n type MessageStatus,\n MessagingError,\n} from \"../core/Messaging.ts\";\nimport type { IdempotencyKey, Principal } from \"../core/Receipt.ts\";\nimport type { WorkerSource } from \"../core/Worker.ts\";\n\nexport interface PeerTarget {\n readonly name: string;\n readonly target: AnyDefinition;\n}\n\n/** A fixed declaration chooses the route. Caller input never selects a destination Thread. */\nexport interface SendPeerMessage extends PeerTarget {\n readonly encodedInput: unknown;\n readonly idempotencyKey: IdempotencyKey;\n /** Correlation on sends; replies additionally resolve and authorize the recorded return address. */\n readonly inReplyTo?: MessageRef;\n}\n\n/** Trusted per-invocation facet. It carries caller authority without exposing it in Tool schemas. */\nexport class MessagingHost extends Context.Service<\n MessagingHost,\n {\n readonly context: Effect.Effect<WorkerSource, MessagingError>;\n readonly send: (request: SendPeerMessage) => Effect.Effect<MessageStatus, MessagingError>;\n readonly reply: (\n request: SendPeerMessage & { readonly inReplyTo: MessageRef },\n ) => Effect.Effect<MessageStatus, MessagingError>;\n readonly inbox: (\n request: PeerTarget & { readonly after?: number; readonly limit: number },\n ) => Effect.Effect<InboxPage, MessagingError>;\n readonly inspect: (\n request: PeerTarget & { readonly message: MessageRef },\n ) => Effect.Effect<MessageStatus, MessagingError>;\n readonly retry: (\n request: PeerTarget & { readonly message: MessageRef },\n ) => Effect.Effect<MessageStatus, MessagingError>;\n }\n>()(\"@effect-agent/engine/MessagingHost\") {\n static readonly unavailable: MessagingHost[\"Service\"] = {\n context: MessagingError.make({ operation: \"context\", reason: \"unavailable\" }),\n send: () => MessagingError.make({ operation: \"send\", reason: \"unavailable\" }),\n reply: () => MessagingError.make({ operation: \"reply\", reason: \"unavailable\" }),\n inbox: () => MessagingError.make({ operation: \"inbox\", reason: \"unavailable\" }),\n inspect: () => MessagingError.make({ operation: \"inspect\", reason: \"unavailable\" }),\n retry: () => MessagingError.make({ operation: \"retry\", reason: \"unavailable\" }),\n };\n\n /** Runtime-owned per-call binding. Unconfigured Runs deny peer operations. */\n static readonly forTool = Context.Reference<\n (source: Extract<WorkerSource, { readonly _tag: \"tool\" }>) => MessagingHost[\"Service\"]\n >(\"@effect-agent/engine/MessagingHost/forTool\", {\n defaultValue: () => () => MessagingHost.unavailable,\n });\n}\n\n/** Separate context, history, send and management grants; incoming messages grant none of them. */\nexport interface PeerAuthorizationRequest {\n readonly source: MessageAddress;\n readonly principal: Principal;\n readonly operation: MessagingError[\"operation\"];\n readonly access: \"context\" | \"read\" | \"send\" | \"control\";\n readonly peerName?: string;\n readonly destination?: MessageAddress;\n}\n\nexport const PeerAuthorizer = Context.Reference<{\n /** Return the stable delivery principal for sends. It is retained with the frozen envelope. */\n readonly authorize: (\n request: PeerAuthorizationRequest,\n ) => Effect.Effect<Principal, MessagingError>;\n}>(\"@effect-agent/thread/PeerAuthorizer\", {\n defaultValue: () => ({\n authorize: (request) => MessagingError.make({ operation: request.operation, reason: \"denied\" }),\n }),\n});\n\n/** Application-owned routing; the target Agent is resolved from the existing exact registrations. */\nexport const PeerRoutes = Context.Reference<{\n readonly resolve: (request: {\n readonly source: MessageAddress;\n readonly principal: Principal;\n readonly peerName: string;\n readonly targetAgentId: MessageAddress[\"agentId\"];\n }) => Effect.Effect<ThreadId, MessagingError>;\n}>(\"@effect-agent/thread/PeerRoutes\", {\n defaultValue: () => ({\n resolve: () => MessagingError.make({ operation: \"send\", reason: \"route-unavailable\" }),\n }),\n});\n\n/**\n * Finite delivery and retained-send window in milliseconds (default one day, maximum seven days).\n * Exhaustion parks outstanding work; terminal sends stop consuming capacity at this deadline.\n */\nexport const PeerDeliveryLifetime = Context.Reference<number>(\n \"@effect-agent/thread/PeerDeliveryLifetime\",\n { defaultValue: () => 86_400_000 },\n);\n\n/**\n * Bound outstanding sends plus terminal sends still inside their delivery window, across all peers\n * and principals in one source Thread (default 256, maximum 1,000). Canonical history and exact\n * idempotent receipts remain retained after expiry without consuming this capacity.\n */\nexport const PeerMessageCapacity = Context.Reference<number>(\n \"@effect-agent/thread/PeerMessageCapacity\",\n { defaultValue: () => 256 },\n);\n"],"mappings":";;;;;;;AASA,MAAa,WAAW,OAAO,eAAe,MAC5C,OAAO,YAAY,EAAE,GACrB,OAAO,UAAU,mBAAmB,CACtC;AAIA,MAAa,iBAAiB,OAAO,OAAO;CAAE,UAAU;CAAU,SAAS;AAAQ,CAAC;;AAIpF,MAAa,mBAAmB,OAAO,OAAO;CAC5C,eAAe,OAAO,QAAQ,CAAC;CAC/B,SAAS;CACT,UAAU;CACV,QAAQ;CACR,eAAe;CACf,WAAW,OAAO,YAAY,UAAU;AAC1C,CAAC,CAAC,CAAC,MACD,OAAO,YACJ,UACC,MAAM,QAAQ,kBAAkB,MAAM,OAAO,YAC7C,MAAM,OAAO,aAAa,MAAM,cAAc,YAC9C,MAAM,OAAO,YAAY,MAAM,cAAc,OACjD,CACF;AAIA,MAAa,aAAa,OAAO,OAAO;CACtC,UAAU,OAAO,QAAQ,MAAM,OAAO,cAAc,CAAC,CAAC;CACtD,WAAW;AACb,CAAC;AAID,MAAa,YAAY,OAAO,OAAO;CACrC,OAAO,OAAO,MAAM,UAAU,CAAC,CAAC,MAAM,OAAO,YAAY,GAAG,CAAC;CAC7D,MAAM,OAAO,OAAO,OAAO,OAAO;AACpC,CAAC;AAID,IAAa,iBAAb,cAAoC,OAAO,YAA4B,CAAC,CAAC,kBAAkB;CACzF,WAAW,OAAO,SAAS;EAAC;EAAW;EAAQ;EAAS;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@@
1
- {"version":3,"file":"RunContinuation-4ZATcVLB.mjs","names":["failure"],"sources":["../src/durable/internal/evidence.ts","../src/durable/internal/run-context-reader.ts","../src/durable/internal/run-context.ts","../src/durable/RunContinuation.ts"],"sourcesContent":["import { Effect, Option } from \"effect\";\n\nimport type { ThreadId } from \"../../core/Identifiers.ts\";\nimport { EvidenceReference, type RecordEnvelope } from \"../Records.ts\";\nimport { getRecord, ThreadStoreError } from \"../ThreadStore.ts\";\n\nconst failure = (message: string, cause?: unknown) =>\n ThreadStoreError.make({\n operation: \"RunContinuation\",\n message,\n ...(cause === undefined ? {} : { cause }),\n });\n\n/** References identify immutable facts; schema and owning readers validate their meaning. */\nexport const reference = (record: RecordEnvelope) =>\n Effect.succeed(EvidenceReference.make({ recordId: record.recordId }));\n\n/** Resolve an immutable fact by Thread and record identity. A failed reference leaves the original work owed. */\nexport const resolveEvidence = Effect.fnUntraced(function* (\n threadId: ThreadId,\n ref: EvidenceReference,\n) {\n const found = yield* getRecord({ threadId, recordId: ref.recordId });\n\n if (Option.isNone(found)) return yield* failure(\"Required canonical evidence is unavailable\");\n\n return found.value;\n});\n","import { Context, Effect, Layer, Option, type Stream } from \"effect\";\n\nimport type { ThreadId } from \"../../core/Identifiers.ts\";\nimport type { CanonicalRecordEnvelope, RecordId } from \"../Records.ts\";\nimport {\n getRecord,\n ThreadReader,\n type ThreadNotMaterialized,\n type ThreadStoreError,\n type ThreadPromptRead,\n} from \"../ThreadStore.ts\";\nimport type { JournalRecordEnvelope } from \"./journal-metadata.ts\";\n\n/** Canonical history access bound by the recovery or verification-snapshot owner. */\nexport class RunContextReader extends Context.Service<\n RunContextReader,\n {\n /** Recovery decodes the prompt view; verification supplies full canonical envelopes. */\n readonly read: (\n request: ThreadPromptRead,\n ) => Stream.Stream<JournalRecordEnvelope, ThreadStoreError | ThreadNotMaterialized>;\n readonly record: (\n recordId: RecordId,\n ) => Effect.Effect<\n CanonicalRecordEnvelope | undefined,\n ThreadStoreError | ThreadNotMaterialized\n >;\n }\n>()(\"@effect-agent/thread/RunContextReader\") {\n static layer(threadId: ThreadId) {\n return Layer.effect(\n RunContextReader,\n Effect.gen(function* () {\n const reader = yield* ThreadReader;\n\n return RunContextReader.of({\n read: reader.readPrompt,\n record: (recordId) =>\n getRecord({ threadId, recordId }).pipe(\n Effect.provideService(ThreadReader, reader),\n Effect.map(Option.getOrUndefined),\n ),\n });\n }),\n );\n }\n}\n","import { type Crypto, Effect, Schema, Stream } from \"effect\";\nimport { Prompt } from \"effect/ai\";\n\nimport { canonicalJson, digestCanonicalJson } from \"../Digest.ts\";\nimport {\n CanonicalSequence,\n PromptRecord,\n type RecordId,\n PROMPT_EVIDENCE_TAGS,\n type CanonicalRecordEnvelope,\n type RunContextRecorded,\n} from \"../Records.ts\";\nimport {\n projectRunJournalStream,\n RunJournalError,\n type RunJournalContext,\n type JournalBoundary,\n} from \"../RunJournal.ts\";\nimport type { ThreadNotMaterialized, ThreadStoreError } from \"../ThreadStore.ts\";\nimport type { JournalRecordEnvelope } from \"./journal-metadata.ts\";\nimport { RunContextReader } from \"./run-context-reader.ts\";\n\nconst invalid = (message: string) => RunJournalError.make({ message });\nconst encodePrompt = Schema.encodeEffect(Schema.toCodecJson(Prompt.Prompt));\n\nconst decodePromptRecord = Schema.decodeUnknownEffect(PromptRecord);\nconst promptTags = new Set<string>(PROMPT_EVIDENCE_TAGS);\n\nconst projectHistoryRecord = (\n entry: JournalRecordEnvelope,\n ownerRunId: RunContextRecorded[\"runId\"],\n): Effect.Effect<JournalRecordEnvelope> => {\n if (!(\"batchId\" in entry)) return Effect.succeed(entry);\n const payload = entry.record.payload;\n\n if ((\"runId\" in payload && payload.runId === ownerRunId) || !promptTags.has(payload._tag))\n return Effect.succeed(entry);\n\n return decodePromptRecord({ recordId: entry.record.recordId, payload }).pipe(\n Effect.map((record) => ({ threadId: entry.threadId, sequence: entry.sequence, record })),\n // Coverage and later canonical validation must retain their original error precedence.\n Effect.catchTag(\"SchemaError\", () => Effect.succeed(entry)),\n );\n};\n\nexport const encodeRunHistory = (prompt: Prompt.Prompt) =>\n encodePrompt(prompt).pipe(\n Effect.map(canonicalJson),\n Effect.mapError((cause) =>\n RunJournalError.make({ message: \"Original model history integrity is unavailable\", cause }),\n ),\n );\n\nexport const digestRunHistory = (prompt: Prompt.Prompt) =>\n encodeRunHistory(prompt).pipe(\n Effect.flatMap(digestCanonicalJson),\n Effect.mapError((cause) =>\n RunJournalError.make({ message: \"Original model history integrity is unavailable\", cause }),\n ),\n );\n\nexport const validateContextBoundary = (\n context: RunContextRecorded,\n original: CanonicalRecordEnvelope,\n): Effect.Effect<void, RunJournalError> =>\n original.record.payload._tag !== \"UserInputRecorded\" ||\n original.record.payload.kind !== \"user\" ||\n original.record.payload.runId !== context.runId ||\n context.historyThrough + 1 !== original.sequence ||\n context.historyFrom < 1 ||\n context.historyFrom > original.sequence ||\n context.retained.some(\n (ref, index) =>\n ref.sequence <= (context.retained[index - 1]?.sequence ?? 0) ||\n ref.sequence >= context.historyFrom,\n )\n ? Effect.fail(invalid(\"Saved context has an invalid original admission boundary\"))\n : Effect.void;\n\ntype ProjectedRunHistory = Pick<\n RunJournalContext,\n \"prompt\" | \"historyFrom\" | \"contextWindowId\" | \"boundaries\"\n>;\n\n/** Reconstruct the exact saved range using the owner's history validation boundary. */\nconst readProjectedHistory = Effect.fnUntraced(function* (\n context: RunContextRecorded,\n original: CanonicalRecordEnvelope,\n): Effect.fn.Return<\n ProjectedRunHistory,\n RunJournalError | ThreadStoreError | ThreadNotMaterialized,\n RunContextReader | Crypto.Crypto\n> {\n yield* validateContextBoundary(context, original);\n const reader = yield* RunContextReader;\n const records: Array<JournalRecordEnvelope> = [];\n\n for (const ref of context.retained) {\n const entry = yield* reader.record(ref.recordId);\n\n if (\n entry === undefined ||\n entry.threadId !== original.threadId ||\n entry.record.recordId !== ref.recordId ||\n entry.sequence !== ref.sequence\n )\n return yield* invalid(\"Saved context has missing or corrupt retained evidence\");\n records.push(yield* projectHistoryRecord(entry, context.runId));\n }\n\n let after = CanonicalSequence.make(context.historyFrom - 1);\n\n while (after < context.historyThrough) {\n const page = yield* reader\n .read({\n threadId: original.threadId,\n throughSequence: context.historyThrough,\n afterSequence: after,\n limit: 8,\n })\n .pipe(Stream.take(9), Stream.runCollect);\n\n if (page.length > 8) return yield* invalid(\"Saved context page exceeds its record bound\");\n for (const entry of page) {\n if (\n entry.threadId !== original.threadId ||\n entry.sequence <= after ||\n entry.sequence > context.historyThrough\n )\n return yield* invalid(\"Saved context range has invalid canonical ordering\");\n after = entry.sequence;\n records.push(yield* projectHistoryRecord(entry, context.runId));\n }\n if (page.length < 8) break;\n }\n\n let through = 0;\n const retained = new Map(context.retained.map((ref) => [ref.sequence, ref.recordId]));\n\n for (const entry of records) {\n if (\n entry.threadId !== original.threadId ||\n entry.sequence <= through ||\n entry.sequence > context.historyThrough ||\n (entry.sequence < context.historyFrom &&\n retained.get(entry.sequence) !== entry.record.recordId)\n )\n return yield* invalid(\"Saved context has invalid canonical range evidence\");\n through = entry.sequence;\n retained.delete(entry.sequence);\n }\n if (retained.size !== 0) return yield* invalid(\"Saved context is missing retained evidence\");\n\n const boundaries: Array<JournalBoundary> = [];\n\n records.push(original);\n\n const history = yield* projectRunJournalStream(\n Stream.fromIterable(records),\n context.runId,\n (boundary) => boundaries.push(boundary),\n );\n\n return {\n prompt: history.prompt,\n historyFrom: history.historyFrom,\n boundaries,\n ...(history.contextWindowId === undefined ? {} : { contextWindowId: history.contextWindowId }),\n };\n});\n\n/** Both readers preserve the exact saved context and historyDigest. */\nexport const readRunContext = Effect.fnUntraced(function* (\n context: RunContextRecorded,\n original: CanonicalRecordEnvelope,\n recordId: RecordId,\n): Effect.fn.Return<\n RunJournalContext,\n RunJournalError | ThreadStoreError | ThreadNotMaterialized,\n RunContextReader | Crypto.Crypto\n> {\n const history = yield* readProjectedHistory(context, original);\n const historyDigest = yield* digestRunHistory(history.prompt);\n\n if (\n historyDigest !== context.historyDigest ||\n history.historyFrom !== context.historyFrom ||\n history.prompt.content.length !== context.priorHistoryLength ||\n history.contextWindowId !== context.contextWindowId\n )\n return yield* invalid(\"Saved context differs from its original model history\");\n\n const prefix = yield* Schema.decodeUnknownEffect(Prompt.Prompt)(context.runScopedInput).pipe(\n Effect.mapError(() => invalid(\"Saved Run instructions and input are malformed\")),\n );\n\n return {\n runId: context.runId,\n prompt: Prompt.fromMessages([...history.prompt.content, ...prefix.content]),\n priorHistoryLength: context.priorHistoryLength,\n historyFrom: context.historyFrom,\n boundaries: history.boundaries.filter(\n (boundary) => boundary.promptLength <= context.priorHistoryLength,\n ),\n recordId,\n ...(context.contextWindowId === undefined ? {} : { contextWindowId: context.contextWindowId }),\n };\n});\n","import { Context, DateTime, Effect, Option, Result, Schema, Semaphore, Stream } from \"effect\";\nimport { Prompt } from \"effect/ai\";\n\nimport { AgentPersistenceCapacityError } from \"../core/AgentError.ts\";\nimport type { RunId, SubmissionId, ThreadId } from \"../core/Identifiers.ts\";\nimport { ToolCallId } from \"../core/Identifiers.ts\";\nimport { utf8ByteLength } from \"../core/internal/utf8.ts\";\nimport { reference, resolveEvidence } from \"./internal/evidence.ts\";\nimport { continuationUsage } from \"./internal/usage-totals.ts\";\nexport { reference, resolveEvidence } from \"./internal/evidence.ts\";\nimport {\n captureRecord,\n recordEncoding,\n type ProgressAppendRecord,\n} from \"./internal/record-encoding.ts\";\nimport {\n canonicalRunIds,\n executionRunIds,\n isPreContinuationFact,\n isTerminalBudgetFact,\n} from \"./internal/record-ownership.ts\";\nexport { terminalUsageCharge } from \"./internal/record-ownership.ts\";\nimport { readRunContext, validateContextBoundary } from \"./internal/run-context.ts\";\nimport {\n type CanonicalRecordEnvelope,\n type ContinuationAccounting,\n type DeploymentId,\n CanonicalBatch,\n CanonicalSequence,\n EvidenceReference,\n MAX_RUN_CONTINUATION_BYTES,\n MAX_RUN_EVIDENCE_BYTES,\n MAX_RUN_TERMINAL_BYTES,\n MAX_RUN_EVIDENCE_RECORDS,\n MAX_RUN_RECOVERY_SUFFIX_BYTES,\n MAX_RUN_RECOVERY_SUFFIX_RECORDS,\n MAX_TURN_CANONICAL_BYTES,\n MAX_PERSISTED_JSON_BYTES,\n RUN_TERMINAL_RESERVE_BYTES,\n RUN_TERMINAL_RESERVE_RECORDS,\n RecordEnvelope,\n RecordId,\n RunContinuation,\n type ModelResponseRecorded,\n type ToolCallSettled,\n} from \"./Records.ts\";\nimport {\n runIdForSubmission,\n runCompletedRecordId,\n toolCallSettledRecordId,\n toolCallResultBatchId,\n subagentRequestedRecordId,\n subagentStartedRecordId,\n} from \"./RunJournal.ts\";\nimport type { RunStorageSession, RunWriter } from \"./RunStorage.ts\";\nimport {\n submissionAbortRecordId,\n submissionInputRecordId,\n submissionSettlementRecordId,\n submissionSettlementBatchId,\n} from \"./SubmissionLedger.ts\";\nimport {\n CommitBatch,\n ExecutionCheckpoint,\n ExecutionUpdate,\n getRecord,\n getRunInput,\n ThreadReader,\n ThreadStoreError,\n} from \"./ThreadStore.ts\";\n\nexport { RunContinuation, RunContextRecorded, EvidenceReference } from \"./Records.ts\";\n\n/** Writer and progress sequencer selected at the local owner's resource boundary. */\nexport class CurrentRunWriter extends Context.Service<\n CurrentRunWriter,\n Pick<RunWriter, \"threadId\" | \"tail\" | \"append\" | \"withProgress\">\n>()(\"@effect-agent/thread/CurrentRunWriter\") {}\n\n/** Settlement publication keeps its original atomic authority and claim-scoped implementation. */\nexport class CurrentRunSettlement extends Context.Service<\n CurrentRunSettlement,\n Pick<RunStorageSession, \"threadId\" | \"tail\" | \"publishSettlement\" | \"withProgress\">\n>()(\"@effect-agent/thread/CurrentRunSettlement\") {}\n\n/** Canonical reads pinned to the append owner's current transaction or mutation gate. */\nexport class ProgressAppendReader extends Context.Service<\n ProgressAppendReader,\n {\n readonly previous: (\n runId: RunId,\n ) => Effect.Effect<RunContinuation | undefined, ThreadStoreError>;\n readonly initial: (\n next: RunContinuation,\n ) => Effect.Effect<ReadonlyArray<RecordEnvelope>, ThreadStoreError>;\n }\n>()(\"@effect-agent/thread/ProgressAppendReader\") {}\n\nexport {\n canonicalRunIds,\n executionRunIds,\n isWorkHandoff,\n isPreContinuationFact,\n} from \"./internal/record-ownership.ts\";\n\nconst failure = (message: string, cause?: unknown) =>\n ThreadStoreError.make({\n operation: \"RunContinuation\",\n message,\n ...(cause === undefined ? {} : { cause }),\n });\n\nconst capacityFailure = (message: string) =>\n failure(message, AgentPersistenceCapacityError.make({ message }));\n\nconst isExecutionProgressRecord = (\n record: RecordEnvelope,\n): record is RecordEnvelope & { readonly payload: RunContinuation } =>\n record.payload._tag === \"RunContinuation\";\n\nconst decodeResponsePrompt = Schema.decodeUnknownEffect(Prompt.Prompt);\n// The decoded Prompt stays private. Progress and capacity are recomputed on every invocation.\nconst responsePrompts = new WeakMap<ModelResponseRecorded, Prompt.Prompt>();\n\n/** Cache eligibility only: freezing does not make accessors or custom iterators immutable. */\nconst isFrozenJsonData = (input: Schema.Json): boolean => {\n const pending: Array<unknown> = [input];\n const seen = new WeakSet<object>();\n\n while (pending.length > 0) {\n const value = pending.pop();\n\n if (value === null) continue;\n if (typeof value !== \"object\") {\n if (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\")\n return false;\n continue;\n }\n if (seen.has(value)) continue;\n seen.add(value);\n const prototype = Object.getPrototypeOf(value);\n\n if (\n !Object.isFrozen(value) ||\n (prototype !== null && prototype !== Object.prototype && prototype !== Array.prototype)\n )\n return false;\n for (const key of Reflect.ownKeys(value)) {\n if (typeof key !== \"string\") return false;\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n\n if (descriptor === undefined || !(\"value\" in descriptor)) return false;\n pending.push(descriptor.value);\n }\n }\n\n return true;\n};\n\nconst validateBatchHeader = Schema.decodeSync(\n Schema.Struct({\n batchId: CanonicalBatch.fields.batchId,\n producerId: CanonicalBatch.fields.producerId,\n }),\n);\n\nconst validateBatchCount = Schema.decodeUnknownSync(\n Schema.NonEmptyArray(Schema.Unknown).check(Schema.isMaxLength(256)),\n);\n\nconst ContinuationBytes = Schema.Struct({\n turnBytes: RunContinuation.fields.turnBytes,\n terminalBytes: RunContinuation.fields.terminalBytes,\n});\n\nconst decodeExecutionFrontier = Schema.decodeUnknownEffect(\n Schema.Struct({\n canonicalRecords: ExecutionCheckpoint.fields.canonicalRecords,\n throughSequence: ExecutionCheckpoint.fields.throughSequence,\n }),\n);\n\n/** One private snapshot for every retry; callers cannot change facts while awaiting the gate. */\nconst captureFacts = (batch: CommitBatch) =>\n Effect.try({\n try: () =>\n Result.gen(function* () {\n const header = validateBatchHeader(batch);\n\n validateBatchCount(batch.records);\n const encodings = yield* Result.all(batch.records.map(captureRecord));\n const records = encodings.map((record) => record.canonical);\n\n return Object.freeze(\n CanonicalBatch.make(\n { ...header, records: [records[0]!, ...records.slice(1)] },\n { disableChecks: true },\n ),\n );\n }),\n catch: (cause) => failure(\"Cannot capture canonical progress facts\", cause),\n }).pipe(\n Effect.flatMap(Effect.fromResult),\n Effect.mapError((cause) =>\n Schema.is(ThreadStoreError)(cause)\n ? cause\n : failure(\"Cannot capture canonical progress facts\", cause),\n ),\n );\n\n/** Exact UTF-8 wire accounting reuses the append's privately captured Schema encoding. */\nexport const canonicalRecordBytes = (record: RecordEnvelope): number => {\n const encoded = recordEncoding(record);\n\n if (Result.isFailure(encoded)) {\n // oxlint-disable-next-line effect/no-untyped-throw, effect/no-native-error -- Public synchronous byte-accounting validation must reject malformed records before returning a number.\n throw encoded.failure.cause ?? new RangeError(encoded.failure.message);\n }\n\n return encoded.success.bytes;\n};\n\nexport type { ProgressAppendRecord } from \"./internal/record-encoding.ts\";\n\n/** Capture before acquiring the mutation owner; summaries never cross a wire boundary. */\nexport const prepareProgressAppend = (\n records: ReadonlyArray<RecordEnvelope>,\n): ReadonlyArray<ProgressAppendRecord> => {\n const encodings = Result.all(records.map(captureRecord));\n\n if (Result.isFailure(encodings)) {\n // oxlint-disable-next-line effect/no-untyped-throw, effect/no-native-error -- Public synchronous progress construction must reject malformed records before acquiring a mutation owner.\n throw encodings.failure.cause ?? new RangeError(encodings.failure.message);\n }\n\n return Object.freeze(encodings.success.map((record) => record.progress));\n};\n\nconst factUsageCharge = (facts: ReadonlyArray<RecordEnvelope>) =>\n Effect.fromResult(Result.all(facts.map(recordEncoding))).pipe(\n Effect.map((encodings) =>\n encodings.reduce((bytes, record) => bytes + record.progress.terminalUsageBytes, 0),\n ),\n Effect.mapError((cause) => failure(\"Cannot account canonical progress facts\", cause)),\n );\n\n/** These values belong to the active Run, not its permanent conversation history. */\nexport const isOperationalRecord = ({ payload }: RecordEnvelope): boolean =>\n payload._tag === \"RunStarted\" ||\n payload._tag === \"RunContextRecorded\" ||\n payload._tag === \"RunCompleted\";\n\nexport const readContinuation = Effect.fnUntraced(function* (\n threadId: ThreadId,\n runId: RunId,\n throughSequence: CanonicalSequence,\n) {\n const reader = yield* ThreadReader;\n\n const loaded = yield* reader\n .readExecution({ threadId, runId })\n .pipe(\n Effect.catchTag(\"ThreadNotMaterialized\", (cause) =>\n throughSequence === 0\n ? Effect.succeed(Option.none())\n : failure(\"Active Run history is not materialized\", cause),\n ),\n );\n\n if (Option.isNone(loaded)) return Option.none();\n const value = loaded.value;\n\n if (\n value.progress.runId !== runId ||\n value.throughSequence > throughSequence ||\n canonicalRecordBytes(value.progressRecord) > MAX_RUN_CONTINUATION_BYTES ||\n value.operational.some(\n (record) => !isOperationalRecord(record) || !executionRunIds(record).includes(runId),\n ) ||\n new Set(value.operational.map((record) => record.recordId)).size !== value.operational.length\n )\n return yield* failure(\"Invalid active Run checkpoint\");\n\n return Option.some({\n ...value,\n checkpoint: value,\n get progress() {\n return value.progress;\n },\n record: value.progressRecord,\n continuation: value.progress,\n });\n});\n\n/** Resolve an active-only fact without presenting it as a canonical envelope or sequence. */\nexport const resolveExecutionEvidence = Effect.fnUntraced(function* (\n threadId: ThreadId,\n checkpoint: ExecutionCheckpoint,\n ref: EvidenceReference,\n) {\n const operational = checkpoint.operational.find((record) => record.recordId === ref.recordId);\n const record = operational ?? (yield* resolveEvidence(threadId, ref)).record;\n\n return record;\n});\n\n/** Each selected page is at most eight records; total resident encoded evidence is bounded. */\nexport const runEvidence = (\n threadId: ThreadId,\n submissionId: SubmissionId,\n throughSequence: CanonicalSequence,\n afterSequence: CanonicalSequence = CanonicalSequence.make(0),\n): Stream.Stream<CanonicalRecordEnvelope, ThreadStoreError, ThreadReader> =>\n Stream.unwrap(\n Effect.map(ThreadReader, (reader) =>\n Stream.suspend(() => {\n let after = afterSequence;\n let count = 0;\n let bytes = 0;\n const runId = runIdForSubmission(submissionId);\n\n const controls = new Set([\n submissionInputRecordId(submissionId),\n submissionAbortRecordId(submissionId),\n submissionSettlementRecordId(submissionId),\n ]);\n\n const next = (): Stream.Stream<CanonicalRecordEnvelope, ThreadStoreError> =>\n Stream.unwrap(\n Stream.runCollect(\n reader.read({\n threadId,\n selection: { _tag: \"RunEvidence\", runId, submissionId, throughSequence },\n page: { limit: 8, ...(after === 0 ? {} : { afterSequence: after }) },\n }),\n ).pipe(\n Effect.mapError((cause) =>\n cause._tag === \"ThreadStoreError\"\n ? cause\n : failure(\"Selected Run disappeared\", cause),\n ),\n Effect.flatMap((page) =>\n Effect.gen(function* () {\n if (page.length > 8)\n return yield* failure(\"Run evidence page exceeds its record bound\");\n for (const entry of page) {\n if (\n entry.threadId !== threadId ||\n entry.sequence <= after ||\n entry.sequence > throughSequence ||\n entry.record.payload._tag === \"RunContinuation\" ||\n (!canonicalRunIds(entry.record).includes(runId) &&\n !controls.has(entry.record.recordId))\n )\n return yield* failure(\"Run evidence page has invalid identity or ordering\");\n after = entry.sequence;\n count += 1;\n bytes += yield* Effect.try({\n try: () => canonicalRecordBytes(entry.record),\n catch: (cause) => failure(\"Selected Run evidence is malformed\", cause),\n });\n if (\n count > MAX_RUN_EVIDENCE_RECORDS + RUN_TERMINAL_RESERVE_RECORDS ||\n bytes > MAX_RUN_EVIDENCE_BYTES + MAX_RUN_TERMINAL_BYTES\n )\n return yield* failure(\"Selected Run evidence exceeds its recovery bound\");\n }\n\n return page.length < 8\n ? Stream.fromIterable(page)\n : Stream.concat(Stream.fromIterable(page), Stream.suspend(next));\n }),\n ),\n ),\n );\n\n return next();\n }),\n ),\n );\n\n/** A bounded selected-Run suffix, never a Thread-wide tail or an implicit replay fallback. */\nexport const validateSuffix = (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n through: CanonicalSequence,\n) => {\n const suffix = records.filter((record) => record.sequence > through);\n\n return (\n suffix.length <= MAX_RUN_RECOVERY_SUFFIX_RECORDS &&\n suffix.reduce((bytes, record) => bytes + canonicalRecordBytes(record.record), 0) <=\n MAX_RUN_RECOVERY_SUFFIX_BYTES\n );\n};\n\n/**\n * Selected semantic evidence without expanding model context. Worker acknowledgements and\n * delivery repair must validate locator completeness before treating missing effects as closed.\n */\nexport const readRunEvidenceSnapshot = Effect.fnUntraced(function* (\n threadId: ThreadId,\n submissionId: SubmissionId,\n throughSequence: CanonicalSequence,\n) {\n const records = yield* Stream.runCollect(runEvidence(threadId, submissionId, throughSequence));\n const runId = runIdForSubmission(submissionId);\n const own = records.filter((entry) => executionRunIds(entry.record).includes(runId));\n const progress = yield* readContinuation(threadId, runId, throughSequence);\n\n if (Option.isNone(progress)) {\n const terminal = own.findLast(\n ({ record }) => record.payload._tag === \"SubmissionSettled\" && record.payload.runId === runId,\n );\n\n if (terminal?.record.payload._tag === \"SubmissionSettled\") {\n if (\n terminal.record.payload.historyRecordCount === undefined ||\n own.filter((entry) => entry.sequence <= terminal.sequence).length !==\n terminal.record.payload.historyRecordCount\n )\n return yield* failure(\"Settled Run history is incomplete\");\n\n return records;\n }\n if (own.some(({ record }) => !isPreContinuationFact(record)))\n return yield* failure(\"Active execution has no durable checkpoint\");\n\n return records;\n }\n const checkpoint = progress.value;\n const cursor = checkpoint.continuation;\n\n if (cursor.submissionId !== submissionId)\n return yield* failure(\"Active checkpoint has another admitted owner\");\n if (\n own.filter((entry) => entry.sequence <= checkpoint.throughSequence).length !==\n checkpoint.canonicalRecords ||\n !validateSuffix(own, checkpoint.throughSequence)\n )\n return yield* failure(\"Selected execution history is incomplete or exceeds its suffix bound\");\n\n const resolve = (ref: EvidenceReference) =>\n resolveExecutionEvidence(threadId, checkpoint.checkpoint, ref);\n\n const input = yield* resolve(cursor.originalInput);\n\n if (\n input.payload._tag !== \"UserInputRecorded\" ||\n input.payload.submissionId !== submissionId ||\n input.payload.kind !== \"user\" ||\n input.payload.runId !== runId\n )\n return yield* failure(\"Active checkpoint has no original accepted input\");\n yield* resolve(cursor.lastFact);\n if (cursor.savedContext !== undefined) {\n const context = yield* resolve(cursor.savedContext);\n\n if (context.payload._tag !== \"RunContextRecorded\" || context.payload.runId !== runId)\n return yield* failure(\"Active checkpoint has invalid saved context\");\n }\n if (cursor.latestResponse !== undefined) {\n const response = yield* resolve(cursor.latestResponse);\n\n if (\n response.payload._tag !== \"ModelResponseRecorded\" ||\n response.payload.runId !== runId ||\n response.payload.turn !== cursor.accounting.committedTurns\n )\n return yield* failure(\"Active checkpoint has invalid operation evidence\");\n }\n if (cursor.terminal !== undefined) {\n const terminal = yield* resolve(cursor.terminal);\n\n if (\n terminal.payload._tag !== \"RunCompleted\" &&\n terminal.payload._tag !== \"RunFailed\" &&\n terminal.payload._tag !== \"SubmissionSettled\"\n )\n return yield* failure(\"Active checkpoint has invalid terminal evidence\");\n }\n\n return records;\n});\n\n/** Called inside the adapter's existing mutation, before publishing any fact or index. */\nexport const validateProgressAppend = Effect.fnUntraced(function* (\n records: ReadonlyArray<ProgressAppendRecord>,\n updates: ReadonlyArray<ExecutionUpdate> = [],\n): Effect.fn.Return<void, ThreadStoreError, ProgressAppendReader> {\n const reader = yield* ProgressAppendReader;\n\n if (records.some((record) => record.continuation !== undefined))\n return yield* failure(\"Interpreter progress must be committed as active execution state\");\n\n const operational = new Map(\n updates.flatMap((update) => update.facts.map((fact) => [fact.recordId, fact] as const)),\n );\n\n const factsAndProgress = [\n ...records,\n ...prepareProgressAppend([...operational.values()]),\n ...prepareProgressAppend(updates.map((update) => update.checkpoint.progressRecord)),\n ];\n\n const seen = new Set<RunId>();\n let progressStarted = false;\n\n for (const record of factsAndProgress) {\n const next = record.continuation;\n\n if (next === undefined) {\n if (progressStarted)\n return yield* failure(\"Execution facts cannot follow their continuation\");\n continue;\n }\n progressStarted = true;\n if (record.recordBytes > MAX_RUN_CONTINUATION_BYTES)\n return yield* failure(\"Encoded continuation exceeds its record byte bound\");\n if (seen.has(next.runId))\n return yield* failure(\"One atomic batch cannot publish conflicting Run progress\");\n seen.add(next.runId);\n\n const update = updates.find((value) => value.checkpoint.progress.runId === next.runId);\n\n if (\n update === undefined ||\n update.previousRevision + 1 !== next.revision ||\n update.facts.some((fact) => !isOperationalRecord(fact)) ||\n (update.retire && (next.position !== \"settled\" || next.terminal === undefined))\n )\n return yield* failure(\"Invalid active execution transition\");\n\n const facts = factsAndProgress.filter(\n (fact) => fact.continuation === undefined && fact.runIds.includes(next.runId),\n );\n\n const frontier = facts.find((fact) => fact.recordId === next.lastFact.recordId);\n const prior = yield* reader.previous(next.runId);\n\n const retained =\n prior === undefined\n ? (yield* reader.initial(next)).filter((fact) => executionRunIds(fact).includes(next.runId))\n : [];\n\n const retainedBytes = retained.reduce((bytes, fact) => bytes + canonicalRecordBytes(fact), 0);\n const factBytes = facts.reduce((bytes, fact) => bytes + fact.recordBytes, 0);\n const turnBase = prior?.turn === next.turn ? prior.turnBytes : retainedBytes;\n const closing = facts.filter((fact) => fact.terminal);\n\n if (\n frontier === undefined ||\n retained.length > MAX_RUN_RECOVERY_SUFFIX_RECORDS ||\n retainedBytes > MAX_RUN_RECOVERY_SUFFIX_BYTES ||\n retained.some(\n (fact) => !isPreContinuationFact(fact) || !executionRunIds(fact).includes(next.runId),\n ) ||\n frontier.recordId !== next.lastFact.recordId ||\n next.revision !== (prior?.revision ?? 0) + 1 ||\n next.recordBytes < (prior?.recordBytes ?? 0) ||\n next.turn < (prior?.turn ?? 0) ||\n (prior !== undefined && next.turn === prior.turn && next.turnBytes <= prior.turnBytes) ||\n next.recordBytes !== (prior?.recordBytes ?? retainedBytes) + factBytes ||\n next.terminalUsageBytes !==\n (prior?.terminalUsageBytes ?? 0) +\n facts.reduce((bytes, fact) => bytes + fact.terminalUsageBytes, 0) ||\n next.turnBytes !== turnBase + factBytes + record.recordBytes ||\n next.recordCount !== (prior?.recordCount ?? retained.length) + facts.length ||\n next.terminalRecords !== (prior?.terminalRecords ?? 0) + closing.length ||\n next.terminalBytes !==\n (prior?.terminalBytes ?? 0) +\n closing.reduce((bytes, fact) => bytes + fact.recordBytes, 0) +\n (closing.length > 0 ? record.recordBytes : 0) ||\n (prior !== undefined &&\n (prior.submissionId !== next.submissionId ||\n !Schema.toEquivalence(EvidenceReference)(prior.originalInput, next.originalInput) ||\n (prior.savedContext !== undefined &&\n (next.savedContext === undefined ||\n !Schema.toEquivalence(EvidenceReference)(prior.savedContext, next.savedContext))))) ||\n (prior !== undefined &&\n (\n [\n \"committedTurns\",\n \"toolCalls\",\n \"programmaticToolCalls\",\n \"modelRestarts\",\n \"modelCalls\",\n \"inputTokens\",\n \"outputTokens\",\n \"costMicrousd\",\n \"unobservedModelCalls\",\n \"accountedToolTurn\",\n ] satisfies ReadonlyArray<keyof ContinuationAccounting>\n ).some((field) => next.accounting[field] < prior.accounting[field])) ||\n (prior?.accounting.finalizationUsed === true && !next.accounting.finalizationUsed)\n )\n return yield* failure(\"Run continuation conflicts with its canonical frontier or revision\");\n }\n});\n\ninterface ChildResultCapacity {\n readonly resultBytes: number;\n readonly remainingBytes: number;\n readonly remainingRecords: number;\n}\n\ninterface ProgressState {\n readonly continuation: RunContinuation;\n readonly record: RecordEnvelope;\n readonly response?: ModelResponseRecorded;\n readonly results: ReadonlyMap<ToolCallId, ToolCallSettled>;\n readonly completionBytes?: number;\n readonly childResults: ReadonlyMap<ToolCallId, ChildResultCapacity>;\n readonly checkpoint?: ExecutionCheckpoint;\n}\n\ntype CapacityState = Omit<ProgressState, \"continuation\" | \"record\"> & {\n readonly continuation: Pick<\n RunContinuation,\n | \"runId\"\n | \"position\"\n | \"turn\"\n | \"turnBytes\"\n | \"recordBytes\"\n | \"recordCount\"\n | \"accounting\"\n | \"terminalUsageBytes\"\n | \"terminalBytes\"\n | \"terminalRecords\"\n >;\n};\n\n/** Headers/identities must themselves fit a continuation. Leave room for a result's cursor too. */\nconst resultCapacity = (state: CapacityState): { bytes: number; records: number } => {\n const response = state.response;\n\n if (\n response === undefined ||\n state.continuation.position === \"settling\" ||\n state.continuation.position === \"settled\" ||\n state.continuation.accounting.accountedToolTurn >= response.turn\n )\n return { bytes: 0, records: 0 };\n let bytes = 0;\n let records = 0;\n\n for (const operation of response.toolOperations) {\n if (state.results.has(operation.toolCallId)) continue;\n\n const identity = JSON.stringify({\n recordId: toolCallSettledRecordId(response.runId, response.turn, operation.toolCallId),\n payload: {\n _tag: \"ToolCallSettled\",\n runId: response.runId,\n toolCallId: operation.toolCallId,\n toolName: operation.toolName,\n result: null,\n isFailure: false,\n },\n });\n\n // An uncertain ordinary call may later close with exact supplier/operator truth, rather\n // than the interpreter's truncated result. Attached joins retain their frozen allocation.\n const resultBytes =\n operation.executionKind === \"ordinary\" && operation.executionClass !== \"readonly\"\n ? MAX_PERSISTED_JSON_BYTES\n : Math.max(\n response.toolResultMaxBytes,\n state.childResults.get(operation.toolCallId)?.resultBytes ?? 0,\n );\n\n const joining = state.childResults.get(operation.toolCallId);\n\n bytes +=\n utf8ByteLength(identity) +\n resultBytes +\n (joining?.remainingBytes ?? 0) +\n response.toolSelectionMaxBytes +\n 2 * MAX_RUN_CONTINUATION_BYTES +\n 256;\n records += joining?.remainingRecords ?? 1;\n }\n\n return { bytes, records };\n};\n\nconst emptyAccounting = (): ContinuationAccounting => ({\n committedTurns: 0,\n toolCalls: 0,\n programmaticToolCalls: 0,\n consecutiveToolFailures: 0,\n finalizationUsed: false,\n modelRestarts: 0,\n modelCalls: 0,\n unobservedModelCalls: 0,\n inputTokens: 0,\n outputTokens: 0,\n lastInputTokens: 0,\n lastOutputTokens: 0,\n costMicrousd: 0,\n accountedToolTurn: 0,\n});\n\n/** Recompute semantic progress solely from immutable owning facts. No port grants authority. */\nconst advanceFacts = Effect.fnUntraced(function* (\n previous: ProgressState | undefined,\n facts: ReadonlyArray<RecordEnvelope>,\n submissionId: SubmissionId,\n initialBytes: number,\n) {\n const accounting = { ...(previous?.continuation.accounting ?? emptyAccounting()) };\n let savedContext = previous?.continuation.savedContext;\n let latestResponse = previous?.continuation.latestResponse;\n let terminal = previous?.continuation.terminal;\n let position = previous?.continuation.position ?? \"starting\";\n let response = previous?.response;\n let responsePrompt: Prompt.Prompt | undefined;\n let results = new Map(previous?.results);\n let childResults = new Map(previous?.childResults);\n let completionBytes = previous?.completionBytes;\n\n for (const fact of facts) {\n const payload = fact.payload;\n\n switch (payload._tag) {\n case \"RunStarted\":\n position = \"awaiting-model\";\n break;\n case \"RunContextRecorded\":\n if (savedContext !== undefined)\n return yield* failure(\"A Run's original context cannot be replaced\");\n savedContext = yield* reference(fact);\n position = \"awaiting-model\";\n break;\n case \"ModelResponseRecorded\": {\n if (savedContext === undefined)\n return yield* failure(\"A model response has no saved original Run context\");\n if (payload.turn !== accounting.committedTurns + 1)\n return yield* failure(\"Canonical Turn progress must advance once\");\n\n const promptInput = payload.messages;\n const retainedPrompt = responsePrompts.get(payload);\n\n const messages =\n retainedPrompt ??\n (yield* decodeResponsePrompt(promptInput).pipe(\n Effect.mapError((cause) => failure(\"Invalid model evidence\", cause)),\n ));\n\n if (retainedPrompt === undefined) {\n const property = Object.getOwnPropertyDescriptor(payload, \"messages\");\n\n if (\n Object.isFrozen(payload) &&\n property !== undefined &&\n \"value\" in property &&\n property.value === promptInput &&\n isFrozenJsonData(promptInput)\n )\n responsePrompts.set(payload, messages);\n }\n responsePrompt = messages;\n\n const calls = messages.content.flatMap((message) =>\n message.role === \"assistant\"\n ? message.content.filter((part) => part.type === \"tool-call\")\n : [],\n );\n\n const summary =\n payload.modelUsage === undefined\n ? undefined\n : yield* continuationUsage(payload.modelUsage).pipe(\n Effect.mapError((cause) => failure(\"Invalid usage evidence\", cause)),\n );\n\n accounting.committedTurns = payload.turn;\n accounting.toolCalls += calls.length;\n accounting.modelCalls += summary?.modelCalls ?? 1;\n accounting.inputTokens += summary?.inputTokens ?? payload.inputTokens ?? 0;\n accounting.outputTokens += summary?.outputTokens ?? payload.outputTokens ?? 0;\n accounting.costMicrousd += summary?.costMicrousd ?? payload.costMicrousd ?? 0;\n accounting.lastInputTokens = summary?.inputTokens ?? payload.inputTokens ?? 0;\n accounting.lastOutputTokens = summary?.outputTokens ?? payload.outputTokens ?? 0;\n accounting.unobservedModelCalls += payload.unobservedModelCalls ?? 0;\n latestResponse = yield* reference(fact);\n response = payload;\n results = new Map();\n childResults = new Map();\n position = payload.toolOperations.length === 0 ? \"awaiting-model\" : \"processing-operations\";\n break;\n }\n case \"ToolCallSettled\":\n results.set(payload.toolCallId, payload);\n childResults.delete(payload.toolCallId);\n break;\n case \"ToolCallUnknown\":\n position = \"unknown\";\n break;\n case \"ToolCallResolved\":\n position = \"processing-operations\";\n break;\n case \"ToolApprovalRequested\":\n position = \"waiting-approval\";\n break;\n case \"ToolApprovalDecided\":\n position = \"processing-operations\";\n break;\n case \"SubagentRequested\":\n childResults.set(payload.toolCallId, {\n resultBytes: Math.min(\n MAX_PERSISTED_JSON_BYTES,\n payload.budget?.allocation.resultBytes ?? MAX_PERSISTED_JSON_BYTES,\n ),\n remainingBytes: RUN_TERMINAL_RESERVE_BYTES,\n remainingRecords: 4,\n });\n position = \"waiting-dependency\";\n break;\n case \"SubagentStarted\":\n {\n const reserved = childResults.get(payload.toolCallId);\n\n if (reserved !== undefined)\n childResults.set(payload.toolCallId, {\n ...reserved,\n remainingBytes: Math.max(\n 0,\n reserved.remainingBytes - canonicalRecordBytes(fact) - MAX_RUN_CONTINUATION_BYTES,\n ),\n remainingRecords: reserved.remainingRecords - 1,\n });\n }\n position = \"waiting-dependency\";\n break;\n case \"RunPolicyUsageReserved\":\n if (\n payload.programmaticToolCalls < accounting.programmaticToolCalls ||\n (accounting.finalizationUsed && !payload.finalizationUsed)\n )\n return yield* failure(\"Run reservations cannot be refunded\");\n accounting.programmaticToolCalls = payload.programmaticToolCalls;\n accounting.finalizationUsed = payload.finalizationUsed;\n break;\n case \"ModelCallAborted\": {\n if (payload.restart !== (accounting.modelRestarts ?? 0) + 1)\n return yield* failure(\"Model restart progress must advance once\");\n\n const summary = yield* continuationUsage(payload.modelUsage).pipe(\n Effect.mapError((cause) => failure(\"Invalid cancelled model usage\", cause)),\n );\n\n accounting.modelRestarts = payload.restart;\n accounting.modelCalls += summary.modelCalls;\n accounting.inputTokens += summary.inputTokens;\n accounting.outputTokens += summary.outputTokens;\n accounting.costMicrousd += summary.costMicrousd;\n accounting.unobservedModelCalls += payload.unobservedModelCalls;\n break;\n }\n case \"RunCompleted\":\n case \"RunFailed\":\n completionBytes =\n payload._tag === \"RunCompleted\"\n ? utf8ByteLength(JSON.stringify(payload.output)) +\n (payload.runDisposition === undefined\n ? 0\n : utf8ByteLength(JSON.stringify(payload.runDisposition)))\n : undefined;\n terminal = yield* reference(fact);\n position = \"settling\";\n break;\n case \"SubmissionSettled\":\n if (payload.submissionId !== submissionId) break;\n terminal = yield* reference(fact);\n position = \"settled\";\n if (payload.usageSummary !== undefined) {\n accounting.modelCalls = payload.usageSummary.modelCalls;\n accounting.inputTokens = payload.usageSummary.inputTokens.total;\n accounting.outputTokens = payload.usageSummary.outputTokens.total;\n accounting.costMicrousd = payload.usageSummary.costMicrousd;\n accounting.unobservedModelCalls =\n payload.usageSummary.unobservedModelCalls ?? accounting.unobservedModelCalls;\n }\n break;\n default:\n break;\n }\n }\n if (\n response !== undefined &&\n response.turn > accounting.accountedToolTurn &&\n response.toolOperations.every((operation) => results.has(operation.toolCallId))\n ) {\n const messages =\n responsePrompt ??\n responsePrompts.get(response) ??\n (yield* decodeResponsePrompt(response.messages).pipe(\n Effect.mapError((cause) => failure(\"Invalid batch evidence\", cause)),\n ));\n\n const parts = messages.content.flatMap((message) =>\n message.role === \"assistant\" ? message.content : [],\n );\n\n for (const call of parts) {\n if (call.type !== \"tool-call\") continue;\n\n const result = call.providerExecuted\n ? parts.find((part) => part.type === \"tool-result\" && part.id === call.id)\n : results.get(ToolCallId.make(call.id));\n\n if (\n result === undefined ||\n !(\"isFailure\" in result) ||\n (\"budgetRejected\" in result && result.budgetRejected === true)\n )\n continue;\n accounting.consecutiveToolFailures = result.isFailure\n ? accounting.consecutiveToolFailures + 1\n : 0;\n }\n accounting.accountedToolTurn = response.turn;\n results.clear();\n if (position !== \"settling\" && position !== \"settled\") position = \"awaiting-model\";\n }\n const last = facts.at(-1);\n\n if (last === undefined) return yield* failure(\"Progress has no owning fact\");\n if (previous?.continuation.position === \"settled\") position = \"settled\";\n else if (previous?.continuation.position === \"settling\" && position !== \"settled\")\n position = \"settling\";\n const factBytes = facts.reduce((bytes, fact) => bytes + canonicalRecordBytes(fact), 0);\n\n const turn = facts.reduce(\n (current, fact) => (\"turn\" in fact.payload ? Math.max(current, fact.payload.turn) : current),\n previous?.continuation.turn ?? 1,\n );\n\n const turnBase =\n (previous?.continuation.turn === turn ? previous.continuation.turnBytes : initialBytes) +\n factBytes;\n\n const usageCharge = yield* factUsageCharge(facts);\n const terminalUsageBytes = (previous?.continuation.terminalUsageBytes ?? 0) + usageCharge;\n\n const closing = facts.filter(isTerminalBudgetFact);\n\n return {\n accounting,\n savedContext,\n latestResponse,\n terminal,\n position,\n response,\n results,\n childResults,\n completionBytes,\n last,\n factBytes,\n turn,\n turnBase,\n usageCharge,\n terminalUsageBytes,\n terminalBytes:\n (previous?.continuation.terminalBytes ?? 0) +\n closing.reduce((bytes, fact) => bytes + canonicalRecordBytes(fact), 0),\n terminalRecords: (previous?.continuation.terminalRecords ?? 0) + closing.length,\n closing: closing.length > 0,\n };\n});\n\n/**\n * Verify retained history. Mutable checkpoint revisions are deliberately not historical proof.\n * Active original context is still checked against its exact retained historyDigest.\n */\nexport const verifyRunContinuations = Effect.fnUntraced(function* (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n options?: {\n readonly verifyContext?: boolean;\n readonly executions?: ReadonlyArray<ExecutionCheckpoint>;\n },\n) {\n const inputs = records.filter(\n ({ record }) =>\n record.payload._tag === \"UserInputRecorded\" &&\n record.payload.kind === \"user\" &&\n record.payload.submissionId !== undefined,\n );\n\n if (records.some(({ record }) => record.payload._tag === \"RunContinuation\"))\n return yield* failure(\"Mutable interpreter progress is not canonical history\");\n for (const input of inputs) {\n const payload = input.record.payload;\n\n if (payload._tag !== \"UserInputRecorded\" || payload.submissionId === undefined) continue;\n const runId = runIdForSubmission(payload.submissionId);\n const own = records.filter((entry) => executionRunIds(entry.record).includes(runId));\n\n const terminal = own.findLast(\n ({ record }) => record.payload._tag === \"SubmissionSettled\" && record.payload.runId === runId,\n );\n\n if (terminal?.record.payload._tag === \"SubmissionSettled\") {\n if (\n terminal.record.payload.historyRecordCount === undefined ||\n own.filter((entry) => entry.sequence <= terminal.sequence).length !==\n terminal.record.payload.historyRecordCount\n )\n return yield* failure(\"Terminal history differs from its retained fact count\");\n continue;\n }\n if (options?.verifyContext === false) continue;\n const checkpoint = options?.executions?.find((value) => value.progress.runId === runId);\n\n if (checkpoint === undefined) {\n if (own.some(({ record }) => !isPreContinuationFact(record)))\n return yield* failure(\"Active execution is missing its authoritative checkpoint\");\n continue;\n }\n\n const saved = checkpoint.operational.find(\n ({ payload }) => payload._tag === \"RunContextRecorded\",\n );\n\n if (saved?.payload._tag === \"RunContextRecorded\") {\n yield* validateContextBoundary(saved.payload, input).pipe(\n Effect.mapError((cause) => failure(\"Context has an invalid admission boundary\", cause)),\n );\n yield* readRunContext(saved.payload, input, saved.recordId).pipe(\n Effect.mapError((cause) => failure(\"Context differs from its original history\", cause)),\n );\n }\n }\n});\n\n/**\n * Prepare progress for the existing atomic append/publication. Accept the returned state only\n * after that append commits; a failed or stale producer cannot publish speculative progress.\n * One writer retains bounded metadata for its active Run, not its historical results or IDs.\n */\nexport const makeProgressWriter = Effect.fnUntraced(function* (\n threadId: ThreadId,\n deploymentId: DeploymentId,\n) {\n const reader = yield* ThreadReader;\n const gate = yield* Semaphore.make(1);\n const cached = new Map<RunId, ProgressState>();\n\n const reservations = new Map<\n RecordId,\n {\n readonly runId: RunId;\n readonly turn: number;\n readonly bytes: number;\n readonly records: number;\n }\n >();\n\n const stagedUsage = new Map<RunId, number>();\n\n const provide = <A, E>(effect: Effect.Effect<A, E, ThreadReader>) =>\n Effect.provideService(effect, ThreadReader, reader);\n\n const loadUncachedState = Effect.fnUntraced(function* (runId: RunId, after: CanonicalSequence) {\n const loaded = yield* provide(readContinuation(threadId, runId, after));\n\n if (Option.isNone(loaded)) return undefined;\n const continuation = loaded.value.continuation;\n let response: ModelResponseRecorded | undefined;\n let completionBytes: number | undefined;\n const results = new Map<ToolCallId, ToolCallSettled>();\n\n const childResults = new Map<ToolCallId, ChildResultCapacity>();\n\n if (continuation.latestResponse !== undefined) {\n const evidence = yield* provide(resolveEvidence(threadId, continuation.latestResponse));\n\n if (\n evidence.record.payload._tag !== \"ModelResponseRecorded\" ||\n evidence.record.payload.runId !== runId\n )\n return yield* failure(\"Continuation operation reference is invalid\");\n response = evidence.record.payload;\n if (continuation.accounting.accountedToolTurn < response.turn) {\n for (const operation of response.toolOperations) {\n const found = yield* provide(\n getRecord({\n threadId,\n recordId: toolCallSettledRecordId(runId, response.turn, operation.toolCallId),\n }),\n );\n\n if (Option.isSome(found)) {\n const result = found.value.record.payload;\n\n if (\n result._tag !== \"ToolCallSettled\" ||\n result.runId !== runId ||\n result.toolCallId !== operation.toolCallId ||\n result.toolName !== operation.toolName\n )\n return yield* failure(\"Continuation result identity is invalid\");\n results.set(operation.toolCallId, result);\n } else if (operation.executionKind === \"delegation\") {\n const requested = yield* provide(\n getRecord({\n threadId,\n recordId: subagentRequestedRecordId(runId, operation.toolCallId),\n }),\n );\n\n if (\n Option.isSome(requested) &&\n requested.value.record.payload._tag === \"SubagentRequested\"\n ) {\n if (\n requested.value.record.payload.runId !== runId ||\n requested.value.record.payload.toolCallId !== operation.toolCallId\n )\n return yield* failure(\"Continuation child request identity is invalid\");\n\n const started = yield* provide(\n getRecord({\n threadId,\n recordId: subagentStartedRecordId(runId, operation.toolCallId),\n }),\n );\n\n if (\n Option.isSome(started) &&\n (started.value.record.payload._tag !== \"SubagentStarted\" ||\n started.value.record.payload.runId !== runId ||\n started.value.record.payload.toolCallId !== operation.toolCallId ||\n started.value.record.payload.childThreadId !==\n requested.value.record.payload.childThreadId)\n )\n return yield* failure(\"Continuation child start identity is invalid\");\n\n const startedBytes = Option.isSome(started)\n ? canonicalRecordBytes(started.value.record) + MAX_RUN_CONTINUATION_BYTES\n : 0;\n\n childResults.set(operation.toolCallId, {\n resultBytes: Math.min(\n MAX_PERSISTED_JSON_BYTES,\n requested.value.record.payload.budget?.allocation.resultBytes ??\n MAX_PERSISTED_JSON_BYTES,\n ),\n remainingBytes: Math.max(0, RUN_TERMINAL_RESERVE_BYTES - startedBytes),\n remainingRecords: Option.isSome(started) ? 3 : 4,\n });\n }\n }\n }\n }\n }\n if (continuation.position === \"settling\" && continuation.terminal !== undefined) {\n const terminal = yield* provide(\n resolveExecutionEvidence(threadId, loaded.value.checkpoint, continuation.terminal),\n );\n\n const payload = terminal.payload;\n\n if (payload._tag === \"RunCompleted\")\n completionBytes =\n utf8ByteLength(JSON.stringify(payload.output)) +\n (payload.runDisposition === undefined\n ? 0\n : utf8ByteLength(JSON.stringify(payload.runDisposition)));\n }\n\n return {\n continuation,\n record: loaded.value.record,\n checkpoint: loaded.value.checkpoint,\n ...(response === undefined ? {} : { response }),\n results,\n childResults,\n ...(completionBytes === undefined ? {} : { completionBytes }),\n };\n });\n\n const loadState = (runId: RunId, after: CanonicalSequence) =>\n Effect.suspend(() => {\n const retained = cached.get(runId);\n\n return retained === undefined ? loadUncachedState(runId, after) : Effect.succeed(retained);\n });\n\n const checkFutureShapes = (\n state: ProgressState,\n cursorBytes?: number,\n ): Effect.Effect<void, ThreadStoreError> => {\n const progress = state.continuation;\n\n if (progress.position === \"settled\") return Effect.void;\n const size = cursorBytes ?? canonicalRecordBytes(state.record);\n const textBytes = (value: string) => utf8ByteLength(JSON.stringify(value));\n const refBytes = (value: EvidenceReference) => utf8ByteLength(JSON.stringify(value));\n\n const ref = (recordId: RecordId) => EvidenceReference.make({ recordId });\n\n const fits = (batchId: string, lastFact: EvidenceReference, terminal?: EvidenceReference) =>\n // Only these identities change. The fixed allowance covers scalar and timestamp growth.\n size +\n textBytes(JSON.stringify([\"continuation@1\", progress.runId, batchId])) -\n textBytes(state.record.recordId) +\n textBytes(deploymentId) -\n textBytes(state.record.deploymentId) +\n refBytes(lastFact) -\n refBytes(progress.lastFact) +\n (terminal === undefined\n ? 0\n : refBytes(terminal) -\n (progress.terminal === undefined ? 0 : refBytes(progress.terminal)) +\n 12) +\n 1024 <=\n MAX_RUN_CONTINUATION_BYTES;\n\n if (\n !fits(\n submissionSettlementBatchId(progress.submissionId),\n ref(submissionSettlementRecordId(progress.submissionId)),\n ref(runCompletedRecordId(progress.runId)),\n )\n )\n return Effect.fail(capacityFailure(\"Run has no room for a terminal continuation envelope\"));\n\n if (\n state.response !== undefined &&\n progress.accounting.accountedToolTurn < state.response.turn\n ) {\n for (const operation of state.response.toolOperations) {\n if (state.results.has(operation.toolCallId)) continue;\n if (\n !fits(\n toolCallResultBatchId(progress.runId, state.response.turn, operation.toolCallId),\n ref(toolCallSettledRecordId(progress.runId, state.response.turn, operation.toolCallId)),\n )\n )\n return Effect.fail(\n capacityFailure(\"Tool dispatch has no room for its result continuation envelope\"),\n );\n }\n }\n\n return Effect.void;\n };\n\n const checkCapacity = (\n state: CapacityState,\n consumed: ReadonlySet<RecordId> = new Set(),\n extra?: { readonly turn: number; readonly bytes: number; readonly records: number },\n committedUsageBytes = 0,\n ): Effect.Effect<void, ThreadStoreError> => {\n const progress = state.continuation;\n const pending = resultCapacity(state);\n\n const terminal =\n progress.position === \"settled\"\n ? 0\n : Math.max(\n 0,\n RUN_TERMINAL_RESERVE_BYTES +\n 2 * (state.completionBytes ?? 0) +\n 2 *\n (progress.terminalUsageBytes +\n Math.max(0, (stagedUsage.get(progress.runId) ?? 0) - committedUsageBytes)) -\n progress.terminalBytes,\n );\n\n let turnBytes =\n (extra !== undefined && extra.turn !== progress.turn ? 0 : progress.turnBytes) +\n pending.bytes +\n terminal +\n (extra?.bytes ?? 0);\n\n let recordBytes = progress.recordBytes + pending.bytes + terminal + (extra?.bytes ?? 0);\n\n let recordCount =\n progress.recordCount +\n pending.records +\n (progress.position === \"settled\"\n ? 0\n : Math.max(0, RUN_TERMINAL_RESERVE_RECORDS - progress.terminalRecords)) +\n (extra?.records ?? 0);\n\n for (const [recordId, reservation] of reservations) {\n if (reservation.runId !== progress.runId || consumed.has(recordId)) continue;\n if (reservation.turn === (extra?.turn ?? progress.turn)) turnBytes += reservation.bytes;\n recordBytes += reservation.bytes;\n recordCount += reservation.records;\n }\n if (\n turnBytes > MAX_TURN_CANONICAL_BYTES ||\n recordBytes > MAX_RUN_EVIDENCE_BYTES ||\n recordCount > MAX_RUN_EVIDENCE_RECORDS\n )\n return Effect.fail(\n failure(\n \"Run has no remaining canonical dispatch capacity\",\n AgentPersistenceCapacityError.make({\n message: \"Run has no room for the next result and a bounded terminal settlement\",\n }),\n ),\n );\n\n return Effect.void;\n };\n\n const prepare = Effect.fnUntraced(function* (\n batch: CanonicalBatch,\n after: CanonicalSequence,\n mode: \"commit\" | \"preflight\" = \"commit\",\n ) {\n if (batch.records.some((record) => record.payload._tag === \"RunContinuation\"))\n return yield* failure(\"A caller cannot supply interpreter progress to the progress writer\");\n\n const ownedRecords = yield* Effect.fromResult(\n Result.all(batch.records.map(captureRecord)),\n ).pipe(\n Effect.map((encodings) => encodings.map((record) => record.canonical)),\n Effect.mapError((cause) => failure(\"Cannot capture canonical progress facts\", cause)),\n );\n\n const groups = new Map<RunId, Array<RecordEnvelope>>();\n\n for (const record of ownedRecords) {\n for (const runId of executionRunIds(record)) {\n const facts = groups.get(runId) ?? [];\n\n facts.push(record);\n groups.set(runId, facts);\n }\n }\n const executions: Array<ExecutionUpdate> = [];\n const accepted = new Map<RunId, ProgressState>();\n let executionCount = 0;\n\n for (const [runId, facts] of groups) {\n const previous = yield* loadState(runId, after);\n\n let original = facts.find(\n (record) =>\n record.payload._tag === \"UserInputRecorded\" &&\n record.payload.kind === \"user\" &&\n record.payload.runId === runId &&\n record.payload.submissionId !== undefined,\n );\n\n let originalCount = 0;\n let initialBytes = 0;\n let originalSequence = previous?.checkpoint?.originalSequence;\n\n if (previous === undefined && original === undefined) {\n const input = yield* provide(getRunInput({ threadId, runId }));\n\n if (\n Option.isNone(input) ||\n input.value.record.payload._tag !== \"UserInputRecorded\" ||\n input.value.record.payload.submissionId === undefined\n )\n continue;\n\n original = input.value.record;\n originalSequence = input.value.sequence;\n }\n\n const submissionId =\n previous?.continuation.submissionId ??\n (original?.payload._tag === \"UserInputRecorded\"\n ? original.payload.submissionId\n : undefined);\n\n if (submissionId === undefined)\n return yield* failure(\"Run progress has no original admission identity\");\n if (runId !== runIdForSubmission(submissionId))\n return yield* failure(\"Run progress conflicts with its original admission\");\n if (previous === undefined && original === undefined)\n return yield* failure(\"Run has no accepted original input\");\n\n if (previous === undefined) {\n const settled = yield* provide(\n getRecord({\n threadId,\n recordId: submissionSettlementRecordId(submissionId),\n }),\n );\n\n if (\n Option.isSome(settled) &&\n settled.value.sequence <= after &&\n settled.value.record.payload._tag === \"SubmissionSettled\" &&\n settled.value.record.payload.runId === runId &&\n settled.value.record.payload.historyRecordCount !== undefined &&\n facts.every(\n ({ payload }) =>\n payload._tag === \"WorkerReportPrepared\" ||\n payload._tag === \"SubmissionSettled\" ||\n payload._tag === \"ToolCallSettled\" ||\n payload._tag === \"ToolCallResolved\" ||\n payload._tag === \"SubagentJoined\",\n )\n )\n // Independent obligations can record factual closure after interpreter retirement.\n continue;\n\n const selected = yield* provide(\n Stream.runCollect(\n runEvidence(threadId, submissionId, after).pipe(\n Stream.take(MAX_RUN_RECOVERY_SUFFIX_RECORDS + 1),\n ),\n ),\n );\n\n const existing = selected.filter(({ record }) => executionRunIds(record).includes(runId));\n\n if (\n !validateSuffix(existing, CanonicalSequence.make(0)) ||\n existing.some(({ record }) => !isPreContinuationFact(record))\n )\n return yield* failure(\n `Run execution has no active checkpoint or exceeds its preparation bound (${facts.map((fact) => fact.payload._tag).join(\", \")})`,\n );\n originalCount = existing.length;\n initialBytes = existing.reduce(\n (bytes, entry) => bytes + canonicalRecordBytes(entry.record),\n 0,\n );\n }\n\n const canonicalRecords =\n (previous?.checkpoint?.canonicalRecords ?? originalCount) +\n facts.filter((fact) => !isOperationalRecord(fact)).length;\n\n for (let index = 0; index < facts.length; index++) {\n const fact = facts[index]!;\n const payload = fact.payload;\n\n if (payload._tag !== \"SubmissionSettled\" || payload.runId !== runId) continue;\n\n const retained = yield* Effect.fromResult(\n captureRecord(\n RecordEnvelope.make({\n ...fact,\n payload: { ...payload, historyRecordCount: canonicalRecords },\n }),\n ),\n ).pipe(\n Effect.map((record) => record.canonical),\n Effect.mapError((cause) => failure(\"Cannot capture canonical progress facts\", cause)),\n );\n\n facts[index] = retained;\n ownedRecords[ownedRecords.indexOf(fact)] = retained;\n }\n\n const originalInput =\n previous !== undefined\n ? previous.continuation.originalInput\n : original === undefined\n ? yield* failure(\"Run progress has no original input\")\n : yield* reference(original);\n\n const next = yield* advanceFacts(previous, facts, submissionId, initialBytes);\n\n const {\n accounting,\n savedContext,\n latestResponse,\n terminal,\n position,\n response,\n results,\n childResults,\n completionBytes,\n last,\n factBytes,\n turn,\n turnBase,\n usageCharge,\n terminalUsageBytes,\n } = next;\n\n let continuation = yield* RunContinuation.makeEffect({\n version: 1,\n runId,\n submissionId,\n revision: (previous?.continuation.revision ?? 0) + 1,\n recordCount: (previous?.continuation.recordCount ?? originalCount) + facts.length,\n recordBytes: (previous?.continuation.recordBytes ?? initialBytes) + factBytes,\n turn,\n turnBytes: turnBase,\n terminalUsageBytes,\n terminalBytes: next.terminalBytes,\n terminalRecords: next.terminalRecords,\n originalInput,\n ...(savedContext === undefined ? {} : { savedContext }),\n ...(latestResponse === undefined ? {} : { latestResponse }),\n ...(terminal === undefined ? {} : { terminal }),\n lastFact: yield* reference(last),\n position,\n accounting,\n }).pipe(\n Effect.mapError(() =>\n capacityFailure(\"Canonical continuation exceeds its protocol bounds\"),\n ),\n );\n\n const header = {\n recordId: RecordId.make(JSON.stringify([\"continuation@1\", runId, batch.batchId])),\n family: \"thread\" as const,\n schemaVersion: 1 as const,\n createdAt: last.createdAt,\n deploymentId: last.deploymentId,\n };\n\n // The validated continuation fields are JSON; only the envelope DateTime needs encoding.\n // Key order does not change byte width. Measure without capturing a provisional record,\n // then compare against the final Schema encoding before accepting its accounting.\n const provisional = {\n ...header,\n createdAt: DateTime.formatIso(header.createdAt),\n payload: continuation,\n } satisfies typeof RecordEnvelope.Encoded;\n\n const initialCursorBytes = utf8ByteLength(JSON.stringify(provisional));\n\n const initialWidth =\n String(continuation.turnBytes).length + String(continuation.terminalBytes).length;\n\n let turnBytes = continuation.turnBytes;\n let terminalBytes = continuation.terminalBytes;\n\n for (let attempts = 0; ; attempts++) {\n const cursorBytes =\n initialCursorBytes +\n String(turnBytes).length +\n String(terminalBytes).length -\n initialWidth;\n\n const nextTurnBytes = turnBase + cursorBytes;\n const nextTerminalBytes = next.terminalBytes + (next.closing ? cursorBytes : 0);\n\n if (nextTurnBytes === turnBytes && nextTerminalBytes === terminalBytes) break;\n if (attempts >= 4) return yield* failure(\"Continuation byte accounting did not converge\");\n turnBytes = nextTurnBytes;\n terminalBytes = nextTerminalBytes;\n }\n\n const checkedBytes = yield* ContinuationBytes.makeEffect({\n turnBytes,\n terminalBytes,\n }).pipe(\n Effect.mapError(() =>\n capacityFailure(\"Turn exceeds its incremental canonical byte budget\"),\n ),\n );\n\n // Every other field was checked above; byte accounting changes only these counters.\n continuation = RunContinuation.make(\n { ...continuation, ...checkedBytes },\n { disableChecks: true },\n );\n\n const proposedRecord = RecordEnvelope.make(\n { ...header, payload: continuation },\n { disableChecks: true },\n );\n\n const cursorBytes = turnBytes - turnBase;\n\n if (cursorBytes > MAX_RUN_CONTINUATION_BYTES)\n return yield* capacityFailure(\n \"Encoded continuation exceeds 8192 bytes including its envelope\",\n );\n executionCount++;\n if (\n mode === \"preflight\" &&\n previous?.checkpoint !== undefined &&\n facts.every(({ payload }) => payload._tag === \"ModelResponseRecorded\")\n ) {\n // The payload and header are validated, and operational facts are unchanged.\n // Dispatch needs their capacity proof; only a commit needs checkpoint wire.\n yield* decodeExecutionFrontier({\n canonicalRecords,\n throughSequence: after + ownedRecords.filter((fact) => !isOperationalRecord(fact)).length,\n }).pipe(Effect.mapError((cause) => failure(\"Active execution exceeds its bounds\", cause)));\n\n const state: ProgressState = {\n continuation,\n record: proposedRecord,\n ...(response === undefined ? {} : { response }),\n results,\n childResults,\n ...(completionBytes === undefined ? {} : { completionBytes }),\n };\n\n yield* checkCapacity(\n state,\n new Set(batch.records.map(({ recordId }) => recordId)),\n undefined,\n usageCharge,\n );\n yield* checkFutureShapes(state, cursorBytes);\n continue;\n }\n\n const record = yield* Effect.fromResult(captureRecord(proposedRecord)).pipe(\n Effect.map((record) => record.canonical),\n Effect.mapError((cause) => failure(\"Cannot capture canonical progress facts\", cause)),\n );\n\n if (!isExecutionProgressRecord(record))\n return yield* failure(\"Captured execution has no Run continuation\");\n if (canonicalRecordBytes(record) !== cursorBytes)\n return yield* failure(\"Continuation byte accounting differs from its Schema encoding\");\n\n const operational = new Map(\n (previous?.checkpoint?.operational ?? []).map((fact) => [fact.recordId, fact]),\n );\n\n const changed = facts.filter(isOperationalRecord);\n\n for (const fact of changed) {\n const prior = operational.get(fact.recordId);\n\n if (\n prior !== undefined &&\n (yield* Effect.fromResult(recordEncoding(prior)).pipe(\n Effect.mapError((cause) => failure(\"Cannot encode active Run fact\", cause)),\n )).json !==\n (yield* Effect.fromResult(recordEncoding(fact)).pipe(\n Effect.mapError((cause) => failure(\"Cannot encode active Run fact\", cause)),\n )).json\n )\n return yield* failure(\"An active Run fact cannot change after becoming durable\");\n operational.set(fact.recordId, fact);\n }\n\n const checkpoint = yield* ExecutionCheckpoint.makeEffect({\n version: 2,\n progressRecord: record,\n operational: [...operational.values()],\n canonicalRecords,\n originalSequence:\n originalSequence ??\n CanonicalSequence.make(\n after +\n ownedRecords\n .filter((fact) => !isOperationalRecord(fact))\n .findIndex((fact) => fact.recordId === originalInput.recordId) +\n 1,\n ),\n throughSequence: CanonicalSequence.make(\n after + ownedRecords.filter((fact) => !isOperationalRecord(fact)).length,\n ),\n batchId: batch.batchId,\n }).pipe(Effect.mapError((cause) => failure(\"Active execution exceeds its bounds\", cause)));\n\n const state = {\n continuation,\n record,\n checkpoint,\n ...(response === undefined ? {} : { response }),\n results,\n childResults,\n ...(completionBytes === undefined ? {} : { completionBytes }),\n };\n\n if (\n !facts.every((fact) => isTerminalBudgetFact(fact) && fact.payload._tag !== \"RunCompleted\")\n )\n yield* checkCapacity(\n state,\n new Set(batch.records.map(({ recordId }) => recordId)),\n undefined,\n usageCharge,\n );\n yield* checkFutureShapes(state);\n executions.push(\n ExecutionUpdate.make({\n previousRevision: previous?.continuation.revision ?? 0,\n checkpoint,\n facts: changed,\n // Pending operations and handoffs retain their own recovery rows and original facts.\n retire: position === \"settled\",\n }),\n );\n accepted.set(runId, state);\n }\n\n if (ownedRecords.length + executionCount > 256)\n return yield* failure(\"Progress and facts exceed the atomic batch bound\");\n\n const prepared = CommitBatch.make(\n {\n ...batch,\n records: ownedRecords.filter((fact) => !isOperationalRecord(fact)),\n },\n { disableChecks: true },\n );\n\n return {\n batch: prepared,\n executions,\n accept: () => {\n for (const record of batch.records) reservations.delete(record.recordId);\n for (const [runId, state] of accepted) {\n if (executions.find((update) => update.checkpoint.progress.runId === runId)?.retire)\n cached.delete(runId);\n else cached.set(runId, state);\n }\n // Administrative writers can address many old Runs; retention is still bounded.\n while (cached.size > 8) {\n const first = cached.keys().next().value;\n\n if (first !== undefined) cached.delete(first);\n }\n },\n };\n });\n\n const tail = Effect.flatMap(CurrentRunWriter, (writer) =>\n writer.threadId !== threadId\n ? Effect.fail(failure(\"Progress writer belongs to another Thread\"))\n : Effect.map(writer.tail, (position) => position.sequence),\n );\n\n const commitCaptured = Effect.fnUntraced(\n function* (batch: CanonicalBatch) {\n const writer = yield* CurrentRunWriter;\n\n for (let retries = 0; ; retries++) {\n const prepared = yield* prepare(batch, yield* tail).pipe(\n Effect.catchTag(\"ThreadNotMaterialized\", (cause) =>\n failure(\"Selected Run disappeared during progress publication\", cause),\n ),\n );\n\n const result = yield* writer.append(prepared.batch, prepared.executions).pipe(\n Effect.catchTag(\"AppendConflict\", (conflict) => {\n if (conflict.reason !== \"tail\" || retries >= 8) return Effect.fail(conflict);\n cached.clear();\n\n return Effect.succeed(undefined);\n }),\n );\n\n if (result === undefined) continue;\n\n if (result.replayed) cached.clear();\n else prepared.accept();\n\n return result;\n }\n },\n (effect) =>\n Effect.flatMap(CurrentRunWriter, (writer) =>\n writer.withProgress(gate.withPermits(1)(effect)),\n ),\n );\n\n const publishCaptured = Effect.fnUntraced(\n function* (batch: CanonicalBatch) {\n const publisher = yield* CurrentRunSettlement;\n\n if (publisher.threadId !== threadId)\n return yield* failure(\"Settlement publisher belongs to another Thread\");\n\n for (let retries = 0; ; retries++) {\n const prepared = yield* prepare(batch, (yield* publisher.tail).sequence).pipe(\n Effect.catchTag(\"ThreadNotMaterialized\", (cause) =>\n failure(\"Selected Run disappeared during progress publication\", cause),\n ),\n );\n\n const first = prepared.batch.records[0];\n\n if (first === undefined)\n return yield* failure(\"Settlement must publish a retained terminal fact\");\n\n const terminalBatch = yield* CanonicalBatch.makeEffect({\n ...prepared.batch,\n records: [first, ...prepared.batch.records.slice(1)],\n }).pipe(\n Effect.mapError((cause) =>\n failure(\"Settlement must publish a retained terminal fact\", cause),\n ),\n );\n\n const result = yield* publisher.publishSettlement(terminalBatch, prepared.executions).pipe(\n Effect.catchTag(\"AppendConflict\", (conflict) => {\n if (conflict.reason !== \"tail\" || retries >= 8) return Effect.fail(conflict);\n cached.clear();\n\n return Effect.succeed(undefined);\n }),\n );\n\n if (result === undefined) continue;\n\n if (result.replayed) cached.clear();\n else prepared.accept();\n\n return result;\n }\n },\n (effect) =>\n Effect.flatMap(CurrentRunSettlement, (writer) =>\n writer.withProgress(gate.withPermits(1)(effect)),\n ),\n );\n\n const commit = (batch: CommitBatch) => captureFacts(batch).pipe(Effect.flatMap(commitCaptured));\n\n const publish = (batch: CanonicalBatch) =>\n captureFacts(batch).pipe(Effect.flatMap(publishCaptured));\n\n const reserve = (runId: RunId, probe: CanonicalBatch, bytes: number) =>\n gate.withPermits(1)(\n Effect.gen(function* () {\n const after = yield* tail;\n\n yield* prepare(yield* captureFacts(probe), after);\n const recordId = probe.records[0].recordId;\n const state = yield* loadState(runId, after);\n\n if (state === undefined) return yield* failure(\"Dispatch has no canonical Run progress\");\n if (reservations.has(recordId))\n return yield* failure(\"Dispatch capacity is already reserved\");\n yield* checkCapacity(state, new Set(), {\n turn: state.continuation.turn,\n bytes,\n records: 1,\n });\n reservations.set(recordId, { runId, turn: state.continuation.turn, bytes, records: 1 });\n\n return gate.withPermits(1)(\n Effect.sync(() => {\n reservations.delete(recordId);\n }),\n );\n }),\n );\n\n const defer = (batch: CanonicalBatch) =>\n gate.withPermits(1)(\n Effect.gen(function* () {\n const after = yield* tail;\n\n const owned = yield* captureFacts(batch);\n\n yield* prepare(owned, after, \"preflight\");\n\n const response = owned.records.find(\n (record) => record.payload._tag === \"ModelResponseRecorded\",\n );\n\n if (response === undefined || response.payload._tag !== \"ModelResponseRecorded\")\n return yield* failure(\"Deferred dispatch has no response\");\n const progress = yield* loadState(response.payload.runId, after);\n\n if (progress === undefined) return yield* failure(\"Deferred dispatch has no Run progress\");\n\n const pending = resultCapacity({\n ...progress,\n continuation: {\n ...progress.continuation,\n accounting: { ...progress.continuation.accounting, accountedToolTurn: 0 },\n },\n response: response.payload,\n results: new Map(),\n childResults: new Map(),\n });\n\n const bytes =\n owned.records.reduce((total, record) => total + canonicalRecordBytes(record), 0) +\n MAX_RUN_CONTINUATION_BYTES +\n pending.bytes;\n\n const records = owned.records.length + pending.records;\n\n yield* checkCapacity(progress, new Set(), { turn: response.payload.turn, bytes, records });\n reservations.set(response.recordId, {\n runId: response.payload.runId,\n turn: response.payload.turn,\n bytes,\n records,\n });\n\n return owned;\n }),\n );\n\n const check = (runId: RunId) =>\n gate.withPermits(1)(\n Effect.gen(function* () {\n const state = yield* loadState(runId, yield* tail);\n\n if (state === undefined) return yield* failure(\"Execution has no canonical Run progress\");\n // Accepted states were shape-checked during preparation; recovered states still need proof.\n if (cached.get(runId) !== state) yield* checkFutureShapes(state);\n if (state.continuation.position !== \"settling\" && state.continuation.position !== \"settled\")\n yield* checkCapacity(state);\n }),\n );\n\n return {\n commit,\n publish,\n reserve,\n defer,\n check,\n stageUsage: (runId: RunId, bytes: number) => {\n if (bytes === 0) stagedUsage.delete(runId);\n else stagedUsage.set(runId, bytes);\n },\n };\n});\n"],"mappings":";;;;;;;;;;;;AAMA,MAAMA,aAAW,SAAiB,UAChC,iBAAiB,KAAK;CACpB,WAAW;CACX;CACA,GAAI,UAAU,KAAA,IAAY,CAAC,IAAI,EAAE,MAAM;AACzC,CAAC;;AAGH,MAAa,aAAa,WACxB,OAAO,QAAQ,kBAAkB,KAAK,EAAE,UAAU,OAAO,SAAS,CAAC,CAAC;;AAGtE,MAAa,kBAAkB,OAAO,WAAW,WAC/C,UACA,KACA;CACA,MAAM,QAAQ,OAAO,UAAU;EAAE;EAAU,UAAU,IAAI;CAAS,CAAC;CAEnE,IAAI,OAAO,OAAO,KAAK,GAAG,OAAO,OAAOA,UAAQ,4CAA4C;CAE5F,OAAO,MAAM;AACf,CAAC;;;;ACbD,IAAa,mBAAb,MAAa,yBAAyB,QAAQ,QAc5C,CAAC,CAAC,uCAAuC,CAAC,CAA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;GAAM;GAAO;EAAQ,CAAC;EACzF,aAAa,IAAI,SAAS,UAAU;GAClC,OAAO,SAAS,QAAQ;GACxB,MAAM,SAAS,QAAQ;GACvB;GACA;EACF,CAAC;EAED,OAAO;CACT,CAAC,CACH;CAEF,MAAM,SAAS,UACb,KAAK,YAAY,CAAC,CAAC,CACjB,OAAO,IAAI,aAAa;EACtB,MAAM,QAAQ,OAAO,UAAU,OAAO,OAAO,IAAI;EAEjD,IAAI,UAAU,KAAA,GAAW,OAAO,OAAO,QAAQ,yCAAyC;EAExF,IAAI,OAAO,IAAI,KAAK,MAAM,OAAO,OAAO,kBAAkB,KAAK;EAC/D,IAAI,MAAM,aAAa,aAAa,cAAc,MAAM,aAAa,aAAa,WAChF,OAAO,cAAc,KAAK;CAC9B,CAAC,CACH;CAEF,OAAO;EACL;EACA;EACA;EACA;EACA;EACA,aAAa,OAAc,UAAkB;GAC3C,IAAI,UAAU,GAAG,YAAY,OAAO,KAAK;QACpC,YAAY,IAAI,OAAO,KAAK;EACnC;CACF;AACF,CAAC"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"RunJournal-CNZqA3Ge.mjs","names":["makeRecordId"],"sources":["../src/durable/internal/journal-metadata.ts","../src/durable/internal/usage-totals.ts","../src/durable/RunJournal.ts"],"sourcesContent":["import { Brand } from \"effect\";\n\nimport { type RunId, type ToolCallId } from \"../../core/Identifiers.ts\";\nimport {\n type RecordId,\n type CanonicalRecordEnvelope,\n type PromptRecordEnvelope,\n type CompactionCreated,\n type ToolCallSettled,\n} from \"../Records.ts\";\n\n// These constructors produce nonempty strings from fixed prefixes or validated nonempty IDs.\n// Keep the canonical Schemas as the validation boundary for incoming and persisted values.\nconst makeRecordId = Brand.nominal<RecordId>();\n\n/** Deterministic canonical record identity of one Turn's Tool result. */\nexport const toolCallSettledRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => makeRecordId(`tool-settled:${runId}:${turn}:${toolCallId}`);\n\nexport type JournalRecordEnvelope = CanonicalRecordEnvelope | PromptRecordEnvelope;\n\n/** Metadata for one exact canonical prefix, including the exact selected Run evidence. */\nexport interface JournalMetadata {\n readonly ownerRunId: RunId | undefined;\n readonly firstSequenceByRun: ReadonlyMap<string, number>;\n readonly responseSequencesByRun: ReadonlyMap<string, ReadonlyArray<number>>;\n readonly terminalSequenceByRun: ReadonlyMap<string, number>;\n readonly settledSpans: ReadonlyArray<{\n readonly from: number;\n readonly to: number;\n readonly runId: RunId;\n readonly recordId: string;\n }>;\n readonly settledSequenceById: ReadonlyMap<string, number>;\n readonly settledToolCallRecordIds: ReadonlySet<string>;\n readonly settledById: ReadonlyMap<\n string,\n Pick<ToolCallSettled, \"isFailure\" | \"budgetRejected\" | \"toolSelection\">\n >;\n readonly compactions: ReadonlyArray<{\n readonly payload: CompactionCreated;\n readonly sequence: number;\n }>;\n}\n\n/**\n * Attempt-local metadata collector. Feed every validated record exactly once, in canonical order,\n * including records omitted from the control view. Calling finish transfers its collections;\n * discard the collector afterward. The metadata may only accompany a replay stream bounded at\n * that same captured tail. A later prefix requires a new collector.\n */\nexport const makeJournalMetadata = (ownerRunId: RunId | undefined) => {\n const firstSequenceByRun = new Map<string, number>();\n\n const responseSequencesByRun = new Map<string, Array<number>>();\n\n const declarationsByRun = new Map<\n RunId,\n Array<{\n readonly sequence: number;\n readonly turn: number;\n readonly callIds: ReadonlyArray<string>;\n }>\n >();\n\n const terminalSequenceByRun = new Map<string, number>();\n\n const settledSpans: Array<{\n readonly from: number;\n readonly to: number;\n readonly runId: RunId;\n readonly recordId: string;\n }> = [];\n\n const settledSequenceById = new Map<string, number>();\n\n const settledToolCallRecordIds = new Set<string>();\n\n const settledById = new Map<\n string,\n Pick<ToolCallSettled, \"isFailure\" | \"budgetRejected\" | \"toolSelection\">\n >();\n\n const compactions: Array<{ readonly payload: CompactionCreated; readonly sequence: number }> = [];\n\n return {\n add: (envelope: JournalRecordEnvelope): void => {\n const payload = envelope.record.payload;\n\n if (\n (payload._tag === \"RunCompleted\" ||\n payload._tag === \"RunFailed\" ||\n payload._tag === \"SubmissionSettled\") &&\n payload.runId !== undefined &&\n !terminalSequenceByRun.has(payload.runId)\n )\n terminalSequenceByRun.set(payload.runId, envelope.sequence);\n if (payload._tag === \"CompactionCreated\") {\n compactions.push({ payload, sequence: envelope.sequence });\n\n return;\n }\n if (\n \"runId\" in payload &&\n typeof payload.runId === \"string\" &&\n !firstSequenceByRun.has(payload.runId)\n )\n firstSequenceByRun.set(payload.runId, envelope.sequence);\n if (payload._tag === \"ModelResponseRecorded\") {\n const sequences = responseSequencesByRun.get(payload.runId) ?? [];\n\n sequences.push(envelope.sequence);\n responseSequencesByRun.set(payload.runId, sequences);\n\n const callIds =\n \"toolOperations\" in payload\n ? payload.toolOperations.map((operation) => operation.toolCallId)\n : payload.messages.content.flatMap((message) =>\n message.role === \"assistant\"\n ? message.content.flatMap((part) =>\n part.type === \"tool-call\" && !part.providerExecuted ? [part.id] : [],\n )\n : [],\n );\n\n if (callIds.length > 0) {\n const declarations = declarationsByRun.get(payload.runId) ?? [];\n\n // Retain references to bounded source identities, not an expanded settlement-ID\n // string and Map entry for every declared operation in the context.\n declarations.push({ sequence: envelope.sequence, turn: payload.turn, callIds });\n declarationsByRun.set(payload.runId, declarations);\n }\n } else if (payload._tag === \"ToolCallSettled\") {\n settledToolCallRecordIds.add(envelope.record.recordId);\n settledSequenceById.set(envelope.record.recordId, envelope.sequence);\n if (payload.runId === ownerRunId)\n settledById.set(envelope.record.recordId, {\n isFailure: payload.isFailure,\n ...(!(\"toolSelection\" in payload) || payload.toolSelection === undefined\n ? {}\n : { toolSelection: payload.toolSelection }),\n ...(!(\"budgetRejected\" in payload) || payload.budgetRejected === undefined\n ? {}\n : { budgetRejected: payload.budgetRejected }),\n });\n\n const from = declarationsByRun\n .get(payload.runId)\n ?.findLast(\n (declaration) =>\n declaration.callIds.includes(payload.toolCallId) &&\n toolCallSettledRecordId(payload.runId, declaration.turn, payload.toolCallId) ===\n envelope.record.recordId,\n )?.sequence;\n\n if (from !== undefined && from < envelope.sequence)\n settledSpans.push({\n from,\n to: envelope.sequence,\n runId: payload.runId,\n recordId: envelope.record.recordId,\n });\n }\n },\n finish: (): JournalMetadata => {\n responseSequencesByRun.forEach((sequences, runId) => {\n responseSequencesByRun.set(runId, sequences.slice());\n });\n\n return {\n ownerRunId,\n firstSequenceByRun,\n responseSequencesByRun,\n terminalSequenceByRun,\n settledSpans,\n settledSequenceById,\n settledToolCallRecordIds,\n settledById,\n compactions,\n };\n },\n };\n};\n","import { Effect } from \"effect\";\n\nimport { summarizeModelUsage, type ModelCallUsage } from \"../../core/Usage.ts\";\n\n/** Captured calls are additive and nonnegative; progress does not need attribution groups. */\nexport const continuationUsage = Effect.fnUntraced(function* (\n calls: ReadonlyArray<ModelCallUsage>,\n) {\n let inputTokens = 0;\n let outputTokens = 0;\n let costMicrousd = 0;\n let knownWebSearchCalls = 0;\n\n for (const call of calls) {\n inputTokens += call.inputTokens.total;\n outputTokens += call.outputTokens.total;\n costMicrousd += call.costMicrousd;\n knownWebSearchCalls += call.webSearchCalls ?? 0;\n }\n if (\n Number.isSafeInteger(inputTokens) &&\n Number.isSafeInteger(outputTokens) &&\n Number.isSafeInteger(costMicrousd) &&\n Number.isSafeInteger(knownWebSearchCalls)\n )\n return { modelCalls: calls.length, inputTokens, outputTokens, costMicrousd };\n\n // Safe global sums bound every component/group. On overflow retain the full validator,\n // including groups whose hosted-search coverage differs from the aggregate's coverage.\n const summary = yield* summarizeModelUsage(calls);\n\n return {\n modelCalls: summary.modelCalls,\n inputTokens: summary.inputTokens.total,\n outputTokens: summary.outputTokens.total,\n costMicrousd: summary.costMicrousd,\n };\n});\n","import { Brand, Effect, Predicate, Schema, Stream, type DateTime } from \"effect\";\nimport { Prompt } from \"effect/ai\";\n\nimport {\n type RunId,\n type TurnId,\n ThreadId,\n ToolCallId,\n type SubmissionId,\n} from \"../core/Identifiers.ts\";\nimport { copyJson } from \"../core/internal/json.ts\";\nimport { type ExhaustedLimit } from \"../core/RunEvent.ts\";\nimport { RunPolicyUsage } from \"../core/RunPolicyUsage.ts\";\nimport { type Selection, type Snapshot } from \"../core/ToolExposure.ts\";\nimport type { ToolParameterRejection } from \"../core/ToolResult.ts\";\nimport { ModelCallUsage, summarizeModelUsage, type RunUsageSummary } from \"../core/Usage.ts\";\nimport type { WorkerRef } from \"../core/Worker.ts\";\nimport {\n CLEARED_TOOL_RESULT,\n COMPACTION_SUMMARY_PREFIX,\n contextWindowId,\n contextWindowMessage,\n} from \"../engine/Compaction.ts\";\nimport type { RunTurnToolResult } from \"../engine/RunOptions.ts\";\nimport { digestJson } from \"./Digest.ts\";\nimport {\n makeJournalMetadata,\n toolCallSettledRecordId,\n type JournalMetadata,\n type JournalRecordEnvelope,\n} from \"./internal/journal-metadata.ts\";\nimport { continuationUsage } from \"./internal/usage-totals.ts\";\nimport {\n type BatchId,\n type RecordId,\n type CompactionCreated,\n CanonicalBatch,\n ModelResponseRecorded,\n MAX_PERSISTED_JSON_BYTES,\n PersistedJson,\n RecordEnvelope,\n RunCompleted,\n ToolCallSettled,\n type CanonicalRecordEnvelope,\n CanonicalSequence,\n type DeploymentId,\n type ProducerId,\n} from \"./Records.ts\";\nimport { IdempotencyKey } from \"./SubmissionLedger.ts\";\n\n/** A canonical record could not be projected into Run/Prompt state. */\nexport class RunJournalError extends Schema.TaggedError<RunJournalError>()(\"RunJournalError\", {\n message: Schema.String,\n cause: Schema.optionalKey(Schema.Defect()),\n}) {}\n\nconst journalError = (message: string, cause?: unknown): RunJournalError =>\n cause === undefined\n ? RunJournalError.make({ message })\n : RunJournalError.make({ message, cause });\n\n// These constructors produce nonempty strings from fixed prefixes or validated nonempty IDs.\n// Keep the canonical Schemas as the validation boundary for incoming and persisted values.\nconst makeRunId = Brand.nominal<RunId>();\nconst makeTurnId = Brand.nominal<TurnId>();\nconst makeBatchId = Brand.nominal<BatchId>();\nconst makeRecordId = Brand.nominal<RecordId>();\n\n/**\n * Deterministic Run identity pinned per Submission (plan §Coordinator flow). Every Attempt of one\n * Submission shares this Run identity, so canonical per-Turn records from different Attempts\n * belong to one logical Run.\n */\nexport const runIdForSubmission = (submissionId: SubmissionId): RunId =>\n makeRunId(`run:${submissionId}`);\n\n/** Stable canonical clock identity shared by every Attempt of one Run. */\nexport const runStartedRecordId = (runId: RunId): RecordId => makeRecordId(`run-start:${runId}`);\n\nexport const runStartedBatchId = (runId: RunId): BatchId => makeBatchId(`run-start:${runId}`);\n\nexport const runDurationRecordId = (runId: RunId): RecordId =>\n makeRecordId(`run-duration:${runId}`);\n\nexport const runDurationBatchId = (runId: RunId): BatchId => makeBatchId(`run-duration:${runId}`);\n\n/** Deterministic Turn identity: Attempt-independent for one (Run, canonical turn) pair. */\nexport const turnIdForRun = (runId: RunId, turn: number): TurnId =>\n makeTurnId(`turn:${runId}:${turn}`);\n\n/** Deterministic batch identity of a response committed atomically with its closed Turn outcomes. */\nexport const turnBatchId = (runId: RunId, turn: number): BatchId =>\n makeBatchId(`turn:${runId}:${turn}`);\n\n/**\n * Deterministic batch identity of a tool-declaring Turn's RESPONSE commit (plan §2.1 commit 1):\n * the assistant response plus pending steering becomes canonical before approval preflight and\n * dispatch fencing, or when readonly execution first requires a persisted call-scoped capability.\n * Unsettled declarations conservatively record possible execution.\n */\nexport const turnResponseBatchId = (runId: RunId, turn: number): BatchId =>\n makeBatchId(`turn-response:${runId}:${turn}`);\n\n/**\n * Deterministic batch identity of a tool-declaring Turn's RESULTS commit (plan §2.1 commit 5):\n * every `ToolCallSettled` record of the Turn, in declaration order, model-visible atomically.\n */\nexport const turnResultsBatchId = (runId: RunId, turn: number): BatchId =>\n makeBatchId(`turn-results:${runId}:${turn}`);\n\n/**\n * Deterministic per-call late-settle batch identity used by the resolution path when one\n * recovered/resolved call settles outside its Turn's results batch. Record identity\n * (`tool-settled:{runId}:{turn}:{toolCallId}`) dedupes double-settles across both paths.\n */\nexport const toolCallResultBatchId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): BatchId => makeBatchId(`turn-results:${runId}:${turn}:${toolCallId}`);\n\n/**\n * Deterministic identity of one pre-Turn compaction record (RUN-026,\n * RUN-026). Keyed by Run, Turn, and kind — the engine performs at most one\n * threshold compaction per Turn plus at most one overflow-forced summarize,\n * so a superseding Attempt that re-decides the same compaction replays the\n * batch identity instead of duplicating the record.\n */\nexport const compactionRecordId = (\n runId: RunId,\n turn: number,\n kind: \"clear-tool-results\" | \"summarize\" | \"rollover\",\n): RecordId => makeRecordId(`compaction:${runId}:${turn}:${kind}`);\n\n/** Deterministic batch identity of one compaction append (same string as its record id). */\nexport const compactionBatchId = (\n runId: RunId,\n turn: number,\n kind: \"clear-tool-results\" | \"summarize\" | \"rollover\",\n): BatchId => makeBatchId(`compaction:${runId}:${turn}:${kind}`);\n\n/** Deterministic canonical record identity of one Turn's `ModelResponseRecorded` record. */\nexport const modelResponseRecordId = (runId: RunId, turn: number): RecordId =>\n makeRecordId(`model-response:${runId}:${turn}`);\n\n/** Terminal Tool completion marker committed atomically with its settled Tool result. */\nexport const runCompletedRecordId = (runId: RunId): RecordId =>\n makeRecordId(`run-completed:${runId}`);\n\n/** Native source reservation locator, including the first admission of a continuing worker. */\nexport const workerInputRecordId = (messageId: IdempotencyKey): RecordId =>\n makeRecordId(`worker-input:${messageId}`);\n\n/** Source-owned first reservation; native worker identity is minted from its first message. */\nexport const firstWorkerInputRecordId = (worker: WorkerRef): RecordId =>\n makeRecordId(`worker-input:${worker.threadId}`);\n\nexport const workerOriginRecordId = (threadId: ThreadId): RecordId =>\n makeRecordId(`worker-origin:${threadId}`);\n\nexport const workerReportRecordId = (messageId: IdempotencyKey): RecordId =>\n makeRecordId(`worker-report:${messageId}`);\n\nexport const peerMessageRecordId = (messageId: IdempotencyKey): RecordId => makeRecordId(messageId);\n\n/** Same immutable tuple used by native update admission; callers never parse its hash. */\nexport const agentUpdateRecordId = Effect.fnUntraced(function* (\n threadId: ThreadId,\n runId: RunId,\n updateId: IdempotencyKey,\n) {\n return makeRecordId(`agent-update:${yield* digestJson([threadId, runId, updateId])}`);\n});\n\n/** Deterministic canonical record identity of one Turn's `ToolCallSettled` record. */\nexport { toolCallSettledRecordId };\n\n/** Deterministic batch identity of one Turn's `ToolCallUnknown` marking append. */\nexport const markUnknownBatchId = (submissionId: SubmissionId, turn: number): BatchId =>\n makeBatchId(`mark-unknown:${submissionId}:${turn}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolCallUnknown` record. */\nexport const toolCallUnknownRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => makeRecordId(`tool-unknown:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic batch identity of one Tool Call's resolution append (DUR-017). */\nexport const toolCallResolutionBatchId = (\n submissionId: SubmissionId,\n toolCallId: ToolCallId,\n): BatchId => makeBatchId(`resolve:${submissionId}:${toolCallId}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolCallResolved` record. */\nexport const toolCallResolvedRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => makeRecordId(`tool-resolved:${runId}:${turn}:${toolCallId}`);\n\n/**\n * Deterministic identity of one accepted Durable Step result. The one-record batch reuses the\n * SAME string, so batch idempotency plus the epoch fence realize the durability §11\n * racing-writers rule: only the fenced winner's record commits; the loser replays it.\n * A versioned JSON tuple keeps separator characters in each identity component distinct.\n * Replay derives this key from the structured payload, including records with legacy IDs.\n */\nexport const toolStepSettledRecordId = (\n runId: RunId,\n toolCallId: ToolCallId,\n stepName: string,\n): RecordId => makeRecordId(JSON.stringify([\"step@2\", runId, toolCallId, stepName]));\n\n/** Deterministic batch identity of one Durable Step commit (same string as its record id). */\nexport const toolStepSettledBatchId = (\n runId: RunId,\n toolCallId: ToolCallId,\n stepName: string,\n): BatchId => makeBatchId(toolStepSettledRecordId(runId, toolCallId, stepName));\n\n/** Deterministic batch identity of one Turn's canonical approval-request append (plan §2.6). */\nexport const turnApprovalsBatchId = (runId: RunId, turn: number): BatchId =>\n makeBatchId(`turn-approvals:${runId}:${turn}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolApprovalRequested` record. */\nexport const toolApprovalRequestRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => makeRecordId(`approval-request:${runId}:${turn}:${toolCallId}`);\n\n/** Deterministic batch identity of one Tool Call's canonical approval-decision append. */\nexport const approvalDecisionBatchId = (\n submissionId: SubmissionId,\n toolCallId: ToolCallId,\n): BatchId => makeBatchId(`approval-decision:${submissionId}:${toolCallId}`);\n\n/** Deterministic canonical record identity of one Tool Call's `ToolApprovalDecided` record. */\nexport const toolApprovalDecisionRecordId = (\n runId: RunId,\n turn: number,\n toolCallId: ToolCallId,\n): RecordId => makeRecordId(`approval-decision:${runId}:${turn}:${toolCallId}`);\n\n/**\n * One conservative incomplete-usage marker per Run, regardless of how often recovery occurs.\n */\nexport const modelResponseInterruptedRecordId = (runId: RunId): RecordId =>\n makeRecordId(`interrupted:${runId}`);\n\n/** Deterministic batch identity of one `ModelResponseInterrupted` append (same string). */\nexport const modelResponseInterruptedBatchId = (runId: RunId): BatchId =>\n makeBatchId(`interrupted:${runId}`);\n\nconst decodeThreadId = Schema.decodeSync(ThreadId);\nconst decodeIdempotencyKey = Schema.decodeSync(IdempotencyKey);\n\n/**\n * Deterministic canonical record identity of one parent Tool Call's `SubagentRequested` record.\n * The one-record batch reuses the same string, so batch\n * idempotency plus the parent epoch fence make the request append exactly-once-canonical.\n */\nexport const subagentRequestedRecordId = (runId: RunId, toolCallId: ToolCallId): RecordId =>\n makeRecordId(`subagent-requested:${runId}:${toolCallId}`);\n\n/** Deterministic batch identity of one `SubagentRequested` append (same string). */\nexport const subagentRequestedBatchId = (runId: RunId, toolCallId: ToolCallId): BatchId =>\n makeBatchId(`subagent-requested:${runId}:${toolCallId}`);\n\n/**\n * Deterministic canonical record identity of one parent Tool Call's `SubagentStarted` record.\n * Recovery's start-link repair appends the EXACT same record\n * under this identity, so a raced repair replays instead of duplicating (SUB-016/SUB-017).\n */\nexport const subagentStartedRecordId = (runId: RunId, toolCallId: ToolCallId): RecordId =>\n makeRecordId(`subagent-started:${runId}:${toolCallId}`);\n\n/** Deterministic batch identity of one `SubagentStarted` append (same string). */\nexport const subagentStartedBatchId = (runId: RunId, toolCallId: ToolCallId): BatchId =>\n makeBatchId(`subagent-started:${runId}:${toolCallId}`);\n\n/**\n * Deterministic batch identity of one parent Tool Call's atomic settlement join: the\n * `SubagentJoined` record plus the parent's `ToolCallSettled` record (its existing\n * `tool-settled:{runId}:{turn}:{toolCallId}` identity) commit as ONE canonical batch (SUB-019).\n */\nexport const subagentJoinBatchId = (runId: RunId, toolCallId: ToolCallId): BatchId =>\n makeBatchId(`subagent-join:${runId}:${toolCallId}`);\n\n/** Deterministic canonical record identity of one parent Tool Call's `SubagentJoined` record. */\nexport const subagentJoinedRecordId = (runId: RunId, toolCallId: ToolCallId): RecordId =>\n makeRecordId(`subagent-joined:${runId}:${toolCallId}`);\n\n/**\n * Deterministic identity of one child Thread's `SubagentLineageRecorded` record.\n * Its own single-record batch reuses the same string so the generic\n * `thread-created:{cid}` batch identity is never contradicted.\n */\nexport const subagentLineageRecordId = (threadId: ThreadId): RecordId =>\n makeRecordId(`subagent-lineage:${threadId}`);\n\n/** Deterministic batch identity of one `SubagentLineageRecorded` append (same string). */\nexport const subagentLineageBatchId = (threadId: ThreadId): BatchId =>\n makeBatchId(`subagent-lineage:${threadId}`);\n\n/**\n * Deterministic intended child Thread identity: the\n * parent Submission and Tool Call pair addresses exactly one child Thread, so a replayed\n * establishment converges on the one existing child (SUB-016).\n */\nexport const childThreadIdFor = (\n parentSubmissionId: SubmissionId,\n toolCallId: ToolCallId,\n): ThreadId => decodeThreadId(`subagent:${parentSubmissionId}:${toolCallId}`);\n\n/**\n * Deterministic child admission idempotency key: scoped to\n * the parent Run and Tool Call identity, so duplicate admission attempts resolve through the\n * ledger's idempotency contract to one child Receipt (SUB-016, SUB-031). The ledger key is\n * bounded (256); coordinator-minted Run and Tool Call identities stay far below that bound.\n */\nexport const childIdempotencyKeyFor = (\n parentRunId: RunId,\n toolCallId: ToolCallId,\n): IdempotencyKey => decodeIdempotencyKey(`subagent:${parentRunId}:${toolCallId}`);\n\nconst decodePersistedPrompt = (\n messages: PersistedJson,\n): Effect.Effect<Prompt.Prompt, RunJournalError> =>\n Schema.decodeUnknownEffect(Prompt.Prompt)(messages).pipe(\n Effect.mapError((cause) =>\n journalError(\"Canonical messages are not Schema-encoded Prompt messages\", cause),\n ),\n );\n\n// Canonical payloads are immutable. Weak keys let retained storage rows own the lifetime\n// while repeated projections of an advancing tail reuse their validated Prompt values.\nconst decodedMessages = new WeakMap<object, Prompt.Prompt>();\n\nconst decodePromptMessages = (messages: PersistedJson | Prompt.Prompt) =>\n Effect.suspend(() => {\n if (Prompt.isPrompt(messages)) return Effect.succeed(messages);\n if (!Predicate.isObject(messages)) return decodePersistedPrompt(messages);\n const cached = decodedMessages.get(messages);\n\n return cached === undefined\n ? decodePersistedPrompt(messages).pipe(\n Effect.tap((prompt) =>\n Effect.sync(() => {\n decodedMessages.set(messages, prompt);\n }),\n ),\n )\n : Effect.succeed(cached);\n });\n\ninterface PendingSettledTool {\n readonly record: Pick<ToolCallSettled, \"toolCallId\" | \"toolName\" | \"result\" | \"isFailure\">;\n /** RUN-026: a `clear-tool-results` compaction covers this record's sequence. */\n readonly cleared: boolean;\n}\n\nconst toolMessageFromSettled = (\n settled: ReadonlyArray<PendingSettledTool>,\n): Effect.Effect<Prompt.Message, RunJournalError> =>\n Effect.try({\n try: () =>\n Prompt.makeMessage(\"tool\", {\n content: settled.map(({ record, cleared }) =>\n Prompt.makePart(\"tool-result\", {\n id: record.toolCallId,\n name: record.toolName,\n result: cleared ? CLEARED_TOOL_RESULT : record.result,\n isFailure: record.isFailure,\n providerExecuted: false,\n }),\n ),\n }),\n catch: (cause) => journalError(\"Unable to rebuild Tool message from ToolCallSettled\", cause),\n });\n\n/**\n * Pure canonical projection of one Run's durable execution state.\n *\n * Prompt reconstruction contract (D8):\n *\n * - `ModelResponseRecorded.messages` carries the Schema-encoded Prompt messages the Turn appended\n * to the model-visible prompt — for the Run's FIRST committed Turn that includes the evaluated\n * instruction and user-input messages, for later Turns only the assistant response messages.\n * Tool messages are excluded from `messages`.\n * - `ToolCallSettled` records (committed in the same per-Turn batch, in declaration order)\n * deterministically rebuild the Turn's single Tool message.\n * - `UserInputRecorded` records input, with a Submission identity only for durable admission. Its\n * Prompt-visible form (instructions + user message) becomes canonical inside the owning Run's\n * first `ModelResponseRecorded`. The projection consumes it only for Run correlation.\n * - Immediate retained history uses `ModelCompleted.history` as a full retained model-context\n * snapshot. Its `messages` separately preserve the successful Run's exact source contribution\n * for recall. It has no resumable Turn state.\n */\n/** Cumulative committed usage of the projected Run (RUN-023 resume re-seed). */\nexport interface RunJournalUsage {\n readonly modelCalls: number;\n /** Known accounting gaps retained across Attempts without changing numeric usage totals. */\n readonly unobservedModelCalls?: number | undefined;\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly lastInputTokens: number;\n readonly lastOutputTokens: number;\n /** Cumulative persisted spend of the projected Run's committed calls (RUN-023). */\n readonly costMicrousd: number;\n /** Canonical per-call detail used for settlement aggregation and recovery. */\n readonly modelUsage: ReadonlyArray<ModelCallUsage>;\n /** Detailed usage of retired records, grouped without retaining per-call payloads. */\n readonly summarizedModelUsage?: RunUsageSummary | undefined;\n}\n\nexport interface RunJournalProjection {\n readonly toolSelection?: Selection | undefined;\n readonly policyUsage: RunPolicyUsage;\n /** Canonical projection for the requested Run; may end at its resumable Tool declaration. */\n readonly prompt: Prompt.Prompt;\n /** Prior-Run history with model-only unknown results closing incomplete application calls. */\n readonly historyBefore: Prompt.Prompt;\n /** Inclusive range after effective summarize/rollover coverage; earlier used facts stay retained. */\n readonly historyFrom: CanonicalSequence;\n /** Number of canonical Turns already committed for the projected Run. */\n readonly committedTurns: number;\n /** Summed per-call usage of the projected Run's committed responses; zeros for records predating usage capture. */\n readonly usage: RunJournalUsage;\n /** Latest committed context window identity, retained across ownership changes. */\n readonly contextWindowId?: string | undefined;\n /** Canonical evaluated instructions and initial input for this Run, independent of the view. */\n readonly protectedContext?: Prompt.Prompt | undefined;\n /** Last successful singleton Tool awaiting possible context-control interpretation by the engine. */\n readonly pendingContextToolCallId?: string | undefined;\n}\n\ninterface ProjectedResponseUsage {\n readonly modelCalls: number;\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly costMicrousd: number;\n readonly modelUsage: ReadonlyArray<ModelCallUsage>;\n}\n\nconst projectedResponseUsage = (\n response: ModelResponseRecorded,\n): Effect.Effect<ProjectedResponseUsage, RunJournalError> =>\n Effect.gen(function* () {\n const calls = response.modelUsage;\n\n if (calls === undefined) {\n return {\n modelCalls: 1,\n inputTokens: response.inputTokens ?? 0,\n outputTokens: response.outputTokens ?? 0,\n costMicrousd: response.costMicrousd ?? 0,\n modelUsage: [],\n };\n }\n if (calls.length === 0) {\n return yield* journalError(\"A canonical modelUsage list must not be empty\");\n }\n\n const summary = yield* summarizeModelUsage(calls).pipe(\n Effect.mapError((cause) =>\n journalError(\"Canonical model usage exceeds accounting bounds\", cause),\n ),\n );\n\n if (\n (response.inputTokens !== undefined && response.inputTokens !== summary.inputTokens.total) ||\n (response.outputTokens !== undefined &&\n response.outputTokens !== summary.outputTokens.total) ||\n (response.costMicrousd !== undefined && response.costMicrousd !== summary.costMicrousd)\n ) {\n return yield* journalError(\"Canonical detailed and aggregate model usage disagree\");\n }\n\n return {\n modelCalls: summary.modelCalls,\n inputTokens: summary.inputTokens.total,\n outputTokens: summary.outputTokens.total,\n costMicrousd: summary.costMicrousd,\n modelUsage: calls,\n };\n });\n\nconst addProjectedUsage = (\n field: string,\n left: number,\n right: number,\n): Effect.Effect<number, RunJournalError> =>\n Schema.decodeEffect(Schema.Natural)(left + right).pipe(\n Effect.mapError((cause) =>\n journalError(`Canonical projected usage exceeds safe-integer bounds at ${field}`, cause),\n ),\n );\n\ninterface FoldState {\n readonly all: Array<Prompt.Message>;\n readonly before: Array<Prompt.Message>;\n readonly pendingTools: Array<PendingSettledTool>;\n readonly pendingToolsForRun: boolean;\n readonly committedTurns: number;\n}\n\nconst decodeToolCallId = Schema.decodeSync(ToolCallId);\nconst decodeToolCallIdEffect = Schema.decodeEffect(ToolCallId);\n\nconst declaredApplicationToolCallIds = (prompt: Prompt.Prompt): ReadonlyArray<string> => {\n const ids: Array<string> = [];\n\n for (const message of prompt.content) {\n if (message.role !== \"assistant\") continue;\n for (const part of message.content) {\n if (part.type === \"tool-call\" && !part.providerExecuted) ids.push(part.id);\n }\n }\n\n return ids;\n};\n\n/**\n * Phase 5 audit tags that are prompt-transparent: they carry durability evidence (approval,\n * unknown marking, resolution, Step results, approvals, interruption) but contribute nothing to\n * the model-visible Prompt, and — unlike the P4 tags — they do NOT split a contiguous\n * `ToolCallSettled` group into separate Tool messages, so a late-settled call's audit records\n * cannot change the replayed prompt shape.\n *\n * The four S2 Subagent lifecycle tags are prompt-transparent for the same reason (spec §5/§11):\n * the parent prompt never carries child transcript or establishment evidence — the joined child\n * result reaches the model exclusively through the paired `ToolCallSettled` record, and the\n * child-log lineage record is not model input.\n */\nconst PROMPT_TRANSPARENT_TAGS: ReadonlySet<string> = new Set([\n \"RunPolicyUsageReserved\",\n \"RunStarted\",\n \"RunContextRecorded\",\n \"RunContinuation\",\n \"RunDurationExhausted\",\n \"ToolCallUnknown\",\n \"ToolCallResolved\",\n \"ToolStepSettled\",\n \"ToolApprovalRequested\",\n \"ToolApprovalDecided\",\n \"ModelResponseInterrupted\",\n \"ModelCallAborted\",\n \"SubagentRequested\",\n \"SubagentStarted\",\n \"SubagentJoined\",\n \"SubagentLineageRecorded\",\n \"WorkerInputRequested\",\n \"WorkerOriginRecorded\",\n \"WorkerInputCompleted\",\n \"WorkerInputRefused\",\n \"WorkerReportPrepared\",\n \"AgentUpdateEmitted\",\n \"WorkerReportRefused\",\n \"PeerMessagePrepared\",\n \"SubtreeBudgetReserved\",\n]);\n\n/**\n * Pure projection: rebuild one Run's resume state from canonical records (DUR-015). Canonical\n * order is authoritative; the fold projects each `ModelResponseRecorded` Turn and the\n * owning Run's resumable incomplete Tool Turn. It flushes each contiguous group of valid `ToolCallSettled` records into one Tool message,\n * exactly mirroring the per-Turn commit shape produced by `turnCanonicalBatch` and the\n * `turnResponseBatch`/`turnResultsBatch` split. The Phase 5 audit tags\n * are skipped transparently, so split-batch commits replay to the same prompt as P4 single-batch\n * commits.\n *\n * An incomplete application Tool turn remains visible while projecting its owning Run so active\n * recovery can resume the declared batch. It is not a valid model-visible Turn boundary for a\n * later Run until model-only unknown results close its missing calls. Those explanatory results\n * are never canonical settlements or evidence for compaction, recovery or accounting. Real\n * results replace them at the original declaration, including results appended after another Run.\n * Prior user intent and assistant text remain visible; prior system instructions do not.\n * Each Run retains the history preceding its start and its own continuation. Other Runs'\n * subsequent Turns cannot replace its input. Compaction covers only its creator's Run view;\n * a projection without an owner retains interleaved exchanges from the complete Thread history.\n */\n/** @internal Lightweight canonical boundaries collected without retaining record payloads. */\nexport interface JournalBoundary {\n readonly sequence: CanonicalSequence;\n readonly tag:\n | \"ModelCompleted\"\n | \"ModelResponseRecorded\"\n | \"ToolCallSettled\"\n | \"CompactionCreated\";\n readonly promptLength: number;\n /** A declaration without all settled results requires terminal-prior-Run proof for coverage. */\n readonly incomplete?: true | undefined;\n /** The Run terminated after its last response and differs from the projection's owner. */\n readonly terminalPriorRun?: true | undefined;\n}\n\n/** Resolved immutable context. Persistence keeps a canonical range and digest, not this Prompt. */\nexport interface RunJournalContext {\n readonly runId: RunId;\n readonly prompt: Prompt.Prompt;\n readonly priorHistoryLength: number;\n readonly historyFrom: CanonicalSequence;\n readonly boundaries: ReadonlyArray<JournalBoundary>;\n readonly contextWindowId?: string | undefined;\n readonly recordId: RecordId;\n}\n\n/**\n * Reconstruct a fixed canonical prefix from a re-readable stream. The caller must keep the same\n * records visible on every traversal. The first collects compaction and settlement metadata;\n * rollovers additionally validate covered Tool batches before rebuilding Prompt and usage. Metadata and the\n * live Prompt remain resident; covered historical message/tool payloads do not. An uncompacted Prompt still grows\n * with its conversation, so hosts must configure an appropriate context compaction policy.\n * Prepared metadata must describe exactly this stream through the same fixed tail;\n * it skips only the metadata scan, never covered-Tool validation or the canonical fold.\n * @internal\n */\nexport const projectRunJournalStream = Effect.fnUntraced(function* <\n E,\n R,\n A extends JournalRecordEnvelope,\n>(\n records: Stream.Stream<A, E, R>,\n ownerRunId: RunId | undefined,\n onBoundary?: (boundary: JournalBoundary) => void,\n savedContext?: RunJournalContext,\n preparedMetadata?: JournalMetadata,\n onEvidence?: (envelope: A) => void,\n): Effect.fn.Return<RunJournalProjection, RunJournalError | E, R> {\n if (savedContext !== undefined && savedContext.runId !== ownerRunId)\n return yield* journalError(\"Saved original context belongs to another Run\");\n\n const initialContext = savedContext?.prompt;\n\n if (\n initialContext !== undefined &&\n savedContext !== undefined &&\n savedContext.priorHistoryLength > initialContext.content.length\n )\n return yield* journalError(\"Saved original context has an invalid ownership boundary\");\n const historical = initialContext?.content.slice(0, savedContext?.priorHistoryLength) ?? [];\n\n let state: FoldState = {\n all: [],\n before: [],\n pendingTools: [],\n pendingToolsForRun: false,\n committedTurns: 0,\n };\n\n // RUN-026 pre-scan: valid compactions retire only their creator's Run view. A bound\n // stays below its own sequence and cannot split a visible response from its settled results.\n // Pruning and rollovers may cover complete owner-Run batches; a summarize record carries\n // its summary. Invalid records leave full history authoritative. A wider containing view\n // replaces earlier coverage, with equal bounds preferring the later record.\n // Exact declaration spans are validated at each compaction's own captured prefix.\n // Later results preserve committed coverage and close retained or summarized calls below.\n if (preparedMetadata !== undefined && preparedMetadata.ownerRunId !== ownerRunId)\n return yield* journalError(\"Prepared journal metadata belongs to another replay\");\n\n let metadata = preparedMetadata;\n\n if (metadata === undefined) {\n const collected = makeJournalMetadata(ownerRunId);\n\n yield* Stream.runForEach(records, (envelope) => Effect.sync(() => collected.add(envelope)));\n metadata = collected.finish();\n }\n\n const {\n firstSequenceByRun,\n responseSequencesByRun,\n terminalSequenceByRun,\n settledSpans,\n settledSequenceById,\n settledToolCallRecordIds,\n settledById,\n } = metadata;\n\n const declarationByResultSequence = new Map(settledSpans.map(({ from, to }) => [to, from]));\n const spansByDeclaration = new Map<number, Array<(typeof settledSpans)[number]>>();\n\n for (const span of settledSpans) {\n const spans = spansByDeclaration.get(span.from) ?? [];\n\n spans.push(span);\n spansByDeclaration.set(span.from, spans);\n }\n\n const isInRunView = (\n sequence: number,\n payload: { readonly _tag: string; readonly runId?: RunId | undefined },\n runId: RunId | undefined,\n ): boolean => {\n if (runId === undefined || payload.runId === undefined || payload.runId === runId) return true;\n const first = firstSequenceByRun.get(runId) ?? Number.POSITIVE_INFINITY;\n\n return (\n sequence < first ||\n (payload._tag === \"ToolCallSettled\" &&\n (declarationByResultSequence.get(sequence) ?? Number.POSITIVE_INFINITY) < first)\n );\n };\n\n const compactions = metadata.compactions.filter(({ sequence, payload }) =>\n isInRunView(sequence, payload, ownerRunId),\n );\n\n const recordsForRun = records.pipe(\n Stream.filter(({ sequence, record: { payload } }) =>\n isInRunView(sequence, payload, ownerRunId),\n ),\n );\n\n const isCovered = (envelope: JournalRecordEnvelope, compaction: CompactionCreated): boolean =>\n envelope.sequence <= compaction.coversThrough &&\n isInRunView(envelope.sequence, envelope.record.payload, compaction.runId);\n\n const settledCoverage = compactions.reduce(\n (through, { payload }) =>\n payload.kind !== \"summarize\" ? Math.max(through, payload.coversThrough) : through,\n 0,\n );\n\n // Terminality changes only prompt coverage; it never settles or resolves the Tool Call.\n // Compare against the compaction's Run and sequence, independent of the replay's owner.\n const isTerminalPriorRun = (\n candidateRunId: RunId,\n compactionRunId: RunId | undefined,\n beforeSequence: number,\n ): boolean => {\n const terminal = terminalSequenceByRun.get(candidateRunId);\n\n return (\n candidateRunId !== compactionRunId &&\n terminal !== undefined &&\n terminal < beforeSequence &&\n terminal >\n (responseSequencesByRun\n .get(candidateRunId)\n ?.findLast((sequence) => sequence < beforeSequence) ?? 0)\n );\n };\n\n const incompleteResponseSequences: Array<{\n readonly sequence: number;\n readonly runId: RunId;\n readonly lastSettlementSequence: number;\n }> = [];\n\n let ownerPrefixSequence = firstSequenceByRun.get(ownerRunId ?? \"\") ?? Number.POSITIVE_INFINITY;\n\n let protectedContext: Prompt.Prompt | undefined =\n initialContext === undefined\n ? undefined\n : Prompt.fromMessages(initialContext.content.slice(savedContext?.priorHistoryLength));\n\n if (settledCoverage > 0) {\n yield* Stream.runForEach(recordsForRun, (envelope) =>\n Effect.gen(function* () {\n const payload = envelope.record.payload;\n\n if (payload._tag !== \"ModelResponseRecorded\" || envelope.sequence > settledCoverage) return;\n const messages = yield* decodePromptMessages(payload.messages);\n const declared = declaredApplicationToolCallIds(messages);\n\n let lastSettlementSequence = 0;\n\n for (const id of declared) {\n const callId = yield* decodeToolCallIdEffect(id).pipe(\n Effect.mapError((cause) =>\n journalError(\"Failed to decode a declared Tool Call ID\", cause),\n ),\n );\n\n lastSettlementSequence = Math.max(\n lastSettlementSequence,\n settledSequenceById.get(toolCallSettledRecordId(payload.runId, payload.turn, callId)) ??\n Infinity,\n );\n }\n if (declared.length > 0)\n incompleteResponseSequences.push({\n sequence: envelope.sequence,\n runId: payload.runId,\n lastSettlementSequence,\n });\n if (\n payload.runId === ownerRunId &&\n payload.turn === 1 &&\n payload.runScopedPrefixLength !== undefined\n ) {\n ownerPrefixSequence = envelope.sequence;\n protectedContext = Prompt.fromMessages(\n messages.content.slice(0, payload.runScopedPrefixLength),\n );\n }\n }),\n );\n }\n\n const boundIsValid = (\n payload: CompactionCreated,\n ownSequence: number,\n evidence?: Set<number>,\n ): boolean => {\n const { runId, coversThrough } = payload;\n\n if (coversThrough <= 0 || coversThrough >= ownSequence) return false;\n const ownerFirst = firstSequenceByRun.get(runId);\n\n if (payload.kind === \"summarize\" && ownerFirst !== undefined && coversThrough >= ownerFirst)\n return false;\n if (\n payload.kind !== \"summarize\" &&\n savedContext?.boundaries.some(\n (boundary) =>\n boundary.sequence <= coversThrough &&\n boundary.incomplete === true &&\n boundary.terminalPriorRun !== true,\n )\n )\n return false;\n if (payload.kind !== \"summarize\") {\n for (const response of incompleteResponseSequences) {\n if (\n response.sequence > coversThrough ||\n response.lastSettlementSequence < ownSequence ||\n !isInRunView(\n response.sequence,\n { _tag: \"ModelResponseRecorded\", runId: response.runId },\n runId,\n )\n )\n continue;\n if (evidence !== undefined) {\n evidence.add(response.sequence);\n const terminal = terminalSequenceByRun.get(response.runId);\n\n const lastResponse = responseSequencesByRun\n .get(response.runId)\n ?.findLast((sequence) => sequence < ownSequence);\n\n if (terminal !== undefined) evidence.add(terminal);\n if (lastResponse !== undefined) evidence.add(lastResponse);\n }\n if (!isTerminalPriorRun(response.runId, runId, ownSequence)) return false;\n }\n }\n for (const span of settledSpans) {\n if (\n span.from <= coversThrough &&\n coversThrough < span.to &&\n span.to < ownSequence &&\n isInRunView(span.from, { _tag: \"ModelResponseRecorded\", runId: span.runId }, runId)\n ) {\n evidence?.add(span.from);\n evidence?.add(span.to);\n\n return false;\n }\n }\n\n return true;\n };\n\n type CompactionView = (typeof compactions)[number];\n\n let replacements: ReadonlyArray<CompactionView> = [];\n let clearings: ReadonlyArray<CompactionView> = [];\n\n const retainCompaction = (views: ReadonlyArray<CompactionView>, next: CompactionView) => {\n // Independent Run views overlap without containing one another. Retire an overlay only\n // when the replacement actually contains its view, not merely a larger sequence number.\n if (\n views.some(\n (prior) =>\n prior.payload.coversThrough > next.payload.coversThrough &&\n isInRunView(next.sequence, next.payload, prior.payload.runId),\n )\n )\n return views;\n\n return [\n ...views.filter(\n (prior) =>\n next.payload.coversThrough < prior.payload.coversThrough ||\n !isInRunView(prior.sequence, prior.payload, next.payload.runId),\n ),\n next,\n ];\n };\n\n let latestWindowId: string | undefined = savedContext?.contextWindowId;\n let latestWindowSequence = -1;\n let latestWindow: CompactionView | undefined;\n let rolloverCoveredThrough = 0;\n\n for (const { payload, sequence } of compactions) {\n if (!boundIsValid(payload, sequence)) continue;\n if (payload.kind === \"rollover\" && sequence > latestWindowSequence) {\n latestWindowId = contextWindowId(payload.runId, payload.turn);\n latestWindowSequence = sequence;\n latestWindow = { payload, sequence };\n }\n if (payload.kind === \"rollover\")\n rolloverCoveredThrough = Math.max(rolloverCoveredThrough, payload.coversThrough);\n if (payload.kind === \"summarize\" || payload.kind === \"rollover\") {\n if (payload.kind === \"summarize\" && payload.summary === undefined) continue;\n replacements = retainCompaction(replacements, { payload, sequence });\n } else clearings = retainCompaction(clearings, { payload, sequence });\n }\n\n // A superseding summary retires the overlay, but the latest rollover still owns the window.\n const contextViews = [\n ...replacements,\n ...clearings,\n ...(latestWindow === undefined ? [] : [latestWindow]),\n ];\n\n const contextCompactions = new Set(contextViews.map(({ sequence }) => sequence));\n\n const historyFrom = CanonicalSequence.make(\n replacements.reduce(\n (from, { payload }) => Math.max(from, payload.coversThrough + 1),\n savedContext?.historyFrom ?? 1,\n ),\n );\n\n const contextValidationViews = compactions.filter(\n ({ sequence }) => sequence >= historyFrom || contextCompactions.has(sequence),\n );\n\n const contextEvidence = new Set(\n contextValidationViews.flatMap(({ payload }) => {\n const sequence = firstSequenceByRun.get(payload.runId);\n\n return sequence === undefined ? [] : [sequence];\n }),\n );\n\n // Reread compactions must keep the facts that accepted or rejected their original bounds.\n if (onEvidence !== undefined)\n for (const { payload, sequence } of contextValidationViews)\n boundIsValid(payload, sequence, contextEvidence);\n\n const retainEvidence = (envelope: A): void => {\n if (onEvidence === undefined) return;\n onEvidence(envelope);\n if (envelope.sequence < historyFrom && envelope.record.payload._tag === \"ModelResponseRecorded\")\n // A retained declaration must preserve its already-settled siblings for later coverage checks.\n for (const span of spansByDeclaration.get(envelope.sequence) ?? [])\n if (span.to < historyFrom) contextEvidence.add(span.to);\n };\n\n let summaryEmitted = false;\n\n const retainedPrefix = replacements.some(\n ({ payload }) =>\n payload.kind === \"rollover\" &&\n payload.runId === ownerRunId &&\n ownerPrefixSequence <= payload.coversThrough,\n )\n ? (protectedContext?.content ?? [])\n : [];\n\n const replacementLength = retainedPrefix.length + replacements.length;\n\n const emitSummary = () => {\n if (summaryEmitted || replacements.length === 0) return;\n summaryEmitted = true;\n state.all.push(...retainedPrefix);\n for (const { payload: replacement } of replacements) {\n const message =\n replacement.kind === \"rollover\"\n ? contextWindowMessage(\n contextWindowId(replacement.runId, replacement.turn),\n replacement.handoff,\n )\n : Prompt.makeMessage(\"user\", {\n content: [\n Prompt.makePart(\"text\", {\n text: `${COMPACTION_SUMMARY_PREFIX}${replacement.summary}`,\n }),\n ],\n });\n\n state.all.push(message);\n if (replacement.kind !== \"rollover\" || replacement.runId !== ownerRunId)\n state.before.push(message);\n // Marker coverage comes from its compaction, even when covered facts leave the saved range.\n onBoundary?.({\n sequence: replacement.coversThrough,\n tag: \"CompactionCreated\",\n promptLength: state.all.length,\n });\n }\n };\n\n // The original context is canonical model input, not a reconstruction of later Thread\n // traffic. Its bounded mapping lets compaction cover exactly the same historical prefix.\n if (savedContext !== undefined) {\n emitSummary();\n for (const [index, message] of historical.entries()) {\n const boundary = savedContext.boundaries.find((entry) => entry.promptLength > index);\n\n if (boundary === undefined && replacements.length > 0)\n return yield* journalError(\"Saved context lacks its canonical compaction boundary\");\n if (\n boundary !== undefined &&\n replacements.some(({ payload }) => boundary.sequence <= payload.coversThrough)\n )\n continue;\n\n const visible =\n message.role === \"tool\" &&\n boundary !== undefined &&\n clearings.some(({ payload }) => boundary.sequence <= payload.coversThrough)\n ? Prompt.makeMessage(\"tool\", {\n content: message.content.map((part) =>\n part.type === \"tool-result\"\n ? Prompt.makePart(\"tool-result\", { ...part, result: CLEARED_TOOL_RESULT })\n : part,\n ),\n })\n : message;\n\n state.all.push(visible);\n state.before.push(visible);\n }\n for (const boundary of savedContext.boundaries) {\n const removed = savedContext.boundaries.reduce(\n (length, candidate) =>\n candidate.sequence <= boundary.sequence &&\n replacements.some(({ payload }) => candidate.sequence <= payload.coversThrough)\n ? Math.max(length, candidate.promptLength)\n : length,\n 0,\n );\n\n onBoundary?.({\n ...boundary,\n promptLength: replacementLength + Math.max(0, boundary.promptLength - removed),\n });\n }\n }\n\n const modelUsage: Array<ModelCallUsage> = [];\n let unobservedModelCalls = 0;\n\n const usage = {\n modelCalls: 0,\n inputTokens: 0,\n outputTokens: 0,\n lastInputTokens: 0,\n lastOutputTokens: 0,\n costMicrousd: 0,\n modelUsage,\n };\n\n let toolSelection: Selection | undefined;\n let usageTurn = 0;\n\n const incompleteToolTurns = new Set<string>();\n const incompleteToolCalls = new Set<string>();\n const incompleteContextRuns = new Set<RunId>();\n\n for (const response of incompleteResponseSequences)\n if (\n contextViews.some(\n (view) =>\n view.payload.kind !== \"summarize\" &&\n response.sequence <= view.payload.coversThrough &&\n response.lastSettlementSequence >= view.sequence,\n )\n )\n incompleteContextRuns.add(response.runId);\n let pendingContextToolCallId: string | undefined;\n let ownerTerminated = false;\n\n const policyUsage = {\n committedTurns: 0,\n toolCalls: 0,\n programmaticToolCalls: 0,\n consecutiveToolFailures: 0,\n finalizationUsed: false,\n modelRestarts: 0,\n };\n\n const accountResponse = Effect.fnUntraced(function* (\n envelope: JournalRecordEnvelope,\n payload: Extract<\n JournalRecordEnvelope[\"record\"][\"payload\"],\n { readonly _tag: \"ModelResponseRecorded\" }\n >,\n messages: Prompt.Prompt,\n ) {\n const record = envelope.record;\n\n const declared = declaredApplicationToolCallIds(messages);\n const actualResultIds: Array<RecordId> = [];\n let incomplete = false;\n\n for (const id of declared) {\n const toolCallId = yield* Effect.try({\n try: () => decodeToolCallId(id),\n catch: (cause) => journalError(\"Failed to decode a declared Tool Call ID\", cause),\n });\n\n const resultId = toolCallSettledRecordId(payload.runId, payload.turn, toolCallId);\n\n if (settledToolCallRecordIds.has(resultId)) actualResultIds.push(resultId);\n else incomplete = true;\n }\n if (incomplete) {\n incompleteToolTurns.add(envelope.record.recordId);\n incompleteContextRuns.add(payload.runId);\n for (const recordId of actualResultIds) incompleteToolCalls.add(recordId);\n }\n if (payload.runId !== ownerRunId) return;\n if (!(\"toolOperations\" in payload))\n return yield* journalError(\"Owning Run execution requires full canonical evidence\");\n if (payload.turn === 1 && payload.runScopedPrefixLength !== undefined) {\n protectedContext = Prompt.fromMessages(\n messages.content.slice(0, payload.runScopedPrefixLength),\n );\n }\n\n const responseUsage = yield* projectedResponseUsage(payload);\n\n unobservedModelCalls = yield* addProjectedUsage(\n \"unobservedModelCalls\",\n unobservedModelCalls,\n payload.unobservedModelCalls ?? 0,\n );\n\n usage.modelCalls = yield* addProjectedUsage(\n \"modelCalls\",\n usage.modelCalls,\n responseUsage.modelCalls,\n );\n usage.inputTokens = yield* addProjectedUsage(\n \"inputTokens\",\n usage.inputTokens,\n responseUsage.inputTokens,\n );\n usage.outputTokens = yield* addProjectedUsage(\n \"outputTokens\",\n usage.outputTokens,\n responseUsage.outputTokens,\n );\n usage.costMicrousd = yield* addProjectedUsage(\n \"costMicrousd\",\n usage.costMicrousd,\n responseUsage.costMicrousd,\n );\n usage.modelUsage.push(...responseUsage.modelUsage);\n if (payload.turn > usageTurn) {\n usageTurn = payload.turn;\n usage.lastInputTokens = responseUsage.inputTokens;\n usage.lastOutputTokens = responseUsage.outputTokens;\n }\n\n policyUsage.committedTurns = Math.max(policyUsage.committedTurns, payload.turn);\n\n const calls = messages.content.flatMap((message) =>\n message.role === \"assistant\"\n ? message.content.filter((part) => part.type === \"tool-call\")\n : [],\n );\n\n const candidate = calls.length === 1 ? calls[0] : undefined;\n\n const candidateResult =\n candidate === undefined\n ? undefined\n : settledById.get(`tool-settled:${ownerRunId}:${payload.turn}:${candidate.id}`);\n\n pendingContextToolCallId =\n candidate !== undefined &&\n !candidate.providerExecuted &&\n candidateResult?.isFailure === false &&\n candidateResult.budgetRejected !== true &&\n envelope.sequence > rolloverCoveredThrough\n ? candidate.id\n : undefined;\n\n policyUsage.toolCalls += calls.length;\n if (payload.toolExposure !== undefined) toolSelection = payload.toolExposure.selection;\n if (incompleteToolTurns.has(record.recordId)) return;\n for (const call of calls) {\n const result = call.providerExecuted\n ? messages.content\n .flatMap((message) => (message.role === \"assistant\" ? message.content : []))\n .find(\n (part) => part.type === \"tool-result\" && part.providerExecuted && part.id === call.id,\n )\n : settledById.get(`tool-settled:${ownerRunId}:${payload.turn}:${call.id}`);\n\n if (result === undefined || (\"budgetRejected\" in result && result.budgetRejected === true))\n continue;\n if (!(\"isFailure\" in result)) continue;\n if (!result.isFailure && \"toolSelection\" in result && result.toolSelection !== undefined)\n toolSelection = result.toolSelection;\n policyUsage.consecutiveToolFailures = result.isFailure\n ? policyUsage.consecutiveToolFailures + 1\n : 0;\n }\n });\n\n // Slots refer to the retained Prompt itself, not an additional history payload index.\n // Only still-unseen results retain a slot; late results fill the original declaration in place.\n const historicalResults = new Map<\n string,\n {\n readonly allIndex: number;\n readonly beforeIndex: number;\n readonly parts: Array<Prompt.ToolResultPart>;\n readonly partIndex: number;\n }\n >();\n\n // Only exact calls needed by late results survive retirement, never their old messages.\n const retiredLateCalls = new Map<string, Prompt.ToolCallPart>();\n\n let pendingToolOrder = new Map<string, number>();\n\n const flushTools = Effect.fnUntraced(function* (\n current: FoldState,\n ): Effect.fn.Return<FoldState, RunJournalError> {\n if (current.pendingTools.length === 0) return current;\n\n // Suspension can persist an ordinary sibling before a delegated call joins. Model context\n // still uses declaration order, matching the live interpreter's completed results batch.\n const ordered = current.pendingTools.toSorted(\n (left, right) =>\n (pendingToolOrder.get(left.record.toolCallId) ?? Number.MAX_SAFE_INTEGER) -\n (pendingToolOrder.get(right.record.toolCallId) ?? Number.MAX_SAFE_INTEGER),\n );\n\n const toolMessage = yield* toolMessageFromSettled(ordered);\n\n current.all.push(toolMessage);\n if (!current.pendingToolsForRun) current.before.push(toolMessage);\n\n return {\n ...current,\n pendingTools: [],\n pendingToolsForRun: false,\n };\n });\n\n yield* Stream.runForEach(recordsForRun, (envelope) =>\n Effect.gen(function* () {\n const payload = envelope.record.payload;\n\n if (contextEvidence.has(envelope.sequence)) retainEvidence(envelope);\n if (\n (payload._tag === \"RunCompleted\" ||\n payload._tag === \"RunFailed\" ||\n payload._tag === \"SubmissionSettled\") &&\n payload.runId !== undefined &&\n incompleteContextRuns.has(payload.runId)\n )\n retainEvidence(envelope);\n\n if (\n ((payload._tag === \"RunCompleted\" || payload._tag === \"RunFailed\") &&\n payload.runId === ownerRunId) ||\n (payload._tag === \"SubmissionSettled\" &&\n runIdForSubmission(payload.submissionId) === ownerRunId)\n )\n ownerTerminated = true;\n\n if (payload._tag === \"RunPolicyUsageReserved\" && payload.runId === ownerRunId) {\n if (\n payload.programmaticToolCalls < policyUsage.programmaticToolCalls ||\n (policyUsage.finalizationUsed && !payload.finalizationUsed)\n ) {\n return yield* journalError(\"Run policy reservations must be monotonic\");\n }\n policyUsage.programmaticToolCalls = payload.programmaticToolCalls;\n policyUsage.finalizationUsed = payload.finalizationUsed;\n }\n if (payload._tag === \"ModelCallAborted\" && payload.runId === ownerRunId) {\n if (payload.restart !== policyUsage.modelRestarts + 1)\n return yield* journalError(\"Model restart reservations must advance once\");\n policyUsage.modelRestarts = payload.restart;\n\n const summary = yield* summarizeModelUsage(payload.modelUsage).pipe(\n Effect.mapError((cause) =>\n journalError(\"Aborted model usage exceeds accounting bounds\", cause),\n ),\n );\n\n usage.modelCalls = yield* addProjectedUsage(\n \"modelCalls\",\n usage.modelCalls,\n summary.modelCalls,\n );\n usage.inputTokens = yield* addProjectedUsage(\n \"inputTokens\",\n usage.inputTokens,\n summary.inputTokens.total,\n );\n usage.outputTokens = yield* addProjectedUsage(\n \"outputTokens\",\n usage.outputTokens,\n summary.outputTokens.total,\n );\n usage.costMicrousd = yield* addProjectedUsage(\n \"costMicrousd\",\n usage.costMicrousd,\n summary.costMicrousd,\n );\n usage.modelUsage.push(...payload.modelUsage);\n unobservedModelCalls = yield* addProjectedUsage(\n \"unobservedModelCalls\",\n unobservedModelCalls,\n payload.unobservedModelCalls,\n );\n }\n if (PROMPT_TRANSPARENT_TAGS.has(payload._tag)) return;\n // The compaction record governs the fold (pre-scan) and contributes no\n // message of its own; records at or below the summarize bound render as\n // the one summary message emitted at the covered/kept transition.\n if (payload._tag === \"CompactionCreated\") {\n if (contextCompactions.has(envelope.sequence)) retainEvidence(envelope);\n\n return;\n }\n if (replacements.some(({ payload }) => isCovered(envelope, payload))) {\n if (payload._tag === \"ModelResponseRecorded\" && payload.runId !== ownerRunId) {\n const late = (spansByDeclaration.get(envelope.sequence) ?? []).filter((span) =>\n replacements.some(\n (view) => isCovered(envelope, view.payload) && span.to > view.sequence,\n ),\n );\n\n if (late.length > 0) {\n // Even a rollover-hidden late result needs its exact declaration to stay hidden.\n retainEvidence(envelope);\n if (latestWindow !== undefined && isCovered(envelope, latestWindow.payload)) return;\n const messages = yield* decodePromptMessages(payload.messages);\n\n for (const message of messages.content) {\n if (message.role !== \"assistant\") continue;\n for (const call of message.content) {\n if (call.type !== \"tool-call\" || call.providerExecuted) continue;\n\n const callId = yield* decodeToolCallIdEffect(call.id).pipe(\n Effect.mapError((cause) => journalError(\"Invalid retired Tool Call ID\", cause)),\n );\n\n const id = toolCallSettledRecordId(payload.runId, payload.turn, callId);\n\n if (late.some((span) => span.recordId === id)) retiredLateCalls.set(id, call);\n }\n }\n }\n }\n // Retiring Prompt payloads does not retire the owning Run's policy or usage accounting.\n if (payload._tag === \"ModelResponseRecorded\" && payload.runId === ownerRunId) {\n const messages = yield* decodePromptMessages(payload.messages);\n\n yield* accountResponse(envelope, payload, messages);\n state = { ...state, committedTurns: Math.max(state.committedTurns, payload.turn) };\n }\n\n return;\n }\n emitSummary();\n if (payload._tag === \"ToolCallSettled\") {\n const declaration = declarationByResultSequence.get(envelope.sequence);\n\n const declarationFact = {\n sequence: declaration ?? Infinity,\n record: { payload: { _tag: \"ModelResponseRecorded\", runId: payload.runId } },\n };\n\n const declarationCovered = (compaction: CompactionCreated) =>\n declarationFact.sequence <= compaction.coversThrough &&\n isInRunView(declarationFact.sequence, declarationFact.record.payload, compaction.runId);\n\n if (latestWindow !== undefined && declarationCovered(latestWindow.payload)) return;\n retainEvidence(envelope);\n if (payload.runId !== ownerRunId) {\n const slot = historicalResults.get(envelope.record.recordId);\n\n if (slot === undefined) {\n const call = retiredLateCalls.get(envelope.record.recordId);\n\n if (\n call === undefined ||\n call.id !== payload.toolCallId ||\n call.name !== payload.toolName\n )\n return yield* journalError(\"Historical Tool result has no matching declaration\");\n\n const pair = [\n Prompt.makeMessage(\"assistant\", { content: [call] }),\n Prompt.makeMessage(\"tool\", {\n content: [\n Prompt.makePart(\"tool-result\", {\n id: call.id,\n name: call.name,\n result: clearings.some(({ payload }) => declarationCovered(payload))\n ? CLEARED_TOOL_RESULT\n : payload.result,\n isFailure: payload.isFailure,\n providerExecuted: false,\n }),\n ],\n }),\n ];\n\n state.all.push(...pair);\n state.before.push(...pair);\n retiredLateCalls.delete(envelope.record.recordId);\n onBoundary?.({\n sequence: envelope.sequence,\n tag: payload._tag,\n promptLength: state.all.length,\n });\n\n return;\n }\n const declared = slot.parts[slot.partIndex];\n\n if (declared?.id !== payload.toolCallId || declared.name !== payload.toolName)\n return yield* journalError(\"Historical Tool result differs from its declaration\");\n slot.parts[slot.partIndex] = Prompt.makePart(\"tool-result\", {\n id: payload.toolCallId,\n name: payload.toolName,\n result: clearings.some(\n ({ payload }) => isCovered(envelope, payload) || declarationCovered(payload),\n )\n ? CLEARED_TOOL_RESULT\n : payload.result,\n isFailure: payload.isFailure,\n providerExecuted: false,\n });\n const message = Prompt.makeMessage(\"tool\", { content: [...slot.parts] });\n\n state.all[slot.allIndex] = message;\n state.before[slot.beforeIndex] = message;\n historicalResults.delete(envelope.record.recordId);\n onBoundary?.({\n sequence: envelope.sequence,\n tag: payload._tag,\n promptLength: state.all.length,\n ...(incompleteToolCalls.has(envelope.record.recordId) ? { incomplete: true } : {}),\n ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)\n ? { terminalPriorRun: true }\n : {}),\n });\n\n return;\n }\n if (\n state.pendingTools.length > 0 &&\n state.pendingToolsForRun !== (payload.runId === ownerRunId)\n ) {\n state = yield* flushTools(state);\n }\n state.pendingTools.push({\n record: payload,\n cleared: clearings.some(({ payload }) => isCovered(envelope, payload)),\n });\n state = {\n ...state,\n pendingToolsForRun: payload.runId === ownerRunId,\n };\n onBoundary?.({\n sequence: envelope.sequence,\n tag: payload._tag,\n promptLength: state.all.length + 1,\n ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)\n ? { terminalPriorRun: true }\n : {}),\n ...(incompleteToolCalls.has(envelope.record.recordId) ? { incomplete: true } : {}),\n });\n\n return;\n }\n state = yield* flushTools(state);\n if (payload._tag === \"ModelCompleted\" && payload.history !== undefined) {\n retainEvidence(envelope);\n const messages = yield* decodePromptMessages(payload.history);\n\n state.all.length = 0;\n state.before.length = 0;\n historicalResults.clear();\n\n for (const message of messages.content) {\n state.all.push(message);\n if (payload.runId !== ownerRunId) state.before.push(message);\n }\n // Persistent, non-durable model history needs the same original compaction mapping\n // as durable responses; cold selected-Run recovery cannot infer it from later history.\n onBoundary?.({\n sequence: envelope.sequence,\n tag: payload._tag,\n promptLength: state.all.length,\n });\n\n return;\n }\n if (payload._tag !== \"ModelResponseRecorded\") return;\n retainEvidence(envelope);\n const messages = yield* decodePromptMessages(payload.messages);\n const forRun = payload.runId === ownerRunId;\n\n pendingToolOrder = new Map(\n declaredApplicationToolCallIds(messages).map((id, index) => [id, index]),\n );\n\n yield* accountResponse(envelope, payload, messages);\n\n const visibleMessages = forRun\n ? messages.content\n : messages.content.filter((message) => message.role !== \"system\");\n\n for (const message of visibleMessages) {\n state.all.push(message);\n if (!forRun) state.before.push(message);\n }\n if (!forRun) {\n const calls = messages.content.flatMap((message) =>\n message.role === \"assistant\"\n ? message.content.filter(\n (part): part is Prompt.ToolCallPart =>\n part.type === \"tool-call\" && !part.providerExecuted,\n )\n : [],\n );\n\n if (calls.length > 0) {\n const parts = calls.map((call) =>\n Prompt.makePart(\"tool-result\", {\n id: call.id,\n name: call.name,\n result: {\n _tag: \"ToolOutcomeUnknown\",\n message:\n \"This earlier operation has no recorded outcome. It may have executed. Do not assume success or retry it; its original operation remains unresolved.\",\n },\n isFailure: true,\n providerExecuted: false,\n }),\n );\n\n const allIndex = state.all.length;\n const beforeIndex = state.before.length;\n const message = Prompt.makeMessage(\"tool\", { content: parts });\n\n state.all.push(message);\n state.before.push(message);\n for (const [partIndex, call] of calls.entries()) {\n const callId = yield* decodeToolCallIdEffect(call.id).pipe(\n Effect.mapError((cause) => journalError(\"Invalid historical Tool Call ID\", cause)),\n );\n\n const resultId = toolCallSettledRecordId(payload.runId, payload.turn, callId);\n\n // A fixed replay can fill only a result present in its captured metadata. Missing\n // calls retain their visible Unknown part without an expanded identity directory.\n if (!settledToolCallRecordIds.has(resultId)) continue;\n historicalResults.set(resultId, {\n allIndex,\n beforeIndex,\n parts,\n partIndex,\n });\n }\n }\n }\n state = {\n ...state,\n committedTurns: forRun\n ? Math.max(state.committedTurns, payload.turn)\n : state.committedTurns,\n };\n onBoundary?.({\n sequence: envelope.sequence,\n tag: payload._tag,\n promptLength: state.all.length,\n ...(isTerminalPriorRun(payload.runId, ownerRunId, Number.POSITIVE_INFINITY)\n ? { terminalPriorRun: true }\n : {}),\n ...(incompleteToolTurns.has(envelope.record.recordId) ? { incomplete: true } : {}),\n });\n }),\n );\n emitSummary();\n state = yield* flushTools(state);\n\n const validatedPolicyUsage = yield* Schema.decodeEffect(RunPolicyUsage)(policyUsage).pipe(\n Effect.mapError((cause) =>\n journalError(\"Run policy accounting exceeds its Schema bounds\", cause),\n ),\n );\n\n return {\n ...(toolSelection === undefined ? {} : { toolSelection }),\n policyUsage: validatedPolicyUsage,\n prompt: Prompt.fromMessages(state.all),\n historyBefore: Prompt.fromMessages(state.before),\n historyFrom,\n committedTurns: state.committedTurns,\n usage: unobservedModelCalls === 0 ? usage : { ...usage, unobservedModelCalls },\n ...(latestWindowId === undefined ? {} : { contextWindowId: latestWindowId }),\n ...(protectedContext === undefined ? {} : { protectedContext }),\n ...(ownerTerminated || pendingContextToolCallId === undefined\n ? {}\n : { pendingContextToolCallId }),\n };\n});\n\n/** Pure projection of one Run's durable recovery state from canonical records. */\nexport const projectRunJournal = (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n runId: RunId,\n): Effect.Effect<RunJournalProjection, RunJournalError> =>\n projectRunJournalStream(Stream.fromIterable(records), runId);\n\n/**\n * Pure valid-prompt projection from canonical records: `UserInputRecorded` +\n * `ModelResponseRecorded` + complete `ToolCallSettled` batches → the deterministic model-visible\n * Prompt (plan §Coordinator flow step 3).\n */\nexport const promptFromCanonicalRecords = (\n records: ReadonlyArray<CanonicalRecordEnvelope>,\n): Effect.Effect<Prompt.Prompt, RunJournalError> =>\n projectRunJournalStream(Stream.fromIterable(records), undefined).pipe(\n Effect.map((projection) => projection.prompt),\n );\n\n/** Everything one committed Turn contributes to its canonical batch. */\n/**\n * Staged usage is validated, never repaired: clamping negatives or truncating\n * fractions would under-record canonical usage, and NaN/Infinity must fail\n * typed instead of escaping as a record-construction defect (RUN-023).\n */\nconst validStagedUsage = (label: string, value: number): Effect.Effect<number, RunJournalError> =>\n Number.isSafeInteger(value) && value >= 0\n ? Effect.succeed(value)\n : Effect.fail(\n journalError(`Staged ${label} must be a non-negative safe integer, got ${String(value)}`),\n );\n\nexport interface TurnCommitInput {\n readonly toolResultMaxBytes?: number | undefined;\n readonly toolSelectionMaxBytes?: number | undefined;\n readonly toolOperations?: ModelResponseRecorded[\"toolOperations\"] | undefined;\n readonly toolParameterRejections?: ReadonlyArray<ToolParameterRejection> | undefined;\n readonly toolExposure?: Snapshot | undefined;\n readonly runId: RunId;\n /** Canonical (Run-relative, Attempt-independent) Turn number; must be positive. */\n readonly turn: number;\n readonly turnId: TurnId;\n /**\n * Exact response and leading input/instruction messages. Application Tool outcomes\n * are supplied separately; the journal does not reconstruct them from Prompt history.\n */\n readonly responseMessages: ReadonlyArray<Prompt.Message>;\n readonly toolResults: ReadonlyArray<RunTurnToolResult>;\n readonly producerId: ProducerId;\n readonly deploymentId: DeploymentId;\n readonly createdAt: DateTime.Utc;\n /** Leading instruction/wake messages that stay canonical but are hidden from later Runs. */\n readonly runScopedPrefixLength?: number | undefined;\n /** Terminal output committed atomically with this Turn's final canonical batch. */\n readonly runCompletion?:\n | {\n readonly output: PersistedJson;\n readonly runDisposition?: PersistedJson | undefined;\n readonly finishReason?: \"budget-exhausted\" | undefined;\n readonly exhausted?: ExhaustedLimit | undefined;\n }\n | undefined;\n /** Known missing-accounting invocations staged before this canonical response. */\n readonly unobservedModelCalls?: number | undefined;\n /** Per-call provider usage staged by the engine's `noteTurnUsage` (RUN-023). */\n readonly usage?:\n | {\n readonly inputTokens: number;\n readonly outputTokens: number;\n readonly costMicrousd?: number | undefined;\n readonly modelUsage?: ReadonlyArray<ModelCallUsage> | undefined;\n }\n | undefined;\n}\n\nconst decodePersistedJson = Schema.decodeUnknownEffect(PersistedJson);\nconst encodePrompt = Schema.encodeEffect(Prompt.Prompt);\nconst decodeModelUsage = Schema.decodeUnknownEffect(Schema.Array(ModelCallUsage));\n\nconst requireCanonicalTurn = (turn: number): Effect.Effect<void, RunJournalError> =>\n !Number.isInteger(turn) || turn <= 0\n ? Effect.fail(journalError(`Canonical turn number must be a positive integer: ${turn}`))\n : Effect.void;\n\nconst modelResponseRecord = Effect.fnUntraced(function* (\n input: TurnCommitInput,\n): Effect.fn.Return<RecordEnvelope, RunJournalError> {\n const promptMessages = input.responseMessages;\n\n if (promptMessages.length === 0) {\n return yield* journalError(`Turn ${input.turn} appended no model-visible Prompt messages`);\n }\n if (promptMessages.some((message) => message.role === \"tool\")) {\n return yield* journalError(\"Application Tool outcomes must be supplied as terminal facts\");\n }\n const runScopedPrefixLength = input.runScopedPrefixLength;\n\n if (\n runScopedPrefixLength !== undefined &&\n (input.turn !== 1 ||\n !Number.isSafeInteger(runScopedPrefixLength) ||\n runScopedPrefixLength <= 0 ||\n runScopedPrefixLength >= promptMessages.length ||\n promptMessages\n .slice(0, runScopedPrefixLength)\n .some((message) => message.role !== \"system\" && message.role !== \"user\"))\n ) {\n return yield* journalError(\n \"Run-scoped Prompt provenance must identify a non-empty system/user prefix of Turn 1 before its assistant response\",\n );\n }\n\n const encodedMessages = yield* encodePrompt(Prompt.fromMessages([...promptMessages])).pipe(\n Effect.mapError((cause) => journalError(\"Turn Prompt messages failed to encode\", cause)),\n );\n\n const messages = yield* decodePersistedJson(encodedMessages).pipe(\n Effect.map(copyJson),\n Effect.mapError((cause) =>\n journalError(\"Turn Prompt messages exceed canonical persistence bounds\", cause),\n ),\n );\n\n const modelUsage =\n input.usage?.modelUsage === undefined\n ? undefined\n : yield* decodeModelUsage(input.usage.modelUsage).pipe(\n Effect.mapError((cause) => journalError(\"Turn model usage failed to decode\", cause)),\n );\n\n if (modelUsage !== undefined) {\n if (modelUsage.length === 0) {\n return yield* journalError(\"Turn model usage must contain at least one completed call\");\n }\n\n const summary = yield* continuationUsage(modelUsage).pipe(\n Effect.mapError((cause) => journalError(\"Turn model usage exceeds accounting bounds\", cause)),\n );\n\n if (\n input.usage === undefined ||\n input.usage.inputTokens !== summary.inputTokens ||\n input.usage.outputTokens !== summary.outputTokens ||\n (input.usage.costMicrousd ?? 0) !== summary.costMicrousd\n ) {\n return yield* journalError(\"Turn detailed and aggregate model usage disagree\");\n }\n }\n\n return RecordEnvelope.make({\n recordId: modelResponseRecordId(input.runId, input.turn),\n family: \"thread\",\n schemaVersion: 1,\n createdAt: input.createdAt,\n deploymentId: input.deploymentId,\n payload: yield* ModelResponseRecorded.makeEffect({\n toolResultMaxBytes: input.toolResultMaxBytes ?? MAX_PERSISTED_JSON_BYTES,\n toolSelectionMaxBytes: input.toolSelectionMaxBytes ?? 0,\n toolOperations: input.toolOperations ?? [],\n ...(input.toolParameterRejections === undefined || input.toolParameterRejections.length === 0\n ? {}\n : { toolParameterRejections: input.toolParameterRejections }),\n ...(input.toolExposure === undefined ? {} : { toolExposure: input.toolExposure }),\n runId: input.runId,\n turnId: input.turnId,\n turn: input.turn,\n messages,\n ...(runScopedPrefixLength === undefined ? {} : { runScopedPrefixLength }),\n ...(modelUsage === undefined ? {} : { modelUsage }),\n ...(input.unobservedModelCalls === undefined || input.unobservedModelCalls === 0\n ? {}\n : {\n unobservedModelCalls: yield* validStagedUsage(\n \"unobservedModelCalls\",\n input.unobservedModelCalls,\n ),\n }),\n ...(input.usage === undefined\n ? {}\n : {\n inputTokens: yield* validStagedUsage(\"inputTokens\", input.usage.inputTokens),\n outputTokens: yield* validStagedUsage(\"outputTokens\", input.usage.outputTokens),\n // Written only when non-zero: absent re-seeds as zero, so the\n // no-estimator case stays byte-identical to pre-cost histories.\n ...(input.usage.costMicrousd === undefined || input.usage.costMicrousd === 0\n ? {}\n : {\n costMicrousd: yield* validStagedUsage(\"costMicrousd\", input.usage.costMicrousd),\n }),\n }),\n }).pipe(\n Effect.mapError((cause) => journalError(\"Invalid model response operation evidence\", cause)),\n ),\n });\n});\n\nconst toolSettledRecords = Effect.fnUntraced(function* (\n input: TurnCommitInput,\n): Effect.fn.Return<Array<RecordEnvelope>, RunJournalError> {\n const toolRecords: Array<RecordEnvelope> = [];\n\n for (const part of input.toolResults) {\n const result = yield* decodePersistedJson(part.result).pipe(\n Effect.mapError((cause) =>\n journalError(`Tool result ${part.toolCallId} exceeds canonical persistence bounds`, cause),\n ),\n );\n\n const toolCallId = yield* Effect.try({\n try: () => decodeToolCallId(part.toolCallId),\n catch: (cause) => journalError(`Invalid Tool Call ID ${part.toolCallId}`, cause),\n });\n\n toolRecords.push(\n RecordEnvelope.make({\n recordId: toolCallSettledRecordId(input.runId, input.turn, toolCallId),\n family: \"thread\",\n schemaVersion: 1,\n createdAt: input.createdAt,\n deploymentId: input.deploymentId,\n payload: ToolCallSettled.make({\n ...(part.toolSelection === undefined ? {} : { toolSelection: part.toolSelection }),\n runId: input.runId,\n toolCallId,\n toolName: part.toolName,\n result,\n isFailure: part.isFailure,\n ...(part.budgetRejected === true ? { budgetRejected: true } : {}),\n }),\n }),\n );\n }\n\n return toolRecords;\n});\n\nconst runCompletionRecord = Effect.fnUntraced(function* (input: TurnCommitInput) {\n if (input.runCompletion === undefined) return undefined;\n const completion = { runId: input.runId, ...input.runCompletion };\n\n return RecordEnvelope.make({\n recordId: runCompletedRecordId(input.runId),\n family: \"thread\",\n schemaVersion: 1,\n createdAt: input.createdAt,\n deploymentId: input.deploymentId,\n payload: RunCompleted.make({\n ...completion,\n }),\n });\n});\n\n/**\n * Build a canonical batch from interpreter-validated Turn facts: one\n * `ModelResponseRecorded` record plus one `ToolCallSettled` record per terminal Tool result, all\n * under the WP0-style deterministic identities, committed as ONE atomic batch. The same input\n * always yields byte-identical content, so an in-Attempt append retry is an honest batch replay.\n *\n * No-tool Turns and eligible readonly Turns use this shape; a terminal `RunCompleted` marker\n * joins the response in the same atomic batch. Other application Turns split into\n * `turnResponseBatch` + `turnResultsBatch` before execution.\n */\nexport const turnCanonicalBatch = Effect.fnUntraced(function* (\n input: TurnCommitInput,\n): Effect.fn.Return<CanonicalBatch, RunJournalError> {\n yield* requireCanonicalTurn(input.turn);\n const modelResponse = yield* modelResponseRecord(input);\n const toolRecords = yield* toolSettledRecords(input);\n const completionRecord = yield* runCompletionRecord(input);\n\n return CanonicalBatch.make({\n batchId: turnBatchId(input.runId, input.turn),\n producerId: input.producerId,\n records:\n completionRecord === undefined\n ? [modelResponse, ...toolRecords]\n : [modelResponse, ...toolRecords, completionRecord],\n });\n});\n\n/**\n * Commit the normalized response and original operation contracts before application Tools\n * execute, or promote a deferred readonly response before a persisted call-scoped capability.\n * An unsettled application declaration is conservative uncertainty after ownership\n * loss; approvals and the dispatch fence remain separate execution requirements. Provider\n * results stay in assistant content. Application outcomes belong to the results commit.\n */\nexport const turnResponseBatch = Effect.fnUntraced(function* (\n input: TurnCommitInput,\n): Effect.fn.Return<CanonicalBatch, RunJournalError> {\n yield* requireCanonicalTurn(input.turn);\n const modelResponse = yield* modelResponseRecord(input);\n\n return CanonicalBatch.make({\n batchId: turnResponseBatchId(input.runId, input.turn),\n producerId: input.producerId,\n records: [modelResponse],\n });\n});\n\n/**\n * Commit 5 of a tool-declaring Turn (plan §2.1): the Turn's `ToolCallSettled` records in\n * declaration order under batch identity `turn-results:{runId}:{turn}` — the batch becomes\n * model-visible atomically. A completion after already committed Tool results gets its own\n * terminal batch; it never rewrites or repeats the earlier Tool outcomes.\n */\nexport const turnResultsBatch = Effect.fnUntraced(function* (\n input: TurnCommitInput,\n): Effect.fn.Return<CanonicalBatch, RunJournalError> {\n yield* requireCanonicalTurn(input.turn);\n const toolRecords = yield* toolSettledRecords(input);\n const first = toolRecords[0];\n const completionRecord = yield* runCompletionRecord(input);\n\n if (first === undefined) {\n if (completionRecord === undefined) {\n return yield* journalError(`Turn ${input.turn} has no terminal Tool results to commit`);\n }\n\n return CanonicalBatch.make({\n batchId: makeBatchId(runCompletedRecordId(input.runId)),\n producerId: input.producerId,\n records: [completionRecord],\n });\n }\n if (input.runCompletion !== undefined && toolRecords.length !== 1) {\n return yield* journalError(\"A terminal Tool completion requires exactly one settled result\");\n }\n\n return CanonicalBatch.make({\n batchId: turnResultsBatchId(input.runId, input.turn),\n producerId: input.producerId,\n records:\n completionRecord === undefined\n ? [first, ...toolRecords.slice(1)]\n : [first, ...toolRecords.slice(1), completionRecord],\n });\n});\n"],"mappings":";;;;;;;;;;;;AAaA,MAAMA,iBAAe,MAAM,QAAkB;;AAG7C,MAAa,2BACX,OACA,MACA,eACaA,eAAa,gBAAgB,MAAM,GAAG,KAAK,GAAG,YAAY;;;;;;;AAkCzE,MAAa,uBAAuB,eAAkC;CACpE,MAAM,qCAAqB,IAAI,IAAoB;CAEnD,MAAM,yCAAyB,IAAI,IAA2B;CAE9D,MAAM,oCAAoB,IAAI,IAO5B;CAEF,MAAM,wCAAwB,IAAI,IAAoB;CAEtD,MAAM,eAKD,CAAC;CAEN,MAAM,sCAAsB,IAAI,IAAoB;CAEpD,MAAM,2CAA2B,IAAI,IAAY;CAEjD,MAAM,8BAAc,IAAI,IAG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